text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Minimum number of bits required to be flipped such that Bitwise OR of A and B is equal to C | Function to count the number of bit flips required on A and B such that Bitwise OR of A and B is C ; Stores the count of flipped bit ; Iterate over the range [ 0 , 32 ] ; Check if i - th bit of A is set ; Check if i - th bit of B is set or not ; Check if i - th bit of C is set or not ; If i - th bit of C is unset ; Check if i - th bit of A is set or not ; Check if i - th bit of B is set or not ; Check if i - th bit of C is set or not ; Check if i - th bit of both A and B is set ; Return the count of bits flipped ; Driver Code
def minimumFlips ( A , B , C ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT x , y , z = 0 , 0 , 0 NEW_LINE if ( A & ( 1 << i ) ) : NEW_LINE INDENT x = 1 NEW_LINE DEDENT if ( B & ( 1 << i ) ) : NEW_LINE INDENT y = 1 NEW_LINE DEDENT if ( C & ( 1 << i ) ) : NEW_LINE INDENT z = 1 NEW_LINE DEDENT if ( z == 0 ) : NEW_LINE INDENT if ( x ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( y ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT if ( z == 1 ) : NEW_LINE INDENT if ( x == 0 and y == 0 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B , C = 2 , 6 , 5 NEW_LINE print ( minimumFlips ( A , B , C ) ) NEW_LINE DEDENT
Queries to calculate Bitwise AND of an array with updates | Store the number of set bits at each position ; Function to precompute the prefix count array ; Iterate over the range [ 0 , 31 ] ; Set the bit at position i if arr [ 0 ] is set at position i ; Traverse the array and take prefix sum ; Update prefixCount [ i ] [ j ] ; Function to find the Bitwise AND of all array elements ; Stores the required result ; Iterate over the range [ 0 , 31 ] ; Stores the number of set bits at position i ; If temp is N , then set ith position in the result ; Print the result ; Function to update the prefix count array in each query ; Iterate through all the bits of the current number ; Store the bit at position i in the current value and the new value ; If bit2 is set and bit1 is unset , then increase the set bits at position i by 1 ; If bit1 is set and bit2 is unset , then decrease the set bits at position i by 1 ; Function to find the bitwise AND of the array after each query ; Fill the prefix count array ; Traverse the queries ; Store the index and the new value ; Store the current element at the index ; Update the array element ; Apply the changes to the prefix count array ; Print the bitwise AND of the modified array ; Driver Code
prefixCount = [ [ 0 for x in range ( 32 ) ] for y in range ( 10000 ) ] NEW_LINE def findPrefixCount ( arr , size ) : NEW_LINE INDENT for i in range ( 32 ) : NEW_LINE INDENT prefixCount [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) NEW_LINE for j in range ( 1 , size ) : NEW_LINE INDENT prefixCount [ i ] [ j ] = ( ( arr [ j ] >> i ) & 1 ) NEW_LINE prefixCount [ i ] [ j ] += prefixCount [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT def arrayBitwiseAND ( size ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT temp = prefixCount [ i ] [ size - 1 ] NEW_LINE if ( temp == size ) : NEW_LINE INDENT result = ( result | ( 1 << i ) ) NEW_LINE DEDENT DEDENT print ( result , end = " ▁ " ) NEW_LINE DEDENT def applyQuery ( currentVal , newVal , size ) : NEW_LINE INDENT for i in range ( 32 ) : NEW_LINE INDENT bit1 = ( ( currentVal >> i ) & 1 ) NEW_LINE bit2 = ( ( newVal >> i ) & 1 ) NEW_LINE if ( bit2 > 0 and bit1 == 0 ) : NEW_LINE INDENT prefixCount [ i ] [ size - 1 ] += 1 NEW_LINE DEDENT elif ( bit1 > 0 and bit2 == 0 ) : NEW_LINE INDENT prefixCount [ i ] [ size - 1 ] -= 1 NEW_LINE DEDENT DEDENT DEDENT def findbitwiseAND ( queries , arr , N , M ) : NEW_LINE INDENT findPrefixCount ( arr , N ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT id = queries [ i ] [ 0 ] NEW_LINE newVal = queries [ i ] [ 1 ] NEW_LINE currentVal = arr [ id ] NEW_LINE arr [ id ] = newVal NEW_LINE applyQuery ( currentVal , newVal , N ) NEW_LINE arrayBitwiseAND ( N ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE queries = [ [ 0 , 2 ] , [ 3 , 3 ] , [ 4 , 2 ] ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( queries ) NEW_LINE findbitwiseAND ( queries , arr , N , M ) NEW_LINE DEDENT
Find the winner of a game of donating i candies in every i | Function to find the winning player in a game of donating i candies to opponent in i - th move ; Steps in which number of candies of player A finishes ; Steps in which number of candies of player B finishes ; If A 's candies finishes first ; Otherwise ; Candies possessed by player A ; Candies possessed by player B
def stepscount ( a , b ) : NEW_LINE INDENT chance_A = 2 * a - 1 NEW_LINE chance_B = 2 * b NEW_LINE if ( chance_A < chance_B ) : NEW_LINE INDENT return ' B ' NEW_LINE DEDENT else : NEW_LINE INDENT return " A " NEW_LINE DEDENT DEDENT A = 2 NEW_LINE B = 3 NEW_LINE print ( stepscount ( A , B ) ) NEW_LINE
Check if a point is inside , outside or on a Hyperbola | Python3 program for the above approach ; Function to check if the point ( x , y ) lies inside , on or outside the given hyperbola ; Stores the value of the equation ; Generate output based on value of p ; Driver Code
from math import pow NEW_LINE def checkpoint ( h , k , x , y , a , b ) : NEW_LINE INDENT p = ( ( pow ( ( x - h ) , 2 ) // pow ( a , 2 ) ) - ( pow ( ( y - k ) , 2 ) // pow ( b , 2 ) ) ) NEW_LINE if ( p > 1 ) : NEW_LINE INDENT print ( " Outside " ) NEW_LINE DEDENT elif ( p == 1 ) : NEW_LINE INDENT print ( " On ▁ the ▁ Hyperbola " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Inside " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT h = 0 NEW_LINE k = 0 NEW_LINE x = 2 NEW_LINE y = 1 NEW_LINE a = 4 NEW_LINE b = 5 NEW_LINE checkpoint ( h , k , x , y , a , b ) NEW_LINE DEDENT
Count subarrays having even Bitwise XOR | Function to count the number of subarrays having even Bitwise XOR ; Store the required result ; Generate subarrays with arr [ i ] as the first element ; Store XOR of current subarray ; Generate subarrays with arr [ j ] as the last element ; Calculate Bitwise XOR of the current subarray ; If XOR is even , increase ans by 1 ; Prthe result ; Driver Code ; Given array ; Stores the size of the array ; Function Call
def evenXorSubarray ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT XOR = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT XOR = XOR ^ arr [ j ] NEW_LINE if ( ( XOR & 1 ) == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE evenXorSubarray ( arr , N ) NEW_LINE DEDENT
Modify a Binary String by flipping characters such that any pair of indices consisting of 1 s are neither co | Function to modify a string such that there doesn 't exist any pair of indices consisting of 1s, whose GCD is 1 and are divisible by each other ; Flips characters at indices 4 N , 4 N - 2 , 4 N - 4 . ... upto N terms ; Print the string ; Driver code ; Initialize the string S ; function call
def findString ( S , N ) : NEW_LINE INDENT strLen = 4 * N NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT S [ strLen - 1 ] = '1' NEW_LINE strLen -= 2 NEW_LINE DEDENT for i in range ( 4 * N ) : NEW_LINE INDENT print ( S [ i ] , end = " " ) NEW_LINE DEDENT DEDENT N = 2 NEW_LINE S = [ 0 ] * ( 4 * N ) NEW_LINE for i in range ( 4 * N ) : NEW_LINE INDENT S [ i ] = '0' NEW_LINE DEDENT findString ( S , N ) NEW_LINE
Check if a string can be split into two substrings with equal number of vowels | Function to check if any character is a vowel or not ; Lowercase vowels ; Uppercase vowels ; Otherwise ; Function to check if string S can be split into two substrings with equal number of vowels ; Stores the count of vowels in the string S ; Traverse over the string ; If S [ i ] is vowel ; Stores the count of vowels upto the current index ; Traverse over the string ; If S [ i ] is vowel ; If vowelsTillNow and totalVowels are equal ; Otherwise ; Driver Code
def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ch == ' A ' or ch == ' E ' or ch == ' I ' or ch == ' O ' or ch == ' U ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def containsEqualStrings ( S ) : NEW_LINE INDENT totalVowels = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( isVowel ( S [ i ] ) ) : NEW_LINE INDENT totalVowels += 1 NEW_LINE DEDENT DEDENT vowelsTillNow = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( isVowel ( S [ i ] ) ) : NEW_LINE INDENT vowelsTillNow += 1 NEW_LINE totalVowels -= 1 NEW_LINE if ( vowelsTillNow == totalVowels ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT DEDENT return " No " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeks " NEW_LINE print ( containsEqualStrings ( S ) ) NEW_LINE DEDENT
Maximize matrix sum by repeatedly multiplying pairs of adjacent elements with | Python3 program to implement the above approach ; Function to calculate maximum sum possible of a matrix by multiplying pairs of adjacent elements with - 1 any number of times ( possibly zero ) ; Store the maximum sum of matrix possible ; Stores the count of negative values in the matrix ; Store minimum absolute value present in the matrix ; Traverse the matrix row - wise ; Update sum ; If current element is negative , increment the negative count ; If current value is less than the overall minimum in A [ ] , update the overall minimum ; If there are odd number of negative values , then the answer will be sum of the absolute values of all elements - 2 * minVal ; Print maximum sum ; Driver Code ; Given matrix ; Dimensions of matrix
import sys NEW_LINE def getMaxSum ( A , M , N ) : NEW_LINE INDENT sum = 0 NEW_LINE negative = 0 NEW_LINE minVal = sys . maxsize NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT sum += abs ( A [ i ] [ j ] ) NEW_LINE if ( A [ i ] [ j ] < 0 ) : NEW_LINE INDENT negative += 1 NEW_LINE DEDENT minVal = min ( minVal , abs ( A [ i ] [ j ] ) ) NEW_LINE DEDENT DEDENT if ( negative % 2 ) : NEW_LINE INDENT sum -= 2 * minVal NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 4 , - 8 , 6 ] , [ 3 , 7 , 2 ] ] NEW_LINE M = len ( A ) NEW_LINE N = len ( A [ 0 ] ) NEW_LINE getMaxSum ( A , M , N ) NEW_LINE DEDENT
Calculate total wall area of houses painted | Function to find the total area of walls painted in N row - houses ; Stores total area of N row - houses that needs to be painted ; Traverse the array of wall heights ; Update total area painted ; Update total ; Traverse all the houses and print the shared walls ; Update total ; Print total area needs to paint ; Driver Code ; Given N , W & L ; Given heights of houses ; Function Call
def areaToPaint ( N , W , L , Heights ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT total += 2 * Heights [ i ] * W NEW_LINE DEDENT total += L * ( Heights [ 0 ] + Heights [ N - 1 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT total += L * abs ( Heights [ i ] - Heights [ i - 1 ] ) NEW_LINE DEDENT print ( total ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE W = 1 NEW_LINE L = 1 NEW_LINE Heights = [ 4 , 3 , 1 , 2 , 3 , 4 , 2 ] NEW_LINE areaToPaint ( N , W , L , Heights ) NEW_LINE DEDENT
Maximize sum of count of distinct prime factors of K array elements | Python 3 program for the above approach ; Function to find the maximum sum of count of distinct prime factors of K array elements ; Stores the count of distinct primes ; Stores 1 and 0 at prime and non - prime indices respectively ; Initialize the count of factors to 0 ; Sieve of Eratosthenes ; Count of factors of a prime number is 1 ; Increment CountDistinct of all multiples of i ; Mark its multiples non - prime ; Stores the maximum sum of distinct prime factors of K array elements ; Stores the count of all distinct prime factors ; Traverse the array to find count of all array elements ; Maximum sum of K prime factors of array elements ; Check for the largest prime factor ; Increment sum ; Decrement its count and K ; Print the maximum sum ; Driver code ; Given array ; Size of the array ; Given value of K
MAX = 1000000 NEW_LINE def maxSumOfDistinctPrimeFactors ( arr , N , K ) : NEW_LINE INDENT CountDistinct = [ 0 ] * ( MAX + 1 ) NEW_LINE prime = [ False ] * ( MAX + 1 ) NEW_LINE for i in range ( MAX + 1 ) : NEW_LINE INDENT CountDistinct [ i ] = 0 NEW_LINE prime [ i ] = True NEW_LINE DEDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT CountDistinct [ i ] = 1 NEW_LINE for j in range ( i * 2 , MAX + 1 , i ) : NEW_LINE INDENT CountDistinct [ j ] += 1 NEW_LINE prime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT sum = 0 NEW_LINE PrimeFactor = [ 0 ] * 20 NEW_LINE for i in range ( N ) : NEW_LINE INDENT PrimeFactor [ CountDistinct [ arr [ i ] ] ] += 1 NEW_LINE DEDENT for i in range ( 19 , 0 , - 1 ) : NEW_LINE INDENT while ( PrimeFactor [ i ] > 0 ) : NEW_LINE INDENT sum += i NEW_LINE PrimeFactor [ i ] -= 1 NEW_LINE K -= 1 NEW_LINE if ( K == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( K == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 9 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE maxSumOfDistinctPrimeFactors ( arr , N , K ) NEW_LINE DEDENT
Minimum replacements such that no palindromic substring of length exceeding 1 is present in the given string | Function to count the changes required such that no palindromic subof length exceeding 1 is present in the string ; ; Stores the count ; Iterate over the string ; Palindromic Subof Length 2 ; Replace the next character ; Increment changes ; Palindromic Subof Length 3 ; Replace the next character ; Increment changes ; Driver Code
def maxChange ( str ) : NEW_LINE INDENT str = [ i for i in str ] NEW_LINE DEDENT / * Base Case * / NEW_LINE INDENT if ( len ( str ) <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT minChanges = 0 NEW_LINE for i in range ( len ( str ) - 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ i + 1 ] ) : NEW_LINE INDENT str [ i + 1 ] = ' N ' NEW_LINE minChanges += 1 NEW_LINE DEDENT elif ( i > 0 and str [ i - 1 ] == str [ i + 1 ] ) : NEW_LINE INDENT str [ i + 1 ] = ' N ' NEW_LINE minChanges += 1 NEW_LINE DEDENT DEDENT return minChanges NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " bbbbbbb " NEW_LINE print ( maxChange ( str ) ) NEW_LINE DEDENT
Smallest positive integer K such that all array elements can be made equal by incrementing or decrementing by at most K | Function to find smallest integer K such that incrementing or decrementing each element by K at most once makes all elements equal ; Store distinct array elements ; Traverse the array , A [ ] ; Count elements into the set ; Iterator to store first element of B ; If M is greater than 3 ; If M is equal to 3 ; Stores the first smallest element ; Stores the second smallest element ; Stores the largest element ; IF difference between B_2 and B_1 is equal to B_3 and B_2 ; If M is equal to 2 ; Stores the smallest element ; Stores the largest element ; If difference is an even ; If M is equal to 1 ; Driver Code ; Given array ; Given size ; Print the required smallest integer
def findMinKToMakeAllEqual ( N , A ) : NEW_LINE INDENT B = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT B [ A [ i ] ] = 1 NEW_LINE DEDENT M = len ( B ) NEW_LINE itr , i = list ( B . keys ( ) ) , 0 NEW_LINE if ( M > 3 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT elif ( M == 3 ) : NEW_LINE INDENT B_1 , i = itr [ i ] , i + 1 NEW_LINE B_2 , i = itr [ i ] , i + 1 NEW_LINE B_3 , i = itr [ i ] , i + 1 NEW_LINE if ( B_2 - B_1 == B_3 - B_2 ) : NEW_LINE INDENT print ( B_2 - B_1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT elif ( M == 2 ) : NEW_LINE INDENT B_1 , i = itr [ i ] , i + 1 NEW_LINE B_2 , i = itr [ i ] , i + 1 NEW_LINE if ( ( B_2 - B_1 ) % 2 == 0 ) : NEW_LINE INDENT print ( ( B_2 - B_1 ) // 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( B_2 - B_1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 3 , 5 , 1 ] NEW_LINE N = len ( A ) NEW_LINE findMinKToMakeAllEqual ( N , A ) NEW_LINE DEDENT
Maximum number of times a given string needs to be concatenated to form a substring of another string | Function to find lps [ ] for given pattern pat [ 0. . M - 1 ] ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Iterate string to calculate lps [ i ] ; If the current character of the pattern matches ; Otherwise ; Otherwise ; Function to implement KMP algorithm ; Stores the longest prefix and suffix values for pattern ; Preprocess the pattern and find the lps [ ] array ; Index for txt [ ] ; Index for pat [ ] ; If pattern is found return 1 ; Mismatch after j matches ; Don 't match lps[0, lps[j - 1]] characters they will match anyway ; Return 0 if the pattern is not found ; Function to find the maximum value K for which S2 concatenated K times is a subof S1 ; Store the required maximum number ; Create a temporary to store word ; Store the maximum number of times S2 can occur in S1 ; Traverse in range [ 0 , numWords - 1 ] ; If curWord is found in sequence ; Concatenate word to curWord ; Increment resCount by 1 ; Otherwise break the loop ; Print the answer ; Driver Code ; Function Call
def computeLPSArray ( pat , M , lps ) : NEW_LINE INDENT lenn = 0 NEW_LINE lps [ 0 ] = 0 NEW_LINE i = 1 NEW_LINE while ( i < M ) : NEW_LINE INDENT if ( pat [ i ] == pat [ lenn ] ) : NEW_LINE INDENT lenn += 1 NEW_LINE lps [ i ] = lenn NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( lenn != 0 ) : NEW_LINE INDENT lenn = lps [ lenn - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lps [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def KMPSearch ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE lps = [ 0 for i in range ( M ) ] NEW_LINE computeLPSArray ( pat , M , lps ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT if ( pat [ j ] == txt [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( j == M ) : NEW_LINE INDENT return 1 NEW_LINE j = lps [ j - 1 ] NEW_LINE DEDENT elif ( i < N and pat [ j ] != txt [ i ] ) : NEW_LINE INDENT if ( j != 0 ) : NEW_LINE INDENT j = lps [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT def maxRepeating ( seq , word ) : NEW_LINE INDENT resCount = 0 NEW_LINE curWord = word NEW_LINE numWords = len ( seq ) // len ( word ) NEW_LINE for i in range ( numWords ) : NEW_LINE INDENT if ( KMPSearch ( curWord , seq ) ) : NEW_LINE INDENT curWord += word NEW_LINE resCount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( resCount ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 , S2 = " ababc " , " ab " NEW_LINE maxRepeating ( S1 , S2 ) NEW_LINE DEDENT
Count all possible strings that can be generated by placing spaces | Function to count the number of strings that can be generated by placing spaces between pair of adjacent characters ; Length of the string ; Count of positions for spaces ; Count of possible strings ; Driver Code
def countNumberOfStrings ( s ) : NEW_LINE INDENT length = len ( s ) NEW_LINE n = length - 1 NEW_LINE count = 2 ** n NEW_LINE return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ABCD " NEW_LINE print ( countNumberOfStrings ( S ) ) NEW_LINE DEDENT
Minimum time required to reach a given score | Function to calculate minimum time required to achieve given score target ; Store the frequency of elements ; Traverse the array p [ ] ; Update the frequency ; Stores the minimim time required ; Store the current score at any time instant t ; Iterate until sum is at least equal to target ; Increment time with every iteration ; Traverse the map ; Increment the points ; Prthe time required ; Driver Code ; Function Call
def findMinimumTime ( p , n , target ) : NEW_LINE INDENT um = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT um [ p [ i ] ] = um . get ( p [ i ] , 0 ) + 1 NEW_LINE DEDENT time = 0 NEW_LINE sum = 0 NEW_LINE while ( sum < target ) : NEW_LINE INDENT sum = 0 NEW_LINE time += 1 NEW_LINE for it in um : NEW_LINE INDENT sum += um [ it ] * ( time // it ) NEW_LINE DEDENT DEDENT print ( time ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE target = 10 NEW_LINE findMinimumTime ( arr , N , target ) NEW_LINE DEDENT
Construct MEX array from the given array | Python3 program for the above approach ; Function to construct array B [ ] that stores MEX of array A [ ] excluding A [ i ] ; Stores elements present in arr [ ] ; Mark all values 1 , if present ; Initialize variable to store MEX ; Find MEX of arr [ ] ; Stores MEX for all indices ; Traverse the given array ; Update MEX ; MEX default ; Prthe array B ; Driver Code ; Given array ; Size of array ; Function call
MAXN = 100001 NEW_LINE def constructMEX ( arr , N ) : NEW_LINE INDENT hash = [ 0 ] * MAXN NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash [ arr [ i ] ] = 1 NEW_LINE DEDENT MexOfArr = 0 NEW_LINE for i in range ( 1 , MAXN ) : NEW_LINE INDENT if ( hash [ i ] == 0 ) : NEW_LINE INDENT MexOfArr = i NEW_LINE break NEW_LINE DEDENT DEDENT B = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < MexOfArr ) : NEW_LINE INDENT B [ i ] = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT B [ i ] = MexOfArr NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( B [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE constructMEX ( arr , N ) NEW_LINE DEDENT
Minimize remaining array element by repeatedly replacing pairs by half of one more than their sum | Function to print smallest element left in the array and the pairs by given operation ; Stores array elements and return the minimum element of arr [ ] in O ( 1 ) ; Stores all the pairs that can be selected by the given operations ; Traverse the array arr [ ] ; Traverse pq while count of elements left in pq greater than 1 ; Stores top element of pq ; Pop top element of pq ; Stores top element of pq ; Pop top element of pq ; Insert ( X + Y + 1 ) / 2 in pq ; Insert the pair ( X , Y ) in pairsArr [ ] ; Print element left in pq by performing the given operations ; Stores count of elements in pairsArr [ ] ; Print the pairs that can be selected in given operations ; If i is the first index of pairsArr [ ] ; Print pairs of pairsArr [ ] ; If i is not the last index of pairsArr [ ] ; If i is the last index of pairsArr [ ] ; Driver Code
def smallestNumberLeftInPQ ( arr , N ) : NEW_LINE INDENT pq = [ ] NEW_LINE pairsArr = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( arr [ i ] ) NEW_LINE DEDENT pq = sorted ( pq ) NEW_LINE while ( len ( pq ) > 1 ) : NEW_LINE INDENT X = pq [ - 1 ] NEW_LINE del pq [ - 1 ] NEW_LINE Y = pq [ - 1 ] NEW_LINE del pq [ - 1 ] NEW_LINE pq . append ( ( X + Y + 1 ) // 2 ) NEW_LINE pairsArr . append ( [ X , Y ] ) NEW_LINE pq = sorted ( pq ) NEW_LINE DEDENT print ( " { " , pq [ - 1 ] , " } , ▁ " , end = " " ) NEW_LINE sz = len ( pairsArr ) NEW_LINE for i in range ( sz ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT print ( " { ▁ " , end = " " ) NEW_LINE DEDENT print ( " ( " , pairsArr [ i ] [ 0 ] , " , " , pairsArr [ i ] [ 1 ] , " ) " , end = " " ) NEW_LINE if ( i != sz - 1 ) : NEW_LINE INDENT print ( end = " , ▁ " ) NEW_LINE DEDENT if ( i == sz - 1 ) : NEW_LINE INDENT print ( end = " ▁ } " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE smallestNumberLeftInPQ ( arr , N ) NEW_LINE DEDENT
Move weighting scale alternate under given constraints | DFS method to traverse among states of weighting scales ; If we reach to more than required steps , return true ; Try all possible weights and choose one which returns 1 afterwards ; Try this weight only if it is greater than current residueand not same as previous chosen weight ; assign this weight to array and recur for next state ; if any weight is not possible , return false ; method prints weights for alternating scale and if not possible prints ' not ▁ possible ' ; call dfs with current residue as 0 and current steps as 0 ; Driver Code
def dfs ( residue , curStep , wt , arr , N , steps ) : NEW_LINE INDENT if ( curStep >= steps ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > residue and arr [ i ] != wt [ curStep - 1 ] ) : NEW_LINE INDENT wt [ curStep ] = arr [ i ] NEW_LINE if ( dfs ( arr [ i ] - residue , curStep + 1 , wt , arr , N , steps ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def printWeightsOnScale ( arr , N , steps ) : NEW_LINE INDENT wt = [ 0 ] * ( steps ) NEW_LINE if ( dfs ( 0 , 0 , wt , arr , N , steps ) ) : NEW_LINE INDENT for i in range ( steps ) : NEW_LINE INDENT print ( wt [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Not ▁ possible " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE steps = 10 NEW_LINE printWeightsOnScale ( arr , N , steps ) NEW_LINE DEDENT
Minimum removals required such that sum of remaining array modulo M is X | Python3 program for the above approach ; Function to find the minimum elements having sum x ; Initialize dp table ; Pre - compute subproblems ; If mod is smaller than element ; Minimum elements with sum j upto index i ; Return answer ; Function to find minimum number of removals to make sum % M in remaining array is equal to X ; Sum of all elements ; Sum to be removed ; Print answer ; Driver Code ; Given array ; Given size ; Given mod and x ; Function call
import sys NEW_LINE def findSum ( S , n , x ) : NEW_LINE INDENT table = [ [ 0 for x in range ( x + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , x + 1 ) : NEW_LINE INDENT table [ 0 ] [ i ] = sys . maxsize - 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , x + 1 ) : NEW_LINE INDENT if ( S [ i - 1 ] > j ) : NEW_LINE INDENT table [ i ] [ j ] = table [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT table [ i ] [ j ] = min ( table [ i - 1 ] [ j ] , table [ i ] [ j - S [ i - 1 ] ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT if ( table [ n ] [ x ] > n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return table [ n ] [ x ] NEW_LINE DEDENT def minRemovals ( arr , n , m , x ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT requied_Sum = 0 NEW_LINE if ( sum % m < x ) : NEW_LINE INDENT requied_Sum = m + sum % m - x NEW_LINE DEDENT else : NEW_LINE INDENT requied_Sum = sum % m - x NEW_LINE DEDENT print ( findSum ( arr , n , requied_Sum ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE m = 4 NEW_LINE x = 2 NEW_LINE minRemovals ( arr , n , m , x % m ) NEW_LINE DEDENT
Count minimum character replacements required such that given string satisfies the given conditions | Function that finds the minimum count of steps required to make the string special ; Stores the frequency of the left & right half of string ; Find frequency of left half ; Find frequency of left half ; Make all characters equal to character c ; Case 1 : For s [ i ] < s [ j ] ; Subtract all the characters on left side that are <= d ; Adding all characters on the right side that same as d ; Find minimum value of count ; Similarly for Case 2 : s [ i ] > s [ j ] ; Return the minimum changes ; Driver Code ; Given string S ; Function Call
def minChange ( s , n ) : NEW_LINE INDENT L = [ 0 ] * 26 ; NEW_LINE R = [ 0 ] * 26 ; NEW_LINE for i in range ( 0 , n // 2 ) : NEW_LINE INDENT ch = s [ i ] ; NEW_LINE L [ ord ( ch ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( n // 2 , n ) : NEW_LINE INDENT ch = s [ i ] ; NEW_LINE R [ ord ( ch ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT count = n ; NEW_LINE for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) ) : NEW_LINE INDENT count = min ( count , n - L [ ch - ord ( ' a ' ) ] - R [ ch - ord ( ' a ' ) ] ) ; NEW_LINE DEDENT change = n / 2 ; NEW_LINE for d in range ( 0 , 25 ) : NEW_LINE INDENT change -= L [ d ] ; NEW_LINE change += R [ d ] ; NEW_LINE count = min ( count , change ) ; NEW_LINE DEDENT change = n / 2 ; NEW_LINE for d in range ( 0 , 25 ) : NEW_LINE INDENT change -= R [ d ] ; NEW_LINE change += L [ d ] ; NEW_LINE count = min ( change , count ) ; NEW_LINE DEDENT return int ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " aababc " ; NEW_LINE N = len ( S ) ; NEW_LINE print ( minChange ( S , N ) ) ; NEW_LINE DEDENT
Rearrange string to obtain Longest Palindromic Substring | Function to rearrange the string to get the longest palindromic substring ; Stores the length of str ; Store the count of occurrence of each character ; Traverse the string , str ; Count occurrence of each character ; Store the left half of the longest palindromic substring ; Store the right half of the longest palindromic substring ; Traverse the array , hash [ ] ; Append half of the characters to res1 ; Append half of the characters to res2 ; reverse string res2 to make res1 + res2 palindrome ; Store the remaining characters ; Check If any odd character appended to the middle of the resultant string or not ; Append all the character which occurs odd number of times ; If count of occurrence of characters is odd ; Driver Code
def longestPalinSub ( st ) : NEW_LINE INDENT N = len ( st ) NEW_LINE hash1 = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash1 [ ord ( st [ i ] ) ] += 1 NEW_LINE DEDENT res1 = " " NEW_LINE res2 = " " NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT for j in range ( hash1 [ i ] // 2 ) : NEW_LINE INDENT res1 += chr ( i ) NEW_LINE DEDENT for j in range ( ( hash1 [ i ] + 1 ) // 2 , hash1 [ i ] ) : NEW_LINE INDENT res2 += chr ( i ) NEW_LINE DEDENT DEDENT p = list ( res2 ) NEW_LINE p . reverse ( ) NEW_LINE res2 = ' ' . join ( p ) NEW_LINE res3 = " " NEW_LINE f = False NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( hash1 [ i ] % 2 ) : NEW_LINE INDENT if ( not f ) : NEW_LINE INDENT res1 += chr ( i ) NEW_LINE f = True NEW_LINE DEDENT else : NEW_LINE INDENT res3 += chr ( i ) NEW_LINE DEDENT DEDENT DEDENT return ( res1 + res2 + res3 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " geeksforgeeks " NEW_LINE print ( longestPalinSub ( st ) ) NEW_LINE DEDENT
Maximize subsequences having array elements not exceeding length of the subsequence | Python3 program for the above approach ; Function to calculate the number of subsequences that can be formed ; Stores the number of subsequences ; Iterate over the map ; Count the number of subsequences that can be formed from x . first ; Number of occurrences of x . first which are left ; Return the number of subsequences ; Function to create the maximum count of subsequences that can be formed ; Stores the frequency of arr [ ] ; Update the frequency ; Print the number of subsequences ; Driver Code ; Given array arr [ ] ; Function Call
from collections import defaultdict NEW_LINE def No_Of_subsequences ( mp ) : NEW_LINE INDENT count = 0 NEW_LINE left = 0 NEW_LINE for x in mp : NEW_LINE INDENT mp [ x ] += left NEW_LINE count += ( mp [ x ] // x ) NEW_LINE left = mp [ x ] % x NEW_LINE DEDENT return count NEW_LINE DEDENT def maximumsubsequences ( arr , n ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT print ( No_Of_subsequences ( mp ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE maximumsubsequences ( arr , N ) NEW_LINE DEDENT
Check if concatenation of any permutation of given list of arrays generates the given array | Python3 program for the above approach ; Function to check if it is possible to obtain array by concatenating the arrays in list pieces [ ] ; Stores the index of element in the given array arr [ ] ; Traverse over the list pieces ; If item size is 1 and exists in map ; If item contains > 1 element then check order of element ; If end of the array ; Check the order of elements ; If order is same as the array elements ; Increment idx ; If order breaks ; Otherwise ; Return false if the first element doesn 't exist in m ; Return true ; Driver Code ; Given target list ; Given array of list ; Function call
from array import * NEW_LINE def check ( arr , pieces ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT m [ arr [ i ] ] = i + 1 NEW_LINE DEDENT for i in range ( 0 , len ( pieces ) ) : NEW_LINE INDENT if ( len ( pieces [ i ] ) == 1 and m [ pieces [ i ] [ 0 ] ] != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( len ( pieces [ i ] ) > 1 and m [ pieces [ i ] [ 0 ] ] != 0 ) : NEW_LINE INDENT idx = m [ pieces [ i ] [ 0 ] ] - 1 NEW_LINE idx = idx + 1 NEW_LINE if idx >= len ( arr ) : NEW_LINE INDENT return False NEW_LINE DEDENT for j in range ( 1 , len ( pieces [ i ] ) ) : NEW_LINE INDENT if arr [ idx ] == pieces [ i ] [ j ] : NEW_LINE INDENT idx = idx + 1 NEW_LINE if ( idx >= len ( arr ) and j < len ( pieces [ i ] ) - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 3 ] NEW_LINE pieces = [ [ 1 ] , [ 4 , 3 ] , [ 2 ] ] NEW_LINE if check ( arr , pieces ) == True : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Modify given array to make sum of odd and even indexed elements same | Function to modify array to make sum of odd and even indexed elements equal ; Stores the count of 0 s , 1 s ; Stores sum of odd and even indexed elements respectively ; Count 0 s ; Count 1 s ; Calculate odd_sum and even_sum ; If both are equal ; Print the original array ; Otherwise ; Print all the 0 s ; For checking even or odd ; Update total count of 1 s ; Print all 1 s ; Given array arr [ ] ; Function call
def makeArraySumEqual ( a , N ) : NEW_LINE INDENT count_0 = 0 NEW_LINE count_1 = 0 NEW_LINE odd_sum = 0 NEW_LINE even_sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT if ( ( i + 1 ) % 2 == 0 ) : NEW_LINE INDENT even_sum += a [ i ] NEW_LINE DEDENT elif ( ( i + 1 ) % 2 > 0 ) : NEW_LINE INDENT odd_sum += a [ i ] NEW_LINE DEDENT DEDENT if ( odd_sum == even_sum ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( count_0 >= N / 2 ) : NEW_LINE INDENT for i in range ( count_0 ) : NEW_LINE INDENT print ( "0" , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT is_Odd = count_1 % 2 NEW_LINE count_1 -= is_Odd NEW_LINE for i in range ( count_1 ) : NEW_LINE INDENT print ( "1" , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 1 , 1 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE makeArraySumEqual ( arr , N ) NEW_LINE
Minimum replacement of pairs by their LCM required to reduce given array to its LCM | Python3 program for the above approach ; Boolean array to set or unset prime non - prime indices ; Stores the prefix sum of the count of prime numbers ; Function to check if a number is prime or not from 0 to N ; If p is a prime ; Set its multiples as non - prime ; Function to store the count of prime numbers ; Function to count the operations to reduce the array to one element by replacing each pair with its LCM ; Generating Prime Number ; Corner Case ; Driver code ; Given array arr ; Function call
maxm = 10001 ; NEW_LINE prime = [ True ] * ( maxm + 1 ) ; NEW_LINE prime_number = [ 0 ] * ( maxm + 1 ) ; NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT for p in range ( 2 , ( int ( maxm ** 1 / 2 ) ) ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , maxm , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT prime [ 0 ] = False ; NEW_LINE prime [ 1 ] = False ; NEW_LINE DEDENT def num_prime ( ) : NEW_LINE INDENT prime_number [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , maxm + 1 ) : NEW_LINE INDENT tmp = - 1 ; NEW_LINE if ( prime [ i ] == True ) : NEW_LINE INDENT tmp = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT tmp = 0 ; NEW_LINE DEDENT prime_number [ i ] = prime_number [ i - 1 ] + tmp ; NEW_LINE DEDENT DEDENT def min_steps ( arr , n ) : NEW_LINE INDENT SieveOfEratosthenes ( ) ; NEW_LINE num_prime ( ) ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT print ( "0" ) ; NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT print ( "1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( prime_number [ n ] - 1 + ( n - 2 ) ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 3 , 2 , 1 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE min_steps ( arr , N ) ; NEW_LINE DEDENT
Find the winner of a game of removing any number of stones from the least indexed non | Function to find the winner of game between A and B ; win = 1 means B is winner win = 0 means A is winner ; If size is even , winner is B ; If size is odd , winner is A ; Stone will be removed by B ; B will take n - 1 stones from current pile having n stones and force A to pick 1 stone ; Stone will be removed by A ; A will take n - 1 stones from current pile having n stones and force B to pick 1 stone ; Print the winner accordingly ; Driver Code ; Given piles of stone ; Function call
def findWinner ( a , n ) : NEW_LINE INDENT win = 0 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT win = 1 NEW_LINE DEDENT else : NEW_LINE INDENT win = 0 NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT if ( win == 0 and a [ i ] > 1 ) : NEW_LINE INDENT win = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( win == 1 and a [ i ] > 1 ) : NEW_LINE INDENT win = 0 NEW_LINE DEDENT DEDENT DEDENT if ( win == 0 ) : NEW_LINE INDENT print ( " A " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " B " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE findWinner ( arr , N ) NEW_LINE DEDENT
Check if a destination is reachable from source with two movements allowed | Set 2 | Check if ( x2 , y2 ) can be reached from ( x1 , y1 ) ; Reduce x2 by y2 until it is less than or equal to x1 ; Reduce y2 by x2 until it is less than or equal to y1 ; If x2 is reduced to x1 ; Check if y2 can be reduced to y1 or not ; If y2 is reduced to y1 ; Check if x2 can be reduced to x1 or not ; Driver Code
def isReachable ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT while ( x2 > x1 and y2 > y1 ) : NEW_LINE INDENT if ( x2 > y2 ) : NEW_LINE INDENT x2 %= y2 NEW_LINE DEDENT else : NEW_LINE INDENT y2 %= x2 NEW_LINE DEDENT DEDENT if ( x2 == x1 ) : NEW_LINE INDENT return ( y2 - y1 ) >= 0 and ( y2 - y1 ) % x1 == 0 NEW_LINE DEDENT elif ( y2 == y1 ) : NEW_LINE INDENT return ( x2 - x1 ) >= 0 and ( x2 - x1 ) % y1 == 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT source_x = 2 NEW_LINE source_y = 10 NEW_LINE dest_x = 26 NEW_LINE dest_y = 12 NEW_LINE if ( isReachable ( source_x , source_y , dest_x , dest_y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find the player who wins the game by removing the last of given N cards | Function to check which player can win the game ; Driver Code
def checkWinner ( N , K ) : NEW_LINE INDENT if ( N % ( K + 1 ) ) : NEW_LINE INDENT print ( " A " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " B " ) NEW_LINE DEDENT DEDENT N = 50 NEW_LINE K = 10 NEW_LINE checkWinner ( N , K ) NEW_LINE
Length of longest subarray having only K distinct Prime Numbers | Python3 program to implement the above approach ; Function to precalculate all the prime up to 10 ^ 6 ; Initialize prime to true ; Iterate [ 2 , sqrt ( N ) ] ; If p is prime ; Mark all multiple of p as true ; Function that finds the length of longest subarray K distinct primes ; Precompute all prime up to 2 * 10 ^ 6 ; Keep track occurrence of prime ; Initialize result to - 1 ; If number is prime then increment its count and decrease k ; Decrement K ; Remove required elements till k become non - negative ; Decrease count so that it may appear in another subarray appearing after this present subarray ; Increment K ; Take the max value as length of subarray ; Return the final length ; Given array arr [ ] ; Function call
from collections import defaultdict NEW_LINE isprime = [ True ] * 2000010 NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT isprime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( isprime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT isprime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def KDistinctPrime ( arr , n , k ) : NEW_LINE INDENT SieveOfEratosthenes ( 2000000 ) NEW_LINE cnt = defaultdict ( lambda : 0 ) NEW_LINE result = - 1 NEW_LINE j = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE if ( isprime [ x ] ) : NEW_LINE INDENT cnt [ x ] += 1 NEW_LINE if ( cnt [ x ] == 1 ) : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT DEDENT DEDENT while ( k < 0 ) : NEW_LINE INDENT j += 1 NEW_LINE x = arr [ j ] NEW_LINE if ( isprime [ x ] ) : NEW_LINE INDENT cnt [ x ] -= 1 NEW_LINE if ( cnt [ x ] == 0 ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT if ( k == 0 ) : NEW_LINE INDENT result = max ( result , i - j ) NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( KDistinctPrime ( arr , N , K ) ) NEW_LINE
Smallest composite number not divisible by first N prime numbers | Initializing the max value ; Function to generate N prime numbers using Sieve of Eratosthenes ; Stores the primes ; Setting all numbers to be prime initially ; If a prime number is encountered ; Set all its multiples as composites ; Store all the prime numbers ; Function to find the square of the ( N + 1 ) - th prime number ; Driver Code ; Stores all prime numbers
MAX_SIZE = 1000005 NEW_LINE def SieveOfEratosthenes ( StorePrimes ) : NEW_LINE INDENT IsPrime = [ True for i in range ( MAX_SIZE ) ] NEW_LINE p = 2 NEW_LINE while ( p * p < MAX_SIZE ) : NEW_LINE INDENT if ( IsPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX_SIZE , p ) : NEW_LINE INDENT IsPrime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , MAX_SIZE ) : NEW_LINE INDENT if ( IsPrime [ p ] ) : NEW_LINE INDENT StorePrimes . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def Smallest_non_Prime ( StorePrimes , N ) : NEW_LINE INDENT x = StorePrimes [ N ] NEW_LINE return x * x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE StorePrimes = [ ] NEW_LINE SieveOfEratosthenes ( StorePrimes ) NEW_LINE print ( Smallest_non_Prime ( StorePrimes , N ) ) NEW_LINE DEDENT
Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | Python3 program for the above approach ; Function to print the required N - th subset ; Nearest power of 2 <= N ; Now insert k ^ p in the answer ; Update N ; Print the subset ; Driver Code
import math NEW_LINE def printSubset ( N , K ) : NEW_LINE INDENT answer = " " NEW_LINE while ( N > 0 ) : NEW_LINE INDENT p = int ( math . log ( N , 2 ) ) NEW_LINE answer = str ( K ** p ) + " ▁ " + answer NEW_LINE N = N % ( 2 ** p ) NEW_LINE DEDENT print ( answer ) NEW_LINE DEDENT N = 5 NEW_LINE K = 4 NEW_LINE printSubset ( N , K ) NEW_LINE
Count total set bits in all numbers from range L to R | Returns position of leftmost set bit The rightmost position is taken as 0 ; Function that gives the position of previous leftmost set bit in n ; Function that returns count of set bits present in all numbers from 1 to n ; Get the position of leftmost set bit in n ; Use the position ; Function to count the set bits between the two numbers N and M ; Base Case ; Get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 ; Update n for next recursive call ; Function that counts the set bits between L and R ; Driver Code ; Given L and R ; Function Call
def getLeftmostBit ( n ) : NEW_LINE INDENT m = 0 ; NEW_LINE while ( n > 1 ) : NEW_LINE INDENT n = n >> 1 ; NEW_LINE m += 1 ; NEW_LINE DEDENT return m ; NEW_LINE DEDENT def getNextLeftmostBit ( n , m ) : NEW_LINE INDENT temp = 1 << m ; NEW_LINE while ( n < temp ) : NEW_LINE INDENT temp = temp >> 1 ; NEW_LINE m -= 1 ; NEW_LINE DEDENT return m ; NEW_LINE DEDENT def countSetBit ( n ) : NEW_LINE INDENT m = getLeftmostBit ( n ) ; NEW_LINE return _countSetBit ( n , m ) ; NEW_LINE DEDENT def _countSetBit ( n , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT m = getNextLeftmostBit ( n , m ) ; NEW_LINE if ( n == int ( 1 << ( m + 1 ) ) - 1 ) : NEW_LINE INDENT return int ( m + 1 ) * ( 1 << m ) ; NEW_LINE DEDENT n = n - ( 1 << m ) ; NEW_LINE return ( ( n + 1 ) + countSetBit ( n ) + m * ( 1 << ( m - 1 ) ) ) ; NEW_LINE DEDENT def countSetBits ( L , R ) : NEW_LINE INDENT return abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; NEW_LINE R = 5 ; NEW_LINE print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT
Permutation of Array such that products of all adjacent elements are even | Function to print the required permutation ; push odd elements in ' odd ' and even elements in 'even ; Check if it possible to arrange the elements ; else print the permutation ; Print remaining odds are even . and even elements ; Driver Code
def printPermutation ( arr , n ) : NEW_LINE INDENT odd , even = [ ] , [ ] NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT odd . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT size_odd = len ( odd ) NEW_LINE size_even = len ( even ) NEW_LINE if ( size_odd > size_even + 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE while ( i < size_odd and j < size_even ) : NEW_LINE INDENT print ( odd [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE print ( even [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while ( i < size_odd ) : NEW_LINE INDENT print ( odd [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT while ( j < size_even ) : NEW_LINE INDENT print ( even [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT arr = [ 6 , 7 , 9 , 8 , 10 , 11 ] NEW_LINE N = len ( arr ) NEW_LINE printPermutation ( arr , N ) NEW_LINE
Maximize GCD of all possible pairs from 1 to N | Function to obtain the maximum gcd of all pairs from 1 to n ; Print the answer ; Driver Code ; Function call
def find ( n ) : NEW_LINE INDENT print ( n // 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE find ( n ) NEW_LINE DEDENT
Count of pairs of Array elements which are divisible by K when concatenated | Python3 program to count pairs of array elements which are divisible by K when concatenated ; Function to calculate and return the count of pairs ; Compute power of 10 modulo k ; Calculate length of a [ i ] ; Increase count of remainder ; Calculate ( a [ i ] * 10 ^ lenj ) % k ; Calculate ( k - ( a [ i ] * 10 ^ lenj ) % k ) % k ; Increase answer by count ; If a pair ( a [ i ] , a [ i ] ) is counted ; Return the count of pairs ; Driver Code
rem = [ [ 0 for x in range ( 11 ) ] for y in range ( 11 ) ] NEW_LINE def countPairs ( a , n , k ) : NEW_LINE INDENT l = [ 0 ] * n NEW_LINE p = [ 0 ] * ( 11 ) NEW_LINE p [ 0 ] = 1 NEW_LINE for i in range ( 1 , 11 ) : NEW_LINE INDENT p [ i ] = ( p [ i - 1 ] * 10 ) % k NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE while ( x > 0 ) : NEW_LINE INDENT l [ i ] += 1 NEW_LINE x //= 10 NEW_LINE DEDENT rem [ l [ i ] ] [ a [ i ] % k ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , 11 ) : NEW_LINE INDENT r = ( a [ i ] * p [ j ] ) % k NEW_LINE xr = ( k - r ) % k NEW_LINE ans += rem [ j ] [ xr ] NEW_LINE if ( l [ i ] == j and ( r + a [ i ] % k ) % k == 0 ) : NEW_LINE INDENT ans -= 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 4 , 5 , 2 ] NEW_LINE n = len ( a ) NEW_LINE k = 2 NEW_LINE print ( countPairs ( a , n , k ) ) NEW_LINE
Count of N digit Numbers whose sum of every K consecutive digits is equal | Function to count the number of N - digit numbers such that sum of every k consecutive digits are equal ; Range of numbers ; Extract digits of the number ; Store the sum of first K digits ; Check for every k - consecutive digits using sliding window ; Driver Code ; Given integer N and K
def countDigitSum ( N , K ) : 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 ( 1 , r + 1 ) : NEW_LINE INDENT num = i ; NEW_LINE digits = [ 0 ] * ( N ) ; NEW_LINE for j in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT digits [ j ] = num % 10 ; NEW_LINE num //= 10 ; NEW_LINE DEDENT sum = 0 ; NEW_LINE flag = 0 ; NEW_LINE for j in range ( 0 , K ) : NEW_LINE INDENT sum += digits [ j ] ; NEW_LINE DEDENT for j in range ( K , N ) : NEW_LINE INDENT if ( sum - digits [ j - K ] + digits [ j ] != sum ) : NEW_LINE INDENT flag = 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 ; NEW_LINE K = 1 ; NEW_LINE print ( countDigitSum ( N , K ) ) ; NEW_LINE DEDENT
Array formed using sum of absolute differences of that element with all other elements | Function to return the new array private static List < Integer > ; Length of the arraylist ; Initialize the Arraylist ; Sum of absolute differences of element with all elements ; Initialize sum to 0 ; Add the value of sum to ans ; Return the final ans ; Driver Code ; Given array arr [ ] ; Function call
def calculate ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE ans = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for j in range ( len ( arr ) ) : NEW_LINE INDENT sum += abs ( arr [ i ] - arr [ j ] ) NEW_LINE DEDENT ans . append ( sum ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 6 ] NEW_LINE print ( calculate ( arr ) ) NEW_LINE DEDENT
Number of pair of positions in matrix which are not accessible | Counts number of vertices connected in a component containing x . Stores the count in k . ; Incrementing the number of node in a connected component . ; Return the number of count of non - accessible cells . ; Initialize count of connected vertices found by DFS starting from i . ; Update result ; Inserting the edge between edge . ; Mapping the cell coordinate into node number . ; Inserting the edge . ; Driver Code
def dfs ( graph , visited , x , k ) : NEW_LINE INDENT for i in range ( len ( graph [ x ] ) ) : NEW_LINE INDENT if ( not visited [ graph [ x ] [ i ] ] ) : NEW_LINE INDENT k [ 0 ] += 1 NEW_LINE visited [ graph [ x ] [ i ] ] = True NEW_LINE dfs ( graph , visited , graph [ x ] [ i ] , k ) NEW_LINE DEDENT DEDENT DEDENT def countNonAccessible ( graph , N ) : NEW_LINE INDENT visited = [ False ] * ( N * N + N ) NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , N * N + 1 ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT visited [ i ] = True NEW_LINE k = [ 1 ] NEW_LINE dfs ( graph , visited , i , k ) NEW_LINE ans += k [ 0 ] * ( N * N - k [ 0 ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def insertpath ( graph , N , x1 , y1 , x2 , y2 ) : NEW_LINE INDENT a = ( x1 - 1 ) * N + y1 NEW_LINE b = ( x2 - 1 ) * N + y2 NEW_LINE graph [ a ] . append ( b ) NEW_LINE graph [ b ] . append ( a ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE graph = [ [ ] for i in range ( N * N + 1 ) ] NEW_LINE insertpath ( graph , N , 1 , 1 , 1 , 2 ) NEW_LINE insertpath ( graph , N , 1 , 2 , 2 , 2 ) NEW_LINE print ( countNonAccessible ( graph , N ) ) NEW_LINE DEDENT
Minimum number of distinct powers of 2 required to express a given binary number | Function to return the minimum distinct powers of 2 required to express s ; Reverse the string to start from lower powers ; Check if the character is 1 ; Add in range provided range ; Initialize the counter ; Check if the character is not 0 ; Increment the counter ; Print the result ; Driver Code
def findMinimum ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE x = [ 0 ] * ( n + 1 ) NEW_LINE s = s [ : : - 1 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT if ( x [ i ] == 1 ) : NEW_LINE INDENT x [ i + 1 ] = 1 NEW_LINE x [ i ] = 0 NEW_LINE DEDENT elif ( i and x [ i - 1 ] == 1 ) : NEW_LINE INDENT x [ i + 1 ] = 1 NEW_LINE x [ i - 1 ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x [ i ] = 1 NEW_LINE DEDENT DEDENT DEDENT c = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( x [ i ] != 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT print ( c ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "111" NEW_LINE findMinimum ( str ) NEW_LINE DEDENT
Split a Numeric String into Fibonacci Sequence | Python3 program of the above approach ; Function that returns true if Fibonacci sequence is found ; Base condition : If pos is equal to length of S and seq length is greater than 3 ; Return true ; Stores current number ; Add current digit to num ; Avoid integer overflow ; Avoid leading zeros ; If current number is greater than last two number of seq ; If seq length is less 2 or current number is is equal to the last two of the seq ; Add to the seq ; Recur for i + 1 ; Remove last added number ; If no sequence is found ; Function that prints the Fibonacci sequence from the split of string S ; Initialize a vector to store the sequence ; Call helper function ; If sequence length is greater than 3 ; Print the sequence ; If no sequence is found ; Print - 1 ; Driver Code ; Given String ; Function Call
import sys NEW_LINE def splitIntoFibonacciHelper ( pos , S , seq ) : NEW_LINE INDENT if ( pos == len ( S ) and ( len ( seq ) >= 3 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT num = 0 NEW_LINE for i in range ( pos , len ( S ) ) : NEW_LINE INDENT num = num * 10 + ( ord ( S [ i ] ) - ord ( '0' ) ) NEW_LINE if ( num > sys . maxsize ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( ord ( S [ pos ] ) == ord ( '0' ) and i > pos ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( len ( seq ) > 2 and ( num > ( seq [ - 1 ] + seq [ len ( seq ) - 2 ] ) ) ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( len ( seq ) < 2 or ( num == ( seq [ - 1 ] + seq [ len ( seq ) - 2 ] ) ) ) : NEW_LINE INDENT seq . append ( num ) NEW_LINE if ( splitIntoFibonacciHelper ( i + 1 , S , seq ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT seq . pop ( ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def splitIntoFibonacci ( S ) : NEW_LINE INDENT seq = [ ] NEW_LINE splitIntoFibonacciHelper ( 0 , S , seq ) NEW_LINE if ( len ( seq ) >= 3 ) : NEW_LINE INDENT for i in seq : NEW_LINE INDENT print ( i , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 , end = ' ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "11235813" NEW_LINE splitIntoFibonacci ( S ) NEW_LINE DEDENT
Count pair of strings whose concatenation has every vowel | Function to return the count of all concatenated string with each vowel at least once ; Creating a hash array with initial value as 0 ; Traversing through each string and getting hash value for each of them ; Initializing the weight of each string ; Find the hash value for each string ; Increasing the count of the hash value ; Getting all possible pairs of indexes in hash array ; Check if the pair which has hash value 31 and multiplying the count of string and add it strCount ; Corner case , for strings which independently has all the vowels ; Return thre final count ; Given array of strings ;
def good_pairs ( Str , N ) : NEW_LINE INDENT arr = [ 0 for i in range ( 32 ) ] NEW_LINE strCount = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT Weight = 0 NEW_LINE for j in range ( len ( Str [ i ] ) ) : NEW_LINE INDENT switcher = { ' a ' : 1 , ' e ' : 2 , ' i ' : 4 , ' o ' : 8 , ' u ' : 16 , } NEW_LINE Weight = Weight | switcher . get ( Str [ i ] [ j ] , 0 ) NEW_LINE DEDENT arr [ Weight ] += 1 NEW_LINE DEDENT for i in range ( 32 ) : NEW_LINE INDENT for j in range ( i + 1 , 32 ) : NEW_LINE INDENT if ( ( i j ) == 31 ) : NEW_LINE INDENT strCount += arr [ i ] * arr [ j ] NEW_LINE DEDENT DEDENT DEDENT strCount += int ( ( arr [ 31 ] * ( arr [ 31 ] - 1 ) ) / 2 ) NEW_LINE return strCount NEW_LINE DEDENT Str = [ " aaweiolkju " , " oxdfgujkmi " ] NEW_LINE N = len ( Str ) NEW_LINE / * Function call * / NEW_LINE print ( good_pairs ( Str , N ) ) NEW_LINE
Color a grid such that all same color cells are connected either horizontally or vertically | Python3 program to color a grid such that all same color cells are connected either horizontally or vertically ; Current color ; Final grid ; If even row ; Traverse from left to right ; If color has been exhausted , move to the next color ; Color the grid at this position print ( i , j ) ; Reduce the color count ; Traverse from right to left for odd rows ; Print the grid ; Driver code
def solve ( arr , r , c ) : NEW_LINE INDENT idx = 1 NEW_LINE dp = [ [ 0 for i in range ( c ) ] for i in range ( r ) ] NEW_LINE for i in range ( r ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT if ( arr [ idx - 1 ] == 0 ) : NEW_LINE INDENT idx += 1 NEW_LINE DEDENT dp [ i ] [ j ] = idx NEW_LINE arr [ idx - 1 ] -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for j in range ( c - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ idx - 1 ] == 0 ) : NEW_LINE INDENT idx += 1 NEW_LINE DEDENT dp [ i ] [ j ] = idx NEW_LINE arr [ idx - 1 ] -= 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT print ( dp [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT r = 3 NEW_LINE c = 5 NEW_LINE n = 5 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE solve ( arr , r , c ) NEW_LINE DEDENT
Count of 0 s to be flipped to make any two adjacent 1 s at least K 0 s apart | Function to find the count of 0 s to be flipped ; Loop traversal to mark K adjacent positions to the right of already existing 1 s . ; Loop traversal to mark K adjacent positions to the left of already existing 1 s . ; Loop to count the maximum number of 0 s that will be replaced by 1 s ; Driver code
def count ( k , s ) : NEW_LINE INDENT ar = [ 0 ] * len ( s ) NEW_LINE end = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] == '1' : NEW_LINE INDENT for j in range ( i , len ( s ) ) : NEW_LINE INDENT if ( j <= i + k ) : NEW_LINE INDENT ar [ j ] = - 1 NEW_LINE end = j NEW_LINE DEDENT DEDENT i = end NEW_LINE DEDENT DEDENT end = 0 NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT for j in range ( i , - 1 , - 1 ) : NEW_LINE INDENT if ( j >= i - k ) : NEW_LINE INDENT ar [ j ] = - 1 NEW_LINE end = j NEW_LINE DEDENT DEDENT i = end NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE end = 0 NEW_LINE for j in range ( len ( s ) ) : NEW_LINE INDENT if ( ar [ j ] == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE for g in range ( j , len ( s ) ) : NEW_LINE INDENT if ( g <= j + k ) : NEW_LINE INDENT ar [ g ] = - 1 NEW_LINE end = g NEW_LINE DEDENT DEDENT j = end - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT K = 2 NEW_LINE s = "000000" NEW_LINE print ( count ( K , s ) ) NEW_LINE
Length of longest connected 1 Γ’ €ℒ s in a Binary Grid | Python3 program for the above approach ; Keeps a track of directions that is up , down , left , right ; Function to perform the dfs traversal ; Mark the current node as visited ; Increment length from this node ; Update the diameter length ; Move to next cell in x - direction ; Move to next cell in y - direction ; Check if cell is invalid then continue ; Perform DFS on new cell ; Decrement the length ; Function to find the maximum length of connected 1 s in the given grid ; Increment the id ; Traverse the grid [ ] ; Find start point of start dfs call ; DFS Traversal from cell ( x , y ) ; Print the maximum length ; Driver Code ; Given grid [ ] [ ] ; Function Call
row = 6 NEW_LINE col = 7 NEW_LINE vis = [ [ 0 for i in range ( col + 1 ) ] for j in range ( row + 1 ) ] NEW_LINE id = 0 NEW_LINE diameter = 0 NEW_LINE length = 0 NEW_LINE dx = [ - 1 , 1 , 0 , 0 ] NEW_LINE dy = [ 0 , 0 , - 1 , 1 ] NEW_LINE def dfs ( a , b , lis , x , y ) : NEW_LINE INDENT global id , length , diameter NEW_LINE vis [ a ] [ b ] = id NEW_LINE length += 1 NEW_LINE if ( length > diameter ) : NEW_LINE INDENT x = a NEW_LINE y = b NEW_LINE diameter = length NEW_LINE DEDENT for j in range ( 4 ) : NEW_LINE INDENT cx = a + dx [ j ] NEW_LINE cy = b + dy [ j ] NEW_LINE if ( cx < 0 or cy < 0 or cx >= row or cy >= col or lis [ cx ] [ cy ] == 0 or vis [ cx ] [ cy ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( cx , cy , lis , x , y ) NEW_LINE DEDENT vis [ a ] [ b ] = 0 NEW_LINE length -= 1 NEW_LINE return x , y NEW_LINE DEDENT def findMaximumLength ( lis ) : NEW_LINE INDENT global id , length , diameter NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE id += 1 NEW_LINE length = 0 NEW_LINE diameter = 0 NEW_LINE for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT if ( lis [ i ] [ j ] != 0 ) : NEW_LINE INDENT x , y = dfs ( i , j , lis , x , y ) NEW_LINE i = row NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT id += 1 NEW_LINE length = 0 NEW_LINE diameter = 0 NEW_LINE x , y = dfs ( x , y , lis , x , y ) NEW_LINE print ( diameter ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ [ 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 0 , 1 , 0 , 1 , 0 ] , [ 0 , 1 , 1 , 1 , 1 , 1 , 0 ] , [ 0 , 0 , 0 , 1 , 0 , 0 , 0 ] ] NEW_LINE findMaximumLength ( grid ) NEW_LINE DEDENT
Last two digits of powers of 7 | Function to find the last two digits of 7 ^ N ; Case 4 ; Case 3 ; Case 2 ; Case 1 ; Given number ; Function call
def get_last_two_digit ( N ) : NEW_LINE INDENT if ( N % 4 == 0 ) : NEW_LINE INDENT return "01" ; NEW_LINE DEDENT elif ( N % 4 == 1 ) : NEW_LINE INDENT return "07" ; NEW_LINE DEDENT elif ( N % 4 == 2 ) : NEW_LINE INDENT return "49" ; NEW_LINE DEDENT return "43" ; NEW_LINE DEDENT N = 12 ; NEW_LINE print ( get_last_two_digit ( N ) ) NEW_LINE
Subsequence with maximum pairwise absolute difference and minimum size | Function to find the subsequence with maximum absolute difference ; To store the resultant subsequence ; First element should be included in the subsequence ; Traverse the given array arr [ ] ; If current element is greater than the previous element ; If the current element is not the local maxima then continue ; Else push it in subsequence ; If the current element is less then the previous element ; If the current element is not the local minima then continue ; Else push it in subsequence ; Last element should also be included in subsequence ; Print the element ; Driver Code ; Given array ; Function Call
def getSubsequence ( ar ) : NEW_LINE INDENT N = len ( ar ) NEW_LINE ans = [ ] NEW_LINE ans . append ( ar [ 0 ] ) NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT if ( ar [ i ] > ar [ i - 1 ] ) : NEW_LINE INDENT if ( i < N - 1 and ar [ i ] <= ar [ i + 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( ar [ i ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( i < N - 1 and ar [ i + 1 ] < ar [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( ar [ i ] ) NEW_LINE DEDENT DEDENT DEDENT ans . append ( ar [ N - 1 ] ) NEW_LINE for it in ans : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 3 , 5 ] NEW_LINE getSubsequence ( arr ) NEW_LINE DEDENT
Maximum product of two non | Returns maximum length path in subtree rooted at u after removing edge connecting u and v ; To find lengths of first and second maximum in subtrees . currMax is to store overall maximum . ; loop through all neighbors of u ; if neighbor is v , then skip it ; call recursively with current neighbor as root ; get max from one side and update ; store total length by adding max and second max ; update current max by adding 1 , i . e . current node is included ; method returns maximum product of length of two non - intersecting paths ; one by one removing all edges and calling dfs on both subtrees ; calling dfs on subtree rooted at g [ i ] [ j ] , excluding edge from g [ i ] [ j ] to i . ; calling dfs on subtree rooted at i , edge from i to g [ i ] [ j ] ; Utility function to add an undirected edge ( u , v ) ; Driver code ; there are N edges , so + 1 for nodes and + 1 for 1 - based indexing
def dfs ( g , curMax , u , v ) : NEW_LINE INDENT max1 = 0 NEW_LINE max2 = 0 NEW_LINE total = 0 NEW_LINE for i in range ( len ( g [ u ] ) ) : NEW_LINE INDENT if ( g [ u ] [ i ] == v ) : NEW_LINE INDENT continue NEW_LINE DEDENT total = max ( total , dfs ( g , curMax , g [ u ] [ i ] , u ) ) NEW_LINE if ( curMax [ 0 ] > max1 ) : NEW_LINE INDENT max2 = max1 NEW_LINE max1 = curMax [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT max2 = max ( max2 , curMax [ 0 ] ) NEW_LINE DEDENT DEDENT total = max ( total , max1 + max2 ) NEW_LINE curMax [ 0 ] = max1 + 1 NEW_LINE return total NEW_LINE DEDENT def maxProductOfTwoPaths ( g , N ) : NEW_LINE INDENT res = - 999999999999 NEW_LINE path1 , path2 = None , None NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( len ( g [ i ] ) ) : NEW_LINE INDENT curMax = [ 0 ] NEW_LINE path1 = dfs ( g , curMax , g [ i ] [ j ] , i ) NEW_LINE curMax = [ 0 ] NEW_LINE path2 = dfs ( g , curMax , i , g [ i ] [ j ] ) NEW_LINE res = max ( res , path1 * path2 ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def addEdge ( g , u , v ) : NEW_LINE INDENT g [ u ] . append ( v ) NEW_LINE g [ v ] . append ( u ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ 1 , 8 ] , [ 2 , 6 ] , [ 3 , 1 ] , [ 5 , 3 ] , [ 7 , 8 ] , [ 8 , 4 ] , [ 8 , 6 ] ] NEW_LINE N = len ( edges ) NEW_LINE g = [ [ ] for i in range ( N + 2 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT addEdge ( g , edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) NEW_LINE DEDENT print ( maxProductOfTwoPaths ( g , N ) ) NEW_LINE DEDENT
Minimum steps to reach N from 1 by multiplying each step by 2 , 3 , 4 or 5 | Function to find a minimum number of steps to reach N from 1 ; Check until N is greater than 1 and operations can be applied ; Condition to choose the operations greedily ; Driver code
def Minsteps ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT if ( n % 5 == 0 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE n = n / 5 NEW_LINE continue NEW_LINE DEDENT elif ( n % 4 == 0 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE n = n / 4 NEW_LINE continue NEW_LINE DEDENT elif ( n % 3 == 0 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE n = n / 3 NEW_LINE continue NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE n = n / 2 NEW_LINE continue NEW_LINE DEDENT return - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 10 NEW_LINE print ( Minsteps ( n ) ) NEW_LINE
Check if the square of a number is divisible by K or not | Python3 implementation to check if the square of X is divisible by K ; Function to return if square of X is divisible by K ; Finding gcd of x and k ; Dividing k by their gcd ; Check for divisibility of X by reduced K ; Driver Code
from math import gcd NEW_LINE def checkDivisible ( x , k ) : NEW_LINE INDENT g = gcd ( x , k ) NEW_LINE k //= g NEW_LINE if ( x % k == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 6 NEW_LINE k = 9 NEW_LINE checkDivisible ( x , k ) ; NEW_LINE DEDENT
Find the minimum value of the given expression over all pairs of the array | Python3 program to find the minimum value of the given expression over all pairs of the array ; Function to find the minimum value of the expression ; The expression simplifies to finding the minimum xor value pair Sort given array ; Calculate min xor of consecutive pairs ; Driver code
import sys NEW_LINE def MinimumValue ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE minXor = sys . maxsize ; NEW_LINE val = 0 ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT val = arr [ i ] ^ arr [ i + 1 ] ; NEW_LINE minXor = min ( minXor , val ) ; NEW_LINE DEDENT return minXor ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE A = [ 12 , 3 , 14 , 5 , 9 , 8 ] ; NEW_LINE print ( MinimumValue ( A , N ) ) ; NEW_LINE DEDENT
Find length of longest substring with at most K normal characters | Function to find maximum length of normal substrings ; keeps count of normal characters ; indexes of substring ; maintain length of longest substring with at most K normal characters ; get position of character ; check if current character is normal ; check if normal characters count exceeds K ; update answer with substring length ; get position of character ; check if character is normal then decrement count ; Driver code ; initialise the string
def maxNormalSubstring ( P , Q , K , N ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE left , right = 0 , 0 NEW_LINE ans = 0 NEW_LINE while ( right < N ) : NEW_LINE INDENT while ( right < N and count <= K ) : NEW_LINE INDENT pos = ord ( P [ right ] ) - ord ( ' a ' ) NEW_LINE if ( Q [ pos ] == '0' ) : NEW_LINE INDENT if ( count + 1 > K ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT right += 1 NEW_LINE if ( count <= K ) : NEW_LINE INDENT ans = max ( ans , right - left ) NEW_LINE DEDENT DEDENT while ( left < right ) : NEW_LINE INDENT pos = ord ( P [ left ] ) - ord ( ' a ' ) NEW_LINE left += 1 NEW_LINE if ( Q [ pos ] == '0' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < K ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if ( __name__ == " _ _ main _ _ " ) : NEW_LINE INDENT P = " giraffe " NEW_LINE Q = "01111001111111111011111111" NEW_LINE K = 2 NEW_LINE N = len ( P ) NEW_LINE print ( maxNormalSubstring ( P , Q , K , N ) ) NEW_LINE DEDENT
Make all the elements of array even with given operations | Function to count the total number of operations needed to make all array element even ; Traverse the given array ; If an odd element occurs then increment that element and next adjacent element by 1 ; Traverse the array if any odd element occurs then return - 1 ; Returns the count of operations ; Driver code
def countOperations ( arr , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT arr [ i ] += 1 ; NEW_LINE arr [ i + 1 ] += 1 ; NEW_LINE count += 2 ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countOperations ( arr , n ) ) ; NEW_LINE DEDENT
Count of pairs with difference at most K with no element repeating | Function to count the number of pairs whose difference is atmost K in an array ; Sorting the Array ; Variable to store the count of pairs whose difference is atmost K ; Loop to consider the consecutive pairs of the array ; if Pair found increment the index by 2 ; Driver Code ; Function Call
def countPairs ( arr , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE pair = 0 NEW_LINE index = 0 NEW_LINE while ( index < len ( arr ) - 1 ) : NEW_LINE INDENT if arr [ index + 1 ] - arr [ index ] <= k : NEW_LINE INDENT pair += 1 NEW_LINE index += 2 NEW_LINE DEDENT else : NEW_LINE INDENT index += 1 NEW_LINE DEDENT DEDENT return pair NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 4 , 3 , 7 , 5 ] NEW_LINE k = 2 NEW_LINE count = countPairs ( arr , k ) NEW_LINE print ( count ) NEW_LINE DEDENT
Maximum profit by selling N items at two markets | Function to calculate max profit ; Prefix sum array for profitA [ ] ; Suffix sum array for profitB [ ] ; If all the items are sold in market A ; Find the maximum profit when the first i items are sold in market A and the rest of the items are sold in market B for all possible values of i ; If all the items are sold in market B ; Driver code ; Function to calculate max profit
def maxProfit ( profitA , profitB , n ) : NEW_LINE INDENT preSum = [ 0 ] * n ; NEW_LINE preSum [ 0 ] = profitA [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT preSum [ i ] = preSum [ i - 1 ] + profitA [ i ] ; NEW_LINE DEDENT suffSum = [ 0 ] * n ; NEW_LINE suffSum [ n - 1 ] = profitB [ n - 1 ] ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffSum [ i ] = suffSum [ i + 1 ] + profitB [ i ] ; NEW_LINE DEDENT res = preSum [ n - 1 ] ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT res = max ( res , preSum [ i ] + suffSum [ i + 1 ] ) ; NEW_LINE DEDENT res = max ( res , suffSum [ 0 ] ) ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT profitA = [ 2 , 3 , 2 ] ; NEW_LINE profitB = [ 10 , 30 , 40 ] ; NEW_LINE n = len ( profitA ) ; NEW_LINE print ( maxProfit ( profitA , profitB , n ) ) ; NEW_LINE DEDENT
Find if possible to visit every nodes in given Graph exactly once based on given conditions | Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call
def findpath ( N , a ) : NEW_LINE INDENT if ( a [ 0 ] ) : NEW_LINE INDENT print ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT if ( a [ i ] == 0 and a [ i + 1 ] ) : NEW_LINE INDENT for j in range ( 1 , i + 1 , 1 ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT print ( N + 1 , end = " ▁ " ) ; NEW_LINE for j in range ( i + 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( N + 1 , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE arr = [ 0 , 1 , 0 ] NEW_LINE findpath ( N , arr ) NEW_LINE DEDENT
Minimum number of edges that need to be added to form a triangle | Function to return the minimum number of edges that need to be added to the given graph such that it contains at least one triangle ; adj is the adjacency matrix such that adj [ i ] [ j ] = 1 when there is an edge between i and j ; As the graph is undirected so there will be an edge between ( i , j ) and ( j , i ) ; To store the required count of edges ; For every possible vertex triplet ; If the vertices form a triangle ; If no edges are present ; If only 1 edge is required ; Two edges are required ; Driver code ; Number of nodes ; Storing the edges in a vector of pairs
def minEdges ( v , n ) : NEW_LINE INDENT adj = dict . fromkeys ( range ( n + 1 ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT adj [ i ] = [ 0 ] * ( n + 1 ) ; NEW_LINE DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT adj [ v [ i ] [ 0 ] ] [ v [ i ] [ 1 ] ] = 1 ; NEW_LINE adj [ v [ i ] [ 1 ] ] [ v [ i ] [ 0 ] ] = 1 ; NEW_LINE DEDENT edgesNeeded = 3 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n + 1 ) : NEW_LINE INDENT if ( adj [ i ] [ j ] and adj [ j ] [ k ] and adj [ k ] [ i ] ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( not ( adj [ i ] [ j ] or adj [ j ] [ k ] or adj [ k ] [ i ] ) ) : NEW_LINE INDENT edgesNeeded = min ( edgesNeeded , 3 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( adj [ i ] [ j ] and adj [ j ] [ k ] ) or ( adj [ j ] [ k ] and adj [ k ] [ i ] ) or ( adj [ k ] [ i ] and adj [ i ] [ j ] ) ) : NEW_LINE INDENT edgesNeeded = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT edgesNeeded = min ( edgesNeeded , 2 ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return edgesNeeded ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE v = [ [ 1 , 2 ] , [ 1 , 3 ] ] ; NEW_LINE print ( minEdges ( v , n ) ) ; NEW_LINE DEDENT
Modify a numeric string to a balanced parentheses by replacements | Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Given Input ; Function Call
def balBracketSequence ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( str [ 0 ] == str [ n - 1 ] ) : NEW_LINE INDENT print ( " No " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT cntForOpen = 0 NEW_LINE cntForClose = 0 NEW_LINE check = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT cntForOpen += 1 NEW_LINE DEDENT elif str [ i ] == str [ n - 1 ] : NEW_LINE INDENT cntForOpen -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntForOpen += 1 NEW_LINE DEDENT if ( cntForOpen < 0 ) : NEW_LINE INDENT check = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( check and cntForOpen == 0 ) : NEW_LINE INDENT print ( " Yes , ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ n - 1 ] ) : NEW_LINE INDENT print ( ' ) ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ( ' , end = " " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT cntForClose += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntForClose -= 1 NEW_LINE DEDENT if ( cntForClose < 0 ) : NEW_LINE INDENT check = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( check and cntForClose == 0 ) : NEW_LINE INDENT print ( " Yes , ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT print ( ' ( ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ) ' , end = " " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT DEDENT print ( " NO " , end = " " ) NEW_LINE DEDENT DEDENT str = "123122" NEW_LINE balBracketSequence ( str ) NEW_LINE
Length of the longest subsequence such that xor of adjacent elements is non | Function to find the length of the longest subsequence such that the XOR of adjacent elements in the subsequence must be non - decreasing ; Computing xor of all the pairs of elements and store them along with the pair ( i , j ) ; Sort all possible xor values ; Initialize the dp array ; Calculating the dp array for each possible position and calculating the max length that ends at a particular index ; Taking maximum of all position ; Driver code
def LongestXorSubsequence ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT v . append ( [ ( arr [ i ] ^ arr [ j ] ) , ( i , j ) ] ) NEW_LINE DEDENT DEDENT v . sort ( ) NEW_LINE dp = [ 1 for x in range ( 88 ) ] NEW_LINE for a , b in v : NEW_LINE INDENT dp [ b [ 1 ] ] = max ( dp [ b [ 1 ] ] , 1 + dp [ b [ 0 ] ] ) NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 12 , 6 , 7 , 13 , 14 , 8 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( LongestXorSubsequence ( arr , n ) ) NEW_LINE
Delete Edge to minimize subtree sum difference | DFS method to traverse through edges , calculating subtree Sum at each node and updating the difference between subtrees ; loop for all neighbors except parent and aggregate Sum over all subtrees ; store Sum in current node 's subtree index ; at one side subtree Sum is ' Sum ' and other side subtree Sum is ' totalSum ▁ - ▁ Sum ' so their difference will be totalSum - 2 * Sum , by which we 'll update res ; Method returns minimum subtree Sum difference ; Calculating total Sum of tree and initializing subtree Sum 's by vertex values ; filling edge data structure ; calling DFS method at node 0 , with parent as - 1 ; Driver Code
def dfs ( u , parent , totalSum , edge , subtree , res ) : NEW_LINE INDENT Sum = subtree [ u ] NEW_LINE for i in range ( len ( edge [ u ] ) ) : NEW_LINE INDENT v = edge [ u ] [ i ] NEW_LINE if ( v != parent ) : NEW_LINE INDENT dfs ( v , u , totalSum , edge , subtree , res ) NEW_LINE Sum += subtree [ v ] NEW_LINE DEDENT DEDENT subtree [ u ] = Sum NEW_LINE if ( u != 0 and abs ( totalSum - 2 * Sum ) < res [ 0 ] ) : NEW_LINE INDENT res [ 0 ] = abs ( totalSum - 2 * Sum ) NEW_LINE DEDENT DEDENT def getMinSubtreeSumDifference ( vertex , edges , N ) : NEW_LINE INDENT totalSum = 0 NEW_LINE subtree = [ None ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT subtree [ i ] = vertex [ i ] NEW_LINE totalSum += vertex [ i ] NEW_LINE DEDENT edge = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT edge [ edges [ i ] [ 0 ] ] . append ( edges [ i ] [ 1 ] ) NEW_LINE edge [ edges [ i ] [ 1 ] ] . append ( edges [ i ] [ 0 ] ) NEW_LINE DEDENT res = [ 999999999999 ] NEW_LINE dfs ( 0 , - 1 , totalSum , edge , subtree , res ) NEW_LINE return res [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT vertex = [ 4 , 2 , 1 , 6 , 3 , 5 , 2 ] NEW_LINE edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 0 , 3 ] , [ 2 , 4 ] , [ 2 , 5 ] , [ 3 , 6 ] ] NEW_LINE N = len ( vertex ) NEW_LINE print ( getMinSubtreeSumDifference ( vertex , edges , N ) ) NEW_LINE DEDENT
Minimum operations required to make every element greater than or equal to K | Function to calculate gcd of two numbers ; function to get minimum operation needed ; The priority queue holds a minimum element in the top position ; push value one by one from the given array ; store count of minimum operation needed ; All elements are now >= k ; It is impossible to make as there are no sufficient elements available ; Take two smallest elements and replace them by their LCM first smallest element ; Second smallest element ; Increment the count ; Driver code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE return b NEW_LINE return gcd ( b % a , a ) NEW_LINE DEDENT def FindMinOperation ( a , n , k ) : NEW_LINE INDENT Q = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE Q . append ( a [ i ] ) NEW_LINE Q . sort ( ) NEW_LINE ans = 0 NEW_LINE while ( True ) : NEW_LINE if ( Q [ 0 ] >= k ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( len ( Q ) < 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = Q [ 0 ] NEW_LINE Q . pop ( 0 ) NEW_LINE y = Q [ 0 ] NEW_LINE Q . pop ( 0 ) NEW_LINE z = ( x * y ) // gcd ( x , y ) NEW_LINE Q . append ( z ) NEW_LINE Q . sort ( ) NEW_LINE ans += 1 NEW_LINE return ans NEW_LINE DEDENT a = [ 3 , 5 , 7 , 6 , 8 ] NEW_LINE k = 8 NEW_LINE n = len ( a ) NEW_LINE print ( FindMinOperation ( a , n , k ) ) NEW_LINE
Find the lexicographically smallest string which satisfies the given condition | Function to return the required string ; First character will always be 'a ; To store the resultant string ; Since length of the string should be greater than 0 and first element of array should be 1 ; Check one by one all element of given prefix array ; If the difference between any two consecutive elements of the prefix array is greater than 1 then there will be no such string possible that satisfies the given array . Also , string cannot have more than 26 distinct characters ; If difference is 0 then the ( i + 1 ) th character will be same as the ith character ; If difference is 1 then the ( i + 1 ) th character will be different from the ith character ; Return the resultant string ; Driver code
def smallestString ( N , A ) : NEW_LINE ' NEW_LINE INDENT ch = ' a ' NEW_LINE S = " " NEW_LINE if ( N < 1 or A [ 0 ] != 1 ) : NEW_LINE INDENT S = " - 1" NEW_LINE return S NEW_LINE DEDENT S += str ( ch ) NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT diff = A [ i ] - A [ i - 1 ] NEW_LINE if ( diff > 1 or diff < 0 or A [ i ] > 26 ) : NEW_LINE INDENT S = " - 1" NEW_LINE return S NEW_LINE DEDENT elif ( diff == 0 ) : NEW_LINE INDENT S += ' a ' NEW_LINE DEDENT else : NEW_LINE INDENT S += ch NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE DEDENT DEDENT return S NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( smallestString ( n , arr ) ) NEW_LINE
Count of alphabets whose ASCII values can be formed with the digits of N | Python3 implementation of the approach ; Function that returns true if num can be formed with the digits in digits [ ] array ; Copy of the digits array ; Get last digit ; If digit array doesn 't contain current digit ; One occurrence is used ; Remove the last digit ; Function to return the count of required alphabets ; To store the occurrences of digits ( 0 - 9 ) ; Get last digit ; Update the occurrence of the digit ; Remove the last digit ; If any lowercase character can be picked from the current digits ; If any uppercase character can be picked from the current digits ; Return the required count of alphabets ; Driver code
import math NEW_LINE def canBePicked ( digits , num ) : NEW_LINE INDENT copyDigits = [ ] ; NEW_LINE for i in range ( len ( digits ) ) : NEW_LINE INDENT copyDigits . append ( digits [ i ] ) ; NEW_LINE DEDENT while ( num > 0 ) : NEW_LINE INDENT digit = num % 10 ; NEW_LINE if ( copyDigits [ digit ] == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT copyDigits [ digit ] -= 1 ; NEW_LINE DEDENT num = math . floor ( num / 10 ) ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def countAlphabets ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE digits = [ 0 ] * 10 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = n % 10 ; NEW_LINE digits [ digit ] += 1 ; NEW_LINE n = math . floor ( n / 10 ) ; NEW_LINE DEDENT for i in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT if ( canBePicked ( digits , i ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT for i in range ( ord ( ' A ' ) , ord ( ' Z ' ) + 1 ) : NEW_LINE INDENT if ( canBePicked ( digits , i ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT n = 1623455078 ; NEW_LINE print ( countAlphabets ( n ) ) ; NEW_LINE
Largest number less than X having at most K set bits | Function to return the greatest number <= X having at most K set bits . ; Remove rightmost set bits one by one until we count becomes k ; Return the required number ; Driver code
def greatestKBits ( X , K ) : NEW_LINE INDENT set_bit_count = bin ( X ) . count ( '1' ) NEW_LINE if ( set_bit_count <= K ) : NEW_LINE INDENT return X NEW_LINE DEDENT diff = set_bit_count - K NEW_LINE for i in range ( 0 , diff , 1 ) : NEW_LINE INDENT X &= ( X - 1 ) NEW_LINE DEDENT return X NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 21 NEW_LINE K = 2 NEW_LINE print ( greatestKBits ( X , K ) ) NEW_LINE DEDENT
Find the minimum number of moves needed to move from one cell of matrix to another | Python3 program to find the minimum numbers of moves needed to move from source to destination . ; add edge to graph ; Level BFS function to find minimum path from source to sink ; Base case ; make initial distance of all vertex - 1 from source ; Create a queue for BFS ; Mark the source node level [ s ] = '0 ; it will be used to get all adjacent vertices of a vertex ; Dequeue a vertex from queue ; Get all adjacent vertices of the dequeued vertex s . If a adjacent has not been visited ( level [ i ] < '0' ) , then update level [ i ] = = parent_level [ s ] + 1 and enqueue it ; Else , continue to do BFS ; return minimum moves from source to sink ; Returns minimum numbers of moves from a source ( a cell with value 1 ) to a destination ( a cell with value 2 ) ; ; create graph with n * n node each cell consider as node Number of current vertex ; connect all 4 adjacent cell to current cell ; source index ; destination index ; find minimum moves ; Driver Code
class Graph : NEW_LINE INDENT def __init__ ( self , V ) : NEW_LINE INDENT self . V = V NEW_LINE self . adj = [ [ ] for i in range ( V ) ] NEW_LINE DEDENT def addEdge ( self , s , d ) : NEW_LINE INDENT self . adj [ s ] . append ( d ) NEW_LINE self . adj [ d ] . append ( s ) NEW_LINE DEDENT def BFS ( self , s , d ) : NEW_LINE INDENT if ( s == d ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT level = [ - 1 ] * self . V NEW_LINE queue = [ ] NEW_LINE level [ s ] = 0 NEW_LINE queue . append ( s ) NEW_LINE while ( len ( queue ) != 0 ) : NEW_LINE INDENT s = queue . pop ( ) NEW_LINE i = 0 NEW_LINE while i < len ( self . adj [ s ] ) : NEW_LINE INDENT if ( level [ self . adj [ s ] [ i ] ] < 0 or level [ self . adj [ s ] [ i ] ] > level [ s ] + 1 ) : NEW_LINE INDENT level [ self . adj [ s ] [ i ] ] = level [ s ] + 1 NEW_LINE queue . append ( self . adj [ s ] [ i ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT return level [ d ] NEW_LINE DEDENT DEDENT def isSafe ( i , j , M ) : NEW_LINE INDENT global N NEW_LINE if ( ( i < 0 or i >= N ) or ( j < 0 or j >= N ) or M [ i ] [ j ] == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def MinimumPath ( M ) : NEW_LINE INDENT global N NEW_LINE s , d = None , None NEW_LINE V = N * N + 2 NEW_LINE g = Graph ( V ) NEW_LINE k = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( M [ i ] [ j ] != 0 ) : NEW_LINE INDENT if ( isSafe ( i , j + 1 , M ) ) : NEW_LINE INDENT g . addEdge ( k , k + 1 ) NEW_LINE DEDENT if ( isSafe ( i , j - 1 , M ) ) : NEW_LINE INDENT g . addEdge ( k , k - 1 ) NEW_LINE DEDENT if ( j < N - 1 and isSafe ( i + 1 , j , M ) ) : NEW_LINE INDENT g . addEdge ( k , k + N ) NEW_LINE DEDENT if ( i > 0 and isSafe ( i - 1 , j , M ) ) : NEW_LINE INDENT g . addEdge ( k , k - N ) NEW_LINE DEDENT DEDENT if ( M [ i ] [ j ] == 1 ) : NEW_LINE INDENT s = k NEW_LINE DEDENT if ( M [ i ] [ j ] == 2 ) : NEW_LINE INDENT d = k NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT return g . BFS ( s , d ) NEW_LINE DEDENT N = 4 NEW_LINE M = [ [ 3 , 3 , 1 , 0 ] , [ 3 , 0 , 3 , 3 ] , [ 2 , 3 , 0 , 3 ] , [ 0 , 3 , 3 , 3 ] ] NEW_LINE print ( MinimumPath ( M ) ) NEW_LINE
Find two numbers whose sum and GCD are given | Python 3 program to find two numbers whose sum and GCD is given ; Function to find two numbers whose sum and gcd is given ; sum != gcd checks that both the numbers are positive or not ; Driver code
from math import gcd as __gcd NEW_LINE def findTwoNumbers ( sum , gcd ) : NEW_LINE INDENT if ( __gcd ( gcd , sum - gcd ) == gcd and sum != gcd ) : NEW_LINE INDENT print ( " a ▁ = " , min ( gcd , sum - gcd ) , " , ▁ b ▁ = " , sum - min ( gcd , sum - gcd ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sum = 8 NEW_LINE gcd = 2 NEW_LINE findTwoNumbers ( sum , gcd ) NEW_LINE DEDENT
Find maximum distance between any city and station | Function to calculate the maximum distance between any city and its nearest station ; Initialize boolean list ; Assign True to cities containing station ;
def findMaxDistance ( numOfCities , station ) : NEW_LINE INDENT hasStation = [ False ] * numOfCities NEW_LINE for city in station : NEW_LINE INDENT hasStation [ city ] = True NEW_LINE DEDENT dist , maxDist = 0 , min ( station ) NEW_LINE for city in range ( numOfCities ) : NEW_LINE INDENT if hasStation [ city ] == True : NEW_LINE INDENT maxDist = max ( ( dist + 1 ) // 2 , maxDist ) NEW_LINE dist = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dist += 1 NEW_LINE DEDENT DEDENT return max ( maxDist , dist ) NEW_LINE DEDENT / * Driver code * / NEW_LINE numOfCities = 6 NEW_LINE station = [ 3 , 1 ] NEW_LINE print ( " Max ▁ Distance : " , findMaxDistance ( numOfCities , station ) ) NEW_LINE
Split the number into N parts such that difference between the smallest and the largest part is minimum | Function that prints the required sequence ; If we cannot split the number into exactly ' N ' parts ; If x % n == 0 then the minimum difference is 0 and all numbers are x / n ; upto n - ( x % n ) the values will be x / n after that the values will be x / n + 1 ; Driver code
def split ( x , n ) : NEW_LINE INDENT if ( x < n ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT elif ( x % n == 0 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( x // n , end = " ▁ " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT zp = n - ( x % n ) NEW_LINE pp = x // n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i >= zp ) : NEW_LINE INDENT print ( pp + 1 , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( pp , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT x = 5 NEW_LINE n = 3 NEW_LINE split ( x , n ) NEW_LINE
Minimum time to reach a point with + t and | returns the minimum time required to reach 'X ; Stores the minimum time ; increment ' t ' by 1 ; update the sum ; Driver code
' NEW_LINE def cal_minimum_time ( X ) : NEW_LINE INDENT t = 0 NEW_LINE sum = 0 NEW_LINE while ( sum < X ) : NEW_LINE INDENT t = t + 1 NEW_LINE sum = sum + t ; NEW_LINE DEDENT return t ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE ans = cal_minimum_time ( n ) NEW_LINE print ( " The ▁ minimum ▁ time ▁ required ▁ is ▁ : " , ans ) NEW_LINE DEDENT
Check if a string can be rearranged to form special palindrome | Driver code ; creating a list which stores the frequency of each character ; Checking if a character is uppercase or not ; Increasing by 1 if uppercase ; Decreasing by 1 if lower case ; Storing the sum of positive numbers in the frequency array ; Storing the sum of negative numbers in the frequency array ; If all character balances out then its Yes ; If there is only 1 character which does not balances then also it is Yes
s = " ABCdcba " NEW_LINE u = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] . isupper ( ) ) : NEW_LINE INDENT u [ ord ( s [ i ] ) - 65 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT u [ ord ( s [ i ] ) - 97 ] -= 1 NEW_LINE DEDENT DEDENT fl = True NEW_LINE po = 0 NEW_LINE ne = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( u [ i ] > 0 ) : NEW_LINE INDENT po += u [ i ] NEW_LINE DEDENT if ( u [ i ] < 0 ) : NEW_LINE INDENT ne += u [ i ] NEW_LINE DEDENT DEDENT if ( po == 0 and ne == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT elif ( po == 1 and ne == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT elif ( po == 0 and ne == - 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Count substrings made up of a single distinct character | Function to count the number of substrings made up of a single distinct character ; Stores the required count ; Stores the count of substrings possible by using current character ; Stores the previous character ; Traverse the string ; If current character is same as the previous character ; Increase count of substrings possible with current character ; Reset count of substrings possible with current character ; Update count of substrings ; Update previous character ; Driver Code
def countSubstrings ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE subs = 1 NEW_LINE pre = ' ' NEW_LINE for i in s : NEW_LINE INDENT if pre == i : NEW_LINE INDENT subs += 1 NEW_LINE DEDENT else : NEW_LINE INDENT subs = 1 NEW_LINE DEDENT ans += subs NEW_LINE pre = i NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT s = ' geeksforgeeks ' NEW_LINE countSubstrings ( s ) NEW_LINE
Sum of minimum difference between consecutive elements of an array | Utility pair ; function to find minimum sum of difference of consecutive element ; ul to store upper limit ll to store lower limit ; storethe lower range in ll and upper range in ul ; initialize the answer with 0 ; iterate for all ranges ; case 1 , in this case the difference will be 0 ; change upper limit and lower limit ; case 2 ; store the difference ; case 3 ; store the difference ; array of range
class pair : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE def __init__ ( self , a , b ) : NEW_LINE INDENT self . first = a NEW_LINE self . second = b NEW_LINE DEDENT DEDENT def solve ( v , n ) : NEW_LINE INDENT ans = 0 ; ul = 0 ; ll = 0 ; NEW_LINE ll = v [ 0 ] . first NEW_LINE ul = v [ 0 ] . second NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( v [ i ] . first <= ul and v [ i ] . first >= ll ) or ( v [ i ] . second >= ll and v [ i ] . second <= ul ) : NEW_LINE INDENT if v [ i ] . first > ll : NEW_LINE INDENT ll = v [ i ] . first NEW_LINE DEDENT if v [ i ] . second < ul : NEW_LINE INDENT ul = v [ i ] . second ; NEW_LINE DEDENT DEDENT elif v [ i ] . first > ul : NEW_LINE INDENT ans += abs ( ul - v [ i ] . first ) NEW_LINE ul = v [ i ] . first NEW_LINE ll = v [ i ] . first NEW_LINE DEDENT elif v [ i ] . second < ll : NEW_LINE INDENT ans += abs ( ll - v [ i ] . second ) ; NEW_LINE ul = v [ i ] . second ; NEW_LINE ll = v [ i ] . second ; NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT v = [ pair ( 1 , 3 ) , pair ( 2 , 5 ) , pair ( 6 , 8 ) , pair ( 1 , 2 ) , pair ( 2 , 3 ) ] NEW_LINE n = len ( v ) NEW_LINE print ( solve ( v , n ) ) NEW_LINE
Find the Largest Cube formed by Deleting minimum Digits from a number | Python3 code to implement maximum perfect cube formed after deleting minimum digits ; Returns vector of Pre Processed perfect cubes ; convert the cube to string and push into preProcessedCubes vector ; Utility function for findLargestCube ( ) . Returns the Largest cube number that can be formed ; reverse the preProcessed cubes so that we have the largest cube in the beginning of the vector ; iterate over all cubes ; check if the current digit of the cube matches with that of the number num ; if control reaches here , the its not possible to form a perfect cube ; wrapper for findLargestCubeUtil ( ) ; pre process perfect cubes ; convert number n to String ; Driver Code
import math as mt NEW_LINE def preProcess ( n ) : NEW_LINE INDENT preProcessedCubes = list ( ) NEW_LINE for i in range ( 1 , mt . ceil ( n ** ( 1. / 3. ) ) ) : NEW_LINE INDENT iThCube = i ** 3 NEW_LINE cubeString = str ( iThCube ) NEW_LINE preProcessedCubes . append ( cubeString ) NEW_LINE DEDENT return preProcessedCubes NEW_LINE DEDENT def findLargestCubeUtil ( num , preProcessedCubes ) : NEW_LINE INDENT preProcessedCubes = preProcessedCubes [ : : - 1 ] NEW_LINE totalCubes = len ( preProcessedCubes ) NEW_LINE for i in range ( totalCubes ) : NEW_LINE INDENT currCube = preProcessedCubes [ i ] NEW_LINE digitsInCube = len ( currCube ) NEW_LINE index = 0 NEW_LINE digitsInNumber = len ( num ) NEW_LINE for j in range ( digitsInNumber ) : NEW_LINE INDENT if ( num [ j ] == currCube [ index ] ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT if ( digitsInCube == index ) : NEW_LINE INDENT return currCube NEW_LINE DEDENT DEDENT DEDENT return " Not ▁ Possible " NEW_LINE DEDENT def findLargestCube ( n ) : NEW_LINE INDENT preProcessedCubes = preProcess ( n ) NEW_LINE num = str ( n ) NEW_LINE ans = findLargestCubeUtil ( num , preProcessedCubes ) NEW_LINE print ( " Largest ▁ Cube ▁ that ▁ can ▁ be ▁ formed ▁ from " , n , " is " , ans ) NEW_LINE DEDENT n = 4125 NEW_LINE findLargestCube ( n ) NEW_LINE n = 876 NEW_LINE findLargestCube ( n ) NEW_LINE
Water Connection Problem | number of houses and number of pipes ; Array rd stores the ending vertex of pipe ; Array wd stores the value of diameters between two pipes ; Array cd stores the starting end of pipe ; List a , b , c are used to store the final output ; Function performing calculations . ; If a pipe has no ending vertex but has starting vertex i . e is an outgoing pipe then we need to start DFS with this vertex . ; We put the details of component in final output array ; main function ; set the value of the araray to zero
n = 0 NEW_LINE p = 0 NEW_LINE rd = [ 0 ] * 1100 NEW_LINE wt = [ 0 ] * 1100 NEW_LINE cd = [ 0 ] * 1100 NEW_LINE a = [ ] NEW_LINE b = [ ] NEW_LINE c = [ ] NEW_LINE ans = 0 NEW_LINE def dfs ( w ) : NEW_LINE INDENT global ans NEW_LINE if ( cd [ w ] == 0 ) : NEW_LINE INDENT return w NEW_LINE DEDENT if ( wt [ w ] < ans ) : NEW_LINE INDENT ans = wt [ w ] NEW_LINE DEDENT return dfs ( cd [ w ] ) NEW_LINE DEDENT def solve ( arr ) : NEW_LINE INDENT global ans NEW_LINE i = 0 NEW_LINE while ( i < p ) : NEW_LINE INDENT q = arr [ i ] [ 0 ] NEW_LINE h = arr [ i ] [ 1 ] NEW_LINE t = arr [ i ] [ 2 ] NEW_LINE cd [ q ] = h NEW_LINE wt [ q ] = t NEW_LINE rd [ h ] = q NEW_LINE i += 1 NEW_LINE DEDENT a = [ ] NEW_LINE b = [ ] NEW_LINE c = [ ] NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( rd [ j ] == 0 and cd [ j ] ) : NEW_LINE INDENT ans = 1000000000 NEW_LINE w = dfs ( j ) NEW_LINE a . append ( j ) NEW_LINE b . append ( w ) NEW_LINE c . append ( ans ) NEW_LINE DEDENT DEDENT print ( len ( a ) ) NEW_LINE for j in range ( len ( a ) ) : NEW_LINE INDENT print ( a [ j ] , b [ j ] , c [ j ] ) NEW_LINE DEDENT DEDENT n = 9 NEW_LINE p = 6 NEW_LINE arr = [ [ 7 , 4 , 98 ] , [ 5 , 9 , 72 ] , [ 4 , 6 , 10 ] , [ 2 , 8 , 22 ] , [ 9 , 7 , 17 ] , [ 3 , 1 , 66 ] ] NEW_LINE solve ( arr ) NEW_LINE
Print a closest string that does not contain adjacent duplicates | Function to print simple string ; If any two adjacent characters are equal ; Initialize it to ' a ' ; Traverse the loop until it is different from the left and right letter . ; Driver Function
def noAdjacentDup ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = " a " NEW_LINE while ( s [ i ] == s [ i - 1 ] or ( i + 1 < n and s [ i ] == s [ i + 1 ] ) ) : NEW_LINE INDENT s [ i ] += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT s = list ( " geeksforgeeks " ) NEW_LINE print ( " " . join ( noAdjacentDup ( s ) ) ) NEW_LINE
Array element moved by k using single moves | Python3 code to find winner of game ; if the number of steps is more then n - 1 ; initially the best is 0 and no of wins is 0. ; traverse through all the numbers ; if the value of array is more then that of previous best ; best is replaced by a [ i ] ; if not the first index ; no of wins is 1 now ; if any position has more then k wins then return ; Maximum element will be winner because we move smaller element at end and repeat the process . ; driver code
def winner ( a , n , k ) : NEW_LINE INDENT if k >= n - 1 : NEW_LINE INDENT return n NEW_LINE DEDENT best = 0 NEW_LINE times = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] > best : NEW_LINE INDENT best = a [ i ] NEW_LINE if i == True : NEW_LINE INDENT times = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE if times >= k : NEW_LINE INDENT return best NEW_LINE DEDENT DEDENT return best NEW_LINE DEDENT a = [ 2 , 1 , 3 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE k = 2 NEW_LINE print ( winner ( a , n , k ) ) NEW_LINE
Paper Cut into Minimum Number of Squares | Returns min number of squares needed ; swap if a is small size side . ; Iterate until small size side is greater then 0 ; Update result ; Driver code
def minimumSquare ( a , b ) : NEW_LINE INDENT result = 0 NEW_LINE rem = 0 NEW_LINE if ( a < b ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT while ( b > 0 ) : NEW_LINE INDENT result += int ( a / b ) NEW_LINE rem = int ( a % b ) NEW_LINE a = b NEW_LINE b = rem NEW_LINE DEDENT return result NEW_LINE DEDENT n = 13 NEW_LINE m = 29 NEW_LINE print ( minimumSquare ( n , m ) ) NEW_LINE
Count of non decreasing Arrays with ith element in range [ A [ i ] , B [ i ] ] | Function to count the total number of possible valid arrays ; Make a 2D DP table ; Make a 2D prefix sum table ; ; Base Case ; Initialize the prefix values ; Iterate over the range and update the dp table accordingly ; Add the dp values to the prefix sum ; Update the prefix sum table ; Find the result count of arrays formed ; Return the total count of arrays ; Driver Code
def totalValidArrays ( a , b , N ) : NEW_LINE INDENT dp = [ [ 0 for _ in range ( b [ N - 1 ] + 1 ) ] for _ in range ( N + 1 ) ] NEW_LINE pref = [ [ 0 for _ in range ( b [ N - 1 ] + 1 ) ] for _ in range ( N + 1 ) ] NEW_LINE DEDENT / * Initialize all values to 0 * / NEW_LINE INDENT dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 0 , b [ N - 1 ] + 1 ) : NEW_LINE INDENT pref [ 0 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( a [ i - 1 ] , b [ i - 1 ] + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += pref [ i - 1 ] [ j ] NEW_LINE pref [ i ] [ j ] += dp [ i ] [ j ] NEW_LINE DEDENT for j in range ( 0 , b [ N - 1 ] + 1 ) : NEW_LINE INDENT if ( j > 0 ) : NEW_LINE INDENT pref [ i ] [ j ] += pref [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( a [ N - 1 ] , b [ N - 1 ] + 1 ) : NEW_LINE INDENT ans += dp [ N ] [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 1 ] NEW_LINE B = [ 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( totalValidArrays ( A , B , N ) ) NEW_LINE DEDENT
Count of integers in range [ L , R ] having even frequency of each digit | Stores the upper limit of the range ; Stores the overlapping states ; Recursive Function to calculate the count of valid integers in the range [ 1 , s ] using memoization ; Base Case ; If current integer has even count of digits and is not repeated ; If current state is already considered ; Stores the maximum valid digit at the current index ; Stores the count of valid integers ; If the current digit is not the most significant digit , i . e , the integer is already started ; Iterate through all valid digits ; Recursive call for ith digit at the current index ; Recursive call for integers having leading zeroes in the beginning ; Iterate through all valid digits as most significant digits ; Recursive call for ith digit at the current index ; Return answer ; Function to calculate valid number in the range [ 1 , X ] ; Initialize dp array with - 1 ; Store the range in form of string ; Return Count ; Function to find the count of integers in the range [ L , R ] such that the frequency of each digit is even ; Driver Code
s = " " NEW_LINE dp = [ [ [ [ 0 for _ in range ( 2 ) ] for _ in range ( 2 ) ] for _ in range ( 10 ) ] for _ in range ( 1024 ) ] NEW_LINE def calcCnt ( mask , sz , smaller , started ) : NEW_LINE INDENT if ( sz == len ( s ) ) : NEW_LINE INDENT return ( mask == 0 and started ) NEW_LINE DEDENT if ( dp [ mask ] [ sz ] [ smaller ] [ started ] != - 1 ) : NEW_LINE INDENT return dp [ mask ] [ sz ] [ smaller ] [ started ] NEW_LINE DEDENT mx = 9 NEW_LINE if ( not smaller ) : NEW_LINE INDENT mx = ord ( s [ sz ] ) - ord ( '0' ) NEW_LINE DEDENT ans = 0 NEW_LINE if ( started ) : NEW_LINE INDENT for i in range ( 0 , mx + 1 ) : NEW_LINE INDENT ans += calcCnt ( mask ^ ( 1 << i ) , sz + 1 , smaller or ( i < ord ( s [ sz ] ) - ord ( '0' ) ) , 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT ans = calcCnt ( mask , sz + 1 , 1 , 0 ) NEW_LINE for i in range ( 1 , mx + 1 ) : NEW_LINE INDENT ans += calcCnt ( mask ^ ( 1 << i ) , sz + 1 , smaller or ( i < ord ( s [ sz ] ) - ord ( '0' ) ) , 1 ) NEW_LINE DEDENT DEDENT dp [ mask ] [ sz ] [ smaller ] [ started ] = ans NEW_LINE return dp [ mask ] [ sz ] [ smaller ] [ started ] NEW_LINE DEDENT def countInt ( x ) : NEW_LINE INDENT global dp NEW_LINE dp = [ [ [ [ - 1 for _ in range ( 2 ) ] for _ in range ( 2 ) ] for _ in range ( 10 ) ] for _ in range ( 1024 ) ] NEW_LINE global s NEW_LINE s = str ( x ) NEW_LINE return calcCnt ( 0 , 0 , 0 , 0 ) NEW_LINE DEDENT def countIntInRange ( L , R ) : NEW_LINE INDENT return countInt ( R ) - countInt ( L - 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 32 NEW_LINE R = 1010 NEW_LINE print ( countIntInRange ( L , R ) ) NEW_LINE DEDENT
Minimize cost of swapping set bits with unset bits in a given Binary string | Python program for the above approach ; Function to find the minimum cost required to swap every set bit with an unset bit ; Stores the indices of set and unset bits of the string S ; Traverse the string S ; Store the indices ; Initialize a dp table of size n1 * n2 ; Set unreachable states to INF ; Fill the dp Table according to the given recurrence relation ; Update the value of dp [ i ] [ j ] ; Return the minimum cost ; Driver Code
INF = 1000000000 ; NEW_LINE def minimumCost ( s ) : NEW_LINE INDENT N = len ( s ) ; NEW_LINE A = [ ] NEW_LINE B = [ ] NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( s [ i ] == "1" ) : NEW_LINE A . append ( i ) ; NEW_LINE else : NEW_LINE B . append ( i ) ; NEW_LINE DEDENT n1 = len ( A ) NEW_LINE n2 = len ( B ) NEW_LINE dp = [ [ 0 for i in range ( n2 + 1 ) ] for j in range ( n1 + 1 ) ] NEW_LINE for i in range ( 1 , n1 + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = INF NEW_LINE DEDENT for i in range ( 1 , n1 + 1 ) : NEW_LINE INDENT for j in range ( 1 , n2 + 1 ) : NEW_LINE dp [ i ] [ j ] = min ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j - 1 ] + abs ( A [ i - 1 ] - B [ j - 1 ] ) ) ; NEW_LINE DEDENT return dp [ n1 ] [ n2 ] ; NEW_LINE DEDENT S = "1010001" ; NEW_LINE print ( minimumCost ( S ) ) ; NEW_LINE
Queries to find minimum absolute difference between adjacent array elements in given ranges | Python3 program for the above approach ; Function to find the minimum difference between adjacent array element over the given range [ L , R ] for Q Queries ; Find the sum of all queries ; Left and right boundaries of current range ; Print the sum of the current query range ; Function to find the minimum absolute difference of adjacent array elements for the given range ; Stores the absolute difference of adjacent elements ; Find the minimum difference of adjacent elements ; Driver Code
MAX = 5000 ; NEW_LINE def minDifference ( arr , n , q , m ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT L = q [ i ] [ 0 ] ; R = q [ i ] [ 1 ] ; NEW_LINE ans = MAX ; NEW_LINE for i in range ( L , R ) : NEW_LINE INDENT ans = min ( ans , arr [ i ] ) ; NEW_LINE DEDENT print ( ans ) ; NEW_LINE DEDENT DEDENT def minimumDifference ( arr , q , N , m ) : NEW_LINE INDENT diff = [ 0 ] * N ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT diff [ i ] = abs ( arr [ i ] - arr [ i + 1 ] ) ; NEW_LINE DEDENT minDifference ( diff , N - 1 , q , m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 6 , 1 , 8 , 3 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE Q = [ [ 0 , 3 ] , [ 1 , 5 ] , [ 4 , 5 ] ] ; NEW_LINE M = len ( Q ) ; NEW_LINE minimumDifference ( arr , Q , N , M ) ; NEW_LINE DEDENT
Minimum number of flips or swaps of adjacent characters required to make two strings equal | Function to count the minimum number of operations required to make strings A and B equal ; Stores all dp - states ; Iterate rate over the range [ 1 , N ] ; If A [ i - 1 ] equals to B [ i - 1 ] ; Assign Dp [ i - 1 ] to Dp [ i ] ; Otherwise ; Update dp [ i ] ; If swapping is possible ; Update dp [ i ] ; Return the minimum number of steps required ; Given Input ; Function Call
def countMinSteps ( A , B , N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( A [ i - 1 ] == B [ i - 1 ] ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 1 NEW_LINE DEDENT if ( i >= 2 and A [ i - 2 ] == B [ i - 1 ] and A [ i - 1 ] == B [ i - 2 ] ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , dp [ i - 2 ] + 1 ) NEW_LINE DEDENT DEDENT return dp [ N ] NEW_LINE DEDENT A = "0101" NEW_LINE B = "0011" NEW_LINE N = len ( A ) NEW_LINE print ( countMinSteps ( A , B , N ) ) NEW_LINE
Count of N | Python program for the above approach ; Function to find the number of N digit numbers such that at least one digit occurs more than once ; Base Case ; If repeated is true , then for remaining positions any digit can be placed ; If the current state has already been computed , then return it ; Stores the count of number for the current recursive calls ; If n = 1 , 0 can be also placed ; If a digit has occurred for the second time , then set repeated to 1 ; Otherwise ; For remaining positions any digit can be placed ; If a digit has occurred for the second time , then set repeated to 1 ; Return the resultant count for the current recursive call ; Function to count all the N - digit numbers having at least one digit 's occurrence more than once ; Function to count all possible number satisfying the given criteria ; Driver Code
dp = [ [ [ - 1 for i in range ( 2 ) ] for i in range ( 1 << 10 ) ] for i in range ( 50 ) ] NEW_LINE def countOfNumbers ( digit , mask , repeated , n ) : NEW_LINE INDENT global dp NEW_LINE if ( digit == n + 1 ) : NEW_LINE INDENT if ( repeated == True ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( repeated == True ) : NEW_LINE INDENT return pow ( 10 , n - digit + 1 ) NEW_LINE DEDENT val = dp [ digit ] [ mask ] [ repeated ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 4 NEW_LINE if ( digit == 1 ) : NEW_LINE INDENT for i in range ( ( 0 if ( n == 1 ) else 1 ) , 10 ) : NEW_LINE INDENT if ( mask & ( 1 << i ) ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 1 , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 0 , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT if ( mask & ( 1 << i ) ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 1 , n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , mask | ( 1 << i ) , 0 , n ) NEW_LINE DEDENT DEDENT dp [ digit ] [ mask ] [ repeated ] = val NEW_LINE return dp [ digit ] [ mask ] [ repeated ] NEW_LINE DEDENT def countNDigitNumber ( N ) : NEW_LINE INDENT print ( countOfNumbers ( 1 , 0 , 0 , N ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE countNDigitNumber ( N ) NEW_LINE DEDENT
Construct the largest number whose sum of cost of digits is K | Function to find the maximum number among the two numbers S and T ; If "0" exists in the string S ; If "0" exists in the string T ; Else return the maximum number formed ; Recursive function to find maximum number formed such that the sum of cost of digits of formed number is K ; Base Case ; Return the stored state ; Including the digit ( idx + 1 ) ; Excluding the digit ( idx + 1 ) ; Store the result and return ; Function to find the maximum number formed such that the sum of the cost digits in the formed number is K ; Stores all Dp - states ; Recursive Call ; Return the result ; Driver Code
def getMaximum ( S , T ) : NEW_LINE INDENT if ( S . count ( "0" ) > 0 ) : NEW_LINE INDENT return T ; NEW_LINE DEDENT if ( T . count ( "0" ) > 0 ) : NEW_LINE INDENT return S ; NEW_LINE DEDENT return S if len ( S ) > len ( T ) else T ; NEW_LINE DEDENT def recursion ( arr , idx , N , K , dp ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return " " ; NEW_LINE DEDENT if ( K < 0 or idx == N ) : NEW_LINE INDENT return "0" ; NEW_LINE DEDENT if ( dp [ idx ] [ K ] != " - 1" ) : NEW_LINE INDENT return dp [ idx ] [ K ] ; NEW_LINE DEDENT include = str ( idx + 1 ) + recursion ( arr , 0 , N , K - arr [ idx ] , dp ) ; NEW_LINE exclude = recursion ( arr , idx + 1 , N , K , dp ) ; NEW_LINE dp [ idx ] [ K ] = getMaximum ( include , exclude ) NEW_LINE return ( dp [ idx ] [ K ] ) NEW_LINE DEDENT def largestNumber ( arr , N , K ) : NEW_LINE INDENT dp = [ [ " - 1" for i in range ( K + 1 ) ] for i in range ( N + 1 ) ] NEW_LINE ans = recursion ( arr , 0 , N , K , dp ) ; NEW_LINE return "0" if ans == " " else ans ; NEW_LINE DEDENT arr = [ 3 , 12 , 9 , 5 , 3 , 4 , 6 , 5 , 10 ] ; NEW_LINE K = 14 ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( largestNumber ( arr , N , K ) ) ; NEW_LINE
Count of N | Python3 program for the above approach ; Function to calculate count of ' N ' digit numbers such that bitwise AND of adjacent digits is 0. ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If current position is 1 , then any digit from [ 1 - 9 ] can be placed . If n = 1 , 0 can be also placed . ; For remaining positions , any digit from [ 0 - 9 ] can be placed after checking the conditions . ; Check if bitwise AND of current digit and previous digit is 0. ; Return answer ; Driver code ; Given Input ; Function call
dp = [ [ - 1 for i in range ( 10 ) ] for j in range ( 100 ) ] NEW_LINE val = 0 NEW_LINE def countOfNumbers ( digit , prev , n ) : NEW_LINE INDENT global val NEW_LINE global dp NEW_LINE if ( digit == n + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ digit ] [ prev ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 0 NEW_LINE if ( digit == 1 ) : NEW_LINE INDENT i = 0 if n == 1 else 1 NEW_LINE while ( i <= 9 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , i , n ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT if ( ( i & prev ) == 0 ) : NEW_LINE INDENT val += countOfNumbers ( digit + 1 , i , n ) NEW_LINE DEDENT DEDENT DEDENT return val NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( countOfNumbers ( 1 , 0 , N ) ) NEW_LINE DEDENT
Number of ways such that only K bars are visible from the left | dp array ; Function to calculate the number of permutations of N , where only K bars are visible from the left . ; If subproblem has already been calculated , return ; Only ascending order is possible ; N is placed at the first position The nest N - 1 are arranged in ( N - 1 ) ! ways ; Recursing ; Input ; Initialize dp array ; Function call
dp = [ [ 0 for i in range ( 1005 ) ] for j in range ( 1005 ) ] NEW_LINE def KvisibleFromLeft ( N , K ) : NEW_LINE INDENT if ( dp [ N ] [ K ] != - 1 ) : NEW_LINE INDENT return dp [ N ] [ K ] NEW_LINE DEDENT if ( N == K ) : NEW_LINE INDENT dp [ N ] [ K ] = 1 NEW_LINE return dp [ N ] [ K ] NEW_LINE DEDENT if ( K == 1 ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT ans *= i NEW_LINE DEDENT dp [ N ] [ K ] = ans NEW_LINE return dp [ N ] [ K ] NEW_LINE DEDENT dp [ N ] [ K ] = KvisibleFromLeft ( N - 1 , K - 1 ) + ( N - 1 ) * KvisibleFromLeft ( N - 1 , K ) NEW_LINE return dp [ N ] [ K ] NEW_LINE DEDENT N , K = 5 , 2 NEW_LINE for i in range ( 1005 ) : NEW_LINE INDENT for j in range ( 1005 ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT print ( KvisibleFromLeft ( N , K ) ) NEW_LINE
Number of distinct words of size N with at most K contiguous vowels | Power function to calculate long powers with mod ; Function for finding number of ways to create string with length N and atmost K contiguous vowels ; Array dp to store number of ways ; dp [ i ] [ 0 ] = ( dp [ i - 1 ] [ 0 ] + dp [ i - 1 ] [ 1 ] . . dp [ i - 1 ] [ k ] ) * 21 ; Now setting sum to be dp [ i ] [ 0 ] ; If j > i , no ways are possible to create a string with length i and vowel j ; If j = i all the character should be vowel ; dp [ i ] [ j ] relation with dp [ i - 1 ] [ j - 1 ] ; Adding dp [ i ] [ j ] in the sum ; Driver Code ; Input ; Function Call
def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def kvowelwords ( N , K ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE MOD = 1000000007 NEW_LINE dp = [ [ 0 for i in range ( K + 1 ) ] for i in range ( N + 1 ) ] NEW_LINE sum = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = sum * 21 NEW_LINE dp [ i ] [ 0 ] %= MOD NEW_LINE sum = dp [ i ] [ 0 ] NEW_LINE for j in range ( 1 , K + 1 ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( j == i ) : NEW_LINE INDENT dp [ i ] [ j ] = power ( 5 , i , MOD ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] * 5 NEW_LINE DEDENT dp [ i ] [ j ] %= MOD NEW_LINE sum += dp [ i ] [ j ] NEW_LINE sum %= MOD NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 3 NEW_LINE print ( kvowelwords ( N , K ) ) NEW_LINE DEDENT
Maximize the length of upper boundary formed by placing given N rectangles horizontally or vertically | Function to find maximum length of the upper boundary formed by placing each of the rectangles either horizontally or vertically ; Stores the intermediate transition states ; Place the first rectangle horizontally ; Place the first rectangle vertically ; Place horizontally ; Stores the difference in height of current and previous rectangle ; Take maximum out of two options ; Place Vertically ; Stores the difference in height of current and previous rectangle ; Take maximum out two options ; Print maximum of horizontal or vertical alignment of the last rectangle ; Driver Code
def maxBoundary ( N , V ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2 ) ] for j in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = V [ 0 ] [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = V [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = V [ i ] [ 0 ] NEW_LINE height1 = abs ( V [ i - 1 ] [ 1 ] - V [ i ] [ 1 ] ) NEW_LINE height2 = abs ( V [ i - 1 ] [ 0 ] - V [ i ] [ 1 ] ) NEW_LINE dp [ i ] [ 0 ] += max ( height1 + dp [ i - 1 ] [ 0 ] , height2 + dp [ i - 1 ] [ 1 ] ) NEW_LINE dp [ i ] [ 1 ] = V [ i ] [ 1 ] NEW_LINE vertical1 = abs ( V [ i ] [ 0 ] - V [ i - 1 ] [ 1 ] ) ; NEW_LINE vertical2 = abs ( V [ i ] [ 0 ] - V [ i - 1 ] [ 1 ] ) ; NEW_LINE dp [ i ] [ 1 ] += max ( vertical1 + dp [ i - 1 ] [ 0 ] , vertical2 + dp [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT print ( max ( dp [ N - 1 ] [ 0 ] , dp [ N - 1 ] [ 1 ] ) - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE V = [ [ 2 , 5 ] , [ 3 , 8 ] , [ 1 , 10 ] , [ 7 , 14 ] , [ 2 , 5 ] ] NEW_LINE maxBoundary ( N , V ) NEW_LINE DEDENT
Program to find the Nth natural number with exactly two bits set | Set 2 | Function to find the Nth number with exactly two bits set ; Initialize variables ; Initialize the range in which the value of ' a ' is present ; Perform Binary Search ; Find the mid value ; Update the range using the mid value t ; Find b value using a and N ; Print the value 2 ^ a + 2 ^ b ; Driver Code ; Function Call
def findNthNum ( N ) : NEW_LINE INDENT last_num = 0 NEW_LINE left = 1 NEW_LINE right = N NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE t = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( t < N ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT elif ( t == N ) : NEW_LINE INDENT a = mid NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT a = mid NEW_LINE right = mid - 1 NEW_LINE DEDENT DEDENT t = a - 1 NEW_LINE b = N - ( t * ( t + 1 ) ) // 2 - 1 NEW_LINE print ( ( 1 << a ) + ( 1 << b ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 15 NEW_LINE findNthNum ( N ) NEW_LINE DEDENT
Longest subsequence having maximum sum | Function to find the longest subsequence from the given array with maximum sum ; Stores the largest element of the array ; If Max is less than 0 ; Print the largest element of the array ; Traverse the array ; If arr [ i ] is greater than or equal to 0 ; Print elements of the subsequence ; Driver code
def longestSubWithMaxSum ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE if ( Max < 0 ) : NEW_LINE INDENT print ( Max ) NEW_LINE return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , - 4 , - 2 , 3 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE longestSubWithMaxSum ( arr , N ) NEW_LINE
Ways to sum to N using Natural Numbers up to K with repetitions allowed | Function to find the total number of ways to represent N as the sum of integers over the range [ 1 , K ] ; Initialize a list ; Update dp [ 0 ] to 1 ; Iterate over the range [ 1 , K + 1 ] ; Iterate over the range [ 1 , N + 1 ] ; If col is greater than or equal to row ; Update current dp [ col ] state ; Return the total number of ways ; Given inputs
def NumberOfways ( N , K ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE dp [ 0 ] = 1 NEW_LINE for row in range ( 1 , K + 1 ) : NEW_LINE INDENT for col in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( col >= row ) : NEW_LINE INDENT dp [ col ] = dp [ col ] + dp [ col - row ] NEW_LINE DEDENT DEDENT DEDENT return ( dp [ N ] ) NEW_LINE DEDENT N = 8 NEW_LINE K = 2 NEW_LINE print ( NumberOfways ( N , K ) ) NEW_LINE
Queries to check if array elements from indices [ L , R ] forms an Arithmetic Progression or not | Function to check if the given range of queries form an AP or not in the given array arr [ ] ; Stores length of the longest subarray forming AP for every array element ; Iterate over the range [ 0 , N ] ; Stores the index of the last element of forming AP ; Iterate until the element at index ( j , j + 1 ) forms AP ; Increment j by 1 ; Traverse the current subarray over the range [ i , j - 1 ] ; Update the length of the longest subarray at index k ; Update the value of i ; Traverse the given queries ; Print the result ; Otherwise ; Driver Code
def findAPSequence ( arr , N , Q , M ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 5 ) NEW_LINE i = 0 NEW_LINE while i + 1 < N : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j + 1 < N and arr [ j + 1 ] - arr [ j ] == arr [ i + 1 ] - arr [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT for k in range ( i , j ) : NEW_LINE INDENT dp [ k ] = j - k NEW_LINE DEDENT i = j NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT if ( dp [ Q [ i ] [ 0 ] ] >= Q [ i ] [ 1 ] - Q [ i ] [ 0 ] ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 7 , 6 , 5 , 4 , 1 ] NEW_LINE Q = [ [ 0 , 3 ] , [ 3 , 4 ] , [ 2 , 4 ] ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( Q ) NEW_LINE findAPSequence ( arr , N , Q , M ) NEW_LINE DEDENT
Minimize difference between sum of two K | Python3 program for the above approach ; Stores the values at recursive states ; Function to find the minimum difference between sum of two K - length subsets ; Base Case ; If k1 and k2 are 0 , then return the absolute difference between sum1 and sum2 ; Otherwise , return INT_MAX ; If the result is already computed , return the result ; Store the 3 options ; Including the element in first subset ; Including the element in second subset ; Not including the current element in both the subsets ; Store minimum of 3 values obtained ; Return the value for the current states ; Driver Code
import sys NEW_LINE dp = [ [ [ - 1 for i in range ( 100 ) ] for i in range ( 100 ) ] for i in range ( 100 ) ] NEW_LINE def minSumDifference ( arr , n , k1 , k2 , sum1 , sum2 ) : NEW_LINE INDENT global dp NEW_LINE if ( n < 0 ) : NEW_LINE INDENT if ( k1 == 0 and k2 == 0 ) : NEW_LINE INDENT return abs ( sum1 - sum2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return sys . maxsize + 1 NEW_LINE DEDENT DEDENT if ( dp [ n ] [ sum1 ] [ sum2 ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ sum1 ] [ sum2 ] NEW_LINE DEDENT op1 = sys . maxsize + 1 NEW_LINE op2 = sys . maxsize + 1 NEW_LINE op3 = sys . maxsize + 1 NEW_LINE if ( k1 > 0 ) : NEW_LINE INDENT op1 = minSumDifference ( arr , n - 1 , k1 - 1 , k2 , sum1 + arr [ n ] , sum2 ) NEW_LINE DEDENT if ( k2 > 0 ) : NEW_LINE INDENT op2 = minSumDifference ( arr , n - 1 , k1 , k2 - 1 , sum1 , sum2 + arr [ n ] ) NEW_LINE DEDENT op3 = minSumDifference ( arr , n - 1 , k1 , k2 , sum1 , sum2 ) NEW_LINE dp [ n ] [ sum1 ] [ sum2 ] = min ( op1 , min ( op2 , op3 ) ) NEW_LINE return dp [ n ] [ sum1 ] [ sum2 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 3 , 5 , 6 , 7 , 17 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( minSumDifference ( arr , N - 1 , K , K , 0 , 0 ) ) NEW_LINE DEDENT
Geek | Function to calculate the N - th Geek - onacci Number ; Stores the geekonacci series ; Store the first three terms of the series ; Iterate over the range [ 3 , N ] ; Update the value of arr [ i ] as the sum of previous 3 terms in the series ; Return the last element of arr [ ] as the N - th term ; Driver Code
def find ( A , B , C , N ) : NEW_LINE INDENT arr = [ 0 ] * N NEW_LINE arr [ 0 ] = A NEW_LINE arr [ 1 ] = B NEW_LINE arr [ 2 ] = C NEW_LINE for i in range ( 3 , N ) : NEW_LINE INDENT arr [ i ] = ( arr [ i - 1 ] + arr [ i - 2 ] + arr [ i - 3 ] ) NEW_LINE DEDENT return arr [ N - 1 ] NEW_LINE DEDENT A = 1 NEW_LINE B = 3 NEW_LINE C = 2 NEW_LINE N = 4 NEW_LINE print ( find ( A , B , C , N ) ) NEW_LINE
Maximum sum subsequence made up of at most K distant elements including the first and last array elements | Python program for the above approach ; ; Function to find maximum sum of a subsequence satisfying the given conditions ; Stores the maximum sum ; Starting index of the subsequence ; Stores the pair of maximum value and the index of that value ; Traverse the array ; Increment the first value of deque by arr [ i ] and store it in dp [ i ] ; Delete all the values which are less than dp [ i ] in deque ; Append the current pair of value and index in deque ; If first value of the queue is at a distance > K ; Return the value at the last index ; Driver Code
from collections import deque NEW_LINE / * Pair class Store ( x , y ) Pair * / NEW_LINE def maxResult ( arr , k ) : NEW_LINE INDENT dp = [ 0 ] * len ( arr ) NEW_LINE dp [ 0 ] = arr [ 0 ] NEW_LINE q = deque ( [ ( arr [ 0 ] , 0 ) ] ) NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT dp [ i ] = arr [ i ] + q [ 0 ] [ 0 ] NEW_LINE while q and q [ - 1 ] [ 0 ] < dp [ i ] : NEW_LINE INDENT q . pop ( ) NEW_LINE DEDENT q . append ( ( dp [ i ] , i ) ) NEW_LINE if i - k == q [ 0 ] [ 1 ] : NEW_LINE INDENT q . popleft ( ) NEW_LINE DEDENT DEDENT return dp [ - 1 ] NEW_LINE DEDENT arr = [ 10 , - 5 , - 2 , 4 , 0 , 3 ] NEW_LINE K = 3 NEW_LINE print ( maxResult ( arr , K ) ) NEW_LINE
Minimum days required to cure N persons | Function to find minimum count of days required to give a cure such that the high risk person and risk person does not get a dose on same day . ; Stores count of persons whose age is less than or equal to 10 and greater than or equal to 60. ; Stores the count of persons whose age is in the range [ 11 , 59 ] ; Traverse the array arr [ ] ; If age less than or equal to 10 or greater than or equal to 60 ; Update risk ; Update normal_risk ; Calculate days to cure risk and normal_risk persons ; Prthe days ; Driver Code ; Given array ; Size of the array ; Given P
def daysToCure ( arr , N , P ) : NEW_LINE INDENT risk = 0 NEW_LINE normal_risk = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= 60 or arr [ i ] <= 10 ) : NEW_LINE INDENT risk += 1 NEW_LINE DEDENT else : NEW_LINE INDENT normal_risk += 1 NEW_LINE DEDENT DEDENT days = ( risk // P ) + ( risk % P > 0 ) + ( normal_risk // P ) + ( normal_risk % P > 0 ) NEW_LINE print ( days ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 80 , 27 , 72 , 79 ] NEW_LINE N = len ( arr ) NEW_LINE P = 2 NEW_LINE daysToCure ( arr , N , P ) NEW_LINE DEDENT
Count numbers from a given range whose product of digits is K | Python 3 program to implement the above approach ; Function to count numbers in the range [ 0 , X ] whose product of digit is K ; If count of digits in a number greater than count of digits in X ; If product of digits of a number equal to K ; If overlapping subproblems already occurred ; Stores count of numbers whose product of digits is K ; Check if the numbers exceeds K or not ; Iterate over all possible value of i - th digits ; if number contains leading 0 ; Update res ; Update res ; Return res ; Utility function to count the numbers in the range [ L , R ] whose prod of digits is K ; Stores numbers in the form of string ; Stores overlapping subproblems ; Stores count of numbers in the range [ 0 , R ] whose product of digits is k ; Update str ; Stores count of numbers in ; the range [ 0 , L - 1 ] whose product of digits is k ; Driver Code
M = 100 NEW_LINE def cntNum ( X , i , prod , K , st , tight , dp ) : NEW_LINE INDENT end = 0 NEW_LINE if ( i >= len ( X ) or prod > K ) : NEW_LINE INDENT if ( prod == K ) : NEW_LINE return 1 NEW_LINE else : NEW_LINE return 0 NEW_LINE DEDENT if ( dp [ prod ] [ i ] [ tight ] [ st ] != - 1 ) : NEW_LINE INDENT return dp [ prod ] [ i ] [ tight ] [ st ] NEW_LINE DEDENT res = 0 NEW_LINE if ( tight != 0 ) : NEW_LINE INDENT end = ord ( X [ i ] ) - ord ( '0' ) NEW_LINE DEDENT for j in range ( end + 1 ) : NEW_LINE INDENT if ( j == 0 and st == 0 ) : NEW_LINE INDENT res += cntNum ( X , i + 1 , prod , K , False , ( tight & ( j == end ) ) , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT res += cntNum ( X , i + 1 , prod * j , K , True , ( tight & ( j == end ) ) , dp ) NEW_LINE DEDENT DEDENT dp [ prod ] [ i ] [ tight ] [ st ] = res NEW_LINE return res NEW_LINE DEDENT def UtilCntNumRange ( L , R , K ) : NEW_LINE INDENT global M NEW_LINE str1 = str ( R ) NEW_LINE dp = [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for k in range ( M ) ] for l in range ( M ) ] NEW_LINE cntR = cntNum ( str1 , 0 , 1 , K , False , True , dp ) NEW_LINE str1 = str ( L - 1 ) NEW_LINE dp = [ [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 2 ) ] for k in range ( M ) ] for l in range ( M ) ] NEW_LINE cntR = 20 NEW_LINE cntL = cntNum ( str1 , 0 , 1 , K , False , True , dp ) NEW_LINE return ( cntR - cntL ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 20 NEW_LINE R = 10000 NEW_LINE K = 14 NEW_LINE print ( UtilCntNumRange ( L , R , K ) ) NEW_LINE DEDENT
Count all possible N | Function to find the number of vowel permutations possible ; To avoid the large output value ; Initialize 2D dp array ; Initialize dp [ 1 ] [ i ] as 1 since string of length 1 will consist of only one vowel in the string ; Directed graph using the adjacency matrix ; Iterate over the range [ 1 , N ] ; Traverse the directed graph ; Traversing the list ; Update dp [ i + 1 ] [ u ] ; Stores total count of permutations ; Return count of permutations ; Driver code
def countVowelPermutation ( n ) : NEW_LINE INDENT MOD = 1e9 + 7 NEW_LINE dp = [ [ 0 for i in range ( 5 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT relation = [ [ 1 ] , [ 0 , 2 ] , [ 0 , 1 , 3 , 4 ] , [ 2 , 4 ] , [ 0 ] ] NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT for u in range ( 5 ) : NEW_LINE INDENT dp [ i + 1 ] [ u ] = 0 NEW_LINE for v in relation [ u ] : NEW_LINE INDENT dp [ i + 1 ] [ u ] += dp [ i ] [ v ] % MOD NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT ans = ( ans + dp [ n ] [ i ] ) % MOD NEW_LINE DEDENT return int ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( countVowelPermutation ( N ) ) NEW_LINE DEDENT
Queries to calculate Bitwise OR of each subtree of a given node in an N | Maximum Number of nodes ; Adjacency list ; Stores Bitwise OR of each node ; Function to add edges to the Tree ; Traverse the edges ; Add edges ; Function to perform DFS Traversal on the given tree ; Initialize answer with bitwise OR of current node ; Iterate over each child of the current node ; Skip parent node ; Call DFS for each child ; Taking bitwise OR of the answer of the child to find node 's OR value ; Function to call DFS from the '= root for precomputing answers ; Function to calculate and print the Bitwise OR for Q queries ; Perform preprocessing ; Iterate over each given query ; Utility function to find and print bitwise OR for Q queries ; Function to add edges to graph ; Function call ; Driver Code ; Number of nodes ; Function call
N = 100005 ; NEW_LINE adj = [ [ ] for i in range ( N ) ] ; NEW_LINE answer = [ 0 for i in range ( N ) ] NEW_LINE def addEdgesToGraph ( Edges , N ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] ; NEW_LINE v = Edges [ i ] [ 1 ] ; NEW_LINE adj [ u ] . append ( v ) ; NEW_LINE adj [ v ] . append ( u ) ; NEW_LINE DEDENT DEDENT def DFS ( node , parent , Val ) : NEW_LINE INDENT answer [ node ] = Val [ node ] ; NEW_LINE for child in adj [ node ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT DFS ( child , node , Val ) ; NEW_LINE answer [ node ] = ( answer [ node ] answer [ child ] ) ; NEW_LINE DEDENT DEDENT def preprocess ( Val ) : NEW_LINE INDENT DFS ( 1 , - 1 , Val ) ; NEW_LINE DEDENT def findSubtreeOR ( Queries , Q , Val ) : NEW_LINE INDENT preprocess ( Val ) ; NEW_LINE for i in range ( Q ) : NEW_LINE INDENT print ( answer [ Queries [ i ] ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT def findSubtreeORUtil ( N , Edges , Val , Queries , Q ) : NEW_LINE INDENT addEdgesToGraph ( Edges , N ) ; NEW_LINE findSubtreeOR ( Queries , Q , Val ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE Edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 3 , 4 ] , [ 3 , 5 ] ] ; NEW_LINE Val = [ 0 , 2 , 3 , 4 , 8 , 16 ] ; NEW_LINE Queries = [ 2 , 3 , 1 ] ; NEW_LINE Q = len ( Queries ) NEW_LINE findSubtreeORUtil ( N , Edges , Val , Queries , Q ) ; NEW_LINE DEDENT
Maximize sum of K elements selected from a Matrix such that each selected element must be preceded by selected row elements | Python program for the above approach ; Function to return the maximum of two elements ; Function to find the maximum sum of selecting K elements from the given 2D array arr ; dp table of size ( K + 1 ) * ( N + 1 ) ; Initialize dp [ 0 ] [ i ] = 0 ; Initialize dp [ i ] [ 0 ] = 0 ; Selecting i elements ; Select i elements till jth row ; sum = 0 , to keep track of cummulative elements sum ; Traverse arr [ j ] [ k ] until number of elements until k > i ; Select arr [ j ] [ k - 1 ] th item ; Store the maxSum in dp [ i ] [ j + 1 ] ; Return the maximum sum ; Driver Code ; Function Call
import math ; NEW_LINE def max ( a , b ) : NEW_LINE INDENT if ( a > b ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return b ; NEW_LINE DEDENT DEDENT def maximumsum ( arr , K , N , M ) : NEW_LINE INDENT sum = 0 ; NEW_LINE maxSum = 0 ; NEW_LINE dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( K + 1 ) ] NEW_LINE for i in range ( 0 , N + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 0 ; NEW_LINE DEDENT for i in range ( 0 , K + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 ; NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE maxSum = dp [ i ] [ j ] ; NEW_LINE for k in range ( 1 , i + 1 ) : NEW_LINE INDENT if ( k > M ) : NEW_LINE INDENT break ; NEW_LINE DEDENT sum += arr [ j ] [ k - 1 ] ; NEW_LINE maxSum = max ( maxSum , sum + dp [ i - k ] [ j ] ) ; NEW_LINE DEDENT dp [ i ] [ j + 1 ] = maxSum ; NEW_LINE DEDENT DEDENT return dp [ K ] [ N ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 10 , 10 , 100 , 30 ] , [ 80 , 50 , 10 , 50 ] ] ; NEW_LINE N = 2 ; NEW_LINE M = 4 ; NEW_LINE K = 5 ; NEW_LINE print ( maximumsum ( arr , K , N , M ) ) ; NEW_LINE DEDENT
Subsequences of given string consisting of non | Function to find all the subsequences of the str1ing with non - repeating ch1aracters ; Base case ; Insert current subsequence ; If str1 [ i ] is not present in the current subsequence ; Insert str1 [ i ] into the set ; Insert str1 [ i ] into the current subsequence ; Remove str1 [ i ] from current subsequence ; Remove str1 [ i ] from the set ; Not including str1 [ i ] from the current subsequence ; Utility function to print all subsequences of str1ing with non - repeating ch1aracters ; Stores all possible subsequences with non - repeating ch1aracters ; Stores subsequence with non - repeating ch1aracters ; Traverse all possible subsequences containing non - repeating ch1aracters ; Print subsequence ; Driver Code
def FindSub ( sub , ch1 , str1 , res , i ) : NEW_LINE INDENT if ( i == len ( str1 ) ) : NEW_LINE INDENT sub . add ( res ) NEW_LINE return NEW_LINE DEDENT if ( str1 [ i ] not in ch1 ) : NEW_LINE INDENT ch1 . add ( str1 [ i ] ) NEW_LINE FindSub ( sub , ch1 , str1 , res + str1 [ i ] , i + 1 ) NEW_LINE res += str1 [ i ] NEW_LINE res = res [ 0 : len ( res ) - 1 ] NEW_LINE ch1 . remove ( str1 [ i ] ) NEW_LINE DEDENT FindSub ( sub , ch1 , str1 , res , i + 1 ) NEW_LINE DEDENT def printSubwithUniquech1ar ( str1 , N ) : NEW_LINE INDENT sub = set ( ) NEW_LINE ch1 = set ( ) NEW_LINE FindSub ( sub , ch1 , str1 , " " , 0 ) NEW_LINE temp = [ ] NEW_LINE for substr1ing in sub : NEW_LINE temp . append ( substr1ing ) NEW_LINE temp . sort ( reverse = False ) NEW_LINE for x in temp : NEW_LINE print ( x , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str2 = " abac " NEW_LINE N = len ( str2 ) NEW_LINE printSubwithUniquech1ar ( str2 , N ) NEW_LINE DEDENT