
# Finding First and Last Occurrence in a Sorted Array (Java)
When working with sorted arrays, one common problem is to find the first and last occurrence of a given element. This becomes especially interesting when the array contains duplicate values . In this blog, we’ll walk through an efficient approach using Binary Search and implement it in Java. 🚀 Problem Statement Given a sorted array arr[] (possibly with duplicates) and a number x , find: The first occurrence of x The last occurrence of x 👉 Example Input : arr = [ 1 , 2 , 2 , 2 , 3 , 4 , 5 ] x = 2 Output : [ 1 , 3 ] If x is not present, return: [ - 1 , - 1 ] 💡 Key Idea A normal binary search finds any one occurrence of x . But here, we need the extreme positions : First occurrence → keep searching on the left side Last occurrence → keep searching on the right side So, we modify binary search slightly and run it twice . ⚡ Approach 1. Find First Occurrence If arr[mid] == x , store index and move left Continue searching in the left half 2. Find Last Occurrence If arr[mid] == x , store index
Continue reading on Dev.to Tutorial
Opens in a new tab



