706467. First and last occurrences of x
Easy
First and Last Occurrences of x
Summary
Given an array of distinct integers, find the first and last occurrences of a given target integer x. This problem involves searching for specific elements in an array, making it a classic problem in algorithmic programming. The key concept involved is binary search, which allows us to efficiently locate the desired elements.
Detailed Explanation
To solve this problem, we will use binary search to find the first and last occurrences of x in the given array. Here's a step-by-step breakdown of the solution:
- First, sort the input array in ascending order.
- Initialize two variables
first_occurrenceandlast_occurrenceto negative infinity. - Perform a binary search on the sorted array to find the first occurrence of
x. Start by considering the middle element of the array.- If the middle element is equal to
x, updatefirst_occurrenceto the current index and move the search range to the left half of the array. - If the middle element is less than
x, move the search range to the right half of the array. - If the middle element is greater than
x, updatefirst_occurrenceto the current index and move the search range to the left half of the array.
- If the middle element is equal to
- Once we find the first occurrence, perform another binary search to find the last occurrence of
x. Start by considering the middle element of the array.- If the middle element is equal to
x, updatelast_occurrenceto the current index and move the search range to the right half of the array. - If the middle element is less than
x, move the search range to the left half of the array. - If the middle element is greater than
x, updatelast_occurrenceto the current index and move the search range to the right half of the array.
- If the middle element is equal to
- Return the values of
first_occurrenceandlast_occurrence.
Time complexity: O(log n), where n is the length of the input array.
Space complexity: O(1), as we only use a constant amount of space to store the variables first_occurrence, last_occurrence, and the search range.
Optimized Solutions
Java
public class Solution {
public int[] firstAndLastPosition(int[] arr, int x) {
Arrays.sort(arr);
int first = binarySearch(arr, x, true);
int last = binarySearch(arr, x, false);
return new int[]{first, last};
}
private int binarySearch(int[] arr, int x, boolean isFirst) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == x) {
return isFirst ? mid : high;
} else if (arr[mid] < x) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // not found
}
}