VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-first-and-last-positions-of-an-element-in-a-sorted-array/

⇱ First and Last Occurrences in Sorted - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

First and Last Occurrences in Sorted

Last Updated : 15 Apr, 2026

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 5

Input : 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 6

Input: arr[] = [1, 2, 3], x = 4
Output: [-1, -1]
Explanation: No occurrence of 4 in the array, so, output is [-1, -1]

[Naive Approach] - Using Iteration - O(n) Time and O(1) Space

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.


Output
2 5

[Expected Approach] - Two Binary Searches - O(log n) Time and O(1) Space

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.

Finding the First Occurrence of x:

Initialize two pointers, left = 0 and right = n-1.

Initialize first = -1 (default if element not found).

While (left <= right):

  • calculate mid = (left + right) / 2.
  • If the arr[mid] == x, update first = mid and move to the left subarray.
  • If the arr[mid] < x, move to the right subarray.
  • If the arr[mid] > x, move to the left subarray.

first contains the first occurrence index (or -1 if not found).

Finding the Last Occurrence of x:

Initialize two pointers, left = 0 and right = n-1.

Initialize last = -1.

While (left <= right):

  • calculate mid = (left + right) / 2.
  • If arr[mid] == x, update last = mid and move to the right subarray.
  • If arr[mid] < x, move to the right subarray.
  • If arr[mid] > x, move to the left subarray.

last contains the last occurrence index.



Output
2 5

[Alternate Approach] - Using Inbuilt Functions - O(log n) Time and O(1) Space

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.


Output
2 5

Extended Problem : Count number of occurrences in a sorted array

Comment
Article Tags: