Professional Documents
Culture Documents
Dsa
Dsa
private:
int height(TreeNode* node, int& diameter) {
if (!node) {
return 0;
}
struct node {
int data;
struct node * left, * right;
};
}
struct node * newNode(int data) {
struct node * node = (struct node * ) malloc(sizeof(struct node));
node -> data = data;
node -> left = NULL;
node -> right = NULL;
return (node);
}
int main() {
return 0;
}
3.Bottom view of a Binary Tree
Problem Statement: Given a binary tree, print the bottom view from left to right. A
node is included in the bottom view if it can be seen when we look at the tree from
the bottom
class Solution {
public:
vector <int> bottomView(Node *root) {
vector<int> ans;
if(root == NULL) return ans;
map<int,int> mpp;
queue<pair<Node*, int>> q;
q.push({root, 0});
while(!q.empty()) {
auto it = q.front();
q.pop();
Node* node = it.first;
int line = it.second;
mpp[line] = node->data;
if(node->left != NULL) {
q.push({node->left, line-1});
}
if(node->right != NULL) {
q.push({node->right, line + 1});
}
for(auto it : mpp) {
ans.push_back(it.second);
}
return ans;
}
};
4.Lowest Common Ancestor for two given Nodes
Problem Statement: Given a binary tree, Find the Lowest Common Ancestor for two
given Nodes (x,y).
Lowest Common Ancestor(LCA): The lowest common ancestor is defined between two
nodes x and y as the lowest node in T that has both x and y as descendants (where
we allow a node to be a descendant of itself.
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
//base case
if (root == NULL || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
//result
if(left == NULL) {
return right;
}
else if(right == NULL) {
return left;
}
else { //both left and right are not null, we found our result
return root;
}
}
};
5.Construct A Binary Tree from Inorder and Preorder Traversal
In this article we will solve the most asked coding interview problem: Construct A
Binary Tree from Inorder and Preorder Traversal.
Given the Inorder and Preorder Traversal of a binary tree, we need to construct the
unique binary tree represented by them.
#include <bits/stdc++.h>
struct node {
int data;
struct node * left, * right;
};
return (node);
}
node * constructTree(vector < int > & preorder, int preStart, int preEnd, vector
< int > & inorder, int inStart, int inEnd, map < int, int > & mp) {
if (preStart > preEnd || inStart > inEnd) return NULL;
return root;
}
node * buildTree(vector < int > & preorder, vector < int > & inorder) {
int preStart = 0, preEnd = preorder.size() - 1;
int inStart = 0, inEnd = inorder.size() - 1;
int main() {
vector<int> preorder{10,20,40,50,30,60};
vector<int> inorder{40,20,50,10,60,30};
node * root = buildTree(preorder, inorder);
return 0;
}
6.Morris Preorder Traversal of a Binary Tree
Problem Statement: Morris Preorder Traversal of a Binary tree. Given a Binary Tree,
find the Morris preorder traversal of Binary Tree.
#include <bits/stdc++.h>
struct node {
int data;
struct node * left, * right;
};
return (node);
}
int main() {
return 0;
}
7.Rotten Oranges : Min time to rot all oranges : BFS
Problem Statement: You will be given an m x n grid, where each cell has the
following values :
Return the minimum number of minutes required such that none of the cells has a
Fresh Orange. If it’s not possible, return -1.
#include<bits/stdc++.h>
using namespace std;
int orangesRotting(vector<vector<int>>& grid) {
if(grid.empty()) return 0;
int m = grid.size(), n = grid[0].size(), days = 0, tot = 0, cnt = 0;
queue<pair<int, int>> rotten;
for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
if(grid[i][j] != 0) tot++;
if(grid[i][j] == 2) rotten.push({i, j});
}
}
while(!rotten.empty()){
int k = rotten.size();
cnt += k;
while(k--){
int x = rotten.front().first, y = rotten.front().second;
rotten.pop();
for(int i = 0; i < 4; ++i){
int nx = x + dx[i], ny = y + dy[i];
if(nx < 0 || ny < 0 || nx >= m || ny >= n || grid[nx][ny] != 1)
continue;
grid[nx][ny] = 2;
rotten.push({nx, ny});
}
}
if(!rotten.empty()) days++;
}
int main()
{
vector<vector<int>> v{ {2,1,1} , {1,1,0} , {0,1,1} } ;
int rotting = orangesRotting(v);
cout<<"Minimum Number of Minutes Required "<<rotting<<endl;
}
8.Word Ladder – I : G-29
Given are the two distinct words startWord and targetWord, and a list denoting
wordList of unique words of equal lengths. Find the length of the shortest
transformation sequence from startWord to targetWord.
class Solution
{
public:
int wordLadderLength(string startWord, string targetWord,
vector<string> &wordList)
{
// Creating a queue ds of type {word,transitions to reach ‘word’}.
queue<pair<string, int>> q;
int main()
{
Solution obj;
class Solution {
private:
void bfs(int row, int col, vector<vector<int>> &vis, vector<vector<char>>&grid) {
// mark it visited
vis[row][col] = 1;
queue<pair<int,int>> q;
// push the node in queue
q.push({row, col});
int n = grid.size();
int m = grid[0].size();
Solution obj;
cout << obj.numIslands(grid) << endl;
return 0;
}
10.Course Schedule I and II | Pre-requisite Tasks | Topological Sort: G-24
Problem Statement I (Course Schedule): There are a total of n tasks you have to
pick, labeled from 0 to n-1. Some tasks may have prerequisites tasks, for example,
to pick task 0 you have to first finish tasks 1, which is expressed as a pair: [0,
1]
Given the total number of n tasks and a list of prerequisite pairs of size m. Find
the order of tasks you should pick to finish all tasks.
Note: There may be multiple correct orders, you need to return one of them. If it
is impossible to finish all tasks, return an empty array.
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> findOrder(int V, int m, vector<vector<int>> prerequisites)
{
vector<int> adj[V];
for (auto it : prerequisites) {
adj[it[1]].push_back(it[0]);
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
// node is in your topo sort
// so please remove it from the indegree
int main() {
int N = 4;
int M = 3;
vector<vector<int>> prerequisites(3);
prerequisites[0].push_back(0);
prerequisites[0].push_back(1);
prerequisites[1].push_back(1);
prerequisites[1].push_back(2);
prerequisites[2].push_back(2);
prerequisites[2].push_back(3);
Solution obj;
vector<int> ans = obj.findOrder(N, M, prerequisites);
class Solution {
public:
bool isPossible(int V, vector<pair<int, int> >& prerequisites) {
vector<int> adj[V];
for (auto it : prerequisites) {
adj[it.first].push_back(it.second);
}
}
};
int main() {
Solution obj;
bool ans = obj.isPossible(N, prerequisites);
return 0;
}
11.Alien Dictionary – Topological Sort: G-26
Problem Statement: Given a sorted dictionary of an alien language having N words
and k starting alphabets of a standard dictionary. Find the order of characters in
the alien language.
#include <bits/stdc++.h>
using namespace std;
class Solution {
// works for multiple components
private:
vector<int> topoSort(int V, vector<int> adj[])
{
int indegree[V] = {0};
for (int i = 0; i < V; i++) {
for (auto it : adj[i]) {
indegree[it]++;
}
}
queue<int> q;
for (int i = 0; i < V; i++) {
if (indegree[i] == 0) {
q.push(i);
}
}
vector<int> topo;
while (!q.empty()) {
int node = q.front();
q.pop();
topo.push_back(node);
// node is in your topo sort
// so please remove it from the indegree
return topo;
}
public:
string findOrder(string dict[], int N, int K) {
vector<int>adj[K];
for (int i = 0; i < N - 1; i++) {
string s1 = dict[i];
string s2 = dict[i + 1];
int len = min(s1.size(), s2.size());
for (int ptr = 0; ptr < len; ptr++) {
if (s1[ptr] != s2[ptr]) {
adj[s1[ptr] - 'a'].push_back(s2[ptr] - 'a');
break;
}
}
}
int main() {
int N = 5, K = 4;
string dict[] = {"baa", "abcd", "abca", "cab", "cad"};
Solution obj;
string ans = obj.findOrder(dict, N, K);
for (auto ch : ans)
cout << ch << ' ';
cout << endl;
return 0;
}
12.Dijkstra’s Algorithm – Using Set : G-33
Given a weighted, undirected, and connected graph of V vertices and an adjacency
list adj where adj[i] is a list of lists containing two integers where the first
integer of each list j denotes there is an edge between i and j, second integers
corresponds to the weight of that edge. You are given the source vertex S and You
have to Find the shortest distance of all the vertex from the source vertex S. You
have to return a list of integers denoting the shortest distance between each node
and Source vertex S.
#include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
//Function to find the shortest distance of all the vertices
//from the source vertex S.
vector <int> dijkstra(int V, vector<vector<int>> adj[], int S)
{
// Create a set ds for storing the nodes as a pair {dist,node}
// where dist is the distance from source to the node.
// set stores the nodes in ascending order of the distances
set<pair<int,int>> st;
st.insert({0, S});
// Now, erase the minimum distance node first from the set
// and traverse for all its adjacent nodes.
while(!st.empty()) {
auto it = *(st.begin());
int node = it.second;
int dis = it.first;
st.erase(it);
int main()
{
// Driver code.
int V = 3, E = 3, S = 2;
vector<vector<int>> adj[V];
vector<vector<int>> edges;
vector<int> v1{1, 1}, v2{2, 6}, v3{2, 3}, v4{0, 1}, v5{1, 3}, v6{0, 6};
int i = 0;
adj[0].push_back(v1);
adj[0].push_back(v2);
adj[1].push_back(v3);
adj[1].push_back(v4);
adj[2].push_back(v5);
adj[2].push_back(v6);
Solution obj;
vector<int> res = obj.dijkstra(V, adj, S);
class Solution
{
public:
int CheapestFLight(int n, vector<vector<int>> &flights,
int src, int dst, int K)
{
// Create the adjacency list to depict airports and flights in
// the form of a graph.
vector<pair<int, int>> adj[n];
for (auto it : flights)
{
adj[it[0]].push_back({it[1], it[2]});
}
// Create a queue which stores the node and their distances from the
// source in the form of {stops, {node, dist}} with ‘stops’ indicating
// the no. of nodes between src and current node.
queue<pair<int, pair<int, int>>> q;
// We stop the process as soon as the limit for the stops reaches.
if (stops > K)
continue;
for (auto iter : adj[node])
{
int adjNode = iter.first;
int edW = iter.second;
int main()
{
// Driver Code.
int n = 4, src = 0, dst = 3, K = 1;
Solution obj;
int ans = obj.CheapestFLight(n, flights, src, dst, K);
return 0;
}
14.Bellman Ford Algorithm: G-41
Problem Statement: Given a weighted, directed and connected graph of V vertices and
E edges, Find the shortest distance of all the vertices from the source vertex S.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
/* Function to implement Bellman Ford
* edges: vector of vectors which represents the graph
* S: source vertex to start traversing graph with
* V: number of vertices
*/
vector<int> bellman_ford(int V, vector<vector<int>>& edges, int S) {
vector<int> dist(V, 1e8);
dist[S] = 0;
for (int i = 0; i < V - 1; i++) {
for (auto it : edges) {
int u = it[0];
int v = it[1];
int wt = it[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v]) {
dist[v] = dist[u] + wt;
}
}
}
// Nth relaxation to check negative cycle
for (auto it : edges) {
int u = it[0];
int v = it[1];
int wt = it[2];
if (dist[u] != 1e8 && dist[u] + wt < dist[v]) {
return { -1};
}
}
return dist;
}
};
int main() {
int V = 6;
vector<vector<int>> edges(7, vector<int>(3));
edges[0] = {3, 2, 6};
edges[1] = {5, 3, 1};
edges[2] = {0, 1, 5};
edges[3] = {1, 5, -3};
edges[4] = {1, 2, -2};
edges[5] = {3, 4, -2};
edges[6] = {2, 4, 3};
int S = 0;
Solution obj;
vector<int> dist = obj.bellman_ford(V, edges, S);
for (auto d : dist) {
cout << d << " ";
}
cout << endl;
return 0;
}
15.Floyd Warshall Algorithm: G-42
Problem Statement: The problem is to find the shortest distances between every pair
of vertices in a given edge-weighted directed graph. The graph is represented as an
adjacency matrix of size n*n. Matrix[i][j] denotes the weight of the edge from i to
j. If Matrix[i][j]=-1, it means there is no edge from i to j.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
void shortest_distance(vector<vector<int>>&matrix) {
int n = matrix.size();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == -1) {
matrix[i][j] = 1e9;
}
if (i == j) matrix[i][j] = 0;
}
}
int main() {
int V = 4;
vector<vector<int>> matrix(V, vector<int>(V, -1));
matrix[0][1] = 2;
matrix[1][0] = 1;
matrix[1][2] = 3;
matrix[3][0] = 3;
matrix[3][1] = 5;
matrix[3][2] = 4;
Solution obj;
obj.shortest_distance(matrix);
return 0;
}
16.Kruskal’s Algorithm – Minimum Spanning Tree : G-47
Problem Statement: Given a weighted, undirected, and connected graph of V vertices
and E edges. The task is to find the sum of weights of the edges of the Minimum
Spanning Tree.
#include <bits/stdc++.h>
using namespace std;
class DisjointSet {
vector<int> rank, parent, size;
public:
DisjointSet(int n) {
rank.resize(n + 1, 0);
parent.resize(n + 1);
size.resize(n + 1);
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// 5, 1, 2
// 5, 2, 1
vector<pair<int, pair<int, int>>> edges;
for (int i = 0; i < V; i++) {
for (auto it : adj[i]) {
int adjNode = it[0];
int wt = it[1];
int node = i;
if (ds.findUPar(u) != ds.findUPar(v)) {
mstWt += wt;
ds.unionBySize(u, v);
}
}
return mstWt;
}
};
int main() {
int V = 5;
vector<vector<int>> edges = {{0, 1, 2}, {0, 2, 1}, {1, 2, 1}, {2, 3, 2}, {3, 4,
1}, {4, 2, 2}};
vector<vector<int>> adj[V];
for (auto it : edges) {
vector<int> tmp(2);
tmp[0] = it[1];
tmp[1] = it[2];
adj[it[0]].push_back(tmp);
tmp[0] = it[0];
tmp[1] = it[2];
adj[it[1]].push_back(tmp);
}
Solution obj;
int mstWt = obj.spanningTree(V, adj);
cout << "The sum of all the edge weights: " << mstWt << endl;
return 0;
}
17.Accounts Merge – DSU: G-50
Problem Statement: Given a list of accounts where each element account [ i ] is a
list of strings, where the first element account [ i ][ 0 ] is a name, and the
rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the
same person if there is some common email to both accounts. Note that even if two
accounts have the same name, they may belong to different people as people could
have the same name. A person can have any number of accounts initially, but all of
their accounts definitely have the same name.
After merging the accounts, return the accounts in the following format: the first
element of each account is the name, and the rest of the elements are emails in
sorted order.
#include <bits/stdc++.h>
using namespace std;
//User function Template for C++
class DisjointSet {
vector<int> rank, parent, size;
public:
DisjointSet(int n) {
rank.resize(n + 1, 0);
parent.resize(n + 1);
size.resize(n + 1);
for (int i = 0; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
}
class Solution {
public:
vector<vector<string>> accountsMerge(vector<vector<string>> &details) {
int n = details.size();
DisjointSet ds(n);
sort(details.begin(), details.end());
unordered_map<string, int> mapMailNode;
for (int i = 0; i < n; i++) {
for (int j = 1; j < details[i].size(); j++) {
string mail = details[i][j];
if (mapMailNode.find(mail) == mapMailNode.end()) {
mapMailNode[mail] = i;
}
else {
ds.unionBySize(i, mapMailNode[mail]);
}
}
}
vector<string> mergedMail[n];
for (auto it : mapMailNode) {
string mail = it.first;
int node = ds.findUPar(it.second);
mergedMail[node].push_back(mail);
}
vector<vector<string>> ans;
for (int i = 0; i < n; i++) {
if (mergedMail[i].size() == 0) continue;
sort(mergedMail[i].begin(), mergedMail[i].end());
vector<string> temp;
temp.push_back(details[i][0]);
for (auto it : mergedMail[i]) {
temp.push_back(it);
}
ans.push_back(temp);
}
sort(ans.begin(), ans.end());
return ans;
}
};
int main() {
Solution obj;
vector<vector<string>> ans = obj.accountsMerge(accounts);
for (auto acc : ans) {
cout << acc[0] << ":";
int size = acc.size();
for (int i = 1; i < size; i++) {
cout << acc[i] << " ";
}
cout << endl;
}
return 0;
}
19.Bridges in Graph – Using Tarjan’s Algorithm of time in and low time: G-55
Problem Statement: There are n servers numbered from 0 to n – 1 connected by
undirected server-to-server connections forming a network where connections[i] =
[ai, bi] represents a connection between servers ai and bi. Any server can reach
other servers directly or indirectly through the network.
Note: Here servers mean the nodes of the graph. The prob
#include <bits/stdc++.h>
using namespace std;
class Solution {
private:
int timer = 1;
void dfs(int node, int parent, vector<int> &vis,
vector<int> adj[], int tin[], int low[], vector<vector<int>> &bridges)
{
vis[node] = 1;
tin[node] = low[node] = timer;
timer++;
for (auto it : adj[node]) {
if (it == parent) continue;
if (vis[it] == 0) {
dfs(it, node, vis, adj, tin, low, bridges);
low[node] = min(low[it], low[node]);
// node --- it
if (low[it] > tin[node]) {
bridges.push_back({it, node});
}
}
else {
low[node] = min(low[node], low[it]);
}
}
}
public:
vector<vector<int>> criticalConnections(int n,
vector<vector<int>>& connections) {
vector<int> adj[n];
for (auto it : connections) {
int u = it[0], v = it[1];
adj[u].push_back(v);
adj[v].push_back(u);
}
vector<int> vis(n, 0);
int tin[n];
int low[n];
vector<vector<int>> bridges;
dfs(0, -1, vis, adj, tin, low, bridges);
return bridges;
}
};
int main() {
int n = 4;
vector<vector<int>> connections = {
{0, 1}, {1, 2},
{2, 0}, {1, 3}
};
Solution obj;
vector<vector<int>> bridges = obj.criticalConnections(n, connections);
for (auto it : bridges) {
cout << "[" << it[0] << ", " << it[1] << "] ";
}
cout << endl;
return 0;
}
20.Kth largest/smallest element in an array
Problem Statement: Given an unsorted array, print Kth Largest and Smallest Element
from an unsorted array.
#include <bits/stdc++.h>
using namespace std ;
class Solution {
public:
sort(arr.begin(), arr.end()) ;
int n = arr.size() ;
cout << "kth Largest element " << arr[n - k] << ", " <<
"kth Smallest element " << arr[k - 1];
}
} ;
int main() {
vector<int>arr = {1, 2, 6, 4, 5, 3} ;
Solution obj ;
obj.kth_Largest_And_Smallest_By_AscendingOrder(arr, 3) ;
return 0 ;
}
Output: kth Largest element 4, kth
#include <bits/stdc++.h>
using namespace std ;
class Solution {
public:
priority_queue<int>pq ;
int n = arr.size() ;
int f = k - 1 ;
while (f > 0) {
pq.pop() ;
f-- ;
}
cout << "Kth Largest element " << pq.top() << "\n" ;
}
while (f > 0) {
pq.pop() ;
f-- ;
}
cout << "Kth Smallest element " << pq.top() << "\n" ;
}
} ;
int main() {
vector<int>arr = {1, 2, 6, 4, 5, 3} ;
Solution obj ;
obj.kth_Largest_MaxHeap(arr, 3) ;
obj.kth_Smallest_MinHeap(arr, 3) ;
return 0 ;
}
Output:
Code for kth largest element:
#include <bits/stdc++.h>
using namespace std ;
int main() {
vector<int>arr ;
arr.push_back(12) ;
arr.push_back(3) ;
arr.push_back(5) ;
arr.push_back(7) ;
arr.push_back(4) ;
arr.push_back(19) ;
arr.push_back(26) ;
int n = arr.size(), k = 1;
cout << "Kth Largest element is " << kth_Largest_Element(arr, k);
return 0 ;
}
Output: Kth Largest element is 26
#include<bits/stdc++.h>
using namespace std;
if (ind - l == k - 1) {
return arr[ind];
}
if (ind - l > k - 1) {
return kth_Smallest_Element(arr, l, ind - 1, k);
}
int main()
{
vector<int>arr ;
arr.push_back(12) ;
arr.push_back(3) ;
arr.push_back(5) ;
arr.push_back(7) ;
arr.push_back(4) ;
arr.push_back(19) ;
arr.push_back(26) ;
int n = arr.size(), k = 1;
cout << "Kth smallest element is " << kth_Smallest_Element(arr, 0, n - 1, k);
return 0;
}
21.Next Greater Element Using Stack
Problem Statement: Given a circular integer array A, return the next greater
element for every element in A. The next greater element for an element x is the
first element greater than x that we come across while traversing the array in a
clockwise manner. If it doesn’t exist, return -1 for this element.
#include<bits/stdc++.h>
if (i < n) {
if (!st.empty()) nge[i] = st.top();
}
st.push(nums[i % n]);
}
return nge;
}
};
int main() {
Solution obj;
vector < int > v {5,7,1,2,6,0};
vector < int > res = obj.nextGreaterElements(v);
cout << "The next greater elements are" << endl;
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
}
22.Trapping Rainwater
Problem Statement: Given an array of non-negative integers representation elevation
of ground. Your task is to find the water that can be trapped after rain.
#include<bits/stdc++.h>
int main() {
vector < int > arr;
arr = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << "The water that can be trapped is " << trap(arr) << endl;
}
Output: The water that can be trapped is 6
Time Complexity: O(N*N) as for each index we are calculating leftMax and rightMax
so it is a nested loop.
Intuition: We are taking O(N) for computing leftMax and rightMax at each index. The
complexity can be boiled down to O(1) if we precompute the leftMax and rightMax at
each index.
Approach: Take 2 array prefix and suffix array and precompute the leftMax and
rightMax for each index beforehand. Then use the formula min(prefix[I], suffix[i])-
arr[i] to compute water trapped at each index.
Code:
#include<bits/stdc++.h>
int main() {
vector < int > arr;
arr = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << "The water that can be trapped is " << trap(arr) << endl;
}
Output: The water that can be trapped is 6
Time Complexity: O(3*N) as we are traversing through the array only once. And
O(2*N) for computing prefix and suffix array.
Approach: Take 2 pointers l(left pointer) and r(right pointer) pointing to 0th and
(n-1)th index respectively. Take two variables leftMax and rightMax and initialize
them to 0. If height[l] is less than or equal to height[r] then if leftMax is less
than height[l] update leftMax to height[l] else add leftMax-height[l] to your final
answer and move the l pointer to the right i.e l++. If height[r] is less than
height[l], then now we are dealing with the right block. If height[r] is greater
than rightMax, then update rightMax to height[r] else add rightMax-height[r] to the
final answer. Now move r to the left. Repeat these steps till l and r crosses each
other.
Intuition: We need a minimum of leftMax and rightMax.So if we take the case when
height[l]<=height[r] we increase l++, so we can surely say that there is a block
with a height more than height[l] to the right of l. And for the same reason when
height[r]<=height[l] we can surely say that there is a block to the left of r which
is at least of height[r]. So by traversing these cases and using two pointers
approach the time complexity can be decreased without using extra space.
Code:
#include<bits/stdc++.h>
int main() {
vector < int > arr;
arr = {0,1,0,2,1,0,1,3,2,1,2,1};
cout << "The water that can be trapped is " << trap(arr) << endl;
}
Output: The water that can be trapped is 6
Special thanks to Pranav Padawe and Sudip Ghosh for contributing to this article on
takeUforward. If you also wish to share your knowledge with the takeUforward fam,
please check out this article
Example:
#include <bits/stdc++.h>
if (st.empty())
rightsmall[i] = n - 1;
else
rightsmall[i] = st.top() - 1;
st.push(i);
}
int maxA = 0;
for (int i = 0; i < n; i++) {
maxA = max(maxA, heights[i] * (rightsmall[i] - leftsmall[i] + 1));
}
return maxA;
}
};
int main() {
vector<int> heights = {2, 1, 5, 6, 2, 3, 1};
Solution obj;
cout << "The largest area in the histogram is " <<
obj.largestRectangleArea(heights);
return 0;
}
#include <bits/stdc++.h>
void GetMax(vector < int > nums, int l, int r, vector < int > & arr) {
int i, maxi = INT_MIN;
for (i = l; i <= r; i++)
maxi = max(maxi, nums[i]);
arr.push_back(maxi);
}
vector < int > maxSlidingWindow(vector < int > & nums, int k) {
int left = 0, right = 0;
int i, j;
vector < int > arr;
while (right < k - 1) {
right++;
}
while (right < nums.size()) {
GetMax(nums, left, right, arr);
left++;
right++;
}
return arr;
}
int main() {
int i, j, n, k = 3, x;
vector < int > arr {
4,0,
-1,
3,
5,
3,
6,
8};
vector < int > ans;
ans = maxSlidingWindow(arr, k);
cout << "Maximum element in every " << k << " window " << endl;
for (i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
return 0;
}
///
#include<bits/stdc++.h>
vector < int > maxSlidingWindow(vector < int > & nums, int k) {
deque < int > dq;
vector < int > ans;
for (int i = 0; i < nums.size(); i++) {
if (!dq.empty() && dq.front() == i - k) dq.pop_front();
dq.push_back(i);
if (i >= k - 1) ans.push_back(nums[dq.front()]);
}
return ans;
}
int main() {
int i, j, n, k = 3, x;
vector < int > arr {4,0,-1,3,5,3,6,8};
vector < int > ans;
ans = maxSlidingWindow(arr, k);
cout << "Maximum element in every " << k << " window " << endl;
for (i = 0; i < ans.size(); i++)
cout << ans[i] << " ";
return 0;
}
Output:
27.Implement LRU Cache
Problem Statement: “Design a data structure that follows the constraints of Least
Recently Used (LRU) cache”.
LRUCache(int capacity) we need to initialize the LRU cache with positive size
capacity.
int get(int key) returns the value of the key if the key exists, otherwise return -
1.
Void put(int key,int value), Update the value of the key if the key exists.
Otherwise, add the key-value pair to the cache.if the number of keys exceeds the
capacity from this operation, evict the least recently used key.
class LRUCache {
public:
class node {
public:
int key;
int val;
node * next;
node * prev;
node(int _key, int _val) {
key = _key;
val = _val;
}
};
int cap;
unordered_map < int, node * > m;
LRUCache(int capacity) {
cap = capacity;
head -> next = tail;
tail -> prev = head;
}
return -1;
}
string s="abc";
vector<string>ans = AllPossibleStrings(s);
//printint all the subsequence.
cout<<"All possible subsequences are "<<endl;
for (auto it : ans) {
cout << it << " ";
}
}
#include<bits/stdc++.h>
using namespace std;
void solve(int i, string s, string &f) {
if (i == s.length()) {
cout << f << " ";
return;
}
//picking
f = f + s[i];
solve(i + 1, s, f);
//poping out while backtracking
f.pop_back();
solve(i + 1, s, f);
}
int main() {
string s = "abc";
string f = "";
cout<<"All possible subsequences are: "<<endl;
solve(0, s, f);
}
30.Combination Sum – 1
Problem Statement:
Given an array of distinct integers and a target, you have to return the list of
all unique combinations where the chosen numbers sum to target. You may return the
combinations in any order.
The same number may be chosen from the given array an unlimited number of times.
Two combinations are unique if the frequency of at least one of the chosen numbers
is different.
}
public:
vector < vector < int >> combinationSum(vector < int > & candidates, int
target) {
vector < vector < int >> ans;
vector < int > ds;
findCombination(0, target, candidates, ans, ds);
return ans;
}
};
int main() {
Solution obj;
vector < int > v {2,3,6,7};
int target = 7;
col = dupcol;
row = duprow;
while (col >= 0) {
if (board[row][col] == 'Q')
return false;
col--;
}
row = duprow;
col = dupcol;
while (row < n && col >= 0) {
if (board[row][col] == 'Q')
return false;
row++;
col--;
}
return true;
}
public:
void solve(int col, vector < string > & board, vector < vector < string >> &
ans, int n) {
if (col == n) {
ans.push_back(board);
return;
}
for (int row = 0; row < n; row++) {
if (isSafe1(row, col, board, n)) {
board[row][col] = 'Q';
solve(col + 1, board, ans, n);
board[row][col] = '.';
}
}
}
public:
vector < vector < string >> solveNQueens(int n) {
vector < vector < string >> ans;
vector < string > board(n);
string s(n, '.');
for (int i = 0; i < n; i++) {
board[i] = s;
}
solve(0, board, ans, n);
return ans;
}
};
int main() {
int n = 4; // we are taking 4*4 grid and 4 queens
Solution obj;
vector < vector < string >> ans = obj.solveNQueens(n);
for (int i = 0; i < ans.size(); i++) {
cout << "Arrangement " << i + 1 << "\n";
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
cout << endl;
}
cout << endl;
}
return 0;
}
//
#include <bits/stdc++.h>
public:
vector < vector < string >> solveNQueens(int n) {
vector < vector < string >> ans;
vector < string > board(n);
string s(n, '.');
for (int i = 0; i < n; i++) {
board[i] = s;
}
vector < int > leftrow(n, 0), upperDiagonal(2 * n - 1, 0), lowerDiagonal(2 *
n - 1, 0);
solve(0, board, ans, leftrow, upperDiagonal, lowerDiagonal, n);
return ans;
}
};
int main() {
int n = 4; // we are taking 4*4 grid and 4 queens
Solution obj;
vector < vector < string >> ans = obj.solveNQueens(n);
for (int i = 0; i < ans.size(); i++) {
cout << "Arrangement " << i + 1 << "\n";
for (int j = 0; j < ans[0].size(); j++) {
cout << ans[i][j];
cout << endl;
}
cout << endl;
}
return 0;
}
Output:
Arrangement 1
..Q.
Q…
…Q
.Q..
Arrangement 2
.Q..
33.Sudoku Solver
Problem Statement:
Given a 9×9 incomplete sudoku, solve it such that it becomes valid sudoku. Valid
sudoku has the following properties.
#include <vector>
bool isValid(vector < vector < char >> & board, int row, int col, char c) {
for (int i = 0; i < 9; i++) {
if (board[i][col] == c)
return false;
if (board[row][i] == c)
return false;
if (board[3 * (row / 3) + i / 3][3 * (col / 3) + i % 3] == c)
return false;
}
return true;
}
if (solveSudoku(board))
return true;
else
board[i][j] = '.';
}
}
return false;
}
}
}
return true;
}
int main() {
vector<vector<char>>board{
{'9', '5', '7', '.', '1', '3', '.', '8', '4'},
{'4', '8', '3', '.', '5', '7', '1', '.', '6'},
{'.', '1', '2', '.', '4', '9', '5', '3', '7'},
{'1', '7', '.', '3', '.', '4', '9', '.', '2'},
{'5', '.', '4', '9', '7', '.', '3', '6', '.'},
{'3', '.', '9', '5', '.', '8', '7', '.', '1'},
{'8', '4', '5', '7', '9', '.', '6', '1', '3'},
{'.', '9', '1', '.', '3', '6', '.', '7', '5'},
{'7', '.', '6', '1', '8', '5', '4', '.', '9'}
};
solveSudoku(board);
}
return false;
}
int main() {
int N = 4;
int m = 3;
bool graph[101][101];
memset(graph, false, sizeof graph);
// Edges are (0, 1), (1, 2), (2, 3), (3, 0), (0, 2)
graph[0][1] = 1; graph[1][0] = 1;
graph[1][2] = 1; graph[2][1] = 1;
graph[2][3] = 1; graph[3][2] = 1;
graph[3][0] = 1; graph[0][3] = 1;
graph[0][2] = 1; graph[2][0] = 1;
}
36.Word Search – Leetcode
Given an m x n grid of characters board and a string word, return true if the word
exists in the grid. The word can be constructed from letters of sequentially
adjacent cells, where adjacent cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
#include<bits/stdc++.h>
using namespace std;
// top direction
bool top = searchNext(board, word, row - 1, col, index + 1, m, n);
// right direction
bool right = searchNext(board, word, row, col + 1, index + 1, m, n);
// bottom direction
bool bottom = searchNext(board, word, row + 1, col, index + 1, m, n);
// left direction
bool left = searchNext(board, word, row, col - 1, index + 1, m, n);
int m = board.size();
int n = board[0].size();
int index = 0;
if (board[i][j] == word[index]) {
if (searchNext(board, word, i, j, index, m, n))
return true;
}
}
}
return false;
}
int main() {
vector<vector<char>> board {{'A','B','C','E'},
{'S','F','C','S'},
{'A','D','E','E'}};
temp = head;
return temp;
}
};
Solution 2: [Efficient] Tortoise-Hare-Approach
Unlike the above approach, we don’t have to maintain node count here and we will be
able to find the middle node in a single traversal so this approach is more
efficient.
Intuition: In the Tortoise-Hare approach, we increment slow ptr by 1 and fast ptr
by 2, so if take a close look fast ptr will travel double that of the slow pointer.
So when the fast ptr will be at the end of the Linked List, slow ptr would have
covered half of the Linked List till then. So slow ptr will be pointing towards the
middle of Linked List.
Approach:
Create two pointers slow and fast and initialize them to a head pointer.
Move slow ptr by one step and simultaneously fast ptr by two steps until fast ptr
is NULL or next of fast ptr is NULL.
When the above condition is met, we can see that the slow ptr is pointing towards
the middle of the Linked List and hence we can return the slow pointer.
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next)
slow = slow->next, fast = fast->next->next;
return slow;
}
};
Time Complexity: O(N)
Follow-up question you can try: Detect and remove Loop in Linked List
Special thanks to Aditya Shahare and Sudip Ghosh for contributing to this article
on takeUforward. If you also wish to share your knowledge with the takeUforward
fam, please check out this article.
Problem Statement: Given head, the head of a linked list, determine if the linked
list has a cycle in it. There is a cycle in a linked list if there is some node in
the list that can be reached again by continuously following the next pointer.
Return true if there is a cycle in the linked list. Otherwise, return false.
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
if(head == NULL) {
head = newNode;
return;
}
temp->next = newNode;
return;
}
int main() {
node* head = NULL;
insertNode(head,1);
insertNode(head,2);
insertNode(head,3);
insertNode(head,4);
createCycle(head,1,3);//creating cycle in the list
if(cycleDetect(head) == true)
cout<<"Cycle detected\n";
else
cout<<"Cycle not detected\n";
return 0;
}//
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
if(head == NULL) {
head = newNode;
return;
}
temp->next = newNode;
return;
}
int main() {
node* head = NULL;
insertNode(head,1);
insertNode(head,2);
insertNode(head,3);
insertNode(head,4);
createCycle(head,1,3);//creating cycle in the list
if(cycleDetect(head) == true)
cout<<"Cycle detected\n";
else
cout<<"Cycle not detected\n";
return 0;
}
Output: Cycle detected
43.Remove N-th node from the end of a Linked List
Problem Statement: Given a linked list, and a number N. Find the Nth node from the
end of this linked list and delete it. Return the head of the new modified linked
list.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode * start = new ListNode();
start -> next = head;
ListNode* fast = start;
ListNode* slow = start;
slow->next = slow->next->next;
return start->next;
}
};
45.Find intersection of Two Linked Lists
Problem Statement: Given the heads of two singly linked-lists headA and headB,
return the node at which the two lists intersect. If the two linked lists have no
intersection at all, return null.
#include<iostream>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
//utility function to insert node at the end of the linked list
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
temp->next = newNode;
return;
}
int main() {
// creation of both lists
node* head = NULL;
insertNode(head,1);
insertNode(head,3);
insertNode(head,1);
insertNode(head,2);
insertNode(head,4);
node* head1 = head;
head = head->next->next->next;
node* headSec = NULL;
insertNode(headSec,3);
node* head2 = headSec;
headSec->next = head;
//printing of the lists
cout<<"List1: "; printList(head1);
cout<<"List2: "; printList(head2);
//checking if intersection is present
node* answerNode = intersectionPresent(head1,head2);
if(answerNode == NULL )
cout<<"No intersection\n";
else
cout<<"The intersection point is "<<answerNode->num<<endl;
return 0;
}
Output:
List1: 1->3->1->2->4
//
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
//utility function to insert node at the end of the linked list
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
temp->next = newNode;
return;
}
int main() {
// creation of both lists
node* head = NULL;
insertNode(head,1);
insertNode(head,3);
insertNode(head,1);
insertNode(head,2);
insertNode(head,4);
node* head1 = head;
head = head->next->next->next;
node* headSec = NULL;
insertNode(headSec,3);
node* head2 = headSec;
headSec->next = head;
//printing of the lists
cout<<"List1: "; printList(head1);
cout<<"List2: "; printList(head2);
//checking if intersection is present
node* answerNode = intersectionPresent(head1,head2);
if(answerNode == NULL )
cout<<"No intersection\n";
else
cout<<"The intersection point is "<<answerNode->num<<endl;
return 0;
}
//
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
//utility function to insert node at the end of the linked list
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
temp->next = newNode;
return;
}
int getDifference(node* head1,node* head2) {
int len1 = 0,len2 = 0;
while(head1 != NULL || head2 != NULL) {
if(head1 != NULL) {
++len1; head1 = head1->next;
}
if(head2 != NULL) {
++len2; head2 = head2->next;
}
}
return len1-len2;//if difference is neg-> length of list2 > length of list1
else vice-versa
}
int main() {
// creation of both lists
node* head = NULL;
insertNode(head,1);
insertNode(head,3);
insertNode(head,1);
insertNode(head,2);
insertNode(head,4);
node* head1 = head;
head = head->next->next->next;
node* headSec = NULL;
insertNode(headSec,3);
node* head2 = headSec;
headSec->next = head;
//printing of the lists
cout<<"List1: "; printList(head1);
cout<<"List2: "; printList(head2);
//checking if intersection is present
node* answerNode = intersectionPresent(head1,head2);
if(answerNode == NULL )
cout<<"No intersection\n";
else
cout<<"The intersection point is "<<answerNode->num<<endl;
return 0;
}
Output:
//
#include<bits/stdc++.h>
using namespace std;
class node {
public:
int num;
node* next;
node(int val) {
num = val;
next = NULL;
}
};
//utility function to insert node at the end of the linked list
void insertNode(node* &head,int val) {
node* newNode = new node(val);
if(head == NULL) {
head = newNode;
return;
}
temp->next = newNode;
return;
}
//utility function to check presence of intersection
node* intersectionPresent(node* head1,node* head2) {
node* d1 = head1;
node* d2 = head2;
while(d1 != d2) {
d1 = d1 == NULL? head2:d1->next;
d2 = d2 == NULL? head1:d2->next;
}
return d1;
}
int main() {
// creation of both lists
node* head = NULL;
insertNode(head,1);
insertNode(head,3);
insertNode(head,1);
insertNode(head,2);
insertNode(head,4);
node* head1 = head;
head = head->next->next->next;
node* headSec = NULL;
insertNode(headSec,3);
node* head2 = headSec;
headSec->next = head;
//printing of the lists
cout<<"List1: "; printList(head1);
cout<<"List2: "; printList(head2);
//checking if intersection is present
node* answerNode = intersectionPresent(head1,head2);
if(answerNode == NULL )
cout<<"No intersection\n";
else
cout<<"The intersection point is "<<answerNode->num<<endl;
return 0;
}
//45.Search Element in Rotated Sorted Array II
Problem Statement: Given an integer array arr of size N, sorted in ascending order
(may contain duplicate values) and a target value k. Now the array is rotated at
some pivot point unknown to you. Return True if k is present and otherwise, return
False.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr = {7, 8, 1, 2, 3, 3, 3, 4, 5, 6};
int k = 3;
bool ans = searchInARotatedSortedArrayII(arr, k);
if (!ans)
cout << "Target is not present.\n";
else
cout << "Target is present in the array.\n";
return 0;
}
50.Minimum in Rotated Sorted Array
Problem Statement: Given an integer array arr of size N, sorted in ascending order
(with distinct values). Now the array is rotated between 1 to N times which is
unknown. Find the minimum element in the array.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr = {4, 5, 6, 7, 0, 1, 2, 3};
int ans = findMin(arr);
cout << "The minimum element is: " << ans << "\n";
return 0;
}
50.
Peak element in Array
Problem Statement: Given an array of length N. Peak element is defined as the
element greater than both of its neighbors. Formally, if ‘arr[i]’ is the peak
element, ‘arr[i – 1]’ < ‘arr[i]’ and ‘arr[i + 1]’ < ‘arr[i]’. Find the index(0-
based) of a peak element in the array. If there are multiple peak numbers, return
the index of any peak number.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 5, 1};
int ans = findPeakElement(arr);
cout << "The peak is at index: " << ans << "\n";
return 0;
}
66.Koko Eating Bananas
Problem Statement: A monkey is given ‘n’ piles of bananas, whereas the ‘ith’ pile
has ‘a[i]’ bananas. An integer ‘h’ is also given, which denotes the time (in hours)
for all the bananas to be eaten.
Each hour, the monkey chooses a non-empty pile of bananas and eats ‘k’ bananas. If
the pile contains less than ‘k’ bananas, then the monkey consumes all the bananas
and won’t eat any more bananas in that hour.
Find the minimum number of bananas ‘k’ to eat per hour so that the monkey can eat
all the bananas within ‘h’ hours.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v = {7, 15, 6, 3};
int h = 8;
int ans = minimumRateToEatBananas(v, h);
cout << "Koko should eat atleast " << ans << " bananas/hr.\n";
return 0;
}
67.Aggressive Cows : Detailed Solution
Problem Statement: You are given an array ‘arr’ of size ‘n’ which denotes the
position of stalls.
You are also given an integer ‘k’ which denotes the number of aggressive cows.
You are given the task of assigning stalls to ‘k’ cows such that the minimum
distance between any two of them is the maximum possible.
Find the maximum possible minimum distance.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> stalls = {0, 3, 4, 7, 10, 9};
int k = 4;
int ans = aggressiveCows(stalls, k);
cout << "The maximum possible minimum distance is: " << ans << "\n";
return 0;
}
65.Allocate Minimum Number of Pages
Problem Statement: Given an array ‘arr of integer numbers, ‘ar[i]’ represents the
number of pages in the ‘i-th’ book. There are a ‘m’ number of students, and the
task is to allocate all the books to the students.
Allocate books in such a way that:
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr = {25, 46, 28, 49, 24};
int n = 5;
int m = 4;
int ans = findPages(arr, n, m);
cout << "The answer is: " << ans << "\n";
return 0;
}
61.Median of Two Sorted Arrays of different sizes
Problem Statement: Given two sorted arrays arr1 and arr2 of size m and n
respectively, return the median of the two sorted arrays. The median is defined as
the middle value of a sorted list of numbers. In case the length of the list is
even, the median is the average of the two middle elements.
#include <bits/stdc++.h>
using namespace std;
vector<int> arr3;
//apply the merge step:
int i = 0, j = 0;
while (i < n1 && j < n2) {
if (a[i] < b[j]) arr3.push_back(a[i++]);
else arr3.push_back(b[j++]);
}
int main()
{
vector<int> a = {1, 4, 7, 10, 12};
vector<int> b = {2, 3, 6, 15};
cout << "The median of two sorted array is " << fixed << setprecision(1)
<< median(a, b) << '\n';
}
62.Minimise Maximum Distance between Gas Stations
Problem Statement: You are given a sorted array ‘arr’ of length ‘n’, which contains
positive integer positions of ‘n’ gas stations on the X-axis. You are also given an
integer ‘k’. You have to place ‘k’ new gas stations on the X-axis. You can place
them anywhere on the non-negative side of the X-axis, even on non-integer
positions. Let ‘dist’ be the maximum value of the distance between adjacent gas
stations after adding k new gas stations.
Find the minimum value of ‘dist’.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr = {1, 2, 3, 4, 5};
int k = 4;
long double ans = minimiseMaxDistance(arr, k);
cout << "The answer is: " << ans << "\n";
return 0;
}
63.next_permutation : find next lexicographically greater permutation
Problem Statement: Given an array Arr[] of integers, rearrange the numbers of the
given array into the lexicographically next greater permutation of numbers.
#include<iostream>
#include<vector>
#include<algorithm>
int main() {
int arr[] = {1,3,2};
return 0;
}
60.3 Sum : Find triplets that add up to a zero
Problem Statement: Given an array of N integers, your task is to find unique
triplets that add up to give a sum of zero. In short, you need to return an array
of all the unique triplets [arr[a], arr[b], arr[c]] such that i!=j, j!=k, k!=i, and
their sum is equal to zero.
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> arr = { -1, 0, 1, 2, -1, -4};
int n = arr.size();
vector<vector<int>> ans = triplet(n, arr);
for (auto it : ans) {
cout << "[";
for (auto i : it) {
cout << i << " ";
}
cout << "] ";
}
cout << "\n";
return 0;
}
61.Kadane’s Algorithm : Maximum Subarray Sum in an Array
Problem Statement: Given an integer array arr, find the contiguous subarray
(containing at least one number) which
has the largest sum and returns its sum and prints the subarray.
#include <bits/stdc++.h>
using namespace std;
return maxi;
}
int main()
{
int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int maxSum = maxSubarraySum(arr, n);
cout << "The maximum subarray sum is: " << maxSum << endl;
return 0;
}
60.55
Majority Elements(>N/3 times) | Find the elements that appears more than N/3 times
in the array
Problem Statement: Given an array of N integers. Find the elements that appear more
than N/3 times in the array. If no such element exists, return an empty vector.
#include <bits/stdc++.h>
using namespace std;
vector<int> majorityElement(vector<int> v) {
int n = v.size(); //size of the array
vector<int> ls; // list of answers
if (ls.size() == 2) break;
}
return ls;
}
int main()
{
vector<int> arr = {11, 33, 33, 11, 33, 11};
vector<int> ans = majorityElement(arr);
cout << "The majority elements are: ";
for (auto it : ans)
cout << it << " ";
cout << "\n";
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> a = {4, 2, 2, 6, 4};
int k = 6;
int ans = subarraysWithXorK(a, k);
cout << "The number of subarrays with XOR k is: "
<< ans << "\n";
return 0;
}
61.Find the repeating and missing numbers
Problem Statement: You are given a read-only array of N integers with values also
in the range [1, N] both inclusive. Each integer appears exactly once except A
which appears twice and B which is missing. The task is to find the repeating and
missing numbers A and B where A repeats twice and B is missing.
#include <bits/stdc++.h>
using namespace std;
vector<int> findMissingRepeatingNumbers(vector<int> a) {
int n = a.size(); // size of the array
int repeating = -1, missing = -1;
if (cnt == 2) repeating = i;
else if (cnt == 0) missing = i;
int main()
{
vector<int> a = {3, 1, 2, 5, 4, 6, 7, 5};
vector<int> ans = findMissingRepeatingNumbers(a);
cout << "The repeating and missing numbers are: {"
<< ans[0] << ", " << ans[1] << "}\n";
return 0;
}
What is an inversion of an array? Definition: for all i & j < size of array, if i <
j then you have to find pair (A[i],A[j]) such that A[j] < A[i].
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> a = {5, 4, 3, 2, 1};
int n = 5;
int cnt = numberOfInversions(a, n);
cout << "The number of inversions is: "
<< cnt << endl;
return 0;
}
70.Maximum Product Subarray in an Array
Problem Statement: Given an array that contains both negative and positive
integers, find the maximum product subarray.
#include<bits/stdc++.h>
using namespace std;