K’th Least Element in a Min-Heap
Last Updated :
11 Jul, 2025
Given a min-heap of size n, find the kth least element in the min-heap.
Examples:
Input : {10, 50, 40, 75, 60, 65, 45} k = 4
Output : 50
Input : {10, 50, 40, 75, 60, 65, 45} k = 2
Output : 40
Naive approach: We can extract the minimum element from the min-heap k times and the last element extracted will be the kth least element. Each deletion operation takes O(log n) time, so the total time complexity of this approach comes out to be O(k * log n).
Implementation:
C++
// C++ program to find k-th smallest
// element in Min Heap.
#include <bits/stdc++.h>
using namespace std;
// Structure for the heap
struct Heap {
vector<int> v;
int n; // Size of the heap
Heap(int i = 0)
: n(i)
{
v = vector<int>(n);
}
};
// Generic function to
// swap two integers
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
// Returns the index of
// the parent node
inline int parent(int i)
{
return (i - 1) / 2;
}
// Returns the index of
// the left child node
inline int left(int i)
{
return 2 * i + 1;
}
// Returns the index of
// the right child node
inline int right(int i)
{
return 2 * i + 2;
}
// Maintains the heap property
void heapify(Heap& h, int i)
{
int l = left(i), r = right(i), m = i;
if (l < h.n && h.v[i] > h.v[l])
m = l;
if (r < h.n && h.v[m] > h.v[r])
m = r;
if (m != i) {
swap(h.v[m], h.v[i]);
heapify(h, m);
}
}
// Extracts the minimum element
int extractMin(Heap& h)
{
if (!h.n)
return -1;
int m = h.v[0];
h.v[0] = h.v[h.n-- - 1];
heapify(h, 0);
return m;
}
int findKthSmalles(Heap &h, int k)
{
for (int i = 1; i < k; ++i)
extractMin(h);
return extractMin(h);
}
int main()
{
Heap h(7);
h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
int k = 2;
cout << findKthSmalles(h, k);
return 0;
}
Java
import java.util.*;
// Class for the heap
class Heap {
List<Integer> v;
int n; // Size of the heap
Heap(int i) {
n = i;
v = new ArrayList<Integer>(Collections.nCopies(n, 0));
}
}
// Main class
public class Main {
// Generic function to swap two integers
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// Returns the index of the parent node
public static int parent(int i) {
return (i - 1) / 2;
}
// Returns the index of the left child node
public static int left(int i) {
return 2 * i + 1;
}
// Returns the index of the right child node
public static int right(int i) {
return 2 * i + 2;
}
// Maintains the heap property
public static void heapify(Heap h, int i) {
int l = left(i), r = right(i), m = i;
if (l < h.n && h.v.get(i) > h.v.get(l))
m = l;
if (r < h.n && h.v.get(m) > h.v.get(r))
m = r;
if (m != i) {
Collections.swap(h.v, m, i);
heapify(h, m);
}
}
// Extracts the minimum element
public static int extractMin(Heap h) {
if (h.n == 0)
return -1;
int m = h.v.get(0);
h.v.set(0, h.v.get(h.n - 1));
h.n--;
heapify(h, 0);
return m;
}
public static int findKthSmallest(Heap h, int k) {
for (int i = 1; i < k; ++i)
extractMin(h);
return extractMin(h);
}
public static void main(String[] args) {
Heap h = new Heap(7);
h.v = Arrays.asList(10, 50, 40, 75, 60, 65, 45);
int k = 2;
System.out.println(findKthSmallest(h, k));
}
}
Python3
import heapq
# Structure for the heap
class Heap:
def __init__(self, i=0):
self.v = [0] * i
self.n = i
# Returns the index of the parent node
def parent(i):
return (i - 1) // 2
# Returns the index of the left child node
def left(i):
return 2 * i + 1
# Returns the index of the right child node
def right(i):
return 2 * i + 2
# Maintains the heap property
def heapify(h, i):
l, r, m = left(i), right(i), i
if l < h.n and h.v[i] > h.v[l]:
m = l
if r < h.n and h.v[m] > h.v[r]:
m = r
if m != i:
h.v[i], h.v[m] = h.v[m], h.v[i]
heapify(h, m)
# Extracts the minimum element
def extractMin(h):
if not h.n:
return -1
m = h.v[0]
h.v[0] = h.v[h.n - 1]
h.n -= 1
heapify(h, 0)
return m
def findKthSmallest(h, k):
for i in range(1, k):
extractMin(h)
return extractMin(h)
h = Heap(7)
h.v = [10, 50, 40, 75, 60, 65, 45]
k = 2
print(findKthSmallest(h, k))
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Heap {
public List<int> v;
public int n { get; private set; } // Size of the heap
public Heap(int i) {
n = i;
v = Enumerable.Repeat(0, n).ToList();
}
// Maintains the heap property
private void heapify(int i) {
int l = left(i), r = right(i), m = i;
if (l < n && v[i] > v[l])
m = l;
if (r < n && v[m] > v[r])
m = r;
if (m != i) {
swap(v, m, i);
heapify(m);
}
}
// Extracts the minimum element
public int extractMin() {
if (n == 0)
return -1;
int m = v[0];
v[0] = v[n - 1];
n--;
heapify(0);
return m;
}
public int findKthSmallest(int k) {
for (int i = 1; i < k; ++i)
extractMin();
return extractMin();
}
// Returns the index of the parent node
private static int parent(int i) {
return (i - 1) / 2;
}
// Returns the index of the left child node
private static int left(int i) {
return 2 * i + 1;
}
// Returns the index of the right child node
private static int right(int i) {
return 2 * i + 2;
}
// Generic function to swap two integers
private static void swap(List<int> a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
public class MainClass {
public static void Main(string[] args) {
Heap h = new Heap(7);
h.v = new List<int> { 10, 50, 40, 75, 60, 65, 45 };
int k = 2;
Console.WriteLine(h.findKthSmallest(k));
}
}
JavaScript
// Structure for the heap
class Heap {
constructor(i = 0) {
this.v = new Array(i);
this.n = i; // Size of the heap
}
}
// Returns the index of
// the parent node
function parent(i) {
return Math.floor((i - 1) / 2);
}
// Returns the index of
// the left child node
function left(i) {
return 2 * i + 1;
}
// Returns the index of
// the right child node
function right(i) {
return 2 * i + 2;
}
// Maintains the heap property
function heapify(h, i) {
let l = left(i),
r = right(i),
m = i;
if (l < h.n && h.v[i] > h.v[l]) m = l;
if (r < h.n && h.v[m] > h.v[r]) m = r;
if (m != i) {
let temp = h.v[m];
h.v[m] = h.v[i];
h.v[i] = temp;
heapify(h, m);
}
}
// Extracts the minimum element
function extractMin(h) {
if (!h.n) return -1;
let m = h.v[0];
h.v[0] = h.v[h.n-- - 1];
heapify(h, 0);
return m;
}
function findKthSmallest(h, k) {
for (let i = 1; i < k; ++i) extractMin(h);
return extractMin(h);
}
const h = new Heap(7);
h.v = [10, 50, 40, 75, 60, 65, 45];
const k = 2;
console.log(findKthSmallest(h, k));
Time Complexity: O(k * log n)
Efficient approach:
We can note an interesting observation about min-heap. An element x at ith level has i - 1 ancestor. By the property of min-heaps, these i - 1 ancestors are guaranteed to be less than x. This implies that x cannot be among the least i - 1 element of the heap. Using this property, we can conclude that the kth least element can have a level of at most k. We can reduce the size of the min-heap such that it has only k levels. We can then obtain the kth least element by our previous strategy of extracting the minimum element k times.
Note that the size of the heap is reduced to a maximum of 2k - 1, therefore each heapify operation will take O(log 2k) = O(k) time. The total time complexity will be O(k2). If n >> k, then this approach performs better than the previous one.
Implementation:
C++
// C++ program to find k-th smallest
// element in Min Heap using k levels
#include <bits/stdc++.h>
using namespace std;
// Structure for the heap
struct Heap {
vector<int> v;
int n; // Size of the heap
Heap(int i = 0)
: n(i)
{
v = vector<int>(n);
}
};
// Generic function to
// swap two integers
void swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}
// Returns the index of
// the parent node
inline int parent(int i) { return (i - 1) / 2; }
// Returns the index of
// the left child node
inline int left(int i) { return 2 * i + 1; }
// Returns the index of
// the right child node
inline int right(int i) { return 2 * i + 2; }
// Maintains the heap property
void heapify(Heap& h, int i)
{
int l = left(i), r = right(i), m = i;
if (l < h.n && h.v[i] > h.v[l])
m = l;
if (r < h.n && h.v[m] > h.v[r])
m = r;
if (m != i) {
swap(h.v[m], h.v[i]);
heapify(h, m);
}
}
// Extracts the minimum element
int extractMin(Heap& h)
{
if (!h.n)
return -1;
int m = h.v[0];
h.v[0] = h.v[h.n-- - 1];
heapify(h, 0);
return m;
}
int findKthSmalles(Heap& h, int k)
{
h.n = min(h.n, int(pow(2, k) - 1));
for (int i = 1; i < k; ++i)
extractMin(h);
return extractMin(h);
}
int main()
{
Heap h(7);
h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
int k = 2;
cout << findKthSmalles(h, k);
return 0;
}
Java
// Java program to find k-th smallest
// element in Min Heap using k levels
import java.util.*;
// Structure for the heap
class Heap {
Vector<Integer> v;
int n; // Size of the heap
Heap(int i)
{
n = i;
v = new Vector<Integer>(n);
}
}
public class Main {
// Generic function to
// swap two integers
static void swap(Vector<Integer> v, int a, int b)
{
int temp = v.get(a);
v.set(a, v.get(b));
v.set(b, temp);
}
// Returns the index of
// the parent node
static int parent(int i) { return (i - 1) / 2; }
// Returns the index of
// the left child node
static int left(int i) { return 2 * i + 1; }
// Returns the index of
// the right child node
static int right(int i) { return 2 * i + 2; }
// Maintains the heap property
static void heapify(Heap h, int i)
{
int l = left(i), r = right(i), m = i;
if (l < h.n && h.v.get(i) > h.v.get(l))
m = l;
if (r < h.n && h.v.get(m) > h.v.get(r))
m = r;
if (m != i) {
swap(h.v, m, i);
heapify(h, m);
}
}
// Extracts the minimum element
static int extractMin(Heap h)
{
if (h.n == 0)
return -1;
int m = h.v.get(0);
h.v.set(0, h.v.get(h.n-- - 1));
heapify(h, 0);
return m;
}
static int findKthSmalles(Heap h, int k)
{
h.n = Math.min(h.n, (int)Math.pow(2, k) - 1);
for (int i = 1; i < k; ++i)
extractMin(h);
return extractMin(h);
}
public static void main(String[] args)
{
Heap h = new Heap(7);
h.v = new Vector<Integer>(
Arrays.asList(10, 50, 40, 75, 60, 65, 45));
int k = 2;
System.out.println(findKthSmalles(h, k));
}
}
Python3
# Python program to find k-th smallest
# element in Min Heap using k levels
import math
# Structure for the heap
class Heap:
def __init__(self, i=0):
self.v = [0] * i
self.n = i # Size of the heap
# Generic function to
# swap two integers
def swap(a, b):
temp = a
a = b
b = temp
return a, b
# Returns the index of
# the parent node
def parent(i):
return (i - 1) // 2
# Returns the index of
# the left child node
def left(i):
return 2 * i + 1
# Returns the index of
# the right child node
def right(i):
return 2 * i + 2
# Maintains the heap property
def heapify(h, i):
l, r, m = left(i), right(i), i
if l < h.n and h.v[i] > h.v[l]:
m = l
if r < h.n and h.v[m] > h.v[r]:
m = r
if m != i:
h.v[m], h.v[i] = swap(h.v[m], h.v[i])
heapify(h, m)
# Extracts the minimum element
def extractMin(h):
if not h.n:
return -1
m = h.v[0]
h.v[0] = h.v[h.n - 1]
h.n -= 1
heapify(h, 0)
return m
def findKthSmallest(h, k):
h.n = min(h.n, int(math.pow(2, k) - 1))
for i in range(1, k):
extractMin(h)
return extractMin(h)
if __name__ == '__main__':
h = Heap(7)
h.v = [10, 50, 40, 75, 60, 65, 45]
k = 2
print(findKthSmallest(h, k))
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Heap {
public List<int> v;
public int n; // Size of the heap
public Heap(int i)
{
n = i;
v = new List<int>(n);
}
}
public class MainClass {
// Generic function to
// swap two integers
static void swap(List<int> v, int a, int b)
{
int temp = v[a];
v[a] = v[b];
v[b] = temp;
}
// Returns the index of
// the parent node
static int parent(int i) { return (i - 1) / 2; }
// Returns the index of
// the left child node
static int left(int i) { return 2 * i + 1; }
// Returns the index of
// the right child node
static int right(int i) { return 2 * i + 2; }
// Maintains the heap property
static void heapify(Heap h, int i)
{
int l = left(i), r = right(i), m = i;
if (l < h.n && h.v[i] > h.v[l])
m = l;
if (r < h.n && h.v[m] > h.v[r])
m = r;
if (m != i) {
swap(h.v, m, i);
heapify(h, m);
}
}
// Extracts the minimum element
static int extractMin(Heap h)
{
if (h.n == 0)
return -1;
int m = h.v[0];
h.v[0] = h.v[h.n-- - 1];
heapify(h, 0);
return m;
}
static int findKthSmalles(Heap h, int k)
{
h.n = Math.Min(h.n, (int)Math.Pow(2, k) - 1);
for (int i = 1; i < k; ++i)
extractMin(h);
return extractMin(h);
}
public static void Main(string[] args)
{
Heap h = new Heap(7);
h.v = new List<int>(
new int[] { 10, 50, 40, 75, 60, 65, 45 });
int k = 2;
Console.WriteLine(findKthSmalles(h, k));
}
}
JavaScript
// JavaScript program to find k-th smallest
// element in Min Heap using k levels
// Structure for the heap
class Heap {
constructor(i = 0) {
this.v = new Array(i).fill(0);
this.n = i; // Size of the heap
}
}
// Generic function to
// swap two integers
function swap(a, b) {
const temp = a;
a = b;
b = temp;
return [a, b];
}
// Returns the index of
// the parent node
function parent(i) {
return Math.floor((i - 1) / 2);
}
// Returns the index of
// the left child node
function left(i) {
return 2 * i + 1;
}
// Returns the index of
// the right child node
function right(i) {
return 2 * i + 2;
}
// Maintains the heap property
function heapify(h, i) {
let l = left(i);
let r = right(i);
let m = i;
if (l < h.n && h.v[i] > h.v[l]) {
m = l;
}
if (r < h.n && h.v[m] > h.v[r]) {
m = r;
}
if (m != i) {
[h.v[m], h.v[i]] = swap(h.v[m], h.v[i]);
heapify(h, m);
}
}
// Extracts the minimum element
function extractMin(h) {
if (!h.n) {
return -1;
}
let m = h.v[0];
h.v[0] = h.v[h.n - 1];
h.n--;
heapify(h, 0);
return m;
}
function findKthSmallest(h, k) {
h.n = Math.min(h.n, Math.pow(2, k) - 1);
for (let i = 1; i < k; i++) {
extractMin(h);
}
return extractMin(h);
}
const h = new Heap(7);
h.v = [10, 50, 40, 75, 60, 65, 45];
const k = 2;
console.log(findKthSmallest(h, k));
Time Complexity: O(k2) More efficient approach:
We can further improve the time complexity of this problem by the following algorithm:
- Create a priority queue P (or Min Heap) and insert the root node of the min-heap into P. The comparator function of the priority queue should be such that the least element is popped.
- Repeat these steps k - 1 times:
- Pop the least element from P.
- Insert left and right child elements of the popped element. (if they exist).
- The least element in P is the kth least element of the min-heap.
The initial size of the priority queue is one, and it increases by at most one at each of the k - 1 steps. Therefore, there are maximum k elements in the priority queue and the time complexity of the pop and insert operations is O(log k). Thus the total time complexity is O(k * log k).
Implementation:
C++
// C++ program to find k-th smallest
// element in Min Heap using another
// Min Heap (Or Priority Queue)
#include <bits/stdc++.h>
using namespace std;
// Structure for the heap
struct Heap {
vector<int> v;
int n; // Size of the heap
Heap(int i = 0)
: n(i)
{
v = vector<int>(n);
}
};
// Returns the index of
// the left child node
inline int left(int i)
{
return 2 * i + 1;
}
// Returns the index of
// the right child node
inline int right(int i)
{
return 2 * i + 2;
}
int findKthSmalles(Heap &h, int k)
{
// Create a Priority Queue
priority_queue<pair<int, int>,
vector<pair<int, int> >,
greater<pair<int, int> > >
p;
// Insert root into the priority queue
p.push(make_pair(h.v[0], 0));
for (int i = 0; i < k - 1; ++i) {
int j = p.top().second;
p.pop();
int l = left(j), r = right(j);
if (l < h.n)
p.push(make_pair(h.v[l], l));
if (r < h.n)
p.push(make_pair(h.v[r], r));
}
return p.top().first;
}
int main()
{
Heap h(7);
h.v = vector<int>{ 10, 50, 40, 75, 60, 65, 45 };
int k = 4;
cout << findKthSmalles(h, k);
return 0;
}
Java
import java.util.PriorityQueue;
// Structure for the heap
class Heap {
int[] v;
int n; // Size of the heap
Heap(int i) {
n = i;
v = new int[n];
}
}
public class Main {
// Returns the index of the left child node
static int left(int i) {
return 2 * i + 1;
}
// Returns the index of the right child node
static int right(int i) {
return 2 * i + 2;
}
static int findKthSmallest(Heap h, int k) {
// Create a Priority Queue
PriorityQueue<int[]> p = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
// Insert root into the priority queue
p.add(new int[]{h.v[0], 0});
for (int i = 0; i < k - 1; i++) {
int[] top = p.poll();
int j = top[1];
int l = left(j), r = right(j);
if (l < h.n) {
p.add(new int[]{h.v[l], l});
}
if (r < h.n) {
p.add(new int[]{h.v[r], r});
}
}
return p.peek()[0];
}
public static void main(String[] args) {
Heap h = new Heap(7);
h.v = new int[]{10, 50, 40, 75, 60, 65, 45};
int k = 4;
System.out.println(findKthSmallest(h, k));
}
}
Python3
# Python program to find k-th smallest
# element in Min Heap using another
# Min Heap (Or Priority Queue)
import heapq
# Structure for the heap
class Heap:
def __init__(self, n):
self.v = [0] * n
self.n = n
# Returns the index of
# the left child node
def left(i):
return 2 * i + 1
# Returns the index of
# the right child node
def right(i):
return 2 * i + 2
def findKthSmalles(h, k):
# Create a Priority Queue
p = []
# Insert root into the priority queue
heapq.heappush(p, (h.v[0], 0))
for i in range(k - 1):
j = heapq.heappop(p)[1]
l, r = left(j), right(j)
if l < h.n:
heapq.heappush(p, (h.v[l], l))
if r < h.n:
heapq.heappush(p, (h.v[r], r))
return p[0][0]
# Main function
def main():
h = Heap(7)
h.v = [10, 50, 40, 75, 60, 65, 45]
k = 4
print(findKthSmalles(h, k))
if __name__ == '__main__':
main()
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class Heap
{
private int[] v; // Array to store the heap elements
private int n; // Size of the heap
public Heap(int size)
{
v = new int[size]; // Initialize the array for the heap
n = size; // Set the size of the heap
}
// Returns the index of the left child node
private int Left(int i)
{
return 2 * i + 1;
}
// Returns the index of the right child node
private int Right(int i)
{
return 2 * i + 2;
}
// Function to find the k-th smallest element in the heap
public int FindKthSmallest(int k)
{
// Create a Priority Queue using SortedDictionary
var p = new SortedDictionary<int, int>();
// Insert root into the priority queue
p.Add(v[0], 0);
// Iterate k-1 times to find the k-th smallest element
for (int i = 0; i < k - 1; i++)
{
var item = p.First(); // Get the smallest element from the priority queue
p.Remove(item.Key); // Remove the smallest element
int j = item.Value; // Get the index of the smallest element in the heap
int l = Left(j); // Calculate the index of the left child
int r = Right(j); // Calculate the index of the right child
// Add left child to the priority queue if within the heap size
if (l < n)
p.Add(v[l], l);
// Add right child to the priority queue if within the heap size
if (r < n)
p.Add(v[r], r);
}
return p.Keys.First(); // Return the smallest element (k-th smallest)
}
public static void Main(string[] args)
{
Heap h = new Heap(7); // Create a new heap with size 7
h.v = new int[] { 10, 50, 40, 75, 60, 65, 45 }; // Assign heap elements
int k = 4; // Define the value of k
Console.WriteLine(h.FindKthSmallest(k)); // Print the k-th smallest element
}
}
JavaScript
class Heap {
constructor(i) {
this.n = i; // Size of the heap
this.v = new Array(this.n);
}
}
// Returns the index of the left child node
function left(i) {
return 2 * i + 1;
}
// Returns the index of the right child node
function right(i) {
return 2 * i + 2;
}
function findKthSmallest(h, k) {
// Create a Priority Queue
const p = new MinHeap((a, b) => a[0] - b[0]);
// Insert root into the priority queue
p.add([h.v[0], 0]);
for (let i = 0; i < k - 1; i++) {
const top = p.poll();
const j = top[1];
const l = left(j);
const r = right(j);
if (l < h.n) {
p.add([h.v[l], l]);
}
if (r < h.n) {
p.add([h.v[r], r]);
}
}
return p.peek()[0];
}
class MinHeap {
constructor(comparator) {
this.heap = [];
this.comparator = comparator;
}
add(item) {
this.heap.push(item);
this.heapifyUp();
}
poll() {
if (this.isEmpty()) {
throw new Error('The heap is empty.');
}
if (this.heap.length === 1) {
return this.heap.pop();
}
const min = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown();
return min;
}
peek() {
if (this.isEmpty()) {
throw new Error('The heap is empty.');
}
return this.heap[0];
}
isEmpty() {
return this.heap.length === 0;
}
size() {
return this.heap.length;
}
heapifyUp() {
let currentIndex = this.heap.length - 1;
while (this.hasParent(currentIndex) && this.compare(currentIndex, this.parentIndex(currentIndex)) < 0) {
this.swap(currentIndex, this.parentIndex(currentIndex));
currentIndex = this.parentIndex(currentIndex);
}
}
heapifyDown() {
let currentIndex = 0;
while (this.hasLeftChild(currentIndex)) {
let smallerChildIndex = this.leftChildIndex(currentIndex);
if (this.hasRightChild(currentIndex) && this.compare(this.leftChildIndex(currentIndex), this.rightChildIndex(currentIndex)) > 0) {
smallerChildIndex = this.rightChildIndex(currentIndex);
}
if (this.compare(currentIndex, smallerChildIndex) < 0) {
break;
} else {
this.swap(currentIndex, smallerChildIndex);
}
currentIndex = smallerChildIndex;
}
}
hasParent(index) {
return index > 0;
}
parentIndex(index) {
return Math.floor((index - 1) / 2);
}
hasLeftChild(index) {
return this.leftChildIndex(index) < this.heap.length;
}
leftChildIndex(index) {
return index * 2 + 1;
}
hasRightChild(index) {
return this.rightChildIndex(index) < this.heap.length;
}
rightChildIndex(index) {
return index * 2 + 2;
}
compare(index1, index2) {
return this.comparator(this.heap[index1], this.heap[index2]);
}
swap(index1, index2) {
const temp = this.heap[index1];
this.heap[index1] = this.heap[index2];
this.heap[index2] = temp;
}
}
// Main function
function main() {
const h = new Heap(7);
h.v = [10, 50, 40, 75, 60, 65, 45];
const k = 4;
console.log(findKthSmallest(h, k));
}
// Call the main function
main();
Time Complexity: O(k * log k)
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