Search Insert Position

Given a sorted array of distinct integers nums and an integer target, return the index if target is found.

If target is not found, return the index where it would be inserted in order to maintain the sorted order of nums.

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

Example 1
Inputnums = [1,3,5,6], target = 5
Output2
The target value 5 is found at index 2.
Example 2
Inputnums = [1,3,5,6], target = 2
Output1
The target value 2 is not found, and it should be inserted at index 1 to keep the array sorted.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^4 <= nums[i] <= 10^4
  • nums contains distinct values sorted in ascending order
  • -10^4 <= target <= 10^4

Asked at 14 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate