Boss lesson · Unit 02
Divide and conquer
Split in half, and throw a half away when you can
What you practise
- Split in half, solve each, combine: max of a list, recursive binary search
- Depth log n
Try a question from this lesson
Pick one
Eight players split into two groups of four. Each group finds its champion the same way, then the champions play. How many matches in total?
Correct answer
7
Why
Four matches, then two, then the final: 7. Every match removes one player and seven must go, so splitting did not save any matches. What it limits is the number of rounds: only 3.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Divide and conquer
Split the input in half, solve each half with a recursive call, then combine the two answers. The base case is a piece too small to split.
This finds the largest number between positions lo and hi: the champion of each half, then one comparison.
def best(nums, lo, hi):
if lo == hi:
return nums[lo]
mid = (lo + hi) // 2
left = best(nums, lo, mid)
right = best(nums, mid + 1, hi)
return max(left, right)function best(nums, lo, hi) {
if (lo === hi) return nums[lo];
const mid = Math.floor((lo + hi) / 2);
const left = best(nums, lo, mid);
const right = best(nums, mid + 1, hi);
return Math.max(left, right);
}function best(
nums: number[],
lo: number,
hi: number,
): number {
if (lo === hi) return nums[lo];
const mid = Math.floor((lo + hi) / 2);
const left = best(nums, lo, mid);
const right = best(nums, mid + 1, hi);
return Math.max(left, right);
}TypeScript notenums: number[] is checked at every call, including the recursive ones: passing a string for lo would not compile.
Concept
Throw half away
The boss problem: find the position of a target in a sorted list, or -1 if it is missing.
Compare the target with the middle item. Because the list is sorted, one comparison rules out an entire half. Recurse into the other half only.
find 23 in [2, 5, 8, 12, 16, 23, 38]
middle is 12: too small, go right
middle is 23: found at index 5find 23 in [2, 5, 8, 12, 16, 23, 38]
middle is 12: too small, go right
middle is 23: found at index 5find 23 in [2, 5, 8, 12, 16, 23, 38]
middle is 12: too small, go right
middle is 23: found at index 59 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.