Find the Kth occurrence of an element in a sorted Array
Last Updated :
23 Jul, 2025
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 = 2
Output: Starting index of the array is '0' Second occurrence of 5 is at index 6.
Explanation: The first occurrence of 5 is at index 5. And the second occurrence of 5 is at index 6.
Input: N = 8, arr[] = [1, 2, 4, 4, 4, 8, 10, 15], X = 4, K = 1
Output: Starting index of the array is '0' First occurrence of 4 is at index 2.
Explanation: The first occurrence of 4 is at index 2.
Input: N = 4, arr[] = [1, 2, 3, 4], X = 4, K = 2
Output: -1
Approach: To solve the problem follow the below idea:
The idea is to use binary search and check if the middle element is equal to the key, check if the Kth occurrence of the key is to the left of the middle element or to the right of it, or if the middle element itself is the Kth occurrence of the key.
Below are the steps for the above approach:
- Initialize the mid index, mid = start + (end - start) / 2, and a variable ans = -1.
- Run a while loop till start ≤ end index,
- Check if the key element and arr[mid] are the same, there is a possibility that the Kth occurrence of the key element is either on the left side or on the right side of the arr[mid].
- Check if arr[mid-K] and arr[mid] are the same. Then the Kth occurrence of the key element must lie on the left side of the arr[mid].
- Else if arr[mid-(K-1)] and arr[mid] are the same, then arr[mid] itself will be the Kth element, update ans = mid.
- Else Kth occurrence of the element will lie on the right side of the mid-element. For which start becomes start = mid+1 (Going to the right search space)
- If arr[mid] and key elements are not the same, then
- Check if key < arr[mid], then end = mid - 1. Since the key element is smaller than arr[mid], it will lie to the left of arr[mid].
- Check if key > arr[mid], then start = mid +1. Since the key element is greater than arr[mid], it will lie to the right of arr[mid].
- Return the Kth occurrence of the key element.
Below is the code for the above approach:
C++
// C++ code for finding the Kth occurrence
// of an element in a sorted array
// using Binary search
#include <bits/stdc++.h>
using namespace std;
class solution {
public:
int Kth_occurrence(int arr[], int size, int key, int k)
{
int s = 0;
int e = size - 1;
int mid = s + (e - s) / 2;
int ans = -1;
while (s <= e) {
if (arr[mid] == key) {
// If arr[mid] happens to
// be the element(whose
// Kth occurrence we are
// searching for), then
// there is a possibility
// that the Kth occurrence
// of the element can be
// either on left or on
// the right side of arr[mid]
// If the Kth occurrence
// lies to the left side
// of arr[mid]
if (arr[mid - k] == arr[mid])
e = mid - 1;
// If arr[mid] itself is
// the Kth occurrence.
else if (arr[mid - (k - 1)] == arr[mid]) {
ans = mid;
break;
}
// If the Kth occurrence
// lies to the right side
// of arr[mid].
else {
s = mid + 1;
}
}
// Go for the Left portion.
else if (key < arr[mid]) {
e = mid - 1;
}
// Go for the Right
// portion.
else if (key > arr[mid]) {
s = mid + 1;
}
mid = s + (e - s) / 2;
}
return ans;
}
};
// Drivers code
int main()
{
int n = 4;
int arr[4] = { 1, 2, 3, 4 };
int x = 4;
int k = 2;
solution obj;
cout << "Kth occurrence of " << x << " is at index: "
<< obj.Kth_occurrence(arr, n, x, k) << endl;
return 0;
}
Java
// Java code for finding the Kth occurrence
// of an element in a sorted array
// using Binary search
import java.util.*;
class Solution {
public int Kth_occurrence(int arr[], int size, int key,
int k)
{
int s = 0;
int e = size - 1;
int mid = s + (e - s) / 2;
int ans = -1;
while (s <= e) {
if (arr[mid] == key) {
// If arr[mid] happens to
// be the element(whose
// Kth occurrence we are
// searching for), then
// there is a possibility
// that the Kth occurrence
// of the element can be
// either on left or on
// the right side of arr[mid]
// If the Kth occurrence
// lies to the left side
// of arr[mid]
if (arr[mid - k] == arr[mid])
e = mid - 1;
// If arr[mid] itself is
// the Kth occurrence.
else if (arr[mid - (k - 1)] == arr[mid]) {
ans = mid;
break;
}
// If the Kth occurrence
// lies to the right side
// of arr[mid].
else {
s = mid + 1;
}
}
// Go for the Left portion.
else if (key < arr[mid]) {
e = mid - 1;
}
// Go for the Right
// portion.
else if (key > arr[mid]) {
s = mid + 1;
}
mid = s + (e - s) / 2;
}
return ans;
}
}
// Driver code
class GFG {
public static void main(String[] args)
{
int n = 4;
int arr[] = { 1, 2, 3, 4 };
int x = 4;
int k = 2;
Solution obj = new Solution();
System.out.println(
"Kth occurrence of " + x + " is at index: "
+ obj.Kth_occurrence(arr, n, x, k));
}
}
C#
// C# code for finding the Kth occurrence
// of an element in a sorted array
// using Binary search
using System;
class Solution {
public int Kth_occurrence(int[] arr, int size, int key,
int k)
{
int s = 0;
int e = size - 1;
int mid = s + (e - s) / 2;
int ans = -1;
while (s <= e) {
if (arr[mid] == key) {
// If arr[mid] happens to
// be the element(whose
// Kth occurrence we are
// searching for), then
// there is a possibility
// that the Kth occurrence
// of the element can be
// either on left or on
// the right side of arr[mid]
// If the Kth occurrence
// lies to the left side
// of arr[mid]
if (arr[mid - k] == arr[mid]) {
e = mid - 1;
}
// If arr[mid] itself is
// the Kth occurrence.
else if (arr[mid - (k - 1)] == arr[mid]) {
ans = mid;
break;
}
// If the Kth occurrence
// lies to the right side
// of arr[mid].
else {
s = mid + 1;
}
}
// Go for the Left portion.
else if (key < arr[mid]) {
e = mid - 1;
}
// Go for the Right
// portion.
else if (key > arr[mid]) {
s = mid + 1;
}
mid = s + (e - s) / 2;
}
return ans;
}
}
class Program {
static void Main(string[] args)
{
int n = 4;
int[] arr = { 1, 2, 3, 4 };
int x = 4;
int k = 2;
Solution obj = new Solution();
Console.WriteLine(
"Kth occurrence of {0} is at index: {1}", x,
obj.Kth_occurrence(arr, n, x, k));
}
}
// This code is contributed by Gaurav_Arora
JavaScript
class solution {
Kth_occurrence(arr, size, key, k) {
let s = 0;
let e = size - 1;
let mid = s + Math.floor((e - s) / 2);
let ans = -1;
while (s <= e) {
if (arr[mid] === key) {
// If arr[mid] happens to
// be the element(whose
// Kth occurrence we are
// searching for), then
// there is a possibility
// that the Kth occurrence
// of the element can be
// either on left or on
// the right side of arr[mid]
// If the Kth occurrence
// lies to the left side
// of arr[mid]
if (arr[mid - k] === arr[mid]) {
e = mid - 1;
}
// If arr[mid] itself is
// the Kth occurrence.
else if (arr[mid - (k - 1)] === arr[mid]) {
ans = mid;
break;
}
// If the Kth occurrence
// lies to the right side
// of arr[mid].
else {
s = mid + 1;
}
}
// Go for the Left portion.
else if (key < arr[mid]) {
e = mid - 1;
}
// Go for the Right
// portion.
else if (key > arr[mid]) {
s = mid + 1;
}
mid = s + Math.floor((e - s) / 2);
}
return ans;
}
}
// Drivers code
let n = 4;
let arr = [1, 2, 3, 4];
let x = 4;
let k = 2;
let obj = new solution();
console.log("Kth occurrence of " + x + " is at index: " + obj.Kth_occurrence(arr, n, x, k));
Python3
# Python code for finding the Kth occurrence
# of an element in a sorted array
# using Binary search
class Solution:
def Kth_occurrence(self, arr, size, key, k):
s = 0
e = size - 1
mid = s + (e - s) // 2
ans = -1
while s <= e:
if arr[mid] == key:
# If arr[mid] happens to
# be the element(whose
# Kth occurrence we are
# searching for), then
# there is a possibility
# that the Kth occurrence
# of the element can be
# either on left or on
# the right side of arr[mid]
# If the Kth occurrence
# lies to the left side
# of arr[mid]
if arr[mid - k] == arr[mid]:
e = mid - 1
# If arr[mid] itself is
# the Kth occurrence.
elif arr[mid - (k - 1)] == arr[mid]:
ans = mid
break
# If the Kth occurrence
# lies to the right side
# of arr[mid].
else:
s = mid + 1
# Go for the Left portion.
elif key < arr[mid]:
e = mid - 1
# Go for the Right
# portion.
elif key > arr[mid]:
s = mid + 1
mid = s + (e - s) // 2
return ans
# Drivers code
if __name__ == '__main__':
n = 4
arr = [1, 2, 3, 4]
x = 4
k = 2
obj = Solution()
print(f"Kth occurrence of {x} is at index: {obj.Kth_occurrence(arr, n, x, k)}")
# This code is contributed by Susobhan Akhuli
OutputKth occurrence of 4 is at index: -1
Time Complexity: O(logN), because of the binary search approach.
Auxiliary Space: O(1).
Another Approach: (Using Two Binary Search)
Another approach to solve this problem is to use two binary searches - one to find the index of the first occurrence of X and another to find the index of the Kth occurrence of X.
Algorithm:
- Initialize two variables, left and right, to point to the first and last indices of the array, respectively.
- Perform binary search on the array to find the index of the first occurrence of X. If X is not found, return -1.
- Initialize a variable firstIndex to the index of the first occurrence of X.
- Set left to firstIndex + 1 and right to N-1.
- Perform binary search on the subarray arr[left...right] to find the index of the Kth occurrence of X. If Kth occurrence of X is not found, return -1.
- Return the index of the Kth occurrence of X in the array as firstIndex + index found in step 5.
Below is the implementation of the above approach:
C++
// C++ code for finding the Kth occurrence
// of an element in a sorted array
// Using Two Binary Search
#include <iostream>
#include <vector>
using namespace std;
int binarySearch(vector<int>& arr, int left, int right, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int findKthOccurrence(vector<int>& arr, int N, int X, int K) {
int left = 0, right = N - 1;
int firstIndex = binarySearch(arr, left, right, X);
if (firstIndex == -1) {
return -1;
}
left = firstIndex + 1;
right = N - 1;
int count = 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == X) {
count++;
if (count == K) {
return mid;
} else {
left = mid + 1;
}
} else if (arr[mid] < X) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
// Drivers code
int main() {
int n = 4;
vector<int> arr = {1, 2, 3, 4};
int x = 4;
int k = 2;
cout << k << "nd occurrence of " << x << " is at index: " << findKthOccurrence(arr, n, x, k) << endl;
return 0;
}
// This code is contributed by Pushpesh Raj
Java
// Java code for finding the Kth occurrence
// of an element in a sorted array
// Using Two Binary Search
import java.util.*;
class GFG {
public static int binarySearch(List<Integer> arr, int left,
int right, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (arr.get(mid) == target) {
return mid;
} else if (arr.get(mid) < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
public static int findKthOccurrence(List<Integer> arr, int N,
int X, int K) {
int left = 0, right = N - 1;
int firstIndex = binarySearch(arr, left, right, X);
if (firstIndex == -1) {
return -1;
}
left = firstIndex + 1;
right = N - 1;
int count = 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr.get(mid) == X) {
count++;
if (count == K) {
return mid;
} else {
left = mid + 1;
}
} else if (arr.get(mid) < X) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int n = 4;
List<Integer> arr = Arrays.asList(1, 2, 3, 4);
int x = 4;
int k = 2;
System.out.println(k + "nd occurrence of " + x + " is at index: " + findKthOccurrence(arr, n, x, k));
}
}
// This code is contributed by Vaibhav Nandan
C#
// C# code for finding the Kth occurrence
// of an element in a sorted array
// Using Two Binary Search
using System;
class GFG
{
static int BinarySearch(int[] arr, int left, int right, int target)
{
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == target)
{
return mid;
}
else if (arr[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
static int FindKthOccurrence(int[] arr, int N, int X, int K)
{
int left = 0, right = N - 1;
int firstIndex = BinarySearch(arr, left, right, X);
if (firstIndex == -1)
{
return -1;
}
left = firstIndex + 1;
right = N - 1;
int count = 1;
while (left <= right)
{
int mid = (left + right) / 2;
if (arr[mid] == X)
{
count++;
if (count == K)
{
return mid;
}
else
{
left = mid + 1;
}
}
else if (arr[mid] < X)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
// Main function
static void Main()
{
int n = 4;
int[] arr = { 1, 2, 3, 4 };
int x = 4;
int k = 2;
Console.WriteLine($"{k}nd occurrence of {x} is at index: {FindKthOccurrence(arr, n, x, k)}");
}
}
JavaScript
// Function to perform binary search in a sorted array
function binarySearch(arr, left, right, target) {
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid; // Return the index if target is found
} else if (arr[mid] < target) {
left = mid + 1; // Move the search range to the right
} else {
right = mid - 1; // Move the search range to the left
}
}
return -1; // Return -1 if target is not found
}
// Function to find the Kth occurrence of an element in a sorted array
function findKthOccurrence(arr, N, X, K) {
let left = 0;
let right = N - 1;
// Find the index of the first occurrence of X using binary search
let firstIndex = binarySearch(arr, left, right, X);
if (firstIndex === -1) {
return -1; // If X is not present, return -1
}
left = firstIndex + 1;
right = N - 1;
let count = 1;
// Find the index of the Kth occurrence of X using binary search
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === X) {
count++;
if (count === K) {
return mid; // Return the index of the Kth occurrence of X
} else {
left = mid + 1;
}
} else if (arr[mid] < X) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // If Kth occurrence of X is not found, return -1
}
// Driver code
const n = 4;
const arr = [1, 2, 3, 4];
const x = 4;
const k = 2;
console.log(`${k}nd occurrence of ${x} is at index: ${findKthOccurrence(arr, n, x, k)}`);
Python3
# Python code for finding the Kth occurrence
# of an element in a sorted array
# Using Two Binary Search
def binarySearch(arr, left, right, target):
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
def findKthOccurrence(arr, N, X, K):
left, right = 0, N-1
firstIndex = binarySearch(arr, left, right, X)
if firstIndex == -1:
return -1
left, right = firstIndex+1, N-1
count = 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == X:
count += 1
if count == K:
return mid
else:
left = mid + 1
elif arr[mid] < X:
left = mid + 1
else:
right = mid - 1
return -1
# Drivers code
if __name__ == '__main__':
n = 4
arr = [1, 2, 3, 4]
x = 4
k = 2
print(f"{k}nd occurrence of {x} is at index: {findKthOccurrence(arr, n, x, k)}")
# This code is contributed by Susobhan Akhuli
Output2nd occurrence of 4 is at index: -1
Time Complexity: O(log N + log N) = O(log N), as we are performing two binary searches on the array.
Auxiliary Space: O(1), as we are using only a constant amount of extra space to store the variables.
Using inbuilt functions:
This approach to solve the problem is to use inbuilt function lower_bound and upper_bound to get indices of first and last occurrence of the element. Once we get it we can add k to first occurrence index if it's within element's last occcurrence. Else, we can return -1.
Algorithm:
- Define a function Kth_occurrence which takes four arguments: the sorted array arr[], its size n, the key element to be searched key and the integer k representing the Kth occurrence of the key element.
- Initialize ans variable to -1.
- Use the lower_bound() function to find the first occurrence of the key element in the array. Store its index in the lb variable.
- Use the upper_bound() function to find the last occurrence of the key element in the array. Store its index in the ub variable.
- If the key element is not found in the array or the number of occurrences of the key element in the array is less than k, return -1.
- Otherwise, calculate the index of the kth occurrence of the key element by adding k-1 to lb. Store this index in the ans variable.
- Return ans.
Below is the implementation of the approach:
C++
// C++ code for finding the Kth occurrence
// of an element in a sorted array
#include <bits/stdc++.h>
using namespace std;
class solution {
public:
// Function to find the Kth occurrence
// of an element in a sorted Array
int Kth_occurrence(int arr[], int n, int key, int k) {
int ans = -1;
// lower_bound of key
int lb = lower_bound( arr, arr + n, key ) - arr;
// upper_bound of key
int ub = upper_bound( arr, arr + n, key ) - arr;
// if key doesn't exist or k occurrences
// are not there of the key
if( (lb == n || arr[lb] != key) || (ub - lb) < k )
return -1;
ans = lb + k - 1;
return ans;
}
};
// Drivers code
int main() {
int n = 4;
int arr[4] = { 1, 2, 3, 4 };
int x = 4;
int k = 2;
solution obj;
cout << "Kth occurrence of " << x << " is at index: "
<< obj.Kth_occurrence(arr, n, x, k) << endl;
return 0;
}
// This code is contributed by Chandramani Kumar
Java
public class Solution {
// Function to find the Kth occurrence of an element in a sorted Array
public int findKthOccurrence(int[] arr, int key, int k) {
int ans = -1;
// Finding the lower bound index of the key
int lb = lowerBound(arr, key);
// Finding the upper bound index of the key
int ub = upperBound(arr, key);
// If key doesn't exist or there are not k occurrences of the key
if (lb == -1 || arr[lb] != key || (ub - lb) < k) {
return -1;
}
ans = lb + k - 1;
return ans;
}
// Function to find the lower bound index of key
private int lowerBound(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
int lb = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] >= key) {
lb = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return lb;
}
// Function to find the upper bound index of key
private int upperBound(int[] arr, int key) {
int left = 0;
int right = arr.length - 1;
int ub = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] > key) {
ub = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return ub;
}
public static void main(String[] args) {
int n = 4;
int[] arr = {1, 2, 3, 4};
int x = 4;
int k = 2;
Solution obj = new Solution();
int result = obj.findKthOccurrence(arr, x, k);
System.out.println("Kth occurrence of " + x + " is at index: " + result);
}
}
C#
using System;
class Solution
{
// Function to find the Kth occurrence
// of an element in a sorted Array
public int KthOccurrence(int[] arr, int key, int k)
{
int ans = -1;
// Lower bound of key
int lb = Array.BinarySearch(arr, key);
// Upper bound of key
int ub = Array.BinarySearch(arr, key + 1);
// If key doesn't exist or k occurrences
// are not there of the key
if ((lb < 0 || arr[lb] != key) || (ub - lb) < k)
return -1;
ans = lb + k - 1;
return ans;
}
}
class Program
{
static void Main()
{
int[] arr = { 1, 2, 3, 4 };
int x = 4;
int k = 2;
Solution obj = new Solution();
Console.WriteLine("Kth occurrence of " + x + " is at index: " +
obj.KthOccurrence(arr, x, k));
}
}
JavaScript
cpp
// JavaScript code for finding the Kth occurrence
// of an element in a sorted array
class Solution {
// Function to find the Kth occurrence
// of an element in a sorted Array
Kth_occurrence(arr, key, k) {
let ans = -1;
// lower_bound of key
let lb = arr.findIndex((element) => element >= key);
// upper_bound of key
let ub = arr.findIndex((element) => element > key);
// if key doesn't exist or k occurrences
// are not there of the key
if (lb === -1 || arr[lb] !== key || (ub - lb) < k) {
return -1;
}
ans = lb + k - 1;
return ans;
}
}
// Drivers code
let n = 4;
let arr = [1, 2, 3, 4];
let x = 4;
let k = 2;
let obj = new Solution();
console.log("Kth occurrence of " + x + " is at index: " + obj.Kth_occurrence(arr, x, k));
Python3
class Solution:
def kth_occurrence(self, arr, key, k):
lb = self.lower_bound(arr, key)
ub = self.upper_bound(arr, key)
if lb == len(arr) or arr[lb] != key or (ub - lb) < k:
return -1
return lb + k - 1
def lower_bound(self, arr, key):
left, right = 0, len(arr)
while left < right:
mid = left + (right - left) // 2
if arr[mid] < key:
left = mid + 1
else:
right = mid
return left
def upper_bound(self, arr, key):
left, right = 0, len(arr)
while left < right:
mid = left + (right - left) // 2
if arr[mid] <= key:
left = mid + 1
else:
right = mid
return left
# Driver's code
if __name__ == "__main__":
arr = [1, 2, 3, 4]
x = 4
k = 2
obj = Solution()
result = obj.kth_occurrence(arr, x, k)
if result != -1:
print(f"Kth occurrence of {x} is at index: {result}")
else:
print(f"Kth occurrence of {x} not found.")
OutputKth occurrence of 4 is at index: -1
Time Complexity: O(logN) as lower_bound and upper_bound takes logN time. Here, N is size of input array.
Space Complexity: O(1) as no extra space has been used.
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