Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Binary search

Where a value belongs in a sorted array

Easy · Target 10 minutes · Binary search · Type asked atAmazonMicrosoftBloomberg

Given a sorted array nums of distinct integers and an integer target, return the index of target if it is present. Otherwise return the index where it would have to be inserted to keep the array sorted. Use O(log n) comparisons.

Examples

InputOutputWhy
nums = [1, 3, 5, 6], target = 52
nums = [1, 3, 5, 6], target = 212 goes between 1 and 3.
nums = [1, 3, 5, 6], target = 74After the last element: the length of the array.

Constraints

  • 1 ≤ n ≤ 10⁴
  • −10⁴ ≤ nums[i], target ≤ 10⁴
  • nums is strictly increasing

Hints

Hint 1

Both cases ask for the same index: the first position whose element is at least target.

Hint 2

The test "nums[i] ≥ target" is false for a prefix of the array and true for the rest. Search for the first true.

Hint 3

Let hi start at n, one past the end, so that "every element is smaller" has an answer to land on.

Where people lose marks

  • Starting with hi = n − 1, which leaves no way to return n when target is larger than everything.
  • Mixing the closed-range exact search with the half-open lower bound: hi = mid − 1 in a lower bound skips the answer.
  • Returning mid instead of lo after the loop.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.