Disjoint Set Union (Randomized Algorithm)
Last Updated :
23 Jul, 2025
A Disjoint set union is an algorithm that is used to manage a collection of disjoint sets. A disjoint set is a set in which the elements are not in any other set. Also, known as union-find or merge-find.
The disjoint set union algorithm allows you to perform the following operations efficiently:
- Find: Determine which set a given element belongs to.
- Union: Merge two sets into a single set.
There are several ways to implement the disjoint set union algorithm, including the use of a randomized algorithm. Here is one way to implement the disjoint set union algorithm using a randomized approach:
- Initialize an array parent[] of size n, where n is the number of elements in the disjoint set. Set the value of each element in the parent to be its own index. This means that each element is initially in its own set.
- To find the set that a given element x belongs to, follow the chain of parent links until you reach an element whose parent is itself. This is the root element of the set, and it represents the set that x belongs to.
- To merge two sets, find the roots of the two sets and set the parent of one of the roots to be the other root.
- To improve the performance of the algorithm, you can use path compression to flatten the tree structure of the sets. This means that when you follow the parent links to find the root of a set, you also set the parent of each element on the path to be the root. This reduces the height of the tree and makes future operations faster.
- To further improve the performance, you can use randomization to choose which element to set as the root of the merged set. This can help to balance the tree and make the algorithm run more efficiently.
Overall, the disjoint set union algorithm is a useful tool for efficiently managing a collection of disjoint sets. It can be used in a variety of applications, including clustering, graph coloring, and image segmentation.
Here is an example of the disjoint set union algorithm implemented in Python:
C++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
class GFG {
public:
vector<int> parent;
vector<int> size;
public:
GFG(int n)
{
parent.resize(n);
size.resize(n);
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union_(int x, int y)
{
int root_x = find(x);
int root_y = find(y);
if (root_x == root_y) {
return;
}
if (rand() % 2 == 0) {
int temp = root_x;
root_x = root_y;
root_y = temp;
}
parent[root_y] = root_x;
size[root_x] += size[root_y];
}
};
int main()
{
GFG ds(5);
cout << "Initial parent array: ";
for (int i = 0; i < 5; i++)
cout << ds.parent[i] << " ";
cout << endl;
// Union the sets containing elements 0 and 1
ds.union_(0, 1);
cout << "Parent array after union(0, 1): ";
for (int i = 0; i < 5; i++)
cout << ds.parent[i] << " ";
cout << endl;
// Union the sets containing elements 1 and 2
ds.union_(1, 2);
cout << "Parent array after union(1, 2): ";
for (int i = 0; i < 5; i++)
cout << ds.parent[i] << " ";
cout << endl;
// Union the sets containing elements 3 and 4
ds.union_(3, 4);
cout << "Parent array after union(3, 4): ";
for (int i = 0; i < 5; i++)
cout << ds.parent[i] << " ";
cout << endl;
cout << "Root of set containing element 0: "
<< ds.find(0) << endl;
cout << "Root of set containing element 3: "
<< ds.find(3) << endl;
return 0;
}
// Note: As we are using random() function,
// the output values may differ.
// This code is contributed by Prasad Kandekar(prasad264)
Java
// Java code for the above approach
import java.io.*;
import java.util.*;
class GFG {
int[] parent;
int[] size;
Random rand = new Random();
public GFG(int n)
{
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int x, int y)
{
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return;
}
if (rand.nextInt(2) == 0) {
int temp = rootX;
rootX = rootY;
rootY = temp;
}
parent[rootX] = rootY;
size[rootY] += size[rootX];
}
public static void main(String[] args)
{
GFG ds = new GFG(5);
System.out.println("Initial parent array: "
+ Arrays.toString(ds.parent));
// Union the sets containing elements 0 and 1
ds.union(0, 1);
System.out.println(
"Parent array after union(0, 1): "
+ Arrays.toString(ds.parent));
// Union the sets containing elements 1 and 2
ds.union(1, 2);
System.out.println(
"Parent array after union(1, 2): "
+ Arrays.toString(ds.parent));
// Union the sets containing elements 3 and 4
ds.union(3, 4);
System.out.println(
"Parent array after union(3, 4): "
+ Arrays.toString(ds.parent));
System.out.println(
"Root of set containing element 0: "
+ ds.find(0));
System.out.println(
"Root of set containing element 3: "
+ ds.find(3));
}
}
// Note: As we are using random() function,
// the output values may differ.
// This code is contributed by lokesh.
Python
# Python code for the above approach
import random
class DisjointSetUnion:
def __init__(self, n):
self.parent = [i for i in range(n)]
self.size = [1] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x == root_y:
return
if random.randint(0, 1) == 0:
root_x, root_y = root_y, root_x
self.parent[root_y] = root_x
self.size[root_x] += self.size[root_y]
# Driver code
ds = DisjointSetUnion(5)
print("Initial parent array: ", ds.parent)
# Union the sets containing elements
# 0 and 1
ds.union(0, 1)
print("Parent array after union(0, 1): ", ds.parent)
# Union the sets containing elements
# 1 and 2
ds.union(1, 2)
print("Parent array after union(1, 2): ", ds.parent)
# Union the sets containing elements
# 3 and 4
ds.union(3, 4)
print("Parent array after union(3, 4): ", ds.parent)
print("Root of set containing element 0: ", ds.find(0))
print("Root of set containing element 3: ", ds.find(3))
C#
// C# code for the above approach
using System;
public class GFG {
int[] parent;
int[] size;
Random rand = new Random();
public GFG(int n)
{
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
public int Find(int x)
{
if (parent[x] != x) {
parent[x] = Find(parent[x]);
}
return parent[x];
}
public void Union(int x, int y)
{
int rootX = Find(x);
int rootY = Find(y);
if (rootX == rootY) {
return;
}
if (rand.Next(2) == 0) {
int temp = rootX;
rootX = rootY;
rootY = temp;
}
parent[rootX] = rootY;
size[rootY] += size[rootX];
}
static public void Main()
{
// Code
GFG ds = new GFG(5);
Console.WriteLine("Initial parent array: ["
+ string.Join(", ", ds.parent)
+ "]");
// Union the sets containing elements 0 and 1
ds.Union(0, 1);
Console.WriteLine(
"Parent array after union(0, 1): ["
+ string.Join(", ", ds.parent) + "]");
// Union the sets containing elements 1 and 2
ds.Union(1, 2);
Console.WriteLine(
"Parent array after union(1, 2): ["
+ string.Join(", ", ds.parent) + "]");
// Union the sets containing elements 3 and 4
ds.Union(3, 4);
Console.WriteLine(
"Parent array after union(3, 4): ["
+ string.Join(", ", ds.parent) + "]");
Console.WriteLine(
"Root of set containing element 0: "
+ ds.Find(0));
Console.WriteLine(
"Root of set containing element 3: "
+ ds.Find(3));
}
}
// This code is contributed by lokeshmvs21.
JavaScript
// Javascript code for the above approach
class DisjointSetUnion {
constructor(n) {
this.parent = [...Array(n).keys()]
this.size = Array(n).fill(1)
}
find(x) {
if (this.parent[x] !== x) {
this.parent[x] = this.find(this.parent[x])
}
return this.parent[x]
}
union(x, y) {
let root_x = this.find(x)
let root_y = this.find(y)
if (root_x === root_y) {
return
}
if (Math.floor(Math.random() * 2) === 0) {
[root_x, root_y] = [root_y, root_x]
}
this.parent[root_y] = root_x
this.size[root_x] += this.size[root_y]
}
}
let ds = new DisjointSetUnion(5)
console.log("Initial parent array: ", ds.parent.join(" "))
// Union the sets containing elements
// 0 and 1
ds.union(0, 1)
console.log("Parent array after union(0, 1): ", ds.parent.join(" "))
// Union the sets containing elements
// 1 and 2
ds.union(1, 2)
console.log("Parent array after union(1, 2): ", ds.parent.join(" "))
// Union the sets containing elements
// 3 and 4
ds.union(3, 4)
console.log("Parent array after union(3, 4): ", ds.parent.join(" "))
console.log("Root of set containing element 0: ", ds.find(0))
console.log("Root of set containing element 3: ", ds.find(3))
//This code is contributed by shivamsharma215
OutputInitial parent array: 0 1 2 3 4
Parent array after union(0, 1): 0 0 2 3 4
Parent array after union(1, 2): 2 0 2 3 4
Parent array after union(3, 4): 2 0 2 3 3
Root of set containing element 0: 2
Root of set containing element 3: 3
Below is an implementation of the DisjointSetUnion class that uses randomized linking for the union operation:
C++
#include <iostream>
#include <vector>
#include <random>
using namespace std;
// Define the DisjointSetUnion class
class DisjointSetUnion {
public:
// Constructor that initializes the parent and size arrays
DisjointSetUnion(int n) {
parent = vector<int>(n);
size = vector<int>(n, 1);
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
// Find the root of the set containing element x
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
// Merge the sets containing elements x and y
void unite(int x, int y) {
int root_x = find(x);
int root_y = find(y);
if (root_x == root_y) {
return;
}
// Randomly choose one root to be the parent of the other
if (rand() % 2 == 0) {
swap(root_x, root_y);
}
parent[root_y] = root_x;
size[root_x] += size[root_y];
}
private:
vector<int> parent;
vector<int> size;
};
// Driver code
int main() {
DisjointSetUnion ds(5);
cout << "Initial parent array: ";
for (int i = 0; i < 5; i++) {
cout << ds.find(i) << " ";
}
cout << endl;
// Union the sets containing elements 0 and 1
ds.unite(0, 1);
cout << "Parent array after union(0, 1): ";
for (int i = 0; i < 5; i++) {
cout << ds.find(i) << " ";
}
cout << endl;
// Union the sets containing elements 1 and 2
ds.unite(1, 2);
cout << "Parent array after union(1, 2): ";
for (int i = 0; i < 5; i++) {
cout << ds.find(i) << " ";
}
cout << endl;
// Union the sets containing elements 3 and 4
ds.unite(3, 4);
cout << "Parent array after union(3, 4): ";
for (int i = 0; i < 5; i++) {
cout << ds.find(i) << " ";
}
cout << endl;
// Find the root of the set containing element 0
cout << "Root of set containing element 0: " << ds.find(0) << endl;
// Find the root of the set containing element 3
cout << "Root of set containing element 3: " << ds.find(3) << endl;
return 0;
}
Java
import java.util.Arrays;
import java.util.Random;
public class DisjointSetUnion {
private int[] parent;
private int[] size;
public DisjointSetUnion(int n)
{
this.parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
this.size = new int[n];
Arrays.fill(size, 1);
}
public int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public void union(int x, int y)
{
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return;
}
Random rand = new Random();
if (rand.nextInt(2) == 0) {
int temp = rootX;
rootX = rootY;
rootY = temp;
}
parent[rootY] = rootX;
size[rootX] += size[rootY];
}
public static void main(String[] args)
{
DisjointSetUnion ds = new DisjointSetUnion(5);
System.out.println("Initial parent array: "
+ Arrays.toString(ds.parent));
ds.union(0, 1);
System.out.println(
"Parent array after union(0, 1): "
+ Arrays.toString(ds.parent));
ds.union(1, 2);
System.out.println(
"Parent array after union(1, 2): "
+ Arrays.toString(ds.parent));
ds.union(3, 4);
System.out.println(
"Parent array after union(3, 4): "
+ Arrays.toString(ds.parent));
System.out.println(
"Root of set containing element 0: "
+ ds.find(0));
System.out.println(
"Root of set containing element 3: "
+ ds.find(3));
}
}
Python
import random
class DisjointSetUnion:
def __init__(self, n):
self.parent = [i for i in range(n)]
self.size = [1] * n
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
root_x = self.find(x)
root_y = self.find(y)
if root_x == root_y:
return
if random.randint(0, 1) == 0:
root_x, root_y = root_y, root_x
self.parent[root_y] = root_x
self.size[root_x] += self.size[root_y]
# Driver code
ds = DisjointSetUnion(5)
print("Initial parent array: ", ds.parent)
# Union the sets containing elements
# 0 and 1
ds.union(0, 1)
print("Parent array after union(0, 1): ", ds.parent)
# Union the sets containing elements
# 1 and 2
ds.union(1, 2)
print("Parent array after union(1, 2): ", ds.parent)
# Union the sets containing elements
# 3 and 4
ds.union(3, 4)
print("Parent array after union(3, 4): ", ds.parent)
print("Root of set containing element 0: ", ds.find(0))
print("Root of set containing element 3: ", ds.find(3))
C#
// C# code for the approach
using System;
using System.Collections.Generic;
// Define the DisjointSetUnion class
class DisjointSetUnion {
private List<int> parent;
private List<int> size;
// Constructor that initializes the parent and size
// arrays
public DisjointSetUnion(int n)
{
parent = new List<int>(n);
size = new List<int>(n);
for (int i = 0; i < n; i++) {
parent.Add(i);
size.Add(1);
}
}
// Find the root of the set containing element x
public int Find(int x)
{
if (parent[x] != x) {
parent[x] = Find(parent[x]);
}
return parent[x];
}
// Merge the sets containing elements x and y
public void Unite(int x, int y)
{
int root_x = Find(x);
int root_y = Find(y);
if (root_x == root_y) {
return;
}
// Randomly choose one root to be the parent of the
// other
if (new Random().Next(2) == 0) {
int temp = root_x;
root_x = root_y;
root_y = temp;
}
parent[root_y] = root_x;
size[root_x] += size[root_y];
}
}
// Driver code
class Program {
static void Main(string[] args)
{
DisjointSetUnion ds = new DisjointSetUnion(5);
Console.Write("Initial parent array: ");
for (int i = 0; i < 5; i++) {
Console.Write(ds.Find(i) + " ");
}
Console.WriteLine();
// Union the sets containing elements 0 and 1
ds.Unite(0, 1);
Console.Write("Parent array after union(0, 1): ");
for (int i = 0; i < 5; i++) {
Console.Write(ds.Find(i) + " ");
}
Console.WriteLine();
// Union the sets containing elements 1 and 2
ds.Unite(1, 2);
Console.Write("Parent array after union(1, 2): ");
for (int i = 0; i < 5; i++) {
Console.Write(ds.Find(i) + " ");
}
Console.WriteLine();
// Union the sets containing elements 3 and 4
ds.Unite(3, 4);
Console.Write("Parent array after union(3, 4): ");
for (int i = 0; i < 5; i++) {
Console.Write(ds.Find(i) + " ");
}
Console.WriteLine();
// Find the root of the set containing element 0
Console.WriteLine(
"Root of set containing element 0: "
+ ds.Find(0));
// Find the root of the set containing element 3
Console.WriteLine(
"Root of set containing element 3: "
+ ds.Find(3));
}
}
JavaScript
class DisjointSetUnion {
// Constructor that initializes the parent and size arrays
constructor(n) {
this.parent = new Array(n); // Create an array of n elements to store the parent of each node
for (let i = 0; i < n; i++) {
this.parent[i] = i; // Initialize the parent of each node to itself
}
this.size = new Array(n).fill(1); // Create an array of n elements to store the size of each set, initialized to 1 for each node
}
// Method to find the root of the set containing x
find(x) {
if (this.parent[x] !== x) {
// If x is not the root of its set, recursively find the root and update the parent of x to the root to compress the path
this.parent[x] = this.find(this.parent[x]);
}
return this.parent[x]; // Return the root of the set containing x
}
// Method to union the sets containing x and y
union(x, y) {
let rootX = this.find(x); // Find the root of the set containing x
let rootY = this.find(y); // Find the root of the set containing y
if (rootX === rootY) {
// If x and y are already in the same set, do nothing
return;
}
if (Math.floor(Math.random() * 2) === 0) {
// Randomly choose which root becomes the new parent
[rootX, rootY] = [rootY, rootX]; // Swap rootX and rootY
}
this.parent[rootY] = rootX; // Set the new parent of the set containing y to the root of the set containing x
this.size[rootX] += this.size[rootY]; // Update the size of the set containing x to include the size of the set containing y
}
}
// Example usage of the DisjointSetUnion class
const ds = new DisjointSetUnion(5); // Create a new DisjointSetUnion object with 5 nodes
console.log("Initial parent array: " + ds.parent); // Print the initial parent array
ds.union(0, 1); // Union the sets containing 0 and 1
console.log("Parent array after union(0, 1): " + ds.parent); // Print the parent array after the union
ds.union(1, 2); // Union the sets containing 1 and 2
console.log("Parent array after union(1, 2): " + ds.parent); // Print the parent array after the union
ds.union(3, 4); // Union the sets containing 3 and 4
console.log("Parent array after union(3, 4): " + ds.parent); // Print the parent array after the union
console.log("Root of set containing element 0: " + ds.find(0)); // Find and print the root of the set containing 0
console.log("Root of set containing element 3: " + ds.find(3)); // Find and print the root of the set containing 3
OutputInitial parent array: [0, 1, 2, 3, 4]
Parent array after union(0, 1): [0, 0, 2, 3, 4]
Parent array after union(1, 2): [0, 0, 0, 3, 4]
Parent array after union(3, 4): [0, 0, 0, 4, 4]
Root of set containing element 0: 0
Root of set containing element 3: 4
The output of DisjointSetUnion class that uses randomized linking for the union operation:
Initial parent array: [0, 1, 2, 3, 4]
Parent array after union(0, 1): [0, 0, 2, 3, 4]
Parent array after union(1, 2): [0, 0, 0, 3, 4]
Parent array after union(3, 4): [0, 0, 0, 3, 3]
Root of set containing element 0: 0
Root of set containing element 3: 3
One-try and two-try variations of splitting:
The one-try and two-try variations of splitting are techniques that can be used to improve the performance of the disjoint set union (also known as union-find or merge-find) algorithm in certain cases. These variations are used to optimize the find operation, which is used to determine which set a given element belongs to.
- In the basic disjoint set union algorithm, the find operation follows the chain of parent links to find the root of the set that a given element belongs to. This can be slow if the tree structure of the sets is highly unbalanced.
- The one-try and two-try variations of splitting aim to optimize the find operation by reducing the number of times that the parent links need to be followed. They do this by temporarily modifying the parent links during the find operation in order to "split" the tree into smaller pieces.
- The find method follows the parent links as usual, but it also temporarily stores the parent of x in a local variable root. If the parent of x is x itself (indicating that x is the root of the set), then the find method returns the root instead of x. This reduces the number of times that the parent links need to be followed and can improve the performance of the find operation.
Here is an example of how the one-try variation of splitting might be implemented:
C++
int find(int x)
{
if (parent[x] != x) {
int root = parent[x];
parent[x] = find(parent[x]);
if (parent[x] == x) {
return root;
}
}
return parent[x];
}
// This code is contributed by akashish__
Java
public int find(int x)
{
if (parent[x] != x) {
int root = parent[x];
parent[x] = find(parent[x]);
if (parent[x] == x) {
return root;
}
}
return parent[x];
}
Python
def find(self, x):
if self.parent[x] != x:
self.parent[x], root = self.find(self.parent[x]), self.parent[x]
if self.parent[x] == x:
return root
return self.parent[x]
C#
// This function finds the root of the disjoint set that x belongs to.
// It uses path compression technique to optimize the search.
int find(int x)
{
// Check if x is not already the root of its disjoint set
if (parent[x] != x) {
// If not, then find the root of its parent using recursion
int root = parent[x];
parent[x] = find(parent[x]);
// If the root of parent is the same as x, it means we have reached
// the root of the disjoint set. Return the original root.
if (parent[x] == x) {
return root;
}
}
// If x is already the root of its disjoint set, return x.
return parent[x];
}
JavaScript
function find(x)
{
if (parent[x] != x) {
let root = parent[x];
parent[x] = find(parent[x]);
if (parent[x] == x) {
return root;
}
}
return parent[x];
}
// This code is contributed by akashish__
The two-try variation of splitting is similar to the one-try variation, but it involves following the parent links twice instead of once. This can further improve the performance of the find operation in some cases.
Overall, the one-try and two-try variations of splitting are techniques that can be used to optimize the find operation in the disjoint set union algorithm. They can be useful in cases where the tree structure of the sets is highly unbalanced and the find operation is taking a long time. However, they may not always provide a significant improvement in performance and may require additional memory and computation.
Analysis of linking and Analysis splitting:
Time complexity: O(alpha(n)) (for find operation)
Time complexity: O(alpha(n)) (for Union operation)
One variation of the disjoint set union algorithm is to use the one-try or two-try variations of splitting to optimize the find operation. These variations can improve the performance of the find operation in cases where the tree structure of the sets is highly unbalanced, but they may not always provide a significant improvement in performance and may require additional memory and computation.
Advantages over the sequential approach:
- Speed: The disjoint set union algorithm has a time complexity of O(alpha(n)), where alpha(n) is the inverse Ackermann function. This means that it is very efficient and can scale well to large data sets. In contrast, the sequential approach has a time complexity of O(n), which can be slow for large data sets.
- Memory efficiency: The disjoint set union algorithm uses a compact data structure that requires only a single array to store the parent links. This makes it more memory efficient than the sequential approach, which uses an array of parent links and an array of rank values.
- Simplicity: The disjoint set union algorithm is relatively simple to implement and does not require the use of additional data structures or complex data structures like heaps.
Disadvantages over sequential approach:
- Slower performance for small data sets: The disjoint set union algorithm may have slower performance than the sequential approach for small data sets. This is because the time complexity of the disjoint set union algorithm is based on the inverse Ackermann function, which grows very slowly.
- More memory usage: The disjoint set union algorithm requires more memory than the sequential approach. This is because it uses a single array to store the parent links, whereas the sequential approach uses two arrays (one for the parent links and one for the rank values).
Overall, the disjoint set union algorithm is a very efficient and scalable data structure for managing a collection of disjoint sets. It is well-suited for large data sets and can be simpler to implement than the sequential approach. However, it may have slower performance and higher memory usage than the sequential approach for small data sets.
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