├── 01. Graphs ├── 01. Representation │ ├── 1. List.cpp │ └── 2. Matrix.cpp ├── 02. BFS │ ├── 1. Boredom.cpp │ ├── 2. WordLadder2.cpp │ ├── 3. MultiSourceBFS.cpp │ └── 4. ValidBFS.cpp ├── 03. DFS │ ├── 1. JourneyToTheMoon.cpp │ ├── 2. DFSwithStoppingCondition.cpp │ ├── 3. ConnectedComponents.cpp │ └── 4. ReconstructItinerary.cpp ├── 04. CycleDetection │ ├── 1. DetectCycleUndirectedGraph.cpp │ ├── 2. DetectCycleDirectedGraph.cpp │ ├── 3. IsBipartite.cpp │ ├── 4. LengthOfSmallestCycle.cpp │ ├── 5. DetectCyclesin2DGrid.cpp │ └── 6. Maximum Employees to Be Invited to a Meeting.cpp ├── 05. Topological Sort │ ├── 1. TopologicalBFS.cpp │ ├── 2. TopologicalDFS.cpp │ ├── 3. GameRoutes.cpp │ └── 4. LargestColorValueInADirectedGraph.cpp ├── 06. MST │ ├── 1. Kruskals.cpp │ └── 2. Prims.cpp ├── 07. DSU │ ├── 1. DSUSnippetClass.cpp │ └── 2. Redundant Connection II.cpp ├── 08. Shortest Paths Algo │ ├── 1. Dijkstras.cpp │ ├── 2. BellmanFord.cpp │ └── 3. FLoydWarshall.cpp ├── 09. StronglyConnected │ └── 1. Kosarju.cpp ├── 10.Articulation Point and Bridges │ ├── 1. CutEdges.cpp │ └── 2. CutVertex.cpp └── Readme.md ├── 02. Dynamic Programming ├── 1. Barcode.cpp ├── 2. CherryPick.cpp ├── 3. Digit DP-MagicNumbers.cpp └── Readme.md ├── 03. SegmentTree ├── 1. SegmentTreeSnippetClass.cpp ├── 2. Xenia.cpp └── Readme.md ├── 04. Rolling hash └── 1. Rabin_carp.cpp ├── README.md └── Rest of the topics └── Readme.md /01. Graphs/01. Representation/1. List.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int n=6; 6 | vector> edges={{0,3},{1,2},{1,5},{2,4},{3,5},{5,4},{5,0}}; 7 | 8 | map> graph; 9 | 10 | for(int i=0;i"; 18 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() { 5 | int n=6; 6 | vector> edges={{0,3},{1,2},{1,5},{2,4},{3,5},{5,4},{5,0}}; 7 | 8 | int matrix[n][n]; 9 | memset(matrix,0,sizeof matrix); 10 | 11 | for(int i=0;i 2 | using namespace std; 3 | #define ll long long 4 | string solve(int n,int m,vector a){ 5 | // for(auto &x:a) x=x%m; 6 | set mp; 7 | mp.insert(0); 8 | long long sum=0; 9 | for(int i=0;i=0) { 13 | if(mp.find(temp)!=mp.end()) return "Yes"; 14 | temp-=m; 15 | } 16 | 17 | mp.insert(sum); 18 | } 19 | return "No"; 20 | 21 | } 22 | int main() { 23 | int n,m; 24 | cin>>n>>m; 25 | 26 | vector v(n); 27 | for(int i=0;i>v[i]; 28 | cout<&temp, vector>&ans,string node,unordered_map>&adj,string endWord) { 7 | temp.push_back(node); 8 | if(node == endWord) { 9 | ans.push_back(temp); 10 | } else { 11 | for(auto nbr:adj[node]) { 12 | dfs(temp,ans,nbr,adj,endWord); 13 | } 14 | } 15 | temp.pop_back(); 16 | } 17 | vector> findLadders(string beginWord, string endWord, vector& wordList) { 18 | 19 | unordered_map> adj; 20 | unordered_map lvl; 21 | unordered_set dict(wordList.begin(), wordList.end()); 22 | 23 | queue q; 24 | int l = 0; 25 | q.push(beginWord); 26 | lvl[beginWord]=0; 27 | while(q.size()) { 28 | int siz = q.size(); 29 | while(siz--) { 30 | string a = q.front(); 31 | q.pop(); 32 | lvl[a]=l; 33 | for(int i=0;il) { 45 | adj[a].push_back(temp); 46 | } 47 | 48 | } 49 | } 50 | } 51 | } 52 | l++; 53 | } 54 | vector temp; 55 | vector> ans; 56 | dfs(temp,ans,beginWord,adj,endWord); 57 | return ans; 58 | } -------------------------------------------------------------------------------- /01. Graphs/02. BFS/3. MultiSourceBFS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This is a really good usecase of multi-source BFS 3 | In this question we see how we can traverse from a point to tht point itself 4 | using minimum path. 5 | We can go back and forth btw nodes but should never land on the same config again 6 | 7 | */ 8 | 9 | //847. Shortest Path Visiting All Nodes 10 | 11 | 12 | 13 | int shortestPathLength(vector>& graph) { 14 | int n = graph.size(); 15 | map > m; 16 | for(int i=0;i> q; 22 | set>s; 23 | 24 | for(int i=0;i 7 | using namespace std; 8 | 9 | int main() { 10 | int n; 11 | cin>>n; 12 | vector> edges; 13 | vector> adjList(n+1); 14 | for(int i=0;i>a>>b; 17 | edges.push_back({a,b}); 18 | } 19 | 20 | vector seq(n); 21 | for(int i=0;i>seq[i]; 22 | 23 | vector reorder(n+1); 24 | for(int i=0;i&a,vector&b)->bool{ 28 | if(a[0]==b[0]) { 29 | return reorder[a[1]] bool { 41 | // return reorder[a] q; 45 | q.push(1); 46 | vector res; 47 | vector vis(n+1,0); 48 | vis[seq[0]]=1; 49 | while(q.size()) { 50 | 51 | auto a = q.front(); 52 | q.pop(); 53 | res.push_back(a); 54 | 55 | for(auto nbr: adjList[a]) { 56 | if(vis[nbr]==0) { 57 | q.push(nbr); 58 | vis[nbr]=1; 59 | } 60 | } 61 | } 62 | if(res == seq)cout<<"Yes"<>&m,vector&visited,long long &temp) { 9 | visited[i]=1; 10 | temp++; 11 | for(auto a:m[i]) { 12 | if(visited[a]==0) { 13 | dfs(a,m,visited,temp); 14 | } 15 | } 16 | } 17 | int journeyToMoon(int n, vector> astronaut) { 18 | map> m; 19 | for(auto a:astronaut) { 20 | m[a[0]].push_back(a[1]); 21 | m[a[1]].push_back(a[0]); 22 | } 23 | //for(int i=0;i visited(n); 25 | long long ans=0; 26 | for(int i=0;i>>&m,int maxTime,int time,vector&visited,int score, vector&values,int node) { 10 | 11 | 12 | if(time>maxTime) return ; 13 | 14 | if(visited[node]==0){ 15 | score+=values[node]; 16 | } 17 | visited[node]++; 18 | 19 | if(node==0) { 20 | ans=max(ans,score); 21 | } 22 | 23 | for(auto &nbr:m[node]) { 24 | dfs(ans,m,maxTime,time+nbr[1],visited,score,values,nbr[0]); 25 | } 26 | visited[node]--; 27 | 28 | 29 | } 30 | int maximalPathQuality(vector& values, vector>& edges, int maxTime) { 31 | map>> m; 32 | int n=values.size(); 33 | for(auto &a: edges) { 34 | m[a[0]].push_back({a[1],a[2]}); 35 | m[a[1]].push_back({a[0],a[2]}); 36 | } 37 | vector visited(n,0); 38 | int ans=0; 39 | dfs(ans,m,maxTime,0,visited,0,values,0); 40 | return ans; 41 | } -------------------------------------------------------------------------------- /01. Graphs/03. DFS/3. ConnectedComponents.cpp: -------------------------------------------------------------------------------- 1 | //https://leetcode.com/problems/couples-holding-hands/ 2 | 3 | /* 4 | In this questions we just need to form components. 5 | Lets say one partner is present in NodeA and another in NodeB then join them. 6 | 7 | Node numebr is i/2; 8 | 9 | Then lets say a component has n nodes then swapping will be btw only these n node 10 | hence n-1 swappings 11 | 12 | so do the same for all components 13 | 14 | OR 15 | 16 | C1size - 1 + C2size -1 + C3size -1 .. 17 | = V - number of components 18 | */ 19 | 20 | 21 | void dfs(int node,map>&m,vector&visited) { 22 | visited[node]=1; 23 | for(auto a:m[node]) { 24 | if(visited[a]==0) 25 | dfs(a,m,visited); 26 | } 27 | } 28 | int minSwapsCouples(vector& row) { 29 | int n=row.size(); 30 | map m; 31 | for(int i=0;i> g; 35 | for(int i=0;i visited(n/2,0); 47 | for(int i=0;i> &m,string node,vector&ans) { 7 | vector temp; 8 | for(auto a:m[node]) { 9 | temp.push_back(a); 10 | } 11 | for(auto a:temp) { 12 | if(m[node].find(a)!=m[node].end()) { 13 | m[node].erase(m[node].find(a)); 14 | dfs(m,a,ans); 15 | } 16 | } 17 | ans.push_back(node); 18 | } 19 | vector findItinerary(vector>& tickets) { 20 | map> m; 21 | for(auto a : tickets) { 22 | m[a[0]].insert(a[1]); 23 | } 24 | vector ans; 25 | dfs(m,"JFK",ans); 26 | reverse(ans.begin(),ans.end()); 27 | return ans; 28 | } -------------------------------------------------------------------------------- /01. Graphs/04. CycleDetection/1. DetectCycleUndirectedGraph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool detectCycle(unordered_map>& m, unordered_set& visited, int node, int parent) { 5 | visited.insert(node); 6 | for(auto nbr: m[node]) { 7 | if(visited.find(nbr) == visited.end()) { 8 | if(detectCycle(m,visited,nbr,node)) return true; 9 | } 10 | else if(nbr != parent) { 11 | return true; 12 | } 13 | } 14 | return false; 15 | } 16 | 17 | bool solve(int n, vector > edges) 18 | { 19 | unordered_map> graph; 20 | 21 | for(auto a: edges) { 22 | graph[a[0]].push_back(a[1]); 23 | graph[a[1]].push_back(a[0]); 24 | } 25 | unordered_set visited; 26 | for(int i = 1; i < n; i++) { 27 | if(visited.find(i) == visited.end()) { 28 | if(detectCycle(graph, visited, i, -1)) { 29 | return true; 30 | } 31 | } 32 | 33 | } 34 | return false; 35 | 36 | 37 | } -------------------------------------------------------------------------------- /01. Graphs/04. CycleDetection/2. DetectCycleDirectedGraph.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | bool detectCycle(unordered_map>& m, unordered_set& visited, int node, int parent, unordered_set& bag) { 5 | visited.insert(node); 6 | bag.insert(node); 7 | for(auto nbr: m[node]) { 8 | if(bag.find(nbr) != bag.end()) return true; 9 | else if(visited.find(nbr) == visited.end()) { 10 | if(detectCycle(m, visited, nbr, node, bag)) return true; 11 | } 12 | } 13 | bag.erase(node); 14 | return false; 15 | } 16 | 17 | bool solve(int n, vector > edges) 18 | { 19 | unordered_map> graph; 20 | 21 | for(auto a: edges) { 22 | graph[a[0]].push_back(a[1]); 23 | } 24 | unordered_set visited; 25 | unordered_set bag; 26 | for(int i = 1; i < n; i++) { 27 | if(visited.find(i) == visited.end()) { 28 | if(detectCycle(graph, visited, i, -1, bag)) { 29 | return true; 30 | } 31 | } 32 | 33 | } 34 | return false; 35 | 36 | 37 | } -------------------------------------------------------------------------------- /01. Graphs/04. CycleDetection/3. IsBipartite.cpp: -------------------------------------------------------------------------------- 1 | // Notes 2 | 3 | /* 4 | Notes 5 | 1-We can easily solve the problem of IsBipartite graph by DFS/BFS alternate colouring 6 | 2-Property to be Bipartite ( either no cyle ie Tree. OR even len cycles ) 7 | 3-Odd len cycles simply means not bipartite 8 | 4-We can use this colouring technique to find if there is odd len cycle ( just check if graph is not Bipartite) 9 | 10 | */ 11 | bool dfs(int i,vector>& graph,vector& color,int req_color) 12 | { 13 | 14 | if(color[i]==-1) 15 | { 16 | color[i]=req_color; 17 | int ans=1; 18 | for(auto a:graph[i]) 19 | { 20 | ans&=dfs(a,graph,color,1-req_color); 21 | } 22 | return ans; 23 | } 24 | else 25 | { 26 | return color[i]==req_color; 27 | } 28 | } 29 | bool isBipartite(vector>& graph) 30 | { 31 | int n=graph.size(); 32 | vector color(n,-1); 33 | for(int i=0;i 11 | using namespace std; 12 | 13 | int solve(int n, vector> edges){ 14 | int ans = INT_MAX; 15 | unordered_map> m; 16 | for(auto a : edges) { 17 | m[a[0]].push_back(a[1]); 18 | m[a[1]].push_back(a[0]); 19 | if(a[0] == a[1]) return 1; 20 | } 21 | for(int i = 0; i < n; i++) { 22 | 23 | vector parent(n,-1); 24 | vector dis(n,20000); 25 | 26 | queue q; 27 | q.push(i); 28 | dis[i] = 0; 29 | parent[i] = i; 30 | 31 | while(q.size()) { 32 | auto a = q.front(); 33 | q.pop(); 34 | for(auto n : m[a]) { 35 | if(parent[n] == -1) { 36 | parent[n] = a; 37 | dis[n] = dis[a] + 1; 38 | q.push(n); 39 | } else if(parent[a] != n) { 40 | ans = min(ans, dis[n] + dis[a] + 1); 41 | break; 42 | } 43 | } 44 | } 45 | 46 | } 47 | return ans == INT_MAX ? -1 : ans; 48 | 49 | } -------------------------------------------------------------------------------- /01. Graphs/04. CycleDetection/5. DetectCyclesin2DGrid.cpp: -------------------------------------------------------------------------------- 1 | bool dfs(int i, int j, vector>& v, vector>& grid, char c, int pi, int pj, int n, int m) { 2 | 3 | if(i < 0 || i >= n || j < 0 || j >= m || grid[i][j] != c) { 4 | return false; 5 | } 6 | //cout< dir = {1, 0, -1, 0, 1}; 10 | for(int k = 0; k < 4; k++) { 11 | if(i + dir[k] == pi && j + dir[k+1] ==pj) continue; 12 | if(dfs(i + dir[k], j + dir[k+1], v, grid, c, i, j, n, m)) return true; 13 | } 14 | return false; 15 | } 16 | bool containsCycle(vector>& grid) { 17 | int n=grid.size(),m=grid[0].size(); 18 | 19 | vector> v(n,vector(m,0)); 20 | for(int i = 0; i < n; i++) { 21 | for(int j = 0; j < m; j++) { 22 | if(v[i][j] == 0) 23 | if(dfs(i, j, v, grid, grid[i][j], -1, -1, n, m))return true; 24 | } 25 | } 26 | return false; 27 | } 28 | -------------------------------------------------------------------------------- /01. Graphs/04. CycleDetection/6. Maximum Employees to Be Invited to a Meeting.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | An amazing question and usecase of cycle detection. 4 | But here the graph is pretty simple one so we need not apply 5 | the cycle detection DFS. 6 | Rest we need to fist find and all all the 2 len cycles with 7 | their neighbouring chains 8 | then we can find the longest len cycle 9 | return maximum of both 10 | 11 | */ 12 | 13 | class Solution { 14 | public: 15 | int height(int n,vector&vis,vector> &reverseFav) { 16 | vis[n] = 1; 17 | int ans=1; 18 | for(auto a:reverseFav[n]) { 19 | if(vis[a]==0) 20 | ans=max(ans,1+height(a,vis,reverseFav)); 21 | } 22 | return ans; 23 | } 24 | int maximumInvitations(vector& fav) { 25 | int n = fav.size(); 26 | vector> reverseFav(n); 27 | for(int i=0;ivis1(n,0),vis2(n,0); 37 | int x = height(i,vis1,reverseFav); 38 | int y = height(fav[i],vis2,reverseFav); 39 | 40 | ans2LenCycle+=(x+y); 41 | } 42 | } 43 | 44 | vector vis(n,0); 45 | int maxLenCycle=0; 46 | 47 | for(int i=0;i findOrder(int numCourses, vector>& prerequisites) { 4 | vector orderedCourses; 5 | unordered_map> graph; 6 | vector inDegree(numCourses); 7 | for(auto prerequisite : prerequisites) { 8 | graph[prerequisite[1]].push_back(prerequisite[0]); 9 | inDegree[prerequisite[0]]++; 10 | } 11 | queue topoQueue; 12 | 13 | for(int i = 0; i < numCourses; i++) { 14 | if(inDegree[i] == 0) { 15 | topoQueue.push(i); 16 | } 17 | } 18 | while(topoQueue.size()) { 19 | auto course = topoQueue.front(); 20 | topoQueue.pop(); 21 | orderedCourses.push_back(course); 22 | for(auto nbr : graph[course]) { 23 | inDegree[nbr]--; 24 | if(inDegree[nbr] == 0)topoQueue.push(nbr); 25 | } 26 | } 27 | if(orderedCourses.size() < numCourses) { 28 | return {}; 29 | } 30 | return orderedCourses; 31 | } 32 | }; -------------------------------------------------------------------------------- /01. Graphs/05. Topological Sort/2. TopologicalDFS.cpp: -------------------------------------------------------------------------------- 1 | bool dfs(unordered_map> &graph, int node, vector &visited, vector& arrangedCourses, int& i, vector& family) { 2 | visited[node] = 1; 3 | family[node] = 1; 4 | for(int nbr : graph[node]) { 5 | if(family[nbr] == 1) { 6 | return true; 7 | } else if(visited[nbr] == 0) { 8 | if(dfs(graph, nbr, visited, arrangedCourses, i, family)) return true; 9 | } 10 | } 11 | arrangedCourses[i--] = node; 12 | family[node] = 0; 13 | return false; 14 | } 15 | 16 | vector findOrder(int numCourses, vector>& prerequisites) { 17 | 18 | unordered_map> graph; 19 | for(int i = 0; i < prerequisites.size(); i++) { 20 | graph[prerequisites[i][1]].push_back(prerequisites[i][0]); 21 | } 22 | vector visited(numCourses); 23 | vector arrangedCourses(numCourses); 24 | vector family(numCourses); 25 | int n = numCourses - 1; 26 | for(int i = 0; i < numCourses; i++) { 27 | if(visited[i] == 0) { 28 | if(dfs(graph, i, visited, arrangedCourses, n, family) == true) { 29 | return {}; 30 | } 31 | } 32 | } 33 | return arrangedCourses; 34 | } 35 | -------------------------------------------------------------------------------- /01. Graphs/05. Topological Sort/3. GameRoutes.cpp: -------------------------------------------------------------------------------- 1 | int gameRoutes(int n, vector> edges) 2 | { 3 | vector dp(n + 1), indeg(n + 1); 4 | dp[1] = 1; 5 | unordered_map> m1; 6 | 7 | for(auto e : edges) 8 | { 9 | indeg[e[1]]++; 10 | m1[e[0]].push_back(e[1]); 11 | 12 | } 13 | queue q; 14 | for(int i = 1; i <= n; i++) 15 | { 16 | if(!indeg[i]) 17 | { 18 | q.push(i); 19 | } 20 | } 21 | 22 | while(!q.empty()) 23 | { 24 | auto a = q.front(); 25 | q.pop(); 26 | 27 | for(auto b : m1[a]) 28 | { 29 | indeg[b]--; 30 | if(!indeg[b]) 31 | { 32 | q.push(b); 33 | } 34 | dp[b]+=dp[a]; 35 | dp[b]%=1000000007; 36 | } 37 | 38 | } 39 | 40 | return dp[n]; 41 | } -------------------------------------------------------------------------------- /01. Graphs/05. Topological Sort/4. LargestColorValueInADirectedGraph.cpp: -------------------------------------------------------------------------------- 1 | //DP + DAG 2 | 3 | bool dfs(string &colors, unordered_map>&g, vector &v, vector&bag,vector>& colourValue, int node,int& maxColorValue) { 4 | v[node] = 1; 5 | bag[node] = 1; 6 | colourValue[node][colors[node]-'a']=1; 7 | for(auto nbr : g[node]) { 8 | if(bag[nbr] == 1) { 9 | return true; 10 | } else if(v[nbr] == 0) { 11 | if(dfs(colors, g, v, bag, colourValue, nbr, maxColorValue))return true; 12 | 13 | 14 | } 15 | for(int i=0;i<26;i++) { 16 | 17 | colourValue[node][i] = max(colourValue[nbr][i] + (i==(colors[node]-'a')),colourValue[node][i]); 18 | maxColorValue=max(maxColorValue, colourValue[node][i]); 19 | } 20 | } 21 | 22 | bag[node] = 0; 23 | return false; 24 | } 25 | int largestPathValue(string colors, vector>& edges) { 26 | int n = colors.size(); 27 | vector visited(n); 28 | vector bag(n); 29 | vector> colourValue(n,vector(26,0)); 30 | int maxColorValue=1; 31 | unordered_map> m; 32 | for(auto a:edges) { 33 | m[a[0]].push_back(a[1]); 34 | } 35 | for(int i=0;irank[y]) { 25 | parent[y]=x; 26 | rank[x]++; 27 | } else { 28 | parent[x]=y; 29 | rank[y]++; 30 | } 31 | } 32 | 33 | int wtMst(int n, vector>& edges,int skipEdge,int compulsoryEdge) { 34 | 35 | rank = new int[n]; 36 | parent = new int[n]; 37 | for(int i=0;i> findCriticalAndPseudoCriticalEdges(int n, vector>& edges) { 62 | 63 | for(int i=0;i&a,vector&b)->bool{return a[2] critical,psudo_critical; 72 | 73 | for(int i=0;ioriginalMst) { 76 | critical.push_back(edges[i][3]); 77 | } else if(wtMst(n,edges,-1,i)==originalMst) { 78 | 79 | psudo_critical.push_back(edges[i][3]); 80 | } 81 | 82 | } 83 | return {critical,psudo_critical}; 84 | 85 | } -------------------------------------------------------------------------------- /01. Graphs/06. MST/2. Prims.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Notes: 3 | 1- No self loop or parelled edges 4 | 2- We try to connect all the nodes 5 | 3- We start by picking 1 node 6 | 4- Then we select the smallest edge from this node 7 | 5- Now we have 2 nodes 8 | 6- Now we select the min edge from these 2 nodes 9 | 7- This way we keep including nodes and covers up all nodes 10 | 8- In total we have V nodes and V-1 edges 11 | 9- We use adj list 12 | Time Complexity :- O((V+E)Log(V)) 13 | Space Complexity :- O(E+V) 14 | 15 | */ 16 | 17 | #include 18 | using namespace std; 19 | 20 | int minCostConnectPoints(vector>& points) { 21 | int V = points.size(); 22 | vector mst(V,0); 23 | vector key(V,INT_MAX); 24 | vector parent(V,-1); 25 | int ans=0; 26 | priority_queue> q; 27 | q.push({0,0}); 28 | key[0]=0; 29 | 30 | while(q.size()) { 31 | int u = q.top()[1]; 32 | mst[u]=1; 33 | q.pop(); 34 | 35 | for(int v=0;v rank[ele2]) { 27 | parent[ele2] = ele1; 28 | rank[ele1] += rank[ele2]; 29 | } else { 30 | parent[ele1] = ele2; 31 | rank[ele2] += rank[ele1]; 32 | } 33 | } 34 | }; -------------------------------------------------------------------------------- /01. Graphs/07. DSU/2. Redundant Connection II.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | either there are 2 indegree of a node or there will be a cycle or both 4 | 5 | so first find those 2 edges which are causing indegree as 2 6 | then we try to remove the later one to see that if skipping tht will avoid cycle or not, if yes then its the answer 7 | else second edge 8 | if we could not find edge 1 or 2 then return the edge which causes cycle 9 | 10 | 11 | */ 12 | 13 | 14 | class Solution { 15 | public: 16 | int *p,*r; 17 | int find(int x) { 18 | if(p[x]==x) return x; 19 | return p[x]=find(p[x]); 20 | } 21 | void unite(int x,int y) { 22 | x=find(x); 23 | y=find(y); 24 | if(x==y) return ; 25 | if(r[x]>r[y]) { 26 | p[y]=x; 27 | r[x]++; 28 | } else { 29 | p[x]=y; 30 | r[y]++; 31 | } 32 | } 33 | vector findRedundantDirectedConnection(vector>& edges) { 34 | int n = edges.size(); 35 | vector inDegree(n+1,-1); 36 | int rem1=-1,rem2=-1; 37 | for(int i=0;i e=edges[i]; 39 | if(inDegree[e[1]]!=-1) { 40 | rem2=i; 41 | rem1=inDegree[e[1]]; 42 | } 43 | inDegree[e[1]]=i; 44 | } 45 | 46 | p = new int[n+1]; 47 | r = new int [n+1]; 48 | for(int i=0;i>>&m,vector&dis) { 21 | dis[source]=0; 22 | priority_queue> q; 23 | q.push({0,source}); 24 | 25 | while(q.size()) { 26 | auto a=q.top(); 27 | q.pop(); 28 | ll u = a[1]; 29 | if(dis[u]w+dis[u]) { 34 | dis[v]=w+dis[u]; 35 | q.push({-dis[v],v}); 36 | } 37 | } 38 | } 39 | } 40 | long long minimumWeight(int n, vector>& edges, int src1, int src2, int dest) { 41 | map>> m,m1; 42 | for(auto &a:edges) { 43 | m[a[0]].push_back({a[1],a[2]}); 44 | m1[a[1]].push_back({a[0],a[2]}); 45 | } 46 | vector src1Dis(n,LONG_MAX),src2Dis(n,LONG_MAX),destDis(n,LONG_MAX); 47 | dij(src1,m,src1Dis); 48 | dij(src2,m,src2Dis); 49 | dij(dest,m1,destDis); 50 | ll ans=LONG_MAX; 51 | for(int i=0;i>& times, int n, int k) { 14 | vector dis(n+1,6000); 15 | dis[k]=0; 16 | int ans=INT_MIN; 17 | for(int i=0;idis[a[0]]+a[2]) { 20 | dis[a[1]]=dis[a[0]]+a[2]; 21 | } 22 | } 23 | } 24 | for(int i=1;i<=n;i++) { 25 | ans=max(ans,dis[i]); 26 | } 27 | return ans==6000?-1:ans; 28 | } 29 | }; -------------------------------------------------------------------------------- /01. Graphs/08. Shortest Paths Algo/3. FLoydWarshall.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TC O(V^3) 3 | SC O(N) 4 | Give us the min distance btw each pair 5 | */ 6 | 7 | for (int i = 1; i <= n; i++) { 8 | for (int j = 1; j <= n; j++) { 9 | if (i == j) distance[i][j] = 0; 10 | else if (adj[i][j]) distance[i][j] = adj[i][j]; 11 | else distance[i][j] = INF; 12 | } 13 | } 14 | 15 | 16 | for (int k = 1; k <= n; k++) { 17 | for (int i = 1; i <= n; i++) { 18 | for (int j = 1; j <= n; j++) { 19 | distance[i][j] = min(distance[i][j],distance[i][k]+distance[k][j]); 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /01. Graphs/09. StronglyConnected/1. Kosarju.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | TC O(E+V) 3 | SC O(E+V) 4 | 5 | 1- Apply DFS(same as in topo sort) and save outputs of this DSF and revserse it 6 | 2- take transpose of graph 7 | 3- Apply DFS on transpose of graph and find connected comp. 8 | 9 | */ 10 | 11 | 12 | class Solution 13 | { 14 | public: 15 | //Function to find number of strongly connected components in the graph. 16 | void dfs(int node,vector adj[],vector&visited,vector&topo) { 17 | visited[node]=1; 18 | for(auto a:adj[node]) { 19 | if(visited[a]==0) 20 | dfs(a,adj,visited,topo); 21 | } 22 | topo.push_back(node); 23 | } 24 | 25 | int kosaraju(int V, vector adj[]) 26 | { 27 | vector topo; 28 | vector visited(V); 29 | vector revAdj[V]; 30 | 31 | for(int i=0;i temp; 44 | int ans=0; 45 | for(int i=0;i1) { 23 | cout<<"Vertex "< 2 | using namespace std; 3 | #define int long long 4 | int help(int j,int last,int siz,vector&v,int x,int y,int n,int dp[1001][1001][2]) { 5 | if(j==v.size()&&sizy) return INT_MAX; 8 | 9 | if(dp[j][siz][last]!=-1)return dp[j][siz][last]; 10 | int black = v[j]; 11 | int white = n-v[j]; 12 | dp[j][siz][last] = INT_MAX; 13 | if(siz==0) { 14 | dp[j][siz][last]=min(white+help(j+1,1,1,v,x,y,n,dp),black+help(j+1,0,1,v,x,y,n,dp)); 15 | } else { 16 | 17 | dp[j][siz][last] = min(dp[j][siz][last],(last==1?white:black)+help(j+1,last,siz+1,v,x,y,n,dp)); 18 | 19 | if(siz>=x) 20 | { 21 | dp[j][siz][last] = min(dp[j][siz][last],(last==1?black:white)+help(j+1,1-last,1,v,x,y,n,dp)); 22 | } 23 | 24 | } 25 | 26 | return dp[j][siz][last]; 27 | 28 | 29 | 30 | } 31 | int32_t main() { 32 | int n,m,x,y; 33 | 34 | cin>>n>>m>>x>>y; 35 | vector v(m,0); 36 | for(int i=0;i>c; 40 | if(c=='#') v[j]++; 41 | } 42 | } 43 | int dp[1001][1001][2]; 44 | for(int i=0;i<1001;i++) { 45 | for(int j=0;j<1001;j++) { 46 | dp[i][j][0]=-1; 47 | dp[i][j][1]=-1; 48 | } 49 | } 50 | cout<>& grid,int n,int dp[50][50][50]) { 5 | if(i1>=n||j1>=n||i2>=n||j2>=n||grid[i1][j1]==-1||grid[i2][j2]==-1) return INT_MIN; 6 | if(dp[i1][j1][i2]!=-1)return dp[i1][j1][i2]; 7 | int ans=grid[i1][j1]+grid[i2][j2]; 8 | if(i1==i2&&j1==j2) { 9 | ans-=grid[i1][j1]; 10 | } 11 | if(i1==n-1&&j1==n-1) return grid[i1][j1]; 12 | if(i2==n-1&&j2==n-1) return grid[i2][j2]; 13 | return dp[i1][j1][i2]=ans+max({help1(i1+1,j1,i2+1,j2,grid,n,dp),help1(i1+1,j1,i2,j2+1,grid,n,dp),help1(i1,j1+1,i2+1,j2,grid,n,dp),help1(i1,j1+1,i2,j2+1,grid,n,dp)}); 14 | 15 | } 16 | int cherryPickup(vector>& grid) { 17 | int n=grid.size(); 18 | int dp[50][50][50]; 19 | for(int i=0;i<50;i++) { 20 | for(int j=0;j<50;j++) { 21 | for(int k=0;k<50;k++) dp[i][j][k]=-1; 22 | } 23 | } 24 | return max(0,help1(0,0,0,0,grid,n,dp)); 25 | } 26 | }; -------------------------------------------------------------------------------- /02. Dynamic Programming/3. Digit DP-MagicNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define int long long 4 | int mod = 1e9+7; 5 | int dp[2001][2001][2]; 6 | int func(string&v,int i,int cond,int d,int m,int rem) { 7 | 8 | if(i==v.size()) { 9 | 10 | return rem==0; 11 | } else { 12 | if(dp[i][rem][cond]!=-1) return dp[i][rem][cond]; 13 | int last; 14 | if(cond) last=9; 15 | else last = v[i]-'0'; 16 | int ans=0; 17 | for(int j=0;j<=last;j++) { 18 | int newCond=cond; 19 | if(j>m>>d; 35 | string a,b; 36 | cin>>a>>b; 37 | memset(dp,-1,sizeof dp); 38 | int ans=func(b,0,0,d,m,0); 39 | memset(dp,-1,sizeof dp); 40 | ans-=func(a,0,0,d,m,0); 41 | ans+=mod; 42 | ans%=mod; 43 | int flag=1; 44 | int rem=0; 45 | for(int i=0;i 2 | using namespace std; 3 | 4 | class SegmentTree { 5 | private: 6 | int siz; 7 | 8 | 9 | void buildSegmentTree(int startOfRange, int endOfRange, int indexOfSegmentTree, vector&v) { 10 | if(startOfRange == endOfRange) { 11 | segmentTreeArray[indexOfSegmentTree] = v[startOfRange]; 12 | return; 13 | } 14 | int mid = (startOfRange + endOfRange)/2; 15 | 16 | buildSegmentTree(startOfRange, mid, indexOfSegmentTree*2 + 1, v); 17 | buildSegmentTree(mid + 1, endOfRange, indexOfSegmentTree*2 + 2,v); 18 | 19 | segmentTreeArray[indexOfSegmentTree] = segmentTreeArray[indexOfSegmentTree*2 + 1] + segmentTreeArray[indexOfSegmentTree*2 + 2]; 20 | } 21 | 22 | int query(int startOfRange, int endOfRange, int indexOfSegmentTree, int l, int r) { 23 | if(endOfRange < l || startOfRange > r) { 24 | return 0; 25 | } 26 | 27 | if(startOfRange >= l && endOfRange <= r) { 28 | return segmentTreeArray[indexOfSegmentTree]; 29 | } 30 | 31 | int mid = (startOfRange + endOfRange)/2; 32 | int leftSide = query(startOfRange, mid, indexOfSegmentTree*2 + 1, l, r); 33 | int rightSide = query(mid+1, endOfRange, indexOfSegmentTree*2 + 2, l, r); 34 | return leftSide + rightSide; 35 | 36 | } 37 | 38 | void update(int startOfRange, int endOfRange, int indexOfSegmentTree, int index, int val) { 39 | if(startOfRange == endOfRange) { 40 | segmentTreeArray[indexOfSegmentTree] = val; 41 | return; 42 | } 43 | int mid = (startOfRange + endOfRange)/2; 44 | if(mid >= index) { 45 | update(startOfRange, mid, indexOfSegmentTree*2 + 1, index, val); 46 | } else { 47 | update(mid + 1, endOfRange, indexOfSegmentTree*2 + 2, index, val); 48 | } 49 | segmentTreeArray[indexOfSegmentTree] = segmentTreeArray[indexOfSegmentTree*2 +1] + segmentTreeArray[indexOfSegmentTree*2 +2]; 50 | } 51 | public: 52 | vector segmentTreeArray; 53 | SegmentTree(int siz):siz(siz) { 54 | segmentTreeArray.resize(siz*4); 55 | } 56 | 57 | void buildSegmentTree(vector&v) { 58 | buildSegmentTree(0, siz - 1, 0, v); 59 | } 60 | 61 | int query(int l, int r) { 62 | return query(0, siz - 1, 0, l, r); 63 | } 64 | 65 | void update(int index, int val) { 66 | update(0, siz - 1, 0, index, val); 67 | } 68 | }; 69 | 70 | int main() { 71 | vector v = {1, 2, 3, 4, 5}; 72 | SegmentTree segmentTree(5); 73 | segmentTree.buildSegmentTree(v); 74 | // for(auto a:segmentTree.segmentTreeArray) cout< 2 | using namespace std; 3 | 4 | class SegmentTree { 5 | private: 6 | 7 | int n; 8 | int build(int segIndex,int s,int e,vector&v) { 9 | if(s==e) { 10 | segmentTreeArray[segIndex] = v[s]; 11 | return 0; 12 | } 13 | int m = (s+e)/2; 14 | int level; 15 | level=build(segIndex*2+1,s,m,v); 16 | level=build(segIndex*2+2,m+1,e,v); 17 | if(level%2==0) 18 | segmentTreeArray[segIndex] = segmentTreeArray[segIndex*2+1] | segmentTreeArray[segIndex*2+2]; 19 | else segmentTreeArray[segIndex] = segmentTreeArray[segIndex*2+1] ^ segmentTreeArray[segIndex*2+2]; 20 | 21 | return level+1; 22 | } 23 | 24 | int update(int segIndex,int s,int e,int idx,int val) { 25 | if(s==e) { 26 | segmentTreeArray[segIndex] = val; 27 | return 0; 28 | } 29 | int m = (s+e)/2; 30 | int level; 31 | if(idx<=m) { 32 | level=update(segIndex*2+1,s,m,idx,val); 33 | } 34 | else { 35 | level=update(segIndex*2+2,m+1,e,idx,val); 36 | } 37 | if(level%2==0) 38 | segmentTreeArray[segIndex] = segmentTreeArray[segIndex*2+1] | segmentTreeArray[segIndex*2+2]; 39 | else segmentTreeArray[segIndex] = segmentTreeArray[segIndex*2+1] ^ segmentTreeArray[segIndex*2+2]; 40 | 41 | return level+1; 42 | 43 | } 44 | 45 | int query(int segIndex,int s,int e,int l,int r) { 46 | if(l>e||r=e) return segmentTreeArray[segIndex]; 48 | int m = (s+e)/2; 49 | int left = query(segIndex*2+1,s,m,l,r); 50 | int right = query(segIndex*2+2,m+1,e,l,r); 51 | return left+right; 52 | } 53 | 54 | public: 55 | vector segmentTreeArray; 56 | 57 | SegmentTree(int siz) { 58 | n=siz; 59 | segmentTreeArray.resize(4*n); 60 | } 61 | void build(vector&v) { 62 | build(0,0,n-1,v); 63 | } 64 | 65 | void update(int idx,int val) { 66 | update(0,0,n-1,idx,val); 67 | } 68 | 69 | int query(int l, int r) { 70 | return query(0,0,n-1,l,r); 71 | } 72 | 73 | }; 74 | 75 | 76 | int main() { 77 | int n,m; 78 | cin>>n>>m; 79 | SegmentTree segmentTree((1< v(1<>v[i]; 84 | } 85 | segmentTree.build(v); 86 | while(m--) { 87 | int p,b; 88 | cin>>p>>b; 89 | segmentTree.update(p-1,b); 90 | cout< 2 | 3 | #define int long long int 4 | 5 | using namespace std; 6 | 7 | const int p = 31, mod = 1e9 + 7; 8 | 9 | int poly_hash(string s) { 10 | int hash = 0; 11 | int p_power = 1; 12 | 13 | for (int i = 0; i < s.size(); i++) { 14 | hash += (s[i] - 'a' + 1) * p_power; 15 | p_power *= p; 16 | 17 | hash %= mod; 18 | p_power %= mod; 19 | } 20 | 21 | return hash; 22 | } 23 | 24 | int powr(int a, int b) { 25 | // (a^b)%mod 26 | int res = 1; 27 | while (b) { 28 | if (b & 1) res *= a; 29 | b /= 2; 30 | a *= a; 31 | 32 | a %= mod; 33 | res %= mod; 34 | } 35 | return res; 36 | } 37 | 38 | int inv(int x) { 39 | return powr(x, mod - 2); 40 | } 41 | 42 | int32_t main() { 43 | 44 | #ifndef ONLINE_JUDGE 45 | freopen("input.txt", "r", stdin); 46 | freopen("output.txt", "w", stdout); 47 | #endif 48 | 49 | string text = "ababbabbaba"; 50 | string pattern = "aba"; 51 | 52 | int pat_hash = poly_hash(pattern); 53 | 54 | int n = text.size(), m = pattern.size(); 55 | 56 | int text_hash = poly_hash(text.substr(0, m)); 57 | 58 | if (pat_hash == text_hash) { 59 | cout << 0 << '\n'; 60 | } 61 | 62 | 63 | for (int i = 1; i + m <= n; i++) { 64 | // remove last character 65 | text_hash = (text_hash - (text[i - 1] - 'a' + 1) + mod) % mod; 66 | 67 | text_hash = (text_hash * inv(p)) % mod; 68 | 69 | text_hash = (text_hash + (text[i + m - 1] - 'a' + 1) * powr(p, m - 1)) % mod; 70 | 71 | // cout << pat_hash << " " << text_hash << '\n'; 72 | 73 | if (text_hash == pat_hash) { 74 | cout << i << '\n'; 75 | } 76 | } 77 | 78 | return 0; 79 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 3-weeks-Google-Prep 2 | 3 | ## [How I Cracked my Dream Company GOOGLE](https://youtu.be/YlP7CWpHgS4) 4 | 5 | ## [For rest of the topics I reffered my DSA Sheet Questions](https://www.youtube.com/watch?v=NXQi_g1pVqI/) 6 | 7 | ### These are some selected questions apart from my DSA Sheet that I solved to prepare for my Google interviews 8 | 9 | - Graphs 10 | - 01. Representation 11 | - 1. [List.cpp](./01.%20Graphs/01.%20Representation/1.%20List.cpp) 12 | - 2. [Matrix.cpp](./01.%20Graphs/01.%20Representation/2.%20Matrix.cpp) 13 | - 02. BFS 14 | - 1. [Boredom.cpp](./01.%20Graphs/02.%20BFS/1.%20Boredom.cpp) 15 | - 2. [WordLadder2.cpp](./01.%20Graphs/02.%20BFS/2.%20WordLadder2.cpp) 16 | - 3. [MultiSourceBFS.cpp](./01.%20Graphs/02.%20BFS/3.%20MultiSourceBFS.cpp) 17 | - 4. [ValidBFS.cpp](./01.%20Graphs/02.%20BFS/4.%20ValidBFS.cpp) 18 | - 03. DFS 19 | - 1. [JourneyToTheMoon.cpp](./03.%20DFS/1.%20JourneyToTheMoon.cpp) 20 | - 2. [DFSwithStoppingCondition.cpp](./01.%20Graphs/03.%20DFS/2.%20DFSwithStoppingCondition.cpp) 21 | - 3. [ConnectedComponents.cpp](./03.%20DFS/3.%20ConnectedComponents.cpp) 22 | - 4. [ReconstructItinerary.cpp](./01.%20Graphs/03.%20DFS/4.%20ReconstructItinerary.cpp) 23 | - 04. CycleDetection 24 | - 1. [DetectCycleUnirectedGraph.cpp](./01.%20Graphs/04.%20CycleDetection/1.%20DetectCycleUndirectedGraph.cpp) 25 | - 2. [DetectCycleDirectedGraph.cpp](./01.%20Graphs/04.%20CycleDetection/2.%20DetectCycleDirectedGraph.cpp) 26 | - 3. [IsBipartite.cpp](./01.%20Graphs/04.%20CycleDetection/3.%20IsBipartite.cpp) 27 | - 4. [LengthOfSmallestCycle.cpp](./01.%20Graphs/04.%20CycleDetection/4.%20LengthOfSmallestCycle.cpp) 28 | - 5. [DetectCyclesin2DGrid.cpp](./01.%20Graphs/04.%20CycleDetection/5.%20DetectCyclesin2DGrid.cpp) 29 | - 6. [Maximum Employees to Be Invited to a Meeting.cpp](./01.%20Graphs/04.%20CycleDetection/6.%20Maximum%20Employees%20to%20Be%20Invited%20to%20a%20Meeting.cpp) 30 | - 05. Topological Sort 31 | - 1. [TopologicalBFS.cpp](./01.%20Graphs/05.%20Topological%20Sort/1.%20TopologicalBFS.cpp) 32 | - 2. [TopologicalDFS.cpp](./01.%20Graphs/05.%20Topological%20Sort/2.%20TopologicalDFS.cpp) 33 | - 3. [GameRoutes.cpp](./01.%20Graphs/05.%20Topological%20Sort/3.%20GameRoutes.cpp) 34 | - 4. [LargestColorValueInADirectedGraph.cpp](./01.%20Graphs/05.%20Topological%20Sort/4.%20LargestColorValueInADirectedGraph.cpp) 35 | - 06. MST 36 | - 1. [Kruskals.cpp](./01.%20Graphs/06.%20MST/1.%20Kruskals.cpp) 37 | - 2. [Prims.cpp](./01.%20Graphs/06.%20MST/2.%20Prims.cpp) 38 | - 07. DSU 39 | - 1. [DSUSnippetClass.cpp](./01.%20Graphs/07.%20DSU/1.%20DSUSnippetClass.cpp) 40 | - 2. [Redundant Connection II.cpp](./01.%20Graphs/07.%20DSU/2.%20Redundant%20Connection%20II.cpp) 41 | - 08. Shortest Paths Algo 42 | - 1. [Dijkstras.cpp](./01.%20Graphs/08.%20Shortest%20Paths%20Algo/1.%20Dijkstras.cpp) 43 | - 2. [BellmanFord.cpp](./01.%20Graphs/08.%20Shortest%20Paths%20Algo/2.%20BellmanFord.cpp) 44 | - 3. [FLoydWarshall.cpp](./01.%20Graphs/08.%20Shortest%20Paths%20Algo/3.%20FLoydWarshall.cpp) 45 | - 09. StronglyConnected 46 | - 1. [Kosarju.cpp](./01.%20Graphs/09.%20StronglyConnected/1.%20Kosarju.cpp) 47 | - 10. Articulation Point and Bridges 48 | - 1. [CutEdges.cpp](./01.%20Graphs/10.Articulation%20Point%20and%20Bridges/1.%20CutEdges.cpp) 49 | - 2. [CutVertex.cpp](./01.%20Graphs/10.Articulation%20Point%20and%20Bridges/2.%20CutVertex.cpp) 50 | - Readme.md 51 | - Dynamic Programming 52 | - 1. [Barcode.cpp](./02.%20Dynamic%20Programming/1.%20Barcode.cpp) 53 | - 2. [CherryPick.cpp](./02.%20Dynamic%20Programming/2.%20CherryPick.cpp) 54 | - 3. [Digit DP-MagicNumbers.cpp](./02.%20Dynamic%20Programming) 55 | - Readme.md 56 | - SegmentTree 57 | - 1. [SegmentTreeSnippetClass.cpp](./03.%20SegmentTree/1.%20SegmentTreeSnippetClass.cpp) 58 | - 2. [Xenia.cpp](./03.%20SegmentTree/2.%20Xenia.cpp) 59 | - Readme.md 60 | - Rolling hash 61 | - 1. [Rabin_carp.cpp](./04.%20Rolling%20hash/1.%20Rabin_carp.cpp) 62 | - Rest of the Topic 63 | - Readme.md 64 | - README.md 65 | 66 | ## BONUS ;) [Learn from me](https://www.youtube.com/c/LeadCodingbyFRAZ) 67 | -------------------------------------------------------------------------------- /Rest of the topics/Readme.md: -------------------------------------------------------------------------------- 1 | # [For the rest of the topics I referred my DSA Sheet Questions](https://www.youtube.com/watch?v=NXQi_g1pVqI/) 2 | --------------------------------------------------------------------------------