Recursion — a function that calls itself on a smaller input — is the mental model behind searching, sorting and trees. This final chapter ties the course together: recursion, the O(log n) power of binary search, how the fast sorts work, and a first look at trees.
Recursion
Every recursion needs a base case (when to stop) and a recursive case (shrink toward the base):
def factorial(n):if n <= 1: # base casereturn 1return n * factorial(n - 1) # recursive case# Same shape solves many "divide and conquer" problemsdef sum_list(items):if not items: return 0return items[0] + sum_list(items[1:])
Binary search
On a sorted array, binary search halves the search space each step — O(log n). A million items takes about 20 steps:
def binary_search(nums, target): # nums is sortedlo, hi = 0, len(nums) - 1while lo <= hi:mid = (lo + hi) // 2if nums[mid] == target: return midif nums[mid] < target: lo = mid + 1else: hi = mid - 1return -1
Sorting
In practice you call the built-in sort (O(n log n)). But knowing how the fast ones work is standard interview material:
| Sort | Average | Idea |
|---|---|---|
| Bubble / Insertion | O(n²) | Simple, fine for tiny/nearly-sorted data |
| Merge sort | O(n log n) | Split in half, sort each, merge (stable) |
| Quick sort | O(n log n) | Partition around a pivot, recurse |
def merge_sort(a):if len(a) <= 1: return amid = len(a) // 2left, right = merge_sort(a[:mid]), merge_sort(a[mid:])# merge two sorted halvesout, i, j = [], 0, 0while i < len(left) and j < len(right):if left[i] <= right[j]: out.append(left[i]); i += 1else: out.append(right[j]); j += 1return out + left[i:] + right[j:]
A first look at trees
A tree is a branching structure — each node has children. A binary tree has at most two. Traversing one is naturally recursive, and a binary search tree keeps values ordered for O(log n) lookup:
def inorder(node):if not node: returninorder(node.left)print(node.val)inorder(node.right)
Practice
Implement factorial and a recursive list sum, binary search on a sorted array, and merge sort. Then write an in-order traversal of a small binary tree. You've now covered the DSA toolkit that most interviews draw from.
Key takeaways
- 01Recursion needs a base case and a recursive case that shrinks toward it — or it overflows.
- 02Binary search halves a sorted array each step: O(log n).
- 03Merge and quick sort are O(n log n); bubble/insertion are O(n²) — know how they work.
- 04Trees are branching structures traversed recursively; BSTs give O(log n) lookup.
- 05Big-O, arrays/hash maps, linked structures, recursion & sorting/searching cover most interviews.
