First and last position of a value in a sorted list
Coding problemMediumAsked in: Amazon, Google, Microsoft
Given a list of integers sorted from smallest to largest (values may repeat) and a target, return the first and the last position of the target, counting from 0. If the target is not in the list, return [-1, -1].
Aim for O(log n) time: an interviewer will ask what happens when the target fills the whole list.
Examples
Example 1
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Example 3
Input: nums = [2,2], target = 2
Output: [0,1]
Constraints
- The list holds between 0 and 100,000 integers
- Values are 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.