Divide a Problem into Independent Subproblems
Core idea
Divide and conquer splits an input into smaller parts, solves each independently, then combines their answers. A base case stops recursion. For a balanced split with linear total combine work per level, the recurrence T(n)=2T(n/2)+O(n) gives O(n log n); constant combine work instead gives O(n) for a full binary recursion tree with n leaves. Use index bounds to avoid copying slices.
def peak(a, lo, hi): if hi-lo == 1: return a[lo] mid = (lo+hi)//2 return max(peak(a,lo,mid), peak(a,mid,hi))a = [4,9,2,7]print(peak(a,0,len(a)))For a nonempty interval, both halves shrink until each has one item. The maximum combines in constant comparisons.
Count recursive calls
def calls(n): if n == 1: return 1 left = n//2 return 1 + calls(left) + calls(n-left)print(calls(5), calls(8))There are n leaves and n-1 internal nodes for positive n.
Common mistake
An empty interval is outside the peak function contract; it would not reach the stated base case. Splitting with list slices adds copying work that can change complexity.
Practice
Implement a nonempty interval minimum, then count comparisons for five elements. Compare with a loop.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Divide and conquer
Check your understanding of divide and conquer.
What is printed?
print((0+5)//2)What is printed?
print(1+2*3)What ensures recursive termination?
What cost does index-based splitting avoid?