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

Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, what to keep, what's wrong, and the complexity of your solution.

Sign in to evaluate