text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Union and Intersection of two sorted arrays | Function prints Intersection of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Driver program to test above function ; Function calling | def printIntersection ( arr1 , arr2 , m , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE while i < m and j < n : NEW_LINE INDENT if arr1 [ i ] < arr2 [ j ] : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif arr2 [ j ] < arr1 [ i ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr2 [ j ] ) NEW_LINE j += 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT arr1 = [ 1 , 2 , 4 , 5 , 6 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 7 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE printIntersection ( arr1 , arr2 , m , n ) NEW_LINE |
Count numbers less than N containing digits from the given set : Digit DP | Python3 implementation to find the count of numbers possible less than N , such that every digit is from the given set of digits ; Function to convert integer into the string ; Recursive function to find the count of numbers possible less than N , such that every digit is from the given set of digits ; Base case ; Condition when the subproblem is computed previously ; Condition when the number chosen till now is definietly smaller than the given number N ; Loop to traverse all the digits of the given set ; Loop to traverse all the digits from the given set ; Store the solution for current subproblem ; Function to count the numbers less then N from given set of digits ; Converting the number to string ; Find the solution of all the number equal to the length of the given number N ; Loop to find the number less in in the length of the given number ; Driver Code ; Function Call | import numpy as np ; NEW_LINE dp = np . ones ( ( 15 , 2 ) ) * - 1 ; NEW_LINE def convertToString ( num ) : NEW_LINE INDENT return str ( num ) ; NEW_LINE DEDENT def calculate ( pos , tight , D , sz , num ) : NEW_LINE INDENT if ( pos == len ( num ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( dp [ pos ] [ tight ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ tight ] ; NEW_LINE DEDENT val = 0 ; NEW_LINE if ( tight == 0 ) : NEW_LINE INDENT for i in range ( sz ) : NEW_LINE INDENT if ( D [ i ] < ( ord ( num [ pos ] ) - ord ( '0' ) ) ) : NEW_LINE INDENT val += calculate ( pos + 1 , 1 , D , sz , num ) ; NEW_LINE DEDENT elif ( D [ i ] == ord ( num [ pos ] ) - ord ( '0' ) ) : NEW_LINE INDENT val += calculate ( pos + 1 , tight , D , sz , num ) ; NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( sz ) : NEW_LINE INDENT val += calculate ( pos + 1 , tight , D , sz , num ) ; NEW_LINE DEDENT DEDENT dp [ pos ] [ tight ] = val ; NEW_LINE return dp [ pos ] [ tight ] ; NEW_LINE DEDENT def countNumbers ( D , N , sz ) : NEW_LINE INDENT num = convertToString ( N ) ; NEW_LINE length = len ( num ) ; NEW_LINE ans = calculate ( 0 , 0 , D , sz , num ) ; NEW_LINE for i in range ( 1 , length ) : NEW_LINE INDENT ans += calculate ( i , 1 , D , sz , num ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sz = 3 ; NEW_LINE D = [ 1 , 4 , 9 ] ; NEW_LINE N = 10 ; NEW_LINE print ( countNumbers ( D , N , sz ) ) ; NEW_LINE DEDENT |
Maximum sum of elements divisible by K from the given array | Python3 implementation ; Function to return the maximum sum divisible by k from elements of v ; check if sum of elements excluding the current one is divisible by k ; check if sum of elements including the current one is divisible by k ; Store the maximum ; Driver code | dp = [ [ - 1 for i in range ( 1001 ) ] for j in range ( 1001 ) ] NEW_LINE def find_max ( i , sum , v , k ) : NEW_LINE INDENT if ( i == len ( v ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ sum ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( ( sum + find_max ( i + 1 , sum , v , k ) ) % k == 0 ) : NEW_LINE INDENT ans = find_max ( i + 1 , sum , v , k ) NEW_LINE DEDENT if ( ( sum + v [ i ] + find_max ( i + 1 , ( sum + v [ i ] ) % k , v , k ) ) % k == 0 ) : NEW_LINE INDENT ans = max ( ans , v [ i ] + find_max ( i + 1 , ( sum + v [ i ] ) % k , v , k ) ) NEW_LINE DEDENT dp [ i ] [ sum ] = ans NEW_LINE return dp [ i ] [ sum ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 43 , 1 , 17 , 26 , 15 ] NEW_LINE k = 16 NEW_LINE print ( find_max ( 0 , 0 , arr , k ) ) NEW_LINE DEDENT |
Find Union and Intersection of two unsorted arrays | Prints union of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding union , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort the first array and print its elements ( these two steps can be swapped as order in output is not important ) ; Search every element of bigger array in smaller array and print the element if not found ; Prints intersection of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding intersection , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort smaller array arr1 [ 0. . m - 1 ] ; Search every element of bigger array in smaller array and print the element if found ; A recursive binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be presen in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code ; Function call | def printUnion ( arr1 , arr2 , m , n ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT tempp = arr1 NEW_LINE arr1 = arr2 NEW_LINE arr2 = tempp NEW_LINE temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT print ( arr1 [ i ] , end = " β " ) NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( binarySearch ( arr1 , 0 , m - 1 , arr2 [ i ] ) == - 1 ) : NEW_LINE INDENT print ( arr2 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT def printIntersection ( arr1 , arr2 , m , n ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT tempp = arr1 NEW_LINE arr1 = arr2 NEW_LINE arr2 = tempp NEW_LINE temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( binarySearch ( arr1 , 0 , m - 1 , arr2 [ i ] ) != - 1 ) : NEW_LINE INDENT print ( arr2 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if ( r >= l ) : NEW_LINE INDENT mid = int ( l + ( r - l ) / 2 ) NEW_LINE if ( arr [ mid ] == x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( arr [ mid ] > x ) : NEW_LINE INDENT return binarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr1 = [ 7 , 1 , 5 , 2 , 3 , 6 ] NEW_LINE arr2 = [ 3 , 8 , 6 , 20 , 7 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE print ( " Union β of β two β arrays β is β " ) NEW_LINE printUnion ( arr1 , arr2 , m , n ) NEW_LINE print ( " Intersection of two arrays is " ) NEW_LINE printIntersection ( arr1 , arr2 , m , n ) NEW_LINE |
Find the maximum sum leaf to root path in a Binary Tree | A tree node structure ; A utility function that prints all nodes on the path from root to target_leaf ; base case ; return True if this node is the target_leaf or target leaf is present in one of its descendants ; This function Sets the target_leaf_ref to refer the leaf node of the maximum path sum . Also , returns the max_sum using max_sum_ref ; Update current sum to hold sum of nodes on path from root to this node ; If this is a leaf node and path to this node has maximum sum so far , then make this node target_leaf ; If this is not a leaf node , then recur down to find the target_leaf ; Returns the maximum sum and prints the nodes on max sum path ; base case ; find the target leaf and maximum sum ; print the path from root to the target leaf ; return maximum sum ; Utility function to create a new Binary Tree node ; Driver function to test above functions | class node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printPath ( root , target_leaf ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( root == target_leaf or printPath ( root . left , target_leaf ) or printPath ( root . right , target_leaf ) ) : NEW_LINE INDENT print ( root . data , end = " β " ) NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT max_sum_ref = 0 NEW_LINE target_leaf_ref = None NEW_LINE def getTargetLeaf ( Node , curr_sum ) : NEW_LINE INDENT global max_sum_ref NEW_LINE global target_leaf_ref NEW_LINE if ( Node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT curr_sum = curr_sum + Node . data NEW_LINE if ( Node . left == None and Node . right == None ) : NEW_LINE INDENT if ( curr_sum > max_sum_ref ) : NEW_LINE INDENT max_sum_ref = curr_sum NEW_LINE target_leaf_ref = Node NEW_LINE DEDENT DEDENT getTargetLeaf ( Node . left , curr_sum ) NEW_LINE getTargetLeaf ( Node . right , curr_sum ) NEW_LINE DEDENT def maxSumPath ( Node ) : NEW_LINE INDENT global max_sum_ref NEW_LINE global target_leaf_ref NEW_LINE if ( Node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT target_leaf_ref = None NEW_LINE max_sum_ref = - 32676 NEW_LINE getTargetLeaf ( Node , 0 ) NEW_LINE printPath ( Node , target_leaf_ref ) ; NEW_LINE return max_sum_ref ; NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( ) ; NEW_LINE temp . data = data ; NEW_LINE temp . left = None ; NEW_LINE temp . right = None ; NEW_LINE return temp ; NEW_LINE DEDENT root = None ; NEW_LINE root = newNode ( 10 ) ; NEW_LINE root . left = newNode ( - 2 ) ; NEW_LINE root . right = newNode ( 7 ) ; NEW_LINE root . left . left = newNode ( 8 ) ; NEW_LINE root . left . right = newNode ( - 4 ) ; NEW_LINE print ( " Following β are β the β nodes β on β the β maximum β sum β path β " ) ; NEW_LINE sum = maxSumPath ( root ) ; NEW_LINE print ( " Sum of the nodes is " , sum ) ; NEW_LINE |
Find Union and Intersection of two unsorted arrays | Function to find intersection ; when both are equal ; Driver Code ; sort ; function call | def intersection ( a , b , n , m ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( a [ i ] > b [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( b [ j ] > a [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 3 , 2 , 3 , 4 , 5 , 5 , 6 ] NEW_LINE b = [ 3 , 3 , 5 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE intersection ( a , b , n , m ) NEW_LINE DEDENT |
Count of 1 's in any path in a Binary Tree | A binary tree node ; A utility function to allocate a new node ; This function updates overall count of 1 in ' res ' And returns count 1 s going through root . ; Base Case ; l and r store count of 1 s going through left and right child of root respectively ; maxCount represents the count of 1 s when the Node under consideration is the root of the maxCount path and no ancestors of the root are there in maxCount path ; if the value at node is 1 then its count will be considered including the leftCount and the rightCount ; Store the Maximum Result . ; if the value at node is 1 then its count will be considered including the maximum of leftCount or the rightCount ; Returns maximum count of 1 in any path in tree with given root ; Initialize result ; Compute and return result ; Driver program | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT newNode = Node ( ) NEW_LINE newNode . data = data NEW_LINE newNode . left = newNode . right = None NEW_LINE return ( newNode ) NEW_LINE DEDENT res = 0 NEW_LINE def countUntil ( root ) : NEW_LINE INDENT global res NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l = countUntil ( root . left ) NEW_LINE r = countUntil ( root . right ) NEW_LINE maxCount = 0 NEW_LINE if ( root . data == 1 ) : NEW_LINE INDENT maxCount = l + r + 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxCount = l + r NEW_LINE DEDENT res = max ( res , maxCount ) NEW_LINE if ( root . data == 1 ) : NEW_LINE INDENT return max ( l , r ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return max ( l , r ) NEW_LINE DEDENT DEDENT def findMaxCount ( root ) : NEW_LINE INDENT global res NEW_LINE res = - 999999 NEW_LINE countUntil ( root ) NEW_LINE return res NEW_LINE DEDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 0 ) NEW_LINE root . right = newNode ( 1 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 1 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . left . right . right = newNode ( 0 ) NEW_LINE print ( findMaxCount ( root ) ) NEW_LINE |
Find Union and Intersection of two unsorted arrays | Prints union of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Prints intersection of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Driver Program ; Function call | def printUnion ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT hs = set ( ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT hs . add ( arr1 [ i ] ) NEW_LINE DEDENT for i in range ( 0 , n2 ) : NEW_LINE INDENT hs . add ( arr2 [ i ] ) NEW_LINE DEDENT print ( " Union : " ) NEW_LINE for i in hs : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT def printIntersection ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT hs = set ( ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT hs . add ( arr1 [ i ] ) NEW_LINE DEDENT print ( " Intersection : " ) NEW_LINE for i in range ( 0 , n2 ) : NEW_LINE INDENT if arr2 [ i ] in hs : NEW_LINE INDENT print ( arr2 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr1 = [ 7 , 1 , 5 , 2 , 3 , 6 ] NEW_LINE arr2 = [ 3 , 8 , 6 , 20 , 7 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE n2 = len ( arr2 ) NEW_LINE printUnion ( arr1 , arr2 , n1 , n2 ) NEW_LINE printIntersection ( arr1 , arr2 , n1 , n2 ) NEW_LINE |
Find Union and Intersection of two unsorted arrays | Prints intersection of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Iterate first array ; Iterate second array ; Prints union of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; placeZeroes function ; Function to itreate array ; placeValue function ; Hashing collision happened increment position and do recursive call ; Driver code | def findPosition ( a , b ) : NEW_LINE INDENT v = len ( a ) + len ( b ) ; NEW_LINE ans = [ 0 ] * v ; NEW_LINE zero1 = zero2 = 0 ; NEW_LINE print ( " Intersection β : " , end = " β " ) ; NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT zero1 = iterateArray ( a , v , ans , i ) ; NEW_LINE DEDENT for j in range ( len ( b ) ) : NEW_LINE INDENT zero2 = iterateArray ( b , v , ans , j ) ; NEW_LINE DEDENT zero = zero1 + zero2 ; NEW_LINE placeZeros ( v , ans , zero ) ; NEW_LINE printUnion ( v , ans , zero ) ; NEW_LINE DEDENT def printUnion ( v , ans , zero ) : NEW_LINE INDENT zero1 = 0 ; NEW_LINE print ( " Union : " , end = " " ) ; NEW_LINE for i in range ( v ) : NEW_LINE INDENT if ( ( zero == 0 and ans [ i ] == 0 ) or ( ans [ i ] == 0 and zero1 > 0 ) ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( ans [ i ] == 0 ) : NEW_LINE INDENT zero1 += 1 ; NEW_LINE DEDENT print ( ans [ i ] , end = " , " ) ; NEW_LINE DEDENT DEDENT def placeZeros ( v , ans , zero ) : NEW_LINE INDENT if ( zero == 2 ) : NEW_LINE INDENT print ( "0" ) ; NEW_LINE d = [ 0 ] ; NEW_LINE placeValue ( d , ans , 0 , 0 , v ) ; NEW_LINE DEDENT if ( zero == 1 ) : NEW_LINE INDENT d = [ 0 ] ; NEW_LINE placeValue ( d , ans , 0 , 0 , v ) ; NEW_LINE DEDENT DEDENT def iterateArray ( a , v , ans , i ) : NEW_LINE INDENT if ( a [ i ] != 0 ) : NEW_LINE INDENT p = a [ i ] % v ; NEW_LINE placeValue ( a , ans , i , p , v ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT def placeValue ( a , ans , i , p , v ) : NEW_LINE INDENT p = p % v ; NEW_LINE if ( ans [ p ] == 0 ) : NEW_LINE INDENT ans [ p ] = a [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ans [ p ] == a [ i ] ) : NEW_LINE INDENT print ( a [ i ] , end = " , " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT p = p + 1 ; NEW_LINE placeValue ( a , ans , i , p , v ) ; NEW_LINE DEDENT DEDENT DEDENT a = [ 7 , 1 , 5 , 2 , 3 , 6 ] ; NEW_LINE b = [ 3 , 8 , 6 , 20 , 7 ] ; NEW_LINE findPosition ( a , b ) ; NEW_LINE |
Minimum number of coins that can generate all the values in the given range | Function to return the count of minimum coins required ; To store the required sequence ; Creating list of the sum of all previous bit values including that bit value ; Driver code | def findCount ( N ) : NEW_LINE INDENT list = [ ] NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , 20 ) : NEW_LINE INDENT sum += 2 ** i NEW_LINE list . append ( sum ) NEW_LINE DEDENT for value in list : NEW_LINE INDENT if ( value >= N ) : NEW_LINE INDENT return ( list . index ( value ) + 1 ) NEW_LINE DEDENT DEDENT DEDENT N = 10 NEW_LINE print ( findCount ( N ) ) NEW_LINE |
Sort an array of 0 s , 1 s and 2 s | Function to sort array ; Function to print array ; Driver Program | def sort012 ( a , arr_size ) : NEW_LINE INDENT lo = 0 NEW_LINE hi = arr_size - 1 NEW_LINE mid = 0 NEW_LINE while mid <= hi : NEW_LINE INDENT if a [ mid ] == 0 : NEW_LINE INDENT a [ lo ] , a [ mid ] = a [ mid ] , a [ lo ] NEW_LINE lo = lo + 1 NEW_LINE mid = mid + 1 NEW_LINE DEDENT elif a [ mid ] == 1 : NEW_LINE INDENT mid = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ mid ] , a [ hi ] = a [ hi ] , a [ mid ] NEW_LINE hi = hi - 1 NEW_LINE DEDENT DEDENT return a NEW_LINE DEDENT def printArray ( a ) : NEW_LINE INDENT for k in a : NEW_LINE INDENT print k , NEW_LINE DEDENT DEDENT arr = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE arr = sort012 ( arr , arr_size ) NEW_LINE print " Array after segregation : NEW_LINE " , NEW_LINE printArray ( arr ) NEW_LINE |
Calculate the number of set bits for every number from 0 to N | Function to find the count of set bits in all the integers from 0 to n ; dp [ i ] will store the count of set bits in i Initialise the dp array ; Count of set bits in 0 is 0 ; For every number starting from 1 ; If current number is even ; Count of set bits in i is equal to the count of set bits in ( i / 2 ) ; If current element is odd ; Count of set bits in i is equal to the count of set bits in ( i / 2 ) + 1 ; Print the count of set bits in i ; Driver code | def findSetBits ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) ; NEW_LINE print ( dp [ 0 ] , end = " β " ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT dp [ i ] = dp [ i // 2 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i // 2 ] + 1 ; NEW_LINE DEDENT print ( dp [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE findSetBits ( n ) ; NEW_LINE DEDENT |
Sort an array of 0 s , 1 s and 2 s | Utility function to print contents of an array ; Function to sort the array of 0 s , 1 s and 2 s ; Count the number of 0 s , 1 s and 2 s in the array ; Update the array ; Store all the 0 s in the beginning ; Then all the 1 s ; Finally all the 2 s ; Prthe sorted array ; Driver code | def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT cnt0 = 0 NEW_LINE cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT elif arr [ i ] == 1 : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT elif arr [ i ] == 2 : NEW_LINE INDENT cnt2 += 1 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while ( cnt0 > 0 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE i += 1 NEW_LINE cnt0 -= 1 NEW_LINE DEDENT while ( cnt1 > 0 ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE i += 1 NEW_LINE cnt1 -= 1 NEW_LINE DEDENT while ( cnt2 > 0 ) : NEW_LINE INDENT arr [ i ] = 2 NEW_LINE i += 1 NEW_LINE cnt2 -= 1 NEW_LINE DEDENT printArr ( arr , n ) NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE |
Find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted | Python3 program to find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted ; step 1 ( a ) of above algo ; step 1 ( b ) of above algo ; step 2 ( a ) of above algo ; step 2 ( b ) of above algo ; step 2 ( c ) of above algo ; step 3 of above algo | def printUnsorted ( arr , n ) : NEW_LINE INDENT e = n - 1 NEW_LINE for s in range ( 0 , n - 1 ) : NEW_LINE INDENT if arr [ s ] > arr [ s + 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if s == n - 1 : NEW_LINE INDENT print ( " The β complete β array β is β sorted " ) NEW_LINE exit ( ) NEW_LINE DEDENT e = n - 1 NEW_LINE while e > 0 : NEW_LINE INDENT if arr [ e ] < arr [ e - 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT e -= 1 NEW_LINE DEDENT max = arr [ s ] NEW_LINE min = arr [ s ] NEW_LINE for i in range ( s + 1 , e + 1 ) : NEW_LINE INDENT if arr [ i ] > max : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT if arr [ i ] < min : NEW_LINE INDENT min = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( s ) : NEW_LINE INDENT if arr [ i ] > min : NEW_LINE INDENT s = i NEW_LINE break NEW_LINE DEDENT DEDENT i = n - 1 NEW_LINE while i >= e + 1 : NEW_LINE INDENT if arr [ i ] < max : NEW_LINE INDENT e = i NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( " The β unsorted β subarray β which β makes β the β given β array " ) NEW_LINE print ( " sorted β lies β between β the β indexes β % d β and β % d " % ( s , e ) ) NEW_LINE DEDENT arr = [ 10 , 12 , 20 , 30 , 25 , 40 , 32 , 31 , 35 , 50 , 60 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printUnsorted ( arr , arr_size ) NEW_LINE |
Count the number of possible triangles | Function to count all possible triangles with arr [ ] elements ; Count of triangles ; The three loops select three different values from array ; The innermost loop checks for the triangle property ; Sum of two sides is greater than the third ; Driver code | def findNumberOfTriangles ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] > arr [ k ] and arr [ i ] + arr [ k ] > arr [ j ] and arr [ k ] + arr [ j ] > arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 10 , 21 , 22 , 100 , 101 , 200 , 300 ] NEW_LINE size = len ( arr ) NEW_LINE print ( " Total β number β of β triangles β possible β is " , findNumberOfTriangles ( arr , size ) ) NEW_LINE |
Count the number of possible triangles | Function to count all possible triangles with arr [ ] elements ; Sort array and initialize count as 0 ; Initialize count of triangles ; Fix the first element . We need to run till n - 3 as the other two elements are selected from arr [ i + 1. . . n - 1 ] ; Initialize index of the rightmost third element ; Fix the second element ; Find the rightmost element which is smaller than the sum of two fixed elements The important thing to note here is , we use the previous value of k . If value of arr [ i ] + arr [ j - 1 ] was greater than arr [ k ] , then arr [ i ] + arr [ j ] must be greater than k , because the array is sorted . ; Total number of possible triangles that can be formed with the two fixed elements is k - j - 1. The two fixed elements are arr [ i ] and arr [ j ] . All elements between arr [ j + 1 ] to arr [ k - 1 ] can form a triangle with arr [ i ] and arr [ j ] . One is subtracted from k because k is incremented one extra in above while loop . k will always be greater than j . If j becomes equal to k , then above loop will increment k , because arr [ k ] + arr [ i ] is always greater than arr [ k ] ; Driver function to test above function | def findnumberofTriangles ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE arr . sort ( ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT k = i + 2 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT while ( k < n and arr [ i ] + arr [ j ] > arr [ k ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT if ( k > j ) : NEW_LINE INDENT count += k - j - 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 10 , 21 , 22 , 100 , 101 , 200 , 300 ] NEW_LINE print " Number β of β Triangles : " , findnumberofTriangles ( arr ) NEW_LINE |
Count the number of possible triangles | CountTriangles function ; If it is possible with a [ l ] , a [ r ] and a [ i ] then it is also possible with a [ l + 1 ] . . a [ r - 1 ] , a [ r ] and a [ i ] ; checking for more possible solutions ; if not possible check for higher values of arr [ l ] ; Driver Code | def CountTriangles ( A ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE A . sort ( ) ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT l = 0 ; NEW_LINE r = i - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( A [ l ] + A [ r ] > A [ i ] ) : NEW_LINE INDENT count += r - l ; NEW_LINE r -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( " No β of β possible β solutions : β " , count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 4 , 3 , 5 , 7 , 6 ] ; NEW_LINE CountTriangles ( A ) ; NEW_LINE DEDENT |
Maximum sum of nodes in Binary tree such that no two are adjacent | A binary tree node structure ; Utility function to create a new Binary Tree node ; method returns maximum sum possible from subtrees rooted at grandChildrens of node ; call for children of left child only if it is not NULL ; call for children of right child only if it is not NULL ; Utility method to return maximum sum rooted at node ; If node is already processed then return calculated value from map ; take current node value and call for all grand children ; don 't take current node value and call for all children ; choose maximum from both above calls and store that in map ; Returns maximum sum from subset of nodes of binary tree under given constraints ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp ; NEW_LINE DEDENT def sumOfGrandChildren ( node , mp ) : NEW_LINE INDENT sum = 0 ; NEW_LINE if ( node . left ) : NEW_LINE INDENT sum += ( getMaxSumUtil ( node . left . left , mp ) + getMaxSumUtil ( node . left . right , mp ) ) ; NEW_LINE DEDENT if ( node . right ) : NEW_LINE INDENT sum += ( getMaxSumUtil ( node . right . left , mp ) + getMaxSumUtil ( node . right . right , mp ) ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def getMaxSumUtil ( node , mp ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if node in mp : NEW_LINE INDENT return mp [ node ] ; NEW_LINE DEDENT incl = ( node . data + sumOfGrandChildren ( node , mp ) ) ; NEW_LINE excl = ( getMaxSumUtil ( node . left , mp ) + getMaxSumUtil ( node . right , mp ) ) ; NEW_LINE mp [ node ] = max ( incl , excl ) ; NEW_LINE return mp [ node ] ; NEW_LINE DEDENT def getMaxSum ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT mp = dict ( ) NEW_LINE return getMaxSumUtil ( node , mp ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = newNode ( 1 ) ; NEW_LINE root . left = newNode ( 2 ) ; NEW_LINE root . right = newNode ( 3 ) ; NEW_LINE root . right . left = newNode ( 4 ) ; NEW_LINE root . right . right = newNode ( 5 ) ; NEW_LINE root . left . left = newNode ( 1 ) ; NEW_LINE print ( getMaxSum ( root ) ) NEW_LINE DEDENT |
Flip minimum signs of array elements to get minimum sum of positive elements possible | Function to return the minimum number of elements whose sign must be flipped to get the positive sum of array elements as close to 0 as possible ; boolean variable used for toggling between maps ; Calculate the sum of all elements of the array ; Initializing first map ( dp [ 0 ] ) with INT_MAX because for i = 0 , there are no elements in the array to flip ; Base Case ; For toggling ; Required sum is minimum non - negative So , we iterate from i = 0 to sum and find the first i where dp [ flag ^ 1 ] [ i ] != INT_MAX ; In worst case we will flip max n - 1 elements ; Driver code | def solve ( A , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2000 ) ] for i in range ( 2000 ) ] NEW_LINE flag = 1 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT for i in range ( - sum , sum + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 10 ** 9 NEW_LINE DEDENT dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( - sum , sum + 1 ) : NEW_LINE INDENT dp [ flag ] [ j ] = 10 ** 9 NEW_LINE if ( j - A [ i - 1 ] <= sum and j - A [ i - 1 ] >= - sum ) : NEW_LINE INDENT dp [ flag ] [ j ] = dp [ flag ^ 1 ] [ j - A [ i - 1 ] ] NEW_LINE DEDENT if ( j + A [ i - 1 ] <= sum and j + A [ i - 1 ] >= - sum and dp [ flag ^ 1 ] [ j + A [ i - 1 ] ] != 10 ** 9 ) : NEW_LINE INDENT dp [ flag ] [ j ] = min ( dp [ flag ] [ j ] , dp [ flag ^ 1 ] [ j + A [ i - 1 ] ] + 1 ) NEW_LINE DEDENT DEDENT flag = flag ^ 1 NEW_LINE DEDENT for i in range ( sum + 1 ) : NEW_LINE INDENT if ( dp [ flag ^ 1 ] [ i ] != 10 ** 9 ) : NEW_LINE INDENT return dp [ flag ^ 1 ] [ i ] NEW_LINE DEDENT DEDENT return n - 1 NEW_LINE DEDENT arr = [ 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 ] NEW_LINE n = len ( arr ) NEW_LINE print ( solve ( arr , n ) ) NEW_LINE |
Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | | def countPairsBruteForce ( X , Y , m , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( pow ( X [ i ] , Y [ j ] ) > pow ( Y [ j ] , X [ i ] ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT |
Maximum items that can be filled in K Knapsacks of given Capacity | 2 - d array to store states of DP ; 2 - d array to store if a state has been solved ; Vector to store power of variable ' C ' . ; function to compute the states ; Base case ; Checking if a state has been solved ; Setting a state as solved ; Recurrence relation ; Returning the solved state ; Function to initialize global variables and find the initial value of 'R ; Resizing the variables ; Variable to store the initial value of R ; Input array ; number of knapsacks and capacity ; Performing required pre - computation ; finding the required answer | x = 100 NEW_LINE dp = [ [ 0 for i in range ( x ) ] for i in range ( x ) ] NEW_LINE v = [ [ 0 for i in range ( x ) ] for i in range ( x ) ] NEW_LINE exp_c = [ ] NEW_LINE def FindMax ( i , r , w , n , c , k ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT return dp [ i ] [ r ] NEW_LINE DEDENT v [ i ] [ r ] = 1 NEW_LINE dp [ i ] [ r ] = FindMax ( i + 1 , r , w , n , c , k ) NEW_LINE for j in range ( k ) : NEW_LINE INDENT x = ( r // exp_c [ j ] ) % ( c + 1 ) NEW_LINE if ( x - w [ i ] >= 0 ) : NEW_LINE INDENT dp [ i ] [ r ] = max ( dp [ i ] [ r ] , w [ i ] + FindMax ( i + 1 , r - w [ i ] * exp_c [ j ] , w , n , c , k ) ) NEW_LINE DEDENT DEDENT return dp [ i ] [ r ] NEW_LINE DEDENT ' NEW_LINE def PreCompute ( n , c , k ) : NEW_LINE INDENT exp_c . append ( 1 ) NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT exp_c [ i ] = ( exp_c [ i - 1 ] * ( c + 1 ) ) NEW_LINE DEDENT R = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT R += exp_c [ i ] * c NEW_LINE DEDENT return R NEW_LINE DEDENT w = [ 3 , 8 , 9 ] NEW_LINE k = 1 NEW_LINE c = 11 NEW_LINE n = len ( w ) NEW_LINE r = PreCompute ( n , c , k ) NEW_LINE print ( FindMax ( 0 , r , w , n , c , k ) ) NEW_LINE |
Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | Python3 program to find the number of pairs ( x , y ) in an array such that x ^ y > y ^ x ; Function to return count of pairs with x as one element of the pair . It mainly looks for all values in Y where x ^ Y [ i ] > Y [ i ] ^ x ; If x is 0 , then there cannot be any value in Y such that x ^ Y [ i ] > Y [ i ] ^ x ; If x is 1 , then the number of pairs is equal to number of zeroes in Y ; Find number of elements in Y [ ] with values greater than x , bisect . bisect_right gets address of first greater element in Y [ 0. . n - 1 ] ; If we have reached here , then x must be greater than 1 , increase number of pairs for y = 0 and y = 1 ; Decrease number of pairs for x = 2 and ( y = 4 or y = 3 ) ; Increase number of pairs for x = 3 and y = 2 ; Function to return count of pairs ( x , y ) such that x belongs to X , y belongs to Y and x ^ y > y ^ x ; To store counts of 0 , 1 , 2 , 3 , and 4 in array Y ; Sort Y so that we can do binary search in it ; Initialize result ; Take every element of X and count pairs with it ; Driver Code | import bisect NEW_LINE def count ( x , Y , n , NoOfY ) : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if x == 1 : NEW_LINE INDENT return NoOfY [ 0 ] NEW_LINE DEDENT idx = bisect . bisect_right ( Y , x ) NEW_LINE ans = n - idx NEW_LINE ans += NoOfY [ 0 ] + NoOfY [ 1 ] NEW_LINE if x == 2 : NEW_LINE INDENT ans -= NoOfY [ 3 ] + NoOfY [ 4 ] NEW_LINE DEDENT if x == 3 : NEW_LINE INDENT ans += NoOfY [ 2 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT def count_pairs ( X , Y , m , n ) : NEW_LINE INDENT NoOfY = [ 0 ] * 5 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if Y [ i ] < 5 : NEW_LINE INDENT NoOfY [ Y [ i ] ] += 1 NEW_LINE DEDENT DEDENT Y . sort ( ) NEW_LINE total_pairs = 0 NEW_LINE for x in X : NEW_LINE INDENT total_pairs += count ( x , Y , n , NoOfY ) NEW_LINE DEDENT return total_pairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = [ 2 , 1 , 6 ] NEW_LINE Y = [ 1 , 5 ] NEW_LINE print ( " Total β pairs β = β " , count_pairs ( X , Y , len ( X ) , len ( Y ) ) ) NEW_LINE DEDENT |
Count all distinct pairs with difference equal to k | A simple program to count pairs with difference k ; Pick all elements one by one ; See if there is a pair of this picked element ; Driver program | def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ i ] - arr [ j ] == k or arr [ j ] - arr [ i ] == k : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Count β of β pairs β with β given β diff β is β " , countPairsWithDiffK ( arr , n , k ) ) NEW_LINE |
Count all distinct pairs with difference equal to k | Standard binary search function ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; Pick a first element point ; Driver Code | def binarySearch ( arr , low , high , x ) : NEW_LINE INDENT if ( high >= low ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if x == arr [ mid ] : NEW_LINE INDENT return ( mid ) NEW_LINE DEDENT elif ( x > arr [ mid ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high , x ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( arr , low , ( mid - 1 ) , x ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT if ( binarySearch ( arr , i + 1 , n - 1 , arr [ i ] + k ) != - 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Count β of β pairs β with β given β diff β is β " , countPairsWithDiffK ( arr , n , k ) ) NEW_LINE |
Count all distinct pairs with difference equal to k | Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; arr [ r ] - arr [ l ] < sum ; Driver code | def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while r < n : NEW_LINE INDENT if arr [ r ] - arr [ l ] == k : NEW_LINE INDENT count += 1 NEW_LINE l += 1 NEW_LINE r += 1 NEW_LINE DEDENT elif arr [ r ] - arr [ l ] > k : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " Count β of β pairs β with β given β diff β is β " , countPairsWithDiffK ( arr , n , k ) ) NEW_LINE DEDENT |
Count of sub | Python3 implementation of the approach ; Function to return the total number of required sub - sets ; Variable to store total elements which on dividing by 3 give remainder 0 , 1 and 2 respectively ; Create a dp table ; Process for n states and store the sum ( mod 3 ) for 0 , 1 and 2 ; Use of MOD for large numbers ; Final answer store at dp [ n - 1 ] [ 0 ] ; Driver Code | import math NEW_LINE def totalSubSets ( n , l , r ) : NEW_LINE INDENT MOD = 1000000007 ; NEW_LINE zero = ( math . floor ( r / 3 ) - math . ceil ( l / 3 ) + 1 ) ; NEW_LINE one = ( math . floor ( ( r - 1 ) / 3 ) - math . ceil ( ( l - 1 ) / 3 ) + 1 ) ; NEW_LINE two = ( math . floor ( ( r - 2 ) / 3 ) - math . ceil ( ( l - 2 ) / 3 ) + 1 ) ; NEW_LINE dp = [ [ 0 for x in range ( 3 ) ] for y in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = zero ; NEW_LINE dp [ 0 ] [ 1 ] = one ; NEW_LINE dp [ 0 ] [ 2 ] = two ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( ( dp [ i - 1 ] [ 0 ] * zero ) + ( dp [ i - 1 ] [ 1 ] * two ) + ( dp [ i - 1 ] [ 2 ] * one ) ) % MOD ; NEW_LINE dp [ i ] [ 1 ] = ( ( dp [ i - 1 ] [ 0 ] * one ) + ( dp [ i - 1 ] [ 1 ] * zero ) + ( dp [ i - 1 ] [ 2 ] * two ) ) % MOD ; NEW_LINE dp [ i ] [ 2 ] = ( ( dp [ i - 1 ] [ 0 ] * two ) + ( dp [ i - 1 ] [ 1 ] * one ) + ( dp [ i - 1 ] [ 2 ] * zero ) ) % MOD ; NEW_LINE DEDENT return dp [ n - 1 ] [ 0 ] ; NEW_LINE DEDENT n = 5 ; NEW_LINE l = 10 ; NEW_LINE r = 100 ; NEW_LINE print ( totalSubSets ( n , l , r ) ) ; NEW_LINE |
Check if a word exists in a grid or not | Python3 program to check if the word exists in the grid or not ; Function to check if a word exists in a grid starting from the first match in the grid level : index till which pattern is matched x , y : current position in 2D array ; Pattern matched ; Out of Boundary ; If grid matches with a letter while recursion ; Marking this cell as visited ; finding subpattern in 4 directions ; marking this cell as unvisited again ; else : Not matching then false ; Function to check if the word exists in the grid or not ; if total characters in matrix is less then pattern lenghth ; Traverse in the grid ; If first letter matches , then recur and check ; Driver Code ; Function to check if word exists or not | r = 4 NEW_LINE c = 4 NEW_LINE def findmatch ( mat , pat , x , y , nrow , ncol , level ) : NEW_LINE INDENT l = len ( pat ) NEW_LINE if ( level == l ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( x < 0 or y < 0 or x >= nrow or y >= ncol ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( mat [ x ] [ y ] == pat [ level ] ) : NEW_LINE INDENT temp = mat [ x ] [ y ] NEW_LINE mat [ x ] . replace ( mat [ x ] [ y ] , ' # ' ) NEW_LINE res = ( findmatch ( mat , pat , x - 1 , y , nrow , ncol , level + 1 ) | findmatch ( mat , pat , x + 1 , y , nrow , ncol , level + 1 ) | findmatch ( mat , pat , x , y - 1 , nrow , ncol , level + 1 ) | findmatch ( mat , pat , x , y + 1 , nrow , ncol , level + 1 ) ) NEW_LINE mat [ x ] . replace ( mat [ x ] [ y ] , temp ) NEW_LINE return res NEW_LINE return False NEW_LINE DEDENT DEDENT def checkMatch ( mat , pat , nrow , ncol ) : NEW_LINE INDENT l = len ( pat ) NEW_LINE if ( l > nrow * ncol ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( nrow ) : NEW_LINE INDENT for j in range ( ncol ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == pat [ 0 ] ) : NEW_LINE INDENT if ( findmatch ( mat , pat , i , j , nrow , ncol , 0 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ " axmy " , " bgdf " , " xeet " , " raks " ] NEW_LINE if ( checkMatch ( grid , " geeks " , r , c ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Construct an array from its pair | Fills element in arr [ ] from its pair sum array pair [ ] . n is size of arr [ ] ; Driver code | def constructArr ( arr , pair , n ) : NEW_LINE INDENT arr [ 0 ] = ( pair [ 0 ] + pair [ 1 ] - pair [ n - 1 ] ) // 2 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT arr [ i ] = pair [ i - 1 ] - arr [ 0 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT pair = [ 15 , 13 , 11 , 10 , 12 , 10 , 9 , 8 , 7 , 5 ] NEW_LINE n = 5 NEW_LINE arr = [ 0 ] * n NEW_LINE constructArr ( arr , pair , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT |
Merge two sorted arrays with O ( 1 ) extra space | Merge ar1 [ ] and ar2 [ ] with O ( 1 ) extra space ; Iterate through all elements of ar2 [ ] starting from the last element ; Find the smallest element greater than ar2 [ i ] . Move all elements one position ahead till the smallest greater element is not found ; If there was a greater element ; Driver program | def merge ( ar1 , ar2 , m , n ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT last = ar1 [ m - 1 ] NEW_LINE j = m - 2 NEW_LINE while ( j >= 0 and ar1 [ j ] > ar2 [ i ] ) : NEW_LINE INDENT ar1 [ j + 1 ] = ar1 [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT if ( j != m - 2 or last > ar2 [ i ] ) : NEW_LINE INDENT ar1 [ j + 1 ] = ar2 [ i ] NEW_LINE ar2 [ i ] = last NEW_LINE DEDENT DEDENT DEDENT ar1 = [ 1 , 5 , 9 , 10 , 15 , 20 ] NEW_LINE ar2 = [ 2 , 3 , 8 , 13 ] NEW_LINE m = len ( ar1 ) NEW_LINE n = len ( ar2 ) NEW_LINE merge ( ar1 , ar2 , m , n ) NEW_LINE print ( " After Merging First Array : " , β end = " " ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT print ( ar1 [ i ] , " β " , end = " " ) NEW_LINE DEDENT print ( " Second Array : " , β end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ar2 [ i ] , " β " , end = " " ) NEW_LINE DEDENT |
Gould 's Sequence | Function to generate gould 's Sequence ; loop to generate each row of pascal 's Triangle up to nth row ; Loop to generate each element of ith row ; if c is odd increment count ; print count of odd elements ; Get n ; Function call | def gouldSequence ( n ) : NEW_LINE INDENT for row_num in range ( 1 , n ) : NEW_LINE INDENT count = 1 NEW_LINE c = 1 NEW_LINE for i in range ( 1 , row_num ) : NEW_LINE INDENT c = c * ( row_num - i ) / i NEW_LINE if ( c % 2 == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = " β " ) NEW_LINE DEDENT DEDENT n = 16 ; NEW_LINE gouldSequence ( n ) NEW_LINE |
Product of maximum in first array and minimum in second | Function to calculate the product ; Sort the arrays to find the maximum and minimum elements in given arrays ; Return product of maximum and minimum . ; Driver Program | def minmaxProduct ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE return arr1 [ n1 - 1 ] * arr2 [ 0 ] NEW_LINE DEDENT arr1 = [ 10 , 2 , 3 , 6 , 4 , 1 ] NEW_LINE arr2 = [ 5 , 1 , 4 , 2 , 6 , 9 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( minmaxProduct ( arr1 , arr2 , n1 , n2 ) ) NEW_LINE |
Minimum odd cost path in a matrix | Python3 program to find Minimum odd cost path in a matrix ; Function to find the minimum cost ; leftmost element ; rightmost element ; Any element except leftmost and rightmost element of a row is reachable from direct upper or left upper or right upper row 's block ; Counting the minimum cost ; Find the minimum cost ; Driver code | M = 100 NEW_LINE N = 100 NEW_LINE def find_min_odd_cost ( given , m , n ) : NEW_LINE INDENT floor = [ [ 0 for i in range ( M ) ] for i in range ( N ) ] NEW_LINE min_odd_cost = 0 NEW_LINE i , j , temp = 0 , 0 , 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT floor [ 0 ] [ j ] = given [ 0 ] [ j ] NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT floor [ i ] [ j ] = given [ i ] [ j ] ; NEW_LINE floor [ i ] [ j ] += min ( floor [ i - 1 ] [ j ] , floor [ i - 1 ] [ j + 1 ] ) NEW_LINE DEDENT elif ( j == n - 1 ) : NEW_LINE INDENT floor [ i ] [ j ] = given [ i ] [ j ] ; NEW_LINE floor [ i ] [ j ] += min ( floor [ i - 1 ] [ j ] , floor [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT temp = min ( floor [ i - 1 ] [ j ] , floor [ i - 1 ] [ j - 1 ] ) NEW_LINE temp = min ( temp , floor [ i - 1 ] [ j + 1 ] ) NEW_LINE floor [ i ] [ j ] = given [ i ] [ j ] + temp NEW_LINE DEDENT DEDENT DEDENT min_odd_cost = 10 ** 9 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( floor [ n - 1 ] [ j ] % 2 == 1 ) : NEW_LINE INDENT if ( min_odd_cost > floor [ n - 1 ] [ j ] ) : NEW_LINE INDENT min_odd_cost = floor [ n - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT if ( min_odd_cost == - 10 ** 9 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return min_odd_cost NEW_LINE DEDENT m , n = 5 , 5 NEW_LINE given = [ [ 1 , 2 , 3 , 4 , 6 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 100 , 2 , 3 , 4 , 5 ] ] NEW_LINE print ( " Minimum β odd β cost β is " , find_min_odd_cost ( given , m , n ) ) NEW_LINE |
Product of maximum in first array and minimum in second | Function to calculate the product ; Initialize max of first array ; initialize min of second array ; To find the maximum element in first array ; To find the minimum element in second array ; Process remaining elements ; Driver code | def minMaxProduct ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT max = arr1 [ 0 ] NEW_LINE min = arr2 [ 0 ] NEW_LINE i = 1 NEW_LINE while ( i < n1 and i < n2 ) : NEW_LINE INDENT if ( arr1 [ i ] > max ) : NEW_LINE INDENT max = arr1 [ i ] NEW_LINE DEDENT if ( arr2 [ i ] < min ) : NEW_LINE INDENT min = arr2 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT while ( i < n1 ) : NEW_LINE INDENT if ( arr1 [ i ] > max ) : NEW_LINE INDENT max = arr1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT while ( i < n2 ) : NEW_LINE INDENT if ( arr2 [ i ] < min ) : NEW_LINE INDENT min = arr2 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT return max * min NEW_LINE DEDENT arr1 = [ 10 , 2 , 3 , 6 , 4 , 1 ] NEW_LINE arr2 = [ 5 , 1 , 4 , 2 , 6 , 9 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE n2 = len ( arr1 ) NEW_LINE print ( minMaxProduct ( arr1 , arr2 , n1 , n2 ) ) NEW_LINE |
Search , insert and delete in an unsorted array | Function to implement search operation ; Driver Code ; Using a last element as search element | def findElement ( arr , n , key ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == key ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 12 , 34 , 10 , 6 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE key = 40 NEW_LINE index = findElement ( arr , n , key ) NEW_LINE if index != - 1 : NEW_LINE INDENT print ( " element β found β at β position : β " + str ( index + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " element β not β found " ) NEW_LINE DEDENT |
Search , insert and delete in a sorted array | function to implement binary search ; low + ( high - low ) / 2 ; Driver program to check above functions Let us search 3 in below array | def binarySearch ( arr , low , high , key ) : NEW_LINE INDENT mid = ( low + high ) / 2 NEW_LINE if ( key == arr [ int ( mid ) ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( key > arr [ int ( mid ) ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high , key ) NEW_LINE DEDENT if ( key < arr [ int ( mid ) ] ) : NEW_LINE INDENT return binarySearch ( arr , low , ( mid - 1 ) , key ) NEW_LINE DEDENT return 0 NEW_LINE DEDENT arr = [ 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE key = 10 NEW_LINE print ( " Index : " , int ( binarySearch ( arr , 0 , n - 1 , key ) ) ) NEW_LINE |
Search , insert and delete in a sorted array | Inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . This function returns n + 1 if insertion is successful , else n . ; Cannot insert more elements if n is already more than or equal to capcity ; Driver Code ; Inserting key | def insertSorted ( arr , n , key , capacity ) : NEW_LINE INDENT if ( n >= capacity ) : NEW_LINE INDENT return n NEW_LINE DEDENT i = n - 1 NEW_LINE while i >= 0 and arr [ i ] > key : NEW_LINE INDENT arr [ i + 1 ] = arr [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT arr [ i + 1 ] = key NEW_LINE return ( n + 1 ) NEW_LINE DEDENT arr = [ 12 , 16 , 20 , 40 , 50 , 70 ] NEW_LINE for i in range ( 20 ) : NEW_LINE INDENT arr . append ( 0 ) NEW_LINE DEDENT capacity = len ( arr ) NEW_LINE n = 6 NEW_LINE key = 26 NEW_LINE print ( " Before β Insertion : β " , end = " β " ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT n = insertSorted ( arr , n , key , capacity ) NEW_LINE print ( " After Insertion : " , β end β = β " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Search , insert and delete in a sorted array | To search a ley to be deleted ; Function to delete an element ; Find position of element to be deleted ; Deleting element ; Driver code | def binarySearch ( arr , low , high , key ) : NEW_LINE INDENT if ( high < low ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( low + high ) // 2 NEW_LINE if ( key == arr [ mid ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( key > arr [ mid ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high , key ) NEW_LINE DEDENT return binarySearch ( arr , low , ( mid - 1 ) , key ) NEW_LINE DEDENT def deleteElement ( arr , n , key ) : NEW_LINE INDENT pos = binarySearch ( arr , 0 , n - 1 , key ) NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( " Element β not β found " ) NEW_LINE return n NEW_LINE DEDENT for i in range ( pos , n - 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i + 1 ] NEW_LINE DEDENT return n - 1 NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 40 , 50 ] NEW_LINE n = len ( arr ) NEW_LINE key = 30 NEW_LINE print ( " Array β before β deletion " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT n = deleteElement ( arr , n , key ) NEW_LINE print ( " Array after deletion " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Queries on number of Binary sub | Python 3 Program to answer queries on number of submatrix of given size ; Solve each query on matrix ; For each of the cell . ; finding submatrix size of oth row and column . ; intermediate cells . ; Find frequency of each distinct size for 0 s and 1 s . ; Find the Cumulative Sum . ; Output the answer for each query ; Driver Program | MAX = 100 NEW_LINE N = 5 NEW_LINE M = 4 NEW_LINE def solveQuery ( n , m , mat , q , a , binary ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m ) ] for y in range ( n ) ] NEW_LINE max = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT elif ( ( mat [ i ] [ j ] == mat [ i - 1 ] [ j ] ) and ( mat [ i ] [ j ] == mat [ i ] [ j - 1 ] ) and ( mat [ i ] [ j ] == mat [ i - 1 ] [ j - 1 ] ) ) : NEW_LINE INDENT dp [ i ] [ j ] = ( min ( dp [ i - 1 ] [ j ] , min ( dp [ i - 1 ] [ j - 1 ] , dp [ i ] [ j - 1 ] ) ) + 1 ) NEW_LINE if ( max < dp [ i ] [ j ] ) : NEW_LINE INDENT max = dp [ i ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT freq0 = [ 0 ] * MAX NEW_LINE freq1 = [ 0 ] * MAX NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT freq0 [ dp [ i ] [ j ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq1 [ dp [ i ] [ j ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( max - 1 , - 1 , - 1 ) : NEW_LINE INDENT freq0 [ i ] += freq0 [ i + 1 ] NEW_LINE freq1 [ i ] += freq1 [ i + 1 ] NEW_LINE DEDENT for i in range ( q ) : NEW_LINE INDENT if ( binary [ i ] == 0 ) : NEW_LINE INDENT print ( freq0 [ a [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( freq1 [ a [ i ] ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 4 NEW_LINE mat = [ [ 0 , 0 , 1 , 1 ] , [ 0 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 ] , [ 0 , 1 , 1 , 1 ] ] NEW_LINE q = 2 NEW_LINE a = [ 2 , 2 ] NEW_LINE binary = [ 1 , 0 ] NEW_LINE solveQuery ( n , m , mat , q , a , binary ) NEW_LINE DEDENT |
Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space | Function that matches input txt with given wildcard pattern ; empty pattern can only match with empty sting Base case ; step 1 initialize markers : ; For step - ( 2 , 5 ) ; For step - ( 3 ) ; For step - ( 4 ) ; For step - ( 5 ) ; For step - ( 6 ) ; For step - ( 7 ) ; Final Check ; Driver code | def stringmatch ( txt , pat , n , m ) : NEW_LINE INDENT if ( m == 0 ) : NEW_LINE INDENT return ( n == 0 ) NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE index_txt = - 1 NEW_LINE index_pat = - 1 NEW_LINE while ( i < n - 2 ) : NEW_LINE INDENT if ( j < m and txt [ i ] == pat [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT elif ( j < m and pat [ j ] == ' ? ' ) : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT elif ( j < m and pat [ j ] == ' * ' ) : NEW_LINE INDENT index_txt = i NEW_LINE index_pat = j NEW_LINE j += 1 NEW_LINE DEDENT elif ( index_pat != - 1 ) : NEW_LINE INDENT j = index_pat + 1 NEW_LINE i = index_txt + 1 NEW_LINE index_txt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT while ( j < m and pat [ j ] == ' * ' ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( j == m ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT strr = " baaabab " NEW_LINE pattern = " * * * * * ba * * * * * ab " NEW_LINE char pattern [ ] = " ba * * * * * ab " NEW_LINE char pattern [ ] = " ba β * β ab " NEW_LINE char pattern [ ] = " a * ab NEW_LINE if ( stringmatch ( strr , pattern , len ( strr ) , len ( pattern ) ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT pattern2 = " a * * * * * ab " ; NEW_LINE if ( stringmatch ( strr , pattern2 , len ( strr ) , len ( pattern2 ) ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find n | function to find nth stern ' diatomic series ; Initializing the DP array ; SET the Base case ; Traversing the array from 2 nd Element to nth Element ; Case 1 : for even n ; Case 2 : for odd n ; Driver program | def findSDSFunc ( n ) : NEW_LINE INDENT DP = [ 0 ] * ( n + 1 ) NEW_LINE DP [ 0 ] = 0 NEW_LINE DP [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( int ( i % 2 ) == 0 ) : NEW_LINE INDENT DP [ i ] = DP [ int ( i / 2 ) ] NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i ] = ( DP [ int ( ( i - 1 ) / 2 ) ] + DP [ int ( ( i + 1 ) / 2 ) ] ) NEW_LINE DEDENT DEDENT return DP [ n ] NEW_LINE DEDENT n = 15 NEW_LINE print ( findSDSFunc ( n ) ) NEW_LINE |
Check if any valid sequence is divisible by M | Python3 Program to Check if any valid sequence is divisible by M ; Calculate modulo for this call ; Base case ; check if sum is divisible by M ; check if the current state is already computed ; 1. Try placing '+ ; 2. Try placing '- ; calculate value of res for recursive case ; store the value for res for current states and return for parent call ; Driver code ; MAX is the Maximum value M can take | MAX = 100 NEW_LINE def isPossible ( n , index , modulo , M , arr , dp ) : NEW_LINE INDENT modulo = ( ( modulo % M ) + M ) % M NEW_LINE if ( index == n ) : NEW_LINE INDENT if ( modulo == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ modulo ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ modulo ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT placeAdd = isPossible ( n , index + 1 , modulo + arr [ index ] , M , arr , dp ) NEW_LINE DEDENT ' NEW_LINE INDENT placeMinus = isPossible ( n , index + 1 , modulo - arr [ index ] , M , arr , dp ) NEW_LINE res = bool ( placeAdd or placeMinus ) NEW_LINE dp [ index ] [ modulo ] = res NEW_LINE return res NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE M = 4 NEW_LINE dp = [ [ - 1 ] * ( n + 1 ) ] * MAX NEW_LINE res = isPossible ( n , 1 , arr [ 0 ] , M , arr , dp ) NEW_LINE if ( res == True ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT |
Find common elements in three sorted arrays | This function prints common elements in ar1 ; Initialize starting indexes for ar1 [ ] , ar2 [ ] and ar3 [ ] ; Iterate through three arrays while all arrays have elements ; If x = y and y = z , print any of them and move ahead in all arrays ; x < y ; y < z ; We reach here when x > y and z < y , i . e . , z is smallest ; Driver program to check above function | def findCommon ( ar1 , ar2 , ar3 , n1 , n2 , n3 ) : NEW_LINE INDENT i , j , k = 0 , 0 , 0 NEW_LINE while ( i < n1 and j < n2 and k < n3 ) : NEW_LINE INDENT if ( ar1 [ i ] == ar2 [ j ] and ar2 [ j ] == ar3 [ k ] ) : NEW_LINE INDENT print ar1 [ i ] , NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT elif ar1 [ i ] < ar2 [ j ] : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ar2 [ j ] < ar3 [ k ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT DEDENT ar1 = [ 1 , 5 , 10 , 20 , 40 , 80 ] NEW_LINE ar2 = [ 6 , 7 , 20 , 80 , 100 ] NEW_LINE ar3 = [ 3 , 4 , 15 , 20 , 30 , 70 , 80 , 120 ] NEW_LINE n1 = len ( ar1 ) NEW_LINE n2 = len ( ar2 ) NEW_LINE n3 = len ( ar3 ) NEW_LINE print " Common β elements β are " , NEW_LINE findCommon ( ar1 , ar2 , ar3 , n1 , n2 , n3 ) NEW_LINE |
Dynamic Programming on Trees | Set | Python3 code to find the maximum path sum ; Function for dfs traversal and to store the maximum value in dp [ ] for every node till the leaves ; Initially dp [ u ] is always a [ u ] ; Stores the maximum value from nodes ; Traverse the tree ; If child is parent , then we continue without recursing further ; Call dfs for further traversal ; Store the maximum of previous visited node and present visited node ; Add the maximum value returned to the parent node ; Function that returns the maximum value ; Driver Code ; Number of nodes ; Adjacency list as a dictionary ; Create undirected edges initialize the tree given in the diagram ; Values of node 1 , 2 , 3. ... 14 ; Function call | dp = [ 0 ] * 100 NEW_LINE def dfs ( a , v , u , parent ) : NEW_LINE INDENT dp [ u ] = a [ u - 1 ] NEW_LINE maximum = 0 NEW_LINE for child in v [ u ] : NEW_LINE INDENT if child == parent : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( a , v , child , u ) NEW_LINE maximum = max ( maximum , dp [ child ] ) NEW_LINE DEDENT dp [ u ] += maximum NEW_LINE DEDENT def maximumValue ( a , v ) : NEW_LINE INDENT dfs ( a , v , 1 , 0 ) NEW_LINE return dp [ 1 ] NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT n = 14 NEW_LINE v = { } NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT v [ i ] = [ ] NEW_LINE DEDENT v [ 1 ] . append ( 2 ) , v [ 2 ] . append ( 1 ) NEW_LINE v [ 1 ] . append ( 3 ) , v [ 3 ] . append ( 1 ) NEW_LINE v [ 1 ] . append ( 4 ) , v [ 4 ] . append ( 1 ) NEW_LINE v [ 2 ] . append ( 5 ) , v [ 5 ] . append ( 2 ) NEW_LINE v [ 2 ] . append ( 6 ) , v [ 6 ] . append ( 2 ) NEW_LINE v [ 3 ] . append ( 7 ) , v [ 7 ] . append ( 3 ) NEW_LINE v [ 4 ] . append ( 8 ) , v [ 8 ] . append ( 4 ) NEW_LINE v [ 4 ] . append ( 9 ) , v [ 9 ] . append ( 4 ) NEW_LINE v [ 4 ] . append ( 10 ) , v [ 10 ] . append ( 4 ) NEW_LINE v [ 5 ] . append ( 11 ) , v [ 11 ] . append ( 5 ) NEW_LINE v [ 5 ] . append ( 12 ) , v [ 12 ] . append ( 5 ) NEW_LINE v [ 7 ] . append ( 13 ) , v [ 13 ] . append ( 7 ) NEW_LINE v [ 7 ] . append ( 14 ) , v [ 14 ] . append ( 7 ) NEW_LINE a = [ 3 , 2 , 1 , 10 , 1 , 3 , 9 , 1 , 5 , 3 , 4 , 5 , 9 , 8 ] NEW_LINE print ( maximumValue ( a , v ) ) NEW_LINE DEDENT main ( ) NEW_LINE |
Jacobsthal and Jacobsthal | Return nth Jacobsthal number . ; base case ; Return nth Jacobsthal - Lucas number . ; base case ; Driven Program | def Jacobsthal ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 2 * dp [ i - 2 ] NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT def Jacobsthal_Lucas ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 2 NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 2 * dp [ i - 2 ] ; NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT n = 5 NEW_LINE print ( " Jacobsthal β number : " , Jacobsthal ( n ) ) NEW_LINE print ( " Jacobsthal - Lucas β number : " , Jacobsthal_Lucas ( n ) ) NEW_LINE |
Find position of an element in a sorted array of infinite numbers | Binary search algorithm implementation ; function takes an infinite size array and a key to be searched and returns its position if found else - 1. We don 't know size of a[] and we can assume size to be infinite in this function. NOTE THAT THIS FUNCTION ASSUMES a[] TO BE OF INFINITE SIZE THEREFORE, THERE IS NO INDEX OUT OF BOUND CHECKING ; Find h to do binary search ; store previous high ; double high index ; update new val ; at this point we have updated low and high indices , thus use binary search between them ; Driver function | def binary_search ( arr , l , r , x ) : NEW_LINE INDENT if r >= l : NEW_LINE INDENT mid = l + ( r - l ) / 2 NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ mid ] > x : NEW_LINE INDENT return binary_search ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binary_search ( arr , mid + 1 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def findPos ( a , key ) : NEW_LINE INDENT l , h , val = 0 , 1 , arr [ 0 ] NEW_LINE while val < key : NEW_LINE INDENT l = h NEW_LINE h = 2 * h NEW_LINE val = arr [ h ] NEW_LINE DEDENT return binary_search ( a , l , h , key ) NEW_LINE DEDENT arr = [ 3 , 5 , 7 , 9 , 10 , 90 , 100 , 130 , 140 , 160 , 170 ] NEW_LINE ans = findPos ( arr , 10 ) NEW_LINE if ans == - 1 : NEW_LINE INDENT print " Element β not β found " NEW_LINE DEDENT else : NEW_LINE INDENT print " Element β found β at β index " , ans NEW_LINE DEDENT |
Count of possible hexagonal walks | Python 3 implementation of counting number of possible hexagonal walks ; We initialize our origin with 1 ; For each N = 1 to 14 , we traverse in all possible direction . Using this 3D array we calculate the number of ways at each step and the total ways for a given step shall be found at ways [ step number ] [ 8 ] [ 8 ] because all the steps after that will be used to trace back to the original point index 0 : 0 according to the image . ; This array stores the number of ways possible for a given step ; Driver Code ; Preprocessing all possible ways | depth = 16 NEW_LINE ways = [ [ [ 0 for i in range ( 17 ) ] for i in range ( 17 ) ] for i in range ( 17 ) ] NEW_LINE def preprocess ( list , steps ) : NEW_LINE INDENT ways [ 0 ] [ 8 ] [ 8 ] = 1 NEW_LINE for N in range ( 1 , 16 , 1 ) : NEW_LINE INDENT for i in range ( 1 , depth , 1 ) : NEW_LINE INDENT for j in range ( 1 , depth , 1 ) : NEW_LINE INDENT ways [ N ] [ i ] [ j ] = ( ways [ N - 1 ] [ i ] [ j + 1 ] + ways [ N - 1 ] [ i ] [ j - 1 ] + ways [ N - 1 ] [ i + 1 ] [ j ] + ways [ N - 1 ] [ i - 1 ] [ j ] + ways [ N - 1 ] [ i + 1 ] [ j - 1 ] + ways [ N - 1 ] [ i - 1 ] [ j + 1 ] ) NEW_LINE DEDENT DEDENT list [ N ] = ways [ N ] [ 8 ] [ 8 ] NEW_LINE DEDENT print ( " Number β of β walks β possible β is / are " , list [ steps ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT list = [ 0 for i in range ( 16 ) ] NEW_LINE steps = 4 NEW_LINE preprocess ( list , steps ) NEW_LINE DEDENT |
Check if possible to cross the matrix with given power | Python3 program to find if it is possible to cross the matrix with given power ; For each value of dp [ i ] [ j ] [ k ] ; For first cell and for each value of k ; For first cell of each row ; For first cell of each column ; For rest of the cell ; Down movement . ; Right movement . ; Diagonal movement . ; Finding maximum k . ; Driver Code | N = 105 NEW_LINE R = 3 NEW_LINE C = 4 NEW_LINE def maximumValue ( n , m , p , grid ) : NEW_LINE INDENT dp = [ [ [ False for i in range ( N ) ] for j in range ( N ) ] for k in range ( N ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT k = grid [ i ] [ j ] NEW_LINE while ( k <= p ) : NEW_LINE INDENT if ( i == 0 and j == 0 ) : NEW_LINE INDENT if ( k == grid [ i ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = True NEW_LINE DEDENT DEDENT elif ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = ( dp [ i ] [ j ] [ k ] or dp [ i ] [ j - 1 ] [ k - grid [ i ] [ j ] ] ) NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = ( dp [ i ] [ j ] [ k ] or dp [ i - 1 ] [ j ] [ k - grid [ i ] [ j ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = ( dp [ i ] [ j ] [ k ] or dp [ i ] [ j - 1 ] [ k - grid [ i ] [ j ] ] ) NEW_LINE dp [ i ] [ j ] [ k ] = ( dp [ i ] [ j ] [ k ] or dp [ i - 1 ] [ j ] [ k - grid [ i ] [ j ] ] ) NEW_LINE dp [ i ] [ j ] [ k ] = ( dp [ i ] [ j ] [ k ] or dp [ i - 1 ] [ j - 1 ] [ k - grid [ i ] [ j ] ] ) NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT DEDENT ans = k NEW_LINE while ( ans >= 0 ) : NEW_LINE INDENT if ( dp [ n - 1 ] [ m - 1 ] [ ans ] ) : NEW_LINE INDENT break NEW_LINE DEDENT ans -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 3 NEW_LINE m = 4 NEW_LINE p = 9 NEW_LINE grid = [ [ 2 , 3 , 4 , 1 ] , [ 6 , 5 , 5 , 3 ] , [ 5 , 2 , 3 , 4 ] ] NEW_LINE print ( maximumValue ( n , m , p , grid ) ) NEW_LINE |
Number of n digit stepping numbers | function that calculates the answer ; dp [ i ] [ j ] stores count of i digit stepping numbers ending with digit j . ; if n is 1 then answer will be 10. ; Initialize values for count of digits equal to 1. ; Compute values for count of digits more than 1. ; If ending digit is 0 ; If ending digit is 9 ; For other digits . ; stores the final answer ; Driver Code | def answer ( n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( 10 ) ] for y in range ( n + 1 ) ] ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 10 ; NEW_LINE DEDENT for j in range ( 10 ) : NEW_LINE INDENT dp [ 1 ] [ j ] = 1 ; NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j + 1 ] ; NEW_LINE DEDENT elif ( j == 9 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j + 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT sum = 0 ; NEW_LINE for j in range ( 1 , 10 ) : NEW_LINE INDENT sum = sum + dp [ n ] [ j ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT n = 2 ; NEW_LINE print ( answer ( n ) ) ; NEW_LINE |
Print Longest Palindromic Subsequence | Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a string length index + 1 and fill it with \ 0 ; Start from the right - most - bottom - most corner and one by one store characters in lcs [ ] ; If current character in X [ ] and Y are same , then current character is part of LCS ; Put current character in result ; reduce values of i , j and index ; If not same , then find the larger of two and go in the direction of larger value ; Returns longest palindromic subsequence of str ; Find reverse of str ; Return LCS of str and its reverse ; Driver Code | def lcs_ ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ 0 ] * ( n + 1 ) ] * ( m + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 ; NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT index = L [ m ] [ n ] ; NEW_LINE lcs = [ " " ] * ( index + 1 ) NEW_LINE i , j = m , n NEW_LINE while ( i > 0 and j > 0 ) : NEW_LINE INDENT if ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT lcs [ index - 1 ] = X [ i - 1 ] NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE index -= 1 NEW_LINE DEDENT elif ( L [ i - 1 ] [ j ] > L [ i ] [ j - 1 ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT ans = " " NEW_LINE for x in range ( len ( lcs ) ) : NEW_LINE INDENT ans += lcs [ x ] NEW_LINE DEDENT return ans NEW_LINE DEDENT def longestPalSubseq ( string ) : NEW_LINE INDENT rev = string [ : : - 1 ] NEW_LINE return lcs_ ( string , rev ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GEEKSFORGEEKS " ; NEW_LINE print ( longestPalSubseq ( string ) ) NEW_LINE DEDENT |
Count all subsequences having product less than K | Function to count numbers of such subsequences having product less than k . ; number of subsequence using j - 1 terms ; if arr [ j - 1 ] > i it will surely make product greater thus it won 't contribute then ; number of subsequence using 1 to j - 1 terms and j - th term ; Driver code | def productSubSeqCount ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( k + 1 ) ] NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j - 1 ] NEW_LINE if arr [ j - 1 ] <= i and arr [ j - 1 ] > 0 : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i // arr [ j - 1 ] ] [ j - 1 ] + 1 NEW_LINE DEDENT DEDENT DEDENT return dp [ k ] [ n ] NEW_LINE DEDENT A = [ 1 , 2 , 3 , 4 ] NEW_LINE k = 10 NEW_LINE print ( productSubSeqCount ( A , k ) ) NEW_LINE |
Find the element that appears once in an array where every other element appears twice | function to find the once appearing element in array ; Do XOR of all elements and return ; Driver code | def findSingle ( ar , n ) : NEW_LINE INDENT res = ar [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = res ^ ar [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT ar = [ 2 , 3 , 5 , 4 , 5 , 3 , 4 ] NEW_LINE print " Element β occurring β once β is " , findSingle ( ar , len ( ar ) ) NEW_LINE |
Count all triplets whose sum is equal to a perfect cube | Python 3 program to calculate all triplets whose sum is perfect cube . ; Function to calculate all occurrence of a number in a given range ; if i == 0 assign 1 to present state ; else add + 1 to current state with previous state ; Function to calculate triplets whose sum is equal to the perfect cube ; Initialize answer ; count all occurrence of third triplet in range from j + 1 to n ; Driver code | dp = [ [ 0 for i in range ( 15001 ) ] for j in range ( 1001 ) ] NEW_LINE def computeDpArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , 15001 , 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( j == arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + ( arr [ i ] == j ) NEW_LINE DEDENT DEDENT DEDENT DEDENT def countTripletSum ( arr , n ) : NEW_LINE INDENT computeDpArray ( arr , n ) NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , n - 2 , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 , 1 ) : NEW_LINE INDENT for k in range ( 1 , 25 , 1 ) : NEW_LINE INDENT cube = k * k * k NEW_LINE rem = cube - ( arr [ i ] + arr [ j ] ) NEW_LINE if ( rem > 0 ) : NEW_LINE INDENT ans += dp [ n - 1 ] [ rem ] - dp [ j ] [ rem ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , 1 , 20 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countTripletSum ( arr , n ) ) NEW_LINE DEDENT |
Find the element that appears once in an array where every other element appears twice | function which find number ; applying the formula . ; driver code | def singleNumber ( nums ) : NEW_LINE INDENT return 2 * sum ( set ( nums ) ) - sum ( nums ) NEW_LINE DEDENT a = [ 2 , 3 , 5 , 4 , 5 , 3 , 4 ] NEW_LINE print ( int ( singleNumber ( a ) ) ) NEW_LINE a = [ 15 , 18 , 16 , 18 , 16 , 15 , 89 ] NEW_LINE print ( int ( singleNumber ( a ) ) ) NEW_LINE |
Maximum Subarray Sum Excluding Certain Elements | Function to check the element present in array B ; Utility function for findMaxSubarraySum ( ) with the following parameters A = > Array A , B = > Array B , n = > Number of elements in Array A , m = > Number of elements in Array B ; set max_so_far to INT_MIN ; if the element is present in B , set current max to 0 and move to the next element ; Proceed as in Kadane 's Algorithm ; Wrapper for findMaxSubarraySumUtil ( ) ; This case will occour when all elements of A are present in B , thus no subarray can be formed ; Driver code ; Function call | INT_MIN = - 2147483648 NEW_LINE def isPresent ( B , m , x ) : NEW_LINE INDENT for i in range ( 0 , m ) : NEW_LINE INDENT if B [ i ] == x : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findMaxSubarraySumUtil ( A , B , n , m ) : NEW_LINE INDENT max_so_far = INT_MIN NEW_LINE curr_max = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if isPresent ( B , m , A [ i ] ) == True : NEW_LINE INDENT curr_max = 0 NEW_LINE continue NEW_LINE DEDENT curr_max = max ( A [ i ] , curr_max + A [ i ] ) NEW_LINE max_so_far = max ( max_so_far , curr_max ) NEW_LINE DEDENT return max_so_far NEW_LINE DEDENT def findMaxSubarraySum ( A , B , n , m ) : NEW_LINE INDENT maxSubarraySum = findMaxSubarraySumUtil ( A , B , n , m ) NEW_LINE if maxSubarraySum == INT_MIN : NEW_LINE INDENT print ( ' Maximum β Subarray β Sum β cant β be β found ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' The β Maximum β Subarray β Sum β = ' , maxSubarraySum ) NEW_LINE DEDENT DEDENT A = [ 3 , 4 , 5 , - 4 , 6 ] NEW_LINE B = [ 1 , 8 , 5 ] NEW_LINE n = len ( A ) NEW_LINE m = len ( B ) NEW_LINE findMaxSubarraySum ( A , B , n , m ) NEW_LINE |
Number of n | Python3 program for counting n digit numbers with non decreasing digits ; Returns count of non - decreasing numbers with n digits . ; a [ i ] [ j ] = count of all possible number with i digits having leading digit as j ; Initialization of all 0 - digit number ; Initialization of all i - digit non - decreasing number leading with 9 ; for all digits we should calculate number of ways depending upon leading digits ; Driver Code | import numpy as np NEW_LINE def nonDecNums ( n ) : NEW_LINE INDENT a = np . zeros ( ( n + 1 , 10 ) ) NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT a [ 0 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT a [ i ] [ 9 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 8 , - 1 , - 1 ) : NEW_LINE INDENT a [ i ] [ j ] = a [ i - 1 ] [ j ] + a [ i ] [ j + 1 ] NEW_LINE DEDENT DEDENT return int ( a [ n ] [ 0 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE print ( " Non - decreasing β digits β = β " , nonDecNums ( n ) ) NEW_LINE DEDENT |
Count Balanced Binary Trees of Height h | Python3 program to count number of balanced binary trees of height h . ; base cases ; Driver program | def countBT ( h ) : NEW_LINE INDENT MOD = 1000000007 NEW_LINE dp = [ 0 for i in range ( h + 1 ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , h + 1 ) : NEW_LINE INDENT dp [ i ] = ( dp [ i - 1 ] * ( ( 2 * dp [ i - 2 ] ) % MOD + dp [ i - 1 ] ) % MOD ) % MOD NEW_LINE DEDENT return dp [ h ] NEW_LINE DEDENT h = 3 NEW_LINE print ( " No . β of β balanced β binary β trees β of β height β " + str ( h ) + " β is : β " + str ( countBT ( h ) ) ) NEW_LINE |
Maximum Subarray Sum Excluding Certain Elements | Python3 program implementation of the above idea ; Function to calculate the max sum of contigous subarray of B whose elements are not present in A ; Mark all the elements present in B ; Initialize max_so_far with INT_MIN ; Traverse the array A ; If current max is greater than max so far then update max so far ; Driver Code ; Function call | import sys NEW_LINE def findMaxSubarraySum ( A , B ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( len ( B ) ) : NEW_LINE INDENT if B [ i ] not in m : NEW_LINE INDENT m [ B [ i ] ] = 0 NEW_LINE DEDENT m [ B [ i ] ] = 1 NEW_LINE DEDENT max_so_far = - sys . maxsize - 1 NEW_LINE currmax = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( currmax < 0 or ( A [ i ] in m and m [ A [ i ] ] == 1 ) ) : NEW_LINE INDENT currmax = 0 NEW_LINE continue NEW_LINE DEDENT currmax = max ( A [ i ] , A [ i ] + currmax ) NEW_LINE if ( max_so_far < currmax ) : NEW_LINE INDENT max_so_far = currmax NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 3 , 4 , 5 , - 4 , 6 ] NEW_LINE b = [ 1 , 8 , 5 ] NEW_LINE print ( findMaxSubarraySum ( a , b ) ) NEW_LINE DEDENT |
Print all k | utility function to print contents of a vector from index i to it 's end ; Binary Tree Node ; This function prints all paths that have sum k ; empty node ; add current node to the path ; check if there 's any k sum path in the left sub-tree. ; check if there 's any k sum path in the right sub-tree. ; check if there 's any k sum path that terminates at this node Traverse the entire path as there can be negative elements too ; If path sum is k , print the path ; Remove the current element from the path ; A wrapper over printKPathUtil ( ) ; Driver Code | def printVector ( v , i ) : NEW_LINE INDENT for j in range ( i , len ( v ) ) : NEW_LINE INDENT print ( v [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT class newNode : 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 printKPathUtil ( root , path , k ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT path . append ( root . data ) NEW_LINE printKPathUtil ( root . left , path , k ) NEW_LINE printKPathUtil ( root . right , path , k ) NEW_LINE f = 0 NEW_LINE for j in range ( len ( path ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT f += path [ j ] NEW_LINE if ( f == k ) : NEW_LINE INDENT printVector ( path , j ) NEW_LINE DEDENT DEDENT path . pop ( - 1 ) NEW_LINE DEDENT def printKPath ( root , k ) : NEW_LINE INDENT path = [ ] NEW_LINE printKPathUtil ( root , path , k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 2 ) NEW_LINE root . left . right = newNode ( 1 ) NEW_LINE root . left . right . left = newNode ( 1 ) NEW_LINE root . right = newNode ( - 1 ) NEW_LINE root . right . left = newNode ( 4 ) NEW_LINE root . right . left . left = newNode ( 1 ) NEW_LINE root . right . left . right = newNode ( 2 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE root . right . right . right = newNode ( 2 ) NEW_LINE k = 5 NEW_LINE printKPath ( root , k ) NEW_LINE DEDENT |
Equilibrium index of an array | function to find the equilibrium index ; Check for indexes one by one until an equilibrium index is found ; get left sum ; get right sum ; if leftsum and rightsum are same , then we are done ; return - 1 if no equilibrium index is found ; driver code | def equilibrium ( arr ) : NEW_LINE INDENT leftsum = 0 NEW_LINE rightsum = 0 NEW_LINE n = len ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT leftsum = 0 NEW_LINE rightsum = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT leftsum += arr [ j ] NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT rightsum += arr [ j ] NEW_LINE DEDENT if leftsum == rightsum : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ - 7 , 1 , 5 , 2 , - 4 , 3 , 0 ] NEW_LINE print ( equilibrium ( arr ) ) NEW_LINE |
Find number of endless points | Python3 program to find count of endless points ; Returns count of endless points ; Fills column matrix . For every column , start from every last row and fill every entry as blockage after a 0 is found . ; flag which will be zero once we get a '0' and it will be 1 otherwise ; encountered a '0' , set the isEndless variable to false ; Similarly , fill row matrix ; Calculate total count of endless points ; If there is NO blockage in row or column after this point , increment result . print ( row [ i ] [ j ] , col [ i ] [ j ] ) ; Driver code | import numpy as np NEW_LINE def countEndless ( input_mat , n ) : NEW_LINE INDENT row = np . zeros ( ( n , n ) ) NEW_LINE col = np . zeros ( ( n , n ) ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT isEndless = 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( input_mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT isEndless = 0 NEW_LINE DEDENT col [ i ] [ j ] = isEndless NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT isEndless = 1 NEW_LINE for j in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( input_mat [ i ] [ j ] == 0 ) : NEW_LINE INDENT isEndless = 0 NEW_LINE DEDENT row [ i ] [ j ] = isEndless NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( row [ i ] [ j ] and col [ i ] [ j ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input_mat = [ [ 1 , 0 , 1 , 1 ] , [ 0 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 ] , [ 0 , 1 , 1 , 0 ] ] NEW_LINE n = 4 NEW_LINE print ( countEndless ( input_mat , n ) ) NEW_LINE DEDENT |
Equilibrium index of an array | function to find the equilibrium index ; finding the sum of whole array ; total_sum is now right sum for index i ; If no equilibrium index found , then return - 1 ; Driver code | def equilibrium ( arr ) : NEW_LINE INDENT total_sum = sum ( arr ) NEW_LINE leftsum = 0 NEW_LINE for i , num in enumerate ( arr ) : NEW_LINE INDENT total_sum -= num NEW_LINE if leftsum == total_sum : NEW_LINE INDENT return i NEW_LINE DEDENT leftsum += num NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ - 7 , 1 , 5 , 2 , - 4 , 3 , 0 ] NEW_LINE print ( ' First β equilibrium β index β is β ' , equilibrium ( arr ) ) NEW_LINE |
Sum of all substrings of a string representing a number | Set 1 | Returns sum of all substring of num ; allocate memory equal to length of string ; initialize first value with first digit ; loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; Driver code | def sumOfSubstrings ( num ) : NEW_LINE INDENT n = len ( num ) NEW_LINE sumofdigit = [ ] NEW_LINE sumofdigit . append ( int ( num [ 0 ] ) ) NEW_LINE res = sumofdigit [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT numi = int ( num [ i ] ) NEW_LINE sumofdigit . append ( ( i + 1 ) * numi + 10 * sumofdigit [ i - 1 ] ) NEW_LINE res += sumofdigit [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT num = "1234" NEW_LINE print ( sumOfSubstrings ( num ) ) NEW_LINE |
Sum of all substrings of a string representing a number | Set 1 | Returns sum of all substring of num ; storing prev value ; substrings sum upto current index loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; prev = current update previous ; Driver code to test above methods | def sumOfSubstrings ( num ) : NEW_LINE INDENT n = len ( num ) NEW_LINE prev = int ( num [ 0 ] ) NEW_LINE res = prev NEW_LINE current = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT numi = int ( num [ i ] ) NEW_LINE current = ( i + 1 ) * numi + 10 * prev NEW_LINE res += current NEW_LINE DEDENT return res NEW_LINE DEDENT num = "1234" NEW_LINE print ( sumOfSubstrings ( num ) ) NEW_LINE |
Equilibrium index of an array | Python program to find the equilibrium index of an array Function to find the equilibrium index ; Iterate from 0 to len ( arr ) ; If i is not 0 ; Iterate from 0 to len ( arr ) ; If no equilibrium index found , then return - 1 ; Driver code | def equilibrium ( arr ) : NEW_LINE INDENT left_sum = [ ] NEW_LINE right_sum = [ ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( i ) : NEW_LINE INDENT left_sum . append ( left_sum [ i - 1 ] + arr [ i ] ) NEW_LINE right_sum . append ( right_sum [ i - 1 ] + arr [ len ( arr ) - 1 - i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT left_sum . append ( arr [ i ] ) NEW_LINE right_sum . append ( arr [ len ( arr ) - 1 ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( left_sum [ i ] == right_sum [ len ( arr ) - 1 - i ] ) : NEW_LINE INDENT return ( i ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ - 7 , 1 , 5 , 2 , - 4 , 3 , 0 ] NEW_LINE print ( ' First β equilibrium β index β is β ' , equilibrium ( arr ) ) NEW_LINE |
Leaders in an array | Python Function to print leaders in array ; If loop didn 't break ; Driver function | def printLeaders ( arr , size ) : NEW_LINE INDENT for i in range ( 0 , size ) : NEW_LINE INDENT for j in range ( i + 1 , size ) : NEW_LINE INDENT if arr [ i ] <= arr [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if j == size - 1 : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT DEDENT arr = [ 16 , 17 , 4 , 3 , 5 , 2 ] NEW_LINE printLeaders ( arr , len ( arr ) ) NEW_LINE |
Leaders in an array | Python function to print leaders in array ; Rightmost element is always leader ; Driver function | def printLeaders ( arr , size ) : NEW_LINE INDENT max_from_right = arr [ size - 1 ] NEW_LINE print max_from_right , NEW_LINE for i in range ( size - 2 , - 1 , - 1 ) : NEW_LINE INDENT if max_from_right < arr [ i ] : NEW_LINE INDENT print arr [ i ] , NEW_LINE max_from_right = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT arr = [ 16 , 17 , 4 , 3 , 5 , 2 ] NEW_LINE printLeaders ( arr , len ( arr ) ) NEW_LINE |
Unbounded Knapsack ( Repetition of items allowed ) | Returns the maximum value with knapsack of W capacity ; dp [ i ] is going to store maximum value with knapsack capacity i . ; Fill dp [ ] using above recursive formula ; Driver program | def unboundedKnapsack ( W , n , val , wt ) : NEW_LINE INDENT dp = [ 0 for i in range ( W + 1 ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( W + 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( wt [ j ] <= i ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ i - wt [ j ] ] + val [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ W ] NEW_LINE DEDENT W = 100 NEW_LINE val = [ 10 , 30 , 20 ] NEW_LINE wt = [ 5 , 10 , 15 ] NEW_LINE n = len ( val ) NEW_LINE print ( unboundedKnapsack ( W , n , val , wt ) ) NEW_LINE |
Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to first element , then return the first element ; Otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ i + 1 ] , then return arr [ i + 1 ] ; If we reach here then x is greater than the last element of the array , return - 1 in this case ; Driver program to check above functions | def ceilSearch ( arr , low , high , x ) : NEW_LINE INDENT if x <= arr [ low ] : NEW_LINE INDENT return low NEW_LINE DEDENT i = low NEW_LINE for i in range ( high ) : NEW_LINE INDENT if arr [ i ] == x : NEW_LINE INDENT return i NEW_LINE DEDENT if arr [ i ] < x and arr [ i + 1 ] >= x : NEW_LINE INDENT return i + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 1 , 2 , 8 , 10 , 10 , 12 , 19 ] NEW_LINE n = len ( arr ) NEW_LINE x = 3 NEW_LINE index = ceilSearch ( arr , 0 , n - 1 , x ) ; NEW_LINE if index == - 1 : NEW_LINE INDENT print ( " Ceiling β of β % d β doesn ' t β exist β in β array β " % x ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ceiling β of β % d β is β % d " % ( x , arr [ index ] ) ) NEW_LINE DEDENT |
Maximum sum subarray removing at most one element | Method returns maximum sum of all subarray where removing one element is also allowed ; Maximum sum subarrays in forward and backward directions ; Initialize current max and max so far . ; calculating maximum sum subarrays in forward direction ; storing current maximum till ith , in forward array ; calculating maximum sum subarrays in backward direction ; storing current maximum from ith , in backward array ; Initializing final ans by max_so_far so that , case when no element is removed to get max sum subarray is also handled ; choosing maximum ignoring ith element ; Driver code to test above methods | def maxSumSubarrayRemovingOneEle ( arr , n ) : NEW_LINE INDENT fw = [ 0 for k in range ( n ) ] NEW_LINE bw = [ 0 for k in range ( n ) ] NEW_LINE cur_max , max_so_far = arr [ 0 ] , arr [ 0 ] NEW_LINE fw [ 0 ] = cur_max NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT cur_max = max ( arr [ i ] , cur_max + arr [ i ] ) NEW_LINE max_so_far = max ( max_so_far , cur_max ) NEW_LINE fw [ i ] = cur_max NEW_LINE DEDENT cur_max = max_so_far = bw [ n - 1 ] = arr [ n - 1 ] NEW_LINE i = n - 2 NEW_LINE while i >= 0 : NEW_LINE INDENT cur_max = max ( arr [ i ] , cur_max + arr [ i ] ) NEW_LINE max_so_far = max ( max_so_far , cur_max ) NEW_LINE bw [ i ] = cur_max NEW_LINE i -= 1 NEW_LINE DEDENT fans = max_so_far NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT fans = max ( fans , fw [ i - 1 ] + bw [ i + 1 ] ) NEW_LINE DEDENT return fans NEW_LINE DEDENT arr = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE print maxSumSubarrayRemovingOneEle ( arr , n ) NEW_LINE |
Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] low + ( high - low ) / 2 ; If x is same as middle element , then return mid ; If x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; If x is smaller than arr [ mid ] , then either arr [ mid ] is ceiling of x or ceiling lies in arr [ low ... mid - 1 ] ; Driver program to check above functions | def ceilSearch ( arr , low , high , x ) : NEW_LINE INDENT if x <= arr [ low ] : NEW_LINE INDENT return low NEW_LINE DEDENT if x > arr [ high ] : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( low + high ) / 2 ; NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] < x : NEW_LINE INDENT if mid + 1 <= high and x <= arr [ mid + 1 ] : NEW_LINE INDENT return mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ceilSearch ( arr , mid + 1 , high , x ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if mid - 1 >= low and x > arr [ mid - 1 ] : NEW_LINE INDENT return mid NEW_LINE DEDENT else : NEW_LINE INDENT return ceilSearch ( arr , low , mid - 1 , x ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , 8 , 10 , 10 , 12 , 19 ] NEW_LINE n = len ( arr ) NEW_LINE x = 20 NEW_LINE index = ceilSearch ( arr , 0 , n - 1 , x ) ; NEW_LINE if index == - 1 : NEW_LINE INDENT print ( " Ceiling β of β % d β doesn ' t β exist β in β array β " % x ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " ceiling β of β % d β is β % d " % ( x , arr [ index ] ) ) NEW_LINE DEDENT |
Sum of heights of all individual nodes in a binary tree | Compute the " maxHeight " of a particular Node ; compute the height of each subtree ; use the larger one ; Helper class that allocates a new Node with the given data and None left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code | def getHeight ( Node ) : NEW_LINE INDENT if ( Node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lHeight = getHeight ( Node . left ) NEW_LINE rHeight = getHeight ( Node . right ) NEW_LINE if ( lHeight > rHeight ) : NEW_LINE INDENT return ( lHeight + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( rHeight + 1 ) NEW_LINE DEDENT DEDENT DEDENT 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 getTotalHeight ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( getTotalHeight ( root . left ) + getHeight ( root ) + getTotalHeight ( root . right ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE DEDENT print ( " Sum β of β heights β of β all β Nodes β = " , getTotalHeight ( root ) ) NEW_LINE |
Path with maximum average value | Maximum number of rows and / or columns ; method returns maximum average of all path of cost matrix ; Initialize first column of total cost ( dp ) array ; Initialize first row of dp array ; Construct rest of the dp array ; divide maximum sum by constant path length : ( 2 N - 1 ) for getting average ; Driver program to test above function | M = 100 NEW_LINE def maxAverageOfPath ( cost , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = cost [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + cost [ i ] [ 0 ] NEW_LINE DEDENT for j in range ( 1 , N ) : NEW_LINE INDENT dp [ 0 ] [ j ] = dp [ 0 ] [ j - 1 ] + cost [ 0 ] [ j ] NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) + cost [ i ] [ j ] NEW_LINE DEDENT DEDENT return dp [ N - 1 ] [ N - 1 ] / ( 2 * N - 1 ) NEW_LINE DEDENT cost = [ [ 1 , 2 , 3 ] , [ 6 , 5 , 4 ] , [ 7 , 3 , 9 ] ] NEW_LINE print ( maxAverageOfPath ( cost , 3 ) ) NEW_LINE |
Maximum weight path ending at any element of last row in a matrix | Python3 program to find the path having the maximum weight in matrix ; Function which return the maximum weight path sum ; creat 2D matrix to store the sum of the path ; Initialize first column of total weight array ( dp [ i to N ] [ 0 ] ) ; Calculate rest path sum of weight matrix ; find the max weight path sum to reach the last row ; return maximum weight path sum ; Driver Program | MAX = 1000 NEW_LINE def maxCost ( mat , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , min ( i + 1 , N ) ) : NEW_LINE INDENT dp [ i ] [ j ] = mat [ i ] [ j ] + max ( dp [ i - 1 ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT result = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( result < dp [ N - 1 ] [ i ] ) : NEW_LINE INDENT result = dp [ N - 1 ] [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT mat = [ [ 4 , 1 , 5 , 6 , 1 ] , [ 2 , 9 , 2 , 11 , 10 ] , [ 15 , 1 , 3 , 15 , 2 ] , [ 16 , 92 , 41 , 4 , 3 ] , [ 8 , 142 , 6 , 4 , 8 ] ] NEW_LINE N = 5 NEW_LINE print ( ' Maximum β Path β Sum β : ' , maxCost ( mat , N ) ) NEW_LINE |
Number of permutation with K inversions | Limit on N and K ; 2D array memo for stopping solving same problem again ; method recursively calculates permutation with K inversion ; Base cases ; If already solved then return result directly ; Calling recursively all subproblem of permutation size N - 1 ; Call recursively only if total inversion to be made are less than size ; store result into memo ; Driver code | M = 100 NEW_LINE memo = [ [ 0 for i in range ( M ) ] for j in range ( M ) ] NEW_LINE def numberOfPermWithKInversion ( N , K ) : NEW_LINE INDENT if ( N == 0 ) : return 0 NEW_LINE if ( K == 0 ) : return 1 NEW_LINE if ( memo [ N ] [ K ] != 0 ) : NEW_LINE INDENT return memo [ N ] [ K ] NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( K + 1 ) : NEW_LINE INDENT if ( i <= N - 1 ) : NEW_LINE INDENT sum += numberOfPermWithKInversion ( N - 1 , K - i ) NEW_LINE DEDENT DEDENT memo [ N ] [ K ] = sum NEW_LINE return sum NEW_LINE DEDENT N = 4 ; K = 2 NEW_LINE print ( numberOfPermWithKInversion ( N , K ) ) NEW_LINE |
Check if an array has a majority element | Returns true if there is a majority element in a [ ] ; Insert all elements in a hash table ; Check if frequency of any element is n / 2 or more . ; Driver code | def isMajority ( a ) : NEW_LINE INDENT mp = { } NEW_LINE for i in a : NEW_LINE INDENT if i in mp : mp [ i ] += 1 NEW_LINE else : mp [ i ] = 1 NEW_LINE DEDENT for x in mp : NEW_LINE INDENT if mp [ x ] >= len ( a ) // 2 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT a = [ 2 , 3 , 9 , 2 , 2 ] NEW_LINE print ( " Yes " if isMajority ( a ) else " No " ) NEW_LINE |
Two Pointers Technique | Naive solution to find if there is a pair in A [ 0. . N - 1 ] with given sum . ; as equal i and j means same element ; pair exists ; as the array is sorted ; No pair found with given sum ; Driver code ; Function call | def isPairSum ( A , N , X ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( A [ i ] + A [ j ] == X ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( A [ i ] + A [ j ] > X ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT arr = [ 3 , 5 , 9 , 2 , 8 , 10 , 11 ] NEW_LINE val = 17 NEW_LINE print ( isPairSum ( arr , len ( arr ) , val ) ) NEW_LINE |
Remove minimum elements from either side such that 2 * min becomes more than max | A utility function to find minimum in arr [ l . . h ] ; A utility function to find maximum in arr [ l . . h ] ; Returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; If there is 1 or less elements , return 0 For a single element , 2 * min > max ( Assumption : All elements are positive in arr [ ] ) ; 1 ) Find minimum and maximum in arr [ l . . h ] ; If the property is followed , no removals needed ; Otherwise remove a character from left end and recur , then remove a character from right end and recur , take the minimum of two is returned ; Driver Code | def mini ( arr , l , h ) : NEW_LINE INDENT mn = arr [ l ] NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( mn > arr [ i ] ) : NEW_LINE INDENT mn = arr [ i ] NEW_LINE DEDENT DEDENT return mn NEW_LINE DEDENT def max ( arr , l , h ) : NEW_LINE INDENT mx = arr [ l ] NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( mx < arr [ i ] ) : NEW_LINE INDENT mx = arr [ i ] NEW_LINE DEDENT DEDENT return mx NEW_LINE DEDENT def minRemovals ( arr , l , h ) : NEW_LINE INDENT if ( l >= h ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mn = mini ( arr , l , h ) NEW_LINE mx = max ( arr , l , h ) NEW_LINE if ( 2 * mn > mx ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( min ( minRemovals ( arr , l + 1 , h ) , minRemovals ( arr , l , h - 1 ) ) + 1 ) NEW_LINE DEDENT arr = [ 4 , 5 , 100 , 9 , 10 , 11 , 12 , 15 , 200 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minRemovals ( arr , 0 , n - 1 ) ) NEW_LINE |
Two Pointers Technique | Two pointer technique based solution to find if there is a pair in A [ 0. . N - 1 ] with a given sum . ; represents first pointer ; represents second pointer ; If we find a pair ; If sum of elements at current pointers is less , we move towards higher values by doing i += 1 ; If sum of elements at current pointers is more , we move towards lower values by doing j -= 1 ; array declaration ; value to search ; Function call | def isPairSum ( A , N , X ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( A [ i ] + A [ j ] == X ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( A [ i ] + A [ j ] < X ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT arr = [ 3 , 5 , 9 , 2 , 8 , 10 , 11 ] NEW_LINE val = 17 NEW_LINE print ( isPairSum ( arr , len ( arr ) , val ) ) NEW_LINE |
Sum of heights of all individual nodes in a binary tree | A binary tree Node has data , pointer to left child and a pointer to right child ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code | 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 sum = 0 NEW_LINE def getTotalHeightUtil ( root ) : NEW_LINE INDENT global sum NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT lh = getTotalHeightUtil ( root . left ) NEW_LINE rh = getTotalHeightUtil ( root . right ) NEW_LINE h = max ( lh , rh ) + 1 NEW_LINE sum = sum + h NEW_LINE return h NEW_LINE DEDENT def getTotalHeight ( root ) : NEW_LINE INDENT getTotalHeightUtil ( root ) NEW_LINE return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( " Sum β of β heights β of β all β Nodes β = " , getTotalHeight ( root ) ) NEW_LINE DEDENT |
Inorder Tree Traversal without Recursion | A binary tree node ; Iterative function for inorder tree traversal ; traverse the tree ; Reach the left most Node of the current Node ; Place pointer to a tree node on the stack before traversing the node 's left subtree ; BackTrack from the empty subtree and visit the Node at the top of the stack ; however , if the stack is empty you are done ; We have visited the node and its left subtree . Now , it ' s β right β subtree ' s turn ; Constructed binary tree is 1 / \ 2 3 / \ 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 inOrder ( root ) : NEW_LINE INDENT current = root NEW_LINE stack = [ ] NEW_LINE done = 0 NEW_LINE while True : NEW_LINE INDENT if current is not None : NEW_LINE INDENT stack . append ( current ) NEW_LINE current = current . left NEW_LINE DEDENT elif ( stack ) : NEW_LINE INDENT current = stack . pop ( ) NEW_LINE print ( current . data , end = " β " ) NEW_LINE current = current . right NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE inOrder ( root ) NEW_LINE |
Count all possible paths from top left to bottom right of a mXn matrix | Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 2D table to store results of subproblems one - liner logic to take input for rows and columns mat = [ [ int ( input ( ) ) for x in range ( C ) ] for y in range ( R ) ] ; Count of paths to reach any cell in first column is 1 ; Count of paths to reach any cell in first column is 1 ; Calculate count of paths for other cells in bottom - up manner using the recursive solution ; By uncommenting the last part the code calculates the total possible paths if the diagonal Movements are allowed ; Driver program to test above function | def numberOfPaths ( m , n ) : NEW_LINE INDENT count = [ [ 0 for x in range ( n ) ] for y in range ( m ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT count [ i ] [ 0 ] = 1 ; NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT count [ 0 ] [ j ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT count [ i ] [ j ] = count [ i - 1 ] [ j ] + count [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT return count [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT m = 3 NEW_LINE n = 3 NEW_LINE print ( numberOfPaths ( m , n ) ) NEW_LINE |
Split array into two equal length subsets such that all repetitions of a number lies in a single subset | Python3 program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store frequencies in subset [ ] array ; Return frequency array ; Function to check is sum N / 2 can be formed using some subset ; dp [ i ] [ j ] store the answer to form sum j using 1 st i elements ; Initialize dp [ ] [ ] with true ; Fill the subset table in the bottom up manner ; If current element is less than j ; Update current state ; Return the result ; Function to check if the given array can be split into required sets ; Store frequencies of arr [ ] ; If size of arr [ ] is odd then print " Yes " ; Check if answer is true or not ; Print the result ; Driver Code ; Given array arr ; Function Call | from collections import defaultdict NEW_LINE def findSubsets ( arr ) : NEW_LINE INDENT M = defaultdict ( int ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 NEW_LINE DEDENT subsets = [ 0 ] * len ( M ) NEW_LINE i = 0 NEW_LINE for j in M : NEW_LINE INDENT subsets [ i ] = M [ j ] NEW_LINE i += 1 NEW_LINE DEDENT return subsets NEW_LINE DEDENT def subsetSum ( subsets , target ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( target + 1 ) ] for y in range ( len ( subsets ) + 1 ) ] NEW_LINE for i in range ( len ( dp ) ) : NEW_LINE INDENT dp [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , len ( subsets ) + 1 ) : NEW_LINE INDENT for j in range ( 1 , target + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE if ( j >= subsets [ i - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] |= ( dp [ i - 1 ] [ j - subsets [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ len ( subsets ) ] [ target ] NEW_LINE DEDENT def divideInto2Subset ( arr ) : NEW_LINE INDENT subsets = findSubsets ( arr ) NEW_LINE if ( len ( arr ) % 2 == 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT isPossible = subsetSum ( subsets , len ( arr ) // 2 ) NEW_LINE if ( isPossible ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 2 , 3 ] NEW_LINE divideInto2Subset ( arr ) NEW_LINE DEDENT |
Maximum Product Cutting | DP | The main function that returns maximum product obtainable from a rope of length n ; Base cases ; Make a cut at different places and take the maximum of all ; Return the maximum of all values ; Driver program to test above functions | def maxProd ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT max_val = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT max_val = max ( max_val , max ( i * ( n - i ) , maxProd ( n - i ) * i ) ) NEW_LINE DEDENT return max_val ; NEW_LINE DEDENT print ( " Maximum β Product β is β " , maxProd ( 10 ) ) ; NEW_LINE |
Assembly Line Scheduling | DP | Python program to find minimum possible time by the car chassis to complete ; time taken to leave ; first station in line 1 time taken to leave ; Fill tables T1 [ ] and T2 [ ] using above given recursive relations ; consider exit times and return minimum ; Driver code | def carAssembly ( a , t , e , x ) : NEW_LINE INDENT NUM_STATION = len ( a [ 0 ] ) NEW_LINE T1 = [ 0 for i in range ( NUM_STATION ) ] NEW_LINE T2 = [ 0 for i in range ( NUM_STATION ) ] NEW_LINE DEDENT T1 [ 0 ] = e [ 0 ] + a [ 0 ] [ 0 ] NEW_LINE T2 [ 0 ] = e [ 1 ] + a [ 1 ] [ 0 ] NEW_LINE INDENT for i in range ( 1 , NUM_STATION ) : NEW_LINE INDENT T1 [ i ] = min ( T1 [ i - 1 ] + a [ 0 ] [ i ] , T2 [ i - 1 ] + t [ 1 ] [ i ] + a [ 0 ] [ i ] ) NEW_LINE T2 [ i ] = min ( T2 [ i - 1 ] + a [ 1 ] [ i ] , T1 [ i - 1 ] + t [ 0 ] [ i ] + a [ 1 ] [ i ] ) NEW_LINE DEDENT return min ( T1 [ NUM_STATION - 1 ] + x [ 0 ] , T2 [ NUM_STATION - 1 ] + x [ 1 ] ) NEW_LINE DEDENT a = [ [ 4 , 5 , 3 , 2 ] , [ 2 , 10 , 1 , 4 ] ] NEW_LINE t = [ [ 0 , 7 , 4 , 5 ] , [ 0 , 9 , 2 , 8 ] ] NEW_LINE e = [ 10 , 12 ] NEW_LINE x = [ 18 , 7 ] NEW_LINE print ( carAssembly ( a , t , e , x ) ) NEW_LINE |
Longest Common Substring | DP | Returns length of longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains the length of longest common suffix of X [ 0. . . i - 1 ] and Y [ 0. . . j - 1 ] . The first row and first column entries have no logical meaning , they are used only for simplicity of the program . ; To store the length of longest common substring ; Following steps to build LCSuff [ m + 1 ] [ n + 1 ] in bottom up fashion ; Driver Code | def LCSubStr ( X , Y , m , n ) : NEW_LINE INDENT LCSuff = [ [ 0 for k in range ( n + 1 ) ] for l in range ( m + 1 ) ] NEW_LINE result = 0 NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 NEW_LINE result = max ( result , LCSuff [ i ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT X = ' OldSite : GeeksforGeeks . org ' NEW_LINE Y = ' NewSite : GeeksQuiz . com ' NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE print ( ' Length β of β Longest β Common β Substring β is ' , LCSubStr ( X , Y , m , n ) ) NEW_LINE |
Minimum insertions to form a palindrome | DP | A utility function to find minimum of two integers ; A DP function to find minimum number of insertions ; Create a table of size n * n . table [ i ] [ j ] will store minimum number of insertions needed to convert str1 [ i . . j ] to a palindrome . ; Fill the table ; Return minimum number of insertions for str1 [ 0. . n - 1 ] ; Driver Code | def Min ( a , b ) : NEW_LINE INDENT return min ( a , b ) NEW_LINE DEDENT def findMinInsertionsDP ( str1 , n ) : NEW_LINE INDENT table = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE l , h , gap = 0 , 0 , 0 NEW_LINE for gap in range ( 1 , n ) : NEW_LINE INDENT l = 0 NEW_LINE for h in range ( gap , n ) : NEW_LINE INDENT if str1 [ l ] == str1 [ h ] : NEW_LINE INDENT table [ l ] [ h ] = table [ l + 1 ] [ h - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT table [ l ] [ h ] = ( Min ( table [ l ] [ h - 1 ] , table [ l + 1 ] [ h ] ) + 1 ) NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT return table [ 0 ] [ n - 1 ] ; NEW_LINE DEDENT str1 = " geeks " NEW_LINE print ( findMinInsertionsDP ( str1 , len ( str1 ) ) ) NEW_LINE |
Maximum Subarray Sum using Divide and Conquer algorithm | Find the maximum possible sum in arr [ ] auch that arr [ m ] is part of it ; Include elements on left of mid . ; Include elements on right of mid ; Return sum of elements on left and right of mid returning only left_sum + right_sum will fail for [ - 2 , 1 ] ; Returns sum of maximum sum subarray in aa [ l . . h ] ; Base Case : Only one element ; Find middle point ; Return maximum of following three possible cases a ) Maximum subarray sum in left half b ) Maximum subarray sum in right half c ) Maximum subarray sum such that the subarray crosses the midpoint ; Driver Code | def maxCrossingSum ( arr , l , m , h ) : NEW_LINE INDENT sm = 0 NEW_LINE left_sum = - 10000 NEW_LINE for i in range ( m , l - 1 , - 1 ) : NEW_LINE INDENT sm = sm + arr [ i ] NEW_LINE if ( sm > left_sum ) : NEW_LINE INDENT left_sum = sm NEW_LINE DEDENT DEDENT sm = 0 NEW_LINE right_sum = - 1000 NEW_LINE for i in range ( m + 1 , h + 1 ) : NEW_LINE INDENT sm = sm + arr [ i ] NEW_LINE if ( sm > right_sum ) : NEW_LINE INDENT right_sum = sm NEW_LINE DEDENT DEDENT return max ( left_sum + right_sum , left_sum , right_sum ) NEW_LINE DEDENT def maxSubArraySum ( arr , l , h ) : NEW_LINE INDENT if ( l == h ) : NEW_LINE INDENT return arr [ l ] NEW_LINE DEDENT m = ( l + h ) // 2 NEW_LINE return max ( maxSubArraySum ( arr , l , m ) , maxSubArraySum ( arr , m + 1 , h ) , maxCrossingSum ( arr , l , m , h ) ) NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 5 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE max_sum = maxSubArraySum ( arr , 0 , n - 1 ) NEW_LINE print ( " Maximum β contiguous β sum β is β " , max_sum ) NEW_LINE |
Largest Independent Set Problem | DP | A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree ; Calculate size excluding the current node ; Calculate size including the current node ; Return the maximum of two sizes ; A utility function to create a node ; Let us construct the tree given in the above diagram | def max ( x , y ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return y NEW_LINE DEDENT DEDENT class node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def LISS ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT size_excl = LISS ( root . left ) + LISS ( root . right ) NEW_LINE size_incl = 1 NEW_LINE if ( root . left != None ) : NEW_LINE INDENT size_incl += LISS ( root . left . left ) + LISS ( root . left . right ) NEW_LINE DEDENT if ( root . right != None ) : NEW_LINE INDENT size_incl += LISS ( root . right . left ) + LISS ( root . right . right ) NEW_LINE DEDENT return max ( size_incl , size_excl ) NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( ) NEW_LINE temp . data = data NEW_LINE temp . left = temp . right = None NEW_LINE return temp NEW_LINE DEDENT root = newNode ( 20 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 12 ) NEW_LINE root . left . right . left = newNode ( 10 ) NEW_LINE root . left . right . right = newNode ( 14 ) NEW_LINE root . right = newNode ( 22 ) NEW_LINE root . right . right = newNode ( 25 ) NEW_LINE print ( " Size β of β the β Largest " , " β Independent β Set β is β " , LISS ( root ) ) NEW_LINE |
Program to find amount of water in a given glass | Returns the amount of water in jth glass of ith row ; A row number i has maximum i columns . So input column number must be less than i ; There will be i * ( i + 1 ) / 2 glasses till ith row ( including ith row ) and Initialize all glasses as empty ; Put all water in first glass ; Now let the water flow to the downward glasses till the row number is less than or / equal to i ( given row ) correction : X can be zero for side glasses as they have lower rate to fill ; Fill glasses in a given row . Number of columns in a row is equal to row number ; Get the water from current glass ; Keep the amount less than or equal to capacity in current glass ; Get the remaining amount ; Distribute the remaining amount to the down two glasses ; The index of jth glass in ith row will be i * ( i - 1 ) / 2 + j - 1 ; Driver Code ; Total amount of water | def findWater ( i , j , X ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT print ( " Incorrect β Input " ) ; NEW_LINE return ; NEW_LINE DEDENT glass = [ 0 ] * int ( i * ( i + 1 ) / 2 ) ; NEW_LINE index = 0 ; NEW_LINE glass [ index ] = X ; NEW_LINE for row in range ( 1 , i ) : NEW_LINE INDENT for col in range ( 1 , row + 1 ) : NEW_LINE INDENT X = glass [ index ] ; NEW_LINE glass [ index ] = 1.0 if ( X >= 1.0 ) else X ; NEW_LINE X = ( X - 1 ) if ( X >= 1.0 ) else 0.0 ; NEW_LINE glass [ index + row ] += ( X / 2 ) ; NEW_LINE glass [ index + row + 1 ] += ( X / 2 ) ; NEW_LINE index += 1 ; NEW_LINE DEDENT DEDENT return glass [ int ( i * ( i - 1 ) / 2 + j - 1 ) ] ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT i = 2 ; NEW_LINE j = 2 ; NEW_LINE X = 2.0 ; NEW_LINE res = repr ( findWater ( i , j , X ) ) ; NEW_LINE print ( " Amount β of β water β in β jth β glass β of β ith β row β is : " , res . ljust ( 8 , '0' ) ) ; NEW_LINE DEDENT |
Maximum Length Chain of Pairs | DP | Python program for above approach ; This function assumes that arr [ ] is sorted in increasing order according the first ( or smaller ) values in pairs . ; Initialize MCL ( max chain length ) values for all indices ; Compute optimized chain length values in bottom up manner ; Pick maximum of all MCL values ; Driver program to test above function | class Pair ( object ) : NEW_LINE INDENT def __init__ ( self , a , b ) : NEW_LINE INDENT self . a = a NEW_LINE self . b = b NEW_LINE DEDENT DEDENT def maxChainLength ( arr , n ) : NEW_LINE INDENT max = 0 NEW_LINE mcl = [ 1 for i in range ( n ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if ( arr [ i ] . a > arr [ j ] . b and mcl [ i ] < mcl [ j ] + 1 ) : NEW_LINE INDENT mcl [ i ] = mcl [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( max < mcl [ i ] ) : NEW_LINE INDENT max = mcl [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT arr = [ Pair ( 5 , 24 ) , Pair ( 15 , 25 ) , Pair ( 27 , 40 ) , Pair ( 50 , 60 ) ] NEW_LINE print ( ' Length β of β maximum β size β chain β is ' , maxChainLength ( arr , len ( arr ) ) ) NEW_LINE |
Palindrome Partitioning | DP | Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum number of cuts needed for palindrome partitioning of substring str [ i . . j ] P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false . Note that C [ i ] [ j ] is 0 if P [ i ] [ j ] is true ; different looping variables ; Every substring of length 1 is a palindrome ; L is substring length . Build the solution in bottom - up manner by considering all substrings of length starting from 2 to n . The loop structure is the same as Matrix Chain Multiplication problem ( See https : www . geeksforgeeks . org / matrix - chain - multiplication - dp - 8 / ) ; For substring of length L , set different possible starting indexes ; Set ending index ; If L is 2 , then we just need to compare two characters . Else need to check two corner characters and value of P [ i + 1 ] [ j - 1 ] ; IF str [ i . . j ] is palindrome , then C [ i ] [ j ] is 0 ; Make a cut at every possible location starting from i to j , and get the minimum cost cut . ; Return the min cut value for complete string . i . e . , str [ 0. . n - 1 ] ; Driver code | def minPalPartion ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE C = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE P = [ [ False for i in range ( n ) ] for i in range ( n ) ] NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE L = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT P [ i ] [ i ] = True ; NEW_LINE C [ i ] [ i ] = 0 ; NEW_LINE DEDENT for L in range ( 2 , n + 1 ) : NEW_LINE INDENT for i in range ( n - L + 1 ) : NEW_LINE INDENT j = i + L - 1 NEW_LINE if L == 2 : NEW_LINE INDENT P [ i ] [ j ] = ( str [ i ] == str [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT P [ i ] [ j ] = ( ( str [ i ] == str [ j ] ) and P [ i + 1 ] [ j - 1 ] ) NEW_LINE DEDENT if P [ i ] [ j ] == True : NEW_LINE INDENT C [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = 100000000 NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT C [ i ] [ j ] = min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return C [ 0 ] [ n - 1 ] NEW_LINE DEDENT str = " ababbbabbababa " NEW_LINE print ( ' Min β cuts β needed β for β Palindrome β Partitioning β is ' , minPalPartion ( str ) ) NEW_LINE |
Count subtrees that sum up to a given value x only using single recursive function | class to get a new node ; put in the data ; function to count subtress that Sum up to a given value x ; if tree is empty ; Sum of nodes in the left subtree ; Sum of nodes in the right subtree ; Sum of nodes in the subtree rooted with 'root.data ; if true ; return subtree 's nodes Sum ; utility function to count subtress that Sum up to a given value x ; if tree is empty ; Sum of nodes in the left subtree ; Sum of nodes in the right subtree ; if tree 's nodes Sum == x ; required count of subtrees ; Driver Code ; binary tree creation 5 / \ - 10 3 / \ / \ 9 8 - 4 7 | class getNode : 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 countSubtreesWithSumX ( root , count , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ls = countSubtreesWithSumX ( root . left , count , x ) NEW_LINE rs = countSubtreesWithSumX ( root . right , count , x ) NEW_LINE Sum = ls + rs + root . data NEW_LINE if ( Sum == x ) : NEW_LINE INDENT count [ 0 ] += 1 NEW_LINE DEDENT return Sum NEW_LINE DEDENT def countSubtreesWithSumXUtil ( root , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = [ 0 ] NEW_LINE ls = countSubtreesWithSumX ( root . left , count , x ) NEW_LINE rs = countSubtreesWithSumX ( root . right , count , x ) NEW_LINE if ( ( ls + rs + root . data ) == x ) : NEW_LINE INDENT count [ 0 ] += 1 NEW_LINE DEDENT return count [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 5 ) NEW_LINE root . left = getNode ( - 10 ) NEW_LINE root . right = getNode ( 3 ) NEW_LINE root . left . left = getNode ( 9 ) NEW_LINE root . left . right = getNode ( 8 ) NEW_LINE root . right . left = getNode ( - 4 ) NEW_LINE root . right . right = getNode ( 7 ) NEW_LINE x = 7 NEW_LINE print ( " Count β = " , countSubtreesWithSumXUtil ( root , x ) ) NEW_LINE DEDENT |
Minimum replacements required to make given Matrix palindromic | Function to count minimum changes to make the matrix palindromic ; Rows in the matrix ; Columns in the matrix ; Traverse the given matrix ; Store the frequency of the four cells ; Iterate over the map ; Min changes to do to make all ; Four elements equal ; Make the middle row palindromic ; Make the middle column palindromic ; Prminimum changes ; Given matrix ; Function Call | def minchanges ( mat ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE ans = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT for j in range ( M // 2 ) : NEW_LINE INDENT mp [ mat [ i ] [ M - 1 - j ] ] = mp . get ( mat [ i ] [ M - 1 - j ] , 0 ) + 1 NEW_LINE mp [ mat [ i ] [ j ] ] = mp . get ( mat [ i ] [ j ] , 0 ) + 1 NEW_LINE mp [ mat [ N - 1 - i ] [ M - 1 - j ] ] = mp . get ( mat [ N - 1 - i ] [ M - 1 - j ] , 0 ) + 1 NEW_LINE mp [ mat [ N - 1 - i ] [ j ] ] = mp . get ( mat [ N - 1 - i ] [ j ] , 0 ) + 1 NEW_LINE x = 0 NEW_LINE for it in mp : NEW_LINE INDENT x = max ( x , mp [ it ] ) NEW_LINE DEDENT ans = ans + 4 - x NEW_LINE mp . clear ( ) NEW_LINE DEDENT DEDENT if ( N % 2 == 1 ) : NEW_LINE INDENT for i in range ( M // 2 ) : NEW_LINE INDENT if ( mat [ N // 2 ] [ i ] != mat [ N // 2 ] [ M - 1 - i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT if ( M % 2 == 1 ) : NEW_LINE INDENT for i in range ( N // 2 ) : NEW_LINE INDENT if ( mat [ i ] [ M // 2 ] != mat [ N - 1 - i ] [ M // 2 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 3 ] , [ 1 , 2 , 1 ] ] NEW_LINE minchanges ( mat ) NEW_LINE |
Check if a number starts with another number or not | Function to check if B is a prefix of A or not ; Convert numbers into strings ; Check if s2 is a prefix of s1 or not using startswith ( ) function ; If result is true print Yes ; Driver code ; Given numbers ; Function call | def checkprefix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) NEW_LINE s2 = str ( B ) NEW_LINE result = s1 . startswith ( s2 ) NEW_LINE if result : 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 = 12345 NEW_LINE B = 12 NEW_LINE checkprefix ( A , B ) NEW_LINE DEDENT |
Check three or more consecutive identical characters or numbers | Python3 program to check three or more consecutiveidentical characters or numbers using regular expression ; Function to check three or more consecutiveidentical characters or numbers using regular expression ; Regex to check three or more consecutive identical characters or numbers ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 : | import re NEW_LINE def isValidGUID ( str ) : NEW_LINE INDENT regex = " \\b ( [ a - zA - Z0-9 ] ) \\1\\1 + \\b " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = " aaa " NEW_LINE print ( isValidGUID ( str1 ) ) NEW_LINE str2 = "11111" NEW_LINE print ( isValidGUID ( str2 ) ) NEW_LINE str3 = " aaab " NEW_LINE print ( isValidGUID ( str3 ) ) NEW_LINE str4 = " abc " NEW_LINE print ( isValidGUID ( str4 ) ) NEW_LINE str5 = " aa " NEW_LINE print ( isValidGUID ( str5 ) ) NEW_LINE |
How to validate MAC address using Regular Expression | Python3 program to validate MAC address using using regular expression ; Function to validate MAC address . ; Regex to check valid MAC address ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 : | import re NEW_LINE def isValidMACAddress ( str ) : NEW_LINE INDENT regex = ( " ^ ( [0-9A - Fa - f ] {2 } [ : - ] ) " + " { 5 } ( [0-9A - Fa - f ] {2 } ) | " + " ( [0-9a - fA - F ] {4 } \\ . " + " [ 0-9a - fA - F ] {4 } \\ . " + " [ 0-9a - fA - F ] {4 } ) $ " ) NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = "01-23-45-67-89 - AB " NEW_LINE print ( isValidMACAddress ( str1 ) ) NEW_LINE str2 = "01:23:45:67:89 : AB " NEW_LINE print ( isValidMACAddress ( str2 ) ) NEW_LINE str3 = "0123.4567.89AB " NEW_LINE print ( isValidMACAddress ( str3 ) ) NEW_LINE str4 = "01-23-45-67-89 - AH " NEW_LINE print ( isValidMACAddress ( str4 ) ) NEW_LINE str5 = "01-23-45-67 - AH " NEW_LINE print ( isValidMACAddress ( str5 ) ) NEW_LINE |
How to validate GUID ( Globally Unique Identifier ) using Regular Expression | Python3 program to validate GUID ( Globally Unique Identifier ) using regular expression ; Function to validate GUID ( Globally Unique Identifier ) ; Regex to check valid GUID ( Globally Unique Identifier ) ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : | import re NEW_LINE def isValidGUID ( str ) : NEW_LINE INDENT regex = " ^ [ { ] ? [ 0-9a - fA - F ] {8 } " + " - ( [ 0-9a - fA - F ] {4 } - ) " + " { 3 } [ 0-9a - fA - F ] {12 } [ } ] ? $ " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = "123e4567 - e89b - 12d3" + " - a456-9AC7CBDCEE52" NEW_LINE print ( isValidGUID ( str1 ) ) NEW_LINE str2 = " { 123e4567 - e89b - 12d3 - " + " a456-9AC7CBDCEE52 } " NEW_LINE print ( isValidGUID ( str2 ) ) NEW_LINE str3 = "123e4567 - h89b - 12d3 - a456" + " - 9AC7CBDCEE52" NEW_LINE print ( isValidGUID ( str3 ) ) NEW_LINE str4 = "123e4567 - h89b - 12d3 - a456" NEW_LINE print ( isValidGUID ( str4 ) ) NEW_LINE |
How to validate Indian driving license number using Regular Expression | Python program to validate Indian driving license number using regular expression ; Function to validate Indian driving license number . ; Regex to check valid Indian driving license number ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 : | import re NEW_LINE def isValidLicenseNo ( str ) : NEW_LINE INDENT regex = ( " ^ ( ( [ A - Z ] {2 } [ 0-9 ] { 2 } ) " + " ( β ) | ( [ A - Z ] {2 } - [0-9 ] " + " { 2 } ) ) ( (19 β 20 ) [ 0-9 ] " + " [ 0-9 ] ) [0-9 ] { 7 } $ " ) NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = " HR - 0619850034761" NEW_LINE print ( isValidLicenseNo ( str1 ) ) NEW_LINE str2 = " UP14 β 20160034761" NEW_LINE print ( isValidLicenseNo ( str2 ) ) NEW_LINE str3 = "12HR - 37200602347" NEW_LINE print ( isValidLicenseNo ( str3 ) ) NEW_LINE str4 = " MH27 β 30123476102" NEW_LINE print ( isValidLicenseNo ( str4 ) ) NEW_LINE str5 = " GJ - 2420180" NEW_LINE print ( isValidLicenseNo ( str5 ) ) NEW_LINE |
Count subtrees that sum up to a given value x only using single recursive function | Structure of a node of binary tree ; Function to get a new node ; Allocate space ; Utility function to count subtress that sum up to a given value x ; Driver code ; binary tree creation 5 / \ - 10 3 / \ / \ 9 8 - 4 7 | 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 getNode ( data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE return newNode NEW_LINE DEDENT count = 0 NEW_LINE ptr = None NEW_LINE def countSubtreesWithSumXUtil ( root , x ) : NEW_LINE INDENT global count , ptr NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l += countSubtreesWithSumXUtil ( root . left , x ) NEW_LINE r += countSubtreesWithSumXUtil ( root . right , x ) NEW_LINE if ( l + r + root . data == x ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( ptr != root ) : NEW_LINE INDENT return l + root . data + r NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 5 ) NEW_LINE root . left = getNode ( - 10 ) NEW_LINE root . right = getNode ( 3 ) NEW_LINE root . left . left = getNode ( 9 ) NEW_LINE root . left . right = getNode ( 8 ) NEW_LINE root . right . left = getNode ( - 4 ) NEW_LINE root . right . right = getNode ( 7 ) NEW_LINE x = 7 NEW_LINE ptr = root NEW_LINE print ( " Count β = β " + str ( countSubtreesWithSumXUtil ( root , x ) ) ) NEW_LINE DEDENT |
How to validate Indian Passport number using Regular Expression | Python3 program to validate passport number of India using regular expression ; Function to validate the pin code of India . ; Regex to check valid pin code of India . ; Compile the ReGex ; If the string is empty return false ; Pattern class contains matcher ( ) method to find matching between given string and regular expression . ; Return True if the string matched the ReGex else False ; Driver code . ; Test Case 1 ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 : | import re NEW_LINE def isValidPassportNo ( string ) : NEW_LINE INDENT regex = " ^ [ A - PR - WYa - pr - wy ] [1-9 ] \\d " + p = re . compile ( regex ) NEW_LINE if ( string == ' ' ) : NEW_LINE INDENT return False NEW_LINE DEDENT m = re . match ( p , string ) NEW_LINE if m is None : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " A21 β 90457" NEW_LINE print ( isValidPassportNo ( str1 ) ) NEW_LINE str2 = " A0296457" NEW_LINE print ( isValidPassportNo ( str2 ) ) NEW_LINE str3 = " Q2096453" NEW_LINE print ( isValidPassportNo ( str3 ) ) NEW_LINE str4 = "12096457" NEW_LINE print ( isValidPassportNo ( str4 ) ) NEW_LINE str5 = " A209645704" NEW_LINE print ( isValidPassportNo ( str5 ) ) NEW_LINE DEDENT |