text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Maximize sum of product of neighbouring elements of the element removed from Array | Function to calculate maximum possible score using the given operations ; Iterate through all possible len1gths of the subarray ; Iterate through all the possible starting indices i having len1gth len1 ; Stores the rightmost index of the current subarray ; Initial dp [ i ] [ j ] will be 0. ; Iterate through all possible values of k in range [ i + 1 , j - 1 ] ; Return the answer ; Driver Code ; Function Call ; Function Call
def maxMergingScore ( A , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 101 ) ] for j in range ( 101 ) ] NEW_LINE for len1 in range ( 1 , N , 1 ) : NEW_LINE INDENT for i in range ( 0 , N - len1 , 1 ) : NEW_LINE INDENT j = i + len1 NEW_LINE dp [ i ] [ j ] = 0 NEW_LINE for k in range ( i + 1 , j , 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k ] [ j ] + A [ i ] * A [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ 0 ] [ N - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE A = [ 1 , 2 , 3 , 4 ] NEW_LINE print ( maxMergingScore ( A , N ) ) NEW_LINE N = 2 NEW_LINE B = [ 1 , 55 ] NEW_LINE print ( maxMergingScore ( B , N ) ) NEW_LINE DEDENT
Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp Initializing dp with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp with ( previous dp value ) + 1 ; Storing max element so far to ans ; Returning the final answer ; Input ; Function call
def LongestOddEvenSubarray ( A , N ) : NEW_LINE INDENT dp = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 0 and A [ i - 1 ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ i - 1 ] % 2 != 0 ) ) : NEW_LINE INDENT dp = dp + 1 NEW_LINE ans = max ( ans , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT dp = 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( LongestOddEvenSubarray ( A , N ) ) NEW_LINE
Count of N | python program for the above approach ; Function to find number of ' N ' digit numbers such that the element is mean of sum of its adjacent digits ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If current position is 1 , then any digit from [ 1 - 9 ] can be placed . If n = 1 , 0 can be also placed . ; If current position is 2 , then any digit from [ 1 - 9 ] can be placed . ; previous digit selected is the mean . ; mean = ( current + prev2 ) / 2 current = ( 2 * mean ) - prev2 ; Check if current and current + 1 can be valid placements ; return answer ; Given Input ; Function call
dp = [ [ [ - 1 for i in range ( 10 ) ] for col in range ( 20 ) ] for row in range ( 100 ) ] NEW_LINE def countOfNumbers ( digit , prev1 , prev2 , n ) : NEW_LINE INDENT if ( digit == n + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ digit ] [ prev1 ] [ prev2 ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 0 NEW_LINE if ( digit == 1 ) : NEW_LINE INDENT start = 1 NEW_LINE if ( n == 1 ) : NEW_LINE INDENT start = 0 NEW_LINE DEDENT for i in range ( start , 10 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , i , prev1 , n ) NEW_LINE DEDENT DEDENT elif ( digit == 2 ) : NEW_LINE INDENT for i in range ( 0 , 10 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , i , prev1 , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT mean = prev1 NEW_LINE current = ( 2 * mean ) - prev2 NEW_LINE if ( current >= 0 and current <= 9 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , current , prev1 , n ) NEW_LINE DEDENT if ( ( current + 1 ) >= 0 and ( current + 1 ) <= 9 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , current + 1 , prev1 , n ) NEW_LINE DEDENT DEDENT return val NEW_LINE DEDENT n = 2 NEW_LINE print ( countOfNumbers ( 1 , 0 , 0 , n ) ) NEW_LINE
Count half nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Iterative Method to count half nodes of binary tree ; Base Case ; Create an empty queue for level order traversal ; initialize count for half nodes ; Enqueue left child ; Enqueue right child ; Driver Program to test above function
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 gethalfCount ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT queue = [ ] NEW_LINE queue . append ( root ) NEW_LINE count = 0 NEW_LINE while ( len ( queue ) > 0 ) : NEW_LINE INDENT node = queue . pop ( 0 ) NEW_LINE if node . left is not None and node . right is None or node . left is None and node . right is not None : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT if node . left is not None : NEW_LINE INDENT queue . append ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT queue . append ( node . right ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT root = Node ( 2 ) NEW_LINE root . left = Node ( 7 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . left . right . left = Node ( 1 ) NEW_LINE root . left . right . right = Node ( 11 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE root . right . right . left = Node ( 4 ) NEW_LINE print " % d " % ( gethalfCount ( root ) ) NEW_LINE
Count N | Python3 program for the above approach ; Function to count N digit numbers whose digits are less than or equal to the absolute difference of previous two digits ; If all digits are traversed ; If the state has already been computed ; If the current digit is 1 , any digit from [ 1 - 9 ] can be placed . If N == 1 , 0 can also be placed . ; If the current digit is 2 , any digit from [ 0 - 9 ] can be placed ; For other digits , any digit from 0 to abs ( prev1 - prev2 ) can be placed ; Return the answer ; Driver code ; Input ; Function call
dp = [ [ [ - 1 for i in range ( 10 ) ] for j in range ( 10 ) ] for k in range ( 50 ) ] NEW_LINE def countOfNumbers ( digit , prev1 , prev2 , N ) : NEW_LINE INDENT if ( digit == N + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ digit ] [ prev1 ] [ prev2 ] != - 1 ) : NEW_LINE INDENT return dp [ digit ] [ prev1 ] [ prev2 ] NEW_LINE DEDENT dp [ digit ] [ prev1 ] [ prev2 ] = 0 NEW_LINE if ( digit == 1 ) : NEW_LINE INDENT term = 0 if N == 1 else 1 NEW_LINE for j in range ( term , 10 , 1 ) : NEW_LINE INDENT dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) NEW_LINE DEDENT DEDENT elif ( digit == 2 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for j in range ( abs ( prev1 - prev2 ) + 1 ) : NEW_LINE INDENT dp [ digit ] [ prev1 ] [ prev2 ] += countOfNumbers ( digit + 1 , j , prev1 , N ) NEW_LINE DEDENT DEDENT return dp [ digit ] [ prev1 ] [ prev2 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( countOfNumbers ( 1 , 0 , 0 , N ) ) NEW_LINE DEDENT
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 colored ends ; Print the total number of ways ; Driver Code ; Function call
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 ) NEW_LINE
Maximize sum by selecting X different | Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; Selecting i - th element from A [ ] ; Selecting i - th element from B [ ] ; Selecting i - th element from C [ ] ; i - th elements not selected from any of the arrays ; Select the maximum sum from all the possible calls ; Driver Code ; Given X , Y and Z ; Given A [ ] ; Given B [ ] ; Given C [ ] ; Given Size ; Function Call
def FindMaxS ( X , Y , Z , n ) : NEW_LINE INDENT global A , B , C NEW_LINE if ( X < 0 or Y < 0 or Z < 0 ) : NEW_LINE INDENT return - 10 ** 9 NEW_LINE DEDENT if ( n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ch = A [ n ] + FindMaxS ( X - 1 , Y , Z , n - 1 ) NEW_LINE ca = B [ n ] + FindMaxS ( X , Y - 1 , Z , n - 1 ) NEW_LINE co = C [ n ] + FindMaxS ( X , Y , Z - 1 , n - 1 ) NEW_LINE no = FindMaxS ( X , Y , Z , n - 1 ) NEW_LINE maximum = max ( ch , max ( ca , max ( co , no ) ) ) NEW_LINE return maximum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 1 NEW_LINE Y = 1 NEW_LINE Z = 1 NEW_LINE A = [ 10 , 0 , 5 ] NEW_LINE B = [ 5 , 10 , 0 ] NEW_LINE C = [ 0 , 5 , 10 ] NEW_LINE n = len ( B ) NEW_LINE print ( FindMaxS ( X , Y , Z , n - 1 ) ) NEW_LINE DEDENT
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 ; Perform Swap ; Change the sign ; Marked element positive ; Print final array ; Driver Code ; Given array arr [ ] ; Function Call
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 [ j ] = - arr [ j ] NEW_LINE break NEW_LINE DEDENT elif ( 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 [ j ] = - arr [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = abs ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE replace ( arr , n ) NEW_LINE DEDENT
Count half nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Function to get the count of half Nodes in a binary tree ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example
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 gethalfCount ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE if ( root . left == None and root . right != None ) or ( root . left != None and root . right == None ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT res += ( gethalfCount ( root . left ) + gethalfCount ( root . right ) ) NEW_LINE return res NEW_LINE DEDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . right . right . left = newNode ( 4 ) NEW_LINE print ( gethalfCount ( root ) ) NEW_LINE
Minimize cost to reduce array to a single element by replacing K consecutive elements by their sum | Function to find the minimum cost to reduce given array to a single element by replacing consecutive K array elements ; Stores length of arr ; If ( N - 1 ) is not multiple of ( K - 1 ) ; Store prefix sum of the array ; Iterate over the range [ 1 , N ] ; Update prefixSum [ i ] ; dp [ i ] [ j ] : Store minimum cost to merge array elements interval [ i , j ] ; L : Stores length of interval [ i , j ] ; Iterate over each interval [ i , j ] of length L in in [ 0 , N ] ; Stores index of last element of the interval [ i , j ] ; If L is greater than K ; Update dp [ i ] [ j ] ; If ( L - 1 ) is multiple of ( K - 1 ) ; Update dp [ i ] [ j ] ; Return dp [ 0 ] [ N - 1 ] ; Driver Code ; Function Call
def minimumCostToMergeK ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE if ( N - 1 ) % ( K - 1 ) != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT prefixSum = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT prefixSum [ i ] = ( prefixSum [ i - 1 ] + arr [ i - 1 ] ) NEW_LINE DEDENT dp = [ [ 0 ] * N for _ in range ( N ) ] NEW_LINE for L in range ( K , N + 1 ) : NEW_LINE INDENT for i in range ( N - L + 1 ) : NEW_LINE INDENT j = i + L - 1 NEW_LINE if L > K : NEW_LINE INDENT dp [ i ] [ j ] = ( min ( [ dp [ i ] [ x ] + dp [ x + 1 ] [ j ] for x in range ( i , j , K - 1 ) ] ) ) NEW_LINE DEDENT if ( L - 1 ) % ( K - 1 ) == 0 : NEW_LINE INDENT dp [ i ] [ j ] += ( prefixSum [ j + 1 ] - prefixSum [ i ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ 0 ] [ N - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 5 , 1 , 2 , 6 ] NEW_LINE K = 3 NEW_LINE DEDENT print ( minimumCostToMergeK ( arr , K ) ) NEW_LINE
Check if end of a sorted Array can be reached by repeated jumps of one more , one less or same number of indices as previous jump | Python3 program for the above approach ; Utility function to check if it is possible to move from index 1 to N - 1 ; Successfully reached end index ; memo [ i ] [ j ] is already calculated ; Check if there is any index having value of A [ i ] + j - 1 , A [ i ] + j or A [ i ] + j + 1 ; If A [ k ] > A [ i ] + j + 1 , can 't make a move further ; It 's possible to move A[k] ; Check is it possible to move from index k having previously taken A [ k ] - A [ i ] steps ; If yes then break the loop ; Store value of flag in memo ; Return memo [ i ] [ j ] ; Function to check if it is possible to move from index 1 to N - 1 ; Stores the memoized state ; Initialize all values as - 1 ; Initially , starting index = 1 ; Function call ; Driver Code ; Function Call
N = 8 NEW_LINE def check ( memo , i , j , A ) : NEW_LINE INDENT if ( i == N - 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( memo [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return memo [ i ] [ j ] NEW_LINE DEDENT flag = 0 NEW_LINE for k in range ( i + 1 , N ) : NEW_LINE INDENT if ( A [ k ] - A [ i ] > j + 1 ) : NEW_LINE break NEW_LINE if ( A [ k ] - A [ i ] >= j - 1 and A [ k ] - A [ i ] <= j + 1 ) : NEW_LINE flag = check ( memo , k , A [ k ] - A [ i ] , A ) NEW_LINE if ( flag != 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT memo [ i ] [ j ] = flag NEW_LINE return memo [ i ] [ j ] NEW_LINE DEDENT def checkEndReach ( A , K ) : NEW_LINE INDENT memo = [ [ 0 ] * N ] * N NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE memo [ i ] [ j ] = - 1 NEW_LINE DEDENT startIndex = 1 NEW_LINE if ( check ( memo , startIndex , K , A ) != 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 0 , 1 , 3 , 5 , 6 , 8 , 12 , 17 ] NEW_LINE K = 1 NEW_LINE checkEndReach ( A , K ) NEW_LINE DEDENT
Maximum subsequence sum such that no K elements are consecutive | Function to find the maximum sum of a subsequence consisting of no K consecutive array elements ; Stores states of dp ; Stores the prefix sum ; Update the prefix sum ; Base case for i < K ; For indices less than k take all the elements ; For i >= K case ; Skip each element from i to ( i - K + 1 ) to ensure that no K elements are consecutive ; Update the current dp state ; dp [ N ] stores the maximum sum ; Driver Code ; Given array arr [ ] ; Function call
def Max_Sum ( arr , K , N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE prefix = [ None ] * ( N + 1 ) NEW_LINE prefix [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , K ) : NEW_LINE INDENT dp [ i ] = prefix [ i ] NEW_LINE DEDENT for i in range ( K , N + 1 ) : NEW_LINE INDENT for j in range ( i , i - K , - 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ j - 1 ] + prefix [ i ] - prefix [ j ] ) NEW_LINE DEDENT DEDENT return dp [ N ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 12 , 22 , 18 , 34 , 12 , 25 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE print ( Max_Sum ( arr , K , N ) ) NEW_LINE DEDENT
Count possible splits of sum N into K integers such that the minimum is at least P | Function that finds the value of the Binomial Coefficient C ( n , k ) ; Stores the value of Binomial Coefficient in bottom up manner ; Base Case ; Find the value using previously stored values ; Return the value of C ( N , K ) ; Function that count the number of ways to divide N into K integers >= P such that their sum is N ; Update the value of N ; Find the binomial coefficient recursively ; Given K , N , and P
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return C [ n ] [ k ] NEW_LINE DEDENT def waysToSplitN ( k , n , P ) : NEW_LINE INDENT new_N = n - k * P NEW_LINE return binomialCoeff ( new_N + k - 1 , new_N ) NEW_LINE DEDENT K = 3 NEW_LINE N = 8 NEW_LINE P = 2 NEW_LINE print ( waysToSplitN ( K , N , P ) ) NEW_LINE
Minimum pair merge operations required to make Array non | Function to find the minimum operations to make the array Non - increasing ; Size of the array ; Dp table initialization ; dp [ i ] : Stores minimum number of operations required to make subarray { A [ i ] , ... , A [ N ] } non - increasing ; Increment the value of j ; Add current value to sum ; Update the dp tables ; Return the answer ; Driver Code
def solve ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE val = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = a [ i ] NEW_LINE j = i NEW_LINE while ( j + 1 < n and sum < val [ j + 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE sum += a [ j ] NEW_LINE DEDENT dp [ i ] = ( j - i ) + dp [ j + 1 ] NEW_LINE val [ i ] = sum NEW_LINE DEDENT return dp [ 0 ] NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 9 , 1 ] NEW_LINE print ( solve ( arr ) ) NEW_LINE
Count full nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Iterative Method to count full nodes of binary tree ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize count ; initialize count for full nodes ; Enqueue left child ; Enqueue right child ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown
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 getfullCount ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT queue = [ ] NEW_LINE queue . append ( root ) NEW_LINE count = 0 NEW_LINE while ( len ( queue ) > 0 ) : NEW_LINE INDENT node = queue . pop ( 0 ) NEW_LINE if node . left is not None and node . right is not None : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT if node . left is not None : NEW_LINE INDENT queue . append ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT queue . append ( node . right ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT root = Node ( 2 ) NEW_LINE root . left = Node ( 7 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . left . right . left = Node ( 1 ) NEW_LINE root . left . right . right = Node ( 11 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE root . right . right . left = Node ( 4 ) NEW_LINE print " % d " % ( getfullCount ( root ) ) NEW_LINE
Count of Distinct Substrings occurring consecutively in a given String | Function to count the distinct substrings placed consecutively in the given string ; Length of the string ; If length of the string does not exceed 1 ; Initialize a DP - table ; Stores the distinct substring ; Iterate from end of the string ; Iterate backward until dp table is all computed ; If character at i - th index is same as character at j - th index ; Update dp [ i ] [ j ] based on previously computed value ; Otherwise ; Condition for consecutively placed similar substring ; Return the count ; Driver Code
def distinctSimilarSubstrings ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE substrings = set ( ) NEW_LINE for j in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for i in range ( j - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i + 1 ] [ j + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] >= j - i ) : NEW_LINE INDENT substrings . add ( str [ i : j - i ] ) NEW_LINE DEDENT DEDENT DEDENT return len ( substrings ) NEW_LINE DEDENT str = " geeksgeeksforgeeks " NEW_LINE print ( distinctSimilarSubstrings ( str ) ) NEW_LINE
Finding shortest path between any two nodes using Floyd Warshall Algorithm | Initializing the distance and Next array ; No edge between node i and j ; Function construct the shortest path between u and v ; If there 's no path between node u and v, simply return an empty array ; Storing the path in a vector ; Standard Floyd Warshall Algorithm with little modification Now if we find that dis [ i ] [ j ] > dis [ i ] [ k ] + dis [ k ] [ j ] then we modify next [ i ] [ j ] = next [ i ] [ k ] ; We cannot travel through edge that doesn 't exist ; Print the shortest path ; Driver code ; Function to initialise the distance and Next array ; Calling Floyd Warshall Algorithm , this will update the shortest distance as well as Next array ; Path from node 1 to 3 ; Path from node 0 to 2 ; Path from node 3 to 2
def initialise ( V ) : NEW_LINE INDENT global dis , Next NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT dis [ i ] [ j ] = graph [ i ] [ j ] NEW_LINE if ( graph [ i ] [ j ] == INF ) : NEW_LINE INDENT Next [ i ] [ j ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT Next [ i ] [ j ] = j NEW_LINE DEDENT DEDENT DEDENT DEDENT def constructPath ( u , v ) : NEW_LINE INDENT global graph , Next NEW_LINE if ( Next [ u ] [ v ] == - 1 ) : NEW_LINE INDENT return { } NEW_LINE DEDENT path = [ u ] NEW_LINE while ( u != v ) : NEW_LINE INDENT u = Next [ u ] [ v ] NEW_LINE path . append ( u ) NEW_LINE DEDENT return path NEW_LINE DEDENT def floydWarshall ( V ) : NEW_LINE INDENT global dist , Next NEW_LINE for k in range ( V ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if ( dis [ i ] [ k ] == INF or dis [ k ] [ j ] == INF ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( dis [ i ] [ j ] > dis [ i ] [ k ] + dis [ k ] [ j ] ) : NEW_LINE INDENT dis [ i ] [ j ] = dis [ i ] [ k ] + dis [ k ] [ j ] NEW_LINE Next [ i ] [ j ] = Next [ i ] [ k ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def printPath ( path ) : NEW_LINE INDENT n = len ( path ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT print ( path [ i ] , end = " ▁ - > ▁ " ) NEW_LINE DEDENT print ( path [ n - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT MAXM , INF = 100 , 10 ** 7 NEW_LINE dis = [ [ - 1 for i in range ( MAXM ) ] for i in range ( MAXM ) ] NEW_LINE Next = [ [ - 1 for i in range ( MAXM ) ] for i in range ( MAXM ) ] NEW_LINE V = 4 NEW_LINE graph = [ [ 0 , 3 , INF , 7 ] , [ 8 , 0 , 2 , INF ] , [ 5 , INF , 0 , 1 ] , [ 2 , INF , INF , 0 ] ] NEW_LINE initialise ( V ) NEW_LINE floydWarshall ( V ) NEW_LINE path = [ ] NEW_LINE print ( " Shortest ▁ path ▁ from ▁ 1 ▁ to ▁ 3 : ▁ " , end = " " ) NEW_LINE path = constructPath ( 1 , 3 ) NEW_LINE printPath ( path ) NEW_LINE print ( " Shortest ▁ path ▁ from ▁ 0 ▁ to ▁ 2 : ▁ " , end = " " ) NEW_LINE path = constructPath ( 0 , 2 ) NEW_LINE printPath ( path ) NEW_LINE print ( " Shortest ▁ path ▁ from ▁ 3 ▁ to ▁ 2 : ▁ " , end = " " ) NEW_LINE path = constructPath ( 3 , 2 ) NEW_LINE printPath ( path ) NEW_LINE DEDENT
Count sequences of length K having each term divisible by its preceding term | Stores the factors of i - th element in v [ i ] ; Function to find all the factors of N ; Iterate upto sqrt ( N ) ; Function to return the count of sequences of length K having all terms divisible by its preceding term ; Calculate factors of i ; Initialize dp [ 0 ] [ i ] = 0 : No subsequence of length 0 ending with i - th element exists ; Initialize dp [ 0 ] [ i ] = 1 : Only 1 subsequence of length 1 ending with i - th element exists ; Iterate [ 2 , K ] to obtain sequences of each length ; Calculate sum of all dp [ i - 1 ] [ vp [ j ] [ k ] ] ; vp [ j ] [ k ] stores all factors of j ; Store the sum in A [ i ] [ j ] ; Sum of all dp [ K ] [ j ] obtain all K length sequences ending with j ; Driver code
vp = [ [ ] for i in range ( 2009 ) ] NEW_LINE def finding_factors ( n ) : NEW_LINE INDENT i = 1 NEW_LINE a = 0 NEW_LINE global vp NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i * i == n ) : NEW_LINE INDENT vp [ n ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT vp [ n ] . append ( i ) NEW_LINE vp [ n ] . append ( int ( n / i ) ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def countSeq ( N , K ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE dp = [ [ 0 for i in range ( 109 ) ] for j in range ( 109 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT finding_factors ( i ) NEW_LINE dp [ 0 ] [ i ] = 0 NEW_LINE dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , K + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT Sum = 0 NEW_LINE for k in range ( len ( vp [ j ] ) ) : NEW_LINE INDENT Sum += dp [ i - 1 ] [ vp [ j ] [ k ] ] NEW_LINE DEDENT dp [ i ] [ j ] = Sum NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for j in range ( 1 , N + 1 ) : NEW_LINE INDENT ans += dp [ K ] [ j ] NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 3 NEW_LINE K = 2 NEW_LINE print ( countSeq ( N , K ) ) NEW_LINE
Largest possible square submatrix with maximum AND value | Function to calculate and return the length of square submatrix with maximum AND value ; Extract dimensions ; Auxiliary array Initialize auxiliary array ; c : Stores the maximum value in the matrix p : Stores the number of elements in the submatrix having maximum AND value ; Iterate over the matrix to fill the auxiliary matrix ; Find the max element in the matrix side by side ; Fill first row and column with 1 's ; For every cell , check if the elements at the left , top and top left cells from the current cell are equal or not ; Store the minimum possible submatrix size these elements are part of ; Store 1 otherwise ; Checking maximum value ; If the maximum AND value occurs more than once ; Update the maximum size of submatrix ; Final output ; Driver Code
def MAX_value ( arr ) : NEW_LINE INDENT row = len ( arr ) NEW_LINE col = len ( arr ) NEW_LINE dp = [ [ 0 for i in range ( col ) ] for j in range ( row ) ] NEW_LINE i , j = 0 , 0 NEW_LINE c , p = arr [ 0 ] [ 0 ] , 0 NEW_LINE d = row NEW_LINE for i in range ( d ) : NEW_LINE INDENT for j in range ( d ) : NEW_LINE INDENT if ( c < arr [ i ] [ j ] ) : NEW_LINE INDENT c = arr [ i ] [ j ] NEW_LINE DEDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( arr [ i - 1 ] [ j - 1 ] == arr [ i ] [ j ] and arr [ i - 1 ] [ j ] == arr [ i ] [ j ] and arr [ i ] [ j - 1 ] == arr [ i ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i - 1 ] [ j - 1 ] , min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( d ) : NEW_LINE INDENT for j in range ( d ) : NEW_LINE INDENT if ( arr [ i ] [ j ] == c ) : NEW_LINE INDENT if ( p < dp [ i ] [ j ] ) : NEW_LINE INDENT p = dp [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return p * p NEW_LINE DEDENT arr = [ [ 9 , 9 , 3 , 3 , 4 , 4 ] , [ 9 , 9 , 7 , 7 , 7 , 4 ] , [ 1 , 2 , 7 , 7 , 7 , 4 ] , [ 4 , 4 , 7 , 7 , 7 , 4 ] , [ 5 , 5 , 1 , 1 , 2 , 7 ] , [ 2 , 7 , 1 , 1 , 4 , 4 ] ] NEW_LINE print ( MAX_value ( arr ) ) NEW_LINE
Smallest power of 2 consisting of N digits | Python3 program to implement the above approach ; Function to return smallest power of 2 with N digits ; Iterate through all powers of 2 ; Driver Code
from math import log10 , log NEW_LINE def smallestNum ( n ) : NEW_LINE INDENT res = 1 NEW_LINE i = 2 NEW_LINE while ( True ) : NEW_LINE INDENT length = int ( log10 ( i ) + 1 ) NEW_LINE if ( length == n ) : NEW_LINE INDENT return int ( log ( i ) // log ( 2 ) ) NEW_LINE DEDENT i *= 2 NEW_LINE DEDENT DEDENT n = 4 NEW_LINE print ( smallestNum ( n ) ) NEW_LINE
Maximum weighted edge in path between two nodes in an N | Python3 implementation to find the maximum weighted edge in the simple path between two nodes in N - ary Tree ; Depths of Nodes ; Parent at every 2 ^ i level ; Maximum node at every 2 ^ i level ; Graph that stores destinations and its weight ; Function to traverse the nodes using the Depth - First Search Traversal ; Condition to check if its equal to its parent then skip ; DFS Recursive Call ; Function to find the ansector ; Loop to set every 2 ^ i distance ; Loop to calculate for each node in the N - ary tree ; Storing maximum edge ; Swaping if node a is at more depth than node b because we will always take at more depth ; Difference between the depth of the two given nodes ; Changing Node B to its parent at 2 ^ i distance ; Subtracting distance by 2 ^ i ; Take both a , b to its lca and find maximum ; Loop to find the maximum 2 ^ ith parent the is different for both a and b ; Updating ans ; Changing value to its parent ; Function to compute the Least common Ansector ; Driver code ; Undirected tree ; Computing LCA
import math NEW_LINE N = 100005 ; NEW_LINE level = [ 0 for i in range ( N ) ] NEW_LINE LG = 20 ; NEW_LINE dp = [ [ 0 for j in range ( N ) ] for i in range ( LG ) ] NEW_LINE mx = [ [ 0 for j in range ( N ) ] for i in range ( LG ) ] NEW_LINE v = [ [ ] for i in range ( N ) ] NEW_LINE n = 0 NEW_LINE def dfs_lca ( a , par , lev ) : NEW_LINE INDENT dp [ 0 ] [ a ] = par ; NEW_LINE level [ a ] = lev ; NEW_LINE for i in v [ a ] : NEW_LINE INDENT if ( i [ 0 ] == par ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT mx [ 0 ] [ i [ 0 ] ] = i [ 1 ] ; NEW_LINE dfs_lca ( i [ 0 ] , a , lev + 1 ) ; NEW_LINE DEDENT DEDENT def find_ancestor ( ) : NEW_LINE INDENT for i in range ( 1 , 16 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ dp [ i - 1 ] [ j ] ] ; NEW_LINE mx [ i ] [ j ] = max ( mx [ i - 1 ] [ j ] , mx [ i - 1 ] [ dp [ i - 1 ] [ j ] ] ) ; NEW_LINE DEDENT DEDENT DEDENT def getMax ( a , b ) : NEW_LINE INDENT if ( level [ b ] < level [ a ] ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT ans = 0 ; NEW_LINE diff = level [ b ] - level [ a ] ; NEW_LINE while ( diff > 0 ) : NEW_LINE INDENT log = int ( math . log2 ( diff ) ) ; NEW_LINE ans = max ( ans , mx [ log ] [ b ] ) ; NEW_LINE b = dp [ log ] [ b ] ; NEW_LINE diff -= ( 1 << log ) ; NEW_LINE DEDENT while ( a != b ) : NEW_LINE INDENT i = int ( math . log2 ( level [ a ] ) ) ; NEW_LINE while ( i > 0 and dp [ i ] [ a ] == dp [ i ] [ b ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT ans = max ( ans , mx [ i ] [ a ] ) ; NEW_LINE ans = max ( ans , mx [ i ] [ b ] ) ; NEW_LINE a = dp [ i ] [ a ] ; NEW_LINE b = dp [ i ] [ b ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def compute_lca ( ) : NEW_LINE INDENT dfs_lca ( 1 , 0 , 0 ) ; NEW_LINE find_ancestor ( ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE v [ 1 ] . append ( [ 2 , 2 ] ) ; NEW_LINE v [ 2 ] . append ( [ 1 , 2 ] ) ; NEW_LINE v [ 1 ] . append ( [ 3 , 5 ] ) ; NEW_LINE v [ 3 ] . append ( [ 1 , 5 ] ) ; NEW_LINE v [ 3 ] . append ( [ 4 , 3 ] ) ; NEW_LINE v [ 4 ] . append ( [ 3 , 4 ] ) ; NEW_LINE v [ 3 ] . append ( [ 5 , 1 ] ) ; NEW_LINE v [ 5 ] . append ( [ 3 , 1 ] ) ; NEW_LINE compute_lca ( ) ; NEW_LINE queries = [ [ 3 , 5 ] , [ 2 , 3 ] , [ 2 , 4 ] ] NEW_LINE q = 3 ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT max_edge = getMax ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ; NEW_LINE print ( max_edge ) NEW_LINE DEDENT DEDENT
Count full nodes in a Binary tree ( Iterative and Recursive ) | A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of full Nodes in a binary tree ; Driver code ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown
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 getfullCount ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE if ( root . left and root . right ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT res += ( getfullCount ( root . left ) + getfullCount ( root . right ) ) NEW_LINE return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . right . right . left = newNode ( 4 ) NEW_LINE print ( getfullCount ( root ) ) NEW_LINE DEDENT
Count Possible Decodings of a given Digit Sequence in O ( N ) time and Constant Auxiliary space | A Dynamic programming based function to count decodings in digit sequence ; For base condition "01123" should return 0 ; Using last two calculated values , calculate for ith index ; Change boolean to int ; Return the required answer ; Driver Code ; Function call
def countDecodingDP ( digits , n ) : NEW_LINE INDENT if ( digits [ 0 ] == '0' ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT count0 = 1 ; count1 = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dig1 = 0 ; dig3 = 0 ; NEW_LINE if ( digits [ i - 1 ] != '0' ) : NEW_LINE INDENT dig1 = 1 ; NEW_LINE DEDENT if ( digits [ i - 2 ] == '1' ) : NEW_LINE INDENT dig2 = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dig2 = 0 ; NEW_LINE DEDENT if ( digits [ i - 2 ] == '2' and digits [ i - 1 ] < '7' ) : NEW_LINE INDENT dig3 = 1 ; NEW_LINE DEDENT count2 = dig1 * count1 + NEW_LINE INDENT dig2 + dig3 * count0 ; NEW_LINE DEDENT count0 = count1 ; NEW_LINE count1 = count2 ; NEW_LINE DEDENT return count1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT digits = "1234" ; NEW_LINE n = len ( digits ) ; NEW_LINE print ( countDecodingDP ( digits , n ) ) ; NEW_LINE DEDENT
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Function to find the maximum distance ; Set up top row and left column ; Pass one : top left to bottom right ; Check if there was no " One " Cell ; Set up top row and left column ; Past two : bottom right to top left ; Driver code
def maxDistance ( grid ) : NEW_LINE INDENT if ( len ( grid ) == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT N = len ( grid ) NEW_LINE INF = 1000000 NEW_LINE if grid [ 0 ] [ 0 ] == 1 : NEW_LINE INDENT grid [ 0 ] [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT grid [ 0 ] [ 0 ] = INF NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if grid [ 0 ] [ i ] == 1 : NEW_LINE INDENT grid [ 0 ] [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT grid [ 0 ] [ i ] = grid [ 0 ] [ i - 1 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if grid [ i ] [ 0 ] == 1 : NEW_LINE INDENT grid [ i ] [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT grid [ i ] [ 0 ] = grid [ i - 1 ] [ 0 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , N ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 : NEW_LINE INDENT grid [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT grid [ i ] [ j ] = min ( grid [ i - 1 ] [ j ] , grid [ i ] [ j - 1 ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT if ( grid [ N - 1 ] [ N - 1 ] >= INF ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxi = grid [ N - 1 ] [ N - 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT grid [ N - 1 ] [ i ] = min ( grid [ N - 1 ] [ i ] , grid [ N - 1 ] [ i + 1 ] + 1 ) NEW_LINE maxi = max ( grid [ N - 1 ] [ i ] , maxi ) NEW_LINE DEDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT grid [ i ] [ N - 1 ] = min ( grid [ i ] [ N - 1 ] , grid [ i + 1 ] [ N - 1 ] + 1 ) NEW_LINE maxi = max ( grid [ i ] [ N - 1 ] , maxi + 1 ) NEW_LINE DEDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT grid [ i ] [ j ] = min ( grid [ i ] [ j ] , min ( grid [ i + 1 ] [ j ] + 1 , grid [ i ] [ j + 1 ] + 1 ) ) NEW_LINE maxi = max ( grid [ i ] [ j ] , maxi ) NEW_LINE DEDENT DEDENT if maxi == 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return maxi NEW_LINE DEDENT DEDENT arr = [ [ 0 , 0 , 1 ] , [ 0 , 0 , 0 ] , [ 0 , 0 , 0 ] ] NEW_LINE print ( maxDistance ( arr ) ) NEW_LINE
Minimize total cost without repeating same task in two consecutive iterations | Function to return the minimum cost for N iterations ; Construct the dp table ; 1 st row of dp table will be equal to the 1 st of cost matrix ; Iterate through all the rows ; To iterate through the columns of current row ; Initialize val as infinity ; To iterate through the columns of previous row ; Fill the dp matrix ; Returning the minimum value ; Driver Code ; Number of iterations ; Number of tasks ; Cost matrix
def findCost ( cost_mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 ] * M for _ in range ( M ) ] NEW_LINE dp [ 0 ] = cost_mat [ 0 ] NEW_LINE for row in range ( 1 , N ) : NEW_LINE INDENT for curr_col in range ( M ) : NEW_LINE INDENT val = 999999999 NEW_LINE for prev_col in range ( M ) : NEW_LINE INDENT if curr_col != prev_col : NEW_LINE INDENT val = min ( val , dp [ row - 1 ] [ prev_col ] ) NEW_LINE DEDENT DEDENT dp [ row ] [ curr_col ] = val + cost_mat [ row ] [ curr_col ] NEW_LINE DEDENT DEDENT return min ( dp [ - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE M = 4 NEW_LINE cost_mat = [ [ 4 , 5 , 3 , 2 ] , [ 6 , 2 , 8 , 1 ] , [ 6 , 2 , 2 , 1 ] , [ 0 , 5 , 5 , 1 ] ] NEW_LINE print ( findCost ( cost_mat , N , M ) ) NEW_LINE DEDENT
Split the given string into Primes : Digit DP | Function to precompute all the primes upto 1000000 and store it in a set using Sieve of Eratosthenes ; Here str ( ) is used for converting int to string ; A function to find the minimum number of segments the given string can be divided such that every segment is a prime ; Declare a splitdp [ ] array and initialize to - 1 ; Call sieve function to store primes in primes array ; Build the DP table in a bottom - up manner ; If the prefix is prime then the prefix will be found in the prime set ; If the Given Prefix can be split into Primes then for the remaining string from i to j Check if Prime . If yes calculate the minimum split till j ; To check if the substring from i to j is a prime number or not ; If it is a prime , then update the dp array ; Return the minimum number of splits for the entire string ; Driver code
def getPrimesFromSeive ( primes ) : NEW_LINE INDENT prime = [ True ] * ( 1000001 ) NEW_LINE prime [ 0 ] , prime [ 1 ] = False , False NEW_LINE i = 2 NEW_LINE while ( i * i <= 1000000 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT for j in range ( i * i , 1000001 , i ) : NEW_LINE INDENT prime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT for i in range ( 2 , 1000001 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT primes . append ( str ( i ) ) NEW_LINE DEDENT DEDENT DEDENT def splitIntoPrimes ( number ) : NEW_LINE INDENT numLen = len ( number ) NEW_LINE splitDP = [ - 1 ] * ( numLen + 1 ) NEW_LINE primes = [ ] NEW_LINE getPrimesFromSeive ( primes ) NEW_LINE for i in range ( 1 , numLen + 1 ) : NEW_LINE INDENT if ( i <= 6 and ( number [ 0 : i ] in primes ) ) : NEW_LINE INDENT splitDP [ i ] = 1 NEW_LINE DEDENT if ( splitDP [ i ] != - 1 ) : NEW_LINE INDENT j = 1 NEW_LINE while ( j <= 6 and ( i + j <= numLen ) ) : NEW_LINE INDENT if ( number [ i : i + j ] in primes ) : NEW_LINE INDENT if ( splitDP [ i + j ] == - 1 ) : NEW_LINE INDENT splitDP [ i + j ] = 1 + splitDP [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT splitDP [ i + j ] = min ( splitDP [ i + j ] , 1 + splitDP [ i ] ) NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return splitDP [ numLen ] NEW_LINE DEDENT print ( splitIntoPrimes ( "13499315" ) ) NEW_LINE print ( splitIntoPrimes ( "43" ) ) NEW_LINE
Connect Nodes at same Level ( Level Order Traversal ) | connect nodes at same level using level order traversal ; Node class ; set nextRight of all nodes of a tree ; null marker to represent end of current level ; do level order of tree using None markers ; next element in queue represents next node at current level ; pus left and right children of current node ; if queue is not empty , push NULL to mark nodes at this level are visited ; Driver program to test above functions . ; Constructed binary tree is 10 / \ 8 2 / \ 3 90 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers ; print level by level ; print inorder
import sys NEW_LINE 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 self . nextRight = None NEW_LINE DEDENT def __str__ ( self ) : NEW_LINE INDENT return ' { } ' . format ( self . data ) NEW_LINE DEDENT DEDENT def connect ( root ) : NEW_LINE INDENT queue = [ ] NEW_LINE queue . append ( root ) NEW_LINE queue . append ( None ) NEW_LINE while queue : NEW_LINE INDENT p = queue . pop ( 0 ) NEW_LINE if p : NEW_LINE INDENT p . nextRight = queue [ 0 ] NEW_LINE if p . left : NEW_LINE INDENT queue . append ( p . left ) NEW_LINE DEDENT if p . right : NEW_LINE INDENT queue . append ( p . right ) NEW_LINE DEDENT DEDENT elif queue : NEW_LINE INDENT queue . append ( None ) NEW_LINE DEDENT DEDENT DEDENT def main ( ) : NEW_LINE INDENT root = Node ( 10 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 2 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 90 ) NEW_LINE connect ( root ) NEW_LINE print ( " Following are populated nextRight pointers in " " the tree ( - 1 is printed if there is no nextRight ) " ) NEW_LINE if ( root . nextRight != None ) : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . data , root . nextRight . data ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . data , - 1 ) ) NEW_LINE DEDENT if ( root . left . nextRight != None ) : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . left . data , root . left . nextRight . data ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . left . data , - 1 ) ) NEW_LINE DEDENT if ( root . right . nextRight != None ) : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . right . data , root . right . nextRight . data ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . right . data , - 1 ) ) NEW_LINE DEDENT if ( root . left . left . nextRight != None ) : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . left . left . data , root . left . left . nextRight . data ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . left . left . data , - 1 ) ) NEW_LINE DEDENT if ( root . right . right . nextRight != None ) : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . right . right . data , root . right . right . nextRight . data ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " nextRight of % d is % d " % ( root . right . right . data , - 1 ) ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT def printLevelByLevel ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT node = root NEW_LINE while node : NEW_LINE INDENT print ( ' { } ' . format ( node . data ) , end = ' ▁ ' ) NEW_LINE node = node . nextRight NEW_LINE DEDENT print ( ) NEW_LINE if root . left : NEW_LINE INDENT printLevelByLevel ( root . left ) NEW_LINE DEDENT else : NEW_LINE INDENT printLevelByLevel ( root . right ) NEW_LINE DEDENT DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . data , end = ' ▁ ' ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT
Number of ways to convert a character X to a string Y | Python3 implementation of the approach ; Function to find the modular - inverse ; While power > 1 ; Updating s and a ; Updating power ; Return the final answer ; Function to return the count of ways ; To store the final answer ; To store pre - computed factorials ; Computing factorials ; Loop to find the occurrences of x and update the ans ; Multiplying the answer by ( n - 1 ) ! ; Return the final answer ; Driver code
MOD = 1000000007 ; NEW_LINE def modInv ( a , p = MOD - 2 ) : NEW_LINE INDENT s = 1 ; NEW_LINE while ( p != 1 ) : NEW_LINE INDENT if ( p % 2 ) : NEW_LINE INDENT s = ( s * a ) % MOD ; NEW_LINE DEDENT a = ( a * a ) % MOD ; NEW_LINE p //= 2 ; NEW_LINE DEDENT return ( a * s ) % MOD ; NEW_LINE DEDENT def findCnt ( x , y ) : NEW_LINE INDENT ans = 0 ; NEW_LINE fact = [ 1 ] * ( len ( y ) + 1 ) ; NEW_LINE for i in range ( 1 , len ( y ) ) : NEW_LINE INDENT fact [ i ] = ( fact [ i - 1 ] * i ) % MOD ; NEW_LINE DEDENT for i in range ( len ( y ) ) : NEW_LINE INDENT if ( y [ i ] == x ) : NEW_LINE INDENT ans += ( modInv ( fact [ i ] ) * modInv ( fact [ len ( y ) - i - 1 ] ) ) % MOD ; NEW_LINE ans %= MOD ; NEW_LINE DEDENT DEDENT ans *= fact [ ( len ( y ) - 1 ) ] ; NEW_LINE ans %= MOD ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = ' a ' ; NEW_LINE y = " xxayy " ; NEW_LINE print ( findCnt ( x , y ) ) ; NEW_LINE DEDENT
Find the Largest divisor Subset in the Array | Function to find the required subsequence ; Sort the array ; Keep a count of the length of the subsequence and the previous element Set the initial values ; Maximum length of the subsequence and the last element ; Run a loop for every element ; Check for all the divisors ; If the element is a divisor and the length of subsequence will increase by adding j as previous element of i ; Increase the count ; Update the max count ; Get the last index of the subsequence ; Print the element ; Move the index to the previous element ; Driver code
def findSubSeq ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE count = [ 1 ] * n ; NEW_LINE prev = [ - 1 ] * n ; NEW_LINE max = 0 ; NEW_LINE maxprev = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] % arr [ j ] == 0 and count [ j ] + 1 > count [ i ] ) : NEW_LINE INDENT count [ i ] = count [ j ] + 1 ; NEW_LINE prev [ i ] = j ; NEW_LINE DEDENT DEDENT if ( max < count [ i ] ) : NEW_LINE INDENT max = count [ i ] ; NEW_LINE maxprev = i ; NEW_LINE DEDENT DEDENT i = maxprev ; NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( arr [ i ] != - 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT i = prev [ i ] ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findSubSeq ( arr , n ) ; NEW_LINE DEDENT
Minimum number of integers required such that each Segment contains at least one of them | Function to compute minimum number of points which cover all segments ; Sort the list of tuples by their second element . ; To store the solution ; Iterate over all the segments ; Get the start point of next segment ; Loop over all those segments whose start point is less than the end point of current segment ; Print the possibles values of M ; Driver Code ; Starting points of segments ; Ending points of segments ; Insert ranges in points [ ] ; Function Call
def minPoints ( points ) : NEW_LINE INDENT points . sort ( key = lambda x : x [ 1 ] ) NEW_LINE coordinates = [ ] NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT seg = points [ i ] [ 1 ] NEW_LINE coordinates . append ( seg ) NEW_LINE p = i + 1 NEW_LINE if p >= n : NEW_LINE INDENT break NEW_LINE DEDENT arrived = points [ p ] [ 0 ] NEW_LINE while seg >= arrived : NEW_LINE INDENT p += 1 NEW_LINE if p >= n : NEW_LINE INDENT break NEW_LINE DEDENT arrived = points [ p ] [ 0 ] NEW_LINE DEDENT i = p NEW_LINE DEDENT for point in coordinates : NEW_LINE INDENT print ( point , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE start = [ 4 , 1 , 2 , 5 ] NEW_LINE end = [ 7 , 3 , 5 , 6 ] NEW_LINE points = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT tu = ( start [ i ] , end [ i ] ) NEW_LINE points . append ( tu ) NEW_LINE DEDENT minPoints ( points ) NEW_LINE
Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Python3 implementation of the approach ; Function to find the minimum required sum using dynamic programming ; dp [ i ] [ j ] = minimum val of accommodation till j 'th index of the string using i+1 number of buckets. Final ans will be in dp[n-1][K-1] Initialise dp with all states as 0 ; Corner cases ; Filling first row , if only 1 bucket then simple count number of zeros and ones and do the multiplication ; If k = 0 then this arrangement is not possible ; If no arrangement is possible then our answer will remain INT_MAX so return - 1 ; Driver code ; K buckets
import sys NEW_LINE def solve ( Str , K ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE dp = [ [ 0 for i in range ( n ) ] for j in range ( K ) ] NEW_LINE if ( n < K ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT elif ( n == K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT zeroes = 0 NEW_LINE ones = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str [ i ] == '0' ) : NEW_LINE INDENT zeroes += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT dp [ 0 ] [ i ] = ones * zeroes NEW_LINE DEDENT for s in range ( 1 , K ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT dp [ s ] [ i ] = sys . maxsize NEW_LINE ones = 0 NEW_LINE zeroes = 0 NEW_LINE for k in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( Str [ k ] == '0' ) : NEW_LINE INDENT zeroes += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT temp = 0 NEW_LINE if ( k - 1 >= 0 ) : NEW_LINE INDENT temp = ones * zeroes + dp [ s - 1 ] [ k - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT temp = sys . maxsize NEW_LINE DEDENT dp [ s ] [ i ] = min ( dp [ s ] [ i ] , temp ) NEW_LINE DEDENT DEDENT DEDENT if ( dp [ K - 1 ] [ n - 1 ] == sys . maxsize ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return dp [ K - 1 ] [ n - 1 ] NEW_LINE DEDENT DEDENT S = "0101" NEW_LINE K = 2 NEW_LINE print ( solve ( S , K ) ) NEW_LINE
Queries for bitwise AND in the index range [ L , R ] of the given array | Python3 implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix count ; Function to answer query ; To store the answer ; Loop for each bit ; To store the number of variables with ith bit set ; Condition for ith bit of answer to be set ; Driver code
import numpy as np NEW_LINE MAX = 100000 NEW_LINE bitscount = 32 NEW_LINE prefix_count = np . zeros ( ( bitscount , MAX ) ) ; NEW_LINE def findPrefixCount ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , bitscount ) : NEW_LINE INDENT prefix_count [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) ; NEW_LINE prefix_count [ i ] [ j ] += prefix_count [ i ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT DEDENT def rangeOr ( l , r ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( bitscount ) : NEW_LINE INDENT x = 0 ; NEW_LINE if ( l == 0 ) : NEW_LINE INDENT x = prefix_count [ i ] [ r ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x = prefix_count [ i ] [ r ] - prefix_count [ i ] [ l - 1 ] ; NEW_LINE DEDENT if ( x == r - l + 1 ) : NEW_LINE INDENT ans = ( ans | ( 1 << i ) ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 5 , 3 , 5 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findPrefixCount ( arr , n ) ; NEW_LINE queries = [ [ 1 , 3 ] , [ 4 , 5 ] ] ; NEW_LINE q = len ( queries ) ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( rangeOr ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) ) ; NEW_LINE DEDENT DEDENT
Longest path in a directed Acyclic graph | Dynamic Programming | Function to traverse the DAG and apply Dynamic Programming to find the longest path ; Mark as visited ; Traverse for all its children ; If not visited ; Store the max of the paths ; Function to add an edge ; Function that returns the longest path ; Dp array ; Visited array to know if the node has been visited previously or not ; Call DFS for every unvisited vertex ; Traverse and find the maximum of all dp [ i ] ; Driver Code ; Example - 1
def dfs ( node , adj , dp , vis ) : NEW_LINE INDENT vis [ node ] = True NEW_LINE for i in range ( 0 , len ( adj [ node ] ) ) : NEW_LINE INDENT if not vis [ adj [ node ] [ i ] ] : NEW_LINE INDENT dfs ( adj [ node ] [ i ] , adj , dp , vis ) NEW_LINE DEDENT dp [ node ] = max ( dp [ node ] , 1 + dp [ adj [ node ] [ i ] ] ) NEW_LINE DEDENT DEDENT def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE DEDENT def findLongestPath ( adj , n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE vis = [ False ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if not vis [ i ] : NEW_LINE INDENT dfs ( i , adj , dp , vis ) NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE adj = [ [ ] for i in range ( n + 1 ) ] NEW_LINE addEdge ( adj , 1 , 2 ) NEW_LINE addEdge ( adj , 1 , 3 ) NEW_LINE addEdge ( adj , 3 , 2 ) NEW_LINE addEdge ( adj , 2 , 4 ) NEW_LINE addEdge ( adj , 3 , 4 ) NEW_LINE print ( findLongestPath ( adj , n ) ) NEW_LINE DEDENT
Largest subset of rectangles such that no rectangle fit in any other rectangle | Recursive function to get the largest subset ; Base case when it exceeds ; If the state has been visited previously ; Initialize ; No elements in subset yet ; First state which includes current index ; Second state which does not include current index ; If the rectangle fits in , then do not include the current index in subset ; First state which includes current index ; Second state which does not include current index ; Function to get the largest subset ; Sort the array ; Get the answer ; Driver code ; ( height , width ) pairs
def findLongest ( a , n , present , previous ) : NEW_LINE INDENT if present == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif previous != - 1 : NEW_LINE INDENT if dp [ present ] [ previous ] != - 1 : NEW_LINE INDENT return dp [ present ] [ previous ] NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE if previous == - 1 : NEW_LINE INDENT ans = 1 + findLongest ( a , n , present + 1 , present ) NEW_LINE ans = max ( ans , findLongest ( a , n , present + 1 , previous ) ) NEW_LINE DEDENT else : NEW_LINE INDENT h1 = a [ previous ] [ 0 ] NEW_LINE h2 = a [ present ] [ 0 ] NEW_LINE w1 = a [ previous ] [ 1 ] NEW_LINE w2 = a [ present ] [ 1 ] NEW_LINE if h1 <= h2 and w1 <= w2 : NEW_LINE INDENT ans = max ( ans , findLongest ( a , n , present + 1 , previous ) ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = 1 + findLongest ( a , n , present + 1 , present ) NEW_LINE ans = max ( ans , findLongest ( a , n , present + 1 , previous ) ) NEW_LINE DEDENT DEDENT dp [ present ] [ previous ] = ans NEW_LINE return ans NEW_LINE DEDENT def getLongest ( a , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE ans = findLongest ( a , n , 0 , - 1 ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ [ 1 , 5 ] , [ 2 , 4 ] , [ 1 , 1 ] , [ 3 , 3 ] ] NEW_LINE N = 10 NEW_LINE dp = [ [ - 1 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE n = len ( a ) NEW_LINE print ( getLongest ( a , n ) ) NEW_LINE DEDENT
Maximum length subsequence such that adjacent elements in the subsequence have a common factor | Python3 implementation of the above approach ; to compute least prime divisor of i ; Function that returns the maximum length subsequence such that adjacent elements have a common factor . ; Initialize dp array with 1. ; p has appeared at least once . ; Update latest occurrence of prime p . ; Take maximum value as the answer . ; Driver code
import math as mt NEW_LINE N = 100005 NEW_LINE MAX = 1000002 NEW_LINE lpd = [ 0 for i in range ( MAX ) ] NEW_LINE def preCompute ( ) : NEW_LINE INDENT lpd [ 0 ] , lpd [ 1 ] = 1 , 1 NEW_LINE for i in range ( 2 , mt . ceil ( mt . sqrt ( MAX ) ) ) : NEW_LINE INDENT for j in range ( 2 * i , MAX , i ) : NEW_LINE INDENT if ( lpd [ j ] == 0 ) : NEW_LINE INDENT lpd [ j ] = i NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , MAX ) : NEW_LINE INDENT if ( lpd [ i ] == 0 ) : NEW_LINE INDENT lpd [ i ] = i NEW_LINE DEDENT DEDENT DEDENT def maxLengthSubsequence ( arr , n ) : NEW_LINE INDENT dp = [ 1 for i in range ( N + 1 ) ] NEW_LINE pos = dict ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT while ( arr [ i ] > 1 ) : NEW_LINE INDENT p = lpd [ arr [ i ] ] NEW_LINE if ( p in pos . keys ( ) ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , 1 + dp [ pos [ p ] ] ) NEW_LINE DEDENT pos [ p ] = i NEW_LINE while ( arr [ i ] % p == 0 ) : NEW_LINE INDENT arr [ i ] //= p NEW_LINE DEDENT DEDENT DEDENT ans = 1 NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 13 , 2 , 8 , 6 , 3 , 1 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE preCompute ( ) NEW_LINE print ( maxLengthSubsequence ( arr , n ) ) NEW_LINE
Number of ways to partition a string into two balanced subsequences | For maximum length of input string ; Declaring the DP table ; Function to calculate the number of valid assignments ; Return 1 if both subsequences are balanced ; Increment the count if it is an opening bracket ; Decrement the count if it a closing bracket ; Driver code ; Initial value for c_x and c_y is zero
MAX = 10 NEW_LINE F = [ [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] for k in range ( MAX ) ] NEW_LINE def noOfAssignments ( S , n , i , c_x , c_y ) : NEW_LINE INDENT if F [ i ] [ c_x ] [ c_y ] != - 1 : NEW_LINE INDENT return F [ i ] [ c_x ] [ c_y ] NEW_LINE DEDENT if i == n : NEW_LINE INDENT F [ i ] [ c_x ] [ c_y ] = not c_x and not c_y NEW_LINE return F [ i ] [ c_x ] [ c_y ] NEW_LINE DEDENT if S [ i ] == ' ( ' : NEW_LINE INDENT F [ i ] [ c_x ] [ c_y ] = noOfAssignments ( S , n , i + 1 , c_x + 1 , c_y ) + noOfAssignments ( S , n , i + 1 , c_x , c_y + 1 ) NEW_LINE return F [ i ] [ c_x ] [ c_y ] NEW_LINE DEDENT F [ i ] [ c_x ] [ c_y ] = 0 NEW_LINE if c_x : NEW_LINE INDENT F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( S , n , i + 1 , c_x - 1 , c_y ) NEW_LINE DEDENT if c_y : NEW_LINE INDENT F [ i ] [ c_x ] [ c_y ] += noOfAssignments ( S , n , i + 1 , c_x , c_y - 1 ) NEW_LINE DEDENT return F [ i ] [ c_x ] [ c_y ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ( ( ) ) " NEW_LINE n = len ( S ) NEW_LINE print ( noOfAssignments ( S , n , 0 , 0 , 0 ) ) NEW_LINE DEDENT
Gould 's Sequence | Utility function to count odd numbers in ith row of Pascals 's triangle ; Initialize count as zero ; Return 2 ^ count ; Function to generate gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call
def countOddNumber ( row_num ) : NEW_LINE INDENT count = 0 NEW_LINE while row_num != 0 : NEW_LINE INDENT count += row_num & 1 NEW_LINE row_num >>= 1 NEW_LINE DEDENT return ( 1 << count ) NEW_LINE DEDENT def gouldSequence ( n ) : NEW_LINE INDENT for row_num in range ( 0 , n ) : NEW_LINE INDENT print ( countOddNumber ( row_num ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 16 NEW_LINE gouldSequence ( n ) NEW_LINE DEDENT
Count numbers ( smaller than or equal to N ) with given digit sum | N can be max 10 ^ 18 and hence digitsum will be 162 maximum . ; If sum_so_far equals to given sum then return 1 else 0 ; Our constructed number should not become greater than N . ; If tight is true then it will also be true for ( i + 1 ) digit . ; Driver code
def solve ( i , tight , sum_so_far , Sum , number , length ) : NEW_LINE INDENT if i == length : NEW_LINE INDENT if sum_so_far == Sum : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT ans = dp [ i ] [ tight ] [ sum_so_far ] NEW_LINE if ans != - 1 : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = 0 NEW_LINE for currdigit in range ( 0 , 10 ) : NEW_LINE INDENT currdigitstr = str ( currdigit ) NEW_LINE if not tight and currdigitstr > number [ i ] : NEW_LINE INDENT break NEW_LINE DEDENT ntight = tight or currdigitstr < number [ i ] NEW_LINE nsum_so_far = sum_so_far + currdigit NEW_LINE ans += solve ( i + 1 , ntight , nsum_so_far , Sum , number , length ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT count , Sum = 0 , 4 NEW_LINE number = "100" NEW_LINE dp = [ [ [ - 1 for i in range ( 162 ) ] for j in range ( 2 ) ] for k in range ( 18 ) ] NEW_LINE print ( solve ( 0 , 0 , 0 , Sum , number , len ( number ) ) ) NEW_LINE DEDENT
Longest dividing subsequence | lds ( ) returns the length of the longest dividing subsequence in arr [ ] of size n ; Compute optimized lds values in bottom up manner ; Return maximum value in lds [ ] ; Driver Code
def lds ( arr , n ) : NEW_LINE INDENT lds = [ 0 for i in range ( n ) ] NEW_LINE lds [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT lds [ i ] = 1 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( lds [ j ] != 0 and arr [ i ] % arr [ j ] == 0 ) : NEW_LINE INDENT lds [ i ] = max ( lds [ i ] , lds [ j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT return max ( lds ) NEW_LINE DEDENT arr = [ 2 , 11 , 16 , 12 , 36 , 60 , 71 , 17 , 29 , 144 , 288 , 129 , 432 , 993 ] NEW_LINE print ( " Length ▁ of ▁ lds ▁ is " , lds ( arr , len ( arr ) ) ) NEW_LINE
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future function calls ; store it in arr to avoid further repetitive work in future function calls ; Driver Code
def lcs ( X , Y , Z , m , n , o ) : NEW_LINE INDENT global arr NEW_LINE if ( m == 0 or n == 0 or o == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ m - 1 ] [ n - 1 ] [ o - 1 ] != - 1 ) : NEW_LINE INDENT return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] and Y [ n - 1 ] == Z [ o - 1 ] ) : NEW_LINE INDENT arr [ m - 1 ] [ n - 1 ] [ o - 1 ] = 1 + lcs ( X , Y , Z , m - 1 , n - 1 , o - 1 ) NEW_LINE return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT arr [ m - 1 ] [ n - 1 ] [ o - 1 ] = max ( lcs ( X , Y , Z , m , n - 1 , o ) , max ( lcs ( X , Y , Z , m - 1 , n , o ) , lcs ( X , Y , Z , m , n , o - 1 ) ) ) NEW_LINE return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] NEW_LINE DEDENT DEDENT arr = [ [ [ 0 for k in range ( 100 ) ] for j in range ( 100 ) ] for i in range ( 100 ) ] NEW_LINE for i in range ( 100 ) : NEW_LINE INDENT for j in range ( 100 ) : NEW_LINE INDENT for k in range ( 100 ) : NEW_LINE INDENT arr [ i ] [ j ] [ k ] = - 1 NEW_LINE DEDENT DEDENT DEDENT X = " geeks " NEW_LINE Y = " geeksfor " NEW_LINE Z = " geeksforgeeks " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE o = len ( Z ) NEW_LINE print ( " Length ▁ of ▁ LCS ▁ is ▁ " , lcs ( X , Y , Z , m , n , o ) ) NEW_LINE
Find the probability of reaching all points after N moves from point N | Function to calculate the probabilities ; Array where row represent the pass and the column represents the points on the line ; Initially the person can reach left or right with one move ; Calculate probabilities for N - 1 moves ; When the person moves from ith index in right direction when i moves has been done ; When the person moves from ith index in left direction when i moves has been done ; Print the arr ; Driver code
def printProbabilities ( n , left ) : NEW_LINE INDENT right = 1 - left ; NEW_LINE arr = [ [ 0 for j in range ( 2 * n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE arr [ 1 ] [ n + 1 ] = right ; NEW_LINE arr [ 1 ] [ n - 1 ] = left ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , 2 * n + 1 ) : NEW_LINE INDENT arr [ i ] [ j ] += ( arr [ i - 1 ] [ j - 1 ] * right ) ; NEW_LINE DEDENT for j in range ( 2 * n - 1 , - 1 , - 1 ) : NEW_LINE INDENT arr [ i ] [ j ] += ( arr [ i - 1 ] [ j + 1 ] * left ) ; NEW_LINE DEDENT DEDENT for i in range ( 2 * n + 1 ) : NEW_LINE INDENT print ( " { :5.4f } ▁ " . format ( arr [ n ] [ i ] ) , end = ' ▁ ' ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE left = 0.5 ; NEW_LINE printProbabilities ( n , left ) ; NEW_LINE DEDENT
Check if it is possible to reach a number by making jumps of two given length | Python3 implementation of the approach ; Function to perform BFS traversal to find minimum number of step needed to reach x from K ; Calculate GCD of d1 and d2 ; If position is not reachable return - 1 ; Queue for BFS ; Hash Table for marking visited positions ; we need 0 steps to reach K ; Mark starting position as visited ; stp is the number of steps to reach position s ; if position not visited add to queue and mark visited ; Driver Code
from math import gcd as __gcd NEW_LINE from collections import deque as queue NEW_LINE def minStepsNeeded ( k , d1 , d2 , x ) : NEW_LINE INDENT gcd = __gcd ( d1 , d2 ) NEW_LINE if ( ( k - x ) % gcd != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT q = queue ( ) NEW_LINE visited = dict ( ) NEW_LINE q . appendleft ( [ k , 0 ] ) NEW_LINE visited [ k ] = 1 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT sr = q . pop ( ) NEW_LINE s , stp = sr [ 0 ] , sr [ 1 ] NEW_LINE if ( s == x ) : NEW_LINE INDENT return stp NEW_LINE DEDENT if ( s + d1 not in visited ) : NEW_LINE INDENT q . appendleft ( [ ( s + d1 ) , stp + 1 ] ) NEW_LINE visited [ ( s + d1 ) ] = 1 NEW_LINE DEDENT if ( s + d2 not in visited ) : NEW_LINE INDENT q . appendleft ( [ ( s + d2 ) , stp + 1 ] ) NEW_LINE visited [ ( s + d2 ) ] = 1 NEW_LINE DEDENT if ( s - d1 not in visited ) : NEW_LINE INDENT q . appendleft ( [ ( s - d1 ) , stp + 1 ] ) NEW_LINE visited [ ( s - d1 ) ] = 1 NEW_LINE DEDENT if ( s - d2 not in visited ) : NEW_LINE INDENT q . appendleft ( [ ( s - d2 ) , stp + 1 ] ) NEW_LINE visited [ ( s - d2 ) ] = 1 NEW_LINE DEDENT DEDENT DEDENT k = 10 NEW_LINE d1 = 4 NEW_LINE d2 = 6 NEW_LINE x = 8 NEW_LINE print ( minStepsNeeded ( k , d1 , d2 , x ) ) NEW_LINE
Tiling with Dominoes | Python 3 program to find no . of ways to fill a 3 xn board with 2 x1 dominoes . ; Driver Code
def countWays ( n ) : NEW_LINE INDENT A = [ 0 ] * ( n + 1 ) NEW_LINE B = [ 0 ] * ( n + 1 ) NEW_LINE A [ 0 ] = 1 NEW_LINE A [ 1 ] = 0 NEW_LINE B [ 0 ] = 0 NEW_LINE B [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT A [ i ] = A [ i - 2 ] + 2 * B [ i - 1 ] NEW_LINE B [ i ] = A [ i - 1 ] + B [ i - 2 ] NEW_LINE DEDENT return A [ n ] NEW_LINE DEDENT n = 8 NEW_LINE print ( countWays ( n ) ) NEW_LINE
Newman | Recursive function to find the n - th element of sequence ; Driver code
def sequence ( n ) : NEW_LINE INDENT if n == 1 or n == 2 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return sequence ( sequence ( n - 1 ) ) + sequence ( n - sequence ( n - 1 ) ) ; NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT n = 10 NEW_LINE print sequence ( n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Connect nodes at same level | A binary tree node ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the nextRight pointer for p 's left child ; Set the nextRight pointer for p 's right child p.nextRight will be None if p is the right most child at its level ; Set nextRight for other nodes in pre order fashion ; Driver Code ; Constructed binary tree is 10 / \ 8 2 / 3 ; Populates nextRight pointer in all nodes ; Let us check the values of nextRight pointers
class newnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = self . nextRight = None NEW_LINE DEDENT DEDENT def connect ( p ) : NEW_LINE INDENT p . nextRight = None NEW_LINE connectRecur ( p ) NEW_LINE DEDENT def connectRecur ( p ) : NEW_LINE INDENT if ( not p ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( p . left ) : NEW_LINE INDENT p . left . nextRight = p . right NEW_LINE DEDENT if ( p . right ) : NEW_LINE INDENT if p . nextRight : NEW_LINE INDENT p . right . nextRight = p . nextRight . left NEW_LINE DEDENT else : NEW_LINE INDENT p . right . nextRight = None NEW_LINE DEDENT DEDENT connectRecur ( p . left ) NEW_LINE connectRecur ( p . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newnode ( 10 ) NEW_LINE root . left = newnode ( 8 ) NEW_LINE root . right = newnode ( 2 ) NEW_LINE root . left . left = newnode ( 3 ) NEW_LINE connect ( root ) NEW_LINE print ( " Following ▁ are ▁ populated ▁ nextRight " , " pointers ▁ in ▁ the ▁ tree ▁ ( -1 ▁ is ▁ printed " , " if ▁ there ▁ is ▁ no ▁ nextRight ) " ) NEW_LINE print ( " nextRight ▁ of " , root . data , " is ▁ " , end = " " ) NEW_LINE if root . nextRight : NEW_LINE INDENT print ( root . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT print ( " nextRight ▁ of " , root . left . data , " is ▁ " , end = " " ) NEW_LINE if root . left . nextRight : NEW_LINE INDENT print ( root . left . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT print ( " nextRight ▁ of " , root . right . data , " is ▁ " , end = " " ) NEW_LINE if root . right . nextRight : NEW_LINE INDENT print ( root . right . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT print ( " nextRight ▁ of " , root . left . left . data , " is ▁ " , end = " " ) NEW_LINE if root . left . left . nextRight : NEW_LINE INDENT print ( root . left . left . nextRight . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Base condition ; A participant can choose to consider ( 1 ) Remains single . Number of people reduce to ( x - 1 ) ( 2 ) Pairs with one of the ( x - 1 ) others . For every pairing , number of people reduce to ( x - 2 ) . ; Driver code
def numberOfWays ( x ) : NEW_LINE INDENT if x == 0 or x == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( numberOfWays ( x - 1 ) + ( x - 1 ) * numberOfWays ( x - 2 ) ) NEW_LINE DEDENT DEDENT x = 3 NEW_LINE print ( numberOfWays ( x ) ) NEW_LINE
Counting pairs when a person can form pair with at most one | Python program to find Number of ways in which participant can take part . ; Driver code
def numberOfWays ( x ) : NEW_LINE INDENT dp = [ ] NEW_LINE dp . append ( 1 ) NEW_LINE dp . append ( 1 ) NEW_LINE for i in range ( 2 , x + 1 ) : NEW_LINE INDENT dp . append ( dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ) NEW_LINE DEDENT return ( dp [ x ] ) NEW_LINE DEDENT x = 3 NEW_LINE print ( numberOfWays ( x ) ) NEW_LINE
Longest Repeated Subsequence | Refer https : www . geeksforgeeks . org / longest - repeating - subsequence / for complete code . This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; Create and initialize DP table ; Fill dp table ( similar to LCS loops ) ; If characters match and indices are not same ; If characters do not match
def findLongestRepeatingSubSeq ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE dp = [ [ 0 for k in range ( n + 1 ) ] for l in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ j - 1 ] and i != j ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ n ] NEW_LINE DEDENT
Number of ways to arrange N items under given constraints | Python3 program to find number of ways to arrange items under given constraint ; method returns number of ways with which items can be arranged ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; declare dp array to store result up to ith colored item ; variable to keep track of count of items considered till now ; loop over all different colors ; populate next value using current value and stated relation ; return value stored at last index ; Driver code
import numpy as np NEW_LINE def waysToArrange ( N , K , k ) : NEW_LINE INDENT C = np . zeros ( ( N + 1 , N + 1 ) ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = ( C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT dp = np . zeros ( ( K + 1 ) ) NEW_LINE count = 0 NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( K ) : NEW_LINE INDENT dp [ i + 1 ] = ( dp [ i ] * C [ count + k [ i ] - 1 ] [ k [ i ] - 1 ] ) NEW_LINE count += k [ i ] NEW_LINE DEDENT return dp [ K ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE k = [ 2 , 2 ] NEW_LINE K = len ( k ) NEW_LINE print ( int ( waysToArrange ( N , K , k ) ) ) NEW_LINE DEDENT
Minimum cells required to reach destination with jumps equal to cell values | Python3 implementation to count minimum cells required to be covered to reach destination ; function to count minimum cells required to be covered to reach destination ; to store min cells required to be covered to reach a particular cell ; base case ; building up the dp [ ] [ ] matrix ; dp [ i ] [ j ] != MAX denotes that cell ( i , j ) can be reached from cell ( 0 , 0 ) and the other half of the condition finds the cell on the right that can be reached from ( i , j ) ; the other half of the condition finds the cell right below that can be reached from ( i , j ) ; it true then cell ( m - 1 , n - 1 ) can be reached from cell ( 0 , 0 ) and returns the minimum number of cells covered ; cell ( m - 1 , n - 1 ) cannot be reached from cell ( 0 , 0 ) ; Driver program to test above
SIZE = 100 NEW_LINE MAX = 10000000 NEW_LINE def minCells ( mat , m , n ) : NEW_LINE INDENT dp = [ [ MAX for i in range ( n ) ] for i in range ( m ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( dp [ i ] [ j ] != MAX and ( j + mat [ i ] [ j ] ) < n and ( dp [ i ] [ j ] + 1 ) < dp [ i ] [ j + mat [ i ] [ j ] ] ) : NEW_LINE INDENT dp [ i ] [ j + mat [ i ] [ j ] ] = dp [ i ] [ j ] + 1 NEW_LINE DEDENT if ( dp [ i ] [ j ] != MAX and ( i + mat [ i ] [ j ] ) < m and ( dp [ i ] [ j ] + 1 ) < dp [ i + mat [ i ] [ j ] ] [ j ] ) : NEW_LINE INDENT dp [ i + mat [ i ] [ j ] ] [ j ] = dp [ i ] [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT if ( dp [ m - 1 ] [ n - 1 ] != MAX ) : NEW_LINE INDENT return dp [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT mat = [ [ 2 , 3 , 2 , 1 , 4 ] , [ 3 , 2 , 5 , 8 , 2 ] , [ 1 , 1 , 2 , 2 , 1 ] ] NEW_LINE m = 3 NEW_LINE n = 5 NEW_LINE print ( " Minimum ▁ number ▁ of ▁ cells ▁ = ▁ " , minCells ( mat , m , n ) ) NEW_LINE
Find longest bitonic sequence such that increasing and decreasing parts are from two different arrays | Python3 to find largest bitonic sequence such that ; utility Binary search ; function to find LIS in reverse form ; leN = 1 it will always poto empty location ; new smallest value ; arr [ i ] wants to extend largest subsequence ; arr [ i ] wants to be a potential candidate of future subsequence It will replace ceil value in tailIndices ; put LIS into vector ; function for finding longest bitonic seq ; find LIS of array 1 in reverse form ; reverse res to get LIS of first array ; reverse array2 and find its LIS ; print result ; Driver program
res = [ ] NEW_LINE def GetCeilIndex ( arr , T , l , r , key ) : NEW_LINE INDENT while ( r - l > 1 ) : NEW_LINE INDENT m = l + ( r - l ) // 2 ; NEW_LINE if ( arr [ T [ m ] ] >= key ) : NEW_LINE INDENT r = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m NEW_LINE DEDENT DEDENT return r NEW_LINE DEDENT def LIS ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ tailIndices [ 0 ] ] ) : NEW_LINE INDENT tailIndices [ 0 ] = i NEW_LINE DEDENT elif ( arr [ i ] > arr [ tailIndices [ leN - 1 ] ] ) : NEW_LINE INDENT prevIndices [ i ] = tailIndices [ leN - 1 ] NEW_LINE tailIndices [ leN ] = i NEW_LINE leN += 1 NEW_LINE DEDENT else : NEW_LINE INDENT pos = GetCeilIndex ( arr , tailIndices , - 1 , leN - 1 , arr [ i ] ) NEW_LINE prevIndices [ i ] = tailIndices [ pos - 1 ] NEW_LINE tailIndices [ pos ] = i NEW_LINE DEDENT DEDENT i = tailIndices [ leN - 1 ] NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT res . append ( arr [ i ] ) NEW_LINE i = prevIndices [ i ] NEW_LINE DEDENT DEDENT def longestBitonic ( arr1 , n1 , arr2 , n2 ) : NEW_LINE INDENT global res NEW_LINE LIS ( arr1 , n1 ) NEW_LINE res = res [ : : - 1 ] NEW_LINE arr2 = arr2 [ : : - 1 ] NEW_LINE LIS ( arr2 , n2 ) NEW_LINE for i in res : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr1 = [ 1 , 2 , 4 , 3 , 2 ] NEW_LINE arr2 = [ 8 , 6 , 4 , 7 , 8 , 9 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE n2 = len ( arr2 ) NEW_LINE longestBitonic ( arr1 , n1 , arr2 , n2 ) ; NEW_LINE
Maximize the binary matrix by filpping submatrix once | Python 3 program to find maximum number of ones after one flipping in Binary Matrix ; Return number of ones in square submatrix of size k x k starting from ( x , y ) ; Return maximum number of 1 s after flipping a submatrix ; Precomputing the number of 1 s ; Finding the maximum number of 1 s after flipping ; Driver code
R = 3 NEW_LINE C = 3 NEW_LINE def cal ( ones , x , y , k ) : NEW_LINE INDENT return ( ones [ x + k - 1 ] [ y + k - 1 ] - ones [ x - 1 ] [ y + k - 1 ] - ones [ x + k - 1 ] [ y - 1 ] + ones [ x - 1 ] [ y - 1 ] ) NEW_LINE DEDENT def sol ( mat ) : NEW_LINE INDENT ans = 0 NEW_LINE ones = [ [ 0 for i in range ( C + 1 ) ] for i in range ( R + 1 ) ] NEW_LINE for i in range ( 1 , R + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , C + 1 , 1 ) : NEW_LINE INDENT ones [ i ] [ j ] = ( ones [ i - 1 ] [ j ] + ones [ i ] [ j - 1 ] - ones [ i - 1 ] [ j - 1 ] + ( mat [ i - 1 ] [ j - 1 ] == 1 ) ) NEW_LINE DEDENT DEDENT for k in range ( 1 , min ( R , C ) + 1 , 1 ) : NEW_LINE INDENT for i in range ( 1 , R - k + 2 , 1 ) : NEW_LINE INDENT for j in range ( 1 , C - k + 2 , 1 ) : NEW_LINE INDENT ans = max ( ans , ( ones [ R ] [ C ] + k * k - 2 * cal ( ones , i , j , k ) ) ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 0 , 1 ] , [ 0 , 0 , 1 ] , [ 1 , 0 , 1 ] ] NEW_LINE print ( sol ( mat ) ) NEW_LINE DEDENT
Level with maximum number of nodes | Python3 implementation to find the level having Maximum number of Nodes Importing Queue ; Helper class that allocates a new node with the given data and None left and right pointers . ; function to find the level having Maximum number of Nodes ; Current level ; Maximum Nodes at same level ; Level having Maximum Nodes ; Count Nodes in a level ; If it is Maximum till now Update level_no to current level ; Pop complete current level ; Increment for next level ; Driver Code ; binary tree formation 2 ; / \ ; 1 3 ; / \ \ ; 4 6 8 ; / ; 5 ;
from queue import Queue 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 DEDENT DEDENT def maxNodeLevel ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE level = 0 NEW_LINE Max = - 999999999999 NEW_LINE level_no = 0 NEW_LINE while ( 1 ) : NEW_LINE INDENT NodeCount = q . qsize ( ) NEW_LINE if ( NodeCount == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( NodeCount > Max ) : NEW_LINE INDENT Max = NodeCount NEW_LINE level_no = level NEW_LINE DEDENT while ( NodeCount > 0 ) : NEW_LINE INDENT Node = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( Node . left != None ) : NEW_LINE INDENT q . put ( Node . left ) NEW_LINE DEDENT if ( Node . right != None ) : NEW_LINE INDENT q . put ( Node . right ) NEW_LINE DEDENT NodeCount -= 1 NEW_LINE DEDENT level += 1 NEW_LINE DEDENT return level_no NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 8 ) NEW_LINE root . left . right . left = newNode ( 5 ) NEW_LINE print ( " Level ▁ having ▁ Maximum ▁ number ▁ of ▁ Nodes ▁ : ▁ " , maxNodeLevel ( root ) ) NEW_LINE DEDENT
Minimum steps to minimize n as per given condition | A tabulation based solution in Python3 ; driver program
def getMinSteps ( n ) : NEW_LINE INDENT table = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT table [ i ] = n - i NEW_LINE DEDENT for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( not ( i % 2 ) ) : NEW_LINE INDENT table [ i // 2 ] = min ( table [ i ] + 1 , table [ i // 2 ] ) NEW_LINE DEDENT if ( not ( i % 3 ) ) : NEW_LINE INDENT table [ i // 3 ] = min ( table [ i ] + 1 , table [ i // 3 ] ) NEW_LINE DEDENT DEDENT return table [ 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 14 NEW_LINE print ( getMinSteps ( n ) ) NEW_LINE DEDENT
How to solve a Dynamic Programming Problem ? | Returns the number of arrangements to form 'n ; Base case
' NEW_LINE def solve ( n ) : NEW_LINE INDENT if n < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( solve ( n - 1 ) + solve ( n - 3 ) + solve ( n - 5 ) ) NEW_LINE DEDENT
Maximum points collected by two persons allowed to meet once | Python program to find maximum points that can be collected by two persons in a matrix . ; To store points collected by Person P1 when he / she begins journy from start and from end . ; To store points collected by Person P2 when he / she begins journey from start and from end . ; Table for P1 's journey from start to meeting cell ; Table for P1 's journey from end to meet cell ; Table for P2 's journey from start to meeting cell ; Table for P2 's journey from end to meeting cell ; Now iterate over all meeting positions ( i , j ) ;
M = 3 NEW_LINE N = 3 NEW_LINE def findMaxPoints ( A ) : NEW_LINE INDENT P1S = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE P1E = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE P2S = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE P2E = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 ) : NEW_LINE INDENT P1S [ i ] [ j ] = max ( P1S [ i - 1 ] [ j ] , P1S [ i ] [ j - 1 ] ) + A [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( N , 0 , - 1 ) : NEW_LINE INDENT for j in range ( M , 0 , - 1 ) : NEW_LINE INDENT P1E [ i ] [ j ] = max ( P1E [ i + 1 ] [ j ] , P1E [ i ] [ j + 1 ] ) + A [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( N , 0 , - 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 ) : NEW_LINE INDENT P2S [ i ] [ j ] = max ( P2S [ i + 1 ] [ j ] , P2S [ i ] [ j - 1 ] ) + A [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( M , 0 , - 1 ) : NEW_LINE INDENT P2E [ i ] [ j ] = max ( P2E [ i - 1 ] [ j ] , P2E [ i ] [ j + 1 ] ) + A [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT for j in range ( 2 , M ) : NEW_LINE INDENT op1 = P1S [ i ] [ j - 1 ] + P1E [ i ] [ j + 1 ] + P2S [ i + 1 ] [ j ] + P2E [ i - 1 ] [ j ] NEW_LINE op2 = P1S [ i - 1 ] [ j ] + P1E [ i + 1 ] [ j ] + P2S [ i ] [ j - 1 ] + P2E [ i ] [ j + 1 ] NEW_LINE ans = max ( ans , max ( op1 , op2 ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT / * input the calories burnt matrix * / NEW_LINE A = [ [ 100 , 100 , 100 ] , [ 100 , 1 , 100 ] , [ 100 , 100 , 100 ] ] NEW_LINE print ( " Max ▁ Points ▁ : ▁ " , findMaxPoints ( A ) ) NEW_LINE
Longest subsequence such that difference between adjacents is one | Function to find the length of longest subsequence ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Start traversing the given array ; Compare with all the previous elements ; If the element is consecutive then consider this subsequence and update dp [ i ] if required . ; Longest length will be the maximum value of dp array . ; Driver code ; Longest subsequence with one difference is { 1 , 2 , 3 , 4 , 3 , 2 }
def longestSubseqWithDiffOne ( arr , n ) : NEW_LINE INDENT dp = [ 1 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ i ] == arr [ j ] + 1 ) or ( arr [ i ] == arr [ j ] - 1 ) ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT result = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( result < dp [ i ] ) : NEW_LINE INDENT result = dp [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print longestSubseqWithDiffOne ( arr , n ) NEW_LINE
Non | A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Returns count of ways to connect n points on a circle such that no two connecting lines cross each other and every point is connected with one other point . ; Throw error if n is odd ; Else return n / 2 'th Catalan number ; Driver Code
def catalanDP ( n ) : NEW_LINE INDENT catalan = [ 1 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT catalan [ i ] = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT catalan [ i ] += ( catalan [ j ] * catalan [ i - j - 1 ] ) NEW_LINE DEDENT DEDENT return catalan [ n ] NEW_LINE DEDENT def countWays ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE return 0 NEW_LINE DEDENT return catalanDP ( n // 2 ) NEW_LINE DEDENT print ( countWays ( 6 ) ) NEW_LINE
Ways to arrange Balls such that adjacent balls are of different types | Python3 program to count number of ways to arrange three types of balls such that no two balls of same color are adjacent to each other ; table to store to store results of subproblems ; Returns count of arrangements where last placed ball is ' last ' . ' last ' is 0 for ' p ' , 1 for ' q ' and 2 for 'r ; if number of balls of any color becomes less than 0 the number of ways arrangements is 0. ; If last ball required is of type P and the number of balls of P type is 1 while number of balls of other color is 0 the number of ways is 1. ; Same case as above for ' q ' and 'r ; If this subproblem is already evaluated ; if last ball required is P and the number of ways is the sum of number of ways to form sequence with ' p - 1' P balls , q Q Balls and r R balls ending with Q and R . ; Same as above case for ' q ' and 'r ; ( last == 2 ) ; Returns count of required arrangements ; Three cases arise : Last required balls is type P Last required balls is type Q Last required balls is type R ; Driver Code
MAX = 100 ; NEW_LINE dp = [ [ [ [ - 1 ] * 4 for i in range ( MAX ) ] for j in range ( MAX ) ] for k in range ( MAX ) ] ; NEW_LINE ' NEW_LINE def countWays ( p , q , r , last ) : NEW_LINE INDENT if ( p < 0 or q < 0 or r < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( p == 1 and q == 0 and r == 0 and last == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( p == 0 and q == 1 and r == 0 and last == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( p == 0 and q == 0 and r == 1 and last == 2 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( dp [ p ] [ q ] [ r ] [ last ] != - 1 ) : NEW_LINE INDENT return dp [ p ] [ q ] [ r ] [ last ] ; NEW_LINE DEDENT if ( last == 0 ) : NEW_LINE INDENT dp [ p ] [ q ] [ r ] [ last ] = ( countWays ( p - 1 , q , r , 1 ) + countWays ( p - 1 , q , r , 2 ) ) ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT elif ( last == 1 ) : NEW_LINE INDENT dp [ p ] [ q ] [ r ] [ last ] = ( countWays ( p , q - 1 , r , 0 ) + countWays ( p , q - 1 , r , 2 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ p ] [ q ] [ r ] [ last ] = ( countWays ( p , q , r - 1 , 0 ) + countWays ( p , q , r - 1 , 1 ) ) ; NEW_LINE DEDENT return dp [ p ] [ q ] [ r ] [ last ] ; NEW_LINE DEDENT def countUtil ( p , q , r ) : NEW_LINE INDENT return ( countWays ( p , q , r , 0 ) + countWays ( p , q , r , 1 ) + countWays ( p , q , r , 2 ) ) ; NEW_LINE DEDENT p , q , r = 1 , 1 , 1 ; NEW_LINE print ( countUtil ( p , q , r ) ) ; NEW_LINE
Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Base cases ; countDer ( n ) = ( n - 1 ) [ countDer ( n - 1 ) + der ( n - 2 ) ] ; Driver Code
def countDer ( n ) : NEW_LINE INDENT if ( n == 1 ) : return 0 NEW_LINE if ( n == 2 ) : return 1 NEW_LINE return ( n - 1 ) * ( countDer ( n - 1 ) + countDer ( n - 2 ) ) NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count ▁ of ▁ Derangements ▁ is ▁ " , countDer ( n ) ) NEW_LINE
Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Create an array to store counts for subproblems ; Base cases ; Fill der [ 0. . n ] in bottom up manner using above recursive formula ; Return result for n ; Driver Code
def countDer ( n ) : NEW_LINE INDENT der = [ 0 for i in range ( n + 1 ) ] NEW_LINE der [ 1 ] = 0 NEW_LINE der [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) NEW_LINE DEDENT return der [ n ] NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count ▁ of ▁ Derangements ▁ is ▁ " , countDer ( n ) ) NEW_LINE
Find number of solutions of a linear equation of n variables | Returns count of solutions for given rhs and coefficients coeff [ 0. . . n - 1 ] ; Create and initialize a table to store results of subproblems ; Fill table in bottom up manner ; Driver Code
def countSol ( coeff , n , rhs ) : NEW_LINE INDENT dp = [ 0 for i in range ( rhs + 1 ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( coeff [ i ] , rhs + 1 ) : NEW_LINE INDENT dp [ j ] += dp [ j - coeff [ i ] ] NEW_LINE DEDENT DEDENT return dp [ rhs ] NEW_LINE DEDENT coeff = [ 2 , 2 , 5 ] NEW_LINE rhs = 4 NEW_LINE n = len ( coeff ) NEW_LINE print ( countSol ( coeff , n , rhs ) ) NEW_LINE
Largest value in each level of Binary Tree | Set | Python program to print largest value on each level of binary tree ; Helper function that allocates a new node with the given data and None left and right pointers . ; put in the data ; function to find largest values ; if tree is empty ; push root to the queue ' q ' ; node count for the current level ; if true then all the nodes of the tree have been traversed ; maximum element for the current level ; get the front element from 'q ; remove front element from 'q ; if true , then update 'max ; if left child exists ; if right child exists ; print maximum element of current level ; Driver Code ; Let us construct the following Tree 4 / \ 9 2 / \ \ 3 5 7 ; Function call
INT_MIN = - 2147483648 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 DEDENT DEDENT def largestValueInEachLevel ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE nc = 10 NEW_LINE max = 0 NEW_LINE q . append ( root ) NEW_LINE while ( 1 ) : NEW_LINE INDENT nc = len ( q ) NEW_LINE if ( nc == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT max = INT_MIN NEW_LINE while ( nc ) : NEW_LINE INDENT front = q [ 0 ] NEW_LINE q = q [ 1 : ] NEW_LINE if ( max < front . data ) : NEW_LINE INDENT max = front . data NEW_LINE DEDENT if ( front . left ) : NEW_LINE INDENT q . append ( front . left ) NEW_LINE DEDENT if ( front . right != None ) : NEW_LINE INDENT q . append ( front . right ) NEW_LINE DEDENT nc -= 1 NEW_LINE DEDENT print ( max , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 4 ) NEW_LINE root . left = newNode ( 9 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE largestValueInEachLevel ( root ) NEW_LINE DEDENT
Populate Inorder Successor for all nodes | Tree node ; Set next of p and all descendants of p by traversing them in reverse Inorder ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in left subtree ; UTILITY FUNCTIONS Helper function that allocates a new node with the given data and None left and right pointers . ; Driver Code Constructed binary tree is 10 / \ 8 12 / 3 ; Populates nextRight pointer in all nodes ; Let us see the populated values ; - 1 is printed if there is no successor
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 self . next = None NEW_LINE DEDENT DEDENT next = None NEW_LINE def populateNext ( p ) : NEW_LINE INDENT global next NEW_LINE if ( p != None ) : NEW_LINE INDENT populateNext ( p . right ) NEW_LINE p . next = next NEW_LINE next = p NEW_LINE populateNext ( p . left ) NEW_LINE DEDENT DEDENT def newnode ( data ) : NEW_LINE INDENT node = Node ( 0 ) NEW_LINE node . data = data NEW_LINE node . left = None NEW_LINE node . right = None NEW_LINE node . next = None NEW_LINE return ( node ) NEW_LINE DEDENT root = newnode ( 10 ) NEW_LINE root . left = newnode ( 8 ) NEW_LINE root . right = newnode ( 12 ) NEW_LINE root . left . left = newnode ( 3 ) NEW_LINE p = populateNext ( root ) NEW_LINE ptr = root . left . left NEW_LINE while ( ptr != None ) : NEW_LINE INDENT out = 0 NEW_LINE if ( ptr . next != None ) : NEW_LINE INDENT out = ptr . next . data NEW_LINE DEDENT else : NEW_LINE INDENT out = - 1 NEW_LINE DEDENT print ( " Next ▁ of " , ptr . data , " is " , out ) NEW_LINE ptr = ptr . next NEW_LINE DEDENT
Maximum Product Cutting | DP | The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver program to test above functions
def maxProd ( n ) : NEW_LINE INDENT if ( n == 2 or n == 3 ) : NEW_LINE INDENT return ( n - 1 ) NEW_LINE DEDENT res = 1 NEW_LINE while ( n > 4 ) : NEW_LINE INDENT n -= 3 ; NEW_LINE res *= 3 ; NEW_LINE DEDENT return ( n * res ) NEW_LINE DEDENT print ( " Maximum ▁ Product ▁ is ▁ " , maxProd ( 10 ) ) ; NEW_LINE
Dice Throw | DP | The main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are never used . ; Table entries for only one dice ; Fill rest of the entries in table using recursive relation i : number of dice , j : sum ; Return value ; Driver code
def findWays ( m , n , x ) : NEW_LINE INDENT table = [ [ 0 ] * ( x + 1 ) for i in range ( n + 1 ) ] NEW_LINE for j in range ( 1 , min ( m + 1 , x + 1 ) ) : NEW_LINE INDENT table [ 1 ] [ j ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , x + 1 ) : NEW_LINE INDENT for k in range ( 1 , min ( m + 1 , j ) ) : NEW_LINE INDENT table [ i ] [ j ] += table [ i - 1 ] [ j - k ] NEW_LINE DEDENT DEDENT DEDENT return table [ - 1 ] [ - 1 ] NEW_LINE DEDENT print ( findWays ( 4 , 2 , 1 ) ) NEW_LINE print ( findWays ( 2 , 2 , 3 ) ) NEW_LINE print ( findWays ( 6 , 3 , 8 ) ) NEW_LINE print ( findWays ( 4 , 2 , 5 ) ) NEW_LINE print ( findWays ( 4 , 3 , 5 ) ) NEW_LINE
Dice Throw | DP | * Count ways * * @ param f * @ param d * @ param s * @ return ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are never used . ; Table entries for no dices If you do not have any data , then the value must be 0 , so the result is 1 ; Iterate over dices ; Iterate over sum ; The result is obtained in two ways , pin the current dice and spending 1 of the value , so we have mem [ i - 1 ] [ j - 1 ] remaining combinations , to find the remaining combinations we would have to pin the values ? ? above 1 then we use mem [ i ] [ j - 1 ] to sum all combinations that pin the remaining j - 1 's. But there is a way, when "j-f-1> = 0" we would be adding extra combinations, so we remove the combinations that only pin the extrapolated dice face and subtract the extrapolated combinations. ; Driver code
def findWays ( f , d , s ) : NEW_LINE INDENT mem = [ [ 0 for i in range ( s + 1 ) ] for j in range ( d + 1 ) ] NEW_LINE mem [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , d + 1 ) : NEW_LINE INDENT for j in range ( 1 , s + 1 ) : NEW_LINE INDENT mem [ i ] [ j ] = mem [ i ] [ j - 1 ] + mem [ i - 1 ] [ j - 1 ] NEW_LINE if j - f - 1 >= 0 : NEW_LINE INDENT mem [ i ] [ j ] -= mem [ i - 1 ] [ j - f - 1 ] NEW_LINE DEDENT DEDENT DEDENT return mem [ d ] [ s ] NEW_LINE DEDENT print ( findWays ( 4 , 2 , 1 ) ) NEW_LINE print ( findWays ( 2 , 2 , 3 ) ) NEW_LINE print ( findWays ( 6 , 3 , 8 ) ) NEW_LINE print ( findWays ( 4 , 2 , 5 ) ) NEW_LINE print ( findWays ( 4 , 3 , 5 ) ) NEW_LINE
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver Code
import sys NEW_LINE def findMinInsertions ( str , l , h ) : NEW_LINE INDENT if ( l > h ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( l == h ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l == h - 1 ) : NEW_LINE INDENT return 0 if ( str [ l ] == str [ h ] ) else 1 NEW_LINE DEDENT if ( str [ l ] == str [ h ] ) : NEW_LINE INDENT return findMinInsertions ( str , l + 1 , h - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeks " NEW_LINE print ( findMinInsertions ( str , 0 , len ( str ) - 1 ) ) NEW_LINE DEDENT
Longest Palindromic Subsequence | DP | A utility function to get max of two egers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and last characters do not match ; Driver Code
def max ( x , y ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT return x NEW_LINE DEDENT return y NEW_LINE DEDENT def lps ( seq , i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( seq [ i ] == seq [ j ] and i + 1 == j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if ( seq [ i ] == seq [ j ] ) : NEW_LINE INDENT return lps ( seq , i + 1 , j - 1 ) + 2 NEW_LINE DEDENT return max ( lps ( seq , i , j - 1 ) , lps ( seq , i + 1 , j ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT seq = " GEEKSFORGEEKS " NEW_LINE n = len ( seq ) NEW_LINE print ( " The ▁ length ▁ of ▁ the ▁ LPS ▁ is " , lps ( seq , 0 , n - 1 ) ) NEW_LINE DEDENT
Smallest value in each level of Binary Tree | Python3 program to print smallest element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Inorder Traversal Search minimum element in each level and store it into vector array . ; height of tree for the size of vector array ; vector for store all minimum of every level ; save every level minimum using inorder traversal ; print every level minimum ; Utility function to create a new tree node ; Driver code ; Let us create binary tree shown in below diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
INT_MAX = 1000006 NEW_LINE 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 heightoftree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT left = heightoftree ( root . left ) ; NEW_LINE right = heightoftree ( root . right ) ; NEW_LINE return ( ( left if left > right else right ) + 1 ) ; NEW_LINE DEDENT def printPerLevelMinimum ( root , res , level ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT res = printPerLevelMinimum ( root . left , res , level + 1 ) ; NEW_LINE if ( root . data < res [ level ] ) : NEW_LINE INDENT res [ level ] = root . data ; NEW_LINE DEDENT res = printPerLevelMinimum ( root . right , res , level + 1 ) ; NEW_LINE DEDENT return res NEW_LINE DEDENT def perLevelMinimumUtility ( root ) : NEW_LINE INDENT n = heightoftree ( root ) NEW_LINE i = 0 NEW_LINE res = [ INT_MAX for i in range ( n ) ] NEW_LINE res = printPerLevelMinimum ( root , res , 0 ) ; NEW_LINE print ( " Every ▁ level ▁ minimum ▁ is " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ' level ▁ ' + str ( i ) + ' ▁ min ▁ is ▁ = ▁ ' + str ( res [ i ] ) ) NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 7 ) ; NEW_LINE root . left = newNode ( 6 ) ; NEW_LINE root . right = newNode ( 5 ) ; NEW_LINE root . left . left = newNode ( 4 ) ; NEW_LINE root . left . right = newNode ( 3 ) ; NEW_LINE root . right . left = newNode ( 2 ) ; NEW_LINE root . right . right = newNode ( 1 ) ; NEW_LINE perLevelMinimumUtility ( root ) ; NEW_LINE DEDENT
Smallest value in each level of Binary Tree | Python3 program to prminimum element in each level of binary tree . Importing Queue ; Utility class to create a new tree node ; return height of tree p ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order traversal ; put the root for Change the level ; for go level by level ; for check the level ; Get get of queue ; if node == None ( Means this is boundary between two levels ) ; here queue is empty represent no element in the actual queue ; increment level ; Reset min for next level minimum value ; get Minimum in every level ; Enqueue left child ; Enqueue right child ; Driver Code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
from queue import Queue NEW_LINE 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 heightoftree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = heightoftree ( root . left ) NEW_LINE right = heightoftree ( root . right ) NEW_LINE if left > right : NEW_LINE INDENT return left + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return right + 1 NEW_LINE DEDENT DEDENT def printPerLevelMinimum ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE q . put ( None ) NEW_LINE Min = 9999999999999 NEW_LINE level = 0 NEW_LINE while ( q . empty ( ) == False ) : NEW_LINE INDENT node = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( node == None ) : NEW_LINE INDENT print ( " level " , level , " min ▁ is ▁ = " , Min ) NEW_LINE if ( q . empty ( ) ) : NEW_LINE INDENT break NEW_LINE DEDENT q . put ( None ) NEW_LINE level += 1 NEW_LINE Min = 999999999999 NEW_LINE continue NEW_LINE DEDENT if ( Min > node . data ) : NEW_LINE INDENT Min = node . data NEW_LINE DEDENT if ( node . left != None ) : NEW_LINE INDENT q . put ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . put ( node . right ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 7 ) NEW_LINE root . left = newNode ( 6 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 2 ) NEW_LINE root . right . right = newNode ( 1 ) NEW_LINE print ( " Every ▁ Level ▁ minimum ▁ is " ) NEW_LINE printPerLevelMinimum ( root ) NEW_LINE DEDENT
Count occurrences of a string that can be constructed from another given string | Python3 implementation of the above approach ; Function to find the count ; Initialize hash for both strings ; hash the frequency of letters of str1 ; hash the frequency of letters of str2 ; Find the count of str2 constructed from str1 ; Return answer ; Driver code
import sys NEW_LINE def findCount ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE ans = sys . maxsize NEW_LINE hash1 = [ 0 ] * 26 NEW_LINE hash2 = [ 0 ] * 26 NEW_LINE for i in range ( 0 , len1 ) : NEW_LINE INDENT hash1 [ ord ( str1 [ i ] ) - 97 ] = hash1 [ ord ( str1 [ i ] ) - 97 ] + 1 NEW_LINE DEDENT for i in range ( 0 , len2 ) : NEW_LINE INDENT hash2 [ ord ( str2 [ i ] ) - 97 ] = hash2 [ ord ( str2 [ i ] ) - 97 ] + 1 NEW_LINE DEDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT if ( hash2 [ i ] != 0 ) : NEW_LINE INDENT ans = min ( ans , hash1 [ i ] // hash2 [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT str1 = " geeksclassesatnoida " NEW_LINE str2 = " sea " NEW_LINE print ( findCount ( str1 , str2 ) ) NEW_LINE
Check if a string is the typed name of the given name | Check if the character is vowel or not ; Returns true if ' typed ' is a typed name given str ; Traverse through all characters of str ; If current characters do not match ; If not vowel , simply move ahead in both ; Count occurrences of current vowel in str ; Count occurrence of current vowel in typed ; Driver code
def isVowel ( c ) : NEW_LINE INDENT vowel = " aeiou " NEW_LINE for i in range ( len ( vowel ) ) : NEW_LINE INDENT if ( vowel [ i ] == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printRLE ( str , typed ) : NEW_LINE INDENT n = len ( str ) NEW_LINE m = len ( typed ) NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str [ i ] != typed [ j ] : NEW_LINE INDENT return False NEW_LINE DEDENT if isVowel ( str [ i ] ) == False : NEW_LINE INDENT j = j + 1 NEW_LINE continue NEW_LINE DEDENT count1 = 1 NEW_LINE while ( i < n - 1 and ( str [ i ] == str [ i + 1 ] ) ) : NEW_LINE INDENT count1 = count1 + 1 NEW_LINE i = i + 1 NEW_LINE DEDENT count2 = 1 NEW_LINE while ( j < m - 1 and typed [ j ] == str [ i ] ) : NEW_LINE INDENT count2 = count2 + 1 NEW_LINE j = j + 1 NEW_LINE DEDENT if count1 > count2 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT name = " alex " NEW_LINE typed = " aaalaeex " NEW_LINE if ( printRLE ( name , typed ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Get Level of a node in a Binary Tree | Python3 program to Get Level of a node in a Binary Tree Helper function that allocates a new node with the given data and None left and right pairs . ; Constructor to create a new node ; Helper function for getLevel ( ) . It returns level of the data if data is present in tree , otherwise returns 0 ; Returns level of given data value ; Driver Code ; Let us construct the Tree shown in the above figure
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 getLevelUtil ( node , data , level ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . data == data ) : NEW_LINE INDENT return level NEW_LINE DEDENT downlevel = getLevelUtil ( node . left , data , level + 1 ) NEW_LINE if ( downlevel != 0 ) : NEW_LINE INDENT return downlevel NEW_LINE DEDENT downlevel = getLevelUtil ( node . right , data , level + 1 ) NEW_LINE return downlevel NEW_LINE DEDENT def getLevel ( node , data ) : NEW_LINE INDENT return getLevelUtil ( node , data , 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 3 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE for x in range ( 1 , 6 ) : NEW_LINE INDENT level = getLevel ( root , x ) NEW_LINE if ( level ) : NEW_LINE INDENT print ( " Level ▁ of " , x , " is " , getLevel ( root , x ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( x , " is ▁ not ▁ present ▁ in ▁ tree " ) NEW_LINE DEDENT DEDENT DEDENT
Program to replace a word with asterisks in a sentence | Function takes two parameter ; Break down sentence by ' ▁ ' spaces and store each individual word in a different list ; A new string to store the result ; Creating the censor which is an asterisks " * " text of the length of censor word ; count variable to access our word_list ; Iterating through our list of extracted words ; changing the censored word to created asterisks censor ; join the words ; Driver code
def censor ( text , word ) : NEW_LINE INDENT word_list = text . split ( ) NEW_LINE result = ' ' NEW_LINE stars = ' * ' * len ( word ) NEW_LINE count = 0 NEW_LINE index = 0 ; NEW_LINE for i in word_list : NEW_LINE INDENT if i == word : NEW_LINE INDENT word_list [ index ] = stars NEW_LINE DEDENT index += 1 NEW_LINE DEDENT result = ' ▁ ' . join ( word_list ) NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT extract = " GeeksforGeeks ▁ is ▁ a ▁ computer ▁ science ▁ portal ▁ for ▁ geeks . \ STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL I ▁ am ▁ pursuing ▁ my ▁ major ▁ in ▁ computer ▁ science . ▁ " NEW_LINE cen = " computer " NEW_LINE print ( censor ( extract , cen ) ) NEW_LINE DEDENT
Finite Automata algorithm for Pattern Searching | Python program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function
NO_OF_CHARS = 256 NEW_LINE def getNextState ( pat , M , state , x ) : NEW_LINE INDENT if state < M and x == ord ( pat [ state ] ) : NEW_LINE INDENT return state + 1 NEW_LINE DEDENT i = 0 NEW_LINE for ns in range ( state , 0 , - 1 ) : NEW_LINE INDENT if ord ( pat [ ns - 1 ] ) == x : NEW_LINE INDENT while ( i < ns - 1 ) : NEW_LINE INDENT if pat [ i ] != pat [ state - ns + 1 + i ] : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if i == ns - 1 : NEW_LINE INDENT return ns NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT def computeTF ( pat , M ) : NEW_LINE INDENT global NO_OF_CHARS NEW_LINE TF = [ [ 0 for i in range ( NO_OF_CHARS ) ] \ for _ in range ( M + 1 ) ] NEW_LINE for state in range ( M + 1 ) : NEW_LINE INDENT for x in range ( NO_OF_CHARS ) : NEW_LINE INDENT z = getNextState ( pat , M , state , x ) NEW_LINE TF [ state ] [ x ] = z NEW_LINE DEDENT DEDENT return TF NEW_LINE DEDENT def search ( pat , txt ) : NEW_LINE INDENT global NO_OF_CHARS NEW_LINE M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE TF = computeTF ( pat , M ) NEW_LINE state = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT state = TF [ state ] [ ord ( txt [ i ] ) ] NEW_LINE if state == M : NEW_LINE INDENT print ( " Pattern ▁ found ▁ at ▁ index : ▁ { } " . format ( i - M + 1 ) ) NEW_LINE DEDENT DEDENT DEDENT def main ( ) : NEW_LINE INDENT txt = " AABAACAADAABAAABAA " NEW_LINE pat = " AABA " NEW_LINE search ( pat , txt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Longest Substring containing '1' | Function to find length of longest substring containing '1 ; Count the number of contiguous 1 's ; Driver Code
' NEW_LINE def maxlength ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count = 1 NEW_LINE j = i + 1 NEW_LINE while ( j <= n - 1 and s [ j ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE j += 1 NEW_LINE DEDENT ans = max ( ans , count ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT s = "11101110" ; NEW_LINE print ( maxlength ( s ) ) NEW_LINE
Generate all possible strings formed by replacing letters with given respective symbols | Function to generate all possible string by replacing the characters with mapped symbols ; Base Case ; Function call with the P - th character not replaced ; Replace the P - th character ; Function call with the P - th character replaced ; Driver Code ; Function Call
def generateLetters ( S , P , M ) : NEW_LINE INDENT if ( P == len ( S ) ) : NEW_LINE INDENT print ( S ) ; NEW_LINE return NEW_LINE DEDENT generateLetters ( S , P + 1 , M ) ; NEW_LINE S = S . replace ( S [ P ] , M [ S [ P ] ] ) NEW_LINE generateLetters ( S , P + 1 , M ) ; NEW_LINE DEDENT S = " aBc " ; NEW_LINE M = { } ; NEW_LINE M [ ' a ' ] = ' $ ' NEW_LINE M [ ' B ' ] = ' # ' NEW_LINE M [ ' c ' ] = ' ^ ' NEW_LINE M [ ' d ' ] = ' & ' NEW_LINE M [ '1' ] = ' * ' NEW_LINE M [ '2' ] = ' ! ' NEW_LINE M [ ' E ' ] = ' @ ' NEW_LINE generateLetters ( S , 0 , M ) ; NEW_LINE
Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same | Python3 program for the above approach ; Function to check if S contains any pair of adjacent characters that are same ; Traverse the String S ; If current pair of adjacent characters are the same ; Return true ; Utility function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; Check if the required String is formed already ; Traverse the String S ; Swap the characters at i and j position ; Swap for Backtracking Step ; Function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; Stores the resultant minimum number of swaps required ; Function call to find the minimum swaps required ; Prvar the result ; Driver code
import sys NEW_LINE ansSwaps = 0 NEW_LINE def check ( S ) : NEW_LINE INDENT for i in range ( 1 , len ( S ) ) : NEW_LINE INDENT if ( S [ i - 1 ] == S [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def minimumSwaps ( S , swaps , idx ) : NEW_LINE INDENT global ansSwaps NEW_LINE if ( check ( S ) ) : NEW_LINE INDENT ansSwaps = 1 + min ( ansSwaps , swaps ) NEW_LINE DEDENT for i in range ( idx , len ( S ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( S ) ) : NEW_LINE INDENT swap ( S , i , j ) NEW_LINE minimumSwaps ( S , swaps + 1 , i + 1 ) NEW_LINE S = swap ( S , i , j ) NEW_LINE DEDENT DEDENT DEDENT def swap ( arr , i , j ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = temp NEW_LINE return arr NEW_LINE DEDENT def findMinimumSwaps ( S ) : NEW_LINE INDENT global ansSwaps NEW_LINE ansSwaps = sys . maxsize NEW_LINE minimumSwaps ( S , 0 , 0 ) NEW_LINE if ( ansSwaps == sys . maxsize ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ansSwaps ) NEW_LINE DEDENT DEDENT S = " ABAACD " NEW_LINE findMinimumSwaps ( S . split ( ) ) NEW_LINE
Get level of a node in binary tree | iterative approach | Python3 program to find closest value in Binary search Tree ; Helper function that allocates a new node with the given data and None left and right poers . ; utility function to return level of given node ; extra None is appended to keep track of all the nodes to be appended before level is incremented by 1 ; Driver Code ; create a binary tree ; return level of node
_MIN = - 2147483648 NEW_LINE _MAX = 2147483648 NEW_LINE class getnode : 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 getlevel ( root , data ) : NEW_LINE INDENT q = [ ] NEW_LINE level = 1 NEW_LINE q . append ( root ) NEW_LINE q . append ( None ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( temp == None ) : NEW_LINE INDENT if len ( q ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( q [ 0 ] != None ) : NEW_LINE INDENT q . append ( None ) NEW_LINE DEDENT level += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( temp . data == data ) : NEW_LINE INDENT return level NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getnode ( 20 ) NEW_LINE root . left = getnode ( 10 ) NEW_LINE root . right = getnode ( 30 ) NEW_LINE root . left . left = getnode ( 5 ) NEW_LINE root . left . right = getnode ( 15 ) NEW_LINE root . left . right . left = getnode ( 12 ) NEW_LINE root . right . left = getnode ( 25 ) NEW_LINE root . right . right = getnode ( 40 ) NEW_LINE level = getlevel ( root , 30 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 30 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 30 ▁ not ▁ found " ) NEW_LINE DEDENT level = getlevel ( root , 12 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 12 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 12 ▁ not ▁ found " ) NEW_LINE DEDENT level = getlevel ( root , 25 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 25 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 25 ▁ not ▁ found " ) NEW_LINE DEDENT level = getlevel ( root , 27 ) NEW_LINE if level != 0 : NEW_LINE INDENT print ( " level ▁ of ▁ node ▁ 27 ▁ is " , level ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " node ▁ 27 ▁ not ▁ found " ) NEW_LINE DEDENT DEDENT
Lexicographically smallest Palindromic Path in a Binary Tree | Struct binary tree node ; Function to check if the is palindrome or not ; Function to find the lexicographically smallest palindromic path in the Binary Tree ; Base case ; Append current node 's data to the string ; Check if a node is leaf or not ; Check for the 1 st Palindromic Path ; Store lexicographically the smallest palindromic path ; Recursively traverse left subtree ; Recursively traverse right subtree ; Function to get smallest lexographical palindromic path ; Variable which stores the final result ; Function call to compute lexicographically smallest palindromic Path ; Driver Code ; Construct binary tree
class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def checkPalindrome ( s ) : NEW_LINE INDENT low , high = 0 , len ( s ) - 1 NEW_LINE while ( low < high ) : NEW_LINE INDENT if ( s [ low ] != s [ high ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def lexicographicallySmall ( root , s ) : NEW_LINE INDENT global finalAns NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT s += root . data NEW_LINE if ( not root . left and not root . right ) : NEW_LINE INDENT if ( checkPalindrome ( s ) ) : NEW_LINE INDENT if ( finalAns == " $ " ) : NEW_LINE INDENT finalAns = s NEW_LINE DEDENT else : NEW_LINE INDENT finalAns = min ( finalAns , s ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT lexicographicallySmall ( root . left , s ) NEW_LINE lexicographicallySmall ( root . right , s ) NEW_LINE DEDENT def getPalindromePath ( root ) : NEW_LINE INDENT global finalAns NEW_LINE finalAns = " $ " NEW_LINE lexicographicallySmall ( root , " " ) NEW_LINE if ( finalAns == " $ " ) : NEW_LINE INDENT print ( " No ▁ Palindromic ▁ Path ▁ exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( finalAns ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT finalAns = " " NEW_LINE root = Node ( ' a ' ) NEW_LINE root . left = Node ( ' c ' ) NEW_LINE root . left . left = Node ( ' a ' ) NEW_LINE root . left . right = Node ( ' g ' ) NEW_LINE root . right = Node ( ' b ' ) NEW_LINE root . right . left = Node ( ' b ' ) NEW_LINE root . right . right = Node ( ' x ' ) NEW_LINE root . right . left . right = Node ( ' a ' ) NEW_LINE getPalindromePath ( root ) NEW_LINE DEDENT
Find mirror of a given node in Binary tree | Python3 program to find the mirror node in Binary tree ; A binary tree node has data , reference to left child and a reference to right child ; recursive function to find mirror ; If any of the node is none then node itself and decendent have no mirror , so return none , no need to further explore ! ; if left node is target node , then return right 's key (that is mirror) and vice versa ; first recur external nodes ; if no mirror found , recur internal nodes ; interface for mirror search ; Driver ; target node whose mirror have to be searched
class Node : NEW_LINE INDENT def __init__ ( self , key , lchild = None , rchild = None ) : NEW_LINE INDENT self . key = key NEW_LINE self . lchild = None NEW_LINE self . rchild = None NEW_LINE DEDENT DEDENT def findMirrorRec ( target , left , right ) : NEW_LINE INDENT if left == None or right == None : NEW_LINE INDENT return None NEW_LINE DEDENT if left . key == target : NEW_LINE INDENT return right . key NEW_LINE DEDENT if right . key == target : NEW_LINE INDENT return left . key NEW_LINE DEDENT mirror_val = findMirrorRec ( target , left . lchild , right . rchild ) NEW_LINE if mirror_val != None : NEW_LINE INDENT return mirror_val NEW_LINE DEDENT findMirrorRec ( target , left . rchild , right . lchild ) NEW_LINE DEDENT def findMirror ( root , target ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return None NEW_LINE DEDENT if root . key == target : NEW_LINE INDENT return target NEW_LINE DEDENT return findMirrorRec ( target , root . lchild , root . rchild ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE n1 = Node ( 2 ) NEW_LINE n2 = Node ( 3 ) NEW_LINE root . lchild = n1 NEW_LINE root . rchild = n2 NEW_LINE n3 = Node ( 4 ) NEW_LINE n4 = Node ( 5 ) NEW_LINE n5 = Node ( 6 ) NEW_LINE n1 . lchild = n3 NEW_LINE n2 . lchild = n4 NEW_LINE n2 . rchild = n5 NEW_LINE n6 = Node ( 7 ) NEW_LINE n7 = Node ( 8 ) NEW_LINE n8 = Node ( 9 ) NEW_LINE n3 . rchild = n6 NEW_LINE n4 . lchild = n7 NEW_LINE n4 . rchild = n8 NEW_LINE target = n3 . key NEW_LINE mirror = findMirror ( root , target ) NEW_LINE print ( " Mirror ▁ of ▁ node ▁ { } ▁ is ▁ node ▁ { } " . format ( target , mirror ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Smallest substring with each letter occurring both in uppercase and lowercase | python 3 program for the above approach ; Function to check if the current string is balanced or not ; For every character , check if there exists uppercase as well as lowercase characters ; Function to find smallest length substring in the given string which is balanced ; Store frequency of lowercase characters ; Stores frequency of uppercase characters ; Count frequency of characters ; Mark those characters which are not present in both lowercase and uppercase ; Initialize the frequencies back to 0 ; Marks the start and end of current substring ; Marks the start and end of required substring ; Stores the length of smallest balanced substring ; Remove all characters obtained so far ; Remove extra characters from front of the current substring ; If substring ( st , i ) is balanced ; No balanced substring ; Store answer string ; Driver Code ; Given string
import sys NEW_LINE def balanced ( small , caps ) : NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT if ( small [ i ] != 0 and ( caps [ i ] == 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( ( small [ i ] == 0 ) and ( caps [ i ] != 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def smallestBalancedSubstring ( s ) : NEW_LINE INDENT small = [ 0 for i in range ( 26 ) ] NEW_LINE caps = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) >= 65 and ord ( s [ i ] ) <= 90 ) : NEW_LINE INDENT caps [ ord ( s [ i ] ) - 65 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT small [ ord ( s [ i ] ) - 97 ] += 1 NEW_LINE DEDENT DEDENT mp = { } NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( small [ i ] and caps [ i ] == 0 ) : NEW_LINE INDENT mp [ chr ( i + 97 ) ] = 1 NEW_LINE DEDENT elif ( caps [ i ] and small [ i ] == 0 ) : NEW_LINE INDENT mp [ chr ( i + 65 ) ] = 1 NEW_LINE DEDENT DEDENT for i in range ( len ( small ) ) : NEW_LINE INDENT small [ i ] = 0 NEW_LINE caps [ i ] = 0 NEW_LINE DEDENT i = 0 NEW_LINE st = 0 NEW_LINE start = - 1 NEW_LINE end = - 1 NEW_LINE minm = sys . maxsize NEW_LINE while ( i < len ( s ) ) : NEW_LINE INDENT if ( s [ i ] in mp ) : NEW_LINE INDENT while ( st < i ) : NEW_LINE INDENT if ( ord ( s [ st ] ) >= 65 and ord ( s [ st ] ) <= 90 ) : NEW_LINE INDENT caps [ ord ( s [ st ] ) - 65 ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT small [ ord ( s [ st ] ) - 97 ] -= 1 NEW_LINE DEDENT st += 1 NEW_LINE DEDENT i += 1 NEW_LINE st = i NEW_LINE DEDENT else : NEW_LINE INDENT if ( ord ( s [ i ] ) >= 65 and ord ( s [ i ] ) <= 90 ) : NEW_LINE INDENT caps [ ord ( s [ i ] ) - 65 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT small [ ord ( s [ i ] ) - 97 ] += 1 NEW_LINE DEDENT while ( 1 ) : NEW_LINE INDENT if ( ord ( s [ st ] ) >= 65 and ord ( s [ st ] ) <= 90 and caps [ ord ( s [ st ] ) - 65 ] > 1 ) : NEW_LINE INDENT caps [ ord ( s [ st ] ) - 65 ] -= 1 NEW_LINE st += 1 NEW_LINE DEDENT elif ( ord ( s [ st ] ) >= 97 and ord ( s [ st ] ) <= 122 and small [ ord ( s [ st ] ) - 97 ] > 1 ) : NEW_LINE INDENT small [ ord ( s [ st ] ) - 97 ] -= 1 NEW_LINE st += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( balanced ( small , caps ) ) : NEW_LINE INDENT if ( minm > ( i - st + 1 ) ) : NEW_LINE INDENT minm = i - st + 1 NEW_LINE start = st NEW_LINE end = i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT if ( start == - 1 or end == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = " " NEW_LINE for i in range ( start , end + 1 , 1 ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " azABaabba " NEW_LINE smallestBalancedSubstring ( s ) NEW_LINE DEDENT
Convert given string to another by minimum replacements of subsequences by its smallest character | Function to return the minimum number of operation ; Storing data ; Initialize both arrays ; Stores the index of character ; Filling str1array , convChar and hashmap convertMap . ; Not possible to convert ; Calculate result Initializing return values ; Iterating the character from the end ; Increment the number of operations ; Not possible to convert ; To check whether the final element has been added in set S or not . ; Check if v1 [ j ] is present in hashmap or not ; Already converted then then continue ; Not possible to convert ; Print the result ; Given strings ; Function call
def transformString ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE convChar = [ ] NEW_LINE str1array = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT convChar . append ( [ ] ) NEW_LINE str1array . append ( [ ] ) NEW_LINE DEDENT convertMap = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT str1array [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( str1 [ i ] < str2 [ i ] ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT elif ( str1 [ i ] == str2 [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT convChar [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE convertMap [ i ] = str2 [ i ] NEW_LINE DEDENT DEDENT ret = 0 NEW_LINE retv = [ ] NEW_LINE for i in range ( 25 , - 1 , - 1 ) : NEW_LINE INDENT v = convChar [ i ] NEW_LINE if ( len ( v ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ret += 1 ; NEW_LINE v1 = str1array [ i ] NEW_LINE if ( len ( v1 ) == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT isScompleted = False NEW_LINE for j in range ( len ( v1 ) ) : NEW_LINE INDENT if ( v1 [ j ] in convertMap ) : NEW_LINE INDENT a = v1 [ j ] NEW_LINE if ( a > i + ord ( ' a ' ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( v1 [ j ] ) NEW_LINE isScompleted = True NEW_LINE retv . append ( v ) NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT v . append ( v1 [ j ] ) NEW_LINE isScompleted = True NEW_LINE retv . append ( v ) NEW_LINE break NEW_LINE DEDENT DEDENT if ( isScompleted == False ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( ret ) NEW_LINE DEDENT A = " abcab " NEW_LINE B = " aabab " NEW_LINE transformString ( A , B ) NEW_LINE
Find largest subtree having identical left and right subtrees | Helper class that allocates a new node with the given data and None left and right pointers . ; Sets maxSize to size of largest subtree with identical left and right . maxSize is set with size of the maximum sized subtree . It returns size of subtree rooted with current node . This size is used to keep track of maximum size . ; string to store structure of left and right subtrees ; traverse left subtree and finds its size ; traverse right subtree and finds its size ; if left and right subtrees are similar update maximum subtree if needed ( Note that left subtree may have a bigger value than right and vice versa ) ; append left subtree data ; append current node data ; append right subtree data ; function to find the largest subtree having identical left and right subtree ; Driver Code ; Let us construct the following Tree 50 / \ 10 60 / \ / \ 5 20 70 70 / \ / \ 65 80 65 80
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 largestSubtreeUtil ( root , Str , maxSize , maxNode ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = [ " " ] NEW_LINE right = [ " " ] NEW_LINE ls = largestSubtreeUtil ( root . left , left , maxSize , maxNode ) NEW_LINE rs = largestSubtreeUtil ( root . right , right , maxSize , maxNode ) NEW_LINE size = ls + rs + 1 NEW_LINE if ( left [ 0 ] == right [ 0 ] ) : NEW_LINE INDENT if ( size > maxSize [ 0 ] ) : NEW_LINE INDENT maxSize [ 0 ] = size NEW_LINE maxNode [ 0 ] = root NEW_LINE DEDENT DEDENT Str [ 0 ] = Str [ 0 ] + " | " + left [ 0 ] + " | " NEW_LINE Str [ 0 ] = Str [ 0 ] + " | " + str ( root . data ) + " | " NEW_LINE Str [ 0 ] = Str [ 0 ] + " | " + right [ 0 ] + " | " NEW_LINE return size NEW_LINE DEDENT def largestSubtree ( node , maxNode ) : NEW_LINE INDENT maxSize = [ 0 ] NEW_LINE Str = [ " " ] NEW_LINE largestSubtreeUtil ( node , Str , maxSize , maxNode ) NEW_LINE return maxSize NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 50 ) NEW_LINE root . left = newNode ( 10 ) NEW_LINE root . right = newNode ( 60 ) NEW_LINE root . left . left = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 20 ) NEW_LINE root . right . left = newNode ( 70 ) NEW_LINE root . right . left . left = newNode ( 65 ) NEW_LINE root . right . left . right = newNode ( 80 ) NEW_LINE root . right . right = newNode ( 70 ) NEW_LINE root . right . right . left = newNode ( 65 ) NEW_LINE root . right . right . right = newNode ( 80 ) NEW_LINE maxNode = [ None ] NEW_LINE maxSize = largestSubtree ( root , maxNode ) NEW_LINE print ( " Largest ▁ Subtree ▁ is ▁ rooted ▁ at ▁ node ▁ " , maxNode [ 0 ] . data ) NEW_LINE print ( " and ▁ its ▁ size ▁ is ▁ " , maxSize ) NEW_LINE DEDENT
Smallest number containing all possible N length permutations using digits 0 to D | Initialize set to see if all the possible permutations are present in the min length string ; To keep min length string ; Generate the required string ; Iterate over all possible character ; Append to make a new string ; If the new string is not visited ; Add in set ; Call the dfs function on the last d characters ; Base case ; Append '0' n - 1 times ; Call the DFS Function ; Driver Code
visited = set ( ) NEW_LINE ans = [ ] NEW_LINE def dfs ( curr , D ) : NEW_LINE INDENT for c in range ( D ) : NEW_LINE INDENT c = str ( c ) NEW_LINE neighbour = curr + c NEW_LINE if neighbour not in visited : NEW_LINE INDENT visited . add ( neighbour ) NEW_LINE dfs ( neighbour [ 1 : ] , D ) NEW_LINE ans . append ( c ) NEW_LINE DEDENT DEDENT DEDENT def reqString ( N , D ) : NEW_LINE INDENT if ( N == 1 and D == 1 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT start = ' ' . join ( [ '0' ] * ( N - 1 ) ) NEW_LINE dfs ( start , D ) NEW_LINE ans . extend ( [ '0' ] * ( N - 1 ) ) NEW_LINE return ' ' . join ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , D = 2 , 2 NEW_LINE print ( reqString ( N , D ) ) NEW_LINE DEDENT
Check if a string is a scrambled form of another string | Python3 program to check if a given string is a scrambled form of another string ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Check for the condition of anagram ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ 0. . . i ] and if S2 [ i + 1. . . n ] is a scrambled string of S1 [ i + 1. . . n ] ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ n - i ... n ] and S2 [ i + 1. . . n ] is a scramble string of S1 [ 0. . . n - i - 1 ] ; If none of the above conditions are satisfied ; Driver Code
def isScramble ( S1 : str , S2 : str ) : NEW_LINE INDENT if len ( S1 ) != len ( S2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = len ( S1 ) NEW_LINE if not n : NEW_LINE INDENT return True NEW_LINE DEDENT if S1 == S2 : NEW_LINE INDENT return True NEW_LINE DEDENT if sorted ( S1 ) != sorted ( S2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( isScramble ( S1 [ : i ] , S2 [ : i ] ) and isScramble ( S1 [ i : ] , S2 [ i : ] ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( isScramble ( S1 [ - i : ] , S2 [ : i ] ) and isScramble ( S1 [ : - i ] , S2 [ i : ] ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S1 = " coder " NEW_LINE S2 = " ocred " NEW_LINE if ( isScramble ( S1 , S2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Smallest number possible by swapping adjacent even odd pairs | Function to return the smallest number possible ; Arrays to store odd and even digits in the order of their appearance in the given string ; Insert the odd and even digits ; pointer to odd digit ; pointer to even digit ; In case number of even and odd digits are not equal If odd digits are remaining ; If even digits are remaining ; Removal of leading 0 's ; Driver Code
def findAns ( s ) : NEW_LINE INDENT odd = [ ] NEW_LINE even = [ ] NEW_LINE for c in s : NEW_LINE INDENT digit = int ( c ) NEW_LINE if ( digit & 1 ) : NEW_LINE INDENT odd . append ( digit ) NEW_LINE DEDENT else : NEW_LINE INDENT even . append ( digit ) NEW_LINE DEDENT DEDENT i = 0 NEW_LINE j = 0 NEW_LINE ans = " " NEW_LINE while ( i < len ( odd ) and j < len ( even ) ) : NEW_LINE INDENT if ( odd [ i ] < even [ j ] ) : NEW_LINE INDENT ans += str ( odd [ i ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += str ( even [ j ] ) NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT while ( i < len ( odd ) ) : NEW_LINE INDENT ans += str ( odd [ i ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT while ( j < len ( even ) ) : NEW_LINE INDENT ans += str ( even [ j ] ) NEW_LINE j = j + 1 NEW_LINE DEDENT while ( ans [ 0 ] == '0' ) : NEW_LINE INDENT ans = ans [ 1 : ] NEW_LINE DEDENT return ans NEW_LINE DEDENT s = "894687536" NEW_LINE print ( findAns ( s ) ) NEW_LINE
Program to Convert BCD number into Decimal number | Function to convert BCD to Decimal ; Iterating through the bits backwards ; Forming the equivalent digit ( 0 to 9 ) from the group of 4. ; Reinitialize all variables and compute the number ; Update the answer ; Reverse the number formed . ; Driver Code ; Function Call
def bcdToDecimal ( s ) : NEW_LINE INDENT length = len ( s ) ; NEW_LINE check = 0 ; NEW_LINE check0 = 0 ; NEW_LINE num = 0 ; NEW_LINE sum = 0 ; NEW_LINE mul = 1 ; NEW_LINE rev = 0 ; NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += ( ord ( s [ i ] ) - ord ( '0' ) ) * mul ; NEW_LINE mul *= 2 ; NEW_LINE check += 1 ; NEW_LINE if ( check == 4 or i == 0 ) : NEW_LINE INDENT if ( sum == 0 and check0 == 0 ) : NEW_LINE INDENT num = 1 ; NEW_LINE check0 = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT num = num * 10 + sum ; NEW_LINE DEDENT check = 0 ; NEW_LINE sum = 0 ; NEW_LINE mul = 1 ; NEW_LINE DEDENT DEDENT while ( num > 0 ) : NEW_LINE INDENT rev = rev * 10 + ( num % 10 ) ; NEW_LINE num //= 10 ; NEW_LINE DEDENT if ( check0 == 1 ) : NEW_LINE INDENT return rev - 1 ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "100000101000" ; NEW_LINE print ( bcdToDecimal ( s ) ) ; NEW_LINE DEDENT
Find Count of Single Valued Subtrees | Utility function to create a new node ; This function increments count by number of single valued subtrees under root . It returns true if subtree under root is Singly , else false . ; Return False to indicate None ; Recursively count in left and right subtress also ; If any of the subtress is not singly , then this cannot be singly ; If left subtree is singly and non - empty , but data doesn 't match ; same for right subtree ; If none of the above conditions is True , then tree rooted under root is single valued , increment count and return true ; This function mainly calss countSingleRec ( ) after initializing count as 0 ; initialize result ; Recursive function to count ; Let us construct the below tree 5 / \ 4 5 / \ \ 4 4 5
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 countSingleRec ( root , count ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT left = countSingleRec ( root . left , count ) NEW_LINE right = countSingleRec ( root . right , count ) NEW_LINE if left == False or right == False : NEW_LINE INDENT return False NEW_LINE DEDENT if root . left and root . data != root . left . data : NEW_LINE INDENT return False NEW_LINE DEDENT if root . right and root . data != root . right . data : NEW_LINE INDENT return False NEW_LINE DEDENT count [ 0 ] += 1 NEW_LINE return True NEW_LINE DEDENT def countSingle ( root ) : NEW_LINE INDENT count = [ 0 ] NEW_LINE countSingleRec ( root , count ) NEW_LINE return count [ 0 ] NEW_LINE DEDENT root = Node ( 5 ) NEW_LINE root . left = Node ( 4 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 4 ) NEW_LINE root . right . right = Node ( 5 ) NEW_LINE countSingle ( root ) NEW_LINE print " Count ▁ of ▁ Single ▁ Valued ▁ Subtress ▁ is " , countSingle ( root ) NEW_LINE
Count minimum swap to make string palindrome | Function to Count minimum swap ; Counter to count minimum swap ; A loop which run in half string from starting ; Left pointer ; Right pointer ; A loop which run from right pointer to left pointer ; if both char same then break the loop if not same then we have to move right pointer to one step left ; it denotes both pointer at same position and we don 't have sufficient char to make palindrome string ; Driver Code ; Length of string ; Function calling
def CountSwap ( s , n ) : NEW_LINE INDENT s = list ( s ) NEW_LINE count = 0 NEW_LINE ans = True NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT left = i NEW_LINE right = n - left - 1 NEW_LINE while left < right : NEW_LINE INDENT if s [ left ] == s [ right ] : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT DEDENT if left == right : NEW_LINE INDENT ans = False NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( right , n - left - 1 ) : NEW_LINE INDENT ( s [ j ] , s [ j + 1 ] ) = ( s [ j + 1 ] , s [ j ] ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT if ans : NEW_LINE INDENT return ( count ) NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT s = ' geeksfgeeks ' NEW_LINE n = len ( s ) NEW_LINE ans1 = CountSwap ( s , n ) NEW_LINE ans2 = CountSwap ( s [ : : - 1 ] , n ) NEW_LINE print ( max ( ans1 , ans2 ) ) NEW_LINE
Bitwise XOR of a Binary array | Function to return the bitwise XOR of all the binary strings ; Get max size and reverse each string Since we have to perform XOR operation on bits from right to left Reversing the string will make it easier to perform operation from left to right ; Add 0 s to the end of strings if needed ; Perform XOR operation on each bit ; Reverse the resultant string to get the final string ; Return the final string ; Driver code
import sys NEW_LINE def strBitwiseXOR ( arr , n ) : NEW_LINE INDENT result = " " NEW_LINE max_len = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_len = max ( max_len , len ( arr [ i ] ) ) NEW_LINE arr [ i ] = arr [ i ] [ : : - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT s = " " NEW_LINE for j in range ( max_len - len ( arr [ i ] ) ) : NEW_LINE INDENT s += "0" NEW_LINE DEDENT arr [ i ] = arr [ i ] + s NEW_LINE DEDENT for i in range ( max_len ) : NEW_LINE INDENT pres_bit = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT pres_bit = pres_bit ^ ( ord ( arr [ j ] [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT result += chr ( ( pres_bit ) + ord ( '0' ) ) NEW_LINE DEDENT result = result [ : : - 1 ] NEW_LINE print ( result ) NEW_LINE DEDENT if ( __name__ == " _ _ main _ _ " ) : NEW_LINE INDENT arr = [ "1000" , "10001" , "0011" ] NEW_LINE n = len ( arr ) NEW_LINE strBitwiseXOR ( arr , n ) NEW_LINE DEDENT
Count of sticks required to represent the given string | stick [ ] stores the count of matchsticks required to represent the alphabets ; number [ ] stores the count of matchsticks required to represent the numerals ; Function that return the count of sticks required to represent the given string ; For every char of the given string ; Add the count of sticks required to represent the current character ; Driver code ; Function call to find the count of matchsticks
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 ( string ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT ch = string [ i ] ; NEW_LINE if ( ch >= ' A ' and ch <= ' Z ' ) : NEW_LINE INDENT cnt += sticks [ ord ( ch ) - ord ( ' A ' ) ] ; NEW_LINE DEDENT else : NEW_LINE INDENT cnt += number [ ord ( ch ) - ord ( '0' ) ] ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GEEKSFORGEEKS " ; NEW_LINE print ( countSticks ( string ) ) ; NEW_LINE DEDENT
Find the last remaining Character in the Binary String according to the given conditions | Python3 implementation of the above approach ; Converting string to array ; Delete counters for each to count the deletes ; Counters to keep track of characters left from each type ; Queue to simulate the process ; Initializing the queue ; Looping till at least 1 digit is left from both the type ; If there is a floating delete for current character we will delete it and move forward otherwise we will increase delete counter for opposite digit ; If 0 are left then answer is 0 else answer is 1 ; Driver Code ; Input String ; Length of String ; Printing answer
from collections import deque ; NEW_LINE def remainingDigit ( S , N ) : NEW_LINE INDENT c = [ i for i in S ] NEW_LINE de = [ 0 , 0 ] NEW_LINE count = [ 0 , 0 ] NEW_LINE q = deque ( ) NEW_LINE for i in c : NEW_LINE INDENT x = 0 NEW_LINE if i == '1' : NEW_LINE INDENT x = 1 NEW_LINE DEDENT count [ x ] += 1 NEW_LINE q . append ( x ) NEW_LINE DEDENT while ( count [ 0 ] > 0 and count [ 1 ] > 0 ) : NEW_LINE INDENT t = q . popleft ( ) NEW_LINE if ( de [ t ] > 0 ) : NEW_LINE INDENT de [ t ] -= 1 NEW_LINE count [ t ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT de [ t ^ 1 ] += 1 NEW_LINE q . append ( t ) NEW_LINE DEDENT DEDENT if ( count [ 0 ] > 0 ) : NEW_LINE INDENT return "0" NEW_LINE DEDENT return "1" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "1010100100000" NEW_LINE N = len ( S ) NEW_LINE print ( remainingDigit ( S , N ) ) NEW_LINE DEDENT
Closest leaf to a given node in Binary Tree | Utility class to create a new node ; This function finds closest leaf to root . This distance is stored at * minDist . ; base case ; If this is a leaf node , then check if it is closer than the closest so far ; Recur for left and right subtrees ; This function finds if there is closer leaf to x through parent node . ; Base cases ; Search x in left subtree of root ; If left subtree has x ; Find closest leaf in right subtree ; Search x in right subtree of root ; If right subtree has x ; Find closest leaf in left subtree ; Returns minimum distance of a leaf from given node x ; Initialize result ( minimum distance from a leaf ) ; Find closest leaf down to x ; See if there is a closer leaf through parent ; Driver Code ; Let us create Binary Tree shown in above example
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 findLeafDown ( root , lev , minDist ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT if ( lev < ( minDist [ 0 ] ) ) : NEW_LINE INDENT minDist [ 0 ] = lev NEW_LINE DEDENT return NEW_LINE DEDENT findLeafDown ( root . left , lev + 1 , minDist ) NEW_LINE findLeafDown ( root . right , lev + 1 , minDist ) NEW_LINE DEDENT def findThroughParent ( root , x , minDist ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( root == x ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l = findThroughParent ( root . left , x , minDist ) NEW_LINE if ( l != - 1 ) : NEW_LINE INDENT findLeafDown ( root . right , l + 2 , minDist ) NEW_LINE return l + 1 NEW_LINE DEDENT r = findThroughParent ( root . right , x , minDist ) NEW_LINE if ( r != - 1 ) : NEW_LINE INDENT findLeafDown ( root . left , r + 2 , minDist ) NEW_LINE return r + 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def minimumDistance ( root , x ) : NEW_LINE INDENT minDist = [ 999999999999 ] NEW_LINE findLeafDown ( x , 0 , minDist ) NEW_LINE findThroughParent ( root , x , minDist ) NEW_LINE return minDist [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 12 ) NEW_LINE root . right = newNode ( 13 ) NEW_LINE root . right . left = newNode ( 14 ) NEW_LINE root . right . right = newNode ( 15 ) NEW_LINE root . right . left . left = newNode ( 21 ) NEW_LINE root . right . left . right = newNode ( 22 ) NEW_LINE root . right . right . left = newNode ( 23 ) NEW_LINE root . right . right . right = newNode ( 24 ) NEW_LINE root . right . left . left . left = newNode ( 1 ) NEW_LINE root . right . left . left . right = newNode ( 2 ) NEW_LINE root . right . left . right . left = newNode ( 3 ) NEW_LINE root . right . left . right . right = newNode ( 4 ) NEW_LINE root . right . right . left . left = newNode ( 5 ) NEW_LINE root . right . right . left . right = newNode ( 6 ) NEW_LINE root . right . right . right . left = newNode ( 7 ) NEW_LINE root . right . right . right . right = newNode ( 8 ) NEW_LINE x = root . right NEW_LINE print ( " The ▁ closest ▁ leaf ▁ to ▁ the ▁ node ▁ with ▁ value " , x . key , " is ▁ at ▁ a ▁ distance ▁ of " , minimumDistance ( root , x ) ) NEW_LINE DEDENT
Find the closest leaf in a Binary Tree | Python program to find closest leaf of a given key in binary tree ; A binary tree node ; A utility function to find distance of closest leaf of the tree rooted under given root ; Base Case ; Return minum of left and right plus one ; Returns destance of the closes leaf to a given key k The array ancestors us used to keep track of ancestors of current node and ' index ' is used to keep track of current index in 'ancestors[i] ; Base Case ; if key found ; Find closest leaf under the subtree rooted with given key ; Traverse ll ancestors and update result if any parent node gives smaller distance ; if key node found , store current node and recur for left and right childrens ; The main function that return distance of the clses key to key '. It mainly uses recursive function findClosestUtil() to find the closes distance ; Create an arrray to store ancestors Assumption : Maximum height of tree is 100 ; Let us construct the BST shown in the above figure
INT_MAX = 2 ** 32 NEW_LINE 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 def closestDown ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return INT_MAX NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 + min ( closestDown ( root . left ) , closestDown ( root . right ) ) NEW_LINE DEDENT def findClosestUtil ( root , k , ancestors , index ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return INT_MAX NEW_LINE DEDENT if root . key == k : NEW_LINE INDENT res = closestDown ( root ) NEW_LINE for i in reversed ( range ( 0 , index ) ) : NEW_LINE INDENT res = min ( res , index - i + closestDown ( ancestors [ i ] ) ) NEW_LINE DEDENT return res NEW_LINE DEDENT ancestors [ index ] = root NEW_LINE return min ( findClosestUtil ( root . left , k , ancestors , index + 1 ) , findClosestUtil ( root . right , k , ancestors , index + 1 ) ) NEW_LINE DEDENT def findClosest ( root , k ) : NEW_LINE INDENT ancestors = [ None for i in range ( 100 ) ] NEW_LINE return findClosestUtil ( root , k , ancestors , 0 ) NEW_LINE DEDENT root = Node ( ' A ' ) NEW_LINE root . left = Node ( ' B ' ) NEW_LINE root . right = Node ( ' C ' ) ; NEW_LINE root . right . left = Node ( ' E ' ) ; NEW_LINE root . right . right = Node ( ' F ' ) ; NEW_LINE root . right . left . left = Node ( ' G ' ) ; NEW_LINE root . right . left . left . left = Node ( ' I ' ) ; NEW_LINE root . right . left . left . right = Node ( ' J ' ) ; NEW_LINE root . right . right . right = Node ( ' H ' ) ; NEW_LINE root . right . right . right . left = Node ( ' K ' ) ; NEW_LINE k = ' H ' ; NEW_LINE print " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " + k + " ▁ is " , NEW_LINE print findClosest ( root , k ) NEW_LINE k = ' C ' NEW_LINE print " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " + k + " ▁ is " , NEW_LINE print findClosest ( root , k ) NEW_LINE k = ' E ' NEW_LINE print " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " + k + " ▁ is " , NEW_LINE print findClosest ( root , k ) NEW_LINE k = ' B ' NEW_LINE print " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " + k + " ▁ is " , NEW_LINE print findClosest ( root , k ) NEW_LINE
Find the time which is palindromic and comes after the given time | Function to return the required time ; To store the resultant time ; Hours are stored in h as integer ; Minutes are stored in m as integer ; Reverse of h ; Reverse of h as a string ; If MM < reverse of ( HH ) ; 0 is added if HH < 10 ; 0 is added if rev_h < 10 ; Increment hours ; Reverse of the hour after incrementing 1 ; 0 is added if HH < 10 ; 0 is added if rev_h < 10 ; Driver code
def getTime ( s , n ) : NEW_LINE INDENT res = " " NEW_LINE h = int ( s [ 0 : 2 ] ) ; NEW_LINE m = int ( s [ 3 : 5 ] ) ; NEW_LINE rev_h = ( h % 10 ) * 10 + ( ( h % 100 ) - ( h % 10 ) ) // 10 ; NEW_LINE rev_hs = str ( rev_h ) NEW_LINE temp = " " NEW_LINE if ( h == 23 and m >= 32 ) : NEW_LINE INDENT res = " - 1" ; NEW_LINE DEDENT elif ( m < rev_h ) : NEW_LINE INDENT if ( h < 10 ) : NEW_LINE INDENT temp = "0" ; NEW_LINE DEDENT temp = temp + str ( h ) ; NEW_LINE if ( rev_h < 10 ) : NEW_LINE INDENT res = res + temp + " : 0" + rev_hs ; NEW_LINE DEDENT else : NEW_LINE INDENT res = res + temp + " : " + rev_hs ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT h += 1 NEW_LINE rev_h = ( h % 10 ) * 10 + ( ( h % 100 ) - ( h % 10 ) ) // 10 ; NEW_LINE rev_hs = str ( rev_h ) ; NEW_LINE if ( h < 10 ) : NEW_LINE INDENT temp = "0" ; NEW_LINE DEDENT temp = temp + str ( h ) ; NEW_LINE if ( rev_h < 10 ) : NEW_LINE INDENT res = res + temp + " : 0" + rev_hs ; NEW_LINE DEDENT else : NEW_LINE INDENT res = res + temp + " : " + rev_hs ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "21:12" ; NEW_LINE n = len ( s ) ; NEW_LINE print ( getTime ( s , n ) ) ; NEW_LINE DEDENT
Count of sub | Function to return the count of valid sub - Strings ; Variable ans to store all the possible subStrings Initialize its value as total number of subStrings that can be formed from the given String ; Stores recent index of the characters ; If character is a update a 's index and the variable ans ; If character is b update b 's index and the variable ans ; If character is c update c 's index and the variable ans ; Driver code
def CountSubString ( Str , n ) : NEW_LINE INDENT ans = ( n * ( n + 1 ) ) // 2 NEW_LINE a_index = 0 NEW_LINE b_index = 0 NEW_LINE c_index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str [ i ] == ' a ' ) : NEW_LINE INDENT a_index = i + 1 NEW_LINE ans -= min ( b_index , c_index ) NEW_LINE DEDENT elif ( Str [ i ] == ' b ' ) : NEW_LINE INDENT b_index = i + 1 NEW_LINE ans -= min ( a_index , c_index ) NEW_LINE DEDENT else : NEW_LINE INDENT c_index = i + 1 NEW_LINE ans -= min ( a_index , b_index ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT Str = " babac " NEW_LINE n = len ( Str ) NEW_LINE print ( CountSubString ( Str , n ) ) NEW_LINE
Find the numbers of strings that can be formed after processing Q queries | Python3 program to implement above approach ; To store the size of string and number of queries ; To store parent and rank of ith place ; To store maximum interval ; Function for initialization ; Function to find parent ; Function to make union ; Power function to calculate a raised to m1 under modulo 10000007 ; Function to take maxmium interval ; Function to find different possible strings ; make union of all chracters which are meant to be same ; find number of different sets formed ; return the required answer ; Driver Code ; queries
N = 2005 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE n , q = 0 , 0 NEW_LINE par = [ 0 for i in range ( N ) ] NEW_LINE Rank = [ 0 for i in range ( N ) ] NEW_LINE m = dict ( ) NEW_LINE def initialize ( ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT Rank [ i ] , par [ i ] = 0 , i NEW_LINE DEDENT DEDENT def find ( x ) : NEW_LINE INDENT if ( par [ x ] != x ) : NEW_LINE INDENT par [ x ] = find ( par [ x ] ) NEW_LINE DEDENT return par [ x ] NEW_LINE DEDENT def Union ( x , y ) : NEW_LINE INDENT xpar = find ( x ) NEW_LINE ypar = find ( y ) NEW_LINE if ( Rank [ xpar ] < Rank [ ypar ] ) : NEW_LINE INDENT par [ xpar ] = ypar NEW_LINE DEDENT elif ( Rank [ xpar ] > Rank [ ypar ] ) : NEW_LINE INDENT par [ ypar ] = xpar NEW_LINE DEDENT else : NEW_LINE INDENT par [ ypar ] = xpar NEW_LINE Rank [ xpar ] += 1 NEW_LINE DEDENT DEDENT def power ( a , m1 ) : NEW_LINE INDENT if ( m1 == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( m1 == 1 ) : NEW_LINE INDENT return a NEW_LINE DEDENT elif ( m1 == 2 ) : NEW_LINE INDENT return ( a * a ) % mod NEW_LINE DEDENT elif ( m1 & 1 ) : NEW_LINE INDENT return ( a * power ( power ( a , m1 // 2 ) , 2 ) ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT return power ( power ( a , m1 // 2 ) , 2 ) % mod NEW_LINE DEDENT DEDENT def query ( l , r ) : NEW_LINE INDENT if l + r in m . keys ( ) : NEW_LINE INDENT m [ l + r ] = max ( m [ l + r ] , r ) NEW_LINE DEDENT else : NEW_LINE INDENT m [ l + r ] = max ( 0 , r ) NEW_LINE DEDENT DEDENT def possiblestrings ( ) : NEW_LINE INDENT initialize ( ) NEW_LINE for i in m : NEW_LINE INDENT x = i - m [ i ] NEW_LINE y = m [ i ] NEW_LINE while ( x < y ) : NEW_LINE INDENT Union ( x , y ) NEW_LINE x += 1 NEW_LINE y -= 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( par [ i ] == i ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return power ( 26 , ans ) % mod NEW_LINE DEDENT n = 4 NEW_LINE query ( 1 , 3 ) NEW_LINE query ( 2 , 4 ) NEW_LINE print ( possiblestrings ( ) ) NEW_LINE
Iterative Search for a key ' x ' in Binary Tree | Iterative level order traversal based method to search in Binary Tree importing Queue ; Helper function that allocates a new node with the given data and None left and right pointers . ; An iterative process to search an element x in a given binary tree ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; Queue based level order traversal ; See if current node is same as x ; Remove current node and enqueue its children ; Driver Code
from queue import Queue NEW_LINE 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 iterativeSearch ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE while ( q . empty ( ) == False ) : NEW_LINE INDENT node = q . queue [ 0 ] NEW_LINE if ( node . data == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT q . get ( ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . put ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . put ( node . right ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 2 ) NEW_LINE root . left = newNode ( 7 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 11 ) NEW_LINE root . right . right = newNode ( 9 ) NEW_LINE root . right . right . left = newNode ( 4 ) NEW_LINE if iterativeSearch ( root , 6 ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Found " ) NEW_LINE DEDENT if iterativeSearch ( root , 12 ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Found " ) NEW_LINE DEDENT DEDENT