Where It Would Go

EasyBinary Search≈ 15 min

You are given a list of distinct integers nums, sorted from smallest to largest, and a target. If target is in the list, return its index. If it is not, return the index where it would go: the place it would take if it were inserted so that the list stays sorted.

Examples

text
nums = [1, 3, 5, 6], target = 5   →  2
nums = [1, 3, 5, 6], target = 2   →  1
nums = [1, 3, 5, 6], target = 7   →  4
nums = [1, 3, 5, 6], target = 0   →  0

2 would go between 1 and 3, at index 1. 7 is larger than every number, so it would go at the end, index 4.

Constraints

  • Between 0 and 100,000 numbers, sorted and distinct, each between -1,000,000,000 and 1,000,000,000.
  • Aim for O(log n): a list four times longer should take only a couple of steps more.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.