text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Number of ways to represent a number as sum of k fibonacci numbers | To store fibonacci numbers 42 second number in fibonacci series largest possible integer ; Function to generate fibonacci series ; Recursive function to return the number of ways ; base condition ; for recursive function call ; Driver code | fib = [ 0 ] * 43 NEW_LINE def fibonacci ( ) : NEW_LINE INDENT fib [ 0 ] = 1 NEW_LINE fib [ 1 ] = 2 NEW_LINE for i in range ( 2 , 43 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DEDENT def rec ( x , y , last ) : NEW_LINE INDENT if y == 0 : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT Sum , i = 0 , last NEW_LINE while i >= 0 and fib [ i ] * y >= x : NEW_LINE INDENT if fib [ i ] > x : NEW_LINE INDENT i -= 1 NEW_LINE continue NEW_LINE DEDENT Sum += rec ( x - fib [ i ] , y - 1 , i ) NEW_LINE i -= 1 NEW_LINE DEDENT return Sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT fibonacci ( ) NEW_LINE n , k = 13 , 3 NEW_LINE print ( " Possible β ways β are : " , rec ( n , k , 42 ) ) NEW_LINE DEDENT |
Minimum cost to reach the top of the floor by climbing stairs | function to find the minimum cost to reach N - th floor ; declare an array ; base case ; initially to climb till 0 - th or 1 th stair ; iterate for finding the cost ; return the minimum ; Driver Code | def minimumCost ( cost , n ) : NEW_LINE INDENT dp = [ None ] * n NEW_LINE if n == 1 : NEW_LINE INDENT return cost [ 0 ] NEW_LINE DEDENT dp [ 0 ] = cost [ 0 ] NEW_LINE dp [ 1 ] = cost [ 1 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 1 ] , dp [ i - 2 ] ) + cost [ i ] NEW_LINE DEDENT return min ( dp [ n - 2 ] , dp [ n - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 16 , 19 , 10 , 12 , 18 ] NEW_LINE n = len ( a ) NEW_LINE print ( minimumCost ( a , n ) ) NEW_LINE DEDENT |
Minimum cost to reach the top of the floor by climbing stairs | function to find the minimum cost to reach N - th floor ; traverse till N - th stair ; update the last two stairs value ; Driver Code | def minimumCost ( cost , n ) : NEW_LINE INDENT dp1 = 0 NEW_LINE dp2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp0 = cost [ i ] + min ( dp1 , dp2 ) NEW_LINE dp2 = dp1 NEW_LINE dp1 = dp0 NEW_LINE DEDENT return min ( dp1 , dp2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 5 , 3 , 1 , 7 , 3 , 4 ] NEW_LINE n = len ( a ) NEW_LINE print ( minimumCost ( a , n ) ) NEW_LINE DEDENT |
Sudo Placement [ 1.5 ] | Wolfish | Python program for SP - Wolfish ; Function to find the maxCost of path from ( n - 1 , n - 1 ) to ( 0 , 0 ) ; base condition ; reaches the point ; if the state has been visited previously ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function to return the maximum cost ; calling dp function to get the answer ; Driver Code ; Function calling to get the answer | size = 1000 ; NEW_LINE def maxCost ( a , m , n , dp ) : NEW_LINE INDENT if ( n < 0 or m < 0 ) : NEW_LINE INDENT return int ( - 1e9 ) ; NEW_LINE DEDENT elif ( m == 0 and n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT elif ( dp [ m ] [ n ] != - 1 ) : NEW_LINE INDENT return dp [ m ] [ n ] ; NEW_LINE DEDENT else : NEW_LINE INDENT num = m + n ; NEW_LINE if ( ( num & ( num - 1 ) ) == 0 ) : NEW_LINE INDENT dp [ m ] [ n ] = a [ m ] [ n ] + maxCost ( a , m - 1 , n - 1 , dp ) ; NEW_LINE return dp [ m ] [ n ] ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ m ] [ n ] = ( a [ m ] [ n ] + max ( maxCost ( a , m - 1 , n , dp ) , maxCost ( a , m , n - 1 , dp ) ) ) ; NEW_LINE return dp [ m ] [ n ] ; NEW_LINE DEDENT DEDENT DEDENT def answer ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( size ) ] for j in range ( size ) ] ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT for j in range ( size ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 ; NEW_LINE DEDENT DEDENT return maxCost ( a , n - 1 , n - 1 , dp ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 1 , 2 , 3 , 1 ] , [ 4 , 5 , 6 , 1 ] , [ 7 , 8 , 9 , 1 ] , [ 1 , 1 , 1 , 1 ] ] ; NEW_LINE n = 4 ; NEW_LINE print ( answer ( a , n ) ) ; NEW_LINE DEDENT |
Edit distance and LCS ( Longest Common Subsequence ) | Python 3 program to find Edit Distance ( when only two operations are allowed , insert and delete ) using LCS . ; Find LCS ; Edit distance is delete operations + insert operations . ; Driver Code | def editDistanceWith2Ops ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ 0 for x in range ( n + 1 ) ] for y in range ( m + 1 ) ] 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 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 lcs = L [ m ] [ n ] NEW_LINE return ( m - lcs ) + ( n - lcs ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " abc " NEW_LINE Y = " acd " NEW_LINE print ( editDistanceWith2Ops ( X , Y ) ) NEW_LINE DEDENT |
Longest Common Subsequence | DP using Memoization | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code ; Find the length of string | def lcs ( X , Y , m , n ) : NEW_LINE INDENT if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT return 1 + lcs ( X , Y , m - 1 , n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE print ( " Length β of β LCS : " , lcs ( X , Y , m , n ) ) NEW_LINE DEDENT |
Number of different cyclic paths of length N in a tetrahedron | Function to count the number of steps in a tetrahedron ; initially coming to B is B -> B ; cannot reach A , D or C ; iterate for all steps ; recurrence relation ; memoize previous values ; returns steps ; Driver code | def countPaths ( n ) : NEW_LINE INDENT zB = 1 NEW_LINE zADC = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT nzB = zADC * 3 NEW_LINE nzADC = ( zADC * 2 + zB ) NEW_LINE zB = nzB NEW_LINE zADC = nzADC NEW_LINE DEDENT return zB NEW_LINE DEDENT n = 3 NEW_LINE print ( countPaths ( n ) ) NEW_LINE |
Minimum steps to reach target by a Knight | Set 2 | initializing the matrix . ; if knight is on the target position return 0. ; if already calculated then return that value . Taking absolute difference . ; there will be two distinct positions from the knight towards a target . if the target is in same row or column as of knight than there can be four positions towards the target but in that two would be the same and the other two would be the same . ; ( x1 , y1 ) and ( x2 , y2 ) are two positions . these can be different according to situation . From position of knight , the chess board can be divided into four blocks i . e . . N - E , E - S , S - W , W - N . ; ans will be , 1 + minimum of steps required from ( x1 , y1 ) and ( x2 , y2 ) . ; exchanging the coordinates x with y of both knight and target will result in same ans . ; Driver Code ; size of chess board n * n ; ( x , y ) coordinate of the knight . ( tx , ty ) coordinate of the target position . ; ( Exception ) these are the four corner points for which the minimum steps is 4. ; dp [ a ] [ b ] , here a , b is the difference of x & tx and y & ty respectively . | dp = [ [ 0 for i in range ( 8 ) ] for j in range ( 8 ) ] ; NEW_LINE def getsteps ( x , y , tx , ty ) : NEW_LINE INDENT if ( x == tx and y == ty ) : NEW_LINE INDENT return dp [ 0 ] [ 0 ] ; NEW_LINE DEDENT elif ( dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] != 0 ) : NEW_LINE INDENT return dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x1 , y1 , x2 , y2 = 0 , 0 , 0 , 0 ; NEW_LINE if ( x <= tx ) : NEW_LINE INDENT if ( y <= ty ) : NEW_LINE INDENT x1 = x + 2 ; NEW_LINE y1 = y + 1 ; NEW_LINE x2 = x + 1 ; NEW_LINE y2 = y + 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT x1 = x + 2 ; NEW_LINE y1 = y - 1 ; NEW_LINE x2 = x + 1 ; NEW_LINE y2 = y - 2 ; NEW_LINE DEDENT DEDENT elif ( y <= ty ) : NEW_LINE INDENT x1 = x - 2 ; NEW_LINE y1 = y + 1 ; NEW_LINE x2 = x - 1 ; NEW_LINE y2 = y + 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT x1 = x - 2 ; NEW_LINE y1 = y - 1 ; NEW_LINE x2 = x - 1 ; NEW_LINE y2 = y - 2 ; NEW_LINE DEDENT dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] = min ( getsteps ( x1 , y1 , tx , ty ) , getsteps ( x2 , y2 , tx , ty ) ) + 1 ; NEW_LINE dp [ abs ( y - ty ) ] [ abs ( x - tx ) ] = dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] ; NEW_LINE return dp [ abs ( x - tx ) ] [ abs ( y - ty ) ] ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 100 ; NEW_LINE x = 4 ; NEW_LINE y = 5 ; NEW_LINE tx = 1 ; NEW_LINE ty = 1 ; NEW_LINE if ( ( x == 1 and y == 1 and tx == 2 and ty == 2 ) or ( x == 2 and y == 2 and tx == 1 and ty == 1 ) ) : NEW_LINE INDENT ans = 4 ; NEW_LINE DEDENT elif ( ( x == 1 and y == n and tx == 2 and ty == n - 1 ) or ( x == 2 and y == n - 1 and tx == 1 and ty == n ) ) : NEW_LINE INDENT ans = 4 ; NEW_LINE DEDENT elif ( ( x == n and y == 1 and tx == n - 1 and ty == 2 ) or ( x == n - 1 and y == 2 and tx == n and ty == 1 ) ) : NEW_LINE INDENT ans = 4 ; NEW_LINE DEDENT elif ( ( x == n and y == n and tx == n - 1 and ty == n - 1 ) or ( x == n - 1 and y == n - 1 and tx == n and ty == n ) ) : NEW_LINE INDENT ans = 4 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] [ 0 ] = 3 ; NEW_LINE dp [ 0 ] [ 1 ] = 3 ; NEW_LINE dp [ 1 ] [ 1 ] = 2 ; NEW_LINE dp [ 2 ] [ 0 ] = 2 ; NEW_LINE dp [ 0 ] [ 2 ] = 2 ; NEW_LINE dp [ 2 ] [ 1 ] = 1 ; NEW_LINE dp [ 1 ] [ 2 ] = 1 ; NEW_LINE ans = getsteps ( x , y , tx , ty ) ; NEW_LINE DEDENT print ( ans ) ; NEW_LINE DEDENT |
Number of subsets with sum divisible by m | Use Dynamic Programming to find sum of subsequences . ; Find sum pf array elements ; dp [ i ] [ j ] would be > 0 if arr [ 0. . i - 1 ] has a subsequence with sum equal to j . ; There is always sum equals zero ; Fill up the dp table ; Initialize the counter ; Check if the sum exists ; check sum is divisible by m ; Driver Code | def sumSubSequence ( arr , length , m ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in arr : NEW_LINE INDENT summ += i NEW_LINE DEDENT dp = [ [ 0 for i in range ( summ + 1 ) ] for j in range ( length + 1 ) ] NEW_LINE for i in range ( length + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] += 1 NEW_LINE DEDENT for i in range ( 1 , length + 1 ) : NEW_LINE INDENT dp [ i ] [ arr [ i - 1 ] ] += 1 NEW_LINE for j in range ( 1 , summ + 1 ) : NEW_LINE INDENT if dp [ i - 1 ] [ j ] > 0 : NEW_LINE INDENT dp [ i ] [ j ] += 1 NEW_LINE dp [ i ] [ j + arr [ i - 1 ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( 1 , summ + 1 ) : NEW_LINE INDENT if dp [ length ] [ i ] > 0 : NEW_LINE INDENT if i % m == 0 : NEW_LINE INDENT count += dp [ length ] [ i ] NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE m = 3 NEW_LINE length = len ( arr ) NEW_LINE print ( sumSubSequence ( arr , length , m ) ) NEW_LINE DEDENT |
Longest Decreasing Subsequence | Function that returns the length of the longest decreasing subsequence ; Initialize LDS with 1 for all index The minimum LDS starting with any element is always 1 ; Compute LDS from every index in bottom up manner ; Select the maximum of all the LDS values ; returns the length of the LDS ; Driver Code | def lds ( arr , n ) : NEW_LINE INDENT lds = [ 0 ] * n NEW_LINE max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT lds [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] < arr [ j ] and lds [ i ] < lds [ j ] + 1 ) : NEW_LINE INDENT lds [ i ] = lds [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( max < lds [ i ] ) : NEW_LINE INDENT max = lds [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 15 , 27 , 14 , 38 , 63 , 55 , 46 , 65 , 85 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Length β of β LDS β is " , lds ( arr , n ) ) NEW_LINE DEDENT |
Total number of decreasing paths in a matrix | Python3 program to count number of decreasing path in a matrix ; Function that returns the number of decreasing paths from a cell ( i , j ) ; checking if already calculated ; all possible paths ; counts the total number of paths ; In all four allowed direction . ; new co - ordinates ; Checking if not going out of matrix and next cell value is less than current cell value . ; function that returns the answer ; Function that counts the total decreasing path in the matrix ; Initialising dp [ ] [ ] to - 1. ; Calculating number of decreasing path from each cell . ; Driver Code ; function call that returns the count of decreasing paths in a matrix | MAX = 100 NEW_LINE def CountDecreasingPathsCell ( mat , dp , n , x , y ) : NEW_LINE INDENT if ( dp [ x ] [ y ] != - 1 ) : NEW_LINE INDENT return dp [ x ] [ y ] NEW_LINE DEDENT delta = [ [ 0 , 1 ] , [ 1 , 0 ] , [ - 1 , 0 ] , [ 0 , - 1 ] ] NEW_LINE newx , newy = 0 , 0 NEW_LINE ans = 1 NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT newx = x + delta [ i ] [ 0 ] NEW_LINE newy = y + delta [ i ] [ 1 ] NEW_LINE if ( newx >= 0 and newx < n and newy >= 0 and newy < n and mat [ newx ] [ newy ] < mat [ x ] [ y ] ) : NEW_LINE INDENT ans += CountDecreasingPathsCell ( mat , dp , n , newx , newy ) NEW_LINE DEDENT DEDENT dp [ x ] [ y ] = ans NEW_LINE return dp [ x ] [ y ] NEW_LINE DEDENT def countDecreasingPathsMatrix ( n , mat ) : NEW_LINE INDENT dp = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT l = [ ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT l . append ( - 1 ) NEW_LINE DEDENT dp . append ( l ) NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sum += CountDecreasingPathsCell ( mat , dp , n , i , j ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT n = 2 NEW_LINE mat = [ [ 1 , 2 ] , [ 1 , 3 ] ] NEW_LINE print ( countDecreasingPathsMatrix ( n , mat ) ) NEW_LINE |
Sum of product of consecutive Binomial Coefficients | Python3 Program to find sum of product of consecutive Binomial Coefficient . ; Find the binomial coefficient upto nth term ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return the sum of the product of consecutive binomial coefficient . ; finding the sum of product of consecutive coefficient . ; Driver Code | MAX = 100 ; NEW_LINE def binomialCoeff ( C , n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , n ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] ; NEW_LINE DEDENT DEDENT return C ; NEW_LINE DEDENT def sumOfproduct ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE C = [ 0 ] * MAX ; NEW_LINE C = binomialCoeff ( C , n ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT sum += C [ i ] * C [ i + 1 ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( sumOfproduct ( n ) ) ; NEW_LINE |
Sum of product of r and rth Binomial Coefficient ( r * nCr ) | Python 3 Program to find sum of product of r and rth Binomial Coefficient i . e summation r * nCr ; Return the first n term of binomial coefficient . ; C [ 0 ] = 1 nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return summation of r * nCr ; finding the first n term of binomial coefficient ; Iterate a loop to find the sum . ; Driver Code | MAX = 100 NEW_LINE def binomialCoeff ( n , C ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , n ) , - 1 , - 1 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT def summation ( n ) : NEW_LINE INDENT C = [ 0 ] * MAX NEW_LINE binomialCoeff ( n , C ) NEW_LINE sum = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT sum += ( i * C [ i ] ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE print ( summation ( n ) ) NEW_LINE DEDENT |
Number of arrays of size N whose elements are positive integers and sum is K | Return nCr ; C [ 0 ] = 1 ; nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Return the number of array that can be formed of size n and sum equals to k . ; Driver Code | def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] ; NEW_LINE DEDENT DEDENT return C [ k ] ; NEW_LINE DEDENT def countArray ( N , K ) : NEW_LINE INDENT return binomialCoeff ( K - 1 , N - 1 ) ; NEW_LINE DEDENT N = 2 ; NEW_LINE K = 3 ; NEW_LINE print ( countArray ( N , K ) ) ; NEW_LINE |
Partitioning into two contiguous element subarrays with equal sums | Class to store the minimum element and its position ; initialize prefix and suffix sum arrays with 0 ; add current element to Sum ; add current element to Sum ; initialize the minimum element to be a large value ; check for the minimum absolute difference between current prefix sum and the next suffix sum element ; if prefixsum has a greater value then position is the next element , else it 's the same element. ; return the data in class . ; Driver Code | class Data : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . element = - 1 NEW_LINE self . position = - 1 NEW_LINE DEDENT DEDENT def findMinElement ( arr , n ) : NEW_LINE INDENT result = Data ( ) NEW_LINE prefixSum = [ 0 ] * n NEW_LINE suffixSum = [ 0 ] * n NEW_LINE prefixSum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefixSum [ i ] = prefixSum [ i - 1 ] + arr [ i ] suffixSum [ n - 1 ] = arr [ n - 1 ] NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffixSum [ i ] = suffixSum [ i + 1 ] + arr [ i ] NEW_LINE DEDENT mini = suffixSum [ 0 ] NEW_LINE pos = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if abs ( suffixSum [ i + 1 ] - prefixSum [ i ] ) < mini : NEW_LINE INDENT mini = abs ( suffixSum [ i + 1 ] - prefixSum [ i ] ) NEW_LINE if suffixSum [ i + 1 ] < prefixSum [ i ] : NEW_LINE INDENT pos = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT pos = i NEW_LINE DEDENT DEDENT DEDENT result . element = mini NEW_LINE result . position = pos NEW_LINE return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE values = Data ( ) NEW_LINE values = findMinElement ( arr , n ) NEW_LINE print ( " Minimum β element β : " , values . element , " Position : " , values . position ) NEW_LINE DEDENT |
Number of circular tours that visit all petrol pumps | Python 3 Program to find the number of circular tour that visits all petrol pump ; Return the number of pumps from where we can start the journey . ; Making Circular Array . ; for each of the petrol pump . ; If tank is less than 0. ; If starting pump is greater than n , return ans as 0. ; For each of the petrol pump ; Finding the need array ; If need is 0 , increment the count . ; Driver Code | N = 100 NEW_LINE def count ( n , c , a , b ) : NEW_LINE INDENT need = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT a [ i + n ] = a [ i ] NEW_LINE b [ i + n ] = b [ i ] NEW_LINE DEDENT s = 0 NEW_LINE tank = 0 NEW_LINE for i in range ( 0 , 2 * n , 1 ) : NEW_LINE INDENT tank += a [ i ] NEW_LINE tank = min ( tank , c ) NEW_LINE tank -= b [ i ] NEW_LINE if ( tank < 0 ) : NEW_LINE INDENT tank = 0 NEW_LINE s = i + 1 NEW_LINE DEDENT DEDENT if ( s >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 1 NEW_LINE need [ s + n ] = 0 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT id = s + n - i NEW_LINE need [ id ] = max ( 0 , need [ id + 1 ] + b [ id ] - min ( a [ id ] , c ) ) NEW_LINE if ( need [ id ] == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE c = 3 NEW_LINE a = [ 3 , 1 , 2 , 0 , 0 , 0 ] NEW_LINE b = [ 2 , 2 , 2 , 0 , 0 , 0 ] NEW_LINE print ( count ( n , c , a , b ) ) NEW_LINE DEDENT |
Print equal sum sets of array ( Partition Problem ) | Set 2 | Python3 program to print equal sum sets of array . ; Function to print equal sum sets of array . ; Finding sum of array elements ; Check sum is even or odd . If odd then array cannot be partitioned . Print - 1 and return . ; Divide sum by 2 to find sum of two possible subsets . ; Boolean DP table to store result of states . dp [ i ] [ j ] = true if there is a subset of elements in first i elements of array that has sum equal to j . ; If number of elements are zero , then no sum can be obtained . ; Sum 0 can be obtained by not selecting any element . ; Fill the DP table in bottom up manner . ; Excluding current element . ; Including current element ; Required sets set1 and set2 . ; If partition is not possible print - 1 and return . ; Start from last element in dp table . ; If current element does not contribute to k , then it belongs to set 2. ; If current element contribute to k then it belongs to set 1. ; Print elements of both the sets . ; Driver Code | import numpy as np NEW_LINE def printEqualSumSets ( arr , n ) : NEW_LINE INDENT sum_array = sum ( arr ) NEW_LINE if ( sum_array & 1 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT k = sum_array >> 1 NEW_LINE dp = np . zeros ( ( n + 1 , k + 1 ) ) NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for currSum in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ i ] [ currSum ] = dp [ i - 1 ] [ currSum ] NEW_LINE if ( arr [ i - 1 ] <= currSum ) : NEW_LINE INDENT dp [ i ] [ currSum ] = ( dp [ i ] [ currSum ] or dp [ i - 1 ] [ currSum - arr [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT set1 , set2 = [ ] , [ ] NEW_LINE if ( not dp [ n ] [ k ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT i = n NEW_LINE currSum = k NEW_LINE while ( i > 0 and currSum >= 0 ) : NEW_LINE INDENT if ( dp [ i - 1 ] [ currSum ] ) : NEW_LINE INDENT i -= 1 NEW_LINE set2 . append ( arr [ i ] ) NEW_LINE DEDENT elif ( dp [ i - 1 ] [ currSum - arr [ i - 1 ] ] ) : NEW_LINE INDENT i -= 1 NEW_LINE currSum -= arr [ i ] NEW_LINE set1 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT print ( " Set β 1 β elements : " , end = " β " ) NEW_LINE for i in range ( len ( set1 ) ) : NEW_LINE INDENT print ( set1 [ i ] , end = " β " ) NEW_LINE DEDENT print ( " Set 2 elements : " , β end β = β " " ) NEW_LINE for i in range ( len ( set2 ) ) : NEW_LINE INDENT print ( set2 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 5 , 1 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE printEqualSumSets ( arr , n ) NEW_LINE DEDENT |
Maximum average sum partition of an array | Python3 program for maximum average sum partition ; storing prefix sums ; for each i to n storing averages ; Driver code ; K = 3 ; atmost partitioning size | def largestSumOfAverages ( A , K ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE pre_sum = [ 0 ] * ( n + 1 ) ; NEW_LINE pre_sum [ 0 ] = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT pre_sum [ i + 1 ] = pre_sum [ i ] + A [ i ] ; NEW_LINE DEDENT dp = [ 0 ] * n ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = ( pre_sum [ n ] - pre_sum [ i ] ) / ( n - i ) ; NEW_LINE DEDENT for k in range ( K - 1 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , ( pre_sum [ j ] - pre_sum [ i ] ) / ( j - i ) + dp [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT return int ( dp [ 0 ] ) ; NEW_LINE DEDENT A = [ 9 , 1 , 2 , 3 , 9 ] ; NEW_LINE print ( largestSumOfAverages ( A , K ) ) ; NEW_LINE |
Find maximum sum array of length less than or equal to m | N and M to define sizes of arr , dp , current_arr and maxSum ; INF to define min value ; Function to find maximum sum ; dp array of size N x M ; current_arr of size M ; maxsum of size M ; If we have 0 elements from 0 th array ; Compute the cumulative sum array ; Calculating the maximum contiguous array for every length j , j is from 1 to lengtn of the array ; Every state is depending on its previous state ; computation of dp table similar approach as knapsack problem ; Now we have done processing with the last array lets find out what is the maximum sum possible ; Driver code ; First element of each row is the size of that row | N = 105 NEW_LINE M = 1001 NEW_LINE INF = - 1111111111 NEW_LINE def maxSum ( arr ) : NEW_LINE INDENT dp = [ [ - 1 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE current_arr = [ 0 ] * M NEW_LINE maxsum = [ 0 ] * M NEW_LINE current_arr [ 0 ] = 0 NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( 1 , 6 ) : NEW_LINE INDENT len = arr [ i - 1 ] [ 0 ] NEW_LINE for j in range ( 1 , len + 1 ) : NEW_LINE INDENT current_arr [ j ] = arr [ i - 1 ] [ j ] NEW_LINE current_arr [ j ] += current_arr [ j - 1 ] NEW_LINE maxsum [ j ] = INF NEW_LINE DEDENT j = 1 NEW_LINE while j <= len and j <= 6 : NEW_LINE INDENT for k in range ( 1 , len + 1 ) : NEW_LINE INDENT if ( j + k - 1 <= len ) : NEW_LINE INDENT maxsum [ j ] = max ( maxsum [ j ] , current_arr [ j + k - 1 ] - current_arr [ k - 1 ] ) NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT for j in range ( 7 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT for j in range ( 1 , 7 ) : NEW_LINE INDENT cur = 1 NEW_LINE while cur <= j and cur <= len : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - cur ] + maxsum [ cur ] ) NEW_LINE cur += 1 NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 7 ) : NEW_LINE INDENT ans = max ( ans , dp [ 5 ] [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 3 , 2 , 3 , 5 ] , [ 2 , 7 , - 1 ] , [ 2 , 8 , 10 ] , [ 4 , 5 , 2 , 6 , 1 ] , [ 3 , 2 , 3 , - 2 ] ] NEW_LINE print ( " Maximum β sum β can β be β obtained " , " is β : β " , maxSum ( arr ) ) NEW_LINE DEDENT |
Maximize array elements upto given number | Function to find maximum possible value of number that can be obtained using array elements . ; Variable to represent current index . ; Variable to show value between 0 and maxLimit . ; Table to store whether a value can be obtained or not upto a certain index 1. dp [ i , j ] = 1 if value j can be obtained upto index i . 2. dp [ i , j ] = 0 if value j cannot be obtained upto index i . ; Check for index 0 if given value val can be obtained by either adding to or subtracting arr [ 0 ] from num . ; 1. If arr [ ind ] is added to obtain given val then val - arr [ ind ] should be obtainable from index ind - 1. 2. If arr [ ind ] is subtracted to obtain given val then val + arr [ ind ] should be obtainable from index ind - 1. Check for both the conditions . ; If either of one condition is True , then val is obtainable at index ind . ; Find maximum value that is obtained at index n - 1. ; If no solution exists return - 1. ; Driver Code | def findMaxVal ( arr , n , num , maxLimit ) : NEW_LINE INDENT ind = - 1 ; NEW_LINE val = - 1 ; NEW_LINE dp = [ [ 0 for i in range ( maxLimit + 1 ) ] for j in range ( n ) ] ; NEW_LINE for ind in range ( n ) : NEW_LINE INDENT for val in range ( maxLimit + 1 ) : NEW_LINE INDENT if ( ind == 0 ) : NEW_LINE INDENT if ( num - arr [ ind ] == val or num + arr [ ind ] == val ) : NEW_LINE INDENT dp [ ind ] [ val ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ ind ] [ val ] = 0 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( val - arr [ ind ] >= 0 and val + arr [ ind ] <= maxLimit ) : NEW_LINE INDENT if ( dp [ ind - 1 ] [ val - arr [ ind ] ] == 1 or dp [ ind - 1 ] [ val + arr [ ind ] ] == 1 ) : NEW_LINE INDENT dp [ ind ] [ val ] = 1 ; NEW_LINE DEDENT DEDENT elif ( val - arr [ ind ] >= 0 ) : NEW_LINE INDENT dp [ ind ] [ val ] = dp [ ind - 1 ] [ val - arr [ ind ] ] ; NEW_LINE DEDENT elif ( val + arr [ ind ] <= maxLimit ) : NEW_LINE INDENT dp [ ind ] [ val ] = dp [ ind - 1 ] [ val + arr [ ind ] ] ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ ind ] [ val ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT for val in range ( maxLimit , - 1 , - 1 ) : NEW_LINE INDENT if ( dp [ n - 1 ] [ val ] == 1 ) : NEW_LINE INDENT return val ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = 1 ; NEW_LINE arr = [ 3 , 10 , 6 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE maxLimit = 15 ; NEW_LINE print ( findMaxVal ( arr , n , num , maxLimit ) ) ; NEW_LINE DEDENT |
Moser | Function to generate nth term of Moser - de Bruijn Sequence ; S ( 0 ) = 0 ; S ( 1 ) = 1 ; S ( 2 * n ) = 4 * S ( n ) ; S ( 2 * n + 1 ) = 4 * S ( n ) + 1 ; Generating the first ' n ' terms of Moser - de Bruijn Sequence ; Driver Program | def gen ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif n % 2 == 0 : NEW_LINE INDENT return 4 * gen ( n // 2 ) NEW_LINE DEDENT elif n % 2 == 1 : NEW_LINE INDENT return 4 * gen ( n // 2 ) + 1 NEW_LINE DEDENT DEDENT def moserDeBruijn ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( gen ( i ) , end = " β " ) NEW_LINE DEDENT DEDENT n = 15 NEW_LINE print ( " First " , n , " terms β of β " , " Moser - de β Bruijn β Sequence : " ) NEW_LINE moserDeBruijn ( n ) NEW_LINE |
Minimum Sum Path in a Triangle | Util function to find minimum sum for a path ; For storing the result in a 1 - D array , and simultaneously updating the result . ; For the bottom row ; Calculation of the remaining rows , in bottom up manner . ; return the top element ; Driver Code | def minSumPath ( A ) : NEW_LINE INDENT memo = [ None ] * len ( A ) NEW_LINE n = len ( A ) - 1 NEW_LINE for i in range ( len ( A [ n ] ) ) : NEW_LINE INDENT memo [ i ] = A [ n ] [ i ] NEW_LINE DEDENT for i in range ( len ( A ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( len ( A [ i ] ) ) : NEW_LINE INDENT memo [ j ] = A [ i ] [ j ] + min ( memo [ j ] , memo [ j + 1 ] ) ; NEW_LINE DEDENT DEDENT return memo [ 0 ] NEW_LINE DEDENT A = [ [ 2 ] , [ 3 , 9 ] , [ 1 , 6 , 7 ] ] NEW_LINE print ( minSumPath ( A ) ) NEW_LINE |
Check if any valid sequence is divisible by M | ; Base case ; check if sum is divisible by M ; 1. Try placing '+ ; 2. Try placing '- | def isPossible ( index , sum ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT if ( ( sum % M ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT placeAdd = isPossible ( index + 1 , sum + arr [ index ] ) ; NEW_LINE DEDENT ' NEW_LINE INDENT placeMinus = isPossible ( index + 1 , sum - arr [ index ] ) ; NEW_LINE if ( placeAdd or placeMinus ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT |
Minimum removals from array to make max | Python program to find minimum removals to make max - min <= K ; function to check all possible combinations of removal and return the minimum one ; base case when all elements are removed ; if condition is satisfied , no more removals are required ; if the state has already been visited ; when Amax - Amin > d ; minimum is taken of the removal of minimum element or removal of the maximum element ; To sort the array and return the answer ; sort the array ; fill all stated with - 1 when only one element ; Driver Code | MAX = 100 NEW_LINE dp = [ [ 0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE for i in range ( 0 , MAX ) : NEW_LINE INDENT for j in range ( 0 , MAX ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT def countRemovals ( a , i , j , k ) : NEW_LINE INDENT global dp NEW_LINE if ( i >= j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( ( a [ j ] - a [ i ] ) <= k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT elif ( ( a [ j ] - a [ i ] ) > k ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + min ( countRemovals ( a , i + 1 , j , k ) , countRemovals ( a , i , j - 1 , k ) ) NEW_LINE DEDENT return dp [ i ] [ j ] NEW_LINE DEDENT def removals ( a , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return countRemovals ( a , 0 , n - 1 , k ) NEW_LINE DEDENT DEDENT a = [ 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 ] NEW_LINE n = len ( a ) NEW_LINE k = 4 NEW_LINE print ( removals ( a , n , k ) ) NEW_LINE |
Minimum removals from array to make max | Function to find rightmost index which satisfies the condition arr [ j ] - arr [ i ] <= k ; Initialising start to i + 1 ; Initialising end to n - 1 ; Binary search implementation to find the rightmost element that satisfy the condition ; Check if the condition satisfies ; Store the position ; Make start = mid + 1 ; Make end = mid ; Return the rightmost position ; Function to calculate minimum number of elements to be removed ; Sort the given array ; Iterate from 0 to n - 1 ; Find j such that arr [ j ] - arr [ i ] <= k ; If there exist such j that satisfies the condition ; Number of elements to be removed for this particular case is ( j - i + 1 ) ; Return answer ; Driver Code | def findInd ( key , i , n , k , arr ) : NEW_LINE INDENT ind = - 1 NEW_LINE start = i + 1 NEW_LINE end = n - 1 ; NEW_LINE while ( start < end ) : NEW_LINE INDENT mid = int ( start + ( end - start ) / 2 ) NEW_LINE if ( arr [ mid ] - key <= k ) : NEW_LINE INDENT ind = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid NEW_LINE DEDENT DEDENT return ind NEW_LINE DEDENT def removals ( arr , n , k ) : NEW_LINE INDENT ans = n - 1 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT j = findInd ( arr [ i ] , i , n , k , arr ) NEW_LINE if ( j != - 1 ) : NEW_LINE INDENT ans = min ( ans , n - ( j - i + 1 ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 1 , 3 , 4 , 9 , 10 , 11 , 12 , 17 , 20 ] NEW_LINE n = len ( a ) NEW_LINE k = 4 NEW_LINE print ( removals ( a , n , k ) ) NEW_LINE |
Number of ordered pairs such that ( Ai & Aj ) = 0 | Naive function to count the number of ordered pairs such that their bitwise and is 0 ; check for all possible pairs ; add 2 as ( i , j ) and ( j , i ) are considered different ; Driver Code | def countPairs ( a , n ) : 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 ( a [ i ] & a [ j ] ) == 0 : NEW_LINE INDENT count += 2 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT a = [ 3 , 4 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n ) ) NEW_LINE |
Number of ordered pairs such that ( Ai & Aj ) = 0 | Python program to calculate the number of ordered pairs such that their bitwise and is zero ; efficient function to count pairs ; stores the frequency of each number ; initialize 0 to all ; count the frequency of every element ; iterate for al possible values that a [ i ] can be ; if the last bit is ON ; else : is the last bit is OFF ; iterate till n ; if mask 's ith bit is set ; else : if mask 's ith bit is not set ; iterate for all the array element and count the number of pairs ; return answer ; Driver Code | N = 15 NEW_LINE def countPairs ( a , n ) : NEW_LINE INDENT Hash = { } NEW_LINE dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( 1 << N ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] not in Hash : NEW_LINE INDENT Hash [ a [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT Hash [ a [ i ] ] += 1 NEW_LINE DEDENT DEDENT mask = 0 NEW_LINE while ( mask < ( 1 << N ) ) : NEW_LINE INDENT if mask not in Hash : NEW_LINE INDENT Hash [ mask ] = 0 NEW_LINE DEDENT if ( mask & 1 ) : NEW_LINE INDENT dp [ mask ] [ 0 ] = Hash [ mask ] + Hash [ mask ^ 1 ] NEW_LINE dp [ mask ] [ 0 ] = Hash [ mask ] NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( mask & ( 1 << i ) ) : NEW_LINE INDENT dp [ mask ] [ i ] = dp [ mask ] [ i - 1 ] + dp [ mask ^ ( 1 << i ) ] [ i - 1 ] NEW_LINE dp [ mask ] [ i ] = dp [ mask ] [ i - 1 ] NEW_LINE DEDENT DEDENT mask += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += dp [ ( ( 1 << N ) - 1 ) ^ a [ i ] ] [ N ] NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 5 , 4 , 1 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n ) ) NEW_LINE |
Minimum sum of multiplications of n numbers | Python3 program to find the minimum sum of multiplication of n numbers ; Used in recursive memoized solution ; function to calculate the cumulative sum from a [ i ] to a [ j ] ; base case ; memoization , if the partition has been called before then return the stored value ; store a max value ; we break them into k partitions ; store the min of the formula thus obtained ; return the minimum ; Driver code | import numpy as np NEW_LINE import sys NEW_LINE dp = np . zeros ( ( 1000 , 1000 ) ) NEW_LINE def sum ( a , i , j ) : NEW_LINE INDENT ans = 0 NEW_LINE for m in range ( i , j + 1 ) : NEW_LINE INDENT ans = ( ans + a [ m ] ) % 100 NEW_LINE DEDENT return ans NEW_LINE DEDENT def solve ( a , i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT dp [ i ] [ j ] = sys . maxsize NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , ( solve ( a , i , k ) + solve ( a , k + 1 , j ) + ( sum ( a , i , k ) * sum ( a , k + 1 , j ) ) ) ) NEW_LINE DEDENT return dp [ i ] [ j ] NEW_LINE DEDENT def initialize ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 40 , 60 , 20 ] NEW_LINE n = len ( a ) NEW_LINE initialize ( n ) NEW_LINE print ( int ( solve ( a , 0 , n - 1 ) ) ) NEW_LINE DEDENT |
Print Fibonacci Series in reverse order | Python 3 Program to print Fibonacci series in reverse order ; assigning first and second elements ; storing sum in the preceding location ; printing array in reverse order ; Driver function | def reverseFibonacci ( n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE a [ 0 ] = 0 NEW_LINE a [ 1 ] = 1 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT a [ i ] = a [ i - 2 ] + a [ i - 1 ] NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE reverseFibonacci ( n ) NEW_LINE |
Check if it is possible to transform one string to another | function to check if a string can be converted to another string by performing following operations ; calculates length ; mark 1 st position as true ; traverse for all DPi , j ; if possible for to convert i characters of s1 to j characters of s2 ; if upper_case ( s1 [ i ] ) == s2 [ j ] is same ; if not upper then deletion is possible ; driver code | def check ( s1 , s2 ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE m = len ( s2 ) NEW_LINE dp = ( [ [ False for i in range ( m + 1 ) ] for i in range ( n + 1 ) ] ) NEW_LINE dp [ 0 ] [ 0 ] = True NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT for j in range ( len ( s2 ) + 1 ) : NEW_LINE INDENT if ( dp [ i ] [ j ] ) : NEW_LINE INDENT if ( ( j < len ( s2 ) and ( s1 [ i ] . upper ( ) == s2 [ j ] ) ) ) : NEW_LINE INDENT dp [ i + 1 ] [ j + 1 ] = True NEW_LINE DEDENT if ( s1 [ i ] . isupper ( ) == False ) : NEW_LINE INDENT dp [ i + 1 ] [ j ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT return ( dp [ n ] [ m ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " daBcd " NEW_LINE s2 = " ABC " NEW_LINE if ( check ( s1 , s2 ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Probability of reaching a point with 2 or 3 steps at a time | Returns probability to reach N ; Driver code | def find_prob ( N , P ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 1 NEW_LINE dp [ 1 ] = 0 NEW_LINE dp [ 2 ] = P NEW_LINE dp [ 3 ] = 1 - P NEW_LINE for i in range ( 4 , N + 1 ) : NEW_LINE INDENT dp [ i ] = ( P ) * dp [ i - 2 ] + ( 1 - P ) * dp [ i - 3 ] NEW_LINE DEDENT return dp [ N ] NEW_LINE DEDENT n = 5 NEW_LINE p = 0.2 NEW_LINE print ( round ( find_prob ( n , p ) , 2 ) ) NEW_LINE |
Minimum number of deletions to make a string palindrome | Set 2 | Python3 program to find minimum deletions to make palindrome . ; Find reverse of input string ; Create a DP table for storing edit distance of string and reverse . ; Find edit distance between input and revInput considering only delete operation . ; Go from bottom left to top right and find the minimum ; Driver Code | INT_MAX = 99999999999 NEW_LINE def getLevenstein ( inpt ) : NEW_LINE INDENT revInput = inpt [ : : - 1 ] NEW_LINE n = len ( inpt ) NEW_LINE dp = [ [ - 1 for _ in range ( n + 1 ) ] for __ in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = i NEW_LINE dp [ i ] [ 0 ] = i NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if inpt [ i - 1 ] == revInput [ j - 1 ] : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT res = INT_MAX NEW_LINE i , j = n , 0 NEW_LINE while i >= 0 : NEW_LINE INDENT res = min ( res , dp [ i ] [ j ] ) NEW_LINE if i < n : NEW_LINE INDENT res = min ( res , dp [ i + 1 ] [ j ] ) NEW_LINE DEDENT if i > 0 : NEW_LINE INDENT res = min ( res , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT i -= 1 NEW_LINE j += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT inpt = " myfirstgeekarticle " NEW_LINE print ( getLevenstein ( inpt ) ) NEW_LINE DEDENT |
Number of ways to form a heap with n distinct integers | dp [ i ] = number of max heaps for i distinct integers ; nck [ i ] [ j ] = number of ways to choose j elements form i elements , no order ; log2 [ i ] = floor of logarithm of base 2 of i ; to calculate nCk ; calculate l for give value of n ; number of elements that are actually present in last level ( hth level ) ( 2 ^ h - 1 ) ; if more than half - filled ; return ( 1 << h ) - 1 ( 2 ^ h ) - 1 ; find maximum number of heaps for n ; function to initialize arrays ; for each power of two find logarithm ; Driver code | dp = [ 0 ] * MAXN NEW_LINE nck = [ [ 0 for i in range ( MAXN ) ] for j in range ( MAXN ) ] NEW_LINE log2 = [ 0 ] * MAXN NEW_LINE def choose ( n , k ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( nck [ n ] [ k ] != - 1 ) : NEW_LINE INDENT return nck [ n ] [ k ] NEW_LINE DEDENT answer = choose ( n - 1 , k - 1 ) + choose ( n - 1 , k ) NEW_LINE nck [ n ] [ k ] = answer NEW_LINE return answer NEW_LINE DEDENT def getLeft ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT h = log2 [ n ] NEW_LINE last = n - ( ( 1 << h ) - 1 ) NEW_LINE if ( last >= ( numh // 2 ) ) : NEW_LINE else : NEW_LINE INDENT return ( 1 << h ) - 1 - ( ( numh // 2 ) - last ) NEW_LINE DEDENT DEDENT def numberOfHeaps ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT left = getLeft ( n ) NEW_LINE ans = ( choose ( n - 1 , left ) * numberOfHeaps ( left ) ) * ( numberOfHeaps ( n - 1 - left ) ) NEW_LINE dp [ n ] = ans NEW_LINE return ans NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT nck [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT currLog2 = - 1 NEW_LINE currPower2 = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( currPower2 == i ) : NEW_LINE INDENT currLog2 += 1 NEW_LINE currPower2 *= 2 NEW_LINE DEDENT log2 [ i ] = currLog2 NEW_LINE DEDENT return numberOfHeaps ( n ) NEW_LINE DEDENT n = 10 NEW_LINE print ( solve ( n ) ) NEW_LINE |
Hosoya 's Triangle | Python3 Program to print Hosoya 's triangle of height n. ; Print the Hosoya triangle of height n . ; base case . ; For each row . ; for each column ; recursive steps . ; printing the solution ; Driver Code | N = 5 NEW_LINE def printHosoya ( n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N ) ] for i in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = dp [ 1 ] [ 0 ] = dp [ 1 ] [ 1 ] = 1 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i > j ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] + dp [ i - 2 ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j - 1 ] + dp [ i - 2 ] [ j - 2 ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT print ( dp [ i ] [ j ] , end = ' β ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE printHosoya ( n ) NEW_LINE |
Different ways to sum n using numbers greater than or equal to m | Python3 Program to find number of ways to which numbers that are greater than given number can be added to get sum . ; Return number of ways to which numbers that are greater than given number can be added to get sum . ; Filling the table . k is for numbers greater than or equal that are allowed . ; i is for sum ; initializing dp [ i ] [ k ] to number ways to get sum using numbers greater than or equal k + 1 ; if i > k ; Driver Code | MAX = 100 NEW_LINE import numpy as np NEW_LINE def numberofways ( n , m ) : NEW_LINE INDENT dp = np . zeros ( ( n + 2 , n + 2 ) ) NEW_LINE dp [ 0 ] [ n + 1 ] = 1 NEW_LINE for k in range ( n , m - 1 , - 1 ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ k ] = dp [ i ] [ k + 1 ] NEW_LINE if ( i - k >= 0 ) : NEW_LINE INDENT dp [ i ] [ k ] = ( dp [ i ] [ k ] + dp [ i - k ] [ k ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ m ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m = 3 , 1 NEW_LINE print ( numberofways ( n , m ) ) NEW_LINE DEDENT |
Entringer Number | Return Entringer Number E ( n , k ) ; Base Case ; Base Case ; Recursive step ; Driven Program | def zigzag ( n , k ) : NEW_LINE INDENT if ( n == 0 and k == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return zigzag ( n , k - 1 ) + zigzag ( n - 1 , n - k ) ; NEW_LINE DEDENT n = 4 NEW_LINE k = 3 NEW_LINE print ( zigzag ( n , k ) ) NEW_LINE |
Eulerian Number | Return euleriannumber A ( n , m ) ; For each row from 1 to n ; For each column from 0 to m ; If i is greater than j ; If j is 0 , then make that state as 1. ; basic recurrence relation . ; Driven Program | def eulerian ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , m + 1 ) : NEW_LINE INDENT if ( i > j ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( ( ( i - j ) * dp [ i - 1 ] [ j - 1 ] ) + ( ( j + 1 ) * dp [ i - 1 ] [ j ] ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ n ] [ m ] NEW_LINE DEDENT n = 3 NEW_LINE m = 1 NEW_LINE print ( eulerian ( n , m ) ) NEW_LINE |
Delannoy Number | Return the nth Delannoy Number . ; Base case ; Recursive step . ; Driven code | def dealnnoy ( n , m ) : NEW_LINE INDENT if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return dealnnoy ( m - 1 , n ) + dealnnoy ( m - 1 , n - 1 ) + dealnnoy ( m , n - 1 ) NEW_LINE DEDENT n = 3 NEW_LINE m = 4 ; NEW_LINE print ( dealnnoy ( n , m ) ) NEW_LINE |
Delannoy Number | Return the nth Delannoy Number . ; Base cases ; Driven code | def dealnnoy ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( n + 1 ) ] for x in range ( m + 1 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - 1 ] + dp [ i ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT n = 3 NEW_LINE m = 4 NEW_LINE print ( dealnnoy ( n , m ) ) NEW_LINE |
Longest alternating ( positive and negative ) subarray starting at every index | Python3 program to find longest alternating subarray starting from every index . ; Fill count [ ] from end . ; Print result ; Driver Code | def longestAlternating ( arr , n ) : NEW_LINE INDENT count = [ None ] * n NEW_LINE count [ n - 1 ] = 1 NEW_LINE i = n - 2 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( arr [ i ] * arr [ i + 1 ] < 0 ) : NEW_LINE INDENT count [ i ] = count [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ i ] = 1 ; NEW_LINE DEDENT i = i - 1 NEW_LINE DEDENT i = 0 NEW_LINE while i < n : NEW_LINE INDENT print ( count [ i ] , end = " β " ) NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT a = [ - 5 , - 1 , - 1 , 2 , - 2 , - 3 ] NEW_LINE n = len ( a ) NEW_LINE longestAlternating ( a , n ) ; NEW_LINE |
Maximum value with the choice of either dividing or considering as it is | function for calculating max possible result ; Compute remaining values in bottom up manner . ; driver code | def maxDP ( n ) : NEW_LINE INDENT res = list ( ) NEW_LINE res . append ( 0 ) NEW_LINE res . append ( 1 ) NEW_LINE i = 2 NEW_LINE while i < n + 1 : NEW_LINE INDENT res . append ( max ( i , ( res [ int ( i / 2 ) ] + res [ int ( i / 3 ) ] + res [ int ( i / 4 ) ] + res [ int ( i / 5 ) ] ) ) ) NEW_LINE i = i + 1 NEW_LINE DEDENT return res [ n ] NEW_LINE DEDENT n = 60 NEW_LINE print ( " MaxSum β = " , maxDP ( n ) ) NEW_LINE |
Maximum difference of zeros and ones in binary string | Python Program to find the length of substring with maximum difference of zeroes and ones in binary string . ; Return true if there all 1 s ; Checking each index is 0 or not . ; Find the length of substring with maximum difference of zeroes and ones in binary string ; If string is over ; If the state is already calculated . ; Returns length of substring which is having maximum difference of number of 0 s and number of 1 s ; If all 1 s return - 1. ; Else find the length . ; Driven Program | MAX = 100 NEW_LINE def allones ( s , n ) : NEW_LINE INDENT co = 0 NEW_LINE for i in s : NEW_LINE INDENT co += 1 if i == '1' else 0 NEW_LINE DEDENT return co == n NEW_LINE DEDENT def findlength ( arr , s , n , ind , st , dp ) : NEW_LINE INDENT if ind >= n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ ind ] [ st ] != - 1 : NEW_LINE INDENT return dp [ ind ] [ st ] NEW_LINE DEDENT if not st : NEW_LINE INDENT dp [ ind ] [ st ] = max ( arr [ ind ] + findlength ( arr , s , n , ind + 1 , 1 , dp ) , ( findlength ( arr , s , n , ind + 1 , 0 , dp ) ) ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ ind ] [ st ] = max ( arr [ ind ] + findlength ( arr , s , n , ind + 1 , 1 , dp ) , 0 ) NEW_LINE DEDENT return dp [ ind ] [ st ] NEW_LINE DEDENT def maxLen ( s , n ) : NEW_LINE INDENT if allones ( s , n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT arr = [ 0 ] * MAX NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = 1 if s [ i ] == '0' else - 1 NEW_LINE DEDENT dp = [ [ - 1 ] * 3 for _ in range ( MAX ) ] NEW_LINE return findlength ( arr , s , n , 0 , 0 , dp ) NEW_LINE DEDENT s = "11000010001" NEW_LINE n = 11 NEW_LINE print ( maxLen ( s , n ) ) NEW_LINE |
Minimum jumps to reach last building in a matrix | Recursive Python3 program to find minimum jumps to reach last building from first . ; Returns minimum jump path from ( 0 , 0 ) to ( m , n ) in height [ R ] [ C ] ; base case ; Find minimum jumps if we go through diagonal ; Find minimum jumps if we go through down ; Find minimum jumps if we go through right ; return minimum jumps ; Driver Code | R = 4 NEW_LINE C = 3 NEW_LINE def isSafe ( x , y ) : NEW_LINE INDENT return ( x < R and y < C ) NEW_LINE DEDENT def minJump ( height , x , y ) : NEW_LINE INDENT if ( x == R - 1 and y == C - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT diag = 10 ** 9 NEW_LINE if ( isSafe ( x + 1 , y + 1 ) ) : NEW_LINE INDENT diag = ( minJump ( height , x + 1 , y + 1 ) + abs ( height [ x ] [ y ] - height [ x + 1 ] [ y + 1 ] ) ) NEW_LINE DEDENT down = 10 ** 9 NEW_LINE if ( isSafe ( x + 1 , y ) ) : NEW_LINE INDENT down = ( minJump ( height , x + 1 , y ) + abs ( height [ x ] [ y ] - height [ x + 1 ] [ y ] ) ) NEW_LINE DEDENT right = 10 ** 9 NEW_LINE if ( isSafe ( x , y + 1 ) ) : NEW_LINE INDENT right = ( minJump ( height , x , y + 1 ) + abs ( height [ x ] [ y ] - height [ x ] [ y + 1 ] ) ) NEW_LINE DEDENT return min ( [ down , right , diag ] ) NEW_LINE DEDENT height = [ [ 5 , 4 , 2 ] , [ 9 , 2 , 1 ] , [ 2 , 5 , 9 ] , [ 1 , 3 , 11 ] ] NEW_LINE print ( minJump ( height , 0 , 0 ) ) NEW_LINE |
Maximum sum subsequence with at | Python3 program to find maximum sum subsequence such that elements are at least k distance away . ; MS [ i ] is going to store maximum sum subsequence in subarray from arr [ i ] to arr [ n - 1 ] ; We fill MS from right to left . ; Driver code | def maxSum ( arr , N , k ) : NEW_LINE INDENT MS = [ 0 for i in range ( N ) ] NEW_LINE MS [ N - 1 ] = arr [ N - 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( i + k + 1 >= N ) : NEW_LINE INDENT MS [ i ] = max ( arr [ i ] , MS [ i + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT MS [ i ] = max ( arr [ i ] + MS [ i + k + 1 ] , MS [ i + 1 ] ) NEW_LINE DEDENT DEDENT return MS [ 0 ] NEW_LINE DEDENT N = 10 ; k = 2 NEW_LINE arr = [ 50 , 70 , 40 , 50 , 90 , 70 , 60 , 40 , 70 , 50 ] NEW_LINE print ( maxSum ( arr , N , k ) ) NEW_LINE |
Length of Longest Balanced Subsequence | Python3 program to find length of the longest balanced subsequence ; Variable to count all the open brace that does not have the corresponding closing brace . ; To count all the close brace that does not have the corresponding open brace . ; Iterating over the String ; Number of open braces that hasn 't been closed yet. ; Number of close braces that cannot be mapped to any open brace . ; Mapping the ith close brace to one of the open brace . ; Driver Code | def maxLength ( s , n ) : NEW_LINE INDENT invalidOpenBraces = 0 ; NEW_LINE invalidCloseBraces = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT invalidOpenBraces += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( invalidOpenBraces == 0 ) : NEW_LINE INDENT invalidCloseBraces += 1 NEW_LINE DEDENT else : NEW_LINE INDENT invalidOpenBraces -= 1 NEW_LINE DEDENT DEDENT DEDENT return ( n - ( invalidOpenBraces + invalidCloseBraces ) ) NEW_LINE DEDENT s = " ( ) ( ( ( ( ( ( ) " NEW_LINE n = len ( s ) NEW_LINE print ( maxLength ( s , n ) ) NEW_LINE |
Longest alternating sub | Function to calculate alternating sub - array for each index of array elements ; Initialize the base state of len [ ] ; Calculating value for each element ; If both elements are different then add 1 to next len [ i + 1 ] ; else initialize to 1 ; Print lengths of binary subarrays . ; Driver code | def alternateSubarray ( arr , n ) : NEW_LINE INDENT len = [ ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT len . append ( 0 ) NEW_LINE DEDENT len [ n - 1 ] = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] ^ arr [ i + 1 ] == True ) : NEW_LINE INDENT len [ i ] = len [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT len [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( len [ i ] , " β " , end = " " ) NEW_LINE DEDENT DEDENT arr = [ True , False , True , False , False , True ] NEW_LINE n = len ( arr ) NEW_LINE alternateSubarray ( arr , n ) NEW_LINE |
Longest alternating sub | Function to calculate alternating sub - array for each index of array elements ; Initialize count variable for storing length of sub - array ; Initialize ' prev ' variable which indicates the previous element while traversing for index 'i ; If both elements are same , print elements because alternate element is not found for current index ; print count and decrement it . ; Increment count for next element ; Re - initialize previous variable ; If elements are still available after traversing whole array , print it ; Driver Code | def alternateSubarray ( arr , n ) : NEW_LINE INDENT count = 1 NEW_LINE DEDENT ' NEW_LINE INDENT prev = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( ( arr [ i ] ^ prev ) == 0 ) : NEW_LINE INDENT while ( count ) : NEW_LINE INDENT print ( count , end = " β " ) NEW_LINE count -= 1 NEW_LINE DEDENT DEDENT count += 1 NEW_LINE prev = arr [ i ] NEW_LINE DEDENT while ( count ) : NEW_LINE INDENT print ( count , end = " β " ) NEW_LINE count -= 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE alternateSubarray ( arr , n ) NEW_LINE DEDENT |
Longest Common Subsequence with at most k changes allowed | Python3 program to find LCS of two arrays with k changes allowed in the first array . ; Return LCS with at most k changes allowed . ; If at most changes is less than 0. ; If any of two array is over . ; Making a reference variable to dp [ n ] [ m ] [ k ] ; If value is already calculated , return that value . ; calculating LCS with no changes made . ; calculating LCS when array element are same . ; calculating LCS with changes made . ; Driven Program | MAX = 10 NEW_LINE def lcs ( dp , arr1 , n , arr2 , m , k ) : NEW_LINE INDENT if k < 0 : NEW_LINE INDENT return - ( 10 ** 7 ) NEW_LINE DEDENT if n < 0 or m < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = dp [ n ] [ m ] [ k ] NEW_LINE if ans != - 1 : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = max ( lcs ( dp , arr1 , n - 1 , arr2 , m , k ) , lcs ( dp , arr1 , n , arr2 , m - 1 , k ) ) NEW_LINE if arr1 [ n - 1 ] == arr2 [ m - 1 ] : NEW_LINE INDENT ans = max ( ans , 1 + lcs ( dp , arr1 , n - 1 , arr2 , m - 1 , k ) ) NEW_LINE DEDENT ans = max ( ans , lcs ( dp , arr1 , n - 1 , arr2 , m - 1 , k - 1 ) ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 1 NEW_LINE arr1 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE arr2 = [ 5 , 3 , 1 , 4 , 2 ] NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE dp = [ [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] for k in range ( MAX ) ] NEW_LINE print ( lcs ( dp , arr1 , n , arr2 , m , k ) ) NEW_LINE DEDENT |
Count ways to build street under given constraints | function to count ways of building a street of n rows ; base case ; ways of building houses in both the spots of ith row ; ways of building an office in one of the two spots of ith row ; total ways for n rows ; Driver Code | def countWays ( n ) : NEW_LINE INDENT dp = [ [ 0 ] * ( n + 1 ) for i in range ( 2 ) ] NEW_LINE dp [ 0 ] [ 1 ] = 1 NEW_LINE dp [ 1 ] [ 1 ] = 2 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + dp [ 1 ] [ i - 1 ] NEW_LINE dp [ 1 ] [ i ] = ( dp [ 0 ] [ i - 1 ] * 2 + dp [ 1 ] [ i - 1 ] ) NEW_LINE DEDENT return dp [ 0 ] [ n ] + dp [ 1 ] [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE print ( " Total β no β of β ways β with β n β = " , n , " are : " , countWays ( n ) ) NEW_LINE DEDENT |
Count ways to build street under given constraints | Program to count ways ; Iterate from 2 to n ; Driver code ; Count Ways | def countways ( n ) : NEW_LINE INDENT A = [ 0 for i in range ( n + 2 ) ] NEW_LINE A [ 0 ] = 1 NEW_LINE A [ 1 ] = 3 NEW_LINE A [ 2 ] = 7 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT A [ i ] = 2 * A [ i - 1 ] + A [ i - 2 ] NEW_LINE DEDENT return A [ n ] NEW_LINE DEDENT n = 5 NEW_LINE print ( countways ( 5 ) ) NEW_LINE |
Maximum length subsequence with difference between adjacent elements as either 0 or 1 | function to find maximum length subsequence with difference between adjacent elements as either 0 or 1 ; Initialize mls [ ] values for all indexes ; Compute optimized maximum length subsequence values in bottom up manner ; Store maximum of all ' mls ' values in 'max ; required maximum length subsequence ; Driver program to test above | def maxLenSub ( arr , n ) : NEW_LINE INDENT mls = [ ] NEW_LINE max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mls . append ( 1 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( abs ( arr [ i ] - arr [ j ] ) <= 1 and mls [ i ] < mls [ j ] + 1 ) : NEW_LINE INDENT mls [ i ] = mls [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( max < mls [ i ] ) : NEW_LINE INDENT max = mls [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT arr = [ 2 , 5 , 6 , 3 , 7 , 6 , 5 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β length β subsequence β = β " , maxLenSub ( arr , n ) ) NEW_LINE |
Coin game winner where every player has three choices | To find winner of game ; To store results ; Initial values ; Computing other values . ; If A losses any of i - 1 or i - x or i - y game then he will definitely win game i ; Else A loses game . ; If dp [ n ] is true then A will game otherwise he losses ; Driver Code | def findWinner ( x , y , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] = False NEW_LINE dp [ 1 ] = True NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i - 1 >= 0 and not dp [ i - 1 ] ) : NEW_LINE INDENT dp [ i ] = True NEW_LINE DEDENT elif ( i - x >= 0 and not dp [ i - x ] ) : NEW_LINE INDENT dp [ i ] = True NEW_LINE DEDENT elif ( i - y >= 0 and not dp [ i - y ] ) : NEW_LINE INDENT dp [ i ] = True NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = False NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT x = 3 ; y = 4 ; n = 5 NEW_LINE if ( findWinner ( x , y , n ) ) : NEW_LINE INDENT print ( ' A ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' B ' ) NEW_LINE DEDENT |
Maximum games played by winner | method returns maximum games a winner needs to play in N - player tournament ; for 0 games , 1 player is needed for 1 game , 2 players are required ; loop until i - th Fibonacci number is less than or equal to N ; result is ( i - 1 ) because i will be incremented one extra in while loop and we want the last value which is smaller than N , so ; Driver code | def maxGameByWinner ( N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE dp [ 1 ] = 2 NEW_LINE i = 1 NEW_LINE while dp [ i ] <= N : NEW_LINE INDENT i = i + 1 NEW_LINE dp [ i ] = dp [ i - 1 ] + dp [ i - 2 ] NEW_LINE DEDENT return ( i - 1 ) NEW_LINE DEDENT N = 10 NEW_LINE print ( maxGameByWinner ( N ) ) NEW_LINE |
Convert to Strictly increasing integer array with minimum changes | Find min elements to remove from array to make it strictly increasing ; Mark all elements of LIS as 1 ; Find LIS of array ; Return min changes for array to strictly increasing ; Driver Code | def minRemove ( arr , n ) : NEW_LINE INDENT LIS = [ 0 for i in range ( n ) ] NEW_LINE len = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT LIS [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and ( i - j ) <= ( arr [ i ] - arr [ j ] ) ) : NEW_LINE INDENT LIS [ i ] = max ( LIS [ i ] , LIS [ j ] + 1 ) NEW_LINE DEDENT DEDENT len = max ( len , LIS [ i ] ) NEW_LINE DEDENT return ( n - len ) NEW_LINE DEDENT arr = [ 1 , 2 , 6 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minRemove ( arr , n ) ) NEW_LINE |
Ways of transforming one string to other by removing 0 or more characters | Python3 program to count the distinct transformation of one string to other . ; If b = " " i . e . , an empty string . There is only one way to transform ( remove all characters ) ; Fill dp [ ] [ ] in bottom up manner Traverse all character of b [ ] ; Traverse all characters of a [ ] for b [ i ] ; Filling the first row of the dp matrix . ; Filling other rows ; Driver Code | def countTransformation ( a , b ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if m == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT dp = [ [ 0 ] * ( n ) for _ in range ( m ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT if i == 0 : NEW_LINE INDENT if j == 0 : NEW_LINE INDENT if a [ j ] == b [ i ] : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT elif a [ j ] == b [ i ] : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if a [ j ] == b [ i ] : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = " abcccdf " NEW_LINE b = " abccdf " NEW_LINE print ( countTransformation ( a , b ) ) NEW_LINE DEDENT |
n | Python code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; function to convert num to base 6 ; Driver code ; initialize an array to 0 ; function calling to convert number n to base 6 ; if size is zero then return zero | max = 100000 ; NEW_LINE def baseconversion ( arr , num , base ) : NEW_LINE INDENT i = 0 ; NEW_LINE if ( num == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( num > 0 ) : NEW_LINE INDENT rem = num % base ; NEW_LINE i = i + 1 ; NEW_LINE arr [ i ] = rem ; NEW_LINE num = num // base ; NEW_LINE DEDENT return i ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 for i in range ( max ) ] ; NEW_LINE n = 10 ; NEW_LINE size = baseconversion ( arr , n - 1 , 6 ) ; NEW_LINE if ( size == 0 ) : NEW_LINE INDENT print ( size ) ; NEW_LINE DEDENT for i in range ( size , 0 , - 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " " ) ; NEW_LINE DEDENT DEDENT |
Find length of longest subsequence of one string which is substring of another string | Python3 program to find maximum length of subsequence of a string X such it is substring in another string Y . ; Return the maximum size of substring of X which is substring in Y . ; Calculating value for each element . ; If alphabet of string X and Y are equal make dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; Else copy the previous value in the row i . e dp [ i - 1 ] [ j - 1 ] ; Finding the maximum length ; Driver Code | MAX = 1000 NEW_LINE def maxSubsequenceSubstring ( x , y , n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( x [ j - 1 ] == y [ i - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] [ n ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT x = " ABCD " NEW_LINE y = " BACDBDCD " NEW_LINE n = len ( x ) NEW_LINE m = len ( y ) NEW_LINE print ( maxSubsequenceSubstring ( x , y , n , m ) ) NEW_LINE |
Choose maximum weight with given weight and value ratio | Python3 program to choose item with maximum sum of weight under given constraint ; base cases : if no item is remaining ; first make pair with last chosen item and difference between weight and values ; choose maximum value from following two 1 ) not selecting the current item and calling recursively 2 ) selection current item , including the weight and updating the difference before calling recursively ; method returns maximum sum of weight with K as ration of sum of weight and their values ; Driver code | INT_MIN = - 9999999999 NEW_LINE def maxWeightRec ( wt , val , K , mp , last , diff ) : NEW_LINE INDENT if last == - 1 : NEW_LINE INDENT if diff == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return INT_MIN NEW_LINE DEDENT DEDENT tmp = ( last , diff ) NEW_LINE if tmp in mp : NEW_LINE INDENT return mp [ tmp ] NEW_LINE DEDENT mp [ tmp ] = max ( maxWeightRec ( wt , val , K , mp , last - 1 , diff ) , wt [ last ] + maxWeightRec ( wt , val , K , mp , last - 1 , diff + wt [ last ] - val [ last ] * K ) ) NEW_LINE return mp [ tmp ] NEW_LINE DEDENT def maxWeight ( wt , val , K , N ) : NEW_LINE INDENT return maxWeightRec ( wt , val , K , { } , N - 1 , 0 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT wt = [ 4 , 8 , 9 ] NEW_LINE val = [ 2 , 4 , 6 ] NEW_LINE N = len ( wt ) NEW_LINE K = 2 NEW_LINE print ( maxWeight ( wt , val , K , N ) ) NEW_LINE DEDENT |
Pyramid form ( increasing then decreasing ) consecutive array using reduce operations | Returns minimum cost to form a pyramid ; Store the maximum possible pyramid height ; Maximum height at start is 1 ; For each position calculate maximum height ; Maximum height at end is 1 ; For each position calculate maximum height ; Find minimum possible among calculated values ; Find maximum height of pyramid ; Calculate cost of this pyramid ; Calculate cost of left half ; Calculate cost of right half ; Driver Code | def minPyramidCost ( arr : list , N ) : NEW_LINE INDENT left = [ 0 ] * N NEW_LINE right = [ 0 ] * N NEW_LINE left [ 0 ] = min ( arr [ 0 ] , 1 ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT left [ i ] = min ( arr [ i ] , min ( left [ i - 1 ] + 1 , i + 1 ) ) NEW_LINE DEDENT right [ N - 1 ] = min ( arr [ N - 1 ] , 1 ) NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT right [ i ] = min ( arr [ i ] , min ( right [ i + 1 ] + 1 , N - i ) ) NEW_LINE DEDENT tot = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT tot [ i ] = min ( right [ i ] , left [ i ] ) NEW_LINE DEDENT max_ind = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if tot [ i ] > tot [ max_ind ] : NEW_LINE INDENT max_ind = i NEW_LINE DEDENT DEDENT cost = 0 NEW_LINE height = tot [ max_ind ] NEW_LINE for x in range ( max_ind , - 1 , - 1 ) : NEW_LINE INDENT cost += arr [ x ] - height NEW_LINE if height > 0 : NEW_LINE INDENT height -= 1 NEW_LINE DEDENT DEDENT height = tot [ max_ind ] - 1 NEW_LINE for x in range ( max_ind + 1 , N ) : NEW_LINE INDENT cost += arr [ x ] - height NEW_LINE if height > 0 : NEW_LINE INDENT height -= 1 NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minPyramidCost ( arr , N ) ) NEW_LINE DEDENT |
Maximum sum in a 2 x n grid such that no two elements are adjacent | Function to find max sum without adjacent ; Sum including maximum element of first column ; Not including first column 's element ; Traverse for further elements ; Update max_sum on including or excluding of previous column ; Include current column . Add maximum element from both row of current column ; If current column doesn 't to be included ; Return maximum of excl and incl As that will be the maximum sum ; Driver code | def maxSum ( grid , n ) : NEW_LINE INDENT incl = max ( grid [ 0 ] [ 0 ] , grid [ 1 ] [ 0 ] ) NEW_LINE excl = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT excl_new = max ( excl , incl ) NEW_LINE incl = excl + max ( grid [ 0 ] [ i ] , grid [ 1 ] [ i ] ) NEW_LINE excl = excl_new NEW_LINE DEDENT return max ( excl , incl ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 10 ] ] NEW_LINE n = 5 NEW_LINE print ( maxSum ( grid , n ) ) NEW_LINE DEDENT // This code is contributed by Ryuga NEW_LINE |
Minimum insertions to sort an array | method returns min steps of insertion we need to perform to sort array 'arr ; lis [ i ] is going to store length of lis that ends with i . ; Initialize lis values for all indexes ; Compute optimized lis values in bottom up manner ; The overall LIS must end with of the array elements . Pick maximum of all lis values ; return size of array minus length of LIS as final result ; Driver Code | ' NEW_LINE def minInsertionStepToSortArray ( arr , N ) : NEW_LINE INDENT lis = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT lis [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] >= arr [ j ] and lis [ i ] < lis [ j ] + 1 ) : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT max = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( max < lis [ i ] ) : NEW_LINE INDENT max = lis [ i ] NEW_LINE DEDENT DEDENT return ( N - max ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 1 , 4 , 7 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minInsertionStepToSortArray ( arr , N ) ) NEW_LINE DEDENT |
Print all distinct characters of a string in order ( 3 Methods ) | ; checking if two charactors are equal | string = " GeeksforGeeks " NEW_LINE for i in range ( 0 , len ( string ) ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( 0 , len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == string [ j ] and i != j ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) NEW_LINE DEDENT DEDENT |
Print all distinct characters of a string in order ( 3 Methods ) | Python3 program to print distinct characters of a string . ; Print duplicates present in the passed string ; Create an array of size 256 and count of every character in it ; Count array with frequency of characters ; Print characters having count more than 0 ; Driver Code | NO_OF_CHARS = 256 NEW_LINE def printDistinct ( str ) : NEW_LINE INDENT count = [ 0 ] * NO_OF_CHARS NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] != ' β ' ) : NEW_LINE INDENT count [ ord ( str [ i ] ) ] += 1 NEW_LINE DEDENT DEDENT n = i NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( count [ ord ( str [ i ] ) ] == 1 ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " GeeksforGeeks " NEW_LINE printDistinct ( str ) NEW_LINE DEDENT |
Shortest Uncommon Subsequence | A simple recursive Python program to find shortest uncommon subsequence . ; A recursive function to find the length of shortest uncommon subsequence ; S String is empty ; T String is empty ; Loop to search for current character ; char not found in T ; Return minimum of following two Not including current char in answer Including current char ; Driver code | MAX = 1005 NEW_LINE def shortestSeq ( S , T , m , n ) : NEW_LINE INDENT if m == 0 : NEW_LINE INDENT return MAX NEW_LINE DEDENT if ( n <= 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for k in range ( n ) : NEW_LINE INDENT if ( T [ k ] == S [ 0 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( k == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return min ( shortestSeq ( S [ 1 : ] , T , m - 1 , n ) , 1 + shortestSeq ( ( S [ 1 : ] ) , T [ k + 1 : ] , m - 1 , n - k - 1 ) ) NEW_LINE DEDENT S = " babab " NEW_LINE T = " babba " NEW_LINE m = len ( S ) NEW_LINE n = len ( T ) NEW_LINE ans = shortestSeq ( S , T , m , n ) NEW_LINE if ( ans >= MAX ) : NEW_LINE INDENT ans = - 1 NEW_LINE DEDENT print ( " Length β of β shortest β subsequence β is : " , ans ) NEW_LINE |
Shortest Uncommon Subsequence | A dynamic programming based Python program to find shortest uncommon subsequence . ; Returns length of shortest common subsequence ; declaring 2D array of m + 1 rows and n + 1 columns dynamically ; T string is empty ; S string is empty ; char not present in T ; Driver Code | MAX = 1005 NEW_LINE def shortestSeq ( S : list , T : list ) : NEW_LINE INDENT m = len ( S ) NEW_LINE n = len ( T ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = MAX NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT ch = S [ i - 1 ] NEW_LINE k = j - 1 NEW_LINE while k >= 0 : NEW_LINE INDENT if T [ k ] == ch : NEW_LINE INDENT break NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT if k == - 1 : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i - 1 ] [ j ] , dp [ i - 1 ] [ k ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT ans = dp [ m ] [ n ] NEW_LINE if ans >= MAX : NEW_LINE INDENT ans = - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " babab " NEW_LINE T = " babba " NEW_LINE print ( " Length β of β shortest β subsequence β is : " , shortestSeq ( S , T ) ) NEW_LINE DEDENT |
Count number of ways to jump to reach end | Function to count ways to jump to reach end for each array element ; count_jump [ i ] store number of ways arr [ i ] can reach to the end ; Last element does not require to jump . Count ways to jump for remaining elements ; if the element can directly jump to the end ; Add the count of all the elements that can reach to end and arr [ i ] can reach to them ; if element can reach to end then add its count to count_jump [ i ] ; if arr [ i ] cannot reach to the end ; print count_jump for each array element ; Driver code | def countWaysToJump ( arr , n ) : NEW_LINE INDENT count_jump = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] >= n - i - 1 ) : NEW_LINE INDENT count_jump [ i ] += 1 NEW_LINE DEDENT j = i + 1 NEW_LINE while ( j < n - 1 and j <= arr [ i ] + i ) : NEW_LINE INDENT if ( count_jump [ j ] != - 1 ) : NEW_LINE INDENT count_jump [ i ] += count_jump [ j ] NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( count_jump [ i ] == 0 ) : NEW_LINE INDENT count_jump [ i ] = - 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( count_jump [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 5 , 8 , 9 , 1 , 0 , 7 , 6 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE countWaysToJump ( arr , n ) NEW_LINE |
Minimum steps to delete a string after repeated deletion of palindrome substrings | method returns minimum step for deleting the string , where in one step a palindrome is removed ; declare dp array and initialize it with 0 s ; loop for substring length we are considering ; loop with two variables i and j , denoting starting and ending of substrings ; If substring length is 1 , then 1 step will be needed ; delete the ith char individually and assign result for subproblem ( i + 1 , j ) ; if current and next char are same , choose min from current and subproblem ( i + 2 , j ) ; loop over all right characters and suppose Kth char is same as ith character then choose minimum from current and two substring after ignoring ith and Kth char ; Uncomment below snippet to print actual dp tablex for ( int i = 0 ; i < N ; i ++ , cout << endl ) for ( int j = 0 ; j < N ; j ++ ) cout << dp [ i ] [ j ] << " β " ; ; Driver Code | def minStepToDeleteString ( str ) : NEW_LINE INDENT N = len ( str ) NEW_LINE dp = [ [ 0 for x in range ( N + 1 ) ] for y in range ( N + 1 ) ] NEW_LINE for l in range ( 1 , N + 1 ) : NEW_LINE INDENT i = 0 NEW_LINE j = l - 1 NEW_LINE while j < N : NEW_LINE INDENT if ( l == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i + 1 ] [ j ] NEW_LINE if ( str [ i ] == str [ i + 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( 1 + dp [ i + 2 ] [ j ] , dp [ i ] [ j ] ) NEW_LINE DEDENT for K in range ( i + 2 , j + 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ K ] ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i + 1 ] [ K - 1 ] + dp [ K + 1 ] [ j ] , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return dp [ 0 ] [ N - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "2553432" NEW_LINE print ( minStepToDeleteString ( str ) ) NEW_LINE DEDENT |
Clustering / Partitioning an array such that sum of square differences is minimum | Initialize answer as infinite . ; function to generate all possible answers . and compute minimum of all costs . i -- > is index of previous partition par -- > is current number of partitions a [ ] and n -- > Input array and its size current_ans -- > Cost of partitions made so far . ; If number of partitions is more than k ; If we have mad k partitions and have reached last element ; 1 ) Partition array at different points 2 ) For every point , increase count of partitions , " par " by 1. 3 ) Before recursive call , add cost of the partition to current_ans ; Driver code | inf = 1000000000 NEW_LINE ans = inf NEW_LINE def solve ( i , par , a , n , k , current_ans ) : NEW_LINE INDENT if ( par > k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT global ans NEW_LINE if ( par == k and i == n - 1 ) : NEW_LINE INDENT ans = min ( ans , current_ans ) NEW_LINE return 0 NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT solve ( j , par + 1 , a , n , k , current_ans + ( a [ j ] - a [ i + 1 ] ) * ( a [ j ] - a [ i + 1 ] ) ) NEW_LINE DEDENT DEDENT k = 2 NEW_LINE a = [ 1 , 5 , 8 , 10 ] NEW_LINE n = len ( a ) NEW_LINE solve ( - 1 , 0 , a , n , k , 0 ) NEW_LINE print ( ans ) NEW_LINE |
Minimum steps to minimize n as per given condition | function to calculate min steps ; base case ; store temp value for n as min ( f ( n - 1 ) , f ( n2 ) , f ( n3 ) ) + 1 ; store memo [ n ] and return ; This function mainly initializes memo [ ] and calls getMinSteps ( n , memo ) ; initialize memoized array ; driver program | def getMinSteps ( n , memo ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( memo [ n ] != - 1 ) : NEW_LINE INDENT return memo [ n ] NEW_LINE DEDENT res = getMinSteps ( n - 1 , memo ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT res = min ( res , getMinSteps ( n // 2 , memo ) ) NEW_LINE DEDENT if ( n % 3 == 0 ) : NEW_LINE INDENT res = min ( res , getMinSteps ( n // 3 , memo ) ) NEW_LINE DEDENT memo [ n ] = 1 + res NEW_LINE return memo [ n ] NEW_LINE DEDENT def getsMinSteps ( n ) : NEW_LINE INDENT memo = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT memo [ i ] = - 1 NEW_LINE DEDENT return getMinSteps ( n , memo ) NEW_LINE DEDENT n = 10 NEW_LINE print ( getsMinSteps ( n ) ) NEW_LINE |
Count of arrays in which all adjacent elements are such that one of them divide the another | Python3 program to count the number of arrays of size n such that every element is in range [ 1 , m ] and adjacent are divisible ; For storing factors . ; For storing multiples . ; calculating the factors and multiples of elements [ 1. . . m ] . ; Initialising for size 1 array for each i <= m . ; Calculating the number of array possible of size i and starting with j . ; For all previous possible values . Adding number of factors . ; Adding number of multiple . ; Calculating the total count of array which start from [ 1. . . m ] . ; Driven Program | MAX = 1000 NEW_LINE def numofArray ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE di = [ [ ] for i in range ( MAX ) ] NEW_LINE mu = [ [ ] for i in range ( MAX ) ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 2 * i , m + 1 , i ) : NEW_LINE INDENT di [ j ] . append ( i ) NEW_LINE mu [ i ] . append ( j ) NEW_LINE DEDENT di [ i ] . append ( i ) NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE for x in di [ j ] : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ x ] NEW_LINE DEDENT for x in mu [ j ] : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ x ] NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT ans += dp [ n ] [ i ] NEW_LINE di [ i ] . clear ( ) NEW_LINE mu [ i ] . clear ( ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = m = 3 NEW_LINE print ( numofArray ( n , m ) ) NEW_LINE DEDENT |
Temple Offerings | Python3 program to find temple offerings required ; To store count of increasing order temples on left and right ( including current temple ) ; Returns count of minimum offerings for n temples of given heights . ; Initialize counts for all temples ; Values corner temples ; Filling left and right values using same values of previous ( or next ; Computing max of left and right for all temples and returing sum ; Driver code | from typing import List NEW_LINE class Temple : NEW_LINE INDENT def __init__ ( self , l : int , r : int ) : NEW_LINE INDENT self . L = l NEW_LINE self . R = r NEW_LINE DEDENT DEDENT def offeringNumber ( n : int , templeHeight : List [ int ] ) -> int : NEW_LINE INDENT chainSize = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT chainSize [ i ] = Temple ( - 1 , - 1 ) NEW_LINE DEDENT chainSize [ 0 ] . L = 1 NEW_LINE chainSize [ - 1 ] . R = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if templeHeight [ i - 1 ] < templeHeight [ i ] : NEW_LINE INDENT chainSize [ i ] . L = chainSize [ i - 1 ] . L + 1 NEW_LINE DEDENT else : NEW_LINE INDENT chainSize [ i ] . L = 1 NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if templeHeight [ i + 1 ] < templeHeight [ i ] : NEW_LINE INDENT chainSize [ i ] . R = chainSize [ i + 1 ] . R + 1 NEW_LINE DEDENT else : NEW_LINE INDENT chainSize [ i ] . R = 1 NEW_LINE DEDENT DEDENT sm = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sm += max ( chainSize [ i ] . L , chainSize [ i ] . R ) NEW_LINE DEDENT return sm NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 , 2 ] NEW_LINE print ( offeringNumber ( 3 , arr1 ) ) NEW_LINE arr2 = [ 1 , 4 , 3 , 6 , 2 , 1 ] NEW_LINE print ( offeringNumber ( 6 , arr2 ) ) NEW_LINE DEDENT |
Smallest length string with repeated replacement of two distinct adjacent | Returns smallest possible length with given operation allowed . ; Counint occurrences of three different characters ' a ' , ' b ' and ' c ' in str ; If all characters are same . ; If all characters are present even number of times or all are present odd number of times . ; Answer is 1 for all other cases . ; Driver code | def stringReduction ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE count = [ 0 ] * 3 NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT if ( count [ 0 ] == n or count [ 1 ] == n or count [ 2 ] == n ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( ( count [ 0 ] % 2 ) == ( count [ 1 ] % 2 ) and ( count [ 1 ] % 2 ) == ( count [ 2 ] % 2 ) ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT return 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " abcbbaacb " NEW_LINE print ( stringReduction ( str ) ) NEW_LINE DEDENT |
Largest sum Zigzag sequence in a matrix | Memoization based Python3 program to find the largest sum zigzag sequence ; Returns largest sum of a Zigzag sequence starting from ( i , j ) and ending at a bottom cell . ; If we have reached bottom ; Find the largest sum by considering all possible next elements in sequence . ; Returns largest possible sum of a Zizag sequence starting from top and ending at bottom . ; Consider all cells of top row as starting point ; Driver code | MAX = 100 ; NEW_LINE dp = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE def largestZigZagSumRec ( mat , i , j , n ) : NEW_LINE INDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] ; NEW_LINE DEDENT if ( i == n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = mat [ i ] [ j ] ; NEW_LINE return ( dp [ i ] [ j ] ) ; NEW_LINE DEDENT zzs = 0 ; NEW_LINE for k in range ( n ) : NEW_LINE INDENT if ( k != j ) : NEW_LINE INDENT zzs = max ( zzs , largestZigZagSumRec ( mat , i + 1 , k , n ) ) ; NEW_LINE DEDENT DEDENT dp [ i ] [ j ] = ( zzs + mat [ i ] [ j ] ) ; NEW_LINE return ( dp [ i ] [ j ] ) ; NEW_LINE DEDENT def largestZigZag ( mat , n ) : NEW_LINE INDENT for i in range ( MAX ) : NEW_LINE INDENT for k in range ( MAX ) : NEW_LINE INDENT dp [ i ] [ k ] = - 1 ; NEW_LINE DEDENT DEDENT res = 0 ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT res = max ( res , largestZigZagSumRec ( mat , 0 , j , n ) ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE mat = [ [ 4 , 2 , 1 ] , [ 3 , 9 , 6 ] , [ 11 , 3 , 15 ] ] ; NEW_LINE print ( " Largest β zigzag β sum : β " , largestZigZag ( mat , n ) ) ; NEW_LINE DEDENT |
Number of subsequences of the form a ^ i b ^ j c ^ k | Returns count of subsequences of the form a ^ i b ^ j c ^ k ; Initialize counts of different subsequences caused by different combination of 'a ; Initialize counts of different subsequences caused by different combination of ' a ' and different combination of 'b ; Initialize counts of different subsequences caused by different combination of ' a ' , ' b ' and ' c ' . ; Traverse all characters of given string ; If current character is ' a ' , then there are following possibilities : a ) Current character begins a new subsequence . b ) Current character is part of aCount subsequences . c ) Current character is not part of aCount subsequences . ; If current character is ' b ' , then there are following possibilities : a ) Current character begins a new subsequence of b 's with aCount subsequences. b) Current character is part of bCount subsequences. c) Current character is not part of bCount subsequences. ; If current character is ' c ' , then there are following possibilities : a ) Current character begins a new subsequence of c 's with bCount subsequences. b) Current character is part of cCount subsequences. c) Current character is not part of cCount subsequences. ; Driver code | def countSubsequences ( s ) : NEW_LINE ' NEW_LINE INDENT aCount = 0 NEW_LINE DEDENT ' NEW_LINE INDENT bCount = 0 NEW_LINE cCount = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT aCount = ( 1 + 2 * aCount ) NEW_LINE DEDENT elif ( s [ i ] == ' b ' ) : NEW_LINE INDENT bCount = ( aCount + 2 * bCount ) NEW_LINE DEDENT elif ( s [ i ] == ' c ' ) : NEW_LINE INDENT cCount = ( bCount + 2 * cCount ) NEW_LINE DEDENT DEDENT return cCount NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abbc " NEW_LINE print ( countSubsequences ( s ) ) NEW_LINE DEDENT |
Highway Billboard Problem | Python3 program to find maximum revenue by placing billboard on the highway with given constraints . ; Array to store maximum revenue at each miles . ; actual minimum distance between 2 billboards . ; check if all billboards are already placed . ; check if we have billboard for that particular mile . If not , copy the previous maximum revenue . ; we do have billboard for this mile . ; If current position is less than or equal to t , then we can have only one billboard . ; Else we may have to remove previously placed billboard ; Driver Code | def maxRevenue ( m , x , revenue , n , t ) : NEW_LINE INDENT maxRev = [ 0 ] * ( m + 1 ) NEW_LINE nxtbb = 0 ; NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( nxtbb < n ) : NEW_LINE INDENT if ( x [ nxtbb ] != i ) : NEW_LINE INDENT maxRev [ i ] = maxRev [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT if ( i <= t ) : NEW_LINE INDENT maxRev [ i ] = max ( maxRev [ i - 1 ] , revenue [ nxtbb ] ) NEW_LINE DEDENT else : NEW_LINE INDENT maxRev [ i ] = max ( maxRev [ i - t - 1 ] + revenue [ nxtbb ] , maxRev [ i - 1 ] ) ; NEW_LINE DEDENT nxtbb += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT maxRev [ i ] = maxRev [ i - 1 ] NEW_LINE DEDENT DEDENT return maxRev [ m ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = 20 NEW_LINE x = [ 6 , 7 , 12 , 13 , 14 ] NEW_LINE revenue = [ 5 , 6 , 5 , 3 , 1 ] NEW_LINE n = len ( x ) NEW_LINE t = 5 NEW_LINE print ( maxRevenue ( m , x , revenue , n , t ) ) NEW_LINE DEDENT |
Finding the maximum square sub | Python 3 program to find maximum K such that K x K is a submatrix with equal elements . ; Returns size of the largest square sub - matrix with all same elements . ; If elements is at top row or first column , it wont form a square matrix 's bottom-right ; Check if adjacent elements are equal ; If not equal , then it will form a 1 x1 submatrix ; Update result at each ( i , j ) ; Driver Code | Row = 6 NEW_LINE Col = 6 NEW_LINE def largestKSubmatrix ( a ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( Row ) ] for y in range ( Col ) ] NEW_LINE result = 0 NEW_LINE for i in range ( Row ) : NEW_LINE INDENT for j in range ( Col ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( a [ i ] [ j ] == a [ i - 1 ] [ j ] and a [ i ] [ j ] == a [ i ] [ j - 1 ] and a [ i ] [ j ] == a [ i - 1 ] [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) , dp [ i - 1 ] [ j - 1 ] ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT result = max ( result , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT a = [ [ 2 , 2 , 3 , 3 , 4 , 4 ] , [ 5 , 5 , 7 , 7 , 7 , 4 ] , [ 1 , 2 , 7 , 7 , 7 , 4 ] , [ 4 , 4 , 7 , 7 , 7 , 4 ] , [ 5 , 5 , 5 , 1 , 2 , 7 ] , [ 8 , 7 , 9 , 4 , 4 , 4 ] ] ; NEW_LINE print ( largestKSubmatrix ( a ) ) NEW_LINE |
Number of subsequences in a string divisible by n | Returns count of subsequences of str divisible by n . ; division by n can leave only n remainder [ 0. . n - 1 ] . dp [ i ] [ j ] indicates number of subsequences in string [ 0. . i ] which leaves remainder j after division by n . ; Filling value for first digit in str ; start a new subsequence with index i ; exclude i 'th character from all the current subsequences of string [0...i-1] ; include i 'th character in all the current subsequences of string [0...i-1] ; Driver code | def countDivisibleSubseq ( str , n ) : NEW_LINE INDENT l = len ( str ) NEW_LINE dp = [ [ 0 for x in range ( l ) ] for y in range ( n ) ] NEW_LINE dp [ 0 ] [ ( ord ( str [ 0 ] ) - ord ( '0' ) ) % n ] += 1 NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT dp [ i ] [ ( ord ( str [ i ] ) - ord ( '0' ) ) % n ] += 1 NEW_LINE for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE dp [ i ] [ ( j * 10 + ( ord ( str [ i ] ) - ord ( '0' ) ) ) % n ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT return dp [ l - 1 ] [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "1234" NEW_LINE n = 4 NEW_LINE print ( countDivisibleSubseq ( str , n ) ) NEW_LINE DEDENT |
Size of array after repeated deletion of LIS | Function to construct Maximum Sum LIS ; L [ i ] - The Maximum Sum Increasing Subsequence that ends with arr [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; L [ i ] = MaxSum ( L [ j ] ) + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; L [ i ] ends with arr [ i ] ; set lis = LIS whose size is max among all ; The > sign makes sure that the LIS ending first is chose . ; Function to minimize array ; Find LIS of current array ; If all elements are in decreasing order ; Remove lis elements from current array . Note that both lis [ ] and arr [ ] are sorted in increasing order . ; If first element of lis [ ] is found ; Remove lis element from arr [ ] ; Erase first element of lis [ ] ; print remaining element of array ; print - 1 for empty array ; Driver function ; minimize array after deleting LIS | from typing import List NEW_LINE def findLIS ( arr : List [ int ] , n : int ) -> List [ int ] : NEW_LINE INDENT L = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT L [ i ] = [ ] NEW_LINE DEDENT L [ 0 ] . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and ( len ( L [ i ] ) < len ( L [ j ] ) ) ) : NEW_LINE INDENT L [ i ] = L [ j ] . copy ( ) NEW_LINE DEDENT DEDENT L [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT maxSize = 1 NEW_LINE lis : List [ int ] = [ ] NEW_LINE for x in L : NEW_LINE INDENT if ( len ( x ) > maxSize ) : NEW_LINE INDENT lis = x . copy ( ) NEW_LINE maxSize = len ( x ) NEW_LINE DEDENT DEDENT return lis NEW_LINE DEDENT def minimize ( input : List [ int ] , n : int ) -> None : NEW_LINE INDENT arr = input . copy ( ) NEW_LINE while len ( arr ) : NEW_LINE INDENT lis = findLIS ( arr , len ( arr ) ) NEW_LINE if ( len ( lis ) < 2 ) : NEW_LINE INDENT break NEW_LINE DEDENT i = 0 NEW_LINE while i < len ( arr ) and len ( lis ) > 0 : NEW_LINE INDENT if ( arr [ i ] == lis [ 0 ] ) : NEW_LINE INDENT arr . remove ( arr [ i ] ) NEW_LINE i -= 1 NEW_LINE lis . remove ( lis [ 0 ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while i < len ( arr ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input = [ 3 , 2 , 6 , 4 , 5 , 1 ] NEW_LINE n = len ( input ) NEW_LINE minimize ( input , n ) NEW_LINE DEDENT |
Probability of getting at least K heads in N tosses of Coins | Naive approach in Python3 to find probability of at least k heads ; Returns probability of getting at least k heads in n tosses . ; Probability of getting exactly i heads out of n heads ; Note : 1 << n = pow ( 2 , n ) ; Preprocess all factorial only upto 19 , as after that it will overflow ; Driver code ; Probability of getting 2 head out of 3 coins ; Probability of getting 3 head out of 6 coins ; Probability of getting 12 head out of 18 coins | MAX = 21 NEW_LINE fact = [ 0 ] * MAX NEW_LINE def probability ( k , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( k , n + 1 ) : NEW_LINE INDENT ans += fact [ n ] / ( fact [ i ] * fact [ n - i ] ) NEW_LINE DEDENT ans = ans / ( 1 << n ) NEW_LINE return ans NEW_LINE DEDENT def precompute ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE fact [ 1 ] = 1 NEW_LINE for i in range ( 2 , 20 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT precompute ( ) NEW_LINE print ( probability ( 2 , 3 ) ) NEW_LINE print ( probability ( 3 , 6 ) ) NEW_LINE print ( probability ( 12 , 18 ) ) NEW_LINE DEDENT |
Count binary strings with k times appearing adjacent two set bits | Python3 program to count number of binary strings with k times appearing consecutive 1 's. ; dp [ i ] [ j ] [ 0 ] stores count of binary strings of length i with j consecutive 1 ' s β and β ending β at β 0 . β β dp [ i ] [ j ] [1 ] β stores β count β of β binary β β strings β of β length β i β with β j β consecutive β β 1' s and ending at 1. ; If n = 1 and k = 0. ; number of adjacent 1 's can not exceed i-1 ; Driver Code | def countStrings ( n , k ) : NEW_LINE INDENT dp = [ [ [ 0 , 0 ] for __ in range ( k + 1 ) ] for _ in range ( n + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 0 ] [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ 0 ] = ( dp [ i - 1 ] [ j ] [ 0 ] + dp [ i - 1 ] [ j ] [ 1 ] ) NEW_LINE dp [ i ] [ j ] [ 1 ] = dp [ i - 1 ] [ j ] [ 0 ] NEW_LINE if j >= 1 : NEW_LINE INDENT dp [ i ] [ j ] [ 1 ] += dp [ i - 1 ] [ j - 1 ] [ 1 ] NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ k ] [ 0 ] + dp [ n ] [ k ] [ 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE k = 2 NEW_LINE print ( countStrings ( n , k ) ) NEW_LINE DEDENT |
Check if all people can vote on two machines | Returns true if n people can vote using two machines in x time . ; calculate total sum i . e total time taken by all people ; if total time is less than x then all people can definitely vote hence return true ; sort the list ; declare a list presum of same size as that of a and initialize it with 0 ; prefixsum for first element will be element itself ; fill the array ; Set i and j and check if array from i to j - 1 gives sum <= x ; Driver code | def canVote ( a , n , x ) : NEW_LINE INDENT total_sum = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT total_sum += a [ i ] NEW_LINE DEDENT if ( total_sum <= x ) : NEW_LINE INDENT return True NEW_LINE DEDENT a . sort ( ) NEW_LINE presum = [ 0 for i in range ( len ( a ) ) ] NEW_LINE presum [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 1 , len ( presum ) ) : NEW_LINE INDENT presum [ i ] = presum [ i - 1 ] + a [ i ] NEW_LINE DEDENT for i in range ( 0 , len ( presum ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( presum ) ) : NEW_LINE INDENT arr1_sum = ( presum [ i ] + ( total_sum - presum [ j ] ) ) NEW_LINE if ( ( arr1_sum <= x ) and ( total_sum - arr1_sum ) <= x ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT n = 3 NEW_LINE x = 4 NEW_LINE a = [ 2 , 4 , 2 ] NEW_LINE if ( canVote ( a , n , x ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Friends Pairing Problem | Python3 program for solution of friends pairing problem Using Recursion ; Returns count of ways n people can remain single or paired up . ; Driver Code | dp = [ - 1 ] * 1000 NEW_LINE def countFriendsPairings ( n ) : NEW_LINE INDENT global dp NEW_LINE if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT dp [ n ] = ( countFriendsPairings ( n - 1 ) + ( n - 1 ) * countFriendsPairings ( n - 2 ) ) NEW_LINE return dp [ n ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ n ] = n NEW_LINE return dp [ n ] NEW_LINE DEDENT DEDENT n = 4 NEW_LINE print ( countFriendsPairings ( n ) ) NEW_LINE |
Friends Pairing Problem | Python3 soln using mathematical approach factorial array is stored dynamically ; Returns count of ways n people can remain single or paired up . ; pow of 1 will always be one ; Driver Code pre - compute factorial | fact = [ 1 ] NEW_LINE def preComputeFact ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact . append ( ( fact [ i - 1 ] * i ) ) NEW_LINE DEDENT DEDENT def countFriendsPairings ( n ) : NEW_LINE INDENT ones = n NEW_LINE twos = 1 NEW_LINE ans = 0 NEW_LINE while ( ones >= 0 ) : NEW_LINE INDENT ans = ans + ( fact [ n ] // ( twos * fact [ ones ] * fact [ ( n - ones ) // 2 ] ) ) NEW_LINE ones = ones - 2 NEW_LINE twos = twos * 2 NEW_LINE DEDENT return ( ans ) NEW_LINE DEDENT preComputeFact ( 1000 ) NEW_LINE n = 4 NEW_LINE print ( countFriendsPairings ( n ) ) NEW_LINE |
Maximum path sum in a triangle . | Python program for Dynamic Programming implementation of Max sum problem in a triangle ; Function for finding maximum sum ; loop for bottom - up calculation ; for each element , check both elements just below the number and below right to the number add the maximum of them to it ; return the top element which stores the maximum sum ; Driver program to test above function | N = 3 NEW_LINE def maxPathSum ( tri , m , n ) : NEW_LINE INDENT for i in range ( m - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( tri [ i + 1 ] [ j ] > tri [ i + 1 ] [ j + 1 ] ) : NEW_LINE INDENT tri [ i ] [ j ] += tri [ i + 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT tri [ i ] [ j ] += tri [ i + 1 ] [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT return tri [ 0 ] [ 0 ] NEW_LINE DEDENT tri = [ [ 1 , 0 , 0 ] , [ 4 , 8 , 0 ] , [ 1 , 5 , 3 ] ] NEW_LINE print ( maxPathSum ( tri , 2 , 2 ) ) NEW_LINE |
Find Maximum dot product of two arrays with insertion of 0 's | Function compute Maximum Dot Product and return it ; Create 2D Matrix that stores dot product dp [ i + 1 ] [ j + 1 ] stores product considering B [ 0. . i ] and A [ 0. . . j ] . Note that since all m > n , we fill values in upper diagonal of dp [ ] [ ] ; Traverse through all elements of B [ ] ; Consider all values of A [ ] with indexes greater than or equal to i and compute dp [ i ] [ j ] ; Two cases arise 1 ) Include A [ j ] 2 ) Exclude A [ j ] ( insert 0 in B [ ] ) ; return Maximum Dot Product ; Driver Code | def MaxDotProduct ( A , B , m , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , m + 1 , 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( ( dp [ i - 1 ] [ j - 1 ] + ( A [ j - 1 ] * B [ i - 1 ] ) ) , dp [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n ] [ m ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 3 , 1 , 7 , 8 ] NEW_LINE B = [ 3 , 6 , 7 ] NEW_LINE m = len ( A ) NEW_LINE n = len ( B ) NEW_LINE print ( MaxDotProduct ( A , B , m , n ) ) NEW_LINE DEDENT |
LCS ( Longest Common Subsequence ) of three strings | Python3 program to find LCS of three strings ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] and Z [ 0. . o - 1 ] ; Driver code | X = " AGGT12" NEW_LINE Y = "12TXAYB " NEW_LINE Z = "12XBA " NEW_LINE dp = [ [ [ - 1 for i in range ( 100 ) ] for j in range ( 100 ) ] for k in range ( 100 ) ] NEW_LINE def lcsOf3 ( i , j , k ) : NEW_LINE INDENT if ( i == - 1 or j == - 1 or k == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] [ k ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] [ k ] NEW_LINE DEDENT if ( X [ i ] == Y [ j ] and Y [ j ] == Z [ k ] ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = 1 + lcsOf3 ( i - 1 , j - 1 , k - 1 ) NEW_LINE return dp [ i ] [ j ] [ k ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = max ( max ( lcsOf3 ( i - 1 , j , k ) , lcsOf3 ( i , j - 1 , k ) ) , lcsOf3 ( i , j , k - 1 ) ) NEW_LINE return dp [ i ] [ j ] [ k ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE o = len ( Z ) NEW_LINE print ( " Length β of β LCS β is " , lcsOf3 ( m - 1 , n - 1 , o - 1 ) ) NEW_LINE DEDENT |
Minimum number of elements which are not part of Increasing or decreasing subsequence in array | Python3 program to return minimum number of elements which are not part of increasing or decreasing subsequences . ; Return minimum number of elements which is not part of any of the sequence . ; If already calculated , return value . ; If whole array is traversed . ; calculating by considering element as part of decreasing sequence . ; calculating by considering element as part of increasing sequence . ; If cannot be calculated for decreasing sequence . ; After considering once by decreasing sequence , now try for increasing sequence . ; If element cannot be part of any of the sequence . ; After considering element as part of increasing and decreasing sequence trying as not part of any of the sequence . ; Wrapper Function ; Adding two number at the end of array , so that increasing and decreasing sequence can be made . MAX - 2 index is assigned INT_MAX for decreasing sequence because / next number of sequence must be less than it . Similarly , for Increasing sequence INT_MIN is assigned to MAX - 1 index . ; Driver code | MAX = 102 NEW_LINE def countMin ( arr , dp , n , dec , inc , i ) : NEW_LINE INDENT if dp [ dec ] [ inc ] [ i ] != - 1 : NEW_LINE INDENT return dp [ dec ] [ inc ] [ i ] NEW_LINE DEDENT if i == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if arr [ i ] < arr [ dec ] : NEW_LINE INDENT dp [ dec ] [ inc ] [ i ] = countMin ( arr , dp , n , i , inc , i + 1 ) NEW_LINE DEDENT if arr [ i ] > arr [ inc ] : NEW_LINE INDENT if dp [ dec ] [ inc ] [ i ] == - 1 : NEW_LINE INDENT dp [ dec ] [ inc ] [ i ] = countMin ( arr , dp , n , dec , i , i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ dec ] [ inc ] [ i ] = min ( countMin ( arr , dp , n , dec , i , i + 1 ) , dp [ dec ] [ inc ] [ i ] ) NEW_LINE DEDENT DEDENT if dp [ dec ] [ inc ] [ i ] == - 1 : NEW_LINE INDENT dp [ dec ] [ inc ] [ i ] = 1 + countMin ( arr , dp , n , dec , inc , i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ dec ] [ inc ] [ i ] = min ( 1 + countMin ( arr , dp , n , dec , inc , i + 1 ) , dp [ dec ] [ inc ] [ i ] ) NEW_LINE DEDENT return dp [ dec ] [ inc ] [ i ] NEW_LINE DEDENT def wrapper ( arr , n ) : NEW_LINE INDENT arr [ MAX - 2 ] = 1000000000 NEW_LINE arr [ MAX - 1 ] = - 1000000000 NEW_LINE dp = [ [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE return countMin ( arr , dp , n , MAX - 2 , MAX - 1 , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE arr = [ 7 , 8 , 1 , 2 , 4 , 6 , 3 , 5 , 2 , 1 , 8 , 7 ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT arr . append ( 0 ) NEW_LINE DEDENT print ( wrapper ( arr , n ) ) NEW_LINE DEDENT |
Find all distinct subset ( or subsequence ) sums of an array | sum denotes the current sum of the subset currindex denotes the index we have reached in the given array ; This function mainly calls recursive function distSumRec ( ) to generate distinct sum subsets . And finally prints the generated subsets . ; Print the result ; Driver code | def distSumRec ( arr , n , sum , currindex , s ) : NEW_LINE INDENT if ( currindex > n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( currindex == n ) : NEW_LINE INDENT s . add ( sum ) NEW_LINE return NEW_LINE DEDENT distSumRec ( arr , n , sum + arr [ currindex ] , currindex + 1 , s ) NEW_LINE distSumRec ( arr , n , sum , currindex + 1 , s ) NEW_LINE DEDENT def printDistSum ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE distSumRec ( arr , n , 0 , 0 , s ) NEW_LINE for i in s : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printDistSum ( arr , n ) NEW_LINE DEDENT |
Find all distinct subset ( or subsequence ) sums of an array | Uses Dynamic Programming to find distinct subset Sums ; dp [ i ] [ j ] would be true if arr [ 0. . i - 1 ] has a subset with Sum equal to j . ; There is always a subset with 0 Sum ; Fill dp [ ] [ ] in bottom up manner ; Sums that were achievable without current array element ; Print last row elements ; Driver code | def printDistSum ( arr , n ) : NEW_LINE INDENT Sum = sum ( arr ) NEW_LINE dp = [ [ False for i in range ( Sum + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ arr [ i - 1 ] ] = True NEW_LINE for j in range ( 1 , Sum + 1 ) : NEW_LINE INDENT if ( dp [ i - 1 ] [ j ] == True ) : NEW_LINE INDENT dp [ i ] [ j ] = True NEW_LINE dp [ i ] [ j + arr [ i - 1 ] ] = True NEW_LINE DEDENT DEDENT DEDENT for j in range ( Sum + 1 ) : NEW_LINE INDENT if ( dp [ n ] [ j ] == True ) : NEW_LINE INDENT print ( j , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printDistSum ( arr , n ) NEW_LINE |
Super Ugly Number ( Number whose prime factors are in given set ) | function will return the nth super ugly number ; n cannot be negative hence return - 1 if n is 0 or - ve ; Declare a min heap priority queue ; Push all the array elements to priority queue ; once count = n we return no ; sorted ( pq ) Get the minimum value from priority_queue ; If top of pq is no then don 't increment count. This to avoid duplicate counting of same no. ; Push all the multiples of no . to priority_queue ; cnt += 1 ; Return nth super ugly number ; Driver program to test above functions | def ugly ( a , size , n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT pq = [ ] NEW_LINE for i in range ( size ) : NEW_LINE INDENT pq . append ( a [ i ] ) NEW_LINE DEDENT count = 1 NEW_LINE no = 0 NEW_LINE pq = sorted ( pq ) NEW_LINE while ( count < n ) : NEW_LINE INDENT no = pq [ 0 ] NEW_LINE del pq [ 0 ] NEW_LINE if ( no != pq [ 0 ] ) : NEW_LINE INDENT count += 1 NEW_LINE for i in range ( size ) : NEW_LINE INDENT pq . append ( no * a [ i ] ) NEW_LINE DEDENT DEDENT pq = sorted ( pq ) NEW_LINE DEDENT return no NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 3 , 5 ] NEW_LINE size = len ( a ) NEW_LINE print ( ugly ( a , size , 1000 ) ) NEW_LINE DEDENT |
Count number of ways to reach destination in a Maze | Python 3 program to count number of paths in a maze with obstacles . ; Returns count of possible paths in a maze [ R ] [ C ] from ( 0 , 0 ) to ( R - 1 , C - 1 ) ; If the initial cell is blocked , there is no way of moving anywhere ; Initializing the leftmost column ; If we encounter a blocked cell in leftmost row , there is no way of visiting any cell directly below it . ; Similarly initialize the topmost row ; If we encounter a blocked cell in bottommost row , there is no way of visiting any cell directly below it . ; The only difference is that if a cell is - 1 , simply ignore it else recursively compute count value maze [ i ] [ j ] ; If blockage is found , ignore this cell ; If we can reach maze [ i ] [ j ] from maze [ i - 1 ] [ j ] then increment count . ; If we can reach maze [ i ] [ j ] from maze [ i ] [ j - 1 ] then increment count . ; If the final cell is blocked , output 0 , otherwise the answer ; Driver code | R = 4 NEW_LINE C = 4 NEW_LINE def countPaths ( maze ) : NEW_LINE INDENT if ( maze [ 0 ] [ 0 ] == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( R ) : NEW_LINE INDENT if ( maze [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT maze [ i ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( 1 , C , 1 ) : NEW_LINE INDENT if ( maze [ 0 ] [ i ] == 0 ) : NEW_LINE INDENT maze [ 0 ] [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( 1 , R , 1 ) : NEW_LINE INDENT for j in range ( 1 , C , 1 ) : NEW_LINE INDENT if ( maze [ i ] [ j ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( maze [ i - 1 ] [ j ] > 0 ) : NEW_LINE INDENT maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i - 1 ] [ j ] ) NEW_LINE DEDENT if ( maze [ i ] [ j - 1 ] > 0 ) : NEW_LINE INDENT maze [ i ] [ j ] = ( maze [ i ] [ j ] + maze [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if ( maze [ R - 1 ] [ C - 1 ] > 0 ) : NEW_LINE INDENT return maze [ R - 1 ] [ C - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT maze = [ [ 0 , 0 , 0 , 0 ] , [ 0 , - 1 , 0 , 0 ] , [ - 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE print ( countPaths ( maze ) ) NEW_LINE DEDENT |
Minimum sum subsequence such that at least one of every four consecutive elements is picked | Returns sum of minimum sum subsequence such that one of every four consecutive elements is picked from arr [ ] . ; dp [ i ] is going to store minimum sum subsequence of arr [ 0. . i ] such that arr [ i ] is part of the solution . Note that this may not be the best solution for subarray arr [ 0. . i ] ; If there is single value , we get the minimum sum equal to arr [ 0 ] ; If there are two values , we get the minimum sum equal to the minimum of two values ; If there are three values , return minimum of the three elements of array ; If there are four values , return minimum of the four elements of array ; Return the minimum of last 4 index ; Driver code | def minSum ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return min ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE DEDENT if ( n == 3 ) : NEW_LINE INDENT return min ( arr [ 0 ] , min ( arr [ 1 ] , arr [ 2 ] ) ) NEW_LINE DEDENT if ( n == 4 ) : NEW_LINE INDENT return min ( min ( arr [ 0 ] , arr [ 1 ] ) , min ( arr [ 2 ] , arr [ 3 ] ) ) NEW_LINE DEDENT dp [ 0 ] = arr [ 0 ] NEW_LINE dp [ 1 ] = arr [ 1 ] NEW_LINE dp [ 2 ] = arr [ 2 ] NEW_LINE dp [ 3 ] = arr [ 3 ] NEW_LINE for i in range ( 4 , n ) : NEW_LINE INDENT dp [ i ] = arr [ i ] + min ( min ( dp [ i - 1 ] , dp [ i - 2 ] ) , min ( dp [ i - 3 ] , dp [ i - 4 ] ) ) NEW_LINE DEDENT return min ( min ( dp [ n - 1 ] , dp [ n - 2 ] ) , min ( dp [ n - 4 ] , dp [ n - 3 ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 4 , 5 , 6 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minSum ( arr , n ) ) NEW_LINE DEDENT |
Maximum decimal value path in a binary matrix | Python3 program to find maximum decimal value path in binary matrix ; Returns maximum decimal value in binary matrix . Here p indicate power of 2 ; Out of matrix boundary ; If current matrix value is 1 then return result + power ( 2 , p ) else result ; Driver Program | N = 4 NEW_LINE def maxDecimalValue ( mat , i , j , p ) : NEW_LINE INDENT if i >= N or j >= N : NEW_LINE INDENT return 0 NEW_LINE DEDENT result = max ( maxDecimalValue ( mat , i , j + 1 , p + 1 ) , maxDecimalValue ( mat , i + 1 , j , p + 1 ) ) NEW_LINE if mat [ i ] [ j ] == 1 : NEW_LINE INDENT return pow ( 2 , p ) + result NEW_LINE DEDENT else : NEW_LINE INDENT return result NEW_LINE DEDENT DEDENT mat = [ [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 ] ] NEW_LINE print ( maxDecimalValue ( mat , 0 , 0 , 0 ) ) NEW_LINE |
Maximum decimal value path in a binary matrix | Python3 program to find Maximum decimal value Path in Binary matrix ; Returns maximum decimal value in binary matrix . Here p indicate power of 2 ; Compute binary stream of first row of matrix and store result in dp [ 0 ] [ i ] ; indicate 1 * ( 2 ^ i ) + result of previous ; indicate 0 * ( 2 ^ i ) + result of previous ; Compute binary stream of first column of matrix and store result in dp [ i ] [ 0 ] ; indicate 1 * ( 2 ^ i ) + result of previous ; indicate 0 * ( 2 ^ i ) + result of previous ; Traversal rest Binary matrix and Compute maximum decimal value ; Here ( i + j ) indicate the current power of 2 in path that is 2 ^ ( i + j ) ; Return maximum decimal value in binary matrix ; Driver program | N = 4 NEW_LINE def MaximumDecimalValue ( mat , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE if ( mat [ 0 ] [ 0 ] == 1 ) : NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( mat [ 0 ] [ i ] == 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] + 2 ** i NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ i ] = dp [ 0 ] [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( mat [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + 2 ** i NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 1 , n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) + ( 2 ** ( i + j ) ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n - 1 ] [ n - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 1 , 0 ] , [ 1 , 0 , 0 , 1 ] , [ 1 , 0 , 1 , 1 ] ] NEW_LINE print ( MaximumDecimalValue ( mat , 4 ) ) NEW_LINE DEDENT |
Count All Palindrome Sub | Returns total number of palindrome substring of length greater then equal to 2 ; creat empty 2 - D matrix that counts all palindrome substring . dp [ i ] [ j ] stores counts of palindromic substrings in st [ i . . j ] ; P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false ; palindrome of single length ; palindrome of length 2 ; Palindromes of length more than 2. This loop is similar to Matrix Chain Multiplication . We start with a gap of length 2 and fill DP table in a way that the gap between starting and ending indexes increase one by one by outer loop . ; Pick a starting point for the current gap ; Set ending point ; If current string is palindrome ; Add current palindrome substring ( + 1 ) and rest palindrome substring ( dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] ) remove common palindrome substrings ( - dp [ i + 1 ] [ j - 1 ] ) ; return total palindromic substrings ; Driver Code | def CountPS ( str , n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE P = [ [ False for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT P [ i ] [ i ] = True NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ i + 1 ] ) : NEW_LINE INDENT P [ i ] [ i + 1 ] = True NEW_LINE dp [ i ] [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT for gap in range ( 2 , n ) : NEW_LINE INDENT for i in range ( n - gap ) : NEW_LINE INDENT j = gap + i NEW_LINE if ( str [ i ] == str [ j ] and P [ i + 1 ] [ j - 1 ] ) : NEW_LINE INDENT P [ i ] [ j ] = True NEW_LINE DEDENT if ( P [ i ] [ j ] == True ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] + 1 - dp [ i + 1 ] [ j - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i ] [ j - 1 ] + dp [ i + 1 ] [ j ] - dp [ i + 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ 0 ] [ n - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " abaab " NEW_LINE n = len ( str ) NEW_LINE print ( CountPS ( str , n ) ) NEW_LINE DEDENT |
Maximum subsequence sum such that no three are consecutive | Returns maximum subsequence sum such that no three elements are consecutive ; Stores result for subarray arr [ 0. . i ] , i . e . , maximum possible sum in subarray arr [ 0. . i ] such that no three elements are consecutive . ; Base cases ( process first three elements ) ; Process rest of the elements We have three cases 1 ) Exclude arr [ i ] , i . e . , sum [ i ] = sum [ i - 1 ] 2 ) Exclude arr [ i - 1 ] , i . e . , sum [ i ] = sum [ i - 2 ] + arr [ i ] 3 ) Exclude arr [ i - 2 ] , i . e . , sum [ i - 3 ] + arr [ i ] + arr [ i - 1 ] ; Driver code | def maxSumWO3Consec ( arr , n ) : NEW_LINE INDENT sum = [ 0 for k in range ( n ) ] NEW_LINE if n >= 1 : NEW_LINE INDENT sum [ 0 ] = arr [ 0 ] NEW_LINE DEDENT if n >= 2 : NEW_LINE INDENT sum [ 1 ] = arr [ 0 ] + arr [ 1 ] NEW_LINE DEDENT if n > 2 : NEW_LINE INDENT sum [ 2 ] = max ( sum [ 1 ] , max ( arr [ 1 ] + arr [ 2 ] , arr [ 0 ] + arr [ 2 ] ) ) NEW_LINE DEDENT for i in range ( 3 , n ) : NEW_LINE INDENT sum [ i ] = max ( max ( sum [ i - 1 ] , sum [ i - 2 ] + arr [ i ] ) , arr [ i ] + arr [ i - 1 ] + sum [ i - 3 ] ) NEW_LINE DEDENT return sum [ n - 1 ] NEW_LINE DEDENT arr = [ 100 , 1000 , 100 , 1000 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print maxSumWO3Consec ( arr , n ) NEW_LINE |
Maximum sum of pairs with specific difference | method to return maximum sum we can get by get by finding less than K difference pair ; Sort input array in ascending order . ; dp [ i ] denotes the maximum disjoint pair sum we can achieve using first i elements ; if no element then dp value will be 0 ; first give previous value to dp [ i ] i . e . no pairing with ( i - 1 ) th element ; if current and previous element can form a pair ; update dp [ i ] by choosing maximum between pairing and not pairing ; last index will have the result ; Driver code to test above methods | def maxSumPairWithDifferenceLessThanK ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE dp = [ 0 ] * N NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE if ( arr [ i ] - arr [ i - 1 ] < K ) : NEW_LINE INDENT if ( i >= 2 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ i - 2 ] + arr [ i ] + arr [ i - 1 ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , arr [ i ] + arr [ i - 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT return dp [ N - 1 ] NEW_LINE DEDENT arr = [ 3 , 5 , 10 , 15 , 17 , 12 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE print ( maxSumPairWithDifferenceLessThanK ( arr , N , K ) ) NEW_LINE |
Recursively break a number in 3 parts to get maximum sum | Function to find the maximum sum ; base conditions ; recursively break the number and return what maximum you can get ; Driver Code | def breakSum ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return max ( ( breakSum ( n // 2 ) + breakSum ( n // 3 ) + breakSum ( n // 4 ) ) , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 12 NEW_LINE print ( breakSum ( n ) ) NEW_LINE DEDENT |
Count All Palindromic Subsequence in a given String | Function return the total palindromic subsequence ; Create a 2D array to store the count of palindromic subsequence ; palindromic subsequence of length 1 ; check subsequence of length L is palindrome or not ; return total palindromic subsequence ; Driver program | def countPS ( str ) : NEW_LINE INDENT N = len ( str ) NEW_LINE cps = [ [ 0 for i in range ( N + 2 ) ] for j in range ( N + 2 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT cps [ i ] [ i ] = 1 NEW_LINE DEDENT for L in range ( 2 , N + 1 ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT k = L + i - 1 NEW_LINE if ( k < N ) : NEW_LINE INDENT if ( str [ i ] == str [ k ] ) : NEW_LINE INDENT cps [ i ] [ k ] = ( cps [ i ] [ k - 1 ] + cps [ i + 1 ] [ k ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT cps [ i ] [ k ] = ( cps [ i ] [ k - 1 ] + cps [ i + 1 ] [ k ] - cps [ i + 1 ] [ k - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return cps [ 0 ] [ N - 1 ] NEW_LINE DEDENT str = " abcb " NEW_LINE print ( " Total β palindromic β subsequence β are β : β " , countPS ( str ) ) NEW_LINE |
Count All Palindromic Subsequence in a given String | Python 3 program to counts Palindromic Subsequence in a given String using recursion ; Function return the total palindromic subsequence ; Driver code | str = " abcb " NEW_LINE def countPS ( i , j ) : NEW_LINE INDENT if ( i > j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT elif ( str [ i ] == str [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = ( countPS ( i + 1 , j ) + countPS ( i , j - 1 ) + 1 ) NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( countPS ( i + 1 , j ) + countPS ( i , j - 1 ) - countPS ( i + 1 , j - 1 ) ) NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT dp = [ [ - 1 for x in range ( 1000 ) ] for y in range ( 1000 ) ] NEW_LINE n = len ( str ) NEW_LINE print ( " Total β palindromic β subsequence β are β : " , countPS ( 0 , n - 1 ) ) NEW_LINE DEDENT |
Subsets and Splits