![]() |
VOOZH | about |
Given a sorted array arr[] with possibly some duplicates, the task is to find the first and last occurrences of an element x in the given array.
Note: If the number x is not found in the array then return both the indices as -1.
Examples:
Input : arr[] = [1, 3, 5, 5, 5, 5, 67, 123, 125], x = 5
Output : [2, 5]
Explanation: First occurrence of 5 is at index 2 and last occurrence of 5 is at index 5Input : arr[] = [1, 3, 5, 5, 5, 5, 7, 123, 125 ], x = 7
Output : [6, 6]
Explanation: First and last occurrence of 7 is at index 6Input: arr[] = [1, 2, 3], x = 4
Output: [-1, -1]
Explanation: No occurrence of 4 in the array, so, output is [-1, -1]
Table of Content
The idea is to simply iterate on the elements of the given array and keep track of first and last occurrence of the value x.
2 5
The idea in this is as the array is sorted so we can use the binary search to find the first and last occurrence of x.
Initialize two pointers, left = 0 and right = n-1.
Initialize first = -1 (default if element not found).
While (left <= right):
first contains the first occurrence index (or -1 if not found).
Initialize two pointers, left = 0 and right = n-1.
Initialize last = -1.
While (left <= right):
last contains the last occurrence index.
2 5
The idea is to use inbuilt functions to find the first and last occurrence of the number in the array arr[]. Like in C++, we can use lower bound to find the first occurrence and upper bound to find the last occurrence of the number.
2 5
Extended Problem : Count number of occurrences in a sorted array