Open In App

Find first and last positions of an element in a sorted array

Last Updated : 04 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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.

C++
#include <bits/stdc++.h>
using namespace std;

// Function for finding first and last occurrence of x
vector<int> find(vector<int> arr, int x) {
    int n = arr.size();

    // Initialize first and last index
    int first = -1, last = -1;

    for (int i = 0; i < n; i++) {

        // If x is different, continue
        if (x != arr[i])
            continue;
        
        // If first occurrence found
        if (first == -1)
            first = i;
        
        // Update last occurrence
        last = i;
    }
    vector<int> res = {first, last};
    return res;
}

int main() {
    vector<int> arr = {1, 3, 5, 5, 5, 5, 67, 123, 125};
    int x = 5;
    vector<int> res = find(arr, x);
    cout << res[0] << " " << res[1];
    return 0;
}
Java Python C# JavaScript

Output
2 5

[Expected Approach] – Using Binary Search – O(log n) Time and O(1) Space

The idea is to find the first and last occurrence of a given number separately using binary search.

Follow the below given approach:

1. For the first occurrence of a number 

  • If (high >= low): Calculate  mid = low + (high – low)/2;
  • If ((mid == 0 || x > arr[mid-1]) && arr[mid] == x): return mid
  • Else if (x > arr[mid]): return first(arr, (mid + 1), high, x, n);
  • Else: return first(arr, low, (mid -1), x, n);
  • Otherwise: return -1;

2. For the last occurrence of a number 

  • if (high >= low): calculate mid = low + (high – low)/2;
  • if( ( mid == n-1 || x < arr[mid+1]) && arr[mid] == x ): return mid;
  • else if(x < arr[mid]): return last(arr, low, (mid -1), x, n);
  • else: return last(arr, (mid + 1), high, x, n);
  • otherwise: return -1;
C++
#include <bits/stdc++.h>
using namespace std;

//Function for finding last occurrence of x
int findLast(vector<int> arr, int x) {
    int n = arr.size();

    // Initialize low and high index
    // to find the last occurrence
    int low = 0, high = n - 1;

    // Initialize last occurrence
    int last = -1;

    // Find last occurrence of x
    while(low <= high) {

        // Find the mid index
        int mid = (low + high) / 2;

        // If x is equal to arr[mid]
        if (x == arr[mid]) {
            last = mid;
            low = mid + 1;
        }

        // If x is less than arr[mid], 
        // then search in the left subarray
        else if (x < arr[mid])
            high = mid - 1;

        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            low = mid + 1;
    }

    return last;
}

// Function for finding first occurrence of x
int findFirst(vector<int> arr, int x) {
    int n = arr.size();

    // Initialize low and high index
    // to find the first occurrence
    int low = 0, high = n - 1;

    // Initialize first occurrence
    int first = -1;

    // Find first occurrence of x
    while(low <= high) {

        // Find the mid index
        int mid = (low + high) / 2;

        // If x is equal to arr[mid]
        if (x == arr[mid]) {
            first = mid;
            high = mid - 1;
        }

        // If x is less than arr[mid], 
        // then search in the left subarray
        else if (x < arr[mid])
            high = mid - 1;

        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            low = mid + 1;
    }

    return first;
}

// Function for finding first and last occurrence of x
vector<int> find(vector<int> arr, int x) {
    int n = arr.size();

    // Find first and last index
    int first = findFirst(arr, x);
    int last = findLast(arr, x);

    vector<int> res = {first, last};
    return res;
}

int main() {
    vector<int> arr = {1, 3, 5, 5, 5, 5, 67, 123, 125};
    int x = 5;
    vector<int> res = find(arr, x);
    cout << res[0] << " " << res[1];
    return 0;
}
Java Python C# JavaScript

Output
2 5

[Alternate Approach – 1] – Using Binary Search – O(log n) Time and O(1) Space

In the above given approach, we are creating two functions to find the first and last occurrence of the number separately. But instead of doing so, we can use a Boolean findFirst, which will be “true”, if we are searching for the first index and false otherwise. If arr[mid] == x, and findFirst is “true” set high = mid – 1, else set low = mid + 1. Everything else will work similar to above approach.     

C++
#include <bits/stdc++.h>
using namespace std;

int search(vector<int> &arr, int x, bool findStart) {
    int n = arr.size();

    // Initialize low and high index
    int low = 0, high = n - 1;

    // Initialize the index
    int ind = -1;

    // Find occurrence of x
    while(low <= high) {

        // Find the mid index
        int mid = (low + high) / 2;

        // If x is equal to arr[mid]
        if (x == arr[mid]) {
            ind = mid;

            if(findStart == true)
                high = mid - 1;
            else
                low = mid + 1;
        }

        // If x is less than arr[mid], 
        // then search in the left subarray
        else if (x < arr[mid])
            high = mid - 1;

        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            low = mid + 1;
    }

    return ind;
}

// Function for finding first and last occurrence of x
vector<int> find(vector<int> &arr, int x) {

    // return index of first occurrence
    int first = search(arr, x, true);

    // return index of last occurrence
    int last = search(arr, x, false);
    vector<int> res = {first, last};
    return res;
}

int main() {
    vector<int> arr = {1, 3, 5, 5, 5, 5, 67, 123, 125};
    int x = 5;
    vector<int> res = find(arr, x);
    cout << res[0] << " " << res[1];
    return 0;
}
Java Python C# JavaScript

Output
2 5

[Alternate Approach – 2] – 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 and upper bound to find the last occurrence of the number.

C++
#include <bits/stdc++.h>
using namespace std;

// Function for finding first and last occurrence of x
vector<int> find(vector<int> arr, int x) {
    int n = arr.size();

    // return index of first number
    // greater than or equal to x
    int first = lower_bound(arr.begin(), arr.end(), x) - arr.begin();

    // return index of first number
    // greater than x
    int last = upper_bound(arr.begin(), arr.end(), x) - arr.begin() - 1;

    // If x is not present
    if (first == n || arr[first] != x) {
        first = -1;
        last = -1;
    }
    vector<int> res = {first, last};
    return res;
}

int main() {
    vector<int> arr = {1, 3, 5, 5, 5, 5, 67, 123, 125};
    int x = 5;
    vector<int> res = find(arr, x);
    cout << res[0] << " " << res[1];
    return 0;
}
Java Python C# JavaScript

Output
2 5

Extended Problem : Count number of occurrences in a sorted array




Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg