Sort an array according to count of set bits
Last Updated :
10 Mar, 2025
Given an array of integers, sort the array (in descending order) according to count of set bits in binary representation of array elements.
Note: For integers having same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort.
Examples:
Input: arr[] = [5, 2, 3, 9, 4, 6, 7, 15, 32]
Output: 15 7 5 3 9 6 2 4 32
Explanation: The integers in their binary representation are:
15 -1111
7 -0111
5 -0101
3 -0011
9 -1001
6 -0110
2 -0010
4- -0100
32 -10000
Hence the non-increasing sorted order is: {15}, {7}, {5, 3, 9, 6}, {2, 4, 32}.
Input: arr[] = [1, 2, 3, 4, 5, 6]
Output: 3 5 6 1 2 4
Explanation: The integers in their binary representation are:
3 - 0011
5 - 0101
6 - 0110
1 - 0001
2 - 0010
4 - 0100
hence the non-increasing sorted order is {3, 5, 6}, {1, 2, 4}.
[Naive Approach] - Using Insertion Sort - O(n ^ 2) Time and O(n) Space
The idea is to store the set-bit counts of all the integers in the auxiliary array and simultaneously sort both arrays according to the non-increasing order of auxiliary array.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to simultaneously sort both
// arrays using insertion sort
void insertionSort(vector<int> &arr, vector<int> &bitCnt) {
int n = arr.size();
for (int i = 1; i < n; i++) {
int key1 = bitCnt[i];
int key2 = arr[i];
int j = i - 1;
while (j >= 0 && bitCnt[j] < key1) {
bitCnt[j + 1] = bitCnt[j];
arr[j + 1] = arr[j];
j = j - 1;
}
bitCnt[j + 1] = key1;
arr[j + 1] = key2;
}
}
// Function to count set bits in an integer
int countBits(int a) {
int count = 0;
while (a) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
void sortBySetBitCount(vector<int>& arr) {
int n = arr.size();
// Create an array and store
// count of set bits in it.
vector<int> bitCnt(n);
for (int i = 0; i < n; i++)
bitCnt[i] = countBits(arr[i]);
// sort the array
insertionSort(arr, bitCnt);
}
int main() {
vector<int> arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 };
sortBySetBitCount(arr);
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
Java
// Function to simultaneously sort both
// arrays using insertion sort
import java.util.*;
class GfG {
// Function to simultaneously sort both
// arrays using insertion sort
static void insertionSort(int[] arr, int[] bitCnt) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key1 = bitCnt[i];
int key2 = arr[i];
int j = i - 1;
while (j >= 0 && bitCnt[j] < key1) {
bitCnt[j + 1] = bitCnt[j];
arr[j + 1] = arr[j];
j = j - 1;
}
bitCnt[j + 1] = key1;
arr[j + 1] = key2;
}
}
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
int n = arr.length;
// Create an array and store
// count of set bits in it.
int[] bitCnt = new int[n];
for (int i = 0; i < n; i++)
bitCnt[i] = countBits(arr[i]);
// sort the array
insertionSort(arr, bitCnt);
}
public static void main(String[] args) {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
sortBySetBitCount(arr);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Function to simultaneously sort both
# arrays using insertion sort
def insertionSort(arr, bitCnt):
n = len(arr)
for i in range(1, n):
key1 = bitCnt[i]
key2 = arr[i]
j = i - 1
while j >= 0 and bitCnt[j] < key1:
bitCnt[j + 1] = bitCnt[j]
arr[j + 1] = arr[j]
j = j - 1
bitCnt[j + 1] = key1
arr[j + 1] = key2
# Function to count set bits in an integer
def countBits(a):
count = 0
while a:
if a % 2 != 0:
count += 1
a = a // 2
return count
# Function to sort an array according to bit count
def sortBySetBitCount(arr):
n = len(arr)
# Create an array and store
# count of set bits in it.
bitCnt = [0] * n
for i in range(n):
bitCnt[i] = countBits(arr[i])
# sort the array
insertionSort(arr, bitCnt)
if __name__ == "__main__":
arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]
sortBySetBitCount(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
C#
// Function to simultaneously sort both
// arrays using insertion sort
using System;
using System.Collections.Generic;
class GfG {
// Function to simultaneously sort both
// arrays using insertion sort
static void insertionSort(int[] arr, int[] bitCnt) {
int n = arr.Length;
for (int i = 1; i < n; i++) {
int key1 = bitCnt[i];
int key2 = arr[i];
int j = i - 1;
while (j >= 0 && bitCnt[j] < key1) {
bitCnt[j + 1] = bitCnt[j];
arr[j + 1] = arr[j];
j = j - 1;
}
bitCnt[j + 1] = key1;
arr[j + 1] = key2;
}
}
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
int n = arr.Length;
// Create an array and store
// count of set bits in it.
int[] bitCnt = new int[n];
for (int i = 0; i < n; i++)
bitCnt[i] = countBits(arr[i]);
// sort the array
insertionSort(arr, bitCnt);
}
static void Main() {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
sortBySetBitCount(arr);
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
JavaScript
// Function to simultaneously sort both
// arrays using insertion sort
function insertionSort(arr, bitCnt) {
let n = arr.length;
for (let i = 1; i < n; i++) {
let key1 = bitCnt[i];
let key2 = arr[i];
let j = i - 1;
while (j >= 0 && bitCnt[j] < key1) {
bitCnt[j + 1] = bitCnt[j];
arr[j + 1] = arr[j];
j = j - 1;
}
bitCnt[j + 1] = key1;
arr[j + 1] = key2;
}
}
// Function to count set bits in an integer
function countBits(a) {
let count = 0;
while (a) {
if (a % 2 !== 0)
count += 1;
a = Math.floor(a / 2);
}
return count;
}
// Function to sort an array according to bit count
function sortBySetBitCount(arr) {
let n = arr.length;
// Create an array and store
// count of set bits in it.
let bitCnt = new Array(n).fill(0);
for (let i = 0; i < n; i++)
bitCnt[i] = countBits(arr[i]);
// sort the array
insertionSort(arr, bitCnt);
}
let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32];
sortBySetBitCount(arr);
for (let i = 0; i < arr.length; i++)
process.stdout.write(arr[i] + " ");
Output15 7 5 3 9 6 2 4 32
[Better Approach] - Using Inbuilt Sort Function - O(n * log n) Time and O(1) Space
The idea is to use the inbuilt sort function and custom comparator to sort the array according to set-bit count.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to count set bits in an integer
int countBits(int a) {
int count = 0;
while (a) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// custom comparator of std::sort
bool cmp(int a, int b) {
int count1 = countBits(a);
int count2 = countBits(b);
// this takes care of the stability of sorting algorithm too
if (count1 <= count2)
return false;
return true;
}
// Function to sort an array according to bit count
void sortBySetBitCount(vector<int>& arr) {
stable_sort(arr.begin(), arr.end(), cmp);
}
int main() {
vector<int> arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 };
sortBySetBitCount(arr);
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
Java
// Function to count set bits in an integer
import java.util.*;
class GfG {
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
// using stable sort
static int[] sortBySetBitCount(int[] arr) {
int n = arr.length;
Integer[] arrObj = new Integer[n];
for (int i = 0; i < n; i++) {
arrObj[i] = arr[i];
}
Arrays.sort(arrObj, new Comparator<Integer>() {
public int compare(Integer a, Integer b) {
int c1 = countBits(a);
int c2 = countBits(b);
if(c1 == c2)
return 0;
return c1 < c2 ? 1 : -1;
}
});
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = arrObj[i];
}
return ans;
}
public static void main(String[] args) {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
int[] ans = sortBySetBitCount(arr);
for (int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
}
}
Python
# Function to count set bits in an integer
def countBits(a):
count = 0
while a:
if a % 2 != 0:
count += 1
a //= 2
return count
# Function to sort an array according to bit count
# using stable sort
def sortBySetBitCount(arr):
arr.sort(key=lambda x: -countBits(x))
return arr
if __name__ == "__main__":
arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]
sortBySetBitCount(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
C#
// Function to count set bits in an integer
using System;
using System.Linq;
class GfG {
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
// using stable sort
static int[] sortBySetBitCount(int[] arr) {
int n = arr.Length;
var sorted = arr.Select((x, i) => new { Value = x, Index = i })
.OrderByDescending(item => countBits(item.Value))
.ThenBy(item => item.Index)
.Select(item => item.Value)
.ToArray();
return sorted;
}
static void Main() {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
int[] ans = sortBySetBitCount(arr);
for (int i = 0; i < ans.Length; i++)
Console.Write(ans[i] + " ");
}
}
JavaScript
// Function to count set bits in an integer
function countBits(a) {
let count = 0;
while (a) {
if (a % 2 !== 0)
count += 1;
a = Math.floor(a / 2);
}
return count;
}
// Function to sort an array according to bit count
// using stable sort
function sortBySetBitCount(arr) {
arr.sort((a, b) => {
let c1 = countBits(a);
let c2 = countBits(b);
if (c1 === c2)
return 0;
return c1 < c2 ? 1 : -1;
});
return arr;
}
let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32];
sortBySetBitCount(arr);
for (let i = 0; i < arr.length; i++)
process.stdout.write(arr[i] + " ");
Output15 7 5 3 9 6 2 4 32
[Expected Approach] - Using Counting Sort - O(n) Time and O(n) Space
The idea is to use counting sort to arrange the elements in descending order of count of set-bits. For any integer, assuming the minimum and maximum set-bits can be 1 and 31 respectively, create an array count[][] of size 32, where each element count[i] stores the elements of given array with count of their set bits equal to i. After inserting all the elements, traverse count[][] in reverse order, and store the elements at each index in the given array.

C++
#include <bits/stdc++.h>
using namespace std;
// Function to count set bits in an integer
int countBits(int a) {
int count = 0;
while (a) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
void sortBySetBitCount(vector<int>& arr) {
int n = arr.size();
// Create a 2d array to map array elements
// to their corresponding set bit count
vector<vector<int>> count(32);
// insert elements in the 2d array
for (int i=0; i<n; i++) {
int setBit = countBits(arr[i]);
count[setBit].push_back(arr[i]);
}
// to track the index of sorted array
int j = 0;
// Traverse through all bit counts
for (int i = 31; i >= 0; i--) {
// Traverse through all elements
// of current bit count
for(int k = 0; k < count[i].size(); k++) {
arr[j++] = count[i][k];
}
}
}
int main() {
vector<int> arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 };
sortBySetBitCount(arr);
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
Java
// Function to count set bits in an integer
import java.util.*;
class GfG {
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
int n = arr.length;
// Create a 2d array to map array elements
// to their corresponding set bit count
ArrayList<ArrayList<Integer>> count = new ArrayList<>();
for (int i = 0; i < 32; i++) {
count.add(new ArrayList<>());
}
// insert elements in the 2d array
for (int i = 0; i < n; i++) {
int setBit = countBits(arr[i]);
count.get(setBit).add(arr[i]);
}
// to track the index of sorted array
int j = 0;
// Traverse through all bit counts
for (int i = 31; i >= 0; i--) {
// Traverse through all elements
// of current bit count
ArrayList<Integer> curr = count.get(i);
for (int k = 0; k < curr.size(); k++) {
arr[j++] = curr.get(k);
}
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
sortBySetBitCount(arr);
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
Python
# Function to count set bits in an integer
def countBits(a):
count = 0
while a:
if a % 2 != 0:
count += 1
a = a // 2
return count
# Function to sort an array according to bit count
def sortBySetBitCount(arr):
n = len(arr)
# Create a 2d array to map array elements
# to their corresponding set bit count
count = [[] for _ in range(32)]
# insert elements in the 2d array
for i in range(n):
setBit = countBits(arr[i])
count[setBit].append(arr[i])
# to track the index of sorted array
j = 0
# Traverse through all bit counts
for i in range(31, -1, -1):
# Traverse through all elements
# of current bit count
for k in range(len(count[i])):
arr[j] = count[i][k]
j += 1
# Driver Code
if __name__ == "__main__":
arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]
sortBySetBitCount(arr)
for i in range(len(arr)):
print(arr[i], end=" ")
C#
// Function to count set bits in an integer
using System;
using System.Collections.Generic;
class GfG {
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
static void sortBySetBitCount(int[] arr) {
int n = arr.Length;
// Create a 2d array to map array elements
// to their corresponding set bit count
List<List<int>> count = new List<List<int>>();
for (int i = 0; i < 32; i++) {
count.Add(new List<int>());
}
// insert elements in the 2d array
for (int i = 0; i < n; i++) {
int setBit = countBits(arr[i]);
count[setBit].Add(arr[i]);
}
// to track the index of sorted array
int j = 0;
// Traverse through all bit counts
for (int i = 31; i >= 0; i--) {
// Traverse through all elements
// of current bit count
for (int k = 0; k < count[i].Count; k++) {
arr[j++] = count[i][k];
}
}
}
static void Main() {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
sortBySetBitCount(arr);
for (int i = 0; i < arr.Length; i++)
Console.Write(arr[i] + " ");
}
}
JavaScript
// Function to count set bits in an integer
function countBits(a) {
let count = 0;
while (a) {
if (a % 2 !== 0)
count += 1;
a = Math.floor(a / 2);
}
return count;
}
// Function to sort an array according to bit count
function sortBySetBitCount(arr) {
let n = arr.length;
// Create a 2d array to map array elements
// to their corresponding set bit count
let count = [];
for (let i = 0; i < 32; i++) {
count.push([]);
}
// insert elements in the 2d array
for (let i = 0; i < n; i++) {
let setBit = countBits(arr[i]);
count[setBit].push(arr[i]);
}
// to track the index of sorted array
let j = 0;
// Traverse through all bit counts
for (let i = 31; i >= 0; i--) {
// Traverse through all elements
// of current bit count
for (let k = 0; k < count[i].length; k++) {
arr[j++] = count[i][k];
}
}
}
let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32];
sortBySetBitCount(arr);
for (let i = 0; i < arr.length; i++)
process.stdout.write(arr[i] + " ");
Output15 7 5 3 9 6 2 4 32
[Alternate Approach] - Using Multimap - O(n * log n) Time and O(n) Space
The idea is store the elements corresponding to negative (to ensure elements are sorted in descending order) of their count of set-bits in a multimap.
- Create a MultiMap whose key values will be the negative of the number of set-bits of the element.
- Traverse the array and do following for each element:
- Count the number set-bits of this element. Let it be 'setBitCount'
- count.insert({(-1) * setBitCount, element})
- Traverse 'count' and print the second elements.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to count set bits in an integer
int countBits(int a) {
int count = 0;
while (a) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
void sortBySetBitCount(vector<int>& arr) {
int n = arr.size();
// to map the elements to their
// corresponding set bit count
multimap<int, int> count;
// Iterate over all values and
// insert into multimap
for( int i = 0 ; i < n ; i++ ) {
count.insert({(-1) * countBits(arr[i]), arr[i]});
}
int j = 0;
// Iterate over all values and
// insert into the array
for(auto i: count) {
arr[j++] = i.second;
}
}
int main() {
vector<int> arr = { 5, 2, 3, 9, 4, 6, 7, 15, 32 };
sortBySetBitCount(arr);
for (int i = 0; i < arr.size(); i++)
cout << arr[i] << " ";
return 0;
}
Java
// Function to count set bits in an integer
import java.util.*;
class Pair {
int val;
int idx;
Pair(int val, int idx) {
this.val = val;
this.idx = idx;
}
}
class GfG {
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
static int[] sortBySetBitCount(int[] arr) {
int n = arr.length;
Pair[] pairs = new Pair[n];
for (int i = 0; i < n; i++) {
pairs[i] = new Pair(arr[i], i);
}
Arrays.sort(pairs, new Comparator<Pair>() {
public int compare(Pair p1, Pair p2) {
int c1 = countBits(p1.val);
int c2 = countBits(p2.val);
if (c1 == c2)
return Integer.compare(p1.idx, p2.idx);
return Integer.compare(c2, c1);
}
});
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
ans[i] = pairs[i].val;
}
return ans;
}
public static void main(String[] args) {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
int[] ans = sortBySetBitCount(arr);
for (int i = 0; i < ans.length; i++)
System.out.print(ans[i] + " ");
}
}
Python
# Function to count set bits in an integer
def countBits(a):
count = 0
while a:
if a % 2 != 0:
count += 1
a //= 2
return count
# Function to sort an array according to bit count
def sortBySetBitCount(arr):
n = len(arr)
# Create an array of (index, value) pairs
paired = list(enumerate(arr))
# Stable sort: first by descending countBits, then by original index
paired.sort(key=lambda x: (-countBits(x[1]), x[0]))
ans = [x[1] for x in paired]
return ans
if __name__ == "__main__":
arr = [5, 2, 3, 9, 4, 6, 7, 15, 32]
ans = sortBySetBitCount(arr)
for i in range(len(ans)):
print(ans[i], end=" ")
C#
// Function to count set bits in an integer
using System;
using System.Linq;
using System.Collections.Generic;
class GfG {
// Function to count set bits in an integer
static int countBits(int a) {
int count = 0;
while (a != 0) {
if (a % 2 != 0)
count += 1;
a = a / 2;
}
return count;
}
// Function to sort an array according to bit count
static int[] sortBySetBitCount(int[] arr) {
int n = arr.Length;
var paired = arr.Select((val, idx) => new { val, idx });
var sorted = paired.OrderByDescending(x => countBits(x.val))
.ThenBy(x => x.idx)
.Select(x => x.val)
.ToArray();
return sorted;
}
static void Main() {
int[] arr = {5, 2, 3, 9, 4, 6, 7, 15, 32};
int[] ans = sortBySetBitCount(arr);
for (int i = 0; i < ans.Length; i++)
Console.Write(ans[i] + " ");
}
}
JavaScript
// Function to count set bits in an integer
function countBits(a) {
let count = 0;
while (a) {
if (a % 2 !== 0)
count += 1;
a = Math.floor(a / 2);
}
return count;
}
// Function to sort an array according to bit count
function sortBySetBitCount(arr) {
let n = arr.length;
// Create an array of pairs [index, value]
let paired = arr.map((val, idx) => [idx, val]);
// Stable sort: first by descending countBits, then by original index
paired.sort((a, b) => {
let c1 = countBits(a[1]);
let c2 = countBits(b[1]);
if (c1 === c2)
return a[0] - b[0];
return c2 - c1;
});
let ans = paired.map(x => x[1]);
return ans;
}
let arr = [5, 2, 3, 9, 4, 6, 7, 15, 32];
let ans = sortBySetBitCount(arr);
for (let i = 0; i < ans.length; i++)
process.stdout.write(ans[i] + " ");
Output15 7 5 3 9 6 2 4 32
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