code
stringlengths
195
7.9k
space_complexity
stringclasses
6 values
time_complexity
stringclasses
7 values
# Python program for Dijkstra's single # source shortest path algorithm. The program is # for adjacency matrix representation of the graph # Library for INT_MAX import sys class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print("Vertex \tDistance from Source") for node in range(self.V): print(node, "\t", dist[node]) # A utility function to find the vertex with # minimum distance value, from the set of vertices # not yet included in shortest path tree def minDistance(self, dist, sptSet): # Initialize minimum distance for next node min = sys.maxsize # Search not nearest vertex not in the # shortest path tree for u in range(self.V): if dist[u] < min and sptSet[u] == False: min = dist[u] min_index = u return min_index # Function that implements Dijkstra's single source # shortest path algorithm for a graph represented # using adjacency matrix representation def dijkstra(self, src): dist = [sys.maxsize] * self.V dist[src] = 0 sptSet = [False] * self.V for cout in range(self.V): # Pick the minimum distance vertex from # the set of vertices not yet processed. # x is always equal to src in first iteration x = self.minDistance(dist, sptSet) # Put the minimum distance vertex in the # shortest path tree sptSet[x] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for y in range(self.V): if self.graph[x][y] > 0 and sptSet[y] == False and \ dist[y] > dist[x] + self.graph[x][y]: dist[y] = dist[x] + self.graph[x][y] self.printSolution(dist) # Driver's code if __name__ == "__main__": g = Graph(9) g.graph = [[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] ] g.dijkstra(0) # This code is contributed by Divyanshu Mehta and Updated by Pranav Singh Sambyal
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
# Python3 program for Bellman-Ford's single source # shortest path algorithm. # Class to represent a graph class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = [] # function to add an edge to graph def addEdge(self, u, v, w): self.graph.append([u, v, w]) # utility function used to print the solution def printArr(self, dist): print("Vertex Distance from Source") for i in range(self.V): print("{0}\t\t{1}".format(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 def BellmanFord(self, src): # Step 1: Initialize distances from src to all other vertices # as INFINITE dist = [float("Inf")] * self.V 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 _ in range(self.V - 1): # Update dist value and parent index of the adjacent vertices of # the picked vertex. Consider only those vertices which are still in # queue for u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: dist[v] = dist[u] + w # 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 u, v, w in self.graph: if dist[u] != float("Inf") and dist[u] + w < dist[v]: print("Graph contains negative weight cycle") return # print all distance self.printArr(dist) # Driver's code if __name__ == '__main__': g = Graph(5) g.addEdge(0, 1, -1) g.addEdge(0, 2, 4) g.addEdge(1, 2, 3) g.addEdge(1, 3, 2) g.addEdge(1, 4, 2) g.addEdge(3, 2, 5) g.addEdge(3, 1, 1) g.addEdge(4, 3, -3) # function call g.BellmanFord(0) # Initially, Contributed by Neelam Yadav # Later On, Edited by Himanshu Garg
linear
quadratic
# Python3 Program for Floyd Warshall Algorithm # Number of vertices in the graph V = 4 # Define infinity as the large # enough value. This value will be # used for vertices not connected to each other INF = 99999 # Solves all pair shortest path # via Floyd Warshall Algorithm def floydWarshall(graph): """ dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices """ """ initializing the solution matrix same as input graph matrix OR we can say that the initial values of shortest distances are based on shortest paths considering no intermediate vertices """ dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) """ 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 the set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} """ for k in range(V): # pick all vertices as source one by one for i in range(V): # Pick all vertices as destination for the # above picked source for j in range(V): # If vertex k is on the shortest path from # i to j, then update the value of dist[i][j] dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j] ) printSolution(dist) # A utility function to print the solution def printSolution(dist): print("Following matrix shows the shortest distances\ between every pair of vertices") for i in range(V): for j in range(V): if(dist[i][j] == INF): print("%7s" % ("INF"), end=" ") else: print("%7d\t" % (dist[i][j]), end=' ') if j == V-1: print() # Driver's code if __name__ == "__main__": """ 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 """ graph = [[0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ] # Function call floydWarshall(graph) # This code is contributed by Mythri J L
quadratic
cubic
# Dynamic Programming based Python3 # program to find shortest path with # A Dynamic programming based function # to find the shortest path from u to v # with exactly k edges. def shortestPath(graph, u, v, k): global V, INF # 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 sp = [[None] * V for i in range(V)] for i in range(V): for j in range(V): sp[i][j] = [None] * (k + 1) # Loop for number of edges from 0 to k for e in range(k + 1): for i in range(V): # for source for j in range(V): # for destination # initialize value sp[i][j][e] = INF # from base cases if (e == 0 and i == j): sp[i][j][e] = 0 if (e == 1 and 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 a in range(V): # 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 and i != a and j!= a and 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 Code # Define number of vertices in # the graph and infinite value V = 4 INF = 999999999999 # Let us create the graph shown # in above diagram graph = [[0, 10, 3, 2], [INF, 0, INF, 7], [INF, INF, 0, 6], [INF, INF, INF, 0]] u = 0 v = 3 k = 2 print("Weight of the shortest path is", shortestPath(graph, u, v, k)) # This code is contributed by PranchalK
np
cubic
# Python3 code for printing shortest path between # two vertices of unweighted graph # utility function to form edge between two vertices # source and dest def add_edge(adj, src, dest): adj[src].append(dest); adj[dest].append(src); # a modified version of BFS that stores predecessor # of each vertex in array p # and its distance from source in array d def BFS(adj, src, dest, v, pred, dist): # a queue to maintain queue of vertices whose # adjacency list is to be scanned as per normal # DFS algorithm queue = [] # boolean array visited[] which stores the # information whether ith vertex is reached # at least once in the Breadth first search visited = [False for i in range(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 i in range(v): dist[i] = 1000000 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.append(src); # standard BFS algorithm while (len(queue) != 0): u = queue[0]; queue.pop(0); for i in range(len(adj[u])): if (visited[adj[u][i]] == False): visited[adj[u][i]] = True; dist[adj[u][i]] = dist[u] + 1; pred[adj[u][i]] = u; queue.append(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 def printShortestDistance(adj, s, dest, v): # predecessor[i] array stores predecessor of # i and distance array stores distance of i # from s pred=[0 for i in range(v)] dist=[0 for i in range(v)]; if (BFS(adj, s, dest, v, pred, dist) == False): print("Given source and destination are not connected") # vector path stores the shortest path path = [] crawl = dest; path.append(crawl); while (pred[crawl] != -1): path.append(pred[crawl]); crawl = pred[crawl]; # distance from source is in distance array print("Shortest path length is : " + str(dist[dest]), end = '') # printing path from source to destination print("\nPath is : : ") for i in range(len(path)-1, -1, -1): print(path[i], end=' ') # Driver program to test above functions if __name__=='__main__': # no. of vertices v = 8; # array of vectors is used to store the graph # in the form of an adjacency list adj = [[] for i in range(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); source = 0 dest = 7; printShortestDistance(adj, source, dest, v); # This code is contributed by rutvik_56
linear
linear
# Python program to get least cost path in a grid from # top-left to bottom-right from functools import cmp_to_key ROW = 5 COL = 5 def mycmp(a,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) # structure for information of each cell class cell: def __init__(self,x, y, distance): self.x = x self.y = y self.distance = distance # Utility method to check whether a point is # inside the grid or not def isInsideGrid(i, j): return (i >= 0 and i < ROW and j >= 0 and j < COL) # Method returns minimum cost to reach bottom # right from top left def shortest(grid, row, col): dis = [[0 for i in range(col)]for j in range(row)] # initializing distance array by INT_MAX for i in range(row): for j in range(col): dis[i][j] = 1000000000 # direction arrays for simplification of getting # neighbour dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] st = [] # insert (0, 0) cell with 0 distance st.append(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 (len(st)!=0): # get the cell with minimum distance and delete # it from the set k = st[0] st = st[1:] # looping through all neighbours for i in range(4): x = k.x + dx[i] y = k.y + dy[i] # if not inside boundary, ignore them if (isInsideGrid(x, y) == 0): 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]): # update the distance and insert new updated # cell in set dis[x][y] = dis[k.x][k.y] + grid[x][y] st.append(cell(x, y, dis[x][y])) st.sort(key=cmp_to_key(mycmp)) # uncomment below code to print distance # of each cell from (0, 0) # for i in range(row): # for j in range(col): # print(dis[i][j] ,end= " ") # print() # 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 grid = [[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]] print(shortest(grid, ROW, COL)) # This code is contributed by shinjanpatra
quadratic
quadratic
# Python3 program to replace all of the O's in the matrix # with their shortest distance from a guard from collections import deque as queue # store dimensions of the matrix M = 5 N = 5 # These arrays are used to get row and column # numbers of 4 neighbors of a given cell row = [-1, 0, 1, 0] col = [0, 1, 0, -1] # return true if row number and column number # is in range def isValid(i, j): if ((i < 0 or i > M - 1) or (j < 0 or 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 def isSafe(i, j,matrix, output): if (matrix[i][j] != 'O' or 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 def findDistance(matrix): output = [[ -1 for i in range(N)]for i in range(M)] q = queue() # finding Guards location and adding into queue for i in range(M): for j in range(N): # initialize each cell as -1 output[i][j] = -1 if (matrix[i][j] == 'G'): pos = [i, j, 0] q.appendleft(pos) # guard has 0 distance output[i][j] = 0 # do till queue is empty while (len(q) > 0): # get the front cell in the queue and update # its adjacent cells curr = q.pop() x, y, dist = curr[0], curr[1], curr[2] # do for each adjacent cell for i in range(4): # if adjacent cell is valid, has path and # not visited yet, en-queue it. if isValid(x + row[i], y + col[i]) and isSafe(x + row[i], y + col[i], matrix, output) : output[x + row[i]][y + col[i]] = dist + 1 pos = [x + row[i], y + col[i], dist + 1] q.appendleft(pos) # print output matrix for i in range(M): for j in range(N): if output[i][j] > 0: print(output[i][j], end=" ") else: print(output[i][j],end=" ") print() # Driver code matrix = [['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) # This code is contributed by mohit kumar 29
quadratic
quadratic
# Python program to find articulation points in an undirected graph from collections import defaultdict # This class represents an undirected graph # using adjacency list representation class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that find articulation points using DFS traversal u --> The vertex to be visited next visited[] --> keeps track of visited vertices disc[] --> Stores discovery times of visited vertices parent[] --> Stores parent vertices in DFS tree ap[] --> Store articulation points''' def APUtil(self, u, visited, ap, parent, low, disc): # Count of children in current node children = 0 # Mark the current node as visited and print it visited[u]= True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 # Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if visited[v] == False : parent[v] = u children += 1 self.APUtil(v, visited, ap, parent, low, disc) # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more children. if parent[u] == -1 and children > 1: ap[u] = True #(2) If u is not root and low value of one of its child is more # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: ap[u] = True # Update low value of u for parent function calls elif v != parent[u]: low[u] = min(low[u], disc[v]) # The function to do DFS traversal. It uses recursive APUtil() def AP(self): # Mark all the vertices as not visited # and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float("Inf")] * (self.V) low = [float("Inf")] * (self.V) parent = [-1] * (self.V) ap = [False] * (self.V) # To store articulation points # Call the recursive helper function # to find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if visited[i] == False: self.APUtil(i, visited, ap, parent, low, disc) for index, value in enumerate (ap): if value == True: print (index,end=" ") # Create a graph given in the above diagram g1 = Graph(5) g1.addEdge(1, 0) g1.addEdge(0, 2) g1.addEdge(2, 1) g1.addEdge(0, 3) g1.addEdge(3, 4) print ("\nArticulation points in first graph ") g1.AP() g2 = Graph(4) g2.addEdge(0, 1) g2.addEdge(1, 2) g2.addEdge(2, 3) print ("\nArticulation points in second graph ") g2.AP() g3 = Graph (7) g3.addEdge(0, 1) g3.addEdge(1, 2) g3.addEdge(2, 0) g3.addEdge(1, 3) g3.addEdge(1, 4) g3.addEdge(1, 6) g3.addEdge(3, 5) g3.addEdge(4, 5) print ("\nArticulation points in third graph ") g3.AP() # This code is contributed by Neelam Yadav
linear
linear
# Program to count islands in boolean 2D matrix class Graph: def __init__(self, row, col, g): self.ROW = row self.COL = col self.graph = g # A function to check if a given cell # (row, col) can be included in DFS def isSafe(self, i, j, visited): # row number is in range, column number # is in range and value is 1 # and not yet visited return (i >= 0 and i < self.ROW and j >= 0 and j < self.COL and not visited[i][j] and self.graph[i][j]) # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j, visited): # These arrays are used to get row and # column numbers of 8 neighbours # of a given cell rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1] colNbr = [-1, 0, 1, -1, 1, -1, 0, 1] # Mark this cell as visited visited[i][j] = True # Recur for all connected neighbours for k in range(8): if self.isSafe(i + rowNbr[k], j + colNbr[k], visited): self.DFS(i + rowNbr[k], j + colNbr[k], visited) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Make a bool array to mark visited cells. # Initially all cells are unvisited visited = [[False for j in range(self.COL)]for i in range(self.ROW)] # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if visited[i][j] == False and self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j, visited) count += 1 return count graph = [[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]] row = len(graph) col = len(graph[0]) g = Graph(row, col, graph) print("Number of islands is:") print(g.countIslands()) # This code is contributed by Neelam Yadav
quadratic
quadratic
# Program to count islands in boolean 2D matrix class Graph: def __init__(self, row, col, graph): self.ROW = row self.COL = col self.graph = graph # A utility function to do DFS for a 2D # boolean matrix. It only considers # the 8 neighbours as adjacent vertices def DFS(self, i, j): if i < 0 or i >= len(self.graph) or j < 0 or j >= len(self.graph[0]) or self.graph[i][j] != 1: return # mark it as visited self.graph[i][j] = -1 # Recur for 8 neighbours self.DFS(i - 1, j - 1) self.DFS(i - 1, j) self.DFS(i - 1, j + 1) self.DFS(i, j - 1) self.DFS(i, j + 1) self.DFS(i + 1, j - 1) self.DFS(i + 1, j) self.DFS(i + 1, j + 1) # The main function that returns # count of islands in a given boolean # 2D matrix def countIslands(self): # Initialize count as 0 and traverse # through the all cells of # given matrix count = 0 for i in range(self.ROW): for j in range(self.COL): # If a cell with value 1 is not visited yet, # then new island found if self.graph[i][j] == 1: # Visit all cells in this island # and increment island count self.DFS(i, j) count += 1 return count graph = [ [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] ] row = len(graph) col = len(graph[0]) g = Graph(row, col, graph) print("Number of islands is:", g.countIslands()) # This code is contributed by Shivam Shrey
quadratic
quadratic
# Python3 program to find # the number of islands using # Disjoint Set data structure. # Class to represent # Disjoint Set Data structure class DisjointUnionSets: def __init__(self, n): self.rank = [0] * n self.parent = [0] * n self.n = n self.makeSet() def makeSet(self): # Initially, all elements are in their # own set. for i in range(self.n): self.parent[i] = i # Finds the representative of the set that x # is an element of def find(self, x): if (self.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 self.parent[x]=self.find(self.parent[x]) return self.parent[x] # Unites the set that includes x and # the set that includes y def Union(self, x, y): # Find the representatives(or the root nodes) # for x an y xRoot = self.find(x) yRoot = self.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 self.rank[xRoot] < self.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 elif self.rank[yRoot] < self.rank[xRoot]: self.parent[yRoot] = xRoot else: # Else if their ranks are the same # Then move y under x (doesn't matter # which one goes where) self.parent[yRoot] = xRoot # And increment the result tree's # rank by 1 self.rank[xRoot] = self.rank[xRoot] + 1 # Returns number of islands in a[][] def countIslands(a): n = len(a) m = len(a[0]) dus = DisjointUnionSets(n * m) # The following loop checks for its neighbours # and unites the indexes if both are 1. for j in range(0, n): for k in range(0, m): # 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 and a[j + 1][k] == 1: dus.Union(j * (m) + k, (j + 1) * (m) + k) if j - 1 >= 0 and a[j - 1][k] == 1: dus.Union(j * (m) + k, (j - 1) * (m) + k) if k + 1 < m and a[j][k + 1] == 1: dus.Union(j * (m) + k, (j) * (m) + k + 1) if k - 1 >= 0 and a[j][k - 1] == 1: dus.Union(j * (m) + k, (j) * (m) + k - 1) if (j + 1 < n and k + 1 < m and a[j + 1][k + 1] == 1): dus.Union(j * (m) + k, (j + 1) * (m) + k + 1) if (j + 1 < n and k - 1 >= 0 and a[j + 1][k - 1] == 1): dus.Union(j * m + k, (j + 1) * (m) + k - 1) if (j - 1 >= 0 and k + 1 < m and a[j - 1][k + 1] == 1): dus.Union(j * m + k, (j - 1) * m + k + 1) if (j - 1 >= 0 and k - 1 >= 0 and a[j - 1][k - 1] == 1): dus.Union(j * m + k, (j - 1) * m + k - 1) # Array to note down frequency of each set c = [0] * (n * m) numberOfIslands = 0 for j in range(n): for k in range(n): if a[j][k] == 1: x = dus.find(j * m + k) # If frequency of set is 0, # increment numberOfIslands if c[x] == 0: numberOfIslands += 1 c[x] += 1 else: c[x] += 1 return numberOfIslands # Driver Code 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]] print("Number of Islands is:", countIslands(a)) # This code is contributed by ankush_953
quadratic
quadratic
# Python3 program to count walks from # u to v with exactly k edges # Number of vertices in the graph V = 4 # A naive recursive function to count # walks from u to v with k edges def countwalks(graph, u, v, k): # Base cases if (k == 0 and u == v): return 1 if (k == 1 and graph[u][v]): return 1 if (k <= 0): return 0 # Initialize result count = 0 # Go to all adjacents of u and recur for i in range(0, V): # Check if is adjacent of u if (graph[u][i] == 1): count += countwalks(graph, i, v, k-1) return count # Driver Code # Let us create the graph shown in above diagram graph = [[0, 1, 1, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 1, ], [0, 0, 0, 0] ] u = 0; v = 3; k = 2 print(countwalks(graph, u, v, k)) # This code is contributed by Smitha Dinesh Semwal.
linear
quadratic
# Python3 program to count walks from # u to v with exactly k edges # Number of vertices V = 4 # A Dynamic programming based function # to count walks from u to v with k edges def countwalks(graph, u, v, 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 count = [[[0 for k in range(k + 1)] for i in range(V)] for j in range(V)] # Loop for number of edges from 0 to k for e in range(0, k + 1): # For Source for i in range(V): # For Destination for j in range(V): # Initialize value # count[i][j][e] = 0 # From base cases if (e == 0 and i == j): count[i][j][e] = 1 if (e == 1 and graph[i][j] != 0): count[i][j][e] = 1 # Go to adjacent only when number # of edges is more than 1 if (e > 1): for a in range(V): # Adjacent of i if (graph[i][a] != 0): count[i][j][e] += count[a][j][e - 1] return count[u][v][k] # Driver code if __name__ == '__main__': # Let us create the graph shown # in above diagram graph = [[0, 1, 1, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 0]] u = 0 v = 3 k = 2 print(countwalks(graph, u, v, k)) # This code is contributed by Rajput-Ji
np
cubic
# Python program to print all paths from a source to destination. from collections import defaultdict # This class represents a directed graph # using adjacency list representation class Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) '''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[]''' def printAllPathsUtil(self, u, d, visited, path): # Mark the current node as visited and store in path visited[u]= True path.append(u) # If current vertex is same as destination, then print # current path[] if u == d: print (path) else: # If current vertex is not destination # Recur for all the vertices adjacent to this vertex for i in self.graph[u]: if visited[i]== False: self.printAllPathsUtil(i, d, visited, path) # Remove current vertex from path[] and mark it as unvisited path.pop() visited[u]= False # Prints all paths from 's' to 'd' def printAllPaths(self, s, d): # Mark all the vertices as not visited visited =[False]*(self.V) # Create an array to store paths path = [] # Call the recursive helper function to print all paths self.printAllPathsUtil(s, d, visited, path) # Create a graph given in the above diagram g = Graph(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) s = 2 ; d = 3 print ("Following are all different paths from % d to % d :" %(s, d)) g.printAllPaths(s, d) # This code is contributed by Neelam Yadav
np
quadratic
# Python3 code to check if # cyclic order is possible # among strings under given # constraints M = 26 # Utility method for a depth # first search among vertices def dfs(g, u, visit): visit[u] = True for i in range(len(g[u])): if(not 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 def isConnected(g, mark, s): # Initialize all vertices # as not visited visit = [False for i in range(M)] # Perform a dfs from s dfs(g, s, visit) # Now loop through # all characters for i in range(M): # 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] and (not visit[i])): return False # If we reach that means # graph is connected return True # return true if an order among # strings is possible def possibleOrderAmongString(arr, N): # Create an empty graph g = {} # Initialize all vertices # as not marked mark = [False for i in range(M)] # Initialize indegree and # outdegree of every # vertex as 0. In = [0 for i in range(M)] out = [0 for i in range(M)] # Process all strings # one by one for i in range(N): # Find first and last # characters f = (ord(arr[i][0]) - ord('a')) l = (ord(arr[i][-1]) - ord('a')) # Mark the characters mark[f] = True mark[l] = True # Increase indegree # and outdegree count In[l] += 1 out[f] += 1 if f not in g: g[f] = [] # Add an edge in graph g[f].append(l) # If for any character # indegree is not equal to # outdegree then ordering # is not possible for i in range(M): if(In[i] != out[i]): return False return isConnected(g, mark, ord(arr[0][0]) - ord('a')) # Driver code arr = ["ab", "bc", "cd", "de", "ed", "da"] N = len(arr) if(possibleOrderAmongString(arr, N) == False): print("Ordering not possible") else: print("Ordering is possible") # This code is contributed by avanitrachhadiya2155
linear
linear
# Python3 program for the above approach def maxindex(dist, n): mi = 0 for i in range(n): if (dist[i] > dist[mi]): mi = i return mi def selectKcities(n, weights, k): dist = [0]*n centers = [] for i in range(n): dist[i] = 10**9 # index of city having the # maximum distance to it's # closest center max = 0 for i in range(k): centers.append(max) for j in range(n): # 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 # print() print(dist[max]) # Printing the cities that # were chosen to be made # centers for i in centers: print(i, end = " ") # Driver Code if __name__ == '__main__': n = 4 weights = [ [ 0, 4, 8, 5 ], [ 4, 0, 10, 7 ], [ 8, 10, 0, 9 ], [ 5, 7, 9, 0 ] ] k = 2 # Function Call selectKcities(n, weights, k) # This code is contributed by mohit kumar 29.
constant
quadratic
# Python3 program to find minimum time required to make all # oranges rotten from collections import deque # function to check whether a cell is valid / invalid def isvalid(i, j): return (i >= 0 and j >= 0 and i < 3 and j < 5) # Function to check whether the cell is delimiter # which is (-1, -1) def isdelim(temp): return (temp[0] == -1 and temp[1] == -1) # Function to check whether there is still a fresh # orange remaining def checkall(arr): for i in range(3): for j in range(5): 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 def rotOranges(arr): # Create a queue of cells Q = deque() temp = [0, 0] ans = 1 # Store all the cells having # rotten orange in first time frame for i in range(3): for j in range(5): if (arr[i][j] == 2): temp[0] = i temp[1] = j Q.append([i, j]) # Separate these rotten oranges # from the oranges which will rotten # due the oranges in first time # frame using delimiter which is (-1, -1) temp[0] = -1 temp[1] = -1 Q.append([-1, -1]) # print(Q) # Process the grid while there are # rotten oranges in the Queue while False: # 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. flag = False print(len(Q)) # Process all the rotten # oranges in current time frame. while not isdelim(Q[0]): temp = Q[0] print(len(Q)) # Check right adjacent cell that if it can be rotten if (isvalid(temp[0] + 1, temp[1]) and arr[temp[0] + 1][temp[1]] == 1): # if this is the first orange to get rotten, increase # count and set the flag. if (not flag): ans, flag = ans + 1, True # Make the orange rotten arr[temp[0] + 1][temp[1]] = 2 # append the adjacent orange to Queue temp[0] += 1 Q.append(temp) temp[0] -= 1 # Move back to current cell # Check left adjacent cell that if it can be rotten if (isvalid(temp[0] - 1, temp[1]) and arr[temp[0] - 1][temp[1]] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0] - 1][temp[1]] = 2 temp[0] -= 1 Q.append(temp) # append this cell to Queue temp[0] += 1 # Check top adjacent cell that if it can be rotten if (isvalid(temp[0], temp[1] + 1) and arr[temp[0]][temp[1] + 1] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0]][temp[1] + 1] = 2 temp[1] += 1 Q.append(temp) # Push this cell to Queue temp[1] -= 1 # Check bottom adjacent cell if it can be rotten if (isvalid(temp[0], temp[1] - 1) and arr[temp[0]][temp[1] - 1] == 1): if (not flag): ans, flag = ans + 1, True arr[temp[0]][temp[1] - 1] = 2 temp[1] -= 1 Q.append(temp) # append this cell to Queue Q.popleft() # Pop the delimiter Q.popleft() # If oranges were rotten in # current frame than separate the # rotten oranges using delimiter # for the next frame for processing. if (len(Q) == 0): temp[0] = -1 temp[1] = -1 Q.append(temp) # If Queue was empty than no rotten oranges left to process so exit # Return -1 if all arranges could not rot, otherwise return ans. return ans + 1 if(checkall(arr)) else -1 # Driver program if __name__ == '__main__': arr = [[2, 1, 0, 2, 1], [1, 0, 1, 2, 1], [1, 0, 0, 2, 1]] ans = rotOranges(arr) if (ans == -1): print("All oranges cannot rotn") else: print("Time required for all oranges to rot => ", ans) # This code is contributed by mohit kumar 29
quadratic
quadratic
# Python 3 program to find whether an array # is subset of another array # Return 1 if arr2[] is a subset of # arr1[] def isSubset(arr1, arr2, m, n): i = 0 j = 0 for i in range(n): for j in range(m): if(arr2[i] == arr1[j]): break # If the above inner loop was # not broken at all then arr2[i] # is not present in arr1[] if (j == m): return 0 # If we reach here then all # elements of arr2[] are present # in arr1[] return 1 # Driver code if __name__ == "__main__": arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if(isSubset(arr1, arr2, m, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[]") # This code is contributed by ita_c
constant
quadratic
# Python3 program to find whether an array # is subset of another array # Return 1 if arr2[] is a subset of arr1[] def isSubset(arr1, arr2, m, n): i = 0 quickSort(arr1, 0, m-1) for i in range(n): if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): return 0 # If we reach here then all elements # of arr2[] are present in arr1[] return 1 # FOLLOWING FUNCTIONS ARE ONLY FOR # SEARCHING AND SORTING PURPOSE # Standard Binary Search function def binarySearch(arr, low, high, x): if(high >= low): mid = (low + high)//2 # Check if arr[mid] is the first # occurrence of x. # arr[mid] is first occurrence if x is # one of the following # is true: # (i) mid == 0 and arr[mid] == x # (ii) arr[mid-1] < x and arr[mid] == x if((mid == 0 or x > arr[mid-1]) and (arr[mid] == x)): return mid elif(x > arr[mid]): return binarySearch(arr, (mid + 1), high, x) else: return binarySearch(arr, low, (mid - 1), x) return -1 def partition(A, si, ei): x = A[ei] i = (si - 1) for j in range(si, ei): if(A[j] <= x): i += 1 A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return (i + 1) # Implementation of Quick Sort # A[] --> Array to be sorted # si --> Starting index # ei --> Ending index def quickSort(A, si, ei): # Partitioning index if(si < ei): pi = partition(A, si, ei) quickSort(A, si, pi - 1) quickSort(A, pi + 1, ei) # Driver code arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if(isSubset(arr1, arr2, m, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[] ") # This code is contributed by chandan_jnu
linear
nlogn
# Python3 program to find whether an array # is subset of another array # Return 1 if arr2[] is a subset of arr1[] */ def isSubset(arr1, arr2, m, n): i = 0 j = 0 if m < n: return 0 arr1.sort() arr2.sort() while i < n and j < m: if arr1[j] < arr2[i]: j += 1 elif arr1[j] == arr2[i]: j += 1 i += 1 elif arr1[j] > arr2[i]: return 0 return False if i < n else True # Driver code arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if isSubset(arr1, arr2, m, n) == True: print("arr2 is subset of arr1 ") else: printf("arr2 is not a subset of arr1 ") # This code is contributed by Shrikant13
constant
nlogn
# Python3 program to find whether an array # is subset of another array # Return true if arr2[] is a subset # of arr1[] def isSubset(arr1, m, arr2, n): # Using STL set for hashing hashset = set() # hset stores all the values of arr1 for i in range(0, m): hashset.add(arr1[i]) # Loop to check if all elements # of arr2 also lies in arr1 for i in range(0, n): if arr2[i] in hashset: continue else: return False return True # Driver Code if __name__ == '__main__': arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if (isSubset(arr1, m, arr2, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[] ") # This code is contributed by akhilsaini
linear
nlogn
# Python3 code arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) s = set() for i in range(m): s.add(arr1[i]) p = len(s) for i in range(n): s.add(arr2[i]) if (len(s) == p): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not subset of arr1[] ") # This code is contributed by divyeshrabadiya07.
linear
linear
# Python3 program to find whether an array # is subset of another array # Return true if arr2[] is a subset of arr1[] def isSubset(arr1, m, arr2, n): # Create a Frequency Table using STL frequency = {} # Increase the frequency of each element # in the frequency table. for i in range(0, m): if arr1[i] in frequency: frequency[arr1[i]] = frequency[arr1[i]] + 1 else: frequency[arr1[i]] = 1 # Decrease the frequency if the # element was found in the frequency # table with the frequency more than 0. # else return 0 and if loop is # completed return 1. for i in range(0, n): if (frequency[arr2[i]] > 0): frequency[arr2[i]] -= 1 else: return False return True # Driver Code if __name__ == '__main__': arr1 = [11, 1, 13, 21, 3, 7] arr2 = [11, 3, 7, 1] m = len(arr1) n = len(arr2) if (isSubset(arr1, m, arr2, n)): print("arr2[] is subset of arr1[] ") else: print("arr2[] is not a subset of arr1[] ") # This code is contributed by akhilsaini
linear
linear
# This python program tells if there exists a pair in array whose sum results in x. # Function to find and print pair def chkPair(A, size, x): for i in range(0, size - 1): for j in range(i + 1, size): if (A[i] + A[j] == x): return 1 return 0 if __name__ == "__main__": A = [0, -1, 2, -3, 1] x = -2 size = len(A) if (chkPair(A, size, x)): print("Yes") else: print("No") # This code is contributed by rakeshsahni
constant
quadratic
# Python program to check for the sum # condition to be satisfied def hasArrayTwoCandidates(A, arr_size, sum): # sort the array quickSort(A, 0, arr_size-1) l = 0 r = arr_size-1 # traverse the array for the two elements while l < r: if (A[l] + A[r] == sum): return 1 elif (A[l] + A[r] < sum): l += 1 else: r -= 1 return 0 # Implementation of Quick Sort # A[] --> Array to be sorted # si --> Starting index # ei --> Ending index def quickSort(A, si, ei): if si < ei: pi = partition(A, si, ei) quickSort(A, si, pi-1) quickSort(A, pi + 1, ei) # Utility function for partitioning # the array(used in quick sort) def partition(A, si, ei): x = A[ei] i = (si-1) for j in range(si, ei): if A[j] <= x: i += 1 # This operation is used to swap # two variables is python A[i], A[j] = A[j], A[i] A[i + 1], A[ei] = A[ei], A[i + 1] return i + 1 # Driver program to test the functions A = [1, 4, 45, 6, 10, -8] n = 16 if (hasArrayTwoCandidates(A, len(A), n)): print("Yes") else: print("No") # This code is contributed by __Devesh Agrawal__
constant
nlogn
# Python program to check for the sum # condition to be satisfied def binarySearch(A, low, high, searchKey): m = 0 while (low <= high): m = (high + low) // 2 # Check if searchKey is present at mid if (A[m] == searchKey): return 1 # 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 0 def checkTwoSum(A, arr_size, sum): # sort the array A.sort() l = 0 r = arr_size-1 # Traversing all element in an array search for searchKey i = 0 while i < arr_size-1: searchKey = sum-A[i] # calling binarySearch function if(binarySearch(A, i+1, r, searchKey) == 1): return 1 i = i+1 return 0 # Driver program to test the functions A = [1, 4, 45, 6, 10, -8] n = 14 if (checkTwoSum(A, len(A), n)): print("Yes") else: print("No")
constant
nlogn
# Python program to find if there are # two elements with given sum # function to check for the given sum # in the array def printPairs(arr, arr_size, sum): # Create an empty hash map # using an hashmap allows us to store the indices hashmap = {} for i in range(0, arr_size): temp = sum-arr[i] if (temp in hashmap): print('Yes') return hashmap[arr[i]] = i print("No") # driver code A = [1, 4, 45, 6, 10, 8] n = 16 printPairs(A, len(A), n) # This code will also work in case the array has the same number twice # and target is the sum of those numbers # Eg: Array = [4,6,4] Target = 8 # This code is contributed by __Achyut Upadhyay__
linear
linear
# Code in Python3 to tell if there # exists a pair in array whose # sum results in x. # Function to print pairs def printPairs(a, n, x): rem = [] for i in range(x): # Initializing the rem # values with 0's. rem.append(0) for i in range(n): if (a[i] < x): # 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. rem[a[i] % x] += 1 # Traversing the remainder list from # start to middle to find pairs for i in range(1, x // 2): if (rem[i] > 0 and 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. print("Yes") 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 (rem[x // 2] > 1): # 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 than 1 # element, print "No". print("Yes") else: print("No") else: # When x is odd we continue # the same process which we # did in previous loop. if (rem[x // 2] > 0 and rem[x - x // 2] > 0): print("Yes") else: print("No") # Driver Code A = [1, 4, 45, 6, 10, 8] n = 16 arr_size = len(A) # Function calling printPairs(A, arr_size, n) # This code is contributed by subhammahato348
constant
linear
# Python3 program to find the minimum # number of operations required to # make all elements of array equal from collections import defaultdict # Function for min operation def minOperation(arr, n): # Insert all elements in hash. Hash = defaultdict(lambda:0) for i in range(0, n): Hash[arr[i]] += 1 # find the max frequency max_count = 0 for i in Hash: if max_count < Hash[i]: max_count = Hash[i] # return result return n - max_count # Driver Code if __name__ == "__main__": arr = [1, 5, 2, 1, 3, 2, 1] n = len(arr) print(minOperation(arr, n)) # This code is contributed # by Rituraj Jain
linear
linear
# Python program to find maximum distance between two # same occurrences of a number. # Function to find maximum distance between equal elements def maxDistance(arr, n): # Used to store element to first index mapping mp = {} # Traverse elements and find maximum distance between # same occurrences with the help of map. maxDict = 0 for i in range(n): # If this is first occurrence of element, insert its # index in map if arr[i] not in mp.keys(): mp[arr[i]] = i # Else update max distance else: maxDict = max(maxDict, i-mp[arr[i]]) return maxDict # Driver Program if __name__=='__main__': arr = [3, 2, 1, 2, 1, 4, 5, 8, 6, 7, 4, 2] n = len(arr) print (maxDistance(arr, n)) # Contributed By: Harshit Sidhwa
linear
linear
# python3 program to find maximum number of 2D points that lie on the same line. from collections import defaultdict from math import gcd from typing import DefaultDict, List, Tuple IntPair = Tuple[int, int] def normalized_slope(a: IntPair, b: IntPair) -> IntPair: """ Returns normalized (rise, run) tuple. We won't return the actual rise/run result in order to avoid floating point math, which leads to faulty comparisons. See https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems """ run = b[0] - a[0] # normalize undefined slopes to (1, 0) if run == 0: return (1, 0) # normalize to left-to-right if run < 0: a, b = b, a run = b[0] - a[0] rise = b[1] - a[1] # Normalize by greatest common divisor. # math.gcd only works on positive numbers. gcd_ = gcd(abs(rise), run) return ( rise // gcd_, run // gcd_, ) def maximum_points_on_same_line(points: List[List[int]]) -> int: # You need at least 3 points to potentially have non-collinear points. # For [0, 2] points, all points are on the same line. if len(points) < 3: return len(points) # Note that every line we find will have at least 2 points. # There will be at least one line because len(points) >= 3. # Therefore, it's safe to initialize to 0. max_val = 0 for a_index in range(0, len(points) - 1): # All lines in this iteration go through point a. # Note that lines a-b and a-c cannot be parallel. # Therefore, if lines a-b and a-c have the same slope, they're the same # line. a = tuple(points[a_index]) # Fresh lines already have a, so default=1 slope_counts: DefaultDict[IntPair, int] = defaultdict(lambda: 1) for b_index in range(a_index + 1, len(points)): b = tuple(points[b_index]) slope_counts[normalized_slope(a, b)] += 1 max_val = max( max_val, max(slope_counts.values()), ) return max_val print(maximum_points_on_same_line([ [-1, 1], [0, 0], [1, 1], [2, 2], [3, 3], [3, 4], ])) # This code is contributed by Jose Alvarado Torre
linear
quadratic
# Python3 implementation of the # above approach # 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 def findDuplicates(arr, Len): # Initialize ifPresent as false ifPresent = False # ArrayList to store the output a1 = [] for i in range(Len - 1): for j in range(i + 1, Len): # Checking if element is # present in the ArrayList # or not if present then break if (arr[i] == arr[j]): if arr[i] in a1: break # If element is not present in the # ArrayList then add it to ArrayList # and make ifPresent at true else: a1.append(arr[i]) ifPresent = True # If duplicates is present # then print ArrayList if (ifPresent): print(a1, end = " ") else: print("No duplicates present in arrays") # Driver Code arr = [ 12, 11, 40, 12, 5, 6, 5, 12, 11 ] n = len(arr) findDuplicates(arr, n) # This code is contributed by rag2127
linear
quadratic
# Python3 program to find duplicates # using dictionary approach. def printDuplicates(arr): dict = {} for ele in arr: try: dict[ele] += 1 except: dict[ele] = 1 for item in dict: # if frequency is more than 1 # print the element if(dict[item] > 1): print(item, end=" ") print("\n") # Driver Code if __name__ == "__main__": list = [12, 11, 40, 12, 5, 6, 5, 12, 11] printDuplicates(list) # This code is contributed # by Sushil Bhile
linear
linear
# Python program to find top k elements in a stream # Function to print top k numbers def kTop(a, n, k): # list of size k + 1 to store elements top = [0 for i in range(k + 1)] # dictionary to keep track of frequency freq = {i:0 for i in range(k + 1)} # iterate till the end of stream for m in range(n): # increase the frequency if a[m] in freq.keys(): freq[a[m]] += 1 else: freq[a[m]] = 1 # store that element in top vector top[k] = a[m] i = top.index(a[m]) i -= 1 while i >= 0: # compare the frequency and swap if higher # frequency element is stored next to it if (freq[top[i]] < freq[top[i + 1]]): t = top[i] top[i] = top[i + 1] top[i + 1] = t # if frequency is same compare the elements # and swap if next element is high else if ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])): t = top[i] top[i] = top[i + 1] top[i + 1] = t else: break i -= 1 # print top k elements i = 0 while i < k and top[i] != 0: print(top[i],end=" ") i += 1 print() # Driver program to test above function k = 4 arr = [ 5, 2, 1, 3, 2 ] n = len(arr) kTop(arr, n, k) # This code is contributed by Sachin Bisht
linear
quadratic
# Python3 program to find the most # frequent element in an array. def mostFrequent(arr, n): maxcount = 0; element_having_max_freq = 0; for i in range(0, n): count = 0 for j in range(0, n): if(arr[i] == arr[j]): count += 1 if(count > maxcount): maxcount = count element_having_max_freq = arr[i] return element_having_max_freq; # Driver Code arr = [40,50,30,40,50,30,30] n = len(arr) print(mostFrequent(arr, n)) # This code is contributed by Arpit Jain
constant
quadratic
# Python3 program to find the most # frequent element in an array. def mostFrequent(arr, n): # Sort the array arr.sort() # find the max frequency using # linear traversal max_count = 1 res = arr[0] curr_count = 1 for i in range(1, n): if (arr[i] == arr[i - 1]): curr_count += 1 else: curr_count = 1 # If last element is most frequent if (curr_count > max_count): max_count = curr_count res = arr[i - 1] return res # Driver Code arr = [40,50,30,40,50,30,30] n = len(arr) print(mostFrequent(arr, n)) # This code is contributed by Smitha Dinesh Semwal.
constant
nlogn
# Python3 program to find the most # frequent element in an array. import math as mt def mostFrequent(arr, n): # Insert all elements in Hash. Hash = dict() for i in range(n): if arr[i] in Hash.keys(): Hash[arr[i]] += 1 else: Hash[arr[i]] = 1 # find the max frequency max_count = 0 res = -1 for i in Hash: if (max_count < Hash[i]): res = i max_count = Hash[i] return res # Driver Code arr = [ 40,50,30,40,50,30,30] n = len(arr) print(mostFrequent(arr, n)) # This code is contributed # by Mohit kumar 29
linear
linear
def maxFreq(arr, n): # Using moore's voting algorithm res = 0 count = 1 for i in range(1, n): if (arr[i] == arr[res]): count += 1 else: count -= 1 if (count == 0): res = i count = 1 return arr[res] # Driver code arr = [ 40, 50, 30, 40, 50, 30, 30 ] n = len(arr) freq = maxFreq(arr, n) count = 0 for i in range (n): if(arr[i] == freq): count += 1 print("Element ", maxFreq(arr , n), " occurs ", count, " times") # This code is contributed by shivanisinghss2110
constant
linear
# Python3 implementation to # find first element # occurring k times # function to find the # first element occurring # k number of times def firstElement(arr, n, k): # dictionary to count # occurrences of # each element for i in arr: count=0 for j in arr: if i==j: count=count+1 if count == k: return i # no element occurs k times return -1 # Driver Code if __name__=="__main__": arr = [1, 7, 4, 3, 4, 8, 7]; n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed by Arpit Jain
constant
quadratic
# Python3 implementation to # find first element # occurring k times # function to find the # first element occurring # k number of times def firstElement(arr, n, k): # dictionary to count # occurrences of # each element count_map = {}; for i in range(0, n): if(arr[i] in count_map.keys()): count_map[arr[i]] += 1 else: count_map[arr[i]] = 1 i += 1 for i in range(0, n): # if count of element == k , # then it is the required # first element if (count_map[arr[i]] == k): return arr[i] i += 1 # no element occurs k times return -1 # Driver Code if __name__=="__main__": arr = [1, 7, 4, 3, 4, 8, 7]; n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed # by Abhishek Sharma
linear
linear
# importing counter from collections from collections import Counter # Python3 implementation to find # first element occurring k times # function to find the first element # occurring k number of times def firstElement(arr, n, k): # calculating frequencies using Counter count_map = Counter(arr) for i in range(0, n): # If count of element == k , # then it is the required # first element if (count_map[arr[i]] == k): return arr[i] i += 1 # No element occurs k times return -1 # Driver Code if __name__ == "__main__": arr = [1, 7, 4, 3, 4, 8, 7] n = len(arr) k = 2 print(firstElement(arr, n, k)) # This code is contributed by vikkycirus
linear
nlogn
# A Python3 program to find all symmetric # pairs in a given array of pairs. # Print all pairs that have # a symmetric counterpart def findSymPairs(arr, row): # This loop for selection of one pair for i in range(0, row): # This loop for searching of symmetric pair for j in range(i + 1, row): # Condition of symmetric pair if (arr[i][0] == arr[j][1] and arr[i][1] == arr[j][0]): print("(",arr[i][0],",",arr[i][1],")") # Driver Code if __name__ == '__main__': arr = [[0 for i in range(2)] for i in range(5)] arr[0][0], arr[0][1] = 11, 20 arr[1][0], arr[1][1] = 30, 40 arr[2][0], arr[2][1] = 5, 10 arr[3][0], arr[3][1] = 40, 30 arr[4][0], arr[4][1] = 10, 5 findSymPairs(arr, 5) # This code is contributed by Arpit Jain
constant
quadratic
# A Python3 program to find all symmetric # pairs in a given array of pairs. # Print all pairs that have # a symmetric counterpart def findSymPairs(arr, row): # Creates an empty hashMap hM hM = dict() # Traverse through the given array for i in range(row): # First and second elements # of current pair first = arr[i][0] sec = arr[i][1] # If found and value in hash matches with first # element of this pair, we found symmetry if (sec in hM.keys() and hM[sec] == first): print("(", sec,",", first, ")") else: # Else put sec element of # this pair in hash hM[first] = sec # Driver Code if __name__ == '__main__': arr = [[0 for i in range(2)] for i in range(5)] arr[0][0], arr[0][1] = 11, 20 arr[1][0], arr[1][1] = 30, 40 arr[2][0], arr[2][1] = 5, 10 arr[3][0], arr[3][1] = 40, 30 arr[4][0], arr[4][1] = 10, 5 findSymPairs(arr, 5) # This code is contributed by Mohit Kumar
linear
linear
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): for i in range(N): for j in range(i + 1, N): if (arr[i] == arr[j]): return arr[i] # Driver's Code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Arpit Jain
constant
quadratic
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): arr.sort() for i in range(1, N): if(arr[i] != i+1): return arr[i] # Driver's Code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Arpit Jain
constant
nlogn
# Python3 program to find the only # repeating element in an array # where elements are from 1 to n-1. def findRepeating(arr, N): s = set() for i in range(N): if arr[i] in s: return arr[i] s.add(arr[i]) # If input is correct, we should # never reach here return -1 # Driver code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed # by Shrikant13
linear
linear
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): # Find array sum and subtract sum # first n-1 natural numbers from it # to find the result. return sum(arr) - (((N - 1) * N) // 2) # Driver's Code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed # by mohit kumar
constant
linear
# Python3 program to find the only # repeating element in an array where # elements are from 1 to N-1. def findRepeating(arr, N): # res is going to store value of # 1 ^ 2 ^ 3 .. ^ (N-1) ^ arr[0] ^ # arr[1] ^ .... arr[n-1] res = 0 for i in range(0, N-1): res = res ^ (i+1) ^ arr[i] res = res ^ arr[N-1] return res # Driver code if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Smitha Dinesh Semwal.
constant
linear
# Python3 program to find the only # repeating element in an array # where elements are from 1 to N-1. # Function to find repeated element def findRepeating(arr, N): missingElement = 0 # indexing based for i in range(0, N): 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 if __name__ == "__main__": arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] N = len(arr) # Function call print(findRepeating(arr, N)) # This code is contributed by Smitha Dinesh Semwal.
constant
linear
class GFG : @staticmethod def findDuplicate( nums) : slow = nums[0] fast = nums[0] while True : slow = nums[slow] fast = nums[nums[fast]] if((slow != fast) == False) : break fast = nums[0] while (slow != fast) : slow = nums[slow] fast = nums[fast] return slow @staticmethod def main( args) : arr = [9, 8, 2, 6, 1, 8, 5, 3, 4, 7] # Function call ans = GFG.findDuplicate(arr) print(ans) if __name__=="__main__": GFG.main([]) # This code is contributed by aadityaburujwale.
constant
linear
# Python 3program to find one of the repeating # elements in a read only array from math import sqrt # Function to find one of the repeating # elements def findRepeatingNumber(arr, n): for i in arr: count = 0; for j in arr: if i == j: count=count+1 if(count>1): return i # return -1 if no repeating element exists return -1 # Driver Code if __name__ == '__main__': # read only array, not to be modified arr = [1, 1, 2, 3, 5, 4] # array of size 6(n + 1) having # elements between 1 and 5 n = 5 print("One of the numbers repeated in the array is:", findRepeatingNumber(arr, n)) # This code is contributed by Arpit Jain
constant
quadratic
# Python Program to Find the top three repeated numbers # User defined Pair class import sys class Pair: def __init__(self,first = 0,second = 0): self.first = first self.second = second # Function to print top three repeated numbers def top3Repeated(arr, n): # There should be atleast two elements if (n < 3): print("Invalid Input") return # Count Frequency of each element arr.sort() freq = {} for i in range(n): if (arr[i] in freq): freq[arr[i]] = 1 + freq[arr[i]] else: freq[arr[i]] = 1 # Initialize first value of each variable # of Pair type is INT_MIN x = Pair() y = Pair() z = Pair() x.first = y.first = z.first = -sys.maxsize -1 for curr,curr2 in freq.items(): # If frequency of current element # is not zero and greater than # frequency of first largest element if (int(curr2) > x.first): # Update second and third largest z.first = y.first z.second = y.second y.first = x.first y.second = x.second # Modify values of x Number x.first = int((curr2)) x.second = int((curr)) # 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 elif (int((curr2)) > y.first): # Modify values of third largest z.first = y.first z.second = y.second # Modify values of second largest y.first = int((curr2)) y.second = int((curr)) # 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. elif (int((curr2)) > z.first): # Modify values of z Number z.first = int((curr2)) z.second = int((curr)) print(f"Three largest elements are {x.second} {y.second} {z.second}") # Driver's Code arr = [ 3, 4, 2, 3, 16, 3, 15, 16, 15, 15, 16, 2, 3 ] n = len(arr) top3Repeated(arr, n) # This code is contributed by shinjanpatra
linear
linear
# A simple Python 3 program to # group multiple occurrences of # individual array elements # A simple method to group all # occurrences of individual elements def groupElements(arr, n): # Initialize all elements # as not visited visited = [False] * n for i in range(0, n): visited[i] = False # Traverse all elements for i in range(0, n): # Check if this is # first occurrence if (visited[i] == False): # If yes, print it and # all subsequent occurrences print(arr[i], end = " ") for j in range(i + 1, n): if (arr[i] == arr[j]): print(arr[i], end = " ") visited[j] = True # Driver Code arr = [4, 6, 9, 2, 3, 4, 9, 6, 10, 4] n = len(arr) groupElements(arr, n) # This code is contributed # by Smitha
linear
quadratic
# Python3 program to group multiple # occurrences of individual array elements # A hashing based method to group # all occurrences of individual elements def orderedGroup(arr): # Creates an empty hashmap hM = {} # Traverse the array elements, and store # count for every element in HashMap for i in range(0, len(arr)): # Increment count of elements # in HashMap hM[arr[i]] = hM.get(arr[i], 0) + 1 # Traverse array again for i in range(0, len(arr)): # Check if this is first occurrence count = hM.get(arr[i], None) if count != None: # If yes, then print # the element 'count' times for j in range(0, count): print(arr[i], end = " ") # And remove the element from HashMap. del hM[arr[i]] # Driver Code if __name__ == "__main__": arr = [10, 5, 3, 10, 10, 4, 1, 3] orderedGroup(arr) # This code is contributed by Rituraj Jain
linear
linear
# A Simple python 3 program to check # if two sets are disjoint # Returns true if set1[] and set2[] are disjoint, else false def areDisjoint(set1, set2, m, n): # Take every element of set1[] and search it in set2 for i in range(0, m): for j in range(0, n): if (set1[i] == set2[j]): return False # If no element of set1 is present in set2 return True # Driver program set1 = [12, 34, 11, 9, 3] set2 = [7, 2, 1, 5] m = len(set1) n = len(set2) print("yes") if areDisjoint(set1, set2, m, n) else(" No") # This code ia contributed by Smitha Dinesh Semwal
constant
quadratic
# A Simple Python 3 program to check # if two sets are disjoint # Returns true if set1[] and set2[] # are disjoint, else false def areDisjoint(set1, set2, m, n): # Sort the given two sets set1.sort() set2.sort() # Check for same elements # using merge like process i = 0; j = 0 while (i < m and j < n): if (set1[i] < set2[j]): i += 1 elif (set2[j] < set1[i]): j += 1 else: # if set1[i] == set2[j] return False return True # Driver Code set1 = [12, 34, 11, 9, 3] set2 = [7, 2, 1, 5] m = len(set1) n = len(set2) print("Yes") if areDisjoint(set1, set2, m, n) else print("No") # This code is contributed by Smitha Dinesh Semwal
constant
nlogn
# Python3 program to # check if two sets are # distinct or not # This function prints # all distinct elements def areDisjoint(set1, set2, n1, n2): # Creates an empty hashset myset = set([]) # Traverse the first set # and store its elements in hash for i in range (n1): myset.add(set1[i]) # Traverse the second set # and check if any element of it # is already in hash or not. for i in range (n2): if (set2[i] in myset): return False return True # Driver method to test above method if __name__ == "__main__": set1 = [10, 5, 3, 4, 6] set2 = [8, 7, 9, 3] n1 = len(set1) n2 = len(set2) if (areDisjoint(set1, set2, n1, n2)): print ("Yes") else: print("No") # This code is contributed by Chitranayal
linear
linear
# Python3 program to find Non-overlapping sum from collections import defaultdict # Function for calculating # Non-overlapping sum of two array def findSum(A, B, n): # Insert elements of both arrays Hash = defaultdict(lambda:0) for i in range(0, n): Hash[A[i]] += 1 Hash[B[i]] += 1 # calculate non-overlapped sum Sum = 0 for x in Hash: if Hash[x] == 1: Sum += x return Sum # Driver code if __name__ == "__main__": A = [5, 4, 9, 2, 3] B = [2, 8, 7, 6, 3] # size of array n = len(A) # Function call print(findSum(A, B, n)) # This code is contributed # by Rituraj Jain
linear
linear
# Python 3 simple program to find elements # which are not present in second array # Function for finding elements which # are there in a[] but not in b[]. def findMissing(a, b, n, m): for i in range(n): for j in range(m): if (a[i] == b[j]): break if (j == m - 1): print(a[i], end = " ") # Driver code if __name__ == "__main__": a = [ 1, 2, 6, 3, 4, 5 ] b = [ 2, 4, 3, 1, 0 ] n = len(a) m = len(b) findMissing(a, b, n, m) # This code is contributed # by ChitraNayal
constant
quadratic
# Python3 efficient program to find elements # which are not present in second array # Function for finding elements which # are there in a[] but not in b[]. def findMissing(a, b, n, m): # Store all elements of second # array in a hash table s = dict() for i in range(m): s[b[i]] = 1 # Print all elements of first array # that are not present in hash table for i in range(n): if a[i] not in s.keys(): print(a[i], end = " ") # Driver code a = [ 1, 2, 6, 3, 4, 5 ] b = [ 2, 4, 3, 1, 0 ] n = len(a) m = len(b) findMissing(a, b, n, m) # This code is contributed by mohit kumar
linear
linear
# Python3 program to find given # two array are equal or not # Returns true if arr1[0..n-1] and # arr2[0..m-1] contain same elements. def areEqual(arr1, arr2, N, M): # If lengths of array are not # equal means array are not equal if (N != M): return False # Sort both arrays arr1.sort() arr2.sort() # Linearly compare elements for i in range(0, N): if (arr1[i] != arr2[i]): return False # If all elements were same. return True # Driver Code if __name__ == "__main__": arr1 = [3, 5, 2, 5, 2] arr2 = [2, 3, 5, 5, 2] n = len(arr1) m = len(arr2) if (areEqual(arr1, arr2, n, m)): print("Yes") else: print("No")
constant
nlogn
# Python3 program for the above approach # Returns true if arr1[0..N-1] and # arr2[0..M-1] contain same elements. def is_arr_equal(arr1, arr2): # Check if the length of arrays are # equal or not: A Easy Logic Check if len(arr1) != len(arr2): return False # Create a dict named count to # store counts of each element count = {} # Store the elements of arr1 # and their counts in the dictionary for i in arr1: if i in count: # Element already in dict, simply increment its count count[i] += 1 else: # Element found for first time, initialize it with value 1. count[i] = 1 # Traverse through arr2 and compare # the elements and its count with # the elements of arr1 for i in arr2: # Return false if the element # is not in count or if any element # appears more no. of times than in arr1 if i not in count or count[i] == 0: return False else: # If element is found, decrement # its value in the dictionary count[i] -= 1 # Return true if both arr1 and # arr2 are equal return True # Driver Code if __name__ == "__main__": arr1 = [3, 5, 2, 5, 2] arr2 = [2, 3, 5, 5, 2] if is_arr_equal(arr1, arr2): print("Yes") else: print("No")
linear
linear
# Python3 code to find maximum shortest # distance from endpoints # function to find maximum shortest distance def find_maximum(a, n, k): # stores the shortest distance of every # element in original array. b = dict() for i in range(n): x = a[i] # shortest distance from ends d = min(1 + i, n - i) if x not in b.keys(): 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]) ans = 10**9 for i in range(n): x = a[i] # similar elements ignore them # cause we need distinct elements if (x != (k - x) and (k - x) in b.keys()): ans = min(max(b[x], b[k - x]), ans) return ans # Driver code a = [3, 5, 8, 6, 7] K = 11 n = len(a) print(find_maximum(a, n, K)) # This code is contributed by mohit kumar
linear
linear
# Python library for binary search from bisect import bisect_left # A sorting based C++ program to find missing # elements from an array # Print all elements of range [low, high] that # are not present in arr[0..n-1] def printMissing(arr, n, low, high): # Sort the array arr.sort() # Do binary search for 'low' in sorted # array and find index of first element # which either equal to or greater than # low. ptr = bisect_left(arr, low) index = ptr # Start from the found index and linearly # search every range element x after this # index in arr[] i = index x = low while (i < n and x <= high): # If x doesn't match with current element # print it if(arr[i] != x): print(x, end =" ") # If x matches, move to next element in arr[] else: i = i + 1 # Move to next element in range [low, high] x = x + 1 # Print range elements that are greater than the # last element of sorted array. while (x <= high): print(x, end =" ") x = x + 1 # Driver code arr = [1, 3, 5, 4] n = len(arr) low = 1 high = 10 printMissing(arr, n, low, high); # This code is contributed by YatinGupta
linear
nlogn
# An array-based Python3 program to # find missing elements from an array # Print all elements of range # [low, high] that are not # present in arr[0..n-1] def printMissing(arr, n, low, high): # Create boolean list of size # high-low+1, each index i # representing whether (i+low)th # element found or not. points_of_range = [False] * (high-low+1) for i in range(n) : # if ith element of arr is in range # low to high then mark corresponding # index as true in array if ( low <= arr[i] and arr[i] <= high ) : points_of_range[arr[i]-low] = True # Traverse through the range # and print all elements whose value # is false for x in range(high-low+1) : if (points_of_range[x]==False) : print(low+x, end = " ") # Driver Code arr = [1, 3, 5, 4] n = len(arr) low, high = 1, 10 printMissing(arr, n, low, high) # This code is contributed # by Shubh Bansal
linear
linear
# A hashing based Python3 program to # find missing elements from an array # Print all elements of range # [low, high] that are not # present in arr[0..n-1] def printMissing(arr, n, low, high): # Insert all elements of # arr[] in set s = set(arr) # Traverse through the range # and print all missing elements for x in range(low, high + 1): if x not in s: print(x, end = ' ') # Driver Code arr = [1, 3, 5, 4] n = len(arr) low, high = 1, 10 printMissing(arr, n, low, high) # This code is contributed # by SamyuktaSHegde
linear
linear
# Python3 program to find the k-th # missing element in a given sequence # Returns k-th missing element. It returns -1 if # no k is more than number of missing elements. def find(a, b, k, n1, n2): # insert all elements of # given sequence b[]. s = set() for i in range(n2): s.add(b[i]) # Traverse through increasing sequence and # keep track of count of missing numbers. missing = 0 for i in range(n1): if a[i] not in s: missing += 1 if missing == k: return a[i] return -1 # Driver code a = [0, 2, 4, 6, 8, 10, 12, 14, 15] b = [4, 10, 6, 8, 12] n1 = len(a) n2 = len(b) k = 3 print(find(a, b, k, n1, n2)) # This code is contributed by Shrikant13
quadratic
linear
# Python 3 program to find a pair # with product in given array. # Function to find greatest number def findGreatest( arr , n): result = -1 for i in range(n): for j in range(n - 1): for k in range(j + 1, n): if (arr[j] * arr[k] == arr[i]): result = max(result, arr[i]) return result # Driver code if __name__ == "__main__": arr = [10, 3, 5, 30, 35] n = len(arr) print(findGreatest(arr, n)) # This code is contributed by ita_c
constant
cubic
# Python3 program to find the largest product number from math import sqrt # Function to find greatest number def findGreatest(arr, n): # Store occurrences of all elements in hash # array m = dict() for i in arr: m[i] = m.get(i, 0) + 1 # Sort the array and traverse all elements from # end. arr = sorted(arr) for i in range(n - 1, 0, -1): # For every element, check if there is another # element which divides it. j = 0 while(j < i and arr[j] <= sqrt(arr[i])): if (arr[i] % arr[j] == 0): 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] and (result in m.keys())and m[result] > 0): return arr[i] # To handle the case like arr[i] = 4 and # arr[j] = 2 elif (result == arr[j] and (result in m.keys()) and m[result] > 1): return arr[i] j += 1 return -1 # Drivers code arr = [10, 3, 5, 30, 35] n = len(arr) print(findGreatest(arr, n)) # This code is contributed by mohit kumar
linear
nlogn
# A sorting based solution to find the # minimum number of subsets of a set # such that every subset contains distinct # elements. # function to count subsets such that all # subsets have distinct elements. def subset(ar, n): # take input and initialize res = 0 res = 0 # sort the array ar.sort() # traverse the input array and # find maximum frequency for i in range(0, n) : count = 1 # for each number find its repetition / frequency for i in range(n - 1): if ar[i] == ar[i + 1]: count+=1 else: break # update res res = max(res, count) return res # Driver code ar = [ 5, 6, 9, 3, 4, 3, 4 ] n = len(ar) print(subset(ar, n)) # This code is contributed by # Smitha Dinesh Semwal
constant
quadratic
# A hashing based solution to find the # minimum number of subsets of a set such # that every subset contains distinct # elements. # Function to count subsets such that # all subsets have distinct elements. def subset(arr, n): # Traverse the input array and # store frequencies of elements mp = {i:0 for i in range(10)} for i in range(n): mp[arr[i]] += 1 # Find the maximum value in map. res = 0 for key, value in mp.items(): res = max(res, value) return res # Driver code if __name__ == '__main__': arr = [5, 6, 9, 3, 4, 3, 4] n = len(arr) print(subset(arr, n)) # This code is contributed by # Surendra_Gangwar
linear
linear
# Python3 program to find minimum # element to remove so no common # element exist in both array # To find no elements to remove # so no common element exist def minRemove(a, b, n, m): # To store count of array element countA = dict() countB = dict() # Count elements of a for i in range(n): countA[a[i]] = countA.get(a[i], 0) + 1 # Count elements of b for i in range(n): countB[b[i]] = countB.get(b[i], 0) + 1 # Traverse through all common # element, and pick minimum # occurrence from two arrays res = 0 for x in countA: if x in countB.keys(): res += min(countA[x],countB[x]) # To return count of # minimum elements return res # Driver Code a = [ 1, 2, 3, 4 ] b = [2, 3, 4, 5, 8 ] n = len(a) m = len(b) print(minRemove(a, b, n, m)) # This code is contributed # by mohit kumar
linear
linear
# Python implementation to # count items common to both # the lists but with different # prices # function to count items # common to both # the lists but with different prices def countItems(list1, list2): count = 0 # for each item of 'list1' # check if it is in 'list2' # but with a different price for i in list1: for j in list2: if i[0] == j[0] and i[1] != j[1]: count += 1 # required count of items return count # Driver program to test above list1 = [("apple", 60), ("bread", 20), ("wheat", 50), ("oil", 30)] list2 = [("milk", 20), ("bread", 15), ("wheat", 40), ("apple", 60)] print("Count = ", countItems(list1, list2)) # This code is contributed by Ansu Kumari.
constant
quadratic
# Python3 implementation to count # items common to both the lists # but with different prices # Details of an item from ast import Str from functools import cmp_to_key class item: def __init__(self, name, price): self.name = name self.price = price # 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 def binary_search(list2, low, high, str): while (low <= high): mid = ((low + high) // 2) # if true the item 'str' is in 'list2' # print(list2[mid].name,str) if (list2[mid].name == str): return list2[mid].price elif (list2[mid].name < str): 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 def custom_logic(a, b): return a.name == b.name def countItems(list1, m, list2, n): # sort 'list2' in alphabetical # order of items name sorted(list2,key=cmp_to_key(custom_logic)) # initial count count = 0 for i in range(m): # get the price of item 'list1[i]' # from 'list2' if item in not # present in second list then -1 # is being obtained r = binary_search(list2, 0, n - 1, list1[i].name) # if item is present in list2 # with a different price if ((r != -1) and (r != list1[i].price)): count += 1 # Required count of items return count # Driver code list1=[item("apple", 60), item("bread", 20), item("wheat", 50), item("oil", 30)] list2=[item("milk", 20), item("bread", 15), item("wheat", 40), item("apple", 60)] m = len(list1) n = len(list2) print(f"Count = {countItems(list1, m,list2, n)}") # This code is contributed by shinjanpatra
constant
nlogn
# Python3 implementation to count items common to both # the lists but with different prices # details of an item class item: def __init__(self, name, price): self.name = name self.price = price # function to count items common to both # the lists but with different prices def countItems(list1, m,list2, n): # 'um' implemented as hash table that contains # item name as the key and price as the value # associated with the key um = {} count = 0 # insert elements of 'list1' in 'um' for i in range(m): 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 i in range(n): if ((um.get(list2[i].name) != None) and (um[list2[i].name] != list2[i].price)): count+=1 # required count of items return count # Driver program to test above list1=[item("apple", 60), item("bread", 20), item("wheat", 50), item("oil", 30)] list2=[item("milk", 20), item("bread", 15), item("wheat", 40), item("apple", 60)] m = len(list1) n = len(list2) print("Count = " ,countItems(list1, m, list2, n)) # This code is contributed by Abhijeet Kumar(abhijeet19403)
linear
linear
# Function to print common strings # with minimum index sum def find(list1, list2): res = [] # resultant list max_possible_sum = len(list1) + len(list2) - 2 # iterating over sum in ascending order for sum in range(max_possible_sum + 1): # iterating over one list and check index # (Corresponding to given sum) in other list for i in range(sum + 1): # put common strings in resultant list if (i < len(list1) and (sum - i) < len(list2) and list1[i] == list2[sum - i]): res.append(list1[i]) # if common string found then break as we are # considering index sums in increasing order. if (len(res) > 0): break # print the resultant list for i in range(len(res)): print(res[i], end = " ") # Driver code # Creating list1 list1 = [] list1.append("GeeksforGeeks") list1.append("Udemy") list1.append("Coursera") list1.append("edX") # Creating list2 list2 = [] list2.append("Codecademy") list2.append("Khan Academy") list2.append("GeeksforGeeks") find(list1, list2) # This code is contributed by Mohit Kumar
linear
linear
# Hashing based Python3 program to find # common elements with minimum index sum import sys # Function to print common strings # with minimum index sum def find(list1, list2): # Mapping strings to their indices Map = {} for i in range(len(list1)): Map[list1[i]] = i # Resultant list res = [] minsum = sys.maxsize for j in range(len(list2)): if list2[j] in Map: # If current sum is smaller # than minsum Sum = j + Map[list2[j]] if (Sum < minsum): minsum = Sum res.clear() res.append(list2[j]) # If index sum is same then put this # string in resultant list as well else if (Sum == minsum): res.append(list2[j]) # Print result print(*res, sep = " ") # Driver code # Creating list1 list1 = [] list1.append("GeeksforGeeks") list1.append("Udemy") list1.append("Coursera") list1.append("edX") # Creating list2 list2 = [] list2.append("Codecademy") list2.append("Khan Academy") list2.append("GeeksforGeeks") find(list1, list2) # This code is contributed by avanitrachhadiya2155
linear
linear
# Python 3 program to find a pair with # given sum such that every element of # pair is in different rows. 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 def pairSum(mat, n, sum): # First sort all the rows # in ascending order for i in range(n): mat[i].sort() # 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 i in range(n - 1): for j in range(i + 1, n): left = 0 right = n - 1 while (left < n and right >= 0): if ((mat[i][left] + mat[j][right]) == sum): print( "(", mat[i][left], ", ", mat[j][right], "), ", end = " ") left += 1 right -= 1 else: if ((mat[i][left] + mat[j][right]) < sum): left += 1 else: right -= 1 # Driver Code if __name__ == "__main__": n = 4 sum = 11 mat = [[1, 3, 2, 4], [5, 8, 7, 6], [9, 10, 13, 11], [12, 0, 14, 15]] pairSum(mat, n, sum) # This code is contributed # by ChitraNayal
constant
cubic
# A Program to prints common element # in all rows of matrix # Specify number of rows and columns M = 4 N = 5 # prints common element in all # rows of matrix def printCommonElements(mat): mp = dict() # initialize 1st row elements # with value 1 for j in range(N): mp[mat[0][j]] = 1 # traverse the matrix for i in range(1, M): for j in range(N): # If element is present in the # map and is not duplicated in # current row. if (mat[i][j] in mp.keys() and 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: print(mat[i][j], end = " ") # Driver Code mat = [[1, 2, 1, 4, 8], [3, 7, 8, 5, 1], [8, 7, 7, 3, 1], [8, 1, 2, 7, 9]] printCommonElements(mat) # This code is contributed # by mohit kumar 29
linear
quadratic
# Python program to find all # permutations of a given row # Function to find all # permuted rows of a given row r def permutatedRows(mat, m, n, r): # Creating an empty set s=set() # Count frequencies of # elements in given row r for j in range(n): s.add(mat[r][j]) # Traverse through all remaining rows for i in range(m): # 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 for j in range(n): if mat[i][j] not in s: # to avoid the case when last # element does not match j = j - 2 break; if j + 1 != n: continue print(i) # Driver program to run the case m = 4 n = 4 r = 3 mat = [[3, 1, 4, 2], [1, 6, 9, 3], [1, 2, 3, 4], [4, 3, 2, 1]] permutatedRows(mat, m, n, r) # This code is contributed # by Upendra Singh Bartwal.
linear
quadratic
# Python3 code to make a permutation # of numbers from 1 to n using # minimum changes. def makePermutation (a, n): # Store counts of all elements. count = dict() for i in range(n): if count.get(a[i]): count[a[i]] += 1 else: count[a[i]] = 1; next_missing = 1 for i in range(n): if count[a[i]] != 1 or a[i] > n or a[i] < 1: count[a[i]] -= 1 # Find next missing element to put # in place of current element. while count.get(next_missing): next_missing+=1 # Replace with next missing and # insert the missing element in hash. a[i] = next_missing count[next_missing] = 1 # Driver Code A = [ 2, 2, 3, 3 ] n = len(A) makePermutation(A, n) for i in range(n): print(A[i], end = " ") # This code is contributed by "Sharad_Bhardwaj".
linear
nlogn
# Python3 implementation of simple method # to find count of pairs with given sum. # Returns number of pairs in arr[0..n-1] # with sum equal to 'sum' def getPairsCount(arr, n, sum): count = 0 # Initialize result # Consider all possible pairs # and check their sums for i in range(0, n): for j in range(i + 1, n): if arr[i] + arr[j] == sum: count += 1 return count # Driver function arr = [1, 5, 7, -1, 5] n = len(arr) sum = 6 print("Count of pairs is", getPairsCount(arr, n, sum)) # This code is contributed by Smitha Dinesh Semwal
constant
quadratic
# Python code to implement the approach import bisect # Function to find the count of pairs def getPairsCount(arr, n, k): arr.sort() x, c = 0, 0 for i in range(n-1): x = k-arr[i] # Lower bound from i+1 y = bisect.bisect_left(arr, x, i+1, n) # Upper bound from i+1 z = bisect.bisect(arr, x, i+1, n) c = c+z-y return c # Driver function arr = [1, 5, 7, -1, 5] n = len(arr) k = 6 # Function call print("Count of pairs is", getPairsCount(arr, n, k)) # This code is contributed by Pushpesh Raj
constant
nlogn
# Python 3 implementation of simple method # to find count of pairs with given sum. import sys # Returns number of pairs in arr[0..n-1] # with sum equal to 'sum' def getPairsCount(arr, n, sum): m = [0] * 1000 # Store counts of all elements in map m for i in range(0, n): m[arr[i]] += 1 twice_count = 0 # Iterate through each element and increment # the count (Notice that every pair is # counted twice) for i in range(0, n): twice_count += m[sum - arr[i]] # if (arr[i], arr[i]) pair satisfies the # condition, then we need to ensure that # the count is decreased by one such # that the (arr[i], arr[i]) pair is not # considered if (sum - arr[i] == arr[i]): twice_count -= 1 # return the half of twice_count return int(twice_count / 2) # Driver function arr = [1, 5, 7, -1, 5] n = len(arr) sum = 6 print("Count of pairs is", getPairsCount(arr, n, sum)) # This code is contributed by # Smitha Dinesh Semwal
linear
linear
# Python implementation of simple method to find count of # pairs with given sum. # Returns number of pairs in arr[0..n-1] with sum equal to 'sum' def getPairsCount(arr, n, sum): unordered_map = {} count = 0 for i in range(n): if sum - arr[i] in unordered_map: count += unordered_map[sum - arr[i]] if arr[i] in unordered_map: unordered_map[arr[i]] += 1 else: unordered_map[arr[i]] = 1 return count # Driver code arr = [1, 5, 7, -1, 5] n = len(arr) sum = 6 print('Count of pairs is', getPairsCount(arr, n, sum)) # This code is contributed by Manish Thapa
linear
linear
# A Python3 implementation to count # quadruples from four sorted arrays # whose sum is equal to a given value x # function to count all quadruples # from four sorted arrays whose sum # is equal to a given value x def countquadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # generate all possible # quadruples from the four # sorted arrays for i in range(n): for j in range(n): for k in range(n): for l in range(n): # check whether elements of # quadruple sum up to x or not if (arr1[i] + arr2[j] + arr3[k] + arr4[l] == x): count += 1 # required count of quadruples return count # Driver Code arr1 = [1, 4, 5, 6] arr2 = [2, 3, 7, 8] arr3 = [1, 4, 6, 10] arr4 = [2, 4, 7, 8 ] n = len(arr1) x = 30 print("Count = ", countquadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed # by Shrikant13
constant
np
# Python implementation to count quadruples from # four sorted arrays whose sum is equal to a # given value x # find the 'value' in the given array 'arr[]' # binary search technique is applied def isPresent(arr,low,high,value): while(low<=high): mid=(low+high)//2 # 'value' found if(arr[mid]==value): return True elif(arr[mid]>value): high=mid-1 else: low=mid+1 # 'value' not found return False # function to count all quadruples from four # sorted arrays whose sum is equal to a given value x def countQuadruples(arr1,arr2,arr3,arr4,n,x): count=0 #generate all triplets from the 1st three arrays for i in range(n): for j in range(n): for k in range(n): # calculate the sum of elements in # the triplet so generated T=arr1[i]+arr2[j]+arr3[k] # check if 'x-T' is present in 4th # array or not if(isPresent(arr4,0,n-1,x-T)): # increment count count=count+1 # required count of quadruples return count # Driver program to test above # four sorted arrays each of size 'n' arr1=[1, 4, 5, 6] arr2=[2, 3, 7, 8] arr3=[1, 4, 6, 10] arr4=[2, 4, 7, 8] n=len(arr1) x=30 print("Count = {}".format(countQuadruples(arr1,arr2,arr3,arr4,n,x))) # This code is contributed by Pushpesh Raj.
constant
cubic
# Python3 implementation to # count quadruples from four # sorted arrays whose sum is # equal to a given value x # count pairs from the two # sorted array whose sum # is equal to the given 'value' def countPairs(arr1, arr2, n, value): count = 0 l = 0 r = n - 1 # traverse 'arr1[]' from # left to right # traverse 'arr2[]' from # right to left while (l < n and r >= 0): sum = arr1[l] + arr2[r] # if the 'sum' is equal # to 'value', then # increment 'l', decrement # 'r' and increment 'count' if (sum == value): l += 1 r -= 1 count += 1 # if the 'sum' is greater # than 'value', then decrement r elif (sum > value): r -= 1 # else increment l else: l += 1 # required count of pairs # print(count) return count # function to count all quadruples # from four sorted arrays whose sum # is equal to a given value x def countQuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # generate all pairs from # arr1[] and arr2[] for i in range(0, n): for j in range(0, n): # calculate the sum of # elements in the pair # so generated p_sum = arr1[i] + arr2[j] # count pairs in the 3rd # and 4th array having # value 'x-p_sum' and then # accumulate it to 'count count += int(countPairs(arr3, arr4, n, x - p_sum)) # required count of quadruples return count # Driver code arr1 = [1, 4, 5, 6] arr2 = [2, 3, 7, 8] arr3 = [1, 4, 6, 10] arr4 = [2, 4, 7, 8] n = len(arr1) x = 30 print("Count = ", countQuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed by Stream_Cipher
constant
cubic
# Python implementation to count quadruples from # four sorted arrays whose sum is equal to a # given value x # function to count all quadruples from four sorted # arrays whose sum is equal to a given value x def countQuadruples(arr1, arr2, arr3, arr4, n, x): count = 0 # unordered_map 'um' implemented as hash table # for <sum, frequency> tuples m = {} # count frequency of each sum obtained from the # pairs of arr1[] and arr2[] and store them in 'um' for i in range(n): for j in range(n): if (arr1[i] + arr2[j]) in m: m[arr1[i] + arr2[j]] += 1 else: m[arr1[i] + arr2[j]] = 1 # generate pair from arr3[] and arr4[] for k in range(n): for l in range(n): # calculate the sum of elements in # the pair so generated p_sum = arr3[k] + arr4[l] # if 'x-p_sum' is present in 'um' then # add frequency of 'x-p_sum' to 'count' if (x - p_sum) in m: count += m[x - p_sum] # required count of quadruples return count # Driver program to test above # four sorted arrays each of size 'n' arr1 = [1, 4, 5, 6] arr2 = [2, 3, 7, 8 ] arr3 = [1, 4, 6, 10] arr4 = [2, 4, 7, 8 ] n = len(arr1) x = 30 print("Count =", countQuadruples(arr1, arr2, arr3, arr4, n, x)) # This code is contributed by avanitrachhadiya2155
quadratic
quadratic
# Python3 program for # the above approach arr = [ 10, 2, -2, -20, 10 ] n = len(arr) k = -10 res = 0 # Calculate all subarrays for i in range(n): summ = 0 for j in range(i, n): # Calculate required sum summ += arr[j] # Check if sum is equal to # required sum if summ == k: res += 1 print(res) # This code is contributed by kavan155gondalia
constant
quadratic
# Python3 program to find the number of # subarrays with sum exactly equal to k. from collections import defaultdict # Function to find number of subarrays # with sum exactly equal to k. def findSubarraySum(arr, n, Sum): # Dictionary to store number of subarrays # starting from index zero having # particular value of sum. prevSum = defaultdict(lambda : 0) res = 0 # Sum of elements so far. currsum = 0 for i in range(0, n): # Add current element to sum so far. currsum += arr[i] # If currsum is equal to desired sum, # then a new subarray is found. So # increase count of subarrays. if currsum == Sum: res += 1 # currsum exceeds given sum by currsum - sum. # Find number of subarrays having # this sum and exclude those subarrays # from currsum by increasing count by # same amount. if (currsum - Sum) in prevSum: res += prevSum[currsum - Sum] # Add currsum value to count of # different values of sum. prevSum[currsum] += 1 return res if __name__ == "__main__": arr = [10, 2, -2, -20, 10] Sum = -10 n = len(arr) print(findSubarraySum(arr, n, Sum)) # This code is contributed by Rituraj Jain
linear
linear
# Python 3 program to find all # pairs in both arrays whose # sum is equal to given value x # Function to print all pairs # in both arrays whose sum is # equal to given value x def findPairs(arr1, arr2, n, m, x): for i in range(0, n): for j in range(0, m): if (arr1[i] + arr2[j] == x): print(arr1[i], arr2[j]) # Driver code arr1 = [1, 2, 3, 7, 5, 4] arr2 = [0, 7, 4, 3, 2, 1] n = len(arr1) m = len(arr2) x = 8 findPairs(arr1, arr2, n, m, x) # This code is contributed by Smitha Dinesh Semwal
constant
quadratic
# Python3 program to find all # pair in both arrays whose # sum is equal to given value x # Function to find all pairs # in both arrays whose sum is # equal to given value x def findPairs(arr1, arr2, n, m, x): # Insert all elements of # first array in a hash s = set() for i in range (0, n): s.add(arr1[i]) # Subtract sum from second # array elements one by one # and check it's present in # array first or not for j in range(0, m): if ((x - arr2[j]) in s): print((x - arr2[j]), '', arr2[j]) # Driver code arr1 = [1, 0, -4, 7, 6, 4] arr2 = [0, 2, 4, -3, 2, 1] x = 8 n = len(arr1) m = len(arr2) findPairs(arr1, arr2, n, m, x) # This code is contributed # by ihritik
linear
linear
# Python3 program to count cumulative # frequencies of elements in an unsorted array. def countFreq(a, n): # Insert elements and their # frequencies in hash map. hm = {} for i in range(0, n): hm[a[i]] = hm.get(a[i], 0) + 1 # Declare a set st = set() # Insert the element and # its frequency in a set for x in hm: st.add((x, hm[x])) cumul = 0 # Iterate the set and print # the cumulative frequency for x in sorted(st): cumul += x[1] print(x[0], cumul) # Driver Code if __name__ == "__main__": a = [1, 3, 2, 4, 2, 1] n = len(a) countFreq(a, n) # This code is contributed by Rituraj Jain
linear
nlogn
# Python3 program to print the cumulative # frequency according to the order given # Function to print the cumulative frequency # according to the order given def countFreq(a, n): # Insert elements and their # frequencies in hash map. hm = dict() for i in range(n): hm[a[i]] = hm.get(a[i], 0) + 1 cumul = 0 # traverse in the array for i in range(n): # add the frequencies cumul += hm[a[i]] # if the element has not been # visited previously if(hm[a[i]] > 0): print(a[i], "->", cumul) # mark the hash 0 # as the element's cumulative # frequency has been printed hm[a[i]] = 0 # Driver Code a = [1, 3, 2, 4, 2, 1] n = len(a) countFreq(a, n) # This code is contributed by mohit kumar
linear
linear
# Used for sorting by frequency. And if frequency is same, # then by appearance from functools import cmp_to_key def sortByVal(a,b): # If frequency is same then sort by index if (a[1] == b[1]): return a[0] - b[0] return b[1] - a[1] # function to sort elements by frequency def sortByFreq(a, n): res = [] m = {} v = [] for i in range(n): # Map m is used to keep track of count # of elements in array if(a[i] in m): m[a[i]] = m[a[i]]+1 else: m[a[i]] = 1 for key,value in m.items(): v.append([key,value]) # Sort the element of array by frequency v.sort(key = cmp_to_key(sortByVal)) for i in range(len(v)): while(v[i][1]): res.append(v[i][0]) v[i][1] -= 1 return res # Driver program a = [ 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 ] n = len(a) res = [] res = sortByFreq(a, n) for i in range(len(res)): print(res[i],end = " ") # This code is contributed by shinjanpatra
linear
linear
# A simple python program to find pair # whose sum already exists in array # Function to find pair whose sum # exists in arr[] def findPair(arr, n): found = False for i in range(0, n): for j in range(i + 1, n): for k in range(0, n): if (arr[i] + arr[j] == arr[k]): print(arr[i], arr[j]) found = True if (found == False): print("Not exist") # Driver code if __name__ == '__main__': arr = [ 10, 4, 8, 13, 5 ] n = len(arr) findPair(arr, n) # This code contributed by 29AjayKumar
constant
cubic
# Python3 program to find pair whose # sum already exist in array # Function to find pair whose # sum exists in arr[] def findPair(arr, n): # hash to store all element of array s = {i : 1 for i in arr} found = False for i in range(n): for j in range(i + 1, n): # check if sum already exists or not if arr[i] + arr[j] in s.keys(): print(arr[i], arr[j]) found = True if found == False: print("Not exist") # Driver code arr = [10, 4, 8, 13, 5] n = len(arr) findPair(arr, n) # This code is contributed # by Mohit Kumar
quadratic
quadratic
# Python3 implementation to find such pairs # Function to find pair such that (a % b = k) def printPairs(arr, n, k): isPairFound = True # Consider each and every pair for i in range(0, n): for j in range(0, n): # Print if their modulo equals to k if (i != j and arr[i] % arr[j] == k): print("(", arr[i], ", ", arr[j], ")", sep = "", end = " ") isPairFound = True return isPairFound # Driver Code arr = [2, 3, 5, 4, 7] n = len(arr) k = 3 if (printPairs(arr, n, k) == False): print("No such pair exists") # This article is contributed by Smitha Dinesh Semwal.
constant
quadratic