Find First and Last Position of Element in Sorted Array - Problem

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Input & Output

Example 1 — Basic Range
$ Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
💡 Note: Target 8 appears at indices 3 and 4. The first occurrence is at index 3, last occurrence at index 4.
Example 2 — Target Not Found
$ Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
💡 Note: Target 6 is not present in the array, so return [-1, -1].
Example 3 — Single Element
$ Input: nums = [], target = 0
Output: [-1,-1]
💡 Note: Empty array, target cannot be found.

Constraints

  • 0 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • nums is a non-decreasing array
  • -109 ≤ target ≤ 109

Visualization

Tap to expand
Find First and Last Position in Sorted Array INPUT Sorted Array (nums): 5 0 7 1 7 2 8 3 8 4 10 5 Index Target Value: 8 Binary Search Range: left=0 mid right=5 Required: O(log n) Use Binary Search! ALGORITHM STEPS 1 Find Left Bound Binary search for first occurrence of target 2 Find Right Bound Binary search for last occurrence of target 3 Left Search Logic if nums[mid] >= target: right = mid - 1 4 Right Search Logic if nums[mid] <= target: left = mid + 1 Search Iterations: Left: mid=2(7) --> mid=4(8) --> mid=3(8) [Found: 3] Right: mid=2(7) --> mid=4(8) [Found: 4] FINAL RESULT Target 8 found at positions: 5 7 7 8 8 10 First: 3 Last: 4 Output: [3, 4] OK - Verified Time: O(log n) Space: O(1) Key Insight: Use TWO binary searches: one modified to find the leftmost occurrence and another for the rightmost. For left bound: when nums[mid] == target, continue searching left (right = mid - 1). For right bound: when nums[mid] == target, continue searching right (left = mid + 1). TutorialsPoint - Find First and Last Position of Element in Sorted Array | Optimal Solution
Asked in
Meta 85 Amazon 72 Microsoft 65 Google 58
456.0K Views
High Frequency
~25 min Avg. Time
15.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen