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 retu...
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 ret...
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 , ...
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 ...
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 : N...
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 NE...
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...
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 ...
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...
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 ...
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 , ...
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 LD...
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 ] = ...
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 -...
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_...
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 c...
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...
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...
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 , ...
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 ...
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 differ...
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 f...
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 tha...
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 ...
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 tw...
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 INDE...
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_L...
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 ...
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_L...
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 ]...
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 -...
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...
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 ...
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 = ...
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 be...
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...
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...
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 : NE...
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 ...
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 [...
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_...
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 ;...
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 =...
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...
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_ca...
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 ]...
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 ...
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 f...
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 DEDEN...
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 th...
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 ...
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 [ ...
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 num...
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 -...
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_LI...
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 fo...
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 DED...
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 DE...
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 stri...
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 ] !...
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 ; Fin...
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 = ( ...
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 ( a...
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...
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 +...
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 cod...
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 ...
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 al...
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 DEDE...
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 ...
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 , ...
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...
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 ) ) ...
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 max...
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 INDEN...
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 Cod...
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 ] ) ...
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...
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 ( maxGame...
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 ...
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 ...
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 =...
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 ; N...
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 alphabe...
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 +...
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 t...
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 retur...
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...
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 ] , ...
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 . ...
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 ...
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 element...
' 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 ...
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 (...
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 t...
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 ( coun...
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 ...
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...
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 d...
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 th...
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 ...
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 st...
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_LIN...
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 cu...
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 (...
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 pro...
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 ...
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 elem...
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 IN...
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 valu...
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 ) ...
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 pr...
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 ( ( coun...
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 . ...
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 ...
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 ; ...
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 b...
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 particul...
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 ...
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 ...
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_LIN...
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...
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_LI...
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 ]...
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 I...
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...
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 fa...
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 ▁ o...
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 - ...
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 ...
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...
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...
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 ...
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 ; ret...
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 ]...
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 [ ] [ ] ; T...
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...
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 ] ...
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 , ret...
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 ( ...
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...
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 , su...
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 cur...
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_...
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 v...
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_LI...
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 ...
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...
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 solutio...
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 ...
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 ) + res...
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 previou...
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 DED...
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 fa...
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 [ ...
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 thre...
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 ]...
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 previo...
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 ...
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_LIN...
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 ] ...