Search insert position
Coding problemEasyAsked in: Adobe, Amazon, Apple, Google, Meta, Microsoft
Given a list of distinct integers sorted from smallest to largest and a target value, return the position of the target if it is in the list. If it is not, return the position where it would be inserted to keep the list sorted. Positions count from 0.
Use the sorted order to halve the search each step.
Examples
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
After the last value.
Constraints
- The list holds between 0 and 100,000 integers
- Values are distinct, sorted ascending, and between -1,000,000,000 and 1,000,000,000
- The target is in the same range
Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.
Run your code to see the results here. Ctrl or Cmd + Enter runs; add Shift to submit.
to answer and keep your progress. Reading is free for everyone.