Loading practice problems…
Loading your practice workspace…
Loading code editor…
13 / 29
Sign in
Algorithms/Binary Search

Search Insert Position

easy20 min

Given a sorted array of distinct integers and a target, return the target's index when present.

Otherwise, return the index where the target should be inserted to keep the array sorted.

Example 1

Inputnums = [1, 3, 5, 6], target = 5

Output2

5 is already the third element. Its zero-based index is 2.

Example 2

Inputnums = [1, 3, 5, 6], target = 2

Output1

2 belongs between 1 and 3, so its insertion index is 1.

Constraints

  • 1 ≤ nums.length ≤ 10,000
  • nums is strictly increasing.
Binary SearchArrays