Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Javascript Program for Search an element in a sorted and rotated array
Next article icon

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

Last Updated : 04 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
  • [Expected Approach] – Using Binary Search – O(log n) Time and O(1) Space
  • [Alternate Approach – 1] – Using Binary Search – O(log n) Time and O(1) Space
  • [Alternate Approach – 2] – Using Inbuilt Functions – O(log n) Time and O(1) Space

[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
// 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));     } } 
Python
# 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]) 
C#
// 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]);     } } 
JavaScript
// 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;
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
// 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));     } } 
Python
# 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]) 
C#
// 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]);     } } 
JavaScript
// 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.     

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
// 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));     } } 
Python
# 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]) 
C#
// 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]);     } } 
JavaScript
// 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.

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
// 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));     } } 
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, 67, 123, 125]     x = 5     res = find(arr, x)     print(res[0], res[1]) 
C#
// 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]);     } } 
JavaScript
// 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




Next Article
Javascript Program for Search an element in a sorted and rotated array

D

DANISH_RAZA
Improve
Article Tags :
  • Arrays
  • DSA
  • Amazon
  • Binary Search
Practice Tags :
  • Amazon
  • Arrays
  • Binary Search

Similar Reads

  • Find position of an element in a sorted array of infinite numbers
    Given a sorted array arr[] of infinite numbers. The task is to search for an element k in the array. Examples: Input: arr[] = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170], k = 10Output: 4Explanation: 10 is at index 4 in array. Input: arr[] = [2, 5, 7, 9], k = 3Output: -1Explanation: 3 is not presen
    15+ min read
  • Find start and ending index of an element in an unsorted array
    Given an array of integers, task is to find the starting and ending position of a given key. Examples: Input : arr[] = {1, 2, 3, 4, 5, 5} Key = 5Output : Start index: 4 Last index: 5Explanation: Starting index where 5is present is 4 and ending index is 5. Input :arr[] = {1, 3, 7, 8, 6}, Key = 2Outpu
    11 min read
  • Find Second largest element in an array | Set 2
    Given an array arr[] consisting of N integers, the task is to find the second largest element in the given array using N+log2(N) - 2 comparisons. Examples: Input : arr[] = {22, 33, 14, 55, 100, 12}Output : 55 Input : arr[] = {35, 23, 12, 35, 19, 100}Output : 35 Sorting and Two-Traversal Approach: Re
    9 min read
  • Find the position of the last removed element from the array
    Given an array of size [Tex]N [/Tex]and an integer [Tex]M [/Tex]. Perform the following operations on the given array: If a[i] > M then push a[i] - M to end of the array, otherwise remove it from the array.Perform the first operation while the array is non-empty. The task is to find the original
    6 min read
  • Javascript Program for Search an element in a sorted and rotated array
    An element in a sorted array can be found in O(log n) time via binary search. But suppose we rotate an ascending order sorted array at some pivot unknown to you beforehand. So for instance, 1 2 3 4 5 might become 3 4 5 1 2. Devise a way to find an element in the rotated array in O(log n) time.  Exam
    7 min read
  • Find all indices of a given element in sorted form of given Array
    Given an array arr[] of integers of size N and a target value val. Your task is to find the indices of val in the array after sorting the array in increasing order. Note: The indices must be in increasing order. Examples: Input: arr = [1, 2, 5, 2, 3], val = 2Output: 1 2Explanation: After sorting, ar
    6 min read
  • Find the Kth occurrence of an element in a sorted Array
    Given a sorted array arr[] of size N, an integer X, and a positive integer K, the task is to find the index of Kth occurrence of X in the given array. Examples: Input: N = 10, arr[] = [1, 2, 3, 3, 4, 5, 5, 5, 5, 5], X = 5, K = 2Output: Starting index of the array is '0' Second occurrence of 5 is at
    15+ min read
  • k-th missing element in an unsorted array
    Given an unsorted sequence a[], the task is to find the K-th missing contiguous element in the increasing sequence of the array elements i.e. consider the array in sorted order and find the kth missing number. If no k-th missing element is there output -1. Note: Only elements exists in the range of
    6 min read
  • Find index of an extra element present in one sorted array
    Given two sorted arrays. There is only 1 difference between the arrays. The first array has one element extra added in between. Find the index of the extra element. Examples: Input: {2, 4, 6, 8, 9, 10, 12}; {2, 4, 6, 8, 10, 12}; Output: 4 Explanation: The first array has an extra element 9. The extr
    15+ min read
  • Find floor and ceil in an unsorted array
    Given an unsorted array arr[] and an element x, find floor and ceiling of x in arr[0..n-1].Floor of x is the largest element which is smaller than or equal to x. Floor of x doesn't exist if x is smaller than smallest element of arr[].Ceil of x is the smallest element which is greater than or equal t
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences