text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Maximum sum after rearranging the array for K queries | Function to find maximum sum after rearranging array elements ; Auxiliary array to find the count of each selected elements Initialize with 0 ; Finding count of every element to be selected ; Making it to 0 - indexing ; Prefix sum array concept is used to obtain t... | def maxSumArrangement ( A , R , N , M ) : NEW_LINE INDENT count = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l = l - 1 NEW_LINE r = r - 1 NEW_LINE count [ l ] = count [ l ] + 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT count [ r ] =... |
Sum of M maximum distinct digit sum from 1 to N that are factors of K | Python 3 implementation to find the sum of maximum distinct digit sum of at most M numbers from 1 to N that are factors of K ; Function to find the factors of K in N ; Initialise a vector ; Find out the factors of K less than N ; Find the digit sum... | import math NEW_LINE def findFactors ( n , k ) : NEW_LINE INDENT factors = [ ] NEW_LINE sqt = ( int ) ( math . sqrt ( k ) ) NEW_LINE for i in range ( 1 , sqt ) : NEW_LINE INDENT if ( k % i == 0 ) : NEW_LINE INDENT if ( k // i == i and i <= n ) : NEW_LINE INDENT factors . append ( i ) NEW_LINE DEDENT else : NEW_LINE IND... |
Sorting objects using In | Partition function which will partition the array and into two parts ; Compare hash values of objects ; Classic quicksort algorithm ; Function to sort and print the objects ; As the sorting order is blue objects , red objects and then yellow objects ; Quick sort function ; Printing the sorted... | objects = [ ] NEW_LINE hash = dict ( ) NEW_LINE def partition ( l , r ) : NEW_LINE INDENT global objects , hash NEW_LINE j = l - 1 NEW_LINE last_element = hash [ objects [ r ] ] NEW_LINE for i in range ( l , r ) : NEW_LINE INDENT if ( hash [ objects [ i ] ] <= last_element ) : NEW_LINE INDENT j += 1 NEW_LINE ( objects ... |
Sort the numbers according to their product of digits | Function to return the product of the digits of n ; Function to sort the array according to the product of the digits of elements ; Vector to store the digit product with respective elements ; Inserting digit product with elements in the vector pair ; Sort the vec... | def productOfDigit ( n ) : NEW_LINE INDENT product = 1 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT product *= ( n % 10 ) ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return product ; NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( ( product... |
Minimum steps required to reduce all the elements of the array to zero | Function to return the minimum steps required to reduce all the elements to 0 ; Maximum element from the array ; Driver code | def minSteps ( arr , n ) : NEW_LINE INDENT maxVal = max ( arr ) NEW_LINE return maxVal NEW_LINE DEDENT arr = [ 1 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minSteps ( arr , n ) ) NEW_LINE |
Maximum water that can be stored between two buildings | Return the maximum water that can be stored ; Check all possible pairs of buildings ; Maximum so far ; Driver code | def maxWater ( height , n ) : NEW_LINE INDENT maximum = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT current = min ( height [ i ] , height [ j ] ) * ( j - i - 1 ) ; NEW_LINE maximum = max ( maximum , current ) ; NEW_LINE DEDENT DEDENT return maximum ; NEW_LINE D... |
Check if the given array contains all the divisors of some integer | Python 3 implementation of the approach ; Function that returns true if arr [ ] contains all the divisors of some integer ; Maximum element from the array ; Vector to store divisors of the maximum element i . e . X ; Store all the divisors of X ; If t... | from math import sqrt NEW_LINE def checkDivisors ( a , n ) : NEW_LINE INDENT X = max ( a ) NEW_LINE b = [ ] NEW_LINE for i in range ( 1 , int ( sqrt ( X ) ) + 1 ) : NEW_LINE INDENT if ( X % i == 0 ) : NEW_LINE INDENT b . append ( i ) NEW_LINE if ( X // i != i ) : NEW_LINE INDENT b . append ( X // i ) NEW_LINE DEDENT DE... |
Kth largest node among all directly connected nodes to the given node in an undirected graph | Function to print Kth node for each node ; Vector to store nodes directly connected to ith node along with their values ; Add edges to the vector along with the values of the node ; Sort neighbors of every node and find the K... | def findKthNode ( u , v , n , val , V , k ) : NEW_LINE INDENT g = [ [ ] for i in range ( V ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT g [ u [ i ] ] . append ( ( val [ v [ i ] ] , v [ i ] ) ) NEW_LINE g [ v [ i ] ] . append ( ( val [ u [ i ] ] , u [ i ] ) ) NEW_LINE DEDENT for i in range ( 0 , V ) : NEW_LIN... |
Minimum length of square to contain at least half of the given Coordinates | Function to Calculate the Minimum value of M ; To store the minimum M for each point in array ; Sort the array ; Index at which atleast required point are inside square of length 2 * M ; Driver Code | def findSquare ( n ) : NEW_LINE INDENT points = [ [ 1 , 2 ] , [ - 3 , 4 ] , [ 1 , 78 ] , [ - 3 , - 7 ] ] NEW_LINE a = [ None ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT x = points [ i ] [ 0 ] NEW_LINE y = points [ i ] [ 1 ] NEW_LINE a [ i ] = max ( abs ( x ) , abs ( y ) ) NEW_LINE DEDENT a . sort ( ) NEW_... |
Eulerian Path in undirected graph | Function to find out the path It takes the adjacency matrix representation of the graph as input ; Find out number of edges each vertex has ; Find out how many vertex has odd number edges ; If number of vertex with odd number of edges is greater than two return " No β Solution " . ; ... | def findpath ( graph , n ) : NEW_LINE INDENT numofadj = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT numofadj . append ( sum ( graph [ i ] ) ) NEW_LINE DEDENT startpoint , numofodd = 0 , 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( numofadj [ i ] % 2 == 1 ) : NEW_LINE INDENT numofodd +=... |
Array element with minimum sum of absolute differences | Function to return the minimized sum ; Sort the array ; Median of the array ; Calculate the minimized sum ; Return the required sum ; Driver code | def minSum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE x = arr [ n // 2 ] ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += abs ( arr [ i ] - x ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 9 , 3 , 6 ] ; NEW_LINE ... |
Sort even and odd placed elements in increasing order | function to prin the odd and even indexed digits ; lists to store the odd and even positioned digits ; traverse through all the indexes in the integer ; if the digit is in odd_index position append it to odd_position list ; else append it to the even_position list... | def odd_even ( n ) : NEW_LINE INDENT odd_indexes = [ ] NEW_LINE even_indexes = [ ] NEW_LINE for i in range ( len ( n ) ) : NEW_LINE INDENT if i % 2 == 0 : odd_indexes . append ( n [ i ] ) NEW_LINE else : even_indexes . append ( n [ i ] ) NEW_LINE DEDENT for i in sorted ( odd_indexes ) : print ( i , end = " β " ) NEW_LI... |
Number of pairs whose sum is a power of 2 | Function to return the count of valid pairs ; Storing occurrences of each element ; Sort the array in deceasing order ; Start taking largest element each time ; If element has already been paired ; Find the number which is greater than a [ i ] and power of two ; If there is a... | def countPairs ( a , n ) : NEW_LINE INDENT mp = dict . fromkeys ( a , 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ a [ i ] ] += 1 NEW_LINE DEDENT a . sort ( reverse = True ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( mp [ a [ i ] ] < 1 ) : NEW_LINE INDENT continue NEW_LINE DEDEN... |
Maximizing the elements with a [ i + 1 ] > a [ i ] | Returns the number of positions where A ( i + 1 ) is greater than A ( i ) after rearrangement of the array ; Creating a HashMap containing char as a key and occurrences as a value ; Find the maximum frequency ; Driver code | def countMaxPos ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE Map = { } NEW_LINE for x in arr : NEW_LINE INDENT if x in Map : NEW_LINE INDENT Map [ x ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Map [ x ] = 1 NEW_LINE DEDENT DEDENT max_freq = 0 NEW_LINE for entry in Map : NEW_LINE INDENT max_freq = max ( max_freq... |
Permutation of an array that has smaller values from another array | Function to print required permutation ; Storing elements and indexes ; Filling the answer array ; pair element of A and B ; Fill the remaining elements of answer ; Output required permutation ; Driver Code | def anyPermutation ( A , B , n ) : NEW_LINE INDENT Ap , Bp = [ ] , [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Ap . append ( [ A [ i ] , i ] ) NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT Bp . append ( [ B [ i ] , i ] ) NEW_LINE DEDENT Ap . sort ( ) NEW_LINE Bp . sort ( ) NEW_LINE i , j = 0 , ... |
Rearrange all elements of array which are multiples of x in increasing order | Function to sort all the multiples of x from the array in ascending order ; Insert all multiples of 5 to a vector ; Sort the vector ; update the array elements ; Driver code ; Print the result | def sortMultiples ( arr , n , x ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] % x == 0 ) : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( reverse = False ) NEW_LINE j = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i... |
Minimum increment in the sides required to get non | Function to return the minimum increase in side lengths of the triangle ; push the three sides to a array ; sort the array ; check if sum is greater than third side ; Driver code | def minimumIncrease ( a , b , c ) : NEW_LINE INDENT arr = [ a , b , c ] NEW_LINE arr . sort ( ) NEW_LINE if arr [ 0 ] + arr [ 1 ] >= arr [ 2 ] : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return arr [ 2 ] - ( arr [ 0 ] + arr [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE ... |
Minimum sum of differences with an element in an array | function to find min sum after operation ; Sort the array ; Pick middle value ; Sum of absolute differences . ; Driver Code | def absSumDidd ( a , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE midValue = a [ ( int ) ( n // 2 ) ] NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + abs ( a [ i ] - midValue ) NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 5 , 11 , 14 , 10 , 17 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE p... |
Printing frequency of each character just after its consecutive occurrences | Python 3 program to print run length encoding of a string ; Counting occurrences of s [ i ] ; Driver Code | def printRLE ( s ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < len ( s ) - 1 ) : NEW_LINE INDENT count = 1 NEW_LINE while s [ i ] == s [ i + 1 ] : NEW_LINE INDENT i += 1 NEW_LINE count += 1 NEW_LINE if i + 1 == len ( s ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( str ( s [ i ] ) + str ( count ) , end = " β... |
Word Ladder ( Length of shortest chain to reach a target word ) | Python3 program to find length of the shortest chain transformation from source to target ; Returns length of shortest chain to reach ' target ' from ' start ' using minimum number of adjacent moves . D is dictionary ; If the target is not present in the... | from collections import deque NEW_LINE def shortestChainLen ( start , target , D ) : NEW_LINE INDENT if start == target : NEW_LINE return 0 NEW_LINE if target not in D : NEW_LINE INDENT return 0 NEW_LINE DEDENT level , wordlength = 0 , len ( start ) NEW_LINE Q = deque ( ) NEW_LINE Q . append ( start ) NEW_LINE while ( ... |
Find if an array of strings can be chained to form a circle | Set 2 | Python3 code to check if cyclic order is possible among strings under given constrainsts ; Utility method for a depth first search among vertices ; Returns true if all vertices are strongly connected i . e . can be made as loop ; Initialize all verti... | M = 26 NEW_LINE def dfs ( g , u , visit ) : NEW_LINE INDENT visit [ u ] = True NEW_LINE for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT if ( not visit [ g [ u ] [ i ] ] ) : NEW_LINE INDENT dfs ( g , g [ u ] [ i ] , visit ) NEW_LINE DEDENT DEDENT DEDENT def isConnected ( g , mark , s ) : NEW_LINE INDENT visit = [ F... |
Dynamic Connectivity | Set 1 ( Incremental ) | Finding the root of node i ; union of two nodes a and b ; union based on rank ; Returns true if two nodes have same root ; Performing an operation according to query type ; type 1 query means checking if node x and y are connected or not ; If roots of x and y is same then ... | def root ( arr , i ) : NEW_LINE INDENT while ( arr [ i ] != i ) : NEW_LINE INDENT arr [ i ] = arr [ arr [ i ] ] NEW_LINE i = arr [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def weighted_union ( arr , rank , a , b ) : NEW_LINE INDENT root_a = root ( arr , a ) NEW_LINE root_b = root ( arr , b ) NEW_LINE if ( rank [ ro... |
Perfect Binary Tree Specific Level Order Traversal | A binary tree ndoe ; Given a perfect binary tree print its node in specific order ; Let us print root and next level first ; Since it is perfect Binary tree , one of the node is needed to be checked ; Do anythong more if there are nodes at next level in given perfect... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printSpecificLevelOrder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT print root . data , NEW_LINE if roo... |
Ford | Python program for implementation of Ford Fulkerson algorithm ; Returns true if there is a path from source ' s ' to sink ' t ' in residual graph . Also fills parent [ ] to store the path ; Mark all the vertices as not visited ; Create a queue for BFS ; Standard BFS Loop ; If we find a connection to the sink nod... | from collections import defaultdict NEW_LINE INDENT def BFS ( self , s , t , parent ) : NEW_LINE INDENT visited = [ False ] * ( self . ROW ) NEW_LINE queue = [ ] NEW_LINE queue . append ( s ) NEW_LINE visited [ s ] = True NEW_LINE while queue : NEW_LINE INDENT u = queue . pop ( 0 ) NEW_LINE for ind , val in enumerate (... |
Channel Assignment Problem | A Depth First Search based recursive function that returns true if a matching for vertex u is possible ; Try every receiver one by one ; If sender u has packets to send to receiver v and receiver v is not already mapped to any other sender just check if the number of packets is greater than... | def bpm ( table , u , seen , matchR ) : NEW_LINE INDENT global M , N NEW_LINE for v in range ( N ) : NEW_LINE INDENT if ( table [ u ] [ v ] > 0 and not seen [ v ] ) : NEW_LINE INDENT seen [ v ] = True NEW_LINE if ( matchR [ v ] < 0 or bpm ( table , matchR [ v ] , seen , matchR ) ) : NEW_LINE INDENT matchR [ v ] = u NEW... |
Prim 's algorithm using priority_queue in STL | If v is not in MST and weight of ( u , v ) is smaller than current key of v ; Updating key of v | if ( inMST [ v ] == False and key [ v ] > weight ) : NEW_LINE INDENT key [ v ] = weight NEW_LINE pq . append ( [ key [ v ] , v ] ) NEW_LINE parent [ v ] = u NEW_LINE DEDENT |
Graph implementation using STL for competitive programming | Set 2 ( Weighted graph ) | To add an edge ; Print adjacency list representaion ot graph ; Driver code | def addEdge ( adj , u , v , wt ) : NEW_LINE INDENT adj [ u ] . append ( [ v , wt ] ) NEW_LINE adj [ v ] . append ( [ u , wt ] ) NEW_LINE return adj NEW_LINE DEDENT def printGraph ( adj , V ) : NEW_LINE INDENT v , w = 0 , 0 NEW_LINE for u in range ( V ) : NEW_LINE INDENT print ( " Node " , u , " makes β an β edge β with... |
K Centers Problem | Set 1 ( Greedy Approximate Algorithm ) | Python3 program for the above approach ; index of city having the maximum distance to it 's closest center ; updating the distance of the cities to their closest centers ; updating the index of the city with the maximum distance to it 's closest center ; Pri... | def maxindex ( dist , n ) : NEW_LINE INDENT mi = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( dist [ i ] > dist [ mi ] ) : NEW_LINE INDENT mi = i NEW_LINE DEDENT DEDENT return mi NEW_LINE DEDENT def selectKcities ( n , weights , k ) : NEW_LINE INDENT dist = [ 0 ] * n NEW_LINE centers = [ ] NEW_LINE for i in r... |
Hierholzer 's Algorithm for directed graph | Python3 program to print Eulerian circuit in given directed graph using Hierholzer algorithm ; adj represents the adjacency list of the directed graph edge_count represents the number of edges emerging from a vertex ; find the count of edges to keep track of unused edges ; e... | def printCircuit ( adj ) : NEW_LINE INDENT edge_count = dict ( ) NEW_LINE for i in range ( len ( adj ) ) : NEW_LINE INDENT edge_count [ i ] = len ( adj [ i ] ) NEW_LINE DEDENT if len ( adj ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT curr_path = [ ] NEW_LINE circuit = [ ] NEW_LINE curr_path . append ( 0 ) NEW_LINE c... |
Perfect Binary Tree Specific Level Order Traversal | Set 2 | Linked List node ; Given a perfect binary tree , print its nodes in specific level order ; for level order traversal ; Stack to print reverse ; vector to store the level ; considering size of the level ; push data of the node of a particular level to vector ;... | 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 specific_level_order_traversal ( root ) : NEW_LINE INDENT q = [ ] NEW_LINE s = [ ] NEW_LINE q . append ( root ) NEW_LINE sz = 0 NEW_LINE whil... |
Number of Triangles in an Undirected Graph | Number of vertices in the graph ; Utility function for matrix multiplication ; Utility function to calculate trace of a matrix ( sum ofdiagnonal elements ) ; Utility function for calculating number of triangles in graph ; To Store graph ^ 2 ; To Store graph ^ 3 ; Initialisin... | V = 4 NEW_LINE def multiply ( A , B , C ) : NEW_LINE INDENT global V NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT C [ i ] [ j ] = 0 NEW_LINE for k in range ( V ) : NEW_LINE INDENT C [ i ] [ j ] += A [ i ] [ k ] * B [ k ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def getTrace (... |
Subsequence queries after removing substrings | arrays to store results of preprocessing ; function to preprocess the strings ; initialize it as 0. ; store subsequence count in forward direction ; store number of matches till now ; store subsequence count in backward direction ; store number of matches till now ; funct... | fwd = [ 0 ] * 100 NEW_LINE bwd = [ 0 ] * 100 NEW_LINE def preProcess ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE j = 0 NEW_LINE for i in range ( 1 , len ( a ) + 1 ) : NEW_LINE INDENT if j < len ( b ) and a [ i - 1 ] == b [ j ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT fwd [ i ] = j NEW_LINE DEDENT j = 0 NEW_LINE ... |
Count subsequence of length three in a given string | Function to find number of occurrences of a subsequence of length three in a string ; variable to store no of occurrences ; loop to find first character ; loop to find 2 nd character ; loop to find 3 rd character ; increment count if subsequence is found ; Driver Co... | def findOccurrences ( str , substr ) : NEW_LINE INDENT counter = 0 NEW_LINE for i in range ( 0 , len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == substr [ 0 ] ) : NEW_LINE INDENT for j in range ( i + 1 , len ( str ) ) : NEW_LINE INDENT if ( str [ j ] == substr [ 1 ] ) : NEW_LINE INDENT for k in range ( j + 1 , len ( s... |
Count subsequence of length three in a given string | Function to find number of occurrences of a subsequence of length three in a string ; calculate length of string ; auxiliary array to store occurrences of first character ; auxiliary array to store occurrences of third character ; calculate occurrences of first char... | def findOccurrences ( str1 , substr ) : NEW_LINE INDENT n = len ( str1 ) NEW_LINE preLeft = [ 0 for i in range ( n ) ] NEW_LINE preRight = [ 0 for i in range ( n ) ] NEW_LINE if ( str1 [ 0 ] == substr [ 0 ] ) : NEW_LINE INDENT preLeft [ 0 ] += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( str1 [ i ]... |
Mirror characters of a string | Function which take the given string and the position from which the reversing shall be done and returns the modified string ; Creating a string having reversed alphabetical order ; The string up to the point specified in the question , the string remains unchanged and from the point up ... | def compute ( st , n ) : NEW_LINE INDENT reverseAlphabet = " zyxwvutsrqponmlkjihgfedcba " NEW_LINE l = len ( st ) NEW_LINE answer = " " NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT answer = answer + st [ i ] ; NEW_LINE DEDENT for i in range ( n , l ) : NEW_LINE INDENT answer = ( answer + reverseAlphabet [ ord ( ... |
Lexicographically first alternate vowel and consonant string | Python3 implementation of lexicographically first alternate vowel and consonant string ; ' ch ' is vowel or not ; create alternate vowel and consonant string str1 [ 0. . . l1 - 1 ] and str2 [ start ... l2 - 1 ] ; first adding character of vowel / consonant ... | SIZE = 26 NEW_LINE def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def createAltStr ( str1 , str2 , start , l ) : NEW_LINE INDENT finalStr = " " NEW_LINE i = 0 NEW_LINE j = star... |
Print all possible strings that can be made by placing spaces | Python 3 program to print all strings that can be made by placing spaces ; Function to print all subsequences ; Driver code | from math import pow NEW_LINE def printSubsequences ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE opsize = int ( pow ( 2 , n - 1 ) ) NEW_LINE for counter in range ( opsize ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( str [ j ] , end = " " ) NEW_LINE if ( counter & ( 1 << j ) ) : NEW_LINE INDE... |
Find n | Python3 program to print n - th permutation ; Utility for calculating factorials ; Function for nth permutation ; length of given string ; Count frequencies of all characters ; out string for output string ; iterate till sum equals n ; We update both n and sum in this loop . ; check for characters present in f... | MAX_CHAR = 26 NEW_LINE MAX_FACT = 20 NEW_LINE fact = [ None ] * ( MAX_FACT ) NEW_LINE def precomputeFactorials ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , MAX_FACT ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT def nPermute ( string , n ) : NEW_LINE INDENT precomputeFa... |
Minimum number of deletions so that no two consecutive are same | Function for counting deletions ; If two consecutive characters are the same , delete one of them . ; Driver code ; Function call to print answer | def countDeletions ( string ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( string ) - 1 ) : NEW_LINE INDENT if ( string [ i ] == string [ i + 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT string = " AAABBB " NEW_LINE print countDeletions ( string ) NEW_LINE |
Count words that appear exactly two times in an array of words | Returns count of words with frequency exactly 2. ; Driver code | def countWords ( stri , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ stri [ i ] ] = m . get ( stri [ i ] , 0 ) + 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in m . values ( ) : NEW_LINE INDENT if i == 2 : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT s... |
Check whether a given graph is Bipartite or not | Python3 program to find out whether a given graph is Bipartite or not using recursion . ; color this pos as c and all its neighbours and 1 - c ; start is vertex 0 ; two colors 1 and 0 ; Driver Code | V = 4 NEW_LINE def colorGraph ( G , color , pos , c ) : NEW_LINE INDENT if color [ pos ] != - 1 and color [ pos ] != c : NEW_LINE INDENT return False NEW_LINE DEDENT color [ pos ] = c NEW_LINE ans = True NEW_LINE for i in range ( 0 , V ) : NEW_LINE INDENT if G [ pos ] [ i ] : NEW_LINE INDENT if color [ i ] == - 1 : NEW... |
Nth Even length Palindrome | Python3 program to find n = th even length string . ; Function to find nth even length Palindrome ; string r to store resultant palindrome . Initialize same as s ; In this loop string r stores reverse of string s after the string s in consecutive manner . ; Driver code ; Function call | import math as mt NEW_LINE def evenlength ( n ) : NEW_LINE INDENT res = n NEW_LINE for j in range ( len ( n ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT res += n [ j ] NEW_LINE DEDENT return res NEW_LINE DEDENT n = "10" NEW_LINE print ( evenlength ( n ) ) NEW_LINE |
Program for First Fit algorithm in Memory Management | Function to allocate memory to blocks as per First fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; Reduce available memory... | def firstFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT allocation [ i ] = j NEW_LINE blockSize [ j ] -= processSize [ i ] NEW_LINE break N... |
Determine if a string has all Unique Characters | Python program to illustrate string with unique characters using brute force technique ; If at any time we encounter 2 same characters , return false ; If no duplicate characters encountered , return true ; Driver Code | def uniqueCharacters ( str ) : NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT str = " GeeksforGeeks " ; NEW_LINE if ( uniq... |
Check if given string can be split into four distinct strings | Return if the given string can be split or not . ; We can always break a of size 10 or more into four distinct strings . ; Brute Force ; Making 4 from the given ; Checking if they are distinct or not . ; Driver Code | def check ( s ) : NEW_LINE INDENT if ( len ( s ) >= 10 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT for k in range ( j + 1 , len ( s ) ) : NEW_LINE INDENT s1 = s [ 0 : i ] NEW_LINE s2 = s [ i : j - i ] NEW_LINE ... |
Multiply Large Numbers represented as Strings | Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; G... | def multiply ( num1 , num2 ) : NEW_LINE INDENT len1 = len ( num1 ) NEW_LINE len2 = len ( num2 ) NEW_LINE if len1 == 0 or len2 == 0 : NEW_LINE INDENT return "0" NEW_LINE DEDENT result = [ 0 ] * ( len1 + len2 ) NEW_LINE i_n1 = 0 NEW_LINE i_n2 = 0 NEW_LINE for i in range ( len1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT carry = ... |
Find an equal point in a string of brackets | Method to find an equal index ; Store the number of opening brackets at each index ; Store the number of closing brackets at each index ; check if there is no opening or closing brackets ; check if there is any index at which both brackets are equal ; Driver Code | def findIndex ( str ) : NEW_LINE INDENT l = len ( str ) NEW_LINE open = [ 0 ] * ( l + 1 ) NEW_LINE close = [ 0 ] * ( l + 1 ) NEW_LINE index = - 1 NEW_LINE open [ 0 ] = 0 NEW_LINE close [ l ] = 0 NEW_LINE if ( str [ 0 ] == ' ( ' ) : NEW_LINE INDENT open [ 1 ] = 1 NEW_LINE DEDENT if ( str [ l - 1 ] == ' ) ' ) : NEW_LINE ... |
Convert decimal fraction to binary number | Function to convert decimal to binary upto k - precision after decimal point ; Fetch the integral part of decimal number ; Fetch the fractional part decimal number ; Conversion of integral part to binary equivalent ; Append 0 in binary ; Reverse string to get original binary ... | def decimalToBinary ( num , k_prec ) : NEW_LINE INDENT binary = " " NEW_LINE Integral = int ( num ) NEW_LINE fractional = num - Integral NEW_LINE while ( Integral ) : NEW_LINE INDENT rem = Integral % 2 NEW_LINE binary += str ( rem ) ; NEW_LINE Integral //= 2 NEW_LINE DEDENT binary = binary [ : : - 1 ] NEW_LINE binary +... |
Difference of two large numbers | Returns true if str1 is smaller than str2 , else false . ; Calculate lengths of both string ; Function for finding difference of larger numbers ; Before proceeding further , make sure str1 is not smaller ; Take an empty string for storing result ; Calculate lengths of both string ; Ini... | def isSmaller ( str1 , str2 ) : NEW_LINE INDENT n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE if ( n1 < n2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n2 < n1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( n1 ) : NEW_LINE INDENT if ( str1 [ i ] < str2 [ i ] ) : NEW_LINE INDENT return... |
Efficiently check if a string has all unique characters without using any additional data structure | Driver code | def unique ( s ) : NEW_LINE INDENT s = list ( s ) NEW_LINE s . sort ( ) NEW_LINE for i in range ( len ( s ) - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE break NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if ( unique ( " abcdd " ) == True ) : NEW_LINE INDENT print (... |
Check if two strings are k | Optimized Python3 program to check if two strings are k anagram or not . ; Function to check if str1 and str2 are k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Store the occurrence of all characters ... | MAX_CHAR = 26 ; NEW_LINE def areKAnagrams ( str1 , str2 , k ) : NEW_LINE INDENT n = len ( str1 ) ; NEW_LINE if ( len ( str2 ) != n ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT hash_str1 = [ 0 ] * ( MAX_CHAR ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash_str1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ;... |
Nth character in Concatenated Decimal String | Method to get dth digit of number N ; Method to return Nth character in concatenated decimal string ; sum will store character escaped till now ; dist will store numbers escaped till now ; loop for number lengths ; nine * len will be incremented characters and nine will be... | def getDigit ( N , d ) : NEW_LINE INDENT string = str ( N ) NEW_LINE return string [ d - 1 ] ; NEW_LINE DEDENT def getNthChar ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE nine = 9 NEW_LINE dist = 0 NEW_LINE for len in range ( 1 , N ) : NEW_LINE INDENT sum += nine * len NEW_LINE dist += nine NEW_LINE if ( sum >= N ) : NEW_L... |
Minimum characters to be added at front to make string palindrome | function for checking string is palindrome or not ; Driver code ; if string becomes palindrome then break ; erase the last element of the string ; print the number of insertion at front | def ispalindrome ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE i = 0 NEW_LINE j = l - 1 NEW_LINE while i <= j : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s... |
Count characters at same position as in English alphabet | Function to count the number of characters at same position as in English alphabets ; Traverse the input string ; Check that index of characters of string is same as of English alphabets by using ASCII values and the fact that all lower case alphabetic characte... | def findCount ( str ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( ( i == ord ( str [ i ] ) - ord ( ' a ' ) ) or ( i == ord ( str [ i ] ) - ord ( ' A ' ) ) ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT str = ' AbgdeF ' NEW_LINE print ... |
Remove a character from a string to make it a palindrome | Utility method to check if substring from low to high is palindrome or not . ; This method returns - 1 if it is not possible to make string a palindrome . It returns - 2 if string is already a palindrome . Otherwise it returns index of character whose removal c... | def isPalindrome ( string : str , low : int , high : int ) -> bool : NEW_LINE INDENT while low < high : NEW_LINE INDENT if string [ low ] != string [ high ] : NEW_LINE INDENT return False NEW_LINE DEDENT low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def possiblepalinByRemovingOneChar ( string ... |
Count number of unique ways to paint a N x 3 grid | Function to count the number of ways to paint N * 3 grid based on given conditions ; Count of ways to pain a row with same colored ends ; Count of ways to pain a row with different colored ends ; Traverse up to ( N - 1 ) th row ; For same colored ends ; For different ... | def waysToPaint ( n ) : NEW_LINE INDENT same = 6 NEW_LINE diff = 6 NEW_LINE for _ in range ( n - 1 ) : NEW_LINE INDENT sameTmp = 3 * same + 2 * diff NEW_LINE diffTmp = 2 * same + 2 * diff NEW_LINE same = sameTmp NEW_LINE diff = diffTmp NEW_LINE DEDENT print ( same + diff ) NEW_LINE DEDENT N = 2 NEW_LINE waysToPaint ( N... |
Generate all binary strings from given pattern | Recursive function to generate all binary strings formed by replacing each wildcard character by 0 or 1 ; replace ' ? ' by '0' and recurse ; replace ' ? ' by '1' and recurse ; NOTE : Need to backtrack as string is passed by reference to the function ; Driver code | def _print ( string , index ) : NEW_LINE INDENT if index == len ( string ) : NEW_LINE INDENT print ( ' ' . join ( string ) ) NEW_LINE return NEW_LINE DEDENT if string [ index ] == " ? " : NEW_LINE INDENT string [ index ] = '0' NEW_LINE _print ( string , index + 1 ) NEW_LINE string [ index ] = '1' NEW_LINE _print ( stri... |
Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace each even element by odd and vice - versa in a given array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ... | def replace ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ j ] >= 0 and arr [ i ] % 2 == 0 and arr [ j ] % 2 != 0 ) : NEW_LINE INDENT tmp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = tmp NEW_LINE arr [ ... |
Find the most frequent digit without using array / string | Simple function to count occurrences of digit d in x ; count = 0 ; Initialize count of digit d ; Increment count if current digit is same as d ; Returns the max occurring digit in x ; Handle negative number ; Traverse through all digits ; Count occurrences of ... | def countOccurrences ( x , d ) : NEW_LINE INDENT while ( x ) : NEW_LINE INDENT if ( x % 10 == d ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT x = int ( x / 10 ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def maxOccurring ( x ) : NEW_LINE INDENT if ( x < 0 ) : NEW_LINE INDENT x = - x ; NEW_LINE DEDENT for d in ... |
Remove recurring digits in a given number | Removes recurring digits in num [ ] ; Index in modified string ; Traverse digits of given number one by one ; Copy the first occurrence of new digit ; Remove repeating occurrences of digit ; Driver code | def removeRecurringDigits ( num ) : NEW_LINE INDENT l = len ( num ) NEW_LINE ( i , j ) = ( 0 , 0 ) NEW_LINE str = ' ' NEW_LINE while i < l : NEW_LINE INDENT str += num [ i ] NEW_LINE j += 1 NEW_LINE while ( i + 1 < l and num [ i ] == num [ i + 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return... |
Find the maximum subarray XOR in a given array | A simple Python program to find max subarray XOR ; Initialize result ; Pick starting points of subarrays ; to store xor of current subarray ; Pick ending points of subarrays starting with i ; Driver code | def maxSubarrayXOR ( arr , n ) : NEW_LINE INDENT ans = - 2147483648 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_xor = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT curr_xor = curr_xor ^ arr [ j ] NEW_LINE ans = max ( ans , curr_xor ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 8 , 1 , 2 ,... |
Recursive Implementation of atoi ( ) | Recursive function to compute atoi ( ) ; base case , we 've hit the end of the string, we just return the last value ; If more than 1 digits , recur for ( n - 1 ) , multiplu result with 10 and add last digit ; Driver Code | def myAtoiRecursive ( string , num ) : NEW_LINE INDENT if len ( string ) == 1 : NEW_LINE INDENT return int ( string ) + ( num * 10 ) NEW_LINE DEDENT num = int ( string [ 0 : 1 ] ) + ( num * 10 ) NEW_LINE return myAtoiRecursive ( string [ 1 : ] , num ) NEW_LINE DEDENT string = "112" NEW_LINE print ( myAtoiRecursive ( st... |
Print string of odd length in ' X ' format | Function to print the given string in respective pattern ; Print characters at corresponding places satisfying the two conditions ; Print blank space at rest of places ; Driver code | def printPattern ( Str , Len ) : NEW_LINE INDENT for i in range ( Len ) : NEW_LINE INDENT for j in range ( Len ) : NEW_LINE INDENT if ( ( i == j ) or ( i + j == Len - 1 ) ) : NEW_LINE INDENT print ( Str [ j ] , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT DEDENT print (... |
Find the longest substring with k unique characters in a given string | Python program to find the longest substring with k unique characters in a given string ; This function calculates number of unique characters using a associative array count [ ] . Returns true if no . of characters are less than required else retu... | MAX_CHARS = 26 NEW_LINE def isValid ( count , k ) : NEW_LINE INDENT val = 0 NEW_LINE for i in range ( MAX_CHARS ) : NEW_LINE INDENT if count [ i ] > 0 : NEW_LINE INDENT val += 1 NEW_LINE DEDENT DEDENT return ( k >= val ) NEW_LINE DEDENT def kUniques ( s , k ) : NEW_LINE INDENT count = [ 0 ] * MAX_CHARS NEW_LINE for i i... |
Check if characters of a given string can be rearranged to form a palindrome | Python3 implementation of above approach . ; bitvector to store the record of which character appear odd and even number of times ; Driver Code | def canFormPalindrome ( s ) : NEW_LINE INDENT bitvector = 0 NEW_LINE for str in s : NEW_LINE INDENT bitvector ^= 1 << ord ( str ) NEW_LINE DEDENT return bitvector == 0 or bitvector & ( bitvector - 1 ) == 0 NEW_LINE DEDENT if canFormPalindrome ( " geeksforgeeks " ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT els... |
Print all pairs of anagrams in a given array of strings | Python3 program to find best meeting point in 2D array ; function to check whether two strings are anagram of each other ; Create two count arrays and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count a... | NO_OF_CHARS = 256 NEW_LINE def areAnagram ( str1 : str , str2 : str ) -> bool : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) and i < len ( str2 ) : NEW_LINE INDENT count [ ord ( str1 [ i ] ) ] += 1 NEW_LINE count [ ord ( str2 [ i ] ) ] -= 1 NEW_LINE i += 1 NEW_LINE DEDENT i... |
Program to print all palindromes in a given range | A function to check if n is palindrome ; Find reverse of n ; If n and rev are same , then n is palindrome ; prints palindrome between min and max ; Driver Code | def isPalindrome ( n : int ) -> bool : NEW_LINE INDENT rev = 0 NEW_LINE i = n NEW_LINE while i > 0 : NEW_LINE INDENT rev = rev * 10 + i % 10 NEW_LINE i //= 10 NEW_LINE DEDENT return ( n == rev ) NEW_LINE DEDENT def countPal ( minn : int , maxx : int ) -> None : NEW_LINE INDENT for i in range ( minn , maxx + 1 ) : NEW_L... |
Length of the longest substring without repeating characters | Python3 program to find the length of the longest substring without repeating characters ; Result ; Note : Default values in visited are false ; If current character is visited Break the loop ; Else update the result if this window is larger , and mark curr... | def longestUniqueSubsttr ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT visited = [ 0 ] * 256 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT if ( visited [ ord ( str [ j ] ) ] == True ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT res = ... |
Length of the longest substring without repeating characters | Creating a set to store the last positions of occurrence ; starting the initial point of window to index 0 ; Checking if we have already seen the element or not ; If we have seen the number , move the start pointer to position after the last occurrence ; Up... | def longestUniqueSubsttr ( string ) : NEW_LINE INDENT seen = { } NEW_LINE maximum_length = 0 NEW_LINE start = 0 NEW_LINE for end in range ( len ( string ) ) : NEW_LINE INDENT if string [ end ] in seen : NEW_LINE INDENT start = max ( start , seen [ string [ end ] ] + 1 ) NEW_LINE DEDENT seen [ string [ end ] ] = end NEW... |
Find the smallest window in a string containing all characters of another string | Python solution ; Starting index of ans ; Answer Length of ans ; creating map ; References of Window ; Traversing the window ; Calculating ; Condition matching ; calculating answer . ; Sliding I Calculation for removing I ; Driver code | def smallestWindow ( s , p ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if n < len ( p ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mp = [ 0 ] * 256 NEW_LINE start = 0 NEW_LINE ans = n + 1 NEW_LINE cnt = 0 NEW_LINE for i in p : NEW_LINE INDENT mp [ ord ( i ) ] += 1 NEW_LINE if mp [ ord ( i ) ] == 1 : NEW_LINE INDENT cn... |
Run Length Encoding | Python3 program to implement run length encoding ; Count occurrences of current character ; Print character and its count ; Driver code | def printRLE ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE i = 0 NEW_LINE while i < n - 1 : NEW_LINE INDENT count = 1 NEW_LINE while ( i < n - 1 and st [ i ] == st [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE print ( st [ i - 1 ] + str ( count ) , end = " " ) NEW_LINE DEDE... |
Print list items containing all characters of a given word | Python program to print the list items containing all characters of a given word ; Prints list items having all characters of word ; Set the values in map ; Get the length of given word ; Check each item of list if has all characters of words ; unset the bit ... | NO_OF_CHARS = 256 NEW_LINE def printList ( list , word , list_size ) : NEW_LINE INDENT map = [ 0 ] * NO_OF_CHARS NEW_LINE for i in word : NEW_LINE INDENT map [ ord ( i ) ] = 1 NEW_LINE DEDENT word_size = len ( word ) NEW_LINE for i in list : NEW_LINE INDENT count = 0 NEW_LINE for j in i : NEW_LINE INDENT if map [ ord (... |
Given a string , find its first non | Python program to print the first non - repeating character ; Returns an array of size 256 containing count of characters in the passed char array ; The function returns index of first non - repeating character in a string . If all characters are repeating then returns - 1 ; Driver... | NO_OF_CHARS = 256 NEW_LINE def getCharCountArray ( string ) : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE for i in string : NEW_LINE INDENT count [ ord ( i ) ] += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def firstNonRepeating ( string ) : NEW_LINE INDENT count = getCharCountArray ( string ) NEW_LINE inde... |
Divide a string in N equal parts | Function to print n equal parts of string ; Check if string can be divided in n equal parts ; Calculate the size of parts to find the division points ; Driver program to test the above function Length of string is 28 ; ; Print 4 equal parts of the string | def divideString ( string , n ) : NEW_LINE INDENT str_size = len ( string ) NEW_LINE if str_size % n != 0 : NEW_LINE INDENT print " Invalid β Input : β String β size β is β not β divisible β by β n " NEW_LINE return NEW_LINE DEDENT part_size = str_size / n NEW_LINE k = 0 NEW_LINE for i in string : NEW_LINE INDENT if k ... |
Print all paths from a source point to all the 4 corners of a Matrix | Function to check if we reached on of the entry / exit ( corner ) point . ; Function to check if the index is within the matrix boundary . ; Recursive helper function ; If any corner is reached push the string t into ans and return ; For all the fou... | def isCorner ( i , j , M , N ) : NEW_LINE INDENT if ( ( i == 0 and j == 0 ) or ( i == 0 and j == N - 1 ) or ( i == M - 1 and j == N - 1 ) or ( i == M - 1 and j == 0 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isValid ( i , j , M , N ) : NEW_LINE INDENT if ( i < 0 or i >= M or j < ... |
Remove all subtrees consisting only of even valued nodes from a Binary Tree | Node of the tree ; Function to print tree level wise ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root ; Print front of queue and remove it from queue ; If left child is present ; Otherwise ; If right child is prese... | 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 printLevelOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) ... |
Count total ways to reach destination from source in an undirected Graph | Utility Function to count total ways ; Base condition When reach to the destination ; Make vertex visited ; Recursive function , for count ways ; Backtracking Make vertex unvisited ; Return total ways ; Function to count total ways to reach dest... | def countWays ( mtrx , vrtx , i , dest , visited ) : NEW_LINE INDENT if ( i == dest ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT total = 0 NEW_LINE for j in range ( vrtx ) : NEW_LINE INDENT if ( mtrx [ i ] [ j ] == 1 and not visited [ j ] ) : NEW_LINE INDENT visited [ j ] = True ; NEW_LINE total += countWays ( mtrx , v... |
Print path from given Source to Destination in 2 | Function to print the path ; Base condition ; Pop stores elements ; Recursive call for printing stack In reverse order ; Function to store the path into The stack , if path exist ; Base condition ; Push current elements ; Condition to check whether reach to the Destina... | def printExistPath ( sx , sy , last ) : NEW_LINE INDENT if ( len ( sx ) == 0 or len ( sy ) == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT x = sx [ - 1 ] ; NEW_LINE y = sy [ - 1 ] NEW_LINE sx . pop ( ) ; NEW_LINE sy . pop ( ) ; NEW_LINE printExistPath ( sx , sy , last ) ; NEW_LINE if ( len ( sx ) == last - 1 ) : NEW_LI... |
Count even paths in Binary Tree | A Tree node ; Utility function to count the even path in a given Binary tree ; Base Condition , when node pointer becomes null or node value is odd ; Increment count when encounter leaf node with all node value even ; Left recursive call , and save the value of count ; Right recursive ... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def evenPaths ( node , count ) : NEW_LINE INDENT if ( node == None or ( node . key % 2 != 0 ) ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( not ... |
Sum of subsets of all the subsets of an array | O ( 3 ^ N ) | ; Function to sum of all subsets of a given array ; Base case ; Recursively calling subsetSum ; Function to generate the subsets ; Base - case ; Finding the sum of all the subsets of the generated subset ; Recursively accepting and rejecting the current num... | / * To store the final ans * / NEW_LINE c = [ ] NEW_LINE ans = 0 NEW_LINE def subsetSum ( i , curr ) : NEW_LINE INDENT global ans , c NEW_LINE if ( i == len ( c ) ) : NEW_LINE INDENT ans += curr NEW_LINE return NEW_LINE DEDENT subsetSum ( i + 1 , curr + c [ i ] ) NEW_LINE subsetSum ( i + 1 , curr ) NEW_LINE DEDENT def ... |
Print the DFS traversal step | Python3 program to print the complete DFS - traversal of graph using back - tracking ; Function to print the complete DFS - traversal ; Check if all th node is visited or not and count unvisited nodes ; If all the node is visited return ; Mark not visited node as visited ; Track the curre... | N = 1000 NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE def dfsUtil ( u , node , visited , road_used , parent , it ) : NEW_LINE INDENT c = 0 NEW_LINE for i in range ( node ) : NEW_LINE INDENT if ( visited [ i ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c == node ) : NEW_LINE INDENT return NEW_LINE DE... |
Find Maximum number possible by doing at | Python3 program to find maximum integer possible by doing at - most K swap operations on its digits . ; function to find maximum integer possible by doing at - most K swap operations on its digits ; return if no swaps left ; consider every digit ; and compare it with all digit... | def swap ( string , i , j ) : NEW_LINE INDENT return ( string [ : i ] + string [ j ] + string [ i + 1 : j ] + string [ i ] + string [ j + 1 : ] ) NEW_LINE DEDENT def findMaximumNum ( string , k , maxm ) : NEW_LINE INDENT if k == 0 : NEW_LINE INDENT return NEW_LINE DEDENT n = len ( string ) NEW_LINE for i in range ( n -... |
Print all possible paths from top left to bottom right of a mXn matrix | Python3 program to Print all possible paths from top left to bottom right of a mXn matrix ; if we reach the bottom of maze , we can only move right ; path . append ( maze [ i ] [ k ] ) ; if we hit this block , it means one path is completed . Add ... | allPaths = [ ] NEW_LINE def findPaths ( maze , m , n ) : NEW_LINE INDENT path = [ 0 for d in range ( m + n - 1 ) ] NEW_LINE findPathsUtil ( maze , m , n , 0 , 0 , path , 0 ) NEW_LINE DEDENT def findPathsUtil ( maze , m , n , i , j , path , indx ) : NEW_LINE INDENT global allPaths NEW_LINE if i == m - 1 : NEW_LINE INDEN... |
Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Function to find and print pair ; Driver code | def chkPair ( A , size , x ) : NEW_LINE INDENT for i in range ( 0 , size - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , size ) : NEW_LINE INDENT if ( A [ i ] + A [ j ] == x ) : NEW_LINE INDENT print ( " Pair β with β a β given β sum β " , x , " β is β ( " , A [ i ] , " , β " , A [ j ] , " ) " ) NEW_LINE return True N... |
Significant Inversions in an Array | Function that sorts the input array and returns the number of inversions in the array ; Recursive function that sorts the input array and returns the number of inversions in the array ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Invers... | def mergeSort ( arr , array_size ) : NEW_LINE INDENT temp = [ 0 for i in range ( array_size ) ] NEW_LINE return _mergeSort ( arr , temp , 0 , array_size - 1 ) NEW_LINE DEDENT def _mergeSort ( arr , temp , left , right ) : NEW_LINE INDENT mid , inv_count = 0 , 0 NEW_LINE if ( right > left ) : NEW_LINE INDENT mid = ( rig... |
Find the number of different numbers in the array after applying the given operation q times | Python3 implementation for above approach ; To store the tree in lazy propagation ; To store the different numbers ; Function to update in the range [ x , y ) with given value ; check out of bound ; check for complete overlap... | N = 100005 NEW_LINE lazy = [ 0 ] * ( 4 * N ) ; NEW_LINE se = set ( ) NEW_LINE def update ( x , y , value , id , l , r ) : NEW_LINE INDENT if ( x >= r or l >= y ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( x <= l and r <= y ) : NEW_LINE INDENT lazy [ id ] = value ; NEW_LINE return ; NEW_LINE DEDENT mid = ( l + r ) ... |
Find Nth term ( A matrix exponentiation example ) | Python3 program to find n - th term of a recursive function using matrix exponentiation . ; This power function returns first row of { Transformation Matrix } ^ n - 1 * Initial Vector ; This is an identity matrix . ; this is Transformation matrix . ; Matrix exponentia... | MOD = 1000000009 ; NEW_LINE def power ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT n -= 1 ; NEW_LINE res = [ [ 1 , 0 ] , [ 0 , 1 ] ] ; NEW_LINE tMat = [ [ 2 , 3 ] , [ 1 , 0 ] ] ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT tmp = [ [ 0 for x in range ( 2 ) ... |
Shuffle 2 n integers in format { a1 , b1 , a2 , b2 , a3 , b3 , ... ... , an , bn } without using extra space | Function to shuffle an array of size 2 n ; Rotate the element to the left ; swap a [ j - 1 ] , a [ j ] ; Driver Code | def shuffleArray ( a , n ) : NEW_LINE INDENT i , q , k = 0 , 1 , n NEW_LINE while ( i < n ) : NEW_LINE INDENT j = k NEW_LINE while ( j > i + q ) : NEW_LINE INDENT a [ j - 1 ] , a [ j ] = a [ j ] , a [ j - 1 ] NEW_LINE j -= 1 NEW_LINE DEDENT i += 1 NEW_LINE k += 1 NEW_LINE q += 1 NEW_LINE DEDENT DEDENT a = [ 1 , 3 , 5 ,... |
Place k elements such that minimum distance is maximized | Returns true if it is possible to arrange k elements of arr [ 0. . n - 1 ] with minimum distance given as mid . ; Place first element at arr [ 0 ] position ; Initialize count of elements placed . ; Try placing k elements with minimum distance mid . ; Place next... | def isFeasible ( mid , arr , n , k ) : NEW_LINE INDENT pos = arr [ 0 ] NEW_LINE elements = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] - pos >= mid ) : NEW_LINE INDENT pos = arr [ i ] NEW_LINE elements += 1 NEW_LINE if ( elements == k ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT D... |
Find frequency of each element in a limited range array in less than O ( n ) time | It prints number of occurrences of each element in the array . ; HashMap to store frequencies ; traverse the array ; update the frequency ; traverse the hashmap ; Driver function | def findFrequency ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in mp : NEW_LINE INDENT mp [ arr [ i ] ] = 0 NEW_LINE DEDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in mp : NEW_LINE INDENT print ( " Element " , i , " occurs " , mp [ i ] , " times " ) NEW_LIN... |
Square root of an integer | Returns floor of square root of x ; Base cases ; Do Binary Search for floor ( sqrt ( x ) ) ; If x is a perfect square ; Since we need floor , we update answer when mid * mid is smaller than x , and move closer to sqrt ( x ) ; If mid * mid is greater than x ; driver code | def floorSqrt ( x ) : NEW_LINE INDENT if ( x == 0 or x == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT start = 1 NEW_LINE end = x NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( mid * mid == x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( mid * mid < x ) : NEW_LINE IND... |
Sine Rule with Derivation , Example and Implementation | Python3 program for the above approach ; Function to calculate remaining two sides ; Calculate angle B ; Convert angles to their respective radians for using trigonometric functions ; Sine rule ; Print the answer ; Input ; Function Call | import math NEW_LINE def findSides ( A , C , c ) : NEW_LINE INDENT B = 180 - ( A + C ) NEW_LINE A = A * ( 3.14159 / 180 ) NEW_LINE C = C * ( 3.14159 / 180 ) NEW_LINE B = B * ( 3.14159 / 180 ) NEW_LINE a = ( c / math . sin ( C ) ) * math . sin ( A ) NEW_LINE b = ( c / math . sin ( C ) ) * math . sin ( B ) NEW_LINE print... |
Reverse alternate levels of a perfect binary tree | Python3 program to reverse alternate levels of a binary tree ; A Binary Tree node ; A utility function to create a new Binary Tree Node ; Function to store nodes of alternate levels in an array ; Base case ; Store elements of left subtree ; Store this node only if thi... | MAX = 100 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def newNode ( item ) : NEW_LINE INDENT temp = Node ( item ) NEW_LINE return temp NEW_LINE DEDENT def storeAlternate ( root , a... |
Equation of a straight line passing through a point and making a given angle with a given line | Python3 program for the above approach ; Function to find slope of given line ; Special case when slope of line is infinity or is perpendicular to x - axis ; Function to find equations of lines passing through the given poi... | import math NEW_LINE def line_slope ( a , b ) : NEW_LINE INDENT if ( a != 0 ) : NEW_LINE INDENT return - b / a NEW_LINE DEDENT else : NEW_LINE INDENT return ( - 2 ) NEW_LINE DEDENT DEDENT def line_equation ( a , b , c , x1 , y1 , alfa ) : NEW_LINE INDENT given_slope = line_slope ( a , b ) NEW_LINE x = alfa * 3.14159 / ... |
Equation of a normal to a Circle from a given point | Function to calculate the slope ; Store the coordinates the center of the circle ; If slope becomes infinity ; Stores the slope ; If slope is zero ; Return the result ; Function to find the equation of the normal to a circle from a given point ; Stores the slope of ... | def normal_slope ( a , b , x1 , y1 ) : NEW_LINE INDENT g = a / 2 NEW_LINE f = b / 2 NEW_LINE if ( g - x1 == 0 ) : NEW_LINE INDENT return ( - 1 ) NEW_LINE DEDENT slope = ( f - y1 ) / ( g - x1 ) NEW_LINE if ( slope == 0 ) : NEW_LINE INDENT return ( - 2 ) NEW_LINE DEDENT return slope NEW_LINE DEDENT def normal_equation ( ... |
Sum of squares of distances between all pairs from given points | Function to find the sum of squares of distance between all distinct pairs ; Stores final answer ; Traverse the array ; Adding the effect of this point for all the previous x - points ; Temporarily add the square of x - coordinate ; Add the effect of thi... | def findSquareSum ( Coordinates , N ) : NEW_LINE INDENT xq , yq = 0 , 0 NEW_LINE xs , ys = 0 , 0 NEW_LINE res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a = Coordinates [ i ] [ 0 ] NEW_LINE b = Coordinates [ i ] [ 1 ] NEW_LINE res += xq NEW_LINE res -= 2 * xs * a NEW_LINE res += i * ( a * a ) NEW_LINE xq += a ... |
Count points from an array that lies inside a semi | Python implementation of above approach ; Traverse the array ; Stores if a point lies above the diameter or not ; Stores if the R is less than or equal to the distance between center and point ; Driver Code | def getPointsIns ( x1 , y1 , radius , x2 , y2 , points ) : NEW_LINE INDENT for point in points : NEW_LINE INDENT condOne = ( point [ 1 ] - y2 ) * ( x2 - x1 ) - ( y2 - y1 ) * ( point [ 0 ] - x2 ) >= 0 NEW_LINE condTwo = radius >= ( ( y1 - point [ 1 ] ) ** 2 + ( x1 - point [ 0 ] ) ** 2 ) ** ( 0.5 ) NEW_LINE if condOne an... |
Count pairs of points having distance between them equal to integral values in a K | Function to find pairs whose distance between the points of is an integer value . ; Stores count of pairs whose distance between points is an integer ; Traverse the array , points [ ] ; Stores distance between points ( i , j ) ; Traver... | def cntPairs ( points , n , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT dist = 0 NEW_LINE for k in range ( K ) : NEW_LINE INDENT temp = ( points [ i ] [ k ] - points [ j ] [ k ] ) NEW_LINE dist += temp * temp NEW_LINE DEDENT if ( ( ( d... |
Circumradius of a Cyclic Quadrilateral using the length of Sides | Program to find Circumradius of a cyclic quadrilateral using sides ; Function to return the Circumradius of a cyclic quadrilateral using sides ; Find semiperimeter ; Calculate the radius ; Driver Code ; Function Call ; Print the radius | import math NEW_LINE def Circumradius ( a , b , c , d ) : NEW_LINE INDENT s = ( a + b + c + d ) / 2 NEW_LINE radius = ( 1 / 4 ) * math . sqrt ( ( ( a * b ) + ( c * d ) ) * ( ( a * c ) + ( b * d ) ) * ( ( a * d ) + ( b * c ) ) / ( ( s - a ) * ( s - b ) * ( s - c ) * ( s - d ) ) ) NEW_LINE return radius NEW_LINE DEDENT A... |
Area of Triangle using Side | Python3 program to calculate the area of a triangle when the length of two adjacent sides and the angle between them is provided ; Function to return the area of triangle using Side - Angle - Side formula ; Driver Code ; Function Call ; Print the final answer | import math NEW_LINE def Area_of_Triangle ( a , b , k ) : NEW_LINE INDENT area = ( 1 / 2 ) * a * b * math . sin ( k ) NEW_LINE return area NEW_LINE DEDENT a = 9 NEW_LINE b = 12 NEW_LINE k = 2 NEW_LINE ans = Area_of_Triangle ( a , b , k ) NEW_LINE print ( round ( ans , 2 ) ) NEW_LINE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.