You are given a list of distinct whole numbers, nums, sorted from smallest to largest, and a number target.
If target is in the list, return its index. If it is not, return the index it would take if you inserted it so the list stayed sorted. Your solution must run in O(log n) time.
Example 1
Input: nums = [2, 4, 7, 10, 13], target = 10 Output: 3 Why: 10 is already at index 3
2 more examples and the constraints
Example 2
Input: nums = [2, 4, 7, 10, 13], target = 5 Output: 2 Why: 5 fits between 4 and 7
Example 3
Input: nums = [2, 4, 7, 10, 13], target = 15 Output: 5 Why: 15 is bigger than everything, so it goes at the end
Constraints
- 1 ≤ length of nums ≤ 10,000
- −10,000 ≤ each number, and the target, ≤ 10,000
- nums is sorted in increasing order with no repeats
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan from the leftO(n)
- Binary searchO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 numbers | Verdict |
|---|---|---|---|
| Scan from the left | O(n) | Correct, but misses O(log n) | |
| Binary search | O(log n) | Best; about 14 reads |
n = length of nums.
Edge cases to test
- Target before every value. [2, 4, 7, 10, 13] with target −1 gives 0.
- Target after every value. The answer is the length of the list, an index that does not exist yet.
loends there naturally. - A single number. [6] gives 0 for a target of 3 or 6, and 1 for 9.
- Target present. Return its own index, not the spot after it.
Common mistakes
- Returning
hiormidafter the loop instead oflo;lois the only one that always lands on the insert spot. - Writing
while lo < hiwithhi = mid - 1, which skips the last candidate. - Returning −1 when the target is missing, as plain binary search does.
How to talk through it
- 1Clarify. Are the values distinct? Can the answer be one past the last index?
- 2Give the scan. The first value at least the target is the answer; it is O(n), and the list is sorted, so we can do better.
- 3Reframe as a boundary. Every value left of the answer is smaller and every value from it on is not. Binary search finds that boundary.
- 4Code it and explain lo. Say why
lois the insert spot when the loop ends: everything left of it is smaller, everything right ofhiis bigger. - 5Test out loud. Run a target smaller than all, larger than all, and one that is present.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?