text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Find the last remaining element after repeated removal of an element from pairs of increasing adjacent array elements | Function to print the last remaining array element after after performing given operations ; If size of the array is 1 ; Check for the condition ; If condition is not satisfied ; Driver Code ; Function Call | def canArrayBeReduced ( arr , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( arr [ 0 ] ) NEW_LINE return NEW_LINE DEDENT if ( arr [ 0 ] < arr [ N - 1 ] ) : NEW_LINE INDENT print ( arr [ N - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 5 , 2 , 4 , 1 , 3 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE canArrayBeReduced ( arr , N ) NEW_LINE DEDENT |
Minimum prefix increments required to make all elements of an array multiples of another array | Python3 program for the above approach ; Function to find minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores minimum count of operations required to make A [ i ] multiple of B [ i ] by incrementing prefix subarray ; Stores the carry ; Stores minimum difference of correspoinding element in prefix subarray ; Traverse the array ; Stores the closest greater or equal number to A [ i ] which is a multiple of B [ i ] ; Stores minimum difference ; Update totalOperations ; Update carry ; Driver Code ; Input arrays A [ ] and B [ ] ; Length of arrays | from math import ceil , floor NEW_LINE def MinimumMoves ( A , B , N ) : NEW_LINE INDENT totalOperations = 0 NEW_LINE carry = 0 NEW_LINE K = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT nearestMultiple = ceil ( ( A [ i ] + carry ) / B [ i ] ) * B [ i ] NEW_LINE K = nearestMultiple - ( A [ i ] + carry ) NEW_LINE totalOperations += K NEW_LINE carry += K NEW_LINE DEDENT return totalOperations NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 4 , 5 , 2 , 5 , 5 , 9 ] NEW_LINE B = [ 1 , 1 , 9 , 6 , 3 , 8 , 7 ] NEW_LINE N = len ( A ) NEW_LINE print ( MinimumMoves ( A , B , N ) ) NEW_LINE DEDENT |
Minimize deviation of an array by given operations | Function to find the minimum deviation of the array A [ ] ; Store all array elements in sorted order ; Odd number are transformed using 2 nd operation ; ( Maximum - Minimum ) ; Check if the size of set is > 0 and the maximum element is divisible by 2 ; Maximum element of the set ; Erase the maximum element ; Using operation 1 ; ( Maximum - Minimum ) ; Print the Minimum Deviation Obtained ; Driver Code ; Function Call to find Minimum Deviation of A [ ] | def minimumDeviation ( A , N ) : NEW_LINE INDENT s = set ( [ ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT s . add ( A [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT s . add ( 2 * A [ i ] ) NEW_LINE DEDENT DEDENT s = list ( s ) NEW_LINE diff = s [ - 1 ] - s [ 0 ] NEW_LINE while ( len ( s ) and s [ - 1 ] % 2 == 0 ) : NEW_LINE INDENT maxEl = s [ - 1 ] NEW_LINE s . remove ( maxEl ) NEW_LINE s . append ( maxEl // 2 ) NEW_LINE diff = min ( diff , s [ - 1 ] - s [ 0 ] ) NEW_LINE DEDENT print ( diff ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 4 , 1 , 5 , 20 , 3 ] NEW_LINE N = len ( A ) NEW_LINE minimumDeviation ( A , N ) NEW_LINE DEDENT |
Maximize given integer by swapping pairs of unequal bits | Function to return the maximum possible value that can be obtained from the given integer by performing given operations ; Convert to equivalent binary representation ; Stores binary representation of the maximized value ; Store the count of 0 ' s β and β 1' s ; Stores the total Number of Bits ; If current bit is set ; Increment Count1 ; Increment Count0 ; Shift all set bits to left to maximize the value ; Shift all unset bits to right to maximize the value ; Return the maximized value ; Driver Code ; Given "Input ; Function call to find the Maximum Possible Number | def findMaxNum ( num ) : NEW_LINE INDENT binaryNumber = bin ( num ) [ 2 : ] NEW_LINE maxBinaryNumber = " " NEW_LINE count0 , count1 = 0 , 0 NEW_LINE N = len ( binaryNumber ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( binaryNumber [ i ] == '1' ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT DEDENT for i in range ( count1 ) : NEW_LINE INDENT maxBinaryNumber += '1' NEW_LINE DEDENT for i in range ( count0 ) : NEW_LINE INDENT maxBinaryNumber += '0' NEW_LINE DEDENT return int ( maxBinaryNumber , 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 NEW_LINE print ( findMaxNum ( N ) ) NEW_LINE DEDENT |
Minimum deletions to convert given integer to an odd number whose sum of digits is even | Set 2 | Function to find minimum count of digits required to be remove to make N odd and the sum of digits of N even ; Stores count of even digits ; Stores count of odd digits ; Iterate over the digits of N ; If current digit is even ; Update even ; Otherwise ; Update odd ; Base conditions ; Stores count of digits required to be removed to make N odd and the sum of digits of N even ; Iterate over the digits of N ; If current digit is even ; Update ans ; Otherwise , ; Update ans ; If count of odd digits is odd ; Update ans ; Finally print the ans ; Driver code ; Input String ; Function call | def minOperations ( N ) : NEW_LINE INDENT even = 0 ; NEW_LINE odd = 0 ; NEW_LINE for it in N : NEW_LINE INDENT if ( int ( ord ( it ) - ord ( '0' ) ) % 2 == 0 ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 ; NEW_LINE DEDENT DEDENT if ( odd == 0 or odd == 1 ) : NEW_LINE INDENT print ( " Not β Possible " + " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 ; NEW_LINE for it in N : NEW_LINE INDENT if ( int ( ord ( it ) - ord ( '0' ) ) % 2 == 0 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 ; NEW_LINE DEDENT DEDENT if ( odd % 2 != 0 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT print ( ans , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = "12345" ; NEW_LINE minOperations ( N ) ; NEW_LINE DEDENT |
Find the player with least 0 s after emptying a Binary String by removing non | Function to find the player who wins the game ; Stores total count of 0 s in the string ; Stores count of consecutive 1 s ; Stores Nim - Sum on count of consecutive 1 s ; Stores length of the string ; Traverse the string ; If the current character is 1 ; Update cntConOne ; Update nimSum ; Update cntConOne ; Update cntZero ; Update nimSum ; If countZero is an even number ; nimSum is not 0 ; If nimSum is zero ; Driver Code | def FindwinnerOfGame ( S ) : NEW_LINE INDENT cntZero = 0 NEW_LINE cntConOne = 0 NEW_LINE nimSum = 0 NEW_LINE N = len ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT cntConOne += 1 NEW_LINE DEDENT else : NEW_LINE INDENT nimSum ^= cntConOne NEW_LINE cntConOne = 0 NEW_LINE cntZero += 1 NEW_LINE DEDENT DEDENT nimSum ^= cntConOne NEW_LINE if ( cntZero % 2 == 0 ) : NEW_LINE INDENT print ( " Tie " ) NEW_LINE DEDENT elif ( nimSum ) : NEW_LINE INDENT print ( " player β 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " player β 2" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "0110011" NEW_LINE FindwinnerOfGame ( S ) NEW_LINE DEDENT |
Place first N natural numbers at indices not equal to their values in an array | Function to place first N natural numbers in an array such that none of the values are equal to its indices ; Stores the required array ; Place N at the first position ; Iterate the range [ 1 , N ) ; Append elements to the sequence ; Print the sequence ; Driver Code | def generatepermutation ( N ) : NEW_LINE INDENT answer = [ ] NEW_LINE answer . append ( N ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT answer . append ( i ) NEW_LINE DEDENT print ( * answer ) NEW_LINE DEDENT N = 4 NEW_LINE generatepermutation ( N ) NEW_LINE |
Maximize element at index K in an array with at most sum M and difference between adjacent elements at most 1 | Function to calculate the maximum possible value at index K ; Stores the sum of elements in the left and right of index K ; Stores the maximum possible value at index K ; Prthe answer ; Driver Code ; Given N , K & M | def maxValueAtIndexK ( N , K , M ) : NEW_LINE INDENT S1 = 0 ; S2 = 0 ; NEW_LINE S1 = K * ( K + 1 ) // 2 ; NEW_LINE S2 = ( N - K - 1 ) * ( N - K ) // 2 ; NEW_LINE X = ( M + S1 + S2 ) // N ; NEW_LINE print ( X ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; K = 1 ; M = 7 ; NEW_LINE maxValueAtIndexK ( N , K , M ) ; NEW_LINE DEDENT |
Farthest cell from a given cell in a Matrix | Function to find the farthest cell distance from the given cell ; From cell ( N , M ) ; From Cell ( 1 , 1 ) ; From cell ( N , 1 ) ; From cell ( 1 , M ) ; Finding out maximum ; Prthe answer ; Driver Code | def farthestCellDistance ( N , M , R , C ) : NEW_LINE INDENT d1 = N + M - R - C ; NEW_LINE d2 = R + C - 2 ; NEW_LINE d3 = N - R + C - 1 ; NEW_LINE d4 = M - C + R - 1 ; NEW_LINE maxDistance = max ( d1 , max ( d2 , max ( d3 , d4 ) ) ) ; NEW_LINE print ( maxDistance ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 ; NEW_LINE M = 12 ; NEW_LINE R = 1 ; NEW_LINE C = 6 ; NEW_LINE farthestCellDistance ( N , M , R , C ) ; NEW_LINE DEDENT |
Maximize every array element by repeatedly adding all valid i + a [ i ] th array element | Function to maximize value at every array index by performing given operations ; Traverse the array in reverse ; If the current index is a valid index ; Prthe array ; Driver Code ; Given array ; Size of the array | def maxSum ( arr , N ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT t = i ; NEW_LINE if ( t + arr [ i ] < N ) : NEW_LINE INDENT arr [ i ] += arr [ t + arr [ i ] ] ; NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 7 , 1 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE maxSum ( arr , N ) ; NEW_LINE DEDENT |
Path from the root node to a given node in an N | Python3 program for the above approach ; Function to find the path from root to N ; Stores the number of nodes at ( i + 1 ) - th level ; Stores the number of nodes ; Stores if the current level is even or odd ; If level is odd ; If level is even ; If level with node N is reached ; Push into vector ; Compute prefix sums of count of nodes in each level ; Stores the level in which node N s present ; Store path ; Insert temp into path ; Print path ; Driver Code ; Function Call | from bisect import bisect_left NEW_LINE def PrintPathNodes ( N ) : NEW_LINE INDENT arr = [ ] NEW_LINE arr . append ( 1 ) NEW_LINE k = 1 NEW_LINE flag = True NEW_LINE while ( k < N ) : NEW_LINE INDENT if ( flag == True ) : NEW_LINE INDENT k *= 2 NEW_LINE flag = False NEW_LINE DEDENT else : NEW_LINE INDENT k *= 4 NEW_LINE flag = True NEW_LINE DEDENT if ( k > N ) : NEW_LINE INDENT break NEW_LINE DEDENT arr . append ( k ) NEW_LINE DEDENT lenn = len ( arr ) NEW_LINE prefix = [ 0 ] * ( lenn ) NEW_LINE prefix [ 0 ] = 1 NEW_LINE for i in range ( 1 , lenn ) : NEW_LINE INDENT prefix [ i ] = arr [ i ] + prefix [ i - 1 ] NEW_LINE DEDENT it = bisect_left ( prefix , N ) NEW_LINE ind = it NEW_LINE temp = N NEW_LINE path = [ ] NEW_LINE path . append ( N ) NEW_LINE while ( ind > 1 ) : NEW_LINE INDENT val = temp - prefix [ ind - 1 ] NEW_LINE if ( ind % 2 != 0 ) : NEW_LINE INDENT temp = prefix [ ind - 2 ] + ( val + 1 ) // 2 NEW_LINE DEDENT else : NEW_LINE INDENT temp = prefix [ ind - 2 ] + ( val + 3 ) // 4 NEW_LINE DEDENT ind -= 1 NEW_LINE path . append ( temp ) NEW_LINE DEDENT if ( N != 1 ) : NEW_LINE INDENT path . append ( 1 ) NEW_LINE DEDENT for i in range ( len ( path ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( path [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 14 NEW_LINE PrintPathNodes ( N ) NEW_LINE DEDENT |
Generate an N | Python3 program for the above approach ; Function to construct an array with given conditions ; Traverse the array arr [ ] ; Stores closest power of 2 less than or equal to arr [ i ] ; Stores R into brr [ i ] ; Prarray elements ; Driver Code ; Given array ; Size of the array ; Function Call | from math import log NEW_LINE def constructArray ( arr , N ) : NEW_LINE INDENT brr = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT K = int ( log ( arr [ i ] ) / log ( 2 ) ) NEW_LINE R = pow ( 2 , K ) NEW_LINE brr [ i ] = R NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( brr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 5 , 7 , 3 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE constructArray ( arr , N ) NEW_LINE DEDENT |
Find the element at specified index in a Spiral Matrix | Function to the find element at ( i , j ) index ; Driver Code ; Function Call | def findInGrid ( i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return ( i * i - ( i - 1 ) ) NEW_LINE DEDENT elif ( i > j ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT return i * i - ( j - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( i - 1 ) * ( i - 1 ) + 1 + ( j - 1 ) ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( j % 2 == 0 ) : NEW_LINE INDENT return ( ( j - 1 ) * ( j - 1 ) + 1 + ( i - 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return j * j - ( i - 1 ) NEW_LINE DEDENT DEDENT DEDENT i = 3 NEW_LINE j = 4 NEW_LINE print ( findInGrid ( i , j ) ) NEW_LINE |
Make all array elements equal to 0 by replacing minimum subsequences consisting of equal elements | Function to find minimum count of operations required to convert all array elements to zero by replacing subsequence of equal elements to 0 ; Store distinct elements present in the array ; Traverse the array ; If arr [ i ] is already present in the Set or arr [ i ] is equal to 0 ; Otherwise , increment ans by 1 and insert current element ; Given array ; Size of the given array | def minOpsToTurnArrToZero ( arr , N ) : NEW_LINE INDENT st = dict ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i in st . keys ( ) or arr [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT st [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT print ( len ( st ) ) NEW_LINE DEDENT arr = [ 3 , 7 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE minOpsToTurnArrToZero ( arr , N ) NEW_LINE |
Split an array into equal length subsequences consisting of equal elements only | Python3 program for the above approach ; Function to find the GCD of two numbers a and b ; Function to check if it is possible to split the array into equal length subsequences such that all elements in the subsequence are equal ; Store frequencies of array elements ; Traverse the array ; Update frequency of arr [ i ] ; Store the GCD of frequencies of all array elements ; Traverse the map ; Update GCD ; If the GCD is greater than 1 , print YES otherwise print NO ; Driver Code ; Given array ; Store the size of the array | from collections import defaultdict 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 splitArray ( arr , N ) : NEW_LINE INDENT mp = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT G = 0 NEW_LINE for i in mp : NEW_LINE INDENT G = gcd ( G , mp [ i ] ) NEW_LINE DEDENT if ( G > 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE splitArray ( arr , n ) NEW_LINE DEDENT |
Minimize count of given operations required to be performed to make all array elements equal to 1 | Python 3 program to implement the above approach ; Function to check if all array elements are equal or not ; Traverse the array ; If all array elements are not equal ; Function to find minimum count of operation to make all the array elements equal to 1 ; Stores largest element of the array ; Check if a number is a power of 2 or not ; If Max is a power of 2 and all array elements are equal ; Driver Code | import math NEW_LINE def CheckAllEqual ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def minCntOperations ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE isPower2 = not ( Max and ( Max & ( Max - 1 ) ) ) NEW_LINE if ( isPower2 and CheckAllEqual ( arr , N ) ) : NEW_LINE INDENT return log2 ( Max ) NEW_LINE DEDENT else : NEW_LINE INDENT return math . ceil ( math . log2 ( Max ) ) + 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minCntOperations ( arr , N ) ) NEW_LINE DEDENT |
Largest number not exceeding N that does not contain any of the digits of S | Function to obtain the largest number not exceeding num which does not contain any digits present in S ; Stores digits of S ; Traverse the string S ; Set occurrence as true ; Traverse the string n ; All digits of num are not present in string s ; Largest Digit not present in the string s ; Set all digits from positions in + 1 to n - 1 as LargestDig ; Counting leading zeroes ; Removing leading zeroes ; If the string becomes null ; Return the largest number ; Driver code | def greatestReducedNumber ( num , s ) : NEW_LINE INDENT vis_s = [ False ] * 10 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE vis_s [ ( ord ) ( s [ i ] ) - 48 ] = True NEW_LINE n = len ( num ) NEW_LINE In = - 1 NEW_LINE for i in range ( n ) : NEW_LINE if ( vis_s [ ord ( num [ i ] ) - ord ( '0' ) ] ) : NEW_LINE INDENT In = i NEW_LINE break NEW_LINE DEDENT if ( In == - 1 ) : NEW_LINE return num NEW_LINE for dig in range ( ord ( num [ In ] ) , ord ( '0' ) - 1 , - 1 ) : NEW_LINE if ( vis_s [ dig - ord ( '0' ) ] == False ) : NEW_LINE INDENT num = num [ 0 : In ] + chr ( dig ) + num [ In + 1 : n - In - 1 ] NEW_LINE break NEW_LINE DEDENT LargestDig = '0' NEW_LINE for dig in range ( ord ( '9' ) , ord ( '0' ) - 1 , - 1 ) : NEW_LINE if ( vis_s [ dig - ord ( '0' ) ] == False ) : NEW_LINE INDENT LargestDig = dig NEW_LINE break NEW_LINE DEDENT for i in range ( In + 1 , n ) : NEW_LINE num = num [ 0 : i ] + chr ( LargestDig ) NEW_LINE Count = 0 NEW_LINE for i in range ( n ) : NEW_LINE if ( num [ i ] == '0' ) : NEW_LINE INDENT Count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT num = num [ Count : n ] NEW_LINE if ( int ( len ( num ) ) == 0 ) : NEW_LINE return "0" NEW_LINE return num NEW_LINE DEDENT N = "12345" NEW_LINE S = "23" NEW_LINE print ( greatestReducedNumber ( N , S ) ) NEW_LINE |
Generate an array of minimum sum whose XOR of same | Function to generate an array whose XOR with same - indexed elements of the given array is always a prime ; Traverse the array ; If current array element is 2 ; Print its XOR with 3 ; Otherwise ; Print its XOR with 2 ; Driver Code ; Given array ; Size of the array ; Prints the required array | def minXOR ( Arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( Arr [ i ] == 2 ) : NEW_LINE INDENT print ( Arr [ i ] ^ 3 , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( Arr [ i ] ^ 2 , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Arr = [ 5 , 4 , 7 , 6 ] NEW_LINE N = len ( Arr ) NEW_LINE minXOR ( Arr , N ) NEW_LINE DEDENT |
Find the largest element in an array generated using the given conditions | Function to generate the required array ; Stores the array ; Base case ; Iterate over the indices ; If current index is even ; Otherwise ; Function to find and return the maximum array element ; If n is 0 ; If n is 1 ; Generates the required array ; Return maximum element of Arr ; Driver Code | def findArray ( n ) : NEW_LINE INDENT Arr = [ 0 ] * ( n + 1 ) NEW_LINE Arr [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT Arr [ i ] = Arr [ i // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT Arr [ i ] = ( Arr [ ( i - 1 ) // 2 ] + Arr [ ( i - 1 ) // 2 + 1 ] ) NEW_LINE DEDENT DEDENT return Arr NEW_LINE DEDENT def maxElement ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT Arr = findArray ( n ) NEW_LINE return max ( Arr ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 7 NEW_LINE print ( maxElement ( N ) ) NEW_LINE DEDENT |
Construct a graph using N vertices whose shortest distance between K pair of vertices is 2 | Function to construct the simple and connected graph such that the distance between exactly K pairs of vertices is 2 ; Stores maximum possible count of edges in a graph ; Base case ; Stores edges of a graph ; Connect all vertices of pairs ( i , j ) ; Print first ( ( N - 1 ) + Max - K ) elements of edges [ ] ; Driver code | def constGraphWithCon ( N , K ) : NEW_LINE INDENT Max = ( ( N - 1 ) * ( N - 2 ) ) // 2 NEW_LINE if ( K > Max ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans = [ ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N + 1 ) : NEW_LINE INDENT ans . append ( [ i , j ] ) NEW_LINE DEDENT DEDENT for i in range ( 0 , ( N - 1 ) + Max - K ) : NEW_LINE INDENT print ( ans [ i ] [ 0 ] , ans [ i ] [ 1 ] , sep = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE constGraphWithCon ( N , K ) NEW_LINE DEDENT |
Minimum steps required to visit all corners of an N * M grid | Python3 program to implement the above approach ; Function to find the minimum count of steps required to visit all the corners of the grid ; Stores corner of the grid ; Stores minimum count of steps required to visit the first corner of the grid ; Checking for leftmost upper corner ; Checking for leftmost down corner ; Checking for rightmost upper corner ; Checking for rightmost down corner ; Stores minimum count of steps required to visit remaining three corners of the grid ; Driver Code | import sys NEW_LINE INT_MAX = sys . maxsize ; NEW_LINE def min_steps_required ( n , m , r , c ) : NEW_LINE INDENT i = 0 ; j = 0 ; NEW_LINE corner_steps_req = INT_MAX ; NEW_LINE i = 1 ; NEW_LINE j = 1 ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = n ; NEW_LINE j = 1 ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = 1 ; NEW_LINE j = m ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE i = n ; NEW_LINE j = m ; NEW_LINE corner_steps_req = min ( corner_steps_req , abs ( r - i ) + abs ( j - c ) ) ; NEW_LINE minimum_steps = min ( 2 * ( n - 1 ) + m - 1 , 2 * ( m - 1 ) + n - 1 ) ; NEW_LINE return minimum_steps + corner_steps_req ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE m = 2 ; NEW_LINE r = 1 ; NEW_LINE c = 1 ; NEW_LINE print ( min_steps_required ( n , m , r , c ) ) ; NEW_LINE DEDENT |
Minimum replacements required to have at most K distinct elements in the array | Function to find minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Store the frequency of each distinct element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Store frequency of each distinct element of the array ; Traverse the map ; Stores key of the map ; Insert mp [ i ] into Freq [ ] ; Sort Freq [ ] in descending order ; Stores size of Freq [ ] ; If len is less than or equal to K ; Stores minimum count of array elements required to be replaced such that count of distinct elements is at most K ; Iterate over the range [ K , len ] ; Update cntMin ; Driver code | def min_elements ( arr , N , K ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT Freq = [ ] NEW_LINE for it in mp : NEW_LINE INDENT i = it NEW_LINE Freq . append ( mp [ i ] ) NEW_LINE DEDENT Freq . sort ( ) NEW_LINE Freq . reverse ( ) NEW_LINE Len = len ( Freq ) NEW_LINE if ( Len <= K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cntMin = 0 NEW_LINE for i in range ( K , Len ) : NEW_LINE INDENT cntMin += Freq [ i ] NEW_LINE DEDENT return cntMin NEW_LINE DEDENT arr = [ 5 , 1 , 3 , 2 , 4 , 1 , 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 ; NEW_LINE print ( min_elements ( arr , N , K ) ) NEW_LINE |
Check if sum of the given array can be reduced to 0 by reducing array elements by K | Function to check if the sum can be made 0 or not ; Stores sum of array elements ; Traverse the array ; Driver Code ; Given array arr [ ] | def sumzero ( arr , N , K ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT elif ( sum > 0 ) : NEW_LINE INDENT if ( sum % K == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 1 , - 6 , 2 , 2 ] ; NEW_LINE K = 1 ; NEW_LINE N = len ( arr1 ) ; NEW_LINE sumzero ( arr1 , N , K ) ; NEW_LINE DEDENT |
Counts 1 s that can be obtained in an Array by performing given operations | Function to count total number of 1 s in array by performing given operations ; Stores count of 1 s in the array by performing the operations ; Iterate over the range [ 1 , N ] ; Flip all array elements whose index is multiple of i ; Update arr [ i ] ; Traverse the array ; If current element is 1 ; Update cntOnes ; Driver Code | def cntOnesArrWithGivenOp ( arr , N ) : NEW_LINE INDENT cntOnes = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( i - 1 , N , i ) : NEW_LINE INDENT arr [ j ] = 1 if arr [ j ] == 0 else 0 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cntOnes += 1 NEW_LINE DEDENT DEDENT return cntOnes NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 0 , 0 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntOnesArrWithGivenOp ( arr , N ) ) NEW_LINE DEDENT |
Counts 1 s that can be obtained in an Array by performing given operations | Function to count total number of 1 s in array by performing the given operations ; Stores count of 1 s in the array by performing the operations ; Update cntOnes ; Driver Code | def cntOnesArrWithGivenOp ( arr , N ) : NEW_LINE INDENT cntOnes = 0 ; NEW_LINE cntOnes = int ( N ** ( 1 / 2 ) ) ; NEW_LINE return cntOnes ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 0 , 0 , 0 , 0 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( cntOnesArrWithGivenOp ( arr , N ) ) ; NEW_LINE DEDENT |
Count Knights that can attack a given pawn in an N * N board | Function to count the knights that are attacking the pawn in an M * M board ; Stores count of knights that are attacking the pawn ; Traverse the knights array ; Stores absolute difference of X co - ordinate of i - th knight and pawn ; Stores absolute difference of Y co - ordinate of i - th knight and pawn ; If X is 1 and Y is 2 or X is 2 and Y is 1 ; Update cntKnights ; Driver code ; Stores total count of knights | def cntKnightsAttackPawn ( knights , pawn , M ) : NEW_LINE INDENT cntKnights = 0 ; NEW_LINE for i in range ( M ) : NEW_LINE INDENT X = abs ( knights [ i ] [ 0 ] - pawn [ 0 ] ) ; NEW_LINE Y = abs ( knights [ i ] [ 1 ] - pawn [ 1 ] ) ; NEW_LINE if ( ( X == 1 and Y == 2 ) or ( X == 2 and Y == 1 ) ) : NEW_LINE INDENT cntKnights += 1 ; NEW_LINE DEDENT DEDENT return cntKnights ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT knights = [ [ 0 , 4 ] , [ 4 , 5 ] , [ 1 , 4 ] , [ 3 , 1 ] ] ; NEW_LINE pawn = [ 2 , 3 ] ; NEW_LINE M = len ( knights ) ; NEW_LINE print ( cntKnightsAttackPawn ( knights , pawn , M ) ) ; NEW_LINE DEDENT |
Find the winner of game of removing array elements having GCD equal to 1 | Function to find the winner of the game by removing array elements whose GCD is 1 ; mp [ i ] : Stores count of array elements whose prime factor is i ; Traverse the array ; Calculate the prime factors of arr [ i ] ; If arr [ i ] is divisible by j ; Update mp [ j ] ; Update arr [ i ] ; If arr [ i ] exceeds 1 ; Stores maximum value present in the Map ; Traverse the map ; Update maxCnt ; If n is an even number ; If maxCnt is greater than or equal to n - 1 ; Player 1 wins ; Player 2 wins ; If maxCnt equal to n ; Player 1 wins ; Player 2 wins ; Driver Code | def findWinnerGameRemoveGCD ( arr , n ) : NEW_LINE INDENT mp = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 , int ( arr [ i ] * ( 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( arr [ i ] % j == 0 ) : NEW_LINE INDENT mp [ j ] += 1 ; NEW_LINE while ( arr [ i ] % j == 0 ) : NEW_LINE INDENT arr [ i ] = arr [ i ] // j ; NEW_LINE DEDENT DEDENT DEDENT if ( arr [ i ] > 1 ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 ; NEW_LINE DEDENT DEDENT maxCnt = 0 ; NEW_LINE for i in mp : NEW_LINE INDENT maxCnt = max ( maxCnt , mp [ i ] ) ; NEW_LINE DEDENT if ( n % 2 == 0 ) : NEW_LINE INDENT if ( maxCnt >= n - 1 ) : NEW_LINE INDENT print ( " Player β 1" , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Player β 2" , end = " " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( maxCnt == n ) : NEW_LINE INDENT print ( " Player β 1" , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Player β 2" , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findWinnerGameRemoveGCD ( arr , N ) ; NEW_LINE DEDENT |
Maximum possible sum of K even multiples of 5 in a given range | Function to find the maximum sum of K even multiples of 5 in the range [ L , R ] ; Store the total number of even multiples of 5 in the range [ L , R ] ; Check if K > N ; If true , print - 1 and return ; Otherwise , divide R by 10 ; Store the sum using the formula ; Print the sum ; Driver Code ; Given L , R and K ; Function Call | def maxksum ( L , R , K ) : NEW_LINE INDENT N = ( R // 10 - L // 10 ) + 1 ; NEW_LINE if ( K > N ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE return ; NEW_LINE DEDENT R = R // 10 ; NEW_LINE X = R - K ; NEW_LINE sum = 10 * ( ( R * ( R + 1 ) ) // 2 - ( X * ( X + 1 ) ) // 2 ) ; NEW_LINE print ( sum ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 16 ; R = 60 ; K = 4 ; NEW_LINE maxksum ( L , R , K ) ; NEW_LINE DEDENT |
Minimum swaps of same | Function to count the minimum swaps of same - indexed elements from arrays arr1 and arr2 required to make the sum of both the arrays even ; Store the sum of elements of the array arr1 and arr2 respectively ; Store the array sum of both the arrays ; If both sumArr1 and sumArr2 are even , pr0 and return ; If both sumArr1 and sumArr2 are odd and check for a pair with sum odd sum ; Stores if a pair with odd sum exists or not ; Traverse the array ; If a pair exists with odd sum , set flag = 1 ; Print the answer and return ; For all other cases , pr - 1 ; Driver code ; Function Call | def minimumSwaps ( arr1 , arr2 , n ) : NEW_LINE INDENT sumArr1 = 0 ; sumArr2 = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sumArr1 += arr1 [ i ] ; NEW_LINE sumArr2 += arr2 [ i ] ; NEW_LINE DEDENT if ( sumArr1 % 2 == 0 and sumArr2 % 2 == 0 ) : NEW_LINE INDENT print ( 0 ) ; NEW_LINE return ; NEW_LINE DEDENT if ( sumArr1 % 2 != 0 and sumArr2 % 2 != 0 ) : NEW_LINE INDENT flag = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr1 [ i ] + arr2 [ i ] ) % 2 == 1 ) : NEW_LINE INDENT flag = 1 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT print ( flag ) ; NEW_LINE return ; NEW_LINE DEDENT print ( - 1 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 11 , 14 , 20 , 2 ] ; NEW_LINE arr2 = [ 5 , 9 , 6 , 3 ] ; NEW_LINE N = len ( arr1 ) ; NEW_LINE minimumSwaps ( arr1 , arr2 , N ) ; NEW_LINE DEDENT |
Count of seats booked on each of the given N flights | Function to find the total of the seats booked in each of the flights ; Stores the resultant sequence ; Traverse the array ; Store the first booked flight ; Store the last booked flight ; Store the total number of seats booked in flights [ l , r ] ; Add K to the flight L ; Subtract K from flight number R + 1 ; Find the prefix sum of the array ; Print total number of seats booked in each flight ; Driver Code ; Given list of bookings ; Function Call | def corpFlightBookings ( Bookings , N ) : NEW_LINE INDENT res = [ 0 ] * N NEW_LINE for i in range ( len ( Bookings ) ) : NEW_LINE INDENT l = Bookings [ i ] [ 0 ] NEW_LINE r = Bookings [ i ] [ 1 ] NEW_LINE K = Bookings [ i ] [ 2 ] NEW_LINE res [ l - 1 ] = res [ l - 1 ] + K NEW_LINE if ( r <= len ( res ) - 1 ) : NEW_LINE INDENT res [ r ] = ( - K ) + res [ r ] NEW_LINE DEDENT DEDENT for i in range ( 1 , len ( res ) ) : NEW_LINE INDENT res [ i ] = res [ i ] + res [ i - 1 ] NEW_LINE DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT bookings = [ [ 1 , 3 , 100 ] , [ 2 , 6 , 100 ] , [ 3 , 4 , 100 ] ] NEW_LINE N = 6 NEW_LINE corpFlightBookings ( bookings , N ) NEW_LINE DEDENT |
Bitwise XOR of all odd numbers from a given range | Function to calculate Bitwise XOR of odd numbers in the range [ 1 , N ] ; N & 3 is equivalent to n % 4 ; If n is multiple of 4 ; If n % 4 gives remainder 1 ; If n % 4 gives remainder 2 ; If n % 4 gives remainder 3 ; Function to find the XOR of odd numbers less than or equal to N ; If number is even ; Prthe answer ; If number is odd ; Prthe answer ; Driver Code ; Function Call | def findXOR ( n ) : NEW_LINE INDENT if ( n % 4 == 0 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT elif ( n % 4 == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( n % 4 == 2 ) : NEW_LINE INDENT return n + 1 ; NEW_LINE DEDENT elif ( n % 4 == 3 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT def findOddXOR ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT print ( ( ( findXOR ( n ) ) ^ ( 2 * findXOR ( n // 2 ) ) ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( ( findXOR ( n ) ) ^ ( 2 * findXOR ( ( n - 1 ) // 2 ) ) ) ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 ; NEW_LINE findOddXOR ( N ) ; NEW_LINE DEDENT |
Smallest number greater than or equal to N which is divisible by its non | Function to find the smallest number greater than or equal to N such that it is divisible by its non - zero digits ; Iterate in range [ N , N + 2520 ] ; To check if the current number satisfies the given condition ; Store the number in a temporary variable ; Loop until temp > 0 ; Check only for non zero digits ; Extract the current digit ; If number is divisible by current digit or not ; Otherwise , set possible to 0 ; Break out of the loop ; Divide by 10 ; Driver Code ; Function Call | def findSmallestNumber ( n ) : NEW_LINE INDENT for i in range ( n , n + 2521 ) : NEW_LINE INDENT possible = 1 NEW_LINE temp = i NEW_LINE while ( temp ) : NEW_LINE INDENT if ( temp % 10 != 0 ) : NEW_LINE INDENT digit = temp % 10 NEW_LINE if ( i % digit != 0 ) : NEW_LINE INDENT possible = 0 NEW_LINE break NEW_LINE DEDENT DEDENT temp //= 10 NEW_LINE DEDENT if ( possible == 1 ) : NEW_LINE INDENT print ( i , end = " " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 31 NEW_LINE findSmallestNumber ( N ) NEW_LINE DEDENT |
Print path from a node to root of given Complete Binary Tree | Function to print the path from node to root ; Iterate until root is reached ; Print the value of the current node ; Move to parent of the current node ; Driver Code | def path_to_root ( node ) : NEW_LINE INDENT while ( node >= 1 ) : NEW_LINE INDENT print ( node , end = " β " ) NEW_LINE node //= 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE path_to_root ( N ) NEW_LINE DEDENT |
Smallest number whose sum of digits is N and every digit occurring at most K times | Function to find the smallest number whose sum of digits is N and each digit occurring at most K times ; Maximum sum possible using each digit at most K times ; Append smallest number into the resultant string ; Iterate over the range [ 9 , 1 ] ; If the count of the digit is K , then update count and check for the next digit ; If N is greater than current digit ; Subtract i from N ; Insert i as a digit ; Insert remaining N as a digit ; Increment count ; Reverse the string ; Print the answer ; Driver Code ; Function Call | def findSmallestNumberPossible ( N , K ) : NEW_LINE INDENT if ( N > 45 * K ) : NEW_LINE INDENT print ( " - 1" , endl = " " ) ; NEW_LINE return ; NEW_LINE DEDENT res = " " ; NEW_LINE count = 0 ; NEW_LINE i = 9 ; NEW_LINE while i >= 1 : NEW_LINE INDENT if ( count == K ) : NEW_LINE INDENT i -= 1 ; NEW_LINE count = 0 ; NEW_LINE DEDENT if ( N > i ) : NEW_LINE INDENT N -= i ; NEW_LINE res += chr ( 48 + i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res += chr ( N + 48 ) ; NEW_LINE N = 0 ; NEW_LINE break ; NEW_LINE DEDENT count += 1 ; NEW_LINE DEDENT res = res [ : : - 1 ] NEW_LINE print ( res , end = " " ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 25 ; K = 3 ; NEW_LINE findSmallestNumberPossible ( N , K ) ; NEW_LINE DEDENT |
Minimum sum of values subtracted from array elements to make all array elements equal | Function to find the sum of values removed to make all array elements equal ; Stores the minimum of the array ; Stores required sum ; Traverse the array ; Add the value subtracted from the current element ; Return the total sum ; Driver Code ; Function Call | def minValue ( arr , n ) : NEW_LINE INDENT minimum = min ( arr ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + ( arr [ i ] - minimum ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minValue ( arr , N ) ) NEW_LINE DEDENT |
Smallest positive number made up of non | Function to find smallest positive number made up of non - repeating digits whose sum of its digits is equal to n ; No such number exists ; Stores the required answer ; Store the digit at unit 's place ; Iterate until n > digit ; Push digit at the start of res ; Decrement n by digit ; Decrement digit by 1 ; Push the remaining number as the starting digit ; Print the required number ; Driver Code ; Function Call | def result ( n ) : NEW_LINE INDENT if ( n > 45 ) : NEW_LINE INDENT print ( - 1 , end = " " ) NEW_LINE return NEW_LINE DEDENT res = " " NEW_LINE digit = 9 NEW_LINE while ( n > digit ) : NEW_LINE INDENT res = str ( digit ) + res NEW_LINE n -= digit NEW_LINE digit -= 1 NEW_LINE DEDENT if ( n > 0 ) : NEW_LINE INDENT res = str ( n ) + res NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 19 NEW_LINE result ( N ) NEW_LINE DEDENT |
Count pair of integers having even sum | Python3 program for the above approach ; Function to count even pairs ; Stores count of pairs having even sum ; Stores count of even numbers up to N ; Stores count of odd numbers up to N ; Stores count of even numbers up to M ; Stores count of odd numbers up to M ; Return the count ; Driver Code | import math NEW_LINE def countEvenPairs ( N , M ) : NEW_LINE INDENT count = 0 ; NEW_LINE nEven = int ( math . floor ( N / 2 ) ) ; NEW_LINE nOdd = int ( math . ceil ( N / 2 ) ) ; NEW_LINE mEven = int ( math . floor ( M / 2 ) ) ; NEW_LINE mOdd = int ( math . ceil ( M / 2 ) ) ; NEW_LINE count = nEven * mEven + nOdd * mOdd ; NEW_LINE return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE M = 6 ; NEW_LINE print ( countEvenPairs ( N , M ) ) ; NEW_LINE DEDENT |
Generate an N | Function to generate a string of length N having longest palindromic substring of length K ; Fill first K characters with 'a ; Stores a non - palindromic sequence to be repeated for N - k slots ; PrN - k remaining characters ; Driver Code ; Given N and K | def string_palindrome ( N , K ) : NEW_LINE ' NEW_LINE INDENT for i in range ( K ) : NEW_LINE INDENT print ( " a " , end = " " ) NEW_LINE DEDENT s = " bcd " NEW_LINE for i in range ( N - K ) : NEW_LINE INDENT print ( s [ i % 3 ] , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K = 5 , 3 NEW_LINE string_palindrome ( N , K ) NEW_LINE DEDENT |
Last remaining character after repeated removal of the first character and flipping of characters of a Binary String | Function to find the last removed character from the string ; Stores length of the string ; Base Case : ; If the second last character is '0 ; If the second last character is '1 ; Driver Code | def lastRemovedCharacter ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return ord ( str [ 0 ] ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( str [ n - 2 ] == '0' ) : NEW_LINE INDENT return ( ord ( '1' ) - ord ( str [ n - 1 ] ) + ord ( '0' ) ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT return ord ( str [ n - 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "10010" NEW_LINE print ( chr ( lastRemovedCharacter ( str ) ) ) NEW_LINE DEDENT |
Find the triplet from given Bitwise XOR and Bitwise AND values of all its pairs | Function to find the triplet with given Bitwise XOR and Bitwise AND values of all possible pairs of the triplet ; Stores values of a triplet ; Stores a + b ; Stores a + c ; Stores b + c ; Calculate aSUMb ; Calculate aSUMc ; Calculate bSUMc ; Calculate a ; Calculate b ; Calculate c ; Pra ; Prb ; Prc ; Driver Code | def findNumbers ( aXORb , aANDb , aXORc , aANDc , bXORc , bANDc ) : NEW_LINE INDENT a , b , c = 0 , 0 , 0 ; NEW_LINE aSUMb = 0 ; NEW_LINE aSUMc = 0 ; NEW_LINE bSUMc = 0 ; NEW_LINE aSUMb = aXORb + aANDb * 2 ; NEW_LINE aSUMc = aXORc + aANDc * 2 ; NEW_LINE bSUMc = bXORc + bANDc * 2 ; NEW_LINE a = ( aSUMb - bSUMc + aSUMc ) // 2 ; NEW_LINE b = aSUMb - a ; NEW_LINE c = aSUMc - a ; NEW_LINE print ( " a β = β " , a , end = " " ) ; NEW_LINE print ( " , β b β = β " , b , end = " " ) ; NEW_LINE print ( " , β c β = β " , c , end = " " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT aXORb = 30 ; aANDb = 0 ; aXORc = 20 ; aANDc = 10 ; bXORc = 10 ; bANDc = 20 ; NEW_LINE findNumbers ( aXORb , aANDb , aXORc , aANDc , bXORc , bANDc ) ; NEW_LINE DEDENT |
Find N distinct numbers whose Bitwise XOR is equal to K | Function to find N integers having Bitwise XOR equal to K ; Base Cases ; Assign values to P and Q ; Stores Bitwise XOR of the first ( N - 3 ) elements ; Print the first N - 3 elements ; Calculate Bitwise XOR of first ( N - 3 ) elements ; Driver Code ; Function Call | def findArray ( N , K ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( K , end = " β " ) NEW_LINE return NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT print ( "0" , end = " β " ) NEW_LINE print ( K , end = " β " ) NEW_LINE return NEW_LINE DEDENT P = N - 2 NEW_LINE Q = N - 1 NEW_LINE VAL = 0 NEW_LINE for i in range ( 1 , N - 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE VAL ^= i NEW_LINE DEDENT if ( VAL == K ) : NEW_LINE INDENT print ( P , end = " β " ) NEW_LINE print ( Q , end = " β " ) NEW_LINE print ( P ^ Q , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" , end = " β " ) NEW_LINE print ( P , end = " β " ) NEW_LINE print ( P ^ K ^ VAL , end = " β " ) NEW_LINE DEDENT DEDENT N = 4 NEW_LINE X = 6 NEW_LINE findArray ( N , X ) NEW_LINE |
Flip consecutive set bits starting from LSB of a given number | Function to find the number after converting 1 s from end to 0 s ; Count of 1 s ; AND operation of N and 1 ; Left shift N by count ; Driver Code ; Function Call | def findNumber ( N ) : NEW_LINE INDENT count = 0 NEW_LINE while ( ( N & 1 ) == 1 ) : NEW_LINE INDENT N = N >> 1 NEW_LINE count += 1 NEW_LINE DEDENT return N << count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 39 NEW_LINE print ( findNumber ( N ) ) NEW_LINE DEDENT |
Flip consecutive set bits starting from LSB of a given number | Function to find the number after converting 1 s from end to 0 s ; Return the logical AND of N and ( N + 1 ) ; Driver Code ; Function Call | def findNumber ( N ) : NEW_LINE INDENT return N & ( N + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 39 NEW_LINE print ( findNumber ( N ) ) NEW_LINE DEDENT |
Count of substrings of a string containing another given string as a substring | Function to store all substrings of S ; Stores the substrings of S ; Pick start point in outer loop and lengths of different strings for a given starting point ; Return the array containing substrings of S ; Function to check if a is present in another string ; Check if target is in the str or not ; Function to count the subof S containing T in it as substring ; Store all substrings of S in the array v [ ] ; Store required count of substrings ; Iterate through all the substrings of S ; If T is present in the current substring , then increment the ans ; Print the answer ; Driver code ; Function Call | def subString ( s , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for len in range ( 1 , n - i + 1 ) : NEW_LINE INDENT find = s [ i : i + len ] NEW_LINE v . append ( find ) NEW_LINE DEDENT DEDENT return v NEW_LINE DEDENT def IsPresent ( str , target ) : NEW_LINE INDENT if ( target in str ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def countSubstrings ( S , T ) : NEW_LINE INDENT v = subString ( S , len ( S ) ) NEW_LINE ans = 0 NEW_LINE for it in v : NEW_LINE INDENT if ( IsPresent ( it , T ) != - 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " dabc " NEW_LINE T = " ab " NEW_LINE countSubstrings ( S , T ) NEW_LINE DEDENT |
Minimum flips of odd indexed elements from odd length subarrays to make two given arrays equal | Function to find the minimum flip of subarrays required at alternate index to make binary arrays equals ; Stores count of total operations ; Stores count of consecutive unequal elements ; Loop to run on odd positions ; Incrementing the global counter ; Change count to 0 ; If all last elements are equal ; Loop to run on even positions ; Incrementing the global counter ; Change count to 0 ; Print minimum operations ; Driver Code ; Function Call | def minOperation ( X , Y , n ) : NEW_LINE INDENT C = 0 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT if ( X [ i ] != Y [ i ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( count != 0 ) : NEW_LINE INDENT C += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE DEDENT DEDENT if ( count != 0 ) : NEW_LINE INDENT C += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT if ( X [ i ] != Y [ i ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( count != 0 ) : NEW_LINE INDENT C += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE DEDENT DEDENT if ( count != 0 ) : NEW_LINE INDENT C += 1 ; NEW_LINE DEDENT print ( C ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = [ 1 , 0 , 0 , 0 , 0 , 1 ] ; NEW_LINE Y = [ 1 , 1 , 0 , 1 , 1 , 1 ] ; NEW_LINE N = len ( X ) ; NEW_LINE minOperation ( X , Y , N ) ; NEW_LINE DEDENT |
Minimum subarray reversals required to make given binary array alternating | Function to count minimum subarray reversal operations required to make array alternating ; Stores minimum count of operations required to make array alternating ; Traverse the array ; If arr [ i ] is greater than arr [ i + 1 ] ; Update cntOp ; Driver Code | def minimumcntOperationReq ( arr , N ) : NEW_LINE INDENT cntOp = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT cntOp += 1 NEW_LINE DEDENT DEDENT return ( cntOp + 1 ) // 2 NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 0 , 1 , 0 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimumcntOperationReq ( arr , N ) ) NEW_LINE |
Modify sequence of first N natural numbers to a given array by replacing pairs with their GCD | Function to check if array arr [ ] can be obtained from first N natural numbers or not ; Driver Code ; Function Call | def isSequenceValid ( B , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( ( i + 1 ) % B [ i ] != 0 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT N = 4 NEW_LINE arr = [ 1 , 2 , 3 , 2 ] NEW_LINE isSequenceValid ( arr , N ) NEW_LINE |
Construct an array of first N natural numbers such that every adjacent pair is coprime | Function to construct an arrary with adjacent elements as co - prime numbers ; Iterate over the range [ 1 , N ] ; Print i ; Driver Code | def ConstArrayAdjacentCoprime ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE ConstArrayAdjacentCoprime ( N ) NEW_LINE DEDENT |
Minimum cost to convert one given string to another using swap , insert or delete operations | Function to find the minimum cost to convert a to b ; Stores the frequency of string a and b respectively ; Store the frequencies of characters in a ; Store the frequencies of characters in b ; Minimum cost to convert A to B ; Find the minimum cost ; Print the minimum cost ; Driver Code ; Function Call | def minimumCost ( a , b ) : NEW_LINE INDENT fre1 = [ 0 ] * ( 256 ) NEW_LINE fre2 = [ 0 ] * ( 256 ) NEW_LINE for c in a : NEW_LINE INDENT fre1 [ ord ( c ) ] += 1 NEW_LINE DEDENT for c in b : NEW_LINE INDENT fre2 [ ord ( c ) ] += 1 NEW_LINE DEDENT mincost = 0 NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT mincost += abs ( fre1 [ i ] - fre2 [ i ] ) NEW_LINE DEDENT print ( mincost ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = "1AB + - " NEW_LINE B = " cc " NEW_LINE minimumCost ( A , B ) NEW_LINE DEDENT |
Minimum cost required to move all elements to the same position | Function to find the minimum cost required to place all elements in the same position ; Stores the count of even and odd elements ; Traverse the array arr [ ] ; Count even elements ; Count odd elements ; Print the minimum count ; Driver Code ; Given array ; Function Call | def minCost ( arr ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT print ( min ( even , odd ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE minCost ( arr ) NEW_LINE DEDENT |
Maximize array sum by alternating the signs of adjacent elements | Function to find the maximum sum by alternating the signs of adjacent elements of the array ; Stores count of negative elements in the array ; Stores maximum sum by alternating the signs of adjacent elements ; Stores smallest absolute value of array elements ; Stores sum of absolute value of array elements ; Traverse the array ; If arr [ i ] is a negative number ; Update cntNeg ; Update sum ; Update SmValue ; Update MaxAltSum ; If cntNeg is an odd number ; Update MaxAltSum ; Driver Code | def findMaxSumByAlternatingSign ( arr , N ) : NEW_LINE INDENT cntNeg = 0 NEW_LINE MaxAltSum = 0 NEW_LINE SmValue = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cntNeg += 1 NEW_LINE DEDENT sum += abs ( arr [ i ] ) NEW_LINE SmValue = min ( SmValue , abs ( arr [ i ] ) ) NEW_LINE DEDENT MaxAltSum = sum NEW_LINE if ( cntNeg & 1 ) : NEW_LINE INDENT MaxAltSum -= 2 * SmValue NEW_LINE DEDENT return MaxAltSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , - 2 , - 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaxSumByAlternatingSign ( arr , N ) ) NEW_LINE DEDENT |
Construct array with sum of product of same indexed elements in the given array equal to zero | Function to generate a new array with product of same indexed elements with arr [ ] equal to 0 ; Stores sum of same indexed array elements of arr and new array ; Traverse the array ; If i is an even number ; Insert arr [ i + 1 ] into the new array newArr [ ] ; Insert - arr [ i - 1 ] into the new array newArr [ ] ; Print new array elements ; Driver code | def constructNewArraySumZero ( arr , N ) : NEW_LINE INDENT newArr = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT newArr [ i ] = arr [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT newArr [ i ] = - arr [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( newArr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , - 5 , - 6 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE constructNewArraySumZero ( arr , N ) NEW_LINE |
Generate Bitonic Sequence of length N from integers in a given range | Python3 program for the above approach ; Function to construct bitonic sequence of length N from integers in the range [ L , R ] ; If sequence is not possible ; Store the resultant list ; If size of deque < n ; Add elements from start ; Print the stored in the list ; Driver Code ; Function Call | from collections import deque NEW_LINE def bitonicSequence ( num , lower , upper ) : NEW_LINE INDENT if ( num > ( upper - lower ) * 2 + 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT ans = deque ( ) NEW_LINE for i in range ( min ( upper - lower + 1 , num - 1 ) ) : NEW_LINE INDENT ans . append ( upper - i ) NEW_LINE DEDENT for i in range ( num - len ( ans ) ) : NEW_LINE INDENT ans . appendleft ( upper - i - 1 ) NEW_LINE DEDENT print ( list ( ans ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE L = 3 NEW_LINE R = 10 NEW_LINE bitonicSequence ( N , L , R ) NEW_LINE DEDENT |
Count substrings of same length differing by a single character from two given strings | Function to count the number of substrings of equal length which differ by a single character ; Stores the count of pairs of substrings ; Traverse the string s ; Traverse the string t ; Different character ; Increment the answer ; Count equal substrings from next index ; Increment the count ; Increment q ; Check the condition ; Increment k ; Add q to count ; Decrement z ; Return the final count ; Driver Code ; Function Call | def countSubstrings ( s , t ) : NEW_LINE INDENT answ = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT for j in range ( len ( t ) ) : NEW_LINE INDENT if t [ j ] != s [ i ] : NEW_LINE INDENT answ += 1 NEW_LINE k = 1 NEW_LINE z = - 1 NEW_LINE q = 1 NEW_LINE while ( j + z >= 0 <= i + z and s [ i + z ] == t [ j + z ] ) : NEW_LINE INDENT z -= 1 NEW_LINE answ += 1 NEW_LINE q += 1 NEW_LINE DEDENT while ( len ( s ) > i + k and j + k < len ( t ) and s [ i + k ] == t [ j + k ] ) : NEW_LINE INDENT k += 1 NEW_LINE answ += q NEW_LINE z = - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return answ NEW_LINE DEDENT S = " aba " NEW_LINE T = " baba " NEW_LINE print ( countSubstrings ( S , T ) ) NEW_LINE |
Minimum flips to make all 1 s in right and 0 s in left | Function to find the minimum count of flips required to make all 1 s on the right and all 0 s on the left of the given string ; Stores length of str ; Store count of 0 s in the string ; Traverse the string ; If current character is 0 ; Update zeros ; If count of 0 s in the string is 0 or n ; Store minimum count of flips required to make all 0 s on the left and all 1 s on the right ; Stores count of 1 s on the left of each index ; Stores count of flips required to make all 0 s on the left and all 1 s on the right ; Traverse the string ; If current character is 1 ; Update currOnes ; Update flips ; Update the minimum count of flips ; Driver Code | def minimumCntOfFlipsRequired ( str ) : NEW_LINE INDENT n = len ( str ) ; NEW_LINE zeros = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT zeros += 1 ; NEW_LINE DEDENT DEDENT if ( zeros == 0 or zeros == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT minFlips = 10000001 ; NEW_LINE currOnes = 0 ; NEW_LINE flips = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT currOnes += 1 ; NEW_LINE DEDENT flips = currOnes + ( zeros - ( i + 1 - currOnes ) ) ; NEW_LINE minFlips = min ( minFlips , flips ) ; NEW_LINE DEDENT return minFlips ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "100101" ; NEW_LINE print ( minimumCntOfFlipsRequired ( str ) ) ; NEW_LINE DEDENT |
Maximize length of longest non | Function to find the length of the longest non - decreasing array that can be generated ; Stores the length of the longest non - decreasing array that can be generated from the array ; Stores index of start pointer ; Stores index of end pointer ; Stores previously inserted element into the new array ; Traverse the array ; If A [ start ] is less than or equal to A [ end ] ; If no element inserted into the newly generated array ; Update prev ; Update res ; Update start ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ end ] is greater than A [ start ] ; If no element inserted into the newly generated array ; Update prev ; Update res ; Update end ; If A [ end ] is greater than or equal to prev ; Update res ; Update prev ; Update end ; If A [ start ] is greater than or equal to prev ; Update res ; Update prev ; Update start ; Driver Code ; Function call | def findLongestNonDecreasing ( A , N ) : NEW_LINE INDENT res = 0 ; NEW_LINE start = 0 ; NEW_LINE end = N - 1 ; NEW_LINE prev = - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT if ( A [ start ] <= A [ end ] ) : NEW_LINE INDENT if ( prev == - 1 ) : NEW_LINE INDENT prev = A [ start ] ; NEW_LINE res += 1 NEW_LINE start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( A [ start ] >= prev ) : NEW_LINE INDENT res += 1 NEW_LINE prev = A [ start ] ; NEW_LINE start += 1 NEW_LINE DEDENT elif ( A [ end ] >= prev ) : NEW_LINE INDENT res += 1 NEW_LINE prev = A [ end ] ; NEW_LINE end -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT if ( prev == - 1 ) : NEW_LINE INDENT prev = A [ end ] ; NEW_LINE res += 1 NEW_LINE end -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( A [ end ] >= prev ) : NEW_LINE INDENT res += 1 NEW_LINE prev = A [ end ] ; NEW_LINE end -= 1 NEW_LINE DEDENT elif ( A [ start ] >= prev ) : NEW_LINE INDENT res += 1 NEW_LINE prev = A [ start ] ; NEW_LINE start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 1 , 3 , 5 , 4 , 3 , 6 , 2 , 1 ] NEW_LINE N = len ( A ) NEW_LINE print ( findLongestNonDecreasing ( A , N ) ) ; NEW_LINE DEDENT |
Non | Function to print all pairs whose sum of Bitwise OR and AND is N ; Iterate from i = 0 to N ; Print pairs ( i , N - i ) ; Driver code | def findPairs ( N ) : NEW_LINE INDENT for i in range ( 0 , N + 1 ) : NEW_LINE INDENT print ( " ( " , i , " , " , N - i , " ) , β " , end = " " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE findPairs ( N ) NEW_LINE DEDENT |
Minimum index to split array into subarrays with co | Function to find the GCD of 2 numbers ; Base Case ; Find the GCD recursively ; Function to find the minimum partition index K s . t . product of both subarrays around that partition are co - prime ; Stores the prefix and suffix array product ; Update the prefix array ; Update the suffix array ; Iterate the given array ; Check if prefix [ k ] and suffix [ k + 1 ] are co - prime ; If no index for partition exists , then return - 1 ; Driver Code ; Function call | 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 findPartition ( nums , N ) : NEW_LINE INDENT prefix = [ 0 ] * N NEW_LINE suffix = [ 0 ] * N NEW_LINE prefix [ 0 ] = nums [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT prefix [ i ] = ( prefix [ i - 1 ] * nums [ i ] ) NEW_LINE DEDENT suffix [ N - 1 ] = nums [ N - 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix [ i ] = ( suffix [ i + 1 ] * nums [ i ] ) NEW_LINE DEDENT for k in range ( N - 1 ) : NEW_LINE INDENT if ( GCD ( prefix [ k ] , suffix [ k + 1 ] ) == 1 ) : NEW_LINE INDENT return k NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findPartition ( arr , N ) ) NEW_LINE DEDENT |
Minimum subarray reversals required such that sum of all pairs of adjacent elements is odd | Function to count reversals to separate elements with same parity ; Traverse the given array ; Count size of subarray having integers with same parity only ; Otherwise ; Reversals required is equal to one less than subarray size ; Return the total reversals ; Function to print the array elements ; Function to count the minimum reversals required to make make sum of all adjacent elements odd ; Stores operations required for separating adjacent odd elements ; Stores operations required for separating adjacent even elements ; Maximum of two is the return ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call | def separate ( arr , n , parity ) : NEW_LINE INDENT count = 1 NEW_LINE res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( ( ( arr [ i ] + parity ) & 1 ) and ( ( arr [ i - 1 ] + parity ) & 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( count > 1 ) : NEW_LINE INDENT res += count - 1 NEW_LINE DEDENT count = 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def requiredOps ( arr , N ) : NEW_LINE INDENT res1 = separate ( arr , N , 0 ) NEW_LINE res2 = separate ( arr , N , 1 ) NEW_LINE print ( max ( res1 , res2 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 13 , 2 , 6 , 8 , 3 , 5 , 7 , 10 , 14 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE requiredOps ( arr , N ) NEW_LINE DEDENT |
Count prime pairs whose difference is also a Prime Number | Python3 program to implement the above approach ; Function to find all prime numbers in the range [ 1 , N ] ; isPrime [ i ] : Stores if i is a prime number or not ; Calculate all prime numbers up to Max using Sieve of Eratosthenes ; If P is a prime number ; Set all multiple of P as non - prime ; Update isPrime ; Function to count pairs of prime numbers in the range [ 1 , N ] whose difference is prime ; Function to count pairs of prime numbers whose difference is also a prime number ; isPrime [ i ] : Stores if i is a prime number or not ; Iterate over the range [ 2 , N ] ; If i and i - 2 is a prime number ; Update cntPairs ; Driver Code | from math import sqrt NEW_LINE def SieveOfEratosthenes ( N ) : NEW_LINE INDENT isPrime = [ True for i in range ( N + 1 ) ] NEW_LINE isPrime [ 0 ] = False NEW_LINE isPrime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT for i in range ( p * p , N + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT return isPrime NEW_LINE DEDENT def cntPairsdiffOfPrimeisPrime ( N ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE isPrime = SieveOfEratosthenes ( N ) NEW_LINE for i in range ( 2 , N + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ i ] and isPrime [ i - 2 ] ) : NEW_LINE INDENT cntPairs += 2 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( cntPairsdiffOfPrimeisPrime ( N ) ) NEW_LINE DEDENT |
Length of longest subsequence consisting of distinct adjacent elements | Function that finds the length of longest subsequence having different adjacent elements ; Stores the length of the longest subsequence ; Traverse the array ; If previous and current element are not same ; Increment the count ; Print the maximum length ; Driver Code ; Size of Array ; Function Call | def longestSubsequence ( arr , N ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 1 , 2 , 2 , 5 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE longestSubsequence ( arr , N ) NEW_LINE DEDENT |
Count of substrings having the most frequent character in the string as first character | Python3 program for the above approach ; Function to find all substrings whose first character occurs maximum number of times ; Stores frequency of characters ; Stores character that appears maximum number of times max_char = ; Stores max frequency of character ; Updates frequency of characters ; Update maxfreq ; Character that occures maximum number of times ; Update the maximum frequency character ; Stores all count of substrings ; Traverse over string ; Get the current character ; Update count of substrings ; Return the count of all valid substrings ; Driver Code ; Function Call | import sys NEW_LINE def substringCount ( s ) : NEW_LINE INDENT freq = [ 0 for i in range ( 26 ) ] NEW_LINE DEDENT INDENT maxfreq = - sys . maxsize - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE if ( maxfreq < freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] ) : NEW_LINE INDENT maxfreq = freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( maxfreq == freq [ i ] ) : NEW_LINE INDENT max_char = chr ( i + ord ( ' a ' ) ) NEW_LINE break NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ch = s [ i ] NEW_LINE if ( max_char == ch ) : NEW_LINE INDENT ans += ( len ( s ) - i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcab " NEW_LINE print ( substringCount ( S ) ) NEW_LINE DEDENT |
Minimum sum possible by assigning every increasing / decreasing consecutive pair with values in that order | Function to print the minimum sum of values assigned to each element of the array as per given conditions ; Initialize vectors with value 1 ; Traverse from left to right ; Update if ans [ i ] > ans [ i - 1 ] ; Traverse from right to left ; Update as ans [ i ] > ans [ i + 1 ] if arr [ i ] > arr [ i + 1 ] ; Find the minimum sum ; Print the sum ; Driver Code ; Given array arr [ ] ; Function Call | def minSum ( arr , n ) : NEW_LINE INDENT ans = [ 1 ] * ( n ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT ans [ i ] = max ( ans [ i ] , ans [ i - 1 ] + 1 ) NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT ans [ i ] = max ( ans [ i ] , ans [ i + 1 ] + 1 ) NEW_LINE DEDENT DEDENT s = 0 NEW_LINE for x in ans : NEW_LINE INDENT s = s + x NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minSum ( arr , N ) NEW_LINE DEDENT |
Maximize sum of assigned weights by flipping at most K bits in given Binary String | Function to find maximum sum of weights of binary string after at most K flips ; Stores lengths of substrings of the form 1. . 00. . 1 s ; Stores the index of last 1 encountered in the string ; Stores the index of first 1 encountered ; Stores lengths of all substrings having of 0 s enclosed by 1 s at both ends ; Traverse the string ; If character is 0 ; If character is 1 First Priority ; Second Priority ; Add according to the first priority ; Stores length of the shortest substring of 0 s ; Convert shortest substrings of 0 s to 1 s ; Add according to the first priority ; Add according to the third priority ; If more 0 s can be made into 1 , then check for 0 s at ends ; Update the ans ; If K is non - zero , then flip 0 s at the beginning ; Return the final weights ; Driver Code ; Given string str ; Given K flips ; Function Call | def findMax ( s , n , k ) : NEW_LINE INDENT ans = 0 ; NEW_LINE l = 0 ; NEW_LINE ind = - 1 ; NEW_LINE indf = - 1 ; NEW_LINE ls = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT elif ( s [ i ] == '1' and l > 0 and ans != 0 ) : NEW_LINE INDENT ls . add ( l ) ; NEW_LINE l = 0 ; NEW_LINE DEDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT ind = i ; NEW_LINE l = 0 ; NEW_LINE if ( indf == - 1 ) : NEW_LINE INDENT indf = i ; NEW_LINE DEDENT if ( i > 0 and s [ i - 1 ] == '1' ) : NEW_LINE INDENT ans += 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT DEDENT curr = 0 NEW_LINE while ( k > 0 and len ( ls ) != 0 ) : NEW_LINE INDENT for i in ls : NEW_LINE curr = i NEW_LINE break NEW_LINE if ( k >= curr ) : NEW_LINE INDENT ans += ( 2 * curr + 1 ) ; NEW_LINE k -= curr ; NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( 2 * k ) ; NEW_LINE k = 0 ; NEW_LINE DEDENT ls . remove ( curr ) ; NEW_LINE DEDENT if ( k > 0 ) : NEW_LINE INDENT ans += ( 2 * min ( k , n - ( ind + 1 ) ) - 1 ) ; NEW_LINE k -= min ( k , n - ( ind + 1 ) ) ; NEW_LINE if ( ind > - 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( k > 0 ) : NEW_LINE INDENT ans += ( min ( indf , k ) * 2 - 1 ) ; NEW_LINE if ( indf > - 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "1110000101" ; NEW_LINE N = len ( s ) NEW_LINE K = 3 ; NEW_LINE print ( findMax ( s , N , K ) ) ; NEW_LINE DEDENT |
Minimum removal of consecutive similar characters required to empty a Binary String | Python3 program for the above approach ; Function to find minimum steps to make the empty ; Stores the modified string ; Size of string ; Removing substring of same character from modified string ; Print the minimum steps required ; Driver Code ; Given S ; Function Call | from math import ceil NEW_LINE def minSteps ( S ) : NEW_LINE INDENT new_str = " " NEW_LINE N = len ( S ) NEW_LINE i = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT new_str += S [ i ] NEW_LINE j = i NEW_LINE while ( i < N and S [ i ] == S [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT print ( ceil ( ( len ( new_str ) + 1 ) / 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "0010100" NEW_LINE minSteps ( S ) NEW_LINE DEDENT |
Count pairs with equal Bitwise AND and Bitwise OR value | Function to count pairs in an array whose bitwise AND equal to bitwise OR ; Store count of pairs whose bitwise AND equal to bitwise OR ; Stores frequency of distinct elements of array ; Traverse the array ; Increment the frequency of arr [ i ] ; Traverse map ; Driver Code | def countPairs ( arr , N ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE mp = { } NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT for freq in mp : NEW_LINE INDENT cntPairs += int ( ( mp [ freq ] * ( mp [ freq ] - 1 ) ) / 2 ) NEW_LINE DEDENT return cntPairs NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT |
Minimum increments required to make given matrix palindromic | Function to evaluate minimum number of operation required to convert the matrix to a palindrome matrix ; Variable to store number of operations required ; Iterate over the first quadrant of the matrix ; Store positions of all four values from four quadrants ; Store the values having unique indexes ; Largest value in the values vector ; Evaluate minimum increments required to make all vector elements equal ; Print the answer ; Driver Code ; Function Call | def palindromeMatrix ( N , M , arr ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( ( N + 1 ) // 2 ) : NEW_LINE INDENT for j in range ( ( M + 1 ) // 2 ) : NEW_LINE INDENT s = { } NEW_LINE s [ ( i , j ) ] = 1 NEW_LINE s [ ( i , M - j - 1 ) ] = 1 NEW_LINE s [ ( N - i - 1 , j ) ] = 1 NEW_LINE s [ ( N - i - 1 , M - j - 1 ) ] = 1 NEW_LINE values = [ ] NEW_LINE for p , q in s : NEW_LINE INDENT values . append ( arr [ p ] [ q ] ) NEW_LINE DEDENT maxm = max ( values ) NEW_LINE for k in range ( len ( values ) ) : NEW_LINE INDENT ans += maxm - values [ k ] NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 3 , 3 NEW_LINE arr = [ [ 1 , 2 , 1 ] , [ 3 , 4 , 1 ] , [ 1 , 2 , 1 ] ] NEW_LINE palindromeMatrix ( N , M , arr ) NEW_LINE DEDENT |
Minimum division by 10 and multiplication by 2 required to reduce given number to 1 | Function to find the minimum number operations required to reduce N to 1 ; Stores count of powers of 2 and 5 ; Calculating the primefactors 2 ; Calculating the primefactors 5 ; If n is 1 and cnt2 <= cnt5 ; Return the minimum operations ; Otherwise , n can 't be reduced ; Driver Code ; Given Number N ; Function Call | def minimumMoves ( n ) : NEW_LINE INDENT cnt2 = 0 NEW_LINE cnt5 = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n //= 2 NEW_LINE cnt2 += 1 NEW_LINE DEDENT while ( n % 5 == 0 ) : NEW_LINE INDENT n //= 5 NEW_LINE cnt5 += 1 NEW_LINE DEDENT if ( n == 1 and cnt2 <= cnt5 ) : NEW_LINE INDENT return 2 * cnt5 - cnt2 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( minimumMoves ( N ) ) NEW_LINE DEDENT |
Check if permutation of first N natural numbers exists having Bitwise AND of adjacent elements non | Function to check if a permutation of first N natural numbers exist with Bitwise AND of adjacent elements not equal to 0 ; If n is a power of 2 ; Driver Code | def check ( n ) : NEW_LINE INDENT if ( ( n & n - 1 ) != 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE check ( n ) NEW_LINE DEDENT |
Minimize adding odd and subtracting even numbers to make all array elements equal to K | Function to find the minimum operations required to make array elements equal to K ; Stores minimum count of operations ; Traverse the given array ; If K is greater than arr [ i ] ; If ( K - arr [ i ] ) is even ; Update cntOpe ; Update cntOpe ; If K is less than arr [ i ] ; If ( arr [ i ] - K ) is even ; Update cntOpe ; Update cntOpe ; Driver Code | def MinOperation ( arr , N , K ) : NEW_LINE INDENT cntOpe = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K > arr [ i ] ) : NEW_LINE INDENT if ( ( K - arr [ i ] ) % 2 == 0 ) : NEW_LINE INDENT cntOpe += 2 NEW_LINE DEDENT else : NEW_LINE INDENT cntOpe += 1 NEW_LINE DEDENT DEDENT elif ( K < arr [ i ] ) : NEW_LINE INDENT if ( ( K - arr [ i ] ) % 2 == 0 ) : NEW_LINE INDENT cntOpe += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntOpe += 2 NEW_LINE DEDENT DEDENT DEDENT return cntOpe NEW_LINE DEDENT arr = [ 8 , 7 , 2 , 1 , 3 ] NEW_LINE K = 5 NEW_LINE N = len ( arr ) NEW_LINE print ( MinOperation ( arr , N , K ) ) NEW_LINE |
Rearrange array to make Bitwise XOR of similar indexed elements of two arrays is same | Function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store frequency of elements ; Stores xor value ; Taking xor of all the values of both arrays ; Store frequency of B [ ] ; Find the array B [ ] after rearrangement ; If the updated value is present then decrement its frequency ; Otherwise return empty vector ; Utility function to rearrange the array B [ ] such that A [ i ] ^ B [ i ] is same for each element ; Store rearranged array B ; If rearrangement possible ; Otherwise return - 1 ; Driver Code ; Given vector A ; Given vector B ; Size of the vector ; Function Call | def rearrangeArray ( A , B , N ) : NEW_LINE INDENT m = { } NEW_LINE xor_value = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT xor_value ^= A [ i ] NEW_LINE xor_value ^= B [ i ] NEW_LINE if B [ i ] in m : NEW_LINE m [ B [ i ] ] = m [ B [ i ] ] + 1 NEW_LINE else : NEW_LINE m [ B [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT B [ i ] = A [ i ] ^ xor_value NEW_LINE if B [ i ] in m : NEW_LINE m [ B [ i ] ] = m [ B [ i ] ] - 1 NEW_LINE else : NEW_LINE X = [ ] NEW_LINE return X NEW_LINE DEDENT return B NEW_LINE DEDENT def rearrangeArrayUtil ( A , B , N ) : NEW_LINE INDENT ans = rearrangeArray ( A , B , N ) NEW_LINE if ( len ( ans ) > 0 ) : NEW_LINE INDENT for x in ans : NEW_LINE INDENT print ( x , end = ' β ' ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 13 , 21 , 33 , 49 , 53 ] NEW_LINE B = [ 54 , 50 , 34 , 22 , 14 ] NEW_LINE N = len ( A ) NEW_LINE rearrangeArrayUtil ( A , B , N ) NEW_LINE DEDENT |
Count sequences of given length having non | Function to find the Binomial Coefficient C ( n , r ) ; Stores the value C ( n , r ) ; Update C ( n , r ) = C ( n , n - r ) ; Find C ( n , r ) iteratively ; Return the final value ; Function to find number of sequence whose prefix sum at each index is always non - negative ; Find n ; Value of C ( 2 n , n ) ; Catalan number ; Print the answer ; Driver Code ; Given M and X ; Function Call | def binCoff ( n , r ) : NEW_LINE INDENT val = 1 NEW_LINE if ( r > ( n - r ) ) : NEW_LINE INDENT r = ( n - r ) NEW_LINE DEDENT for i in range ( 0 , r ) : NEW_LINE INDENT val *= ( n - i ) NEW_LINE val //= ( i + 1 ) NEW_LINE DEDENT return val NEW_LINE DEDENT def findWays ( M ) : NEW_LINE INDENT n = M // 2 NEW_LINE a = binCoff ( 2 * n , n ) NEW_LINE b = a // ( n + 1 ) NEW_LINE print ( b ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 4 NEW_LINE X = 5 NEW_LINE findWays ( M ) NEW_LINE DEDENT |
XOR of array elements whose modular inverse with a given number exists | Function to return the gcd of a & b ; Base Case ; Recursively calculate GCD ; Function to print the Bitwise XOR of elements of arr [ ] if gcd ( arr [ i ] , M ) is 1 ; Initialize xor ; Traversing the array ; GCD of M and arr [ i ] ; If GCD is 1 , update xor ; Print xor ; Drive Code ; Given array arr [ ] ; Given number M ; Size of the array ; Function Call | 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 countInverse ( arr , N , M ) : NEW_LINE INDENT XOR = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT gcdOfMandelement = gcd ( M , arr [ i ] ) NEW_LINE if ( gcdOfMandelement == 1 ) : NEW_LINE INDENT XOR = XOR ^ arr [ i ] NEW_LINE DEDENT DEDENT print ( XOR ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE M = 4 NEW_LINE N = len ( arr ) NEW_LINE countInverse ( arr , N , M ) NEW_LINE DEDENT |
Count positions in a chessboard that can be visited by the Queen which are not visited by the King | Function to print the number of cells only visited by the queen ; Find all the moves ; Find all moves for x + 1 , y + 1 ; Find all moves for x - 1 , y - 1 ; Find all moves for x - 1 , y + 1 ; Find all moves for x + 1 , y - 1 ; Find all squares visited by King x + 1 , in same row ; x - 1 , in same row ; y + 1 , in same column ; y - 1 , in same column ; Return answer ; Driver Code ; Dimension of Board ; Position of Cell ; Function Call | def Moves_Calculator ( x , y , row , col ) : NEW_LINE INDENT total_moves = 0 NEW_LINE if ( row - x ) > 0 and ( col - y ) > 0 : NEW_LINE INDENT total_moves += min ( ( row - x ) , ( col - y ) ) NEW_LINE DEDENT if ( y - 1 ) > 0 and ( x - 1 ) > 0 : NEW_LINE INDENT total_moves += min ( ( y - 1 ) , ( x - 1 ) ) NEW_LINE DEDENT if ( x - 1 ) > 0 and ( col - y ) > 0 : NEW_LINE INDENT total_moves += min ( ( x - 1 ) , ( col - y ) ) NEW_LINE DEDENT if ( row - x ) > 0 and ( y - 1 ) > 0 : NEW_LINE INDENT total_moves += min ( ( row - x ) , ( y - 1 ) ) NEW_LINE DEDENT total_moves += ( row - 1 ) + ( col - 1 ) NEW_LINE king_moves = 0 NEW_LINE if x + 1 <= m : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if x - 1 > 0 : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if y + 1 <= n : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if y - 1 > 0 : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if x + 1 <= m and y + 1 <= n : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if x + 1 <= m and y - 1 > 0 : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if x - 1 > 0 and y - 1 > 0 : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT if x - 1 > 0 and y + 1 <= n : NEW_LINE INDENT king_moves += 1 NEW_LINE DEDENT return total_moves - king_moves NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n , m = 8 , 8 NEW_LINE x , y = 1 , 1 NEW_LINE print ( Moves_Calculator ( x , y , m , n ) ) NEW_LINE DEDENT |
Nearest smaller number to N having multiplicative inverse under modulo N equal to that number | Function to find the nearest smaller number satisfying the condition ; Driver Code | def clstNum ( N ) : NEW_LINE INDENT return ( N - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 NEW_LINE print ( clstNum ( N ) ) NEW_LINE DEDENT |
Count array elements having modular inverse under given prime number P equal to itself | Function to get the count of elements that satisfy the given condition . ; Stores count of elements that satisfy the condition ; Traverse the given array . ; If square of current element is equal to 1 ; Driver Code | def equvInverse ( arr , N , P ) : NEW_LINE INDENT cntElem = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( ( arr [ i ] * arr [ i ] ) % P == 1 ) : NEW_LINE INDENT cntElem = cntElem + 1 NEW_LINE DEDENT DEDENT return cntElem NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 6 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE P = 7 NEW_LINE print ( equvInverse ( arr , N , P ) ) NEW_LINE DEDENT |
Count ways to split array into K non | Function to get the value of pow ( K , M ) ; Stores value of pow ( K , M ) ; Calculate value of pow ( K , N ) ; If N is odd , update res ; Update M to M / 2 ; Update K ; Function to print total ways to split the array that satisfies the given condition ; Stores total ways that satisfies the given condition ; Stores count of distinct elements in the given arr ; Store distinct elements of the given array ; Traverse the given array ; Insert current element into set st . ; Update M ; Update cntways ; Driver Code | def power ( K , M ) : NEW_LINE INDENT res = 1 NEW_LINE while ( M > 0 ) : NEW_LINE INDENT if ( ( M & 1 ) == 1 ) : NEW_LINE INDENT res = ( res * K ) NEW_LINE DEDENT M = M >> 1 NEW_LINE K = ( K * K ) NEW_LINE DEDENT return res NEW_LINE DEDENT def cntWays ( arr , N , K ) : NEW_LINE INDENT cntways = 0 NEW_LINE M = 0 NEW_LINE st = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT st . add ( arr [ i ] ) NEW_LINE DEDENT M = len ( st ) NEW_LINE cntways = power ( K , M ) NEW_LINE return cntways NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( cntWays ( arr , N , K ) ) NEW_LINE DEDENT |
Minimize product of first N | Python3 program for the above approach ; Function to find the minimum product of 1 to N - 1 after performing the given operations ; Initialize ans with 1 ; Multiply ans with N - 2 ( ( N - 4 ) / 2 ) times ; Multiply ans with N - 1 and N - 2 once ; Print ans ; Driver Code ; Given number N ; Function call | mod = 1e9 + 7 NEW_LINE def minProduct ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , ( n - 4 ) // 2 + 1 ) : NEW_LINE INDENT ans = ( ans * ( n - 2 ) ) % mod NEW_LINE DEDENT ans = ( ans * ( n - 2 ) * ( n - 1 ) ) % mod NEW_LINE print ( int ( ans ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE minProduct ( N ) NEW_LINE DEDENT |
Bitwise XOR of all unordered pairs from a given array | Function to get bitwise XOR of all possible pairs of the given array ; Stores bitwise XOR of all possible pairs ; Generate all possible pairs and calculate bitwise XOR of all possible pairs ; Calculate bitwise XOR of each pair ; Driver code | def TotalXorPair ( arr , N ) : NEW_LINE INDENT totalXOR = 0 ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT totalXOR ^= arr [ i ] ^ arr [ j ] ; NEW_LINE DEDENT DEDENT return totalXOR ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( TotalXorPair ( arr , N ) ) ; NEW_LINE DEDENT |
Count permutations of all integers upto N that can form an acyclic graph based on given conditions | Find the count of possible graphs ; Driver code | def possibleAcyclicGraph ( N ) : NEW_LINE INDENT print ( pow ( 2 , N - 1 ) ) NEW_LINE return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE possibleAcyclicGraph ( N ) NEW_LINE DEDENT |
Minimize positive product of two given numbers by at most N decrements | Function to minimize the product of two numbers ; Reducing X , N times , minimizes the product ; Reduce X to 1 and reduce remaining N from Y ; Reducing Y , N times , minimizes the product ; Reduce Y to 1 and reduce remaining N from X ; Driver Code | def minProd ( X , Y , N ) : NEW_LINE INDENT if ( X <= Y ) : NEW_LINE INDENT if ( N < X ) : NEW_LINE INDENT return ( X - N ) * Y NEW_LINE DEDENT else : NEW_LINE INDENT return max ( Y - ( N - X + 1 ) , 1 ) NEW_LINE DEDENT DEDENT if ( Y >= N ) : NEW_LINE INDENT return ( Y - N ) * X NEW_LINE DEDENT return max ( X - ( N - Y + 1 ) , 1 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 47 NEW_LINE Y = 42 NEW_LINE N = 167 NEW_LINE print ( minProd ( X , Y , N ) ) NEW_LINE DEDENT |
Count pairs from an array having product of their sum and difference equal to 1 | Function to count the desired number of pairs ; Initialize oneCount ; Initialize the desiredPair ; Traverse the given array ; If 1 is encountered ; If 0 is encountered ; Update count of pairs ; Return the final count ; Driver Code ; Given array arr [ ] ; Function call | def countPairs ( arr , n ) : NEW_LINE INDENT oneCount = 0 NEW_LINE desiredPair = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT oneCount += 1 NEW_LINE DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT desiredPair += oneCount NEW_LINE DEDENT DEDENT return desiredPair NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT |
Smallest missing non | Function to prthe smallest missing non - negative integer up to every array indices ; Stores the smallest missing non - negative integers between start index to current index ; Store the boolean value to check smNonNeg present between start index to each index of the array ; Traverse the array ; Since output always lies in the range [ 0 , N - 1 ] ; Check if smNonNeg is present between start index and current index or not ; Print smallest missing non - negative integer ; Driver Code | def smlstNonNeg ( arr , N ) : NEW_LINE INDENT smNonNeg = 0 NEW_LINE hash = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ i ] < N ) : NEW_LINE INDENT hash [ arr [ i ] ] = True NEW_LINE DEDENT while ( hash [ smNonNeg ] ) : NEW_LINE INDENT smNonNeg += 1 NEW_LINE DEDENT print ( smNonNeg , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 2 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE smlstNonNeg ( arr , N ) NEW_LINE DEDENT |
Split array into two subsequences having minimum count of pairs with sum equal to X | Function to split the array into two subsequences ; Stores the two subsequences ; Flag to set / reset to split arrays elements alternately into two arrays ; Traverse the given array ; If 2 * arr [ i ] is less than X ; Push element into the first array ; If 2 * arr [ i ] is greater than X ; Push element into the second array ; If 2 * arr [ i ] is equal to X ; Alternatively place the elements into the two arrays ; Print both the arrays ; Driver Code ; Size of the array ; Function Call | def solve ( arr , N , X ) : NEW_LINE INDENT A = [ ] NEW_LINE B = [ ] NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ( 2 * arr [ i ] ) < X ) : NEW_LINE INDENT A . append ( arr [ i ] ) NEW_LINE DEDENT elif ( ( 2 * arr [ i ] ) > X ) : NEW_LINE INDENT B . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( c % 2 == 0 ) : NEW_LINE INDENT A . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT B . append ( arr [ i ] ) NEW_LINE DEDENT c += 1 NEW_LINE DEDENT DEDENT print ( " The β First β Array β is β - β " , end = " β " ) NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE print ( " The β Second β Array β is β - β " , end = " β " ) NEW_LINE for i in range ( len ( B ) ) : NEW_LINE INDENT print ( B [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 4 , 3 , 6 , 2 , 4 , 3 ] NEW_LINE X = 7 NEW_LINE N = len ( arr ) NEW_LINE solve ( arr , N , X ) NEW_LINE DEDENT |
Split array into minimum number of subsets having maximum pair sum at most K | Function to get the minimum count of subsets that satisfy the given condition ; Store the minimum count of subsets that satisfy the given condition ; Stores start index of the sorted array . ; Stores end index of the sorted array ; Sort the given array ; Traverse the array ; If only two elements of sorted array left ; If only one elements left in the array ; Driver Code | def cntMinSub ( arr , N , K ) : NEW_LINE INDENT res = 0 NEW_LINE start = 0 NEW_LINE end = N - 1 NEW_LINE arr = sorted ( arr ) NEW_LINE while ( end - start > 1 ) : NEW_LINE INDENT if ( arr [ start ] + arr [ end ] <= K ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT if ( end - start == 1 ) : NEW_LINE INDENT if ( arr [ start ] + arr [ end ] <= K ) : NEW_LINE INDENT res += 1 NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT res += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT if ( start == end ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 6 , 8 , 10 , 20 , 25 ] NEW_LINE N = len ( arr ) NEW_LINE K = 26 NEW_LINE print ( cntMinSub ( arr , N , K ) ) NEW_LINE DEDENT |
Count possible values of K such that X | Function to count integers K satisfying given equation ; Calculate the absoluter difference between a and b ; Iterate till sqrt of the difference ; Return the count ; Driver Code | def condition ( a , b ) : NEW_LINE INDENT d = abs ( a - b ) NEW_LINE count = 0 NEW_LINE for i in range ( 1 , d + 1 ) : NEW_LINE INDENT if i * i > d : NEW_LINE INDENT break NEW_LINE DEDENT if ( d % i == 0 ) : NEW_LINE INDENT if ( d // i == i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 2 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 2 NEW_LINE y = 6 NEW_LINE print ( condition ( x , y ) ) NEW_LINE DEDENT |
Count pairs in an array whose product is composite number | Function to check if a number is prime or not ; Check if N is multiple of i or not . ; If N is multiple of i . ; Function to get the count of pairs whose product is a composite number . ; Stores the count of pairs whose product is a composite number ; Generate all possible pairs ; Stores the product of element of current pair ; If prod is a composite number ; Driver Code | def isComposite ( N ) : NEW_LINE INDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def compositePair ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT prod = arr [ i ] * arr [ j ] NEW_LINE if ( isComposite ( prod ) ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( compositePair ( arr , N ) ) NEW_LINE DEDENT |
Count N | Python3 program for the above approach ; Function for calculate ( x ^ y ) % mod in O ( log y ) ; Base Condition ; Transition state of power Function ; Function for counting total numbers that can be formed such that digits X , Y are present in each number ; Calculate the given expression ; Return the final answer ; Driver Code | mod = 1e9 + 7 NEW_LINE def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT p = power ( x , y // 2 ) % mod NEW_LINE p = ( p * p ) % mod NEW_LINE if ( y & 1 ) : NEW_LINE INDENT p = ( x * p ) % mod NEW_LINE DEDENT return p NEW_LINE DEDENT def TotalNumber ( N ) : NEW_LINE INDENT ans = ( power ( 10 , N ) - 2 * power ( 9 , N ) + power ( 8 , N ) + 2 * mod ) % mod NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE X = 3 NEW_LINE Y = 4 NEW_LINE print ( TotalNumber ( N ) ) NEW_LINE DEDENT |
Array obtained by repeatedly reversing array after every insertion from given array | Python3 program of the above approach ; Function to generate the array by inserting array elements one by one followed by reversing the array ; Doubly ended Queue ; Iterate over the array ; Push array elements alternately to the front and back ; If size of list is odd ; Reverse the list ; Print the elements of the array ; Driver Code | from collections import deque NEW_LINE def generateArray ( arr , n ) : NEW_LINE INDENT ans = deque ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i & 1 != 0 ) : NEW_LINE INDENT ans . appendleft ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT if ( n & 1 != 0 ) : NEW_LINE INDENT ans . reverse ( ) NEW_LINE DEDENT for x in ans : NEW_LINE INDENT print ( x , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT n = 4 NEW_LINE arr = [ 1 , 2 , 3 , 4 ] NEW_LINE generateArray ( arr , n ) NEW_LINE |
Find the greater number closest to N having at most one non | Function to get closest greater number with at most non zero digit ; Stores the closest greater number with at most one non - zero digit ; Stores length of str ; Append 10 to the end of resultant String ; Append n - 1 times '0' to the end of resultant String ; Driver Code | def closestgtNum ( str ) : NEW_LINE INDENT res = " " ; NEW_LINE n = len ( str ) ; NEW_LINE if ( str [ 0 ] < '9' ) : NEW_LINE INDENT res += ( chr ) ( ord ( str [ 0 ] ) + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res += ( chr ) ( '1' ) ; NEW_LINE res += ( chr ) ( '0' ) ; NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT res += ( '0' ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "120" ; NEW_LINE print ( closestgtNum ( str ) ) ; NEW_LINE DEDENT |
Count maximum non | Function to count maximum number of non - overlapping subarrays with sum equals to the target ; Stores the final count ; Next subarray should start from index >= availIdx ; Tracks the prefix sum ; Map to store the prefix sum for respective indices ; Check if cur_sum - target is present in the array or not ; Update the index of current prefix sum ; Return the count of subarrays ; Driver Code ; Given array arr [ ] ; Given sum target ; Function call | def maximumSubarrays ( arr , N , target ) : NEW_LINE INDENT ans = 0 NEW_LINE availIdx = - 1 NEW_LINE cur_sum = 0 NEW_LINE mp = { } NEW_LINE mp [ 0 ] = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_sum += arr [ i ] NEW_LINE if ( ( cur_sum - target ) in mp and mp [ cur_sum - target ] >= availIdx ) : NEW_LINE INDENT ans += 1 NEW_LINE availIdx = i NEW_LINE DEDENT mp [ cur_sum ] = i NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 1 , 4 , 3 , 6 , 4 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE target = 6 NEW_LINE print ( maximumSubarrays ( arr , N , target ) ) NEW_LINE DEDENT |
Maximize array sum by replacing equal adjacent pairs by their sum and X respectively | Function to calculate x ^ y ; Base Case ; Find the value in temp ; If y is even ; Function that find the maximum possible sum of the array ; Print the result using the formula ; Driver Code ; Function call | def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = power ( x , y // 2 ) NEW_LINE if ( y % 2 == 0 ) : NEW_LINE INDENT return temp * temp NEW_LINE DEDENT else : NEW_LINE INDENT return x * temp * temp NEW_LINE DEDENT DEDENT def maximumPossibleSum ( N , X ) : NEW_LINE INDENT print ( X * ( power ( 2 , N ) - 1 ) ) NEW_LINE DEDENT N = 3 NEW_LINE X = 5 NEW_LINE maximumPossibleSum ( N , X ) NEW_LINE |
Count ways to generate pairs having Bitwise XOR and Bitwise AND equal to X and Y respectively | Function to return the count of possible pairs of A and B whose Bitwise XOR is X and Y respectively ; Stores the count of pairs ; Iterate till any bit are set ; Extract i - th bit of X and Y ; Divide X and Y by 2 ; If Xi = 1 and Yi = 2 , multiply counter by 2 ; Increase required count ; If Xi = 1 and Yi = 1 ; No answer exists ; Return the final count ; Given X and Y ; Function call | def countOfPairs ( x , y ) : NEW_LINE INDENT counter = 1 NEW_LINE while ( x or y ) : NEW_LINE INDENT bit1 = x % 2 NEW_LINE bit2 = y % 2 NEW_LINE x >>= 1 NEW_LINE y >>= 1 NEW_LINE if ( bit1 == 1 and bit2 == 0 ) : NEW_LINE INDENT counter *= 2 NEW_LINE continue NEW_LINE DEDENT if ( bit1 & bit2 ) : NEW_LINE INDENT counter = 0 NEW_LINE break NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT X = 2 NEW_LINE Y = 5 NEW_LINE print ( countOfPairs ( X , Y ) ) NEW_LINE |
Make all array elements equal by repeated subtraction of absolute difference of pairs from their maximum | Function to return gcd of a and b ; Base Case ; Recursive call ; Function to find gcd of array ; Initialise the result ; Traverse the array arr [ ] ; Update result as gcd of the result and arr [ i ] ; Return the resultant GCD ; Given array arr [ ] ; Function call | 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 findGCD ( arr , N ) : NEW_LINE INDENT result = 0 NEW_LINE for element in arr : NEW_LINE INDENT result = gcd ( result , element ) NEW_LINE if ( result == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findGCD ( arr , N ) ) NEW_LINE |
Check if any permutation of array contains sum of every adjacent pair not divisible by 3 | Function to checks if any permutation of the array exists whose sum of adjacent pairs is not divisible by 3 ; Count remainder 0 ; Count remainder 1 ; Count remainder 2 ; Condition for valid arrangements ; Given array arr [ ] ; Function call | def factorsOf3 ( arr , N ) : NEW_LINE INDENT a = 0 NEW_LINE b = 0 NEW_LINE c = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 3 == 0 ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT elif ( arr [ i ] % 3 == 1 ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT elif ( arr [ i ] % 3 == 2 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( a >= 1 and a <= b + c + 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT elif ( a == 0 and b == 0 and c > 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT elif ( a == 0 and c == 0 and b > 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE factorsOf3 ( arr , N ) NEW_LINE |
Check if a number is a perfect square having all its digits as a perfect square | Python3 program for the above approach ; Function to check if digits of N is a perfect square or not ; Iterate over the digits ; Extract the digit ; Check if digit is a perfect square or not ; Divide N by 10 ; Return true ; Function to check if N is a perfect square or not ; If floor and ceil of n is not same ; Function to check if N satisfies the required conditions or not ; If both the conditions are satisfied ; Driver Code ; Function call | import math NEW_LINE def check_digits ( N ) : NEW_LINE INDENT while ( N > 0 ) : NEW_LINE INDENT n = N % 10 NEW_LINE if ( ( n != 0 ) and ( n != 1 ) and ( n != 4 ) and ( n != 9 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT N = N // 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def is_perfect ( N ) : NEW_LINE INDENT n = math . sqrt ( N ) NEW_LINE if ( math . floor ( n ) != math . ceil ( n ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def isFullSquare ( N ) : NEW_LINE INDENT if ( is_perfect ( N ) and check_digits ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT N = 144 NEW_LINE isFullSquare ( N ) NEW_LINE |
Count substrings with different first and last characters | Function to count the substrings having different first & last character ; Stores frequency of each char ; Loop to store frequency of the characters in a Map ; To store final result ; Traversal of string ; Store answer for every iteration ; Map traversal ; Compare current char ; Print the final count ; Given string ; Length of the string ; Function Call | def countSubstring ( s , n ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = - 1 NEW_LINE DEDENT for value in m : NEW_LINE INDENT if ( value == s [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT cnt += m [ value ] NEW_LINE DEDENT DEDENT ans += cnt NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = " abcab " NEW_LINE N = 5 NEW_LINE countSubstring ( S , N ) NEW_LINE |
Maximize count of empty water bottles from N filled bottles | Function to find the maximum bottles that can be emptied ; Iterate until a is non - zero ; Add the number of bottles that are emptied ; Update a after exchanging empty bottles ; Stores the number of bottles left after the exchange ; Return the answer ; Driver Code ; Function call | def maxBottles ( n , e ) : NEW_LINE INDENT s = 0 NEW_LINE b = 0 NEW_LINE a = n NEW_LINE while ( a != 0 ) : NEW_LINE INDENT s = s + a NEW_LINE a = ( a + b ) // e NEW_LINE b = n - ( a * e ) NEW_LINE n = a + b NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 NEW_LINE e = 3 NEW_LINE s = maxBottles ( n , e ) NEW_LINE print ( s ) NEW_LINE DEDENT |
Count all N digit numbers whose digits are multiple of X | Function to calculate x ^ n using binary - exponentiation ; Stores the resultant power ; Stores the value of x ^ ( n / 2 ) ; Function to count aN - digit numbers whose digits are multiples of x ; Count adigits which are multiples of x ; Check if current number is a multiple of X ; Increase count of multiples ; Check if it 's a 1 digit number ; Count the total numbers ; Return the total numbers ; Driver Code ; Given N and X ; Function call | def power ( x , n ) : NEW_LINE INDENT temp = [ ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = power ( x , n // 2 ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT return temp * temp NEW_LINE DEDENT else : NEW_LINE INDENT return x * temp * temp NEW_LINE DEDENT DEDENT def count_Total_Numbers ( n , x ) : NEW_LINE INDENT total , multiples = 0 , 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( i % x == 0 ) : NEW_LINE INDENT multiples += 1 NEW_LINE DEDENT DEDENT if ( n == 1 ) : NEW_LINE INDENT return multiples NEW_LINE DEDENT total = ( ( multiples - 1 ) * power ( multiples , n - 1 ) ) NEW_LINE return total NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1 NEW_LINE X = 3 NEW_LINE print ( count_Total_Numbers ( N , X ) ) NEW_LINE DEDENT |
Find the vertex diagonally opposite to the vertex M from an N | Function to return the required vertex ; Case 1 : ; Case 2 : ; Driver Code | def getPosition ( N , M ) : NEW_LINE INDENT if ( M > ( N // 2 ) ) : NEW_LINE INDENT return ( M - ( N // 2 ) ) NEW_LINE DEDENT return ( M + ( N // 2 ) ) NEW_LINE DEDENT N = 8 NEW_LINE M = 5 NEW_LINE print ( getPosition ( N , M ) ) NEW_LINE |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.