Skip to content

Find First and Last Position of Element in Sorted Array

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

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

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

InputTargetOutputExplanation
[5, 7, 7, 8, 8, 10]8[3, 4]First 8 at index 3, last 8 at index 4
[5, 7, 7, 8, 8, 10]6[-1, -1]Target not in array
[]0[-1, -1]Empty array
[1]1[0, 0]Single element matches target
  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is a non-decreasing array
  • -10^9 <= target <= 10^9
ApproachTimeSpaceBest When
Binary SearchO(log n)O(1)Standard approach, O(log n) required
Linear SearchO(n)O(1)Very small arrays or exact match scenarios
  • Pick Binary Search to meet the O(log n) constraint and learn the two-search pattern.
  • Pick Linear Search to understand the problem conceptually.
Required Time
Binary Search
O(log n) time · O(1) space
Simplicity
Linear Search
O(n) time · O(1) space
★ Recommended

Perform two binary searches: one to find the leftmost position by continuing left when target is found, and one to find the rightmost position by continuing right when target is found.

⏱ Time O(log n) Two binary searches 💾 Space O(1) Only pointers

Input: nums = [5, 7, 7, 8, 8, 10], target = 8

First search (find leftmost 8):

Stepleftrightmidnums[mid]Action
10527< 8 → left = 3
23548== 8 → right = 3
33338== 8 → right = 2
432first = 3

Second search (find rightmost 8):

Stepleftrightmidnums[mid]Action
10527< 8 → left = 3
23548== 8 → left = 5
355510> 8 → right = 4
454last = 4

Result: [3, 4]

function searchRange(nums, target):
// Find first position
left, right = 0, len(nums) - 1
first = -1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
first = mid
right = mid - 1 // Continue searching left
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
if first == -1:
return [-1, -1]
// Find last position
left, right = 0, len(nums) - 1
last = -1
while left <= right:
mid = left + (right - left) / 2
if nums[mid] == target:
last = mid
left = mid + 1 // Continue searching right
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return [first, last]
find_first_last_position_binary_search.py
"""
#34 Find First and Last Position of Element in Sorted Array - Binary Search
Time: O(log n), Space: O(1)
Find the starting and ending position of a given target value in a sorted array.
Use two binary searches: one to find first position, one to find last.
"""
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
"""
Two binary searches to find first and last positions.
"""
if not nums:
return [-1, -1]
# Find first position
left, right = 0, len(nums) - 1
first_pos = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
first_pos = mid
right = mid - 1 # Continue searching left
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
# If target not found
if first_pos == -1:
return [-1, -1]
# Find last position
left, right = 0, len(nums) - 1
last_pos = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
last_pos = mid
left = mid + 1 # Continue searching right
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return [first_pos, last_pos]
# Test cases
if __name__ == "__main__":
sol = Solution()
assert sol.searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert sol.searchRange([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert sol.searchRange([], 0) == [-1, -1]
assert sol.searchRange([1], 1) == [0, 0]
assert sol.searchRange([1, 3], 3) == [1, 1]
print("All test cases passed!")
✓ Simple

Iterate from the start to find the first occurrence, then iterate from the end to find the last occurrence. If the target is not found during the first pass, return [-1, -1].

⏱ Time O(n) Two passes 💾 Space O(1) Only pointers

Input: nums = [5, 7, 7, 8, 8, 10], target = 8

First pass (find first 8):

inums[i]Match?Action
05NoContinue
17NoContinue
27NoContinue
38Yesfirst = 3, break

Second pass (find last 8):

inums[i]Match?Action
510NoContinue
48Yeslast = 4, break

Result: [3, 4]

function searchRange(nums, target):
if len(nums) == 0:
return [-1, -1]
first = -1
for i in range(len(nums)):
if nums[i] == target:
first = i
break
if first == -1:
return [-1, -1]
last = -1
for i in range(len(nums) - 1, -1, -1):
if nums[i] == target:
last = i
break
return [first, last]
find_first_last_position_linear_search.py
"""
#34 Find First and Last Position of Element in Sorted Array - Linear Search
Time: O(n), Space: O(1)
Linear scan to find first and last occurrences of target value.
"""
class Solution:
def searchRange(self, nums: list[int], target: int) -> list[int]:
"""
Linear search to find first and last positions.
"""
if not nums:
return [-1, -1]
first_pos = -1
last_pos = -1
# Find first position
for i in range(len(nums)):
if nums[i] == target:
first_pos = i
break
# If target not found
if first_pos == -1:
return [-1, -1]
# Find last position
for i in range(len(nums) - 1, -1, -1):
if nums[i] == target:
last_pos = i
break
return [first_pos, last_pos]
# Test cases
if __name__ == "__main__":
sol = Solution()
assert sol.searchRange([5, 7, 7, 8, 8, 10], 8) == [3, 4]
assert sol.searchRange([5, 7, 7, 8, 8, 10], 6) == [-1, -1]
assert sol.searchRange([], 0) == [-1, -1]
assert sol.searchRange([1], 1) == [0, 0]
assert sol.searchRange([1, 3], 3) == [1, 1]
print("All test cases passed!")
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
find_first_and_last_position_of_element_in_sorted_array_space_optimized.py
"""
Solution for Find First and Last Position of Element in Sorted Array
"""
def solve():
"""Implementation for approach 3 of Find First and Last Position of Element in Sorted Array"""
pass
if __name__ == "__main__":
print("Solution ready")