text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Length of longest Palindromic Subsequence of even length with no two adjacent characters same | To store the values of subproblems ; Function to find the Longest Palindromic subsequence of even length with no two adjacent characters same ; Base cases If the string length is 1 return 0 ; If the string length is 2 ; Chec...
dp = { } NEW_LINE def solve ( s , c ) : NEW_LINE INDENT if ( len ( s ) == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( len ( s ) == 2 ) : NEW_LINE INDENT if ( s [ 0 ] == s [ 1 ] and s [ 0 ] == c ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( s + " ▁ " + c...
Eggs dropping puzzle | Set 2 | Function to return the minimum number of trials needed in the worst case with n eggs and k floors ; Fill all the entries in table using optimal substructure property ; Return the minimum number of moves ; Driver code
def eggDrop ( n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( k + 1 ) ] NEW_LINE x = 0 ; NEW_LINE while ( dp [ x ] [ n ] < k ) : NEW_LINE INDENT x += 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ x ] [ i ] = dp [ x - 1 ] [ i - 1 ] + dp [ x - 1 ] [ i ] + 1 ; NEW_LINE D...
Maximum length of Strictly Increasing Sub | Function to return the maximum length of strictly increasing subarray after removing atmost one element ; Create two arrays pre and pos ; Find out the contribution of the current element in array [ 0 , i ] and update pre [ i ] ; Find out the contribution of the current elemen...
def maxIncSubarr ( a , n ) : NEW_LINE INDENT pre = [ 0 ] * n ; NEW_LINE pos = [ 0 ] * n ; NEW_LINE pre [ 0 ] = 1 ; NEW_LINE pos [ n - 1 ] = 1 ; NEW_LINE l = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] > a [ i - 1 ] ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + 1 ; NEW_LINE DEDENT else : NEW_L...
Number of square matrices with all 1 s | Python3 program to return the number of square submatrices with all 1 s ; Function to return the number of square submatrices with all 1 s ; Initialize count variable ; If a [ i ] [ j ] is equal to 0 ; Calculate number of square submatrices ending at ( i , j ) ; Calculate the su...
n = 3 NEW_LINE m = 3 NEW_LINE def countSquareMatrices ( a , N , M ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT if ( a [ i ] [ j ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT a [ i ] [ j ] = min ( [ a [ i - 1 ] [ j ] , a [ i ] [ j - 1 ...
Count number of increasing sub | Python3 implementation of the approach ; Segment tree array ; Function for point update in segment tree ; Base case ; If l == r == up ; Mid element ; Updating the segment tree ; Function for the range sum - query ; Base case ; Mid element ; CallIng for the left and the right subtree ; F...
N = 10000 NEW_LINE seg = [ 0 ] * ( 3 * N ) NEW_LINE def update ( In , l , r , up_In , val ) : NEW_LINE INDENT if ( r < up_In or l > up_In ) : NEW_LINE INDENT return seg [ In ] NEW_LINE DEDENT if ( l == up_In and r == up_In ) : NEW_LINE INDENT seg [ In ] = val NEW_LINE return val NEW_LINE DEDENT m = ( l + r ) // 2 NEW_L...
Minimum cost to build N blocks from one block | Function to calculate min cost to build N blocks ; Initialize base case ; Recurence when i is odd ; Recurence when i is even ; Driver code
def minCost ( n , x , y , z ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = dp [ 1 ] = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ ( i + 1 ) // 2 ] + x + z , dp [ i - 1 ] + y ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( ...
Size of the largest divisible subset in an Array | Python3 implementation of the above approach ; Function to find the size of the largest divisible subarray ; Mark all elements of the array ; Traverse reverse ; For all multiples of i ; Return the required answer ; Driver code ; Function call
N = 1000005 NEW_LINE def maximum_set ( a , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE for i in a : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( dp [ i ] != 0 ) : NEW_LINE INDENT for j in range ( 2 * i , N , i ) : NEW_LINE IND...
Longest sub | Python3 implementation of the approach ; Function to return the length of the largest sub - string divisible by 3 ; Base - case ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE import sys NEW_LINE N = 100 NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) NEW_LINE dp = np . zeros ( ( N , 3 ) ) ; NEW_LINE v = np . zeros ( ( N , 3 ) ) ; NEW_LINE def findLargestString ( s , i , r ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT retur...
Number of sub | Python3 implementation of th approach ; Function to return the number of sub - sequences divisible by 3 ; Base - cases ; If the state has been solved before then return its value ; Marking the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE N = 100 NEW_LINE dp = np . zeros ( ( N , 3 ) ) ; NEW_LINE v = np . zeros ( ( N , 3 ) ) ; NEW_LINE def findCnt ( s , i , r ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT D...
Remove minimum elements from ends of array so that sum decreases by at least K | O ( N ) | Function to return the count of minimum elements to be removed from the ends of the array such that the sum of the array decrease by at least K ; To store the final answer ; Maximum possible sum required ; Left point ; Right poin...
def minCount ( arr , n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT sum -= k ; NEW_LINE l = 0 ; NEW_LINE r = 0 ; NEW_LINE tot = 0 ; NEW_LINE while ( l < n ) : NEW_LINE INDENT if ( tot <= sum ) : NEW_LINE INDENT ans = max ( ans , ...
Minimum cost to merge all elements of List | Python3 implementation of the approach ; To store the states of DP ; Function to return the minimum merge cost ; Base case ; If the state has been solved before ; Marking the state as solved ; Reference to dp [ i ] [ j ] ; To store the sum of all the elements in the subarray...
import sys NEW_LINE N = 401 ; NEW_LINE dp = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] ; NEW_LINE v = [ [ False for i in range ( N ) ] for j in range ( N ) ] ; NEW_LINE def minMergeCost ( i , j , arr ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( v [ i ] [ j ] ) : NEW_LINE ...
Expected number of moves to reach the end of a board | Dynamic programming | Python3 implementation of the approach ; To store the states of dp ; To determine whether a state has been solved before ; Function to return the count ; Base cases ; If a state has been solved before it won 't be evaluated again ; Recurrence ...
maxSize = 50 NEW_LINE dp = [ 0 ] * maxSize NEW_LINE v = [ 0 ] * maxSize NEW_LINE def expectedSteps ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( x <= 5 ) : NEW_LINE INDENT return 6 NEW_LINE DEDENT if ( v [ x ] ) : NEW_LINE INDENT return dp [ x ] NEW_LINE DEDENT v [ x ] = 1 NEW_LI...
Number of subsequences in a given binary string divisible by 2 | Function to return the count of the required subsequences ; To store the final answer ; Multiplier ; Loop to find the answer ; Condition to update the answer ; updating multiplier ; Driver code
def countSubSeq ( strr , lenn ) : NEW_LINE INDENT ans = 0 NEW_LINE mul = 1 NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( strr [ i ] == '0' ) : NEW_LINE INDENT ans += mul NEW_LINE DEDENT mul *= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT strr = "10010" NEW_LINE lenn = len ( strr ) NEW_LINE print ( countSubSeq...
Knapsack with large Weights | Python3 implementation of the approach ; To store the states of DP ; Function to solve the recurrence relation ; Base cases ; Marking state as solved ; Recurrence relation ; Function to return the maximum weight ; Iterating through all possible values to find the the largest value that can...
V_SUM_MAX = 1000 NEW_LINE N_MAX = 100 NEW_LINE W_MAX = 10000000 NEW_LINE dp = [ [ 0 for i in range ( N_MAX ) ] for i in range ( V_SUM_MAX + 1 ) ] NEW_LINE v = [ [ 0 for i in range ( N_MAX ) ] for i in range ( V_SUM_MAX + 1 ) ] NEW_LINE def solveDp ( r , i , w , val , n ) : NEW_LINE INDENT if ( r <= 0 ) : NEW_LINE INDEN...
Sum of lengths of all paths possible in a given tree | Python3 implementation of the approach ; Number of vertices ; Adjacency list representation of the tree ; Array that stores the subtree size ; Array to mark all the vertices which are visited ; Utility function to create an edge between two vertices ; Add a to b 's...
sz = 10 ** 5 NEW_LINE n = 5 NEW_LINE an = 0 NEW_LINE tree = [ [ ] for i in range ( sz ) ] NEW_LINE subtree_size = [ 0 ] * sz NEW_LINE vis = [ 0 ] * sz NEW_LINE def addEdge ( a , b ) : NEW_LINE INDENT tree [ a ] . append ( b ) NEW_LINE tree [ b ] . append ( a ) NEW_LINE DEDENT def dfs ( node ) : NEW_LINE INDENT leaf = T...
Number of cells in a matrix that satisfy the given condition | Python3 implementation of the approach ; Function to return the number of cells in which mirror can be placed ; Update the row array where row [ i ] [ j ] will store whether the current row i contains all 1 s in the columns starting from j ; Update the colu...
N = 3 NEW_LINE def numberOfCells ( mat ) : NEW_LINE INDENT row = [ [ False for i in range ( N ) ] for i in range ( N ) ] NEW_LINE col = [ [ False for i in range ( N ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1...
Maximum sum subarray after altering the array | Python3 implementation of the approach ; Function to return the maximum subarray sum ; Function to reverse the subarray arr [ 0. . . i ] ; Function to return the maximum subarray sum after performing the given operation at most once ; To store the result ; When no operati...
import sys NEW_LINE def maxSumSubarray ( arr , size ) : NEW_LINE INDENT max_so_far = - sys . maxsize - 1 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + arr [ i ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_he...
Maximum possible GCD after replacing at most one element in the given array | Python3 implementation of the approach ; Function to return the maximum possible gcd after replacing a single element ; Prefix and Suffix arrays ; Single state dynamic programming relation for storing gcd of first i elements from the left in ...
from math import gcd as __gcd NEW_LINE def MaxGCD ( a , n ) : NEW_LINE INDENT Prefix = [ 0 ] * ( n + 2 ) ; NEW_LINE Suffix = [ 0 ] * ( n + 2 ) ; NEW_LINE Prefix [ 1 ] = a [ 0 ] ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT Prefix [ i ] = __gcd ( Prefix [ i - 1 ] , a [ i - 1 ] ) ; NEW_LINE DEDENT Suffix [ n ...
Sum of products of all possible K size subsets of the given array | Function to return the sum of products of all the possible k size subsets ; Initialising all the values to 0 ; To store the answer for current value of k ; For k = 1 , the answer will simply be the sum of all the elements ; Filling the table in bottom ...
def sumOfProduct ( arr , n , k ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE cur_sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = arr [ i - 1 ] NEW_LINE cur_sum += arr [ i - 1 ] NEW_LINE DEDENT for i in range ( 2 , k + 1 ) : NEW_LINE INDENT...
Find the equal pairs of subsequence of S and subsequence of T | Python3 implementation of the approach ; Function to return the pairs of subsequences from S [ ] and subsequences from T [ ] such that both have the same content ; Create dp array ; Base values ; Base values ; Keep previous dp value ; If both elements are ...
import numpy as np NEW_LINE mod = int ( 1e9 + 7 ) NEW_LINE def subsequence ( S , T , n , m ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , m + 1 ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 1 ; NEW_LINE DEDENT for j in range ( m + 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = 1 ; NEW_LINE DEDENT ...
Maximum count of elements divisible on the left for any element | Function to return the maximum count of required elements ; For every element in the array starting from the second element ; Check all the elements on the left of current element which are divisible by the current element ; Driver code
def findMax ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , i ) : NEW_LINE INDENT if arr [ j ] % arr [ i ] == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT res = max ( count , res ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr =...
Maximum count of elements divisible on the left for any element | Function to return the maximum count of required elements ; divisible [ i ] will store true if arr [ i ] is divisible by any element on its right ; To store the maximum required count ; For every element of the array ; If the current element is divisible...
def findMax ( arr , n ) : NEW_LINE INDENT divisible = [ False ] * n ; NEW_LINE res = 0 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( divisible [ i ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ j ] % arr [ i ] ) == 0 ) : N...
Number of subsets with sum divisible by M | Set 2 | Python3 implementation of the approach ; To store the states of DP ; Function to find the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
maxN = 20 NEW_LINE maxM = 10 NEW_LINE dp = [ [ 0 for i in range ( maxN ) ] for i in range ( maxM ) ] NEW_LINE v = [ [ 0 for i in range ( maxN ) ] for i in range ( maxM ) ] NEW_LINE def findCnt ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( curr == 0 ) : NEW_LINE INDENT return 1 NEW_LI...
Longest subsequence with a given OR value : Dynamic Programming Approach | Python3 implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Dri...
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findLen ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( curr == m ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW...
Longest subsequence with a given AND value | Python3 implementation of the approach ; To store the states of DP ; Function to return the required length ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 256 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findLen ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( curr == m ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NE...
Longest subsequence whose sum is divisible by a given number | Python3 implementation of the approach ; To store the states of DP ; Function to return the length of the longest subsequence whose sum is divisible by m ; Base case ; If the state has been solved before return the value of the state ; Setting the state as ...
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findLen ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( not curr ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_...
Count of subsets with sum equal to X | Python3 implementation of the approach ; To store the states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxSum = 50 NEW_LINE minSum = 50 NEW_LINE base = 50 NEW_LINE dp = np . zeros ( ( maxN , maxSum + minSum ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxSum + minSum ) ) ; NEW_LINE def findCnt ( arr , i , required_sum , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if (...
Number of subsets with a given OR value | Python3 implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findCnt ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return ( curr == m ) ; NEW_LINE DEDENT if ( v [ i ] [ curr ] ) : NEW_LIN...
Number of subsets with a given AND value | Python3 implementation of the approach ; To store states of DP ; Function to return the required count ; Base case ; If the state has been solved before return the value of the state ; Setting the state as solved ; Recurrence relation ; Driver code
import numpy as np NEW_LINE maxN = 20 NEW_LINE maxM = 64 NEW_LINE dp1 = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE v1 = np . zeros ( ( maxN , maxM ) ) ; NEW_LINE def findCnt ( arr , i , curr , n , m ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return ( curr == m ) ; NEW_LINE DEDENT if ( v1 [ i ] [ curr ] ) : NEW_...
Count of integers obtained by replacing ? in the given string that give remainder 5 when divided by 13 | Python3 implementation of the approach ; Function to find the count of integers obtained by replacing ' ? ' in a given string such that formed integer gives remainder 5 when it is divided by 13 ; Initialise ; Place ...
import numpy as np NEW_LINE MOD = ( int ) ( 1e9 + 7 ) NEW_LINE def modulo_13 ( s , n ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , 13 ) ) ; NEW_LINE dp [ 0 ] [ 0 ] = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT nxt = ord ( s [ i ] ) - ord ( '0' ) ; NEW_LINE if ( s [ i ] ...
Longest Increasing Subsequence using Longest Common Subsequence Algorithm | Function to return the size of the longest increasing subsequence ; Create an 2D array of integer for tabulation ; Take the second sequence as the sorted sequence of the given sequence ; Classical Dynamic Programming algorithm for Longest Commo...
def LISusingLCS ( seq ) : NEW_LINE INDENT n = len ( seq ) NEW_LINE L = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE sortedseq = sorted ( seq ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = ...
Count of N | Function to return the count of n - digit numbers that satisfy the given conditions ; Base case ; If 0 wasn 't chosen previously ; If 0 wasn 't chosen previously ; Driver code
def count_numbers ( k , n , flag ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT return ( k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT return ( k - 1 ) * ( count_numbers ( k , n - 1 , 0 ) + count_numbers ( k , n - 1 , 1 ) ...
Count of N | Function to return the count of n - digit numbers that satisfy the given conditions ; DP array to store the pre - caluclated states ; Base cases ; i - digit numbers ending with 0 can be formed by concatenating 0 in the end of all the ( i - 1 ) - digit number ending at a non - zero digit ; i - digit numbers...
def count_numbers ( k , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] [ 0 ] = 0 NEW_LINE dp [ 1 ] [ 1 ] = k - 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 1 ] NEW_LINE dp [ i ] [ 1 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ]...
Divide an array into K subarray with the given condition | Function to divide an array into k parts such that the summ of difference of every element with the maximum element of that part is minimum ; Dp to store the values ; Fill up the dp table ; Intitilize maximum value ; Max element and the summ ; Run a loop from i...
def divideArray ( arr , n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 500 ) ] for i in range ( 500 ) ] NEW_LINE k -= 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 10 ** 9 NEW_LINE max_ = - 1 NEW_LINE summ = 0 NEW_LINE for l in r...
Count of subsets not containing adjacent elements | Function to return the count of possible subsets ; Total possible subsets of n sized array is ( 2 ^ n - 1 ) ; To store the required count of subsets ; Run from i 000. .0 to 111. .1 ; If current subset has consecutive elements from the array ; Driver code
def cntSubsets ( arr , n ) : NEW_LINE INDENT max = pow ( 2 , n ) NEW_LINE result = 0 NEW_LINE for i in range ( max ) : NEW_LINE INDENT counter = i NEW_LINE if ( counter & ( counter >> 1 ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT result += 1 NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 3 , 5 , 7 ] NEW_LINE ...
Count of subsets not containing adjacent elements | Function to return the count of possible subsets ; If previous element was 0 then 0 as well as 1 can be appended ; If previous element was 1 then only 0 can be appended ; Store the count of all possible subsets ; Driver code
def cntSubsets ( arr , n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE b = [ 0 ] * n ; NEW_LINE a [ 0 ] = b [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] + b [ i - 1 ] ; NEW_LINE b [ i ] = a [ i - 1 ] ; NEW_LINE DEDENT result = a [ n - 1 ] + b [ n - 1 ] ; NEW_LINE return result ; NE...
Maximum perimeter of a square in a 2D grid | Function to calculate the perfix sum of the rows and the columns of the given matrix ; Number of rows and cols ; First column of the row prefix array ; Update the prefix sum for the rows ; First row of the column prefix array ; Update the prefix sum for the columns ; Functio...
def perfix_calculate ( A , row , col ) : NEW_LINE INDENT n = len ( A ) NEW_LINE m = len ( A [ 0 ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT row [ i ] [ 0 ] = A [ i ] [ 0 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , m ) : NEW_LINE INDENT row [ i ] [ j ] = row [ i ] [ j - 1 ] + A ...
Optimal Strategy for a Game | Set 3 | Calculates the maximum score possible for P1 If only the bags from beg to ed were available ; Length of the game ; Which turn is being played ; Base case i . e last turn ; if it is P1 's turn ; if P2 's turn ; Player picks money from the left end ; Player picks money from the right...
def maxScore ( money , beg , ed ) : NEW_LINE INDENT totalTurns = len ( money ) NEW_LINE turnsTillNow = beg + ( ( totalTurns - 1 ) - ed ) NEW_LINE if ( beg == ed ) : NEW_LINE INDENT if ( turnsTillNow % 2 == 0 ) : NEW_LINE INDENT return [ money [ beg ] , " L " ] NEW_LINE DEDENT else : NEW_LINE INDENT return [ 0 , " L " ]...
Minimum number of Fibonacci jumps to reach end | A Dynamic Programming based Python3 program to find minimum number of jumps to reach Destination ; Function that returns the min number of jump to reach the destination ; We consider only those Fibonacci numbers which are less than n , where we can consider fib [ 30 ] to...
MAX = 1e9 NEW_LINE def minJumps ( arr , N ) : NEW_LINE INDENT fib = [ 0 for i in range ( 30 ) ] NEW_LINE fib [ 0 ] = 0 NEW_LINE fib [ 1 ] = 1 NEW_LINE for i in range ( 2 , 30 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DP = [ 0 for i in range ( N + 2 ) ] NEW_LINE DP [ 0 ] = 0 NEW_LINE ...
Subsequence X of length K such that gcd ( X [ 0 ] , X [ 1 ] ) + ( X [ 2 ] , X [ 3 ] ) + ... is maximized | Python3 program to find the sum of the addition of all possible subsets ; Recursive function to find the maximum value of the given recurrence ; If we get K elements ; If we have reached the end and K elements are...
from math import gcd as __gcd NEW_LINE MAX = 100 NEW_LINE def recur ( ind , cnt , last , a , n , k , dp ) : NEW_LINE INDENT if ( cnt == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( ind == n ) : NEW_LINE INDENT return - 10 ** 9 NEW_LINE DEDENT if ( dp [ ind ] [ cnt ] != - 1 ) : NEW_LINE INDENT return dp [ ind ] [...
Maximum number of given operations to remove the entire string | Function to return the maximum number of given operations required to remove the given entirely ; If length of the is zero ; Single operation can delete the entire string ; To store the prefix of the string which is to be deleted ; Prefix s [ 0. . i ] ; T...
def find ( s ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT c = 1 NEW_LINE d = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT d += s [ i ] NEW_LINE s2 = s [ i + 1 : i + 1 + len ( d ) ] NEW_LINE if ( s2 == d ) : NEW_LINE INDENT c = 1 + find ( s [ i + 1 : ] ) NEW_LINE br...
Sum of the distances from every node to all other nodes is maximum | Python3 program to implement the above approach ; Function to add an edge to the tree ; Function to run DFS and calculate the height of the subtree below it ; Initially initialize with 1 ; Traverse for all nodes connected to node ; If node is not pare...
edges = [ [ ] for i in range ( 100 ) ] NEW_LINE tree = [ [ ] for i in range ( 100 ) ] NEW_LINE def addEdge ( x , y ) : NEW_LINE INDENT edges . append ( [ x , y ] ) NEW_LINE tree [ x ] . append ( y ) NEW_LINE tree [ y ] . append ( x ) NEW_LINE DEDENT def dfs ( node , parent , dp ) : NEW_LINE INDENT dp [ node ] = 1 NEW_L...
Divide the array in K segments such that the sum of minimums is maximized | Python 3 program to find the sum of the minimum of all the segments ; Function to maximize the sum of the minimums ; If k segments have been divided ; If we are at the end ; If we donot reach the end then return a negative number that cannot be...
MAX = 10 NEW_LINE def maximizeSum ( a , n , ind , k , dp ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT if ( ind == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1e9 NEW_LINE DEDENT DEDENT elif ( ind == n ) : NEW_LINE INDENT return - 1e9 NEW_LINE DEDENT elif ( dp [ ind ] [ k ] != -...
Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Function to find the minimum required sum using dynamic programming ; If both start and bucket reached end then return 0 else that arrangement is not possible so return INT_MAX ; Corner case ; If state if already calculated then return its answer ;...
def solveUtil ( start , bucket , str1 , K , dp ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE if ( start == N ) : NEW_LINE INDENT if ( bucket == K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 10 ** 9 NEW_LINE DEDENT if ( bucket == K ) : NEW_LINE INDENT return 10 ** 9 NEW_LINE DEDENT if ( dp [ start ] [ bucket ] !...
Probability of getting more heads than tails when N biased coins are tossed | Python3 implementation of the above approach ; Function to return the probability when number of heads is greater than the number of tails ; Declaring the DP table ; Base case ; Iterating for every coin ; j represents the numbers of heads ; I...
import numpy as np NEW_LINE def Probability ( p , n ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , n + 1 ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0.0 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 1.0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LI...
Number of ways to get a given sum with n number of m | Python3 function to calculate the number of ways to achieve sum x in n no of throws ; Function to calculate recursively the number of ways to get sum in given throws and [ 1. . m ] values ; Base condition 1 ; Base condition 2 ; If value already calculated dont move...
import numpy as np NEW_LINE mod = 1000000007 ; NEW_LINE dp = np . zeros ( ( 55 , 55 ) ) ; NEW_LINE def NoofWays ( face , throws , sum ) : NEW_LINE INDENT if ( sum == 0 and throws == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( sum < 0 or throws == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ thro...
Longest sub | Function to return the length of the longest required sub - sequence ; Sort the array ; To store the resultant length ; If array contains only one element then it divides itself ; Every element divides itself ; Count for all numbers which are lesser than a [ i ] ; If a [ i ] % a [ j ] then update the maxi...
def find ( n , a ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE res = 1 ; NEW_LINE dp = [ 0 ] * n ; NEW_LINE dp [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = 1 ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( a [ i ] % a [ j ] == 0 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , 1 + dp [...
Maximize the happiness of the groups on the Trip | Python3 implementation of the approach ; Function to return the maximized happiness ; Two arrays similar to 0 1 knapsack problem ; To store the happiness of the current group ; Current person is a child ; Woman ; Man ; Old person ; Group 's happiness is the sum of happ...
import numpy as np NEW_LINE def MaxHappiness ( A , N , v ) : NEW_LINE INDENT val = [ 0 ] * N ; wt = [ 0 ] * N ; c = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT string = v [ i ] ; NEW_LINE c = 0 ; NEW_LINE for j in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ j ] == ' c ' ) : NEW_LINE INDENT c += 4 ;...
0 | Python3 implementation of the approach ; To store states of DP ; To check if a state has been solved ; Function to compute the states ; Base case ; Check if a state has been solved ; Setting a state as solved ; Returning the solved state ; Function to pre - compute the states dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] , . . ,...
import numpy as np NEW_LINE import sys NEW_LINE C_MAX = 30 NEW_LINE max_arr_len = 10 NEW_LINE dp = np . zeros ( ( max_arr_len , C_MAX + 1 ) ) ; NEW_LINE v = np . zeros ( ( max_arr_len , C_MAX + 1 ) ) ; NEW_LINE INT_MIN = - ( sys . maxsize ) + 1 NEW_LINE def findMax ( i , r , w , n ) : NEW_LINE INDENT if ( r < 0 ) : NEW...
Maximise array sum after taking non | Python3 implementation of the approach ; To store the states of dp ; To check if a given state has been solved ; To store the prefix - sum ; Function to fill the prefix_sum [ ] with the prefix sum of the given array ; Function to find the maximum sum subsequence such that no two el...
maxLen = 10 NEW_LINE dp = [ 0 ] * maxLen ; NEW_LINE v = [ 0 ] * maxLen ; NEW_LINE prefix_sum = [ 0 ] * maxLen ; NEW_LINE def findPrefixSum ( arr , n ) : NEW_LINE INDENT prefix_sum [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum [ i ] = arr [ i ] + prefix_sum [ i - 1 ] ; NEW_LINE DEDENT DE...
Find maximum path sum in a 2D matrix when exactly two left moves are allowed | Python3 program to find maximum path sum in a 2D matrix when exactly two left moves are allowed ; Function to return the maximum path sum ; Copy last column i . e . starting and ending columns in another array ; Calculate suffix sum in each ...
import numpy as np NEW_LINE N = 3 NEW_LINE M = 3 NEW_LINE def findMaxSum ( arr ) : NEW_LINE INDENT sum = 0 ; NEW_LINE b = np . zeros ( ( N , M ) ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT b [ i ] [ M - 1 ] = arr [ i ] [ M - 1 ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M - 2 , -...
Queries to check if string B exists as substring in string A | Python3 implementation of the approach ; Function to return the modular inverse using Fermat 's little theorem ; Function to generate hash ; To store prefix - sum of rolling hash ; Multiplier for different values of i ; Generating hash value for string b ; ...
mod = 3803 NEW_LINE d = 26 NEW_LINE hash_b = 0 NEW_LINE hash_a = [ ] NEW_LINE mul = [ ] NEW_LINE def mi ( x ) : NEW_LINE INDENT global mod NEW_LINE p = mod - 2 NEW_LINE s = 1 NEW_LINE while p != 1 : NEW_LINE INDENT if p % 2 == 1 : NEW_LINE INDENT s = ( s * x ) % mod NEW_LINE DEDENT x = ( x * x ) % mod NEW_LINE p //= 2 ...
Number of ways to divide an array into K equal sum sub | Python3 implementation of the approach ; Array to store the states of DP ; Array to check if a state has been solved before ; To store the sum of the array elements ; Function to find the sum of all the array elements ; Function to return the number of ways ; If ...
import numpy as np NEW_LINE max_size = 20 NEW_LINE max_k = 20 NEW_LINE dp = np . zeros ( ( max_size , max_k ) ) ; NEW_LINE v = np . zeros ( ( max_size , max_k ) ) ; NEW_LINE sum = 0 ; NEW_LINE def findSum ( arr , n ) : NEW_LINE INDENT global sum NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LIN...
Maximum sum in an array such that every element has exactly one adjacent element to it | Python 3 implementation of the approach ; To store the states of dp ; Function to return the maximized sum ; Base case ; Checks if a state is already solved ; Recurrence relation ; Return the result ; Driver code
arrSize = 51 NEW_LINE dp = [ 0 for i in range ( arrSize ) ] NEW_LINE v = [ False for i in range ( arrSize ) ] NEW_LINE def sumMax ( i , arr , n ) : NEW_LINE INDENT if ( i >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT v [ i ] = True NEW_LINE dp [ i...
Maximum Sum Subsequence of length k | Python program to calculate the maximum sum of increasing subsequence of length k ; In the implementation dp [ n ] [ k ] represents maximum sum subsequence of length k and the subsequence is ending at index n . ; Initializing whole multidimensional dp array with value - 1 ; For eac...
def MaxIncreasingSub ( arr , n , k ) : NEW_LINE INDENT dp = [ - 1 ] * n NEW_LINE ans = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = [ - 1 ] * ( k + 1 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT dp [ i ] [ 1 ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in ...
Generate all unique partitions of an integer | Set 2 | Array to store the numbers used to form the required sum ; Function to print the array which contains the unique partitions which are used to form the required sum ; Function to find all the unique partitions remSum = remaining sum to form maxVal is the maximum num...
dp = [ 0 for i in range ( 200 ) ] NEW_LINE count = 0 NEW_LINE def print1 ( idx ) : NEW_LINE INDENT for i in range ( 1 , idx , 1 ) : NEW_LINE INDENT print ( dp [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , end ▁ = ▁ " " ) NEW_LINE DEDENT def solve ( remSum , maxVal , idx , count ) : NEW_LINE INDENT if ( remSum == ...
Queries for bitwise OR in the given matrix | Python 3 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 for each row ; Finding column - wise prefix count ; Function to return the result for a query ; To store the a...
bitscount = 32 NEW_LINE n = 3 NEW_LINE prefix_count = [ [ [ 0 for i in range ( n ) ] for j in range ( n ) ] for k in range ( bitscount ) ] NEW_LINE def findPrefixCount ( arr ) : NEW_LINE INDENT for i in range ( bitscount ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ 0 ] = ( ( arr...
Queries for bitwise AND in the given matrix | Python 3 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 for each row ; Finding column - wise prefix count ; Function to return the result for a query ; To store the ...
bitscount = 32 NEW_LINE n = 3 NEW_LINE prefix_count = [ [ [ 0 for i in range ( n ) ] for j in range ( n ) ] for k in range ( bitscount ) ] NEW_LINE def findPrefixCount ( arr ) : NEW_LINE INDENT for i in range ( bitscount ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT prefix_count [ i ] [ j ] [ 0 ] = ( ( arr...
Maximum sum such that no two elements are adjacent | Set 2 | Python 3 program to implement above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been...
maxLen = 10 NEW_LINE dp = [ 0 for i in range ( maxLen ) ] NEW_LINE v = [ 0 for i in range ( maxLen ) ] NEW_LINE def maxSum ( arr , i , n ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT v [ i ] = 1 NEW_LINE dp [ i ] = max ( max...
Optimal Strategy for a Game | Set 2 | Python3 program to find out maximum value from a given sequence of coins ; For both of your choices , the opponent gives you total sum minus maximum of his value ; Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ;...
MAX = 100 NEW_LINE memo = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE def oSRec ( arr , i , j , Sum ) : NEW_LINE INDENT if ( j == i + 1 ) : NEW_LINE INDENT return max ( arr [ i ] , arr [ j ] ) NEW_LINE DEDENT if ( memo [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return memo [ i ] [ j ] NEW_LINE DEDENT m...
Minimum cost to select K strictly increasing elements | Python3 program for the above approach ; Function to calculate min cost to choose k increasing elements ; If k elements are counted return 0 ; If all elements of array has been traversed then return MAX_VALUE ; To check if this is already calculated ; When i 'th e...
N = 1005 ; NEW_LINE K = 20 ; NEW_LINE n = 0 NEW_LINE k = 0 NEW_LINE dp = [ [ [ - 1 for k in range ( K + 1 ) ] for j in range ( N + 1 ) ] for i in range ( N + 1 ) ] NEW_LINE def minCost ( i , prev , cnt , ele , cost ) : NEW_LINE INDENT if ( cnt == k + 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i == n + 1 ) : ...
Maximize the subarray sum after multiplying all elements of any subarray with X | Python3 implementation of the approach ; Function to return the maximum sum ; Base case ; If already calculated ; If no elements have been chosen ; Do not choose any element and use Kadane 's algorithm by taking max ; Choose the sub - arr...
N = 5 NEW_LINE def func ( idx , cur , a , dp , n , x ) : NEW_LINE INDENT if ( idx == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ idx ] [ cur ] != - 1 ) : NEW_LINE INDENT return dp [ idx ] [ cur ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( cur == 0 ) : NEW_LINE INDENT ans = max ( ans , a [ idx ] + func ( idx + 1...
Count pairs of non | Python3 implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Check for equal ; Function to return the numbe...
N = 100 NEW_LINE def pre_process ( dp , s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] = False NEW_LINE DEDENT DEDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - j + 1 ) : NEW_LINE INDENT if ( j <= 2 ) : N...
Queries to check if substring [ L ... R ] is palindrome or not | Python3 implementation of the approach ; Pre - processing function ; Get the size of the string ; Initially mark every position as false ; For the length ; Iterate for every index with length j ; If the length is less than 2 ; If characters are equal ; Ch...
N = 100 NEW_LINE def pre_process ( dp , s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT dp [ i ] [ j ] = False NEW_LINE DEDENT DEDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for i in range ( n - j + 1 ) : NEW_LINE INDENT if ( j <= 2 ) : N...
Length of the longest increasing subsequence such that no two adjacent elements are coprime | Python3 program to find the length of the longest increasing sub sequence from the given array such that no two adjacent elements are co prime ; Function to find the length of the longest increasing sub sequence from the given...
N = 100005 NEW_LINE def LIS ( a , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE d = [ 0 for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ a [ i ] ] = 1 NEW_LINE for j in range ( 2 , a [ i ] ) : NEW_LINE INDENT if j * j > a [ i ] : NEW_LINE INDENT break NEW_LIN...
Find the number of binary strings of length N with at least 3 consecutive 1 s | Function that returns true if s contains three consecutive 1 's ; Function to return the count of required strings ; Driver code
def check ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' and s [ i - 1 ] == '1' and s [ i - 2 ] == '1' ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT DEDENT def countStr ( i , s ) : NEW_LINE INDENT if ( i < 0 ) : NEW_LINE INDENT if ( check ( s ) ) ...
Find the number of binary strings of length N with at least 3 consecutive 1 s | Function to return the count of required strings ; '0' at ith position ; '1' at ith position ; Driver code ; Base condition : 2 ^ ( i + 1 ) because of 0 indexing
def solve ( i , x , dp ) : NEW_LINE INDENT if ( i < 0 ) : NEW_LINE INDENT return x == 3 NEW_LINE DEDENT if ( dp [ i ] [ x ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ x ] NEW_LINE DEDENT dp [ i ] [ x ] = solve ( i - 1 , 0 , dp ) NEW_LINE dp [ i ] [ x ] += solve ( i - 1 , x + 1 , dp ) NEW_LINE return dp [ i ] [ x ] NE...
Find the sum of the diagonal elements of the given N X N spiral matrix | Function to return the sum of both the diagonal elements of the required matrix ; Array to store sum of diagonal elements ; Base cases ; Computing the value of dp ; Driver code
def findSum ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE dp [ 1 ] = 1 NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT dp [ i ] = ( ( 4 * ( i * i ) ) - 6 * ( i - 1 ) + dp [ i - 2 ] ) NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' ...
Maximum sum of nodes in Binary tree such that no two are adjacent | Dynamic Programming | Function to find the diameter of the tree using Dynamic Programming ; Traverse for all children of node ; Call DFS function again ; Include the current node then donot include the children ; Donot include current node , then inclu...
def dfs ( node , parent , dp1 , dp2 , adj , tree ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 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 , tree ) ; NEW_LINE sum1 += dp2 [ i ] ; NEW_LINE sum2 += max ( dp1 [ i ] , dp2...
Count number of ways to reach a given score in a Matrix | Python3 implementation of the approach ; To store the states of dp ; To check whether a particular state of dp has been solved ; Function to find the ways using memoization ; Base cases ; If required score becomes negative ; If current state has been reached bef...
n = 3 NEW_LINE MAX = 60 NEW_LINE dp = [ [ [ 0 for i in range ( 30 ) ] for i in range ( 30 ) ] for i in range ( MAX + 1 ) ] NEW_LINE v = [ [ [ 0 for i in range ( 30 ) ] for i in range ( 30 ) ] for i in range ( MAX + 1 ) ] NEW_LINE def findCount ( mat , i , j , m ) : NEW_LINE INDENT if ( i == 0 and j == 0 ) : NEW_LINE IN...
Number of ways of scoring R runs in B balls with at most W wickets | Python3 implementation of the approach ; Function to return the number of ways to score R runs in B balls with at most W wickets ; If the wickets lost are more ; If runs scored are more ; If condition is met ; If no run got scored ; Already visited st...
mod = 1000000007 NEW_LINE RUNMAX = 300 NEW_LINE BALLMAX = 50 NEW_LINE WICKETMAX = 10 NEW_LINE def CountWays ( r , b , l , R , B , W , dp ) : NEW_LINE INDENT if ( l > W ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( r > R ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( b == B and r == R ) : NEW_LINE INDENT retu...
Minimum steps to delete a string by deleting substring comprising of same characters | Function to return the minimum number of delete operations ; When a single character is deleted ; When a group of consecutive characters are deleted if any of them matches ; When both the characters are same then delete the letters i...
def findMinimumDeletion ( l , r , dp , s ) : NEW_LINE INDENT if l > r : NEW_LINE INDENT return 0 NEW_LINE DEDENT if l == r : NEW_LINE INDENT return 1 NEW_LINE DEDENT if dp [ l ] [ r ] != - 1 : NEW_LINE INDENT return dp [ l ] [ r ] NEW_LINE DEDENT res = 1 + findMinimumDeletion ( l + 1 , r , dp , s ) NEW_LINE for i in ra...
Minimal product subsequence where adjacent elements are separated by a maximum distance of K | Python3 implementation of the above approach . ; Function to get the minimum product of subsequence such that adjacent elements are separated by a max distance of K ; multiset will hold pairs pair = ( log value of product , d...
import math NEW_LINE mod = 1000000007 ; NEW_LINE MAX = 100005 ; NEW_LINE def minimumProductSubsequence ( arr , n , k ) : NEW_LINE INDENT s = [ ] NEW_LINE dp = [ 0 for i in range ( MAX ) ] ; NEW_LINE p = [ 0.0 for i in range ( MAX ) ] ; NEW_LINE dp [ 0 ] = arr [ 0 ] ; NEW_LINE p [ 0 ] = math . log ( arr [ 0 ] ) ; NEW_LI...
Ways to form a group from three groups with given constraints | Python3 program to find the number of ways to form the group of peopls ; Function to pre - compute the Combination using DP ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Functi...
C = [ [ 0 for i in range ( 1000 ) ] for i in range ( 1000 ) ] NEW_LINE def binomialCoeff ( n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT...
Longest subsequence such that adjacent elements have at least one common digit | Returns Length of maximum Length subsequence ; To store the Length of the maximum Length subsequence ; To store current element arr [ i ] ; To store the Length of the sub - sequence ending at index i and having common digit d ; To store di...
def findSubsequence ( arr , n ) : NEW_LINE INDENT Len = 1 NEW_LINE tmp = 0 NEW_LINE i , j , d = 0 , 0 , 0 NEW_LINE dp = [ [ 0 for i in range ( 10 ) ] for i in range ( n ) ] NEW_LINE cnt = [ 0 for i in range ( 10 ) ] NEW_LINE locMax = 0 NEW_LINE tmp = arr [ 0 ] NEW_LINE while ( tmp > 0 ) : NEW_LINE INDENT dp [ 0 ] [ tmp...
Count Numbers in Range with difference between Sum of digits at even and odd positions as Prime | Python implementation of the above approach ; Prime numbers upto 100 ; Function to return the count of required numbers from 0 to num ; Base Case ; check if the difference is equal to any prime number ; If this result is a...
M = 18 NEW_LINE prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 ] NEW_LINE def count ( pos , even , odd , tight , num ) : NEW_LINE INDENT if pos == len ( num ) : NEW_LINE INDENT if len ( num ) & 1 : NEW_LINE INDENT odd , even = even , odd NEW_L...
Find the number of distinct pairs of vertices which have a distance of exactly k in a tree | Python3 implementation of the approach ; To store vertices and value of k ; To store number vertices at a level i ; To store the final answer ; Function to add an edge between two nodes ; Function to find the number of distinct...
N = 5005 NEW_LINE n , k = 0 , 0 NEW_LINE gr = [ [ ] for i in range ( N ) ] NEW_LINE d = [ [ 0 for i in range ( 505 ) ] for i in range ( N ) ] NEW_LINE ans = 0 NEW_LINE def Add_edge ( x , y ) : NEW_LINE INDENT gr [ x ] . append ( y ) NEW_LINE gr [ y ] . append ( x ) NEW_LINE DEDENT def dfs ( v , par ) : NEW_LINE INDENT ...
Sum of XOR of all subarrays | Function to calculate the Sum of XOR of all subarrays ; variable to store the final Sum ; multiplier ; variable to store number of sub - arrays with odd number of elements with ith bits starting from the first element to the end of the array ; variable to check the status of the odd - even...
def findXorSum ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE mul = 1 NEW_LINE for i in range ( 30 ) : NEW_LINE INDENT c_odd = 0 NEW_LINE odd = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] & ( 1 << i ) ) > 0 ) : NEW_LINE INDENT odd = ( ~ odd ) NEW_LINE DEDENT if ( odd ) : NEW_LINE INDENT c_odd += ...
Minimum replacements to make adjacent characters unequal in a ternary string | Set | Python 3 program to count the minimal replacements such that adjacent characters are unequal ; function to return integer value of i - th character in the string ; Function to count the number of minimal replacements ; If the string ha...
import sys NEW_LINE def charVal ( s , i ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( s [ i ] == '1' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT def countMinimalReplacements ( s , i , prev , dp , n ) : NEW_LINE INDENT ...
Find probability of selecting element from kth column after N iterations | Python3 implementation of the above approach ; Function to calculate probability ; declare dp [ ] [ ] and sum [ ] ; precalculate the first row ; calculate the probability for each element and update dp table ; return result ; Driver code
n = 4 NEW_LINE m = 4 NEW_LINE def calcProbability ( M , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( m ) ] NEW_LINE Sum = [ 0 for i in range ( n ) ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT dp [ 0 ] [ j ] = M [ 0 ] [ j ] NEW_LINE Sum [ 0 ] += dp [ 0 ] [ j ] NEW_LINE DEDENT for i in ra...
Possible cuts of a number such that maximum parts are divisible by 3 | Python3 program to find the maximum number of numbers divisible by 3 in a large number ; Function to find the maximum number of numbers divisible by 3 in a large number ; store size of the string ; Stores last index of a remainder ; last visited pla...
import math as mt NEW_LINE def MaximumNumbers ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE remIndex = [ - 1 for i in range ( 3 ) ] NEW_LINE remIndex [ 0 ] = 0 NEW_LINE res = [ - 1 for i in range ( n + 1 ) ] NEW_LINE r = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT r = ( r + ord ( string [ i - 1 ] )...
Minimum steps required to convert X to Y where a binary matrix represents the possible conversions | Pyton3 implementation of the above approach ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of numbers ; Initially same as mat ; Add all numbers one by one to th...
INF = 99999 NEW_LINE size = 10 NEW_LINE def findMinimumSteps ( mat , x , y , n ) : NEW_LINE INDENT dist = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE i , j , k = 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 0 ) : NEW_LINE INDEN...
Count number of paths whose weight is exactly X and has at | Python3 program to count the number of paths ; Function to find the number of paths ; If the Summation is more than X ; If exactly X weights have reached ; Already visited ; Count paths ; Traverse in all paths ; If the edge weight is M ; else : Edge 's weight...
Max = 4 NEW_LINE c = 2 NEW_LINE def countPaths ( Sum , get , m , n , dp ) : NEW_LINE INDENT if ( Sum < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( Sum == 0 ) : NEW_LINE INDENT return get NEW_LINE DEDENT if ( dp [ Sum ] [ get ] != - 1 ) : NEW_LINE INDENT return dp [ Sum ] [ get ] NEW_LINE DEDENT res = 0 NEW_LINE...
Minimum Operations to make value of all vertices of the tree Zero | A utility function to add an edge in an undirected graph ; A utility function to print the adjacency list representation of graph ; Utility Function for findMinOperation ( ) ; Base Case for current node ; Iterate over the adjacency list for src ; calcu...
def addEdge ( adj , u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def printGraph ( adj , V ) : NEW_LINE INDENT for v in range ( 0 , V ) : NEW_LINE INDENT print ( " Adjacency ▁ list ▁ of ▁ vertex " , v ) NEW_LINE print ( " head " , end = " ▁ " ) NEW_LINE for x in ad...
Sum of kth powers of first n natural numbers | global array to store factorials ; function to calculate the factorials of all the numbers upto k ; function to return the binomial coeff ; nCr = ( n ! * ( n - r ) ! ) / r ! ; function to return the sum of the kth powers of n natural numbers ; when j is 1 ; calculating sum...
MAX_K = 15 NEW_LINE fac = [ 1 for i in range ( MAX_K ) ] NEW_LINE def factorial ( k ) : NEW_LINE INDENT fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , k + 2 ) : NEW_LINE INDENT fac [ i ] = ( i * fac [ i - 1 ] ) NEW_LINE DEDENT DEDENT def bin ( a , b ) : NEW_LINE INDENT ans = fac [ a ] // ( fac [ a - b ] * fac [ b ] ) NEW_...
Ways to fill N positions using M colors such that there are exactly K pairs of adjacent different colors | Python 3 implementation of the approach ; Recursive function to find the required number of ways ; When all positions are filled ; If adjacent pairs are exactly K ; If already calculated ; Next position filled wit...
max = 4 NEW_LINE def countWays ( index , cnt , dp , n , m , k ) : NEW_LINE INDENT if ( index == n ) : NEW_LINE INDENT if ( cnt == k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( dp [ index ] [ cnt ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ cnt ] NEW_LIN...
Number of balanced bracket expressions that can be formed from a string | Max string length ; Function to check whether index start and end can form a bracket pair or not ; Check for brackets ( ) ; Check for brackets [ ] ; Check for brackets { } ; Function to find number of proper bracket expressions ; If starting inde...
MAX = 300 NEW_LINE def checkFunc ( i , j , st ) : NEW_LINE INDENT if ( st [ i ] == ' ( ' and st [ j ] == ' ) ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' ( ' and st [ j ] == ' ? ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( st [ i ] == ' ? ' and st [ j ] == ' ) ' ) : NEW_LINE INDENT return 1 ...
Count pairs ( A , B ) such that A has X and B has Y number of set bits and A + B = C | Initial DP array ; Recursive function to generate all combinations of bits ; if the state has already been visited ; find if C has no more set bits on left ; if no set bits are left for C and there are no set bits for A and B and the...
dp = [ [ [ [ - 1 , - 1 ] for i in range ( 64 ) ] for j in range ( 64 ) ] for k in range ( 64 ) ] NEW_LINE def func ( third , seta , setb , carry , number ) : NEW_LINE INDENT if dp [ third ] [ seta ] [ setb ] [ carry ] != - 1 : NEW_LINE INDENT return dp [ third ] [ seta ] [ setb ] [ carry ] NEW_LINE DEDENT shift = numbe...
Sum of Fibonacci numbers at even indexes upto N terms | Computes value of first fibonacci numbers and stores the even - indexed sum ; Initialize result ; Add remaining terms ; For even indices ; Return the alternting sum ; Driver code ; Get n ; Find the even - indiced sum
def calculateEvenSum ( n ) : NEW_LINE INDENT if n <= 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT fibo = [ 0 ] * ( 2 * n + 1 ) NEW_LINE fibo [ 0 ] , fibo [ 1 ] = 0 , 1 NEW_LINE sum = 0 NEW_LINE for i in range ( 2 , 2 * n + 1 ) : NEW_LINE INDENT fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] NEW_LINE if i % 2 == 0 : NEW_L...
Sum of Fibonacci numbers at even indexes upto N terms | Python3 Program to find even indexed Fibonacci Sum in O ( Log n ) time . ; Create an array for memoization ; Returns n 'th Fibonacci number using table f[] ; Base cases ; If fib ( n ) is already computed ; Applying above formula [ Note value n & 1 is 1 if n is odd...
MAX = 1000 ; NEW_LINE f = [ 0 ] * MAX ; NEW_LINE def fib ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 or n == 2 ) : NEW_LINE INDENT f [ n ] = 1 ; NEW_LINE return f [ n ] ; NEW_LINE DEDENT if ( f [ n ] ) : NEW_LINE INDENT return f [ n ] ; NEW_LINE DEDENT k = ( n + 1 ) //...
Gould 's Sequence | 32768 = 2 ^ 15 ; Array to store Sequence up to 2 ^ 16 = 65536 ; Utility function to pre - compute odd numbers in ith row of Pascals 's triangle ; First term of the Sequence is 1 ; Initialize i to 1 ; Initialize p to 1 ( i . e 2 ^ i ) in each iteration i will be pth power of 2 ; loop to generate goul...
MAX = 32768 NEW_LINE arr = [ None ] * ( 2 * MAX ) NEW_LINE def gouldSequence ( ) : NEW_LINE INDENT arr [ 0 ] = 1 NEW_LINE i = 1 NEW_LINE p = 1 NEW_LINE while i <= MAX : NEW_LINE INDENT j = 0 NEW_LINE while j < i : NEW_LINE INDENT arr [ i + j ] = 2 * arr [ j ] NEW_LINE j += 1 NEW_LINE DEDENT i = ( 1 << p ) NEW_LINE p +=...
Count the number of ways to traverse a Matrix | Find factorial ; Find number of ways to reach mat [ m - 1 ] [ n - 1 ] from mat [ 0 ] [ 0 ] in a matrix mat [ ] [ ] ] ; Driver code ; Function call
def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res *= i NEW_LINE DEDENT return res NEW_LINE DEDENT def countWays ( m , n ) : NEW_LINE INDENT m = m - 1 NEW_LINE n = n - 1 NEW_LINE return ( factorial ( m + n ) // ( factorial ( m ) * factorial ( n ) ) ) NEW_LINE DEDEN...
Matrix Chain Multiplication ( A O ( N ^ 2 ) Solution ) | Matrix Mi has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; For simplicity of the program , one extra row and one extra column are allocated in dp [ ] [ ] . 0 th row and 0 th column of dp [ ] [ ] are not used ; cost is zero when multiplying one matrix . ; Simp...
def MatrixChainOrder ( p , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ i ] = 0 NEW_LINE DEDENT for L in range ( 1 , n - 1 ) : NEW_LINE INDENT for i in range ( n - L ) : NEW_LINE INDENT dp [ i ] [ i + L ] = min ( dp [ i + 1...
Count common subsequence in two strings | return the number of common subsequence in two strings ; for each character of S ; for each character in T ; if character are same in both the string ; Driver Code
def CommomSubsequencesCount ( s , t ) : NEW_LINE INDENT n1 = len ( s ) NEW_LINE n2 = len ( t ) NEW_LINE dp = [ [ 0 for i in range ( n2 + 1 ) ] for i in range ( n1 + 1 ) ] NEW_LINE for i in range ( 1 , n1 + 1 ) : NEW_LINE INDENT for j in range ( 1 , n2 + 1 ) : NEW_LINE INDENT if ( s [ i - 1 ] == t [ j - 1 ] ) : NEW_LINE...
Minimum number of palindromes required to express N as a sum | Set 2 | A utility for creating palindrome ; checks if number of digits is odd or even if odd then neglect the last digit of _input in finding reverse as in case of odd number of digits middle element occur once ; Creates palindrome by just appending reverse...
def createPalindrome ( _input , isOdd ) : NEW_LINE INDENT n = palin = _input NEW_LINE if isOdd : NEW_LINE INDENT n //= 10 NEW_LINE DEDENT while n > 0 : NEW_LINE INDENT palin = palin * 10 + ( n % 10 ) NEW_LINE n //= 10 NEW_LINE DEDENT return palin NEW_LINE DEDENT def generatePalindromes ( N ) : NEW_LINE INDENT palindrom...
Minimum Cost to make two Numeric Strings Identical | Function to find weight of LCS ; if this state is already calculated then return ; adding required weight for particular match ; recurse for left and right child and store the max ; Function to calculate cost of string ; Driver code ; Minimum cost needed to make two ...
def lcs ( dp , a , b , m , n ) : NEW_LINE INDENT for i in range ( 100 ) : NEW_LINE INDENT for j in range ( 100 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT if ( m < 0 or n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ m ] [ n ] != - 1 ) : NEW_LINE INDENT return dp [ m ] [ n ] NEW_LINE DE...
Sum of elements of all partitions of number such that no element is less than K | Function that returns total number of valid partitions of integer N ; Global declaration of 2D dp array which will be later used for memoization ; Initializing 2D dp array with - 1 we will use this 2D array for memoization ; If this subpr...
def countPartitions ( n , k ) : NEW_LINE INDENT dp = [ [ 0 ] * 201 ] * 201 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT if ( dp [ n ] [ k ] >= 0 ) : NEW_LINE INDENT return dp [ n ] [ k ] NEW_LINE DEDENT if ( n < k ) : NEW_LINE...
Number of Co | Python3 program to count the pairs whose sum of digits is co - prime ; Function to find the elements after doing the sum of digits ; Traverse from a to b ; Find the sum of the digits of the elements in the given range one by one ; Function to count the co - prime pairs ; Function to make the pairs by doi...
from math import gcd NEW_LINE def makePairs ( pairs , a , b ) : NEW_LINE INDENT for i in range ( a , b + 1 , 1 ) : NEW_LINE INDENT sumOfDigits = 0 NEW_LINE k = i NEW_LINE while ( k > 0 ) : NEW_LINE INDENT sumOfDigits += k % 10 NEW_LINE k = int ( k / 10 ) NEW_LINE DEDENT if ( sumOfDigits <= 162 ) : NEW_LINE INDENT pairs...
Number of Co | Python3 program to count the pairs whose sum of digits is co - prime ; Recursive function to return the frequency of numbers having their sum of digits i ; Returns 1 or 0 ; Returns value of the dp if already stored ; Loop from digit 0 to 9 ; To change the tight to 1 ; Calling the recursive function to fi...
import math NEW_LINE def recursive ( idx , sum , tight , st , dp , num ) : NEW_LINE INDENT if ( idx == num ) : NEW_LINE INDENT return sum == 0 NEW_LINE DEDENT if ( dp [ idx ] [ tight ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ idx ] [ tight ] [ sum ] NEW_LINE DEDENT ans = 0 NEW_LINE for d in range ( 10 ) : NEW_LIN...
Semiperfect Number | Python3 program to check if the number is semi - perfect or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself...
import math NEW_LINE def factors ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE v . append ( 1 ) NEW_LINE sqt = int ( math . sqrt ( n ) ) NEW_LINE for i in range ( 2 , sqt + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE if ( n // i != i ) : NEW_LINE INDENT v . append ( n // i ) NEW_LINE ...