34. Find First and Last Position of Element in Sorted Array¶
Edited by Charles
Medium · Python · Array
Problem
Read the original problem on LeetCode.
The official page contains the problem statement, examples, and constraints.
Explanation, examples & other approaches
Core idea
Use Binary Search twice:
Find the leftmost occurrence of target. Find the rightmost occurrence of target.
Original study notes follow, including intermediate snippets and earlier attempts.
Idea¶
Use Binary Search twice:
- Find the leftmost occurrence of
target. - Find the rightmost occurrence of
target.
The key difference from normal binary search is:
When
targetis found, do not immediately return. Continue searching for the boundary.
Find the Left Boundary¶
Use standard binary search:
If:
record the current position:
But this may not be the first occurrence.
For example:
Even if we find 8 at index 4, there may still be another 8 on the left.
Therefore:
This means:
So for the left boundary:
Find the Right Boundary¶
The logic is symmetric.
If:
record the position:
Then continue searching to the right:
because there may be another occurrence of target later in the array.
So for the right boundary:
Example¶
The target range is:
Left Boundary¶
Suppose binary search finds an 8.
Instead of returning immediately:
Continue searching the left half until no earlier 8 exists.
Result:
Right Boundary¶
When an 8 is found:
Continue searching the right half until no later 8 exists.
Result:
Therefore:
If Target Does Not Exist¶
Initialize:
If target is never found, res remains -1.
For example:
Neither binary search finds 6, so:
Key Difference from Normal Binary Search¶
Normal binary search:
LeetCode 34:
Find left boundary:
nums[mid] == target
→ record mid
→ continue left
Find right boundary:
nums[mid] == target
→ record mid
→ continue right
The most important idea is:
We must continue binary search after finding target.
Complexity¶
We perform binary search twice.
Time Complexity:
because:
Space Complexity:
Study record
| Field | Value |
|---|---|
| Attempts | 1 |
| Mastery | ❚ |
| The Latest Attempt | September 8, 2026 |
Python solution¶
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def findLeft():
left, right = 0, len(nums) - 1
res = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
res = mid
right = mid - 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return res
def findRight():
left, right = 0, len(nums) - 1
res = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
res = mid
left = mid + 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return res
return [findLeft(), findRight()]