First and Last Occurrences of an Element in a Sorted Array
Problem Statement
Given a sorted array and a target value, find the first and last position of the target element in the array.
If the target is not found, return [-1, -1].
Examples
Input
arr = [5, 7, 7, 8, 8, 10]
target = 8
Output
[3, 4]
Input
arr = [5, 7, 7, 8, 8, 10]
target = 6
Output
[-1, -1]
Approach Using Binary Search
Since the array is sorted, we can use binary search to efficiently find the first and last occurrences.
Steps to Find First Occurrence
1 Initialize left and right pointers
2 Find mid element
3 If target is found, store index and move left to find earlier
Top comments (0)