text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Count Numbers with N digits which consists of odd number of 0 's | Function to count Numbers with N digits which consists of odd number of 0 's ; Driver code | def countNumbers ( N ) : NEW_LINE INDENT return ( pow ( 10 , N ) - pow ( 8 , N ) ) // 2 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE DEDENT |
Sum of all Primes in a given range using Sieve of Eratosthenes | Python 3 program to find sum of primes in range L to R ; prefix [ i ] is going to store sum of primes till i ( including i ) . ; Function to build the prefix sum array ; Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be... | from math import sqrt NEW_LINE MAX = 10000 NEW_LINE prefix = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def buildPrefix ( ) : NEW_LINE INDENT prime = [ True for i in range ( MAX + 1 ) ] NEW_LINE for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in ra... |
Sum of the first N terms of the series 5 , 12 , 23 , 38. ... | Function to calculate the sum ; Driver code ; number of terms to be included in sum ; find the Sn | def calculateSum ( n ) : NEW_LINE INDENT return ( 2 * ( n * ( n + 1 ) * ( 2 * n + 1 ) // 6 ) + n * ( n + 1 ) // 2 + 2 * ( n ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( " Sum β = " , calculateSum ( n ) ) NEW_LINE DEDENT |
Program to find number of solutions in Quadratic Equation | function to check for solutions of equations ; If the expression is greater than 0 , then 2 solutions ; If the expression is equal 0 , then 1 solutions ; Else no solutions ; Driver code | def checkSolution ( a , b , c ) : NEW_LINE INDENT if ( ( b * b ) - ( 4 * a * c ) ) > 0 : NEW_LINE INDENT print ( "2 β solutions " ) NEW_LINE DEDENT elif ( ( b * b ) - ( 4 * a * c ) ) == 0 : NEW_LINE INDENT print ( "1 β solution " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No β solutions " ) NEW_LINE DEDENT DEDE... |
Program to convert KiloBytes to Bytes and Bits | Function to calculates the bits ; calculates Bits 1 kilobytes ( s ) = 8192 bits ; Function to calculates the bytes ; calculates Bytes 1 KB = 1024 bytes ; Driver code | def Bits ( kilobytes ) : NEW_LINE INDENT Bits = kilobytes * 8192 NEW_LINE return Bits NEW_LINE DEDENT def Bytes ( kilobytes ) : NEW_LINE INDENT Bytes = kilobytes * 1024 NEW_LINE return Bytes NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT kilobytes = 1 NEW_LINE print ( kilobytes , " Kilobytes β = " , ... |
Program to find the Hidden Number | Driver Code ; Getting the size of array ; Getting the array of size n ; Solution ; Finding sum of the . array elements ; Dividing sum by size n ; Print x , if found | if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE a = [ 1 , 2 , 3 ] NEW_LINE i = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT x = sum // n NEW_LINE if ( x * n == sum ) : NEW_LINE INDENT print ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ... |
Find sum of the series ? 3 + ? 12 + ... ... ... upto N terms | Function to find the sum ; Apply AP formula ; number of terms | import math NEW_LINE def findSum ( n ) : NEW_LINE INDENT return math . sqrt ( 3 ) * ( n * ( n + 1 ) / 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( findSum ( n ) ) NEW_LINE DEDENT |
Find the sum of the series x ( x + y ) + x ^ 2 ( x ^ 2 + y ^ 2 ) + x ^ 3 ( x ^ 3 + y ^ 3 ) + ... + x ^ n ( x ^ n + y ^ n ) | Function to return required sum ; sum of first series ; sum of second series ; Driver Code ; function call to print sum | def sum ( x , y , n ) : NEW_LINE INDENT sum1 = ( ( x ** 2 ) * ( x ** ( 2 * n ) - 1 ) ) // ( x ** 2 - 1 ) NEW_LINE sum2 = ( x * y * ( x ** n * y ** n - 1 ) ) // ( x * y - 1 ) NEW_LINE return ( sum1 + sum2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 2 NEW_LINE y = 2 NEW_LINE n = 2 NEW_LINE pri... |
Find any pair with given GCD and LCM | Function to print the pairs ; Driver Code | def printPair ( g , l ) : NEW_LINE INDENT print ( g , l ) NEW_LINE DEDENT g = 3 ; l = 12 ; NEW_LINE printPair ( g , l ) ; NEW_LINE |
Sum of first n terms of a given series 3 , 6 , 11 , ... . . | Function to calculate the sum ; starting number ; common ratio of GP ; common difference Of AP ; no . of the terms for the sum ; Find the Sn | def calculateSum ( n ) : NEW_LINE INDENT a1 = 1 ; NEW_LINE a2 = 2 ; NEW_LINE r = 2 ; NEW_LINE d = 1 ; NEW_LINE return ( ( n ) * ( 2 * a1 + ( n - 1 ) * d ) / 2 + a2 * ( pow ( r , n ) - 1 ) / ( r - 1 ) ) ; NEW_LINE DEDENT n = 5 ; NEW_LINE print ( " Sum β = " , int ( calculateSum ( n ) ) ) NEW_LINE |
Maximum of sum and product of digits until number is reduced to a single digit | Function to sum the digits until it becomes a single digit ; Function to product the digits until it becomes a single digit ; Loop to do sum while sum is not less than or equal to 9 ; Function to find the maximum among repeated sum and rep... | def repeatedSum ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 9 if ( n % 9 == 0 ) else ( n % 9 ) NEW_LINE DEDENT def repeatedProduct ( n ) : NEW_LINE INDENT prod = 1 NEW_LINE while ( n > 0 or prod > 9 ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT n = prod NEW_LINE prod = ... |
Count numbers with exactly K non | To store digits of N ; visited map ; DP Table ; Push all the digits of N into digits vector ; Function returns the count ; If desired number is formed whose sum is odd ; If it is not present in map , mark it as true and return 1 ; Sum is present in map already ; Desired result not fou... | digits = [ ] NEW_LINE vis = [ False for i in range ( 170 ) ] NEW_LINE dp = [ [ [ [ 0 for l in range ( 170 ) ] for k in range ( 2 ) ] for j in range ( 19 ) ] for i in range ( 19 ) ] NEW_LINE def ConvertIntoDigit ( n ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT dig = n % 10 ; NEW_LINE digits . append ( dig ) ; N... |
Count of subsets of integers from 1 to N having no adjacent elements | Function to count subsets ; Driver Code | def countSubsets ( N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT return N NEW_LINE DEDENT if ( N == 3 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT DP = [ 0 ] * ( N + 1 ) NEW_LINE DP [ 0 ] = 0 NEW_LINE DP [ 1 ] = 1 NEW_LINE DP [ 2 ] = 2 NEW_LINE DP [ 3 ] = 2 NEW_LINE for i in range ( 4 , N + 1 ) : NEW_LINE INDEN... |
Count the number of ordered sets not containing consecutive numbers | DP table ; Function to calculate the count of ordered set for a given size ; Base cases ; If subproblem has been soved before ; Store and return answer to this subproblem ; Function returns the count of all ordered sets ; Prestore the factorial value... | dp = [ [ - 1 for j in range ( 500 ) ] for i in range ( 500 ) ] NEW_LINE def CountSets ( x , pos ) : NEW_LINE INDENT if ( x <= 0 ) : NEW_LINE INDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT... |
Count the Arithmetic sequences in the Array of size at least 3 | Function to find all arithmetic sequences of size atleast 3 ; If array size is less than 3 ; Finding arithmetic subarray length ; To store all arithmetic subarray of length at least 3 ; Check if current element makes arithmetic sequence with previous two ... | def numberOfArithmeticSequences ( L , N ) : NEW_LINE INDENT if ( N <= 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE res = 0 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( ( L [ i ] - L [ i - 1 ] ) == ( L [ i - 1 ] - L [ i - 2 ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LI... |
Count triplet of indices ( i , j , k ) such that XOR of elements between [ i , j ) equals [ j , k ] | Function return the count of triplets having subarray XOR equal ; XOR value till i ; Count and ways array as defined above ; Using the formula stated ; Increase the frequency of x ; Add i + 1 to ways [ x ] for upcoming... | def CountOfTriplets ( a , n ) : NEW_LINE INDENT answer = 0 NEW_LINE x = 0 NEW_LINE count = [ 0 for i in range ( 100005 ) ] NEW_LINE ways = [ 0 for i in range ( 100005 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x ^= a [ i ] NEW_LINE answer += count [ x ] * i - ways [ x ] NEW_LINE count [ x ] += 1 NEW_LINE ways ... |
Count of subarrays of an Array having all unique digits | Function to obtain the mask for any integer ; Function to count the number of ways ; Subarray must not be empty ; If subproblem has been solved ; Excluding this element in the subarray ; If there are no common digits then only this element can be included ; Calc... | def getmask ( val ) : NEW_LINE INDENT mask = 0 NEW_LINE if val == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT while ( val ) : NEW_LINE INDENT d = val % 10 ; NEW_LINE mask |= ( 1 << d ) NEW_LINE val = val // 10 NEW_LINE DEDENT return mask NEW_LINE DEDENT def countWays ( pos , mask , a , n ) : NEW_LINE INDENT if pos == ... |
Count of Fibonacci paths in a Binary tree | Vector to store the fibonacci series ; Binary Tree Node ; Function to create a new tree node ; Function to find the height of the given tree ; Function to make fibonacci series upto n terms ; Preorder Utility function to count exponent path in a given Binary tree ; Base Condi... | fib = [ ] NEW_LINE class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( data ) NEW_LINE return temp NEW_LINE DEDENT def height ( root ) : NEW_LIN... |
Numbers with a Fibonacci difference between Sum of digits at even and odd positions in a given range | Python3 program to count the numbers in the range having the difference between the sum of digits at even and odd positions as a Fibonacci Number ; To store all the Fibonacci numbers ; Function to generate Fibonacci n... | M = 18 NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE dp = [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 90 ) ] for k in range ( 90 ) ] for l in range ( M ) ] NEW_LINE fib = set ( ) NEW_LINE def fibonacci ( ) : NEW_LINE INDENT prev = 0 NEW_LINE curr = 1 NEW_LINE fib . add ( prev ) NEW_LINE fib . add ( curr ) NEW_LINE whi... |
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | Python3 implementation to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Function to find the maximum occurrence of the subsequence such that the indices... | import sys NEW_LINE def maximumOccurrence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE freq = [ 0 ] * ( 26 ) NEW_LINE dp = [ [ 0 for i in range ( 26 ) ] for j in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT c = ( ord ( s [ i ] ) - ord ( ' a ' ) ) NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT dp [... |
Count the numbers with N digits and whose suffix is divisible by K | Python3 implementation to Count the numbers with N digits and whose suffix is divisible by K ; Suffix of length pos with remainder rem and Z representing whether the suffix has a non zero digit until now ; Base case ; If count of digits is less than n... | mod = 1000000007 NEW_LINE dp = [ [ [ - 1 for i in range ( 2 ) ] for i in range ( 105 ) ] for i in range ( 1005 ) ] NEW_LINE powers = [ 0 ] * 1005 NEW_LINE powersModk = [ 0 ] * 1005 NEW_LINE def calculate ( pos , rem , z , k , n ) : NEW_LINE INDENT if ( rem == 0 and z ) : NEW_LINE INDENT if ( pos != n ) : NEW_LINE INDEN... |
Shortest path with exactly k edges in a directed and weighted graph | Set 2 | Python3 implementation of the above approach ; Function to find the smallest path with exactly K edges ; Array to store dp ; Loop to solve DP ; Initialising next state ; Recurrence relation ; Returning final answer ; Driver code ; Input edges... | inf = 100000000 NEW_LINE def smPath ( s , d , ed , n , k ) : NEW_LINE INDENT dis = [ inf ] * ( n + 1 ) NEW_LINE dis [ s ] = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT dis1 = [ inf ] * ( n + 1 ) NEW_LINE for it in ed : NEW_LINE INDENT dis1 [ it [ 1 ] ] = min ( dis1 [ it [ 1 ] ] , dis [ it [ 0 ] ] + it [ 2 ] ) NEW... |
Path with smallest product of edges with weight > 0 | Python3 implementation of the approach . ; Function to return the smallest product of edges ; If the source is equal to the destination ; Array to store distances ; Initialising the array ; Bellman ford algorithm ; Loop to detect cycle ; Returning final answer ; Dri... | import sys NEW_LINE inf = sys . maxsize ; NEW_LINE def bellman ( s , d , ed , n ) : NEW_LINE INDENT if ( s == d ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT dis = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dis [ i ] = inf ; NEW_LINE DEDENT dis [ s ] = 1 ; NEW_LINE for i in range ( n -... |
Find Maximum Length Of A Square Submatrix Having Sum Of Elements At | Python3 implementation of the above approach ; Function to return maximum length of square submatrix having sum of elements at - most K ; Matrix to store prefix sum ; Current maximum length ; Variable for storing maximum length of square ; Calculatin... | import numpy as np NEW_LINE def maxLengthSquare ( row , column , arr , k ) : NEW_LINE INDENT sum = np . zeros ( ( row + 1 , column + 1 ) ) ; NEW_LINE cur_max = 1 ; NEW_LINE max = 0 ; NEW_LINE for i in range ( 1 , row + 1 ) : NEW_LINE INDENT for j in range ( 1 , column + 1 ) : NEW_LINE INDENT sum [ i ] [ j ] = sum [ i -... |
Sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times | Python3 program to find sum of all numbers formed having 4 atmost X times , 5 atmost Y times and 6 atmost Z times ; exactsum [ i ] [ j ] [ k ] stores the sum of all the numbers having exact i 4 ' s , β j β 5' s and k 6 's ; exac... | import numpy as np NEW_LINE N = 101 ; NEW_LINE mod = int ( 1e9 ) + 7 ; NEW_LINE exactsum = np . zeros ( ( N , N , N ) ) ; NEW_LINE exactnum = np . zeros ( ( N , N , N ) ) ; NEW_LINE def getSum ( x , y , z ) : NEW_LINE INDENT ans = 0 ; NEW_LINE exactnum [ 0 ] [ 0 ] [ 0 ] = 1 ; NEW_LINE for i in range ( x + 1 ) : NEW_LIN... |
Maximum value obtained by performing given operations in an Array | Python3 implementation of the above approach ; A function to calculate the maximum value ; basecases ; Loop to iterate and add the max value in the dp array ; Driver Code | import numpy as np NEW_LINE def findMax ( a , n ) : NEW_LINE INDENT dp = np . zeros ( ( n , 2 ) ) ; NEW_LINE dp [ 0 ] [ 0 ] = a [ 0 ] + a [ 1 ] ; NEW_LINE dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 1 ] ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( dp [ i - 1 ] [ 0 ] , dp [ i - 1 ] [ 1 ] ) + a [ i... |
Optimal strategy for a Game with modifications | Python3 implementation of the above approach ; Function to return sum of subarray from l to r ; calculate sum by a loop from l to r ; dp to store the values of sub problems ; if length of the array is less than k return the sum ; if the value is previously calculated ; e... | import numpy as np NEW_LINE def Sum ( arr , l , r ) : NEW_LINE INDENT s = 0 ; NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT s += arr [ i ] ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT dp = np . zeros ( ( 101 , 101 , 101 ) ) ; NEW_LINE def solve ( arr , l , r , k ) : NEW_LINE INDENT if ( r - l + 1 <= k ) : NEW... |
Find the minimum difference path from ( 0 , 0 ) to ( N | Python3 implementation of the approach ; Function to return the minimum difference path from ( 0 , 0 ) to ( N - 1 , M - 1 ) ; Terminating case ; Base case ; If it is already visited ; Recursive calls ; Return the value ; Driver code ; Function call | import numpy as np NEW_LINE import sys NEW_LINE MAXI = 50 NEW_LINE INT_MAX = sys . maxsize NEW_LINE dp = np . ones ( ( MAXI , MAXI , MAXI * MAXI ) ) ; NEW_LINE dp *= - 1 NEW_LINE def minDifference ( x , y , k , b , c ) : NEW_LINE INDENT if ( x >= n or y >= m ) : NEW_LINE INDENT return INT_MAX ; NEW_LINE DEDENT if ( x =... |
Longest subsequence having difference atmost K | Function to find the longest Special Sequence ; Creating a list with all 0 's of size equal to the length of string ; Supporting list with all 0 's of size 26 since the given string consists of only lower case alphabets ; Converting the ascii value to list indices ; D... | def longest_subseq ( n , k , s ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE max_length = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE lower = max ( 0 , curr - k ) NEW_LINE upper = min ( 25 , curr + k ) NEW_LINE for j in range ( lower , upper + 1 ) : NEW_LINE ... |
Maximum possible array sum after performing the given operation | Function to return the maximum possible sum after performing the given operation ; Dp vector to store the answer ; Base value ; Return the maximum sum ; Driver code | def max_sum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 ; dp [ 0 ] [ 1 ] = - 999999 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 0 ] + a [ i ] , dp [ i ] [ 1 ] - a [ i ] ) ; NEW_LINE dp [ i + 1 ] [ 1 ... |
Find the number of ways to reach Kth step in stair case | Python3 implementation of the approach ; Function to return the number of ways to reach the kth step ; Create the dp array ; Broken steps ; Calculate the number of ways for the rest of the positions ; If it is a blocked position ; Number of ways to get to the it... | MOD = 1000000007 ; NEW_LINE def number_of_ways ( arr , n , k ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT dp = [ - 1 ] * ( k + 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ arr [ i ] ] = 0 ; NEW_LINE DEDENT dp [ 0 ] = 1 ; NEW_LINE dp [ 1 ] = 1 if ( dp [ 1 ] == - 1 ) else d... |
Minimum number of coins that can generate all the values in the given range | Python3 program to find minimum number of coins ; Function to find minimum number of coins ; Driver code | import math NEW_LINE def findCount ( n ) : NEW_LINE INDENT return int ( math . log ( n , 2 ) ) + 1 NEW_LINE DEDENT N = 10 NEW_LINE print ( findCount ( N ) ) NEW_LINE |
Calculate the number of set bits for every number from 0 to N | Python 3 implementation of the approach ; Function to find the count of set bits in all the integers from 0 to n ; Driver code | def count ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def findSetBits ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT print ( count ( i ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _... |
Count number of ways to arrange first N numbers | Python3 implementation of the approach ; Function to return the count of required arrangements ; Create a vector ; Store numbers from 1 to n ; To store the count of ways ; Initialize flag to true if first element is 1 else false ; Checking if the current permutation sat... | from itertools import permutations NEW_LINE def countWays ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE i = 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT a . append ( i ) NEW_LINE i += 1 NEW_LINE DEDENT ways = 0 NEW_LINE INDENT flag = 1 if ( per [ 0 ] == 1 ) else 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( ab... |
Count number of ways to arrange first N numbers | Function to return the count of required arrangements ; Create the dp array ; Initialize the base cases as explained above ; ( 12 ) as the only possibility ; Generate answer for greater values ; dp [ n ] contains the desired answer ; Driver code | def countWays ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE dp [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + dp [ i - 3 ] + 1 NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT n = 6 NEW_LINE print ( countWays ... |
Number of shortest paths to reach every cell from bottom | Function to find number of shortest paths ; Compute the grid starting from the bottom - left corner ; Print the grid ; Driver code ; Function call | def NumberOfShortestPaths ( n , m ) : NEW_LINE INDENT a = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT a [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT for j in range ( m ) : NEW_L... |
Maximum sum combination from two arrays | Function to maximum sum combination from two arrays ; To store dp value ; For loop to calculate the value of dp ; Return the required answer ; Driver code ; Function call | def Max_Sum ( arr1 , arr2 , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = arr1 [ i ] NEW_LINE dp [ i ] [ 1 ] = arr2 [ i ] NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ ... |
Partition the array in K segments such that bitwise AND of individual segment sum is maximized | Function to check whether a k segment partition is possible such that bitwise AND is 'mask ; dp [ i ] [ j ] stores whether it is possible to partition first i elements into j segments such that all j segments are 'good ; In... | ' NEW_LINE def checkpossible ( mask , arr , prefix , n , k ) : NEW_LINE ' NEW_LINE INDENT dp = [ [ 0 for i in range ( k + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT for l in range ( i - 1 , - 1 , - 1... |
Cost Based Tower of Hanoi | Python3 implementation of the approach ; Function to initialize the dp table ; Initialize with maximum value ; Function to return the minimum cost ; Base case ; If problem is already solved , return the pre - calculated answer ; Number of the auxiliary disk ; Initialize the minimum cost as I... | import numpy as np NEW_LINE import sys NEW_LINE RODS = 3 NEW_LINE N = 3 NEW_LINE dp = np . zeros ( ( N + 1 , RODS + 1 , RODS + 1 ) ) ; NEW_LINE def initialize ( ) : NEW_LINE INDENT for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( 1 , RODS + 1 ) : NEW_LINE INDENT for k in range ( 1 , RODS + 1 ) : NEW_LINE IND... |
Minimum time required to rot all oranges | Dynamic Programming | Python 3 implementation of the approach ; DP table to memoize the values ; Visited array to keep track of visited nodes in order to avoid infinite loops ; Function to return the minimum of four numbers ; Function to return the minimum distance to any rott... | C = 5 NEW_LINE R = 3 NEW_LINE INT_MAX = 10000000 NEW_LINE table = [ [ 0 for i in range ( C ) ] for j in range ( R ) ] NEW_LINE visited = [ [ 0 for i in range ( C ) ] for j in range ( R ) ] NEW_LINE def min ( p , q , r , s ) : NEW_LINE INDENT if ( p < q ) : NEW_LINE INDENT temp1 = p NEW_LINE DEDENT else : NEW_LINE INDEN... |
Maximum sum of non | Python3 program to implement above approach ; Variable to store states of dp ; Variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Variable to store prefix sum fo... | maxLen = 10 NEW_LINE dp = [ 0 ] * maxLen ; NEW_LINE visit = [ 0 ] * maxLen ; NEW_LINE def maxSum ( arr , i , n , k ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( visit [ i ] ) : NEW_LINE INDENT return dp [ i ] ; NEW_LINE DEDENT visit [ i ] = 1 ; NEW_LINE tot = 0 ; NEW_LINE dp [ i ] ... |
Maximum subset sum such that no two elements in set have same digit in them | Python3 implementation of above approach ; Function to create mask for every number ; Recursion for Filling DP array ; Base Condition ; Recurrence Relation ; Function to find Maximum Subset Sum ; Initialize DP array ; Iterate over all possibl... | dp = [ 0 ] * 1024 ; NEW_LINE def get_binary ( u ) : NEW_LINE INDENT ans = 0 ; NEW_LINE while ( u ) : NEW_LINE INDENT rem = u % 10 ; NEW_LINE ans |= ( 1 << rem ) ; NEW_LINE u //= 10 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def recur ( u , array , n ) : NEW_LINE INDENT if ( u == 0 ) : NEW_LINE INDENT return 0 ; NEW... |
Minimize the sum after choosing elements from the given three arrays | Python3 implementation of the above approach ; Function to return the minimized sum ; If all the indices have been used ; If this value is pre - calculated then return its value from dp array instead of re - computing it ; If A [ i - 1 ] was chosen ... | import numpy as np NEW_LINE SIZE = 3 ; NEW_LINE N = 3 ; NEW_LINE def minSum ( A , B , C , i , n , curr , dp ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ n ] [ curr ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ curr ] ; NEW_LINE DEDENT if ( curr == 0 ) : NEW_LINE INDENT dp [ ... |
Maximise matrix sum by following the given Path | Python3 implementation of the approach ; To store the states of the DP ; Function to return the maximum of the three integers ; Function to return the maximum score ; Base cases ; If the state has already been solved then return it ; Marking the state as solved ; Growin... | import numpy as np NEW_LINE n = 3 NEW_LINE dp = np . zeros ( ( n , n , 2 ) ) ; NEW_LINE v = np . zeros ( ( n , n , 2 ) ) ; NEW_LINE def max_three ( a , b , c ) : NEW_LINE INDENT m = a ; NEW_LINE if ( m < b ) : NEW_LINE INDENT m = b ; NEW_LINE DEDENT if ( m < c ) : NEW_LINE INDENT m = c ; NEW_LINE DEDENT return m ; NEW_... |
Find maximum topics to prepare in order to pass the exam | Python3 implementation of the approach ; Function to return the maximum marks by considering topics which can be completed in the given time duration ; If we are given 0 time then nothing can be done So all values are 0 ; If we are given 0 topics then the time ... | import numpy as np NEW_LINE def MaximumMarks ( marksarr , timearr , h , n , p ) : NEW_LINE INDENT no_of_topics = n + 1 ; NEW_LINE total_time = h + 1 ; NEW_LINE T = np . zeros ( ( no_of_topics , total_time ) ) ; NEW_LINE for i in range ( no_of_topics ) : NEW_LINE INDENT T [ i ] [ 0 ] = 0 ; NEW_LINE DEDENT for j in range... |
Minimize the number of steps required to reach the end of the array | Python3 implementation of the above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the minimum number of steps required to reach the end of the array ; base case ; to check if a state... | maxLen = 10 NEW_LINE maskLen = 130 NEW_LINE dp = [ [ 0 for i in range ( maskLen ) ] for i in range ( maxLen ) ] NEW_LINE v = [ [ False for i in range ( maskLen ) ] for i in range ( maxLen ) ] NEW_LINE def minSteps ( arr , i , mask , n ) : NEW_LINE INDENT if ( i == n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if (... |
Optimal Strategy for a Game | Set 2 | python3 program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total Sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ;... | def oSRec ( arr , i , j , Sum ) : NEW_LINE INDENT if ( j == i + 1 ) : NEW_LINE INDENT return max ( arr [ i ] , arr [ j ] ) NEW_LINE DEDENT return max ( ( Sum - oSRec ( arr , i + 1 , j , Sum - arr [ i ] ) ) , ( Sum - oSRec ( arr , i , j - 1 , Sum - arr [ j ] ) ) ) NEW_LINE DEDENT def optimalStrategyOfGame ( arr , n ) : ... |
Minimum number of sub | Function that returns true if n is a power of 5 ; Function to return the decimal value of binary equivalent ; Function to return the minimum cuts required ; Allocating memory for dp [ ] array ; From length 1 to n ; If previous character is '0' then ignore to avoid number with leading 0 s . ; Ign... | def ispower ( n ) : NEW_LINE INDENT if ( n < 125 ) : NEW_LINE INDENT return ( n == 1 or n == 5 or n == 25 ) NEW_LINE DEDENT if ( n % 125 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return ispower ( n // 125 ) NEW_LINE DEDENT DEDENT def number ( s , i , j ) : NEW_LINE INDENT ans = 0 NEW_LINE... |
Minimum number of cubes whose sum equals to given number N | Function to return the minimum number of cubes whose sum is k ; If k is less than the 2 ^ 3 ; Initialize with the maximum number of cubes required ; Driver code | def MinOfCubed ( k ) : NEW_LINE INDENT if ( k < 8 ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT res = k ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT if ( ( i * i * i ) > k ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT res = min ( res , MinOfCubed ( k - ( i * i * i ) ) + 1 ) ; NEW_LINE DEDENT return res... |
Minimum number of cubes whose sum equals to given number N | Python implementation of the approach ; Function to return the minimum number of cubes whose sum is k ; While current perfect cube is less than current element ; If i is a perfect cube ; i = ( i - 1 ) + 1 ^ 3 ; Next perfect cube ; Re - initialization for next... | import sys NEW_LINE def MinOfCubedDP ( k ) : NEW_LINE INDENT DP = [ 0 ] * ( k + 1 ) ; NEW_LINE j = 1 ; NEW_LINE t = 1 ; NEW_LINE DP [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT DP [ i ] = sys . maxsize ; NEW_LINE while ( j <= i ) : NEW_LINE INDENT if ( j == i ) : NEW_LINE INDENT DP [ i ] = 1 ; NE... |
Maximum Subarray Sum after inverting at most two elements | Function to return the maximum required sub - array sum ; Creating one based indexing ; 2d array to contain solution for each step ; Case 1 : Choosing current or ( current + previous ) whichever is smaller ; Case 2 : ( a ) Altering sign and add to previous cas... | def maxSum ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE arr = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT arr [ i ] = a [ i - 1 ] NEW_LINE DEDENT dp = [ [ 0 for i in range ( 3 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( arr ... |
Maximum sum possible for a sub | Function to return the maximum sum possible ; dp [ i ] represent the maximum sum so far after reaching current position i ; Initialize dp [ 0 ] ; Initialize the dp values till k since any two elements included in the sub - sequence must be atleast k indices apart , and thus first elemen... | def maxSum ( arr , k , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] ; NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return max ( arr [ 0 ] , arr [ 1 ] ) ; NEW_LINE DEDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE for ... |
Minimum cost to form a number X by adding up powers of 2 | Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code | def MinimumCost ( a , n , x ) : NEW_LINE INDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT a [ i ] = min ( a [ i ] , 2 * a [ i - 1 ] ) NEW_LINE DEDENT ind = 0 NEW_LINE sum = 0 NEW_LINE while ( x ) : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT sum += a [ ind ] NEW_LINE DEDENT ind += 1 NEW_LINE x = x >> 1 NEW_LINE... |
Ways to form an array having integers in given range such that total sum is divisible by 2 | Function to return the number of ways to form an array of size n such that sum of all elements is divisible by 2 ; Represents first and last numbers of each type ( modulo 0 and 1 ) ; Count of numbers of each type between range ... | def countWays ( n , l , r ) : NEW_LINE INDENT tL , tR = l , r NEW_LINE L = [ 0 for i in range ( 2 ) ] NEW_LINE R = [ 0 for i in range ( 2 ) ] NEW_LINE L [ l % 2 ] = l NEW_LINE R [ r % 2 ] = r NEW_LINE l += 1 NEW_LINE r -= 1 NEW_LINE if ( l <= tR and r >= tL ) : NEW_LINE INDENT L [ l % 2 ] , R [ r % 2 ] = l , r NEW_LINE... |
Color N boxes using M colors such that K boxes have different color from the box on its left | Python3 Program to Paint N boxes using M colors such that K boxes have color different from color of box on its left ; This function returns the required number of ways where idx is the current index and diff is number of box... | M = 1001 ; NEW_LINE MOD = 998244353 ; NEW_LINE dp = [ [ - 1 ] * M ] * M NEW_LINE def solve ( idx , diff , N , M , K ) : NEW_LINE INDENT if ( idx > N ) : NEW_LINE INDENT if ( diff == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ idx ] [ diff ] != - 1 ) : NEW_LINE INDENT return dp [ id... |
Maximum path sum in an Inverted triangle | SET 2 | Python program 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 left to the number add the maximum of them to it ; Return the m... | N = 3 NEW_LINE def maxPathSum ( tri ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , N - i ) : NEW_LINE INDENT if ( j - 1 >= 0 ) : NEW_LINE INDENT tri [ i ] [ j ] += max ( tri [ i + 1 ] [ j ] , tri [ i + 1 ] [ j - 1 ] ) ; NEW_LINE DEDENT else : NEW_LINE ... |
Count no . of ordered subsets having a particular XOR value | Python 3 implementation of the approach ; Returns count of ordered subsets of arr [ ] with XOR value = K ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] [ k ] is the number of subsets of length k having XOR of the... | from math import log2 NEW_LINE def subsetXOR ( arr , n , K ) : NEW_LINE INDENT max_ele = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > max_ele ) : NEW_LINE INDENT max_ele = arr [ i ] NEW_LINE DEDENT DEDENT m = ( 1 << int ( log2 ( max_ele ) + 1 ) ) - 1 NEW_LINE dp = [ [ [ 0 for i in rang... |
Possible cuts of a number such that maximum parts are divisible by 3 | Python3 program to find the maximum number of numbers divisible by 3 in a large number ; This will contain the count of the splits ; This will keep sum of all successive integers , when they are indivisible by 3 ; This is the condition of finding a ... | def get_max_splits ( num_string ) : NEW_LINE INDENT count = 0 NEW_LINE running_sum = 0 NEW_LINE for i in range ( len ( num_string ) ) : NEW_LINE INDENT current_num = int ( num_string [ i ] ) NEW_LINE running_sum += current_num NEW_LINE if current_num % 3 == 0 or ( running_sum != 0 and running_sum % 3 == 0 ) : NEW_LINE ... |
Count of Numbers in a Range where digit d occurs exactly K times | Python Program to find the count of numbers in a range where digit d occurs exactly K times ; states - position , count , tight , nonz ; d is required digit and K is occurrence ; This function returns the count of required numbers from 0 to num ; Last p... | M = 20 NEW_LINE dp = [ ] NEW_LINE d , K = None , None NEW_LINE def count ( pos , cnt , tight , nonz , num : list ) : NEW_LINE INDENT if pos == len ( num ) : NEW_LINE INDENT if cnt == K : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if dp [ pos ] [ cnt ] [ tight ] [ nonz ] != - 1 : NEW_LINE INDENT r... |
Count of Numbers in Range where first digit is equal to last digit of the number | Python3 program to implement the above approach ; Base Case ; Calculating the last digit ; Calculating the first digit ; Driver Code | def solve ( x ) : NEW_LINE INDENT ans , temp = 0 , x NEW_LINE if ( x < 10 ) : NEW_LINE INDENT return x NEW_LINE DEDENT last = x % 10 NEW_LINE while ( x ) : NEW_LINE INDENT first = x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT if ( first <= last ) : NEW_LINE INDENT ans = 9 + temp // 10 NEW_LINE DEDENT else : NEW_LINE INDE... |
Form N | function returns the minimum cost to form a n - copy string Here , x -> Cost to add / remove a single character ' G ' and y -> cost to append the string to itself ; base case : ro form a 1 - copy string we need tp perform an operation of type 1 ( i , e Add ) ; case1 . Perform a Add operation on ( i - 1 ) copy ... | def findMinimumCost ( n , x , y ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] = x NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i & 1 : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 1 ] + x , dp [ ( i + 1 ) // 2 ] + y + x ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( dp ... |
Minimum steps to reach any of the boundary edges of a matrix | Set 1 | Python program to find Minimum steps to reach any of the boundary edges of a matrix ; Function to find out minimum steps ; boundary edges reached ; already had a route through this point , hence no need to re - visit ; visiting a position ; vertical... | r = 4 NEW_LINE col = 5 NEW_LINE def findMinSteps ( mat , n , m , dp , vis ) : NEW_LINE INDENT if ( n == 0 or m == 0 or n == ( r - 1 ) or m == ( col - 1 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ n ] [ m ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ m ] NEW_LINE DEDENT vis [ n ] [ m ] = True NEW_LINE ans1... |
Count the number of special permutations | function to return the number of ways to chooser objects out of n objects ; function to return the number of degrangemnets of n ; function to return the required number of permutations ; ways to chose i indices from n indices ; Dearrangements of ( n - i ) indices ; Driver Code | def nCr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE if r > n - r : NEW_LINE INDENT r = n - r NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT ans *= ( n - i ) NEW_LINE ans /= ( i + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def countDerangements ( n ) : NEW_LINE INDENT der = [ 0 for i in range ( n + 3 ) ] NE... |
Paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally | Python3 program to find paths with maximum number of ' a ' from ( 1 , 1 ) to ( X , Y ) vertically or horizontally ; Function to answer queries ; Iterate till query ; Decrease to get 0 - based indexing ; Print answer ; Function t... | n = 3 NEW_LINE dp = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE def answerQueries ( queries , q ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT x = queries [ i ] [ 0 ] NEW_LINE x -= 1 NEW_LINE y = queries [ i ] [ 1 ] NEW_LINE y -= 1 NEW_LINE print ( dp [ x ] [ y ] ) NEW_LINE DEDENT DEDENT de... |
Ways to place K bishops on an NΓ β N chessboard so that no two attack | returns the number of squares in diagonal i ; returns the number of ways to fill a n * n chessboard with k bishops so that no two bishops attack each other . ; return 0 if the number of valid places to be filled is less than the number of bishops ;... | def squares ( i ) : NEW_LINE INDENT if ( ( i & 1 ) == 1 ) : NEW_LINE INDENT return int ( i / 4 ) * 2 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return int ( ( i - 1 ) / 4 ) * 2 + 2 NEW_LINE DEDENT DEDENT def bishop_placements ( n , k ) : NEW_LINE INDENT if ( k > 2 * n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp... |
Number of ways to partition a string into two balanced subsequences | For maximum length of input string ; Declaring the DP table ; Declaring the prefix array ; Function to calculate the number of valid assignments ; Return 1 if X is balanced . ; Increment the count if it is an opening bracket ; Decrement the count if ... | MAX = 10 NEW_LINE F = [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE C = [ None ] * MAX NEW_LINE def noOfAssignments ( S , n , i , c_x ) : NEW_LINE INDENT if F [ i ] [ c_x ] != - 1 : NEW_LINE INDENT return F [ i ] [ c_x ] NEW_LINE DEDENT if i == n : NEW_LINE INDENT F [ i ] [ c_x ] = not c_x NEW_LINE... |
Minimum sum falling path in a NxN grid | Python3 Program to minimum required sum ; Function to return minimum path falling sum ; R = Row and C = Column We begin from second last row and keep adding maximum sum . ; best = min ( A [ R + 1 ] [ C - 1 ] , A [ R + 1 ] [ C ] , A [ R + 1 ] [ C + 1 ] ) ; Driver code ; function ... | import sys NEW_LINE n = 3 NEW_LINE def minFallingPathSum ( A ) : NEW_LINE INDENT for R in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for C in range ( n ) : NEW_LINE INDENT best = A [ R + 1 ] [ C ] NEW_LINE if C > 0 : NEW_LINE INDENT best = min ( best , A [ R + 1 ] [ C - 1 ] ) NEW_LINE DEDENT if C + 1 < n : NEW_LINE ... |
Find the maximum sum of Plus shape pattern in a 2 | Python 3 program to find the maximum value of a + shaped pattern in 2 - D array ; Function to return maximum Plus value ; Initializing answer with the minimum value ; Initializing all four arrays ; Initializing left and up array . ; Initializing right and down array .... | N = 100 NEW_LINE n = 3 NEW_LINE m = 4 NEW_LINE def maxPlus ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE left = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE right = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE up = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE down = [ [ 0 fo... |
Total number of different staircase that can made from N boxes | Function to find the total number of different staircase that can made from N boxes ; DP table , there are two states . First describes the number of boxes and second describes the step ; Initialize all the elements of the table to zero ; Base case ; When... | def countStaircases ( N ) : NEW_LINE INDENT memo = [ [ 0 for x in range ( N + 5 ) ] for y in range ( N + 5 ) ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( N + 1 ) : NEW_LINE INDENT memo [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT memo [ 3 ] [ 2 ] = memo [ 4 ] [ 2 ] = 1 NEW_LINE for i in range ( 5 , ... |
Find maximum points which can be obtained by deleting elements from array | function to return maximum cost obtained ; find maximum element of the array . ; create and initialize count of all elements to zero . ; calculate frequency of all elements of array . ; stores cost of deleted elements . ; selecting minimum rang... | def maxCost ( a , n , l , r ) : NEW_LINE INDENT mx = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mx = max ( mx , a [ i ] ) NEW_LINE DEDENT count = [ 0 ] * ( mx + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT res = [ 0 ] * ( mx + 1 ) NEW_LINE res [ 0 ] = 0 NEW_LINE l = ... |
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Return 1 if it is the first row or first column ; Recursively find the no of way to reach the last cell . ; Driver code | def countPaths ( m , n ) : NEW_LINE INDENT if m == 1 or n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( countPaths ( m - 1 , n ) + countPaths ( m , n - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 5 NEW_LINE print ( countPaths ( n , m ) ) NEW_LINE DEDENT |
Count the number of ways to traverse a Matrix | Returns The number of way from top - left to mat [ m - 1 ] [ n - 1 ] ; Driver code | def countPaths ( 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 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i == 1 or j == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] ... |
Minimum number of palindromes required to express N as a sum | Set 1 | Declaring the DP table as global variable ; A utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of input in finding reverse as in case of odd number of digits middle element occur once ; C... | dp = [ [ 0 for i in range ( 1000 ) ] for i in range ( 1000 ) ] NEW_LINE def createPalindrome ( input , isOdd ) : NEW_LINE INDENT n = input NEW_LINE palin = input NEW_LINE if ( isOdd ) : NEW_LINE INDENT n //= 10 NEW_LINE DEDENT while ( n > 0 ) : NEW_LINE INDENT palin = palin * 10 + ( n % 10 ) NEW_LINE n //= 10 NEW_LINE ... |
Number of ways a convex polygon of n + 2 sides can split into triangles by connecting vertices | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to... | def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 ; NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) ; NEW_LINE res /= ( i + 1 ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 2 * n... |
Alternate Fibonacci Numbers | Alternate Fibonacci Series using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Driver Code | def alternateFib ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT f1 = 0 ; NEW_LINE f2 = 1 ; NEW_LINE print ( f1 , end = " β " ) ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT f3 = f2 + f1 ; NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT print ( f3 , end = " β " ) ; NEW_LINE ... |
Number of ways to form an array with distinct adjacent elements | Returns the total ways to form arrays such that every consecutive element is different and each element except the first and last can take values from 1 to M ; define the dp [ ] [ ] array ; if the first element is 1 ; there is only one way to place a 1 a... | def totalWays ( N , M , X ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( N + 1 ) ] NEW_LINE if ( X == 1 ) : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ 1 ] = 0 NEW_LINE DEDENT if ( X == 1 ) : NEW_LINE INDENT dp [ 1 ] [ 0 ] = 0 NEW_LINE dp [ 1 ] [ 1 ] = M ... |
Memoization ( 1D , 2D and 3D ) | Fibonacci Series using Recursion ; Base case ; recursive calls ; Driver Code | def fib ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE print ( fib ( n ) ) NEW_LINE DEDENT |
Memoization ( 1D , 2D and 3D ) | Python program to find the Nth term of Fibonacci series ; Fibonacci Series using memoized Recursion ; base case ; if fib ( n ) has already been computed we do not do further recursive calls and hence reduce the number of repeated work ; store the computed value of fib ( n ) in an array ... | term = [ 0 for i in range ( 1000 ) ] NEW_LINE def fib ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return n NEW_LINE DEDENT if term [ n ] != 0 : NEW_LINE INDENT return term [ n ] NEW_LINE DEDENT else : NEW_LINE INDENT term [ n ] = fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE return term [ n ] NEW_LINE DEDENT DEDENT n ... |
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver Code | 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 ) ) ; NE... |
Smallest number with given sum of digits and sum of square of digits | Python3 program to find the Smallest number with given sum of digits and sum of square of digits ; Top down dp to find minimum number of digits with given sum of dits a and sum of square of digits as b ; Invalid condition ; Number of digits satisfie... | dp = [ [ - 1 for i in range ( 8101 ) ] for i in range ( 901 ) ] NEW_LINE def minimumNumberOfDigits ( a , b ) : NEW_LINE INDENT if ( a > b or a < 0 or b < 0 or a > 900 or b > 8100 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( a == 0 and b == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ a ] [ b ] != - 1... |
Sum of product of consecutive Binomial Coefficients | Python3 Program to find sum of product of consecutive Binomial Coefficient . ; Find the binomial coefficient up to 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 ... | MAX = 100 ; NEW_LINE 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 sumOfproduct ( n )... |
Check if array sum can be made K by three operations on it | Python program to find if Array can have sum of K by applying three types of possible operations on it ; Check if it is possible to achieve a sum with three operation allowed ; if sum id negative . ; If going out of bound . ; If sum is achieved . ; If the cur... | MAX = 100 NEW_LINE def check ( i , add , n , k , a , dp ) : NEW_LINE INDENT if add <= 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if i >= n : NEW_LINE INDENT if add == k : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if dp [ i ] [ add ] != - 1 : NEW_LINE INDENT return dp [ i ] [ add ] N... |
Print Fibonacci sequence using 2 variables | Simple Python3 Program to print Fibonacci sequence ; Driver code | def fib ( n ) : NEW_LINE INDENT a = 0 NEW_LINE b = 1 NEW_LINE if ( n >= 0 ) : NEW_LINE INDENT print ( a , end = ' β ' ) NEW_LINE DEDENT if ( n >= 1 ) : NEW_LINE INDENT print ( b , end = ' β ' ) NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT c = a + b NEW_LINE print ( c , end = ' β ' ) NEW_LINE a = b NEW... |
Maximum sum increasing subsequence from a prefix and a given element after prefix is must | Python3 program to find maximum sum increasing subsequence till i - th index and including k - th index . ; Initializing the first row of the dp [ ] [ ] ; Creating the dp [ ] [ ] matrix . ; To calculate for i = 4 and k = 6. ; Dr... | def pre_compute ( a , n , index , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] > a [ 0 ] : NEW_LINE INDENT dp [ 0 ] [ i ] = a [ i ] + a [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ i ] = a [ i ] NEW_LINE DEDENT DEDEN... |
Moser | Function to generate nth term of Moser - de Bruijn Sequence ; 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 Code | def gen ( n ) : NEW_LINE INDENT S = [ 0 , 1 ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT S . append ( 4 * S [ int ( i / 2 ) ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT S . append ( 4 * S [ int ( i / 2 ) ] + 1 ) ; NEW_LINE DEDENT DEDENT z = S [ n ] ; NEW_LINE return z ; NEW_... |
Longest Common Substring ( Space optimized DP solution ) | Space optimized Python3 implementation of longest common substring . ; Function to find longest common substring . ; Find length of both the strings . ; Variable to store length of longest common substring . ; Matrix to store result of two consecutive rows at a... | import numpy as np NEW_LINE def LCSubStr ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE result = 0 NEW_LINE len_mat = np . zeros ( ( 2 , n ) ) NEW_LINE currRow = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( i == 0 j == 0 ) : NEW_LINE INDENT len... |
Minimal moves to form a string by adding characters or appending string itself | Python program to print the Minimal moves to form a string by appending string and adding characters ; function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check ... | INT_MAX = 100000000 NEW_LINE def minimalSteps ( s , n ) : NEW_LINE INDENT dp = [ INT_MAX for i in range ( n ) ] NEW_LINE s1 = " " NEW_LINE s2 = " " NEW_LINE dp [ 0 ] = 1 NEW_LINE s1 += s [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT s1 += s [ i ] NEW_LINE s2 = s [ i + 1 : i + 1 + i + 1 ] NEW_LINE dp [ i ] =... |
Check if any valid sequence is divisible by M | Function to check if any valid sequence is divisible by M ; DEclare mod array ; Calculate the mod array ; Check if sum is divisible by M ; Check if sum is not divisible by 2 ; Remove the first element from the ModArray since it is not possible to place minus on the first ... | def func ( n , m , A ) : NEW_LINE INDENT ModArray = [ 0 ] * n NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ModArray [ i ] = A [ i ] % m NEW_LINE Sum += ModArray [ i ] NEW_LINE DEDENT Sum = Sum % m NEW_LINE if ( Sum % m == 0 ) : NEW_LINE INDENT print ( " True " ) NEW_LINE return NEW_LINE DEDENT if ( ... |
Golomb sequence | Print the first n term of Golomb Sequence ; base cases ; Finding and pring first n terms of Golomb Sequence . ; Driver Code | def Golomb ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 1 ] = 1 NEW_LINE print ( dp [ 1 ] , end = " β " ) NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = 1 + dp [ i - dp [ dp [ i - 1 ] ] ] NEW_LINE print ( dp [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT n = 9 NEW_LINE Golomb ( n ) NEW... |
Balanced expressions such that given positions have opening brackets | Python 3 code to find number of ways of arranging bracket with proper expressions ; function to calculate the number of proper bracket sequence ; hash array to mark the positions of opening brackets ; dp 2d array ; mark positions in hash array ; fir... | N = 1000 NEW_LINE def arrangeBraces ( n , pos , k ) : NEW_LINE INDENT h = [ False for i in range ( N ) ] NEW_LINE dp = [ [ 0 for i in range ( N ) ] for i in range ( N ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT h [ pos [ i ] ] = 1 NEW_LINE DEDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , 2 * n + 1 ) : NE... |
Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s β ' 0 ' add 1 else -1 ; u... | def findLength ( string , n ) : NEW_LINE INDENT current_sum = 0 NEW_LINE max_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT current_sum += ( 1 if string [ i ] == '0' else - 1 ) NEW_LINE if current_sum < 0 : NEW_LINE INDENT current_sum = 0 NEW_LINE DEDENT max_sum = max ( current_sum , max_sum ) NEW_LINE DEDENT ... |
Number of decimal numbers of length k , that are strict monotone | Python3 program to count numbers of k digits that are strictly monotone . ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits ( 1 , 2 , 3 , . .9 ) ; Unit length numbers ; Building dp [ ] in bottom up ; Driver cod... | DP_s = 9 NEW_LINE def getNumStrictMonotone ( ln ) : NEW_LINE INDENT DP = [ [ 0 ] * DP_s for _ in range ( ln ) ] NEW_LINE for i in range ( DP_s ) : NEW_LINE INDENT DP [ 0 ] [ i ] = i + 1 NEW_LINE DEDENT for i in range ( 1 , ln ) : NEW_LINE INDENT for j in range ( 1 , DP_s ) : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i - 1 ... |
Count ways to divide circle using N non | python code to count ways to divide circle using N non - intersecting chords . ; n = no of points required ; dp array containing the sum ; returning the required number ; driver code | def chordCnt ( A ) : NEW_LINE INDENT n = 2 * A NEW_LINE dpArray = [ 0 ] * ( n + 1 ) NEW_LINE dpArray [ 0 ] = 1 NEW_LINE dpArray [ 2 ] = 1 NEW_LINE for i in range ( 4 , n + 1 , 2 ) : NEW_LINE INDENT for j in range ( 0 , i - 1 , 2 ) : NEW_LINE INDENT dpArray [ i ] += ( dpArray [ j ] * dpArray [ i - 2 - j ] ) NEW_LINE DED... |
Check for possible path in 2D matrix | Python3 program to find if there is path from top left to right bottom ; to find the path from top left to bottom right ; set arr [ 0 ] [ 0 ] = 1 ; Mark reachable ( from top left ) nodes in first row and first column . ; Mark reachable nodes in remaining matrix . ; return yes if r... | row = 5 NEW_LINE col = 5 NEW_LINE def isPath ( arr ) : NEW_LINE INDENT arr [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , row ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] != - 1 ) : NEW_LINE INDENT arr [ i ] [ 0 ] = arr [ i - 1 ] [ 0 ] NEW_LINE DEDENT DEDENT for j in range ( 1 , col ) : NEW_LINE INDENT if ( arr [ 0 ] [ j ] ... |
NewmanΓ’ β¬β ShanksΓ’ β¬β Williams prime | return nth NewmanaShanksaWilliams prime ; Base case ; Recursive step ; Driven Program | def nswp ( n ) : NEW_LINE INDENT if n == 0 or n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 2 * nswp ( n - 1 ) + nswp ( n - 2 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( nswp ( n ) ) NEW_LINE |
Newman Shanks Williams prime | return nth Newman Shanks Williams prime ; Base case ; Finding nth Newman Shanks Williams prime ; Driver Code | def nswp ( n ) : NEW_LINE INDENT dp = [ 1 for x in range ( n + 1 ) ] ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = ( 2 * dp [ i - 1 ] + dp [ i - 2 ] ) ; NEW_LINE DEDENT return dp [ n ] ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( nswp ( n ) ) ; NEW_LINE |
Number of ways to insert a character to increase the LCS by one | Python Program to Number of ways to insert a character to increase LCS by one ; Return the Number of ways to insert a character to increase the Longest Common Subsequence by one ; Insert all positions of all characters in string B ; Longest Common Subseq... | MAX = 256 NEW_LINE def numberofways ( A , B , N , M ) : NEW_LINE INDENT pos = [ [ ] for _ in range ( MAX ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT pos [ ord ( B [ i ] ) ] . append ( i + 1 ) NEW_LINE DEDENT dpl = [ [ 0 ] * ( M + 2 ) for _ in range ( N + 2 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE IN... |
Minimum cost to make two strings identical by deleting the digits | Function to returns cost of removing the identical characters in LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains cost of removing identical characters in ... | def lcs ( X , Y , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for i 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... |
Given a large number , check if a subsequence of digits is divisible by 8 | Function to calculate any permutation divisible by 8. If such permutation exists , the function will return that permutation else it will return - 1 ; Generating all possible permutations and checking if any such permutation is divisible by 8 ;... | def isSubSeqDivisible ( st ) : NEW_LINE INDENT l = len ( st ) NEW_LINE arr = [ int ( ch ) for ch in st ] NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT for j in range ( i , l ) : NEW_LINE INDENT for k in range ( j , l ) : NEW_LINE INDENT if ( arr [ i ] % 8 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ... |
Given a large number , check if a subsequence of digits is divisible by 8 | Python3 program to check if given string has a subsequence divisible by 8 ; map key will be tens place digit of number that is divisible by 8 and value will be units place digit ; For filling the map let start with initial value 8 ; key is digi... | Str = "129365" NEW_LINE mp = { } NEW_LINE no = 8 NEW_LINE while ( no < 100 ) : NEW_LINE INDENT no = no + 8 NEW_LINE mp [ ( no // 10 ) % 10 ] = no % 10 NEW_LINE DEDENT visited = [ False ] * 10 NEW_LINE for i in range ( len ( Str ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( Str [ i ] == '8' ) : NEW_LINE INDENT print ( " Ye... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.