From b8e01df1a0679e8df59e6f19ff153faad58faa10 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Fri, 14 May 2021 23:41:54 +0530 Subject: [PATCH 01/75] Create Graphs --- Graphs | 1 + 1 file changed, 1 insertion(+) create mode 100644 Graphs diff --git a/Graphs b/Graphs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Graphs @@ -0,0 +1 @@ + From 363066ebf5b97be218e87d37ac0fe426d36f1590 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Fri, 14 May 2021 23:42:14 +0530 Subject: [PATCH 02/75] Delete Graphs --- Graphs | 1 - 1 file changed, 1 deletion(-) delete mode 100644 Graphs diff --git a/Graphs b/Graphs deleted file mode 100644 index 8b13789..0000000 --- a/Graphs +++ /dev/null @@ -1 +0,0 @@ - From f6443790fd7026b51f20dfc627af6724e080d7da Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Fri, 14 May 2021 23:43:01 +0530 Subject: [PATCH 03/75] Create Graphs --- Graphs | 1 + 1 file changed, 1 insertion(+) create mode 100644 Graphs diff --git a/Graphs b/Graphs new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Graphs @@ -0,0 +1 @@ + From 3b81b37f100c8008bec5b6f5939f3cb34c79288f Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Fri, 14 May 2021 23:43:25 +0530 Subject: [PATCH 04/75] Delete Graphs --- Graphs | 1 - 1 file changed, 1 deletion(-) delete mode 100644 Graphs diff --git a/Graphs b/Graphs deleted file mode 100644 index 8b13789..0000000 --- a/Graphs +++ /dev/null @@ -1 +0,0 @@ - From 6caa4e9e6a21832173a81c8a89d206f7da0e7826 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Fri, 14 May 2021 23:47:21 +0530 Subject: [PATCH 05/75] Create Dijkstra.cpp STL implementation for dijkstra --- Graphs/Dijkstra.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Graphs/Dijkstra.cpp diff --git a/Graphs/Dijkstra.cpp b/Graphs/Dijkstra.cpp new file mode 100644 index 0000000..66c563b --- /dev/null +++ b/Graphs/Dijkstra.cpp @@ -0,0 +1,55 @@ +// Prints shortest paths from src to all other vertices +void dijkstra(int src) +{ + // Create a priority queue to store vertices that + // are being preprocessed. This is weird syntax in C++. + // Refer below link for details of this syntax + // https://www.geeksforgeeks.org/implement-min-heap-using-stl/ + priority_queue< pair, vector > , greater> > pq; + + // Create a vector for distances and initialize all + // distances as infinite (INF) + vector dist(V, INF); + + // Insert source itself in priority queue and initialize + // its distance as 0. + pq.push(make_pair(0, src)); + dist[src] = 0; + + /* Looping till priority queue becomes empty (or all + distances are not finalized) */ + while (!pq.empty()) + { + // The first vertex in pair is the minimum distance + // vertex, extract it from priority queue. + // vertex label is stored in second of pair (it + // has to be done this way to keep the vertices + // sorted distance (distance must be first item + // in pair) + int u = pq.top().second; + pq.pop(); + + // 'i' is used to get all adjacent vertices of a vertex + for (auto &i:arr[u]) + { + // Get vertex label and weight of current adjacent + // of u. + int v = i.first; + int weight = i.second; + + // If there is shorted path to v through u. + if (dist[v] > dist[u] + weight) + { + // Updating distance of v + dist[v] = dist[u] + weight; + pq.push(make_pair(dist[v], v)); + } + } + } + + // Print shortest distances stored in dist[] + printf("Vertex Distance from Source\n"); + for (int i = 0; i < V; ++i) + printf("%d \t\t %d\n", i, dist[i]); +} + From b531080d50bc7d1e5d7279589e5b117a8c9b7cb6 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Fri, 14 May 2021 23:55:49 +0530 Subject: [PATCH 06/75] Create BellmanFord.cpp --- Graphs/BellmanFord.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Graphs/BellmanFord.cpp diff --git a/Graphs/BellmanFord.cpp b/Graphs/BellmanFord.cpp new file mode 100644 index 0000000..c10bb52 --- /dev/null +++ b/Graphs/BellmanFord.cpp @@ -0,0 +1,23 @@ +// Used for negative weights. +vector BellmanFord(int V,int src,vector>edges){ // {src,dest,weight} + vector dist(V,INT_MAX); // initialize to INT_MAX + dist[src]=0; //dist from src will be zero + for (int i = 1; i < V; i++) { + for (int j = 0; j < E; j++) { + int u = edges[i][0]; + int v = edges[i][1]; + int weight = edges[i][2]; + if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) + dist[v] = dist[u] + weight; + } + } + for(int i=0; i < E; i++){ + int u=edges[i][0]; + int v=edges[i][1]; + int w=edges[i][2]; + if(dist[u] != INT_MAX && dist[u] + w Date: Sat, 15 May 2021 00:02:07 +0530 Subject: [PATCH 07/75] Create FloydWarshall.cpp --- Graphs/FloydWarshall.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Graphs/FloydWarshall.cpp diff --git a/Graphs/FloydWarshall.cpp b/Graphs/FloydWarshall.cpp new file mode 100644 index 0000000..0e94642 --- /dev/null +++ b/Graphs/FloydWarshall.cpp @@ -0,0 +1,18 @@ +// to find the min. distances between all vertices of a graph +void FloydWarshall(vector>graph, int V){ + vectordp(V,vector(V,0)); + for(int i=0;i < V; i++){ + for(int j=0;j < V; j++){ + dp[i][j]=graph[i][j] + } + } + for(int k=0; k < V; k++){ + for(int i=0; i < V; i++){ + for(int j=0; j < V; j++){ + if(dp[i][k] != INT_MAX && dp[k][j] != INT_MAX && dp[i][k] + dp[k][j] < dp[i][j]){ + dp[i][j] = dp[i][k] + dp[k][j]; + } + } + } + } +} From e75daef13be03f576f8f5d7a78ff31729a4e3f3d Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 00:07:39 +0530 Subject: [PATCH 08/75] Update BellmanFord.cpp --- Graphs/BellmanFord.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphs/BellmanFord.cpp b/Graphs/BellmanFord.cpp index c10bb52..a7d990f 100644 --- a/Graphs/BellmanFord.cpp +++ b/Graphs/BellmanFord.cpp @@ -1,3 +1,4 @@ +// To find path from src to other vertices having min. sum of weights. // Used for negative weights. vector BellmanFord(int V,int src,vector>edges){ // {src,dest,weight} vector dist(V,INT_MAX); // initialize to INT_MAX From 30f19fdd94cbf4086e2ccfb16f9e4206a3baa003 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 00:20:26 +0530 Subject: [PATCH 09/75] Create Prims.cpp --- Graphs/Prims.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Graphs/Prims.cpp diff --git a/Graphs/Prims.cpp b/Graphs/Prims.cpp new file mode 100644 index 0000000..f30224a --- /dev/null +++ b/Graphs/Prims.cpp @@ -0,0 +1,29 @@ +// to find the MST of the graph. +void Prims(int V,vectorarr[]){ // arr[u] is {v,weight} + vectorinMST(V,false); + vectorkey(V,INT_MAX); + vectorparent(V,-1); + int src=0; + priority_queue< pair, vector> , greater> > pq; + pq.push({0,src}); + key[src]=0; + while(!pq.empty()){ + auto p = pq.top(); + pq.pop(); + int u = p.second; + inMST[u] = true; + for(auto &x:arr[u]){ + int v = x.first; + int w = x.second + if(!inMST[v] && key[v] > w){ + key[v] = w; + pq.push({key[v],v}); + parent[v] = u; + } + } + } + for(int i=1; i < V; i++){ + cout<< parent[i] << " " << i <<"\n"; + } + // key[] contains the weight attached with each vertex. to get the sum of weights of MST, just add all elements in key +} From a2b4aeeeb0957a01bb27200eb0a178fb46c6b8b9 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 00:30:37 +0530 Subject: [PATCH 10/75] Create Dfs.cpp --- Graphs/Dfs.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Graphs/Dfs.cpp diff --git a/Graphs/Dfs.cpp b/Graphs/Dfs.cpp new file mode 100644 index 0000000..83d6f75 --- /dev/null +++ b/Graphs/Dfs.cpp @@ -0,0 +1,19 @@ +// dfs algorithm +// arr[u] is of the form {v, weight} +// V -> vertices +void dfs(int u,vector&visited, vectorarr[]){ + visited[u] = true; + for(auto &x:arr[u]){ + if(!visited[x.first]){ + dfs(x.first,visited,arr); + } + } +} + +int main(){ + // to cover entire graph in case it is disconnected. + for(int i=0;i Date: Sat, 15 May 2021 00:30:56 +0530 Subject: [PATCH 11/75] Rename Dfs.cpp to DFS.cpp --- Graphs/{Dfs.cpp => DFS.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Graphs/{Dfs.cpp => DFS.cpp} (100%) diff --git a/Graphs/Dfs.cpp b/Graphs/DFS.cpp similarity index 100% rename from Graphs/Dfs.cpp rename to Graphs/DFS.cpp From 9b356914663c533d8f91114009383f440234285a Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 00:37:46 +0530 Subject: [PATCH 12/75] Create BFS.cpp --- Graphs/BFS.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Graphs/BFS.cpp diff --git a/Graphs/BFS.cpp b/Graphs/BFS.cpp new file mode 100644 index 0000000..4561fb8 --- /dev/null +++ b/Graphs/BFS.cpp @@ -0,0 +1,23 @@ +// BFS algo +// arr[u] is of the form {v,weight} +void BFS(int src,vectorarr[]){ + queueq; + q.push(src); + vectorvisited(V,false); + visited[src] = true; + while(!q.empty()){ + int u=q.front(); + q.pop(); + for(auto &x:arr[u]){ + int v = x.first; + if(!visited[v]){ + q.push(v); + } + } + } +} +for(int i = 0; i < V; i++){ + if(!visited[i]){ + BFS(i,arr); + } +} From cd4768e119c6e9d05f0b3f74a2e6e9f72b7a8b98 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 00:50:37 +0530 Subject: [PATCH 13/75] Create CycleDetection_DirectedGraph.cpp --- Graphs/CycleDetection_DirectedGraph.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Graphs/CycleDetection_DirectedGraph.cpp diff --git a/Graphs/CycleDetection_DirectedGraph.cpp b/Graphs/CycleDetection_DirectedGraph.cpp new file mode 100644 index 0000000..e48a185 --- /dev/null +++ b/Graphs/CycleDetection_DirectedGraph.cpp @@ -0,0 +1,15 @@ +void Cycle(int u,vector&visited,vectorarr[],vector&visited){ + if(!visited[u]){ + recstack[u] = true; + visited[u] = true; + for(auto &x:arr[u]){ + if(!visited[x] && Cycle(x,visited,arr,recstack)){ + return true; + } + else if(recstack[x]) + return true; + } + } + recstack[u] = false; + return false; +} From 10cb1586c61caebfc14e365fc6333647d966f663 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 00:53:51 +0530 Subject: [PATCH 14/75] Create CycleDetection_UndirectedGraph.cpp --- Graphs/CycleDetection_UndirectedGraph.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Graphs/CycleDetection_UndirectedGraph.cpp diff --git a/Graphs/CycleDetection_UndirectedGraph.cpp b/Graphs/CycleDetection_UndirectedGraph.cpp new file mode 100644 index 0000000..33cbb68 --- /dev/null +++ b/Graphs/CycleDetection_UndirectedGraph.cpp @@ -0,0 +1,14 @@ +void Cycle(int u,vectorarr[],vectorvisited,int p){ + visited[u] = true; + + for(auto &x:arr[u]){ + + if(!visited[x] && Cycle(x,arr,visited,u)) + return true; + + else if(x != p) // to check for back edge. + return true; + } +} + +// call - Cycle(0, arr, visited, -1); From b8a72e40861d1e46046ad73433a2ee95607ef91a Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 01:03:43 +0530 Subject: [PATCH 15/75] Create TopologicalSort.cpp --- Graphs/TopologicalSort.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Graphs/TopologicalSort.cpp diff --git a/Graphs/TopologicalSort.cpp b/Graphs/TopologicalSort.cpp new file mode 100644 index 0000000..66365f3 --- /dev/null +++ b/Graphs/TopologicalSort.cpp @@ -0,0 +1,16 @@ +// This yields the topological sort for the DAG arr[] +// vertex with indegree 0, 1, 2, and so on... +/* *****Applications****** + 1. Sorted dictionary of alien language. (popular question) + 2. Longest path problems for DAG. + 3. Add max edges so that no cycle is formed. +*/ +void Topo(stack&s,vector&visited,vectorarr[],int u){ + visited[u] = true; + for(auto &x:arr[u]){ + if(!visited[x]){ + Topo(s,visited,arr,x); + } + } + s.push(u); +} From 5e6cf977bb90d70c46817a4ca79d5e0851fb5c24 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 01:05:56 +0530 Subject: [PATCH 16/75] Create README.md --- Graphs/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 Graphs/README.md diff --git a/Graphs/README.md b/Graphs/README.md new file mode 100644 index 0000000..87dea00 --- /dev/null +++ b/Graphs/README.md @@ -0,0 +1 @@ +

