Sort a linked list of 0s, 1s and 2s
Last Updated :
27 Aug, 2024
Given a linked list of 0s, 1s and 2s, The task is to sort the list in non-decreasing order.
Examples:
Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL
Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL
Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL
[Expected Approach - 1] By Maintaining Frequency - O(n) Time and O(1) Space:
The idea is to traverse the linked List and count the number of nodes having values 0, 1 and 2 and store them in an array of size 3, say cnt[] such that
- cnt[0] = count of nodes with value 0
- cnt[1] = count of nodes with value 1
- cnt[2] = count of nodes with value 2
Now, traverse the linked list again to fill the first cnt[0] nodes with 0, then next cnt[1] nodes with 1 and finally cnt[2] nodes with 2.
Below is the illustration of above approach :
Below is the implementation of the above approach.
C++
// C++ Program to sort a linked list of 0s, 1s or 2s
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Function to sort a linked list of 0s, 1s and 2s
void sortList(Node* head) {
// Initialize count of '0', '1' and '2' as 0
int cnt[3] = {0, 0, 0};
Node *ptr = head;
// Traverse and count total number of '0', '1' and '2'
// cnt[0] will store total number of '0's
// cnt[1] will store total number of '1's
// cnt[2] will store total number of '2's
while (ptr != NULL) {
cnt[ptr->data] += 1;
ptr = ptr->next;
}
int idx = 0;
ptr = head;
// Fill first cnt[0] nodes with value 0
// Fill next cnt[1] nodes with value 1
// Fill remaining cnt[2] nodes with value 2
while (ptr != nullptr) {
if (cnt[idx] == 0)
idx += 1;
else {
ptr->data = idx;
cnt[idx] -= 1;
ptr = ptr->next;
}
}
}
void printList(Node *node) {
while (node != nullptr) {
cout << " " << node->data;
node = node->next;
}
cout << "\n";
}
int main() {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Node *head = new Node(1);
head->next = new Node(1);
head->next->next = new Node(2);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(0);
cout << "Linked List before Sorting:";
printList(head);
sortList(head);
cout << "Linked List after Sorting:";
printList(head);
return 0;
}
C
// C Program to sort a linked list of 0s, 1s or 2s
#include <stdio.h>
struct Node {
int data;
struct Node *next;
};
// Function to sort a linked list of 0s, 1s and 2s
void sortList(struct Node *head) {
// Initialize count of '0', '1' and '2' as 0
int cnt[3] = {0, 0, 0};
struct Node *ptr = head;
// Traverse and count total number of '0', '1' and '2'
// cnt[0] will store total number of '0's
// cnt[1] will store total number of '1's
// cnt[2] will store total number of '2's
while (ptr != NULL) {
cnt[ptr->data] += 1;
ptr = ptr->next;
}
int idx = 0;
ptr = head;
// Fill first cnt[0] nodes with value 0
// Fill next cnt[1] nodes with value 1
// Fill remaining cnt[2] nodes with value 2
while (ptr != NULL) {
if (cnt[idx] == 0) {
idx += 1;
}
else {
ptr->data = idx;
cnt[idx] -= 1;
ptr = ptr->next;
}
}
}
void printList(struct Node *node) {
while (node != NULL) {
printf(" %d", node->data);
node = node->next;
}
printf("\n");
}
struct Node *createNode(int new_data) {
struct Node *new_node =
(struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
int main() {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
struct Node *head = createNode(1);
head->next = createNode(1);
head->next->next = createNode(2);
head->next->next->next = createNode(1);
head->next->next->next->next = createNode(0);
printf("Linked List before Sorting:");
printList(head);
sortList(head);
printf("Linked List after Sorting:");
printList(head);
return 0;
}
Java
// Java Program to sort a linked list of 0s, 1s or 2s
class Node {
int data;
Node next;
Node(int new_data) {
data = new_data;
next = null;
}
}
// Function to sort a linked list of 0s, 1s and 2s
class GfG {
static void sortList(Node head) {
// Initialize count of '0', '1' and '2' as 0
int[] cnt = { 0, 0, 0 };
Node ptr = head;
// Traverse and count total number of '0', '1' and '2'
// cnt[0] will store total number of '0's
// cnt[1] will store total number of '1's
// cnt[2] will store total number of '2's
while (ptr != null) {
cnt[ptr.data] += 1;
ptr = ptr.next;
}
int idx = 0;
ptr = head;
// Fill first cnt[0] nodes with value 0
// Fill next cnt[1] nodes with value 1
// Fill remaining cnt[2] nodes with value 2
while (ptr != null) {
if (cnt[idx] == 0)
idx += 1;
else {
ptr.data = idx;
cnt[idx] -= 1;
ptr = ptr.next;
}
}
}
static void printList(Node node) {
while (node != null) {
System.out.print(" " + node.data);
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Node head = new Node(1);
head.next = new Node(1);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(0);
System.out.print("Linked List before Sorting:");
printList(head);
sortList(head);
System.out.print("Linked List after Sorting:");
printList(head);
}
}
Python
# Python Program to sort a linked list of 0s, 1s or 2s
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# Function to sort a linked list of 0s, 1s and 2s
def sort_list(head):
# Initialize count of '0', '1' and '2' as 0
cnt = [0, 0, 0]
ptr = head
# Traverse and count total number of '0', '1' and '2'
# cnt[0] will store total number of '0's
# cnt[1] will store total number of '1's
# cnt[2] will store total number of '2's
while ptr is not None:
cnt[ptr.data] += 1
ptr = ptr.next
idx = 0
ptr = head
# Fill first cnt[0] nodes with value 0
# Fill next cnt[1] nodes with value 1
# Fill remaining cnt[2] nodes with value 2
while ptr is not None:
if cnt[idx] == 0:
idx += 1
else:
ptr.data = idx
cnt[idx] -= 1
ptr = ptr.next
def print_list(node):
while node is not None:
print(f" {node.data}", end='')
node = node.next
print("\n")
if __name__ == "__main__":
# Create a hard-coded linked list:
# 1 -> 1 -> 2 -> 1 -> 0 -> NULL
head = Node(1)
head.next = Node(1)
head.next.next = Node(2)
head.next.next.next = Node(1)
head.next.next.next.next = Node(0)
print("Linked List before Sorting:", end='')
print_list(head)
sort_list(head)
print("Linked List after Sorting:", end='')
print_list(head)
C#
// C# Program to sort a linked list of 0s, 1s or 2s
using System;
class Node {
public int Data;
public Node Next;
public Node(int newData) {
Data = newData;
Next = null;
}
}
class GfG {
// Function to sort a linked list of 0s, 1s, and 2s
static void SortList(Node head) {
// Initialize count of '0', '1', and '2' as 0
int[] cnt = { 0, 0, 0 };
Node ptr = head;
// Traverse and count total number of '0', '1', and '2'
// cnt[0] will store total number of '0's
// cnt[1] will store total number of '1's
// cnt[2] will store total number of '2's
while (ptr != null) {
cnt[ptr.Data] += 1;
ptr = ptr.Next;
}
int idx = 0;
ptr = head;
// Fill first cnt[0] nodes with value 0
// Fill next cnt[1] nodes with value 1
// Fill remaining cnt[2] nodes with value 2
while (ptr != null) {
if (cnt[idx] == 0)
idx += 1;
else {
ptr.Data = idx;
cnt[idx] -= 1;
ptr = ptr.Next;
}
}
}
static void PrintList(Node node) {
while (node != null) {
Console.Write(" " + node.Data);
node = node.Next;
}
Console.WriteLine();
}
static void Main() {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Node head = new Node(1);
head.Next = new Node(1);
head.Next.Next = new Node(2);
head.Next.Next.Next = new Node(1);
head.Next.Next.Next.Next = new Node(0);
Console.Write("Linked List before Sorting:");
PrintList(head);
SortList(head);
Console.Write("Linked List after Sorting:");
PrintList(head);
}
}
JavaScript
// JavaScript Program to sort a linked list of 0s, 1s or 2s
class Node {
constructor(newData) {
this.data = newData;
this.next = null;
}
}
// Function to sort a linked list of 0s, 1s and 2s
function sortList(head) {
// Initialize count of '0', '1' and '2' as 0
const cnt = [ 0, 0, 0 ];
let ptr = head;
// Traverse and count total number of '0', '1' and '2'
// cnt[0] will store total number of '0's
// cnt[1] will store total number of '1's
// cnt[2] will store total number of '2's
while (ptr !== null) {
cnt[ptr.data] += 1;
ptr = ptr.next;
}
let idx = 0;
ptr = head;
// Fill first cnt[0] nodes with value 0
// Fill next cnt[1] nodes with value 1
// Fill remaining cnt[2] nodes with value 2
while (ptr !== null) {
if (cnt[idx] === 0) {
idx += 1;
}
else {
ptr.data = idx;
cnt[idx] -= 1;
ptr = ptr.next;
}
}
}
function printList(node) {
while (node !== null) {
console.log(node.data);
node = node.next;
}
console.log();
}
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
let head = new Node(1);
head.next = new Node(1);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(0);
console.log("Linked List before Sorting:");
printList(head);
sortList(head);
console.log("Linked List after Sorting:");
printList(head);
OutputLinked List before Sorting: 1 1 2 1 0
Linked List after Sorting: 0 1 1 1 2
Time Complexity: O(n) where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
[Expected Approach - 2] By Updating Links of Nodes - O(n) Time and O(1) Space:
The idea is to maintain 3 pointers named zero, one and two to point to current ending nodes of linked lists containing 0, 1, and 2 respectively. For every traversed node, we attach it to the end of its corresponding list.
- If the current node's value is 0, append it after pointer zero and move pointer zero to current node.
- If the current node's value is 1, append it after pointer one and move pointer one to current node.
- If the current node's value is 2, append it after pointer two and move pointer two to current node.
Finally, we link all three lists. To avoid many null checks, we use three dummy pointers zeroD, oneD and twoD that work as dummy headers of three lists.
Below is the implementation of the above approach:
C++
// C++ Program to sort a linked list 0s, 1s
// or 2s by updating links
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node *next;
Node(int new_data) {
data = new_data;
next = nullptr;
}
};
// Sort a linked list of 0s, 1s, and 2s by changing pointers
Node *sortList(Node *head) {
if (!head || !(head->next))
return head;
// Create three dummy nodes to point to the beginning of
// three linked lists. These dummy nodes are created to
// avoid null checks.
Node *zeroD = new Node(0);
Node *oneD = new Node(0);
Node *twoD = new Node(0);
// Initialize current pointers for three lists
Node *zero = zeroD, *one = oneD, *two = twoD;
// Traverse the list
Node *curr = head;
while (curr != NULL) {
if (curr->data == 0) {
// If the data of the current node is 0,
// append it to pointer zero and update zero
zero->next = curr;
zero = zero->next;
}
else if (curr->data == 1) {
// If the data of the current node is 1,
// append it to pointer one and update one
one->next = curr;
one = one->next;
}
else {
// If the data of the current node is 2,
// append it to pointer two and update two
two->next = curr;
two = two->next;
}
curr = curr->next;
}
// Combine the three lists
if (oneD->next)
zero->next = oneD->next;
else
zero->next = twoD->next;
one->next = twoD->next;
two->next = nullptr;
// Updated head
head = zeroD->next;
return head;
}
void printList(Node *node) {
while (node != nullptr) {
cout << " " << node->data;
node = node->next;
}
cout << "\n";
}
int main() {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Node *head = new Node(1);
head->next = new Node(1);
head->next->next = new Node(2);
head->next->next->next = new Node(1);
head->next->next->next->next = new Node(0);
cout << "Linked List before Sorting:";
printList(head);
head = sortList(head);
cout << "Linked List after Sorting:";
printList(head);
return 0;
}
C
// C Program to sort a linked list 0s, 1s
// or 2s by updating links
#include <stdio.h>
struct Node {
int data;
struct Node* next;
};
// Function to create a new node
struct Node* createNode(int new_data);
// Sort a linked list of 0s, 1s and 2s
// by changing pointers
struct Node* sortList(struct Node* head) {
if (!head || !(head->next))
return head;
// Create three dummy nodes to point to beginning of
// three linked lists. These dummy nodes are created to
// avoid null checks.
struct Node* zeroD = createNode(0);
struct Node* oneD = createNode(0);
struct Node* twoD = createNode(0);
// Initialize current pointers for three
// lists
struct Node *zero = zeroD, *one = oneD, *two = twoD;
// Traverse list
struct Node* curr = head;
while (curr) {
if (curr->data == 0) {
// If the data of current node is 0,
// append it to pointer zero and update zero
zero->next = curr;
zero = zero->next;
}
else if (curr->data == 1) {
// If the data of current node is 1,
// append it to pointer one and update one
one->next = curr;
one = one->next;
}
else {
// If the data of current node is 2,
// append it to pointer two and update two
two->next = curr;
two = two->next;
}
curr = curr->next;
}
// Combine the three lists
zero->next = (oneD->next) ? (oneD->next) : (twoD->next);
one->next = twoD->next;
two->next = NULL;
// Updated head
head = zeroD->next;
return head;
}
void printList(struct Node* node) {
while (node != NULL) {
printf(" %d", node->data);
node = node->next;
}
printf("\n");
}
struct Node* createNode(int new_data) {
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
int main() {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
struct Node* head = createNode(1);
head->next = createNode(1);
head->next->next = createNode(2);
head->next->next->next = createNode(1);
head->next->next->next->next = createNode(0);
printf("Linked List before Sorting:");
printList(head);
head = sortList(head);
printf("Linked List after Sorting:");
printList(head);
return 0;
}
Java
// Java Program to sort a linked list of 0s, 1s
// or 2s by updating links
class Node {
int data;
Node next;
Node(int new_data) {
data = new_data;
next = null;
}
}
class GfG {
// Sort a linked list of 0s, 1s and 2s
// by changing pointers
static Node sortList(Node head) {
if (head == null || head.next == null)
return head;
// Create three dummy nodes to point to beginning of
// three linked lists. These dummy nodes are created to
// avoid null checks.
Node zeroD = new Node(0);
Node oneD = new Node(0);
Node twoD = new Node(0);
// Initialize current pointers for three
// lists
Node zero = zeroD, one = oneD, two = twoD;
// Traverse list
Node curr = head;
while (curr != null) {
if (curr.data == 0) {
// If the data of current node is 0,
// append it to pointer zero and update zero
zero.next = curr;
zero = zero.next;
}
else if (curr.data == 1) {
// If the data of current node is 1,
// append it to pointer one and update one
one.next = curr;
one = one.next;
}
else {
// If the data of current node is 2,
// append it to pointer two and update two
two.next = curr;
two = two.next;
}
curr = curr.next;
}
// Combine the three lists
zero.next = (oneD.next != null) ? (oneD.next) : (twoD.next);
one.next = twoD.next;
two.next = null;
// Updated head
head = zeroD.next;
return head;
}
static void printList(Node node) {
while (node != null) {
System.out.print(" " + node.data);
node = node.next;
}
System.out.println();
}
public static void main(String[] args) {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Node head = new Node(1);
head.next = new Node(1);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(0);
System.out.print("Linked List before Sorting:");
printList(head);
head = sortList(head);
System.out.print("Linked List after Sorting:");
printList(head);
}
}
Python
# Python Program to sort a linked list 0s, 1s
# or 2s by updating links
class Node:
def __init__(self, new_data):
self.data = new_data
self.next = None
# Sort a linked list of 0s, 1s and 2s
# by changing pointers
def sortList(head):
if not head or not head.next:
return head
# Create three dummy nodes to point to beginning of
# three linked lists. These dummy nodes are created to
# avoid null checks.
zeroD = Node(0)
oneD = Node(0)
twoD = Node(0)
# Initialize current pointers for three
# lists
zero = zeroD
one = oneD
two = twoD
# Traverse list
curr = head
while curr:
if curr.data == 0:
# If the data of current node is 0,
# append it to pointer zero and update zero
zero.next = curr
zero = zero.next
elif curr.data == 1:
# If the data of cu
# append it to pointer one and update one
one.next = curr
one = one.next
else:
# If the data of current node is 2,
# append it to pointer two and update two
two.next = curr
two = two.next
curr = curr.next
# Combine the three lists
zero.next = oneD.next if oneD.next else twoD.next
one.next = twoD.next
two.next = None
# Updated head
head = zeroD.next
return head
def printList(node):
while node is not None:
print(node.data, end=' ')
node = node.next
print()
if __name__ == "__main__":
# Create a hard-coded linked list:
# 1 -> 1 -> 2 -> 1 -> 0 -> NULL
head = Node(1)
head.next = Node(1)
head.next.next = Node(2)
head.next.next.next = Node(1)
head.next.next.next.next = Node(0)
print("Linked List before Sorting: ", end='')
printList(head)
head = sortList(head)
print("Linked List after Sorting: ", end='')
printList(head)
C#
// C# Program to sort a linked list 0s, 1s
// or 2s by updating links
using System;
public class Node {
public int Data;
public Node Next;
public Node(int newData) {
Data = newData;
Next = null;
}
}
// Sort a linked list of 0s, 1s and 2s
// by changing pointers
class GfG {
static Node SortList(Node head) {
if (head == null || head.Next == null)
return head;
// Create three dummy nodes to point to beginning of
// three linked lists. These dummy nodes are created to
// avoid null checks.
Node zeroD = new Node(0);
Node oneD = new Node(0);
Node twoD = new Node(0);
// Initialize current pointers for three
// lists
Node zero = zeroD, one = oneD, two = twoD;
// Traverse list
Node curr = head;
while (curr != null) {
if (curr.Data == 0) {
// If the data of current node is 0,
// append it to pointer zero and update zero
zero.Next = curr;
zero = zero.Next;
}
else if (curr.Data == 1) {
// If the data of current node is 1,
// append it to pointer one and update one
one.Next = curr;
one = one.Next;
}
else {
// If the data of current node is 2,
// append it to pointer two and update two
two.Next = curr;
two = two.Next;
}
curr = curr.Next;
}
// Combine the three lists
zero.Next = (oneD.Next != null) ? (oneD.Next) : (twoD.Next);
one.Next = twoD.Next;
two.Next = null;
// Updated head
head = zeroD.Next;
// Delete dummy nodes
// In C# garbage collection will handle this
return head;
}
// This function prints the contents
// of the linked list starting from the head
static void PrintList(Node node) {
while (node != null) {
Console.Write(" " + node.Data);
node = node.Next;
}
Console.WriteLine();
}
static void Main() {
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
Node head = new Node(1);
head.Next = new Node(1);
head.Next.Next = new Node(2);
head.Next.Next.Next = new Node(1);
head.Next.Next.Next.Next = new Node(0);
Console.Write("Linked List before Sorting:");
PrintList(head);
head = SortList(head);
Console.Write("Linked List after Sorting:");
PrintList(head);
}
}
JavaScript
// Javascript program to sort a linked list of 0s, 1s
// or 2s by updating links
class Node {
constructor(newData) {
this.data = newData;
this.next = null;
}
}
// Sort a linked list of 0s, 1s and 2s
// by changing pointers
function sortList(head) {
if (!head || !head.next)
return head;
// Create three dummy nodes to point to beginning of
// three linked lists. These dummy nodes are created to
// avoid null checks.
let zeroD = new Node(0);
let oneD = new Node(0);
let twoD = new Node(0);
// Initialize current pointers for three
// lists
let zero = zeroD, one = oneD, two = twoD;
// Traverse list
let curr = head;
while (curr) {
if (curr.data === 0) {
// If the data of current node is 0,
// append it to pointer zero and update zero
zero.next = curr;
zero = zero.next;
}
else if (curr.data === 1) {
// If the data of current node is 1,
// append it to pointer one and update one
one.next = curr;
one = one.next;
}
else {
// If the data of current node is 2,
// append it to pointer two and update two
two.next = curr;
two = two.next;
}
curr = curr.next;
}
// Combine the three lists
zero.next = (oneD.next) ? (oneD.next) : (twoD.next);
one.next = twoD.next;
two.next = null;
// Updated head
head = zeroD.next;
return head;
}
function printList(node) {
while (node !== null) {
console.log(node.data);
node = node.next;
}
console.log();
}
// Create a hard-coded linked list:
// 1 -> 1 -> 2 -> 1 -> 0 -> NULL
let head = new Node(1);
head.next = new Node(1);
head.next.next = new Node(2);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(0);
console.log("Linked List before Sorting:");
printList(head);
head = sortList(head);
console.log("Linked List after Sorting:");
printList(head);
OutputLinked List before Sorting: 1 1 2 1 0
Linked List after Sorting: 0 1 1 1 2
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)
Sort a linked list of 0s, 1s and 2s
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