Find first and last positions of an element in a sorted array
Last Updated :
23 Jul, 2025
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
// 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]);
[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]);
[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]);
[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]);
Extended Problem : Count number of occurrences in a sorted array
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem