Lesson 1 · Unit 01
Halve the search
Throw away half the list with every look
What you practise
- Needs sorted input
- Trace
lo,mid,hi - About log₂ n steps
Try a question from this lesson
Pick one
I pick a number from 1 to 100. After each guess I say "higher" or "lower". Which first guess rules out the most numbers, whatever I answer?
Correct answer
50
Why
Guessing 50 removes half the numbers whichever way I answer. Guessing 1 or 99 usually removes a single number. Halving every time is the whole idea of binary search.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Binary search
In a sorted list, keep a window lo..hi of indexes where the target could be, and look at the middle.
Middle too small? The target can only be to the right. Too big? Only to the left. Either way, half the window is gone.
def search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1function search(nums, target) {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}function search(
nums: number[],
target: number,
): number {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (nums[mid] === target) return mid;
if (nums[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}Python note// is integer division: 7 // 2 is 3, so mid is always a usable index.
JavaScript noteMath.floor matters: 7 / 2 is 3.5 in JavaScript, and nums[3.5] is undefined.
TypeScript noteThe long signature is wrapped over four lines. ): number is the return type: an index, or -1 when the target is missing.
10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× match the pairs
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.