text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Edit Distance | DP | A Space efficient Dynamic Programming based Python3 program to find minimum number operations to convert str1 to str2 ; Create a DP array to memoize result of previous computations ; Base condition when second String is empty then we remove all characters ; Start filling the DP This loop run for ev... | def EditDistDP ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE DP = [ [ 0 for i in range ( len1 + 1 ) ] for j in range ( 2 ) ] ; NEW_LINE for i in range ( 0 , len1 + 1 ) : NEW_LINE INDENT DP [ 0 ] [ i ] = i NEW_LINE DEDENT for i in range ( 1 , len2 + 1 ) : NEW_LINE INDENT for... |
Sum of Bitwise XOR of elements of an array with all elements of another array | Function to calculate sum of Bitwise XOR of elements of arr [ ] with k ; Initialize sum to be zero ; Iterate over each set bit ; Stores contribution of i - th bet to the sum ; If the i - th bit is set ; Stores count of elements whose i - th... | def xorSumOfArray ( arr , n , k , count ) : NEW_LINE INDENT sum = 0 NEW_LINE p = 1 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT val = 0 NEW_LINE if ( ( k & ( 1 << i ) ) != 0 ) : NEW_LINE INDENT not_set = n - count [ i ] NEW_LINE val = ( ( not_set ) * p ) NEW_LINE DEDENT else : NEW_LINE INDENT val = ( count [ i ] * ... |
Minimum time required to schedule K processes | Function to execute k processes that can be gained in minimum amount of time ; Stores all the array elements ; Push all the elements to the priority queue ; Stores the required result ; Loop while the queue is not empty and K is positive ; Store the top element from the p... | def executeProcesses ( A , N , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( A [ i ] ) NEW_LINE DEDENT ans = 0 NEW_LINE pq . sort ( ) NEW_LINE while ( len ( pq ) > 0 and K > 0 ) : NEW_LINE INDENT top = pq . pop ( ) NEW_LINE ans += 1 NEW_LINE K -= top NEW_LINE top //= 2 NEW... |
Median of all nodes from a given range in a Binary Search Tree ( BST ) | Tree Node structure ; Function to create a new BST node ; Function to insert a new node with given key in BST ; If the tree is empty , return a new node ; Otherwise , recur down the tree ; Return the node pointer ; Function to find all the nodes t... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT interNodes = [ ] NEW_LINE def newNode ( key ) : NEW_LINE INDENT temp = Node ( key ) NEW_LINE return temp NEW_LINE DEDENT def insertNode ( node , key... |
Count number of pairs ( i , j ) up to N that can be made equal on multiplying with a pair from the range [ 1 , N / 2 ] | Function to compute totient of all numbers smaller than or equal to N ; Iterate over the range [ 2 , N ] ; If phi [ p ] is not computed already then p is prime ; Phi of a prime number p is ( p - 1 ) ... | def computeTotient ( N , phi ) : NEW_LINE INDENT for p in range ( 2 , N + 1 ) : NEW_LINE INDENT if phi [ p ] == p : NEW_LINE INDENT phi [ p ] = p - 1 NEW_LINE for i in range ( 2 * p , N + 1 , p ) : NEW_LINE INDENT phi [ i ] = ( phi [ i ] // p ) * ( p - 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def countPairs ( N ) : NEW... |
Sum of subsets nearest to K possible from two given arrays | Stores the sum closest to K ; Stores the minimum absolute difference ; Function to choose the elements from the array B [ ] ; If absolute difference is less then minimum value ; Update the minimum value ; Update the value of ans ; If absolute difference betwe... | ans = 10 ** 8 NEW_LINE mini = 10 ** 8 NEW_LINE def findClosestTarget ( i , curr , B , M , K ) : NEW_LINE INDENT global ans , mini NEW_LINE if ( abs ( curr - K ) < mini ) : NEW_LINE INDENT mini = abs ( curr - K ) NEW_LINE ans = curr NEW_LINE DEDENT if ( abs ( curr - K ) == mini ) : NEW_LINE INDENT ans = min ( ans , curr... |
Check if every node can me made accessible from a node of a Tree by at most N / 2 given operations | ; Store the indegree of every node ; Store the nodes having indegree equal to 0 ; Traverse the array ; If the indegree of i - th node is 0 ; Increment count0 by 1 ; If the number of operations needed is at most floor (... | / * Function to check if there is a NEW_LINE INDENT node in tree from where all other NEW_LINE nodes are accessible or not * / NEW_LINE DEDENT def findNode ( mp , n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = mp [ i + 1 ] NEW_LINE DEDENT count0 = 0 NEW_LINE for i in range... |
Check if Bitwise AND of concatenation of diagonals exceeds that of middle row / column elements of a Binary Matrix | Functio to convert obtained binary representation to decimal value ; Stores the resultant number ; Traverse string arr ; Return the number formed ; Function to count the number of set bits in the number ... | def convert ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in arr : NEW_LINE INDENT ans = ( ans << 1 ) | i NEW_LINE DEDENT return ans NEW_LINE DEDENT def count ( num ) : NEW_LINE INDENT ans = 0 NEW_LINE while num : NEW_LINE INDENT ans += num & 1 NEW_LINE num >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def checkG... |
Construct a Tree whose sum of nodes of all the root to leaf path is not divisible by the count of nodes in that path | Python3 program for the above approach ; Function to assign values to nodes of the tree s . t . sum of values of nodes of path between any 2 nodes is not divisible by length of path ; Stores the adjace... | from collections import deque NEW_LINE def assignValues ( Edges , n ) : NEW_LINE INDENT tree = [ [ ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] NEW_LINE v = Edges [ i ] [ 1 ] NEW_LINE tree [ u ] . append ( v ) NEW_LINE tree [ v ] . append ( u ) NEW_LINE DEDENT v... |
Number of full binary trees such that each node is product of its children | Return the number of all possible full binary tree with given product property . ; Finding the minimum and maximum values in given array . ; Marking the presence of each array element and initialising the number of possible full binary tree fo... | def numoffbt ( arr , n ) : NEW_LINE INDENT maxvalue = - 2147483647 NEW_LINE minvalue = 2147483647 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxvalue = max ( maxvalue , arr [ i ] ) NEW_LINE minvalue = min ( minvalue , arr [ i ] ) NEW_LINE DEDENT mark = [ 0 for i in range ( maxvalue + 2 ) ] NEW_LINE value = [ 0 for... |
Minimum prime numbers required to be subtracted to make all array elements equal | Python3 program for the above approach ; Stores the sieve of prime numbers ; Function that performs the Sieve of Eratosthenes ; Iterate over the range [ 2 , 1000 ] ; If the current element is a prime number ; Mark all its multiples as fa... | import sys NEW_LINE limit = 100000 NEW_LINE prime = [ True ] * ( limit + 1 ) NEW_LINE def sieve ( ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= limit ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , limit , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p... |
Print all unique digits present in concatenation of all array elements in the order of their occurrence | Function to print unique elements ; Reverse the list ; Traverse the list ; Function which check for all unique digits ; Stores the final number ; Stores the count of unique digits ; Converting string to integer to ... | def printUnique ( lis ) : NEW_LINE INDENT lis . reverse ( ) NEW_LINE for i in lis : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT def checkUnique ( string ) : NEW_LINE INDENT lis = [ ] NEW_LINE res = 0 NEW_LINE N = int ( string ) NEW_LINE cnt = [ 0 ] * 10 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT re... |
Maximize sum of Bitwise AND of same | Function to calculate sum of Bitwise AND of same indexed elements of the arrays p [ ] and arr [ ] ; Stores the resultant sum ; Traverse the array ; Update sum of Bitwise AND ; Return the value obtained ; Function to generate all permutations and calculate the maximum sum of Bitwise... | def calcScore ( p , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT ans += ( p [ i ] & arr [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMaxUtil ( p , arr , ans , chosen , N ) : NEW_LINE INDENT if len ( p ) == N : NEW_LINE INDENT ans = max ( ans , calcScore ( p , ar... |
Sum of array elements whose count of set bits are unique | Function to count the number of set bits in an integer N ; Stores the count of set bits ; Iterate until N is non - zero ; Stores the resultant count ; Function to calculate sum of all array elements whose count of set bits are unique ; Stores frequency of all p... | def setBitCount ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while n : NEW_LINE INDENT ans += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def getSum ( arr ) : NEW_LINE INDENT mp = { } NEW_LINE ans = 0 NEW_LINE for i in arr : NEW_LINE INDENT key = setBitCount ( i ) NEW_LINE mp [ key ] = [ 0 , i ] NEW_L... |
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Function to check if array can be split into three equal sum subarrays by removing a pair ; Stores prefix sum array ; Traverse the array ; Stores sums of all three subarrays ; Sum of left subarray ; Sum of middle ... | def findSplit ( arr , N ) : NEW_LINE INDENT sum = [ i for i in arr ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT sum [ i ] += sum [ i - 1 ] NEW_LINE DEDENT for l in range ( 1 , N - 3 ) : NEW_LINE INDENT for r in range ( l + 2 , N - 1 ) : NEW_LINE INDENT lsum , rsum , msum = 0 , 0 , 0 NEW_LINE lsum = sum [ l - 1... |
Print indices of pair of array elements required to be removed to split array into 3 equal sum subarrays | Function to check if array can be split into three equal sum subarrays by removing a pair ; Two pointers l and r ; Stores prefix sum array ; Traverse the array ; Two pointer approach ; Sum of left subarray ; Sum o... | def findSplit ( arr , N ) : NEW_LINE INDENT l = 1 ; r = N - 2 ; NEW_LINE sum = [ 0 ] * N ; NEW_LINE sum [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT sum [ i ] = sum [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT while ( l < r ) : NEW_LINE INDENT lsum = sum [ l - 1 ] ; NEW_LINE msum = sum [ r - 1 ] -... |
Number of subtrees having odd count of even numbers | Helper class that allocates a new Node with the given data and None left and right pointers . ; Returns count of subtrees having odd count of even numbers ; base condition ; count even nodes in left subtree ; Add even nodes in right subtree ; Check if root data is a... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def countRec ( root , pcount ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT c = countRec ( root . left , pcount ) NEW_LI... |
Inorder Successor of a node in Binary Tree | A Binary Tree Node Utility function to create a new tree node ; function to find left most node in a tree ; function to find right most node in a tree ; recursive function to find the Inorder Scuccessor when the right child of node x is None ; function to find inorder succes... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def leftMostNode ( node ) : NEW_LINE INDENT while ( node != None and node . left != None ) : NEW_LINE INDENT node = node . left NEW_LINE DEDEN... |
Binary Tree | Set 1 ( Introduction ) | Class containing left and right child of current node and key value ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = key NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) ; NEW_LINE root . right = Node ( 3 ) ; NEW_LINE root . left . left = Node ( 4 ) ; NEW_LINE |
Find distance from root to given node in a binary tree | A class to create a new Binary Tree Node ; Returns - 1 if x doesn 't exist in tree. Else returns distance of x from root ; Base case ; Initialize distance ; Check if x is present at root or in left subtree or right subtree . ; Driver Code | class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findDistance ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT dist = - 1 NEW_LINE if ( root . data == x )... |
Find right sibling of a binary tree with parent pointers | A class to create a new Binary Tree Node ; Method to find right sibling ; GET Parent pointer whose right child is not a parent or itself of this node . There might be case when parent has no right child , but , current node is left child of the parent ( second ... | class newNode : NEW_LINE INDENT def __init__ ( self , item , parent ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE self . parent = parent NEW_LINE DEDENT DEDENT def findRightSibling ( node , level ) : NEW_LINE INDENT if ( node == None or node . parent == None ) : NEW_LINE IND... |
Find next right node of a given key | Set 2 | class to create a new tree node ; Function to find next node for given node in same level in a binary tree by using pre - order traversal ; return None if tree is empty ; if desired node is found , set value_level to current level ; if value_level is already set , then curr... | class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def nextRightNode ( root , k , level , value_level ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( root . key == k )... |
Top three elements in binary tree | Helper function that allocates a new Node with the given data and None left and right pointers . ; function to find three largest element ; if data is greater than first large number update the top three list ; if data is greater than second large number and not equal to first update... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def threelargest ( root , first , second , third ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . ... |
Find maximum ( or minimum ) in Binary Tree | A class to create a new node ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; Returns maximum value in a given Binary Tree ; Base case ; Return maximum of 3 values : 1 ) Root 's data 2) Max in Left Subtree 3) Max in right subtr... | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findMax ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return float ( ' - inf ' ) NEW_LINE DEDENT res = root . data NEW_LINE lres = fi... |
Find maximum ( or minimum ) in Binary Tree | Returns the min value in a binary tree | def find_min_in_BT ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return float ( ' inf ' ) NEW_LINE DEDENT res = root . data NEW_LINE lres = find_min_in_BT ( root . leftChild ) NEW_LINE rres = find_min_in_BT ( root . rightChild ) NEW_LINE if lres < res : NEW_LINE INDENT res = lres NEW_LINE DEDENT if rres ... |
Extract Leaves of a Binary Tree in a Doubly Linked List | A binary tree node ; Main function which extracts all leaves from given Binary Tree . The function returns new root of Binary Tree ( Note thatroot may change if Binary Tree has only one node ) . The function also sets * head_ref as head of doubly linked list . l... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def extractLeafList ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . left is None and root . ri... |
Inorder Successor of a node in Binary Tree | A Binary Tree Node ; Function to create a new Node . ; function that prints the inorder successor of a target node . next will point the last tracked node , which will be the answer . ; if root is None then return ; if target node found , then enter this condition ; Driver C... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( val ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = val NEW_LINE temp . left = None NEW_LINE temp . right = None NEW_L... |
Graph representations using set and hash | ; Adds an edge to undirected graph ; Add an edge from source to destination . A new element is inserted to adjacent list of source . ; Add an dge from destination to source . A new element is inserted to adjacent list of destination . ; A utility function to print the adjacen... | class graph ( object ) : NEW_LINE INDENT def __init__ ( self , v ) : NEW_LINE INDENT self . v = v NEW_LINE self . graph = dict ( ) NEW_LINE DEDENT def addEdge ( self , source , destination ) : NEW_LINE INDENT if source not in self . graph : NEW_LINE INDENT self . graph = { destination } NEW_LINE DEDENT else : NEW_LINE ... |
Find n | Python3 program for nth node of inorder traversal ; A Binary Tree Node ; Given a binary tree , print the nth node of inorder traversal ; first recur on left child ; when count = n then prelement ; now recur on right child ; Driver Code | count = [ 0 ] NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . visited = False NEW_LINE DEDENT DEDENT def NthInorder ( node , n ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT ret... |
Minimum initial vertices to traverse whole matrix with given conditions | Python3 program to find minimum initial vertices to reach whole matrix ; ( n , m ) is current source cell from which we need to do DFS . N and M are total no . of rows and columns . ; Marking the vertex as visited ; If below neighbor is valid and... | MAX = 100 NEW_LINE def dfs ( n , m , visit , adj , N , M ) : NEW_LINE INDENT visit [ n ] [ m ] = 1 NEW_LINE if ( n + 1 < N and adj [ n ] [ m ] >= adj [ n + 1 ] [ m ] and not visit [ n + 1 ] [ m ] ) : NEW_LINE INDENT dfs ( n + 1 , m , visit , adj , N , M ) NEW_LINE DEDENT if ( m + 1 < M and adj [ n ] [ m ] >= adj [ n ] ... |
Shortest path to reach one prime to other by changing single digit at a time | Python3 program to reach a prime number from another by changing single digits and using only prime numbers . ; Finding all 4 digit prime numbers ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value ... | import queue NEW_LINE class Graph : NEW_LINE INDENT def __init__ ( self , V ) : NEW_LINE INDENT self . V = V ; NEW_LINE self . l = [ [ ] for i in range ( V ) ] NEW_LINE DEDENT def addedge ( self , V1 , V2 ) : NEW_LINE INDENT self . l [ V1 ] . append ( V2 ) ; NEW_LINE self . l [ V2 ] . append ( V1 ) ; NEW_LINE DEDENT DE... |
Level of Each node in a Tree from source node ( using BFS ) | Python3 Program to determine level of each node and print level ; function to determine level of each node starting from x using BFS ; array to store level of each node ; create a queue ; enqueue element x ; initialize level of source node to 0 ; marked it a... | import queue NEW_LINE def printLevels ( graph , V , x ) : NEW_LINE INDENT level = [ None ] * V NEW_LINE marked = [ False ] * V NEW_LINE que = queue . Queue ( ) NEW_LINE que . put ( x ) NEW_LINE level [ x ] = 0 NEW_LINE marked [ x ] = True NEW_LINE while ( not que . empty ( ) ) : NEW_LINE INDENT x = que . get ( ) NEW_LI... |
Construct binary palindrome by repeated appending and trimming | function to apply DFS ; set the parent marked ; if the node has not been visited set it and its children marked ; link which digits must be equal ; connect the two indices ; set everything connected to first character as 1 ; Driver Code | def dfs ( parent , ans , connectchars ) : NEW_LINE INDENT ans [ parent ] = 1 NEW_LINE for i in range ( len ( connectchars [ parent ] ) ) : NEW_LINE INDENT if ( not ans [ connectchars [ parent ] [ i ] ] ) : NEW_LINE INDENT dfs ( connectchars [ parent ] [ i ] , ans , connectchars ) NEW_LINE DEDENT DEDENT DEDENT def print... |
Find n | A Binary Tree Node Utility function to create a new tree node ; function to find the N - th node in the postorder traversal of a given binary tree ; left recursion ; right recursion ; prints the n - th node of preorder traversal ; Driver Code ; prints n - th node found | class createNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT flag = [ 0 ] NEW_LINE def NthPostordernode ( root , N ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if (... |
Path in a Rectangle with Circles | Python3 program to find out path in a rectangle containing circles . ; Function to find out if there is any possible path or not . ; Take an array of m * n size and initialize each element to 0. ; Now using Pythagorean theorem find if a cell touches or within any circle or not . ; If ... | import math NEW_LINE import queue NEW_LINE def isPossible ( m , n , k , r , X , Y ) : NEW_LINE INDENT rect = [ [ 0 ] * n for i in range ( m ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT for p in range ( k ) : NEW_LINE INDENT if ( math . sqrt ( ( pow ( ( X [ p ] - 1 - i ) , 2... |
DFS for a n | DFS on tree ; Printing traversed node ; Traversing adjacent edges ; Not traversing the parent node ; Driver Code ; Number of nodes ; Adjacency List ; Designing the tree ; Function call | def dfs ( List , node , arrival ) : NEW_LINE INDENT print ( node ) NEW_LINE for i in range ( len ( List [ node ] ) ) : NEW_LINE INDENT if ( List [ node ] [ i ] != arrival ) : NEW_LINE INDENT dfs ( List , List [ node ] [ i ] , node ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT nodes =... |
Maximum number of edges to be added to a tree so that it stays a Bipartite graph | To store counts of nodes with two colors ; Increment count of nodes with current color ; Traversing adjacent nodes ; Not recurring for the parent node ; Finds maximum number of edges that can be added without violating Bipartite property... | def dfs ( adj , node , parent , color ) : NEW_LINE INDENT count_color [ color ] += 1 NEW_LINE for i in range ( len ( adj [ node ] ) ) : NEW_LINE INDENT if ( adj [ node ] [ i ] != parent ) : NEW_LINE INDENT dfs ( adj , adj [ node ] [ i ] , node , not color ) NEW_LINE DEDENT DEDENT DEDENT def findMaxEdges ( adj , n ) : N... |
Min steps to empty an Array by removing a pair each time with sum at most K | Function to count minimum steps ; Function to sort the array ; Run while loop ; Condition to check whether sum exceed the target or not ; Increment the step by 1 ; Return minimum steps ; Given array arr [ ] ; Given target value ; Function cal... | def countMinSteps ( arr , target , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE minimumSteps = 0 NEW_LINE i , j = 0 , n - 1 NEW_LINE while i <= j : NEW_LINE INDENT if arr [ i ] + arr [ j ] <= target : NEW_LINE INDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT minimumSteps += 1... |
Sort the strings based on the numbers of matchsticks required to represent them | Stick [ ] stores the count of sticks required to represent the alphabets ; Number [ ] stores the count of sticks required to represent the numerals ; Function that return the count of sticks required to represent the given string str ; Lo... | sticks = [ 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 ] NEW_LINE number = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] NEW_LINE def countSticks ( st ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( st ) ) : NEW_LINE INDENT ch = st [ i ] NEW_LINE if ( ch... |
Count number of pairs with positive sum in an array | Returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; Initialize result ; Consider all possible pairs and check their sums ; If arr [ i ] & arr [ j ] form valid pair ; Driver 's Code ; Function call to find the count of pairs | def CountPairs ( arr , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE ... |
Find if there exists a direction for ranges such that no two range intersect | Python implementation of the approach ; Function that returns true if the assignment of directions is possible ; Structure to hold details of each interval ; Sort the intervals based on velocity ; Test the condition for all intervals with sa... | MAX = 100001 NEW_LINE def isPossible ( rangee , N ) : NEW_LINE INDENT test = [ [ 0 for x in range ( 3 ) ] for x in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT test [ i ] [ 0 ] = rangee [ i ] [ 0 ] NEW_LINE test [ i ] [ 1 ] = rangee [ i ] [ 1 ] NEW_LINE test [ i ] [ 2 ] = rangee [ i ] [ 2 ] NEW_LINE DE... |
a | Function to return the modified string ; To store the previous character ; To store the starting indices of all the groups ; Starting index of the first group ; If the current character and the previous character differ ; Push the starting index of the new group ; The current character now becomes previous ; Sort t... | def get_string ( st , n ) : NEW_LINE INDENT prev = st [ 0 ] NEW_LINE result = [ ] NEW_LINE result . append ( 0 ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( st [ i ] . isdigit ( ) != prev . isdigit ( ) ) : NEW_LINE INDENT result . append ( i ) NEW_LINE DEDENT prev = st [ i ] NEW_LINE DEDENT st = list ( st ... |
Find the kth smallest number with sum of digits as m | Python3 implementation of the approach ; Recursively moving to add all the numbers upto a limit with sum of digits as m ; Max nber of digits allowed in a nber for this implementation ; Function to return the kth number with sum of digits as m ; The kth smallest num... | N = 2005 NEW_LINE ans = dict ( ) NEW_LINE def dfs ( n , left , ct ) : NEW_LINE INDENT if ( ct >= 15 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( left == 0 ) : NEW_LINE INDENT ans [ n ] = 1 NEW_LINE DEDENT for i in range ( min ( left , 9 ) + 1 ) : NEW_LINE INDENT dfs ( n * 10 + i , left - i , ct + 1 ) NEW_LINE DEDENT... |
Remove minimum elements from the array such that 2 * min becomes more than max | Python3 program to remove minimum elements from the array such that 2 * min becomes more than max ; Function to remove minimum elements from the array such that 2 * min becomes more than max ; Sort the array ; To store the required answer ... | from bisect import bisect_left as upper_bound NEW_LINE def Removal ( v , n ) : NEW_LINE INDENT v = sorted ( v ) NEW_LINE ans = 10 ** 9 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT j = upper_bound ( v , ( 2 * ( a [ i ] ) ) ) NEW_LINE ans = min ( ans , n - ( j - i - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DE... |
Sort the Queue using Recursion | defining a class Queue ; Function to push element in last by popping from front until size becomes 0 ; Base condition ; pop front element and push this last in a queue ; Recursive call for pushing element ; Function to push an element in the queue while maintaining the sorted order ; Ba... | class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . queue = [ ] NEW_LINE DEDENT def put ( self , item ) : NEW_LINE INDENT self . queue . append ( item ) NEW_LINE DEDENT def get ( self ) : NEW_LINE INDENT if len ( self . queue ) < 1 : NEW_LINE INDENT return None NEW_LINE DEDENT return self . que... |
Sort the character array based on ASCII % N | This function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; pivot ; Index of smaller element ; If current element i... | def partition ( arr , low , high , mod ) : NEW_LINE INDENT pivot = ord ( arr [ high ] ) ; NEW_LINE i = ( low - 1 ) ; NEW_LINE piv = pivot % mod ; NEW_LINE for j in range ( low , high ) : NEW_LINE INDENT a = ord ( arr [ j ] ) % mod ; NEW_LINE if ( a <= piv ) : NEW_LINE INDENT i += 1 ; NEW_LINE arr [ i ] , arr [ j ] = ar... |
Iterative selection sort for linked list | Linked List Node ; Function to sort a linked list using selection sort algorithm by swapping the next pointers ; While b is not the last node ; While d is pointing to a valid node ; If d appears immediately after b ; Case 1 : b is the head of the linked list ; Move d before b ... | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def selectionSort ( head ) : NEW_LINE INDENT a = b = head NEW_LINE while b . next : NEW_LINE INDENT c = d = b . next NEW_LINE while d : NEW_LINE INDENT if b . data > d . data :... |
Find original numbers from gcd ( ) every pair | Python 3 implementation of the approach ; Utility function to print the contents of an array ; Function to find the required numbers ; Sort array in decreasing order ; Count frequency of each element ; Size of the resultant array ; Store the highest element in the resulta... | from math import sqrt , gcd NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def findNumbers ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE freq = [ 0 for i in range ( arr [ 0 ] + 1 ) ] NEW_LINE for ... |
Bitwise AND of N binary strings | Python3 implementation of the above approach ; Function to find the bitwise AND of all the binary strings ; To store the largest and the smallest string ' s β size , β We β need β this β to β add β ' 0 's in the resultant string ; Reverse each string Since we need to perform AND opera... | import sys ; NEW_LINE def strBitwiseAND ( arr , n ) : NEW_LINE INDENT res = " " NEW_LINE smallest_size = sys . maxsize ; NEW_LINE largest_size = - ( sys . maxsize - 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] [ : : - 1 ] ; NEW_LINE smallest_size = min ( smallest_size , len ( arr [ i ] ) ... |
Print all paths from a given source to a destination using BFS | Python3 program to print all paths of source to destination in given graph ; Utility function for printing the found path in graph ; Utility function to check if current vertex is already present in path ; Utility function for finding paths in graph from ... | from typing import List NEW_LINE from collections import deque NEW_LINE def printpath ( path : List [ int ] ) -> None : NEW_LINE INDENT size = len ( path ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT print ( path [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def isNotVisited ( x : int , path : ... |
Rearrange Odd and Even values in Alternate Fashion in Ascending Order | Python3 implementation of the above approach ; Sort the array ; v1 = list ( ) to insert even values v2 = list ( ) to insert odd values ; Set flag to true if first element is even ; Start rearranging array ; If first element is even ; Else , first e... | def AlternateRearrange ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT v1 . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT v2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT index = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LI... |
Convert given array to Arithmetic Progression by adding an element | Function to return the number to be added ; If difference of the current consecutive elements is different from the common difference ; If number has already been chosen then it 's not possible to add another number ; If the current different is twic... | def getNumToAdd ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE d = arr [ 1 ] - arr [ 0 ] NEW_LINE numToAdd = - 1 NEW_LINE numAdded = False NEW_LINE for i in range ( 2 , n , 1 ) : NEW_LINE INDENT diff = arr [ i ] - arr [ i - 1 ] NEW_LINE if ( diff != d ) : NEW_LINE INDENT if ( numAdded ) : NEW_LIN... |
Minimum Numbers of cells that are connected with the smallest path between 3 given cells | Function to return the minimum cells that are connected via the minimum length path ; Array to store column number of the given cells ; Sort cells in ascending order of row number ; Middle row number ; Set pair to store required ... | def Minimum_Cells ( v ) : NEW_LINE INDENT col = [ 0 ] * 3 NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT column_number = v [ i ] [ 1 ] NEW_LINE col [ i ] = column_number NEW_LINE DEDENT col . sort ( ) NEW_LINE v . sort ( ) NEW_LINE MidRow = v [ 1 ] [ 0 ] NEW_LINE s = set ( ) NEW_LINE Maxcol = col [ 2 ] NEW_LINE MinCol... |
Get maximum items when other items of total cost of an item are free | Function to count the total number of items ; Sort the prices ; Choose the last element ; Initial count of item ; Sum to keep track of the total price of free items ; If total is less than or equal to z then we will add 1 to the answer ; | def items ( n , a ) : NEW_LINE INDENT a . sort ( ) NEW_LINE z = a [ n - 1 ] NEW_LINE x = 1 NEW_LINE s = 0 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT s += a [ i ] NEW_LINE if ( s <= z ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT / * ... |
Sorting array elements with set bits equal to K | Function to sort elements with set bits equal to k ; initialise two vectors ; first vector contains indices of required element ; second vector contains required elements ; sorting the elements in second vector ; replacing the elements with k set bits with the sorted el... | def sortWithSetbits ( arr , n , k ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( bin ( arr [ i ] ) . count ( '1' ) == k ) : NEW_LINE INDENT v1 . append ( i ) NEW_LINE v2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v2 . sort ( reverse = False ) NEW_LINE for ... |
Minimum boxes required to carry all gifts | Function to return number of boxes ; Sort the boxes in ascending order ; Try to fit smallest box with current heaviest box ( from right side ) ; Driver code | def numBoxex ( A , n , K ) : NEW_LINE INDENT A . sort ( ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE ans = 0 NEW_LINE while i <= j : NEW_LINE INDENT ans += 1 NEW_LINE if A [ i ] + A [ j ] <= K : NEW_LINE INDENT i += 1 NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NE... |
Count triplets in a sorted doubly linked list whose product is equal to a given value x | Python3 implementation to count triplets in a sorted doubly linked list whose product is equal to a given value 'x ; structure of node of doubly linked list ; function to count triplets in a sorted doubly linked list whose product... | ' NEW_LINE from math import ceil NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT ' NEW_LINE def countTriplets ( head , x ) : NEW_LINE INDENT ptr , ptr1 , ptr2 = None , None , None NEW_LINE co... |
Maximize the profit by selling at | Function to find profit ; Calculating profit for each gadget ; sort the profit array in descending order ; variable to calculate total profit ; check for best M profits ; Driver Code | def solve ( N , M , cp , sp ) : NEW_LINE INDENT profit = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT profit . append ( sp [ i ] - cp [ i ] ) NEW_LINE DEDENT profit . sort ( reverse = True ) NEW_LINE sum = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT if profit [ i ] > 0 : NEW_LINE INDENT sum += profit [ i ]... |
Find the largest number that can be formed with the given digits | Function to generate largest possible number with given digits ; sort the given array in descending order ; generate the number ; Driver code | def findMaxNum ( arr , n ) : NEW_LINE INDENT arr . sort ( rever num = arr [ 0 ] se = True ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT num = num * 10 + arr [ i ] NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 0 ] NEW_LINE n = len ( arr )... |
Minimum partitions of maximum size 2 and sum limited by given value | Python 3 program to count minimum number of partitions of size 2 and sum smaller than or equal to given key . ; sort the array ; if sum of ith smaller and jth larger element is less than key , then pack both numbers in a set otherwise pack the jth la... | def minimumSets ( arr , n , key ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE j = n - 1 NEW_LINE for i in range ( 0 , j + 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] <= key ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return i + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE IN... |
Bubble Sort On Doubly Linked List | structure of a node ; Function to insert a node at the beginning of a linked list ; Function to print nodes in a given linked list ; Bubble sort the given linked list ; Checking for empty list ; Driver code ; start with empty linked list ; Create linked list from the array arr [ ] . ... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def insertAtTheBegin ( start_ref , data ) : NEW_LINE INDENT ptr1 = Node ( data ) NEW_LINE ptr1 . data = data ; NEW_LINE ptr1 . next = start_ref ; ... |
Substring Sort | Alternative code to sort substrings ; sort the input array ; repeated length should be the same string ; two different strings with the same length input array cannot be sorted ; validate that each string is a substring of the following one ; get first element ; The array is valid and sorted print the ... | def substringSort ( arr , n , maxLen ) : NEW_LINE INDENT count = [ 0 ] * ( maxLen ) NEW_LINE sortedArr = [ " " ] * ( maxLen ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = arr [ i ] NEW_LINE Len = len ( s ) NEW_LINE if ( count [ Len - 1 ] == 0 ) : NEW_LINE INDENT sortedArr [ Len - 1 ] = s NEW_LINE count [ Len - 1... |
Number of paths from source to destination in a directed acyclic graph | Python3 program for Number of paths from one vertex to another vertex in a Directed Acyclic Graph ; to make graph ; function to add edge in graph ; there is path from a to b . ; function to make topological sorting ; insert all vertices which don ... | from collections import deque NEW_LINE MAXN = 1000005 NEW_LINE v = [ [ ] for i in range ( MAXN ) ] NEW_LINE def add_edge ( a , b , fre ) : NEW_LINE INDENT v [ a ] . append ( b ) NEW_LINE fre [ b ] += 1 NEW_LINE DEDENT def topological_sorting ( fre , n ) : NEW_LINE INDENT q = deque ( ) NEW_LINE for i in range ( n ) : NE... |
Print all the pairs that contains the positive and negative values of an element | Utility binary search ; Function ; Sort the array ; Traverse the array ; For every arr [ i ] < 0 element , do a binary search for arr [ i ] > 0. ; If found , print the pair . ; Driver code | def binary_search ( a , x , lo = 0 , hi = None ) : NEW_LINE INDENT if hi is None : NEW_LINE INDENT hi = len ( a ) NEW_LINE DEDENT while lo < hi : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE midval = a [ mid ] NEW_LINE if midval < x : NEW_LINE INDENT lo = mid + 1 NEW_LINE DEDENT elif midval > x : NEW_LINE INDENT hi ... |
Multiset Equivalence Problem | Python3 program to check if two given multisets are equivalent ; sort the elements of both multisets ; Return true if both multisets are same . ; Driver code | def areSame ( a , b ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE b . sort ( ) ; NEW_LINE return ( a == b ) a = [ 7 , 7 , 5 ] ; NEW_LINE DEDENT b = [ 7 , 5 , 5 ] ; NEW_LINE if ( areSame ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; ; NEW_LINE DEDENT |
Minimum number of edges between two vertices of a Graph | Python3 program to find minimum edge between given two vertex of Graph ; function for finding minimum no . of edge using BFS ; visited [ n ] for keeping track of visited node in BFS ; Initialize distances as 0 ; queue to do BFS . ; update distance for i ; functi... | import queue NEW_LINE def minEdgeBFS ( edges , u , v , n ) : NEW_LINE INDENT visited = [ 0 ] * n NEW_LINE distance = [ 0 ] * n NEW_LINE Q = queue . Queue ( ) NEW_LINE distance [ u ] = 0 NEW_LINE Q . put ( u ) NEW_LINE visited [ u ] = True NEW_LINE while ( not Q . empty ( ) ) : NEW_LINE INDENT x = Q . get ( ) NEW_LINE f... |
Minimum swaps so that binary search can be applied | Function to find minimum swaps . ; Here we are getting number of smaller and greater elements of k . ; Here we are calculating the actual position of k in the array . ; Implementing binary search as per the above - discussed cases . ; If we find the k . ; If we need ... | def findMinimumSwaps ( arr , n , k ) : NEW_LINE INDENT num_min = num_max = need_minimum = 0 NEW_LINE need_maximum = swaps = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < k ) : NEW_LINE INDENT num_min += 1 NEW_LINE DEDENT elif ( arr [ i ] > k ) : NEW_LINE INDENT num_max += 1 NEW_LINE DEDENT DEDENT f... |
Stable sort for descending order | | / * Driver code * / NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE arr . sort ( reverse = True ) NEW_LINE print ( " Array β after β sorting β : β " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ... |
Check if both halves of the string have at least one different character | Function which break string into two halves Sorts the two halves separately Compares the two halves return true if any index has non - zero value ; Declaration and initialization of counter array ; Driver function | def function ( st ) : NEW_LINE INDENT st = list ( st ) NEW_LINE l = len ( st ) NEW_LINE st [ : l // 2 ] = sorted ( st [ : l // 2 ] ) NEW_LINE st [ l // 2 : ] = sorted ( st [ l // 2 : ] ) NEW_LINE for i in range ( l // 2 ) : NEW_LINE INDENT if ( st [ i ] != st [ l // 2 + i ] ) : NEW_LINE INDENT return True NEW_LINE DEDE... |
Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Example input = [ 0 , 1 , 2 , 2 , 0 , 0 ] output = [ 0 , 0 , 0 , 1 , 2 , 2 ] | inputArray = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE outputArray = [ ] NEW_LINE indexOfOne = 0 NEW_LINE for item in inputArray : NEW_LINE INDENT if item == 2 : NEW_LINE INDENT outputArray . append ( item ) NEW_LINE DEDENT elif item == 1 : NEW_LINE INDENT outputArray . insert ( indexOfOne , item ) NEW... |
Number of visible boxes after putting one inside another | Python3 program to count number of visible boxes . ; return the minimum number of visible boxes ; New Queue of integers . ; sorting the array ; traversing the array ; checking if current element is greater than or equal to twice of front element ; Pushing each ... | import collections NEW_LINE def minimumBox ( arr , n ) : NEW_LINE INDENT q = collections . deque ( [ ] ) NEW_LINE arr . sort ( ) NEW_LINE q . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT now = q [ 0 ] NEW_LINE if ( arr [ i ] >= 2 * now ) : NEW_LINE INDENT q . popleft ( ) NEW_LINE DEDENT q . ... |
Sort a binary array using one traversal | A Python program to sort a binary array ; if number is smaller than 1 then swap it with j - th number ; Driver program | def sortBinaryArray ( a , n ) : NEW_LINE INDENT j = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] < 1 : NEW_LINE INDENT j = j + 1 NEW_LINE a [ i ] , a [ j ] = a [ j ] , a [ i ] NEW_LINE DEDENT DEDENT DEDENT a = [ 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 ] NEW_LI... |
Smallest element in an array that is repeated exactly ' k ' times . | finds the smallest number in arr [ ] that is repeated k times ; Sort the array ; Find the first element with exactly k occurrences . ; Driver code | def findDuplicate ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT j , count = i + 1 , 1 NEW_LINE while ( j < n and arr [ j ] == arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE j += 1 NEW_LINE DEDENT if ( count == k ) : NEW_LINE INDENT return arr [ i ] NEW_LIN... |
Longest Common Prefix using Sorting | Python 3 program to find longest common prefix of given array of words . ; if size is 0 , return empty string ; sort the array of strings ; find the minimum length from first and last string ; find the common prefix between the first and last string ; Driver Code | def longestCommonPrefix ( a ) : NEW_LINE INDENT size = len ( a ) NEW_LINE if ( size == 0 ) : NEW_LINE INDENT return " " NEW_LINE DEDENT if ( size == 1 ) : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT a . sort ( ) NEW_LINE end = min ( len ( a [ 0 ] ) , len ( a [ size - 1 ] ) ) NEW_LINE i = 0 NEW_LINE while ( i < end a... |
Find the minimum and maximum amount to buy all N candies | Python implementation to find the minimum and maximum amount ; function to find the maximum and the minimum cost required ; Sort the array ; print the minimum cost ; print the maximum cost ; Driver Code ; Function call | from math import ceil NEW_LINE def find ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE b = int ( ceil ( n / k ) ) NEW_LINE print ( " minimum β " , sum ( arr [ : b ] ) ) NEW_LINE print ( " maximum β " , sum ( arr [ - b : ] ) ) NEW_LINE DEDENT arr = [ 3 , 2 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW... |
Check if it is possible to sort an array with conditional swapping of adjacent allowed | Returns true if it is possible to sort else false / ; We need to do something only if previousl element is greater ; If difference is more than one , then not possible ; Driver code | def checkForSorting ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i + 1 ] == 1 ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE D... |
Sort an array of strings according to string lengths | Function to print the sorted array of string ; Function to Sort the array of string according to lengths . This function implements Insertion Sort . ; Insert s [ j ] at its correct position ; Driver code ; Function to perform sorting ; Calling the function to print... | def printArraystring ( string , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( string [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def sort ( s , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT temp = s [ i ] NEW_LINE j = i - 1 NEW_LINE while j >= 0 and len ( temp ) < len ( s [ j ... |
Hoare 's vs Lomuto partition scheme in QuickSort | This function takes first element as pivot , and places all the elements smaller than the pivot on the left side and all the elements greater than the pivot on the right side . It returns the index of the last element on the smaller side ; Find leftmost element greater... | def partition ( arr , low , high ) : NEW_LINE INDENT pivot = arr [ low ] NEW_LINE i = low - 1 NEW_LINE j = high + 1 NEW_LINE while ( True ) : NEW_LINE INDENT i += 1 NEW_LINE while ( arr [ i ] < pivot ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT j -= 1 NEW_LINE while ( arr [ j ] > pivot ) : NEW_LINE INDENT j -= 1 NEW_LINE... |
K | Return the K - th smallest element . ; sort ( arr , arr + n ) ; Checking if k lies before 1 st element ; If k is the first element of array arr [ ] . ; If k is more than last element ; If first element of array is 1. ; Reducing k by numbers before arr [ 0 ] . ; Finding k 'th smallest element after removing array e... | def ksmallest ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE if ( k < arr [ 0 ] ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT if ( k == arr [ 0 ] ) : NEW_LINE INDENT return arr [ 0 ] + 1 ; NEW_LINE DEDENT if ( k > arr [ n - 1 ] ) : NEW_LINE INDENT return k + n ; NEW_LINE DEDENT if ( arr [ 0 ] == 1 ) : NEW... |
Count nodes within K | Python3 program to count nodes inside K distance range from marked nodes ; Utility bfs method to fill distance vector and returns most distant marked node from node u ; push node u in queue and initialize its distance as 0 ; loop untill all nodes are processed ; if node is marked , update lastMar... | import queue NEW_LINE def bfsWithDistance ( g , mark , u , dis ) : NEW_LINE INDENT lastMarked = 0 NEW_LINE q = queue . Queue ( ) NEW_LINE q . put ( u ) NEW_LINE dis [ u ] = 0 NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT u = q . get ( ) NEW_LINE if ( mark [ u ] ) : NEW_LINE INDENT lastMarked = u NEW_LINE DEDEN... |
Check whether a given number is even or odd | Returns true if n is even , else odd ; n & 1 is 1 , then odd , else even ; Driver code | def isEven ( n ) : NEW_LINE INDENT return ( not ( n & 1 ) ) NEW_LINE DEDENT n = 101 ; NEW_LINE print ( " Even " if isEven ( n ) else " Odd " ) NEW_LINE |
Count distinct occurrences as a subsequence | Python3 program to count number of times S appears as a subsequence in T ; T can 't appear as a subsequence in S ; mat [ i ] [ j ] stores the count of occurrences of T ( 1. . i ) in S ( 1. . j ) . ; Initializing first column with all 0 s . x An empty string can 't have anot... | def findSubsequenceCount ( S , T ) : NEW_LINE INDENT m = len ( T ) NEW_LINE n = len ( S ) NEW_LINE if m > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT mat = [ [ 0 for _ in range ( n + 1 ) ] for __ in range ( m + 1 ) ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT mat [ i ] [ 0 ] = 0 NEW_LINE DEDENT for j in r... |
QuickSort Tail Call Optimization ( Reducing worst case space to Log n ) | Python3 program for the above approach ; pi is partitioning index , arr [ p ] is now at right place ; Separately sort elements before partition and after partition | def quickSort ( arr , low , high ) : NEW_LINE INDENT if ( low < high ) : NEW_LINE INDENT pi = partition ( arr , low , high ) NEW_LINE quickSort ( arr , low , pi - 1 ) NEW_LINE quickSort ( arr , pi + 1 , high ) NEW_LINE DEDENT DEDENT |
Check if a Regular Bracket Sequence can be formed with concatenation of given strings | Function to check possible RBS from the given strings ; Stores the values { sum , min_prefix } ; Iterate over the range ; Stores the total sum ; Stores the minimum prefix ; Check for minimum prefix ; Store these values in vector ; S... | def checkRBS ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE v = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT s = S [ i ] NEW_LINE sum = 0 NEW_LINE pre = 0 NEW_LINE for c in s : NEW_LINE INDENT if ( c == ' ( ' ) : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum -= 1 NEW_LINE DEDENT p... |
Maximize count of unique Squares that can be formed with N arbitrary points in coordinate plane | Python program for the above approach ; Function to find the maximum number of unique squares that can be formed from the given N points ; Stores the resultant count of squares formed ; Base Case ; Subtract the maximum pos... | import math NEW_LINE def maximumUniqueSquares ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE if N < 4 : NEW_LINE INDENT return 0 NEW_LINE DEDENT len = int ( math . sqrt ( N ) ) NEW_LINE N -= len * len NEW_LINE for i in range ( 1 , len ) : NEW_LINE INDENT ans += i * i NEW_LINE DEDENT if ( N >= len ) : NEW_LINE INDENT N -= len... |
Lexicographically smallest permutation number up to K having given array as a subsequence | Function to find the lexicographically smallest permutation such that the given array is a subsequence of it ; Stores the missing elements in arr in the range [ 1 , K ] ; Stores if the ith element is present in arr or not ; Loop... | def findPermutation ( K , arr ) : NEW_LINE INDENT missing = [ ] NEW_LINE visited = [ 0 ] * ( K + 1 ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT visited [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT missing . append ( i ) NEW_LINE DEDENT ... |
Last element remaining after repeated removal of Array elements at perfect square indices | Python 3 program for the above approach ; Function to find last remaining index after repeated removal of perfect square indices ; Initialize the ans variable as N ; Iterate a while loop and discard the possible values ; Total d... | from math import sqrt NEW_LINE def findRemainingIndex ( N ) : NEW_LINE INDENT ans = N NEW_LINE while ( N > 1 ) : NEW_LINE INDENT discard = int ( sqrt ( N ) ) NEW_LINE if ( discard * discard == N ) : NEW_LINE INDENT ans -= 1 NEW_LINE DEDENT N -= discard NEW_LINE DEDENT return ans NEW_LINE DEDENT def findRemainingElement... |
Minimum time to reach from Node 1 to N if travel is allowed only when node is Green | Import library for Queue ; Function to find min edge ; Initialize queue and push [ 1 , 0 ] ; Create visited array to keep the track if node is visited or not ; Run infinite loop ; If node is N , terminate loop ; Travel adjacent nodes ... | from queue import Queue NEW_LINE def minEdge ( ) : NEW_LINE INDENT Q = Queue ( ) NEW_LINE Q . put ( [ 1 , 0 ] ) NEW_LINE V = [ False for _ in range ( N + 1 ) ] NEW_LINE while 1 : NEW_LINE INDENT crnt , c = Q . get ( ) NEW_LINE if crnt == N : NEW_LINE INDENT break NEW_LINE DEDENT for _ in X [ crnt ] : NEW_LINE INDENT if... |
Count of subsets whose product is multiple of unique primes | Python program for the above approach ; Function to check number has distinct prime ; While N has factors of two ; Traversing till sqrt ( N ) ; If N has a factor of i ; While N has a factor of i ; Covering case , N is Prime ; Function to check wheather num c... | from math import gcd , sqrt NEW_LINE def checkDistinctPrime ( n ) : NEW_LINE INDENT original = n NEW_LINE product = 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT product *= 2 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT DEDENT for i in range ( 3 , int ( sqrt ( n ) ) , 2 ) : NEW_LINE INDEN... |
Lexicographically largest possible by merging two strings by adding one character at a time | Recursive function for finding the lexicographically largest string ; If either of the string length is 0 , return the other string ; If s1 is lexicographically larger than s2 ; Take first character of s1 and call the function... | def largestMerge ( s1 , s2 ) : NEW_LINE INDENT if len ( s1 ) == 0 or len ( s2 ) == 0 : NEW_LINE INDENT return s1 + s2 NEW_LINE DEDENT if ( s1 > s2 ) : NEW_LINE INDENT return s1 [ 0 ] + largestMerge ( s1 [ 1 : ] , s2 ) NEW_LINE DEDENT return s2 [ 0 ] + largestMerge ( s1 , s2 [ 1 : ] ) NEW_LINE DEDENT if __name__ == ' _ ... |
Minimum distance between duplicates in a String | This function is used to find the required the minimum distances of repeating characters ; Define dictionary and list ; Traverse through string ; If character present in dictionary ; Difference between current position and last stored value ; Updating current position ;... | def shortestDistance ( S , N ) : NEW_LINE INDENT dic = { } NEW_LINE dis = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] in dic : NEW_LINE INDENT var = i - dic [ S [ i ] ] NEW_LINE dic [ S [ i ] ] = i NEW_LINE dis . append ( var ) NEW_LINE DEDENT else : NEW_LINE INDENT dic [ S [ i ] ] = i NEW_LINE DEDEN... |
Number of open doors | TCS Coding Question | Python3 code for the above approach ; Function that counts the number of doors opens after the Nth turn ; Find the number of open doors ; Return the resultant count of open doors ; Driver Code | import math NEW_LINE def countOpenDoors ( N ) : NEW_LINE INDENT doorsOpen = int ( math . sqrt ( N ) ) NEW_LINE return doorsOpen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 NEW_LINE print ( countOpenDoors ( N ) ) NEW_LINE DEDENT |
Minimum number of candies required to distribute among children based on given conditions | Function to count the minimum number of candies that is to be distributed ; Stores total count of candies ; Stores the amount of candies allocated to a student ; If the value of N is 1 ; Traverse the array arr [ ] ; If arr [ i +... | def countCandies ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = [ 1 ] * n NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i + 1 ] > arr [ i ] and ans [ i + 1 ] <= ans [ i ] ) : NEW_LINE INDENT ans [ i + 1 ] = ans [ i ] + 1 NEW_LINE DEDENT DED... |
Maximize profit possible by selling M products such that profit of a product is the number of products left of that supplier | Function to find the maximum profit by selling M number of products ; Initialize a Max - Heap to keep track of the maximum value ; Stores the maximum profit ; Traverse the array and push all th... | def findMaximumProfit ( arr , M , N ) : NEW_LINE INDENT max_heap = [ ] NEW_LINE maxProfit = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT max_heap . append ( arr [ i ] ) NEW_LINE DEDENT max_heap . sort ( ) NEW_LINE max_heap . reverse ( ) NEW_LINE while ( M > 0 ) : NEW_LINE INDENT M -= 1 NEW_LINE X = max_heap [ ... |
Generate an array with K positive numbers such that arr [ i ] is either | Python program for the above approach Function to generate the resultant sequence of first N natural numbers ; Initialize an array of size N ; Stores the sum of positive and negative elements ; Mark the first N - K elements as negative ; Update t... | def findSequence ( n , k ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE sumPos = 0 NEW_LINE sumNeg = 0 NEW_LINE for i in range ( 0 , n - k ) : NEW_LINE INDENT arr [ i ] = - ( i + 1 ) NEW_LINE sumNeg += arr [ i ] NEW_LINE DEDENT for i in range ( n - k , n ) : NEW_LINE INDENT arr [ i ] = i + 1 NEW_LINE sumPos += arr [ i ] ... |
Print the indices for every row of a grid from which escaping from the grid is possible | Function to find the row index for every row of a matrix from which one can exit the grid after entering from left ; Iterate over the range [ 0 , M - 1 ] ; Stores the direction from which a person enters a cell ; Row index from wh... | def findPath ( arr , M , N ) : NEW_LINE INDENT for row in range ( M ) : NEW_LINE INDENT dir = ' L ' NEW_LINE i = row NEW_LINE j = 0 NEW_LINE while ( j < N ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == 1 ) : NEW_LINE INDENT if ( dir == ' L ' ) : NEW_LINE INDENT i -= 1 NEW_LINE dir = ' D ' NEW_LINE DEDENT elif ( dir == ' U... |
Maximize sum of array by repeatedly removing an element from pairs whose concatenation is a multiple of 3 | Function to calculate sum of digits of an integer ; Function to calculate maximum sum of array after removing pairs whose concatenation is divisible by 3 ; Stores the sum of digits of array element ; Find the sum... | def getSum ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in str ( n ) : NEW_LINE INDENT ans += int ( i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getMax ( arr ) : NEW_LINE INDENT maxRem0 = 0 NEW_LINE rem1 = 0 NEW_LINE rem2 = 0 NEW_LINE for i in arr : NEW_LINE INDENT digitSum = getSum ( i ) NEW_LINE if digitSum %... |
Minimum edge reversals to make a root | Python3 program to find min edge reversal to make every node reachable from root ; Method to dfs in tree and populates disRev values ; Visit current node ; Looping over all neighbors ; Distance of v will be one more than distance of u ; Initialize back edge count same as parent n... | import sys NEW_LINE def dfs ( g , disRev , visit , u ) : NEW_LINE INDENT visit [ u ] = True NEW_LINE totalRev = 0 NEW_LINE for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT v = g [ u ] [ i ] [ 0 ] NEW_LINE if ( not visit [ v ] ) : NEW_LINE INDENT disRev [ v ] [ 0 ] = disRev [ u ] [ 0 ] + 1 NEW_LINE disRev [ v ] [ 1 ... |
Check if 2 * K + 1 non | Function to check if the S can be obtained by ( K + 1 ) non - empty substrings whose concatenation and concatenation of the reverse of these K strings ; Stores the size of the string ; If n is less than 2 * k + 1 ; Stores the first K characters ; Stores the last K characters ; Reverse the strin... | def checkString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if ( 2 * k + 1 > n ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT a = s [ 0 : k ] NEW_LINE b = s [ n - k : n ] NEW_LINE b = b [ : : - 1 ] NEW_LINE if ( a == b ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE IN... |
Minimum number of socks required to picked to have at least K pairs of the same color | Function to count the minimum number of socks to be picked ; Stores the total count of pairs of socks ; Find the total count of pairs ; If K is greater than pairs ; Otherwise ; Driver Code | def findMin ( arr , N , k ) : NEW_LINE INDENT pairs = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pairs += arr [ i ] / 2 NEW_LINE DEDENT if ( k > pairs ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 * k + N - 1 NEW_LINE DEDENT DEDENT arr = [ 4 , 5 , 6 ] NEW_LINE k = 3 NEW_LINE prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.