First and last
medium
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 whole numbers from smallest to largest, and the same number can appear many times in a row.
Return [first, last]: the first and last positions where target appears. If it doesn't appear, return [-1, -1].
Examples
Example 1
- Input
- sorted = [1, 4, 4, 4, 6, 9], target = 4
- Output
- [1, 3]
4 is at positions 1, 2 and 3.
Example 2
- Input
- sorted = [1, 4, 4, 4, 6, 9], target = 5
- Output
- [-1, -1]
There's no 5.
Example 3
- Input
- sorted = [2, 2, 2, 2], target = 2
- Output
- [0, 3]
Every item is a 2.
Rules
sortedhas between 0 and 1,000,000 numbers, from smallest to largest.- Aim for O(log n) time. A value can repeat hundreds of thousands of times, so finding one copy and walking outwards is too slow.
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.
- O(log n): logarithmic time
- The work grows very slowly, because each step throws away half. A million items need only about 20 steps.
- 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, but values can repeat: [1, 4, 4, 4, 6, 9]. All copies of a value sit together. We want where that block of copies starts and ends.
2. Solve an example by hand
In [1, 4, 4, 4, 6, 9], the 4s are at positions 1 to 3. Easy by eye. But a list can have 700,000 copies of the same number.
3. The slow ways
- Check every item: O(n).
- Binary search for any 4, then walk left and right to the ends of the block. That's fast when there are few copies, but with 700,000 copies the walk is O(n) again.
4. Spot the pattern
Sorted list, and we want "the first position where…": binary search, with a twist. Normal binary search stops at the first match it sees, which could be anywhere in the block. We want it to keep going towards the edge.
5. The idea
When sorted[mid] equals the target, don't stop:
- Remember
midas the best answer so far. - For the first copy, keep searching left (
high = mid - 1): there might be an earlier one. - For the last copy, keep searching right (
low = mid + 1).
When the range is empty, the remembered position is the edge. Run it twice, once for each edge.
Binary search that keeps going after a match
sorted
- searching for =
- "the first 4"
- found =
- -1
- answer =
- [-1, -1]
function firstAndLast(sorted, target) { return [findEdge(sorted, target, "first"), findEdge(sorted, target, "last")];} // Binary search that doesn't stop at a match: it remembers it and keeps// looking for an earlier copy ("first") or a later one ("last").function findEdge(sorted, target, edge) { let low = 0; let high = sorted.length - 1; let found = -1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) { found = mid; if (edge === "first") { high = mid - 1; // an earlier copy might be to the left } else { low = mid + 1; // a later copy might be to the right } } else if (sorted[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return found;}Search for the first 4. The range is the whole list.
6. The code, line by line
function firstAndLast(sorted, target) { return [findEdge(sorted, target, "first"), findEdge(sorted, target, "last")];}Two searches: one for each edge. Writing one helper with an
edgesetting avoids writing binary search twice.function findEdge(sorted, target, edge) { let low = 0; let high = sorted.length - 1; let found = -1;The usual range, plus
found: the best match so far, or -1 for none yet.while (low <= high) { const mid = Math.floor((low + high) / 2);Normal binary search: look at the middle.
if (sorted[mid] === target) { found = mid; if (edge === "first") { high = mid - 1; // an earlier copy might be to the left } else { low = mid + 1; // a later copy might be to the right }A match. Remember it, then keep searching on the side where a better match could be.
} else if (sorted[mid] < target) { low = mid + 1; } else { high = mid - 1; }No match: shrink the range towards the target, exactly as in normal binary search.
return found;The range is empty.
foundis the edge, or -1 if the target never appeared.
7. How fast is it?
| One by one | Find any, walk out | Two leaning searches | |
|---|---|---|---|
| Time | O(n) | O(log n + copies) | O(log n) |
| Extra memory | O(1) | O(1) | O(1) |
Common mistakes
- Returning as soon as
sorted[mid] === target. That gives a copy, not the first or last. - Forgetting to remember the match. If you just move
highpast it, and there's no earlier copy, the match is lost.
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: First and last
Read the 24 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 firstAndLast(sorted, target) { return [findEdge(sorted, target, "first"), findEdge(sorted, target, "last")];} // Binary search that doesn't stop at a match: it remembers it and keeps// looking for an earlier copy ("first") or a later one ("last").function findEdge(sorted, target, edge) { let low = 0; let high = sorted.length - 1; let found = -1; while (low <= high) { const mid = Math.floor((low + high) / 2); if (sorted[mid] === target) { found = mid; if (edge === "first") { high = mid - 1; // an earlier copy might be to the left } else { low = mid + 1; // a later copy might be to the right } } else if (sorted[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return found;}