text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Number of closing brackets needed to complete a regular bracket sequence | Function to find number of closing brackets and complete a regular bracket sequence ; Finding the length of sequence ; Counting opening brackets ; Counting closing brackets ; Checking if at any position the number of closing bracket is more then...
def completeSequence ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE open = 0 NEW_LINE close = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT open += 1 NEW_LINE DEDENT else : NEW_LINE INDENT close += 1 NEW_LINE DEDENT if ( close > open ) : NEW_LINE INDENT print ( " IMPOSSIBLE...
Lexicographically smallest permutation with no digits at Original Index | Function to print the smallest permutation ; when n is even ; when n is odd ; handling last 3 digit ; add EOL and print result ; Driver Code
def smallestPermute ( n ) : NEW_LINE INDENT res = [ " " ] * ( n + 1 ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT res [ i ] = chr ( 48 + i + 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = chr ( 48 + i ) NEW_LINE DEDENT DEDENT DEDENT els...
Minimum array insertions required to make consecutive difference <= K | Python3 implementation of above approach ; Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver Code
import math NEW_LINE def minInsertions ( H , n , K ) : NEW_LINE INDENT inser = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT diff = abs ( H [ i ] - H [ i - 1 ] ) ; NEW_LINE if ( diff <= K ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT else : NEW_LINE INDENT inser += math . ceil ( diff / K ) - 1 ; NEW_LINE DED...
Minimum number of operations required to reduce N to 1 | Function that returns the minimum number of operations to be performed to reduce the number to 1 ; To stores the total number of operations to be performed ; if n is divisible by 3 then reduce it to n / 3 ; if n modulo 3 is 1 decrement it by 1 ; if n modulo 3 is ...
def count_minimum_operations ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT if ( n % 3 == 0 ) : NEW_LINE INDENT n //= 3 NEW_LINE DEDENT elif ( n % 3 == 1 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT else : NEW_LINE...
Minimum number of operations required to reduce N to 1 | Function that returns the minimum number of operations to be performed to reduce the number to 1 ; Base cases ; Driver Code
def count_minimum_operations ( n ) : NEW_LINE INDENT if ( n == 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n % 3 == 0 ) : NEW_LINE INDENT return 1 + count_minimum_operations ( n / 3 ) NEW_LINE DEDENT elif ( n % 3 == 1 ) : NEW_LINE INDENT return 1 + coun...
Maximize the sum of array by multiplying prefix of array with | Python implementation of the approach ; To store sum ; To store ending indices of the chosen prefix arrays ; Adding the absolute value of a [ i ] ; If i == 0 then there is no index to be flipped in ( i - 1 ) position ; print the maximised sum ; print the e...
def maxSum ( arr , n ) : NEW_LINE INDENT s = 0 NEW_LINE l = [ ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT s += abs ( a [ i ] ) NEW_LINE if ( a [ i ] >= 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT l . append ( i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT l . append ( i ...
Find the longest common prefix between two strings after performing swaps on second string | Python program to find the longest common prefix between two strings after performing swaps on the second string ; a = len ( x ) length of x b = len ( y ) length of y ; creating frequency array of characters of y ; storing the ...
def LengthLCP ( x , y ) : NEW_LINE INDENT fr = [ 0 ] * 26 NEW_LINE for i in range ( b ) : NEW_LINE INDENT fr [ ord ( y [ i ] ) - 97 ] += 1 NEW_LINE DEDENT c = 0 NEW_LINE for i in range ( a ) : NEW_LINE INDENT if ( fr [ ord ( x [ i ] ) - 97 ] > 0 ) : NEW_LINE INDENT c += 1 NEW_LINE fr [ ord ( x [ i ] ) - 97 ] -= 1 NEW_L...
All possible co | Function to count possible pairs ; total count of numbers in range ; printing count of pairs ; Driver code
def CountPair ( L , R ) : NEW_LINE INDENT x = ( R - L + 1 ) NEW_LINE print ( x // 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 1 , 8 NEW_LINE CountPair ( L , R ) NEW_LINE DEDENT
Problems not solved at the end of Nth day | Function to find problems not solved at the end of Nth day ; Driver Code
def problemsLeft ( K , P , N ) : NEW_LINE INDENT if ( K <= P ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( K - P ) * N ) NEW_LINE DEDENT DEDENT K , P , N = 4 , 1 , 10 NEW_LINE print ( problemsLeft ( K , P , N ) ) NEW_LINE
Kruskal 's Algorithm (Simple Implementation for Adjacency Matrix) | Find set of vertex i ; Does union of i and j . It returns false if i and j are already in same set . ; Finds MST using Kruskal 's algorithm ; Initialize sets of disjoint sets ; Include minimum weight edges one by one ; Let us create the following graph...
def find ( i ) : NEW_LINE INDENT while parent [ i ] != i : NEW_LINE INDENT i = parent [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def union ( i , j ) : NEW_LINE INDENT a = find ( i ) NEW_LINE b = find ( j ) NEW_LINE parent [ a ] = b NEW_LINE DEDENT def kruskalMST ( cost ) : NEW_LINE INDENT for i in range ( V ) : NEW...
Number of chocolates left after k iterations | Function to find the chocolates left ; Driver code
def results ( n , k ) : NEW_LINE INDENT return round ( pow ( n , ( 1.0 / pow ( 2 , k ) ) ) ) NEW_LINE DEDENT k = 3 NEW_LINE n = 100000000 NEW_LINE print ( " Chocolates ▁ left ▁ after " ) , NEW_LINE print ( k ) , NEW_LINE print ( " iterations ▁ are " ) , NEW_LINE print ( int ( results ( n , k ) ) ) NEW_LINE
Subarray whose absolute sum is closest to K | Python Code to find sub - array whose sum shows the minimum deviation ; starting index , ending index , Deviation ; iterate i and j to get all subarrays ; found sub - array with less sum ; exactly same sum ; Driver Code ; Array to store return values
def getSubArray ( arr , n , K ) : NEW_LINE INDENT i = - 1 NEW_LINE j = - 1 NEW_LINE currSum = 0 NEW_LINE result = [ i , j , abs ( K - abs ( currSum ) ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT currSum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT currSum += arr [ j ] NEW_LINE currDev = abs ( K - ...
Longest subsequence whose average is less than K | Python3 program to perform Q queries to find longest subsequence whose average is less than K ; Function to print the length for evey query ; sort array of N elements ; Array to store average from left ; Sort array of average ; number of queries ; print answer to every...
import bisect NEW_LINE def longestSubsequence ( a , n , q , m ) : NEW_LINE INDENT a . sort ( ) NEW_LINE Sum = 0 NEW_LINE b = [ None ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE av = Sum // ( i + 1 ) NEW_LINE b [ i ] = av + 1 NEW_LINE DEDENT b . sort ( ) NEW_LINE for i in range ( 0 ,...
Make array elements equal in Minimum Steps | Returns the minimum steps required to make an array of N elements equal , where the first array element equals M ; Corner Case 1 : When N = 1 ; Corner Case 2 : When N = 2 ; Driver Code
def steps ( N , M ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( N == 2 ) : NEW_LINE INDENT return M NEW_LINE DEDENT return 2 * M + ( N - 3 ) NEW_LINE DEDENT N = 4 NEW_LINE M = 4 NEW_LINE print ( steps ( N , M ) ) NEW_LINE
Minimum increment / decrement to make array non | Python3 code to count the change required to convert the array into non - increasing array ; min heap ; Here in the loop we will check that whether the upcoming element of array is less than top of priority queue . If yes then we calculate the difference . After that we...
from queue import PriorityQueue NEW_LINE def DecreasingArray ( a , n ) : NEW_LINE INDENT ss , dif = ( 0 , 0 ) NEW_LINE pq = PriorityQueue ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT tmp = 0 NEW_LINE if not pq . empty ( ) : NEW_LINE INDENT tmp = pq . get ( ) NEW_LINE pq . put ( tmp ) NEW_LINE DEDENT if not pq . ...
Schedule jobs so that each server gets equal load | Function to find new array a ; find sum S of both arrays a and b . ; Single element case . ; This checks whether sum s can be divided equally between all array elements . i . e . whether all elements can take equal value or not . ; Compute possible value of new array ...
def solve ( a , b , n ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s += a [ i ] + b [ i ] NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] + b [ 0 ] NEW_LINE DEDENT if s % n != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = s // n NEW_LINE for i in range ( 0 , n ) : NEW_LI...
Check if it is possible to survive on Island | function to find the minimum days ; If we can not buy at least a week supply of food during the first week OR We can not buy a day supply of food on the first day then we can 't survive. ; If we can survive then we can buy ceil ( A / N ) times where A is total units of foo...
def survival ( S , N , M ) : NEW_LINE INDENT if ( ( ( N * 6 ) < ( M * 7 ) and S > 6 ) or M > N ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT days = ( M * S ) / N NEW_LINE if ( ( ( M * S ) % N ) != 0 ) : NEW_LINE INDENT days += 1 NEW_LINE DEDENT print ( " Yes ▁ " ) , NEW_LINE print ( days )...
Lexicographically largest subsequence such that every character occurs at least k times | Find lexicographically largest subsequence of s [ 0. . n - 1 ] such that every character appears at least k times . The result is filled in t [ ] ; Starting from largest charter ' z ' to 'a ; Counting the frequency of the characte...
def subsequence ( s , t , n , k ) : NEW_LINE INDENT last = 0 NEW_LINE cnt = 0 NEW_LINE new_last = 0 NEW_LINE size = 0 NEW_LINE string = ' zyxwvutsrqponmlkjihgfedcba ' NEW_LINE DEDENT ' NEW_LINE INDENT for ch in string : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( last , n ) : NEW_LINE INDENT if s [ i ] == ch : NE...
Largest permutation after at most k swaps | Function to find the largest permutation after k swaps ; Storing the elements and their index in map ; If number of swaps allowed are equal to number of elements then the resulting permutation will be descending order of given permutation . ; If j is not at it 's best index ;...
def bestpermutation ( arr , k , n ) : NEW_LINE INDENT h = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT h [ arr [ i ] ] = i NEW_LINE DEDENT if ( n <= k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arr . reverse ( ) NEW_LINE DEDENT else : NEW_LINE INDENT for j in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( k > 0 )...
Program for Best Fit algorithm in Memory Management | Function to allocate memory to blocks as per Best fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; Find the best fit block for current process ; If we could find ...
def bestFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT bestIdx = - 1 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT if bestIdx == - 1 : NEW_LINE INDENT bestIdx = j NEW_LINE DEDE...
Bin Packing Problem ( Minimize number of used Bins ) | Returns number of bins required using first fit online algorithm ; Initialize result ( Count of bins ) ; Create an array to store remaining space in bins there can be at most n bins ; Place items one by one ; Find the first bin that can accommodate weight [ i ] ; I...
def firstFit ( weight , n , c ) : NEW_LINE INDENT res = 0 ; NEW_LINE bin_rem = [ 0 ] * n ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 ; NEW_LINE min = c + 1 ; NEW_LINE bi = 0 ; NEW_LINE for j in range ( res ) : NEW_LINE INDENT if ( bin_rem [ j ] >= weight [ i ] and bin_rem [ j ] - weight [ i ] < min ) : NEW_...
Find minimum time to finish all jobs with given constraints | Utility function to get maximum element in job [ 0. . n - 1 ] ; Returns true if it is possible to finish jobs [ ] within given time 'time ; cnt is count of current assignees required for jobs ; time assigned to current assignee ; If time assigned to current ...
def getMax ( arr , n ) : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] > result : NEW_LINE INDENT result = arr [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT ' NEW_LINE def isPossible ( time , K , job , n ) : NEW_LINE INDENT cnt = 1 NEW_LINE curr_time = ...
Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updatin...
def LongestOddEvenSubarray ( A , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 0 and A [ i - 1 ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ i - 1 ] % 2 != 0 ) ) : NEW_LINE INDENT dp [ i ] = dp [ i ...
Count of subarrays with maximum value as K | Function to count the subarrays with maximum not greater than K ; If arr [ i ] > k then arr [ i ] cannot be a part of any subarray . ; Count the number of elements where arr [ i ] is not greater than k . ; Summation of all possible subarrays in the variable ans . ; Function ...
def totalSubarrays ( arr , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT count = 0 NEW_LINE while ( i < n and arr [ i ] <= k ) : NEW_LINE INDENT i += 1 NEW_LINE count += 1 NEW_LINE DEDENT ans +=...
Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; varia...
def maxSumWO3Consec ( A , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return A [ 0 ] NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return A [ 0 ] + A [ 1 ] NEW_LINE DEDENT third = A [ 0 ] NEW_LINE second = third + A [ 1 ] NEW_LINE first = max ( second , A [ 1 ] + A [ 2 ] ) NEW_LINE sum = max ( max ( third ,...
Minimum number of given operations required to reduce a number to 2 | Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; ...
def findMinOperations ( n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] = 999999 NEW_LINE DEDENT dp [ 2 ] = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i * 5 <= n ) : NEW_LINE INDENT dp [ i * 5 ] = min ( dp [ i * 5 ] , dp [ i ] + ...
Split array into subarrays such that sum of difference between their maximums and minimums is maximum | Function to find maximum sum of difference between maximums and minimums in the splitted subarrays ; Traverse the array ; Stores the maximum and minimum elements upto the i - th index ; Traverse the range [ 0 , i ] ;...
def getValue ( arr , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT minn = arr [ i ] NEW_LINE maxx = arr [ i ] NEW_LINE j = i NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT minn = min ( arr [ j ] , minn ) NEW_LINE maxx = max ( arr [ j ] , maxx ) NEW_LINE dp [ i ] ...
Maximum score possible by removing substrings made up of single distinct character | Function to check if the string s consists of a single distinct character or not ; Function to calculate the maximum score possible by removing substrings ; If string is empty ; If length of string is 1 ; Store the maximum result ; Try...
def isUnique ( s ) : NEW_LINE INDENT return True if len ( set ( s ) ) == 1 else False NEW_LINE DEDENT def maxScore ( s , a ) : NEW_LINE INDENT n = len ( s ) NEW_LINE if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT mx = - 1 NEW_LINE for i in range ( n ) : N...
Maximum score possible by removing substrings made up of single distinct character | Initialize a dictionary to store the precomputed results ; Function to calculate the maximum score possible by removing substrings ; If s is present in dp [ ] array ; Base Cases : ; If length of string is 0 ; If length of string is 1 ;...
dp = dict ( ) NEW_LINE def maxScore ( s , a ) : NEW_LINE INDENT if s in dp : NEW_LINE INDENT return dp [ s ] NEW_LINE DEDENT n = len ( s ) NEW_LINE if n == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return a [ 0 ] NEW_LINE DEDENT head = 0 NEW_LINE mx = - 1 NEW_LINE while head < n : NEW_LIN...
Count all unique outcomes possible by performing S flips on N coins | Dimensions of the DP table ; Stores the dp states ; Function to recursively count the number of unique outcomes possible by performing S flips on N coins ; Base Case ; If the count for the current state is not calculated , then calculate it recursive...
size = 100 NEW_LINE ans = [ [ 0 for i in range ( size ) ] for j in range ( size ) ] NEW_LINE def numberOfUniqueOutcomes ( n , s ) : NEW_LINE INDENT if ( s < n ) : NEW_LINE INDENT ans [ n ] [ s ] = 0 ; NEW_LINE DEDENT elif ( n == 1 or n == s ) : NEW_LINE INDENT ans [ n ] [ s ] = 1 ; NEW_LINE DEDENT elif ( ans [ n ] [ s ...
Minimize removals to remove another string as a subsequence of a given string | Function to print the minimum number of character removals required to remove X as a subsequence from the string str ; Length of the string str ; Length of the string X ; Stores the dp states ; Fill first row of dp [ ] [ ] ; If X [ j ] matc...
def printMinimumRemovals ( s , X ) : NEW_LINE INDENT N = len ( s ) NEW_LINE M = len ( X ) NEW_LINE dp = [ [ 0 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( s [ 0 ] == X [ j ] ) : NEW_LINE INDENT dp [ 0 ] [ j ] = 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW...
Railway Station | TCS CodeVita 2020 | Dp table for memoization ; Function to count the number of ways to N - th station ; Base Cases ; If current state is already evaluated ; Count ways in which train 1 can be chosen ; Count ways in which train 2 can be chosen ; Count ways in which train 3 can be chosen ; Store the cur...
dp = [ - 1 for i in range ( 100000 ) ] NEW_LINE def findWays ( x ) : NEW_LINE INDENT if ( x < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( x == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( x == 1 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if ( x == 2 ) : NEW_LINE INDENT return 4 NEW_LINE DEDENT if ( dp ...
Maximum sum not exceeding K possible for any rectangle of a Matrix | Python3 program for the above approach ; Function to find the maximum possible sum of arectangle which is less than K ; Stores the values ( cum_sum - K ) ; Insert 0 into the set sumSet ; Traverse over the rows ; Get cumulative sum from [ 0 to i ] ; Se...
from bisect import bisect_left , bisect_right NEW_LINE import sys NEW_LINE def maxSubarraySum ( sum , k , row ) : NEW_LINE INDENT curSum , curMax = 0 , - sys . maxsize - 1 NEW_LINE sumSet = { } NEW_LINE sumSet [ 0 ] = 1 NEW_LINE for r in range ( row ) : NEW_LINE INDENT curSum += sum [ r ] NEW_LINE arr = list ( sumSet ....
Count N | Function to count binary strings of length N having substring "11" ; Initialize dp [ ] of size N + 1 ; Base Cases ; Stores the first N powers of 2 ; Generate ; Iterate over the range [ 2 , N ] ; Prtotal count of substrings ; Driver Code
def binaryStrings ( N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 0 NEW_LINE power = [ 0 ] * ( N + 1 ) NEW_LINE power [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT power [ i ] = 2 * power [ i - 1 ] NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDEN...
Maximum sum submatrix | Python3 program for the above approach ; Function to find maximum continuous maximum sum in the array ; Stores current and maximum sum ; Traverse the array v ; Add the value of the current element ; Update the maximum sum ; Return the maximum sum ; Function to find the maximum submatrix sum ; St...
import sys NEW_LINE def kadane ( v ) : NEW_LINE INDENT currSum = 0 NEW_LINE maxSum = - sys . maxsize - 1 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT currSum += v [ i ] NEW_LINE if ( currSum > maxSum ) : NEW_LINE INDENT maxSum = currSum NEW_LINE DEDENT if ( currSum < 0 ) : NEW_LINE INDENT currSum = 0 NEW_LIN...
Minimize cost of painting N houses such that adjacent houses have different colors | Function to find the minimum cost of coloring the houses such that no two adjacent houses has the same color ; Corner Case ; Auxiliary 2D dp array ; Base Case ; If current house is colored with red the take min cost of previous houses ...
def minCost ( costs , N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp = [ [ 0 for i in range ( 3 ) ] for j in range ( 3 ) ] NEW_LINE dp [ 0 ] [ 0 ] = costs [ 0 ] [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = costs [ 0 ] [ 1 ] NEW_LINE dp [ 0 ] [ 2 ] = costs [ 0 ] [ 2 ] NEW_LINE for i in range ( 1 , ...
Minimize count of flips required to make sum of the given array equal to 0 | Initialize dp [ ] [ ] ; Function to find the minimum number of operations to make sum of A [ ] 0 ; Initialize answer ; Base case ; Otherwise , return 0 ; Pre - computed subproblem ; Recurrence relation for finding the minimum of the sum of sub...
dp = [ [ - 1 for i in range ( 2001 ) ] for j in range ( 2001 ) ] NEW_LINE def solve ( A , i , sum , N ) : NEW_LINE INDENT res = 2001 NEW_LINE if ( sum < 0 or ( i == N and sum != 0 ) ) : NEW_LINE INDENT return 2001 NEW_LINE DEDENT if ( sum == 0 or i >= N ) : NEW_LINE INDENT dp [ i ] [ sum ] = 0 NEW_LINE return 0 NEW_LIN...
Count subsequences having average of its elements equal to K | Stores the dp states ; Function to find the count of subsequences having average K ; Base condition ; Three loops for three states ; Recurrence relation ; Stores the sum of dp [ n ] [ j ] [ K * j ] all possible values of j with average K and sum K * j ; Ite...
dp = [ [ [ 0 for i in range ( 1001 ) ] for i in range ( 101 ) ] for i in range ( 101 ) ] NEW_LINE def countAverage ( n , K , arr ) : NEW_LINE INDENT global dp NEW_LINE dp [ 0 ] [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT for s in range ( 100 ) : NEW_LINE INDENT...
Count ways to remove pairs from a matrix such that remaining elements can be grouped in vertical or horizontal pairs | Function to count ways to remove pairs such that the remaining elements can be arranged in pairs vertically or horizontally ; Store the size of matrix ; If N is odd , then no such pair exists ; Store t...
def numberofpairs ( v , k ) : NEW_LINE INDENT n = len ( v ) NEW_LINE if ( n % 2 == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE dp = [ [ 0 for i in range ( 2 ) ] for j in range ( k ) ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT dp [ i ] [...
Maximize sum by selecting X different | Python3 program for the above approach ; Store overlapping subproblems of the recurrence relation ; Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; If the subpr...
import sys NEW_LINE dp = [ [ [ [ - 1 for i in range ( 50 ) ] for j in range ( 50 ) ] for k in range ( 50 ) ] for l in range ( 50 ) ] NEW_LINE def FindMaxS ( X , Y , Z , n , A , B , C ) : NEW_LINE INDENT if ( X < 0 or Y < 0 or Z < 0 ) : NEW_LINE INDENT return - sys . maxsize - 1 NEW_LINE DEDENT if ( n < 0 ) : NEW_LINE I...
Minimize swaps of adjacent characters to sort every possible rearrangement of given Binary String | Python3 program for the above approach ; Precalculate the values of power of 2 ; Function to calculate 2 ^ N % mod ; Function to find sum of inversions ; Initialise a list of 0 s and ? s ; Traverse the string in the reve...
MOD = 10 ** 9 + 7 NEW_LINE MEM = [ 1 , 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 , 512 , 1024 , 2048 , 4096 ] NEW_LINE def mod_pow2 ( n ) : NEW_LINE INDENT while n >= len ( MEM ) : NEW_LINE INDENT MEM . append ( ( MEM [ - 1 ] * 2 ) % MOD ) NEW_LINE DEDENT return MEM [ n ] NEW_LINE DEDENT def inversions ( bstr ) : NEW_LINE I...
Minimum removals required to convert given array to a Mountain Array | Utility function to count array elements required to be removed to make array a mountain array ; Stores length of increasing subsequence from [ 0 , i - 1 ] ; Stores length of increasing subsequence from [ i + 1 , n - 1 ] ; Iterate for each position ...
def minRemovalsUtil ( arr ) : NEW_LINE INDENT result = 0 NEW_LINE if ( len ( arr ) < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT leftIncreasing = [ 0 ] * len ( arr ) NEW_LINE rightIncreasing = [ 0 ] * len ( arr ) NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT i...
Minimum number of jumps to obtain an element of opposite parity | Bfs for odd numbers are source ; Initialize queue ; Stores for each node , the nodes visited and their distances ; If parity is 0 -> odd Otherwise -> even ; Perform multi - source bfs ; Extract the front element of the queue ; Traverse nodes connected to...
def bfs ( n , a , invGr , ans , parity ) : NEW_LINE INDENT q = [ ] NEW_LINE vis = [ 0 for i in range ( n + 1 ) ] NEW_LINE dist = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( ( a [ i ] + parity ) & 1 ) : NEW_LINE INDENT q . append ( i ) NEW_LINE vis [ i ] = 1 NEW_LINE DEDEN...
Longest subsequence having maximum GCD between any pair of distinct elements | Python3 program for the above approach ; Function to find GCD of pair with maximum GCD ; Stores maximum element of arr [ ] ; Find the maximum element ; Maintain a count array ; Store the frequency of arr [ ] ; Stores the multiples of a numbe...
import math NEW_LINE def findMaxGCD ( arr , N ) : NEW_LINE INDENT high = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT high = max ( high , arr [ i ] ) NEW_LINE DEDENT count = [ 0 ] * ( high + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT counter = 0 NEW_LINE fo...
Count unique paths is a matrix whose product of elements contains odd number of divisors | Python3 program for the above approach ; Stores the results ; Count of unique product paths ; Function to check whether number is perfect square or not ; If square root is an integer ; Function to calculate and store all the path...
from math import sqrt , floor NEW_LINE dp = [ [ [ ] for j in range ( 105 ) ] for k in range ( 105 ) ] NEW_LINE countPaths = 0 NEW_LINE def isPerfectSquare ( n ) : NEW_LINE INDENT sr = sqrt ( n ) NEW_LINE return ( ( sr - floor ( sr ) ) == 0 ) NEW_LINE DEDENT def countUniquePaths ( a , m , n , ans ) : NEW_LINE INDENT glo...
Generate a combination of minimum coins that sums to a given value | Python3 program for the above approach ; dp array to memoize the results ; List to store the result ; Function to find the minimum number of coins to make the sum equals to X ; Base case ; If previously computed subproblem occurred ; Initialize result...
import sys NEW_LINE MAX = 100000 NEW_LINE dp = [ - 1 ] * ( MAX + 1 ) NEW_LINE denomination = [ ] NEW_LINE def countMinCoins ( n , C , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT dp [ 0 ] = 0 NEW_LINE return 0 NEW_LINE DEDENT if ( dp [ n ] != - 1 ) : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT ret = sys . ...
Count all possible paths from top left to bottom right of a Matrix without crossing the diagonal | Function to calculate Binomial Coefficient C ( n , r ) ; C ( n , r ) = C ( n , n - r ) ; [ n * ( n - 1 ) * -- - * ( n - r + 1 ) ] / [ r * ( r - 1 ) * -- -- * 1 ] ; Function to calculate the total possible paths ; Update n...
def binCoff ( n , r ) : NEW_LINE INDENT val = 1 NEW_LINE if ( r > ( n - r ) ) : NEW_LINE INDENT r = ( n - r ) NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT val *= ( n - i ) NEW_LINE val //= ( i + 1 ) NEW_LINE DEDENT return val NEW_LINE DEDENT def findWays ( n ) : NEW_LINE INDENT n = n - 1 NEW_LINE a = binCoff ...
Minimum operations to transform given string to another by moving characters to front or end | Python3 program for the above approach ; Function that finds the minimum number of steps to find the minimum characters must be moved to convert string s to t ; r = maximum value over all dp [ i ] [ j ] computed so far ; dp [...
dp = [ [ 0 ] * 1010 ] * 1010 NEW_LINE def solve ( s , t ) : NEW_LINE INDENT n = len ( s ) NEW_LINE r = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE if ( i > 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , dp [ i ] [ j ] ) ...
Longest substring whose characters can be rearranged to form a Palindrome | Function to get the length of longest substring whose characters can be arranged to form a palindromic string ; To keep track of the last index of each xor ; Initialize answer with 0 ; Now iterate through each character of the string ; Convert ...
def longestSubstring ( s : str , n : int ) : NEW_LINE INDENT index = dict ( ) NEW_LINE answer = 0 NEW_LINE mask = 0 NEW_LINE index [ mask ] = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = ord ( s [ i ] ) - 97 NEW_LINE mask ^= ( 1 << temp ) NEW_LINE if mask in index . keys ( ) : NEW_LINE INDENT answer = max...
Count of N | Function to find count of N - digit numbers with single digit XOR ; dp [ i ] [ j ] stores the number of i - digit numbers with XOR equal to j ; For 1 - 9 store the value ; Iterate till N ; Calculate XOR ; Store in DP table ; Initialize count ; Print answer ; Driver Code ; Given number N ; Function Call
def countNums ( N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 16 ) ] for j in range ( N ) ] ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT for k in range ( 0 , 16 ) : NEW_LINE INDENT x...
Count of numbers upto M divisible by given Prime Numbers | Function to count the numbers that are divisible by the numbers in the array from range 1 to M ; Initialize the count variable ; Iterate over [ 1 , M ] ; Iterate over array elements arr [ ] ; Check if i is divisible by a [ j ] ; Increment the count ; Return the...
def count ( a , M , N ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( 1 , M + 1 ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( i % a [ j ] == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT lst = [ 2 , 3 , 5 , 7 ] NEW_LINE m = 100 NEW_LINE n ...
Count of numbers upto N digits formed using digits 0 to K | Python3 implementation to count the numbers upto N digits such that no two zeros are adjacent ; Function to count the numbers upto N digits such that no two zeros are adjacent ; Condition to check if only one element remains ; If last element is non zero , ret...
dp = [ [ 0 ] * 10 for j in range ( 15 ) ] NEW_LINE def solve ( n , last , k ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT if ( last == k ) : NEW_LINE INDENT return ( k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT if ( dp [ n ] [ last ] ) : NEW_LINE INDENT return dp [ n ] [ last ] N...
Count of occurrences of each prefix in a string using modified KMP algorithm | Function to print the count of all prefix in the given string ; Iterate over string s ; Print the prefix and their frequency ; Function to implement the LPS array to store the longest prefix which is also a suffix for every substring of the ...
def Print ( occ , s ) : NEW_LINE INDENT for i in range ( 1 , len ( s ) + 1 ) : NEW_LINE INDENT print ( s [ 0 : i ] , " occur " , occ [ i ] , " times . " ) NEW_LINE DEDENT DEDENT def prefix_function ( s ) : NEW_LINE INDENT LPS = [ 0 for i in range ( len ( s ) ) ] NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDE...
Maximum sum by picking elements from two arrays in order | Set 2 | Function to calculate maximum sum ; Maximum elements that can be chosen from array A ; Maximum elements that can be chosen from array B ; Stores the maximum sum possible ; Fill the dp [ ] for base case when all elements are selected from A [ ] ; Fill th...
def maximumSum ( A , B , length , X , Y ) : NEW_LINE INDENT l = length NEW_LINE l1 = min ( length , X ) NEW_LINE l2 = min ( length , Y ) NEW_LINE dp = [ [ 0 for i in range ( l2 + 1 ) ] for i in range ( l1 + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 0 NEW_LINE max_sum = - 10 * 9 NEW_LINE for i in range ( 1 , l1 + 1 ) : NEW_LINE I...
Min number of operations to reduce N to 0 by subtracting any digits from N | Function to reduce an integer N to Zero in minimum operations by removing digits from N ; Initialise dp [ ] to steps ; Iterate for all elements ; For each digit in number i ; Either select the number or do not select it ; dp [ N ] will give mi...
def reduceZero ( N ) : NEW_LINE INDENT dp = [ 1e9 for i in range ( N + 1 ) ] NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for c in str ( i ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , dp [ i - ( ord ( c ) - 48 ) ] + 1 ) NEW_LINE DEDENT DEDENT return dp [ N ] NEW_LINE DEDENT N = 25 NEW_LI...
Pentanacci Numbers | Function to print Nth Pentanacci number ; Initialize first five numbers to base cases ; declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth to second , third , fourth and curr to fifth respectively ; Driver c...
def printpenta ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT first = 0 NEW_LINE second = 0 NEW_LINE third = 0 NEW_LINE fourth = 0 NEW_LINE fifth = 1 NEW_LINE curr = 0 NEW_LINE if ( n == 0 or n == 1 or \ n == 2 or n == 3 ) : NEW_LINE INDENT print ( first ) NEW_LINE DEDENT elif ( n == 5 ) ...
Count of binary strings of length N with even set bit count and at most K consecutive 1 s | Python3 program for the above approach ; Table to store solution of each subproblem ; Function to calculate the possible binary strings ; If number of ones is equal to K ; pos : current position Base Case : When n length is trav...
import numpy as np NEW_LINE dp = np . ones ( ( ( 100002 , 21 , 3 ) ) ) NEW_LINE dp = - 1 * dp NEW_LINE def possibleBinaries ( pos , ones , sum , k ) : NEW_LINE INDENT if ( ones == k ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( pos == 0 ) : NEW_LINE INDENT return 1 if ( sum == 0 ) else 0 NEW_LINE DEDENT if ( dp [ p...
Sum of absolute difference of all pairs raised to power K | Python3 program for the above approach ; Since K can be 100 max ; Initializing with - 1 ; Making vector A as 1 - Indexing ; To Calculate the value nCk ; Since nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Function that summation of absolute differences of all...
class Solution : NEW_LINE INDENT def __init__ ( self , N , K , B ) : NEW_LINE INDENT self . ncr = [ ] NEW_LINE for i in range ( 101 ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( 101 ) : NEW_LINE INDENT temp . append ( - 1 ) NEW_LINE DEDENT self . ncr . append ( temp ) NEW_LINE DEDENT self . n = N NEW_LINE se...
Count of ways to traverse a Matrix and return to origin in K steps | Python3 program to count total number of ways to return to origin after completing given number of steps . ; Function Initialize dp [ ] [ ] [ ] array with - 1 ; Function returns the total count ; Driver code
MOD = 1000000007 NEW_LINE dp = [ [ [ 0 for i in range ( 101 ) ] for i in range ( 101 ) ] for i in range ( 101 ) ] NEW_LINE N , M , K = 0 , 0 , 0 NEW_LINE def Initialize ( ) : NEW_LINE INDENT for i in range ( 101 ) : NEW_LINE INDENT for j in range ( 101 ) : NEW_LINE INDENT for z in range ( 101 ) : NEW_LINE INDENT dp [ i...
Count of subsequences of length atmost K containing distinct prime elements | Python3 Program to find the count of distinct prime subsequences at most of of length K from a given array ; Initialize all indices as true ; A value in prime [ i ] will finally be false if i is not a prime , else true ; If prime [ p ] is tru...
prime = [ True ] * 1000000 NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT global prime NEW_LINE prime [ 0 ] = prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= 100000 : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 100001 , p ) : NEW_LINE INDENT prime [ i ] = Fal...
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 iterate over every elements of the array ; Loop to find the consecutive smaller elements at left ; Loop to ...
def findMinPrizes ( arr , n ) : NEW_LINE INDENT totalPrizes = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = 1 NEW_LINE j = i NEW_LINE while ( j > 0 and arr [ j ] > arr [ j - 1 ] ) : NEW_LINE INDENT x += 1 NEW_LINE j -= 1 NEW_LINE DEDENT j = i NEW_LINE y = 1 NEW_LINE while ( j < n - 1 and arr [ j ] > arr [ j + 1...
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 ] ; DP Table ; Function to count the number of ways to divide the number N in K groups such that each group has number of ele...
mod = 1000000007 NEW_LINE dp = [ [ - 1 for j in range ( 1000 ) ] for i in range ( 1000 ) ] 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 ==...
Minimum number of squares whose sum equals to given number N | set 2 | Function for finding minimum square numbers ; arr [ i ] of array arr store minimum count of square number to get i ; sqrNum [ i ] store last square number to get i ; Find minimum count of square number for all value 1 to n ; In worst case it will be...
def minSqrNum ( n ) : NEW_LINE INDENT arr = [ 0 ] * ( n + 1 ) NEW_LINE sqrNum = [ 0 ] * ( n + 1 ) NEW_LINE v = [ ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] + 1 NEW_LINE sqrNum [ i ] = 1 NEW_LINE k = 1 ; NEW_LINE while ( k * k <= i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - k * k...