code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
// C++ program to print DFS traversal from // a given vertex in a given graph #include <bits/stdc++.h> using namespace std; // Graph class represents a directed graph // using adjacency list representation class Graph { public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // DFS traversal of the vertices // reachable from v void DFS(int v); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::DFS(int v) { // Mark the current node as visited and // print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent // to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFS(*i); } // Driver's code int main() { // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Following is Depth First Traversal" " (starting from vertex 2) \n"; // Function call g.DFS(2); return 0; } // improved by Vishnudev C
linear
linear
// C++ program to print DFS // traversal for a given // graph #include <bits/stdc++.h> using namespace std; class Graph { // A function used by DFS void DFSUtil(int v); public: map<int, bool> visited; map<int, list<int> > adj; // function to add an edge to graph void addEdge(int v, int w); // prints DFS traversal of the complete graph void DFS(); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } void Graph::DFSUtil(int v) { // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i); } // The function to do DFS traversal. It uses recursive // DFSUtil() void Graph::DFS() { // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first); } // Driver's Code int main() { // Create a graph given in the above diagram Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); cout << "Following is Depth First Traversal \n"; // Function call g.DFS(); return 0; } // improved by Vishnudev C
linear
linear
// C++ program to find a mother vertex in O(V+E) time #include <bits/stdc++.h> using namespace std; class Graph { int V; // No. of vertices list<int>* adj; // adjacency lists // A recursive function to print DFS starting from v void DFSUtil(int v, vector<bool>& visited); public: Graph(int V); void addEdge(int v, int w); int findMother(); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } // A recursive function to print DFS starting from v void Graph::DFSUtil(int v, vector<bool>& visited) { // Mark the current node as visited and print it visited[v] = true; // Recur for all the vertices adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v’s list. } // Returns a mother vertex if exists. Otherwise returns -1 int Graph::findMother() { // visited[] is used for DFS. Initially all are // initialized as not visited vector<bool> visited(V, false); // To store last finished vertex (or mother vertex) int v = 0; // Do a DFS traversal and find the last finished // vertex for (int i = 0; i < V; i++) { if (visited[i] == false) { DFSUtil(i, visited); v = i; } } // If there exist mother vertex (or vertices) in given // graph, then v must be one (or one of them) // Now check if v is actually a mother vertex (or graph // has a mother vertex). We basically check if every // vertex is reachable from v or not. // Reset all values in visited[] as false and do // DFS beginning from v to check if all vertices are // reachable from it or not. fill(visited.begin(), visited.end(), false); DFSUtil(v, visited); for (int i = 0; i < V; i++) if (visited[i] == false) return -1; return v; } // Driver code int main() { // Create a graph given in the above diagram Graph g(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(4, 1); g.addEdge(6, 4); g.addEdge(5, 6); g.addEdge(5, 2); g.addEdge(6, 0); // Function call cout << "A mother vertex is " << g.findMother(); return 0; }
linear
linear
/* * C++ program to count all paths from a source to a * destination. * https://www.geeksforgeeks.org/count-possible-paths-two-vertices/ * Note that the original example has been refactored. */ #include <bits/stdc++.h> using namespace std; /* * A directed graph using adjacency list representation; * every vertex holds a list of all neighbouring vertices * that can be reached from it. */ class Graph { public: // Construct the graph given the number of vertices... Graph(int vertices); // Specify an edge between two vertices void add_edge(int src, int dst); // Call the recursive helper function to count all the // paths int count_paths(int src, int dst, int vertices); private: int m_vertices; list<int>* m_neighbours; void path_counter(int src, int dst, int& path_count, vector<bool>& visited); }; Graph::Graph(int vertices) { m_vertices = vertices; // unused!! /* An array of linked lists - each element corresponds to a vertex and will hold a list of neighbours...*/ m_neighbours = new list<int>[vertices]; } void Graph::add_edge(int src, int dst) { m_neighbours[src].push_back(dst); } int Graph::count_paths(int src, int dst, int vertices) { int path_count = 0; vector<bool> visited(vertices, false); path_counter(src, dst, path_count, visited); return path_count; } /* * A recursive function that counts all paths from src to * dst. Keep track of the count in the parameter. */ void Graph::path_counter(int src, int dst, int& path_count, vector<bool>& visited) { // If we've reached the destination, then increment // count... visited[src] = true; if (src == dst) { path_count++; } // ...otherwise recurse into all neighbours... else { for (auto neighbour : m_neighbours[src]) { if (!visited[neighbour]) path_counter(neighbour, dst, path_count, visited); } } visited[src] = false; } // Driver code int main() { // Create a graph given in the above diagram - see link Graph g(5); g.add_edge(0, 1); g.add_edge(0, 2); g.add_edge(0, 4); g.add_edge(1, 3); g.add_edge(1, 4); g.add_edge(2, 3); g.add_edge(2, 1); g.add_edge(3, 2); // Function call cout << g.count_paths(0, 4, 5); return 0; }
linear
np
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; void printpath(map<pii, pii> mp, pii u) { if (u.first == 0 && u.second == 0) { cout << 0 << " " << 0 << endl; return; } printpath(mp, mp[u]); cout << u.first << " " << u.second << endl; } void BFS(int a, int b, int target) { map<pii, int> m; bool isSolvable = false; map<pii, pii> mp; queue<pii> q; q.push(make_pair(0, 0)); while (!q.empty()) { auto u = q.front(); // cout<<u.first<<" "<<u.second<<endl; q.pop(); if (m[u] == 1) continue; if ((u.first > a || u.second > b || u.first < 0 || u.second < 0)) continue; // cout<<u.first<<" "<<u.second<<endl; m[{ u.first, u.second }] = 1; if (u.first == target || u.second == target) { isSolvable = true; printpath(mp, u); if (u.first == target) { if (u.second != 0) cout << u.first << " " << 0 << endl; } else { if (u.first != 0) cout << 0 << " " << u.second << endl; } return; } // completely fill the jug 2 if (m[{ u.first, b }] != 1) { q.push({ u.first, b }); mp[{ u.first, b }] = u; } // completely fill the jug 1 if (m[{ a, u.second }] != 1) { q.push({ a, u.second }); mp[{ a, u.second }] = u; } // transfer jug 1 -> jug 2 int d = b - u.second; if (u.first >= d) { int c = u.first - d; if (m[{ c, b }] != 1) { q.push({ c, b }); mp[{ c, b }] = u; } } else { int c = u.first + u.second; if (m[{ 0, c }] != 1) { q.push({ 0, c }); mp[{ 0, c }] = u; } } // transfer jug 2 -> jug 1 d = a - u.first; if (u.second >= d) { int c = u.second - d; if (m[{ a, c }] != 1) { q.push({ a, c }); mp[{ a, c }] = u; } } else { int c = u.first + u.second; if (m[{ c, 0 }] != 1) { q.push({ c, 0 }); mp[{ c, 0 }] = u; } } // empty the jug 2 if (m[{ u.first, 0 }] != 1) { q.push({ u.first, 0 }); mp[{ u.first, 0 }] = u; } // empty the jug 1 if (m[{ 0, u.second }] != 1) { q.push({ 0, u.second }); mp[{ 0, u.second }] = u; } } if (!isSolvable) cout << "No solution"; } int main() { int Jug1 = 4, Jug2 = 3, target = 2; cout << "Path from initial state " "to solution state ::\n"; BFS(Jug1, Jug2, target); return 0; }
quadratic
quadratic
// CPP Program to determine level of each node // and print level #include <bits/stdc++.h> using namespace std; // function to determine level of each node starting // from x using BFS void printLevels(vector<int> graph[], int V, int x) { // array to store level of each node int level[V]; bool marked[V]; // create a queue queue<int> que; // enqueue element x que.push(x); // initialize level of source node to 0 level[x] = 0; // marked it as visited marked[x] = true; // do until queue is empty while (!que.empty()) { // get the first element of queue x = que.front(); // dequeue element que.pop(); // traverse neighbors of node x for (int i = 0; i < graph[x].size(); i++) { // b is neighbor of node x int b = graph[x][i]; // if b is not marked already if (!marked[b]) { // enqueue b in queue que.push(b); // level of b is level of x + 1 level[b] = level[x] + 1; // mark b marked[b] = true; } } } // display all nodes and their levels cout << "Nodes" << " " << "Level" << endl; for (int i = 0; i < V; i++) cout << " " << i << " --> " << level[i] << endl; } // Driver Code int main() { // adjacency graph for tree int V = 8; vector<int> graph[V]; graph[0].push_back(1); graph[0].push_back(2); graph[1].push_back(3); graph[1].push_back(4); graph[1].push_back(5); graph[2].push_back(5); graph[2].push_back(6); graph[6].push_back(7); // call levels function with source as 0 printLevels(graph, V, 0); return 0; }
linear
linear
// C++ program to print all paths of source to // destination in given graph #include <bits/stdc++.h> using namespace std; // utility function for printing // the found path in graph void printpath(vector<int>& path) { int size = path.size(); for (int i = 0; i < size; i++) cout << path[i] << " "; cout << endl; } // utility function to check if current // vertex is already present in path int isNotVisited(int x, vector<int>& path) { int size = path.size(); for (int i = 0; i < size; i++) if (path[i] == x) return 0; return 1; } // utility function for finding paths in graph // from source to destination void findpaths(vector<vector<int> >& g, int src, int dst, int v) { // create a queue which stores // the paths queue<vector<int> > q; // path vector to store the current path vector<int> path; path.push_back(src); q.push(path); while (!q.empty()) { path = q.front(); q.pop(); int last = path[path.size() - 1]; // if last vertex is the desired destination // then print the path if (last == dst) printpath(path); // traverse to all the nodes connected to // current vertex and push new path to queue for (int i = 0; i < g[last].size(); i++) { if (isNotVisited(g[last][i], path)) { vector<int> newpath(path); newpath.push_back(g[last][i]); q.push(newpath); } } } } // driver program int main() { vector<vector<int> > g; // number of vertices int v = 4; g.resize(4); // construct a graph g[0].push_back(3); g[0].push_back(1); g[0].push_back(2); g[1].push_back(3); g[2].push_back(0); g[2].push_back(1); int src = 2, dst = 3; cout << "path from src " << src << " to dst " << dst << " are \n"; // function for finding the paths findpaths(g, src, dst, v); return 0; }
quadratic
np
// C++ program to find minimum edge // between given two vertex of Graph #include<bits/stdc++.h> using namespace std; // function for finding minimum no. of edge // using BFS int minEdgeBFS(vector <int> edges[], int u, int v, int n) { // visited[n] for keeping track of visited // node in BFS vector<bool> visited(n, 0); // Initialize distances as 0 vector<int> distance(n, 0); // queue to do BFS. queue <int> Q; distance[u] = 0; Q.push(u); visited[u] = true; while (!Q.empty()) { int x = Q.front(); Q.pop(); for (int i=0; i<edges[x].size(); i++) { if (visited[edges[x][i]]) continue; // update distance for i distance[edges[x][i]] = distance[x] + 1; Q.push(edges[x][i]); visited[edges[x][i]] = 1; } } return distance[v]; } // function for addition of edge void addEdge(vector <int> edges[], int u, int v) { edges[u].push_back(v); edges[v].push_back(u); } // Driver function int main() { // To store adjacency list of graph int n = 9; vector <int> edges[9]; addEdge(edges, 0, 1); addEdge(edges, 0, 7); addEdge(edges, 1, 7); addEdge(edges, 1, 2); addEdge(edges, 2, 3); addEdge(edges, 2, 5); addEdge(edges, 2, 8); addEdge(edges, 3, 4); addEdge(edges, 3, 5); addEdge(edges, 4, 5); addEdge(edges, 5, 6); addEdge(edges, 6, 7); addEdge(edges, 7, 8); int u = 0; int v = 5; cout << minEdgeBFS(edges, u, v, n); return 0; }
linear
linear
// C++ program to find minimum steps to reach to // specific cell in minimum moves by Knight #include <bits/stdc++.h> using namespace std; // structure for storing a cell's data struct cell { int x, y; int dis; cell() {} cell(int x, int y, int dis) : x(x) , y(y) , dis(dis) { } }; // Utility method returns true if (x, y) lies // inside Board bool isInside(int x, int y, int N) { if (x >= 1 && x <= N && y >= 1 && y <= N) return true; return false; } // Method returns minimum step // to reach target position int minStepToReachTarget(int knightPos[], int targetPos[], int N) { // x and y direction, where a knight can move int dx[] = { -2, -1, 1, 2, -2, -1, 1, 2 }; int dy[] = { -1, -2, -2, -1, 1, 2, 2, 1 }; // queue for storing states of knight in board queue<cell> q; // push starting position of knight with 0 distance q.push(cell(knightPos[0], knightPos[1], 0)); cell t; int x, y; bool visit[N + 1][N + 1]; // make all cell unvisited for (int i = 1; i <= N; i++) for (int j = 1; j <= N; j++) visit[i][j] = false; // visit starting state visit[knightPos[0]][knightPos[1]] = true; // loop until we have one element in queue while (!q.empty()) { t = q.front(); q.pop(); // if current cell is equal to target cell, // return its distance if (t.x == targetPos[0] && t.y == targetPos[1]) return t.dis; // loop for all reachable states for (int i = 0; i < 8; i++) { x = t.x + dx[i]; y = t.y + dy[i]; // If reachable state is not yet visited and // inside board, push that state into queue if (isInside(x, y, N) && !visit[x][y]) { visit[x][y] = true; q.push(cell(x, y, t.dis + 1)); } } } } // Driver code int main() { int N = 30; int knightPos[] = { 1, 1 }; int targetPos[] = { 30, 30 }; // Function call cout << minStepToReachTarget(knightPos, targetPos, N); return 0; }
quadratic
quadratic
// C++ Program to find the length of the largest // region in boolean 2D-matrix #include <bits/stdc++.h> using namespace std; #define ROW 4 #define COL 5 // A function to check if // a given cell (row, col) // can be included in DFS int isSafe(int M[][COL], int row, int col, bool visited[][COL]) { // row number is in range, // column number is in // range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); } // A utility function to // do DFS for a 2D boolean // matrix. It only considers // the 8 neighbours as // adjacent vertices void DFS(int M[][COL], int row, int col, bool visited[][COL], int& count) { // These arrays are used // to get row and column // numbers of 8 neighbours // of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) { if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) { // Increment region length by one count++; DFS(M, row + rowNbr[k], col + colNbr[k], visited, count); } } } // The main function that returns // largest length region // of a given boolean 2D matrix int largestRegion(int M[][COL]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize result as 0 and travesle through the // all cells of given matrix int result = INT_MIN; for (int i = 0; i < ROW; ++i) { for (int j = 0; j < COL; ++j) { // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new region found int count = 1; DFS(M, i, j, visited, count); // maximum region result = max(result, count); } } } return result; } // Driver code int main() { int M[][COL] = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; // Function call cout << largestRegion(M); return 0; }
quadratic
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find unit area of the largest region of 1s. int largestRegion(vector<vector<int> >& grid) { int m = grid.size(); int n = grid[0].size(); // creating a queue that will help in bfs traversal queue<pair<int, int> > q; int area = 0; int ans = 0; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { // if the value at any particular cell is 1 then // from here we need to do the BFS traversal if (grid[i][j] == 1) { ans = 0; // pushing the pair<i,j> in the queue q.push(make_pair(i, j)); // marking the value 1 to -1 so that we // don't again push this cell in the queue grid[i][j] = -1; while (!q.empty()) { pair<int, int> t = q.front(); q.pop(); ans++; int x = t.first; int y = t.second; // now we will check in all 8 directions if (x + 1 < m) { if (grid[x + 1][y] == 1) { q.push(make_pair(x + 1, y)); grid[x + 1][y] = -1; } } if (x - 1 >= 0) { if (grid[x - 1][y] == 1) { q.push(make_pair(x - 1, y)); grid[x - 1][y] = -1; } } if (y + 1 < n) { if (grid[x][y + 1] == 1) { q.push(make_pair(x, y + 1)); grid[x][y + 1] = -1; } } if (y - 1 >= 0) { if (grid[x][y - 1] == 1) { q.push(make_pair(x, y - 1)); grid[x][y - 1] = -1; } } if (x + 1 < m && y + 1 < n) { if (grid[x + 1][y + 1] == 1) { q.push(make_pair(x + 1, y + 1)); grid[x + 1][y + 1] = -1; } } if (x - 1 >= 0 && y + 1 < n) { if (grid[x - 1][y + 1] == 1) { q.push(make_pair(x - 1, y + 1)); grid[x - 1][y + 1] = -1; } } if (x - 1 >= 0 && y - 1 >= 0) { if (grid[x - 1][y - 1] == 1) { q.push(make_pair(x - 1, y - 1)); grid[x - 1][y - 1] = -1; } } if (x + 1 < m && y - 1 >= 0) { if (grid[x + 1][y - 1] == 1) { q.push(make_pair(x + 1, y - 1)); grid[x + 1][y - 1] = -1; } } } area = max(ans, area); ans = 0; } } } return area; } // Driver Code int main() { vector<vector<int> > M = { { 0, 0, 1, 1, 0 }, { 1, 0, 1, 1, 0 }, { 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1 } }; // Function call cout << largestRegion(M); return 0; }
quadratic
quadratic
// A C++ Program to detect // cycle in an undirected graph #include <iostream> #include <limits.h> #include <list> using namespace std; // Class for an undirected graph class Graph { // No. of vertices int V; // Pointer to an array // containing adjacency lists list<int>* adj; bool isCyclicUtil(int v, bool visited[], int parent); public: // Constructor Graph(int V); // To add an edge to graph void addEdge(int v, int w); // Returns true if there is a cycle bool isCyclic(); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int v, int w) { // Add w to v’s list. adj[v].push_back(w); // Add v to w’s list. adj[w].push_back(v); } // A recursive function that // uses visited[] and parent to detect // cycle in subgraph reachable // from vertex v. bool Graph::isCyclicUtil(int v, bool visited[], int parent) { // Mark the current node as visited visited[v] = true; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { // If an adjacent vertex is not visited, // then recur for that adjacent if (!visited[*i]) { if (isCyclicUtil(*i, visited, v)) return true; } // If an adjacent vertex is visited and // is not parent of current vertex, // then there exists a cycle in the graph. else if (*i != parent) return true; } return false; } // Returns true if the graph contains // a cycle, else false. bool Graph::isCyclic() { // Mark all the vertices as not // visited and not part of recursion // stack bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper // function to detect cycle in different // DFS trees for (int u = 0; u < V; u++) { // Don't recur for u if // it is already visited if (!visited[u]) if (isCyclicUtil(u, visited, -1)) return true; } return false; } // Driver program to test above functions int main() { Graph g1(5); g1.addEdge(1, 0); g1.addEdge(0, 2); g1.addEdge(2, 1); g1.addEdge(0, 3); g1.addEdge(3, 4); g1.isCyclic() ? cout << "Graph contains cycle\n" : cout << "Graph doesn't contain cycle\n"; Graph g2(3); g2.addEdge(0, 1); g2.addEdge(1, 2); g2.isCyclic() ? cout << "Graph contains cycle\n" : cout << "Graph doesn't contain cycle\n"; return 0; }
linear
linear
// A DFS based approach to find if there is a cycle // in a directed graph. This approach strictly follows // the algorithm given in CLRS book. #include <bits/stdc++.h> using namespace std; enum Color {WHITE, GRAY, BLACK}; // Graph class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices list<int>* adj; // adjacency lists // DFS traversal of the vertices reachable from v bool DFSUtil(int v, int color[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); bool isCyclic(); }; // Constructor Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } // Utility function to add an edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v's list. } // Recursive function to find if there is back edge // in DFS subtree tree rooted with 'u' bool Graph::DFSUtil(int u, int color[]) { // GRAY : This vertex is being processed (DFS // for this vertex has started, but not // ended (or this vertex is in function // call stack) color[u] = GRAY; // Iterate through all adjacent vertices list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // An adjacent of u // If there is if (color[v] == GRAY) return true; // If v is not processed and there is a back // edge in subtree rooted with v if (color[v] == WHITE && DFSUtil(v, color)) return true; } // Mark this vertex as processed color[u] = BLACK; return false; } // Returns true if there is a cycle in graph bool Graph::isCyclic() { // Initialize color of all vertices as WHITE int *color = new int[V]; for (int i = 0; i < V; i++) color[i] = WHITE; // Do a DFS traversal beginning with all // vertices for (int i = 0; i < V; i++) if (color[i] == WHITE) if (DFSUtil(i, color) == true) return true; return false; } // Driver code to test above int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); if (g.isCyclic()) cout << "Graph contains cycle"; else cout << "Graph doesn't contain cycle"; return 0; }
linear
linear
// C++ program to check if there is a cycle of // total odd weight #include <bits/stdc++.h> using namespace std; // This function returns true if the current subpart // of the forest is two colorable, else false. bool twoColorUtil(vector<int>G[], int src, int N, int colorArr[]) { // Assign first color to source colorArr[src] = 1; // Create a queue (FIFO) of vertex numbers and // enqueue source vertex for BFS traversal queue <int> q; q.push(src); // Run while there are vertices in queue // (Similar to BFS) while (!q.empty()){ int u = q.front(); q.pop(); // Find all non-colored adjacent vertices for (int v = 0; v < G[u].size(); ++v){ // An edge from u to v exists and // destination v is not colored if (colorArr[G[u][v]] == -1){ // Assign alternate color to this // adjacent v of u colorArr[G[u][v]] = 1 - colorArr[u]; q.push(G[u][v]); } // An edge from u to v exists and destination // v is colored with same color as u else if (colorArr[G[u][v]] == colorArr[u]) return false; } } return true; } // This function returns true if graph G[V][V] is two // colorable, else false bool twoColor(vector<int>G[], int N){ // Create a color array to store colors assigned // to all vertices. Vertex number is used as index // in this array. The value '-1' of colorArr[i] // is used to indicate that no color is assigned // to vertex 'i'. The value 1 is used to indicate // first color is assigned and value 0 indicates // second color is assigned. int colorArr[N]; for (int i = 1; i <= N; ++i) colorArr[i] = -1; // As we are dealing with graph, the input might // come as a forest, thus start coloring from a // node and if true is returned we'll know that // we successfully colored the subpart of our // forest and we start coloring again from a new // uncolored node. This way we cover the entire forest. for (int i = 1; i <= N; i++) if (colorArr[i] == -1) if (twoColorUtil(G, i, N, colorArr) == false) return false; return true; } // Returns false if an odd cycle is present else true // int info[][] is the information about our graph // int n is the number of nodes // int m is the number of informations given to us bool isOddSum(int info[][3],int n,int m){ // Declaring adjacency list of a graph // Here at max, we can encounter all the edges with // even weight thus there will be 1 pseudo node // for each edge vector<int> G[2*n]; int pseudo = n+1; int pseudo_count = 0; for (int i=0; i<m; i++){ // For odd weight edges, we directly add it // in our graph if (info[i][2]%2 == 1){ int u = info[i][0]; int v = info[i][1]; G[u].push_back(v); G[v].push_back(u); } // For even weight edges, we break it else{ int u = info[i][0]; int v = info[i][1]; // Entering a pseudo node between u---v G[u].push_back(pseudo); G[pseudo].push_back(u); G[v].push_back(pseudo); G[pseudo].push_back(v); // Keeping a record of number of pseudo nodes // inserted pseudo_count++; // Making a new pseudo node for next time pseudo++; } } // We pass number graph G[][] and total number // of node = actual number of nodes + number of // pseudo nodes added. return twoColor(G,n+pseudo_count); } // Driver function int main() { // 'n' correspond to number of nodes in our // graph while 'm' correspond to the number // of information about this graph. int n = 4, m = 4; int info[4][3] = {{1, 2, 12}, {2, 3, 1}, {4, 3, 1}, {4, 1, 20}}; // This function break the even weighted edges in // two parts. Makes the adjacency representation // of the graph and sends it for two coloring. if (isOddSum(info, n, m) == true) cout << "No\n"; else cout << "Yes\n"; return 0; }
linear
quadratic
// CPP program to implement Union-Find with union // by rank and path compression. #include <bits/stdc++.h> using namespace std; const int MAX_VERTEX = 101; // Arr to represent parent of index i int Arr[MAX_VERTEX]; // Size to represent the number of nodes // in subgraph rooted at index i int size[MAX_VERTEX]; // set parent of every node to itself and // size of node to one void initialize(int n) { for (int i = 0; i <= n; i++) { Arr[i] = i; size[i] = 1; } } // Each time we follow a path, find function // compresses it further until the path length // is greater than or equal to 1. int find(int i) { // while we reach a node whose parent is // equal to itself while (Arr[i] != i) { Arr[i] = Arr[Arr[i]]; // Skip one level i = Arr[i]; // Move to the new level } return i; } // A function that does union of two nodes x and y // where xr is root node of x and yr is root node of y void _union(int xr, int yr) { if (size[xr] < size[yr]) // Make yr parent of xr { Arr[xr] = Arr[yr]; size[yr] += size[xr]; } else // Make xr parent of yr { Arr[yr] = Arr[xr]; size[xr] += size[yr]; } } // The main function to check whether a given // graph contains cycle or not int isCycle(vector<int> adj[], int V) { // Iterate through all edges of graph, find // nodes connecting them. // If root nodes of both are same, then there is // cycle in graph. for (int i = 0; i < V; i++) { for (int j = 0; j < adj[i].size(); j++) { int x = find(i); // find root of i int y = find(adj[i][j]); // find root of adj[i][j] if (x == y) return 1; // If same parent _union(x, y); // Make them connect } } return 0; } // Driver progxrm to test above functions int main() { int V = 3; // Initialize the values for array Arr and Size initialize(V); /* Let us create following graph 0 | \ | \ 1-----2 */ vector<int> adj[V]; // Adjacency list for graph adj[0].push_back(1); adj[0].push_back(2); adj[1].push_back(2); // call is_cycle to check if it contains cycle if (isCycle(adj, V)) cout << "Graph contains Cycle.\n"; else cout << "Graph does not contain Cycle.\n"; return 0; }
constant
logn
// C++ program to find number of magical // indices in the given array. #include <bits/stdc++.h> using namespace std; #define mp make_pair #define pb push_back #define mod 1000000007 // Function to count number of magical indices. int solve(int A[], int n) { int i, cnt = 0, j; // Array to store parent node of traversal. int parent[n + 1]; // Array to determine whether current node // is already counted in the cycle. int vis[n + 1]; // Initialize the arrays. memset(parent, -1, sizeof(parent)); memset(vis, 0, sizeof(vis)); for (i = 0; i < n; i++) { j = i; // Check if current node is already // traversed or not. If node is not // traversed yet then parent value // will be -1. if (parent[j] == -1) { // Traverse the graph until an // already visited node is not // found. while (parent[j] == -1) { parent[j] = i; j = (j + A[j] + 1) % n; } // Check parent value to ensure // a cycle is present. if (parent[j] == i) { // Count number of nodes in // the cycle. while (!vis[j]) { vis[j] = 1; cnt++; j = (j + A[j] + 1) % n; } } } } return cnt; } int main() { int A[] = { 0, 0, 0, 2 }; int n = sizeof(A) / sizeof(A[0]); cout << solve(A, n); return 0; }
linear
linear
// C++ program to print all topological sorts of a graph #include <bits/stdc++.h> using namespace std; class Graph { int V; // No. of vertices // Pointer to an array containing adjacency list list<int> *adj; // Vector to store indegree of vertices vector<int> indegree; // A function used by alltopologicalSort void alltopologicalSortUtil(vector<int>& res, bool visited[]); public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w); // Prints all Topological Sorts void alltopologicalSort(); }; // Constructor of graph Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; // Initialising all indegree with 0 for (int i = 0; i < V; i++) indegree.push_back(0); } // Utility function to add edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); // Add w to v's list. // increasing inner degree of w by 1 indegree[w]++; } // Main recursive function to print all possible // topological sorts void Graph::alltopologicalSortUtil(vector<int>& res, bool visited[]) { // To indicate whether all topological are found // or not bool flag = false; for (int i = 0; i < V; i++) { // If indegree is 0 and not yet visited then // only choose that vertex if (indegree[i] == 0 && !visited[i]) { // reducing indegree of adjacent vertices list<int>:: iterator j; for (j = adj[i].begin(); j != adj[i].end(); j++) indegree[*j]--; // including in result res.push_back(i); visited[i] = true; alltopologicalSortUtil(res, visited); // resetting visited, res and indegree for // backtracking visited[i] = false; res.erase(res.end() - 1); for (j = adj[i].begin(); j != adj[i].end(); j++) indegree[*j]++; flag = true; } } // We reach here if all vertices are visited. // So we print the solution here if (!flag) { for (int i = 0; i < res.size(); i++) cout << res[i] << " "; cout << endl; } } // The function does all Topological Sort. // It uses recursive alltopologicalSortUtil() void Graph::alltopologicalSort() { // Mark all the vertices as not visited bool *visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; vector<int> res; alltopologicalSortUtil(res, visited); } // Driver program to test above functions int main() { // Create a graph given in the above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << "All Topological sorts\n"; g.alltopologicalSort(); return 0; }
linear
quadratic
// A C++ program to print topological // sorting of a graph using indegrees. #include <bits/stdc++.h> using namespace std; // Class to represent a graph class Graph { // No. of vertices' int V; // Pointer to an array containing // adjacency listsList list<int>* adj; public: // Constructor Graph(int V); // Function to add an edge to graph void addEdge(int u, int v); // prints a Topological Sort of // the complete graph void topologicalSort(); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); } // The function to do // Topological Sort. void Graph::topologicalSort() { // Create a vector to store // indegrees of all // vertices. Initialize all // indegrees as 0. vector<int> in_degree(V, 0); // Traverse adjacency lists // to fill indegrees of // vertices. This step // takes O(V+E) time for (int u = 0; u < V; u++) { list<int>::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) in_degree[*itr]++; } // Create an queue and enqueue // all vertices with indegree 0 queue<int> q; for (int i = 0; i < V; i++) if (in_degree[i] == 0) q.push(i); // Initialize count of visited vertices int cnt = 0; // Create a vector to store // result (A topological // ordering of the vertices) vector<int> top_order; // One by one dequeue vertices // from queue and enqueue // adjacents if indegree of // adjacent becomes 0 while (!q.empty()) { // Extract front of queue // (or perform dequeue) // and add it to topological order int u = q.front(); q.pop(); top_order.push_back(u); // Iterate through all its // neighbouring nodes // of dequeued node u and // decrease their in-degree // by 1 list<int>::iterator itr; for (itr = adj[u].begin(); itr != adj[u].end(); itr++) // If in-degree becomes zero, // add it to queue if (--in_degree[*itr] == 0) q.push(*itr); cnt++; } // Check if there was a cycle if (cnt != V) { cout << "There exists a cycle in the graph\n"; return; } // Print topological order for (int i = 0; i < top_order.size(); i++) cout << top_order[i] << " "; cout << endl; } // Driver program to test above functions int main() { // Create a graph given in the // above diagram Graph g(6); g.addEdge(5, 2); g.addEdge(5, 0); g.addEdge(4, 0); g.addEdge(4, 1); g.addEdge(2, 3); g.addEdge(3, 1); cout << "Following is a Topological Sort of\n"; g.topologicalSort(); return 0; }
linear
linear
// A C++ program for Prim's Minimum // Spanning Tree (MST) algorithm. The program is // for adjacency matrix representation of the graph #include <bits/stdc++.h> using namespace std; // Number of vertices in the graph #define V 5 // A utility function to find the vertex with // minimum key value, from the set of vertices // not yet included in MST int minKey(int key[], bool mstSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (mstSet[v] == false && key[v] < min) min = key[v], min_index = v; return min_index; } // A utility function to print the // constructed MST stored in parent[] void printMST(int parent[], int graph[V][V]) { cout << "Edge \tWeight\n"; for (int i = 1; i < V; i++) cout << parent[i] << " - " << i << " \t" << graph[i][parent[i]] << " \n"; } // Function to construct and print MST for // a graph represented using adjacency // matrix representation void primMST(int graph[V][V]) { // Array to store constructed MST int parent[V]; // Key values used to pick minimum weight edge in cut int key[V]; // To represent set of vertices included in MST bool mstSet[V]; // Initialize all keys as INFINITE for (int i = 0; i < V; i++) key[i] = INT_MAX, mstSet[i] = false; // Always include first 1st vertex in MST. // Make key 0 so that this vertex is picked as first // vertex. key[0] = 0; parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex from the // set of vertices not yet included in MST int u = minKey(key, mstSet); // Add the picked vertex to the MST Set mstSet[u] = true; // Update key value and parent index of // the adjacent vertices of the picked vertex. // Consider only those vertices which are not // yet included in MST for (int v = 0; v < V; v++) // graph[u][v] is non zero only for adjacent // vertices of m mstSet[v] is false for vertices // not yet included in MST Update the key only // if graph[u][v] is smaller than key[v] if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v]) parent[v] = u, key[v] = graph[u][v]; } // print the constructed MST printMST(parent, graph); } // Driver's code int main() { /* Let us create the following graph 2 3 (0)--(1)--(2) | / \ | 6| 8/ \5 |7 | / \ | (3)-------(4) 9 */ int graph[V][V] = { { 0, 2, 0, 6, 0 }, { 2, 0, 3, 8, 5 }, { 0, 3, 0, 0, 7 }, { 6, 8, 0, 0, 9 }, { 0, 5, 7, 9, 0 } }; // Print the solution primMST(graph); return 0; } // This code is contributed by rathbhupendra
linear
quadratic
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // DSU data structure // path compression + rank by union class DSU { int* parent; int* rank; public: DSU(int n) { parent = new int[n]; rank = new int[n]; for (int i = 0; i < n; i++) { parent[i] = -1; rank[i] = 1; } } // Find function int find(int i) { if (parent[i] == -1) return i; return parent[i] = find(parent[i]); } // Union function void unite(int x, int y) { int s1 = find(x); int s2 = find(y); if (s1 != s2) { if (rank[s1] < rank[s2]) { parent[s1] = s2; rank[s2] += rank[s1]; } else { parent[s2] = s1; rank[s1] += rank[s2]; } } } }; class Graph { vector<vector<int> > edgelist; int V; public: Graph(int V) { this->V = V; } void addEdge(int x, int y, int w) { edgelist.push_back({ w, x, y }); } void kruskals_mst() { // 1. Sort all edges sort(edgelist.begin(), edgelist.end()); // Initialize the DSU DSU s(V); int ans = 0; cout << "Following are the edges in the " "constructed MST" << endl; for (auto edge : edgelist) { int w = edge[0]; int x = edge[1]; int y = edge[2]; // Take this edge in MST if it does // not forms a cycle if (s.find(x) != s.find(y)) { s.unite(x, y); ans += w; cout << x << " -- " << y << " == " << w << endl; } } cout << "Minimum Cost Spanning Tree: " << ans; } }; // Driver's code int main() { /* Let us create following weighted graph 10 0--------1 | \ | 6| 5\ |15 | \ | 2--------3 4 */ Graph g(4); g.addEdge(0, 1, 10); g.addEdge(1, 3, 15); g.addEdge(2, 3, 4); g.addEdge(2, 0, 6); g.addEdge(0, 3, 5); // Function call g.kruskals_mst(); return 0; }
linear
nlogn
/* C++ program to solve N Queen Problem using backtracking */ #include <bits/stdc++.h> #define N 4 using namespace std; /* A utility function to print solution */ void printSolution(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << " " << board[i][j] << " "; printf("\n"); } } /* A utility function to check if a queen can be placed on board[row][col]. Note that this function is called when "col" queens are already placed in columns from 0 to col -1. So we need to check only left side for attacking queens */ bool isSafe(int board[N][N], int row, int col) { int i, j; /* Check this row on left side */ for (i = 0; i < col; i++) if (board[row][i]) return false; /* Check upper diagonal on left side */ for (i = row, j = col; i >= 0 && j >= 0; i--, j--) if (board[i][j]) return false; /* Check lower diagonal on left side */ for (i = row, j = col; j >= 0 && i < N; i++, j--) if (board[i][j]) return false; return true; } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int board[N][N], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ if (isSafe(board, i, col)) { /* Place this queen in board[i][col] */ board[i][col] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK } } /* If the queen cannot be placed in any row in this column col then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout << "Solution does not exist"; return false; } printSolution(board); return true; } // driver program to test above function int main() { solveNQ(); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
quadratic
np
/* C++ program to solve N Queen Problem using backtracking */ #include<bits/stdc++.h> using namespace std; #define N 4 /* ld is an array where its indices indicate row-col+N-1 (N-1) is for shifting the difference to store negative indices */ int ld[30] = { 0 }; /* rd is an array where its indices indicate row+col and used to check whether a queen can be placed on right diagonal or not*/ int rd[30] = { 0 }; /*column array where its indices indicates column and used to check whether a queen can be placed in that row or not*/ int cl[30] = { 0 }; /* A utility function to print solution */ void printSolution(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout<<" "<< board[i][j]<<" "; cout<<endl; } } /* A recursive utility function to solve N Queen problem */ bool solveNQUtil(int board[N][N], int col) { /* base case: If all queens are placed then return true */ if (col >= N) return true; /* Consider this column and try placing this queen in all rows one by one */ for (int i = 0; i < N; i++) { /* Check if the queen can be placed on board[i][col] */ /* A check if a queen can be placed on board[row][col].We just need to check ld[row-col+n-1] and rd[row+coln] where ld and rd are for left and right diagonal respectively*/ if ((ld[i - col + N - 1] != 1 && rd[i + col] != 1) && cl[i] != 1) { /* Place this queen in board[i][col] */ board[i][col] = 1; ld[i - col + N - 1] = rd[i + col] = cl[i] = 1; /* recur to place rest of the queens */ if (solveNQUtil(board, col + 1)) return true; /* If placing queen in board[i][col] doesn't lead to a solution, then remove queen from board[i][col] */ board[i][col] = 0; // BACKTRACK ld[i - col + N - 1] = rd[i + col] = cl[i] = 0; } } /* If the queen cannot be placed in any row in this column col then return false */ return false; } /* This function solves the N Queen problem using Backtracking. It mainly uses solveNQUtil() to solve the problem. It returns false if queens cannot be placed, otherwise, return true and prints placement of queens in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions.*/ bool solveNQ() { int board[N][N] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; if (solveNQUtil(board, 0) == false) { cout<<"Solution does not exist"; return false; } printSolution(board); return true; } // driver program to test above function int main() { solveNQ(); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
linear
np
// C++ program for Dijkstra's single source shortest path // algorithm. The program is for adjacency matrix // representation of the graph #include <iostream> using namespace std; #include <limits.h> // Number of vertices in the graph #define V 9 // A utility function to find the vertex with minimum // distance value, from the set of vertices not yet included // in shortest path tree int minDistance(int dist[], bool sptSet[]) { // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index; } // A utility function to print the constructed distance // array void printSolution(int dist[]) { cout << "Vertex \t Distance from Source" << endl; for (int i = 0; i < V; i++) cout << i << " \t\t\t\t" << dist[i] << endl; } // Function that implements Dijkstra's single source // shortest path algorithm for a graph represented using // adjacency matrix representation void dijkstra(int graph[V][V], int src) { int dist[V]; // The output array. dist[i] will hold the // shortest // distance from src to i bool sptSet[V]; // sptSet[i] will be true if vertex i is // included in shortest // path tree or shortest distance from src to i is // finalized // Initialize all distances as INFINITE and stpSet[] as // false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of // vertices not yet processed. u is always equal to // src in the first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the // picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, // there is an edge from u to v, and total // weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist); } // driver's code int main() { /* Let us create the example graph discussed above */ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; // Function call dijkstra(graph, 0); return 0; } // This code is contributed by shivanisinghss2110
linear
quadratic
// C++ Program to find Dijkstra's shortest path using // priority_queue in STL #include <bits/stdc++.h> using namespace std; #define INF 0x3f3f3f3f // iPair ==> Integer Pair typedef pair<int, int> iPair; // This class represents a directed graph using // adjacency list representation class Graph { int V; // No. of vertices // In a weighted graph, we need to store vertex // and weight pair for every edge list<pair<int, int> >* adj; public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int u, int v, int w); // prints shortest path from s void shortestPath(int s); }; // Allocates memory for adjacency list Graph::Graph(int V) { this->V = V; adj = new list<iPair>[V]; } void Graph::addEdge(int u, int v, int w) { adj[u].push_back(make_pair(v, w)); adj[v].push_back(make_pair(u, w)); } // Prints shortest paths from src to all other vertices void Graph::shortestPath(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<iPair, vector<iPair>, greater<iPair> > pq; // Create a vector for distances and initialize all // distances as infinite (INF) vector<int> 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 list<pair<int, int> >::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { // 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]); } // Driver's code int main() { // create the graph given in above figure int V = 9; Graph g(V); // making above shown graph g.addEdge(0, 1, 4); g.addEdge(0, 7, 8); g.addEdge(1, 2, 8); g.addEdge(1, 7, 11); g.addEdge(2, 3, 7); g.addEdge(2, 8, 2); g.addEdge(2, 5, 4); g.addEdge(3, 4, 9); g.addEdge(3, 5, 14); g.addEdge(4, 5, 10); g.addEdge(5, 6, 2); g.addEdge(6, 7, 1); g.addEdge(6, 8, 6); g.addEdge(7, 8, 7); // Function call g.shortestPath(0); return 0; }
linear
nlogn
// A C++ program for Bellman-Ford's single source // shortest path algorithm. #include <bits/stdc++.h> using namespace std; // a structure to represent a weighted edge in graph struct Edge { int src, dest, weight; }; // a structure to represent a connected, directed and // weighted graph struct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge; }; // Creates a graph with V vertices and E edges struct Graph* createGraph(int V, int E) { struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[E]; return graph; } // A utility function used to print the solution void printArr(int dist[], int n) { printf("Vertex Distance from Source\n"); for (int i = 0; i < n; ++i) printf("%d \t\t %d\n", i, dist[i]); } // The main function that finds shortest distances from src // to all other vertices using Bellman-Ford algorithm. The // function also detects negative weight cycle void BellmanFord(struct Graph* graph, int src) { int V = graph->V; int E = graph->E; int dist[V]; // Step 1: Initialize distances from src to all other // vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. A simple // shortest path from src to any other vertex can have // at-most |V| - 1 edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. The above // step guarantees shortest distances if graph doesn't // contain negative weight cycle. If we get a shorter // path, then there is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { printf("Graph contains negative weight cycle"); return; // If negative cycle is detected, simply // return } } printArr(dist, V); return; } // Driver's code int main() { /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or B-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; // Function call BellmanFord(graph, 0); return 0; }
linear
quadratic
// C++ Program for Floyd Warshall Algorithm #include <bits/stdc++.h> using namespace std; // Number of vertices in the graph #define V 4 /* Define Infinite as a large enough value.This value will be used for vertices not connected to each other */ #define INF 99999 // A function to print the solution matrix void printSolution(int dist[][V]); // Solves the all-pairs shortest path // problem using Floyd Warshall algorithm void floydWarshall(int graph[][V]) { /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of // dist[i][j] if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF && dist[i][k] != INF)) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist); } /* A utility function to print solution */ void printSolution(int dist[][V]) { cout << "The following matrix shows the shortest " "distances" " between every pair of vertices \n"; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) cout << "INF" << " "; else cout << dist[i][j] << " "; } cout << endl; } } // Driver's code int main() { /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[V][V] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF }, { INF, INF, 0, 1 }, { INF, INF, INF, 0 } }; // Function call floydWarshall(graph); return 0; } // This code is contributed by Mythri J L
quadratic
cubic
// Dynamic Programming based C++ program to find shortest path with // exactly k edges #include <iostream> #include <climits> using namespace std; // Define number of vertices in the graph and infinite value #define V 4 #define INF INT_MAX // A Dynamic programming based function to find the shortest path from // u to v with exactly k edges. int shortestPath(int graph[][V], int u, int v, int k) { // Table to be filled up using DP. The value sp[i][j][e] will store // weight of the shortest path from i to j with exactly k edges int sp[V][V][k+1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value sp[i][j][e] = INF; // from base cases if (e == 0 && i == j) sp[i][j][e] = 0; if (e == 1 && graph[i][j] != INF) sp[i][j][e] = graph[i][j]; //go to adjacent only when number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) { // There should be an edge from i to a and a // should not be same as either i or j if (graph[i][a] != INF && i != a && j!= a && sp[a][j][e-1] != INF) sp[i][j][e] = min(sp[i][j][e], graph[i][a] + sp[a][j][e-1]); } } } } } return sp[u][v][k]; } // driver program to test above function int main() { /* Let us create the graph shown in above diagram*/ int graph[V][V] = { {0, 10, 3, 2}, {INF, 0, INF, 7}, {INF, INF, 0, 6}, {INF, INF, INF, 0} }; int u = 0, v = 3, k = 2; cout << shortestPath(graph, u, v, k); return 0; }
np
cubic
// CPP code for printing shortest path between // two vertices of unweighted graph #include <bits/stdc++.h> using namespace std; // utility function to form edge between two vertices // source and dest void add_edge(vector<int> adj[], int src, int dest) { adj[src].push_back(dest); adj[dest].push_back(src); } // a modified version of BFS that stores predecessor // of each vertex in array p // and its distance from source in array d bool BFS(vector<int> adj[], int src, int dest, int v, int pred[], int dist[]) { // a queue to maintain queue of vertices whose // adjacency list is to be scanned as per normal // DFS algorithm list<int> queue; // boolean array visited[] which stores the // information whether ith vertex is reached // at least once in the Breadth first search bool visited[v]; // initially all vertices are unvisited // so v[i] for all i is false // and as no path is yet constructed // dist[i] for all i set to infinity for (int i = 0; i < v; i++) { visited[i] = false; dist[i] = INT_MAX; pred[i] = -1; } // now source is first to be visited and // distance from source to itself should be 0 visited[src] = true; dist[src] = 0; queue.push_back(src); // standard BFS algorithm while (!queue.empty()) { int u = queue.front(); queue.pop_front(); for (int i = 0; i < adj[u].size(); i++) { if (visited[adj[u][i]] == false) { visited[adj[u][i]] = true; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.push_back(adj[u][i]); // We stop BFS when we find // destination. if (adj[u][i] == dest) return true; } } } return false; } // utility function to print the shortest distance // between source vertex and destination vertex void printShortestDistance(vector<int> adj[], int s, int dest, int v) { // predecessor[i] array stores predecessor of // i and distance array stores distance of i // from s int pred[v], dist[v]; if (BFS(adj, s, dest, v, pred, dist) == false) { cout << "Given source and destination" << " are not connected"; return; } // vector path stores the shortest path vector<int> path; int crawl = dest; path.push_back(crawl); while (pred[crawl] != -1) { path.push_back(pred[crawl]); crawl = pred[crawl]; } // distance from source is in distance array cout << "Shortest path length is : " << dist[dest]; // printing path from source to destination cout << "\nPath is::\n"; for (int i = path.size() - 1; i >= 0; i--) cout << path[i] << " "; } // Driver program to test above functions int main() { // no. of vertices int v = 8; // array of vectors is used to store the graph // in the form of an adjacency list vector<int> adj[v]; // Creating graph given in the above diagram. // add_edge function takes adjacency list, source // and destination vertex as argument and forms // an edge between them. add_edge(adj, 0, 1); add_edge(adj, 0, 3); add_edge(adj, 1, 2); add_edge(adj, 3, 4); add_edge(adj, 3, 7); add_edge(adj, 4, 5); add_edge(adj, 4, 6); add_edge(adj, 4, 7); add_edge(adj, 5, 6); add_edge(adj, 6, 7); int source = 0, dest = 7; printShortestDistance(adj, source, dest, v); return 0; }
linear
linear
// C++ program to get least cost path in a grid from // top-left to bottom-right #include <bits/stdc++.h> using namespace std; #define ROW 5 #define COL 5 // structure for information of each cell struct cell { int x, y; int distance; cell(int x, int y, int distance) : x(x) , y(y) , distance(distance) { } }; // Utility method for comparing two cells bool operator<(const cell& a, const cell& b) { if (a.distance == b.distance) { if (a.x != b.x) return (a.x < b.x); else return (a.y < b.y); } return (a.distance < b.distance); } // Utility method to check whether a point is // inside the grid or not bool isInsideGrid(int i, int j) { return (i >= 0 && i < ROW && j >= 0 && j < COL); } // Method returns minimum cost to reach bottom // right from top left int shortest(int grid[ROW][COL], int row, int col) { int dis[row][col]; // initializing distance array by INT_MAX for (int i = 0; i < row; i++) for (int j = 0; j < col; j++) dis[i][j] = INT_MAX; // direction arrays for simplification of getting // neighbour int dx[] = { -1, 0, 1, 0 }; int dy[] = { 0, 1, 0, -1 }; set<cell> st; // insert (0, 0) cell with 0 distance st.insert(cell(0, 0, 0)); // initialize distance of (0, 0) with its grid value dis[0][0] = grid[0][0]; // loop for standard dijkstra's algorithm while (!st.empty()) { // get the cell with minimum distance and delete // it from the set cell k = *st.begin(); st.erase(st.begin()); // looping through all neighbours for (int i = 0; i < 4; i++) { int x = k.x + dx[i]; int y = k.y + dy[i]; // if not inside boundary, ignore them if (!isInsideGrid(x, y)) continue; // If distance from current cell is smaller, // then update distance of neighbour cell if (dis[x][y] > dis[k.x][k.y] + grid[x][y]) { // If cell is already there in set, then // remove its previous entry if (dis[x][y] != INT_MAX) st.erase( st.find(cell(x, y, dis[x][y]))); // update the distance and insert new // updated cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y]; st.insert(cell(x, y, dis[x][y])); } } } // uncomment below code to print distance // of each cell from (0, 0) /* for (int i = 0; i < row; i++, cout << endl) for (int j = 0; j < col; j++) cout << dis[i][j] << " "; */ // dis[row - 1][col - 1] will represent final // distance of bottom right cell from top left cell return dis[row - 1][col - 1]; } // Driver code to test above methods int main() { int grid[ROW][COL] = { 31, 100, 65, 12, 18, 10, 13, 47, 157, 6, 100, 113, 174, 11, 33, 88, 124, 41, 20, 140, 99, 32, 111, 41, 20 }; cout << shortest(grid, ROW, COL) << endl; return 0; }
quadratic
quadratic
// C++ program to replace all of the O's in the matrix // with their shortest distance from a guard #include <bits/stdc++.h> using namespace std; // store dimensions of the matrix #define M 5 #define N 5 // An Data Structure for queue used in BFS struct queueNode { // i, j and distance stores x and y-coordinates // of a matrix cell and its distance from guard // respectively int i, j, distance; }; // These arrays are used to get row and column // numbers of 4 neighbors of a given cell int row[] = { -1, 0, 1, 0}; int col[] = { 0, 1, 0, -1 }; // return true if row number and column number // is in range bool isValid(int i, int j) { if ((i < 0 || i > M - 1) || (j < 0 || j > N - 1)) return false; return true; } // return true if current cell is an open area and its // distance from guard is not calculated yet bool isSafe(int i, int j, char matrix[][N], int output[][N]) { if (matrix[i][j] != 'O' || output[i][j] != -1) return false; return true; } // Function to replace all of the O's in the matrix // with their shortest distance from a guard void findDistance(char matrix[][N]) { int output[M][N]; queue<queueNode> q; // finding Guards location and adding into queue for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { // initialize each cell as -1 output[i][j] = -1; if (matrix[i][j] == 'G') { queueNode pos = {i, j, 0}; q.push(pos); // guard has 0 distance output[i][j] = 0; } } } // do till queue is empty while (!q.empty()) { // get the front cell in the queue and update // its adjacent cells queueNode curr = q.front(); int x = curr.i, y = curr.j, dist = curr.distance; // do for each adjacent cell for (int i = 0; i < 4; i++) { // if adjacent cell is valid, has path and // not visited yet, en-queue it. if (isSafe(x + row[i], y + col[i], matrix, output) && isValid(x + row[i], y + col[i])) { output[x + row[i]][y + col[i]] = dist + 1; queueNode pos = {x + row[i], y + col[i], dist + 1}; q.push(pos); } } // dequeue the front cell as its distance is found q.pop(); } // print output matrix for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) cout << std::setw(3) << output[i][j]; cout << endl; } } // Driver code int main() { char matrix[][N] = { {'O', 'O', 'O', 'O', 'G'}, {'O', 'W', 'W', 'O', 'O'}, {'O', 'O', 'O', 'W', 'O'}, {'G', 'W', 'W', 'W', 'O'}, {'O', 'O', 'O', 'O', 'G'} }; findDistance(matrix); return 0; }
quadratic
quadratic
// C++ program to find articulation points in an undirected graph #include <bits/stdc++.h> using namespace std; // A recursive function that find articulation // points using DFS traversal // adj[] --> Adjacency List representation of the graph // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // low[] -- >> earliest visited vertex (the vertex with minimum // discovery time) that can be reached from subtree // rooted with current vertex // parent --> Stores the parent vertex in DFS tree // isAP[] --> Stores articulation points void APUtil(vector<int> adj[], int u, bool visited[], int disc[], int low[], int& time, int parent, bool isAP[]) { // 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 adjacent to this for (auto v : adj[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++; APUtil(adj, v, visited, disc, low, time, u, isAP); // Check if the subtree rooted with v has // a connection to one of the ancestors of u low[u] = min(low[u], low[v]); // If u is not root and low value of one of // its child is more than discovery value of u. if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } // Update low value of u for parent function calls. else if (v != parent) low[u] = min(low[u], disc[v]); } // If u is root of DFS tree and has two or more children. if (parent == -1 && children > 1) isAP[u] = true; } void AP(vector<int> adj[], int V) { int disc[V] = { 0 }; int low[V]; bool visited[V] = { false }; bool isAP[V] = { false }; int time = 0, par = -1; // Adding this loop so that the // code works even if we are given // disconnected graph for (int u = 0; u < V; u++) if (!visited[u]) APUtil(adj, u, visited, disc, low, time, par, isAP); // Printing the APs for (int u = 0; u < V; u++) if (isAP[u] == true) cout << u << " "; } // Utility function to add an edge void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } int main() { // Create graphs given in above diagrams cout << "Articulation points in first graph \n"; int V = 5; vector<int> adj1[V]; addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); AP(adj1, V); cout << "\nArticulation points in second graph \n"; V = 4; vector<int> adj2[V]; addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); AP(adj2, V); cout << "\nArticulation points in third graph \n"; V = 7; vector<int> adj3[V]; addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); AP(adj3, V); return 0; }
linear
linear
// C++ Program to count islands in boolean 2D matrix #include <bits/stdc++.h> using namespace std; #define ROW 5 #define COL 5 // A function to check if a given // cell (row, col) can be included in DFS int isSafe(int M[][COL], int row, int col, bool visited[][COL]) { // row number is in range, column // number is in range and value is 1 // and not yet visited return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] && !visited[row][col]); } // A utility function to do DFS for a // 2D boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(int M[][COL], int row, int col, bool visited[][COL]) { // These arrays are used to get // row and column numbers of 8 // neighbours of a given cell static int rowNbr[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; static int colNbr[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; // Mark this cell as visited visited[row][col] = true; // Recur for all connected neighbours for (int k = 0; k < 8; ++k) if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited)) DFS(M, row + rowNbr[k], col + colNbr[k], visited); } // The main function that returns // count of islands in a given boolean // 2D matrix int countIslands(int M[][COL]) { // Make a bool array to mark visited cells. // Initially all cells are unvisited bool visited[ROW][COL]; memset(visited, 0, sizeof(visited)); // Initialize count as 0 and // traverse through the all cells of // given matrix int count = 0; for (int i = 0; i < ROW; ++i) for (int j = 0; j < COL; ++j) // If a cell with value 1 is not if (M[i][j] && !visited[i][j]) { // visited yet, then new island found // Visit all cells in this island. DFS(M, i, j, visited); // and increment island count ++count; } return count; } // Driver code int main() { int M[][COL] = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << "Number of islands is: " << countIslands(M); return 0; } // This is code is contributed by rathbhupendra
quadratic
quadratic
// C++Program to count islands in boolean 2D matrix #include <bits/stdc++.h> using namespace std; // A utility function to do DFS for a 2D // boolean matrix. It only considers // the 8 neighbours as adjacent vertices void DFS(vector<vector<int> >& M, int i, int j, int ROW, int COL) { // Base condition // if i less than 0 or j less than 0 or i greater than // ROW-1 or j greater than COL- or if M[i][j] != 1 then // we will simply return if (i < 0 || j < 0 || i > (ROW - 1) || j > (COL - 1) || M[i][j] != 1) { return; } if (M[i][j] == 1) { M[i][j] = 0; DFS(M, i + 1, j, ROW, COL); // right side traversal DFS(M, i - 1, j, ROW, COL); // left side traversal DFS(M, i, j + 1, ROW, COL); // upward side traversal DFS(M, i, j - 1, ROW, COL); // downward side traversal DFS(M, i + 1, j + 1, ROW, COL); // upward-right side traversal DFS(M, i - 1, j - 1, ROW, COL); // downward-left side traversal DFS(M, i + 1, j - 1, ROW, COL); // downward-right side traversal DFS(M, i - 1, j + 1, ROW, COL); // upward-left side traversal } } int countIslands(vector<vector<int> >& M) { int ROW = M.size(); int COL = M[0].size(); int count = 0; for (int i = 0; i < ROW; i++) { for (int j = 0; j < COL; j++) { if (M[i][j] == 1) { count++; DFS(M, i, j, ROW, COL); // traversal starts // from current cell } } } return count; } // Driver Code int main() { vector<vector<int> > M = { { 1, 1, 0, 0, 0 }, { 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1 }, { 0, 0, 0, 0, 0 }, { 1, 0, 1, 0, 1 } }; cout << "Number of islands is: " << countIslands(M); return 0; } // This code is contributed by ajaymakvana. // Code improved by Animesh Singh
quadratic
quadratic
// C++ program to find number of islands // using Disjoint Set data structure. #include <bits/stdc++.h> using namespace std; // Class to represent // Disjoint Set Data structure class DisjointUnionSets { vector<int> rank, parent; int n; public: DisjointUnionSets(int n) { rank.resize(n); parent.resize(n); this->n = n; makeSet(); } void makeSet() { // Initially, all elements // are in their own set. for (int i = 0; i < n; i++) parent[i] = i; } // Finds the representative of the set // that x is an element of int find(int x) { if (parent[x] != x) { // if x is not the parent of itself, // then x is not the representative of // its set. // so we recursively call Find on its parent // and move i's node directly under the // representative of this set parent[x]=find(parent[x]); } return parent[x]; } // Unites the set that includes x and the set // that includes y void Union(int x, int y) { // Find the representatives(or the root nodes) // for x an y int xRoot = find(x); int yRoot = find(y); // Elements are in the same set, // no need to unite anything. if (xRoot == yRoot) return; // If x's rank is less than y's rank // Then move x under y so that // depth of tree remains less if (rank[xRoot] < rank[yRoot]) parent[xRoot] = yRoot; // Else if y's rank is less than x's rank // Then move y under x so that depth of tree // remains less else if (rank[yRoot] < rank[xRoot]) parent[yRoot] = xRoot; else // Else if their ranks are the same { // Then move y under x (doesn't matter // which one goes where) parent[yRoot] = xRoot; // And increment the result tree's // rank by 1 rank[xRoot] = rank[xRoot] + 1; } } }; // Returns number of islands in a[][] int countIslands(vector<vector<int>>a) { int n = a.size(); int m = a[0].size(); DisjointUnionSets *dus = new DisjointUnionSets(n * m); /* The following loop checks for its neighbours and unites the indexes if both are 1. */ for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { // If cell is 0, nothing to do if (a[j][k] == 0) continue; // Check all 8 neighbours and do a Union // with neighbour's set if neighbour is // also 1 if (j + 1 < n && a[j + 1][k] == 1) dus->Union(j * (m) + k, (j + 1) * (m) + k); if (j - 1 >= 0 && a[j - 1][k] == 1) dus->Union(j * (m) + k, (j - 1) * (m) + k); if (k + 1 < m && a[j][k + 1] == 1) dus->Union(j * (m) + k, (j) * (m) + k + 1); if (k - 1 >= 0 && a[j][k - 1] == 1) dus->Union(j * (m) + k, (j) * (m) + k - 1); if (j + 1 < n && k + 1 < m && a[j + 1][k + 1] == 1) dus->Union(j * (m) + k, (j + 1) * (m) + k + 1); if (j + 1 < n && k - 1 >= 0 && a[j + 1][k - 1] == 1) dus->Union(j * m + k, (j + 1) * (m) + k - 1); if (j - 1 >= 0 && k + 1 < m && a[j - 1][k + 1] == 1) dus->Union(j * m + k, (j - 1) * m + k + 1); if (j - 1 >= 0 && k - 1 >= 0 && a[j - 1][k - 1] == 1) dus->Union(j * m + k, (j - 1) * m + k - 1); } } // Array to note down frequency of each set int *c = new int[n * m]; int numberOfIslands = 0; for (int j = 0; j < n; j++) { for (int k = 0; k < m; k++) { if (a[j][k] == 1) { int x = dus->find(j * m + k); // If frequency of set is 0, // increment numberOfIslands if (c[x] == 0) { numberOfIslands++; c[x]++; } else c[x]++; } } } return numberOfIslands; } // Driver Code int main(void) { vector<vector<int>>a = {{1, 1, 0, 0, 0}, {0, 1, 0, 0, 1}, {1, 0, 0, 1, 1}, {0, 0, 0, 0, 0}, {1, 0, 1, 0, 1}}; cout << "Number of Islands is: " << countIslands(a) << endl; } // This code is contributed by ankush_953
quadratic
quadratic
// C++ program to count walks from u to // v with exactly k edges #include <iostream> using namespace std; // Number of vertices in the graph #define V 4 // A naive recursive function to count // walks from u to v with k edges int countwalks(int graph[][V], int u, int v, int k) { // Base cases if (k == 0 && u == v) return 1; if (k == 1 && graph[u][v]) return 1; if (k <= 0) return 0; // Initialize result int count = 0; // Go to all adjacents of u and recur for (int i = 0; i < V; i++) if (graph[u][i] == 1) // Check if is adjacent of u count += countwalks(graph, i, v, k - 1); return count; } // driver program to test above function int main() { /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0; }
linear
quadratic
// C++ program to count walks from // u to v with exactly k edges #include <iostream> using namespace std; // Number of vertices in the graph #define V 4 // A Dynamic programming based function to count walks from u // to v with k edges int countwalks(int graph[][V], int u, int v, int k) { // Table to be filled up using DP. // The value count[i][j][e] will // store count of possible walks from // i to j with exactly k edges int count[V][V][k + 1]; // Loop for number of edges from 0 to k for (int e = 0; e <= k; e++) { for (int i = 0; i < V; i++) // for source { for (int j = 0; j < V; j++) // for destination { // initialize value count[i][j][e] = 0; // from base cases if (e == 0 && i == j) count[i][j][e] = 1; if (e == 1 && graph[i][j]) count[i][j][e] = 1; // go to adjacent only when the // number of edges is more than 1 if (e > 1) { for (int a = 0; a < V; a++) // adjacent of source i if (graph[i][a]) count[i][j][e] += count[a][j][e - 1]; } } } } return count[u][v][k]; } // driver program to test above function int main() { /* Let us create the graph shown in above diagram*/ int graph[V][V] = { { 0, 1, 1, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 1 }, { 0, 0, 0, 0 } }; int u = 0, v = 3, k = 2; cout << countwalks(graph, u, v, k); return 0; }
np
cubic
// C++ program to find length // of the shortest chain // transformation from source // to target #include <bits/stdc++.h> using namespace std; // Returns length of shortest chain // to reach 'target' from 'start' // using minimum number of adjacent // moves. D is dictionary int shortestChainLen( string start, string target, set<string>& D) { if(start == target) return 0; // If the target string is not // present in the dictionary if (D.find(target) == D.end()) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.size(); // Push the starting word into the queue queue<string> Q; Q.push(start); // While the queue is non-empty while (!Q.empty()) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.size(); // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue string word = Q.front(); Q.pop(); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (word == target) return level + 1; // Remove the word from the set // if it is found in it if (D.find(word) == D.end()) continue; D.erase(word); // And push the newly generated word // which will be a part of the chain Q.push(word); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0; } // Driver program int main() { // make dictionary set<string> D; D.insert("poon"); D.insert("plee"); D.insert("same"); D.insert("poie"); D.insert("plie"); D.insert("poin"); D.insert("plea"); string start = "toon"; string target = "plea"; cout << "Length of shortest chain is: " << shortestChainLen(start, target, D); return 0; }
quadratic
cubic
// C++ program to find length // of the shortest chain // transformation from source // to target #include <bits/stdc++.h> using namespace std; // Returns length of shortest chain // to reach 'target' from 'start' // using minimum number of adjacent // moves. D is dictionary int shortestChainLen( string start, string target, set<string>& D) { if(start == target) return 0; // Map of intermediate words and // the list of original words map<string, vector<string>> umap; // Find all the intermediate // words for the start word for(int i = 0; i < start.size(); i++) { string str = start.substr(0,i) + "*" + start.substr(i+1); umap[str].push_back(start); } // Find all the intermediate words for // the words in the given Set for(auto it = D.begin(); it != D.end(); it++) { string word = *it; for(int j = 0; j < word.size(); j++) { string str = word.substr(0,j) + "*" + word.substr(j+1); umap[str].push_back(word); } } // Perform BFS and push (word, distance) queue<pair<string, int>> q; map<string, int> visited; q.push(make_pair(start,1)); visited[start] = 1; // Traverse until queue is empty while(!q.empty()) { pair<string, int> p = q.front(); q.pop(); string word = p.first; int dist = p.second; // If target word is found if(word == target) { return dist; } // Finding intermediate words for // the word in front of queue for(int i = 0; i < word.size(); i++) { string str = word.substr(0,i) + "*" + word.substr(i+1); vector<string> vect = umap[str]; for(int j = 0; j < vect.size(); j++) { // If the word is not visited if(visited[vect[j]] == 0) { visited[vect[j]] = 1; q.push(make_pair(vect[j], dist + 1)); } } } } return 0; } // Driver code int main() { // Make dictionary set<string> D; D.insert("poon"); D.insert("plee"); D.insert("same"); D.insert("poie"); D.insert("plie"); D.insert("poin"); D.insert("plea"); string start = "toon"; string target = "plea"; cout << "Length of shortest chain is: " << shortestChainLen(start, target, D); return 0; }
quadratic
cubic
// C++ program to print all paths // from a source to destination. #include <iostream> #include <list> using namespace std; // A directed graph using // adjacency list representation class Graph { int V; // No. of vertices in graph list<int>* adj; // Pointer to an array containing // adjacency lists // A recursive function used by printAllPaths() void printAllPathsUtil(int, int, bool[], int[], int&); public: Graph(int V); // Constructor void addEdge(int u, int v); void printAllPaths(int s, int d); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } void Graph::addEdge(int u, int v) { adj[u].push_back(v); // Add v to u’s list. } // Prints all paths from 's' to 'd' void Graph::printAllPaths(int s, int d) { // Mark all the vertices as not visited bool* visited = new bool[V]; // Create an array to store paths int* path = new int[V]; int path_index = 0; // Initialize path[] as empty // Initialize all vertices as not visited for (int i = 0; i < V; i++) visited[i] = false; // Call the recursive helper function to print all paths printAllPathsUtil(s, d, visited, path, path_index); } // A recursive function to print all paths from 'u' to 'd'. // visited[] keeps track of vertices in current path. // path[] stores actual vertices and path_index is current // index in path[] void Graph::printAllPathsUtil(int u, int d, bool visited[], int path[], int& path_index) { // Mark the current node and store it in path[] visited[u] = true; path[path_index] = u; path_index++; // If current vertex is same as destination, then print // current path[] if (u == d) { for (int i = 0; i < path_index; i++) cout << path[i] << " "; cout << endl; } else // If current vertex is not destination { // Recur for all the vertices adjacent to current // vertex list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) if (!visited[*i]) printAllPathsUtil(*i, d, visited, path, path_index); } // Remove current vertex from path[] and mark it as // unvisited path_index--; visited[u] = false; } // Driver program int main() { // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(0, 3); g.addEdge(2, 0); g.addEdge(2, 1); g.addEdge(1, 3); int s = 2, d = 3; cout << "Following are all different paths from " << s << " to " << d << endl; g.printAllPaths(s, d); return 0; }
np
quadratic
// C++ code to check if cyclic order is possible among strings // under given constraints #include <bits/stdc++.h> using namespace std; #define M 26 // Utility method for a depth first search among vertices void dfs(vector<int> g[], int u, vector<bool> &visit) { visit[u] = true; for (int i = 0; i < g[u].size(); ++i) if(!visit[g[u][i]]) dfs(g, g[u][i], visit); } // Returns true if all vertices are strongly connected // i.e. can be made as loop bool isConnected(vector<int> g[], vector<bool> &mark, int s) { // Initialize all vertices as not visited vector<bool> visit(M, false); // perform a dfs from s dfs(g, s, visit); // now loop through all characters for (int i = 0; i < M; i++) { /* I character is marked (i.e. it was first or last character of some string) then it should be visited in last dfs (as for looping, graph should be strongly connected) */ if (mark[i] && !visit[i]) return false; } // If we reach that means graph is connected return true; } // return true if an order among strings is possible bool possibleOrderAmongString(string arr[], int N) { // Create an empty graph vector<int> g[M]; // Initialize all vertices as not marked vector<bool> mark(M, false); // Initialize indegree and outdegree of every // vertex as 0. vector<int> in(M, 0), out(M, 0); // Process all strings one by one for (int i = 0; i < N; i++) { // Find first and last characters int f = arr[i].front() - 'a'; int l = arr[i].back() - 'a'; // Mark the characters mark[f] = mark[l] = true; // increase indegree and outdegree count in[l]++; out[f]++; // Add an edge in graph g[f].push_back(l); } // If for any character indegree is not equal to // outdegree then ordering is not possible for (int i = 0; i < M; i++) if (in[i] != out[i]) return false; return isConnected(g, mark, arr[0].front() - 'a'); } // Driver code to test above methods int main() { // string arr[] = {"abc", "efg", "cde", "ghi", "ija"}; string arr[] = {"ab", "bc", "cd", "de", "ed", "da"}; int N = sizeof(arr) / sizeof(arr[0]); if (possibleOrderAmongString(arr, N) == false) cout << "Ordering not possible\n"; else cout << "Ordering is possible\n"; return 0; }
linear
linear
// C++ program to count cyclic points // in an array using Kosaraju's Algorithm #include <bits/stdc++.h> using namespace std; // Most of the code is taken from below link // https://www.geeksforgeeks.org/strongly-connected-components/ class Graph { int V; list<int>* adj; void fillOrder(int v, bool visited[], stack<int>& Stack); int DFSUtil(int v, bool visited[]); public: Graph(int V); void addEdge(int v, int w); int countSCCNodes(); Graph getTranspose(); }; Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } // Counts number of nodes reachable // from v int Graph::DFSUtil(int v, bool visited[]) { visited[v] = true; int ans = 1; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) ans += DFSUtil(*i, visited); return ans; } Graph Graph::getTranspose() { Graph g(V); for (int v = 0; v < V; v++) { list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) g.adj[*i].push_back(v); } return g; } void Graph::addEdge(int v, int w) { adj[v].push_back(w); } void Graph::fillOrder(int v, bool visited[], stack<int>& Stack) { visited[v] = true; list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) fillOrder(*i, visited, Stack); Stack.push(v); } // This function mainly returns total count of // nodes in individual SCCs using Kosaraju's // algorithm. int Graph::countSCCNodes() { int res = 0; stack<int> Stack; bool* visited = new bool[V]; for (int i = 0; i < V; i++) visited[i] = false; for (int i = 0; i < V; i++) if (visited[i] == false) fillOrder(i, visited, Stack); Graph gr = getTranspose(); for (int i = 0; i < V; i++) visited[i] = false; while (Stack.empty() == false) { int v = Stack.top(); Stack.pop(); if (visited[v] == false) { int ans = gr.DFSUtil(v, visited); if (ans > 1) res += ans; } } return res; } // Returns count of cyclic elements in arr[] int countCyclic(int arr[], int n) { int res = 0; // Create a graph of array elements Graph g(n + 1); for (int i = 1; i <= n; i++) { int x = arr[i-1]; // If i + arr[i-1] jumps beyond last // element, we take mod considering // cyclic array int v = (x + i) % n + 1; // If there is a self loop, we // increment count of cyclic points. if (i == v) res++; g.addEdge(i, v); } // Add nodes of strongly connected components // of size more than 1. res += g.countSCCNodes(); return res; } // Driver code int main() { int arr[] = {1, 1, 1, 1}; int n = sizeof(arr)/sizeof(arr[0]); cout << countCyclic(arr, n); return 0; }
linear
linear
// C++ program to print connected components in // an undirected graph #include <bits/stdc++.h> using namespace std; // Graph class represents a undirected graph // using adjacency list representation class Graph { int V; // No. of vertices // Pointer to an array containing adjacency lists list<int>* adj; // A function used by DFS void DFSUtil(int v, bool visited[]); public: Graph(int V); // Constructor ~Graph(); void addEdge(int v, int w); void connectedComponents(); }; // Method to print connected components in an // undirected graph void Graph::connectedComponents() { // Mark all the vertices as not visited bool* visited = new bool[V]; for (int v = 0; v < V; v++) visited[v] = false; for (int v = 0; v < V; v++) { if (visited[v] == false) { // print all reachable vertices // from v DFSUtil(v, visited); cout << "\n"; } } delete[] visited; } void Graph::DFSUtil(int v, bool visited[]) { // Mark the current node as visited and print it visited[v] = true; cout << v << " "; // Recur for all the vertices // adjacent to this vertex list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i, visited); } Graph::Graph(int V) { this->V = V; adj = new list<int>[V]; } Graph::~Graph() { delete[] adj; } // method to add an undirected edge void Graph::addEdge(int v, int w) { adj[v].push_back(w); adj[w].push_back(v); } // Driver code int main() { // Create a graph given in the above diagram Graph g(5); // 5 vertices numbered from 0 to 4 g.addEdge(1, 0); g.addEdge(2, 1); g.addEdge(3, 4); cout << "Following are connected components \n"; g.connectedComponents(); return 0; }
linear
linear
#include <bits/stdc++.h> using namespace std; int merge(int* parent, int x) { if (parent[x] == x) return x; return merge(parent, parent[x]); } int connectedcomponents(int n, vector<vector<int> >& edges) { int parent[n]; for (int i = 0; i < n; i++) { parent[i] = i; } for (auto x : edges) { parent[merge(parent, x[0])] = merge(parent, x[1]); } int ans = 0; for (int i = 0; i < n; i++) { ans += (parent[i] == i); } for (int i = 0; i < n; i++) { parent[i] = merge(parent, parent[i]); } map<int, list<int> > m; for (int i = 0; i < n; i++) { m[parent[i]].push_back(i); } for (auto it = m.begin(); it != m.end(); it++) { list<int> l = it->second; for (auto x : l) { cout << x << " "; } cout << endl; } return ans; } int main() { int n = 5; vector<int> e1 = { 0, 1 }; vector<int> e2 = { 2, 1 }; vector<int> e3 = { 3, 4 }; vector<vector<int> > e; e.push_back(e1); e.push_back(e2); e.push_back(e3); cout << "Following are connected components:\n"; int a = connectedcomponents(n, e); return 0; }
linear
linear
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; int maxindex(int* dist, int n) { int mi = 0; for (int i = 0; i < n; i++) { if (dist[i] > dist[mi]) mi = i; } return mi; } void selectKcities(int n, int weights[4][4], int k) { int* dist = new int[n]; vector<int> centers; for (int i = 0; i < n; i++) { dist[i] = INT_MAX; } // index of city having the // maximum distance to it's // closest center int max = 0; for (int i = 0; i < k; i++) { centers.push_back(max); for (int j = 0; j < n; j++) { // updating the distance // of the cities to their // closest centers dist[j] = min(dist[j], weights[max][j]); } // updating the index of the // city with the maximum // distance to it's closest center max = maxindex(dist, n); } // Printing the maximum distance // of a city to a center // that is our answer cout << endl << dist[max] << endl; // Printing the cities that // were chosen to be made // centers for (int i = 0; i < centers.size(); i++) { cout << centers[i] << " "; } cout << endl; } // Driver Code int main() { int n = 4; int weights[4][4] = { { 0, 4, 8, 5 }, { 4, 0, 10, 7 }, { 8, 10, 0, 9 }, { 5, 7, 9, 0 } }; int k = 2; // Function Call selectKcities(n, weights, k); } // Contributed by Balu Nagar
constant
quadratic
// C++ program to find minimum time required to make all // oranges rotten #include <bits/stdc++.h> #define R 3 #define C 5 using namespace std; // function to check whether a cell is valid / invalid bool isvalid(int i, int j) { return (i >= 0 && j >= 0 && i < R && j < C); } // structure for storing coordinates of the cell struct ele { int x, y; }; // Function to check whether the cell is delimiter // which is (-1, -1) bool isdelim(ele temp) { return (temp.x == -1 && temp.y == -1); } // Function to check whether there is still a fresh // orange remaining bool checkall(int arr[][C]) { for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) if (arr[i][j] == 1) return true; return false; } // This function finds if it is possible to rot all oranges // or not. If possible, then it returns minimum time // required to rot all, otherwise returns -1 int rotOranges(int arr[][C]) { // Create a queue of cells queue<ele> Q; ele temp; int ans = 0; // Store all the cells having rotten orange in first // time frame for (int i = 0; i < R; i++) { for (int j = 0; j < C; j++) { if (arr[i][j] == 2) { temp.x = i; temp.y = j; Q.push(temp); } } } // Separate these rotten oranges from the oranges which // will rotten due the oranges in first time frame using // delimiter which is (-1, -1) temp.x = -1; temp.y = -1; Q.push(temp); // Process the grid while there are rotten oranges in // the Queue while (!Q.empty()) { // This flag is used to determine whether even a // single fresh orange gets rotten due to rotten // oranges in current time frame so we can increase // the count of the required time. bool flag = false; // Process all the rotten oranges in current time // frame. while (!isdelim(Q.front())) { temp = Q.front(); // Check right adjacent cell that if it can be // rotten if (isvalid(temp.x + 1, temp.y) && arr[temp.x + 1][temp.y] == 1) { // if this is the first orange to get // rotten, increase count and set the flag. if (!flag) ans++, flag = true; // Make the orange rotten arr[temp.x + 1][temp.y] = 2; // push the adjacent orange to Queue temp.x++; Q.push(temp); temp.x--; // Move back to current cell } // Check left adjacent cell that if it can be // rotten if (isvalid(temp.x - 1, temp.y) && arr[temp.x - 1][temp.y] == 1) { if (!flag) ans++, flag = true; arr[temp.x - 1][temp.y] = 2; temp.x--; Q.push(temp); // push this cell to Queue temp.x++; } // Check top adjacent cell that if it can be // rotten if (isvalid(temp.x, temp.y + 1) && arr[temp.x][temp.y + 1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y + 1] = 2; temp.y++; Q.push(temp); // Push this cell to Queue temp.y--; } // Check bottom adjacent cell if it can be // rotten if (isvalid(temp.x, temp.y - 1) && arr[temp.x][temp.y - 1] == 1) { if (!flag) ans++, flag = true; arr[temp.x][temp.y - 1] = 2; temp.y--; Q.push(temp); // push this cell to Queue } Q.pop(); } // Pop the delimiter Q.pop(); // If oranges were rotten in current frame then // separate the rotten oranges using delimiter for // the next frame for processing. if (!Q.empty()) { temp.x = -1; temp.y = -1; Q.push(temp); } // If Queue was empty then no rotten oranges left to // process so exit } // Return -1 if all arranges could not rot, otherwise // return ans. return (checkall(arr)) ? -1 : ans; } // Driver program int main() { int arr[][C] = { { 2, 1, 0, 2, 1 }, { 1, 0, 1, 2, 1 }, { 1, 0, 0, 2, 1 } }; int ans = rotOranges(arr); if (ans == -1) cout << "All oranges cannot rotn"; else cout << "Time required for all oranges to rot => " << ans << endl; return 0; }
quadratic
quadratic
// CPP14 program to find common contacts. #include <bits/stdc++.h> using namespace std; // The class DSU will implement the Union Find class DSU { vector<int> parent, size; public: // In the constructor, we assign the each index as its // own parent and size as the number of contacts // available for that index DSU(vector<vector<string> >& contacts) { for (int i = 0; i < contacts.size(); i++) { parent.push_back(i); size.push_back(contacts[i].size()); } } // Finds the set in which the element belongs. Path // compression is used to optimise time complexity int findSet(int v) { if (v == parent[v]) return v; return parent[v] = findSet(parent[v]); } // Unifies the sets a and b where, the element belonging // to the smaller set is merged to the one belonging to // the smaller set void unionSet(int a, int b, vector<string>& person1, vector<string>& person2) { if (size[a] > size[b]) { parent[b] = a; size[a] += size[b]; for (auto contact : person2) person1.push_back(contact); } else { parent[a] = b; size[b] += size[a]; for (auto contact : person1) person2.push_back(contact); } } }; // Driver Code int main() { vector<vector<string> > contacts = { { "Gaurav", "gaurav@gmail.com", "gaurav@gfgQA.com" }, { "Lucky", "lucky@gmail.com", "+1234567" }, { "gaurav123", "+5412312", "gaurav123@skype.com" }, { "gaurav1993", "+5412312", "gaurav@gfgQA.com" }, { "raja", "+2231210", "raja@gfg.com" }, { "bahubali", "+878312", "raja" } }; // Initializing the object of DSU class DSU dsu(contacts); // Will contain the mapping of a contact to all the // indices it is present within unordered_map<string, vector<int> > contactToIndex; for (int index = 0; index < contacts.size(); index++) { for (auto contact : contacts[index]) contactToIndex[contact].push_back(index); } // Unifies the sets of each contact if they are not // present in the same set for (auto contact : contactToIndex) { vector<int> indices = contact.second; for (int i = 0; i < indices.size() - 1; i++) { int set1 = dsu.findSet(indices[i]), set2 = dsu.findSet(indices[i + 1]); if (set1 != set2) dsu.unionSet(set1, set2, contacts[set1], contacts[set2]); } } // Contains a map of all the distinct sets available // after union find has been completed unordered_map<int, vector<int> > unifiedSet; // All parents are mapped to the elements in the set for (int i = 0; i < contacts.size(); i++) { unifiedSet[dsu.findSet(i)].push_back(i); } // Printing out elements from distinct sets for (auto eachSet : unifiedSet) { for (auto element : eachSet.second) cout << element << " "; cout << endl; } return 0; }
linear
np
#include <bits/stdc++.h> using namespace std; void print_sieve(int& x) { int i,temp,digit; bool check; for(i=0;i<=x;i++) { if(i<10) { cout<<i<<" "; continue; } check=1; temp=i; digit=temp%10; temp/=10; while(temp) { if(abs(digit-temp%10)!=1) { check=0; break; } digit=temp%10; temp/=10; } if(check) cout<<i<<" "; } } int main() { int x=105; print_sieve(x); return 0; }
constant
linear
// Finds and prints all jumping numbers smaller than or // equal to x. #include <bits/stdc++.h> using namespace std; // Prints all jumping numbers smaller than or equal to x starting // with 'num'. It mainly does BFS starting from 'num'. void bfs(int x, int num) { // Create a queue and enqueue 'i' to it queue<int> q; q.push(num); // Do BFS starting from i while (!q.empty()) { num = q.front(); q.pop(); if (num <= x) { cout << num << " "; int last_dig = num % 10; // If last digit is 0, append next digit only if (last_dig == 0) q.push((num * 10) + (last_dig + 1)); // If last digit is 9, append previous digit only else if (last_dig == 9) q.push((num * 10) + (last_dig - 1)); // If last digit is neither 0 nor 9, append both // previous and next digits else { q.push((num * 10) + (last_dig - 1)); q.push((num * 10) + (last_dig + 1)); } } } } // Prints all jumping numbers smaller than or equal to // a positive number x void printJumping(int x) { cout << 0 << " "; for (int i = 1; i <= 9 && i <= x; i++) bfs(x, i); } // Driver program int main() { int x = 40; printJumping(x); return 0; }
constant
linear
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find and print pair bool chkPair(int A[], int size, int x) { for (int i = 0; i < (size - 1); i++) { for (int j = (i + 1); j < size; j++) { if (A[i] + A[j] == x) { return 1; } } } return 0; } // Driver code int main() { int A[] = { 0, -1, 2, -3, 1 }; int x = -2; int size = sizeof(A) / sizeof(A[0]); if (chkPair(A, size, x)) { cout << "Yes" << endl; } else { cout << "No" << x << endl; } return 0; } // This code is contributed by Samim Hossain Mondal.
constant
quadratic
// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include <bits/stdc++.h> using namespace std; // Function to check if array has 2 elements // whose sum is equal to the given value bool hasArrayTwoCandidates(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); /* Now look for the two candidates in the sorted array*/ l = 0; r = arr_size - 1; while (l < r) { if (A[l] + A[r] == sum) return 1; else if (A[l] + A[r] < sum) l++; else // A[l] + A[r] > sum r--; } return 0; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (hasArrayTwoCandidates(A, arr_size, n)) cout << "Yes"; else cout << "No"; return 0; }
constant
nlogn
// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include <bits/stdc++.h> using namespace std; bool binarySearch(int A[], int low, int high, int searchKey) { while (low <= high) { int m = low + (high - low) / 2; // Check if searchKey is present at mid if (A[m] == searchKey) return true; // If searchKey greater, ignore left half if (A[m] < searchKey) low = m + 1; // If searchKey is smaller, ignore right half else high = m - 1; } // if we reach here, then element was // not present return false; } bool checkTwoSum(int A[], int arr_size, int sum) { int l, r; /* Sort the elements */ sort(A, A + arr_size); // Traversing all element in an array search for // searchKey for (int i = 0; i < arr_size - 1; i++) { int searchKey = sum - A[i]; // calling binarySearch function if (binarySearch(A, i + 1, arr_size - 1, searchKey) == true) { return true; } } return false; } /* Driver program to test above function */ int main() { int A[] = { 1, 4, 45, 6, 10, -8 }; int n = 14; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling if (checkTwoSum(A, arr_size, n)) cout << "Yes"; else cout << "No"; return 0; }
constant
nlogn
// C++ program to check if given array // has 2 elements whose sum is equal // to the given value #include <bits/stdc++.h> using namespace std; void printPairs(int arr[], int arr_size, int sum) { unordered_set<int> s; for (int i = 0; i < arr_size; i++) { int temp = sum - arr[i]; if (s.find(temp) != s.end()) { cout << "Yes" << endl; return; } s.insert(arr[i]); } cout << "No" << endl; } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; }
linear
linear
// Code in cpp to tell if there exists a pair in array whose // sum results in x. #include <iostream> using namespace std; // Function to print pairs void printPairs(int a[], int n, int x) { int i; int rem[x]; // initializing the rem values with 0's. for (i = 0; i < x; i++) rem[i] = 0; // Perform the remainder operation only if the element // is x, as numbers greater than x can't be used to get // a sum x. Updating the count of remainders. for (i = 0; i < n; i++) if (a[i] < x) rem[a[i] % x]++; // Traversing the remainder list from start to middle to // find pairs for (i = 1; i < x / 2; i++) { if (rem[i] > 0 && rem[x - i] > 0) { // The elements with remainders i and x-i will // result to a sum of x. Once we get two // elements which add up to x , we print x and // break. cout << "Yes\n"; break; } } // Once we reach middle of remainder array, we have to // do operations based on x. if (i >= x / 2) { if (x % 2 == 0) { // if x is even and we have more than 1 elements // with remainder x/2, then we will have two // distinct elements which add up to x. if we // dont have more than 1 element, print "No". if (rem[x / 2] > 1) cout << "Yes\n"; else cout << "No\n"; } else { // When x is odd we continue the same process // which we did in previous loop. if (rem[x / 2] > 0 && rem[x - x / 2] > 0) cout << "Yes\n"; else cout << "No\n"; } } } /* Driver Code */ int main() { int A[] = { 1, 4, 45, 6, 10, 8 }; int n = 16; int arr_size = sizeof(A) / sizeof(A[0]); // Function calling printPairs(A, arr_size, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
linear
linear
// CPP program to find the minimum number of // operations required to make all elements // of array equal #include <bits/stdc++.h> using namespace std; // function for min operation int minOperation (int arr[], int n) { // Insert all elements in hash. unordered_map<int, int> hash; for (int i=0; i<n; i++) hash[arr[i]]++; // find the max frequency int max_count = 0; for (auto i : hash) if (max_count < i.second) max_count = i.second; // return result return (n - max_count); } // driver program int main() { int arr[] = {1, 5, 2, 1, 3, 2, 1}; int n = sizeof(arr) / sizeof(arr[0]); cout << minOperation(arr, n); return 0; }
linear
linear
// C++ program to find maximum distance between two // same occurrences of a number. #include<bits/stdc++.h> using namespace std; // Function to find maximum distance between equal elements int maxDistance(int arr[], int n) { // Used to store element to first index mapping unordered_map<int, int> mp; // Traverse elements and find maximum distance between // same occurrences with the help of map. int max_dist = 0; for (int i=0; i<n; i++) { // If this is first occurrence of element, insert its // index in map if (mp.find(arr[i]) == mp.end()) mp[arr[i]] = i; // Else update max distance else max_dist = max(max_dist, i - mp[arr[i]]); } return max_dist; } // Driver program to run the case int main() { int arr[] = {3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2}; int n = sizeof(arr)/sizeof(arr[0]); cout << maxDistance(arr, n); return 0; }
linear
linear
/* C/C++ program to find maximum number of point which lie on same line */ #include <bits/stdc++.h> #include <boost/functional/hash.hpp> using namespace std; // method to find maximum collinear point int maxPointOnSameLine(vector< pair<int, int> > points) { int N = points.size(); if (N < 2) return N; int maxPoint = 0; int curMax, overlapPoints, verticalPoints; // here since we are using unordered_map // which is based on hash function //But by default we don't have hash function for pairs //so we'll use hash function defined in Boost library unordered_map<pair<int, int>, int,boost:: hash<pair<int, int> > > slopeMap; // looping for each point for (int i = 0; i < N; i++) { curMax = overlapPoints = verticalPoints = 0; // looping from i + 1 to ignore same pair again for (int j = i + 1; j < N; j++) { // If both point are equal then just // increase overlapPoint count if (points[i] == points[j]) overlapPoints++; // If x co-ordinate is same, then both // point are vertical to each other else if (points[i].first == points[j].first) verticalPoints++; else { int yDif = points[j].second - points[i].second; int xDif = points[j].first - points[i].first; int g = __gcd(xDif, yDif); // reducing the difference by their gcd yDif /= g; xDif /= g; // increasing the frequency of current slope // in map slopeMap[make_pair(yDif, xDif)]++; curMax = max(curMax, slopeMap[make_pair(yDif, xDif)]); } curMax = max(curMax, verticalPoints); } // updating global maximum by current point's maximum maxPoint = max(maxPoint, curMax + overlapPoints + 1); // printf("maximum collinear point // which contains current point // are : %d\n", curMax + overlapPoints + 1); slopeMap.clear(); } return maxPoint; } // Driver code int main() { const int N = 6; int arr[N][2] = {{-1, 1}, {0, 0}, {1, 1}, {2, 2}, {3, 3}, {3, 4}}; vector< pair<int, int> > points; for (int i = 0; i < N; i++) points.push_back(make_pair(arr[i][0], arr[i][1])); cout << maxPointOnSameLine(points) << endl; return 0; }
linear
quadratic
// C++ implementation of the // above approach #include <bits/stdc++.h> using namespace std; // Function to find the Duplicates, // if duplicate occurs 2 times or // more than 2 times in array so, // it will print duplicate value // only once at output void findDuplicates(int arr[], int len) { // Initialize ifPresent as false bool ifPresent = false; // ArrayList to store the output vector<int> al; for(int i = 0; i < len - 1; i++) { for(int j = i + 1; j < len; j++) { if (arr[i] == arr[j]) { // Checking if element is // present in the ArrayList // or not if present then break auto it = std::find(al.begin(), al.end(), arr[i]); if (it != al.end()) { break; } // If element is not present in the // ArrayList then add it to ArrayList // and make ifPresent at true else { al.push_back(arr[i]); ifPresent = true; } } } } // If duplicates is present // then print ArrayList if (ifPresent == true) { cout << "[" << al[0] << ", "; for(int i = 1; i < al.size() - 1; i++) { cout << al[i] << ", "; } cout << al[al.size() - 1] << "]"; } else { cout << "No duplicates present in arrays"; } } // Driver code int main() { int arr[] = { 12, 11, 40, 12, 5, 6, 5, 12, 11 }; int n = sizeof(arr) / sizeof(arr[0]); findDuplicates(arr, n); return 0; } // This code is contributed by divyeshrabadiya07
linear
quadratic
// C++ program to find // duplicates in the given array #include <bits/stdc++.h> using namespace std; // function to find and print duplicates void printDuplicates(int arr[], int n) { // unordered_map to store frequencies unordered_map<int, int> freq; for (int i=0; i<n; i++) freq[arr[i]]++; bool dup = false; unordered_map<int, int>:: iterator itr; for (itr=freq.begin(); itr!=freq.end(); itr++) { // if frequency is more than 1 // print the element if (itr->second > 1) { cout << itr->first << " "; dup = true; } } // no duplicates present if (dup == false) cout << "-1"; } // Driver program to test above int main() { int arr[] = {12, 11, 40, 12, 5, 6, 5, 12, 11}; int n = sizeof(arr) / sizeof(arr[0]); printDuplicates(arr, n); return 0; }
linear
linear
// C++ program to find top k elements in a stream #include <bits/stdc++.h> using namespace std; // Function to print top k numbers void kTop(int a[], int n, int k) { // vector of size k+1 to store elements vector<int> top(k + 1); // array to keep track of frequency unordered_map<int, int> freq; // iterate till the end of stream for (int m = 0; m < n; m++) { // increase the frequency freq[a[m]]++; // store that element in top vector top[k] = a[m]; // search in top vector for same element auto it = find(top.begin(), top.end() - 1, a[m]); // iterate from the position of element to zero for (int i = distance(top.begin(), it) - 1; i >= 0; --i) { // compare the frequency and swap if higher // frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]) swap(top[i], top[i + 1]); // if frequency is same compare the elements // and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) && (top[i] > top[i + 1])) swap(top[i], top[i + 1]); else break; } // print top k elements for (int i = 0; i < k && top[i] != 0; ++i) cout << top[i] << ' '; } cout << endl; } // Driver program to test above function int main() { int k = 4; int arr[] = { 5, 2, 1, 3, 2 }; int n = sizeof(arr) / sizeof(arr[0]); kTop(arr, n, k); return 0; }
linear
quadratic
// CPP program to find the most frequent element // in an array. #include <bits/stdc++.h> using namespace std; int mostFrequent(int arr[], int n) { // Sort the array sort(arr, arr + n); // Find the max frequency using linear traversal int max_count = 1, res = arr[0], curr_count = 1; for (int i = 1; i < n; i++) { if (arr[i] == arr[i - 1]) curr_count++; else curr_count = 1; if (curr_count > max_count) { max_count = curr_count; res = arr[i - 1]; } } return res; } // Driver program int main() { int arr[] = { 40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
constant
nlogn
// CPP program to find the most frequent element // in an array. #include <bits/stdc++.h> using namespace std; int mostFrequent(int arr[], int n) { // Insert all elements in hash. unordered_map<int, int> hash; for (int i = 0; i < n; i++) hash[arr[i]]++; // find the max frequency int max_count = 0, res = -1; for (auto i : hash) { if (max_count < i.second) { res = i.first; max_count = i.second; } } return res; } // driver program int main() { int arr[] = {40,50,30,40,50,30,30 }; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFrequent(arr, n); return 0; }
linear
linear
#include <iostream> using namespace std; int maxFreq(int *arr, int n) { //using moore's voting algorithm int res = 0; int count = 1; for(int i = 1; i < n; i++) { if(arr[i] == arr[res]) { count++; } else { count--; } if(count == 0) { res = i; count = 1; } } return arr[res]; } int main() { int arr[] = {40,50,30,40,50,30,30}; int n = sizeof(arr) / sizeof(arr[0]); int freq = maxFreq(arr , n); int count = 0; for(int i = 0; i < n; i++) { if(arr[i] == freq) { count++; } } cout <<"Element " << maxFreq(arr , n) << " occurs " << count << " times" << endl;; return 0; //This code is contributed by Ashish Kumar Shakya }
constant
linear
// C++ implementation to find first // element occurring k times #include <bits/stdc++.h> using namespace std; // Function to find the first element // occurring k number of times int firstElement(int arr[], int n, int k) { // This loop is used for selection // of elements for (int i = 0; i < n; i++) { // Count how many time selected element // occurs int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) count++; } // Check, if it occurs k times or not if (count == k) return arr[i]; } return -1; } // Driver Code int main() { int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0; }
constant
quadratic
// C++ implementation to find first // element occurring k times #include <bits/stdc++.h> using namespace std; // function to find the first element // occurring k number of times int firstElement(int arr[], int n, int k) { // unordered_map to count // occurrences of each element unordered_map<int, int> count_map; for (int i=0; i<n; i++) count_map[arr[i]]++; for (int i=0; i<n; i++) // if count of element == k ,then // it is the required first element if (count_map[arr[i]] == k) return arr[i]; // no element occurs k times return -1; } // Driver program to test above int main() { int arr[] = {1, 7, 4, 3, 4, 8, 7}; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << firstElement(arr, n, k); return 0; }
linear
linear
// C++ implementation to find first // element occurring k times #include <bits/stdc++.h> using namespace std; // function to find the first element // occurring k number of times int firstElement(int arr[], int n, int k) { // unordered_map to count // occurrences of each element map<int, int> count_map; for (int i = 0; i < n; i++) { count_map[arr[i]]++; } // count_map[arr[i]]++; for (int i = 0; i < n; i++) // if count of element == k ,then // it is the required first element { if (count_map.find(arr[i]) != count_map.end()) { if (count_map[arr[i]] == k) return arr[i]; } } // no element occurs k times return -1; } // Driver code int main() { int arr[] = { 1, 7, 4, 3, 4, 8, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; cout << (firstElement(arr, n, k)); return 0; } // This code is contributed by Rajput-Ji
linear
nlogn
// A C++ program to find all symmetric pairs in a given // array of pairs #include <bits/stdc++.h> using namespace std; void findSymPairs(int arr[][2], int row) { // This loop for selection of one pair for (int i = 0; i < row; i++) { // This loop for searching of symmetric pair for (int j = i + 1; j < row; j++) { // Condition of symmetric pair if (arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]) { cout << "(" << arr[i][0] << ", " << arr[i][1] << ")" << endl; } } } } // Driver method int main() { int arr[5][2]; arr[0][0] = 11; arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; arr[2][0] = 5; arr[2][1] = 10; arr[3][0] = 40; arr[3][1] = 30; arr[4][0] = 10; arr[4][1] = 5; cout << "Following pairs have symmetric pairs\n"; findSymPairs(arr, 5); } // This is contributed by Arpit Jain
constant
quadratic
#include<bits/stdc++.h> using namespace std; // A C++ program to find all symmetric pairs in a given array of pairs // Print all pairs that have a symmetric counterpart void findSymPairs(int arr[][2], int row) { // Creates an empty hashMap hM unordered_map<int, int> hM; // Traverse through the given array for (int i = 0; i < row; i++) { // First and second elements of current pair int first = arr[i][0]; int sec = arr[i][1]; // If found and value in hash matches with first // element of this pair, we found symmetry if (hM.find(sec) != hM.end() && hM[sec] == first) cout << "(" << sec << ", " << first << ")" <<endl; else // Else put sec element of this pair in hash hM[first] = sec; } } // Driver method int main() { int arr[5][2]; arr[0][0] = 11; arr[0][1] = 20; arr[1][0] = 30; arr[1][1] = 40; arr[2][0] = 5; arr[2][1] = 10; arr[3][0] = 40; arr[3][1] = 30; arr[4][0] = 10; arr[4][1] = 5; cout<<"Following pairs have symmetric pairs\n"; findSymPairs(arr, 5); } //This is contributed by Chhavi
linear
linear
// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (arr[i] == arr[j]) return arr[i]; } } } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // This code is added by Arpit Jain
constant
quadratic
// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { sort(arr, arr + N); // sort array for (int i = 0; i < N; i++) { // compare array element with its index if (arr[i] != i + 1) { return arr[i]; } } return -1; } // driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; } // this code is contributed by devendra solunke
constant
nlogn
// C++ program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { unordered_set<int> s; for (int i = 0; i < N; i++) { if (s.find(arr[i]) != s.end()) return arr[i]; s.insert(arr[i]); } // If input is correct, we should // never reach here return -1; } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
linear
linear
// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { // Find array sum and subtract sum // first N-1 natural numbers from it // to find the result. return accumulate(arr, arr + N, 0) - ((N - 1) * N / 2); } // Driver's code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
constant
linear
// CPP program to find the only repeating // element in an array where elements are // from 1 to N-1. #include <bits/stdc++.h> using namespace std; int findRepeating(int arr[], int N) { // res is going to store value of // 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ // arr[1] ^ .... arr[N-1] int res = 0; for (int i = 0; i < N - 1; i++) res = res ^ (i + 1) ^ arr[i]; res = res ^ arr[N - 1]; return res; } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
constant
linear
// CPP program to find the only // repeating element in an array // where elements are from 1 to N-1. #include <bits/stdc++.h> using namespace std; // Function to find repeated element int findRepeating(int arr[], int N) { int missingElement = 0; // indexing based for (int i = 0; i < N; i++) { int element = arr[abs(arr[i])]; if (element < 0) { missingElement = arr[i]; break; } arr[abs(arr[i])] = -arr[abs(arr[i])]; } return abs(missingElement); } // Driver code int main() { int arr[] = { 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call cout << findRepeating(arr, N); return 0; }
constant
linear
#include <bits/stdc++.h> using namespace std; int findDuplicate(vector<int>& nums) { int slow = nums[0]; int fast = nums[0]; do { slow = nums[slow]; fast = nums[nums[fast]]; } while (slow != fast); fast = nums[0]; while (slow != fast) { slow = nums[slow]; fast = nums[fast]; } return slow; } // Driver code int main() { vector<int> v{ 9, 8, 2, 6, 1, 8, 5, 3, 4, 7 }; // Function call int ans = findDuplicate(v); cout << ans << endl; return 0; }
constant
linear
// C++ program to find one of the repeating // elements in a read only array #include <bits/stdc++.h> using namespace std; // Function to find one of the repeating // elements int findRepeatingNumber(const int arr[], int n) { for (int i = 0; i < n; i++) { int count = 0; for (int j = 0; j < n; j++) { if (arr[i] == arr[j]) count++; } if (count > 1) return arr[i]; } // If no repeating element exists return -1; } // Driver Code int main() { // Read only array const int arr[] = { 1, 1, 2, 3, 5, 4 }; int n = 5; cout << "One of the numbers repeated in" " the array is: " << findRepeatingNumber(arr, n) << endl; }
constant
quadratic
// C++ Program to Find the top three repeated numbers #include <bits/stdc++.h> using namespace std; /* Function to print top three repeated numbers */ void top3Repeated(int arr[], int n) { // There should be atleast two elements if (n < 3) { cout << "Invalid Input"; return; } // Count Frequency of each element unordered_map<int, int> fre; for (int i = 0; i < n; i++) fre[arr[i]]++; // Initialize first value of each variable // of Pair type is INT_MIN pair<int, int> x, y, z; x.first = y.first = z.first = INT_MIN; for (auto curr : fre) { // If frequency of current element // is not zero and greater than // frequency of first largest element if (curr.second > x.first) { // Update second and third largest z = y; y = x; // Modify values of x Number x.first = curr.second; x.second = curr.first; } // If frequency of current element is // not zero and frequency of current // element is less than frequency of // first largest element, but greater // than y element else if (curr.second > y.first) { // Modify values of third largest z = y; // Modify values of second largest y.first = curr.second; y.second = curr.first; } // If frequency of current element // is not zero and frequency of // current element is less than // frequency of first element and // second largest, but greater than // third largest. else if (curr.second > z.first) { // Modify values of z Number z.first = curr.second; z.second = curr.first; } } cout << "Three largest elements are " << x.second << " " << y.second << " " << z.second; } // Driver's Code int main() { int arr[] = { 3, 4, 2, 3, 16, 3, 15, 16, 15, 15, 16, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); top3Repeated(arr, n); return 0; }
linear
linear
// A simple C++ program to group multiple occurrences of individual // array elements #include<bits/stdc++.h> using namespace std; // A simple method to group all occurrences of individual elements void groupElements(int arr[], int n) { // Initialize all elements as not visited bool *visited = new bool[n]; for (int i=0; i<n; i++) visited[i] = false; // Traverse all elements for (int i=0; i<n; i++) { // Check if this is first occurrence if (!visited[i]) { // If yes, print it and all subsequent occurrences cout << arr[i] << " "; for (int j=i+1; j<n; j++) { if (arr[i] == arr[j]) { cout << arr[i] << " "; visited[j] = true; } } } } delete [] visited; } /* Driver program to test above function */ int main() { int arr[] = {4, 6, 9, 2, 3, 4, 9, 6, 10, 4}; int n = sizeof(arr)/sizeof(arr[0]); groupElements(arr, n); return 0; }
linear
quadratic
#include<bits/stdc++.h> using namespace std; // C++ program to group multiple // occurrences of individual array elements // A hashing based method to group // all occurrences of individual elements void orderedGroup(vector<int>&arr){ // Creates an empty hashmap map<int,int>hM; // Traverse the array elements, and store // count for every element in HashMap for(int i=0;i<arr.size();i++){ // Increment count of elements // in HashMap hM[arr[i]]++; } // Traverse array again for(int i=0;i<arr.size();i++){ // Check if this is first occurrence int count = (hM.find(arr[i]) == hM.end())? 0 : hM[arr[i]]; if(hM.find(arr[i]) != hM.end()){ // If yes, then print // the element 'count' times for(int j=0;j<count;j++){ cout<<arr[i]<<" "; } // And remove the element from HashMap. hM.erase(arr[i]); } } } // Driver Code int main(){ vector<int>arr = {10, 5, 3, 10, 10, 4, 1, 3}; orderedGroup(arr); } // This code is contributed by shinjanpatra
linear
linear
// A Simple C++ program to check if two sets are disjoint #include<bits/stdc++.h> using namespace std; // Returns true if set1[] and set2[] are disjoint, else false bool areDisjoint(int set1[], int set2[], int m, int n) { // Take every element of set1[] and search it in set2 for (int i=0; i<m; i++) for (int j=0; j<n; j++) if (set1[i] == set2[j]) return false; // If no element of set1 is present in set2 return true; } // Driver program to test above function int main() { int set1[] = {12, 34, 11, 9, 3}; int set2[] = {7, 2, 1, 5}; int m = sizeof(set1)/sizeof(set1[0]); int n = sizeof(set2)/sizeof(set2[0]); areDisjoint(set1, set2, m, n)? cout << "Yes" : cout << " No"; return 0; }
constant
quadratic
/* C++ program to check if two sets are distinct or not */ #include<bits/stdc++.h> using namespace std; // This function prints all distinct elements bool areDisjoint(int set1[], int set2[], int n1, int n2) { // Creates an empty hashset set<int> myset; // Traverse the first set and store its elements in hash for (int i = 0; i < n1; i++) myset.insert(set1[i]); // Traverse the second set and check if any element of it // is already in hash or not. for (int i = 0; i < n2; i++) if (myset.find(set2[i]) != myset.end()) return false; return true; } // Driver method to test above method int main() { int set1[] = {10, 5, 3, 4, 6}; int set2[] = {8, 7, 9, 3}; int n1 = sizeof(set1) / sizeof(set1[0]); int n2 = sizeof(set2) / sizeof(set2[0]); if (areDisjoint(set1, set2, n1, n2)) cout << "Yes"; else cout << "No"; } //This article is contributed by Chhavi
linear
linear
// CPP program to find Non-overlapping sum #include <bits/stdc++.h> using namespace std; // function for calculating // Non-overlapping sum of two array int findSum(int A[], int B[], int n) { // Insert elements of both arrays unordered_map<int, int> hash; for (int i = 0; i < n; i++) { hash[A[i]]++; hash[B[i]]++; } // calculate non-overlapped sum int sum = 0; for (auto x: hash) if (x.second == 1) sum += x.first; return sum; } // driver code int main() { int A[] = { 5, 4, 9, 2, 3 }; int B[] = { 2, 8, 7, 6, 3 }; // size of array int n = sizeof(A) / sizeof(A[0]); // function call cout << findSum(A, B, n); return 0; }
linear
linear
// C++ simple program to // find elements which are // not present in second array #include<bits/stdc++.h> using namespace std; // Function for finding // elements which are there // in a[] but not in b[]. void findMissing(int a[], int b[], int n, int m) { for (int i = 0; i < n; i++) { int j; for (j = 0; j < m; j++) if (a[i] == b[j]) break; if (j == m) cout << a[i] << " "; } } // Driver code int main() { int a[] = { 1, 2, 6, 3, 4, 5 }; int b[] = { 2, 4, 3, 1, 0 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[1]); findMissing(a, b, n, m); return 0; }
constant
quadratic
// C++ efficient program to // find elements which are not // present in second array #include<bits/stdc++.h> using namespace std; // Function for finding // elements which are there // in a[] but not in b[]. void findMissing(int a[], int b[], int n, int m) { // Store all elements of // second array in a hash table unordered_set <int> s; for (int i = 0; i < m; i++) s.insert(b[i]); // Print all elements of // first array that are not // present in hash table for (int i = 0; i < n; i++) if (s.find(a[i]) == s.end()) cout << a[i] << " "; } // Driver code int main() { int a[] = { 1, 2, 6, 3, 4, 5 }; int b[] = { 2, 4, 3, 1, 0 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[1]); findMissing(a, b, n, m); return 0; }
linear
linear
// C++ program to find given two array // are equal or not #include <bits/stdc++.h> using namespace std; // Returns true if arr1[0..n-1] and arr2[0..m-1] // contain same elements. bool areEqual(int arr1[], int arr2[], int N, int M) { // If lengths of array are not equal means // array are not equal if (N != M) return false; // Sort both arrays sort(arr1, arr1 + N); sort(arr2, arr2 + M); // Linearly compare elements for (int i = 0; i < N; i++) if (arr1[i] != arr2[i]) return false; // If all elements were same. return true; } // Driver's Code int main() { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int N = sizeof(arr1) / sizeof(int); int M = sizeof(arr2) / sizeof(int); // Function call if (areEqual(arr1, arr2, N, M)) cout << "Yes"; else cout << "No"; return 0; }
constant
nlogn
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Returns true if arr1[0..N-1] and arr2[0..M-1] // contain same elements. bool areEqual(int arr1[], int arr2[], int N, int M) { // If lengths of arrays are not equal if (N != M) return false; // Store arr1[] elements and their counts in // hash map unordered_map<int, int> mp; for (int i = 0; i < N; i++) mp[arr1[i]]++; // Traverse arr2[] elements and check if all // elements of arr2[] are present same number // of times or not. for (int i = 0; i < N; i++) { // If there is an element in arr2[], but // not in arr1[] if (mp.find(arr2[i]) == mp.end()) return false; // If an element of arr2[] appears more // times than it appears in arr1[] if (mp[arr2[i]] == 0) return false; // decrease the count of arr2 elements in the // unordered map mp[arr2[i]]--; } return true; } // Driver's Code int main() { int arr1[] = { 3, 5, 2, 5, 2 }; int arr2[] = { 2, 3, 5, 5, 2 }; int N = sizeof(arr1) / sizeof(int); int M = sizeof(arr2) / sizeof(int); // Function call if (areEqual(arr1, arr2, N, M)) cout << "Yes"; else cout << "No"; return 0; }
linear
linear
// C++ code to find maximum shortest distance // from endpoints #include <bits/stdc++.h> using namespace std; // function to find maximum shortest distance int find_maximum(int a[], int n, int k) { // stores the shortest distance of every // element in original array. unordered_map<int, int> b; for (int i = 0; i < n; i++) { int x = a[i]; // shortest distance from ends int d = min(1 + i, n - i); if (b.find(x) == b.end()) b[x] = d; else /* if duplicates are found, b[x] is replaced with minimum of the previous and current position's shortest distance*/ b[x] = min(d, b[x]); } int ans = INT_MAX; for (int i = 0; i < n; i++) { int x = a[i]; // similar elements ignore them // cause we need distinct elements if (x != k - x && b.find(k - x) != b.end()) ans = min(max(b[x], b[k - x]), ans); } return ans; } // driver code int main() { int a[] = { 3, 5, 8, 6, 7 }; int K = 11; int n = sizeof(a) / sizeof(a[0]); cout << find_maximum(a, n, K) << endl; return 0; }
linear
linear
// C++ program to find the k-th missing element // in a given sequence #include <bits/stdc++.h> using namespace std; // Returns k-th missing element. It returns -1 if // no k is more than number of missing elements. int find(int a[], int b[], int k, int n1, int n2) { // Insert all elements of givens sequence b[]. unordered_set<int> s; for (int i = 0; i < n2; i++) s.insert(b[i]); // Traverse through increasing sequence and // keep track of count of missing numbers. int missing = 0; for (int i = 0; i < n1; i++) { if (s.find(a[i]) == s.end()) missing++; if (missing == k) return a[i]; } return -1; } // driver program to test the above function int main() { int a[] = { 0, 2, 4, 6, 8, 10, 12, 14, 15 }; int b[] = { 4, 10, 6, 8, 12 }; int n1 = sizeof(a) / sizeof(a[0]); int n2 = sizeof(b) / sizeof(b[0]); int k = 3; cout << find(a, b, k, n1, n2); return 0; }
quadratic
linear
// C++ program to find a pair with product // in given array. #include<bits/stdc++.h> using namespace std; // Function to find greatest number that us int findGreatest( int arr[] , int n) { int result = -1; for (int i = 0; i < n ; i++) for (int j = 0; j < n-1; j++) for (int k = j+1 ; k < n ; k++) if (arr[j] * arr[k] == arr[i]) result = max(result, arr[i]); return result; } // Driver code int main() { // Your C++ Code int arr[] = {10, 3, 5, 30, 35}; int n = sizeof(arr)/sizeof(arr[0]); cout << findGreatest(arr, n); return 0; }
constant
cubic
// C++ program to find the largest product number #include <bits/stdc++.h> using namespace std; // Function to find greatest number int findGreatest(int arr[], int n) { // Store occurrences of all elements in hash // array unordered_map<int, int> m; for (int i = 0; i < n; i++) m[arr[i]]++; // Sort the array and traverse all elements from // end. sort(arr, arr + n); for (int i = n - 1; i > 1; i--) { // For every element, check if there is another // element which divides it. for (int j = 0; j < i && arr[j] <= sqrt(arr[i]); j++) { if (arr[i] % arr[j] == 0) { int result = arr[i] / arr[j]; // Check if the result value exists in array // or not if yes the return arr[i] if (result != arr[j] && result!=arr[i] && m[result] > 0) return arr[i]; // To handle the case like arr[i] = 4 and // arr[j] = 2 else if (result == arr[j] && m[result] > 1) return arr[i]; } } } return -1; } // Drivers code int main() { int arr[] = {10, 3, 5, 30, 35}; int n = sizeof(arr) / sizeof(arr[0]); cout << findGreatest(arr, n); return 0; }
linear
nlogn
// A sorting based solution to find the // minimum number of subsets of a set // such that every subset contains distinct // elements. #include <bits/stdc++.h> using namespace std; // Function to count subsets such that all // subsets have distinct elements. int subset(int ar[], int n) { // Take input and initialize res = 0 int res = 0; // Sort the array sort(ar, ar + n); // Traverse the input array and // find maximum frequency for (int i = 0; i < n; i++) { int count = 1; // For each number find its repetition / frequency for (; i < n - 1; i++) { if (ar[i] == ar[i + 1]) count++; else break; } // Update res res = max(res, count); } return res; } // Driver code int main() { int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0; }
constant
quadratic
// A hashing based solution to find the // minimum number of subsets of a set // such that every subset contains distinct // elements. #include <bits/stdc++.h> using namespace std; // Function to count subsets such that all // subsets have distinct elements. int subset(int arr[], int n) { // Traverse the input array and // store frequencies of elements unordered_map<int, int> mp; for (int i = 0; i < n; i++) mp[arr[i]]++; // Find the maximum value in map. int res = 0; for (auto x : mp) res = max(res, x.second); return res; } // Driver code int main() { int arr[] = { 5, 6, 9, 3, 4, 3, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subset(arr, n); return 0; }
linear
linear
// CPP program to find minimum element // to remove so no common element // exist in both array #include <bits/stdc++.h> using namespace std; // To find no elements to remove // so no common element exist int minRemove(int a[], int b[], int n, int m) { // To store count of array element unordered_map<int, int> countA, countB; // Count elements of a for (int i = 0; i < n; i++) countA[a[i]]++; // Count elements of b for (int i = 0; i < m; i++) countB[b[i]]++; // Traverse through all common element, and // pick minimum occurrence from two arrays int res = 0; for (auto x : countA) if (countB.find(x.first) != countB.end()) res += min(x.second, countB[x.first]); // To return count of minimum elements return res; } // Driver program to test minRemove() int main() { int a[] = { 1, 2, 3, 4 }; int b[] = { 2, 3, 4, 5, 8 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); cout << minRemove(a, b, n, m); return 0; }
linear
linear
// C++ implementation to count items common to both // the lists but with different prices #include <bits/stdc++.h> using namespace std; // details of an item struct item { string name; int price; }; // function to count items common to both // the lists but with different prices int countItems(item list1[], int m, item list2[], int n) { int count = 0; // for each item of 'list1' check if it is in 'list2' // but with a different price for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if ((list1[i].name.compare(list2[j].name) == 0) && (list1[i].price != list2[j].price)) count++; // required count of items return count; } // Driver program to test above int main() { item list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}}; item list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << "Count = " << countItems(list1, m, list2, n); return 0; }
constant
quadratic
// C++ implementation to count // items common to both the lists // but with different prices #include <bits/stdc++.h> using namespace std; // Details of an item struct item { string name; int price; }; // comparator function // used for sorting bool compare(struct item a, struct item b) { return (a.name.compare (b.name) <= 0); } // Function to search 'str' // in 'list2[]'. If it exists then // price associated with 'str' // in 'list2[]' is being returned // else -1 is returned. Here binary // search technique is being applied // for searching int binary_search(item list2[], int low, int high, string str) { while (low <= high) { int mid = (low + high) / 2; // if true the item 'str' // is in 'list2' if (list2[mid].name.compare(str) == 0) return list2[mid].price; else if (list2[mid].name.compare(str) < 0) low = mid + 1; else high = mid - 1; } // item 'str' is not in 'list2' return -1; } // Function to count items common to both // the lists but with different prices int countItems(item list1[], int m, item list2[], int n) { // sort 'list2' in alphabetical // order of items name sort(list2, list2 + n, compare); // initial count int count = 0; for (int i = 0; i < m; i++) { // get the price of item 'list1[i]' // from 'list2' if item in not // present in second list then // -1 is being obtained int r = binary_search(list2, 0, n - 1, list1[i].name); // if item is present in list2 // with a different price if ((r != -1) && (r != list1[i].price)) count++; } // Required count of items return count; } // Driver code int main() { item list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}}; item list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << "Count = " << countItems(list1, m, list2, n); return 0; }
constant
nlogn
// C++ implementation to count items common to both // the lists but with different prices #include <bits/stdc++.h> using namespace std; // details of an item struct item { string name; int price; }; // function to count items common to both // the lists but with different prices int countItems(item list1[], int m, item list2[], int n) { // 'um' implemented as hash table that contains // item name as the key and price as the value // associated with the key unordered_map<string, int> um; int count = 0; // insert elements of 'list1' in 'um' for (int i = 0; i < m; i++) um[list1[i].name] = list1[i].price; // for each element of 'list2' check if it is // present in 'um' with a different price // value for (int i = 0; i < n; i++) if ((um.find(list2[i].name) != um.end()) && (um[list2[i].name] != list2[i].price)) count++; // required count of items return count; } // Driver program to test above int main() { item list1[] = {{"apple", 60}, {"bread", 20}, {"wheat", 50}, {"oil", 30}}; item list2[] = {{"milk", 20}, {"bread", 15}, {"wheat", 40}, {"apple", 60}}; int m = sizeof(list1) / sizeof(list1[0]); int n = sizeof(list2) / sizeof(list2[0]); cout << "Count = " << countItems(list1, m, list2, n); return 0; }
linear
linear
#include <bits/stdc++.h> using namespace std; // Function to print common strings with minimum index sum void find(vector<string> list1, vector<string> list2) { vector<string> res; // resultant list int max_possible_sum = list1.size() + list2.size() - 2; // iterating over sum in ascending order for (int sum = 0; sum <= max_possible_sum ; sum++) { // iterating over one list and check index // (Corresponding to given sum) in other list for (int i = 0; i <= sum; i++) // put common strings in resultant list if (i < list1.size() && (sum - i) < list2.size() && list1[i] == list2[sum - i]) res.push_back(list1[i]); // if common string found then break as we are // considering index sums in increasing order. if (res.size() > 0) break; } // print the resultant list for (int i = 0; i < res.size(); i++) cout << res[i] << " "; } // Driver code int main() { // Creating list1 vector<string> list1; list1.push_back("GeeksforGeeks"); list1.push_back("Udemy"); list1.push_back("Coursera"); list1.push_back("edX"); // Creating list2 vector<string> list2; list2.push_back("Codecademy"); list2.push_back("Khan Academy"); list2.push_back("GeeksforGeeks"); find(list1, list2); return 0; }
quadratic
linear
// Hashing based C++ program to find common elements // with minimum index sum. #include <bits/stdc++.h> using namespace std; // Function to print common strings with minimum index sum void find(vector<string> list1, vector<string> list2) { // mapping strings to their indices unordered_map<string, int> map; for (int i = 0; i < list1.size(); i++) map[list1[i]] = i; vector<string> res; // resultant list int minsum = INT_MAX; for (int j = 0; j < list2.size(); j++) { if (map.count(list2[j])) { // If current sum is smaller than minsum int sum = j + map[list2[j]]; if (sum < minsum) { minsum = sum; res.clear(); res.push_back(list2[j]); } // if index sum is same then put this // string in resultant list as well else if (sum == minsum) res.push_back(list2[j]); } } // Print result for (int i = 0; i < res.size(); i++) cout << res[i] << " "; } // Driver code int main() { // Creating list1 vector<string> list1; list1.push_back("GeeksforGeeks"); list1.push_back("Udemy"); list1.push_back("Coursera"); list1.push_back("edX"); // Creating list2 vector<string> list2; list2.push_back("Codecademy"); list2.push_back("Khan Academy"); list2.push_back("GeeksforGeeks"); find(list1, list2); return 0; }
quadratic
linear
// C++ program to find a pair with given sum such that // every element of pair is in different rows. #include<bits/stdc++.h> using namespace std; const int MAX = 100; // Function to find pair for given sum in matrix // mat[][] --> given matrix // n --> order of matrix // sum --> given sum for which we need to find pair void pairSum(int mat[][MAX], int n, int sum) { // First sort all the rows in ascending order for (int i=0; i<n; i++) sort(mat[i], mat[i]+n); // Select i'th row and find pair for element in i'th // row in j'th row whose summation is equal to given sum for (int i=0; i<n-1; i++) { for (int j=i+1; j<n; j++) { int left = 0, right = n-1; while (left<n && right>=0) { if ((mat[i][left] + mat[j][right]) == sum) { cout << "(" << mat[i][left] << ", "<< mat[j][right] << "), "; left++; right--; } else { if ((mat[i][left] + mat[j][right]) < sum) left++; else right--; } } } } } // Driver program to run the case int main() { int n = 4, sum = 11; int mat[][MAX] = {{1, 3, 2, 4}, {5, 8, 7, 6}, {9, 10, 13, 11}, {12, 0, 14, 15}}; pairSum(mat, n, sum); return 0; }
constant
cubic
// A Program to prints common element in all // rows of matrix #include <bits/stdc++.h> using namespace std; // Specify number of rows and columns #define M 4 #define N 5 // prints common element in all rows of matrix void printCommonElements(int mat[M][N]) { unordered_map<int, int> mp; // initialize 1st row elements with value 1 for (int j = 0; j < N; j++) mp[mat[0][j]] = 1; // traverse the matrix for (int i = 1; i < M; i++) { for (int j = 0; j < N; j++) { // If element is present in the map and // is not duplicated in current row. if (mp[mat[i][j]] == i) { // we increment count of the element // in map by 1 mp[mat[i][j]] = i + 1; // If this is last row if (i==M-1 && mp[mat[i][j]]==M) cout << mat[i][j] << " "; } } } } // driver program to test above function int main() { int mat[M][N] = { {1, 2, 1, 4, 8}, {3, 7, 8, 5, 1}, {8, 7, 7, 3, 1}, {8, 1, 2, 7, 9}, }; printCommonElements(mat); return 0; }
linear
quadratic
// C++ program to find all permutations of a given row #include<bits/stdc++.h> #define MAX 100 using namespace std; // Function to find all permuted rows of a given row r void permutatedRows(int mat[][MAX], int m, int n, int r) { // Creating an empty set unordered_set<int> s; // Count frequencies of elements in given row r for (int j=0; j<n; j++) s.insert(mat[r][j]); // Traverse through all remaining rows for (int i=0; i<m; i++) { // we do not need to check for given row r if (i==r) continue; // initialize hash i.e; count frequencies // of elements in row i int j; for (j=0; j<n; j++) if (s.find(mat[i][j]) == s.end()) break; if (j != n) continue; cout << i << ", "; } } // Driver program to run the case int main() { int m = 4, n = 4,r = 3; int mat[][MAX] = {{3, 1, 4, 2}, {1, 6, 9, 3}, {1, 2, 3, 4}, {4, 3, 2, 1}}; permutatedRows(mat, m, n, r); return 0; }
linear
quadratic