First and Last Occurrences in Sorted (original) (raw)

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]

Table of Content

[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 #include

using namespace std;

vector find(vector 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 arr = {1, 3, 5, 5, 5, 5, 7, 123, 125}; int x = 5; vector res = find(arr, x); cout << res[0] << " " << res[1]; return 0; }

C

#include <stdio.h>

void find(int arr[], int n, int x, int *first, int *last) { // Initialize first and last *first = -1; *last = -1;

for (int i = 0; i < n; i++)
{
    // If different element found, continue
    if (arr[i] != x)
        continue;

    // First occurrence found
    if (*first == -1)
        *first = i;

    // Update last occurrence
    *last = i;
}

}

int main() { int arr[] = {1, 3, 5, 5, 5, 5, 7, 123, 125}; int n = sizeof(arr) / sizeof(arr[0]); int x = 5; int first, last; find(arr, n, x, &first, &last); printf("%d %d\n", first, last); return 0; }

Java

import java.util.*;

class GfG { static ArrayList find(int[] arr, int x) { int n = arr.length;

    // 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;
    }
    ArrayList<Integer> res = new ArrayList<>();
    res.add(first);
    res.add(last);
    return res;
}

public static void main(String[] args) {
    int[] arr = {1, 3, 5, 5, 5, 5, 7, 123, 125};
    int x = 5;
    ArrayList<Integer> res = find(arr, x);
    System.out.println(res.get(0) + " " + res.get(1));
}

}

Python

def find(arr, x): n = len(arr)

# Initialize first and last index
first = -1
last = -1

for i in range(n):
    
    # If x is different, continue
    if x != arr[i]:
        continue
    
    # If first occurrence found
    if first == -1:
        first = i
    
    # Update last occurrence
    last = i
res = [first, last]
return res

if name == "main": arr = [1, 3, 5, 5, 5, 5, 7, 123, 125] x = 5 res = find(arr, x) print(res[0], res[1])

C#

using System; using System.Collections.Generic;

class GfG {

static List<int> find(int[] arr, int x) {
    int n = arr.Length;
    
    // 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;
    }
    List<int> res = new List<int> { first, last };
    return res;
}

static void Main() {
    int[] arr = {1, 3, 5, 5, 5, 5, 7, 123, 125};
    int x = 5;
    List<int> res = find(arr, x);
    Console.WriteLine(res[0] + " " + res[1]);
}

}

JavaScript

function find(arr, x) { let n = arr.length;

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

for (let 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;
}
let res = [first, last];
return res;

}

let arr = [1, 3, 5, 5, 5, 5, 7, 123, 125]; let x = 5; let res = find(arr, x); console.log(res[0] + " " + res[1]);

`

[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):

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):

last contains the last occurrence index.

C++ `

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

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

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

// Initialize last occurrence
int last = -1;

// Find last occurrence of x
while(left <= right) {

    // Find the mid index
    int mid = (left + right) / 2;

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

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

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

return last;

}

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

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

// Initialize first occurrence
int first = -1;

// Find first occurrence of x
while(left <= right) {

    // Find the mid index
    int mid = (left + right) / 2;

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

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

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

return first;

}

vector find(vector 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 arr = {1, 3, 5, 5, 5, 5, 7, 123, 125}; int x = 5; vector res = find(arr, x); cout << res[0] << " " << res[1]; return 0; }

C

#include <stdio.h>

// Function to find first occurrence of x int findFirst(int arr[], int n, int x) { int left = 0, right = n - 1; int first = -1;

while (left <= right)
{
    // Find the mid index
    int mid = (left + right) / 2;

    // If arr[mid] == x then store ans
    if (arr[mid] == x)
    {
        first = mid;
        // continue searching in left subarray
        right = mid - 1;
    }
    
    // If x is less than arr[mid] 
    // search in the left subarray
    else if (x < arr[mid])
    {
        right = mid - 1;
    }
    
    // IF x is greater than arr[mid]
    // search in the right subarray
    else
    {
        left = mid + 1;
    }
}

