Find the number
easy
New here? How this page works
- Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
- Open Break it down. Answer the questions in your own words. This is your plan.
- Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
- Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
- Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
- Press Submit. It runs hidden tests too. Pass them all, and it's solved.
sorted is a list of different whole numbers, from smallest to largest. Return the position of target in it, or -1 if it isn't there.
Checking every item works, but try to use the order: it lets you rule out half the list with every look.
Examples
Example 1
- Input
- sorted = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target = 23
- Output
- 5
23 is at position 5.
Example 2
- Input
- sorted = [2, 5, 8, 12, 16], target = 6
- Output
- -1
6 would sit between 5 and 8, but it isn't in the list.
Example 3
- Input
- sorted = [-5, 0, 7], target = -5
- Output
- 0
Rules
sortedhas between 0 and 1,000,000 different numbers, from smallest to largest.- Don't use
indexOforincludes: they check items one by one.
Words on this page, in plain English (3)Open if any word is new to you
- Array (list)
- A list of values kept in order, inside square brackets. Like a row of numbered lockers.
- Index (position)
- Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
- Sorted
- In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.
Answer each question in your own words before you look at ours. Rough notes are fine: the point is to think before you type code. Your answers stay in this browser.
1.What goes in?
Name every input and what it looks like. Can it be empty? Sorted? Negative?
Stuck? Each hint gives a little more away. Try the problem again after each one.
This explains the whole solution.
You will learn the most by trying first, even if you don’t finish. But if this pattern is new to you, reading the walkthrough first is a fine way to learn it.
1. Understand the problem
The list is sorted and has no repeats. We want the position of target, or -1 if it isn't there. Easy to do by checking every item, but the list can have a million items, and we can do much better.
2. Solve an example by hand
Find 23 in [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]. Look in the middle: position 4 is 16. 16 is smaller than 23, and the list is sorted, so 16 and everything before it is too small. Only positions 5 to 9 are left. Their middle, position 7, is 56: too big, so positions 7 to 9 go. Positions 5 to 6 are left. The middle is position 5: 23. Found in 3 looks.
3. The slow way
for (let i = 0; i < sorted.length; i++) { if (sorted[i] === target) return i;}return -1;This is O(n): a million looks in the worst case. It ignores the most useful fact we have, that the list is sorted.
4. Spot the pattern
Sorted list, looking something up: binary search. Every look at the middle rules out half of what's left.
5. The binary search idea
Keep a range from low to high where the target must be, if it's in the list at all. Look at the middle:
- Equal? Found it.
- Too small? The target is to the right:
low = mid + 1. - Too big? The target is to the left:
high = mid - 1.
If the range becomes empty (low > high), the target isn't there.
Halve the range with every look
sorted
- target =
- 23
- looks =
- 0
function findTheNumber(sorted, target) { let low = 0; let high = sorted.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) { return mid; } else if (sorted[mid] < target) { low = mid + 1; // target is to the right } else { high = mid - 1; // target is to the left } } return -1;}The target, 23, could be anywhere from position 0 to 9.
Try it with a missing number too: the range shrinks until it's empty.
Halve the range with every look
sorted
- target =
- 60
- looks =
- 0
function findTheNumber(sorted, target) { let low = 0; let high = sorted.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) { return mid; } else if (sorted[mid] < target) { low = mid + 1; // target is to the right } else { high = mid - 1; // target is to the left } } return -1;}The target, 60, could be anywhere from position 0 to 9.
6. The code, line by line
let low = 0; let high = sorted.length - 1;The range starts as the whole list. Both ends are included.
while (low <= high) { const mid = Math.floor((low + high) / 2);While the range has at least one item (
low <= high), look at its middle.Math.floorrounds down, somidis a whole position.if (sorted[mid] === target) { return mid;Found it.
} else if (sorted[mid] < target) { low = mid + 1; // target is to the rightThe middle is too small, so is everything left of it. The new range starts just after
mid.} else { high = mid - 1; // target is to the left }The middle is too big, so is everything right of it. The new range ends just before
mid.return -1;The range ran out without finding it.
7. How fast is it?
| One by one | Binary search | |
|---|---|---|
| Time | O(n): up to 1,000,000 looks | O(log n): at most 20 looks |
| Extra memory | O(1) | O(1) |
Common mistakes
while (low < high). With<, a range of exactly one item is skipped, so a target sitting there is missed.low = midorhigh = mid.midwas already checked. Leaving it in can make the range stop shrinking, and the loop runs forever.- Searching an unsorted list. Binary search will give wrong answers without any error.
Memorise the solution, once you understand it.
This shows the full solution, then helps you rebuild it from memory in four steps. Remembering it is what lets you write it again in an interview, or in a week. Your result goes into your reviews, so it comes back just before you'd forget.
Learn it by heart: Find the number
Read the 15 lines slowly. For each one, say out loud what it does and why it is there. Then cover it and move on to step 2.
function findTheNumber(sorted, target) { let low = 0; let high = sorted.length - 1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) { return mid; } else if (sorted[mid] < target) { low = mid + 1; // target is to the right } else { high = mid - 1; // target is to the left } } return -1;}