text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Count lexicographically increasing K | Function to count K - length strings from first N alphabets ; To keep track of column sum in dp ; Auxiliary 2d dp array ; Initialize dp [ 0 ] [ i ] = 1 and update the column_sum ; Iterate for K times ; Iterate for N times ; dp [ i ] [ j ] : Stores the number of ways to form i - le... | def waysToArrangeKLengthStrings ( N , K ) : NEW_LINE INDENT column_sum = [ 0 for i in range ( N + 1 ) ] NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( K + 1 ) ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE column_sum [ i ] = 1 NEW_LINE DE... |
Count N | Function to count N - length strings consisting of vowels only sorted lexicographically ; Stores count of strings consisting of vowels sorted lexicographically of all possible lengths ; Initialize DP [ 1 ] [ 1 ] ; Traverse the matrix row - wise ; Base Case ; Return the result ; Driver Code ; Function Call | def findNumberOfStrings ( n ) : NEW_LINE INDENT DP = [ [ 0 for i in range ( 6 ) ] for i in range ( n + 1 ) ] NEW_LINE DP [ 1 ] [ 1 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , 6 ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i ] [ j - 1 ] + 1 NEW_LINE DED... |
Largest subtree sum for each vertex of given N | Python3 program for the above approach ; Function to perform the DFS Traversal on the given Tree ; To check if v is leaf vertex ; Initialize answer for vertex v ; Traverse adjacency list of v ; Update maximum subtree sum ; If v is leaf ; Function to calculate maximum sub... | V = 3 NEW_LINE M = 2 NEW_LINE def dfs ( v , p ) : NEW_LINE INDENT isLeaf = 1 NEW_LINE ans [ v ] = - 10 ** 9 NEW_LINE for u in adj [ v ] : NEW_LINE INDENT if ( u == p ) : NEW_LINE INDENT continue NEW_LINE DEDENT isLeaf = 0 NEW_LINE dfs ( u , v ) NEW_LINE ans [ v ] = max ( ans [ u ] + vals [ v ] , max ( ans [ u ] , vals ... |
Queries to count frequencies of a given character in a given range of indices | Function to prcount of char y present in the range [ l , r ] ; Length of the string ; Stores the precomputed results ; Iterate the given string ; Increment dp [ i ] [ y - ' a ' ] by 1 ; Pre - compute ; Number of queries ; Traverse each quer... | def noOfChars ( s , queries ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ [ 0 for i in range ( 26 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i + 1 ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT dp [ i + 1 ] [ j ] += dp [ i ] [ j ]... |
Minimum cost required to rearrange a given array to make it equal to another given array | Function to find lower_bound ; Function to find length of the longest common subsequence ; Find position where element is to be inserted ; Return the length of LCS ; Function to find the minimum cost required to convert the seque... | def LowerBound ( a , k , x ) : NEW_LINE INDENT l = - 1 NEW_LINE r = k NEW_LINE while ( l + 1 < r ) : NEW_LINE INDENT m = ( l + r ) >> 1 NEW_LINE if ( a [ m ] >= x ) : NEW_LINE INDENT r = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m NEW_LINE DEDENT DEDENT return r NEW_LINE DEDENT def findLCS ( nums , N ) : NEW_LINE IN... |
Maximize count of array elements required to obtain given sum | Function that count the maximum number of elements to obtain sum V ; Stores the maximum number of elements required to obtain V ; Base Case ; Initialize all table values as Infinite ; Find the max arr required for all values from 1 to V ; Go through all ar... | def maxCount ( arr , m , V ) : NEW_LINE INDENT table = [ 0 for i in range ( V + 1 ) ] NEW_LINE table [ 0 ] = 0 NEW_LINE for i in range ( 1 , V + 1 , 1 ) : NEW_LINE INDENT table [ i ] = - 1 NEW_LINE for i in range ( 1 , V + 1 , 1 ) : NEW_LINE INDENT for j in range ( 0 , m , 1 ) : NEW_LINE INDENT if ( arr [ j ] <= i ) : ... |
Maximize path sum from top | Function to get the maximum path sum from top - left cell to all other cells of the given matrix ; Store the maximum path sum Initialize the value of dp [ i ] [ j ] to 0. ; Base case ; Compute the value of dp [ i ] [ j ] using the recurrence relation ; Print maximum path sum from the top - ... | def pathSum ( mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] ) NEW_LINE DEDENT for j in range ( 1 , M ) : NEW_LINE INDENT dp [ 0... |
Length of Longest Palindrome Substring | Function to find the length of the longest palindromic subString ; Length of String str ; Stores the dp states ; All subStrings of length 1 are palindromes ; Check for sub - String of length 2 ; If adjacent character are same ; Update table [ i ] [ i + 1 ] ; Check for lengths gr... | def longestPalSubstr ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE table = [ [ False for i in range ( n ) ] for j in range ( n ) ] ; NEW_LINE maxLength = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT table [ i ] [ i ] = True ; NEW_LINE DEDENT start = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ... |
Maximize sum of an Array by flipping sign of all elements of a single subarray | Python3 program for the above approach ; Function to find the maximum sum after flipping a subarray ; Stores the total sum of array ; Initialize the maximum sum ; Iterate over all possible subarrays ; Initialize sum of the subarray before ... | import sys NEW_LINE def maxSumFlip ( a , n ) : NEW_LINE INDENT total_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_sum += a [ i ] NEW_LINE DEDENT max_sum = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE flip_sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDEN... |
Minimum repeated addition of even divisors of N required to convert N to M | INF is the maximum value which indicates Impossible state ; Stores the dp states ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Check dp [ cur ] is already calculated or not ; Initially it ... | INF = 10000007 ; NEW_LINE max_size = 100007 ; NEW_LINE dp = [ 0 for i in range ( max_size ) ] ; NEW_LINE def min_op ( cur , M ) : NEW_LINE INDENT if ( cur > M ) : NEW_LINE INDENT return INF ; NEW_LINE DEDENT if ( cur == M ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ cur ] != - 1 ) : NEW_LINE INDENT return d... |
Maximize Sum possible from an Array by the given moves | Function to find the maximum sum possible by given moves from the array ; Checking for boundary ; If previously computed subproblem occurs ; If element can be moved left ; Calculate maximum possible sum by moving left from current index ; If element can be moved ... | def maxValue ( a , n , pos , moves , left , dp ) : NEW_LINE INDENT if ( moves == 0 or ( pos > n - 1 or pos < 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ pos ] [ left ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ left ] NEW_LINE DEDENT value = 0 NEW_LINE if ( left > 0 and pos >= 1 ) : NEW_LINE INDENT v... |
Maximize the Sum of a Subsequence from an Array based on given conditions | Function to select the array elements to maximize the sum of the selected elements ; If the entire array is solved ; Memoized subproblem ; Calculate sum considering the current element in the subsequence ; Calculate sum without considering the ... | def maximumSum ( a , count , index , n , dp ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ count ] NEW_LINE DEDENT take_element = ( a [ index ] * count + maximumSum ( a , count + 1 , index + 1 , n , dp ) ) NEW... |
Minimum number of Nodes to be removed such that no subtree has more than K nodes | Variables used to store data globally ; Adjacency list representation of tree ; Function to perform DFS Traversal ; Mark the node as true ; Traverse adjacency list of child node ; If already visited then omit the node ; Add number of nod... | N = 20 NEW_LINE visited = [ False for i in range ( N ) ] NEW_LINE K = 0 NEW_LINE removals = 0 NEW_LINE removed_nodes = [ ] NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE def dfs ( s ) : NEW_LINE INDENT global removals NEW_LINE visited [ s ] = True NEW_LINE nodes = 1 NEW_LINE for child in adj [ s ] : NEW_LINE INDE... |
Queries to find sum of distance of a given node to every leaf node in a Weighted Tree | MAX size ; Graph with { destination , weight } ; For storing the sum for ith node ; Leaves in subtree of ith . ; dfs to find sum of distance of leaves in the subtree of a node ; flag is the node is leaf or not ; Skipping if parent ;... | N = 10 ** 5 + 5 NEW_LINE v = [ [ ] for i in range ( N ) ] NEW_LINE dp = [ 0 ] * N NEW_LINE leaves = [ 0 ] * ( N ) NEW_LINE n = 0 NEW_LINE def dfs ( a , par ) : NEW_LINE INDENT leaf = 1 NEW_LINE for i in v [ a ] : NEW_LINE INDENT if ( i [ 0 ] == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT leaf = 0 NEW_LINE dfs ( i ... |
Minimum changes required to make each path in a matrix palindrome | Function for counting changes ; Maximum distance possible is ( n - 1 + m - 1 ) ; Stores the maximum element ; Update the maximum ; Stores frequencies of values for respective distances ; Initialize frequencies of cells as 0 ; Count frequencies of cell ... | def countChanges ( matrix , n , m ) : NEW_LINE INDENT dist = n + m - 1 NEW_LINE Max_element = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT Max_element = max ( Max_element , matrix [ i ] [ j ] ) NEW_LINE DEDENT DEDENT freq = [ [ 0 for i in range ( Max_element + 1 ) ] for j in ... |
Count of numbers upto N having absolute difference of at most K between any two adjacent digits | Table to store solution of each subproblem ; Function to calculate all possible numbers ; Check if position reaches end that is equal to length of N ; Check if the result is already computed simply return it ; Maximum limi... | dp = [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for i in range ( 10 ) ] for j in range ( 1002 ) ] NEW_LINE def possibleNumber ( pos , previous , tight , start , N , K ) : NEW_LINE INDENT if ( pos == len ( N ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ pos ] [ previous ] [ tight ] [ start ] !=... |
Minimum cost of reducing Array by merging any adjacent elements repetitively | Python3 program for the above approach ; Function to find the total minimum cost of merging two consecutive numbers ; Find the size of numbers [ ] ; If array is empty , return 0 ; To store the prefix Sum of numbers array numbers [ ] ; Traver... | import sys NEW_LINE def mergeTwoNumbers ( numbers ) : NEW_LINE INDENT n = len ( numbers ) NEW_LINE if ( len ( numbers ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT prefixSum = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prefixSum [ i ] = ( prefixSum [ i - 1 ] + numbers [ i - 1 ] ) NE... |
Maximum sum possible for every node by including it in a segment of N | Stores the maximum sum possible for every node by including them in a segment with their successors ; Stores the maximum sum possible for every node by including them in a segment with their ancestors ; Store the maximum sum for every node by inclu... | dp1 = [ 0 for i in range ( 100005 ) ] NEW_LINE dp2 = [ 0 for i in range ( 100005 ) ] NEW_LINE def dfs1 ( u , par , g , weight ) : NEW_LINE INDENT dp1 [ u ] = weight [ u ] NEW_LINE for c in g [ u ] : NEW_LINE INDENT if ( c != par ) : NEW_LINE INDENT dfs1 ( c , u , g , weight ) NEW_LINE dp1 [ u ] += max ( 0 , dp1 ) NEW_L... |
Count array elements that can be maximized by adding any permutation of first N natural numbers | Function to get the count of values that can have the maximum value ; Sort array in decreasing order ; Stores the answer ; mark stores the maximum value till each index i ; Check if arr [ i ] can be maximum ; Update the ma... | def countMaximum ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) ; NEW_LINE count = 0 ; NEW_LINE mark = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( a [ i ] + n >= mark ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT mark = max ( mark , a [ i ] + i + 1 ) ; NEW_LINE DEDENT print ( count ) ; NEW_... |
Count of pairs in an Array with same number of set bits | Function to return the count of Pairs ; Get the maximum element ; Array to store count of bits of all elements upto maxm ; Store the set bits for powers of 2 ; Compute the set bits for the remaining elements ; Store the frequency of respective counts of set bits... | def countPairs ( arr , N ) : NEW_LINE INDENT maxm = max ( arr ) NEW_LINE i = 0 NEW_LINE k = 0 NEW_LINE bitscount = [ 0 for i in range ( maxm + 1 ) ] NEW_LINE i = 1 NEW_LINE while i <= maxm : NEW_LINE INDENT bitscount [ i ] = 1 NEW_LINE i *= 2 NEW_LINE DEDENT for i in range ( 1 , maxm + 1 ) : NEW_LINE INDENT if ( bitsco... |
Largest subarray sum of all connected components in undirected graph | Python3 implementation to find largest subarray sum among all connected components ; Function to traverse the undirected graph using the Depth first traversal ; Marking the visited vertex as true ; Store the connected chain ; Recursive call to the D... | import sys NEW_LINE def depthFirst ( v , graph , visited , storeChain ) : NEW_LINE INDENT visited [ v ] = True ; NEW_LINE storeChain . append ( v ) ; NEW_LINE for i in graph [ v ] : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT depthFirst ( i , graph , visited , storeChain ) ; NEW_LINE DEDENT DEDENT D... |
Count of Binary strings of length N having atmost M consecutive 1 s or 0 s alternatively exactly K times | List to contain the final result ; Function to get the number of desirable binary strings ; If we reach end of string and groups are exhausted , return 1 ; If length is exhausted but groups are still to be made , ... | rows , cols = ( 1000 , 1000 ) NEW_LINE dp = [ [ 0 for i in range ( cols ) ] for j in range ( rows ) ] NEW_LINE def solve ( n , k , m ) : NEW_LINE INDENT if n == 0 and k == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n == 0 and k != 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n != 0 and k == 0 : NEW_LINE INDENT ... |
Maximum neighbor element in a matrix within distance K | Function to print the matrix ; Loop to iterate over the matrix ; Function to find the maximum neighbor within the distance of less than equal to K ; Loop to find the maximum element within the distance of less than K ; Driver Code | def printMatrix ( A ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT for j in range ( len ( A [ 0 ] ) ) : NEW_LINE INDENT print ( A [ i ] [ j ] , end = ' β ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def getMaxNeighbour ( A , K ) : NEW_LINE INDENT ans = A ; NEW_LINE for q in range ( 1 , K + 1... |
Number of distinct ways to represent a number as sum of K unique primes | Prime list ; Sieve array of prime ; DP array ; Sieve of Eratosthenes . ; Push all the primes into prime vector ; Function to get the number of distinct ways to get sum as K different primes ; If index went out of prime array size or the sum becam... | prime = [ ] NEW_LINE isprime = [ True ] * 1000 NEW_LINE dp = [ [ [ '0' for col in range ( 200 ) ] for col in range ( 20 ) ] for row in range ( 1000 ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 2 , 1000 ) : NEW_LINE INDENT if ( isprime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , 1000 , i ) : NEW_... |
Count minimum factor jumps required to reach the end of an Array | Vector to store factors of each integer ; Initialize the dp array ; Precompute all the factors of every integer ; Function to count the minimum factor jump ; 0 jumps required to reach the first cell ; Iterate over all cells ; calculating for each jump ;... | factors = [ [ ] for i in range ( 100005 ) ] ; NEW_LINE dp = [ 1000000000 for i in range ( 100005 ) ] ; NEW_LINE def precompute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT for j in range ( i , 100001 , i ) : NEW_LINE INDENT factors [ j ] . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def solve ... |
Find the length of the Largest subset such that all elements are Pairwise Coprime | Dynamic programming table ; Function to obtain the mask for any integer ; List of prime numbers till 50 ; Iterate through all prime numbers to obtain the mask ; Set this prime 's bit ON in the mask ; Return the mask value ; Function to ... | dp = [ [ - 1 ] * ( ( 1 << 10 ) + 5 ) ] * 5000 NEW_LINE def getmask ( val ) : NEW_LINE INDENT mask = 0 NEW_LINE prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 ] NEW_LINE for i in range ( 1 , 15 ) : NEW_LINE INDENT if val % prime [ i ] == 0 : NEW_LINE INDENT mask = mask | ( 1 << i ) NEW_LI... |
Maximum sum such that exactly half of the elements are selected and no two adjacent | Function return the maximum sum possible under given condition ; Base case ; When i is odd ; When i is even ; Maximum of if we pick last element or not ; Driver code | def MaximumSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( 2 ) ] for y in range ( n + 1 ) ] NEW_LINE dp [ 2 ] [ 1 ] = a [ 1 ] NEW_LINE dp [ 2 ] [ 0 ] = a [ 0 ] NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT temp = max ( [ dp [ i - 3 ] [ 1 ] , dp [ i - 3 ] [ 0 ] , dp [... |
Optimal Strategy for the Divisor game using Dynamic Programming | Python3 program for implementation of Optimal Strategy for the Divisor Game using Dynamic Programming ; Recursive function to find the winner ; check if N = 1 or N = 3 then player B wins ; check if N = 2 then player A wins ; check if current state alread... | from math import sqrt NEW_LINE def divisorGame ( N , A , dp ) : NEW_LINE INDENT if ( N == 1 or N == 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( dp [ N ] [ A ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ A ] NEW_LINE DEDENT if ( A == 1 ) : NEW_LINE... |
Find the count of mountains in a given Matrix | Python3 program find the count of mountains in a given Matrix ; Function to count number of mountains in a given matrix of size n ; form another matrix with one extra layer of border elements . Border elements will contain INT_MIN value . ; For border elements , set value... | MAX = 100 NEW_LINE def countMountains ( a , n ) : NEW_LINE INDENT A = [ [ 0 for i in range ( n + 2 ) ] for i in range ( n + 2 ) ] NEW_LINE count = 0 NEW_LINE for i in range ( n + 2 ) : NEW_LINE INDENT for j in range ( n + 2 ) : NEW_LINE INDENT if ( ( i == 0 ) or ( j == 0 ) or ( i == n + 1 ) or ( j == n + 1 ) ) : NEW_LI... |
Minimum length of the reduced Array formed using given operations | Python3 implementation to find the minimum length of the array ; Function to find the length of minimized array ; Creating the required dp tables Initialising the dp table by - 1 ; base case ; Check if the two subarray can be combined ; Initialising dp... | import numpy as np NEW_LINE def minimalLength ( a , n ) : NEW_LINE INDENT dp = np . ones ( ( n + 1 , n + 1 ) ) * - 1 ; NEW_LINE dp1 = [ 0 ] * n ; NEW_LINE for size in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - size + 1 ) : NEW_LINE INDENT j = i + size - 1 ; NEW_LINE if ( i == j ) : NEW_LINE INDENT dp [ ... |
Maximum score possible after performing given operations on an Array | Memoizing by the use of a table ; Function to calculate maximum score ; Bse case ; If the same state has already been computed ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , a... | dp = [ [ [ - 1 for x in range ( 100 ) ] for y in range ( 100 ) ] for z in range ( 100 ) ] NEW_LINE def MaximumScoreDP ( l , r , prefix_sum , num ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ l ] [ r ] [ num ] != - 1 ) : NEW_LINE INDENT return dp [ l ] [ r ] [ num ] NEW_LINE DEDEN... |
Count number of binary strings without consecutive 1 Γ’ β¬β’ s : Set 2 | Table to store the solution of every sub problem ; Here , pos : keeps track of current position . f1 : is the flag to check if current number is less than N or not . pr : represents the previous digit ; Base case ; Check if this subproblem has alread... | memo = [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for k in range ( 32 ) ] NEW_LINE def dp ( pos , fl , pr , bin ) : NEW_LINE INDENT if ( pos == len ( bin ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( memo [ pos ] [ fl ] [ pr ] != - 1 ) : NEW_LINE INDENT return memo [ pos ] [ fl ] [ pr ] ; NEW_LINE ... |
Count ways to reach end from start stone with at most K jumps at each step | Function which returns total no . of ways to reach nth step from sth steps ; Initialize dp array ; Initialize ( s - 1 ) th index to 1 ; Iterate a loop from s to n ; starting range for counting ranges ; Calculate Maximum moves to Reach ith step... | def TotalWays ( n , s , k ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE dp [ s - 1 ] = 1 NEW_LINE for i in range ( s , n ) : NEW_LINE INDENT idx = max ( s - 1 , i - k ) NEW_LINE for j in range ( idx , i ) : NEW_LINE INDENT dp [ i ] += dp [ j ] NEW_LINE DEDENT DEDENT return dp [ n - 1 ] NEW_LINE DEDENT if __name__ == " _ ... |
Maximum subsequence sum with adjacent elements having atleast K difference in index | Function to find the maximum sum subsequence such that two adjacent element have atleast difference of K in their indices ; DP Array to store the maximum sum obtained till now ; Either select the first element or Nothing ; Either Sele... | def max_sum ( arr , n , k ) : NEW_LINE INDENT dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = max ( 0 , arr [ 0 ] ) ; NEW_LINE i = 1 ; NEW_LINE while ( i < k ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i - 1 ] , arr [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT i = k ; NEW_LINE while ( i < n ) : NEW_LINE INDENT dp [ i ] = max ( dp [ ... |
Number of binary strings such that there is no substring of length Γ’ β°Β₯ 3 | Python3 implementation of the approach ; Function to return the count of all possible binary strings ; Base cases ; dp [ i ] [ j ] is the number of possible strings such that '1' just appeared consecutively j times upto ith index ; Taking previ... | MOD = 1000000007 NEW_LINE def countStr ( N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 3 ) ] for i in range ( N + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = 1 NEW_LINE dp [ 1 ] [ 1 ] = 1 NEW_LINE dp [ 1 ] [ 2 ] = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1... |
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Python program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences ... | def maxLengthOf1s ( arr , n ) : NEW_LINE INDENT prefix = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i - 2 ] == 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] = 0 NEW_LINE DEDENT DEDENT suffix = [ 0 for i in ran... |
Count number of ways to get Odd Sum | Count the ways to sum up with odd by choosing one element form each pair ; Initialize two array with 0 ; if element is even ; store count of even number in i 'th pair ; if the element is odd ; store count of odd number in i 'th pair ; Initial state of dp array ; dp [ i ] [ 0 ] = to... | def CountOfOddSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( n ) ] NEW_LINE cnt = [ [ 0 for i in range ( 2 ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT if ( a [ i ] [ j ] % 2 == 0 ) : NEW_LINE INDENT cnt [ i ] [ 0 ]... |
Longest Consecuetive Subsequence when only one insert operation is allowed | Function to return the length of longest consecuetive subsequence after inserting an element ; Variable to find maximum value of the array ; Calculating maximum value of the array ; Declaring the DP table ; Variable to store the maximum length... | def LongestConsSeq ( arr , N ) : NEW_LINE INDENT maxval = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxval = max ( maxval , arr [ i ] ) NEW_LINE DEDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( maxval + 1 ) ] NEW_LINE ans = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ arr [ i ] ] [ 0 ] = 1 + ... |
Stepping Numbers | This function checks if an integer n is a Stepping Number ; Initalize prevDigit with - 1 ; Iterate through all digits of n and compare difference between value of previous and current digits ; Get Current digit ; Single digit is consider as a Stepping Number ; Check if absolute difference between pre... | def isStepNum ( n ) : NEW_LINE INDENT prevDigit = - 1 NEW_LINE while ( n ) : NEW_LINE INDENT curDigit = n % 10 NEW_LINE if ( prevDigit == - 1 ) : NEW_LINE INDENT prevDigit = curDigit NEW_LINE DEDENT else : NEW_LINE INDENT if ( abs ( prevDigit - curDigit ) != 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT pre... |
Count numbers in given range such that sum of even digits is greater than sum of odd digits | Python code to count number in the range having the sum of even digits greater than the sum of odd digits ; Base Case ; check if condition satisfied or not ; If this result is already computed simply return it ; Maximum limit ... | def memo ( index , evenSum , oddSum , tight ) : NEW_LINE INDENT if index == len ( v ) : NEW_LINE INDENT if evenSum > oddSum : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if dp [ index ] [ evenSum ] [ oddSum ] [ tight ] != - 1 : NEW_LINE INDENT return dp [ index ] [ ev... |
Maximum sub | Function to return the maximum sum of the sub - sequence such that two consecutive elements have a difference of at least 3 in their indices in the given array ; If there is a single element in the array ; Either select it or don 't ; If there are two elements ; Either select the first element or don 't ;... | def max_sum ( a , n ) : NEW_LINE INDENT dp = [ 0 ] * n ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT dp [ 0 ] = max ( 0 , a [ 0 ] ) ; NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT dp [ 0 ] = max ( 0 , a [ 0 ] ) ; NEW_LINE dp [ 1 ] = max ( a [ 1 ] , dp [ 0 ] ) ; NEW_LINE DEDENT elif ( n >= 3 ) : NEW_LINE INDENT dp [ 0 ... |
Minimum count of elements that sums to a given number | Python3 implementation of the above approach ; we will only store min counts of sum upto 100 ; memo [ 0 ] = 0 as 0 is made from 0 elements ; fill memo array with min counts of elements that will constitute sum upto 100 ; min_count will store min count of elements ... | def minCount ( K ) : NEW_LINE INDENT memo = [ 10 ** 9 for i in range ( 100 ) ] NEW_LINE memo [ 0 ] = 0 NEW_LINE for i in range ( 1 , 100 ) : NEW_LINE INDENT memo [ i ] = min ( memo [ i - 1 ] + 1 , memo [ i ] ) NEW_LINE DEDENT for i in range ( 10 , 100 ) : NEW_LINE INDENT memo [ i ] = min ( memo [ i - 10 ] + 1 , memo [ ... |
Number of sub | Python3 implementation of the approach ; Function to return the number of subsequences which have at least one consecutive pair with difference less than or equal to 1 ; Not required sub - sequences which turn required on adding i ; Required sub - sequence till now will be required sequence plus sub - s... | import numpy as np ; NEW_LINE N = 10000 ; NEW_LINE def count_required_sequence ( n , arr ) : NEW_LINE INDENT total_required_subsequence = 0 ; NEW_LINE total_n_required_subsequence = 0 ; NEW_LINE dp = np . zeros ( ( N , 2 ) ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT turn_required = 0 ; NEW_LINE for j in range (... |
Number of ways to choose elements from the array such that their average is K | Python implementation of above approach ; Initialize dp array by - 1 ; Base cases Index can 't be less than 0 ; No element is picked hence average cannot be calculated ; If remainder is non zero , we cannot divide the sum by count i . e . t... | import numpy as np NEW_LINE MAX_INDEX = 51 NEW_LINE MAX_SUM = 2505 NEW_LINE dp = np . ones ( ( MAX_INDEX , MAX_SUM , MAX_INDEX ) ) * - 1 ; NEW_LINE def waysutil ( index , sum , count , arr , K ) : NEW_LINE INDENT if ( index < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( index == 0 ) : NEW_LINE INDENT if ( coun... |
Subset with sum closest to zero | Python3 Code for above implementation ; Variable to store states of dp ; Function to return the number closer to integer s ; To find the sum closest to zero Since sum can be negative , we will add MAX to it to make it positive ; Base cases ; Checks if a state is already solved ; Recurr... | import numpy as np NEW_LINE arrSize = 51 NEW_LINE maxSum = 201 NEW_LINE MAX = 100 NEW_LINE inf = 999999 NEW_LINE dp = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE visit = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE def RetClose ( a , b , s ) : NEW_LINE INDENT if ( abs ( a - s ) < abs ( b - s ) ) : NEW_LINE INDENT ... |
Paths from entry to exit in matrix and maximum path sum | Recursive function to return the total paths from grid [ i ] [ j ] to grid [ n - 1 ] [ n - 1 ] ; Out of bounds ; If the current state hasn 't been solved before ; Only valid move is right ; Only valid move is down ; Right and down , both are valid moves ; Recur... | def totalPaths ( i , j , n , grid , dp ) : NEW_LINE INDENT if ( i < 0 or j < 0 or i >= n or j >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] == - 1 ) : NEW_LINE INDENT if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = totalPaths ( i , j + 1 , n , grid , dp ) NEW_LINE DEDENT elif ( g... |
Queries for bitwise OR in the index range [ L , R ] of the given array | Python3 implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix count ; Function to answer query ; To store the answer ; Loop for each bit ; To store the n... | import numpy as np NEW_LINE MAX = 100000 NEW_LINE bitscount = 32 NEW_LINE prefix_count = np . zeros ( ( bitscount , MAX ) ) ; NEW_LINE def findPrefixCount ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , bitscount ) : NEW_LINE INDENT prefix_count [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; NEW_LINE for j in range ( 1 ... |
Distinct palindromic sub | Python3 implementation of the approach ; Function to return the count of distinct palindromic sub - strings of the given string s ; To store the positions of palindromic sub - strings ; Map to store the sub - strings ; Sub - strings of length 1 are palindromes ; Store continuous palindromic s... | import numpy as np ; NEW_LINE def palindromeSubStrs ( s ) : NEW_LINE INDENT dp = np . zeros ( ( len ( s ) , len ( s ) ) ) ; NEW_LINE m = { } ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT dp [ i ] [ i ] = 1 ; NEW_LINE m [ s [ i : i + 1 ] ] = 1 ; NEW_LINE DEDENT for i in range ( len ( s ) - 1 ) : NEW_LINE IND... |
Maximum sum path in a matrix from top to bottom and back | Python 3 implementation of the approach ; Input matrix ; DP matrix ; Function to return the sum of the cells arr [ i1 ] [ j1 ] and arr [ i2 ] [ j2 ] ; Recursive function to return the required maximum cost path ; Column number of second path ; Base Case ; If al... | import sys NEW_LINE n = 4 NEW_LINE m = 4 NEW_LINE arr = [ [ 1 , 0 , 3 , - 1 ] , [ 3 , 5 , 1 , - 2 ] , [ - 2 , 0 , 1 , 1 ] , [ 2 , 1 , - 1 , 1 ] ] NEW_LINE cache = [ [ [ - 1 for i in range ( 5 ) ] for j in range ( 5 ) ] for k in range ( 5 ) ] NEW_LINE def sum ( i1 , j1 , i2 , j2 ) : NEW_LINE INDENT if ( i1 == i2 and j1 ... |
Bellman Ford Algorithm ( Simple Implementation ) | Python3 program for Bellman - Ford 's single source shortest path algorithm. ; The main function that finds shortest distances from src to all other vertices using Bellman - Ford algorithm . The function also detects negative weight cycle The row graph [ i ] represents... | from sys import maxsize NEW_LINE def BellmanFord ( graph , V , E , src ) : NEW_LINE INDENT dis = [ maxsize ] * V NEW_LINE dis [ src ] = 0 NEW_LINE for i in range ( V - 1 ) : NEW_LINE INDENT for j in range ( E ) : NEW_LINE INDENT if dis [ graph [ j ] [ 0 ] ] + graph [ j ] [ 2 ] < dis [ graph [ j ] [ 1 ] ] : NEW_LINE IND... |
Find number of edges that can be broken in a tree such that Bitwise OR of resulting two trees are equal | Python3 implementation of the approach ; Function to perform simple DFS ; Finding the number of times each bit is set in all the values of a subtree rooted at v ; Checking for each bit whether the numbers with that... | m , x = [ 0 ] * 1000 , [ 0 ] * 22 NEW_LINE a = [ [ 0 for i in range ( 22 ) ] for j in range ( 1000 ) ] NEW_LINE ans = 0 NEW_LINE def dfs ( u , p ) : NEW_LINE INDENT global ans NEW_LINE for i in range ( 0 , len ( g [ u ] ) ) : NEW_LINE INDENT v = g [ u ] [ i ] NEW_LINE if v != p : NEW_LINE INDENT dfs ( v , u ) NEW_LINE ... |
Find the maximum number of composite summands of a number | Python 3 implementation of the above approach ; Function to generate the dp array ; combination of three integers ; take the maximum number of summands ; Function to find the maximum number of summands ; If n is a smaller number , less than 16 , return dp [ n ... | global maxn NEW_LINE maxn = 16 NEW_LINE def precompute ( ) : NEW_LINE INDENT dp = [ - 1 for i in range ( maxn ) ] NEW_LINE dp [ 0 ] = 0 NEW_LINE v = [ 4 , 6 , 9 ] NEW_LINE for i in range ( 1 , maxn , 1 ) : NEW_LINE INDENT for k in range ( 3 ) : NEW_LINE INDENT j = v [ k ] NEW_LINE if ( i >= j and dp [ i - j ] != - 1 ) ... |
Minimum cost to reach end of array array when a maximum jump of K index is allowed | Python3 implementation of the approach ; for calculating the number of elements ; Allocating Memo table and initializing with INT_MAX ; Base case ; For every element relax every reachable element ie relax next k elements ; reaching nex... | import sys NEW_LINE def minCostJumpsDP ( A , k ) : NEW_LINE INDENT size = len ( A ) NEW_LINE x = [ sys . maxsize ] * ( size ) NEW_LINE x [ 0 ] = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT j = i + 1 NEW_LINE while j < i + k + 1 and j < size : NEW_LINE INDENT x [ j ] = min ( x [ j ] , x [ i ] + abs ( A [ i ] - ... |
DP on Trees | Set | Function to find the diameter of the tree using Dynamic Programming ; Store the first maximum and secondmax ; Traverse for all children of node ; Call DFS function again ; Find first max ; Secondmaximum ; elif dp1 [ i ] > secondmax : Find secondmaximum ; Base case for every node ; if firstmax != - 1... | def dfs ( node , parent , dp1 , dp2 , adj ) : NEW_LINE INDENT firstmax , secondmax = - 1 , - 1 NEW_LINE for i in adj [ node ] : NEW_LINE INDENT if i == parent : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( i , node , dp1 , dp2 , adj ) NEW_LINE if firstmax == - 1 : NEW_LINE INDENT firstmax = dp1 [ i ] NEW_LINE DEDENT ... |
Find sub | Python implementation of the approach ; Function to return the sum of the sub - matrix ; Function that returns true if it is possible to find the sub - matrix with required sum ; 2 - D array to store the sum of all the sub - matrices ; Filling of dp [ ] [ ] array ; Checking for each possible sub - matrix of ... | N = 4 NEW_LINE def getSum ( r1 , r2 , c1 , c2 , dp ) : NEW_LINE INDENT return dp [ r2 ] [ c2 ] - dp [ r2 ] [ c1 ] - dp [ r1 ] [ c2 ] + dp [ r1 ] [ c1 ] NEW_LINE DEDENT def sumFound ( K , S , grid ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LIN... |
Stepping Numbers | Prints all stepping numbers reachable from num and in range [ n , m ] ; Queue will contain all the stepping Numbers ; Get the front element and pop from the queue ; If the Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m , no need to explore the neigh... | def bfs ( n , m , num ) : NEW_LINE INDENT q = [ ] NEW_LINE q . append ( num ) NEW_LINE while len ( q ) > 0 : NEW_LINE INDENT stepNum = q [ 0 ] NEW_LINE q . pop ( 0 ) ; NEW_LINE if ( stepNum <= m and stepNum >= n ) : NEW_LINE INDENT print ( stepNum , end = " β " ) NEW_LINE DEDENT if ( num == 0 or stepNum > m ) : NEW_LIN... |
Minimum distance to the end of a grid from source | Python3 implementation of the approach ; Global variables for grid , minDistance and visited array ; Queue for BFS ; Function to find whether the move is valid or not ; Function to return the minimum distance from source to the end of the grid ; If source is one of th... | from collections import deque as queue NEW_LINE row = 5 NEW_LINE col = 5 NEW_LINE minDistance = [ [ 0 for i in range ( col + 1 ) ] for i in range ( row + 1 ) ] NEW_LINE visited = [ [ 0 for i in range ( col + 1 ) ] for i in range ( row + 1 ) ] NEW_LINE que = queue ( ) NEW_LINE def isValid ( grid , i , j ) : NEW_LINE IND... |
Minimum number of operations required to sum to binary string S | Function to return the minimum operations required to sum to a number reprented by the binary string S ; Reverse the string to consider it from LSB to MSB ; initialise the dp table ; If S [ 0 ] = '0' , there is no need to perform any operation ; If S [ 0... | def findMinOperations ( S ) : NEW_LINE INDENT S = S [ : : - 1 ] NEW_LINE n = len ( S ) NEW_LINE dp = [ [ 0 ] * 2 ] * ( n + 1 ) NEW_LINE if ( S [ 0 ] == '0' ) : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT dp [ 0 ] [ 1 ] = 1 NEW_LINE for i in range ( 1 , n ... |
K | Function that finds the Nth element of K - Fibonacci series ; If N is less than K then the element is '1 ; first k elements are 1 ; ( K + 1 ) th element is K ; find the elements of the K - Fibonacci series ; subtract the element at index i - k - 1 and add the element at index i - i from the sum ( sum contains the s... | def solve ( N , K ) : NEW_LINE INDENT Array = [ 0 ] * ( N + 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( N <= K ) : NEW_LINE INDENT print ( "1" ) NEW_LINE return NEW_LINE DEDENT i = 0 NEW_LINE sm = K NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE INDENT Array [ i ] = 1 NEW_LINE DEDENT Array [ i + 1 ] = sm NEW_LINE for ... |
Minimum sum possible of any bracket sequence of length N | Python 3 program to find the Minimum sum possible of any bracket sequence of length N using the given values for brackets ; DP array ; Recursive function to check for correct bracket expression ; Not a proper bracket expression ; If reaches at end ; If proper b... | MAX_VAL = 10000000 NEW_LINE dp = [ [ - 1 for i in range ( 100 ) ] for i in range ( 100 ) ] NEW_LINE def find ( index , openbrk , n , adj ) : NEW_LINE INDENT if ( openbrk < 0 ) : NEW_LINE INDENT return MAX_VAL NEW_LINE DEDENT if ( index == n ) : NEW_LINE INDENT if ( openbrk == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DED... |
Understanding The Coin Change Problem With Dynamic Programming | We have input values of N and an array Coins that holds all of the coins . We use data type of because long we want to be able to test large values without integer overflow ; Create the ways array to 1 plus the amount to stop overflow ; Set the first way ... | def getNumberOfWays ( N , Coins ) : NEW_LINE INDENT ways = [ 0 ] * ( N + 1 ) ; NEW_LINE ways [ 0 ] = 1 ; NEW_LINE for i in range ( len ( Coins ) ) : NEW_LINE INDENT for j in range ( len ( ways ) ) : NEW_LINE INDENT if ( Coins [ i ] <= j ) : NEW_LINE INDENT ways [ j ] += ways [ ( int ) ( j - Coins [ i ] ) ] ; NEW_LINE D... |
Minimum cost to buy N kilograms of sweet for M persons | Function to find the minimum cost of sweets ; Defining the sweet array ; DP array to store the values ; Since index starts from 1 we reassign the array into sweet ; Assigning base cases for dp array ; At 0 it is free ; Package not available for desirable amount o... | def find ( m , n , adj ) : NEW_LINE INDENT sweet = [ 0 ] * ( n + 1 ) NEW_LINE dp = [ [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE sweet [ 0 ] = 0 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT sweet [ i ] = adj [ i - 1 ] NEW_LINE DEDENT for i in range ( m + 1 ... |
Maximum length of segments of 0 ' s β and β 1' s | Recursive Function to find total length of the array where 1 is greater than zero ; If reaches till end ; If dp is saved ; Finding for each length ; If the character scanned is 1 ; If one is greater than zero , add total length scanned till now ; Continue with next len... | def find ( start , adj , n , dp ) : NEW_LINE INDENT if ( start == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ start ] != - 1 ) : NEW_LINE INDENT return dp [ start ] NEW_LINE DEDENT dp [ start ] = 0 NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE for k in range ( start , n , 1 ) : NEW_LINE INDENT if ( adj [ k ]... |
Length of longest common subsequence containing vowels | function to check whether ' ch ' is a vowel or not ; function to find the length of longest common subsequence which contains all vowel characters ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS ... | def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def lcs ( X , Y , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE i , j = 0 , ... |
Minimum number of single digit primes required whose sum is equal to N | function to check if i - th index is valid or not ; function to find the minimum number of single digit prime numbers required which when summed up equals to a given number N . ; Not possible ; Driver Code | def check ( i , val ) : NEW_LINE INDENT if i - val < 0 : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def MinimumPrimes ( n ) : NEW_LINE INDENT dp = [ 10 ** 9 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = dp [ 2 ] = dp [ 3 ] = dp [ 5 ] = dp [ 7 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDE... |
Find all distinct subset ( or subsequence ) sums of an array | Set | Function to print all th distinct sum ; Declare a boolean array of size equal to total sum of the array ; Fill the first row beforehand ; dp [ j ] will be true only if sum j can be formed by any possible addition of numbers in given array upto index i... | def subsetSum ( arr , n , maxSum ) : NEW_LINE INDENT dp = [ False for i in range ( maxSum + 1 ) ] NEW_LINE dp [ arr [ 0 ] ] = True NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT j = maxSum NEW_LINE while ( j >= 1 ) : NEW_LINE INDENT if ( arr [ i ] <= j ) : NEW_LINE INDENT if ( arr [ i ] == j or dp [ j ] or dp ... |
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 ) | recursive approach ; base condition ; reaches the point ; i + j ; check if it is a power of 2 , then only move diagonally ; if not a power of 2 then move side - wise ; Function... | size = 1000 NEW_LINE def maxCost ( a : list , m : int , n : int ) -> int : 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 else : NEW_LINE INDENT num = m + n NEW_LINE if ( num & ( num - 1 ) ) == 0 : NEW_LINE INDEN... |
Longest Common Subsequence | DP using Memoization | Python3 program to memoize recursive implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value ... | maximum = 1000 NEW_LINE def lcs ( X , Y , m , n , dp ) : NEW_LINE INDENT if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ m - 1 ] [ n - 1 ] != - 1 ) : NEW_LINE INDENT return dp [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT dp [ m - 1 ] [ n - 1 ] = 1 ... |
Stepping Numbers | Prints all stepping numbers reachable from num and in range [ n , m ] ; If Stepping Number is in the range [ n , m ] then display ; If Stepping Number is 0 or greater than m , then return ; Get the last digit of the currently visited Stepping Number ; There can be 2 cases either digit to be appended ... | def dfs ( n , m , stepNum ) : NEW_LINE INDENT if ( stepNum <= m and stepNum >= n ) : NEW_LINE INDENT print ( stepNum , end = " β " ) NEW_LINE DEDENT if ( stepNum == 0 or stepNum > m ) : NEW_LINE INDENT return NEW_LINE DEDENT lastDigit = stepNum % 10 NEW_LINE stepNumA = stepNum * 10 + ( lastDigit - 1 ) NEW_LINE stepNumB... |
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future functi... | def lcs ( X , Y , m , n ) : NEW_LINE INDENT global arr NEW_LINE if ( m == 0 or n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ m - 1 ] [ n - 1 ] != - 1 ) : NEW_LINE INDENT return arr [ m - 1 ] [ n - 1 ] NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT arr [ m - 1 ] [ n - 1 ] = 1 + lcs ... |
Number of Unique BST with a given key | Dynamic Programming | Function to find number of unique BST ; DP to store the number of unique BST with key i ; Base case ; fill the dp table in top - down approach . ; n - i in right * i - 1 in left ; Driver Code | def numberOfBST ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] , dp [ 1 ] = 1 , 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i ] + ( dp [ i - j ] * dp [ j - 1 ] ) NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT if __nam... |
Minimum splits in a binary string such that every substring is a power of 4 or 6. | Python 3 program for Minimum splits in a string such that substring is a power of 4 or 6. ; Function to find if given number is power of another number or not . ; Divide given number repeatedly by base value . ; return False not a power... | import sys NEW_LINE def isPowerOf ( val , base ) : NEW_LINE INDENT while ( val > 1 ) : NEW_LINE INDENT if ( val % base != 0 ) : NEW_LINE val //= base NEW_LINE DEDENT return True NEW_LINE DEDENT def numberOfPartitions ( binaryNo ) : NEW_LINE INDENT n = len ( binaryNo ) NEW_LINE dp = [ 0 ] * n NEW_LINE if ( ( ord ( binar... |
Sum of product of r and rth Binomial Coefficient ( r * nCr ) | Return summation of r * nCr ; Driver Code | def summation ( n ) : NEW_LINE INDENT return n << ( n - 1 ) ; NEW_LINE DEDENT n = 2 ; NEW_LINE print ( summation ( n ) ) ; NEW_LINE |
Integers from the range that are composed of a single distinct digit | Function to return the count of digits of a number ; Function to return a number that contains only digit ' d ' repeated exactly count times ; Function to return the count of integers that are composed of a single distinct digit only ; Count of digi... | def countDigits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE n //= 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def getDistinct ( d , count ) : NEW_LINE INDENT num = 0 NEW_LINE count = pow ( 10 , count - 1 ) NEW_LINE while ( count > 0 ) : NEW_LINE INDENT num += ( c... |
Maximum average sum partition of an array | Python3 program for maximum average sum partition ; bottom up approach to calculate score ; storing averages from starting to each i ; ; Driver Code ; atmost partitioning size | MAX = 1000 NEW_LINE memo = [ [ 0.0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def score ( n , A , k ) : NEW_LINE INDENT if ( memo [ n ] [ k ] > 0 ) : NEW_LINE INDENT return memo [ n ] [ k ] NEW_LINE DEDENT sum = 0 NEW_LINE i = n - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE memo... |
Maximum and Minimum Values of an Algebraic Expression | Python3 program to find the maximum and minimum values of an Algebraic expression of given form ; Finding sum of array elements ; shifting the integers by 50 so that they become positive ; dp [ i ] [ j ] represents true if sum j can be reachable by choosing i numb... | def minMaxValues ( arr , n , m ) : NEW_LINE INDENT sum = 0 NEW_LINE INF = 1000000000 NEW_LINE MAX = 50 NEW_LINE for i in range ( 0 , ( n + m ) ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE arr [ i ] += 50 NEW_LINE DEDENT dp = [ [ 0 for x in range ( MAX * MAX + 1 ) ] for y in range ( MAX + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] ... |
Check if any valid sequence is divisible by M | Python3 program to check if any valid sequence is divisible by M ; Base case ; check if sum is divisible by M ; check if the current state is already computed ; 1. Try placing '+ ; 2. Try placing '- ; calculate value of res for recursive case ; store the value for res for... | def isPossible ( n , index , Sum , M , arr , dp ) : NEW_LINE INDENT global MAX NEW_LINE if index == n : NEW_LINE INDENT if ( Sum % M ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if dp [ index ] [ Sum ] != - 1 : NEW_LINE INDENT return dp [ index ] [ Sum ] NEW_LINE DEDENT DEDENT ' NEW... |
Dynamic Programming on Trees | Set 2 | Python3 code to find the maximum path length considering any node as root ; function to pre - calculate the array inn [ ] which stores the maximum height when travelled via branches ; initially every node has 0 height ; traverse in the subtree of u ; if child is same as parent ; d... | inn = [ 0 ] * 100 NEW_LINE out = [ 0 ] * 100 NEW_LINE def dfs1 ( v , u , parent ) : NEW_LINE INDENT global inn , out NEW_LINE inn [ u ] = 0 NEW_LINE for child in v [ u ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs1 ( v , child , u ) NEW_LINE inn [ u ] = max ( inn [ u ] , 1 + ... |
Golomb sequence | Return the nth element of Golomb sequence ; base case ; Recursive Step ; Print the first n term of Golomb Sequence ; Finding first n terms of Golomb Sequence . ; Driver Code | def findGolomb ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 1 + findGolomb ( n - findGolomb ( findGolomb ( n - 1 ) ) ) NEW_LINE DEDENT def printGolomb ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( findGolomb ( i ) , end = " β " ) NEW_LINE DEDEN... |
Printing Items in 0 / 1 Knapsack | Prints the items which are put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; stores the result of Knapsack ; either the result comes from the top ( K [ i - 1 ] [ w ] ) or from ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] ) as in Knapsack table . If it... | def printknapSack ( W , wt , val , n ) : NEW_LINE INDENT K = [ [ 0 for w in range ( W + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for w in range ( W + 1 ) : NEW_LINE INDENT if i == 0 or w == 0 : NEW_LINE INDENT K [ i ] [ w ] = 0 NEW_LINE DEDENT elif wt [ i - 1 ] <= w : NEW_LIN... |
s | To sort the array and return the answer ; sort the array ; Fill all stated with - 1 when only one element ; As dp [ 0 ] = 0 ( base case ) so min no of elements to be removed are n - 1 elements ; Iterate from 1 to n - 1 ; Driver code | def removals ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = - 1 NEW_LINE DEDENT ans = n - 1 NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = i NEW_LINE j = dp [ i - 1 ] NEW_LINE whil... |
Maximum number of segments of lengths a , b and c | function to find the maximum number of segments ; stores the maximum number of segments each index can have ; ; 0 th index will have 0 segments base case ; traverse for all possible segments till n ; conditions if ( i + a <= n ) : avoid buffer overflow ; if ( i + b <... | def maximumSegments ( n , a , b , c ) : NEW_LINE INDENT dp = [ - 1 ] * ( n + 10 ) NEW_LINE DEDENT / * initialize with - 1 * / NEW_LINE INDENT dp [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( dp [ i ] != - 1 ) : NEW_LINE INDENT dp [ i + a ] = max ( dp [ i ] + 1 , dp [ i + a ] ) NEW_LINE dp [ i + b ]... |
Maximize the sum of selected numbers from an array to make it empty | function to maximize the sum of selected numbers ; maximum in the sequence ; stores the occurrences of the numbers ; marks the occurrence of every number in the sequence ; ans to store the result ; Using the above mentioned approach ; if occurence is... | def maximizeSum ( a , n ) : NEW_LINE INDENT maximum = max ( a ) NEW_LINE ans = dict . fromkeys ( range ( 0 , n + 1 ) , 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ a [ i ] ] += 1 NEW_LINE DEDENT result = 0 NEW_LINE i = maximum NEW_LINE while i > 0 : NEW_LINE INDENT if ans [ i ] > 0 : NEW_LINE INDENT result... |
Print n terms of Newman | Function to find the n - th element ; Declare array to store sequence ; driver code | def sequence ( n ) : NEW_LINE INDENT f = [ 0 , 1 , 1 ] NEW_LINE print ( f [ 1 ] , end = " β " ) , NEW_LINE print ( f [ 2 ] , end = " β " ) , NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT f . append ( f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ) NEW_LINE print ( f [ i ] , end = " β " ) , NEW_LINE DEDENT DEDENT ... |
LCS formed by consecutive segments of at least length K | Returns the length of the longest common subsequence with a minimum of length of K consecutive segments ; length of strings ; declare the lcs and cnt array ; iterate from i = 1 to n and j = 1 to j = m ; stores the maximum of lcs [ i - 1 ] [ j ] and lcs [ i ] [ j... | def longestSubsequenceCommonSegment ( k , s1 , s2 ) : NEW_LINE INDENT n = len ( s1 ) NEW_LINE m = len ( s2 ) NEW_LINE lcs = [ [ 0 for x in range ( m + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE cnt = [ [ 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... |
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 ; directions ; queue ; insert the top right corner . ; until queue is empty ; mark as visited ; destination is reached . ; check all four directions ; using the ... | row = 5 NEW_LINE col = 5 NEW_LINE def isPath ( arr ) : NEW_LINE INDENT Dir = [ [ 0 , 1 ] , [ 0 , - 1 ] , [ 1 , 0 ] , [ - 1 , 0 ] ] NEW_LINE q = [ ] NEW_LINE q . append ( ( 0 , 0 ) ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE arr [ p [ 0 ] ] [ p [ 1 ] ] = - 1 NEW_LINE ... |
Next Smaller Element | prints element and NSE pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements ar... | def printNSE ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE mp = { } NEW_LINE s . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( arr [ i ] ) NEW_LINE continue NEW_LINE DEDENT while ( len ( s ) != 0 and s [ - 1 ] > arr [ i ] ) : NEW_LINE INDE... |
Entringer Number | Return Entringer Number E ( n , k ) ; Base cases ; Finding dp [ i ] [ j ] ; Driven Program | def zigzag ( n , k ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT dp ... |
Lobb Number | Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return the Lm , n Lobb Number . ; Driven Program | def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for j in range ( k + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE IND... |
Count of arrays having consecutive element with different values | Return the number of lists with given constraints . ; Initialising dp [ 0 ] and dp [ 1 ] ; Computing f ( i ) for each 2 <= i <= n . ; Driven code | def countarray ( n , k , x ) : NEW_LINE INDENT dp = list ( ) NEW_LINE dp . append ( 0 ) NEW_LINE dp . append ( 1 ) NEW_LINE i = 2 NEW_LINE while i < n : NEW_LINE INDENT dp . append ( ( k - 2 ) * dp [ i - 1 ] + ( k - 1 ) * dp [ i - 2 ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT return ( ( k - 1 ) * dp [ n - 2 ] if x == 1 else... |
Number of palindromic subsequences of length k where k <= 3 | Python3 program to count number of subsequences of given length . ; Precompute the prefix and suffix array . ; Precompute the prefix 2D array ; Precompute the Suffix 2D array . ; Find the number of palindromic subsequence of length k ; If k is 1. ; If k is 2... | MAX = 100 NEW_LINE MAX_CHAR = 26 NEW_LINE def precompute ( s , n , l , r ) : NEW_LINE INDENT l [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( MAX_CHAR ) : NEW_LINE INDENT l [ j ] [ i ] += l [ j ] [ i - 1 ] NEW_LINE DEDENT l [ ord ( s [ i ] ) - ord ( ' ... |
Minimum cost to make Longest Common Subsequence of length k | Python3 program to calculate Minimum cost to make Longest Common Subsequence of length k ; Return Minimum cost to make LCS of length k ; If k is 0 ; If length become less than 0 , return big number ; If state already calculated ; Finding cost ; ; Driver Cod... | N = 30 NEW_LINE def solve ( X , Y , l , r , k , dp ) : NEW_LINE INDENT if k == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if l < 0 or r < 0 : NEW_LINE INDENT return 1000000000 NEW_LINE DEDENT if dp [ l ] [ r ] [ k ] != - 1 : NEW_LINE INDENT return dp [ l ] [ r ] [ k ] NEW_LINE DEDENT cost = ( ( ord ( X [ l ] ) - ord ... |
Maximum sum path in a matrix from top to bottom | Python3 implementation to find the maximum sum path in a matrix ; function to find the maximum sum path in a matric ; if there is a single elementif there is a single element only only ; dp [ ] [ ] matrix to store the results of each iteration ; base case , copying elem... | SIZE = 10 NEW_LINE INT_MIN = - 10000000 NEW_LINE def maxSum ( mat , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return mat [ 0 ] [ 0 ] NEW_LINE DEDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE maxSum = INT_MIN NEW_LINE for j in range ( n ) : NEW_LINE INDENT dp [ n - 1 ] [ j ] = mat [ n - 1... |
Longest Repeated Subsequence | This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; This part of code is same as below post it fills dp [ ] [ ] https : www . geeksforgeeks . org / longest - repeating - subsequence / OR the code mentioned above ; This ... | def longestRepeatedSubSeq ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ j - 1 ] and i != j ) : NEW_LINE INDENT dp [ i ]... |
Sub | Tree traversal to compute minimum difference ; Initial min difference is the color of node ; Traversing its children ; Not traversing the parent ; If the child is Adding positively to difference , we include it in the answer Otherwise , we leave the sub - tree and include 0 ( nothing ) in the answer ; DFS for col... | def dfs ( node , parent , tree , colour , answer ) : NEW_LINE INDENT answer [ node ] = colour [ node ] NEW_LINE for u in tree [ node ] : NEW_LINE INDENT if ( u == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( u , node , tree , colour , answer ) NEW_LINE answer [ node ] += max ( answer [ u ] , 0 ) NEW_LINE D... |
Maximum elements that can be made equal with k updates | Function to calculate the maximum number of equal elements possible with atmost K increment of values . Here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . The loop here will run... | def ElementsCalculationFunc ( pre , maxx , x , k , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = x NEW_LINE while j <= n : NEW_LINE INDENT if ( x * maxx [ j ] - ( pre [ j ] - pre [ i ] ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT def MaxNumberOfEl... |
Remove array end element to maximize the sum of product | Python 3 program to find maximum score we can get by removing elements from either end . ; If only one element left . ; If already calculated , return the value . ; Computing Maximum value when element at index i and index j is to be choosed . ; Driver Code | MAX = 50 NEW_LINE def solve ( dp , a , low , high , turn ) : NEW_LINE INDENT if ( low == high ) : NEW_LINE INDENT return a [ low ] * turn NEW_LINE DEDENT if ( dp [ low ] [ high ] != 0 ) : NEW_LINE INDENT return dp [ low ] [ high ] NEW_LINE DEDENT dp [ low ] [ high ] = max ( a [ low ] * turn + solve ( dp , a , low + 1 ,... |
Maximum sum bitonic subarray | function to find the maximum sum bitonic subarray ; ' msis [ ] ' to store the maximum sum increasing subarray up to each index of ' arr ' from the beginning ' msds [ ] ' to store the maximum sum decreasing subarray from each index of ' arr ' up to the end ; to store the maximum sum bitoni... | def maxSumBitonicSubArr ( arr , n ) : NEW_LINE INDENT msis = [ None ] * n NEW_LINE msds = [ None ] * n NEW_LINE max_sum = 0 NEW_LINE msis [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT msis [ i ] = msis [ i - 1 ] + arr [ i ] NEW_LINE DEDENT else ... |
Find k | Structure to store the start and end point ; Function to find Kth smallest number in a vector of merged intervals ; Traverse merged [ ] to find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ;... | class Interval : NEW_LINE INDENT def __init__ ( self , s , e ) : NEW_LINE INDENT self . s = s NEW_LINE self . e = e NEW_LINE DEDENT DEDENT def kthSmallestNum ( merged : list , k : int ) -> int : NEW_LINE INDENT n = len ( merged ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT if k <= abs ( merged [ j ] . e - merged [ ... |
Shortest possible combination of two strings | Prints super sequence of a [ 0. . m - 1 ] and b [ 0. . n - 1 ] ; Fill table in bottom up manner ; Below steps follow above recurrence ; Following code is used to print supersequence ; Create a string of size index + 1 to store the result ; Start from the right - most - bot... | def printSuperSeq ( a , b ) : NEW_LINE INDENT m = len ( a ) NEW_LINE n = len ( b ) NEW_LINE dp = [ [ 0 ] * ( n + 1 ) for i in range ( m + 1 ) ] NEW_LINE for i in range ( 0 , m + 1 ) : NEW_LINE INDENT for j in range ( 0 , n + 1 ) : NEW_LINE INDENT if not i : NEW_LINE INDENT dp [ i ] [ j ] = j ; NEW_LINE DEDENT elif not ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.