Merge two sorted linked lists such that merged list is in reverse order
Last Updated :
23 Jul, 2025
Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order).
Examples:
Input: a: 5->10->15->40
b: 2->3->20
Output: res: 40->20->15->10->5->3->2
Input: a: NULL
b: 2->3->20
Output: res: 20->3->2
A Simple Solution is to do following.
1) Reverse first list 'a'.
2) Reverse second list 'b'.
3) Merge two reversed lists.
Another Simple Solution is first Merge both lists, then reverse the merged list.
Both of the above solutions require two traversals of linked list.
How to solve without reverse, O(1) auxiliary space (in-place) and only one traversal of both lists?
The idea is to follow merge style process. Initialize result list as empty. Traverse both lists from beginning to end. Compare current nodes of both lists and insert smaller of two at the beginning of the result list.
1) Initialize result list as empty: res = NULL.
2) Let 'a' and 'b' be heads first and second lists respectively.
3) While (a != NULL and b != NULL)
a) Find the smaller of two (Current 'a' and 'b')
b) Insert the smaller value node at the front of result.
c) Move ahead in the list of smaller node.
4) If 'b' becomes NULL before 'a', insert all nodes of 'a'
into result list at the beginning.
5) If 'a' becomes NULL before 'b', insert all nodes of 'a'
into result list at the beginning.
Below is the implementation of above solution.
C++14
/* Given two sorted non-empty linked lists. Merge them in
such a way that the result list will be in reverse
order. Reversing of linked list is not allowed. Also,
extra space should be O(1) */
#include<iostream>
using namespace std;
/* Link list Node */
struct Node
{
int key;
struct Node* next;
};
// Given two non-empty linked lists 'a' and 'b'
Node* SortedMerge(Node *a, Node *b)
{
// If both lists are empty
if (a==NULL && b==NULL) return NULL;
// Initialize head of resultant list
Node *res = NULL;
// Traverse both lists while both of then
// have nodes.
while (a != NULL && b != NULL)
{
// If a's current value is smaller or equal to
// b's current value.
if (a->key <= b->key)
{
// Store next of current Node in first list
Node *temp = a->next;
// Add 'a' at the front of resultant list
a->next = res;
res = a;
// Move ahead in first list
a = temp;
}
// If a's value is greater. Below steps are similar
// to above (Only 'a' is replaced with 'b')
else
{
Node *temp = b->next;
b->next = res;
res = b;
b = temp;
}
}
// If second list reached end, but first list has
// nodes. Add remaining nodes of first list at the
// front of result list
while (a != NULL)
{
Node *temp = a->next;
a->next = res;
res = a;
a = temp;
}
// If first list reached end, but second list has
// node. Add remaining nodes of first list at the
// front of result list
while (b != NULL)
{
Node *temp = b->next;
b->next = res;
res = b;
b = temp;
}
return res;
}
/* Function to print Nodes in a given linked list */
void printList(struct Node *Node)
{
while (Node!=NULL)
{
cout << Node->key << " ";
Node = Node->next;
}
}
/* Utility function to create a new node with
given key */
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
temp->next = NULL;
return temp;
}
/* Driver program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* res = NULL;
/* Let us create two sorted linked lists to test
the above functions. Created lists shall be
a: 5->10->15
b: 2->3->20 */
Node *a = newNode(5);
a->next = newNode(10);
a->next->next = newNode(15);
Node *b = newNode(2);
b->next = newNode(3);
b->next->next = newNode(20);
cout << "List A before merge: \n";
printList(a);
cout << "\nList B before merge: \n";
printList(b);
/* merge 2 increasing order LLs in decreasing order */
res = SortedMerge(a, b);
cout << "\nMerged Linked List is: \n";
printList(res);
return 0;
}
Java
// Java program to merge two sorted linked list such that merged
// list is in reverse order
// Linked List Class
class LinkedList {
Node head; // head of list
static Node a, b;
/* Node Class */
static class Node {
int data;
Node next;
// Constructor to create a new node
Node(int d) {
data = d;
next = null;
}
}
void printlist(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
Node sortedmerge(Node node1, Node node2) {
// if both the nodes are null
if (node1 == null && node2 == null) {
return null;
}
// resultant node
Node res = null;
// if both of them have nodes present traverse them
while (node1 != null && node2 != null) {
// Now compare both nodes current data
if (node1.data <= node2.data) {
Node temp = node1.next;
node1.next = res;
res = node1;
node1 = temp;
} else {
Node temp = node2.next;
node2.next = res;
res = node2;
node2 = temp;
}
}
// If second list reached end, but first list has
// nodes. Add remaining nodes of first list at the
// front of result list
while (node1 != null) {
Node temp = node1.next;
node1.next = res;
res = node1;
node1 = temp;
}
// If first list reached end, but second list has
// node. Add remaining nodes of first list at the
// front of result list
while (node2 != null) {
Node temp = node2.next;
node2.next = res;
res = node2;
node2 = temp;
}
return res;
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
Node result = null;
/*Let us create two sorted linked lists to test
the above functions. Created lists shall be
a: 5->10->15
b: 2->3->20*/
list.a = new Node(5);
list.a.next = new Node(10);
list.a.next.next = new Node(15);
list.b = new Node(2);
list.b.next = new Node(3);
list.b.next.next = new Node(20);
System.out.println("List a before merge :");
list.printlist(a);
System.out.println("");
System.out.println("List b before merge :");
list.printlist(b);
// merge two sorted linkedlist in decreasing order
result = list.sortedmerge(a, b);
System.out.println("");
System.out.println("Merged linked list : ");
list.printlist(result);
}
}
// This code has been contributed by Mayank Jaiswal
Python3
# Given two sorted non-empty linked lists. Merge them in
# such a way that the result list will be in reverse
# order. Reversing of linked list is not allowed. Also,
# extra space should be O(1)
# Node of a linked list
class Node:
def __init__(self, next = None, data = None):
self.next = next
self.data = data
# Given two non-empty linked lists 'a' and 'b'
def SortedMerge(a,b):
# If both lists are empty
if (a == None and b == None):
return None
# Initialize head of resultant list
res = None
# Traverse both lists while both of then
# have nodes.
while (a != None and b != None):
# If a's current value is smaller or equal to
# b's current value.
if (a.key <= b.key):
# Store next of current Node in first list
temp = a.next
# Add 'a' at the front of resultant list
a.next = res
res = a
# Move ahead in first list
a = temp
# If a's value is greater. Below steps are similar
# to above (Only 'a' is replaced with 'b')
else:
temp = b.next
b.next = res
res = b
b = temp
# If second list reached end, but first list has
# nodes. Add remaining nodes of first list at the
# front of result list
while (a != None):
temp = a.next
a.next = res
res = a
a = temp
# If first list reached end, but second list has
# node. Add remaining nodes of first list at the
# front of result list
while (b != None):
temp = b.next
b.next = res
res = b
b = temp
return res
# Function to print Nodes in a given linked list
def printList(Node):
while (Node != None):
print( Node.key, end = " ")
Node = Node.next
# Utility function to create a new node with
# given key
def newNode( key):
temp = Node()
temp.key = key
temp.next = None
return temp
# Driver program to test above functions
# Start with the empty list
res = None
# Let us create two sorted linked lists to test
# the above functions. Created lists shall be
# a: 5.10.15
# b: 2.3.20
a = newNode(5)
a.next = newNode(10)
a.next.next = newNode(15)
b = newNode(2)
b.next = newNode(3)
b.next.next = newNode(20)
print( "List A before merge: ")
printList(a)
print( "\nList B before merge: ")
printList(b)
# merge 2 increasing order LLs in decreasing order
res = SortedMerge(a, b)
print("\nMerged Linked List is: ")
printList(res)
# This code is contributed by Arnab Kundu
C#
// C# program to merge two sorted
// linked list such that merged
// list is in reverse order
// Linked List Class
using System;
class LinkedList
{
public Node head; // head of list
static Node a, b;
/* Node Class */
public class Node
{
public int data;
public Node next;
// Constructor to create a new node
public Node(int d)
{
data = d;
next = null;
}
}
void printlist(Node node)
{
while (node != null)
{
Console.Write(node.data + " ");
node = node.next;
}
}
Node sortedmerge(Node node1, Node node2)
{
// if both the nodes are null
if (node1 == null && node2 == null)
{
return null;
}
// resultant node
Node res = null;
// if both of them have nodes
// present traverse them
while (node1 != null && node2 != null)
{
// Now compare both nodes current data
if (node1.data <= node2.data)
{
Node temp = node1.next;
node1.next = res;
res = node1;
node1 = temp;
}
else
{
Node temp = node2.next;
node2.next = res;
res = node2;
node2 = temp;
}
}
// If second list reached end, but first
// list has nodes. Add remaining nodes of
// first list at the front of result list
while (node1 != null)
{
Node temp = node1.next;
node1.next = res;
res = node1;
node1 = temp;
}
// If first list reached end, but second
// list has node. Add remaining nodes of
// first list at the front of result list
while (node2 != null)
{
Node temp = node2.next;
node2.next = res;
res = node2;
node2 = temp;
}
return res;
}
// Driver code
public static void Main(String[] args)
{
LinkedList list = new LinkedList();
Node result = null;
/*Let us create two sorted linked lists to test
the above functions. Created lists shall be
a: 5->10->15
b: 2->3->20*/
LinkedList.a = new Node(5);
LinkedList.a.next = new Node(10);
LinkedList.a.next.next = new Node(15);
LinkedList.b = new Node(2);
LinkedList.b.next = new Node(3);
LinkedList.b.next.next = new Node(20);
Console.WriteLine("List a before merge :");
list.printlist(a);
Console.WriteLine("");
Console.WriteLine("List b before merge :");
list.printlist(b);
// merge two sorted linkedlist in decreasing order
result = list.sortedmerge(a, b);
Console.WriteLine("");
Console.WriteLine("Merged linked list : ");
list.printlist(result);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// Javascript program to merge two
// sorted linked list such that merged
// list is in reverse order
// Node Class
class Node
{
constructor(d)
{
this.data = d;
this.next = null;
}
}
// Head of list
let head;
let a, b;
function printlist(node)
{
while (node != null)
{
document.write(node.data + " ");
node = node.next;
}
}
function sortedmerge(node1, node2)
{
// If both the nodes are null
if (node1 == null && node2 == null)
{
return null;
}
// Resultant node
let res = null;
// If both of them have nodes present
// traverse them
while (node1 != null && node2 != null)
{
// Now compare both nodes current data
if (node1.data <= node2.data)
{
let temp = node1.next;
node1.next = res;
res = node1;
node1 = temp;
}
else
{
let temp = node2.next;
node2.next = res;
res = node2;
node2 = temp;
}
}
// If second list reached end, but
// first list has nodes. Add
// remaining nodes of first
// list at the front of result list
while (node1 != null)
{
let temp = node1.next;
node1.next = res;
res = node1;
node1 = temp;
}
// If first list reached end, but
// second list has node. Add
// remaining nodes of first
// list at the front of result list
while (node2 != null)
{
let temp = node2.next;
node2.next = res;
res = node2;
node2 = temp;
}
return res;
}
// Driver code
let result = null;
/*Let us create two sorted linked lists to test
the above functions. Created lists shall be
a: 5->10->15
b: 2->3->20*/
a = new Node(5);
a.next = new Node(10);
a.next.next = new Node(15);
b = new Node(2);
b.next = new Node(3);
b.next.next = new Node(20);
document.write("List a before merge :<br>");
printlist(a);
document.write("<br>");
document.write("List b before merge :<br>");
printlist(b);
// Merge two sorted linkedlist in decreasing order
result = sortedmerge(a, b);
document.write("<br>");
document.write("Merged linked list : <br>");
printlist(result);
// This code is contributed by rag2127
</script>
OutputList A before merge:
5 10 15
List B before merge:
2 3 20
Merged Linked List is:
20 15 10 5 3 2
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach:
- Define a struct for linked list nodes with two fields: "data" and "next".
- Define a function "mergeListsReverse" that takes two linked lists "a" and "b" as inputs and returns a pointer to the head of the merged linked list.
- Initialize two pointers "head" and "tail" to "nullptr" for the merged linked list.
- Use a while loop to traverse both linked lists "a" and "b" simultaneously.
- Compare the data values of the current nodes in "a" and "b", and append the smaller node to the head of the merged list.
- Update the corresponding pointer to the next node in the linked list that was appended to the merged list.
- Continue this process until one of the input lists is fully traversed.
- If there are any remaining nodes in list "a", append them to the merged list.
- If there are any remaining nodes in list "b", append them to the merged list.
- Return the head pointer of the merged list.
- Define two utility functions:
a. "push": takes a pointer to a pointer to the head of a linked list and a new integer value, and inserts a new node with the value at the beginning of the list.
b. "printList": takes a pointer to the head of a linked list and prints the values of all nodes in the list.
In the main function, create two empty linked lists "headA" and "headB". - Use the "push" function to insert several integer values into each of the linked lists.
- Print the values of the two input linked lists using the "printList" function.
- Call the "mergeListsReverse" function with the two input linked lists as arguments, and assign the returned head pointer to a new pointer variable "merged".
- Print the values of the merged linked list using the "printList" function.
C++
#include <iostream>
using namespace std;
/* Linked list node */
struct Node {
int data;
Node* next;
};
/* Given two non-empty linked lists 'a' and 'b',
merge them in such a way that the result list
will be in reverse order */
Node* mergeListsReverse(Node* a, Node* b) {
Node* head = nullptr; // head of the merged list
Node* tail = nullptr; // tail of the merged list
while (a && b) {
if (a->data < b->data) {
Node* temp = a->next;
a->next = head;
head = a;
a = temp;
} else {
Node* temp = b->next;
b->next = head;
head = b;
b = temp;
}
}
while (a) {
Node* temp = a->next;
a->next = head;
head = a;
a = temp;
}
while (b) {
Node* temp = b->next;
b->next = head;
head = b;
b = temp;
}
return head;
}
/* Utility function to insert a node at the beginning of a linked list */
void push(Node** headRef, int newData) {
Node* newNode = new Node();
newNode->data = newData;
newNode->next = *headRef;
*headRef = newNode;
}
/* Utility function to print a linked list */
void printList(Node* head) {
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
/* Driver program to test above functions */
int main() {
Node* headA = nullptr;
Node* headB = nullptr;
// Populate list A
push(&headA, 15);
push(&headA, 10);
push(&headA, 5);
// Populate list B
push(&headB, 20);
push(&headB, 3);
push(&headB, 2);
cout << "List A before merge: ";
printList(headA);
cout << "List B before merge: ";
printList(headB);
// Merge the two lists in reverse order
Node* merged = mergeListsReverse(headA, headB);
cout << "Merged list in reverse order: ";
printList(merged);
return 0;
}
Java
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class Main {
/* Given two non-empty linked lists 'a' and 'b',
merge them in such a way that the result list
will be in reverse order */
public static Node mergeListsReverse(Node a, Node b) {
Node head = null; // head of the merged list
Node tail = null; // tail of the merged list
while (a != null && b != null) {
if (a.data < b.data) {
Node temp = a.next;
a.next = head;
head = a;
a = temp;
} else {
Node temp = b.next;
b.next = head;
head = b;
b = temp;
}
}
while (a != null) {
Node temp = a.next;
a.next = head;
head = a;
a = temp;
}
while (b != null) {
Node temp = b.next;
b.next = head;
head = b;
b = temp;
}
return head;
}
/* Utility function to insert a node at the beginning of a linked list */
public static void push(Node headRef, int newData) {
Node newNode = new Node(newData);
newNode.next = headRef;
headRef = newNode;
}
/* Utility function to print a linked list */
public static void printList(Node head) {
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
System.out.println();
}
/* Driver program to test above functions */
public static void main(String[] args) {
Node headA = null;
Node headB = null;
// Populate list A
headA = new Node(5);
headA.next = new Node(10);
headA.next.next = new Node(15);
// Populate list B
headB = new Node(2);
headB.next = new Node(3);
headB.next.next = new Node(20);
System.out.print("List A before merge: ");
printList(headA);
System.out.print("List B before merge: ");
printList(headB);
// Merge the two lists in reverse order
Node merged = mergeListsReverse(headA, headB);
System.out.print("Merged list in reverse order: ");
printList(merged);
}
}
// This code is contributed by rudra1807raj
Python
# Linked list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to merge two linked lists in reverse order
def mergeListsReverse(a, b):
head = None # head of the merged list
while a and b:
if a.data < b.data:
temp = a.next
a.next = head
head = a
a = temp
else:
temp = b.next
b.next = head
head = b
b = temp
while a:
temp = a.next
a.next = head
head = a
a = temp
while b:
temp = b.next
b.next = head
head = b
b = temp
return head
# Utility function to insert a node at the beginning of a linked list
def push(headRef, newData):
newNode = Node(newData)
newNode.next = headRef
headRef = newNode
return headRef
# Utility function to print a linked list
def printList(head):
while head:
print head.data,
head = head.next
print
# Driver program to test above functions
if __name__ == '__main__':
headA = None
headB = None
# Populate list A
headA = push(headA, 15)
headA = push(headA, 10)
headA = push(headA, 5)
# Populate list B
headB = push(headB, 20)
headB = push(headB, 3)
headB = push(headB, 2)
print "List A before merge: ",
printList(headA)
print "List B before merge: ",
printList(headB)
# Merge the two lists in reverse order
merged = mergeListsReverse(headA, headB)
print "Merged list in reverse order: ",
printList(merged)
C#
using System;
// Linked list node
public class Node {
public int data;
public Node next;
}
public class Program {
// Given two non-empty linked lists 'a' and 'b',
// merge them in such a way that the result list
// will be in reverse order
public static Node MergeListsReverse(Node a, Node b) {
Node head = null; // head of the merged list
Node tail = null; // tail of the merged list
while (a != null && b != null) {
if (a.data < b.data) {
Node temp = a.next;
a.next = head;
head = a;
a = temp;
} else {
Node temp = b.next;
b.next = head;
head = b;
b = temp;
}
}
while (a != null) {
Node temp = a.next;
a.next = head;
head = a;
a = temp;
}
while (b != null) {
Node temp = b.next;
b.next = head;
head = b;
b = temp;
}
return head;
}
// Utility function to insert a node at the beginning of a linked list
public static void Push(ref Node headRef, int newData) {
Node newNode = new Node();
newNode.data = newData;
newNode.next = headRef;
headRef = newNode;
}
// Utility function to print a linked list
public static void PrintList(Node head) {
while (head != null) {
Console.Write(head.data + " ");
head = head.next;
}
Console.WriteLine();
}
// Driver program to test above functions
public static void Main() {
Node headA = null;
Node headB = null;
// Populate list A
Push(ref headA, 15);
Push(ref headA, 10);
Push(ref headA, 5);
// Populate list B
Push(ref headB, 20);
Push(ref headB, 3);
Push(ref headB, 2);
Console.Write("List A before merge: ");
PrintList(headA);
Console.Write("List B before merge: ");
PrintList(headB);
// Merge the two lists in reverse order
Node merged = MergeListsReverse(headA, headB);
Console.Write("Merged list in reverse order: ");
PrintList(merged);
}
}
JavaScript
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
/* Given two non-empty linked lists 'a' and 'b',
merge them in such a way that the result list
will be in reverse order */
function mergeListsReverse(a, b) {
let head = null; // head of the merged list
let tail = null; // tail of the merged list
while (a !== null && b !== null) {
if (a.data < b.data) {
let temp = a.next;
a.next = head;
head = a;
a = temp;
} else {
let temp = b.next;
b.next = head;
head = b;
b = temp;
}
}
while (a !== null) {
let temp = a.next;
a.next = head;
head = a;
a = temp;
}
while (b !== null) {
let temp = b.next;
b.next = head;
head = b;
b = temp;
}
return head;
}
/* Utility function to insert a node at the beginning of a linked list */
function push(headRef, newData) {
let newNode = new Node(newData);
newNode.next = headRef;
headRef = newNode;
}
/* Utility function to print a linked list */
function printList(head) {
let result = [];
while (head !== null) {
result.push(head.data);
head = head.next;
}
console.log(result.join(' '));
}
/* Driver program to test above functions */
let headA = null;
let headB = null;
// Populate list A
headA = new Node(5);
headA.next = new Node(10);
headA.next.next = new Node(15);
// Populate list B
headB = new Node(2);
headB.next = new Node(3);
headB.next.next = new Node(20);
console.log("List A before merge: ");
printList(headA);
console.log("List B before merge: ");
printList(headB);
// Merge the two lists in reverse order
let merged = mergeListsReverse(headA, headB);
console.log("Merged list in reverse order: ");
printList(merged);
OutputList A before merge: 5 10 15
List B before merge: 2 3 20
Merged list in reverse order: 20 15 10 5 3 2
Time Complexity: The time complexity of the mergeListsReverse() function is O(m+n), where m and n are the lengths of the input linked lists 'a' and 'b', respectively. This is because each node in both lists is visited exactly once, and constant time operations are performed on each node.
Auxiliary Space: The space complexity of the mergeListsReverse() function is O(1), which is constant space, as only a few temporary variables are used to store the links between the nodes. The space required does not depend on the length of the input lists. However, if we consider the space required to store the linked lists themselves, then the space complexity is O(m+n), where m and n are the lengths of the input linked lists. This is because we are creating a new linked list that has all the elements of both input lists.
This solution traverses both lists only once, doesn't require reverse and works in-place.
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