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 o...
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 DEDE...
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 ] ...
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 ]...
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 ; Candi...
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 ▁ Hy...
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 ...
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__ ...
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 ...
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 ...
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 ...
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 ...
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 ; S...
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 D...
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 to...
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 ] )...
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 co...
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 ) ...
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...
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 +...
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 [ ] ; Coun...
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 =...
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 m...
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 INDE...
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 ...
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 s...
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 indic...
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_LI...
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 ...
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_LI...
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 previo...
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 ] - ...
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 ...
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 ) : ...
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 charac...
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...
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 palindro...
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 ...
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 . fir...
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...
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 piec...
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 IN...
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 ; Pri...
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 ) :...
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...
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 I...
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 cu...
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_...
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 ...
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 eli...
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 sub...
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 is...
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 ...
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 ]...
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 printSubs...
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 ...
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 ; NE...
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 = l...
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 ; Cal...
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 INDEN...
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 w...
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_LI...
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 ; ...
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__ ==...
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 ...
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 ...
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 no...
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...
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 ...
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 >...
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 h...
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 = We...
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 th...
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 ]...
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 maxi...
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 ...
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...
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 N...
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_di...
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 eleme...
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_LI...
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 nei...
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 ] > ma...
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 ) : NE...
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...
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...
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 _...
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 ; ...
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_L...
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 -...
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 INDE...
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 ...
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...
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 p...
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...
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...
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 undir...
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 ] [...
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...
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 ] == s...
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 pos...
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 ...
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 ...
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...
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...
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_LI...
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...
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 ]...
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 ; ...
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 INDEN...
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__ ==...
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 fr...
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...
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 D...
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 ...
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...
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...
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 ▁...
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 ...
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 n...
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 sam...
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 = ' geeksfor...
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...
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 a...
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 ( ) . Ret...
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 preProcessedCub...
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 en...
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 ) : N...
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...
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 inde...
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 t...
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_...
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...
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 ra...
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 repea...
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 ] [ sma...
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 d...
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 )...
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 ...
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...
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 ]...
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...
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 c...
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 ...
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...
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...
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...
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 INDE...
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...
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 ) : ...
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 ] . . d...
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 d...
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 ; ...
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 ]...
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 u...
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 ...
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 sub...
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 , ...
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 ...
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 [ ...
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...
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 ...
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_...
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_...
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 NE...
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 v...
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 [...
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 a...
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 ) ...
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 overlappin...
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 [ ...
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...
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 , ...
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 no...
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 ] ...
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 (...
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...
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 ; Re...
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 ] NE...