Subsets with sum divisible by m
Last Updated :
11 Jul, 2025
Given an array of size n and an integer m, the task is to find the number of non-empty subsequences such that the sum of the subsequence is divisible by m.
Note:
- The sum of all array elements in small, i.e., it is within integer range.
- m > 0.
Examples:
Input : arr[] = [1, 2, 3, 4], m = 2
Output : 7
Explanation: The subsequences are [1, 3], [1, 3, 4], [1, 2, 3], [1, 2, 3, 4], [2], [2, 4], and [4].
Input : arr[] = [1, 2, 3], m = 3
Output : 3
Explanation: The subsequences are [1, 2], [1, 2, 3], [3].
[Naive Approach] Using Recursion - O(2^n) time and O(n) space
The idea is to recursively generate all the possible subsets. For every subset, compute its sum, and if the sum is multiple of m, increment result by 1. Finally, decrement the result value by 1 as empty subset is also counted in this approach.
Recurrence relation:
- subCount(i, sum, m, arr) = subCount(i+1, sum+arr[i], m, arr) + subCount(i+1, sum, m, arr).
Base Case:
- For i == n, subCount(i, sum, m, arr) = 1 if sum % m == 0, 0 otherwise.
C++
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
int subCountRecur(int i, int sum, int m, vector<int> &arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.size()) {
return (sum % m == 0)?1:0;
}
// Include current element in subset
int take = subCountRecur(i+1, sum+arr[i], m, arr);
// Exclude current element
int noTake = subCountRecur(i+1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
Java
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class GfG {
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m, int[] arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.length) {
return (sum % m == 0) ? 1 : 0;
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
Python
# Python program to find Number of
# subsets with sum divisible by m
# Recursive function which finds the number of subsequences
# starting from index i and current sum.
def subCountRecur(i, sum, m, arr):
# Base case: End of array
# Check if sum is divisible by m
if i == len(arr):
return 1 if sum % m == 0 else 0
# Include current element in subset
take = subCountRecur(i + 1, sum + arr[i], m, arr)
# Exclude current element
noTake = subCountRecur(i + 1, sum, m, arr)
return take + noTake
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
# Decrement 1 from answer as empty
# subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
C#
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m, int[] arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.Length) {
return (sum % m == 0) ? 1 : 0;
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
JavaScript
// JavaScript program to find Number of
// subsets with sum divisible by m
// Recursive function which finds the number of subsequences
// starting from index i and current sum.
function subCountRecur(i, sum, m, arr) {
// Base case: End of array
// Check if sum is divisible by m
if (i === arr.length) {
return (sum % m === 0) ? 1 : 0;
}
// Include current element in subset
let take = subCountRecur(i + 1, sum + arr[i], m, arr);
// Exclude current element
let noTake = subCountRecur(i + 1, sum, m, arr);
return take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr) - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
[Better Approach - 1] Using Top-Down DP (Memoization) – O(sum*n) time and O(sum*n) space
Optimal Substructure: Number of subsequences with sum divisible by m starting at index i and sum depends on the subproblems subCount(i+1, sum+arr[i], m) and subCount(i+1, sum, m). By solving these subproblems, we can determine the result for the current state.
Overlapping Subproblems: Recursive calls often compute the same (i, sum) states multiple times. To avoid recomputation, we store results in a 2D memo table.
- Since recursion changes with
i
and sum
, create a 2D memo table of size n * (sum + 1). memo[i][j]
stores the number of subsequences starting from index i
with current sum j
.- Before computing a state, check if it is already stored in
memo
. If yes, return it. - Subtract 1 from the final result to exclude the empty subsequence.
C++
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
int subCountRecur(int i, int sum, int m, vector<int> &arr,
vector<vector<int>> &memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.size()) {
return (sum % m == 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i][sum] != -1) {
return memo[i][sum];
}
// Include current element in subset
int take = subCountRecur(i+1, sum+arr[i], m, arr, memo);
// Exclude current element
int noTake = subCountRecur(i+1, sum, m, arr, memo);
// Store and return the result
return memo[i][sum] = take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
int n = arr.size();
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// Initialize memoization table with -1
vector<vector<int>> memo(arr.size(), vector<int>(totalSum + 1, -1));
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
Java
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class GfG {
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m,
int[] arr, int[][] memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.length) {
return (sum % m == 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i][sum] != -1) {
return memo[i][sum];
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr, memo);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr, memo);
// Store and return the result
return memo[i][sum] = take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.length;
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// Initialize memoization table with -1
int[][] memo = new int[n][totalSum + 1];
for (int i = 0; i < n; i++) {
Arrays.fill(memo[i], -1);
}
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
Python
# Python program to find Number of
# subsets with sum divisible by m
# Memoized function which finds the number of subsequences
# starting from index i and current sum.
def subCountRecur(i, sum, m, arr, memo):
# Base case: End of array
# Check if sum is divisible by m
if i == len(arr):
return 1 if sum % m == 0 else 0
# If this state has already been computed,
# return the stored result
if memo[i][sum] != -1:
return memo[i][sum]
# Include current element in subset
take = subCountRecur(i + 1, sum + arr[i], m, arr, memo)
# Exclude current element
noTake = subCountRecur(i + 1, sum, m, arr, memo)
# Store and return the result
memo[i][sum] = take + noTake
return memo[i][sum]
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
n = len(arr)
# Calculate total sum of array
totalSum = sum(arr)
# Initialize memoization table with -1
memo = [[-1 for _ in range(totalSum + 1)] for _ in range(n)]
# Decrement 1 from answer as empty
# subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
C#
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
static int subCountRecur(int i, int sum, int m,
int[] arr, int[,] memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i == arr.Length) {
return (sum % m == 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i, sum] != -1) {
return memo[i, sum];
}
// Include current element in subset
int take = subCountRecur(i + 1, sum + arr[i], m, arr, memo);
// Exclude current element
int noTake = subCountRecur(i + 1, sum, m, arr, memo);
// Store and return the result
return memo[i, sum] = take + noTake;
}
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.Length;
// Calculate total sum of array
int totalSum = 0;
foreach (int num in arr) {
totalSum += num;
}
// Initialize memoization table with -1
int[,] memo = new int[n, totalSum + 1];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= totalSum; j++) {
memo[i, j] = -1;
}
}
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
JavaScript
// JavaScript program to find Number of
// subsets with sum divisible by m
// Memoized function which finds the number of subsequences
// starting from index i and current sum.
function subCountRecur(i, sum, m, arr, memo) {
// Base case: End of array
// Check if sum is divisible by m
if (i === arr.length) {
return (sum % m === 0) ? 1 : 0;
}
// If this state has already been computed,
// return the stored result
if (memo[i][sum] !== -1) {
return memo[i][sum];
}
// Include current element in subset
let take = subCountRecur(i + 1, sum + arr[i], m, arr, memo);
// Exclude current element
let noTake = subCountRecur(i + 1, sum, m, arr, memo);
// Store and return the result
memo[i][sum] = take + noTake;
return memo[i][sum];
}
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
let n = arr.length;
// Calculate total sum of array
let totalSum = arr.reduce((a, b) => a + b, 0);
// Initialize memoization table with -1
let memo = new Array(n).fill(0).map(() => new Array(totalSum + 1).fill(-1));
// Decrement 1 from answer as empty
// subsequence is also counted.
return subCountRecur(0, 0, m, arr, memo) - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
[Better Approach - 2] Using Bottom-Up DP (Tabulation) – O(sum*n) time and O(sum*n) space
The idea is to fill the DP table based on future values. For each index i
and current sum j
, we either include arr[i]
or exclude it to compute the number of subsequences whose sum is divisible by m
. The table is filled in an iterative manner from i = n-1
down to 0
, and for each sum from 0
to total sum
.
The dynamic programming relation is as follows:
- dp[i][j] = dp[i+1][j] + dp[i+1][j + arr[i]]
At the base case i = n
, we set dp[n][j] = 1
if j % m == 0
, else 0.
Finally, subtract 1 from dp[0][0]
to exclude the empty subsequence.
C++
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
int n = arr.size();
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
vector<vector<int>> dp(n + 1, vector<int>(totalSum + 1, 0));
// Precompute the sums which are divisible
// by m.
for (int j=0; j<=totalSum; j++) {
if (j%m == 0) dp[n][j] = 1;
}
// Current index
for (int i=n-1; i>=0; i--) {
// Current sum
for (int j=0; j<=totalSum; j++) {
dp[i][j] = dp[i+1][j] + dp[i+1][j+arr[i]];
}
}
return dp[0][0] - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
Java
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class Main {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.length;
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
int[][] dp = new int[n + 1][totalSum + 1];
// Precompute the sums which are divisible
// by m.
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[n][j] = 1;
}
// Current index
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Exclude arr[i]
dp[i][j] = dp[i + 1][j];
// Include arr[i]
if (j + arr[i] <= totalSum) {
dp[i][j] += dp[i + 1][j + arr[i]];
}
}
}
return dp[0][0] - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
Python
# Python program to find Number of
# subsets with sum divisible by m
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
n = len(arr)
# Calculate total sum of array
totalSum = 0
for num in arr:
totalSum += num
dp = [[0] * (totalSum + 1) for _ in range(n + 1)]
# Precompute the sums which are divisible
# by m.
for j in range(totalSum + 1):
if j % m == 0:
dp[n][j] = 1
# Current index
for i in range(n - 1, -1, -1):
# Current sum
for j in range(totalSum + 1):
# Exclude arr[i]
dp[i][j] = dp[i + 1][j]
# Include arr[i]
if j + arr[i] <= totalSum:
dp[i][j] += dp[i + 1][j + arr[i]]
return dp[0][0] - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
C#
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.Length;
// Calculate total sum of array
int totalSum = 0;
foreach (int num in arr) {
totalSum += num;
}
int[,] dp = new int[n + 1, totalSum + 1];
// Precompute the sums which are divisible
// by m.
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[n, j] = 1;
}
// Current index
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Exclude arr[i]
dp[i, j] = dp[i + 1, j];
// Include arr[i]
if (j + arr[i] <= totalSum) {
dp[i, j] += dp[i + 1, j + arr[i]];
}
}
}
return dp[0, 0] - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
JavaScript
// JavaScript program to find Number of
// subsets with sum divisible by m
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
let n = arr.length;
// Calculate total sum of array
let totalSum = 0;
for (let num of arr) {
totalSum += num;
}
let dp = new Array(n + 1).fill(0).map(() => new Array(totalSum + 1).fill(0));
// Precompute the sums which are divisible
// by m.
for (let j = 0; j <= totalSum; j++) {
if (j % m === 0) dp[n][j] = 1;
}
// Current index
for (let i = n - 1; i >= 0; i--) {
// Current sum
for (let j = 0; j <= totalSum; j++) {
// Exclude arr[i]
dp[i][j] = dp[i + 1][j];
// Include arr[i]
if (j + arr[i] <= totalSum) {
dp[i][j] += dp[i + 1][j + arr[i]];
}
}
}
return dp[0][0] - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
[Expected Approach - 1] Using Space Optimized DP – O(sum*n) time and O(sum) space
In previous approach of dynamic programming we have derived the relation between states as given below:
- dp[i][j] = dp[i+1][j] + dp[i+1][j + arr[i]]
If we observe carefully, for calculating current dp[i][j]
state we only need values from the next row dp[i+1][...]
. Hence, we can optimize space by using a single 1D array and updating it in reverse to simulate the row transitions.
C++
// C++ program to find Number of
// subsets with sum divisible by m
#include <bits/stdc++.h>
using namespace std;
// Function which finds Number of
// subsets with sum divisible by m
int subCount(vector<int> &arr, int m) {
int n = arr.size();
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// dp array for tabulation
vector<int> dp(totalSum + 1, 0);
// Base case: sums which are divisible by m
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[j] = 1;
}
// Process each element in the array
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j<=totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
int main() {
vector<int> arr = {1, 2, 3, 4};
int m = 2;
cout << subCount(arr, m);
return 0;
}
Java
// Java program to find Number of
// subsets with sum divisible by m
import java.util.*;
class GfG {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.length;
// Calculate total sum of array
int totalSum = 0;
for (int num : arr) {
totalSum += num;
}
// dp array for tabulation
int[] dp = new int[totalSum + 1];
// Base case: sums which are divisible by m
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[j] = 1;
}
// Process each element in the array
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
System.out.println(subCount(arr, m));
}
}
Python
# Python program to find Number of
# subsets with sum divisible by m
# Function which finds Number of
# subsets with sum divisible by m
def subCount(arr, m):
n = len(arr)
# Calculate total sum of array
totalSum = 0
for num in arr:
totalSum += num
# dp array for tabulation
dp = [0] * (totalSum + 1)
# Base case: sums which are divisible by m
for j in range(totalSum + 1):
if j % m == 0:
dp[j] = 1
# Process each element in the array
for i in range(n - 1, -1, -1):
# Current sum
for j in range(totalSum + 1):
# Include arr[i] if possible
if j + arr[i] <= totalSum:
dp[j] += dp[j + arr[i]]
return dp[0] - 1
if __name__ == "__main__":
arr = [1, 2, 3, 4]
m = 2
print(subCount(arr, m))
C#
// C# program to find Number of
// subsets with sum divisible by m
using System;
class GfG {
// Function which finds Number of
// subsets with sum divisible by m
static int subCount(int[] arr, int m) {
int n = arr.Length;
// Calculate total sum of array
int totalSum = 0;
foreach (int num in arr) {
totalSum += num;
}
// dp array for tabulation
int[] dp = new int[totalSum + 1];
// Base case: sums which are divisible by m
for (int j = 0; j <= totalSum; j++) {
if (j % m == 0) dp[j] = 1;
}
// Process each element in the array
for (int i = n - 1; i >= 0; i--) {
// Current sum
for (int j = 0; j <= totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
static void Main(string[] args) {
int[] arr = {1, 2, 3, 4};
int m = 2;
Console.WriteLine(subCount(arr, m));
}
}
JavaScript
// JavaScript program to find Number of
// subsets with sum divisible by m
// Function which finds Number of
// subsets with sum divisible by m
function subCount(arr, m) {
let n = arr.length;
// Calculate total sum of array
let totalSum = 0;
for (let num of arr) {
totalSum += num;
}
// dp array for tabulation
let dp = new Array(totalSum + 1).fill(0);
// Base case: sums which are divisible by m
for (let j = 0; j <= totalSum; j++) {
if (j % m === 0) dp[j] = 1;
}
// Process each element in the array
for (let i = n - 1; i >= 0; i--) {
// Current sum
for (let j = 0; j <= totalSum; j++) {
// Include arr[i] if possible
if (j + arr[i] <= totalSum) {
dp[j] += dp[j + arr[i]];
}
}
}
return dp[0] - 1;
}
let arr = [1, 2, 3, 4];
let m = 2;
console.log(subCount(arr, m));
[Expected Approach - 2] Further Space Optimization - O(sum*n) time and O(m) space
The idea is to reduce the state space by observing that we only care whether a subsequence sum is divisible by m
, so instead of tracking the exact sum, we can track the remainder of the sum modulo m
. We define dp[i][curr]
as the number of subsequences starting from index i
with a current sum having remainder curr
modulo m
. The recurrence becomes dp[i][curr] = dp[i + 1][(curr + arr[i]) % m] + dp[i + 1][curr]
, representing the choices to include or exclude arr[i]
. This allows us to reduce the DP table size from O(n × sum) to O(n × m), optimizing both time and space.
Refer to Number of subsets with sum divisible by M | Set 2 for detailed explanation and code.
Related Articles:
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