Find distinct elements common to all rows of a matrix
Last Updated :
15 Apr, 2023
Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order.
Examples:
Input : mat[][] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} }
Output : 2 3
Input : mat[][] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14} }
Output : 1 3 14
Method 1: Using three nested loops. Check if an element of 1st row is present in all the subsequent rows. Time Complexity of O(n3). Extra space could be required to handle the duplicate elements.
Method 2: Sort all the rows of the matrix individually in increasing order. Then apply a modified approach to the problem of finding common elements in 3 sorted arrays. Below an implementation for the same is given.
C++
// C++ implementation to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
// function to individually sort
// each row in increasing order
void sortRows(int mat[][MAX], int n)
{
for (int i=0; i<n; i++)
sort(mat[i], mat[i] + n);
}
// function to find all the common elements
void findAndPrintCommonElements(int mat[][MAX], int n)
{
// sort rows individually
sortRows(mat, n);
// current column index of each row is stored
// from where the element is being searched in
// that row
int curr_index[n];
memset(curr_index, 0, sizeof(curr_index));
int f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
// value present at the current column index
// of 1st row
int value = mat[0][curr_index[0]];
bool present = true;
// 'value' is being searched in all the
// subsequent rows
for (int i=1; i<n; i++)
{
// iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
// if the element was not present at the column
// before to the 'curr_index' of the row
if (mat[i][curr_index[i]-1] != value)
present = false;
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
cout << value << " ";
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
// Driver program to test above
int main()
{
int mat[][MAX] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
return 0;
}
Java
// JAVA Code to find distinct elements
// common to all rows of a matrix
import java.util.*;
class GFG {
// function to individually sort
// each row in increasing order
public static void sortRows(int mat[][], int n)
{
for (int i=0; i<n; i++)
Arrays.sort(mat[i]);
}
// function to find all the common elements
public static void findAndPrintCommonElements(int mat[][],
int n)
{
// sort rows individually
sortRows(mat, n);
// current column index of each row is stored
// from where the element is being searched in
// that row
int curr_index[] = new int[n];
int f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
// value present at the current column index
// of 1st row
int value = mat[0][curr_index[0]];
boolean present = true;
// 'value' is being searched in all the
// subsequent rows
for (int i=1; i<n; i++)
{
// iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
// if the element was not present at the
// column before to the 'curr_index' of the
// row
if (mat[i][curr_index[i]-1] != value)
present = false;
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
System.out.print(value+" ");
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int mat[][] = { {12, 1, 14, 3, 16},
{14, 2, 1, 3, 35},
{14, 1, 14, 3, 11},
{14, 25, 3, 2, 1},
{1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Python3 implementation to find distinct
# elements common to all rows of a matrix
MAX = 100
# function to individually sort
# each row in increasing order
def sortRows(mat, n):
for i in range(0, n):
mat[i].sort();
# function to find all the common elements
def findAndPrintCommonElements(mat, n):
# sort rows individually
sortRows(mat, n)
# current column index of each row is
# stored from where the element is being
# searched in that row
curr_index = [0] * n
for i in range (0, n):
curr_index[i] = 0
f = 0
while(curr_index[0] < n):
# value present at the current
# column index of 1st row
value = mat[0][curr_index[0]]
present = True
# 'value' is being searched in
# all the subsequent rows
for i in range (1, n):
# iterate through all the elements
# of the row from its current column
# index till an element greater than
# the 'value' is found or the end of
# the row is encountered
while (curr_index[i] < n and
mat[i][curr_index[i]] <= value):
curr_index[i] = curr_index[i] + 1
# if the element was not present at
# the column before to the 'curr_index'
# of the row
if (mat[i][curr_index[i] - 1] != value):
present = False
# if all elements of the row have
# been traversed)
if (curr_index[i] == n):
f = 1
break
# if the 'value' is common to all the rows
if (present):
print(value, end = " ")
# if any row have been completely traversed
# then no more common elements can be found
if (f == 1):
break
curr_index[0] = curr_index[0] + 1
# Driver Code
mat = [[12, 1, 14, 3, 16],
[14, 2, 1, 3, 35],
[14, 1, 14, 3, 11],
[14, 25, 3, 2, 1],
[1, 18, 3, 21, 14]]
n = 5
findAndPrintCommonElements(mat, n)
# This code is contributed by iAyushRaj
C#
// C# Code to find distinct elements
// common to all rows of a matrix
using System;
class GFG
{
// function to individually sort
// each row in increasing order
public static void sortRows(int[][] mat, int n)
{
for (int i = 0; i < n; i++)
{
Array.Sort(mat[i]);
}
}
// function to find all the common elements
public static void findAndPrintCommonElements(int[][] mat,
int n)
{
// sort rows individually
sortRows(mat, n);
// current column index of each row is stored
// from where the element is being searched in
// that row
int[] curr_index = new int[n];
int f = 0;
for (; curr_index[0] < n; curr_index[0]++)
{
// value present at the current column index
// of 1st row
int value = mat[0][curr_index[0]];
bool present = true;
// 'value' is being searched in all the
// subsequent rows
for (int i = 1; i < n; i++)
{
// iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
{
curr_index[i]++;
}
// if the element was not present at the column
// before to the 'curr_index' of the row
if (mat[i][curr_index[i] - 1] != value)
{
present = false;
}
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
{
Console.Write(value + " ");
}
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
{
break;
}
}
}
// Driver Code
public static void Main(string[] args)
{
int[][] mat = new int[][]
{
new int[] {12, 1, 14, 3, 16},
new int[] {14, 2, 1, 3, 35},
new int[] {14, 1, 14, 3, 11},
new int[] {14, 25, 3, 2, 1},
new int[] {1, 18, 3, 21, 14}
};
int n = 5;
findAndPrintCommonElements(mat, n);
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// JavaScript Code to find distinct elements
// common to all rows of a matrix
// function to individually sort
// each row in increasing order
function sortRows(mat,n)
{
for (let i=0; i<n; i++)
mat[i].sort(function(a,b){return a-b;});
}
// function to find all the common elements
function findAndPrintCommonElements(mat,n)
{
// sort rows individually
sortRows(mat, n);
// current column index of each row is stored
// from where the element is being searched in
// that row
let curr_index = new Array(n);
for(let i=0;i<n;i++)
{
curr_index[i]=0;
}
let f = 0;
for (; curr_index[0]<n; curr_index[0]++)
{
// value present at the current column index
// of 1st row
let value = mat[0][curr_index[0]];
let present = true;
// 'value' is being searched in all the
// subsequent rows
for (let i=1; i<n; i++)
{
// iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index[i] < n &&
mat[i][curr_index[i]] <= value)
curr_index[i]++;
// if the element was not present at the
// column before to the 'curr_index' of the
// row
if (mat[i][curr_index[i]-1] != value)
present = false;
// if all elements of the row have
// been traversed
if (curr_index[i] == n)
{
f = 1;
break;
}
}
// if the 'value' is common to all the rows
if (present)
document.write(value+" ");
// if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
/* Driver program to test above function */
let mat = [[12, 1, 14, 3, 16],
[14, 2, 1, 3, 35],
[14, 1, 14, 3, 11],
[14, 25, 3, 2, 1],
[1, 18, 3, 21, 14]]
let n = 5;
findAndPrintCommonElements(mat, n);
// This code is contributed by patel2127
</script>
Time Complexity: O(n2log n), each row of size n requires O(nlogn) for sorting and there are total n rows.
Auxiliary Space: O(n) to store current column indexes for each row.
Method 3: It uses the concept of hashing. The following steps are:
- Map the element of the 1st row in a hash table. Let it be hash.
- Fow row = 2 to n
- Map each element of the current row into a temporary hash table. Let it be temp.
- Iterate through the elements of hash and check that the elements in hash are present in temp. If not present then delete those elements from hash.
- When all the rows are being processed in this manner, then the elements left in hash are the required common elements.
C++
// C++ program to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
// function to individually sort
// each row in increasing order
void findAndPrintCommonElements(int mat[][MAX], int n){
unordered_set<int> us;
// map elements of first row
// into 'us'
for (int i=0; i<n; i++)
us.insert(mat[0][i]);
for (int i=1; i<n; i++){
unordered_set<int> temp;
unordered_set<int> common;
// mapping elements of current row
// in 'temp'
for (int j=0; j<n; j++)
temp.insert(mat[i][j]);
// find common elements between 'us' and 'temp'
for (auto itr : us)
if (temp.find(itr) != temp.end()) common.insert(itr);
// update 'us' with common elements
us = common;
// if size of 'us' becomes 0,
// then there are no common elements
if (us.size() == 0)
break;
}
// print the common elements
for (auto itr : us)
cout << itr << " ";
}
// Driver program to test above
int main(){
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
return 0;
}
Java
// Java program to find distinct elements
// common to all rows of a matrix
import java.util.*;
class GFG{
static int MAX = 100;
// function to individually sort
// each row in increasing order
@SuppressWarnings("unchecked")
static void findAndPrintCommonElements(int mat[][], int n)
{
HashSet<Integer> us = new HashSet<Integer>();
// map elements of first row
// into 'us'
for (int i = 0; i < n; i++)
us.add(mat[0][i]);
for (int i = 1; i < n; i++)
{
HashSet<Integer> temp = new HashSet<Integer>();
// mapping elements of current row
// in 'temp'
for (int j = 0; j < n; j++)
temp.add(mat[i][j]);
HashSet<Integer> itr=(HashSet<Integer>) us.clone();
// iterate through all the elements
// of 'us'
for (int x :itr)
// if an element of 'us' is not present
// into 'temp', then erase that element
// from 'us'
if (!temp.contains(x))
us.remove(x);
// if size of 'us' becomes 0,
// then there are no common elements
if (us.size() == 0)
break;
}
// print the common elements
HashSet<Integer> itr1=(HashSet<Integer>) us.clone();
for (int x :itr1)
System.out.print(x+ " ");
}
// Driver program to test above
public static void main(String[] args)
{
int mat[][] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
}
}
// This code is contributed by shikhasingrajput
Python3
# Python3 program to find distinct elements
# common to all rows of a matrix
MAX = 100
# function to individually sort
# each row in increasing order
def findAndPrintCommonElements(mat, n):
us = dict()
# map elements of first row
# into 'us'
for i in range(n):
us[(mat[0][i])] = 1
for i in range(1, n):
temp = dict()
# mapping elements of current row
# in 'temp'
for j in range(n):
temp[(mat[i][j])] = 1
# iterate through all the elements
# of 'us'
for itr in list(us):
# if an element of 'us' is not present
# into 'temp', then erase that element
# from 'us'
if itr not in temp:
del us[itr]
# if size of 'us' becomes 0,
# then there are no common elements
if (len(us) == 0):
break
# print common elements
for itr in list(us)[::-1]:
print(itr, end = " ")
# Driver Code
mat = [[2, 1, 4, 3],
[1, 2, 3, 2],
[3, 6, 2, 3],
[5, 2, 5, 3]]
n = 4
findAndPrintCommonElements(mat, n)
# This code is contributed by Mohit Kumar
C#
// C# program to find distinct elements
// common to all rows of a matrix
using System;
using System.Collections.Generic;
public class GFG{
static int MAX = 100;
// function to individually sort
// each row in increasing order
static void findAndPrintCommonElements(int [,]mat, int n)
{
HashSet<int> us = new HashSet<int>();
// map elements of first row
// into 'us'
for (int i = 0; i < n; i++)
us.Add(mat[0, i]);
for (int i = 1; i < n; i++)
{
HashSet<int> temp = new HashSet<int>();
// mapping elements of current row
// in 'temp'
for (int j = 0; j < n; j++)
temp.Add(mat[i,j]);
HashSet<int> itr=new HashSet<int>(us);
// iterate through all the elements
// of 'us'
foreach (int x in itr)
// if an element of 'us' is not present
// into 'temp', then erase that element
// from 'us'
if (!temp.Contains(x))
us.Remove(x);
// if size of 'us' becomes 0,
// then there are no common elements
if (us.Count == 0)
break;
}
// print the common elements
HashSet<int> itr1=new HashSet<int>(us);
foreach (int x in itr1)
Console.Write(x+ " ");
}
// Driver program to test above
public static void Main(String[] args)
{
int [,]mat = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
int n = 4;
findAndPrintCommonElements(mat, n);
}
}
// This code is contributed by shikhasingrajput
JavaScript
// Javascript program to find distinct elements
// common to all rows of a matrix
var MAX = 100;
// function to individually sort
// each row in increasing order
function findAndPrintCommonElements(mat, n)
{
var us = new Set();
// map elements of first row
// into 'us'
for (var i = 0; i < n; i++)
us.add(mat[0][i]);
for(var i = 1; i < n; i++)
{
var temp = new Set();
// mapping elements of current row
// in 'temp'
for (var j = 0; j < n; j++)
temp.add(mat[i][j]);
// iterate through all the elements
// of 'us'
for(var itr of us)
{
// if an element of 'us' is not present
// into 'temp', then erase that element
// from 'us'
if(!temp.has(itr))
us.delete(itr);
}
// if size of 'us' becomes 0,
// then there are no common elements
if (us.size == 0)
break;
}
// print the common elements
for(var itr of [...us].sort((a,b)=>b-a))
document.write( itr + " ");
}
// Driver program to test above
var mat = [ [2, 1, 4, 3],
[1, 2, 3, 2],
[3, 6, 2, 3],
[5, 2, 5, 3]];
var n = 4;
findAndPrintCommonElements(mat, n);
// This code is contributed by noob2000.
Output:
3 2
Time Complexity: O(n2)
Space Complexity: O(n), since n extra space has been taken.
Method 4: Using Map
- Insert all the elements of the 1st row in the map.
- Now we check that the elements present in the map are present in each row or not.
- If the element is present in the map and is not duplicated in the current row, then we increment the count of the element in the map by 1.
- If we reach the last row while traversing and if the element appears (N-1) times before then we print the element.
C++
// C++ program to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
// function to individually sort
// each row in increasing order
void distinct(int mat[][MAX], int N)
{
// make an empty map
unordered_map<int,int> ans;
// Insert the elements of
// first row in the map and
// initialize with 1
for (int j = 0; j < N; j++) {
ans[(mat[0][j])]=1;
}
// Traverse the matrix from 2nd row
for (int i = 1; i < N; i++) {
for (int j = 0; j < N; j++) {
// If the element is present in the map
// and is not duplicated in the current row
if (ans[(mat[i][j])] != 0
&& ans[(mat[i][j])] == i) {
// Increment count of the element in
// map by 1
ans[(mat[i][j])]= i + 1;
// If we have reached the last row
if (i == N - 1) {
// Print the element
cout<<mat[i][j]<<" ";
}
}
}
}
}
// Driver program to test above
int main()
{
int N=4;
int mat[][MAX] = { {2, 1, 4, 3},
{1, 2, 3, 2},
{3, 6, 2, 3},
{5, 2, 5, 3} };
distinct(mat, N);
return 0;
}
// This code is Contributed by Aarti_Rathi
Java
// JAVA Code to find distinct elements
// common to all rows of a matrix
import java.io.*;
import java.util.*;
class GFG {
static void distinct(int matrix[][], int N)
{
// make a empty map
Map<Integer, Integer> ans = new HashMap<>();
// Insert the elements of
// first row in the map and
// initialize with 1
for (int j = 0; j < N; j++) {
ans.put(matrix[0][j], 1);
}
// Traverse the matrix from 2nd row
for (int i = 1; i < N; i++) {
for (int j = 0; j < N; j++) {
// If the element is present in the map
// and is not duplicated in the current row
if (ans.get(matrix[i][j]) != null
&& ans.get(matrix[i][j]) == i) {
// Increment count of the element in
// map by 1
ans.put(matrix[i][j], i + 1);
// If we have reached the last row
if (i == N - 1) {
// Print the element
System.out.print(matrix[i][j]
+ " ");
}
}
}
}
}
/* Driver program to test above function */
public static void main(String[] args)
{
int matrix[][] = { { 2, 1, 4, 3 },
{ 1, 2, 3, 2 },
{ 3, 6, 2, 3 },
{ 5, 2, 5, 3 } };
int n = 4;
distinct(matrix, n);
}
}
// This code is Contributed by Darshit Shukla
Python3
# Python code to find distinct elements
# common to all rows of a matrix
def distinct(matrix, N):
# Make a empty map
ans = {}
# Insert the elements of
# first row in the map and
# initialize with 1
for j in range(N):
ans[(matrix[0][j])] = 0
# Traverse the matrix from 2nd row
for i in range(N):
for j in range(N):
# If the element is present in the map
# and is not duplicated in the current row
if matrix[i][j] in ans and ans[(matrix[i][j])] == i:
# Increment count of the element in
# map by 1
ans[(matrix[i][j])] = i + 1
# If we have reached the last row
if (i == N - 1):
# Print the element
print(matrix[i][j],end=" ")
# Driver code
matrix = [ [ 2, 1, 4, 3 ],
[ 1, 2, 3, 2 ],
[ 3, 6, 2, 3 ],
[ 5, 2, 5, 3 ] ]
n = 4
distinct(matrix, n)
# This code is contributed by shinjanpatra
C#
// C# code to find distinct elements
// common to all rows of a matrix
using System;
using System.Collections.Generic;
class GFG{
static void distinct(int[,] matrix, int N)
{
// Make a empty map
Dictionary<int,
int> ans = new Dictionary<int,
int>();
// Insert the elements of
// first row in the map and
// initialize with 1
for(int j = 0; j < N; j++)
{
ans[(matrix[0, j])] = 1;
}
// Traverse the matrix from 2nd row
for(int i = 1; i < N; i++)
{
for(int j = 0; j < N; j++)
{
// If the element is present in the map
// and is not duplicated in the current row
if (ans.ContainsKey(matrix[i, j]) &&
ans[(matrix[i, j])] == i)
{
// Increment count of the element in
// map by 1
ans[(matrix[i, j])] = i + 1;
// If we have reached the last row
if (i == N - 1)
{
// Print the element
Console.Write(matrix[i, j] + " ");
}
}
}
}
}
// Driver code
public static void Main(string[] args)
{
int[,] matrix = { { 2, 1, 4, 3 },
{ 1, 2, 3, 2 },
{ 3, 6, 2, 3 },
{ 5, 2, 5, 3 } };
int n = 4;
distinct(matrix, n);
}
}
// This code is contributed by ukasp
JavaScript
<script>
// Javascript code to find distinct elements
// common to all rows of a matrix
function distinct(matrix, N)
{
// Make a empty map
var ans = new Map()
// Insert the elements of
// first row in the map and
// initialize with 1
for(var j = 0; j < N; j++)
{
ans.set(matrix[0][j], 1);
}
// Traverse the matrix from 2nd row
for(var i = 1; i < N; i++)
{
for(var j = 0; j < N; j++)
{
// If the element is present in the map
// and is not duplicated in the current row
if (ans.has(matrix[i][j]) &&
ans.get(matrix[i][j]) == i)
{
// Increment count of the element in
// map by 1
ans.set(matrix[i][j], i + 1);
// If we have reached the last row
if (i == N - 1)
{
// Print the element
document.write(matrix[i][j] + " ");
}
}
}
}
}
// Driver code
var matrix = [ [ 2, 1, 4, 3 ],
[ 1, 2, 3, 2 ],
[ 3, 6, 2, 3 ],
[ 5, 2, 5, 3 ] ];
var n = 4;
distinct(matrix, n);
// This code is contributed by rutvik_56.
</script>
Time Complexity: O(n2)
Space Complexity: O(n)
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