text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Maximum possible sum of non | Function to find the maximum sum not exceeding K possible by selecting a subset of non - adjacent elements ; Base Case ; Not selecting current element ; If selecting current element is possible ; Return answer ; Driver Code ; Given array arr [ ] ; Given K ; Function Call | def maxSum ( a , n , k ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT option = maxSum ( a , n - 1 , k ) NEW_LINE if ( k >= a [ n - 1 ] ) : NEW_LINE INDENT option = max ( option , a [ n - 1 ] + maxSum ( a , n - 2 , k - a [ n - 1 ] ) ) NEW_LINE DEDENT return option NEW_LINE DEDENT if __name_... |
Count possible binary strings of length N without P consecutive 0 s and Q consecutive 1 s | Function to check if a satisfy the given condition or not ; Stores the length of string ; Stores the previous character of the string ; Stores the count of consecutive equal characters ; Traverse the string ; If current characte... | def checkStr ( str , P , Q ) : NEW_LINE INDENT N = len ( str ) NEW_LINE prev = str [ 0 ] NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str [ i ] == prev ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( prev == '1' and cnt >= Q ) : NEW_LINE INDENT return False NEW_LINE DED... |
Count possible permutations of given array satisfying the given conditions | Function to get the value of binomial coefficient ; Stores the value of binomial coefficient ; Since C ( N , R ) = C ( N , N - R ) ; Calculate the value of C ( N , R ) ; Function to get the count of permutations of the array that satisfy the c... | def binCoff ( N , R ) : NEW_LINE INDENT res = 1 NEW_LINE if ( R > ( N - R ) ) : NEW_LINE INDENT R = ( N - R ) NEW_LINE DEDENT for i in range ( R ) : NEW_LINE INDENT res *= ( N - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def cntPermutation ( N ) : NEW_LINE INDENT C_2N_N = binCoff ( 2 * N ... |
Smallest submatrix with Kth maximum XOR | Function to print smallest index of Kth maximum Xor value of submatrices ; Dimensions of matrix ; Stores XOR values for every index ; Min heap to find the kth maximum XOR value ; Stores indices for corresponding XOR values ; Traversing matrix to calculate XOR values ; Insert ca... | def smallestPosition ( m , k ) : NEW_LINE INDENT n = len ( m ) NEW_LINE mm = len ( m [ 1 ] ) NEW_LINE xor = [ [ 0 for i in range ( mm ) ] for j in range ( n ) ] NEW_LINE minHeap = [ ] NEW_LINE Map = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( mm ) : NEW_LINE INDENT if i - 1 >= 0 : NEW_LINE INDE... |
Length of Longest Palindrome Substring | Function to obtain the length of the longest palindromic substring ; Length of given string ; Stores the maximum length ; Iterate over the string ; Iterate over the string ; Check for palindrome ; If string [ i , j - i + 1 ] is palindromic ; Return length of LPS ; Given string ;... | def longestPalSubstr ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE maxLength = 1 NEW_LINE start = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT for j in range ( i , len ( str ) , 1 ) : NEW_LINE INDENT flag = 1 NEW_LINE for k in range ( ( j - i + 1 ) // 2 ) : NEW_LINE INDENT if ( str [ i + k ] != str ... |
Maximize cost to empty an array by removing contiguous subarrays of equal elements | Initialize dp array ; Function that removes elements from array to maximize the cost ; Base case ; Check if an answer is stored ; Deleting count + 1 i . e . including the first element and starting a new sequence ; Removing [ left + 1 ... | dp = [ [ [ - 1 for x in range ( 101 ) ] for y in range ( 101 ) ] for z in range ( 101 ) ] NEW_LINE def helper ( arr , left , right , count , m ) : NEW_LINE INDENT if ( left > right ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ left ] [ right ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ left ] [ right ] [... |
Minimum cost to convert M to N by repeated addition of its even divisors | Python3 program for the above approach ; Function to find the value of minimum steps to convert m to n ; Base Case ; If n exceeds m ; Iterate through all possible even divisors of m ; If m is divisible by i , then find the minimum cost ; Add the... | inf = 1000000008 NEW_LINE def minSteps ( m , n ) : NEW_LINE INDENT if ( n == m ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( m > n ) : NEW_LINE INDENT return inf NEW_LINE DEDENT min_cost = inf NEW_LINE for i in range ( 2 , m , 2 ) : NEW_LINE INDENT if ( m % i == 0 ) : NEW_LINE INDENT min_cost = min ( min_cost , m /... |
Represent a number as the sum of positive numbers ending with 9 | Function to find the minimum count of numbers ending with 9 to form N ; Extract last digit of N ; Calculate the last digit ; If the last digit satisfies the condition ; Driver Code | def minCountOfNumbers ( N ) : NEW_LINE INDENT k = N % 10 NEW_LINE z = N - ( 9 * ( 9 - k ) ) NEW_LINE if ( z >= 9 and z % 10 == 9 ) : NEW_LINE INDENT return 10 - k NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 156 NEW_LINE print ( minCountO... |
Binary Matrix after flipping submatrices in given range for Q queries | Function to flip a submatrices ; Boundaries of the submatrix ; Iterate over the submatrix ; Check for 1 or 0 and flip accordingly ; Function to perform the queries ; Driver Code ; Function call | def manipulation ( matrix , q ) : NEW_LINE INDENT x1 , y1 , x2 , y2 = q NEW_LINE for i in range ( x1 - 1 , x2 ) : NEW_LINE INDENT for j in range ( y1 - 1 , y2 ) : NEW_LINE INDENT if matrix [ i ] [ j ] : NEW_LINE INDENT matrix [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT matrix [ i ] [ j ] = 1 NEW_LINE DEDENT ... |
Minimum repeated addition of even divisors of N required to convert N to M | INF is the maximum value which indicates Impossible state ; Recursive Function that considers all possible even divisors of cur ; Indicates impossible state ; Return 0 if cur == M ; Initially it is set to INF that means we can 't transform cur... | INF = int ( 1e7 ) ; 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 op = int ( INF ) ; NEW_LINE for i in range ( 2 , int ( cur ** 1 / 2 ) + 1 ) : NEW_LINE INDENT if ( cur % i == 0 ) : NEW_LINE IN... |
Minimum length of subsequence having unit GCD | Function that finds the prime factors of a number ; To store the prime factor ; 2 s that divide n ; N must be odd at this point Skip one element ; Update the prime factor ; If n is a prime number greater than 2 ; Function that finds the shortest subsequence ; Check if the... | def findPrimeFactors ( n ) : NEW_LINE INDENT primeFactors = [ 0 for i in range ( 9 ) ] NEW_LINE j = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT primeFactors [ j ] = 2 NEW_LINE j += 1 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n >>= 1 NEW_LINE DEDENT DEDENT i = 3 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT i... |
Maximum sum of Bitwise XOR of all elements of two equal length subsets | Function that finds the maximum Bitwise XOR sum of the two subset ; Check if the current state is already computed ; Initialize answer to minimum value ; Iterate through all possible pairs ; Check whether ith bit and jth bit of mask is not set the... | def xorSum ( a , n , mask , dp ) : NEW_LINE INDENT if ( dp [ mask ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] NEW_LINE DEDENT max_value = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( i != j and ( mask & ( 1 << i ) ) == 0 and ( mask & ( 1 << j ) ) == 0 ) : NEW... |
Count of ways in which N can be represented as sum of Fibonacci numbers without repetition | Python3 program for the above approach ; Function to generate the fibonacci number ; First two number of fibonacci sqequence ; Function to find maximum ways to represent num as the sum of fibonacci number ; Generate the Canonic... | fib = [ 0 ] * 101 NEW_LINE dp1 = [ 0 ] * 101 NEW_LINE dp2 = [ 0 ] * 101 NEW_LINE v = [ 0 ] * 101 NEW_LINE def fibonacci ( ) : NEW_LINE INDENT fib [ 1 ] = 1 NEW_LINE fib [ 2 ] = 2 NEW_LINE for i in range ( 3 , 87 + 1 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DEDENT def find ( num ) : ... |
Count of N | Function to find count of N - digit numbers with single digit XOR ; Range of numbers ; Calculate XOR of digits ; If XOR <= 9 , then increment count ; Print the count ; Given number ; Function call | def countNums ( N ) : NEW_LINE INDENT l = pow ( 10 , N - 1 ) NEW_LINE r = pow ( 10 , N ) - 1 NEW_LINE count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT xorr = 0 NEW_LINE temp = i NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT xorr = xorr ^ ( temp % 10 ) NEW_LINE temp //= 10 NEW_LINE DEDENT if ( xorr <= 9... |
Maximize length of Non | Python3 program to implement the above approach ; Function to find the maximum length non decreasing subarray by reversing at most one subarray ; dp [ i ] [ j ] be the longest subsequence of a [ 0. . . i ] with first j parts ; Maximum length sub - sequence of ( 0. . ) ; Maximum length sub - seq... | import sys NEW_LINE def main ( arr , n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( n ) ] for y in range ( 4 ) ] NEW_LINE if arr [ 0 ] == 0 : NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW... |
Print the Maximum Subarray Sum | Function to print the elements of Subarray with maximum sum ; Initialize currMax and globalMax with first value of nums ; Iterate for all the elemensts of the array ; Update currMax ; Check if currMax is greater than globalMax ; Traverse in left direction to find start Index of subarray... | def SubarrayWithMaxSum ( nums ) : NEW_LINE INDENT currMax = nums [ 0 ] NEW_LINE globalMax = nums [ 0 ] NEW_LINE for i in range ( 1 , len ( nums ) ) : NEW_LINE INDENT currMax = max ( nums [ i ] , nums [ i ] + currMax ) NEW_LINE if ( currMax > globalMax ) : NEW_LINE INDENT globalMax = currMax NEW_LINE endIndex = i NEW_LI... |
Count of distinct Primonacci Numbers in a given range [ L , R ] | Python3 implementation of the above approach ; Stores list of all primes ; Function to find all primes ; To mark the prime ones ; Initially all indices as prime ; If i is prime ; Set all multiples of i as non - prime ; Adding all primes to a list ; Funct... | M = 100005 NEW_LINE primes = [ ] NEW_LINE def sieve ( ) : NEW_LINE INDENT mark = [ False ] * M NEW_LINE for i in range ( 2 , M ) : NEW_LINE INDENT mark [ i ] = True NEW_LINE DEDENT i = 2 NEW_LINE while i * i < M : NEW_LINE INDENT if ( mark [ i ] ) : NEW_LINE INDENT j = i * i NEW_LINE while j < M : NEW_LINE INDENT mark ... |
Queries to count distinct Binary Strings of all lengths from N to M satisfying given properties | Python3 program to implement the above approach ; Function to calculate the count of possible strings ; Initialize dp [ 0 ] ; dp [ i ] represents count of strings of length i ; Add dp [ i - k ] if i >= k ; Update Prefix Su... | N = int ( 1e5 + 5 ) NEW_LINE MOD = 1000000007 NEW_LINE dp = [ 0 ] * N NEW_LINE def countStrings ( K , Q ) : NEW_LINE INDENT dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE if ( i >= K ) : NEW_LINE INDENT dp [ i ] = ( dp [ i ] + dp [ i - K ] ) % MOD NEW_LINE DEDENT DEDEN... |
Minimum possible sum of prices of a Triplet from the given Array | Python3 program to implement the above approach ; Function to minimize the sum of price by taking a triplet ; Initialize a dp [ ] list ; Stores the final result ; Iterate for all values till N ; Check if num [ j ] > num [ i ] ; Update dp [ j ] if it is ... | import sys ; NEW_LINE def minSum ( n , num , price ) : NEW_LINE INDENT dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = sys . maxsize NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( num [ j ... |
Count of binary strings of length N having equal count of 0 ' s β and β 1' s and count of 1 ' s β Γ’ β° Β₯ β count β of β 0' s in each prefix substring | Function to calculate and returns the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * (... | def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def countStrings ( N ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE ... |
Number of ways to cut a stick of length N into in even length at most K units long pieces | Recursive function to count the total number of ways ; Base case if no - solution exist ; Condition if a solution exist ; Check if already calculated ; Initialize counter ; Recursive call ; Store the answer ; Return the answer ;... | def solve ( n , k , mod , dp ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 2 , k + 1 , 2 ) : NEW_LINE INDENT cnt = ( ( cnt % m... |
Number of ways to select exactly K even numbers from given Array | Python3 program for the above approach ; Function for calculating factorial ; Factorial of n defined as : n ! = n * ( n - 1 ) * ... * 1 ; Function to find the number of ways to select exactly K even numbers from the given array ; Count even numbers ; Ch... | f = [ 0 ] * 12 NEW_LINE def fact ( ) : NEW_LINE INDENT f [ 0 ] = f [ 1 ] = 1 NEW_LINE for i in range ( 2 , 11 ) : NEW_LINE INDENT f [ i ] = i * 1 * f [ i - 1 ] NEW_LINE DEDENT DEDENT def solve ( arr , n , k ) : NEW_LINE INDENT fact ( ) NEW_LINE even = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2... |
Count of binary strings of length N having equal count of 0 ' s β and β 1' s | Python3 program to implement the above approach ; Function to calculate C ( n , r ) % MOD DP based approach ; Corner case ; Stores the last row of Pascal 's Triangle ; Initialize top row of pascal triangle ; Construct Pascal 's Triangle fro... | MOD = 1000000007 NEW_LINE def nCrModp ( n , r ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT C = [ 0 ] * ( r + 1 ) NEW_LINE C [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , r ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = ( C [ j ] + C [ j - 1... |
Convert 1 into X in min steps by multiplying with 2 or 3 or by adding 1 | Function to print the Minimum number of operations required to convert 1 into X by using three given operations ; Initialize a DP array to store min operations for sub - problems ; Base Condition : No operation required when N is 1 ; Multiply the... | def printMinOperations ( N ) : NEW_LINE INDENT dp = [ N ] * ( N + 1 ) NEW_LINE dp [ 1 ] = 0 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 and dp [ i ] > dp [ i // 2 ] + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i // 2 ] + 1 NEW_LINE DEDENT if ( i % 3 == 0 and dp [ i ] > dp [ i // 3 ] + 1 ) : NEW_L... |
Largest subsequence such that all indices and all values are multiples individually | Python3 program for the above approach ; Function that print maximum length of array ; dp [ ] array to store the maximum length ; Find all divisors of i ; If the current value is greater than the divisor 's value ; If current value is... | from math import * NEW_LINE def maxLength ( arr , n ) : NEW_LINE INDENT dp = [ 1 ] * n NEW_LINE for i in range ( n - 1 , 1 , - 1 ) : NEW_LINE INDENT for j in range ( 1 , int ( sqrt ( i ) ) + 1 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT s = i // j NEW_LINE if ( s == j ) : NEW_LINE INDENT if ( arr [ i ] > ar... |
Maximum profit by buying and selling a stock at most twice | Set 2 | Python3 implmenetation to find maximum possible profit with at most two transactions ; Function to find the maximum profit with two transactions on a given list of stock prices ; Set initial buying values to INT_MAX as we want to minimize it ; Set ini... | import sys NEW_LINE def maxProfit ( price , n ) : NEW_LINE INDENT buy1 , buy2 = sys . maxsize , sys . maxsize NEW_LINE profit1 , profit2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT buy1 = min ( buy1 , price [ i ] ) NEW_LINE profit1 = max ( profit1 , price [ i ] - buy1 ) NEW_LINE buy2 = min ( buy2 , price [ ... |
Maximum score of deleting an element from an Array based on given condition | Python3 implementation to find the maximum score of the deleting a element from an array ; Function to find the maximum score of the deleting an element from an array ; Creating a map to keep the frequency of numbers ; Loop to iterate over th... | from collections import defaultdict NEW_LINE def findMaximumScore ( a , n ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT dp = [ 0 ] * ( max ( a ) + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = freq [ 1 ] NEW_LINE for i in range ( 2 ,... |
Reverse a subarray to maximize sum of even | Function to return maximized sum at even indices ; Stores difference with element on the left ; Stores difference with element on the right ; Compute and store left difference ; For first index ; If previous difference is positive ; Otherwise ; For the last index ; Otherwise... | def maximizeSum ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT leftDP = [ 0 ] * ( n ) NEW_LINE rightDP = [ 0 ] * ( n ) NEW_LINE c = 0 NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT leftDiff = arr [ i ] - arr [ ... |
Count of all subsequences having adjacent elements with different parity | Function to find required subsequences ; Initialise the dp [ ] [ ] with 0. ; If odd element is encountered ; Considering i - th element will be present in the subsequence ; Appending i - th element to all non - empty subsequences ending with eve... | def validsubsequences ( arr , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] % 2 ) : NEW_LINE INDENT dp [ i ] [ 1 ] += 1 NEW_LINE dp [ i ] [ 1 ] += dp [ i - 1 ] [ 0 ] NEW_LINE dp [ i ] [ 1 ] += dp [ i - 1 ] [ ... |
Count of N | Function to return count of N - digit numbers with absolute difference of adjacent digits not exceeding K ; For 1 - digit numbers , the count is 10 ; dp [ i ] [ j ] stores the count of i - digit numbers ending with j ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than... | def getCount ( n , k ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 10 NEW_LINE DEDENT dp = [ [ 0 for x in range ( 11 ) ] for y in range ( n + 1 ) ] ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , 10 ) ... |
Find if there is a path between two vertices in a directed graph | Set 2 | Python3 program to find if there is a path between two vertices in a directed graph using Dynamic Programming ; Function to find if there is a path between two vertices in a directed graph ; dp matrix ; Set dp [ i ] [ j ] = true if there is edge... | X = 6 NEW_LINE Z = 2 NEW_LINE def existPath ( V , edges , u , v ) : NEW_LINE INDENT mat = [ [ False for i in range ( V ) ] for j in range ( V ) ] NEW_LINE for i in range ( X ) : NEW_LINE INDENT mat [ edges [ i ] [ 0 ] ] [ edges [ i ] [ 1 ] ] = True NEW_LINE DEDENT for k in range ( V ) : NEW_LINE INDENT for i in range (... |
Maximize the numbers of splits in an Array having sum divisible by 3 | Python3 program for above approach ; prefix array storing right most index with prefix sums 0 , 1 , 2 ; dp array ; current prefix sum ; Calculating the prefix sum modulo 3 ; We dont have a left pointer with prefix sum C ; We cannot consider i as a r... | def calculate_maximum_splits ( arr , N ) : NEW_LINE INDENT pre = [ 0 , - 1 , - 1 ] NEW_LINE dp = [ 0 for i in range ( N ) ] NEW_LINE C = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT C = C + arr [ i ] NEW_LINE C = C % 3 NEW_LINE if pre [ C ] == - 1 : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE DEDENT else : NE... |
Count of elements having Euler 's Totient value one less than itself | Python3 program for the above approach ; Seiev of Erotosthenes method to compute all primes ; If current number is marked prime then mark its multiple as non - prime ; Function to count the number of element satisfying the condition ; Compute the nu... | prime = [ 0 ] * ( 1000001 ) NEW_LINE def seiveOfEratosthenes ( ) : NEW_LINE INDENT for i in range ( 2 , 1000001 ) : NEW_LINE INDENT prime [ i ] = 1 NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i < 1000001 ) : NEW_LINE INDENT if ( prime [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i * i , 1000001 , i ) : NEW_LINE INDEN... |
Count of elements having odd number of divisors in index range [ L , R ] for Q queries | Python3 program for the above approach ; Function count the number of elements having odd number of divisors ; Initialise dp [ ] array ; Precomputation ; Find the Prefix Sum ; Iterate for each query ; Find the answer for each query... | import math NEW_LINE def OddDivisorsCount ( n , q , a , Query ) : NEW_LINE INDENT DP = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = int ( math . sqrt ( a [ i ] ) ) ; NEW_LINE if ( x * x == a [ i ] ) : NEW_LINE INDENT DP [ i ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_... |
Find all possible ways to Split the given string into Primes | Python 3 program to Find all the ways to split the given string into Primes . ; Sieve of Eratosthenes ; Function Convert integer to binary string ; Function print all the all the ways to split the given string into Primes . ; To store all possible strings ;... | primes = [ True ] * 1000001 NEW_LINE maxn = 1000000 NEW_LINE def sieve ( ) : NEW_LINE INDENT primes [ 0 ] = primes [ 1 ] = 0 NEW_LINE i = 2 NEW_LINE while i * i <= maxn : NEW_LINE INDENT if ( primes [ i ] ) : NEW_LINE INDENT for j in range ( i * i , maxn + 1 , i ) : NEW_LINE INDENT primes [ j ] = False NEW_LINE DEDENT ... |
Count of subsequences of length 4 in form ( x , x , x + 1 , x + 1 ) | Set 2 | Function to count the numbers ; Array that stores the digits from left to right ; Array that stores the digits from right to left ; Initially both array store zero ; Fill the table for count1 array ; Update the count of current character ; Fi... | def countStableNum ( Str , N ) : NEW_LINE INDENT count1 = [ [ 0 for j in range ( 10 ) ] for i in range ( N ) ] NEW_LINE count2 = [ [ 0 for j in range ( 10 ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count1 [ i ] [ j ] , count2 [ i ] [ j ] = 0 , 0 NE... |
Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H | Function that prints the number of times X gets a value between L and R ; Base condition ; Condition if X can be made equal to j after i additions ; Compute value of X after adding arr [ i ] ; Compute value of X afte... | def goodInteger ( arr , n , h , l , r ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( h ) ] for j in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( h ) : NEW_LINE INDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT h1 = ( j + arr [ i ] ) % h NEW_LINE h... |
Longest subarray whose elements can be made equal by maximum K increments | Function to find maximum possible length of subarray ; Stores the sum of elements that needs to be added to the sub array ; Stores the index of the current position of subarray ; Stores the maximum length of subarray . ; Maximum element from ea... | def validSubArrLength ( arr , N , K ) : NEW_LINE INDENT dp = [ 0 for i in range ( N + 1 ) ] NEW_LINE pos = 0 NEW_LINE ans = 0 NEW_LINE mx = 0 NEW_LINE pre = 0 NEW_LINE q = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT while ( len ( q ) and arr [ len ( q ) - 1 ] < arr [ i ] ) : NEW_LINE INDENT q . remove ( q [ len... |
Partition of a set into K subsets with equal sum using BitMask and DP | Function to check whether K required partitions are possible or not ; Return true as the entire array is the answer ; If total number of partitions exceeds size of the array ; If the array sum is not divisible by K ; No such partitions are possible... | def isKPartitionPossible ( arr , N , K ) : NEW_LINE INDENT if ( K == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( N < K ) : NEW_LINE INDENT return False NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % K != 0 ) : NEW_LINE INDENT return False N... |
Minimum cost path in a Matrix by moving only on value difference of X | Python3 implementation to find the minimum number of operations required to move from ( 1 , 1 ) to ( N , M ) ; Function to find the minimum operations required to move to bottom - right cell of matrix ; Condition to check if the current cell is the... | MAX = 1e18 NEW_LINE v = [ [ 0 , 0 ] ] * ( 151 ) NEW_LINE dp = [ [ - 1 for i in range ( 151 ) ] for i in range ( 151 ) ] NEW_LINE def min_operation ( i , j , val , x ) : NEW_LINE INDENT if ( i == n - 1 and j == m - 1 ) : NEW_LINE INDENT if ( val > v [ i ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = MAX NEW_LINE return MA... |
Minimum count of numbers required from given array to represent S | Python3 implementation to find the minimum number of sequence required from array such that their sum is equal to given S ; Function to find the minimum elements required to get the sum of given value S ; Condition if the sequence is found ; Condition ... | import sys NEW_LINE def printAllSubsetsRec ( arr , n , v , Sum ) : NEW_LINE INDENT if ( Sum == 0 ) : NEW_LINE INDENT return len ( v ) NEW_LINE DEDENT if ( Sum < 0 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT x = printAllSubsetsRec ( arr , ... |
Minimum count of numbers required from given array to represent S | Function to find the count of minimum length of the sequence ; Loop to initialize the array as infinite in the row 0 ; Loop to find the solution by pre - computation for the sequence ; Minimum possible for the previous minimum value of the sequence ; D... | def Count ( S , m , n ) : NEW_LINE INDENT table = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT table [ 0 ] [ i ] = 10 ** 9 - 1 NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( S [ i -... |
Maximize product of same | Python3 implementation to maximize product of same - indexed elements of same size subsequences ; Utility function to find the maximum ; Utility function to find the maximum scalar product from the equal length sub - sequences taken from the two given array ; Return a very small number if ind... | INF = 10000000 NEW_LINE def maximum ( A , B , C , D ) : NEW_LINE INDENT return max ( max ( A , B ) , max ( C , D ) ) NEW_LINE DEDENT def maxProductUtil ( X , Y , A , B , dp ) : NEW_LINE INDENT if ( X < 0 or Y < 0 ) : NEW_LINE INDENT return - INF NEW_LINE DEDENT if ( dp [ X ] [ Y ] != - 1 ) : NEW_LINE INDENT return dp [... |
Check if one string can be converted to other using given operation | Function that prints whether is it possible to make a equal to T by performing given operations ; Base case , if we put the last character at front of A ; Base case , if we put the last character at back of A ; Condition if current sequence is matcha... | def twoStringsEquality ( s , t ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n ) ] NEW_LINE if ( s [ n - 1 ] == t [ 0 ] ) : NEW_LINE INDENT dp [ n - 1 ] [ 1 ] = 1 NEW_LINE DEDENT if ( s [ n - 1 ] == t [ n - 1 ] ) : NEW_LINE INDENT dp [ n - 1 ] [ 0 ] = 1 NEW_LINE DEDEN... |
Maximize sum of all elements which are not a part of the Longest Increasing Subsequence | Function to find maximum sum ; Find total sum of array ; Maintain a 2D array ; Update the dp array along with sum in the second row ; In case of greater length update the length along with sum ; In case of equal length find length... | def findSum ( arr , n ) : NEW_LINE INDENT totalSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT dp = [ [ 0 ] * n for i in range ( 2 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE dp [ 1 ] [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 ,... |
Count of possible permutations of a number represented as a sum of 2 ' s , β 4' s and 6 's only | Returns number of ways to reach score n ; table [ i ] will store count of solutions for value i . ; Initialize all table values as 0 ; Base case ( If given value is 0 , 1 , 2 , or 4 ) ; Driver Code | def count ( n ) : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( n == 4 ) : NEW_LINE INDENT return 2 ; NEW_LINE DEDENT elif ( n == 6 ) : NEW_LINE INDENT return 4 ; NEW_LINE DEDENT table = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT table [ i ] = 0 ; NEW_LIN... |
Count of ways to split a given number into prime segments | Python3 implementation to count total number of ways to split a string to get prime numbers ; Function to check whether a number is a prime number or not ; Function to find the count of ways to split string into prime numbers ; 1 based indexing ; Consider ever... | MOD = 1000000007 NEW_LINE def isPrime ( number ) : NEW_LINE INDENT num = int ( number ) NEW_LINE i = 2 NEW_LINE while i * i <= num : NEW_LINE INDENT if ( ( num % i ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if num > 1 : NEW_LINE return True NEW_LINE else : NEW_LINE return False NEW_L... |
Count of ways to split a given number into prime segments | Python3 implementation to count total number of ways to split a String to get prime numbers ; Function to build sieve ; If p is a prime ; Update all multiples of p as non prime ; Function to check whether a number is a prime number or not ; Function to find th... | MOD = 1000000007 NEW_LINE sieve = [ 0 ] * ( 1000000 ) NEW_LINE def buildSieve ( ) : NEW_LINE INDENT for i in range ( len ( sieve ) ) : NEW_LINE INDENT sieve [ i ] = True NEW_LINE DEDENT sieve [ 0 ] = False NEW_LINE sieve [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= 1000000 : NEW_LINE INDENT if sieve [ p ] == Tr... |
Check if a matrix contains a square submatrix with 0 as boundary element | Function checks if square with all 0 's in boundary exists in the matrix ; r1 is the top row , c1 is the left col r2 is the bottom row , c2 is the right ; Function checks if the boundary of the square consists of 0 's ; Driver Code | def squareOfZeroes ( ) : NEW_LINE INDENT global matrix , cache NEW_LINE lastIdx = len ( matrix ) - 1 NEW_LINE return hasSquareOfZeroes ( 0 , 0 , lastIdx , lastIdx ) NEW_LINE DEDENT def hasSquareOfZeroes ( r1 , c1 , r2 , c2 ) : NEW_LINE INDENT global matrix , cache NEW_LINE if ( r1 >= r2 or c1 >= c2 ) : NEW_LINE INDENT ... |
Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | Python3 program to calculate the number of ways ; Initialising the array with zeros . You can do using memset too . ; Printing the array ; Driver code | def CountWays ( a , b , c ) : NEW_LINE INDENT x = b + c + 1 ; NEW_LINE arr = [ 0 ] * x ; NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT for j in range ( b , c + 1 ) : NEW_LINE INDENT arr [ i + j ] += 1 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , x ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_L... |
Number of ways to obtain each numbers in range [ 1 , b + c ] by adding any two numbers in range [ a , b ] and [ b , c ] | Python3 program to calculate the number of ways ; 2 is added because sometimes we will decrease the value out of bounds . ; Initialising the array with zeros . ; Printing the array ; Driver code | def CountWays ( a , b , c ) : NEW_LINE INDENT x = b + c + 2 ; NEW_LINE arr = [ 0 ] * x ; NEW_LINE for i in range ( 1 , b + 1 ) : NEW_LINE arr [ i + b ] = arr [ i + b ] + 1 ; NEW_LINE arr [ i + c + 1 ] = arr [ i + c + 1 ] - 1 ; NEW_LINE for i in range ( 1 , x - 1 ) : NEW_LINE arr [ i ] += arr [ i - 1 ] ; NEW_LINE print ... |
Count of distinct possible strings after performing given operations | Function that prints the number of different strings that can be formed ; Computing the length of the given string ; Base case ; Traverse the given string ; If two consecutive 1 ' s β β or β 2' s are present ; Otherwise take the previous value ; Dri... | def differentStrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = dp [ 1 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] and ( s [ i ] == '1' or s [ i ] == '2' ) ) : NEW_LINE INDENT dp [ i + 1 ] = dp [ i ] + dp [ i - 1 ] NEW_LINE DEDENT ... |
Sum of cost of all paths to reach a given cell in a Matrix | Python3 implementation to find the sum of cost of all paths to reach ( M , N ) ; Function for computing combination ; Function to find the factorial of N ; Loop to find the factorial of a given number ; Function for coumputing the sum of all path cost ; Loop ... | Col = 3 ; NEW_LINE def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT res = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def sumPathCost ( grid , m , n ) : ... |
Count numbers in a range with digit sum divisible by K having first and last digit different | Python3 program to count numbers in a range with digit sum divisible by K having first and last digit different ; For calculating the upper bound of the sequence . ; Checking whether the sum of digits = 0 or not and the corne... | K = 0 NEW_LINE N = 0 NEW_LINE v = [ ] NEW_LINE dp = [ [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for k in range ( 10 ) ] for l in range ( 1000 ) ] for m in range ( 20 ) ] NEW_LINE def init ( x ) : NEW_LINE INDENT global K NEW_LINE global N NEW_LINE global v NEW_LINE v = [ ] NEW_LINE while ( x > 0 ) : NEW... |
Split a binary string into K subsets minimizing sum of products of occurrences of 0 and 1 | Python3 program to split a given String into K segments such that the sum of product of occurence of characters in them is minimized ; Function to return the minimum sum of products of occurences of 0 and 1 in each segments ; St... | import sys NEW_LINE def minSumProd ( S , K ) : NEW_LINE INDENT Len = len ( S ) ; NEW_LINE if ( K > Len ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( K == Len ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT dp = [ 0 ] * Len ; NEW_LINE count_zero = 0 ; NEW_LINE count_one = 0 ; NEW_LINE for j in range ( 0 , Len , 1... |
Minimize prize count required such that smaller value gets less prize in an adjacent pair | Function to find the minimum number of required such that adjacent smaller elements gets less number of prizes ; Loop to compute the smaller elements at the left ; Loop to find the smaller elements at the right ; Loop to find th... | def minPrizes ( arr , n ) : NEW_LINE INDENT dpLeft = [ 0 ] * n NEW_LINE dpLeft [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] > arr [ i - 1 ] : NEW_LINE INDENT dpLeft [ i ] = dpLeft [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dpLeft [ i ] = 1 NEW_LINE DEDENT DEDENT dpRight = [ 0 ] * n N... |
Maximum sum subsequence with values differing by at least 2 | Python3 program to find maximum sum subsequence with values differing by at least 2 ; Function to find maximum sum subsequence such that two adjacent values elements are not selected ; Map to store the frequency of array elements ; Make a dp array to store a... | from collections import defaultdict NEW_LINE def get_max_sum ( arr , n ) : NEW_LINE INDENT freq = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT dp = [ 0 ] * 100001 NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = freq [ 0 ] NEW_LINE for i in range ( 2 , 1000... |
Minimum flips required to keep all 1 s together in a Binary string | Python implementation for Minimum number of flips required in a binary string such that all the 1 aTMs are together ; Length of the binary string ; Initial state of the dp dp [ 0 ] [ 0 ] will be 1 if the current bit is 1 and we have to flip it ; Initi... | def minFlip ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE dp = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = int ( a [ 0 ] == '1' ) NEW_LINE dp [ 0 ] [ 1 ] = int ( a [ 0 ] == '0' ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + int ( a [ i ] == '1' ) NEW_LINE d... |
Length of longest increasing index dividing subsequence | Function to find the length of the longest increasing sub - sequence such that the index of the element is divisible by index of previous element ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Traverse the given array ; If the ind... | def LIIDS ( arr , N ) : NEW_LINE INDENT dp = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT dp . append ( 1 ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT j = i + i NEW_LINE while j <= N : NEW_LINE INDENT if j < N and i < N and arr [ j ] > arr [ i ] : NEW_LINE INDENT dp [... |
Count of subarrays having exactly K perfect square numbers | Python3 program to count of subarrays having exactly K perfect square numbers . ; A utility function to check if the number n is perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to find number o... | from collections import defaultdict NEW_LINE import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def findSubarraySum ( arr , n , K ) : NEW_LINE INDENT prevSum = defaultdict ( int ) NEW_LINE res = 0 NEW_LINE currsum... |
Number of ways to split N as sum of K numbers from the given range | Python3 implementation to count the number of ways to divide N in K groups such that each group has elements in range [ L , R ] ; Function to count the number of ways to divide the number N in K groups such that each group has number of elements in ra... | mod = 1000000007 NEW_LINE def calculate ( pos , left , k , L , R ) : NEW_LINE INDENT if ( pos == k ) : NEW_LINE INDENT if ( left == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( left == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT answer = 0 NEW_LINE for i ... |
Check if it is possible to get given sum by taking one element from each row | Function that prints whether is it possible to make sum equal to K ; Base case ; Condition if we can make sum equal to current column by using above rows ; Iterate through current column and check whether we can make sum less than or equal t... | def PossibleSum ( n , m , v , k ) : NEW_LINE INDENT dp = [ [ 0 ] * ( k + 1 ) for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( k + 1 ) : NEW_LINE INDENT if dp [ i ] [ j ] == 1 : NEW_LINE INDENT for d in range ( m ) : NEW_LINE INDENT if ( j + v [ i ] ... |
Modify array by merging elements with addition such that it consists of only Primes . | DP array to store the ans for max 20 elements ; To check whether the number is prime or not ; Function to check whether the array can be modify so that there are only primes ; If curr is prime and all elements are visited , return t... | dp = [ 0 ] * ( 1 << 20 ) NEW_LINE def isprime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def solve ( arr , curr , mask , n ) : NEW_... |
Maximum sum in circular array such that no two elements are adjacent | Set 2 | Store the maximum possible at each index ; When i exceeds the index of the last element simply return 0 ; If the value has already been calculated , directly return it from the dp array ; The next states are don 't take this element and go ... | dp = [ ] NEW_LINE def maxSum ( i , subarr ) : NEW_LINE INDENT if ( i >= len ( subarr ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] != - 1 ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT dp [ i ] = max ( maxSum ( i + 1 , subarr ) , subarr [ i ] + maxSum ( i + 2 , subarr ) ) NEW_LINE return dp [ i ] NE... |
Count all square sub | Python3 program to count total number of k x k sub matrix whose sum is greater than the given number S ; Function to create prefix sum matrix from the given matrix ; Store first value in table ; Initialize first row of matrix ; Initialize first column of matrix ; Initialize rest table with sum ; ... | dim = 5 NEW_LINE def createTable ( mtrx , k , p , dp ) : NEW_LINE INDENT dp [ 0 ] [ 0 ] = mtrx [ 0 ] [ 0 ] NEW_LINE for j in range ( 1 , dim ) : NEW_LINE INDENT dp [ 0 ] [ j ] = mtrx [ 0 ] [ j ] + dp [ 0 ] [ j - 1 ] NEW_LINE DEDENT for i in range ( 1 , dim ) : NEW_LINE INDENT dp [ i ] [ 0 ] = mtrx [ i ] [ 0 ] + dp [ i ... |
Word Break Problem | DP | Unordered_map used for storing the sentences the key string can be broken into ; Unordered_set used to store the dictionary . ; Utility function used for printing the obtained result ; Utility function for appending new words to already existing strings ; Loop to find the append string which c... | mp = dict ( ) NEW_LINE dict_t = set ( ) NEW_LINE def printResult ( A ) : NEW_LINE INDENT for i in range ( len ( A ) ) : NEW_LINE INDENT print ( A [ i ] ) NEW_LINE DEDENT DEDENT def combine ( prev , word ) : NEW_LINE INDENT for i in range ( len ( prev ) ) : NEW_LINE INDENT prev [ i ] += " β " + word ; NEW_LINE DEDENT re... |
Maximize product of digit sum of consecutive pairs in a subsequence of length K | Python3 implementation to find the maximum product of the digit sum of the consecutive pairs of the subsequence of the length K ; Function to find the product of two numbers digit sum in the pair ; Loop to find the digits of the number ; ... | import sys NEW_LINE MAX = 100 NEW_LINE dp = [ ] NEW_LINE for i in range ( 1000 ) : NEW_LINE INDENT temp1 = [ ] NEW_LINE for j in range ( MAX ) : NEW_LINE INDENT temp2 = [ ] NEW_LINE for k in range ( MAX ) : NEW_LINE INDENT temp2 . append ( 0 ) NEW_LINE DEDENT temp1 . append ( temp2 ) NEW_LINE DEDENT dp . append ( temp1... |
Count minimum factor jumps required to reach the end of an Array | vector to store factors of each integer ; dp array ; Precomputing all factors of integers from 1 to 100000 ; Function to count the minimum jumps ; If we reach the end of array , no more jumps are required ; If the jump results in out of index , return I... | factors = [ [ ] for i in range ( 100005 ) ] ; NEW_LINE dp = [ 0 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 ( arr , k... |
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Python3 program to find the maximum distance from a 0 - cell to a 1 - cell ; If the matrix consists of only 0 ' s β β or β only β 1' s ; If it 's a 0-cell ; Calculate its distance with every 1 - cell ; Compare and store the minimum ; Co... | def maxDistance ( grid ) : NEW_LINE INDENT one = [ ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE ans = - 1 NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE if ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT one . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT if ( one == [... |
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Function to find the maximum distance ; Queue to store all 1 - cells ; Grid dimensions ; Directions traversable from a given a particular cell ; If the grid contains only 0 s or only 1 s ; Access every 1 - cell ; Traverse all possible d... | def maxDistance ( grid ) : NEW_LINE INDENT q = [ ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE ans = - 1 NEW_LINE dirs = [ [ 0 , 1 ] , [ 1 , 0 ] , [ 0 , - 1 ] , [ - 1 , 0 ] ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( grid [ i ] [ j ] == 1 ) : NEW_... |
Count the number of ways to give ranks for N students such that same ranks are possible | Python3 program to calculate the number of ways to give ranks for N students such that same ranks are possible ; Initializing a table in order to store the bell triangle ; Function to calculate the K - th bell number ; If we have ... | mod = 1e9 + 7 NEW_LINE dp = [ [ - 1 for x in range ( 6 ) ] for y in range ( 6 ) ] NEW_LINE def f ( n , k ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( k == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] [ k ] != - ... |
Print all Longest dividing subsequence in an Array | Function to print LDS [ i ] element ; Traverse the Max [ ] ; Function to construct and print Longest Dividing Subsequence ; 2D vector for storing sequences ; Push the first element to LDS [ ] [ ] ; Interate over all element ; Loop for every index till i ; If current ... | def printLDS ( Max ) : NEW_LINE INDENT for it in Max : NEW_LINE INDENT print ( it , end = " β " ) NEW_LINE DEDENT DEDENT def LongestDividingSeq ( arr , N ) : NEW_LINE INDENT LDS = [ [ ] for i in range ( N ) ] NEW_LINE LDS [ 0 ] . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( ... |
Count the number of ordered sets not containing consecutive numbers | Function to calculate the count of ordered set for a given size ; Base cases ; Function returns the count of all ordered sets ; Prestore the factorial value ; Iterate all ordered set sizes and find the count for each one maximum ordered set size will... | def CountSets ( x , pos ) : NEW_LINE INDENT if ( x <= 0 ) : NEW_LINE INDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT answer = ( CountSets ( x - 1 , pos ) + CountSets ( x - 2 , pos - 1 ) ) ... |
Maximum sum such that exactly half of the elements are selected and no two adjacent | Python3 program to find maximum sum possible such that exactly floor ( N / 2 ) elements are selected and no two selected elements are adjacent to each other ; Function return the maximum sum possible under given condition ; Intitialis... | import sys NEW_LINE def MaximumSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( 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 ] = - sys . maxsize - 1 NEW_LINE DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE I... |
Check if N can be converted to the form K power K by the given operation | Python3 implementation to Check whether a given number N can be converted to the form K power K by the given operation ; Function to check if N can be converted to K power K ; Check if n is of the form k ^ k ; Iterate through each digit of n ; C... | kPowKform = dict ( ) NEW_LINE def func ( n ) : NEW_LINE INDENT global kPowKform NEW_LINE if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n in kPowKform ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT answer = 0 NEW_LINE x = n NEW_LINE while ( x > 0 ) : NEW_LINE INDENT d = x % 10 NEW_LINE if ( d != 0 ) : NEW_... |
Count of subarrays of an Array having all unique digits | Function to check whether the subarray has all unique digits ; Storing all digits occurred ; Traversing all the numbers of v ; Storing all digits of v [ i ] ; Checking whether digits of v [ i ] have already occurred ; Inserting digits of v [ i ] in the set ; Fun... | def check ( v ) : NEW_LINE INDENT digits = set ( ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT d = set ( ) NEW_LINE while ( v [ i ] != 0 ) : NEW_LINE INDENT d . add ( v [ i ] % 10 ) NEW_LINE v [ i ] //= 10 NEW_LINE DEDENT for it in d : NEW_LINE INDENT if it in digits : NEW_LINE INDENT return False NEW_LINE ... |
Minimum labelled node to be removed from undirected Graph such that there is no cycle | Python3 implementation to find the minimum labelled node to be removed such that there is no cycle in the undirected graph ; Variables to store if a node V has at - most one back edge and store the depth of the node for the edge ; F... | MAX = 100005 ; NEW_LINE totBackEdges = 0 NEW_LINE countAdj = [ 0 for i in range ( MAX ) ] NEW_LINE small = [ 0 for i in range ( MAX ) ] NEW_LINE isPossible = [ 0 for i in range ( MAX ) ] NEW_LINE depth = [ 0 for i in range ( MAX ) ] NEW_LINE adj = [ [ ] for i in range ( MAX ) ] NEW_LINE vis = [ 0 for i in range ( MAX )... |
Find the row whose product has maximum count of prime factors | Python3 implementation to find the row whose product has maximum number of prime factors ; function for SieveOfEratosthenes ; Create a boolean array " isPrime [ 0 . . N ] " and initialize all entries it as true . A value in isPrime [ i ] will finally be fa... | N = 3 NEW_LINE M = 5 NEW_LINE Large = int ( 1e6 ) ; NEW_LINE prime = [ ] ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT isPrime = [ True ] * ( Large + 1 ) ; NEW_LINE for p in range ( 2 , int ( Large ** ( 1 / 2 ) ) ) : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , Larg... |
Smallest N digit number whose sum of square of digits is a Perfect Square | Python3 implementation to find Smallest N digit number whose sum of square of digits is a Perfect Square ; function to check if number is a perfect square ; function to calculate the smallest N digit number ; place digits greater than equal to ... | from math import sqrt NEW_LINE def isSquare ( n ) : NEW_LINE INDENT k = int ( sqrt ( n ) ) NEW_LINE return ( k * k == n ) NEW_LINE DEDENT def calculate ( pos , prev , sum , v ) : NEW_LINE INDENT if ( pos == len ( v ) ) : NEW_LINE INDENT return isSquare ( sum ) NEW_LINE DEDENT for i in range ( prev , 9 + 1 ) : NEW_LINE ... |
Sum of GCD of all possible sequences | Pyhton3 implementation of the above approach ; A recursive function that generates all the sequence and find GCD ; If we reach the sequence of length N g is the GCD of the sequence ; Initialise answer to 0 ; Placing all possible values at this position and recursively find the GCD... | MOD = 1e9 + 7 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def calculate ( pos , g , n , k ) : NEW_LINE INDENT if ( pos == n ) : NEW_LINE INDENT return g NEW_LINE DEDENT answer = 0 NEW_LINE fo... |
Sum of GCD of all possible sequences | Python3 implementation of the above approach ; Function to find a ^ b in log ( b ) ; Function that finds the sum of GCD of all the subsequence of N length ; To stores the number of sequences with gcd i ; Find contribution of each gcd to happen ; To count multiples ; possible seque... | MOD = ( int ) ( 1e9 + 7 ) NEW_LINE def fastexpo ( a , b ) : NEW_LINE INDENT res = 1 NEW_LINE a = a % MOD NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( ( b & 1 ) != 0 ) : NEW_LINE INDENT res = ( res * a ) % MOD NEW_LINE DEDENT a = a * a NEW_LINE a = a % MOD NEW_LINE b = b >> 1 NEW_LINE DEDENT return res NEW_LINE DEDEN... |
Split the given string into Odds : Digit DP | Function to check whether a string is an odd number or not ; A function to find the minimum number of segments the given string can be divided such that every segment is a odd number ; Declare a splitdp [ ] array and initialize to - 1 ; Build the DP table in a bottom - up m... | def checkOdd ( number ) : NEW_LINE INDENT n = len ( number ) NEW_LINE num = ord ( number [ n - 1 ] ) - 48 NEW_LINE return ( num & 1 ) NEW_LINE DEDENT def splitIntoOdds ( number ) : NEW_LINE INDENT numLen = len ( number ) NEW_LINE splitDP = [ - 1 for i in range ( numLen + 1 ) ] NEW_LINE for i in range ( 1 , numLen + 1 )... |
Split the given string into Primes : Digit DP | Function to check whether a string is a prime number or not ; A recursive function to find the minimum number of segments the given string can be divided such that every segment is a prime ; If the number is null ; checkPrime function is called to check if the number is a... | def checkPrime ( number ) : NEW_LINE INDENT num = int ( number ) NEW_LINE for i in range ( 2 , int ( num ** 0.5 ) ) : NEW_LINE INDENT if ( ( num % i ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def splitIntoPrimes ( number ) : NEW_LINE INDENT if ( number == ' ' ) : NEW_LINE... |
Find the numbers from 1 to N that contains exactly k non | Function to find number less than N having k non - zero digits ; Store the memorised values ; Initialise ; Base ; Calculate all states For every state , from numbers 1 to N , the count of numbers which contain exactly j non zero digits is being computed and upd... | def k_nonzero_numbers ( s , n , k ) : NEW_LINE INDENT dp = [ [ [ 0 for i in range ( k + 2 ) ] for i in range ( 2 ) ] for i in range ( n + 2 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT for x in range ( k + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] [ x ] = 0 NEW_LINE DEDENT D... |
Count maximum occurrence of subsequence in string such that indices in subsequence is in A . P . | Function to find the maximum occurrence of the subsequence such that the indices of characters are in arithmetic progression ; Frequencies of subsequence ; Loop to find the frequencies of subsequence of length 1 ; Loop to... | def maximumOccurrence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE freq = { } NEW_LINE for i in s : NEW_LINE INDENT temp = " " NEW_LINE temp += i NEW_LINE freq [ temp ] = freq . get ( temp , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT temp = " " NEW_LI... |
Count ways to partition a string such that both parts have equal distinct characters | Function to count the distinct characters in the string ; Frequency of each character ; Loop to count the frequency of each character of the string ; If frequency is greater than 0 then the character occured ; Function to count the n... | def distinctChars ( s ) : NEW_LINE INDENT freq = [ 0 ] * 26 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT r... |
Count ways to partition a string such that both parts have equal distinct characters | Function to count the number of ways to partition the string such that each partition have same number of distinct character ; Prefix and suffix array for distinct character from start and end ; To check whether a character has appea... | def waysToSplit ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE answer = 0 ; NEW_LINE prefix = [ 0 ] * n ; NEW_LINE suffix = [ 0 ] * n ; NEW_LINE seen = [ 0 ] * 26 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT prev = prefix [ i - 1 ] if ( i - 1 >= 0 ) else 0 ; NEW_LINE if ( seen [ ord ( s [ i ] ) - ord ( ' a ' ) ]... |
Counts paths from a point to reach Origin : Memory Optimized | Function to count the paths from a point to the origin ; Base Case when the point is already at origin ; Base Case when the point is on the x or y - axis ; Loop to fill all the position as 1 in the array ; Loop to count the number of paths from a point to o... | def Count_Paths ( x , y ) : NEW_LINE INDENT if ( x == 0 and y == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( x == 0 and y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT dp = [ 0 ] * ( max ( x , y ) + 1 ) NEW_LINE p = max ( x , y ) NEW_LINE q = min ( x , y ) NEW_LINE for i in range ( p + 1 ) : NEW_LINE INDENT... |
Find the numbers present at Kth level of a Fibonacci Binary Tree | Initializing the max value ; Array to store all the fibonacci numbers ; Function to generate fibonacci numbers using Dynamic Programming ; 0 th and 1 st number of the series are 0 and 1 ; Add the previous two numbers in the series and store it ; Functio... | MAX_SIZE = 100005 NEW_LINE fib = [ 0 ] * ( MAX_SIZE + 1 ) NEW_LINE def fibonacci ( ) : NEW_LINE INDENT fib [ 0 ] = 0 NEW_LINE fib [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAX_SIZE + 1 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] NEW_LINE DEDENT DEDENT def printLevel ( level ) : NEW_LINE INDENT left_inde... |
Count the number of ways to divide N in k groups incrementally | Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; If N is divides completely into less than k groups ; Put all possible values greater equal to prev ; Function to count the nu... | def calculate ( pos , prev , left , k ) : NEW_LINE INDENT if ( pos == k ) : NEW_LINE INDENT if ( left == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( left == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT answer = 0 ; NEW_LINE for i in range ( prev , l... |
Count the number of ways to divide N in k groups incrementally | DP Table ; Function to count the number of ways to divide the number N in groups such that each group has K number of elements ; Base Case ; if N is divides completely into less than k groups ; If the subproblem has been solved , use the value ; put all p... | dp = [ [ [ 0 for i in range ( 50 ) ] for j in range ( 50 ) ] for j in range ( 50 ) ] NEW_LINE def calculate ( pos , prev , left , k ) : NEW_LINE INDENT if ( pos == k ) : NEW_LINE INDENT if ( left == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( left == 0 ... |
Maximum score possible after performing given operations on an Array | Function to calculate maximum score recursively ; Base case ; Sum of array in range ( l , r ) ; If the operation is even - numbered the score is decremented ; Exploring all paths , by removing leftmost and rightmost element and selecting the maximum... | def maxScore ( l , r , prefix_sum , num ) : NEW_LINE INDENT if ( l > r ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( ( l - 1 ) >= 0 ) : NEW_LINE INDENT current_sum = ( prefix_sum [ r ] - prefix_sum [ l - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT current_sum = prefix_sum [ r ] - 0 NEW_LINE DEDENT if ( num % 2 =... |
Make all array elements divisible by a number K | Function to make array divisible ; For each element of array how much number to be subtracted to make it divisible by k ; For each element of array how much number to be added to make it divisible by K ; Calculate minimum difference ; Driver Code | def makeDivisble ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE b1 = [ ] NEW_LINE b2 = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT b1 . append ( arr [ i ] % k ) NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT if ( ( arr [ j ] % k ) != 0 ) : NEW_LINE INDENT b2 . append ( k - ( arr [ j ] % k ) ) NE... |
Finding powers of any number P in N ! | Python3 program to find the power of P in N ! ; Map to store all the prime factors of P ; Function to find the prime factors of N im Map ; Clear map ; Check for factors of 2 ; Find all the prime factors ; If i is a factors then increase the frequency of i ; Function to find the p... | import math NEW_LINE Map = { } NEW_LINE def findPrimeFactors ( N ) : NEW_LINE INDENT Map . clear ( ) NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT if 2 in Map : NEW_LINE INDENT Map [ 2 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Map [ 2 ] = 1 NEW_LINE DEDENT N = N // 2 NEW_LINE DEDENT for i in range ( 3 , int ( mat... |
Longest common subarray in the given two arrays | Function to find the maximum length of equal subarray ; Auxiliary dp [ ] [ ] array ; Updating the dp [ ] [ ] table in Bottom Up approach ; If A [ i ] is equal to B [ i ] then dp [ j ] [ i ] = dp [ j + 1 ] [ i + 1 ] + 1 ; Find maximum of all the values in dp [ ] [ ] arra... | def FindMaxLength ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE m = len ( B ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( m - 1 , - 1 , - 1 ) : NEW_LINE INDENT if A [ i ] == B [ j ] : NEW_LINE INDENT dp [... |
Maximum sum of elements divisible by K from the given array | | k = 16 NEW_LINE arr = [ 43 , 1 , 17 , 26 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE dp = [ [ 0 for i in range ( k ) ] for j in range ( n + 2 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( k ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT dp [ i ] [ arr [ i - 1 ] % k ]... |
Maximum contiguous decreasing sequence obtained by removing any one element | Function to find the maximum length ; Initialise maximum length to 1 ; Initialise left [ ] to find the length of decreasing sequence from left to right ; Initialise right [ ] to find the length of decreasing sequence from right to left ; Init... | def maxLength ( a , n ) : NEW_LINE INDENT maximum = 1 ; NEW_LINE left = [ 0 ] * n ; NEW_LINE right = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT left [ i ] = 1 ; NEW_LINE right [ i ] = 1 ; NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] > a [ i + 1 ] ) : NEW_LINE INDE... |
Longest alternating subsequence in terms of positive and negative integers | Python3 program to find the length of longest alternate subsequence ; LAS [ i ] [ pos ] array to find the length of LAS till index i by including or excluding element arr [ i ] on the basis of value of pos ; Base Case ; If current element is p... | import numpy as np NEW_LINE LAS = np . zeros ( ( 1000 , 2 ) ) NEW_LINE for i in range ( 1000 ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT LAS [ i ] [ j ] = False NEW_LINE DEDENT DEDENT def solve ( arr , n , i , pos ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( LAS [ i... |
Number of subsequences with negative product | Python 3 implementation of the approach ; Function to return the count of all the subsequences with negative product ; To store the count of positive elements in the array ; To store the count of negative elements in the array ; If the current element is positive ; If the ... | import math NEW_LINE def cntSubSeq ( arr , n ) : NEW_LINE INDENT pos_count = 0 ; NEW_LINE neg_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos_count += 1 NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT neg_count += 1 NEW_LINE DEDENT DEDENT result = int ( math .... |
Find minimum number of steps to reach the end of String | Python3 implementation of the approach ; Function to return the minimum number of steps to reach the end ; If the end can 't be reached ; Already at the end ; If the length is 2 or 3 then the end can be reached in a single step ; For the other cases , solve the ... | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def minSteps ( string , n , k ) : NEW_LINE INDENT if ( string [ n - 1 ] == '0' ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n < 4 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT dp = [ 0 ] * n ; NEW... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.