Find Where a Value Belongs in a Sorted Array

Implement searchInsert

Given a sorted array of distinct integers nums and an integer target, return the index of target if it's found — otherwise return the index where it would be inserted to keep the array sorted. Aim for O(log n) time by binary-searching for the leftmost position whose value is greater than or equal to target.

Example 1:

Input: nums = [1,3,5,6], target = 5

Output: 2

Example 2:

Input: nums = [1,3,5,6], target = 2

Output: 1

Example 3:

Input: nums = [1,3,5,6], target = 7

Output: 4

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁴
  • -10⁴ ≤ nums[i] ≤ 10⁴
  • nums contains distinct values sorted in ascending order
  • -10⁴ ≤ target ≤ 10⁴

nums =

[1, 3, 5, 6]

target =

5