Popular graph algorithms and problems (in cpp)

From 6f3b8a2fb81798f131a7c498787d278cb3e22fa4 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 01:30:55 +0530 Subject: [PATCH 17/75] Create LongestPathBtwAnyPairOfVert.cpp --- Graphs/LongestPathBtwAnyPairOfVert.cpp | 34 ++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Graphs/LongestPathBtwAnyPairOfVert.cpp diff --git a/Graphs/LongestPathBtwAnyPairOfVert.cpp b/Graphs/LongestPathBtwAnyPairOfVert.cpp new file mode 100644 index 0000000..4d2ab11 --- /dev/null +++ b/Graphs/LongestPathBtwAnyPairOfVert.cpp @@ -0,0 +1,34 @@ +//Method 1 - simple DFS O(V*(V+E)) +void LongestPath(int u, int sum, vector&visited, vectorarr[], int &ans){ + visited[src] = true; + int curr = 0; + for(auto &x:arr[u]){ + int v = x.first; + int w = x.second; + if(!visited[v]){ + curr = sum + w; + LongestPath(v, curr, visited, arr, ans); + } + ans=max(ans, curr); + } +} + +// Method 2- For a directed graph only O(V*(V+E)) +// Gives longest path between src and any other vertex +void LongestPath(int src){ + // create topological sort/ + vectordist(V,INT_MIN); + dist[src] = 0; + stacks; // s is the stack after topological sort + while(!s.empty()){ + int u = s.top(); + s.pop(); + for(auto &x:arr[u]){ + int v = x.first; + int w = x.second; + if(dist[v] < dist[u] + w){ + dist[v] = dist[u] + w; + } + } + } +} From 8204bafec71beb83652a2bcd76125a6d2478ef85 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 16:14:03 +0530 Subject: [PATCH 18/75] Create MotherVertex.cpp --- Graphs/MotherVertex.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Graphs/MotherVertex.cpp diff --git a/Graphs/MotherVertex.cpp b/Graphs/MotherVertex.cpp new file mode 100644 index 0000000..3baac92 --- /dev/null +++ b/Graphs/MotherVertex.cpp @@ -0,0 +1,25 @@ +// vertex from which we can access all other vertices. +void MotherVertex(){ + int v; + vectorarr[V]; // the graph + vectorvisited(V,false); + for(int i = 0; i < V; i++){ + dfs(i,visited,arr); + v = i; // candidate vertex + } + vectorvisited1(V,false); + dfs(v,visited1,arr); // dfs on candidate vertex + for(int i = 0; i < V;i++){ + if(!visited[i]) return -1; // check if there is any unvisited vertex. + } + return v; +} + +void dfs(int u, vector&visited,vectorarr[]){ + visited[u] = true; + for(auto &x : arr[u]){ + if(!visited[x]){ + dfs(x,visited,arr); + } + } +} From a019d84ba9daf425be31cf8d05621dc19894cfff Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 16:23:21 +0530 Subject: [PATCH 19/75] Create BipartiteGraph.cpp --- Graphs/BipartiteGraph.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Graphs/BipartiteGraph.cpp diff --git a/Graphs/BipartiteGraph.cpp b/Graphs/BipartiteGraph.cpp new file mode 100644 index 0000000..b0728d7 --- /dev/null +++ b/Graphs/BipartiteGraph.cpp @@ -0,0 +1,26 @@ +// to check if graph is bipartite +// also, check for self loops. graphs will not be bipartite in that case +// this algo uses bfs to check for bipartition +bool Bipartite(){ + queueq; + vectorcolor(V,-1); + for(int i = 0; i < V; i++){ + if(color[i] == -1){ + color[i] = 0; + q.push(i); + while(!q.empty()){ + int u = q.front(); + q.pop(); + for(auto &x:arr[u]){ + if(color[x] == -1){ + color[x] = 1-color[u]; + q.push(x); + } + else if (color[x] == color[u]) + return false; + } + } + } + } + return true; +} From 352a006c923dbc2776c193ed5660ddcfb42a9ee1 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 16:26:43 +0530 Subject: [PATCH 20/75] Update BipartiteGraph.cpp --- Graphs/BipartiteGraph.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphs/BipartiteGraph.cpp b/Graphs/BipartiteGraph.cpp index b0728d7..aa321c5 100644 --- a/Graphs/BipartiteGraph.cpp +++ b/Graphs/BipartiteGraph.cpp @@ -1,6 +1,7 @@ // to check if graph is bipartite // also, check for self loops. graphs will not be bipartite in that case // this algo uses bfs to check for bipartition +// A bipartite graph can never have a cycle of odd length. bool Bipartite(){ queueq; vectorcolor(V,-1); From 2844d9d6fbd9759021780d1180d0c4a4cc846892 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 16:43:27 +0530 Subject: [PATCH 21/75] Create DisjointSetUnion.cpp --- Graphs/DisjointSetUnion.cpp | 75 +++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Graphs/DisjointSetUnion.cpp diff --git a/Graphs/DisjointSetUnion.cpp b/Graphs/DisjointSetUnion.cpp new file mode 100644 index 0000000..eb51f75 --- /dev/null +++ b/Graphs/DisjointSetUnion.cpp @@ -0,0 +1,75 @@ +// Method 1 +// simply attach the subset of px to py. +int find(vector&parent, int x){ + if(parent[x] == -1){ + return x; + } + return parent[x] = find(parent,parent[x]); +} +void Union(int x, int y){ + int px = find(parent,x); + int py = find(parent,y); + parent[px] = py; +} +// If you want to check for cycle +int checkcycle(){ + for(int i = 0; i&parent,int x){ + if(parent[x] == -1){ + return x; + } + return parent[x] = find(parent,parent[x]); +} +int Union(){ + if(size[x] < size[y]){ + parent[x] = y; + } + else if(size[x] > size[y]){ + parent[y] = x; + } + else{ + parent[y] = x; + size[x] += size[y]; + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + From ee8c785a0f90af37276e0ef700fd2ac31dea61f1 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 16:55:09 +0530 Subject: [PATCH 22/75] Update DisjointSetUnion.cpp --- Graphs/DisjointSetUnion.cpp | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Graphs/DisjointSetUnion.cpp b/Graphs/DisjointSetUnion.cpp index eb51f75..d1d15fc 100644 --- a/Graphs/DisjointSetUnion.cpp +++ b/Graphs/DisjointSetUnion.cpp @@ -16,7 +16,7 @@ int checkcycle(){ for(int i = 0; i Date: Sat, 15 May 2021 17:27:03 +0530 Subject: [PATCH 23/75] Create Bridges.cpp --- Graphs/Bridges.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Graphs/Bridges.cpp diff --git a/Graphs/Bridges.cpp b/Graphs/Bridges.cpp new file mode 100644 index 0000000..cd9ab73 --- /dev/null +++ b/Graphs/Bridges.cpp @@ -0,0 +1,23 @@ +// Find edges which when removed disconnects the graph +// ans contains the edges +// low -> lowest point reached using dfs from that point +// disc -> time of discovery of that point +void Bridges(){ + time++; + low[u] = time; + disc[u] = time; + for(auto &v:arr[u]){ + if(!visited[v]){ + parent[v] = u; + Bridges() + low[u] = min(low[u], low[v]); + if(low[v] > disc[u]){ + ans.push_back({u,v}); + } + } + else if (v != parent[u] ){ + low[u] = min(low[u], disc[v]); + } + } + return ans; +} From 9d14fd62949993a529245a01c680dc5257bb9322 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 18:50:38 +0530 Subject: [PATCH 24/75] Create CutVertices.cpp --- Graphs/CutVertices.cpp | 81 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Graphs/CutVertices.cpp diff --git a/Graphs/CutVertices.cpp b/Graphs/CutVertices.cpp new file mode 100644 index 0000000..4340e6e --- /dev/null +++ b/Graphs/CutVertices.cpp @@ -0,0 +1,81 @@ +void Graph::APUtil(int u, bool visited[], int disc[], + int low[], int parent[], bool ap[]) +{ + + static int time = 0; + + // Count of children in DFS Tree + int children = 0; + + // Mark the current node as visited + visited[u] = true; + + // Initialize discovery time and low value + disc[u] = low[u] = ++time; + + // Go through all vertices aadjacent to this + list::iterator i; + for (i = adj[u].begin(); i != adj[u].end(); ++i) + { + int v = *i; // v is current adjacent of u + + // If v is not visited yet, then make it a child of u + // in DFS tree and recur for it + if (!visited[v]) + { + children++; + parent[v] = u; + APUtil(v, visited, disc, low, parent, ap); + + // Check if the subtree rooted with v has a connection to + // one of the ancestors of u + low[u] = min(low[u], low[v]); + + // u is an articulation point in following cases + + // (1) u is root of DFS tree and has two or more chilren. + if (parent[u] == NIL && children > 1) + ap[u] = true; + + // (2) If u is not root and low value of one of its child is more + // than discovery value of u. + if (parent[u] != NIL && low[v] >= disc[u]) + ap[u] = true; + } + + // Update low value of u for parent function calls. + else if (v != parent[u]) + low[u] = min(low[u], disc[v]); + } +} + +// The function to do DFS traversal. It uses recursive function APUtil() +void Graph::AP() +{ + // Mark all the vertices as not visited + bool *visited = new bool[V]; + int *disc = new int[V]; + int *low = new int[V]; + int *parent = new int[V]; + bool *ap = new bool[V]; // To store articulation points + + // Initialize parent and visited, and ap(articulation point) arrays + for (int i = 0; i < V; i++) + { + parent[i] = NIL; + visited[i] = false; + ap[i] = false; + } + + // Call the recursive helper function to find articulation points + // in DFS tree rooted with vertex 'i' + for (int i = 0; i < V; i++) + if (visited[i] == false) + APUtil(i, visited, disc, low, parent, ap); + + // Now ap[] contains articulation points, print them + for (int i = 0; i < V; i++) + if (ap[i] == true) + cout << i << " "; +} + From 23cd7fa44e54408532f504401ca4e1f001aee31b Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sat, 15 May 2021 21:10:53 +0530 Subject: [PATCH 25/75] Update README.md --- Graphs/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphs/README.md b/Graphs/README.md index 87dea00..9e48c58 100644 --- a/Graphs/README.md +++ b/Graphs/README.md @@ -1 +1,2 @@

