34. Find First and Last Position of Element in Sorted Array
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
Method Explanation
This solution finds the first and last positions of a target element in a sorted array using a modified binary search approach, which guarantees an O(log n) runtime. Instead of two separate, slightly different binary searches for the first and last positions, a more elegant and reusable approach is to use the concept of lower_bound.
Solution
Find First and Last Position of Element in Sorted Array in Python
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
def find_lower_bound(arr: List[int], val: int) -> int:
"""Finds the first index where element >= val."""
left, right = 0, len(arr)
while left < right:
mid = left + (right - left) // 2
if arr[mid] >= val:
# This could be the lower bound, search in the left half
right = mid
else:
# Element is too small, search in the right half
left = mid + 1
return left
# Find the first position of the target.
start = find_lower_bound(nums, target)
# If the target is not found, return [-1, -1].
# This check handles empty array, target smaller/larger than all elements.
if start == len(nums) or nums[start] != target:
return [-1, -1]
# Find the first position of an element > target.
# This is the same as the lower bound of target + 1.
end_plus_one = find_lower_bound(nums, target + 1)
# The last position of the target is one less than this.
return [start, end_plus_one - 1]
Find First and Last Position of Element in Sorted Array in Java
class Solution {
public int[] searchRange(int[] nums, int target) {
// Find the first occurrence of the target.
int start = findLowerBound(nums, target);
// If 'start' is out of bounds or the element at 'start' is not the target,
// it means the target is not in the array.
if (start == nums.length || nums[start] != target) {
return new int[]{-1, -1};
}
// Find the first occurrence of an element greater than the target.
// This is equivalent to finding the lower bound of target + 1.
int end = findLowerBound(nums, target + 1);
// The last occurrence of the target is at the index just before 'end'.
return new int[]{start, end - 1};
}
// Helper function to find the lower bound of a target in a sorted array.
// The lower bound is the first index 'i' where nums[i] >= target.
private int findLowerBound(int[] nums, int target) {
int left = 0;
int right = nums.length;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
// The element at mid is a potential answer, so we search in the left half [left, mid].
right = mid;
} else {
// The element at mid is too small, so we search in the right half [mid + 1, right].
left = mid + 1;
}
}
// 'left' is the insertion point, which is the lower bound.
return left;
}
}
Find First and Last Position of Element in Sorted Array in C++
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
// Find the first occurrence of target (lower_bound).
int start = lower_bound(nums, target);
// If 'start' is out of bounds or the element at 'start' is not the target,
// then the target is not in the array.
if (start == nums.size() || nums[start] != target) {
return {-1, -1};
}
// Find the first occurrence of an element greater than target.
// The upper_bound of target is the lower_bound of target + 1.
int end = lower_bound(nums, target + 1);
// The last occurrence of target is at index end - 1.
return {start, end - 1};
}
private:
// Helper function to find the first index i such that nums[i] >= target.
// This is equivalent to C++'s std::lower_bound.
int lower_bound(const vector<int>& nums, int target) {
int left = 0, right = nums.size();
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
};
Find First and Last Position of Element in Sorted Array in TypeScript
function searchRange(nums: number[], target: number): number[] {
// Helper function to find the lower bound of a target.
// This is the first index where the element is >= target.
const findLowerBound = (targetValue: number): number => {
let left = 0;
let right = nums.length;
while (left < right) {
// Prevent overflow and get the middle index
const mid = Math.floor(left + (right - left) / 2);
if (nums[mid] >= targetValue) {
// This could be the answer, so search in the left half [left, mid]
right = mid;
} else {
// The element at mid is too small, so search in the right half [mid + 1, right]
left = mid + 1;
}
}
// 'left' will be the insertion point, which is our lower bound.
return left;
};
// Find the starting position of the target.
const start = findLowerBound(target);
// If the target is not found, return [-1, -1].
// This condition checks if 'start' is out of bounds or if the element at 'start' is not the target.
if (start === nums.length || nums[start] !== target) {
return [-1, -1];
}
// Find the starting position of the first element strictly greater than target.
// This is the lower bound of target + 1.
const endPlusOne = findLowerBound(target + 1);
// The ending position of the target is the index just before endPlusOne.
return [start, endPlusOne - 1];
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.