Leetcode 34. 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.
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
Input: nums = [], target = 0
Output: [-1,-1]
O(log n)
complexity.findFirstPosition
that performs binary search to find the first position of the target.findLastPosition
that performs binary search to find the last position of the target.-1
.[firstPosition, lastPosition]
.public class Solution {
public int[] searchRange(int[] nums, int target) {
int firstPos = findFirstPosition(nums, target);
int lastPos = findLastPosition(nums, target);
return new int[]{firstPos, lastPos};
}
private int findFirstPosition(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
right = mid - 1; // Move left to find the first occurrence
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
private int findLastPosition(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
result = mid;
left = mid + 1; // Move right to find the last occurrence
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
}
O(log n)
time.O(log n) + O(log n) = O(log n)
.This approach ensures that we satisfy the requirements of optimal time complexity for this problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?