Popular graph algorithms and problems (in cpp)

+Algos on flow not included for now From 0e12c3575a26ed2d2787b5bdf2ae46ae5b1e3b84 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Sun, 16 May 2021 12:18:24 +0530 Subject: [PATCH 26/75] Update LongestPathBtwAnyPairOfVert.cpp --- Graphs/LongestPathBtwAnyPairOfVert.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Graphs/LongestPathBtwAnyPairOfVert.cpp b/Graphs/LongestPathBtwAnyPairOfVert.cpp index 4d2ab11..fa0104b 100644 --- a/Graphs/LongestPathBtwAnyPairOfVert.cpp +++ b/Graphs/LongestPathBtwAnyPairOfVert.cpp @@ -1,3 +1,4 @@ +//change weight to -w for shortest path //Method 1 - simple DFS O(V*(V+E)) void LongestPath(int u, int sum, vector&visited, vectorarr[], int &ans){ visited[src] = true; From 1383245d5342837a05fb304297bae61b9edb1fa9 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Tue, 18 May 2021 13:59:24 +0530 Subject: [PATCH 27/75] Create LongestCommonSubsequence.cpp DP folder --- .../LongestCommonSubsequence.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 DynamicProgramming/LongestCommonSubsequence.cpp diff --git a/DynamicProgramming/LongestCommonSubsequence.cpp b/DynamicProgramming/LongestCommonSubsequence.cpp new file mode 100644 index 0000000..5712103 --- /dev/null +++ b/DynamicProgramming/LongestCommonSubsequence.cpp @@ -0,0 +1,18 @@ +void LCS(string a,string b){ + int n = a.size(); + int m = b.size(); + vector>dp(n+1,vector(m+1,)); + for(int i = 0;i <= n;i++){ + for(int j = 0; j <= m;j++){ + if(i == 0 || j == 0){ + dp[i][j] = 0; + } + else if(a[i - 1] == b[j - 1]){ + dp[i][j] = dp[i-1][j-1] + 1; + } + else + dp[i][j] = max(dp[i-1][j], dp[i][j-1]); + } + } + return dp[n][m]; +} From 5d3247240c15f7f6a62660970ebdf86fb2baa95c Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:02:07 +0530 Subject: [PATCH 28/75] Create LongestPalindromicSubsequence.cpp --- .../LongestPalindromicSubsequence.cpp | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DynamicProgramming/LongestPalindromicSubsequence.cpp diff --git a/DynamicProgramming/LongestPalindromicSubsequence.cpp b/DynamicProgramming/LongestPalindromicSubsequence.cpp new file mode 100644 index 0000000..4bbe3a3 --- /dev/null +++ b/DynamicProgramming/LongestPalindromicSubsequence.cpp @@ -0,0 +1,30 @@ +int Solution::solve(string A) { + vector>dp(A.size(),vector(A.size(),0)); + int res=1; + for(int i=0;i Date: Wed, 19 May 2021 10:07:02 +0530 Subject: [PATCH 29/75] Create EditDistance.cpp --- DynamicProgramming/EditDistance.cpp | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DynamicProgramming/EditDistance.cpp diff --git a/DynamicProgramming/EditDistance.cpp b/DynamicProgramming/EditDistance.cpp new file mode 100644 index 0000000..d79155e --- /dev/null +++ b/DynamicProgramming/EditDistance.cpp @@ -0,0 +1,34 @@ +/* +Given two strings A and B, find the minimum number of steps required to convert A to B. (each operation is counted as 1 step.) + +You have the following 3 operations permitted on a word: + +Insert a character +Delete a character +Replace a character +*/ +int Solution::minDistance(string A, string B) { + int n=A.size(); + int m=B.size(); + vector>dp(n+1,vector(m+1,INT_MAX)); + for(int i=0;i<=n;i++) + { + for(int j=0;j<=m;j++) + { + if(i==0 || j==0) + { + if(i==0) dp[i][j]=j; // need to delete all char of one string to make it equal to 0 + else dp[i][j]=i; // need to insert... + } + else if(A[i-1]==B[j-1]) + { + dp[i][j]=dp[i-1][j-1]; // same char. no need of operation + } + else + { + dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1])); + } + } + } + return dp[n][m]; +} From 0ff12835a1ae0e098f1762de80bac38732a664d8 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:08:26 +0530 Subject: [PATCH 30/75] Create RepeatingSubsequence.cpp --- DynamicProgramming/RepeatingSubsequence.cpp | 34 +++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DynamicProgramming/RepeatingSubsequence.cpp diff --git a/DynamicProgramming/RepeatingSubsequence.cpp b/DynamicProgramming/RepeatingSubsequence.cpp new file mode 100644 index 0000000..967de29 --- /dev/null +++ b/DynamicProgramming/RepeatingSubsequence.cpp @@ -0,0 +1,34 @@ +/* +Given a string A, find length of the longest repeating sub-sequence such that the two subsequence don’t have same string character at same position, + +i.e., any i’th character in the two subsequences shouldn’t have the same index in the original string. + +NOTE: Sub-sequence length should be greater than or equal to 2 +*/ +int Solution::anytwo(string A) { + vector>dp(A.size()+1,vector(A.size()+1,0)); + int res=-1; + for(int i=0;i<=A.size();i++) + { + for(int j=0;j<=A.size();j++) + { + dp[i][j]=0; + } + } + for(int i=1;i<=A.size();i++) + { + for(int j=1;j<=A.size();j++) + { + if(A[i-1]==A[j-1] && i!=j) + { + dp[i][j]=dp[i-1][j-1]+1; + } + else + { + dp[i][j]=max(dp[i-1][j],dp[i][j-1]); + } + } + } + if(dp[A.size()][A.size()]>=2) return 1; + return 0; +} From 2f63c62be719f58e03920f757273dd0b3a2b528d Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:10:56 +0530 Subject: [PATCH 31/75] Create DistinctSubsequences.cpp --- DynamicProgramming/DistinctSubsequences.cpp | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 DynamicProgramming/DistinctSubsequences.cpp diff --git a/DynamicProgramming/DistinctSubsequences.cpp b/DynamicProgramming/DistinctSubsequences.cpp new file mode 100644 index 0000000..b552bdd --- /dev/null +++ b/DynamicProgramming/DistinctSubsequences.cpp @@ -0,0 +1,32 @@ +/* +Given two sequences A, B, count number of unique ways in sequence A, to form a subsequence that is identical to the sequence B. +*/ + +int Solution::numDistinct(string A, string B) { + int n=A.size(); + int m=B.size(); + vector>dp(n+1,vector(m+1,0)); + for(int i=0;i<=n;i++) + { + dp[i][0]=1; + } + for(int i=1;i<=m;i++) + { + dp[0][i]=0; + } + for(int i=1;i<=n;i++) + { + for(int j=1;j<=m;j++) + { + if(A[i-1]==B[j-1]) + { + dp[i][j]=dp[i-1][j]+dp[i-1][j-1]; + } + else + { + dp[i][j]=dp[i-1][j]; + } + } + } + return dp[n][m]; +} From 88908e78be5d49b960bea5e84d198cbf7a401c18 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:12:05 +0530 Subject: [PATCH 32/75] Create InterleavingStrings.cpp --- DynamicProgramming/InterleavingStrings.cpp | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 DynamicProgramming/InterleavingStrings.cpp diff --git a/DynamicProgramming/InterleavingStrings.cpp b/DynamicProgramming/InterleavingStrings.cpp new file mode 100644 index 0000000..987c23c --- /dev/null +++ b/DynamicProgramming/InterleavingStrings.cpp @@ -0,0 +1,42 @@ +//Given A, B, C, find whether C is formed by the interleaving of A and B. + +int Solution::isInterleave(string A, string B, string C) { + int n=A.size(); + int m=B.size(); + vector>dp(n+1,vector(m+1,false)); + for(int i=0;i<=n;i++) + { + for(int j=0;j<=m;j++) + { + if(i==0 && j==0) + { + dp[i][j]=true; + } + else if(i==0) + { + if(B[j-1]==C[i+j-1]) + dp[i][j]=dp[i][j-1]; + } + else if(j==0) + { + if(A[i-1]==C[i+j-1]) + { + dp[i][j]=dp[i-1][j]; + } + } + else if(A[i-1]==C[i+j-1] && B[j-1]!=C[i+j-1]) + { + dp[i][j]=dp[i-1][j]; + } + else if(B[j-1]==C[i+j-1] && A[i-1]!=C[i+j-1]) + { + dp[i][j]=dp[i][j-1]; + } + else if(C[i+j-1]==B[j-1] && C[i+j-1]==A[i-1]) + { + dp[i][j]=dp[i-1][j] || dp[i][j-1]; + } + } + } + return dp[n][m]; +} From 4eb03c50de42ed35102ae5bfbd3d95dba6b4cdcd Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:13:40 +0530 Subject: [PATCH 33/75] Create RegularExpressions.cpp --- DynamicProgramming/RegularExpressions.cpp | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DynamicProgramming/RegularExpressions.cpp diff --git a/DynamicProgramming/RegularExpressions.cpp b/DynamicProgramming/RegularExpressions.cpp new file mode 100644 index 0000000..e7c3edc --- /dev/null +++ b/DynamicProgramming/RegularExpressions.cpp @@ -0,0 +1,34 @@ +/*Implement wildcard pattern matching with support for ‘?’ and ‘*’ for strings A and B. + +’?’ : Matches any single character. +‘*’ : Matches any sequence of characters (including the empty sequence). +The matching should cover the entire input string (not partial).*/ + +int Solution::isMatch(const string A, const string B) { + int n=A.size(); + int m=B.size(); + vector>dp(n+1,vector(m+1,false)); + dp[0][0]=true; + for(int i=1;i<=m;i++) + { + if(B[i-1]=='*') + { + dp[0][i]=dp[0][i-1]; + } + } + for(int i=1;i<=n;i++) + { + for(int j=1;j<=m;j++) + { + if(B[j-1]=='*') + { + dp[i][j]=dp[i][j-1] || dp[i-1][j]; + } + else if(B[j-1]=='?' || A[i-1]==B[j-1]) + { + dp[i][j]=dp[i-1][j-1]; + } + } + } + return dp[n][m]; +} From 0fec375b10fad0ce77acfd1881612d39c3d7d6af Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:16:05 +0530 Subject: [PATCH 34/75] Create ScrambleString.cpp --- DynamicProgramming/ScrambleString.cpp | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 DynamicProgramming/ScrambleString.cpp diff --git a/DynamicProgramming/ScrambleString.cpp b/DynamicProgramming/ScrambleString.cpp new file mode 100644 index 0000000..d64290d --- /dev/null +++ b/DynamicProgramming/ScrambleString.cpp @@ -0,0 +1,81 @@ +/* +Given a string A, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively. + +Below is one possible representation of A = “great”: + + + great + / \ + gr eat + / \ / \ +g r e at + / \ + a t + +To scramble the string, we may choose any non-leaf node and swap its two children. + +For example, if we choose the node “gr” and swap its two children, it produces a scrambled string “rgeat”. + + rgeat + / \ + rg eat + / \ / \ +r g e at + / \ + a t +We say that “rgeat” is a scrambled string of “great”. + +Similarly, if we continue to swap the children of nodes “eat” and “at”, it produces a scrambled string “rgtae”. + + rgtae + / \ + rg tae + / \ / \ +r g ta e + / \ + t a +We say that “rgtae” is a scrambled string of “great”. + +Given two strings A and B of the same length, determine if B is a scrambled string of S. +*/ + +mapmp; +int Solution::isScramble(const string a, const string b) { + string key = a + " " + b; + if(mp.find(key)!=mp.end()) + return mp[key]; + + if(a==b) + return true; + + if(a.length()<=1) + return false; + + int n=a.length(); + + for(int i=1;i<=n-1;i++) + { + string A1 = a.substr(0,i); + string A2 = a.substr(i,n-i); + string B11 = b.substr(0,i); + string B12 = b.substr(i,n-i); + string B21 = b.substr(0,n-i); + string B22 = b.substr(n-i,i); + + int cont1 = mp[A1+" "+B11] = (mp.find(A1+" "+B11)!=mp.end() ? mp[A1+" "+B11] : isScramble(A1,B11)); + int cont2 = mp[A2+" "+B12] = (mp.find(A2+" "+B12)!=mp.end() ? mp[A2+" "+B12] : isScramble(A2,B12)); + int cont3 = mp[A1+" "+B22] = (mp.find(A1+" "+B22)!=mp.end() ? mp[A1+" "+B22] : isScramble(A1,B22)); + int cont4 = mp[A2+" "+B21] = (mp.find(A2+" "+B21)!=mp.end() ? mp[A2+" "+B21] : isScramble(A2,B21)); + if ((cont1 && cont2) || (cont3 && cont4)) + { + return mp[key]=true; + } + } + return mp[key]=false; +} + + + + + + From 278056d7326fc106ba57ad86a04d29a473549bc2 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:24:46 +0530 Subject: [PATCH 35/75] Create FlipArray.cpp --- DynamicProgramming/FlipArray.cpp | 37 ++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 DynamicProgramming/FlipArray.cpp diff --git a/DynamicProgramming/FlipArray.cpp b/DynamicProgramming/FlipArray.cpp new file mode 100644 index 0000000..b839fcb --- /dev/null +++ b/DynamicProgramming/FlipArray.cpp @@ -0,0 +1,37 @@ +/* +Given an array of positive elements, you have to flip the sign of some of its elements such that the resultant sum of the elements of array should be minimum non-negative(as close to zero as possible). Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is minimum non-negative. +*/ +int Solution::solve(const vector &A) { +int n = A.size(); +int sumv = 0; +for(int i=0;i > dp(n+1,vector(req+1,INT_MAX)); +dp[0][0] = 0; +for(int i=0;i<=n;i++) +{ + dp[i][0] = 0; +} +for(int i=1;i<=n;i++) +{ + for(int j=1;j<=req;j++) + { + int a=INT_MAX; + int b; + if(j>=A[i-1]) + { + a = dp[i-1][j-A[i-1]]; + if(a!=INT_MAX) a+=1; + } + b = dp[i-1][j]; + dp[i][j] = min(a,b); + } +} +for(int i=req;i>=0;i--){ + if(dp[n][i]!=INT_MAX){ + return dp[n][i]; + } +} +} From 06ee3ac3f482fd1cc432e126461fcac3b828dc32 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:26:10 +0530 Subject: [PATCH 36/75] Create 01Knapsack.cpp --- DynamicProgramming/01Knapsack.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 DynamicProgramming/01Knapsack.cpp diff --git a/DynamicProgramming/01Knapsack.cpp b/DynamicProgramming/01Knapsack.cpp new file mode 100644 index 0000000..378c780 --- /dev/null +++ b/DynamicProgramming/01Knapsack.cpp @@ -0,0 +1,29 @@ +/* +Given two integer arrays A and B of size N each which represent values and weights associated with N items respectively. + +Also given an integer C which represents knapsack capacity. + +Find out the maximum value subset of A such that sum of the weights of this subset is smaller than or equal to C. + +NOTE: +You cannot break an item, either pick the complete item, or don’t pick it (0-1 property). +*/ +int Solution::solve(vector &A, vector &B, int C) { + int n=A.size(); + int m=B.size(); + vector>dp(n+1,vector(C+1,0)); + for(int i=1;i<=n;i++)dp[i][0]=0; + for(int i=1;i<=C;i++) dp[0][i]=0; + for(int i=1;i<=n;i++) + { + for(int j=1;j<=C;j++) + { + dp[i][j]=dp[i-1][j]; + if(j>=B[i-1]) + { + dp[i][j]=max(dp[i][j], A[i-1] +dp[i-1][j-B[i-1]]); + } + } + } + return dp[n][C]; +} From f64d6ccc7c74a5807150e1dda9c4b63d42f6fcf1 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:27:50 +0530 Subject: [PATCH 37/75] Create TusharsBirthday.cpp --- DynamicProgramming/TusharsBirthday.cpp | 37 ++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 DynamicProgramming/TusharsBirthday.cpp diff --git a/DynamicProgramming/TusharsBirthday.cpp b/DynamicProgramming/TusharsBirthday.cpp new file mode 100644 index 0000000..138291f --- /dev/null +++ b/DynamicProgramming/TusharsBirthday.cpp @@ -0,0 +1,37 @@ +/* +As it is Tushar’s Birthday on March 1st, he decided to throw a party to all his friends at TGI Fridays in Pune. +Given are the eating capacity of each friend, filling capacity of each dish and cost of each dish. A friend is satisfied if the sum of the filling capacity of dishes he ate is equal to his capacity. Find the minimum cost such that all of Tushar’s friends are satisfied (reached their eating capacity). + +NOTE: + +Each dish is supposed to be eaten by only one person. Sharing is not allowed. +Each friend can take any dish unlimited number of times. +There always exists a dish with filling capacity 1 so that a solution always exists. +*/ +int Solution::solve(const vector &a, const vector &b, const vector &c) { +int maxi = *max_element(a.begin(),a.end()); + vector >dp(b.size()+1,vector(maxi+1,INT_MAX)); + for(int i=0;i<=b.size();i++){ + dp[i][0] = 0; + } + for(int i=1;i<=maxi;i++){ + if(i % b[0] == 0){ + dp[1][i] = (i/b[0])*c[0]; + } +} + for(int i=2;i<=b.size();i++){ + for(int j=1;j<=maxi;j++){ + if(b[i-1] > j){ + dp[i][j] = dp[i-1][j]; + } + else { + dp[i][j] = min(dp[i-1][j],min((c[i-1]+dp[i-1][j-b[i-1]]),(c[i-1]+dp[i][j-b[i-1]]))); + } + } +} + int sum=0; + for(int i=0;i Date: Wed, 19 May 2021 10:33:24 +0530 Subject: [PATCH 38/75] Create MaxSumPathInTree.cpp --- DynamicProgramming/MaxSumPathInTree.cpp | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 DynamicProgramming/MaxSumPathInTree.cpp diff --git a/DynamicProgramming/MaxSumPathInTree.cpp b/DynamicProgramming/MaxSumPathInTree.cpp new file mode 100644 index 0000000..57aad43 --- /dev/null +++ b/DynamicProgramming/MaxSumPathInTree.cpp @@ -0,0 +1,32 @@ +/* +Given a binary tree T, find the maximum path sum. +The path may start and end at any node in the tree. +*/ + + + + + +/** + * Definition for binary tree + * struct TreeNode { + * int val; + * TreeNode *left; + * TreeNode *right; + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} + * }; + */ + int help(TreeNode* A,int &ans){ + if(!A) return 0; + int l=help(A->left,ans); + int r=help(A->right,ans); + int sum=max(max(l,r)+A->val,A->val); + int max_top=max(sum,l+r+A->val); + ans=max(ans,max_top); + return sum; + } +int Solution::maxPathSum(TreeNode* A) { + int ans=INT_MIN; + help(A,ans); + return ans; +} From c946ccfee6be6f6904cb87985114b054c92b0285 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:41:17 +0530 Subject: [PATCH 39/75] Create WordBreak.cpp --- DynamicProgramming/WordBreak.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DynamicProgramming/WordBreak.cpp diff --git a/DynamicProgramming/WordBreak.cpp b/DynamicProgramming/WordBreak.cpp new file mode 100644 index 0000000..60457cc --- /dev/null +++ b/DynamicProgramming/WordBreak.cpp @@ -0,0 +1,30 @@ +/* +Given a string A and a dictionary of words B, determine if A can be segmented into a space-separated sequence of one or more dictionary words. +*/ +int Solution::wordBreak(string A, vector &B) { + int n=A.size(); + vectordp(A.size()+1,false); + dp[n]=true; + mapm; + for(int i=0;i=0;i--) + { + string temp; + for(int j=i;j Date: Wed, 19 May 2021 10:44:33 +0530 Subject: [PATCH 40/75] Create PalindromePartition.cpp --- DynamicProgramming/PalindromePartition.cpp | 46 ++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 DynamicProgramming/PalindromePartition.cpp diff --git a/DynamicProgramming/PalindromePartition.cpp b/DynamicProgramming/PalindromePartition.cpp new file mode 100644 index 0000000..29f50f5 --- /dev/null +++ b/DynamicProgramming/PalindromePartition.cpp @@ -0,0 +1,46 @@ +/*Given a string A, partition A such that every substring of the partition is a palindrome. + +Return the minimum cuts needed for a palindrome partitioning of A.*/ +int Solution::minCut(string s) { + int n=s.size(); + vectorc(n,INT_MAX); + vector>p(n,vector(n,0)); + for(int i=0;i Date: Wed, 19 May 2021 10:47:30 +0530 Subject: [PATCH 41/75] Create UniqueBinarySearchTrees.cpp --- .../UniqueBinarySearchTrees.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 DynamicProgramming/UniqueBinarySearchTrees.cpp diff --git a/DynamicProgramming/UniqueBinarySearchTrees.cpp b/DynamicProgramming/UniqueBinarySearchTrees.cpp new file mode 100644 index 0000000..0825996 --- /dev/null +++ b/DynamicProgramming/UniqueBinarySearchTrees.cpp @@ -0,0 +1,22 @@ +/*Given an integer A, how many structurally unique BST’s (binary search trees) exist that can store values */ +// Catalan Number uses. +/* +1. Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()). +2. Count the number of possible Binary Search Trees with n keys (See this) +3. Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves. +4. Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect. +*/ +int Solution::numTrees(int A) { + int n=A; + vectordp(n+1,0); + dp[0]=1; + dp[1]=1; + for(int i=2;i<=A;i++) + { + for(int j=0;j Date: Wed, 19 May 2021 10:52:13 +0530 Subject: [PATCH 42/75] Create TilingWithDominos.cpp --- DynamicProgramming/TilingWithDominos.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 DynamicProgramming/TilingWithDominos.cpp diff --git a/DynamicProgramming/TilingWithDominos.cpp b/DynamicProgramming/TilingWithDominos.cpp new file mode 100644 index 0000000..3bfed71 --- /dev/null +++ b/DynamicProgramming/TilingWithDominos.cpp @@ -0,0 +1,20 @@ +/*Problem Description + +Given an integer A you have to find the number of ways to fill a 3 x A board with 2 x 1 dominoes. + +Return the answer modulo 109 + 7 . + +*/ +int Solution::solve(int A) +{ + if(A%2) return 0; + vector a(A+1, 0), c(A+1,0); + a[1]=1, c[1]=0, a[2]=0, c[2]=3; + + for(int i=3;i<=A;i++) + { + c[i]=(2*a[i-1]+c[i-2])%1000000007; + a[i]=(c[i-1]+a[i-2])%1000000007; + } + return c[A]; +} From c5ff1aa10a726b8f63e8c41c14c5a8e4f3f4d190 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:53:18 +0530 Subject: [PATCH 43/75] Create SubsetSum.cpp --- DynamicProgramming/SubsetSum.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 DynamicProgramming/SubsetSum.cpp diff --git a/DynamicProgramming/SubsetSum.cpp b/DynamicProgramming/SubsetSum.cpp new file mode 100644 index 0000000..c97320d --- /dev/null +++ b/DynamicProgramming/SubsetSum.cpp @@ -0,0 +1,24 @@ +int Solution::solve(vector &A, int B) { + int n=A.size(); + vector>dp(n+1,vector(B+1,false)); + for(int i=1;i<=B;i++) + { + dp[0][i]=false; + } + for(int i=0;i<=n;i++) + { + dp[i][0]=true; + } + for(int i=1;i<=n;i++) + { + for(int j=1;j<=B;j++) + { + dp[i][j]=dp[i-1][j]; + if(j>=A[i-1]) + { + dp[i][j]=dp[i][j]||dp[i-1][j-A[i-1]]; + } + } + } + return dp[n][B]; +} From 5dfe84f50d55e04aa4a21443a5970407847b66df Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:54:43 +0530 Subject: [PATCH 44/75] Create PaintHouse.cpp --- DynamicProgramming/PaintHouse.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 DynamicProgramming/PaintHouse.cpp diff --git a/DynamicProgramming/PaintHouse.cpp b/DynamicProgramming/PaintHouse.cpp new file mode 100644 index 0000000..86becd0 --- /dev/null +++ b/DynamicProgramming/PaintHouse.cpp @@ -0,0 +1,24 @@ +/* +Problem Description + +There are a row of N houses, each house can be painted with one of the three colors: red, blue or green. + +The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. + +The cost of painting each house with a certain color is represented by a N x 3 cost matrix A. + +For example, A[0][0] is the cost of painting house 0 with color red; A[1][2] is the cost of painting house 1 with color green, and so on. + +Find the minimum total cost to paint all houses. +*/ +int Solution::solve(vector > &A) { + int n=A.size(); + for(int i=n-2;i>=0;i--) + { + for(int j=0;j<3;j++) + { + A[i][j]+=min(A[i+1][(j+1)%3],A[i+1][(j+2)%3]); + } + } + return min(A[0][0],min(A[0][1],A[0][2])); +} From 45c9280441470419821f565a5b86582fa716d619 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:56:13 +0530 Subject: [PATCH 45/75] Create MinSubsetDifference.cpp --- DynamicProgramming/MinSubsetDifference.cpp | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 DynamicProgramming/MinSubsetDifference.cpp diff --git a/DynamicProgramming/MinSubsetDifference.cpp b/DynamicProgramming/MinSubsetDifference.cpp new file mode 100644 index 0000000..0dcf14a --- /dev/null +++ b/DynamicProgramming/MinSubsetDifference.cpp @@ -0,0 +1,32 @@ +int Solution::solve(vector &A) { + int n=A.size(); + if(n==1) return A[0]; + int sum=0; + for(int i=0;i>dp(n+1,vector(sum/2+1,false)); + for(int i=1;i<=n;i++) dp[i][0]=true; + for(int i=1;i<=sum/2;i++) dp[0][i]=false; + for(int i=1;i<=n;i++) + { + for(int j=1;j<=sum/2;j++) + { + dp[i][j]=dp[i-1][j]; + if(j>=A[i-1]) + { + dp[i][j]=dp[i][j]||dp[i-1][j-A[i-1]]; + } + } + } + int minval=INT_MAX; + for(int i=1;i<=sum/2;i++) + { + if(dp[n][i]) + { + minval=min(minval,abs(sum-2*i)); + } + } + return minval; +} From 68b26c788a19061bc0583c3cda465d0a956190f5 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 10:57:09 +0530 Subject: [PATCH 46/75] Create UniquePathsInGrid.cpp --- DynamicProgramming/UniquePathsInGrid.cpp | 34 ++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DynamicProgramming/UniquePathsInGrid.cpp diff --git a/DynamicProgramming/UniquePathsInGrid.cpp b/DynamicProgramming/UniquePathsInGrid.cpp new file mode 100644 index 0000000..378e2f0 --- /dev/null +++ b/DynamicProgramming/UniquePathsInGrid.cpp @@ -0,0 +1,34 @@ +int Solution::uniquePathsWithObstacles(vector > &A) { + int m=A.size(); + int n=A[0].size(); + vector>dp(m,vector(n,0)); + bool flag=false; + for(int i=0;i Date: Wed, 19 May 2021 10:59:24 +0530 Subject: [PATCH 47/75] Create MaximumSizeSquareSub-matrix.cpp --- .../MaximumSizeSquareSub-matrix.cpp | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 DynamicProgramming/MaximumSizeSquareSub-matrix.cpp diff --git a/DynamicProgramming/MaximumSizeSquareSub-matrix.cpp b/DynamicProgramming/MaximumSizeSquareSub-matrix.cpp new file mode 100644 index 0000000..39f229e --- /dev/null +++ b/DynamicProgramming/MaximumSizeSquareSub-matrix.cpp @@ -0,0 +1,29 @@ +/* +Given a 2D binary matrix A of size N x M find the area of maximum size square sub-matrix with all 1's. +*/ +int Solution::solve(vector > &A) { + int n=A.size(); + int m=A[0].size(); + int ans=0; + vector>dp(n,vector(m,0)); + for(int i=0;i Date: Wed, 19 May 2021 11:04:33 +0530 Subject: [PATCH 48/75] Create LengthOfLongestBitonicSubsequence.cpp --- .../LengthOfLongestBitonicSubsequence.cpp | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 DynamicProgramming/LengthOfLongestBitonicSubsequence.cpp diff --git a/DynamicProgramming/LengthOfLongestBitonicSubsequence.cpp b/DynamicProgramming/LengthOfLongestBitonicSubsequence.cpp new file mode 100644 index 0000000..d8ea786 --- /dev/null +++ b/DynamicProgramming/LengthOfLongestBitonicSubsequence.cpp @@ -0,0 +1,32 @@ +/*Given an 1D integer array A of length N, find the length of longest subsequence which is first increasing then decreasing.*/ +int Solution::longestSubsequenceLength(const vector &A) { + int n=A.size(); + vectorinc(n,1); + vectordec(n,1); + for(int i=0;iA[j]) + { + inc[i]=max(inc[i],inc[j]+1); + } + } + } + for(int i=n-1;i>=0;i--) + { + for(int j=n-1;j>i;j--) + { + if(A[i]>A[j]) + { + dec[i]=max(dec[i],dec[j]+1); + } + } + } + int ans=0; + for(int i=0;i Date: Wed, 19 May 2021 11:08:03 +0530 Subject: [PATCH 49/75] Create SmallestSequenceWithPrimes.cpp --- .../SmallestSequenceWithPrimes.cpp | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DynamicProgramming/SmallestSequenceWithPrimes.cpp diff --git a/DynamicProgramming/SmallestSequenceWithPrimes.cpp b/DynamicProgramming/SmallestSequenceWithPrimes.cpp new file mode 100644 index 0000000..c9c3ff8 --- /dev/null +++ b/DynamicProgramming/SmallestSequenceWithPrimes.cpp @@ -0,0 +1,33 @@ +/* +GIven three prime numbers A, B and C and an integer D. + +You need to find the first(smallest) D integers which only have A, B, C or a combination of them as their prime factors. +*/ +vector Solution::solve(int A, int B, int C, int D) { + vectorans; + int i1=0; + int i2=0; + int i3=0; + int next_A=A; + int next_B=B; + int next_C=C; + vectordp(D); + for(int i=0;i Date: Wed, 19 May 2021 11:10:25 +0530 Subject: [PATCH 50/75] Create WaysToDecode.cpp --- DynamicProgramming/WaysToDecode.cpp | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DynamicProgramming/WaysToDecode.cpp diff --git a/DynamicProgramming/WaysToDecode.cpp b/DynamicProgramming/WaysToDecode.cpp new file mode 100644 index 0000000..edd0385 --- /dev/null +++ b/DynamicProgramming/WaysToDecode.cpp @@ -0,0 +1,30 @@ +/* +A message containing letters from A-Z is being encoded to numbers using the following mapping: + + 'A' -> 1 + 'B' -> 2 + ... + 'Z' -> 26 +Given an encoded message A containing digits, determine the total number of ways to decode it modulo 109 + 7. +*/ + +int Solution::numDecodings(string s) { + int n=s.size(); + vectorcount(n+1,0); + if(n==0) return 0; + if(s[0]=='0') return 0; + count[0]=1; + count[1]=1; + for(int i=2;i<=n;i++) + { + if(s[i-1]>'0') + { + count[i]=count[i-1]; + } + if(s[i-2]=='1' || s[i-2]=='2' && s[i-1]<'7') + { + count[i]=(count[i]%1000000007+count[i-2]%1000000007)%1000000007; + } + } + return count[n]%1000000007; +} From e44963d32b8ba0681cd2bc483ba94111e16553ee Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:13:38 +0530 Subject: [PATCH 51/75] Create LongestIncreasingSubsequence.cpp --- .../LongestIncreasingSubsequence.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 DynamicProgramming/LongestIncreasingSubsequence.cpp diff --git a/DynamicProgramming/LongestIncreasingSubsequence.cpp b/DynamicProgramming/LongestIncreasingSubsequence.cpp new file mode 100644 index 0000000..56d5c62 --- /dev/null +++ b/DynamicProgramming/LongestIncreasingSubsequence.cpp @@ -0,0 +1,19 @@ +int Solution::lis(const vector &A) { + int n=A.size(); + vectord(n+1,INT_MAX); + d[0]=INT_MIN; + for(int i=0;id[j-1] && A[i] Date: Wed, 19 May 2021 11:14:45 +0530 Subject: [PATCH 52/75] Create IntersectingChordsInCircles.cpp --- .../IntersectingChordsInCircles.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 DynamicProgramming/IntersectingChordsInCircles.cpp diff --git a/DynamicProgramming/IntersectingChordsInCircles.cpp b/DynamicProgramming/IntersectingChordsInCircles.cpp new file mode 100644 index 0000000..51b9e7b --- /dev/null +++ b/DynamicProgramming/IntersectingChordsInCircles.cpp @@ -0,0 +1,17 @@ +int Solution::chordCnt(int A) +{ +long long int m = 1000000007; +long long int dp[A+1]; +dp[0] = 1; +dp[1]=1; +for(long long int i=2;i<=A;i++) +{ + dp[i] = 0; + for(long long int j=0;j Date: Wed, 19 May 2021 11:16:15 +0530 Subject: [PATCH 53/75] Create JumpGameArray.cpp --- DynamicProgramming/JumpGameArray.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 DynamicProgramming/JumpGameArray.cpp diff --git a/DynamicProgramming/JumpGameArray.cpp b/DynamicProgramming/JumpGameArray.cpp new file mode 100644 index 0000000..812160b --- /dev/null +++ b/DynamicProgramming/JumpGameArray.cpp @@ -0,0 +1,17 @@ +/*Given an array of non-negative integers, A, you are initially positioned at the first index of the array. + +Each element in the array represents your maximum jump length at that position. + +Determine if you are able to reach the last index.*/ + +int Solution::canJump(vector &A) { + int maxindex=0; + if(A.size()==1) return 1; + for(int i=0;i=maxindex) return 0; + if(maxindex >= A.size()-1) return 1; + } + return 0; +} From e527c4cf839cb9bf7e585be4d6479f4d042c4dc2 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:17:12 +0530 Subject: [PATCH 54/75] Create MinJumpsArray.cpp --- DynamicProgramming/MinJumpsArray.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 DynamicProgramming/MinJumpsArray.cpp diff --git a/DynamicProgramming/MinJumpsArray.cpp b/DynamicProgramming/MinJumpsArray.cpp new file mode 100644 index 0000000..5b7bc57 --- /dev/null +++ b/DynamicProgramming/MinJumpsArray.cpp @@ -0,0 +1,27 @@ +/*Given an array of non-negative integers, A, of length N, you are initially positioned at the first index of the array. + +Each element in the array represents your maximum jump length at that position. + +Return the minimum number of jumps required to reach the last index. + +If it is not possible to reach the last index, return -1.*/ +int Solution::jump(vector &A) { + int n=A.size(); + int furthest=0; + int end=0; + int jumps=0; + if(n==1||n==0)return 0; + if(A[0]==0) return -1; + for(int i=0;i Date: Wed, 19 May 2021 11:18:30 +0530 Subject: [PATCH 55/75] Create LongestArithmeticProgression.cpp --- .../LongestArithmeticProgression.cpp | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 DynamicProgramming/LongestArithmeticProgression.cpp diff --git a/DynamicProgramming/LongestArithmeticProgression.cpp b/DynamicProgramming/LongestArithmeticProgression.cpp new file mode 100644 index 0000000..60d131b --- /dev/null +++ b/DynamicProgramming/LongestArithmeticProgression.cpp @@ -0,0 +1,20 @@ +/*Find longest Arithmetic Progression in an integer array A of size N, and return its length. + +More formally, find longest sequence of indices, 0 < i1 < i2 < … < ik < ArraySize(0-indexed) such that sequence A[i1], A[i2], …, A[ik] is an Arithmetic Progression. + +Arithmetic Progression is a sequence in which all the differences between consecutive pairs are the same, i.e sequence B[0], B[1], B[2], …, B[m - 1] of length m is an Arithmetic Progression if and only if B[1] - B[0] == B[2] - B[1] == B[3] - B[2] == … == B[m - 1] - B[m - 2]*/ + +int Solution::solve(const vector &arr) { + int n = arr.size(), res = 2; + if(n <= 2) + return n; + vector> dp(n); //(key, value) => (position, difference) + for(int i=0; i 0 ? dp[j][diff] + 1 : 2; + res = max(res, dp[i][diff]); + } + } + return res; +} From e40bcc20e75d2a45eb7ae3e0372ad152822b5fad Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:22:36 +0530 Subject: [PATCH 56/75] Create BestTimeToBuy&SellStockAtmostBTimes.cpp --- .../BestTimeToBuy&SellStockAtmostBTimes.cpp | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 DynamicProgramming/BestTimeToBuy&SellStockAtmostBTimes.cpp diff --git a/DynamicProgramming/BestTimeToBuy&SellStockAtmostBTimes.cpp b/DynamicProgramming/BestTimeToBuy&SellStockAtmostBTimes.cpp new file mode 100644 index 0000000..589e3ba --- /dev/null +++ b/DynamicProgramming/BestTimeToBuy&SellStockAtmostBTimes.cpp @@ -0,0 +1,22 @@ +/*Given an array of integers A of size N in which ith element is the price of the stock on day i. + +You can complete atmost B transactions. + +Find the maximum profit you can achieve. + +NOTE: You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).*/ +int Solution::solve(vector &A, int B) { + int n=A.size(); + B=min(B,n/2); + vector>dp(n,vector(B+1,0)); + for(int j=1;j<=B;j++) + { + int prev=INT_MIN; + for(int i=1;i Date: Wed, 19 May 2021 11:23:29 +0530 Subject: [PATCH 57/75] Create CoinsInALine.cpp --- DynamicProgramming/CoinsInALine.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 DynamicProgramming/CoinsInALine.cpp diff --git a/DynamicProgramming/CoinsInALine.cpp b/DynamicProgramming/CoinsInALine.cpp new file mode 100644 index 0000000..e1b73be --- /dev/null +++ b/DynamicProgramming/CoinsInALine.cpp @@ -0,0 +1,23 @@ +/*There are A coins (Assume A is even) in a line. + +Two players take turns to take a coin from one of the ends of the line until there are no more coins left. + +The player with the larger amount of money wins, Assume that you go first. + +Return the maximum amount of money you can win.*/ +int ans(int start,int end,vector&A,vector>&dp) +{ + if(start==end) return dp[start][end]=A[end]; + if(dp[start][end]!=-1) return dp[start][end]; + int res=max(A[start]-ans(start+1,end,A,dp), A[end]-ans(start,end-1,A,dp)); + return dp[start][end]=res; +} +int Solution::maxcoin(vector &A) { + int n=A.size(); + vector>dp(n,vector(n,-1)); + ans(0,A.size()-1,A,dp); + int sum=0; + for(int i=0;i Date: Wed, 19 May 2021 11:24:38 +0530 Subject: [PATCH 58/75] Create LongestValidParentheses.cpp --- .../LongestValidParentheses.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 DynamicProgramming/LongestValidParentheses.cpp diff --git a/DynamicProgramming/LongestValidParentheses.cpp b/DynamicProgramming/LongestValidParentheses.cpp new file mode 100644 index 0000000..9b3c7a3 --- /dev/null +++ b/DynamicProgramming/LongestValidParentheses.cpp @@ -0,0 +1,26 @@ +/*Given a string A containing just the characters ’(‘ and ’)’. + +Find the length of the longest valid (well-formed) parentheses substring.*/ +int Solution::longestValidParentheses(string A) { + stacks; + int maxlen=0; + s.push(-1); + for(int i=0;i Date: Wed, 19 May 2021 11:28:13 +0530 Subject: [PATCH 59/75] Create KingdomWar.cpp --- DynamicProgramming/KingdomWar.cpp | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 DynamicProgramming/KingdomWar.cpp diff --git a/DynamicProgramming/KingdomWar.cpp b/DynamicProgramming/KingdomWar.cpp new file mode 100644 index 0000000..6f96766 --- /dev/null +++ b/DynamicProgramming/KingdomWar.cpp @@ -0,0 +1,36 @@ +/*Two kingdoms are on a war right now, kingdom X and kingdom Y. As a war specialist of kingdom X, you scouted kingdom Y area. + +A kingdom area is defined as a N x M grid with each cell denoting a village. +Each cell has a value which denotes the strength of each corresponding village. +The strength can also be negative, representing those warriors of your kingdom who were held hostages. + +There’s also another thing to be noticed. + +The strength of any village on row larger than one (2<=r<=N) is stronger or equal to the strength of village which is exactly above it. +The strength of any village on column larger than one (2<=c<=M) is stronger or equal to the strength of vilage which is exactly to its left. +(stronger means having higher value as defined above). +So your task is, find the largest sum of strength that you can erase by bombing one sub-matrix in the grid.*/ + +int Solution::solve(vector > &A) { + int n=A.size(); + int m=A[0].size(); + for(int i=0;i=0;j--){ + A[i][j]+=sum; + sum=A[i][j]; + } + } + int ans=A[n-1][m-1]; + for(int i=0;i=0;j--){ + A[j][i]+=sum; + sum=A[j][i]; + mx=max(mx,sum); + } + ans=max(ans,mx); + } + return ans; +} From 3f32a2de3f5e51e01f5979031ab91d383edb1656 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:29:16 +0530 Subject: [PATCH 60/75] Create MaximumPathInTriangle.cpp --- DynamicProgramming/MaximumPathInTriangle.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 DynamicProgramming/MaximumPathInTriangle.cpp diff --git a/DynamicProgramming/MaximumPathInTriangle.cpp b/DynamicProgramming/MaximumPathInTriangle.cpp new file mode 100644 index 0000000..f850ae5 --- /dev/null +++ b/DynamicProgramming/MaximumPathInTriangle.cpp @@ -0,0 +1,19 @@ +/*Given a 2D integer array A of size N * N representing a triangle of numbers. + +Find the maximum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. + +NOTE: + +Adjacent cells to cell (i,j) are only (i+1,j) and (i+1,j+1) +Row i contains i integer and n-i zeroes for all i in [1,n] where zeroes represents empty cells.*/ +int Solution::solve(vector > &A) { + int n=A.size()-1; + for(int i=n-2;i>=0;i--) + { + for(int j=0;j Date: Wed, 19 May 2021 11:32:12 +0530 Subject: [PATCH 61/75] Create DungeonPrincess.cpp --- DynamicProgramming/DungeonPrincess.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 DynamicProgramming/DungeonPrincess.cpp diff --git a/DynamicProgramming/DungeonPrincess.cpp b/DynamicProgramming/DungeonPrincess.cpp new file mode 100644 index 0000000..50fa9fe --- /dev/null +++ b/DynamicProgramming/DungeonPrincess.cpp @@ -0,0 +1,22 @@ +/*The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned in the top-left room and must fight his way through the dungeon to rescue the princess. + +The knight has an initial health point represented by a positive integer. If at any point his health point drops to 0 or below, he dies immediately. + +Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0’s) or contain magic orbs that increase the knight’s health (positive integers). + +In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step. +*/ +int Solution::calculateMinimumHP(vector > &A) { + int r=A.size(),c=A[0].size(); + for(int i=r-1;i>=0;i--) + { + for(int j=c-1;j>=0;j--) + { + if(i==r-1&&j==c-1) A[i][j]=max(1-A[i][j],1); + else if(j==c-1) A[i][j]=max(A[i+1][j]-A[i][j],1); + else if(i==r-1) A[i][j]=max(A[i][j+1]-A[i][j],1); + else A[i][j]=max(min(A[i+1][j],A[i][j+1])-A[i][j],1); + } + } + return A[0][0]; +} From c50320f853d5a91b3b57421be933d521d0d997a3 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:33:14 +0530 Subject: [PATCH 62/75] Create MinSumPath.cpp --- DynamicProgramming/MinSumPath.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 DynamicProgramming/MinSumPath.cpp diff --git a/DynamicProgramming/MinSumPath.cpp b/DynamicProgramming/MinSumPath.cpp new file mode 100644 index 0000000..b618da1 --- /dev/null +++ b/DynamicProgramming/MinSumPath.cpp @@ -0,0 +1,22 @@ +int Solution::minPathSum(vector > &A) { + int n=A.size(); + int m=A[0].size(); + vector>dp(n,vector(m,0)); + dp[0][0]=A[0][0]; + for(int i=1;i Date: Wed, 19 May 2021 11:33:57 +0530 Subject: [PATCH 63/75] Create MinPathInTriangle.cpp --- DynamicProgramming/MinPathInTriangle.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 DynamicProgramming/MinPathInTriangle.cpp diff --git a/DynamicProgramming/MinPathInTriangle.cpp b/DynamicProgramming/MinPathInTriangle.cpp new file mode 100644 index 0000000..c82de37 --- /dev/null +++ b/DynamicProgramming/MinPathInTriangle.cpp @@ -0,0 +1,16 @@ +int Solution::minimumTotal(vector > &triangle) { + // Do not write main() function. + // Do not read input, instead use the arguments to the function. + // Do not print the output, instead return values as specified + // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + + int n=triangle.size(); + for(int i=n-2;i>=0;i--) + { + for(int j=0;j Date: Wed, 19 May 2021 11:35:26 +0530 Subject: [PATCH 64/75] Create MaxRectangleInBinaryMatrix.cpp --- .../MaxRectangleInBinaryMatrix.cpp | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 DynamicProgramming/MaxRectangleInBinaryMatrix.cpp diff --git a/DynamicProgramming/MaxRectangleInBinaryMatrix.cpp b/DynamicProgramming/MaxRectangleInBinaryMatrix.cpp new file mode 100644 index 0000000..88fd6ca --- /dev/null +++ b/DynamicProgramming/MaxRectangleInBinaryMatrix.cpp @@ -0,0 +1,51 @@ +/*Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle containing all ones and return its area.*/ +int Solution::maximalRectangle(vector > &A) { + int n=A.size(); + int m=A[0].size(); + vectorheights(m,0); + vectorleft(m,0); + vectorright(m,m-1); + int ans=0; + for(int i=0;i=0;j--) + { + if(A[i][j]==1) + { + right[j]=min(right[j],curr_right); + } + else + { + right[j]=m; + curr_right=j-1; + } + } + for(int j=0;j Date: Wed, 19 May 2021 11:37:55 +0530 Subject: [PATCH 65/75] Create SubMatrixWithSumZero.cpp --- DynamicProgramming/SubMatrixWithSumZero.cpp | 39 +++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 DynamicProgramming/SubMatrixWithSumZero.cpp diff --git a/DynamicProgramming/SubMatrixWithSumZero.cpp b/DynamicProgramming/SubMatrixWithSumZero.cpp new file mode 100644 index 0000000..8739e1a --- /dev/null +++ b/DynamicProgramming/SubMatrixWithSumZero.cpp @@ -0,0 +1,39 @@ +/*Given a 2D matrix, find the number non-empty sub matrices, such that the sum of the elements inside the sub matrix is equal to 0. (note: elements might be negative).*/ + +int find(vector&A) +{ + int ans=0; + mapm; + m[0]=1; + int sum=0; + for(int i=0;i > &A) { + int n=A.size(); + if(n==0) return 0; + int m=A[0].size(); + int count=0; + for(int left=0;lefttemp(n,0); + for(int right=left;right Date: Wed, 19 May 2021 11:38:46 +0530 Subject: [PATCH 66/75] Create CoinSumInfinite.cpp --- DynamicProgramming/CoinSumInfinite.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 DynamicProgramming/CoinSumInfinite.cpp diff --git a/DynamicProgramming/CoinSumInfinite.cpp b/DynamicProgramming/CoinSumInfinite.cpp new file mode 100644 index 0000000..bb86350 --- /dev/null +++ b/DynamicProgramming/CoinSumInfinite.cpp @@ -0,0 +1,18 @@ +/*You are given a set of coins S. In how many ways can you make sum N assuming you have infinite amount of each coin in the set. + +Note : Coins in set S will be unique. Expected space complexity of this problem is O(N).*/ + +int Solution::coinchange2(vector &A, int B) { + int n=A.size(); + vectordp(B+1,0); + dp[0]=1; + sort(A.begin(),A.end()); + for(int i=0;i Date: Wed, 19 May 2021 11:40:30 +0530 Subject: [PATCH 67/75] Create MaxProductSubarray.cpp --- DynamicProgramming/MaxProductSubarray.cpp | 33 +++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 DynamicProgramming/MaxProductSubarray.cpp diff --git a/DynamicProgramming/MaxProductSubarray.cpp b/DynamicProgramming/MaxProductSubarray.cpp new file mode 100644 index 0000000..fb7aba5 --- /dev/null +++ b/DynamicProgramming/MaxProductSubarray.cpp @@ -0,0 +1,33 @@ +/*Find the contiguous subarray within an array (containing at least one number) which has the largest product. +Return an integer corresponding to the maximum product possible.*/ +int Solution::maxProduct(const vector &A) { + int minforward=INT_MIN; + int maxbackward=INT_MIN; + int prod=1; + bool iszero=false; + for(int i=0;i=0;i--) + { + prod*=A[i]; + if(prod==0) + { + iszero=true; + prod=1; + continue; + } + maxbackward=max(maxbackward,prod); + } + if(iszero) return max(0,max(minforward,maxbackward)); + return max(maxbackward,minforward); +} From a5feb19388503bbdd8fb614240ba964671e9155a Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:43:10 +0530 Subject: [PATCH 68/75] Create ChainOfPairs.cpp --- DynamicProgramming/ChainOfPairs.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 DynamicProgramming/ChainOfPairs.cpp diff --git a/DynamicProgramming/ChainOfPairs.cpp b/DynamicProgramming/ChainOfPairs.cpp new file mode 100644 index 0000000..3e84d1a --- /dev/null +++ b/DynamicProgramming/ChainOfPairs.cpp @@ -0,0 +1,26 @@ +/*Given a N * 2 array A where (A[i][0], A[i][1]) represents the ith pair. + +In every pair, the first number is always smaller than the second number. + +A pair (c, d) can follow another pair (a, b) if b < c , similarly in this way a chain of pairs can be formed. + +Find the length of the longest chain subsequence which can be formed from a given set of pairs.*/ + + +int Solution::solve(vector > &A) { + int n=A.size(); + vectordp(n,1); + int ans=1; + for(int i=0;iA[j][1]) + { + dp[i]=max(dp[i],dp[j]+1); + } + ans=max(ans,dp[i]); + } + } + return ans; +} From 7b311d0d4df25a948f67da74ef2cb0311ce18722 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:44:07 +0530 Subject: [PATCH 69/75] Create Arrange.cpp --- DynamicProgramming/Arrange.cpp | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 DynamicProgramming/Arrange.cpp diff --git a/DynamicProgramming/Arrange.cpp b/DynamicProgramming/Arrange.cpp new file mode 100644 index 0000000..c727000 --- /dev/null +++ b/DynamicProgramming/Arrange.cpp @@ -0,0 +1,35 @@ +/*You are given a sequence of black and white horses, and a set of K stables numbered 1 to K. You have to accommodate the horses into the stables in such a way that the following conditions are satisfied: + +You fill the horses into the stables preserving the relative order of horses. For instance, you cannot put horse 1 into stable 2 and horse 2 into stable 1. You have to preserve the ordering of the horses. +No stable should be empty and no horse should be left unaccommodated. +Take the product (number of white horses * number of black horses) for each stable and take the sum of all these products. This value should be the minimum among all possible accommodation arrangements*/ + +int solve(int i,int k,int n,string A, vector>&t) +{ + if(i>=n && k>0) return INT_MAX/2; + if(t[i][k]!=-1) return t[i][k]; + int w=0,b=0; + if(k==1) + { + for(int j=i;jA.size()) return -1; + vector>t(A.size()+1,vector(B+1,-1)); + return solve(0,B,A.size(),A,t); +} From abee8da771294f57b4a02b0359556a747e3084b4 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:45:57 +0530 Subject: [PATCH 70/75] Create MaxSumWithoutAdjacent.cpp --- DynamicProgramming/MaxSumWithoutAdjacent.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 DynamicProgramming/MaxSumWithoutAdjacent.cpp diff --git a/DynamicProgramming/MaxSumWithoutAdjacent.cpp b/DynamicProgramming/MaxSumWithoutAdjacent.cpp new file mode 100644 index 0000000..958e2d3 --- /dev/null +++ b/DynamicProgramming/MaxSumWithoutAdjacent.cpp @@ -0,0 +1,14 @@ +/*Given a 2 x N grid of integer, A, choose numbers such that the sum of the numbers +is maximum and no two chosen numbers are adjacent horizontally, vertically or diagonally, and return it.*/ +int Solution::adjacent(vector > &A) { + int n=A.size(); + vector>dp(n,vector(2,0)); + dp[0][0]=0; + dp[0][1]=max(A[0][0],A[1][0]); + for(int i=1;i Date: Wed, 19 May 2021 11:54:26 +0530 Subject: [PATCH 71/75] Create IncreasingPathInMatrix.cpp --- DynamicProgramming/IncreasingPathInMatrix.cpp | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 DynamicProgramming/IncreasingPathInMatrix.cpp diff --git a/DynamicProgramming/IncreasingPathInMatrix.cpp b/DynamicProgramming/IncreasingPathInMatrix.cpp new file mode 100644 index 0000000..645e92f --- /dev/null +++ b/DynamicProgramming/IncreasingPathInMatrix.cpp @@ -0,0 +1,49 @@ +/*Given a 2D integer matrix A of size N x M. + +From A[i][j] you can move to A[i+1][j], if A[i+1][j] > A[i][j], or can move to A[i][j+1] if A[i][j+1] > A[i][j]. + +The task is to find and output the longest path length if we start from (0, 0). + +NOTE: + +If there doesn't exist a path return -1.*/ +int Solution::solve(vector > &A) { + int n=A.size(); + int m=A[0].size(); + if(n==1 && m==1) return 1; + vector>dp(n,vector(m,0)); + int ans=1; + dp[0][0]=1; + for(int i=0;iA[i][j-1]) + dp[i][j]=1+dp[i][j-1]; + } + else + { + if(A[i][j]>A[i-1][j]) + dp[i][j]=1+dp[i-1][j]; + } + } + else + { + if(A[i][j]>A[i-1][j]) + dp[i][j]=max(dp[i][j],1+dp[i-1][j]); + if(A[i][j]>A[i][j-1]) + { + dp[i][j]=max(dp[i][j],1+dp[i][j-1]); + } + } + ans=max(ans,dp[i][j]); + } + } + if(ans==1) return -1; + return ans; +} From a36f1bd72a1a8b8c0b5d8a7add7e31e599cbfd69 Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Wed, 19 May 2021 11:55:31 +0530 Subject: [PATCH 72/75] Create MergeElements.cpp --- DynamicProgramming/MergeElements.cpp | 30 ++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 DynamicProgramming/MergeElements.cpp diff --git a/DynamicProgramming/MergeElements.cpp b/DynamicProgramming/MergeElements.cpp new file mode 100644 index 0000000..e41c4f4 --- /dev/null +++ b/DynamicProgramming/MergeElements.cpp @@ -0,0 +1,30 @@ +/*Given an integer array A of size N. You have to merge all the elements of the array into one with the minimum possible cost. + +The rule for merging is as follows: + +Choose any two adjacent elements of the array with values say X and Y and merge them into a single element with value (X + Y) paying a total cost of (X + Y). +Return the minimum possible cost of merging all elements.*/ +int Solution::solve(vector &A) { + int n=A.size(); + vector>dp(n,vector(n,0)); + vectorprefix_sum(n,0); + prefix_sum[0]=A[0]; + for(int i=1;i Date: Wed, 19 May 2021 12:17:58 +0530 Subject: [PATCH 73/75] Update IncreasingPathInMatrix.cpp --- DynamicProgramming/IncreasingPathInMatrix.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/DynamicProgramming/IncreasingPathInMatrix.cpp b/DynamicProgramming/IncreasingPathInMatrix.cpp index 645e92f..b40f70c 100644 --- a/DynamicProgramming/IncreasingPathInMatrix.cpp +++ b/DynamicProgramming/IncreasingPathInMatrix.cpp @@ -10,9 +10,8 @@ If there doesn't exist a path return -1.*/ int Solution::solve(vector > &A) { int n=A.size(); int m=A[0].size(); - if(n==1 && m==1) return 1; vector>dp(n,vector(m,0)); - int ans=1; + int ans=-1; dp[0][0]=1; for(int i=0;i > &A) { { if(i==0) { - if(A[i][j]>A[i][j-1]) + if(A[i][j]>A[i][j-1] && dp[i][j-1]!=0) dp[i][j]=1+dp[i][j-1]; } else { - if(A[i][j]>A[i-1][j]) + if(A[i][j]>A[i-1][j] && dp[i-1][j]!=0) dp[i][j]=1+dp[i-1][j]; } } else { - if(A[i][j]>A[i-1][j]) + if(A[i][j]>A[i-1][j] && dp[i-1][j]!=0) dp[i][j]=max(dp[i][j],1+dp[i-1][j]); - if(A[i][j]>A[i][j-1]) + if(A[i][j]>A[i][j-1] && dp[i][j-1]!=0) { dp[i][j]=max(dp[i][j],1+dp[i][j-1]); } } - ans=max(ans,dp[i][j]); } } - if(ans==1) return -1; - return ans; + if(dp[n-1][m-1]==0) return -1; + return dp[n-1][m-1]; } From e2b7b8555cf25a4f84ce4b0a59ff2d50a2622b0d Mon Sep 17 00:00:00 2001 From: SharatMehrotra <47215289+SharatMehrotra@users.noreply.github.com> Date: Thu, 10 Jun 2021 11:48:04 +0530 Subject: [PATCH 74/75] Update BellmanFord.cpp --- Graphs/BellmanFord.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Graphs/BellmanFord.cpp b/Graphs/BellmanFord.cpp index a7d990f..0863560 100644 --- a/Graphs/BellmanFord.cpp +++ b/Graphs/BellmanFord.cpp @@ -13,9 +13,9 @@ vector BellmanFord(int V,int src,vector>edges){ // {src,dest, } } for(int i=0; i < E; i++){ - int u=edges[i][0]; - int v=edges[i][1]; - int w=edges[i][2]; + int u=edges[j][0]; + int v=edges[j][1]; + int w=edges[j][2]; if(dist[u] != INT_MAX && dist[u] + w Date: Thu, 10 Jun 2021 11:49:27 +0530 Subject: [PATCH 75/75] Update BellmanFord.cpp --- Graphs/BellmanFord.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Graphs/BellmanFord.cpp b/Graphs/BellmanFord.cpp index 0863560..5688e9d 100644 --- a/Graphs/BellmanFord.cpp +++ b/Graphs/BellmanFord.cpp @@ -5,17 +5,17 @@ vector BellmanFord(int V,int src,vector>edges){ // {src,dest, dist[src]=0; //dist from src will be zero for (int i = 1; i < V; i++) { for (int j = 0; j < E; j++) { - int u = edges[i][0]; - int v = edges[i][1]; - int weight = edges[i][2]; + int u = edges[j][0]; + int v = edges[j][1]; + int weight = edges[j][2]; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } for(int i=0; i < E; i++){ - int u=edges[j][0]; - int v=edges[j][1]; - int w=edges[j][2]; + int u=edges[i][0]; + int v=edges[i][1]; + int w=edges[i][2]; if(dist[u] != INT_MAX && dist[u] + w