Find first and last positions of an element in a sorted array
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 5Input : 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 6Input: 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.
#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;
}
// Function for finding first and last occurrence of x
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;
// 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, 67, 123, 125};
int x = 5;
ArrayList<Integer> res = find(arr, x);
System.out.println(res.get(0) + " " + res.get(1));
}
}
# Function for finding first and last occurrence of x
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, 67, 123, 125]
x = 5
res = find(arr, x)
print(res[0], res[1])
// Function for finding first and last occurrence of x
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) {
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, 67, 123, 125};
int x = 5;
List<int> res = find(arr, x);
Console.WriteLine(res[0] + " " + res[1]);
}
}
// Function for finding first and last occurrence of x
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, 67, 123, 125];
let x = 5;
let res = find(arr, x);
console.log(res[0] + " " + res[1]);
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;
#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;
}
// Function for finding first and last occurrence of x
import java.util.*;
class GfG {
// Function for finding last occurrence of x
static int findLast(int[] arr, int x) {
int n = arr.length;
// 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
static int findFirst(int[] arr, int x) {
int n = arr.length;
// 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
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, 67, 123, 125};
int x = 5;
ArrayList<Integer> res = find(arr, x);
System.out.println(res.get(0) + " " + res.get(1));
}
}
# Function for finding first and last occurrence of x
def findLast(arr, x):
n = len(arr)
# Initialize low and high index
# to find the last occurrence
low = 0
high = n - 1
# Initialize last occurrence
last = -1
# Find last occurrence of x
while low <= high:
# Find the mid index
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
elif 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
def findFirst(arr, x):
n = len(arr)
# Initialize low and high index
# to find the first occurrence
low = 0
high = n - 1
# Initialize first occurrence
first = -1
# Find first occurrence of x
while low <= high:
# Find the mid index
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
elif 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
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, 67, 123, 125]
x = 5
res = find(arr, x)
print(res[0], res[1])
// Function for finding first and last occurrence of x
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 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
static int findFirst(int[] arr, int x) {
int n = arr.Length;
// 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
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, 67, 123, 125};
int x = 5;
List<int> res = find(arr, x);
Console.WriteLine(res[0] + " " + res[1]);
}
}
// Function for finding first and last occurrence of x
function findFirst(arr, x) {
let n = arr.length;
// Initialize low and high index
let low = 0, high = n - 1;
// Initialize first occurrence
let first = -1;
// Find first occurrence of x
while (low <= high) {
// Find the mid index
let mid = Math.floor((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 findLast(arr, x) {
let n = arr.length;
// Initialize low and high index
let low = 0, high = n - 1;
// Initialize last occurrence
let last = -1;
// Find last occurrence of x
while (low <= high) {
// Find the mid index
let mid = Math.floor((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 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, 67, 123, 125];
let x = 5;
let res = find(arr, x);
console.log(res[0] + " " + res[1]);
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.
#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;
}
// Function for finding first and last occurrence of x
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 occurrence
int first = search(arr, x, true);
// return index of last occurrence
int last = search(arr, x, false);
ArrayList<Integer> res = new ArrayList<>();
res.add(first);
res.add(last);
return res;
}
static int search(int[] arr, int x, boolean findStart) {
int n = arr.length;
// 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)
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;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 5, 5, 5, 67, 123, 125};
int x = 5;
ArrayList<Integer> res = find(arr, x);
System.out.println(res.get(0) + " " + res.get(1));
}
}
# Function for finding first and last occurrence of x
def search(arr, x, findStart):
n = len(arr)
# Initialize low and high index
low = 0
high = n - 1
# Initialize the index
ind = -1
# Find occurrence of x
while low <= high:
# Find the mid index
mid = (low + high) // 2
# If x is equal to arr[mid]
if x == arr[mid]:
ind = mid
if findStart:
high = mid - 1
else:
low = mid + 1
# If x is less than arr[mid],
# then search in the left subarray
elif 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
def find(arr, x):
n = len(arr)
# return index of first occurrence
first = search(arr, x, True)
# return index of last occurrence
last = search(arr, x, False)
res = [first, last]
return res
if __name__ == "__main__":
arr = [1, 3, 5, 5, 5, 5, 67, 123, 125]
x = 5
res = find(arr, x)
print(res[0], res[1])
// Function for finding first and last occurrence of x
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) {
int n = arr.Length;
// return index of first occurrence
int first = search(arr, x, true);
// return index of last occurrence
int last = search(arr, x, false);
List<int> res = new List<int> { first, last };
return res;
}
static int search(int[] arr, int x, bool findStart) {
int n = arr.Length;
// 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)
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;
}
static void Main() {
int[] arr = {1, 3, 5, 5, 5, 5, 67, 123, 125};
int x = 5;
List<int> res = find(arr, x);
Console.WriteLine(res[0] + " " + res[1]);
}
}
// Function for finding first and last occurrence of x
function search(arr, x, findStart) {
let n = arr.length;
// Initialize low and high index
let low = 0, high = n - 1;
// Initialize the index
let ind = -1;
// Find occurrence of x
while (low <= high) {
// Find the mid index
let mid = Math.floor((low + high) / 2);
// If x is equal to arr[mid]
if (x === arr[mid]) {
ind = mid;
if (findStart)
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 find(arr, x) {
let n = arr.length;
// return index of first occurrence
let first = search(arr, x, true);
// return index of last occurrence
let last = search(arr, x, false);
let res = [first, last];
return res;
}
let arr = [1, 3, 5, 5, 5, 5, 67, 123, 125];
let x = 5;
let res = find(arr, x);
console.log(res[0] + " " + res[1]);
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.
#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;
}
// Function for finding first and last occurrence of x
import java.util.*;
class GfG {
// Function for finding first and last occurrence of x
static ArrayList<Integer> find(int[] arr, int x) {
ArrayList<Integer> list = new ArrayList<>();
for (int val : arr) {
list.add(val);
}
// 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;
}
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, 67, 123, 125};
int x = 5;
ArrayList<Integer> res = find(arr, x);
System.out.println(res.get(0) + " " + res.get(1));
}
}
# 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, 67, 123, 125]
x = 5
res = find(arr, x)
print(res[0], res[1])
// Function for finding first and last occurrence of x
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, 67, 123, 125};
int x = 5;
List<int> res = find(arr, x);
Console.WriteLine(res[0] + " " + res[1]);
}
}
// Function for finding first and last occurrence of x
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, 67, 123, 125];
let x = 5;
let res = find(arr, x);
console.log(res[0] + " " + res[1]);
Output
2 5
Extended Problem : Count number of occurrences in a sorted array