AdvancedMath for DSAUsed everywhere

Reading recurrences: T(n) = 2T(n/2) + n

Divide and conquer cost = (number of calls) × (work per call), level by level. : log n levels × n work = .

The idea

A algorithm's cost is a : T(n) = a·T(n/b) + f(n) means a subcalls on inputs of size n/b plus f(n) work to split and combine.

Draw the call tree. Merge sort has log₂ n levels, and each level does n total work, so n log n. is T(n) = T(n/2) + 1: log n levels of . Naive , T(n) = T(n−1) + T(n−2) + 1, doubles each level: about 2ⁿ.

Worked example

Three common recurrences

  1. T(n) = T(n/2) + O(1) → : binary search.
  2. T(n) = 2T(n/2) + → O(n log n): merge sort.
  3. T(n) = 2T(n/2) + O(1) → O(n): visiting every of a tree.

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

T(n) = 2T(n/2) + n:
split into 2 halves, recurse on each, then n work to combine
every level of the call tree does n work
there are log₂ n levels → O(n log n)
T(n) = T(n/2) + 1 → O(log n)(binary search)
T(n) = 2T(n/2) + 1 → O(n)(visit every tree node)

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

T(n) = 2T(n/2) + n, n = 8

level 0: call sizes

8

Solution · Pythonline 5

def merge_sort(nums): # T(n) = 2T(n/2) + n
if len(nums) <= 1:
return nums
mid = len(nums) // 2
left, right = merge_sort(nums[:mid]), merge_sort(nums[mid:])
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i]); i += 1
else:
merged.append(right[j]); j += 1
return merged + left[i:] + right[j:]

Step 1 of 6· line 5

T(n) = 2T(n/2) + n reads: two calls on halves, plus n work to merge. Draw it as a tree of calls and add up each level.

Merge sort: O(n log n) time, O(n) space.

How to spot it

  • Any recursion that splits the input: sorting, tree , , “divide in half”.

Common mistakes

  • Counting only one level's work.
  • Assuming every split is even: 's is T(n) = T(n−1) + n = .

Where it comes up

Go further