AlgoFrames

Search insert position

Challenge · Write code · about 15 min

Given a sorted array of distinct integers nums and a target, return the index of target if it is present. Otherwise return the index where it would be inserted to keep the array sorted.

The solution must run in O(log n) time.

Example 1

Input:

[[1,3,5,6],5]

Output:

2

Example 2

Input:

[[1,3,5,6],2]

Output:

1

2 is missing; it would go between 1 and 3.

Example 3

Input:

[[1,3,5,6],7]

Output:

4

Larger than everything: the position after the last value.

Constraints

  • 1 ≤ nums.length ≤ 10,000 (0 allowed in one hidden test)
  • -10,000 ≤ nums[i], target ≤ 10,000
  • nums is sorted ascending with distinct values

Learn the idea first: Binary search, a visual lesson.

More Binary search problems