DEV Community

Abinaya Dhanraj
Abinaya Dhanraj

Posted on

Finding first and last occurrence in a sorted array

How I Understood Finding First and Last Occurrence in a Sorted Array
When I first saw this problem, it looked tricky because it asks to find both the first and last positions of a target number efficiently.
After thinking about it, I realized binary search can be used twice to solve this in O(log n) time.

Problem
Given a sorted array and a target x, return the first and last indices of x in the array.
If x is not present, return [-1, -1].
Example:
Python
arr = [1, 2, 2, 2, 3, 4, 5]
x = 2

Output: [1, 3]

Python
arr = [1, 2, 3, 4, 5]
x = 6

Output: [-1, -1]

What I Noticed
Instead of scanning the array linearly, I focused on using binary search:
To find the first occurrence, whenever I find x, I continue searching left
To find the last occurrence, whenever I find x, I continue searching right
This guarantees we find both indices in O(log n).

What Helped Me
Breaking the problem into two binary searches makes it very clear:
Find first occurrence:
Binary search
If arr[mid] == x, record mid and move high = mid - 1
Find last occurrence:
Binary search
If arr[mid] == x, record mid and move low = mid + 1
Finally, return both indices as a list.

Code (Python)
Python
class Solution:
def find(self, arr, n, x):
def find_first(arr, x):
low, high = 0, len(arr) - 1
first = -1
while low <= high:
mid = low + (high - low) // 2
if arr[mid] == x:
first = mid
high = mid - 1 # Look to the left
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return first

    def find_last(arr, x):
        low, high = 0, len(arr) - 1
        last = -1
        while low <= high:
            mid = low + (high - low) // 2
            if arr[mid] == x:
                last = mid
                low = mid + 1  # Look to the right
            elif arr[mid] < x:
                low = mid + 1
            else:
                high = mid - 1
        return last

    # Return both indices as a list
    return [find_first(arr, x), find_last(arr, x)]
Enter fullscreen mode Exit fullscreen mode

Example Usage
Python
arr = [1, 2, 2, 2, 3, 4, 5]
x = 2
solution = Solution()
print(solution.find(arr, len(arr), x))
Output:
Plain text
[1, 3]

Complexity
Time: O(log n) — two binary searches
Space: O(1) — constant extra space

What I Learned
This problem shows how slight modifications of binary search can solve many array problems:
Search left to find the first occurrence
Search right to find the last occurrence
Combine results efficiently

Final Thought
At first, finding both indices seemed like multiple passes might be needed.
Once I realized:
“Use binary search twice with small adjustments”
…it became elegant and efficient.
This is a classic example of binary search variants in sorted arrays.

Top comments (0)