Finding the first copy and the insertion point
After this: Change the loop to find the first copy of a value, or where a missing value would go.
On this page · 4 sections · 3 checks
So far, our loop answers one question: is this value here, and at which index? With a few small changes, the same loop answers two more useful questions.
- If a value appears several times, where is the first copy?
- If a value is missing, where would it go?
The first copy
Take [1, 2, 2, 2, 3] and search for 2 with the loop you already know. The first probe is index 2, which holds a 2, so the loop stops and answers 2. That is true, but it is often not what was asked. The first 2 is at index 1.
Finding the first copy of a value is called finding its first occurrence.
- Binary search for 2There are three copies of 2. The plain loop stops at whichever copy it probes first.
- 01
- 12
- 22
- 32
- 43
Run an operation to begin.
A hit at mid proves that the target is there. It does not prove that mid is the first copy. So we do not stop. We remember the hit, and then we keep searching to the left of it, exactly as if the value had been too big.
Here is the search for 2 in [1, 2, 2, 2, 3].
| Probe | lo | hi | mid | nums[mid] | Result |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 2 | A hit. Remember index 2, and hi becomes 1 |
| 2 | 0 | 1 | 0 | 1 | Too small, so lo becomes 1 |
| 3 | 1 | 1 | 1 | 2 | A hit. Remember index 1, and hi becomes 0 |
Now lo is greater than hi, so the range is empty. The last index we remembered is 1, and that is the answer.
def first_occurrence(nums, target): lo, hi = 0, len(nums) - 1 found = -1 while lo <= hi: mid = (lo + hi) // 2 if nums[mid] == target: found = mid # a hit, but maybe not the first: remember it ... hi = mid - 1 # ... and keep looking to the left of it elif nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return found
nums = [1, 2, 2, 2, 3]print(first_occurrence(nums, 2), first_occurrence(nums, 3), first_occurrence(nums, 4))1 4 -1
static int firstOccurrence(int[] nums, int target) { int lo = 0, hi = nums.length - 1; int found = -1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) { found = mid; // a hit, but maybe not the first: remember it ... hi = mid - 1; // ... and keep looking to the left of it } else if (nums[mid] < target) { lo = mid + 1; } else { hi = mid - 1; } } return found;}
int[] nums = {1, 2, 2, 2, 3};System.out.println(firstOccurrence(nums, 2) + " " + firstOccurrence(nums, 3) + " " + firstOccurrence(nums, 4));1 4 -1
Here is how to read it.
foundstarts at −1, which means "no hit yet".- On a hit, the code saves mid in
foundand setshi = mid - 1. These are the highlighted lines. - The other two results work as before. The loop now ends only when the range is empty, and
foundholds the leftmost hit it saw. - The program prints 1, because the first 2 is at index 1. It prints 4 for the 3, and −1 for the 4, which is not there.
The search still cuts the range in half on every probe, so it is still O(log n). The extra copies add no extra work.
If you change the hit line to lo = mid + 1, the search goes right instead and finds the last copy. Then last − first + 1 counts the copies. For the 2s above, that is 3 − 1 + 1 = 3.
Where a missing value would go
Think back to the search for 35 in [10, 20, 30, 40, 50], from the lesson on the loop. It was a miss, and it ended with lo at 3 and hi at 2. The loop returned −1, but it had worked out something useful. Look at index 3, where lo stopped.
| Index | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| Value | 10 | 20 | 30 | 40 | 50 |
Every cell before index 3 is smaller than 35, and every cell from index 3 on is bigger. So 35 belongs at index 3, and the row would become [10, 20, 30, 35, 40, 50].
This is always true when the loop ends without a hit. lo and hi have crossed, so lo = hi + 1. Every cell before lo was ruled out for being too small, and every cell after hi was ruled out for being too big. So lo is the one index where the target can go and keep the row sorted. This index is called the .
Only one line changes: return lo instead of −1.
def insertion_point(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 lo # not found: every cell before lo is smaller, every cell from lo on is bigger
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(insertion_point(nums, 7), insertion_point(nums, 100), insertion_point(nums, 1))2 10 0
static int insertionPoint(int[] nums, int target) { int lo = 0, hi = nums.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return lo; // not found: every cell before lo is smaller, every cell from lo on is bigger}
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(insertionPoint(nums, 7) + " " + insertionPoint(nums, 100) + " " + insertionPoint(nums, 1));2 10 0
Here is what it prints for the ten-cell row.
- 7 goes at index 2, between 5 and 8.
- 100 goes at index 10, which is the length of the row. lo is allowed to end one past the last cell, because an insertion point is a gap between cells, not a cell.
- 1 goes at index 0, the front.
- Binary search for 77 is not here. Watch where lo ends: at index 2, between 5 and 8.
- Binary search for 60
- Binary search for 100
- 02
- 15
- 28
- 312
- 416
- 523
- 638
- 756
- 872
- 991
Run an operation to begin.
Check yourself
Searching [1, 2, 2, 2, 3] for 2 with the first-copy search from the lesson. Which indexes does it probe, in order, and what does it return?
Searching [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] for 60 ends without a hit. What is lo when the loop stops, and what does it mean?
What does this print?
def insertion_point(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 lo # not found: every cell before lo is smaller, every cell from lo on is bigger
nums = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91]print(insertion_point(nums, 7), insertion_point(nums, 100), insertion_point(nums, 1))static int insertionPoint(int[] nums, int target) { int lo = 0, hi = nums.length - 1; while (lo <= hi) { int mid = lo + (hi - lo) / 2; if (nums[mid] == target) return mid; if (nums[mid] < target) lo = mid + 1; else hi = mid - 1; } return lo; // not found: every cell before lo is smaller, every cell from lo on is bigger}
int[] nums = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};System.out.println(insertionPoint(nums, 7) + " " + insertionPoint(nums, 100) + " " + insertionPoint(nums, 1));Connect
- Keep searching to the left after a hit to find the first copy of a value.
- Return lo instead of −1 to get the insertion point of a missing value.