return first;

}

// Function to find last occurrence of x int findLast(int arr[], int n, int x) { int left = 0, right = n - 1; int last = -1;

while (left <= right)
{
    // Find the mid index
    int mid = (left + right) / 2;

    // If arr[mid] == x then store ans
    if (arr[mid] == x)
    {
        last = mid;
        left = mid + 1; // continue searching in right subarray
    }
    
    // If x is less than arr[mid] 
    // search in the left subarray
    else if (x < arr[mid])
    {
        right = mid - 1;
    }
    
    // IF x is greater than arr[mid]
    // search in the right subarray
    else
    {
        left = mid + 1;
    }
}

return last;

}

void find(int arr[], int n, int x, int *first, int *last) { // Find first and last index *first = findFirst(arr, n, x); *last = findLast(arr, n, x); }

int main() { int arr[] = {1, 3, 5, 5, 5, 5, 7, 123, 125}; int n = sizeof(arr) / sizeof(arr[0]); int x = 5; int first, last; find(arr, n, x, &first, &last); printf("%d %d\n", first, last); return 0; }

Java

import java.util.*;

class GfG {

// Function for finding last occurrence of x
static int findLast(int[] arr, int x) {
    int n = arr.length;
    
    // Initialize left and right index
    // to find the last occurrence
    int left = 0, right = n - 1;
    
    // Initialize last occurrence
    int last = -1;
    
    // Find last occurrence of x
    while(left <= right) {
        
        // Find the mid index
        int mid = (left + right) / 2;
        
        // If x is equal to arr[mid]
        if(x == arr[mid]) {
            last = mid;
            left = mid + 1;
        }
        
        // If x is less than arr[mid], 
        // then search in the left subarray
        else if(x < arr[mid])
            right = mid - 1;
        
        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            left = mid + 1;
    }
    
    return last;
}

// Function for finding first occurrence of x
static int findFirst(int[] arr, int x) {
    int n = arr.length;
    
    // Initialize left and right index
    // to find the first occurrence
    int left = 0, right = n - 1;
    
    // Initialize first occurrence
    int first = -1;
    
    // Find first occurrence of x
    while(left <= right) {
        
        // Find the mid index
        int mid = (left + right) / 2;
        
        // If x is equal to arr[mid]
        if(x == arr[mid]) {
            first = mid;
            right = mid - 1;
        }
        
        // If x is less than arr[mid], 
        // then search in the left subarray
        else if(x < arr[mid])
            right = mid - 1;
        
        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            left = mid + 1;
    }
    
    return first;
}

static ArrayList<Integer> find(int[] arr, int x) {
    int n = arr.length;
    
    // Find first and last index
    int first = findFirst(arr, x);
    int last = findLast(arr, x);
    
    ArrayList<Integer> res = new ArrayList<>();
    res.add(first);
    res.add(last);
    return res;
}

public static void main(String[] args) {
    int[] arr = {1, 3, 5, 5, 5, 5, 7, 123, 125};
    int x = 5;
    ArrayList<Integer> res = find(arr, x);
    System.out.println(res.get(0) + " " + res.get(1));
}

}

Python

Function for finding last occurrence of x

def findLast(arr, x): n = len(arr)

# Initialize left and right index
# to find the last occurrence
left = 0
right = n - 1

# Initialize last occurrence
last = -1

# Find last occurrence of x
while left <= right:
    
    # Find the mid index
    mid = (left + right) // 2
    
    # If x is equal to arr[mid]
    if x == arr[mid]:
        last = mid
        left = mid + 1
    # If x is less than arr[mid], 
    # then search in the left subarray
    elif x < arr[mid]:
        right = mid - 1
    # If x is greater than arr[mid], 
    # then search in the right subarray
    else:
        left = mid + 1
return last

Function for finding first occurrence of x

def findFirst(arr, x): n = len(arr)

# Initialize left and right index
# to find the first occurrence
left = 0
right = n - 1

# Initialize first occurrence
first = -1

# Find first occurrence of x
while left <= right:
    
    # Find the mid index
    mid = (left + right) // 2
    
    # If x is equal to arr[mid]
    if x == arr[mid]:
        first = mid
        right = mid - 1
    # If x is less than arr[mid], 
    # then search in the left subarray
    elif x < arr[mid]:
        right = mid - 1
    # If x is greater than arr[mid], 
    # then search in the right subarray
    else:
        left = mid + 1
return first

def find(arr, x): n = len(arr)

# Find first and last index
first = findFirst(arr, x)
last = findLast(arr, x)

res = [first, last]
return res

if name == "main": arr = [1, 3, 5, 5, 5, 5, 7, 123, 125] x = 5 res = find(arr, x) print(res[0], res[1])

C#

using System; using System.Collections.Generic;

class GfG {

// Function for finding last occurrence of x
static int findLast(int[] arr, int x) {
    int n = arr.Length;
    
    // Initialize left and right index
    // to find the last occurrence
    int left = 0, right = n - 1;
    
    // Initialize last occurrence
    int last = -1;
    
    // Find last occurrence of x
    while(left <= right) {
        // Find the mid index
        int mid = (left + right) / 2;
        
        // If x is equal to arr[mid]
        if(x == arr[mid]) {
            last = mid;
            left = mid + 1;
        }
        // If x is less than arr[mid], 
        // then search in the left subarray
        else if(x < arr[mid])
            right = mid - 1;
        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            left = mid + 1;
    }
    return last;
}

// Function for finding first occurrence of x
static int findFirst(int[] arr, int x) {
    int n = arr.Length;
    
    // Initialize left and right index
    // to find the first occurrence
    int left = 0, right = n - 1;
    
    // Initialize first occurrence
    int first = -1;
    
    // Find first occurrence of x
    while(left <= right) {
        // Find the mid index
        int mid = (left + right) / 2;
        
        // If x is equal to arr[mid]
        if(x == arr[mid]) {
            first = mid;
            right = mid - 1;
        }
        // If x is less than arr[mid], 
        // then search in the left subarray
        else if(x < arr[mid])
           right = mid - 1;
        // If x is greater than arr[mid], 
        // then search in the right subarray
        else
            left = mid + 1;
    }
    return first;
}

static List<int> find(int[] arr, int x) {
    int n = arr.Length;
    
    // Find first and last index
    int first = findFirst(arr, x);
    int last = findLast(arr, x);
    
    List<int> res = new List<int> { first, last };
    return res;
}

static void Main() {
    int[] arr = {1, 3, 5, 5, 5, 5, 7, 123, 125};
    int x = 5;
    List<int> res = find(arr, x);
    Console.WriteLine(res[0] + " " + res[1]);
}

}

JavaScript

// Function for finding first occurrence of x function findFirst(arr, x) { let n = arr.length;

// Initialize left and right index
let left = 0, right = n - 1;

// Initialize first occurrence
let first = -1;

// Find first occurrence of x
while (left <= right) {
    
    // Find the mid index
    let mid = Math.floor((left + right) / 2);
    
    // If x is equal to arr[mid]
    if (x === arr[mid]) {
        first = mid;
        right = mid - 1;
    }
    
    // If x is less than arr[mid], 
    // then search in the left subarray
    else if (x < arr[mid])
        right = mid - 1;
    
    // If x is greater than arr[mid], 
    // then search in the right subarray
    else
        left = mid + 1;
}
return first;

} // Function for finding last occurrence of x function findLast(arr, x) { let n = arr.length;

