text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Maximize number of circular buildings that can be covered by L length wire | Python3 program for the above approach ; Function to find the maximum number of buildings covered ; Store the current sum ; Traverse the array ; Add the length of wire required for current building to cur_sum ; Add extra unit distance 1 ; If curr_sum <= length of wire increment count by 1 ; If curr_sum > length of wire increment start by 1 and decrement count by 1 and update the new curr_sum ; Update the max_count ; Return the max_count ; Driver Code ; Given Input ; Size of the array ; Function Call | Pi = 3.141592 NEW_LINE def MaxBuildingsCovered ( arr , N , L ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE start = 0 NEW_LINE curr_count = 0 NEW_LINE max_count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_sum = curr_sum + ( arr [ i ] * Pi ) NEW_LINE if ( i != 0 ) : NEW_LINE INDENT curr_sum += 1 NEW_LINE DEDENT if ( curr_sum <= L ) : NEW_LINE INDENT curr_count += 1 NEW_LINE DEDENT elif ( curr_sum > L ) : NEW_LINE INDENT curr_sum = curr_sum - ( arr [ start ] * Pi ) NEW_LINE curr_sum -= 1 NEW_LINE start += 1 NEW_LINE curr_count -= 1 NEW_LINE DEDENT max_count = max ( curr_count , max_count ) NEW_LINE DEDENT return max_count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 6 , 2 ] NEW_LINE L = 24 NEW_LINE N = len ( arr ) NEW_LINE print ( MaxBuildingsCovered ( arr , N , L ) ) NEW_LINE DEDENT |
Count numbers less than N whose Bitwise AND with N is zero | Function to count number of unset bits in the integer N ; Stores the number of unset bits in N ; Check if N is even ; Increment the value of c ; Right shift N by 1 ; Return the value of count of unset bits ; Function to count numbers whose Bitwise AND with N equal to 0 ; Stores the number of unset bits in N ; Prthe value of 2 to the power of unsetBits ; Driver Code | def countUnsetBits ( N ) : NEW_LINE INDENT c = 0 NEW_LINE while ( N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT N = N >> 1 NEW_LINE DEDENT return c NEW_LINE DEDENT def countBitwiseZero ( N ) : NEW_LINE INDENT unsetBits = countUnsetBits ( N ) NEW_LINE print ( ( 1 << unsetBits ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE countBitwiseZero ( N ) NEW_LINE DEDENT |
Check if a Binary String can be split into disjoint subsequences which are equal to "010" | Function to check if the given string can be partitioned into a number of subsequences all of which are equal to "010" ; Store the size of the string ; Store the count of 0 s and 1 s ; Traverse the given string in the forward direction ; If the character is '0' , increment count_0 by 1 ; If the character is '1' increment count_1 by 1 ; If at any point , count_1 > count_0 , return false ; If count_0 is not equal to twice count_1 , return false ; Reset the value of count_0 and count_1 ; Traverse the string in the reverse direction ; If the character is '0' increment count_0 ; If the character is '1' increment count_1 ; If count_1 > count_0 , return false ; Driver Code ; Given string ; Function Call | def isPossible ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE count_0 , count_1 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT if ( count_1 > count_0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( count_0 != ( 2 * count_1 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT count_0 , count_1 = 0 , 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT count_0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT if ( count_1 > count_0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "010100" NEW_LINE if ( isPossible ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimum number of bricks that can be intersected | Python 3 program for the above approach ; Function to find a line across a wall such that it intersects minimum number of bricks ; Declare a hashmap ; Store the maximum number of brick ending a point on x - axis ; Iterate over all the rows ; Initialize width as 0 ; Iterate over individual bricks ; Add the width of the current brick to the total width ; Increment number of bricks ending at this width position ; Update the variable , res ; Print the answer ; Driver Code ; Given Input ; Function Call | from collections import defaultdict NEW_LINE def leastBricks ( wall ) : NEW_LINE INDENT map = defaultdict ( int ) NEW_LINE res = 0 NEW_LINE for list in wall : NEW_LINE INDENT width = 0 NEW_LINE for i in range ( len ( list ) - 1 ) : NEW_LINE INDENT width += list [ i ] NEW_LINE map [ width ] += 1 NEW_LINE res = max ( res , map [ width ] ) NEW_LINE DEDENT DEDENT print ( len ( wall ) - res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 , 2 , 1 ] , [ 3 , 1 , 2 ] , [ 1 , 3 , 2 ] , [ 2 , 4 ] , [ 3 , 1 , 2 ] , [ 1 , 3 , 1 , 1 ] ] NEW_LINE leastBricks ( arr ) NEW_LINE DEDENT |
Find an N | Function to print the required permutation ; Driver code | def findPermutation ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT print ( " " , β end β = β " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE findPermutation ( N ) NEW_LINE DEDENT |
Maximize count of distinct profits possible by N transactions | Function to count distinct profits possible ; Stores the minimum total profit ; Stores the maximum total profit ; Return count of distinct profits ; Driver code ; Input ; Function call | def numberOfWays ( N , X , Y ) : NEW_LINE INDENT S1 = ( N - 1 ) * X + Y NEW_LINE S2 = ( N - 1 ) * Y + X NEW_LINE return ( S2 - S1 + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE X = 13 NEW_LINE Y = 15 NEW_LINE print ( numberOfWays ( N , X , Y ) ) NEW_LINE DEDENT |
Minimum number of operations required to make a permutation of first N natural numbers equal | Function to find the minimum number of operations required to make all array elements equal ; Store the count of operations required ; Increment by K - 1 , as the last element will be used again for the next K consecutive elements ; Increment count by 1 ; Return the result ; Driver Code ; Given Input | def MinimumOperations ( A , N , K ) : NEW_LINE INDENT Count = 0 NEW_LINE i = 0 NEW_LINE while ( i < N - 1 ) : NEW_LINE INDENT i = i + K - 1 NEW_LINE Count += 1 NEW_LINE DEDENT return Count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 5 , 4 , 3 , 1 , 2 ] NEW_LINE K = 3 NEW_LINE N = len ( A ) NEW_LINE print ( MinimumOperations ( A , N , K ) ) NEW_LINE DEDENT |
Consecutive Prime numbers greater than equal to given number . | python 3 program for the above approach Function to check prime . ; Function to check prime . ; It means it is not a prime ; No factor other than 1 therefore prime number ; Function to find out the required consecutive primes . ; Finding first prime just less than sqrt ( n ) . ; Finding prime just greater than sqrt ( n ) . ; Product of both prime is greater than n then print it ; Finding prime greater than second ; Driver Program | from math import sqrt NEW_LINE def is_prime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def consecutive_primes ( n ) : NEW_LINE INDENT first = - 1 NEW_LINE second = - 1 NEW_LINE i = int ( sqrt ( n ) ) NEW_LINE while ( i >= 2 ) : NEW_LINE INDENT if ( is_prime ( i ) ) : NEW_LINE INDENT first = i NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT for i in range ( int ( sqrt ( n ) ) + 1 , n // 2 + 1 , 1 ) : NEW_LINE INDENT if ( is_prime ( i ) ) : NEW_LINE INDENT second = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( first * second >= n ) : NEW_LINE INDENT print ( first , second ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( second + 1 , n + 1 , 1 ) : NEW_LINE INDENT if ( is_prime ( i ) ) : NEW_LINE INDENT print ( second , i ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 14 NEW_LINE consecutive_primes ( n ) NEW_LINE DEDENT |
Reorder characters of a string to valid English representations of digits | Python program to implement the above approach ; Function to construct the original set of digits from the string in ascending order ; Store the unique characters corresponding to word and number ; Store the required result ; Store the frequency of each character of S ; Traverse the unique characters ; Store the count of k [ i ] in S ; Traverse the corresponding word ; Decrement the frequency of characters by x ; Append the digit x times to ans ; Sort the digits in ascending order ; Given string , s ; Function Call | from collections import Counter NEW_LINE def construct_digits ( s ) : NEW_LINE INDENT k = [ " z " , " w " , " u " , " x " , " g " , " h " , " o " , " f " , " v " , " i " ] NEW_LINE l = [ " zero " , " two " , " four " , " six " , " eight " , " three " , " one " , " five " , " seven " , " nine " ] NEW_LINE c = [ 0 , 2 , 4 , 6 , 8 , 3 , 1 , 5 , 7 , 9 ] NEW_LINE ans = [ ] NEW_LINE d = Counter ( s ) NEW_LINE for i in range ( len ( k ) ) : NEW_LINE INDENT x = d . get ( k [ i ] , 0 ) NEW_LINE for j in range ( len ( l [ i ] ) ) : NEW_LINE INDENT d [ l [ i ] [ j ] ] -= x NEW_LINE DEDENT ans . append ( str ( c [ i ] ) * x ) NEW_LINE DEDENT ans . sort ( ) NEW_LINE return " " . join ( ans ) NEW_LINE DEDENT s = " fviefuro " NEW_LINE print ( construct_digits ( s ) ) NEW_LINE |
Minimum decrements required to make all pairs of adjacent matrix elements distinct | Function to count minimum number of operations required ; Case 1 : ; Case 2 : ; Print the minimum number of operations required ; The given matrix ; Function Call to count the minimum number of decrements required | n = 3 NEW_LINE m = 3 NEW_LINE def countDecrements ( arr ) : NEW_LINE INDENT count_1 = 0 NEW_LINE count_2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( ( i + j ) % 2 == arr [ i ] [ j ] % 2 ) : NEW_LINE INDENT count_1 += 1 NEW_LINE DEDENT if ( 1 - ( i + j ) % 2 == arr [ i ] [ j ] % 2 ) : NEW_LINE INDENT count_2 += 1 NEW_LINE DEDENT DEDENT DEDENT print ( min ( count_1 , count_2 ) ) NEW_LINE DEDENT arr = [ [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] , [ 1 , 2 , 3 ] ] NEW_LINE countDecrements ( arr ) NEW_LINE |
Check if X can be converted to Y by converting to 3 * ( X / 2 ) or X | Function to check if X can be made equal to Y by converting X to ( 3 * X / 2 ) or ( X - 1 ) ; Conditions for possible conversion ; Otherwise , conversion is not possible ; Driver Code | def check ( X , Y ) : NEW_LINE INDENT if ( X > 3 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT elif ( X == 1 and Y == 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT elif ( X == 2 and Y <= 3 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT elif ( X == 3 and Y <= 3 ) : 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 Y = 8 NEW_LINE check ( X , Y ) NEW_LINE DEDENT |
Count distinct sum of pairs possible from a given range | Function to count distinct sum of pairs possible from the range [ L , R ] ; Return the count of distinct sum of pairs ; Driver Code | def distIntegers ( L , R ) : NEW_LINE INDENT return 2 * R - 2 * L + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 3 , 8 NEW_LINE print ( distIntegers ( L , R ) ) NEW_LINE DEDENT |
Count subarrays having even Bitwise XOR | Function to count subarrays having even Bitwise XOR ; Store the required result ; Stores count of subarrays with even and odd XOR values ; Stores Bitwise XOR of current subarray ; Traverse the array ; Update current Xor ; If XOR is even ; Update ans ; Increment count of subarrays with even XOR ; Otherwise , increment count of subarrays with odd XOR ; Print the result ; Given array ; Stores the size of the array | def evenXorSubarray ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE freq = [ 0 ] * n NEW_LINE XOR = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT XOR = XOR ^ arr [ i ] NEW_LINE if ( XOR % 2 == 0 ) : NEW_LINE INDENT ans += freq [ 0 ] + 1 NEW_LINE freq [ 0 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += freq [ 1 ] NEW_LINE freq [ 1 ] += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE evenXorSubarray ( arr , N ) NEW_LINE |
Count occurrences of an element in a matrix of size N * N generated such that each element is equal to product of its indices | Python3 program for the above approach ; Function to count the occurrences of X in the generated square matrix ; Stores the required result ; Iterate upto square root of X ; Check if i divides X ; Store the quotient obtained on dividing X by i ; If both the numbers fall in the range , update count ; Return the result ; Driver Code ; Given N and X ; Function Call | from math import sqrt NEW_LINE def countOccurrences ( N , X ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , int ( sqrt ( X ) ) + 1 ) : NEW_LINE INDENT if X % i == 0 : NEW_LINE INDENT a = i NEW_LINE b = X // i NEW_LINE if a <= N and b <= N : NEW_LINE INDENT if a == b : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 2 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE X = 12 NEW_LINE print ( countOccurrences ( N , X ) ) NEW_LINE DEDENT |
Maximize array product by changing any array element arr [ i ] to ( | Function to find array with maximum product by changing array elements to ( - 1 ) arr [ i ] - 1 ; Traverse the array ; Applying the operation on all the positive elements ; Stores maximum element in array ; Stores index of maximum element ; Check if current element is greater than the maximum element ; Find index of the maximum element ; Perform the operation on the maximum element ; Prthe elements of the array ; Driver Code ; Function Call | def findArrayWithMaxProduct ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] - 1 NEW_LINE DEDENT DEDENT if ( N % 2 == 1 ) : NEW_LINE INDENT max_element = - 1 NEW_LINE index = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) > max_element ) : NEW_LINE INDENT max_element = abs ( arr [ i ] ) NEW_LINE index = i NEW_LINE DEDENT DEDENT arr [ index ] = - arr [ index ] - 1 NEW_LINE DEDENT for i in arr : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 3 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE findArrayWithMaxProduct ( arr , N ) NEW_LINE DEDENT |
Lexicographically smallest permutation of first N natural numbers having K perfect indices | Function to print the lexicographically smallest permutation with K perfect indices ; Iterator to traverse the array ; Traverse first K array indices ; Traverse remaining indices ; Driver Code | def findPerfectIndex ( N , K ) : NEW_LINE INDENT i = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT print ( ( N - K + 1 ) + i , end = " β " ) NEW_LINE DEDENT for i in range ( 3 , N ) : NEW_LINE INDENT print ( i - K + 1 , end = " β " ) NEW_LINE DEDENT DEDENT N = 10 NEW_LINE K = 3 NEW_LINE findPerfectIndex ( N , K ) NEW_LINE |
Count pairs having distinct sum from a given range | Function to count pairs made up of elements from the range [ L , R ] having distinct sum ; Stores the least sum which can be formed by the pairs ; Stores the highest sum which can be formed by the pairs ; Stores the count of pairs having distinct sum ; Print the count of pairs ; Driver Code ; Function call to count the number of pairs having distinct sum in the range [ L , R ] | def countPairs ( L , R ) : NEW_LINE INDENT firstNum = 2 * L NEW_LINE lastNum = 2 * R NEW_LINE Cntpairs = lastNum - firstNum + 1 NEW_LINE print ( Cntpairs ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 2 , 3 NEW_LINE countPairs ( L , R ) NEW_LINE DEDENT |
Count pairs from an array whose Bitwise OR is greater than Bitwise AND | Python 3 program for the above approach ; Function to count the number of pairs ( i , j ) their Bitwise OR is greater than Bitwise AND ; Total number of pairs possible from the array ; Stores frequency of each array element ; Traverse the array A [ ] ; Increment ump [ A [ i ] ] by 1 ; Traverse the Hashmap ump ; Subtract those pairs ( i , j ) from count which has the same element on index i and j ( i < j ) ; Print the result ; Driver Code ; Function Call | from collections import defaultdict NEW_LINE def countPairs ( A , n ) : NEW_LINE INDENT count = ( n * ( n - 1 ) ) // 2 NEW_LINE ump = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ump [ A [ i ] ] += 1 NEW_LINE DEDENT for it in ump . keys ( ) : NEW_LINE INDENT c = ump [ it ] NEW_LINE count = count - ( c * ( c - 1 ) ) // 2 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 4 , 7 ] NEW_LINE N = len ( A ) NEW_LINE countPairs ( A , N ) NEW_LINE DEDENT |
Construct a K | Function to construct binary string according to the given conditions ; Initialize with 1 ; Traverse the array ; To check if the i - th eger needs to be considered or not ; Print the binary string for i in range ( 1 , K ) : print ( bit [ i ] ) ; Given array ; Size of the array ; Given K | def constructBinaryString ( arr , N , K ) : NEW_LINE INDENT bit = 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT bit |= bit << arr [ i ] NEW_LINE DEDENT bit = bin ( bit ) . replace ( "0b " , " " ) NEW_LINE print ( bit [ 1 : K + 1 ] ) NEW_LINE DEDENT arr = [ 1 , 6 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE K = 8 NEW_LINE constructBinaryString ( arr , N , K ) NEW_LINE |
Check if a Rook can reach the given destination in a single move | Function to check if it is possible to reach destination in a single move by a rook ; Given arrays | def check ( current_row , current_col , destination_row , destination_col ) : NEW_LINE INDENT if ( current_row == destination_row ) : NEW_LINE INDENT return ( " POSSIBLE " ) NEW_LINE DEDENT elif ( current_col == destination_col ) : NEW_LINE INDENT return ( " POSSIBLE " ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( " NOT β POSSIBLE " ) NEW_LINE DEDENT DEDENT current_row = 8 NEW_LINE current_col = 8 NEW_LINE destination_row = 8 NEW_LINE destination_col = 4 NEW_LINE output = check ( current_row , current_col , destination_row , destination_col ) NEW_LINE print ( output ) NEW_LINE |
Append X digits to the end of N to make it divisible by M | Base case ; If N is divisible by M ; global variable to store result ; Iterate over the range [ 0 , 9 ] ; if N is Divisible by M upon appending X digits ; Driver Code ; Stores the number by appending X digits on the right side of N | if ( X == 0 ) : NEW_LINE INDENT if ( N % M == 0 ) : NEW_LINE INDENT global res NEW_LINE res = N NEW_LINE return True NEW_LINE DEDENT return False NEW_LINE DEDENT res = - 1 NEW_LINE def isDiv ( N , X , M ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT if ( isDiv ( N * 10 + i , X - 1 , M ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N , M , X = 4 , 50 , 2 NEW_LINE if ( isDiv ( N , X , M ) ) : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT |
Minimum increments to modify array such that value of any array element can be splitted to make all remaining elements equal | Function to count minimum moves ; Stores sum of given array ; Stores maximum array element ; Base Case ; If N is 2 , the answer will always be 0 ; Traverse the array ; Calculate sum of the array ; Finding maximum element ; Calculate ceil ( sum / N - 1 ) ; If k is smaller than maxelement ; Final sum - original sum ; Print the minimum number of increments required ; Driver Code ; Given array ; Size of given array ; Function Call | def minimumMoves ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE maxelement = - 1 NEW_LINE if ( N == 2 ) : NEW_LINE INDENT print ( 0 , end = " " ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE maxelement = max ( maxelement , arr [ i ] ) NEW_LINE DEDENT K = ( sum + N - 2 ) // ( N - 1 ) NEW_LINE K = max ( maxelement , K ) NEW_LINE ans = K * ( N - 1 ) - sum NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 7 ] NEW_LINE N = 3 NEW_LINE minimumMoves ( arr , N ) NEW_LINE DEDENT |
Generate an array with product of all subarrays of length exceeding one divisible by K | Function to check if the required array can be generated or not ; To check if divisor exists ; To store divisiors of K ; Check if K is prime or not ; If array can be generated ; Print d1 and d2 alternatively ; No such array can be generated ; Driver Code ; Given N and K ; Function Call | def array_divisbleby_k ( N , K ) : NEW_LINE INDENT flag = False NEW_LINE d1 , d2 = 0 , 0 NEW_LINE for i in range ( 2 , int ( K ** ( 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( K % i == 0 ) : NEW_LINE INDENT flag = True NEW_LINE d1 = i NEW_LINE d2 = K // i NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT print ( d2 , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( d1 , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE K = 21 NEW_LINE array_divisbleby_k ( N , K ) NEW_LINE DEDENT |
Minimum characters to be replaced to make a string concatenation of a K | Python3 program for the above approach ; Function to add an edge to graph ; Function to perform DFS traversal on the graph recursively from a given vertex u ; Visit the current vertex ; Total number of nodes in this component ; Increment the frequency of u ; Function for finding the minimum number changes required in given string ; Form the edges according to the given conditions ; Find minimum number of operations ; Frequency array for finding the most frequent character ; Frequency array for finding the most frequent character ; Finding most frequent character ; Change rest of the characters to most frequent one ; Print total number of changes ; Driver Code ; Function Call | import sys NEW_LINE sys . setrecursionlimit ( 1500 ) NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def DFS ( u , fre , S ) : NEW_LINE INDENT global visited , adj , cnt NEW_LINE visited [ u ] = 1 NEW_LINE cnt += 1 NEW_LINE fre [ ord ( S [ u ] ) - ord ( ' a ' ) ] += 1 NEW_LINE for i in adj [ u ] : NEW_LINE INDENT if ( visited [ i ] == 0 ) : NEW_LINE INDENT DFS ( i , fre , S ) NEW_LINE DEDENT DEDENT DEDENT def minimumOperations ( S , m ) : NEW_LINE INDENT global adj , visited , cnt NEW_LINE total , N = 0 , len ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT addEdge ( i , N - i - 1 ) NEW_LINE addEdge ( N - i - 1 , i ) NEW_LINE DEDENT for i in range ( N - m ) : NEW_LINE INDENT addEdge ( i , i + m ) NEW_LINE addEdge ( i + m , i ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( not visited [ i ] ) : NEW_LINE INDENT fre = [ 0 ] * 26 NEW_LINE cnt , maxx = 0 , - 1 NEW_LINE DFS ( i , fre , S ) NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT maxx = max ( maxx , fre [ j ] ) NEW_LINE DEDENT total += cnt - maxx NEW_LINE DEDENT DEDENT print ( total ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT adj = [ [ ] for i in range ( 101 ) ] NEW_LINE visited , cnt = [ 0 for i in range ( 101 ) ] , 0 NEW_LINE S = " abaaba " NEW_LINE K = 2 NEW_LINE minimumOperations ( S , K ) NEW_LINE DEDENT |
Replace specified matrix elements such that no two adjacent elements are equal | Function to display the valid matrix ; Traverse the matrix ; If the current cell is a free space and is even - indexed ; If the current cell is a free space and is odd - indexed ; Print the matrix ; Given N and M ; Given matrix ; Function call | def Print ( arr , n , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT a = arr [ i ] [ j ] NEW_LINE if ( ( i + j ) % 2 == 0 and a == ' F ' ) : NEW_LINE INDENT arr [ i ] [ j ] = '1' NEW_LINE DEDENT elif ( a == ' F ' ) : NEW_LINE INDENT arr [ i ] [ j ] = '2' NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT n , m = 4 , 4 NEW_LINE arr = [ [ ' F ' , ' F ' , ' F ' , ' F ' ] , [ ' F ' , ' O ' , ' F ' , ' F ' ] , [ ' F ' , ' F ' , ' O ' , ' F ' ] , [ ' F ' , ' F ' , ' F ' , ' F ' ] ] NEW_LINE Print ( arr , n , m ) NEW_LINE |
Lexicographically smallest string formed by removing duplicates | Function that finds lexicographically smallest after removing the duplicates from the given string ; Stores the frequency of characters ; Mark visited characters ; Stores count of each character ; Stores the resultant string ; Decrease the count of current character ; If character is not already in answer ; Last character > S [ i ] and its count > 0 ; Mark letter unvisited ; Add s [ i ] in res and mark it visited ; Return the resultant string ; Driver Code ; Given S ; Function Call | def removeDuplicateLetters ( s ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE vis = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in s : NEW_LINE INDENT cnt [ ord ( i ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT res = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt [ ord ( s [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE if ( not vis [ ord ( s [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT while ( len ( res ) > 0 and res [ - 1 ] > s [ i ] and cnt [ ord ( res [ - 1 ] ) - ord ( ' a ' ) ] > 0 ) : NEW_LINE INDENT vis [ ord ( res [ - 1 ] ) - ord ( ' a ' ) ] = 0 NEW_LINE del res [ - 1 ] NEW_LINE DEDENT res += s [ i ] NEW_LINE vis [ ord ( s [ i ] ) - ord ( ' a ' ) ] = 1 NEW_LINE DEDENT DEDENT return " " . join ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " acbc " NEW_LINE print ( removeDuplicateLetters ( S ) ) NEW_LINE DEDENT |
Number of pairs whose product is a power of 2 | Function to count pairs having product equal to a power of 2 ; Stores count of array elements which are power of 2 ; If array element contains only one set bit ; Increase count of powers of 2 ; Count required number of pairs ; Print the required number of pairs ; Driver Code ; Given array ; Size of the array ; Function call | def countPairs ( arr , N ) : NEW_LINE INDENT countPowerof2 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( bin ( arr [ i ] ) . count ( '1' ) == 1 ) : NEW_LINE INDENT countPowerof2 += 1 NEW_LINE DEDENT DEDENT desiredPairs = ( countPowerof2 * ( countPowerof2 - 1 ) ) // 2 NEW_LINE print ( desiredPairs ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 7 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT |
Count ways to split N ! into two distinct co | Python3 program for the above approach ; Maximum value of N ; Stores at each indices if given number is prime or not ; Stores count_of_primes ; Function to generate primes using Sieve of Eratsothenes ; Assume all odds are primes ; If a prime is encountered ; Mark all its multiples as non - prime ; Count primes <= MAXN ; Function to calculate ( x ^ y ) % p in O ( log y ) ; Utility function to count the number of ways N ! can be split into co - prime factors ; Driver Code ; Calling sieve function ; Given N ; Function call | import math NEW_LINE MAXN = 1000000 NEW_LINE is_prime = [ 0 ] * MAXN NEW_LINE count_of_primes = [ 0 ] * MAXN NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 3 , MAXN , 2 ) : NEW_LINE INDENT is_prime [ i ] = 1 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( MAXN ) ) , 2 ) : NEW_LINE INDENT if is_prime [ i ] : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT is_prime [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT is_prime [ 2 ] = 1 NEW_LINE for i in range ( 1 , MAXN ) : NEW_LINE INDENT count_of_primes [ i ] = ( count_of_primes [ i - 1 ] + is_prime [ i ] ) NEW_LINE DEDENT DEDENT def power ( x , y , p ) : NEW_LINE INDENT result = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if y & 1 == 1 : NEW_LINE INDENT result = ( result * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE y >>= 1 NEW_LINE DEDENT return result NEW_LINE DEDENT def numberOfWays ( N ) : NEW_LINE INDENT count = count_of_primes [ N ] - 1 NEW_LINE mod = 1000000007 NEW_LINE answer = power ( 2 , count , mod ) NEW_LINE if N == 1 : NEW_LINE INDENT answer = 0 NEW_LINE DEDENT print ( answer ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT sieve ( ) NEW_LINE N = 7 NEW_LINE numberOfWays ( N ) NEW_LINE DEDENT |
Maximum possible sum of squares of stack elements satisfying the given properties | Function to find the maximum sum of squares of stack elements ; Stores the sum ofsquares of stack elements ; Check if sum is valid ; Initialize all stack elements with 1 ; Stores the count the number of stack elements not equal to 1 ; Add the sum of squares of stack elements not equal to 1 ; Add 1 * 1 to res as the remaining stack elements are 1 ; Print the result ; Driver Code ; Function call | def maxSumOfSquares ( N , S ) : NEW_LINE INDENT res = 0 NEW_LINE if ( S < N or S > 9 * N ) : NEW_LINE INDENT cout << - 1 ; NEW_LINE return NEW_LINE DEDENT S = S - N NEW_LINE c = 0 NEW_LINE while ( S > 0 ) : NEW_LINE INDENT c += 1 NEW_LINE if ( S // 8 > 0 ) : NEW_LINE INDENT res += 9 * 9 NEW_LINE S -= 8 NEW_LINE DEDENT else : NEW_LINE INDENT res += ( S + 1 ) * ( S + 1 ) NEW_LINE break NEW_LINE DEDENT DEDENT res = res + ( N - c ) NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE S = 12 NEW_LINE maxSumOfSquares ( N , S ) NEW_LINE DEDENT |
Unset least significant K bits of a given number | Function to return the value after unsetting K LSBs ; Create a mask ; Bitwise AND operation with the number and the mask ; Given N and K ; Function call | def clearLastBit ( N , K ) : NEW_LINE INDENT mask = ( - 1 << K + 1 ) NEW_LINE N = N & mask NEW_LINE return N NEW_LINE DEDENT N = 730 NEW_LINE K = 3 NEW_LINE print ( clearLastBit ( N , K ) ) NEW_LINE |
Check if quantities of 3 distinct colors can be converted to a single color by given merge | Function to check whether it is possible to do the operation or not ; Calculate modulo 3 of all the colors ; Check for any equal pair ; Otherwise ; Given colors ; Function call | def isPossible ( r , b , g ) : NEW_LINE INDENT r = r % 3 NEW_LINE b = b % 3 NEW_LINE g = g % 3 NEW_LINE if ( r == b or b == g or g == r ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT R = 1 NEW_LINE B = 3 NEW_LINE G = 6 NEW_LINE if ( isPossible ( R , B , G ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Minimize steps required to make all array elements same by adding 1 , 2 or 5 | Function to calculate the minimum number of steps ; count stores number of operations required to make all elements equal to minimum value ; Remark , the array should remain unchanged for further calculations with different minimum ; Storing the current value of arr [ i ] in val ; Finds how much extra amount is to be removed ; Subtract the maximum number of 5 and stores remaining ; Subtract the maximum number of 2 and stores remaining ; Restores the actual value of arr [ i ] ; Return the count ; Function to find the minimum number of steps to make array elements same ; Sort the array in descending order ; Stores the minimum array element ; Stores the operations required to make array elements equal to minimum ; Stores the operations required to make array elements equal to minimum - 1 ; Stores the operations required to make array elements equal to minimum - 2 ; Return minimum of the three counts ; Driver Code | def calculate_steps ( arr , n , minimum ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT val = arr [ i ] NEW_LINE if ( arr [ i ] > minimum ) : NEW_LINE INDENT arr [ i ] = arr [ i ] - minimum NEW_LINE count += arr [ i ] // 5 NEW_LINE arr [ i ] = arr [ i ] % 5 NEW_LINE count += arr [ i ] // 2 NEW_LINE arr [ i ] = arr [ i ] % 2 NEW_LINE if ( arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT arr [ i ] = val NEW_LINE DEDENT return count NEW_LINE DEDENT def solve ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE arr = arr [ : : - 1 ] NEW_LINE minimum = arr [ n - 1 ] NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE count3 = 0 NEW_LINE count1 = calculate_steps ( arr , n , minimum ) NEW_LINE count2 = calculate_steps ( arr , n , minimum - 1 ) NEW_LINE count3 = calculate_steps ( arr , n , minimum - 2 ) NEW_LINE return min ( count1 , min ( count2 , count3 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( solve ( arr , N ) ) NEW_LINE DEDENT |
Largest palindromic string possible from given strings by rearranging the characters | Python3 program for the above approach ; Function to find largest palindrome possible from S and P after rearranging characters to make palindromic string T ; Using unordered_map to store frequency of elements mapT will have freq of elements of T ; Size of both the strings ; Take all character in mapT which occur even number of times in respective strings & simultaneously update number of characters left in map ; Check if a unique character is present in both string S and P ; Making string T in two halves half1 - first half half2 - second half ; Reverse the half2 to attach with half1 to make palindrome ; If same unique element is present in both S and P , then taking that only which is already taken through mapT ; If same unique element is not present in S and P , then take characters that make string T lexicographically smallest ; If no unique element is present in both string S and P ; Given string S and P ; Function call | from collections import defaultdict NEW_LINE def mergePalindromes ( S , P ) : NEW_LINE INDENT mapS = defaultdict ( lambda : 0 ) NEW_LINE mapP = defaultdict ( lambda : 0 ) NEW_LINE mapT = defaultdict ( lambda : 0 ) NEW_LINE n = len ( S ) NEW_LINE m = len ( P ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mapS [ ord ( S [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT mapP [ ord ( P [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT if ( mapS [ i ] % 2 == 0 ) : NEW_LINE INDENT mapT [ i ] += mapS [ i ] NEW_LINE mapS [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT mapT [ i ] += mapS [ i ] - 1 NEW_LINE mapS [ i ] = 1 NEW_LINE DEDENT if ( mapP [ i ] % 2 == 0 ) : NEW_LINE INDENT mapT [ i ] += mapP [ i ] NEW_LINE mapP [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT mapT [ i ] += mapP [ i ] - 1 NEW_LINE mapP [ i ] = 1 NEW_LINE DEDENT DEDENT check = 0 NEW_LINE for i in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT if ( mapS [ i ] > 0 and mapP [ i ] > 0 ) : NEW_LINE INDENT mapT [ i ] += 2 NEW_LINE check = 1 NEW_LINE break NEW_LINE DEDENT DEDENT half1 , half2 = " " , " " NEW_LINE for i in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( ( 2 * j ) < mapT [ i ] ) : NEW_LINE INDENT half1 += chr ( i ) NEW_LINE half2 += chr ( i ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT half2 = half2 [ : : - 1 ] NEW_LINE if ( check ) : NEW_LINE INDENT return half1 + half2 NEW_LINE DEDENT for i in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT if ( mapS [ i ] > 0 or mapP [ i ] > 0 ) : NEW_LINE INDENT half1 += chr ( i ) NEW_LINE return half1 + half2 NEW_LINE DEDENT DEDENT return half1 + half2 NEW_LINE DEDENT S = " aeabb " NEW_LINE P = " dfedf " NEW_LINE print ( mergePalindromes ( S , P ) ) NEW_LINE |
Count of subarrays having sum equal to its length | Python3 program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Decrementing all the elements of the array by 1 ; Making prefix sum array ; Declare map to store count of elements upto current element ; To count all the subarrays whose prefix sum is 0 ; Iterate the array ; Increment answer by count of current element of prefix array ; Return the answer ; Given array arr [ ] ; Function call | from collections import defaultdict NEW_LINE def countOfSubarray ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] -= 1 NEW_LINE DEDENT pref = [ 0 ] * N NEW_LINE pref [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] + arr [ i ] NEW_LINE DEDENT mp = defaultdict ( lambda : 0 ) NEW_LINE answer = 0 NEW_LINE mp [ 0 ] += 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT answer += mp [ pref [ i ] ] NEW_LINE mp [ pref [ i ] ] += 1 NEW_LINE DEDENT return answer NEW_LINE DEDENT arr = [ 1 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countOfSubarray ( arr , N ) ) NEW_LINE |
Nth Subset of the Sequence consisting of powers of K in increasing order of their Sum | Python3 program to print subset at the nth position ordered by the sum of the elements ; Function to print the elements of the subset at pos n ; Initialize count = 0 and x = 0 ; Create a vector for storing the elements of subsets ; Doing until all the set bits of n are used ; This part is executed only when the last bit is set ; Right shift the bit by one position ; Increasing the count each time by one ; Printing the values os elements ; Driver Code | import math NEW_LINE def printsubset ( n , k ) : NEW_LINE INDENT count = 0 NEW_LINE x = 0 NEW_LINE vec = [ ] NEW_LINE while ( n > 0 ) : NEW_LINE INDENT x = n & 1 NEW_LINE if ( x ) : NEW_LINE INDENT vec . append ( pow ( k , count ) ) NEW_LINE DEDENT n = n >> 1 NEW_LINE count += 1 NEW_LINE DEDENT for item in vec : NEW_LINE INDENT print ( item , end = " β " ) NEW_LINE DEDENT DEDENT n = 7 NEW_LINE k = 4 NEW_LINE printsubset ( n , k ) NEW_LINE |
Minimum digits to be removed to make either all digits or alternating digits same | Function to find longest possible subsequence of s beginning with x and y ; Iterate over the string ; Increment count ; Swap the positions ; Return the result ; Function that finds all the possible pairs ; Update count ; Return the answer ; Given string s ; Find the size of the string ; Function call ; This value is the count of minimum element to be removed | def solve ( s , x , y ) : NEW_LINE INDENT res = 0 NEW_LINE for c in s : NEW_LINE INDENT if ( ord ( c ) - ord ( '0' ) == x ) : NEW_LINE INDENT res += 1 NEW_LINE x , y = y , x NEW_LINE DEDENT DEDENT if ( x != y and res % 2 == 1 ) : NEW_LINE INDENT res -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def find_min ( s ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT count = max ( count , solve ( s , i , j ) ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT s = "100120013" NEW_LINE n = len ( s ) NEW_LINE answer = find_min ( s ) NEW_LINE print ( n - answer ) NEW_LINE |
Count total set bits in all numbers from range L to R | Function to count set bits in x ; Base Case ; Recursive Call ; Function that returns count of set bits present in all numbers from 1 to N ; Initialize the result ; Return the setbit count ; Driver Code ; Given L and R ; Function Call | def countSetBitsUtil ( x ) : NEW_LINE INDENT if ( x < 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( x % 2 == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + ( countSetBitsUtil ( x / 2 ) ) ; NEW_LINE DEDENT DEDENT def countSetBits ( L , R ) : NEW_LINE INDENT bitCount = 0 ; NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT bitCount += countSetBitsUtil ( i ) ; NEW_LINE DEDENT return bitCount ; 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 |
Possible values of Q such that , for any value of R , their product is equal to X times their sum | Function to find all possible values of Q ; Vector initialization to store all numbers satisfying the given condition ; Iterate for all the values of X ; Check if condition satisfied then push the number ; Possible value of Q ; Print all the numbers ; Driver Code | def values_of_Q ( X ) : NEW_LINE INDENT val_Q = [ ] NEW_LINE for i in range ( 1 , X + 1 ) : NEW_LINE INDENT if ( ( ( ( X + i ) * X ) ) % i == 0 ) : NEW_LINE INDENT val_Q . append ( X + i ) NEW_LINE DEDENT DEDENT print ( len ( val_Q ) ) NEW_LINE for i in range ( len ( val_Q ) ) : NEW_LINE INDENT print ( val_Q [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT X = 3 NEW_LINE values_of_Q ( X ) NEW_LINE |
Program to find Greatest Common Divisor ( GCD ) of N strings | Function that finds gcd of 2 strings ; If str1 length is less than that of str2 then recur with gcd ( str2 , str1 ) ; If str1 is not the concatenation of str2 ; GCD string is found ; Cut off the common prefix part of str1 & then recur ; Function to find GCD of array of strings ; Return the GCD of strings ; Given array of strings ; Function Call | def gcd ( str1 , str2 ) : NEW_LINE INDENT if ( len ( str1 ) < len ( str2 ) ) : NEW_LINE INDENT return gcd ( str2 , str1 ) NEW_LINE DEDENT elif ( not str1 . startswith ( str2 ) ) : NEW_LINE INDENT return " " NEW_LINE DEDENT elif ( len ( str2 ) == 0 ) : NEW_LINE INDENT return str1 NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( str1 [ len ( str2 ) : ] , str2 ) NEW_LINE DEDENT DEDENT def findGCD ( arr , n ) : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT result = gcd ( result , arr [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ " GFGGFG " , " GFGGFG " , " GFGGFGGFGGFG " ] NEW_LINE n = len ( arr ) NEW_LINE print ( findGCD ( arr , n ) ) NEW_LINE |
Check whether the given Matrix is balanced or not | Define the size of the matrix ; Function to check given matrix balanced or unbalanced ; Flag for check matrix is balanced or unbalanced ; Iterate row until condition is true ; Iterate cols until condition is true ; Check for corner edge elements ; Check for border elements ; Check for the middle ones ; Return balanced or not ; Given matrix mat [ ] [ ] ; Function call | N = 4 NEW_LINE M = 4 NEW_LINE def balancedMatrix ( mat ) : NEW_LINE INDENT is_balanced = True NEW_LINE i = 0 NEW_LINE while i < N and is_balanced : NEW_LINE INDENT j = 0 NEW_LINE while j < N and is_balanced : NEW_LINE INDENT if ( ( i == 0 or i == N - 1 ) and ( j == 0 or j == M - 1 ) ) : NEW_LINE INDENT if mat [ i ] [ j ] >= 2 : NEW_LINE INDENT isbalanced = False NEW_LINE DEDENT DEDENT elif ( i == 0 or i == N - 1 or j == 0 or j == M - 1 ) : NEW_LINE INDENT if mat [ i ] [ j ] >= 3 : NEW_LINE INDENT is_balanced = False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if mat [ i ] [ j ] >= 4 : NEW_LINE INDENT is_balanced = False NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if is_balanced : NEW_LINE INDENT return " Balanced " NEW_LINE DEDENT else : NEW_LINE INDENT return " Unbalanced " NEW_LINE DEDENT DEDENT mat = [ [ 1 , 2 , 3 , 4 ] , [ 3 , 5 , 2 , 6 ] , [ 5 , 3 , 6 , 1 ] , [ 9 , 5 , 6 , 0 ] ] NEW_LINE print ( balancedMatrix ( mat ) ) NEW_LINE |
Convert Unix timestamp to DD / MM / YYYY HH : MM : SS format | Function to convert unix time to Human readable format ; Save the time in Human readable format ; Number of days in month in normal year ; Calculate total days unix time T ; Calculating current year ; Updating extradays because it will give days till previous day and we have include current day ; Calculating MONTH and DATE ; Current Month ; Calculating HH : MM : YYYY ; Return the time ; Driver code ; Given unix time ; Function call to convert unix time to human read able ; Print time in format DD : MM : YYYY : HH : MM : SS | def unixTimeToHumanReadable ( seconds ) : NEW_LINE INDENT ans = " " NEW_LINE daysOfMonth = [ 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] NEW_LINE ( currYear , daysTillNow , extraTime , extraDays , index , date , month , hours , minutes , secondss , flag ) = ( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ) NEW_LINE daysTillNow = seconds // ( 24 * 60 * 60 ) NEW_LINE extraTime = seconds % ( 24 * 60 * 60 ) NEW_LINE currYear = 1970 NEW_LINE while ( daysTillNow >= 365 ) : NEW_LINE INDENT if ( currYear % 400 == 0 or ( currYear % 4 == 0 and currYear % 100 != 0 ) ) : NEW_LINE INDENT daysTillNow -= 366 NEW_LINE DEDENT else : NEW_LINE INDENT daysTillNow -= 365 NEW_LINE DEDENT currYear += 1 NEW_LINE DEDENT extraDays = daysTillNow + 1 NEW_LINE if ( currYear % 400 == 0 or ( currYear % 4 == 0 and currYear % 100 != 0 ) ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT month = 0 NEW_LINE index = 0 NEW_LINE if ( flag == 1 ) : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT if ( index == 1 ) : NEW_LINE INDENT if ( extraDays - 29 < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT month += 1 NEW_LINE extraDays -= 29 NEW_LINE DEDENT else : NEW_LINE INDENT if ( extraDays - daysOfMonth [ index ] < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT month += 1 NEW_LINE extraDays -= daysOfMonth [ index ] NEW_LINE DEDENT index += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while ( True ) : NEW_LINE INDENT if ( extraDays - daysOfMonth [ index ] < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT month += 1 NEW_LINE extraDays -= daysOfMonth [ index ] NEW_LINE index += 1 NEW_LINE DEDENT DEDENT if ( extraDays > 0 ) : NEW_LINE INDENT month += 1 NEW_LINE date = extraDays NEW_LINE DEDENT else : NEW_LINE INDENT if ( month == 2 and flag == 1 ) : NEW_LINE INDENT date = 29 NEW_LINE DEDENT else : NEW_LINE INDENT date = daysOfMonth [ month - 1 ] NEW_LINE DEDENT DEDENT hours = extraTime // 3600 NEW_LINE minutes = ( extraTime % 3600 ) // 60 NEW_LINE secondss = ( extraTime % 3600 ) % 60 NEW_LINE ans += str ( date ) NEW_LINE ans += " / " NEW_LINE ans += str ( month ) NEW_LINE ans += " / " NEW_LINE ans += str ( currYear ) NEW_LINE ans += " β " NEW_LINE ans += str ( hours ) NEW_LINE ans += " : " NEW_LINE ans += str ( minutes ) NEW_LINE ans += " : " NEW_LINE ans += str ( secondss ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT T = 1595497956 NEW_LINE ans = unixTimeToHumanReadable ( T ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Maximum area of a Rectangle that can be circumscribed about a given Rectangle of size LxW | Function to find area of rectangle inscribed another rectangle of length L and width W ; Area of rectangle ; Return the area ; Driver Code ; Given Dimensions ; Function Call | def AreaofRectangle ( L , W ) : NEW_LINE INDENT area = ( W + L ) * ( W + L ) / 2 NEW_LINE return area NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 18 NEW_LINE W = 12 NEW_LINE print ( AreaofRectangle ( L , W ) ) NEW_LINE DEDENT |
Minimum number of operations required to reduce N to 0 | Python3 program to implement the above approach ; Function to count the minimum steps required to reduce n ; Base case ; Allocate memory for storing intermediate results ; Store base values ; Stores square root of each number ; Compute square root ; Use rule 1 to find optimized answer ; Check if it perfectly divides n ; Use of rule 2 to find the optimized answer ; Store computed value ; Return answer ; Driver Code | import math NEW_LINE import sys NEW_LINE def downToZero ( n ) : NEW_LINE INDENT if ( n <= 3 ) : NEW_LINE INDENT return n NEW_LINE DEDENT dp = [ - 1 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE dp [ 2 ] = 2 NEW_LINE dp [ 3 ] = 3 NEW_LINE for i in range ( 4 , n + 1 ) : NEW_LINE INDENT sqr = ( int ) ( math . sqrt ( i ) ) NEW_LINE best = sys . maxsize NEW_LINE while ( sqr > 1 ) : NEW_LINE INDENT if ( i % sqr == 0 ) : NEW_LINE INDENT best = min ( best , 1 + dp [ sqr ] ) NEW_LINE DEDENT sqr -= 1 NEW_LINE DEDENT best = min ( best , 1 + dp [ i - 1 ] ) NEW_LINE dp [ i ] = best NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE print ( downToZero ( n ) ) NEW_LINE DEDENT |
Minimum number of operations required to reduce N to 0 | Function to find the minimum steps required to reduce n ; Base case ; Return answer based on parity of n ; Driver Code | def downToZero ( n ) : NEW_LINE INDENT if ( n <= 3 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return 3 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 4 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE print ( downToZero ( n ) ) ; NEW_LINE DEDENT |
Minimum count of elements required to obtain the given Array by repeated mirror operations | Function to find minimum number of elements required to form A [ ] by performing mirroring operation ; Initialize K ; Odd length array cannot be formed by mirror operation ; Check if prefix of length K is palindrome ; Check if not a palindrome ; If found to be palindrome ; Otherwise ; Return the final answer ; Driver code | def minimumrequired ( A , N ) : NEW_LINE INDENT K = N NEW_LINE while ( K > 0 ) : NEW_LINE INDENT if ( K % 2 ) == 1 : NEW_LINE INDENT ans = K NEW_LINE break NEW_LINE DEDENT ispalindrome = 1 NEW_LINE for i in range ( 0 , K // 2 ) : NEW_LINE INDENT if ( A [ i ] != A [ K - 1 - i ] ) : NEW_LINE INDENT ispalindrome = 0 NEW_LINE DEDENT DEDENT if ( ispalindrome == 1 ) : NEW_LINE INDENT ans = K // 2 NEW_LINE K = K // 2 NEW_LINE DEDENT else : NEW_LINE INDENT ans = K NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 1 , 2 , 2 , 1 , 1 , 2 , 2 , 1 ] NEW_LINE N = len ( A ) NEW_LINE print ( minimumrequired ( A , N ) ) NEW_LINE |
Sum of product of all integers upto N with their count of divisors | Function to find the sum of the product of all the integers and their positive divisors up to N ; Iterate for every number between 1 and N ; Find the first multiple of i between 1 and N ; Find the last multiple of i between 1 and N ; Find the total count of multiple of in [ 1 , N ] ; Compute the contribution of i using the formula ; Add the contribution of i to the answer ; Return the result ; Given N ; Function call | def sumOfFactors ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT first = i NEW_LINE last = ( N // i ) * i NEW_LINE factors = ( last - first ) // i + 1 NEW_LINE totalContribution = ( ( ( factors * ( factors + 1 ) ) // 2 ) * i ) NEW_LINE ans += totalContribution NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 3 NEW_LINE print ( sumOfFactors ( N ) ) NEW_LINE |
Find a number M < N such that difference between their XOR and AND is maximum | Function to return M < N such that N ^ M - N & M is maximum ; Initialize variables ; Iterate for all values < N ; Find the difference between Bitwise XOR and AND ; Check if new difference is greater than previous maximum ; Update variables ; Return the answer ; Driver Code ; Given number N ; Function call | def getMaxDifference ( N ) : NEW_LINE INDENT M = - 1 ; NEW_LINE maxDiff = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT diff = ( N ^ i ) - ( N & i ) ; NEW_LINE if ( diff >= maxDiff ) : NEW_LINE INDENT maxDiff = diff ; NEW_LINE M = i ; NEW_LINE DEDENT DEDENT return M ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE print ( getMaxDifference ( N ) ) ; NEW_LINE DEDENT |
Find a number M < N such that difference between their XOR and AND is maximum | Python3 program for the above approach ; Function to flip all bits of N ; Finding most significant bit of N ; Calculating required number ; Return the answer ; Driver Code ; Given number ; Function call | import math NEW_LINE def findM ( N ) : NEW_LINE INDENT M = 0 ; NEW_LINE MSB = int ( math . log ( N ) ) ; NEW_LINE for i in range ( MSB ) : NEW_LINE INDENT if ( ( N & ( 1 << i ) ) == 0 ) : NEW_LINE INDENT M += ( 1 << i ) ; NEW_LINE DEDENT DEDENT return M ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE print ( findM ( N ) ) ; NEW_LINE DEDENT |
Number of containers that can be filled in the given time | Matrix of containers ; Function to find the number of containers that will be filled in X seconds ; Container on top level ; If container gets filled ; Dividing the liquid equally in two halves ; Driver code | cont = [ [ 0 for i in range ( 1000 ) ] for j in range ( 1000 ) ] NEW_LINE def num_of_containers ( n , x ) : NEW_LINE INDENT count = 0 NEW_LINE cont [ 1 ] [ 1 ] = x NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT if ( cont [ i ] [ j ] >= 1 ) : NEW_LINE INDENT count += 1 NEW_LINE cont [ i + 1 ] [ j ] += ( cont [ i ] [ j ] - 1 ) / 2 NEW_LINE cont [ i + 1 ] [ j + 1 ] += ( cont [ i ] [ j ] - 1 ) / 2 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT n = 3 NEW_LINE x = 5 NEW_LINE num_of_containers ( n , x ) NEW_LINE |
Check whether there exists a triplet ( i , j , k ) such that arr [ i ] < arr [ k ] < arr [ j ] for i < j < k | Python3 program for the above approach ; Function to check if there exist triplet in the array such that i < j < k and arr [ i ] < arr [ k ] < arr [ j ] ; Initialize the heights of h1 and h3 to INT_MAX and INT_MIN respectively ; Store the current element as h1 ; If the element at top of stack is less than the current element then pop the stack top and keep updating the value of h3 ; Push the current element on the stack ; If current element is less than h3 , then we found such triplet and return true ; No triplet found , hence return false ; Driver Code ; Given array ; Function Call | import sys NEW_LINE def findTriplet ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE st = [ ] NEW_LINE h3 = - sys . maxsize - 1 NEW_LINE h1 = sys . maxsize NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT h1 = arr [ i ] NEW_LINE while ( len ( st ) > 0 and st [ - 1 ] < arr [ i ] ) : NEW_LINE INDENT h3 = st [ - 1 ] NEW_LINE del st [ - 1 ] NEW_LINE DEDENT st . append ( arr [ i ] ) NEW_LINE if ( h1 < h3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 7 , 5 , 6 ] NEW_LINE if ( findTriplet ( arr ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimum number of distinct elements after removing M items | Set 2 | Function to return minimum distinct character after M removals ; Count the occurences of number and store in count ; Count the occurences of the frequencies ; Take answer as total unique numbers and remove the frequency and subtract the answer ; Remove the minimum number of times ; Return the answer ; Driver Code ; Initialize array ; Size of array ; Function call | def distinctNumbers ( arr , m , n ) : NEW_LINE INDENT count = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ arr [ i ] ] = count . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT fre_arr = [ 0 ] * ( n + 1 ) NEW_LINE for it in count : NEW_LINE INDENT fre_arr [ count [ it ] ] += 1 NEW_LINE DEDENT ans = len ( count ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT temp = fre_arr [ i ] NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT t = min ( temp , m // i ) NEW_LINE ans -= t NEW_LINE m -= i * t NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 5 , 3 , 5 , 1 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE m = 2 NEW_LINE print ( distinctNumbers ( arr , m , n ) ) NEW_LINE DEDENT |
Find minimum moves to bring all elements in one cell of a matrix | Python3 implementation to find the minimum number of moves to bring all non - zero element in one cell of the matrix ; Function to find the minimum number of moves to bring all elements in one cell of matrix ; Moves variable to store the sum of number of moves ; Loop to count the number of the moves ; Condition to check that the current cell is a non - zero element ; Driver Code ; Coordinates of given cell ; Given Matrix ; Element to be moved ; Function call | M = 4 NEW_LINE N = 5 NEW_LINE def no_of_moves ( Matrix , x , y ) : NEW_LINE INDENT moves = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( Matrix [ i ] [ j ] != 0 ) : NEW_LINE INDENT moves += abs ( x - i ) NEW_LINE moves += abs ( y - j ) NEW_LINE DEDENT DEDENT DEDENT print ( moves ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 3 NEW_LINE y = 2 NEW_LINE Matrix = [ [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 1 , 0 , 1 ] , [ 0 , 0 , 1 , 1 , 0 ] , [ 1 , 1 , 1 , 0 , 0 ] ] NEW_LINE num = 1 NEW_LINE no_of_moves ( Matrix , x , y ) NEW_LINE DEDENT |
Check if all array elements can be removed by the given operations | Function to check if it is possible to remove all array elements ; Condition if we can remove all elements from the array ; Driver code | def removeAll ( arr , n ) : NEW_LINE INDENT if arr [ 0 ] < arr [ n - 1 ] : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT arr = [ 10 , 4 , 7 , 1 , 3 , 6 ] NEW_LINE removeAll ( arr , len ( arr ) ) NEW_LINE |
Count substring of Binary string such that each character belongs to a palindrome of size greater than 1 | Function to find the substrings in binary string such that every character belongs to a palindrome ; Total substrings ; Loop to store the count of continuous characters in the given string ; Subtract non special strings from answer ; Driver Code ; Given string ; Function call | def countSubstrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE answer = ( n * ( n - 1 ) ) // 2 NEW_LINE cnt = 1 NEW_LINE v = [ ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( cnt ) NEW_LINE cnt = 1 NEW_LINE DEDENT DEDENT if ( cnt > 0 ) : NEW_LINE INDENT v . append ( cnt ) NEW_LINE DEDENT for i in range ( len ( v ) - 1 ) : NEW_LINE INDENT answer -= ( v [ i ] + v [ i + 1 ] - 1 ) NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "00111" NEW_LINE print ( countSubstrings ( s ) ) NEW_LINE DEDENT |
Minimum minutes needed to make the time palindromic | Function to get the required minutes ; Storing hour and minute value in integral form ; Keep iterating till first digit hour becomes equal to second digit of minute and second digit of hour becomes equal to first digit of minute ; If mins is 60 , increase hour , and reinitilialized to 0 ; If hours is 60 , reinitialized to 0 ; Return the required time ; Given Time as a string ; Function call | def get_palindrome_time ( str ) : NEW_LINE INDENT hh = ( ( ord ( str [ 0 ] ) - 48 ) * 10 + ( ord ( str [ 1 ] ) - 48 ) ) NEW_LINE mm = ( ( ord ( str [ 3 ] ) - 48 ) * 10 + ( ord ( str [ 4 ] ) - 48 ) ) NEW_LINE requiredTime = 0 NEW_LINE while ( hh % 10 != mm // 10 or hh // 10 != mm % 10 ) : NEW_LINE INDENT mm += 1 NEW_LINE if ( mm == 60 ) : NEW_LINE INDENT mm = 0 NEW_LINE hh += 1 NEW_LINE DEDENT if ( hh == 24 ) : NEW_LINE INDENT hh = 0 NEW_LINE DEDENT requiredTime += 1 ; NEW_LINE DEDENT return requiredTime NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "05:39" ; NEW_LINE print ( get_palindrome_time ( str ) ) ; NEW_LINE DEDENT |
Maximum sum of values in a given range of an Array for Q queries when shuffling is allowed | Function to find the maximum sum of all subarrays ; Initialize maxsum and prefixArray ; Find the frequency using prefix Array ; Perform prefix sum ; Sort both arrays to get a greedy result ; Finally multiply largest frequency with largest array element . ; Return the answer ; Driver Code ; Initial Array ; Subarrays ; Function Call | def maximumSubarraySum ( a , n , subarrays ) : NEW_LINE INDENT maxsum = 0 NEW_LINE prefixArray = [ 0 ] * n NEW_LINE for i in range ( len ( subarrays ) ) : NEW_LINE INDENT prefixArray [ subarrays [ i ] [ 0 ] - 1 ] += 1 NEW_LINE prefixArray [ subarrays [ i ] [ 1 ] ] -= 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT prefixArray [ i ] += prefixArray [ i - 1 ] NEW_LINE DEDENT prefixArray . sort ( ) NEW_LINE prefixArray . reverse ( ) NEW_LINE a . sort ( ) NEW_LINE a . reverse ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxsum += a [ i ] * prefixArray [ i ] NEW_LINE DEDENT return maxsum NEW_LINE DEDENT n = 6 NEW_LINE a = [ 4 , 1 , 2 , 1 , 9 , 2 ] NEW_LINE subarrays = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] , [ 3 , 4 ] ] NEW_LINE print ( maximumSubarraySum ( a , n , subarrays ) ) NEW_LINE |
Maximum profit such that total stolen value is less than K to get bonus | Function to find the maximum profit from the given values ; Iterating over every possible permutation ; Driver Code ; Function Call | def maxProfit ( value , N , K ) : NEW_LINE INDENT value . sort ( ) NEW_LINE maxval = value [ N - 1 ] NEW_LINE maxProfit = 0 NEW_LINE while True : NEW_LINE INDENT curr_val = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_val += value [ i ] NEW_LINE if ( curr_val <= K ) : NEW_LINE INDENT maxProfit = max ( curr_val + maxval * ( i + 1 ) , maxProfit ) NEW_LINE DEDENT DEDENT if not next_permutation ( value ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return maxProfit NEW_LINE DEDENT def next_permutation ( p ) : NEW_LINE INDENT for a in range ( len ( p ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT if p [ a ] < p [ a + 1 ] : NEW_LINE INDENT b = len ( p ) - 1 NEW_LINE while True : NEW_LINE INDENT if p [ b ] > p [ a ] : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b = len ( p ) - 1 NEW_LINE while a < b : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT b -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT N , K = 4 , 6 NEW_LINE values = [ 5 , 2 , 7 , 3 ] NEW_LINE print ( maxProfit ( values , N , K ) ) NEW_LINE |
Min operations to reduce N by multiplying by any number or taking square root | Python3 program for the above approach ; Function to reduce N to its minimum possible value by the given operations ; Keep replacing n until is an integer ; Keep replacing n until n is divisible by i * i ; Print the answer ; Given N ; Function call | import math NEW_LINE def MinValue ( n ) : NEW_LINE INDENT while ( int ( math . sqrt ( n ) ) == math . sqrt ( n ) and n > 1 ) : NEW_LINE INDENT n = math . sqrt ( n ) NEW_LINE DEDENT for i in range ( int ( math . sqrt ( n ) ) , 1 , - 1 ) : NEW_LINE INDENT while ( n % ( i * i ) == 0 ) : NEW_LINE INDENT n /= i NEW_LINE DEDENT DEDENT print ( n ) NEW_LINE DEDENT n = 20 NEW_LINE MinValue ( n ) NEW_LINE |
Count of ways to split given string into two non | Function to check whether the substring from l to r is palindrome or not ; If characters at l and r differ ; Not a palindrome ; If the string is a palindrome ; Function to count and return the number of possible splits ; Stores the count of splits ; Check if the two substrings after the split are palindromic or not ; If both are palindromes ; Print the final count ; Driver Code | def isPalindrome ( l , r , s ) : NEW_LINE INDENT while ( l <= r ) : NEW_LINE INDENT if ( s [ l ] != s [ r ] ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT return bool ( True ) NEW_LINE DEDENT def numWays ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( isPalindrome ( 0 , i , s ) and isPalindrome ( i + 1 , n - 1 , s ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT S = " aaaaa " NEW_LINE print ( numWays ( S ) ) NEW_LINE |
Final direction after visiting every cell of Matrix starting from ( 0 , 0 ) | Function to find the direction when stopped moving ; Given size of NxM grid ; Function Call | def findDirection ( n , m ) : NEW_LINE INDENT if ( n > m ) : NEW_LINE INDENT if ( m % 2 == 0 ) : NEW_LINE INDENT print ( " Up " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Down " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT print ( " Left " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Right " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 3 ; m = 3 ; NEW_LINE findDirection ( n , m ) ; NEW_LINE |
Maximize the sum of modulus with every Array element | Function to return the maximum sum of modulus with every array element ; Sum of array elements ; Return the answer ; Driver Code | def maxModulosum ( a , n ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum1 += a [ i ] ; NEW_LINE DEDENT return sum1 - n ; NEW_LINE DEDENT a = [ 3 , 4 , 6 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( maxModulosum ( a , n ) ) ; NEW_LINE |
Minimum jumps required to group all 1 s together in a given Binary string | Function to get the minimum jump value ; Store all indices of ones ; Populating one 's indices ; Calculate median ; Jumps required for 1 's to the left of median ; Jumps required for 1 's to the right of median ; Return the final answer ; Driver Code | def getMinJumps ( s ) : NEW_LINE INDENT ones = [ ] NEW_LINE jumps , median , ind = 0 , 0 , 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT ones . append ( i ) NEW_LINE DEDENT DEDENT if ( len ( ones ) == 0 ) : NEW_LINE INDENT return jumps NEW_LINE DEDENT median = ones [ len ( ones ) // 2 ] NEW_LINE ind = median NEW_LINE for i in range ( ind , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT jumps += ind - i NEW_LINE ind -= 1 NEW_LINE DEDENT DEDENT ind = median NEW_LINE for i in range ( ind , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT jumps += i - ind NEW_LINE ind += 1 NEW_LINE DEDENT DEDENT return jumps NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "00100000010011" NEW_LINE print ( getMinJumps ( s ) ) NEW_LINE DEDENT |
Find GCD of each subtree of a given node in an N | Maximum number of nodes ; Tree represented as adjacency list ; For storing value associates with node ; For storing GCD of every subarray ; Number of nodes ; Function to find GCD of two numbers . Using Euclidean algo ; If b == 0 then simply return a ; DFS function to traverse the tree ; Initializing answer with GCD of this node . ; Iterate over each child of current node ; Skipping the parent ; Call DFS for each child ; Taking GCD of the answer of the child to find node 's GCD ; Calling DFS from the root ( 1 ) for precomputing answers ; Function to find and prGCD for Q queries ; Doing preprocessing ; Iterate over each given query ; Driver code ; Tree : 1 ( 2 ) / \ 2 ( 3 ) 3 ( 4 ) / \ 4 ( 8 ) 5 ( 16 ) ; Making a undirected tree ; Values associated with nodes ; Function call | N = 10 ** 5 + 5 NEW_LINE v = [ [ ] for i in range ( N ) ] NEW_LINE val = [ 0 ] * ( N ) NEW_LINE answer = [ 0 ] * ( N ) NEW_LINE n = 0 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def DFS ( node , parent ) : NEW_LINE INDENT answer [ node ] = val [ node ] NEW_LINE for child in v [ node ] : NEW_LINE INDENT if ( child == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT DFS ( child , node ) NEW_LINE answer [ node ] = gcd ( answer [ node ] , answer [ child ] ) NEW_LINE DEDENT DEDENT def preprocess ( ) : NEW_LINE INDENT DFS ( 1 , - 1 ) NEW_LINE DEDENT def findGCD ( queries , q ) : NEW_LINE INDENT preprocess ( ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT GCD = answer [ queries [ i ] ] NEW_LINE print ( " For β subtree β of β " , queries [ i ] , " , β GCD β = β " , GCD ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE v [ 1 ] . append ( 2 ) NEW_LINE v [ 2 ] . append ( 1 ) NEW_LINE v [ 1 ] . append ( 3 ) NEW_LINE v [ 3 ] . append ( 1 ) NEW_LINE v [ 3 ] . append ( 4 ) NEW_LINE v [ 4 ] . append ( 3 ) NEW_LINE v [ 3 ] . append ( 5 ) NEW_LINE v [ 5 ] . append ( 3 ) NEW_LINE val [ 1 ] = 2 NEW_LINE val [ 2 ] = 3 NEW_LINE val [ 3 ] = 4 NEW_LINE val [ 4 ] = 8 NEW_LINE val [ 5 ] = 16 NEW_LINE queries = [ 2 , 3 , 1 ] NEW_LINE q = len ( queries ) NEW_LINE findGCD ( queries , q ) NEW_LINE DEDENT |
Minimize cost to convert given two integers to zero using given operations | Function to find out the minimum cost to make two number X and Y equal to zero ; If x is greater than y then swap ; Cost of making y equal to x ; Cost if we choose 1 st operation ; Cost if we choose 2 nd operation ; Total cost ; | def makeZero ( x , y , a , b ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT x , y = y , x NEW_LINE DEDENT tot_cost = ( y - x ) * a NEW_LINE cost1 = 2 * x * a NEW_LINE cost2 = x * b NEW_LINE tot_cost += min ( cost1 , cost2 ) NEW_LINE print ( tot_cost ) NEW_LINE DEDENT / * Driver code * / NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X , Y = 1 , 3 NEW_LINE cost1 , cost2 = 391 , 555 NEW_LINE makeZero ( X , Y , cost1 , cost2 ) NEW_LINE DEDENT |
Find N fractions that sum upto a given fraction N / D | Function to split the fraction into the N parts ; Loop to find the N - 1 fraction ; Loop to print the Fractions ; Driver Code ; Function Call | def splitFraction ( n , d ) : NEW_LINE INDENT ar = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ar . append ( 0 ) NEW_LINE DEDENT first = d + n - 1 NEW_LINE ar [ 0 ] = first NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT temp = first - 1 NEW_LINE ar [ i ] = first * temp NEW_LINE first -= 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ar [ i ] % n == 0 : NEW_LINE INDENT print ( "1 / " , int ( ar [ i ] / n ) , " , " , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n , " / " , ar [ i ] , " , " , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT N = 4 NEW_LINE D = 2 NEW_LINE splitFraction ( N , D ) NEW_LINE |
Count of pairs ( i , j ) in the array such that arr [ i ] is a factor of arr [ j ] | Function to return the count of Pairs ; Driver code | def numPairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ j ] % arr [ i ] == 0 : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 2 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( numPairs ( arr , n ) ) NEW_LINE |
Check if array can be converted into strictly decreasing sequence | Function to check that array can be converted into a strictly decreasing sequence ; Loop to check that each element is greater than the ( N - index ) ; If element is less than ( N - index ) ; If array can be converted ; Driver Code ; Function calling | def check ( arr , n ) : NEW_LINE INDENT flag = True ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < n - i ) : NEW_LINE INDENT flag = False ; NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 11 , 11 , 11 , 11 ] ; NEW_LINE n1 = len ( arr1 ) ; NEW_LINE if ( check ( arr1 , n1 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Minimize the non | Function to minimize the non - zero elements in the given array ; To store the min pos needed ; Loop to iterate over the elements of the given array ; If current position A [ i ] is occupied the we can place A [ i ] , A [ i + 1 ] and A [ i + 2 ] elements together at A [ i + 1 ] if exists . ; Driver Code ; Function Call | def minOccupiedPosition ( A , n ) : NEW_LINE INDENT minPos = 0 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT if ( A [ i ] > 0 ) : NEW_LINE INDENT minPos += 1 NEW_LINE i += 2 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return minPos NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 8 , 0 , 7 , 0 , 0 , 6 ] NEW_LINE n = len ( A ) NEW_LINE print ( minOccupiedPosition ( A , n ) ) NEW_LINE DEDENT |
Find minimum number K such that sum of array after multiplication by K exceed S | Python3 implementation of the approach ; Function to return the minimum value of k that satisfies the given condition ; store sum of array elements ; Calculate the sum after ; return minimum possible K ; Driver code | import math NEW_LINE def findMinimumK ( a , n , S ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT return math . ceil ( ( ( S + 1 ) * 1.0 ) / ( sum * 1.0 ) ) NEW_LINE DEDENT a = [ 10 , 7 , 8 , 10 , 12 , 19 ] NEW_LINE n = len ( a ) NEW_LINE s = 200 NEW_LINE print ( findMinimumK ( a , n , s ) ) NEW_LINE |
Find the largest number smaller than integer N with maximum number of set bits | Function to return the largest number less than N ; Iterate through all possible values ; Multiply the number by 2 i times ; Return the final result ; Driver code | def largestNum ( n ) : NEW_LINE INDENT num = 0 ; NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT x = ( 1 << i ) ; NEW_LINE if ( ( x - 1 ) <= n ) : NEW_LINE INDENT num = ( 1 << i ) - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return num ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 345 ; NEW_LINE print ( largestNum ( N ) ) ; NEW_LINE DEDENT |
Find the String having each substring with exactly K distinct characters | Function to find the required output string ; Each element at index i is modulus of K ; Driver code ; initialise integers N and K | def findString ( N , K ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( chr ( ord ( ' A ' ) + i % K ) , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 ; NEW_LINE K = 3 ; NEW_LINE findString ( N , K ) ; NEW_LINE DEDENT |
Find total no of collisions taking place between the balls in which initial direction of each ball is given | Function to count no of collision ; Length of the string ; Driver code | def count ( s ) : NEW_LINE INDENT cnt , ans = 0 , 0 NEW_LINE N = len ( s ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == ' R ' ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( s [ i ] == ' L ' ) : NEW_LINE INDENT ans += cnt NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT s = " RRLL " NEW_LINE print ( count ( s ) ) NEW_LINE |
Maximum number on 7 | Function to find the maximum number that can be displayed using the N segments ; Condition to check base case ; Condition to check if the number is even ; Condition to check if the number is odd ; Driver Code | def segments ( n ) : NEW_LINE INDENT if ( n == 1 or n == 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( n % 2 == 0 ) : NEW_LINE INDENT print ( "1" , end = " " ) ; NEW_LINE segments ( n - 2 ) ; NEW_LINE DEDENT elif ( n % 2 == 1 ) : NEW_LINE INDENT print ( "7" , end = " " ) ; NEW_LINE segments ( n - 3 ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 11 ; NEW_LINE segments ( n ) ; NEW_LINE DEDENT |
Minimum number of subsequences required to convert one string to another using Greedy Algorithm | Function to find the minimum number of subsequences required to convert one to another S2 == A and S1 == B ; At least 1 subsequence is required Even in best case , when A is same as B ; size of B ; size of A ; Create an 2D array next [ ] [ ] of size 26 * sizeOfB to store the next occurrence of a character ( ' a ' to ' z ' ) as an index [ 0 , sizeOfA - 1 ] ; Loop to Store the values of index ; If the value of next [ i ] [ j ] is infinite then update it with next [ i ] [ j + 1 ] ; Greedy algorithm to obtain the maximum possible subsequence of B to cover the remaining of A using next subsequence ; Loop to iterate over the A ; Condition to check if the character is not present in the B ; Condition to check if there is an element in B matching with character A [ i ] on or next to B [ pos ] given by next [ A [ i ] - ' a ' ] [ pos ] ; Condition to check if reached at the end of B or no such element exists on or next to A [ pos ] , thus increment number by one and reinitialise pos to zero ; Driver Code | def findMinimumSubsequences ( A , B ) : NEW_LINE INDENT numberOfSubsequences = 1 NEW_LINE sizeOfB = len ( B ) NEW_LINE sizeOfA = len ( A ) NEW_LINE inf = 1000000 NEW_LINE next = [ [ inf for i in range ( sizeOfB ) ] for i in range ( 26 ) ] NEW_LINE for i in range ( sizeOfB ) : NEW_LINE INDENT next [ ord ( B [ i ] ) - ord ( ' a ' ) ] [ i ] = i NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT for j in range ( sizeOfB - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( next [ i ] [ j ] == inf ) : NEW_LINE INDENT next [ i ] [ j ] = next [ i ] [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT pos = 0 NEW_LINE i = 0 NEW_LINE while ( i < sizeOfA ) : NEW_LINE INDENT if ( pos == 0 and next [ ord ( A [ i ] ) - ord ( ' a ' ) ] [ pos ] == inf ) : NEW_LINE INDENT numberOfSubsequences = - 1 NEW_LINE break NEW_LINE DEDENT elif ( pos < sizeOfB and next [ ord ( A [ i ] ) - ord ( ' a ' ) ] [ pos ] < inf ) : NEW_LINE INDENT nextIndex = next [ ord ( A [ i ] ) - ord ( ' a ' ) ] [ pos ] + 1 NEW_LINE pos = nextIndex NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT numberOfSubsequences += 1 NEW_LINE pos = 0 NEW_LINE DEDENT DEDENT return numberOfSubsequences NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " aacbe " NEW_LINE B = " aceab " NEW_LINE print ( findMinimumSubsequences ( A , B ) ) NEW_LINE DEDENT |
Vertical and Horizontal retrieval ( MRT ) on Tapes | Python3 program to print Horizontal filling ; It is used for checking whether tape is full or not ; It is used for calculating total retrieval time ; It is used for calculating mean retrieval time ; vector is used because n number of records can insert in one tape with size constraint ; Null vector obtained to use fresh vector 'v ; initialize variables to 0 for each iteration ; sum is used for checking whether i 'th tape is full or not ; check sum less than size of tape ; increment in j for next record ; calculating total retrieval time ; MRT formula ; calculating mean retrieval time using formula ; v . size ( ) is function of vector is used to get size of vector ; Driver Code ; store the size of records [ ] ; store the size of tapes [ ] ; sorting of an array is required to attain greedy approach of algorithm | def horizontalFill ( records , tape , nt ) : NEW_LINE INDENT sum = 0 ; NEW_LINE Retrieval_Time = 0 ; NEW_LINE current = 0 ; NEW_LINE v = [ ] ; NEW_LINE for i in range ( nt ) : NEW_LINE DEDENT ' NEW_LINE INDENT v . clear ( ) ; NEW_LINE Retrieval_Time = 0 ; NEW_LINE sum = 0 ; NEW_LINE print ( " tape " , i + 1 , " : β [ β " , end = " " ) ; NEW_LINE sum += records [ current ] ; NEW_LINE while ( sum <= tape [ i ] ) : NEW_LINE INDENT print ( records [ current ] , end = " β " ) ; NEW_LINE v . append ( records [ current ] ) ; NEW_LINE current += 1 ; NEW_LINE sum += records [ current ] ; print ( " ] " , end = " " ) ; NEW_LINE DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT Retrieval_Time += v [ i ] * ( len ( v ) - i ) ; NEW_LINE DEDENT Mrt = Retrieval_Time / len ( v ) ; NEW_LINE print ( " tMRT β : " , Mrt ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT records = [ 15 , 2 , 8 , 23 , 45 , 50 , 60 , 120 ] ; NEW_LINE tape = [ 25 , 80 , 160 ] ; NEW_LINE n = len ( records ) ; NEW_LINE m = len ( tape ) ; NEW_LINE records . sort ( ) ; NEW_LINE horizontalFill ( records , tape , m ) ; NEW_LINE DEDENT |
Circular Convolution using Matrix Method | Python program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec and padding zeros if size of h is less than maxSize ; Generating 2D matrix of circularly shifted elements ; Computing result by matrix multiplication and printing results ; Driver program | MAX_SIZE = 10 ; NEW_LINE def convolution ( x , h , n , m ) : NEW_LINE INDENT row_vec = [ 0 ] * MAX_SIZE ; NEW_LINE col_vec = [ 0 ] * MAX_SIZE ; NEW_LINE out = [ 0 ] * MAX_SIZE ; NEW_LINE circular_shift_mat = [ [ 0 for i in range ( MAX_SIZE ) ] for j in range ( MAX_SIZE ) ] ; NEW_LINE if ( n > m ) : NEW_LINE INDENT maxSize = n ; NEW_LINE DEDENT else : NEW_LINE INDENT maxSize = m ; NEW_LINE DEDENT for i in range ( maxSize ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT row_vec [ i ] = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT row_vec [ i ] = x [ i ] ; NEW_LINE DEDENT DEDENT for i in range ( maxSize ) : NEW_LINE INDENT if ( i >= m ) : NEW_LINE INDENT col_vec [ i ] = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT col_vec [ i ] = h [ i ] ; NEW_LINE DEDENT DEDENT k = 0 ; NEW_LINE d = 0 ; NEW_LINE for i in range ( maxSize ) : NEW_LINE INDENT curIndex = k - d ; NEW_LINE for j in range ( maxSize ) : NEW_LINE INDENT circular_shift_mat [ j ] [ i ] = row_vec [ curIndex % maxSize ] ; NEW_LINE curIndex += 1 ; NEW_LINE DEDENT k = maxSize ; NEW_LINE d += 1 ; NEW_LINE DEDENT for i in range ( maxSize ) : NEW_LINE INDENT for j in range ( maxSize ) : NEW_LINE INDENT out [ i ] += circular_shift_mat [ i ] [ j ] * col_vec [ j ] ; NEW_LINE DEDENT print ( out [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = [ 5 , 7 , 3 , 2 ] ; NEW_LINE n = len ( x ) ; NEW_LINE h = [ 1 , 5 ] ; NEW_LINE m = len ( h ) ; NEW_LINE convolution ( x , h , n , m ) ; NEW_LINE DEDENT |
Maximize the number of palindromic Strings | Python3 program for the above approach ; To check if there is any string of odd length ; If there is at least 1 string of odd length . ; If all the strings are of even length . ; Count of 0 's in all the strings ; Count of 1 's in all the strings ; If z is even and o is even then ans will be N . ; Otherwise ans will be N - 1. ; Driver code | def max_palindrome ( s , n ) : NEW_LINE INDENT flag = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( s [ i ] ) % 2 != 0 ) : NEW_LINE INDENT flag = 1 ; NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT z = 0 ; o = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( len ( s [ i ] ) ) : NEW_LINE INDENT if ( s [ i ] [ j ] == '0' ) : NEW_LINE INDENT z += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT o += 1 ; NEW_LINE DEDENT DEDENT DEDENT if ( o % 2 == 0 and z % 2 == 0 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT else : NEW_LINE INDENT return n - 1 ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE s = [ "1110" , "100110" , "010101" ] ; NEW_LINE print ( max_palindrome ( s , n ) ) ; NEW_LINE DEDENT |
Minimum possible travel cost among N cities | Function to return the minimum cost to travel from the first city to the last ; To store the total cost ; Start from the first city ; If found any city with cost less than that of the previous boarded bus then change the bus ; Calculate the cost to travel from the currently boarded bus till the current city ; Update the currently boarded bus ; Finally calculate the cost for the last boarding bus till the ( N + 1 ) th city ; Driver code | def minCost ( cost , n ) : NEW_LINE INDENT totalCost = 0 NEW_LINE boardingBus = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( cost [ boardingBus ] > cost [ i ] ) : NEW_LINE INDENT totalCost += ( ( i - boardingBus ) * cost [ boardingBus ] ) NEW_LINE boardingBus = i NEW_LINE DEDENT DEDENT totalCost += ( ( n - boardingBus ) * cost [ boardingBus ] ) NEW_LINE return totalCost NEW_LINE DEDENT cost = [ 4 , 7 , 8 , 3 , 4 ] NEW_LINE n = len ( cost ) NEW_LINE print ( minCost ( cost , n ) ) NEW_LINE |
Minimum cells to be flipped to get a 2 * 2 submatrix with equal elements | Python 3 implementation of the approach ; Function to return the minimum flips required such that the submatrix from mat [ i ] [ j ] to mat [ i + 1 ] [ j + 1 ] contains all equal elements ; Function to return the minimum number of slips required such that the matrix contains at least a single submatrix of size 2 * 2 with all equal elements ; To store the result ; For every submatrix of size 2 * 2 ; Update the count of flips required for the current submatrix ; Driver code | import sys NEW_LINE def minFlipsSub ( mat , i , j ) : NEW_LINE INDENT cnt0 = 0 NEW_LINE cnt1 = 0 NEW_LINE if ( mat [ i ] [ j ] == '1' ) : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT if ( mat [ i ] [ j + 1 ] == '1' ) : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT if ( mat [ i + 1 ] [ j ] == '1' ) : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT if ( mat [ i + 1 ] [ j + 1 ] == '1' ) : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT return min ( cnt0 , cnt1 ) NEW_LINE DEDENT def minFlips ( mat , r , c ) : NEW_LINE INDENT res = sys . maxsize NEW_LINE for i in range ( r - 1 ) : NEW_LINE INDENT for j in range ( c - 1 ) : NEW_LINE INDENT res = min ( res , minFlipsSub ( mat , i , j ) ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ "0101" , "0101" , "0101" ] NEW_LINE r = len ( mat ) NEW_LINE c = len ( mat [ 0 ] ) NEW_LINE print ( minFlips ( mat , r , c ) ) NEW_LINE DEDENT |
Count set bits in the Kth number after segregating even and odd from N natural numbers | Function to return the kth element of the Odd - Even sequence of length n ; Finding the index from where the even numbers will be stored ; Return the kth element ; Function to return the count of set bits in the kth number of the odd even sequence of length n ; Required kth number ; Return the count of set bits ; Driver code | def findK ( n , k ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT pos = n // 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT pos = ( n // 2 ) + 1 ; NEW_LINE DEDENT if ( k <= pos ) : NEW_LINE INDENT return ( k * 2 - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( k - pos ) * 2 ) ; NEW_LINE DEDENT DEDENT def countSetBits ( n , k ) : NEW_LINE INDENT kth = findK ( n , k ) ; NEW_LINE return bin ( kth ) . count ( '1' ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 18 ; k = 12 ; NEW_LINE print ( countSetBits ( n , k ) ) ; NEW_LINE DEDENT |
Minimum cost to convert str1 to str2 with the given operations | Function to return the minimum cost to convert str1 to sr2 ; For every character of str1 ; If current character is not equal in both the strings ; If the next character is also different in both the strings then these characters can be swapped ; Change the current character ; Driver code | def minCost ( str1 , str2 , n ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str1 [ i ] != str2 [ i ] ) : NEW_LINE INDENT if ( i < n - 1 and str1 [ i + 1 ] != str2 [ i + 1 ] ) : NEW_LINE INDENT swap ( str1 [ i ] , str1 [ i + 1 ] ) NEW_LINE cost += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cost += 1 NEW_LINE DEDENT DEDENT DEDENT return cost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abb " NEW_LINE str2 = " bba " NEW_LINE n = len ( str1 ) NEW_LINE print ( minCost ( str1 , str2 , n ) ) NEW_LINE DEDENT |
Partition first N natural number into two sets such that their sum is not coprime | Function to find the required sets ; Impossible case ; Sum of first n - 1 natural numbers ; Driver code | def find_set ( n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT sum1 = ( n * ( n - 1 ) ) / 2 ; NEW_LINE sum2 = n ; NEW_LINE print ( sum1 , " β " , sum2 ) ; NEW_LINE DEDENT n = 8 ; NEW_LINE find_set ( n ) ; NEW_LINE |
Count common elements in two arrays containing multiples of N and M | Recursive function to find gcd using euclidean algorithm ; Function to find lcm of two numbers using gcd ; Driver code | def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def lcm ( n , m ) : NEW_LINE INDENT return ( n * m ) // gcd ( n , m ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; m = 3 ; k = 5 ; NEW_LINE print ( k // lcm ( n , m ) ) ; NEW_LINE DEDENT |
Check whether a subsequence exists with sum equal to k if arr [ i ] > 2 * arr [ i | Function to check whether sum of any set of the array element is equal to k or not ; Traverse the array from end to start ; if k is greater than arr [ i ] then subtract it from k ; If there is any subsequence whose sum is equal to k ; Driver code | def CheckForSequence ( arr , n , k ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( k >= arr [ i ] ) : NEW_LINE INDENT k -= arr [ i ] ; NEW_LINE DEDENT DEDENT if ( k != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT else : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 3 , 7 , 15 , 31 ] ; NEW_LINE n = len ( A ) ; NEW_LINE if ( CheckForSequence ( A , n , 18 ) ) : NEW_LINE INDENT print ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( False ) NEW_LINE DEDENT DEDENT |
Maximum possible sub | Function to return the maximum sub - array sum after at most x swaps ; To store the required answer ; For all possible intervals ; Keep current ans as zero ; To store the integers which are not part of the sub - array currently under consideration ; To store elements which are part of the sub - array currently under consideration ; Create two sets ; Swap at most X elements ; Remove the minimum of the taken elements ; Add maximum of the discarded elements ; Update the answer ; Return the maximized sub - array sum ; Driver code | def SubarraySum ( a , n , x ) : NEW_LINE INDENT ans = - 10000 NEW_LINE for i in range ( n ) : NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT curans = 0 NEW_LINE pq = [ ] NEW_LINE pq2 = [ ] NEW_LINE for k in range ( n ) : NEW_LINE if ( k >= i and k <= j ) : NEW_LINE INDENT curans += a [ k ] NEW_LINE pq2 . append ( a [ k ] ) NEW_LINE DEDENT else : NEW_LINE INDENT pq . append ( a [ k ] ) NEW_LINE DEDENT pq . sort ( ) NEW_LINE pq . reverse ( ) NEW_LINE pq2 . sort ( ) NEW_LINE ans = max ( ans , curans ) NEW_LINE for k in range ( 1 , x + 1 ) : NEW_LINE if ( len ( pq ) == 0 or len ( pq2 ) == 0 or pq2 [ 0 ] >= pq [ 0 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT curans -= pq2 [ 0 ] NEW_LINE pq2 . pop ( 0 ) NEW_LINE curans += pq [ 0 ] NEW_LINE pq . pop ( 0 ) NEW_LINE ans = max ( ans , curans ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 5 , - 1 , 2 , 3 , 4 , - 2 , 5 ] NEW_LINE x = 2 ; NEW_LINE n = len ( a ) NEW_LINE print ( SubarraySum ( a , n , x ) ) NEW_LINE |
Generate an array of size K which satisfies the given conditions | Python3 implementation of the approach ; Function to generate and print the required array ; Initializing the array ; Finding r ( from above approach ) ; If r < 0 ; Finding ceiling and floor values ; Fill the array with ceiling values ; Fill the array with floor values ; Add 1 , 2 , 3 , ... with corresponding values ; There is no solution for below cases ; Modify A [ 1 ] and A [ k - 1 ] to get the required array ; Driver Code | import sys NEW_LINE from math import floor , ceil NEW_LINE def generateArray ( n , k ) : NEW_LINE INDENT array = [ 0 ] * k NEW_LINE remaining = n - int ( k * ( k + 1 ) / 2 ) NEW_LINE if remaining < 0 : NEW_LINE INDENT print ( " NO " ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT right_most = remaining % k NEW_LINE high = ceil ( remaining / k ) NEW_LINE low = floor ( remaining / k ) NEW_LINE for i in range ( k - right_most , k ) : NEW_LINE INDENT array [ i ] = high NEW_LINE DEDENT for i in range ( k - right_most ) : NEW_LINE INDENT array [ i ] = low NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT array [ i ] += i + 1 NEW_LINE DEDENT if k - 1 != remaining or k == 1 : NEW_LINE INDENT print ( * array ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT elif k == 2 or k == 3 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT else : NEW_LINE INDENT array [ 1 ] -= 1 NEW_LINE array [ k - 1 ] += 1 NEW_LINE print ( * array ) NEW_LINE sys . exit ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 26 , 6 NEW_LINE generateArray ( n , k ) NEW_LINE DEDENT |
Maximize the given number by replacing a segment of digits with the alternate digits given | Function to return the maximized number ; Iterate till the end of the string ; Check if it is greater or not ; Replace with the alternate till smaller ; Return original s in case no change took place ; Driver Code | def get_maximum ( s , a ) : NEW_LINE INDENT s = list ( s ) NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) < a [ ord ( s [ i ] ) - ord ( '0' ) ] ) : NEW_LINE INDENT j = i NEW_LINE while ( j < n and ( ord ( s [ j ] ) - ord ( '0' ) <= a [ ord ( s [ j ] ) - ord ( '0' ) ] ) ) : NEW_LINE INDENT s [ j ] = chr ( ord ( '0' ) + a [ ord ( s [ j ] ) - ord ( '0' ) ] ) NEW_LINE j += 1 NEW_LINE DEDENT return " " . join ( s ) ; NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "1337" NEW_LINE a = [ 0 , 1 , 2 , 5 , 4 , 6 , 6 , 3 , 1 , 9 ] NEW_LINE print ( get_maximum ( s , a ) ) NEW_LINE DEDENT |
Number of times the largest perfect square number can be subtracted from N | Python3 implementation of the approach ; Function to return the count of steps ; Variable to store the count of steps ; Iterate while N > 0 ; Get the largest perfect square and subtract it from N ; Increment steps ; Return the required count ; Driver code | from math import sqrt NEW_LINE def countSteps ( n ) : NEW_LINE INDENT steps = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT largest = int ( sqrt ( n ) ) ; NEW_LINE n -= ( largest * largest ) ; NEW_LINE steps += 1 ; NEW_LINE DEDENT return steps ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 85 ; NEW_LINE print ( countSteps ( n ) ) ; NEW_LINE DEDENT |
Maximum array sum that can be obtained after exactly k changes | Utility function to return the sum of the array elements ; Function to return the maximized sum of the array after performing the given operation exactly k times ; Sort the array elements ; Change signs of the negative elements starting from the smallest ; If a single operation has to be performed then it must be performed on the smallest positive element ; To store the index of the minimum element ; Update the minimum index ; Perform remaining operation on the smallest element ; Return the sum of the updated array ; Driver code | def sumArr ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def maxSum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE i = 0 NEW_LINE while ( i < n and k > 0 and arr [ i ] < 0 ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE k -= 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( k % 2 == 1 ) : NEW_LINE INDENT min = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ min ] > arr [ i ] ) : NEW_LINE INDENT min = i NEW_LINE DEDENT DEDENT arr [ min ] *= - 1 NEW_LINE DEDENT return sumArr ( arr , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 5 , 4 , 1 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE print ( maxSum ( arr , n , k ) ) NEW_LINE DEDENT |
Spanning Tree With Maximum Degree ( Using Kruskal 's Algorithm) | Python3 implementation of the approach ; par and rank will store the parent and rank of particular node in the Union Find Algorithm ; Find function of Union Find Algorithm ; Union function of Union Find Algorithm ; Function to find the required spanning tree ; Initialising parent of a node by itself ; Variable to store the node with maximum degree ; Finding the node with maximum degree ; Union of all edges incident on vertex with maximum degree ; Carrying out normal Kruskal Algorithm ; Driver code ; Number of nodes ; Number of edges ; ArrayList to store the graph ; Array to store the degree of each node in the graph ; Add edges and update degrees | from typing import List NEW_LINE par = [ ] NEW_LINE rnk = [ ] NEW_LINE def find ( x : int ) -> int : NEW_LINE INDENT global par NEW_LINE if ( par [ x ] != x ) : NEW_LINE INDENT par [ x ] = find ( par [ x ] ) NEW_LINE DEDENT return par [ x ] NEW_LINE DEDENT def Union ( u : int , v : int ) -> None : NEW_LINE INDENT global par , rnk NEW_LINE x = find ( u ) NEW_LINE y = find ( v ) NEW_LINE if ( x == y ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( rnk [ x ] > rnk [ y ] ) : NEW_LINE INDENT par [ y ] = x NEW_LINE DEDENT elif ( rnk [ x ] < rnk [ y ] ) : NEW_LINE INDENT par [ x ] = y NEW_LINE DEDENT else : NEW_LINE INDENT par [ x ] = y NEW_LINE rnk [ y ] += 1 NEW_LINE DEDENT DEDENT def findSpanningTree ( deg : List [ int ] , n : int , m : int , g : List [ List [ int ] ] ) -> None : NEW_LINE INDENT global rnk , par NEW_LINE par = [ i for i in range ( n + 1 ) ] NEW_LINE rnk = [ 0 ] * ( n + 1 ) NEW_LINE max = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( deg [ i ] > deg [ max ] ) : NEW_LINE INDENT max = i NEW_LINE DEDENT DEDENT for v in g [ max ] : NEW_LINE INDENT print ( " { } β { } " . format ( max , v ) ) NEW_LINE Union ( max , v ) NEW_LINE DEDENT for u in range ( 1 , n + 1 ) : NEW_LINE INDENT for v in g [ u ] : NEW_LINE INDENT x = find ( u ) NEW_LINE y = find ( v ) NEW_LINE if ( x == y ) : NEW_LINE INDENT continue NEW_LINE DEDENT Union ( x , y ) NEW_LINE print ( " { } β { } " . format ( u , v ) ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 5 NEW_LINE g = [ [ ] for _ in range ( n + 1 ) ] NEW_LINE deg = [ 0 ] * ( n + 1 ) NEW_LINE g [ 1 ] . append ( 2 ) NEW_LINE g [ 2 ] . append ( 1 ) NEW_LINE deg [ 1 ] += 1 NEW_LINE deg [ 2 ] += 1 NEW_LINE g [ 1 ] . append ( 5 ) NEW_LINE g [ 5 ] . append ( 1 ) NEW_LINE deg [ 1 ] += 1 NEW_LINE deg [ 5 ] += 1 NEW_LINE g [ 2 ] . append ( 3 ) NEW_LINE g [ 3 ] . append ( 2 ) NEW_LINE deg [ 2 ] += 1 NEW_LINE deg [ 3 ] += 1 NEW_LINE g [ 5 ] . append ( 3 ) NEW_LINE g [ 3 ] . append ( 5 ) NEW_LINE deg [ 3 ] += 1 NEW_LINE deg [ 5 ] += 1 NEW_LINE g [ 3 ] . append ( 4 ) NEW_LINE g [ 4 ] . append ( 3 ) NEW_LINE deg [ 3 ] += 1 NEW_LINE deg [ 4 ] += 1 NEW_LINE findSpanningTree ( deg , n , m , g ) NEW_LINE DEDENT |
Given count of digits 1 , 2 , 3 , 4 , find the maximum sum possible | Function to find the maximum possible sum ; To store required sum ; Number of 234 's can be formed ; Sum obtained with 234 s ; Remaining 2 's ; Sum obtained with 12 s ; Return the required sum ; Driver Code | def Maxsum ( c1 , c2 , c3 , c4 ) : NEW_LINE INDENT sum = 0 NEW_LINE two34 = min ( c2 , min ( c3 , c4 ) ) NEW_LINE sum = two34 * 234 NEW_LINE c2 -= two34 NEW_LINE sum += min ( c2 , c1 ) * 12 NEW_LINE return sum NEW_LINE DEDENT c1 = 5 ; c2 = 2 ; c3 = 3 ; c4 = 4 NEW_LINE print ( Maxsum ( c1 , c2 , c3 , c4 ) ) NEW_LINE |
Replace all elements by difference of sums of positive and negative numbers after that element | Function to print the array elements ; Function to replace all elements with absolute difference of absolute sums of positive and negative elements ; calculate difference of both sums ; if i - th element is positive , add it to positive sum ; if i - th element is negative , add it to negative sum ; replace i - th elements with absolute difference ; Driver Code | def printArray ( N , arr ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def replacedArray ( N , arr ) : NEW_LINE INDENT pos_sum = 0 NEW_LINE neg_sum = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT diff = abs ( pos_sum ) - abs ( neg_sum ) NEW_LINE if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos_sum = pos_sum + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT neg_sum = neg_sum + arr [ i ] NEW_LINE DEDENT arr [ i ] = abs ( diff ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE arr = [ 1 , - 1 , 2 , 3 , - 2 ] NEW_LINE replacedArray ( N , arr ) NEW_LINE printArray ( N , arr ) NEW_LINE N = 6 NEW_LINE arr1 = [ - 3 , - 4 , - 2 , 5 , 1 , - 2 ] NEW_LINE replacedArray ( N , arr1 ) NEW_LINE printArray ( N , arr1 ) NEW_LINE |
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; pairs from 1 to n * ( a / n ) and 1 to n * ( b / n ) ; pairs from 1 to n * ( a / n ) and n * ( b / n ) to b ; pairs from n * ( a / n ) to a and 1 to n * ( b / n ) ; pairs from n * ( a / n ) to a and n * ( b / n ) to b ; Return answer ; Driver code | def findCountOfPairs ( a , b , n ) : NEW_LINE INDENT ans = 0 NEW_LINE ans += n * int ( a / n ) * int ( b / n ) NEW_LINE ans += int ( a / n ) * ( b % n ) NEW_LINE ans += ( a % n ) * int ( b / n ) NEW_LINE ans += int ( ( ( a % n ) + ( b % n ) ) / n ) ; NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 5 NEW_LINE b = 13 NEW_LINE n = 3 NEW_LINE print ( findCountOfPairs ( a , b , n ) ) NEW_LINE DEDENT |
Generate array with minimum sum which can be deleted in P steps | Function to find the required array ; calculating minimum possible sum ; Array ; place first P natural elements ; Fill rest of the elements with 1 ; Driver Code | def findArray ( N , P ) : NEW_LINE INDENT ans = ( P * ( P + 1 ) ) // 2 + ( N - P ) ; NEW_LINE arr = [ 0 ] * ( N + 1 ) ; NEW_LINE for i in range ( 1 , P + 1 ) : NEW_LINE INDENT arr [ i ] = i ; NEW_LINE DEDENT for i in range ( P + 1 , N + 1 ) : NEW_LINE INDENT arr [ i ] = 1 ; NEW_LINE DEDENT print ( " The β Minimum β Possible β Sum β is : β " , ans ) ; NEW_LINE print ( " The β Array β Elements β are : β " ) ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT N = 5 ; NEW_LINE P = 3 ; NEW_LINE findArray ( N , P ) ; NEW_LINE |
Find Intersection of all Intervals | Function to print the intersection ; First interval ; Check rest of the intervals and find the intersection ; If no intersection exists ; Else update the intersection ; Driver code | def findIntersection ( intervals , N ) : NEW_LINE INDENT l = intervals [ 0 ] [ 0 ] NEW_LINE r = intervals [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( intervals [ i ] [ 0 ] > r or intervals [ i ] [ 1 ] < l ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT l = max ( l , intervals [ i ] [ 0 ] ) NEW_LINE r = min ( r , intervals [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT print ( " [ " , l , " , β " , r , " ] " ) NEW_LINE DEDENT intervals = [ [ 1 , 6 ] , [ 2 , 8 ] , [ 3 , 10 ] , [ 5 , 8 ] ] NEW_LINE N = len ( intervals ) NEW_LINE findIntersection ( intervals , N ) NEW_LINE |
Maximum size of sub | Function that compares a and b ; Function to return length of longest subarray that satisfies one of the given conditions ; Driver program ; Print the required answer | def cmp ( a , b ) : NEW_LINE INDENT return ( a > b ) - ( a < b ) NEW_LINE DEDENT def maxSubarraySize ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE ans = 1 NEW_LINE anchor = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT c = cmp ( arr [ i - 1 ] , arr [ i ] ) NEW_LINE if c == 0 : NEW_LINE INDENT anchor = i NEW_LINE DEDENT elif i == N - 1 or c * cmp ( arr [ i ] , arr [ i + 1 ] ) != - 1 : NEW_LINE INDENT ans = max ( ans , i - anchor + 1 ) NEW_LINE anchor = i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 9 , 4 , 2 , 10 , 7 , 8 , 8 , 1 , 9 ] NEW_LINE print ( maxSubarraySize ( arr ) ) NEW_LINE |
Maximum count of sub | Function to return the count of the required sub - strings ; Iterate over all characters ; Count with current character ; If the substring has a length k then increment count with current character ; Update max count ; Driver Code | def maxSubStrings ( s , k ) : NEW_LINE INDENT maxSubStr = 0 NEW_LINE n = len ( s ) NEW_LINE for c in range ( 27 ) : NEW_LINE INDENT ch = chr ( ord ( ' a ' ) + c ) NEW_LINE curr = 0 NEW_LINE for i in range ( n - k ) : NEW_LINE INDENT if ( s [ i ] != ch ) : NEW_LINE INDENT continue NEW_LINE DEDENT cnt = 0 NEW_LINE while ( i < n and s [ i ] == ch and cnt != k ) : NEW_LINE INDENT i += 1 NEW_LINE cnt += 1 NEW_LINE DEDENT i -= 1 NEW_LINE if ( cnt == k ) : NEW_LINE INDENT curr += 1 NEW_LINE DEDENT DEDENT maxSubStr = max ( maxSubStr , curr ) NEW_LINE DEDENT return maxSubStr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " aaacaabbaa " NEW_LINE k = 2 NEW_LINE print ( maxSubStrings ( s , k ) ) NEW_LINE DEDENT |
Count valid pairs in the array satisfying given conditions | Function to return total valid pairs ; Initialize count of all the elements ; frequency count of all the elements ; Add total valid pairs ; Exclude pairs made with a single element i . e . ( x , x ) ; Driver Code ; Function call to print required answer | def ValidPairs ( arr ) : NEW_LINE INDENT count = [ 0 ] * 121 NEW_LINE for ele in arr : NEW_LINE INDENT count [ ele ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for eleX , countX in enumerate ( count ) : NEW_LINE INDENT for eleY , countY in enumerate ( count ) : NEW_LINE INDENT if eleX < eleY : NEW_LINE INDENT continue NEW_LINE DEDENT if ( abs ( eleX - eleY ) % 2 == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans += countX * countY NEW_LINE if eleX == eleY : NEW_LINE INDENT ans -= countX NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 16 , 17 , 18 ] NEW_LINE print ( ValidPairs ( arr ) ) NEW_LINE |
Distribution of candies according to ages of students | Function to check The validity of distribution ; Stroring the max age of all students + 1 ; Stroring the max candy + 1 ; creating the frequency array of the age of students ; Creating the frequency array of the packets of candies ; pointer to tell whether we have reached the end of candy frequency array ; Flag to tell if distribution is possible or not ; Flag to tell if we can choose some candy packets for the students with age j ; If the quantity of packets is greater than or equal to the number of students of age j , then we can choose these packets for the students ; Start searching from k + 1 in next operation ; If we cannot choose any packets then the answer is NO ; Driver code | def check_distribution ( n , k , age , candy ) : NEW_LINE INDENT mxage = max ( age ) + 1 NEW_LINE mxcandy = max ( candy ) + 1 NEW_LINE fr1 = [ 0 ] * mxage NEW_LINE fr2 = [ 0 ] * mxcandy NEW_LINE for j in range ( n ) : NEW_LINE INDENT fr1 [ age [ j ] ] += 1 NEW_LINE DEDENT for j in range ( k ) : NEW_LINE INDENT fr2 [ candy [ j ] ] += 1 NEW_LINE DEDENT k = 0 NEW_LINE Tf = True NEW_LINE for j in range ( mxage ) : NEW_LINE INDENT if ( fr1 [ j ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT flag = False NEW_LINE while ( k < mxcandy ) : NEW_LINE INDENT if ( fr1 [ j ] <= fr2 [ k ] ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT k += 1 NEW_LINE DEDENT k = k + 1 NEW_LINE if ( flag == False ) : NEW_LINE INDENT Tf = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( Tf ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT age = [ 5 , 15 , 10 ] NEW_LINE candy = [ 2 , 2 , 2 , 3 , 3 , 4 ] NEW_LINE n = len ( age ) NEW_LINE k = len ( candy ) NEW_LINE check_distribution ( n , k , age , candy ) NEW_LINE |
Minimum number of 1 's to be replaced in a binary array | Function to find minimum number of 1 ' s β to β be β replaced β to β 0' s ; return final answer ; Driver Code | def minChanges ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( ( i - 1 >= 0 ) and A [ i - 1 ] == 1 and A [ i + 1 ] == 1 and A [ i ] == 0 ) : NEW_LINE INDENT A [ i + 1 ] = 0 NEW_LINE cnt = cnt + 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT A = [ 1 , 1 , 0 , 1 , 1 , 0 , 1 , 0 , 1 , 0 ] NEW_LINE n = len ( A ) NEW_LINE print ( minChanges ( A , n ) ) NEW_LINE |