Where it would go
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. You want to add value to it and keep it sorted.
Return the position value should go at: the position of the first number that is not smaller than value. If value is already in the list, that's its own position. If it's bigger than everything, it goes at the end: position sorted.length.
Examples
Example 1
- Input
- sorted = [2, 4, 7, 9], value = 7
- Output
- 2
7 is already there, at position 2.
Example 2
- Input
- sorted = [2, 4, 7, 9], value = 5
- Output
- 2
5 belongs between 4 and 7, at position 2.
Example 3
- Input
- sorted = [2, 4, 7, 9], value = 10
- Output
- 4
10 is bigger than everything, so it goes at the end.
Rules
sortedhas between 0 and 1,000,000 different numbers, from smallest to largest.
Words on this page, in plain English (4)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.
- Length
- How many items a list (or letters a string) has. The last position is always
length - 1. - 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
We're not just looking for value; we want where it belongs. That's the position of the first number that's at least value. If value is already there, that's its own position. If it's bigger than everything, it belongs at the end, position sorted.length, which is one past the last item.
2. Solve an example by hand
[2, 4, 7, 9] and value = 5. Go through and ask "is this at least 5?": 2, no. 4, no. 7, yes. The first yes is at position 2, so 5 goes at position 2.
Notice the answers: no, no, yes, yes. Once they turn to yes, they stay yes, because the list is sorted.
3. The slow way
sorted.findIndex(n => n >= value) asks the question of each item in turn. O(n).
4. Spot the pattern
A yes/no question that flips once along a sorted list, and we want where it flips: that's binary search for the first yes.
5. The idea
The range low to high always contains the answer. This time, high starts at sorted.length, because the answer might be "at the end".
- If
sorted[mid] >= value(yes), the answer ismidor earlier. Keepmidin the range:high = mid. - If not (no), the answer is after
mid:low = mid + 1.
When low and high meet, that's the first yes.
Find the first position that's big enough
sorted
- value =
- 10
function whereItGoes(sorted, value) { let low = 0; let high = sorted.length; // value might go after every item while (low < high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] >= value) { high = mid; // mid could be the answer; look no further right } else { low = mid + 1; // mid is too small; the answer is after it } } return low;}10 could go anywhere from position 0 to 6 (the very end), so the range is 0 to 6.
6. The code, line by line
let low = 0; let high = sorted.length; // value might go after every itemThe answer is somewhere from 0 to
sorted.length. Herehighis a possible answer itself, unlike in Find the number.while (low < high) { const mid = Math.floor((low + high) / 2);low < high, not<=: when they're equal, the range holds exactly one possible answer, and we're done.if (sorted[mid] >= value) { high = mid; // mid could be the answer; look no further rightYes:
midmight be the first yes, so keep it withhigh = mid.} else { low = mid + 1; // mid is too small; the answer is after it }No: everything up to
midis too small.return low;lowis the first position that's big enough.
Why can't this loop forever? mid is always less than high (it rounds down), so high = mid always shrinks the range, and so does low = mid + 1.
7. How fast is it?
| One by one | Binary search | |
|---|---|---|
| Time | O(n) | O(log n) |
| Extra memory | O(1) | O(1) |
This "first yes" search is the most useful form of binary search. Once you know it, many problems become: what's my yes/no question, and is it no-then-yes?
Common mistakes
- Starting
highatsorted.length - 1. Then "after everything" can never be the answer. high = mid - 1in this version.midmight be the answer; don't throw it away.
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: Where it would go
Read the 13 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 whereItGoes(sorted, value) { let low = 0; let high = sorted.length; // value might go after every item while (low < high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] >= value) { high = mid; // mid could be the answer; look no further right } else { low = mid + 1; // mid is too small; the answer is after it } } return low;}