// Initialize left and right index
let left = 0, right = n - 1;

// Initialize last occurrence
let last = -1;

// Find last occurrence of x
while (left <= right) {
    
    // Find the mid index
    let mid = Math.floor((left + right) / 2);
    
    // If x is equal to arr[mid]
    if (x === arr[mid]) {
        last = mid;
        left = mid + 1;
    }
    
    // If x is less than arr[mid], 
    // then search in the left subarray
    else if (x < arr[mid])
        right = mid - 1;
    
    // If x is greater than arr[mid], 
    // then search in the right subarray
    else
        left = mid + 1;
}
return last;

}

function find(arr, x) { let n = arr.length;

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

let res = [first, last];
return res;

}

let arr = [1, 3, 5, 5, 5, 5, 7, 123, 125]; let x = 5; let res = find(arr, x); console.log(res[0] + " " + res[1]);

`

[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.

C++ `

#include #include #include using namespace std;

vector find(vector 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 arr = {1, 3, 5, 5, 5, 5, 7, 123, 125}; int x = 5; vector res = find(arr, x); cout << res[0] << " " << res[1]; return 0; }

Java

import java.util.*;

class GfG {

// Function for finding first and last occurrence of x
static ArrayList<Integer> find(int[] arr, int x) {
    int n = arr.length;

    // return index of first number
    // greater than or equal to x
    int first = lowerBound(arr, x);

    // return index of first number
    // greater than x
    int last = upperBound(arr, x) - 1;

    // If x is not present
    if (first == n || arr[first] != x) {
        first = -1;
        last = -1;
    }

    ArrayList<Integer> res = new ArrayList<>();
    res.add(first);
    res.add(last);
    return res;
}

static int lowerBound(int[] arr, int x) {
    int left = 0, right = arr.length;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] >= x)
            right = mid;
        else
            left = mid + 1;
    }
    return left;
}

static int upperBound(int[] arr, int x) {
    int left = 0, right = arr.length;
    while (left < right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] > x)
            right = mid;
        else
            left = mid + 1;
    }
    return left;
}

public static void main(String[] args) {
    int[] arr = {1, 3, 5, 5, 5, 5, 7, 123, 125};
    int x = 5;
    ArrayList<Integer> res = find(arr, x);
    System.out.println(res.get(0) + " " + res.get(1));
}

}

Python

Function for finding first and last occurrence of x

import bisect

def find(arr, x): n = len(arr)

# return index of first number
# greater than or equal to x
first = bisect.bisect_left(arr, x)

# return index of first number
# greater than x
last = bisect.bisect_right(arr, x) - 1

# If x is not present
if first == n or arr[first] != x:
    first = -1
    last = -1
    
res = [first, last]
return res

if name == "main": arr = [1, 3, 5, 5, 5, 5, 7, 123, 125] x = 5 res = find(arr, x) print(res[0], res[1])

C#

using System; using System.Collections.Generic;

class GfG {

// Function for finding first and last occurrence of x
static List<int> find(int[] arr, int x) {
    List<int> list = new List<int>(arr);
    
    // return index of first number
    // greater than or equal to x
    int first = list.IndexOf(x);
    
    // return index of first number
    // greater than x
    int last = list.LastIndexOf(x);
    
    // If x is not present
    if (first == -1) {
        last = -1;
    }
    List<int> res = new List<int> { first, last };
    return res;
}

static void Main() {
    int[] arr = {1, 3, 5, 5, 5, 5, 7, 123, 125};
    int x = 5;
    List<int> res = find(arr, x);
    Console.WriteLine(res[0] + " " + res[1]);
}

}

JavaScript

function find(arr, x) { let n = arr.length;

// return index of first number
// greater than or equal to x
let first = arr.findIndex(e => e >= x);

// return index of first number
// greater than x
let last = arr.lastIndexOf(x);

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

}

let arr = [1, 3, 5, 5, 5, 5, 7, 123, 125]; let x = 5; let res = find(arr, x); console.log(res[0] + " " + res[1]);

`

**Extended Problem : Count number of occurrences in a sorted array