text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Count of pair of integers ( x , y ) such that difference between square of x and y is a perfect square | python program for the above approach ; Function to find number of pairs ( x , y ) such that x ^ 2 - y is a square number ; Stores the count of total pairs ; Iterate q value 1 to sqrt ( N ) ; Maximum possible value of p is min ( 2 * N - q , N / q ) ; P must be greater than or equal to q ; Total number of pairs are ; Adding all valid pairs to res ; Return total no of pairs ( x , y ) ; Driver Code | import math NEW_LINE def countPairs ( N ) : NEW_LINE INDENT res = 0 NEW_LINE for q in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT maxP = min ( 2 * N - q , N // q ) NEW_LINE if ( maxP < q ) : NEW_LINE INDENT continue NEW_LINE DEDENT cnt = maxP - q + 1 NEW_LINE res += ( cnt // 2 + ( cnt & 1 ) ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( countPairs ( N ) ) NEW_LINE DEDENT |
Maximum size of subset such that product of all subset elements is a factor of N | Function to find the maximum size of the subset such that the product of subset elements is a factor of N ; Base Case ; Stores maximum size of valid subset ; Traverse the given array ; If N % arr [ i ] = 0 , include arr [ i ] in a subset and recursively call for the remaining array integers ; Return Answer ; Driver Code | def maximizeSubset ( N , arr , M , x = 0 ) : NEW_LINE INDENT if ( x == M ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( x , M ) : NEW_LINE INDENT if ( N % arr [ i ] == 0 ) : NEW_LINE INDENT ans = max ( ans , maximizeSubset ( N // arr [ i ] , arr , M , x + 1 ) + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT N = 64 NEW_LINE arr = [ 1 , 2 , 4 , 8 , 16 , 32 ] NEW_LINE M = len ( arr ) NEW_LINE print ( maximizeSubset ( N , arr , M ) ) NEW_LINE |
Count of distinct sums formed by N numbers taken form range [ L , R ] | Function to find total number of different sums of N numbers in the range [ L , R ] ; To store minimum possible sum with N numbers with all as L ; To store maximum possible sum with N numbers with all as R ; All other numbers in between maxSum and minSum can also be formed so numbers in this range is the final answer ; Driver Code | def countDistinctSums ( N , L , R ) : NEW_LINE INDENT minSum = L * N NEW_LINE maxSum = R * N NEW_LINE return maxSum - minSum + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE L = 1 NEW_LINE R = 3 NEW_LINE print ( countDistinctSums ( N , L , R ) ) NEW_LINE DEDENT |
Make the Array sum 0 by using either ceil or floor on each element | Python 3 program for the above approach ; Function to modify the array element such that the sum is close to 0 ; Stores the modified elements ; Stores the sum of array element ; Stores minimum size of the array ; Traverse the array and find the sum ; If sum is positive ; Find the minimum number of elements that must be changed ; Iterate until M elements are modified or the array end ; Update the current array elements to its floor ; Print the resultant array ; Driver Code | import sys NEW_LINE from math import ceil , floor NEW_LINE def setSumtoZero ( arr , N ) : NEW_LINE INDENT A = [ 0 for i in range ( N ) ] NEW_LINE sum = 0 NEW_LINE m = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += ceil ( arr [ i ] ) NEW_LINE A [ i ] = ceil ( arr [ i ] ) NEW_LINE DEDENT if ( sum > 0 ) : NEW_LINE INDENT m = min ( sum , N ) NEW_LINE i = 0 NEW_LINE while ( i < N and m > 0 ) : NEW_LINE INDENT A [ i ] = floor ( arr [ i ] ) NEW_LINE if ( A [ i ] != floor ( arr [ i ] ) ) : NEW_LINE INDENT m -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , - 2 , 4.5 ] NEW_LINE N = len ( arr ) NEW_LINE setSumtoZero ( arr , N ) NEW_LINE DEDENT |
Find first undeleted integer from K to N in given unconnected Graph after performing Q queries | Function to perform th Get operation of disjoint set union ; Function to perform the union operation of dijoint set union ; Update the graph [ a ] as b ; Function to perform given queries on set of vertices initially not connected ; Stores the vertices ; Mark every vertices rightmost vertex as i ; Traverse the queries array ; Check if it is first type of the givan query ; Get the parent of a ; Print the answer for the second query ; Driver Code | def Get ( graph , a ) : NEW_LINE INDENT if graph [ graph [ a ] ] != graph [ a ] : NEW_LINE INDENT graph [ a ] = Get ( graph , graph [ a ] ) NEW_LINE DEDENT else : NEW_LINE INDENT return graph [ a ] NEW_LINE DEDENT DEDENT def Union ( graph , a , b ) : NEW_LINE INDENT a = Get ( graph , a ) NEW_LINE b = Get ( graph , b ) NEW_LINE graph [ a ] = b NEW_LINE DEDENT def Queries ( queries , N , M ) : NEW_LINE INDENT graph = [ 0 for i in range ( N + 2 ) ] NEW_LINE for i in range ( 1 , N + 2 , 1 ) : NEW_LINE INDENT graph [ i ] = i NEW_LINE DEDENT for query in queries : NEW_LINE INDENT if ( query [ 0 ] == 1 ) : NEW_LINE INDENT Union ( graph , query [ 1 ] , query [ 1 ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT a = Get ( graph , query [ 1 ] ) NEW_LINE if ( a == N + 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( graph [ a ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE queries = [ [ 2 , 1 ] , [ 1 , 1 ] , [ 2 , 1 ] , [ 2 , 3 ] ] NEW_LINE Q = len ( queries ) NEW_LINE Queries ( queries , N , Q ) NEW_LINE DEDENT |
Finding the Nth term in a sequence formed by removing digit K from natural numbers | Python 3 implementation for the above approach ; Denotes the digit place ; Method to convert any number to binary equivalent ; denotes the current digits place ; If current digit is >= K increment its value by 1 ; Else add the digit as it is ; Move to the next digit ; Driver code | def convertToBase9 ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE a = 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT ans += ( a * ( n % 9 ) ) NEW_LINE a *= 10 NEW_LINE n //= 9 NEW_LINE DEDENT return ans NEW_LINE DEDENT def getNthnumber ( base9 , K ) : NEW_LINE INDENT ans = 0 NEW_LINE a = 1 NEW_LINE while ( base9 > 0 ) : NEW_LINE INDENT cur = base9 % 10 NEW_LINE if ( cur >= K ) : NEW_LINE INDENT ans += a * ( cur + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += a * cur NEW_LINE DEDENT base9 //= 10 NEW_LINE a *= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE K = 1 NEW_LINE base9 = convertToBase9 ( N ) NEW_LINE print ( getNthnumber ( base9 , K ) ) NEW_LINE DEDENT |
Check if given array can be rearranged such that mean is equal to median | Function to return true or false if size of array is odd ; To prevent overflow ; If element is greater than mid , then it can only be present in right subarray ; If element is smaller than mid , then it can only be present in left subarray ; Else the element is present at the middle then return 1 ; when element is not present in array then return 0 ; Function to return true or false if size of array is even ; Calculating Candidate Median ; If Candidate Median if greater than Mean then decrement j ; If Candidate Median if less than Mean then increment i ; If Candidate Median if equal to Mean then return 1 ; when No candidate found for mean ; Function to return true if Mean can be equal to any candidate median otherwise return false ; Calculating Mean ; If N is Odd ; If N is even ; Driver Code | def binarySearch ( arr , size , key ) : NEW_LINE INDENT low = 0 NEW_LINE high = size - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( key > arr [ mid ] ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT elif ( key < arr [ mid ] ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def twoPointers ( arr , N , mean ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT temp = ( arr [ i ] + arr [ j ] ) / 2 NEW_LINE if ( temp > mean ) : NEW_LINE INDENT j = j - 1 NEW_LINE DEDENT elif ( temp < mean ) : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def checkArray ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT mean = sum / N NEW_LINE if ( N & 1 ) : NEW_LINE INDENT return binarySearch ( arr , N , mean ) NEW_LINE DEDENT else : NEW_LINE INDENT return twoPointers ( arr , N , mean ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1.0 , 3.0 , 6.0 , 9.0 , 12.0 , 32.0 ] NEW_LINE N = len ( arr ) NEW_LINE if ( checkArray ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Count of distinct integers belonging to first N terms of at least one of given GPs | Function to find the count of distinct integers that belong to the first N terms of at least one of them is GP ; Stores the integers that occur in GPs in a set data - structure ; Stores the current integer of the first GP ; Iterate first N terms of first GP ; Insert the ith term of GP in S ; Stores the current integer of the second GP ; Iterate first N terms of second GP ; Return Answer ; Driver Code | def UniqueGeometricTerms ( N , a1 , r1 , a2 , r2 ) : NEW_LINE INDENT S = set ( ) NEW_LINE p1 = a1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT S . add ( p1 ) NEW_LINE p1 = ( p1 * r1 ) NEW_LINE DEDENT p2 = a2 NEW_LINE for i in range ( N ) : NEW_LINE INDENT S . add ( p2 ) NEW_LINE p2 = ( p2 * r2 ) NEW_LINE DEDENT return len ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE a1 = 3 NEW_LINE r1 = 2 NEW_LINE a2 = 2 NEW_LINE r2 = 3 NEW_LINE print ( UniqueGeometricTerms ( N , a1 , r1 , a2 , r2 ) ) NEW_LINE DEDENT |
Minimize operations to make all array elements | Function to find minimum the number of operations required to make all the array elements to - 1 ; Stores the array elements with their corresponding indices ; Push the array element and it 's index ; Sort the elements according to it 's first value ; Stores the minimum number of operations required ; Traverse until vp is not empty ; Stores the first value of vp ; Stores the second value of vp ; Update the minCnt ; Pop the back element from the vp until the first value is same as val and difference between indices is less than K ; Return the minCnt ; Driver Code | def minOperations ( arr , N , K ) : NEW_LINE INDENT vp = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT vp . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT vp . sort ( ) NEW_LINE minCnt = 0 NEW_LINE while ( len ( vp ) != 0 ) : NEW_LINE INDENT val = vp [ - 1 ] [ 0 ] NEW_LINE ind = vp [ - 1 ] [ 1 ] NEW_LINE minCnt += 1 NEW_LINE while ( len ( vp ) != 0 and vp [ - 1 ] [ 0 ] == val and ind - vp [ - 1 ] [ 1 ] + 1 <= K ) : NEW_LINE INDENT vp . pop ( ) NEW_LINE DEDENT DEDENT return minCnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 18 , 11 , 18 , 11 , 18 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N , K ) ) NEW_LINE DEDENT |
Find array sum after incrementing by K adjacent elements of every positive element M times | Function to find the nearest non - zero element in the left direction ; Stores the index of the first element greater than 0 from the right side ; Traverse the array in the range [ 1 , N ] ; Check arr [ i ] is greater than 0 ; Update the value of L ; Traverse the array from the left side ; Check arr [ i ] is greater than 0 ; Update the value of L ; Update the value of steps [ i ] ; Function to find the nearest non - zero element in the right direction ; Stores the index of the first element greater than 0 from the left side ; Traverse the array from the left side ; Check arr [ i ] is greater than 0 ; Update the value of R ; Traverse the array from the right side ; Check arr [ i ] is greater than 0 ; Update the value of R ; Update the value of steps [ i ] ; Function to find the sum of the array after the given operation M times ; Stores the distance of the nearest non zero element . ; Stores sum of the initial array arr [ ] ; Traverse the array from the left side ; Update the value of sum ; Print the total sum of the array ; Driver Code | def nearestLeft ( arr , N , steps ) : NEW_LINE INDENT L = - N NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT L = - ( N - i ) NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT L = i NEW_LINE DEDENT steps [ i ] = i - L NEW_LINE DEDENT DEDENT def nearestRight ( arr , N , steps ) : NEW_LINE INDENT R = 2 * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT R = N + i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT R = i NEW_LINE DEDENT steps [ i ] = min ( steps [ i ] , R - i ) NEW_LINE DEDENT DEDENT def findSum ( arr , N , M , K ) : NEW_LINE INDENT steps = [ 0 ] * N NEW_LINE s = sum ( arr ) NEW_LINE if ( s == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT nearestLeft ( arr , N , steps ) NEW_LINE nearestRight ( arr , N , steps ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT s += 2 * K * max ( 0 , M - steps [ i ] ) NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 1 , 0 , 1 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE M = 2 NEW_LINE K = 1 NEW_LINE print ( findSum ( arr , N , M , K ) ) NEW_LINE DEDENT |
Smallest vertex in the connected components of all the vertices in given undirect graph | Python 3 program for the above approach ; Stores the parent and size of the set of the ith element ; Function to initialize the ith set ; Function to find set of ith vertex ; Base Case ; Recursive call to find set ; Function to unite the set that includes a and the set that includes b ; If a and b are not from same set ; Function to find the smallest vertex in the connected component of the ith vertex for all i in range [ 1 , N ] ; Loop to initialize the ith set ; Loop to unite all vertices connected by edges into the same set ; Stores the minimum vertex value for ith set ; Loop to iterate over all vertices ; If current vertex does not exist in minVal initialize it with i ; Update the minimum value of the set having the ith vertex ; Loop to print required answer ; Driver Code | maxn = 100 NEW_LINE parent = [ 0 ] * maxn NEW_LINE Size = [ 0 ] * maxn NEW_LINE def make_set ( v ) : NEW_LINE INDENT parent [ v ] = v NEW_LINE Size [ v ] = 1 NEW_LINE DEDENT def find_set ( v ) : NEW_LINE INDENT if ( v == parent [ v ] ) : NEW_LINE INDENT return v NEW_LINE DEDENT parent [ v ] = find_set ( parent [ v ] ) NEW_LINE return parent [ v ] NEW_LINE DEDENT def union_sets ( a , b ) : NEW_LINE INDENT a = find_set ( a ) NEW_LINE b = find_set ( b ) NEW_LINE if ( a != b ) : NEW_LINE INDENT if ( Size [ a ] < Size [ b ] ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT parent [ b ] = a NEW_LINE Size [ a ] += Size [ b ] NEW_LINE DEDENT DEDENT def findMinVertex ( N , edges ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT make_set ( i ) NEW_LINE DEDENT for i in range ( len ( edges ) ) : NEW_LINE INDENT union_sets ( edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) NEW_LINE DEDENT minVal = { } NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( find_set ( i ) not in minVal ) : NEW_LINE INDENT minVal [ find_set ( i ) ] = i NEW_LINE DEDENT else : NEW_LINE INDENT minVal [ find_set ( i ) ] = min ( minVal [ find_set ( i ) ] , i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( minVal [ find_set ( i ) ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE edges = [ [ 1 , 3 ] , [ 2 , 4 ] ] NEW_LINE findMinVertex ( N , edges ) NEW_LINE DEDENT |
Count of pairs in given range having their ratio equal to ratio of product of their digits | Function to find the product of digits of the given number ; Function to find the count of pairs ( a , b ) such that a : b = ( product ofdigits of a ) : ( product of digits of b ) ; Stores the count of the valid pairs ; Loop to iterate over all unordered pairs ( a , b ) ; Stores the product of digits of a ; Stores the product of digits of b ; If x != 0 and y != 0 and a : b is equivalent to x : y ; Increment valid pair count ; Return Answer ; Driver code ; Function Call | def getProduct ( n ) : NEW_LINE INDENT product = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT product = product * ( n % 10 ) NEW_LINE n = n // 10 NEW_LINE DEDENT return product NEW_LINE DEDENT def countPairs ( L , R ) : NEW_LINE INDENT cntPair = 0 NEW_LINE for a in range ( L , R + 1 , 1 ) : NEW_LINE INDENT for b in range ( a + 1 , R + 1 , 1 ) : NEW_LINE INDENT x = getProduct ( a ) NEW_LINE y = getProduct ( b ) NEW_LINE if ( x and y and ( a * y ) == ( b * x ) ) : NEW_LINE INDENT cntPair += 1 NEW_LINE DEDENT DEDENT DEDENT return cntPair NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 1 NEW_LINE R = 100 NEW_LINE print ( countPairs ( 1 , 100 ) ) NEW_LINE DEDENT |
Maximize matrix sum by flipping the sign of any adjacent pairs | Python 3 program for the above approach ; Function to find the maximum sum of matrix element after flipping the signs of adjacent matrix elements ; Initialize row and column ; Stores the sum of absolute matrix element ; Find the minimum absolute value in the matrix ; Store count of negatives ; Find the smallest absolute value in the matrix ; Increment the count of negative numbers ; Find the absolute sum ; If the count of negatives is even then print the sum ; Subtract minimum absolute element ; Driver Code | import sys NEW_LINE def maxSum ( matrix ) : NEW_LINE INDENT r = len ( matrix ) NEW_LINE c = len ( matrix [ 0 ] ) NEW_LINE sum = 0 NEW_LINE mini = sys . maxsize NEW_LINE count = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT k = matrix [ i ] [ j ] NEW_LINE mini = min ( mini , abs ( k ) ) NEW_LINE if ( k < 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT sum += abs ( k ) NEW_LINE DEDENT DEDENT if ( count % 2 == 0 ) : NEW_LINE INDENT return sum NEW_LINE DEDENT else : NEW_LINE INDENT return ( sum - 2 * mini ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 2 , - 2 ] , [ - 2 , 2 ] ] NEW_LINE print ( maxSum ( matrix ) ) NEW_LINE DEDENT |
Find the last positive element remaining after repeated subtractions of smallest positive element from all Array elements | Function to calculate last positive element of the array ; Return the first element if N = 1 ; Stores the greatest and the second greatest element ; Traverse the array A [ ] ; If current element is greater than the greatest element ; If current element is greater than second greatest element ; Return the final answer ; Driver Code | def lastPositiveElement ( arr ) : NEW_LINE INDENT N = len ( arr ) ; NEW_LINE if ( N == 1 ) : NEW_LINE INDENT return arr [ 0 ] ; NEW_LINE DEDENT greatest = - 1 ; secondGreatest = - 1 ; NEW_LINE for x in arr : NEW_LINE INDENT if ( x >= greatest ) : NEW_LINE INDENT secondGreatest = greatest ; NEW_LINE greatest = x ; NEW_LINE DEDENT elif ( x >= secondGreatest ) : NEW_LINE INDENT secondGreatest = x ; NEW_LINE DEDENT DEDENT return greatest - secondGreatest ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 5 , 4 , 7 ] ; NEW_LINE print ( lastPositiveElement ( arr ) ) ; NEW_LINE DEDENT |
Reduce given array by replacing subarrays with values less than K with their sum | Function to replace all the subarray having values < K with their sum ; Stores the sum of subarray having elements less than K ; Stores the updated array ; Traverse the array ; Update the sum ; Otherwise , update the vector ; Print the result ; Driver Code | def updateArray ( arr , K ) : NEW_LINE INDENT sum = 0 NEW_LINE res = [ ] NEW_LINE for i in range ( 0 , int ( len ( arr ) ) ) : NEW_LINE INDENT if ( arr [ i ] < K ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT if ( sum != 0 ) : NEW_LINE INDENT res . append ( sum ) NEW_LINE DEDENT sum = 0 NEW_LINE res . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT if ( sum != 0 ) : NEW_LINE INDENT res . append ( sum ) NEW_LINE DEDENT for it in res : NEW_LINE INDENT print ( it , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 200 , 6 , 36 , 612 , 121 , 66 , 63 , 39 , 668 , 108 ] NEW_LINE K = 100 NEW_LINE updateArray ( arr , K ) NEW_LINE DEDENT |
Find if path length is even or odd between given Tree nodes for Q queries | Python program for the above approach ; Stores the input tree ; Stores the set number of all nodes ; Function to add an edge in the tree ; Function to convert the given tree into a bipartite graph using BFS ; Set the set number to - 1 for all node of the given tree ; Stores the current node during the BFS traversal of the tree ; Initialize the set number of 1 st node and enqueue it ; BFS traversal of the given tree ; Current node ; Traverse over all neighbours of the current node ; If the set is not assigned ; Assign set number to node u ; Function to find if the path length between node A and B is even or odd ; If the set number of both nodes is same , path length is odd else even ; Driver Code ; Function to convert tree into bipartite | from queue import Queue NEW_LINE adj = [ [ 0 ] * 100000 ] * 100000 NEW_LINE setNum = [ 0 ] * 100000 NEW_LINE def addEdge ( a1 , a2 ) : NEW_LINE INDENT adj [ a1 ] . append ( a2 ) ; NEW_LINE adj [ a2 ] . append ( a1 ) ; NEW_LINE DEDENT def toBipartite ( N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT setNum [ i ] = - 1 NEW_LINE DEDENT q = Queue ( ) ; NEW_LINE q . put ( 0 ) ; NEW_LINE setNum [ 0 ] = 0 ; NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT v = q . queue [ 0 ] ; NEW_LINE q . get ( ) ; NEW_LINE for u in adj [ v ] : NEW_LINE INDENT if ( setNum [ u ] == - 1 ) : NEW_LINE INDENT setNum [ u ] = setNum [ v ] ^ 1 ; NEW_LINE q . put ( u ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def pathLengthQuery ( A , B ) : NEW_LINE INDENT if ( setNum [ A ] == setNum [ B ] ) : NEW_LINE INDENT print ( " Odd " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Even " ) ; NEW_LINE DEDENT DEDENT N = 7 ; NEW_LINE addEdge ( 0 , 1 ) ; NEW_LINE addEdge ( 0 , 2 ) ; NEW_LINE addEdge ( 1 , 3 ) ; NEW_LINE addEdge ( 3 , 4 ) ; NEW_LINE addEdge ( 3 , 5 ) ; NEW_LINE addEdge ( 2 , 6 ) ; NEW_LINE toBipartite ( N ) ; NEW_LINE pathLengthQuery ( 4 , 2 ) ; NEW_LINE pathLengthQuery ( 0 , 4 ) ; NEW_LINE |
Minimum size of set having either element in range [ 0 , X ] or an odd power of 2 with sum N | Python program for the above approach ; Function to find the highest odd power of 2 in the range [ 0 , N ] ; If P is even , subtract 1 ; Function to find the minimum operations to make N ; If N is odd and X = 0 , then no valid set exist ; Stores the minimum possible size of the valid set ; Loop to subtract highest odd power of 2 while X < N , step 2 ; If N > 0 , then increment the value of answer by 1 ; Return the resultant size of set ; Driver Code | import math NEW_LINE def highestPowerof2 ( n ) : NEW_LINE INDENT p = int ( math . log ( n , 2 ) ) NEW_LINE if p % 2 == 0 : NEW_LINE INDENT p -= 1 NEW_LINE DEDENT return int ( pow ( 2 , p ) ) NEW_LINE DEDENT def minStep ( N , X ) : NEW_LINE INDENT if N % 2 and X == 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT size = 0 NEW_LINE while X < N : NEW_LINE INDENT N -= highestPowerof2 ( N ) NEW_LINE size += 1 NEW_LINE DEDENT if N : NEW_LINE INDENT size += 1 NEW_LINE DEDENT return size NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 NEW_LINE X = 2 NEW_LINE print ( minStep ( N , X ) ) NEW_LINE DEDENT |
Check if all the digits of the given number are same | Function to check if all the digits in the number N is the same or not ; Find the last digit ; Find the current last digit ; Update the value of N ; If there exists any distinct digit , then return No ; Otherwise , return Yes ; Driver Code | def checkSameDigits ( N ) : NEW_LINE INDENT digit = N % 10 ; NEW_LINE while ( N != 0 ) : NEW_LINE INDENT current_digit = N % 10 ; NEW_LINE N = N // 10 ; NEW_LINE if ( current_digit != digit ) : NEW_LINE INDENT return " No " ; NEW_LINE DEDENT DEDENT return " Yes " ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 222 ; NEW_LINE print ( checkSameDigits ( N ) ) ; NEW_LINE DEDENT |
Find number formed by K times alternatively reducing X and adding Y to 0 | Function to find the value obtained after alternatively reducing X and adding Y to 0 total K number of times ; Stores the final result after adding only Y to 0 ; Stores the final number after reducing only X from 0 ; Return the result obtained ; Driver Code | def positionAfterKJumps ( X , Y , K ) : NEW_LINE INDENT addY = Y * ( K // 2 ) NEW_LINE reduceX = - 1 * X * ( K // 2 + K % 2 ) NEW_LINE return addY + reduceX NEW_LINE DEDENT X = 2 NEW_LINE Y = 5 NEW_LINE K = 3 NEW_LINE print ( positionAfterKJumps ( X , Y , K ) ) NEW_LINE |
Maximize the largest number K such that bitwise and of K till N is 0 | Function to find maximum value of k which makes bitwise AND zero . ; Take k = N initially ; Start traversing from N - 1 till 0 ; Whenever we get AND as 0 we stop and return ; Driver Code | def findMaxK ( N ) : NEW_LINE INDENT K = N NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT K &= i NEW_LINE if ( K == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( findMaxK ( N ) ) NEW_LINE DEDENT |
Count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices | Function of find the count of unordered pairs ( i , j ) in the array such that arr [ j ] / arr [ i ] = j / i . ; Stores the count of valid pairs ; Iterating over all possible pairs ; Check if the pair is valid ; Return answer ; Driver Code ; Function Call | def countPairs ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( ( arr [ j ] % arr [ i ] == 0 ) and ( j + 1 ) % ( i + 1 ) == 0 and ( arr [ j ] // arr [ i ] == ( j + 1 ) // ( i + 1 ) ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , - 2 , 4 , 20 , 25 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT |
Count of unordered pair of indices such that ratio of elements at these indices is same as ratio of indices | Function of find the count of unordered pairs ( i , j ) in the array such that arr [ j ] / arr [ i ] = j / i . ; Stores the count of valid pairs ; Iterating over all values of x in range [ 1 , N ] . ; Iterating over all values of y that are divisible by x in the range [ 1 , N ] . ; Check if the pair is valid ; Return answer ; Driver Code ; Function Call | def countPairs ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for x in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for y in range ( 2 * x , n + 1 , x ) : NEW_LINE INDENT if ( ( arr [ y - 1 ] % arr [ x - 1 ] == 0 ) and ( arr [ y - 1 ] // arr [ x - 1 ] == y // x ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , - 2 , 4 , 20 , 25 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE DEDENT |
Number of minimum length paths between 1 to N including each node | Function to calculate the distances from node 1 to N ; Stores the number of edges ; Storing the edges in vector ; Initialize queue ; BFS from 1 st node using queue ; Pop from queue ; Traversing the adjacency list ; Initialize queue ; BFS from last node ; Pop from queue ; Traverse the adjacency list ; Print the count of minimum distance ; Driver Code | def countMinDistance ( n , m , edges ) : NEW_LINE INDENT g = [ [ ] for i in range ( 10005 ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT a = edges [ i ] [ 0 ] - 1 NEW_LINE b = edges [ i ] [ 1 ] - 1 NEW_LINE g [ a ] . append ( b ) NEW_LINE g [ b ] . append ( a ) NEW_LINE DEDENT queue1 = [ ] NEW_LINE queue1 . append ( [ 0 , 0 ] ) NEW_LINE dist = [ 1e9 for i in range ( n ) ] NEW_LINE ways1 = [ 0 for i in range ( n ) ] NEW_LINE dist [ 0 ] = 0 NEW_LINE ways1 [ 0 ] = 1 NEW_LINE while ( len ( queue1 ) > 0 ) : NEW_LINE INDENT up = queue1 [ 0 ] NEW_LINE queue1 = queue1 [ : - 1 ] NEW_LINE x = up [ 0 ] NEW_LINE dis = up [ 1 ] NEW_LINE if ( dis > dist [ x ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( x == n - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for y in g [ x ] : NEW_LINE INDENT if ( dist [ y ] > dis + 1 ) : NEW_LINE INDENT dist [ y ] = dis + 1 NEW_LINE ways1 [ y ] = ways1 [ x ] NEW_LINE queue1 . append ( [ y , dis + 1 ] ) NEW_LINE DEDENT elif ( dist [ y ] == dis + 1 ) : NEW_LINE INDENT ways1 [ y ] += ways1 [ x ] NEW_LINE DEDENT DEDENT DEDENT queue2 = [ ] NEW_LINE queue2 . append ( [ n - 1 , 0 ] ) NEW_LINE dist1 = [ 1e9 for i in range ( n ) ] NEW_LINE ways2 = [ 0 for i in range ( n ) ] NEW_LINE dist1 [ n - 1 ] = 0 NEW_LINE ways2 [ n - 1 ] = 1 NEW_LINE while ( len ( queue2 ) > 0 ) : NEW_LINE INDENT up = queue2 [ 0 ] NEW_LINE queue2 = queue2 [ : - 1 ] NEW_LINE x = up [ 0 ] NEW_LINE dis = up [ 1 ] NEW_LINE if ( dis > dist1 [ x ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( x == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for y in g [ x ] : NEW_LINE INDENT if ( dist1 [ y ] > dis + 1 ) : NEW_LINE INDENT dist1 [ y ] = dis + 1 NEW_LINE ways2 [ y ] = ways2 [ x ] NEW_LINE queue2 . append ( [ y , dis + 1 ] ) NEW_LINE DEDENT elif ( dist1 [ y ] == 1 + dis ) : NEW_LINE INDENT ways2 [ y ] += ways2 [ x ] NEW_LINE DEDENT DEDENT DEDENT ways1 [ n - 1 ] = 1 NEW_LINE ways2 [ n - 1 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ways1 [ i ] * ways2 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 5 NEW_LINE edges = [ [ 1 , 2 ] , [ 1 , 4 ] , [ 1 , 3 ] , [ 2 , 5 ] , [ 2 , 4 ] ] NEW_LINE countMinDistance ( N , M , edges ) NEW_LINE DEDENT |
Count of N | Python program for the above approach ; Function to find the count of odd and even integers having N bits and K set bits ; Find the count of even integers ; Find the count of odd integers ; Print the total count ; Driver Code | import math NEW_LINE def Binary_Num ( N , K ) : NEW_LINE INDENT if N - K - 1 >= 0 and K - 1 >= 0 : NEW_LINE INDENT num_even = math . factorial ( N - 2 ) / ( math . factorial ( K - 1 ) * math . factorial ( N - K - 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT num_even = 0 NEW_LINE DEDENT if K - 2 >= 0 : NEW_LINE INDENT num_odd = math . factorial ( N - 2 ) / ( math . factorial ( K - 2 ) * math . factorial ( N - K ) ) NEW_LINE DEDENT else : NEW_LINE INDENT num_odd = 0 NEW_LINE DEDENT print ( int ( num_even ) , int ( num_odd ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 NEW_LINE K = 6 NEW_LINE Binary_Num ( N , K ) NEW_LINE DEDENT |
Sum of all subsets of a given size ( = K ) | Function to find the sum of all sub - sets of size K ; Frequency of each array element in summation equation . ; calculate factorial of n - 1 ; calculate factorial of k - 1 ; calculate factorial of n - k ; Calculate sum of array . ; Sum of all subsets of size k . ; Driver Code | def findSumOfAllSubsets ( arr , n , k ) : NEW_LINE INDENT factorial_N = 1 NEW_LINE factorial_d = 1 NEW_LINE factorial_D = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT factorial_N *= i NEW_LINE DEDENT for i in range ( 1 , k , 1 ) : NEW_LINE INDENT factorial_d *= i NEW_LINE DEDENT for i in range ( 1 , n - k + 1 , 1 ) : NEW_LINE INDENT factorial_D *= i NEW_LINE DEDENT freq = factorial_N // ( factorial_d * factorial_D ) NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT sum = sum * freq NEW_LINE print ( " Sum β of β all β subsets β of β size β = β " , k , " β is β = > " , sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 5 ] NEW_LINE n = 4 NEW_LINE k = 2 NEW_LINE findSumOfAllSubsets ( arr , n , k ) NEW_LINE DEDENT |
Maximize XOR by selecting 3 numbers in range [ 0 , A ] , [ 0 , B ] , and [ 0 , C ] respectively | Function to calculate maximum triplet XOR form 3 ranges ; Initialize a variable to store the answer ; create minimum number that have a set bit at ith position ; Check for each number and try to greedily choose the bit if possible If A >= cur then A also have a set bit at ith position ; Increment the answer ; Subtract this value from A ; Check for B ; Increment the answer ; Subtract this value from B ; Check for C ; Increment the answer ; Subtract this value from C ; If any of the above conditions is not satisfied then there is no way to turn that bit ON . ; Driver Code | def maximumTripletXOR ( A , B , C ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 30 , - 1 , - 1 ) : NEW_LINE INDENT cur = 1 << i NEW_LINE if ( A >= cur ) : NEW_LINE INDENT ans += cur NEW_LINE A -= cur NEW_LINE DEDENT elif ( B >= cur ) : NEW_LINE INDENT ans += cur NEW_LINE B -= cur NEW_LINE DEDENT elif ( C >= cur ) : NEW_LINE INDENT ans += cur NEW_LINE C -= cur NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = 6 NEW_LINE B = 2 NEW_LINE C = 10 NEW_LINE print ( maximumTripletXOR ( A , B , C ) ) NEW_LINE |
Count of integers in given range having their last K digits are equal | Function to return the count of integers from 1 to X having the last K digits as equal ; Stores the total count of integers ; Loop to iterate over all possible values of z ; Terminate the loop when z > X ; Add count of integers with last K digits equal to z ; Return count ; Function to return the count of integers from L to R having the last K digits as equal ; Driver Code ; Function Call | def intCount ( X , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for z in range ( 0 , int ( pow ( 10 , K ) ) , int ( ( pow ( 10 , K ) - 1 ) / 9 ) ) : NEW_LINE INDENT if ( z > X ) : NEW_LINE INDENT break NEW_LINE DEDENT ans += int ( ( X - z ) / int ( pow ( 10 , K ) ) + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def intCountInRange ( L , R , K ) : NEW_LINE INDENT return ( intCount ( R , K ) - intCount ( L - 1 , K ) ) NEW_LINE DEDENT L = 49 NEW_LINE R = 101 NEW_LINE K = 2 NEW_LINE print ( intCountInRange ( L , R , K ) ) NEW_LINE |
Count subsequence of length 4 having product of the first three elements equal to the fourth element | Function to find the total number of subsequences satisfying the given criteria ; Stores the count of quadruplets ; Stores the frequency of product of the triplet ; Traverse the given array arr [ ] ; Consider arr [ i ] as fourth element of subsequences ; Generate all possible pairs of the array [ 0 , i - 1 ] ; Increment the frequency of the triplet ; Return the total count obtained ; Driver Code | def countQuadruples ( A , N ) : NEW_LINE INDENT ans = 0 NEW_LINE freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if A [ i ] in freq : NEW_LINE INDENT ans += freq [ A [ i ] ] NEW_LINE DEDENT else : NEW_LINE INDENT freq [ A [ i ] ] = 0 NEW_LINE DEDENT for j in range ( i ) : NEW_LINE INDENT for k in range ( j ) : NEW_LINE INDENT if A [ i ] * A [ j ] * A [ k ] in freq : NEW_LINE INDENT freq [ A [ i ] * A [ j ] * A [ k ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ A [ i ] * A [ j ] * A [ k ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 2 , 2 , 7 , 40 , 160 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countQuadruples ( arr , N ) ) NEW_LINE DEDENT |
Maximum times X and Y can be reduced to near 0 using numbers A or B | Helper function to check if we can perform Mid number of moves ; Remove atleast Mid * B from both X and Y ; If any value is negative return false . ; Calculate remaining values ; If val >= Mid then it is possible to perform this much moves ; else return false ; Initialize a variable to store the answer ; Fix the left and right range ; Binary Search over the answer ; Check for the middle value as the answer ; It is possible to perform this much moves ; Maximise the answer ; Return answer ; Driver Code ; Generalise that A >= B | MAXN = 10000000 NEW_LINE def can ( Mid , X , Y , A , B ) : NEW_LINE INDENT p1 = X - Mid * B NEW_LINE p2 = Y - Mid * B NEW_LINE if ( p1 < 0 or p2 < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT k = A - B NEW_LINE if ( k == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT val = p1 // k + p2 // k NEW_LINE if ( val >= Mid ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def maxPossibleMoves ( X , Y , A , B ) : NEW_LINE INDENT ans = 0 NEW_LINE L = 1 NEW_LINE R = MAXN NEW_LINE while ( L <= R ) : NEW_LINE INDENT Mid = ( L + R ) // 2 NEW_LINE if ( can ( Mid , X , Y , A , B ) ) : NEW_LINE INDENT L = Mid + 1 NEW_LINE ans = max ( ans , Mid ) NEW_LINE DEDENT else : NEW_LINE INDENT R = Mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT X = 10 NEW_LINE Y = 12 NEW_LINE A = 2 NEW_LINE B = 5 NEW_LINE if ( A < B ) : NEW_LINE INDENT tmp = A NEW_LINE A = B NEW_LINE B = tmp NEW_LINE DEDENT print ( maxPossibleMoves ( X , Y , A , B ) ) NEW_LINE |
Find two proper factors of N such that their sum is coprime with N | Python Program for the above approach ; Function to find two proper factors of N such that their sum is coprime with N ; Find factors in sorted order ; Find largest value of d2 such that d1 and d2 are co - prime ; Check if d1 and d2 are proper factors of N ; Print answer ; No such factors exist ; Driver code ; Function Call | import math NEW_LINE def printFactors ( n ) : NEW_LINE INDENT for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT d1 = i NEW_LINE d2 = n NEW_LINE while ( d2 % d1 == 0 ) : NEW_LINE INDENT d2 = d2 // d1 NEW_LINE DEDENT if ( d1 > 1 and d2 > 1 ) : NEW_LINE INDENT print ( d1 , d2 , sep = " , β " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT N = 10 NEW_LINE printFactors ( N ) NEW_LINE |
Count of triplets in an Array with odd sum | Function to count the number of unordered triplets such that their sum is an odd integer ; Count the number of odd and even integers in the array ; Number of ways to create triplets using one odd and two even integers ; Number of ways to create triplets using three odd integers ; Return answer ; Driver Code ; Function Call ; Print Answer | def countTriplets ( arr , n ) : NEW_LINE INDENT odd = 0 NEW_LINE even = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT c1 = odd * ( even * ( even - 1 ) ) // 2 NEW_LINE c2 = ( odd * ( odd - 1 ) * ( odd - 2 ) ) // 6 NEW_LINE return c1 + c2 NEW_LINE DEDENT arr = [ 4 , 5 , 6 , 4 , 5 , 10 , 1 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE ans = countTriplets ( arr , n ) NEW_LINE print ( ans ) NEW_LINE |
Longest remaining array of distinct elements possible after repeated removal of maximum and minimum elements of triplets | Function to return length of longest remaining array of pairwise distinct array possible by removing triplets ; Stores the frequency of array elements ; Traverse the array ; Iterate through the map ; If frequency of current element is even ; Stores the required count of unique elements remaining ; If count is odd ; Driver Code | def maxUniqueElements ( A , N ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if A [ i ] in mp : NEW_LINE INDENT mp [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ A [ i ] ] = 1 NEW_LINE DEDENT DEDENT cnt = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT if ( value % 2 == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT ans = len ( mp ) NEW_LINE if ( cnt % 2 == 1 ) : NEW_LINE INDENT ans -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE A = [ 1 , 2 , 1 , 3 , 7 ] NEW_LINE print ( maxUniqueElements ( A , N ) ) NEW_LINE DEDENT |
Count cells in a grid from which maximum number of cells can be reached by K vertical or horizontal jumps | Function to count the number of cells in the grid such that maximum cell is reachable with a jump of K ; Maximum reachable rows from the current row ; Stores the count of cell that are reachable from the current row ; Count of reachable rows ; Update the maximum value ; Add it to the count ; Maximum reachable columns from the current column ; Stores the count of cell that are reachable from the current column ; Count of rechable columns ; Update the maximum value ; Add it to the count ; Return the total count of cells ; Driver Code | def countCells ( n , m , s ) : NEW_LINE INDENT mx1 = - 1 NEW_LINE cont1 = 0 NEW_LINE i = 0 NEW_LINE while ( i < s and i < n ) : NEW_LINE INDENT aux = ( n - ( i + 1 ) ) // s + 1 NEW_LINE if ( aux > mx1 ) : NEW_LINE INDENT mx1 = cont1 = aux NEW_LINE DEDENT elif ( aux == mx1 ) : NEW_LINE INDENT cont1 += aux NEW_LINE DEDENT i += 1 NEW_LINE DEDENT mx2 = - 1 NEW_LINE cont2 = 0 NEW_LINE i = 0 NEW_LINE while ( i < s and i < m ) : NEW_LINE INDENT aux = ( m - ( i + 1 ) ) // s + 1 NEW_LINE if ( aux > mx2 ) : NEW_LINE INDENT mx2 = cont2 = aux NEW_LINE DEDENT elif ( aux == mx2 ) : NEW_LINE INDENT cont2 += aux NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return cont1 * cont2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 5 NEW_LINE K = 2 NEW_LINE print ( countCells ( N , M , K ) ) NEW_LINE DEDENT |
Count of pairs from first N natural numbers with remainder at least K | Function to count the number of pairs ( a , b ) such that a % b is at least K ; Base Case ; Stores resultant count of pairs ; Iterate over the range [ K + 1 , N ] ; Find the cycled elements ; Find the remaining elements ; Return the resultant possible count of pairs ; Driver Code | def countTotalPairs ( N , K ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return N * N NEW_LINE DEDENT ans = 0 NEW_LINE for b in range ( K + 1 , N + 1 ) : NEW_LINE INDENT ans += ( N // b ) * ( b - K ) NEW_LINE ans += max ( N % b - K + 1 , 0 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 5 NEW_LINE K = 2 NEW_LINE print ( countTotalPairs ( N , K ) ) NEW_LINE |
Minimize sum of absolute difference between all pairs of array elements by decrementing and incrementing pairs by 1 | Function to find the minimum value of the sum of absolute difference between all pairs of arrays ; Stores the sum of array elements ; Find the sum of array element ; Store the value of sum % N ; Return the resultant value ; Driver Code | def minSumDifference ( ar , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ar [ i ] NEW_LINE DEDENT rem = sum % n NEW_LINE return rem * ( n - rem ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 8 , 5 , 2 , 1 , 11 , 7 , 10 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minSumDifference ( arr , N ) ) NEW_LINE DEDENT |
Count N | Python program for the above approach ; Function to find the value of x ^ y ; Stores the value of x ^ y ; Iterate until y is positive ; If y is odd ; Divide y by 2 ; Return the value of x ^ y ; Function to find the number of N - digit integers satisfying the given criteria ; Count of even positions ; Count of odd positions ; Return the resultant count ; Driver Code | import math NEW_LINE m = 10 ** 9 + 7 NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE while y > 0 : NEW_LINE INDENT if ( y & 1 ) != 0 : NEW_LINE INDENT res = ( res * x ) % m NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % m NEW_LINE DEDENT return res NEW_LINE DEDENT def countNDigitNumber ( n : int ) -> None : NEW_LINE INDENT ne = N // 2 + N % 2 NEW_LINE no = N // 2 NEW_LINE return power ( 4 , ne ) * power ( 5 , no ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( countNDigitNumber ( N ) % m ) NEW_LINE DEDENT |
Minimum jumps to traverse all integers in range [ 1 , N ] such that integer i can jump i steps | Utility function to find minimum steps ; Initialize count and result ; Traverse over the range [ 1 , N ] ; Update res ; Increment count ; Return res ; Driver Code ; Input ; Function call | def minSteps ( N ) : NEW_LINE INDENT count = 1 NEW_LINE res = 0 NEW_LINE for i in range ( 1 , N + 1 , count ) : NEW_LINE INDENT res = max ( res , count ) NEW_LINE count += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE print ( minSteps ( N ) ) NEW_LINE DEDENT |
Minimum jumps to traverse all integers in range [ 1 , N ] such that integer i can jump i steps | Python 3 implementation of the above approach ; Utility function to find minimum steps ; Driver code ; Input integer ; Function call | from math import sqrt NEW_LINE def minSteps ( N ) : NEW_LINE INDENT res = int ( ( sqrt ( 1 + 8 * N ) - 1 ) // 2 ) NEW_LINE return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE print ( minSteps ( N ) ) NEW_LINE DEDENT |
The dice problem | Function to find number written on the opposite face of the dice ; Stores number on opposite face of dice ; Print the answer ; Given value of N ; Function call to find number written on the opposite face of the dice | def oppositeFaceOfDice ( N ) : NEW_LINE INDENT ans = 7 - N NEW_LINE print ( ans ) NEW_LINE DEDENT N = 2 NEW_LINE oppositeFaceOfDice ( N ) NEW_LINE |
Count numbers from a given range that can be visited moving any number of steps from the range [ L , R ] | Function to count points from the range [ X , Y ] that can be reached by moving by L or R steps ; Initialize difference array ; Initialize Count ; Marking starting point ; Iterating from X to Y ; Accumulate difference array ; If diff_arr [ i ] is greater than 1 ; Updating difference array ; Visited point found ; Driver Code ; Given Input ; Function Call | def countReachablePoints ( X , Y , L , R ) : NEW_LINE INDENT diff_arr = [ 0 for i in range ( 100000 ) ] NEW_LINE count = 0 NEW_LINE diff_arr [ X ] = 1 NEW_LINE diff_arr [ X + 1 ] = - 1 NEW_LINE for i in range ( X , Y + 1 , 1 ) : NEW_LINE INDENT diff_arr [ i ] += diff_arr [ i - 1 ] NEW_LINE if ( diff_arr [ i ] >= 1 ) : NEW_LINE INDENT diff_arr [ i + L ] += 1 NEW_LINE diff_arr [ i + R + 1 ] -= 1 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 3 NEW_LINE Y = 12 NEW_LINE L = 2 NEW_LINE R = 3 NEW_LINE print ( countReachablePoints ( X , Y , L , R ) ) NEW_LINE DEDENT |
Count of triplets having sum of product of any two numbers with the third number equal to N | Function to find the SPF [ i ] using the Sieve Of Erastothenes ; Stores whether i is prime or not ; Initializing smallest factor as 2 for all even numbers ; Iterate for all odd numbers < N ; SPF of i for a prime is the number itself ; Iterate for all the multiples of the current prime number ; The value i is smallest prime factor for i * j ; Function to generate prime factors and its power ; Current prime factor of N ; Stores the powers of the current prime factor ; Find all the prime factors and their powers ; Return the total count of factors ; Function to count the number of triplets satisfying the given criteria ; Stores the count of resultant triplets ; Add the count all factors of N - z to the variable CountTriplet ; Return total count of triplets ; Driver Code ; S [ i ] stores the smallest prime factor for each element i ; Find the SPF [ i ] ; Function Call | def sieveOfEratosthenes ( N , s ) : NEW_LINE INDENT prime = [ False ] * ( N + 1 ) NEW_LINE for i in range ( 2 , N + 1 , 2 ) : NEW_LINE INDENT s [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , N + 1 , 2 ) : NEW_LINE INDENT if ( prime [ i ] == False ) : NEW_LINE INDENT s [ i ] = i NEW_LINE for j in range ( i , int ( N / i ) + 1 , 2 ) : NEW_LINE INDENT if ( prime [ i * j ] == False ) : NEW_LINE INDENT prime [ i * j ] = True NEW_LINE s [ i * j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def generatePrimeFactors ( N ) : NEW_LINE INDENT curr = s [ N ] NEW_LINE cnt = { s [ N ] : 1 } NEW_LINE while ( N > 1 ) : NEW_LINE INDENT N //= s [ N ] NEW_LINE if N and s [ N ] : NEW_LINE INDENT if cnt . get ( s [ N ] , 0 ) == 0 : NEW_LINE INDENT cnt [ s [ N ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ s [ N ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT if 0 in cnt : NEW_LINE INDENT cnt . pop ( 0 ) NEW_LINE DEDENT totfactor = 1 NEW_LINE for i in cnt . values ( ) : NEW_LINE INDENT totfactor *= i + 1 NEW_LINE DEDENT return totfactor NEW_LINE DEDENT def countTriplets ( N ) : NEW_LINE INDENT CountTriplet = 0 NEW_LINE for z in range ( 1 , N + 1 ) : NEW_LINE INDENT p = generatePrimeFactors ( N - z ) NEW_LINE if p > 1 : NEW_LINE INDENT CountTriplet += p NEW_LINE DEDENT DEDENT return CountTriplet + 1 NEW_LINE DEDENT N = 10 NEW_LINE s = [ 0 ] * ( N + 1 ) NEW_LINE sieveOfEratosthenes ( N , s ) NEW_LINE print ( countTriplets ( N ) ) NEW_LINE |
Minimum length of the subarray required to be replaced to make frequency of array elements equal to N / M | Function to find the minimum length of the subarray to be changed . ; Stores the frequencies of array elements ; Stores the number of array elements that are present more than N / M times ; Iterate over the range ; Increment the frequency ; If the frequency of all array elements are already N / M ; Stores the resultant length of the subarray ; The left and right pointers ; Iterate over the range ; If the current element is ; If the value of c is 0 , then find the possible answer ; Iterate over the range ; If the element at left is making it extra ; Update the left pointer ; Update the right pointer ; Return the resultant length ; Driver Code | def minimumSubarray ( arr , n , m ) : NEW_LINE INDENT mapu = [ 0 for i in range ( m + 1 ) ] NEW_LINE c = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mapu [ arr [ i ] ] += 1 NEW_LINE if ( mapu [ arr [ i ] ] == ( n // m ) + 1 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = n NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while ( r < n ) : NEW_LINE INDENT mapu [ arr [ r ] ] -= 1 NEW_LINE if ( mapu [ arr [ r ] ] == ( n // m ) ) : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT if ( c == 0 ) : NEW_LINE INDENT while ( l <= r and c == 0 ) : NEW_LINE INDENT ans = min ( ans , r - l + 1 ) NEW_LINE mapu [ arr [ l ] ] += 1 NEW_LINE if ( mapu [ arr [ l ] ] > ( n // m ) ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT r += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 1 , 2 ] NEW_LINE M = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( minimumSubarray ( arr , N , M ) ) NEW_LINE DEDENT |
Check if the sum of K least and most frequent array elements are equal or not | Function to compare the sum of K most and least occurrences ; Stores frequency of array element ; Stores the frequencies as indexes and putelements with the frequency in a vector ; Find the frequency ; Insert in the vector ; Stores the count of elements ; Traverse the frequency array ; Find the kleastfreqsum ; If the count is K , break ; Reinitialize the count to zero ; Traverse the frequency ; Find the kmostfreqsum ; If the count is K , break ; Comparing the sum ; Otherwise , return No ; Driver Code | def checkSum ( arr , n , k ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in m : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT freq = [ [ ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT f = m [ arr [ i ] ] NEW_LINE if ( f != - 1 ) : NEW_LINE INDENT freq [ f ] . append ( arr [ i ] ) NEW_LINE m [ arr [ i ] ] = - 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE kleastfreqsum = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for x in freq [ i ] : NEW_LINE INDENT kleastfreqsum += x NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT count = 0 NEW_LINE kmostfreqsum = 0 NEW_LINE i = n NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT for x in freq [ i ] : NEW_LINE INDENT kmostfreqsum += x NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( kleastfreqsum == kmostfreqsum ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 2 , 3 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( checkSum ( arr , N , K ) ) NEW_LINE DEDENT |
Print all numbers from a given range that are made up of consecutive digits | Function to find the consecutive digit numbers in the given range ; Initialize num as empty string ; Stores the resultant number ; Iterate over the range [ 1 , 9 ] ; Check if the current number is within range ; Iterate on the digits starting from i ; Checking the consecutive digits numbers starting from i and ending at j is within range or not ; Sort the numbers in the increasing order ; Driver Code ; Print the required numbers | def solve ( start , end ) : NEW_LINE INDENT num = " " NEW_LINE ans = [ ] NEW_LINE for i in range ( 1 , 10 , 1 ) : NEW_LINE INDENT num = str ( i ) NEW_LINE value = int ( num ) NEW_LINE if ( value >= start and value <= end ) : NEW_LINE INDENT ans . append ( value ) NEW_LINE DEDENT for j in range ( i + 1 , 10 , 1 ) : NEW_LINE INDENT num += str ( j ) NEW_LINE value = int ( num ) NEW_LINE if ( value >= start and value <= end ) : NEW_LINE INDENT ans . append ( value ) NEW_LINE DEDENT DEDENT DEDENT ans . sort ( ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 12 NEW_LINE R = 87 NEW_LINE ans = solve ( 12 , 87 ) NEW_LINE for it in ans : NEW_LINE INDENT print ( it , end = " β " ) NEW_LINE DEDENT DEDENT |
Minimum distance a person has to move in order to take a picture of every racer | Python3 program for the above approach ; Function to return the minimum distance the person has to move order to get the pictures ; To store the minimum ending point ; To store the maximum starting point ; Find the values of minSeg and maxSeg ; Impossible ; The person doesn 't need to move ; Get closer to the left point ; Get closer to the right point ; Driver code | import sys NEW_LINE def minDistance ( start , end , n , d ) : NEW_LINE INDENT left = - sys . maxsize NEW_LINE right = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT left = max ( left , start [ i ] ) NEW_LINE right = min ( right , end [ i ] ) NEW_LINE DEDENT if ( left > right ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( d >= left and d <= right ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( d < left ) : NEW_LINE INDENT return ( left - d ) NEW_LINE DEDENT if ( d > right ) : NEW_LINE INDENT return ( d - right ) NEW_LINE DEDENT DEDENT start = [ 0 , 2 , 4 ] NEW_LINE end = [ 7 , 14 , 6 ] NEW_LINE n = len ( start ) NEW_LINE d = 3 NEW_LINE print ( minDistance ( start , end , n , d ) ) NEW_LINE |
Maximum number of Armstrong Numbers present in a subarray of size K | Function to calculate the value of x raised to the power y in O ( log y ) ; Base Case ; If the power y is even ; Otherwise ; Function to calculate the order of the number , i . e . count of digits ; Stores the total count of digits ; Iterate until num is 0 ; Function to check a number is an Armstrong Number or not ; Find the order of the number ; Check for Armstrong Number ; If Armstrong number condition is satisfied ; Utility function to find the maximum sum of a subarray of size K ; If k is greater than N ; Find the sum of first subarray of size K ; Find the sum of the remaining subarray ; Return the maximum sum of subarray of size K ; Function to find all the Armstrong Numbers in the array ; Traverse the array arr [ ] ; If arr [ i ] is an Armstrong Number , then replace it by 1. Otherwise , 0 ; Return the resultant count ; Driver Code | def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( y % 2 == 0 ) : NEW_LINE INDENT return power ( x , y // 2 ) * power ( x , y // 2 ) NEW_LINE DEDENT return x * power ( x , y // 2 ) * power ( x , y // 2 ) NEW_LINE DEDENT def order ( num ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num ) : NEW_LINE INDENT count += 1 NEW_LINE num = num // 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def isArmstrong ( N ) : NEW_LINE INDENT r = order ( N ) NEW_LINE temp = N NEW_LINE sum = 0 NEW_LINE while ( temp ) : NEW_LINE INDENT d = temp % 10 NEW_LINE sum += power ( d , r ) NEW_LINE temp = temp // 10 NEW_LINE DEDENT return ( sum == N ) NEW_LINE DEDENT def maxSum ( arr , N , K ) : NEW_LINE INDENT if ( N < K ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT res += arr [ i ] NEW_LINE DEDENT curr_sum = res NEW_LINE for i in range ( K , N , 1 ) : NEW_LINE INDENT curr_sum += arr [ i ] - arr [ i - K ] NEW_LINE res = max ( res , curr_sum ) NEW_LINE DEDENT return res NEW_LINE DEDENT def maxArmstrong ( arr , N , K ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] = isArmstrong ( arr [ i ] ) NEW_LINE DEDENT return maxSum ( arr , N , K ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 28 , 2 , 3 , 6 , 153 , 99 , 828 , 24 ] NEW_LINE K = 6 NEW_LINE N = len ( arr ) NEW_LINE print ( maxArmstrong ( arr , N , K ) ) NEW_LINE DEDENT |
Count N | Function to calculate the power of n ^ k % p ; Update x if it is more than or equal to p ; In case x is divisible by p ; ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y / 2 ; Function to count the number of arrays satisfying required conditions ; Calculating N ^ K ; Driver Code | def power ( x , y , p ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % p NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def countArrays ( n , k ) : NEW_LINE INDENT mod = 1000000007 NEW_LINE ans = power ( n , k , mod ) NEW_LINE return ans NEW_LINE DEDENT n = 3 NEW_LINE k = 5 NEW_LINE ans = countArrays ( n , k ) NEW_LINE print ( ans ) NEW_LINE |
Count ways to replace ' ? ' in a Binary String to make the count of 0 s and 1 s same as that of another string | Function to find the factorial of the given number N ; Stores the factorial ; Iterate over the range [ 2 , N ] ; Return the resultant result ; Function to find the number of ways of choosing r objects from n distinct objects ; Function to find the number of ways to replace ' ? ' in string t to get the same count of 0 s and 1 s in the string S and T ; Traverse the string s ; If the current character is 1 ; Update the value of the sum1 ; Otherwise ; Traverse the string t ; If the current character is 1 , then update the value of sum2 ; If the current character is 0 ; Otherwise , update the value of K ; Check if P is greater than K or if K - P is odd ; Print the count of ways ; Driver Code | def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) // ( fact ( r ) * fact ( n - r ) ) NEW_LINE DEDENT def countWays ( s , t ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE K = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT sum1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum1 -= 1 NEW_LINE DEDENT DEDENT m = len ( t ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( t [ i ] == '1' ) : NEW_LINE INDENT sum2 += 1 NEW_LINE DEDENT elif ( t [ i ] == '0' ) : NEW_LINE INDENT sum2 -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT K += 1 NEW_LINE DEDENT DEDENT P = abs ( sum1 - sum2 ) NEW_LINE if ( P > K or ( K - P ) % 2 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT print ( nCr ( K , ( P + K ) // 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = "1010" NEW_LINE S2 = "10 ? ? " NEW_LINE countWays ( S1 , S2 ) NEW_LINE DEDENT |
Count pairs of indices having sum of indices same as the sum of elements at those indices | Function to find all possible pairs of the given array such that the sum of arr [ i ] + arr [ j ] is i + j ; Stores the total count of pairs ; Iterate over the range ; Iterate over the range ; Print the total count ; Driver code | def countPairs ( arr , N ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if arr [ i ] + arr [ j ] == i + j : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT DEDENT print ( answer ) NEW_LINE DEDENT arr = [ 0 , 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE |
Distribute R , B beans such that each packet has at least 1 R and 1 B bean with absolute difference at most D | Function to check if it is possible to distribute R red and B blue beans in packets such that the difference between the beans in each packet is atmost D ; Check for the condition to distributing beans ; Print the answer ; Distribution is not possible ; Driver Code | def checkDistribution ( R , B , D ) : NEW_LINE INDENT if ( max ( R , B ) <= min ( R , B ) * ( D + 1 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT R = 1 NEW_LINE B = 1 NEW_LINE D = 0 NEW_LINE checkDistribution ( R , B , D ) NEW_LINE |
Generate a sequence with product N such that for every pair of indices ( i , j ) and i < j , arr [ j ] is divisible by arr [ i ] | Python3 program for the above approach ; Function to calculate the prime factors of N with their count ; Initialize a vector , say v ; Initialize the count ; Count the number of divisors ; Divide the value of N by 2 ; For factor 2 divides it ; Find all prime factors ; Count their frequency ; Push it to the vector ; Push N if it is not 1 ; Function to print the array that have the maximum size ; Stores the all prime factor and their powers ; Traverse the vector and find the maximum power of prime factor ; If max size is less than 2 ; Otherwise ; Print the maximum size of sequence ; Print the final sequence ; Print the prime factor ; Print the last value of the sequence ; Driver Code | from math import sqrt NEW_LINE def primeFactor ( N ) : NEW_LINE INDENT v = [ ] NEW_LINE count = 0 NEW_LINE while ( ( N % 2 ) == 0 ) : NEW_LINE INDENT N >>= 1 NEW_LINE count += 1 NEW_LINE DEDENT if ( count ) : NEW_LINE INDENT v . append ( [ 2 , count ] ) NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( N ) ) + 1 , 2 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( N % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE N = N / i NEW_LINE DEDENT if ( count ) : NEW_LINE INDENT v . append ( [ i , count ] ) NEW_LINE DEDENT DEDENT if ( N > 2 ) : NEW_LINE INDENT v . append ( [ N , 1 ] ) NEW_LINE DEDENT return v NEW_LINE DEDENT def printAnswer ( n ) : NEW_LINE INDENT v = primeFactor ( n ) NEW_LINE maxi_size = 0 NEW_LINE prime_factor = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( maxi_size < v [ i ] [ 1 ] ) : NEW_LINE INDENT maxi_size = v [ i ] [ 1 ] NEW_LINE prime_factor = v [ i ] [ 0 ] NEW_LINE DEDENT DEDENT if ( maxi_size < 2 ) : NEW_LINE INDENT print ( 1 , n ) NEW_LINE DEDENT else : NEW_LINE INDENT product = 1 NEW_LINE print ( maxi_size ) NEW_LINE for i in range ( maxi_size - 1 ) : NEW_LINE INDENT print ( prime_factor , end = " β " ) NEW_LINE product *= prime_factor NEW_LINE DEDENT print ( n // product ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 360 NEW_LINE printAnswer ( N ) NEW_LINE DEDENT |
Check if it is possible to reach destination in even number of steps in an Infinite Matrix | Function to check destination can be reached from source in even number of steps ; Coordinates differences ; Minimum number of steps required ; Minsteps is even ; Minsteps is odd ; Driver Code ; Given Input ; Function Call | def IsEvenPath ( Source , Destination ) : NEW_LINE INDENT x_dif = abs ( Source [ 0 ] - Destination [ 0 ] ) NEW_LINE y_dif = abs ( Source [ 1 ] - Destination [ 1 ] ) NEW_LINE minsteps = x_dif + y_dif NEW_LINE if ( minsteps % 2 == 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 Source = [ 2 , 1 ] NEW_LINE Destination = [ 1 , 4 ] NEW_LINE IsEvenPath ( Source , Destination ) NEW_LINE DEDENT |
Find the closest Fraction to given fraction having minimum absolute difference | Function to find the absolute value of x ; Function to find the fraction with minimum absolute difference ; Initialize the answer variables ; Iterate over the range ; Nearest fraction ; x / y - d / i < x / y - A / B ( B * x - y * A ) * ( i * y ) > ( i * x - y * d ) * ( B * y ) ; Check for d + 1 ; Print the answer ; Driver Code | def ABS ( x ) : NEW_LINE INDENT return max ( x , - x ) NEW_LINE DEDENT def findFraction ( x , y , n ) : NEW_LINE INDENT A = - 1 NEW_LINE B = - 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT d = ( i * x ) // y NEW_LINE if ( d >= 0 and ( A == - 1 or ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) : NEW_LINE INDENT A = d NEW_LINE B = i NEW_LINE DEDENT d += 1 NEW_LINE if ( d >= 0 and ( A == - 1 or ABS ( B * x - y * A ) * ABS ( i * y ) > ABS ( i * x - y * d ) * ABS ( B * y ) ) ) : NEW_LINE INDENT A = d NEW_LINE B = i NEW_LINE DEDENT DEDENT print ( str ( A ) + " / " + str ( B ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 3 NEW_LINE y = 7 NEW_LINE n = 6 NEW_LINE findFraction ( x , y , n ) NEW_LINE DEDENT |
Represent a number N in base | Function to convert N to equivalent representation in base - 2 ; Stores the required answer ; Iterate until N is not equal to zero ; If N is Even ; Add char '0' in front of string ; Add char '1' in front of string ; Decrement N by 1 ; Divide N by - 2 ; If string is empty , that means N is zero ; Put '0' in string s ; Given Input ; Function Call | def BaseConversion ( N ) : NEW_LINE INDENT s = " " NEW_LINE while ( N != 0 ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT s = "0" + s NEW_LINE DEDENT else : NEW_LINE INDENT s = "1" + s NEW_LINE N -= 1 NEW_LINE DEDENT N /= - 2 NEW_LINE DEDENT if ( s == " " ) : NEW_LINE INDENT s = "0" NEW_LINE DEDENT return s NEW_LINE DEDENT N = - 9 NEW_LINE print ( BaseConversion ( N ) ) NEW_LINE |
Find instances at end of time frame after auto scaling | Python program for the above approach ; Function to find the number of instances after completion ; Traverse the array , arr [ ] ; If current element is less than 25 ; Divide instances by 2 ; If the current element is greater than 60 ; Double the instances ; Print the instances at the end of the traversal ; Driver Code ; Function Call | from math import ceil NEW_LINE def finalInstances ( instances , arr ) : NEW_LINE INDENT i = 0 NEW_LINE while i < len ( arr ) : NEW_LINE INDENT if arr [ i ] < 25 and instances > 1 : NEW_LINE INDENT instances = ceil ( instances / 2 ) NEW_LINE i += 10 NEW_LINE DEDENT elif arr [ i ] > 60 and instances <= 10 ** 8 : NEW_LINE INDENT instances *= 2 NEW_LINE i += 10 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( instances ) NEW_LINE DEDENT instances = 2 NEW_LINE arr = [ 25 , 23 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 76 , 80 ] NEW_LINE finalInstances ( instances , arr ) NEW_LINE |
Modify array by making all array elements equal to 0 by subtracting K ^ i from an array element in every i | Function to check whether all array elements can be made zero or not ; Stores if a power of K has already been subtracted or not ; Stores all the Kth power ; Iterate until X is less than INT_MAX ; Traverse the array arr [ ] ; Iterate over the range [ 0 , M ] ; If MP [ V [ j ] ] is 0 and V [ j ] is less than or equal to arr [ i ] ; If arr [ i ] is not 0 ; If i is less than N - 1 ; Otherwise , ; Driver code | def isMakeZero ( arr , N , K ) : NEW_LINE INDENT MP = { } NEW_LINE V = [ ] NEW_LINE X = 1 NEW_LINE while ( X > 0 and X < 10 ** 20 ) : NEW_LINE INDENT V . append ( X ) NEW_LINE X *= K NEW_LINE DEDENT for i in range ( 0 , N , 1 ) : NEW_LINE INDENT for j in range ( len ( V ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( V [ j ] not in MP and V [ j ] <= arr [ i ] ) : NEW_LINE INDENT arr [ i ] -= V [ j ] NEW_LINE MP [ V [ j ] ] = 1 NEW_LINE DEDENT DEDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i < N - 1 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT else : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT arr = [ 8 , 0 , 3 , 4 , 80 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( isMakeZero ( arr , N , K ) ) NEW_LINE |
Check whether the product of every subsequence is a perfect square or not | Python 3 program for the above approach ; Function to check if the product of every subsequence of the array is a perfect square or not ; Traverse the given array ; If arr [ i ] is a perfect square or not ; Return " Yes " ; Driver Code | from math import sqrt NEW_LINE def perfectSquare ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT p = sqrt ( arr [ i ] ) NEW_LINE if ( p * p != arr [ i ] ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 100 ] NEW_LINE N = len ( arr ) NEW_LINE print ( perfectSquare ( arr , N ) ) NEW_LINE DEDENT |
Count of subarrays with average K | Function to count subarray having average exactly equal to K ; To Store the final answer ; Calculate all subarrays ; Calculate required average ; Check if average is equal to k ; Required average found ; Increment res ; Driver code ; Given Input ; Function Call | def countKAverageSubarrays ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE for L in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for R in range ( L , n , 1 ) : NEW_LINE INDENT sum += arr [ R ] NEW_LINE len1 = ( R - L + 1 ) NEW_LINE if ( sum % len1 == 0 ) : NEW_LINE INDENT avg = sum // len1 NEW_LINE if ( avg == k ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 6 NEW_LINE arr = [ 12 , 5 , 3 , 10 , 4 , 8 , 10 , 12 , - 6 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countKAverageSubarrays ( arr , N , K ) ) NEW_LINE DEDENT |
Maximize minimum array element possible by exactly K decrements | Function to find the maximized minimum element of the array after performing given operation exactly K times ; Stores the minimum element ; Traverse the given array ; Update the minimum element ; Stores the required operations to make all elements equal to the minimum element ; Update required operations ; If reqOperations < K ; Decrement the value of K by reqOperations ; Update minElement ; Return minimum element ; Driver Code | def minimumElement ( arr , N , K ) : NEW_LINE INDENT minElement = arr [ 0 ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT minElement = min ( minElement , arr [ i ] ) ; NEW_LINE DEDENT reqOperations = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT reqOperations += arr [ i ] - minElement NEW_LINE DEDENT if ( reqOperations < K ) : NEW_LINE INDENT K -= reqOperations ; NEW_LINE minElement -= ( K + N - 1 ) // N ; NEW_LINE DEDENT return minElement ; NEW_LINE DEDENT arr = [ 10 , 10 , 10 , 10 ] ; NEW_LINE K = 7 ; NEW_LINE N = len ( arr ) NEW_LINE print ( minimumElement ( arr , N , K ) ) ; NEW_LINE |
Split the fraction into sum of multiple fractions having numerator as 1 | Function to split the fraction into distinct unit fraction ; To store answer ; While numerator is positive ; Finding x = ceil ( d / n ) ; Add 1 / x to list of ans ; Update fraction ; Given Input ; Function Call ; Print Answer | def FractionSplit ( n , d ) : NEW_LINE INDENT UnitFactions = [ ] NEW_LINE while ( n > 0 ) : NEW_LINE INDENT x = ( d + n - 1 ) // n NEW_LINE s = "1 / " + str ( x ) NEW_LINE UnitFactions . append ( s ) ; NEW_LINE n = n * x - d ; NEW_LINE d = d * x NEW_LINE DEDENT return UnitFactions ; NEW_LINE DEDENT n = 13 ; NEW_LINE d = 18 ; NEW_LINE res = FractionSplit ( n , d ) ; NEW_LINE for s in res : NEW_LINE INDENT print ( s + " , β " , end = " β " ) ; NEW_LINE DEDENT |
Find permutation of [ 1 , N ] such that ( arr [ i ] != i + 1 ) and sum of absolute difference between arr [ i ] and ( i + 1 ) is minimum | Function to generate the permutation of the first N natural numbers having sum of absolute difference between element and indices as minimum ; Initialize array arr [ ] from 1 to N ; Swap alternate positions ; Check N is greater than 1 and N is odd ; Swapping last two positions ; Print the permutation ; Driver Code | def findPermutation ( N ) : NEW_LINE INDENT arr = [ i + 1 for i in range ( N ) ] NEW_LINE for i in range ( 1 , N , 2 ) : NEW_LINE INDENT arr [ i ] , arr [ i - 1 ] = arr [ i - 1 ] , arr [ i ] NEW_LINE DEDENT if N % 2 and N > 1 : NEW_LINE INDENT arr [ - 1 ] , arr [ - 2 ] = arr [ - 2 ] , arr [ - 1 ] NEW_LINE DEDENT for i in arr : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE findPermutation ( N ) NEW_LINE DEDENT |
Find Array obtained after adding terms of AP for Q queries | Function to find array after performing the given query to the array elements ; Traverse the given query ; Traverse the given array ; Update the value of A [ i ] ; Update the value of curr ; Print the array elements ; Driver Code ; Function Call | def addAP ( A , Q , operations ) : NEW_LINE INDENT for L , R , a , d in operations : NEW_LINE INDENT curr = a NEW_LINE for i in range ( L - 1 , R ) : NEW_LINE INDENT A [ i ] += curr NEW_LINE curr += d NEW_LINE DEDENT DEDENT for i in A : NEW_LINE INDENT print ( i , end = ' β ' ) NEW_LINE DEDENT DEDENT A = [ 5 , 4 , 2 , 8 ] NEW_LINE Q = 2 NEW_LINE Query = [ ( 1 , 2 , 1 , 3 ) , ( 1 , 4 , 4 , 1 ) ] NEW_LINE addAP ( A , Q , Query ) NEW_LINE |
Maximize the number N by inserting given digit at any position | Function to find the maximum value of N after inserting the digit K ; Convert it into N to string ; Stores the maximum value of N after inserting K ; Iterate till all digits that are not less than K ; Add the current digit to the string result ; Add digit ' K ' to result ; Iterate through all remaining characters ; Add current digit to result ; Print the maximum number formed ; Driver Code | def maximizeNumber ( N , K ) : NEW_LINE INDENT s = str ( N ) NEW_LINE L = len ( s ) NEW_LINE result = " " NEW_LINE i = 0 NEW_LINE while ( ( i < L ) and ( K <= ( ord ( s [ i ] ) - ord ( '0' ) ) ) ) : NEW_LINE INDENT result += ( s [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT result += ( chr ( K + ord ( '0' ) ) ) NEW_LINE while ( i < L ) : NEW_LINE INDENT result += ( s [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6673 NEW_LINE K = 6 NEW_LINE maximizeNumber ( N , K ) NEW_LINE DEDENT |
Count of N | Function to find the value of X to the power Y ; Stores the value of X ^ Y ; If y is odd , multiply x with result ; Update the value of y and x ; Return the result ; Function to count number of arrays having element over the range [ 0 , 2 ^ K - 1 ] with Bitwise AND value 0 having maximum possible sum ; Print the value of N ^ K ; Driver Code | def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT y = y >> 1 NEW_LINE x = x * x NEW_LINE DEDENT return res NEW_LINE DEDENT def countArrays ( N , K ) : NEW_LINE INDENT print ( power ( N , K ) ) NEW_LINE DEDENT N = 5 ; NEW_LINE K = 6 ; NEW_LINE countArrays ( N , K ) NEW_LINE |
Minimum absolute value of ( K β arr [ i ] ) for all possible values of K over the range [ 0 , N β 1 ] | Function to find the minimum absolute value of ( K - arr [ i ] ) for each possible value of K over the range [ 0 , N - 1 ] | ; Traverse the given array arr [ ] ; Stores the mininimum distance to any array element arr [ i ] ; Check if there is no safe position smaller than i ; Check if the current position is between two safe positions ; Take the minimum of two distances ; Check if the current index is a safe position ; Check if there is no safe position greater than i ; Print the minimum distance ; Driver Code | def minimumDistance ( arr , N ) : NEW_LINE INDENT ind = 0 ; NEW_LINE prev = arr [ ind ] ; NEW_LINE s = len ( arr ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT distance = 10 ** 9 ; NEW_LINE if ( i < arr [ 0 ] ) : NEW_LINE INDENT distance = arr [ 0 ] - i ; NEW_LINE DEDENT elif ( i >= prev and ind + 1 < s and i <= arr [ ind + 1 ] ) : NEW_LINE INDENT distance = min ( i - prev , arr [ ind + 1 ] - i ) ; NEW_LINE if ( i == arr [ ind + 1 ] ) : NEW_LINE INDENT distance = 0 ; NEW_LINE prev = arr [ ind + 1 ] ; NEW_LINE ind += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT distance = i - prev ; NEW_LINE DEDENT print ( distance , end = " β " ) ; NEW_LINE DEDENT DEDENT N = 5 ; NEW_LINE arr = [ 0 , 4 ] ; NEW_LINE minimumDistance ( arr , N ) ; NEW_LINE |
Count of pairs in Array such that bitwise AND of XOR of pair and X is 0 | Function to find the number of pairs that satisfy the given criteria i . e . , i < j and ( arr [ i ] ^ arr [ j ] ) & X is 0 ; Stores the resultant count of pairs ; Iterate over the range [ 0 , N ) ; Iterate over the range ; Check for the given condition ; Return the resultant count ; Driver Code | def countOfPairs ( arr , N , X ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( ( ( arr [ i ] ^ arr [ j ] ) & X ) == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 5 , 4 , 6 , 7 ] NEW_LINE X = 6 NEW_LINE N = len ( arr ) NEW_LINE print ( countOfPairs ( arr , N , X ) ) NEW_LINE DEDENT |
Count of pairs in Array such that bitwise AND of XOR of pair and X is 0 | Function to find the number of pairs that satisfy the given criteria i . e . , i < j and ( arr [ i ] ^ arr [ j ] ) & X is 0 ; Stores the resultant count of pairs ; Initialize the dictionary M ; Populate the map ; Count number of pairs for every element in map using mathematical concept of combination ; As nC2 = n * ( n - 1 ) / 2 ; Return the resultant count ; Driver Code | def countOfPairs ( arr , N , X ) : NEW_LINE INDENT count = 0 NEW_LINE M = dict ( ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT k = arr [ i ] & X NEW_LINE if k in M : NEW_LINE INDENT M [ k ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT M [ k ] = 1 NEW_LINE DEDENT DEDENT for m in M . keys ( ) : NEW_LINE INDENT p = M [ m ] NEW_LINE count += p * ( p - 1 ) // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 5 , 4 , 6 , 7 ] NEW_LINE X = 6 NEW_LINE N = len ( arr ) NEW_LINE print ( countOfPairs ( arr , N , X ) ) NEW_LINE DEDENT |
Count of square submatrices with average at least K | Function to count submatrixes with average greater than or equals to K ; Stores count of submatrices ; Stores the prefix sum of matrix ; Iterate over the range [ 1 , N ] ; Iterate over the range [ 1 , M ] ; Update the prefix sum ; Iterate over the range [ 1 , N ] ; Iterate over the range [ 1 , M ] ; Iterate until l and r are greater than 0 ; Update count ; Stores sum of submatrix with bottom right corner as ( i , j ) and top left corner as ( l , r ) ; If sum1 is less than or equal to sum2 ; Increment cnt by 1 ; Return cnt as the answer ; Driver Code ; Given Input ; Function Call | def cntMatrices ( arr , N , M , K ) : NEW_LINE INDENT cnt = 0 NEW_LINE pre = [ [ 0 for i in range ( M + 1 ) ] for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 ) : NEW_LINE INDENT pre [ i ] [ j ] = ( arr [ i - 1 ] [ j - 1 ] + pre [ i - 1 ] [ j ] + pre [ i ] [ j - 1 ] - pre [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 ) : NEW_LINE INDENT l , r = i , j NEW_LINE while l > 0 and r > 0 : NEW_LINE INDENT sum1 = ( K * ( i - l + 1 ) * ( i - r + 1 ) ) NEW_LINE sum2 = ( pre [ i ] [ j ] - pre [ l - 1 ] [ r ] - pre [ l ] [ r - 1 ] + pre [ l - 1 ] [ r - 1 ] ) NEW_LINE if ( sum1 <= sum2 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT l -= 1 NEW_LINE r -= 1 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 2 , 2 , 3 ] , [ 3 , 4 , 5 ] , [ 4 , 5 , 5 ] ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE M = len ( arr [ 0 ] ) NEW_LINE print ( cntMatrices ( arr , N , M , K ) ) NEW_LINE DEDENT |
Concatenate the Array of elements into a single element | Python3 program for the above approach ; Function to find the integer value obtained by joining array elements together ; Stores the resulting integer value ; Traverse the array arr [ ] ; Stores the count of digits of arr [ i ] ; Update ans ; Increment ans by arr [ i ] ; Return the ans ; Driver Code ; Input ; Function call | import math NEW_LINE def ConcatenateArr ( arr , N ) : NEW_LINE INDENT ans = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT l = math . floor ( math . log10 ( arr [ i ] ) + 1 ) NEW_LINE ans = ans * math . pow ( 10 , l ) NEW_LINE ans += arr [ i ] NEW_LINE DEDENT return int ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 23 , 456 ] NEW_LINE N = len ( arr ) NEW_LINE print ( ConcatenateArr ( arr , N ) ) NEW_LINE DEDENT |
Count of integers K in range [ 0 , N ] such that ( K XOR K + 1 ) equals ( K + 2 XOR K + 3 ) | Function to count all the integers less than N satisfying the given condition ; Store the count of even numbers less than N + 1 ; Return the count ; Driver Code ; Given Input ; Function Call | def countXor ( N ) : NEW_LINE INDENT cnt = N // 2 + 1 NEW_LINE return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( countXor ( N ) ) NEW_LINE DEDENT |
Maximize absolute displacement from origin by moving on X | Recursive function to find the maximum absolute displacement from origin by performing the given set of moves ; If i is equal to N ; If S [ i ] is equal to 'L ; If S [ i ] is equal to 'R ; If S [ i ] is equal to '? ; Function to find the maximum absolute displacement from the origin ; Return the maximum absolute displacement ; Input ; Function call | def DistRecursion ( S , i , dist ) : NEW_LINE INDENT if i == len ( S ) : NEW_LINE INDENT return abs ( dist ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if S [ i ] == ' L ' : NEW_LINE INDENT return DistRecursion ( S , i + 1 , dist - 1 ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if S [ i ] == ' R ' : NEW_LINE INDENT return DistRecursion ( S , i + 1 , dist + 1 ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT return max ( DistRecursion ( S , i + 1 , dist - 1 ) , DistRecursion ( S , i + 1 , dist + 1 ) ) NEW_LINE DEDENT def maxDistance ( S ) : NEW_LINE INDENT return DistRecursion ( S , 0 , 0 ) NEW_LINE DEDENT S = " ? RRR ? " NEW_LINE print ( maxDistance ( S ) ) NEW_LINE |
Count of pairs in range [ P , Q ] with numbers as multiple of R and their product lie in range [ P * Q / 4 , P * Q ] | Function to find the number of pairs such that both the elements are in the range [ P , Q ] and the numbers should be multiple of R , and the product of numbers should lie in the range [ P * Q / 4 , P * Q ] ; Store multiple of r in range of [ P , Q ] ; Itearte in the range [ p , q ] ; Vector to store pair of answer ; Iterate through the vector v ; Iterate in the range [ i + 1 , v . size ( ) - 1 ] ; If pair follow this condition insert the pair in vector ans ; If no pair satisfy the conditions , pr - 1 ; Print the pairs which satisfy the given condition ; Driver Code ; Given Input ; Function Call | def findPairs ( p , q , r ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( p , q + 1 ) : NEW_LINE INDENT if ( i % r == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT ans = [ ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( v ) ) : NEW_LINE INDENT if ( v [ i ] * v [ j ] >= p * q // 4 and v [ i ] * v [ j ] <= p * q ) : NEW_LINE INDENT ans . append ( [ v [ i ] , v [ j ] ] ) NEW_LINE DEDENT DEDENT DEDENT if ( len ( ans ) == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] [ 0 ] , ans [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 14 NEW_LINE q = 30 NEW_LINE r = 5 NEW_LINE findPairs ( p , q , r ) NEW_LINE DEDENT |
Print rectangular pattern with given center | Function to print the matrix filled with rectangle pattern having center coordinates are c1 , c2 ; Iterate in the range [ 0 , n - 1 ] ; Iterate in the range [ 0 , n - 1 ] ; Given Input ; Function Call | def printRectPattern ( c1 , c2 , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( max ( abs ( c1 - i ) , abs ( c2 - j ) ) , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT DEDENT c1 = 2 NEW_LINE c2 = 2 NEW_LINE n = 5 NEW_LINE printRectPattern ( c1 , c2 , n ) NEW_LINE |
Count of numbers in range [ L , R ] with LSB as 0 in their Binary representation | Function to return the count of required numbers ; If rightmost bit is 0 ; Return the required count ; Driver code ; Call function countNumbers | def countNumbers ( l , r ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( ( i & 1 ) == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT l = 10 NEW_LINE r = 20 NEW_LINE print ( countNumbers ( l , r ) ) NEW_LINE |
Count of numbers in range [ L , R ] with LSB as 0 in their Binary representation | Function to return the count of required numbers ; Count of numbers in range which are divisible by 2 ; Driver code | def countNumbers ( l , r ) : NEW_LINE INDENT return ( ( r // 2 ) - ( l - 1 ) // 2 ) NEW_LINE DEDENT l = 10 NEW_LINE r = 20 NEW_LINE print ( countNumbers ( l , r ) ) NEW_LINE |
Length of longest Fibonacci subarray | Python3 program for the above approach ; A utility function that returns true if x is perfect square ; Returns true if n is a Fibonacci Number , else false ; Here n is fibonacci if one of 5 * n * n + 4 or 5 * n * n - 4 or both is a perfect square ; Function to find the length of the largest sub - array of an array every element of whose is a Fibonacci number ; Traverse the array arr ; Check if arr [ i ] is a Fibonacci number ; stores the maximum length of the Fibonacci number subarray ; Finally , return the maximum length ; Driver code ; Given Input ; Function Call | import math NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT s = int ( math . sqrt ( x ) ) NEW_LINE if s * s == x : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def isFibonacci ( n ) : NEW_LINE INDENT return ( isPerfectSquare ( 5 * n * n + 4 ) or isPerfectSquare ( 5 * n * n - 4 ) ) NEW_LINE DEDENT def contiguousFibonacciNumber ( arr , n ) : NEW_LINE INDENT current_length = 0 NEW_LINE max_length = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if isFibonacci ( arr [ i ] ) : NEW_LINE INDENT current_length += 1 NEW_LINE DEDENT else : NEW_LINE INDENT current_length = 0 NEW_LINE DEDENT max_length = max ( max_length , current_length ) NEW_LINE DEDENT return max_length NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 8 , 21 , 5 , 3 , 28 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( contiguousFibonacciNumber ( arr , n ) ) NEW_LINE DEDENT |
Minimum number of flips required such that a Binary Matrix doesn 't contain any path from the top left to the bottom right consisting only of 0s | The four direction coordinates changes from the current cell ; Function that returns true if there exists any path from the top - left to the bottom - right cell of 0 s ; If the bottom - right cell is reached ; Update the cell to 1 ; Traverse in all four directions ; Find the new coordinates ; If the new cell is valid ; Recursively call DFS ; If path exists , then return true ; Return false , if there doesn 't exists any such path ; Function to flip the minimum number of cells such that there doesn 't exists any such path from (0, 0) to (N - 1, M - 1) cell consisting of 0s ; Case 1 : If no such path exists already ; Case 2 : If there exists only one path ; Case 3 : If there exists two - path ; Driver Code | direction = [ [ - 1 , 0 ] , [ 0 , 1 ] , [ 0 , - 1 ] , [ 1 , 0 ] ] NEW_LINE def dfs ( i , j , N , M ) : NEW_LINE INDENT global matrix NEW_LINE if ( i == N - 1 and j == M - 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT matrix [ i ] [ j ] = 1 NEW_LINE for k in range ( 4 ) : NEW_LINE INDENT newX = i + direction [ k ] [ 0 ] NEW_LINE newY = j + direction [ k ] [ 1 ] NEW_LINE if ( newX >= 0 and newX < N and newY >= 0 and newY < M and matrix [ newX ] [ newY ] == 0 ) : NEW_LINE INDENT if ( dfs ( newX , newY , N , M ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT def solve ( ) : NEW_LINE INDENT global matrix NEW_LINE N = len ( matrix ) NEW_LINE M = len ( matrix [ 0 ] ) NEW_LINE if ( not dfs ( 0 , 0 , N , M ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( not dfs ( 0 , 0 , N , M ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 0 , 1 , 0 , 0 ] , [ 0 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] ] NEW_LINE print ( solve ( ) ) NEW_LINE DEDENT |
Maximize product of subarray sum with its maximum element | Function to find the maximum product of the sum of the subarray with its maximum element ; Traverse the array arr [ ] ; Increment currSum by a [ i ] ; Maximize the value of currMax ; Maximize the value of largestSum ; If currSum goes less than 0 then update currSum = 0 ; Return the resultant value ; Function to maximize the product of the sum of the subarray with its maximum element ; Find the largest sum of the subarray ; Multiply each array element with - 1 ; Find the largest sum of the subarray with negation of all array element ; Return the resultant maximum value ; Driver Code | def Kadane ( arr , n ) : NEW_LINE INDENT largestSum = 0 NEW_LINE currMax = 0 NEW_LINE currSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT currSum += arr [ i ] NEW_LINE currMax = max ( currMax , arr [ i ] ) NEW_LINE largestSum = max ( largestSum , currMax * currSum ) NEW_LINE if ( currSum < 0 ) : NEW_LINE INDENT currMax = 0 NEW_LINE currSum = 0 NEW_LINE DEDENT DEDENT return largestSum NEW_LINE DEDENT def maximumWeight ( arr , n ) : NEW_LINE INDENT largestSum = Kadane ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = - arr [ i ] NEW_LINE DEDENT largestSum = max ( largestSum , Kadane ( arr , n ) ) NEW_LINE return largestSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 3 , 8 , - 2 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumWeight ( arr , N ) ) NEW_LINE DEDENT |
Partition an array into two subsets with equal count of unique elements | Function to partition the array into two subsets such that count of unique elements in both subsets is the same ; Stores the subset number for each array elements ; Stores the count of unique array elements ; Stores the frequency of elements ; Traverse the array ; Count of elements having a frequency of 1 ; Check if there exists any element with frequency > 2 ; Count of elements needed to have frequency exactly 1 in each subset ; Initialize all values in the array ans [ ] as 1 ; Traverse the array ans [ ] ; This array element is a part of first subset ; Half array elements with frequency 1 are part of the second subset ; If count of elements is exactly 1 are odd and has no element with frequency > 2 ; If count of elements that occurs exactly once are even ; Print the result ; If the count of elements has exactly 1 frequency are odd and there is an element with frequency greater than 2 ; Print the result ; Driver Codea | def arrayPartition ( a , n ) : NEW_LINE INDENT ans = [ 0 ] * n NEW_LINE cnt = 0 NEW_LINE ind , flag = 0 , 0 NEW_LINE mp = { } NEW_LINE for i in a : NEW_LINE INDENT mp [ i ] = mp . get ( i , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ( a [ i ] in mp ) and mp [ a [ i ] ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if ( mp [ a [ i ] ] > 2 and flag == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE ind = i NEW_LINE DEDENT DEDENT p = ( cnt + 1 ) // 2 NEW_LINE ans1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans [ i ] = 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ( a [ i ] in mp ) and mp [ a [ i ] ] == 1 and ans1 < p ) : NEW_LINE INDENT ans [ i ] = 1 NEW_LINE ans1 += 1 NEW_LINE DEDENT elif ( ( a [ i ] in mp ) and mp [ a [ i ] ] == 1 ) : NEW_LINE INDENT ans [ i ] = 2 NEW_LINE DEDENT DEDENT if ( cnt % 2 == 1 and flag == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT if ( cnt % 2 == 0 ) : NEW_LINE INDENT print ( * ans ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( ind == i ) : NEW_LINE INDENT print ( 2 , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 3 , 4 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE arrayPartition ( arr , N ) NEW_LINE DEDENT |
Modify a given array by replacing each element with the sum or product of their digits based on a given condition | Function to modify the given array as per the given conditions ; Traverse the given array arr [ ] ; Initialize the count of even and odd digits ; Initialize temp with the current array element ; For count the number of even digits ; Increment the odd count ; Otherwise ; Divide temp by 10 ; Performe addition ; Performe multiplication ; Otherwise ; Driver Code | def evenOdd ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT even_digits = 0 ; NEW_LINE odd_digits = 0 ; NEW_LINE temp = arr [ i ] ; NEW_LINE while ( temp ) : NEW_LINE INDENT if ( ( temp % 10 ) & 1 ) : NEW_LINE INDENT odd_digits += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT even_digits += 1 ; NEW_LINE DEDENT temp = temp // 10 NEW_LINE DEDENT if ( even_digits > odd_digits ) : NEW_LINE INDENT res = 0 ; NEW_LINE while ( arr [ i ] ) : NEW_LINE INDENT res += arr [ i ] % 10 ; NEW_LINE arr [ i ] = arr [ i ] // 10 ; NEW_LINE DEDENT print ( res , end = " β " ) ; NEW_LINE DEDENT elif ( odd_digits > even_digits ) : NEW_LINE INDENT res = 1 ; NEW_LINE while ( arr [ i ] ) : NEW_LINE INDENT res *= arr [ i ] % 10 ; NEW_LINE arr [ i ] = arr [ i ] // 10 NEW_LINE DEDENT print ( res , end = " β " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT DEDENT arr = [ 113 , 141 , 214 , 3186 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE evenOdd ( arr , N ) ; NEW_LINE |
Find prime factors of Z such that Z is product of all even numbers till N that are product of two distinct prime numbers | Function to print the prime factorization of the product of all numbers <= N that are even and can be expressed as a product of two distinct prime numbers ; Sieve of Eratosthenese ; Store prime numbers in the range [ 3 , N / 2 ] ; Print the coefficient of 2 in the prime factorization ; Print the coefficients of other primes ; Driver code ; Input ; Function calling | def primeFactorization ( N ) : NEW_LINE INDENT sieve = [ 0 for i in range ( N // 2 + 1 ) ] NEW_LINE for i in range ( 2 , N // 2 + 1 , 1 ) : NEW_LINE INDENT if ( sieve [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i * i , N // 2 + 1 , i ) : NEW_LINE INDENT sieve [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT prime = [ ] NEW_LINE for i in range ( 3 , N // 2 + 1 , 1 ) : NEW_LINE INDENT if ( sieve [ i ] == 0 ) : NEW_LINE INDENT prime . append ( i ) NEW_LINE DEDENT DEDENT x = len ( prime ) NEW_LINE print ( "2 - > " , x ) NEW_LINE for i in prime : NEW_LINE INDENT print ( i , " - > 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 18 NEW_LINE primeFactorization ( N ) NEW_LINE DEDENT |
Sum of the first M elements of Array formed by infinitely concatenating given array | Function to find the sum of first M numbers formed by the infinite concatenation of the array A [ ] ; Stores the resultant sum ; Iterate over the range [ 0 , M - 1 ] ; Add the value A [ i % N ] to sum ; Return the resultant sum ; Driver Code | def sumOfFirstM ( A , N , M ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT sum = sum + A [ i % N ] NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE M = 5 NEW_LINE N = len ( arr ) NEW_LINE print ( sumOfFirstM ( arr , N , M ) ) NEW_LINE DEDENT |
Check if it is possible to reach M from 0 by given paths | Function to check if it is possible to reach M from 0 ; Stores the farther point that can reach from 1 point ; Stores the farthest point it can go for each index i ; Initialize rightMost [ i ] with 0 ; Traverse the array ; Update the rightMost position reached from a1 ; Find the farthest point it can reach from i ; If point < can be reached ; Driver Code | def canReach0toM ( a , n , m ) : NEW_LINE INDENT rightMost = [ 0 for i in range ( m + 1 ) ] NEW_LINE dp = [ 0 for i in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT rightMost [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT a1 = a [ i ] [ 0 ] NEW_LINE b1 = a [ i ] [ 1 ] NEW_LINE rightMost [ a1 ] = max ( rightMost [ a1 ] , b1 ) NEW_LINE DEDENT i = m NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT dp [ i ] = i NEW_LINE j = min ( m , rightMost [ i ] ) NEW_LINE while ( j > i ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ j ] ) NEW_LINE j -= 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( dp [ 0 ] >= m ) : 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 = [ [ 0 , 2 ] , [ 2 , 2 ] , [ 2 , 5 ] , [ 4 , 5 ] ] NEW_LINE M = 5 NEW_LINE N = len ( arr ) NEW_LINE canReach0toM ( arr , N , M ) NEW_LINE DEDENT |
Count of non co | Recursive program to return gcd of two numbers ; Function to count the number of non co - prime pairs for each query ; Traverse the array arr [ ] ; Stores the count of non co - prime pairs ; Iterate over the range [ 1 , x ] ; Iterate over the range [ x , y ] ; If gcd of current pair is greater than 1 ; Driver code ; Given Input ; 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 countPairs ( arr , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT count = 0 NEW_LINE for x in range ( 1 , arr [ i ] + 1 ) : NEW_LINE INDENT for y in range ( x , arr [ i ] + 1 ) : NEW_LINE INDENT if gcd ( x , y ) > 1 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 10 , 20 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT |
Maximum number of multiplication by 3 or division by 2 operations possible on an array | Function to count maximum number of multiplication by 3 or division by 2 operations that can be performed ; Stores the maximum number of operations possible ; Traverse the array arr [ ] ; Iterate until arr [ i ] is even ; Increment count by 1 ; Update arr [ i ] ; Return the value of Count as the answer ; Given Input ; Function Call | def maximumTurns ( arr , N ) : NEW_LINE INDENT Count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT while ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT Count += 1 NEW_LINE arr [ i ] = arr [ i ] // 2 NEW_LINE DEDENT DEDENT return Count NEW_LINE DEDENT arr = [ 5 , 2 , 4 ] NEW_LINE M = 3 NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( maximumTurns ( arr , N ) ) NEW_LINE |
Distribute the white and black objects into maximum groups under certain constraints | Function to check if it is possible to distribute W and B into maximum groups possible ; If W is greater than B , swap them ; Distribution is not possible ; Distribution is possible ; Driver code ; Input ; Function call | def isPossible ( W , B , D ) : NEW_LINE INDENT if ( W > B ) : NEW_LINE INDENT temp = W NEW_LINE W = B NEW_LINE B = temp NEW_LINE DEDENT if ( B > W * ( D + 1 ) ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT W = 2 NEW_LINE B = 5 NEW_LINE D = 2 NEW_LINE isPossible ( W , B , D ) NEW_LINE DEDENT |
Find the maximum GCD possible for some pair in a given range [ L , R ] | Function to calculate GCD ; Function to calculate maximum GCD in a range ; Variable to store the answer ; If Z has two multiples in [ L , R ] ; Update ans ; Return the value ; Input ; 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 maxGCDInRange ( L , R ) : NEW_LINE INDENT ans = 1 NEW_LINE for Z in range ( R , 1 , - 1 ) : NEW_LINE INDENT if ( ( ( R // Z ) - ( L - 1 ) // Z ) > 1 ) : NEW_LINE INDENT ans = Z NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT L = 102 NEW_LINE R = 139 NEW_LINE print ( maxGCDInRange ( L , R ) ) NEW_LINE |
Number of ways to form a number with maximum Ks in it | Function to calculate number of ways a number can be formed that has the maximum number of Ks ; Convert to string ; Calculate length of subarrays that can contribute to the answer ; Count length of subarray where adjacent digits add up to K ; Current subarray can contribute to the answer only if it is odd ; Return the answer ; Driver code ; Input ; Function call | def noOfWays ( N , K ) : NEW_LINE INDENT S = str ( N ) NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , len ( S ) ) : NEW_LINE INDENT count = 1 NEW_LINE while ( i < len ( S ) and ord ( S [ i ] ) + ord ( S [ i - 1 ] ) - 2 * ord ( '0' ) == K ) : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( count % 2 ) : NEW_LINE INDENT ans *= ( count + 1 ) // 2 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1454781 NEW_LINE K = 9 NEW_LINE print ( noOfWays ( N , K ) ) NEW_LINE DEDENT |
Minimum bit swaps between given numbers to make their Bitwise OR equal to Bitwise AND | Function for counting number of set bit ; Function to return the count of minimum operations required ; cnt to count the number of bits set in A and in B ; If odd numbers of total set bits ; one_zero = 1 in A and 0 in B at ith bit similarly for zero_one ; When bitpos is set in B , unset in B ; When bitpos is set in A , unset in B ; Number of moves is half of number pairs of each group ; Odd number pairs ; Driver code ; Input ; Function call to compute the result | def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def minOperations ( A , B ) : NEW_LINE INDENT cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE cnt1 += countSetBits ( A ) NEW_LINE cnt2 += countSetBits ( B ) NEW_LINE if ( ( cnt1 + cnt2 ) % 2 != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT oneZero = 0 NEW_LINE zeroOne = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( max ( cnt1 , cnt2 ) ) : NEW_LINE INDENT bitpos = 1 << i NEW_LINE if ( ( not ( bitpos & A ) ) and ( bitpos & B ) ) : NEW_LINE INDENT zeroOne += 1 NEW_LINE DEDENT if ( ( bitpos & A ) and ( not ( bitpos & B ) ) ) : NEW_LINE INDENT oneZero += 1 NEW_LINE DEDENT DEDENT ans = ( zeroOne // 2 ) + ( oneZero // 2 ) NEW_LINE if ( zeroOne % 2 != 0 ) : NEW_LINE INDENT ans += 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 27 NEW_LINE B = 5 NEW_LINE print ( minOperations ( A , B ) ) NEW_LINE DEDENT |
Largest sum subarray of size K containing consecutive elements | Python3 program for the above approach ; Function to find the largest sum subarray such that it contains K consecutive elements ; Stores sum of subarray having K consecutive elements ; Stores the maximum sum among all subarrays of size K having consecutive elements ; Traverse the array ; Store K elements of one subarray at a time ; Sort the duplicate array in ascending order ; Checks if elements in subarray are consecutive or not ; Traverse the k elements ; If not consecutive , break ; If flag is true update the maximum sum ; Stores the sum of elements of the current subarray ; Update the max_sum ; Reset curr_sum ; Return the result ; Driver Code | import sys NEW_LINE def maximumSum ( A , N , K ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE max_sum = - sys . maxsize - 1 NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT dupl_arr = A [ i : i + K ] NEW_LINE dupl_arr . sort ( ) NEW_LINE flag = True NEW_LINE for j in range ( 1 , K , 1 ) : NEW_LINE INDENT if ( dupl_arr [ j ] - dupl_arr [ j - 1 ] != 1 ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT temp = 0 NEW_LINE curr_sum = temp NEW_LINE curr_sum = sum ( dupl_arr ) NEW_LINE max_sum = max ( max_sum , curr_sum ) NEW_LINE curr_sum = 0 NEW_LINE DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 12 , 9 , 8 , 10 , 15 , 1 , 3 , 2 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( maximumSum ( arr , N , K ) ) NEW_LINE DEDENT |
Find the count of Smith Brothers Pairs in a given Array | Python3 program for the above approach ; Array to store all prime less than and equal to MAX ; Utility function for sieve of sundaram ; Main logic of Sundaram . ; Since 2 is a prime number ; only primes are selected ; Function to check whether a number is a smith number . ; Find sum the digits of prime factors of n ; Add its digits of prime factors to pDigitSum . ; One prime factor is still to be summed up ; Now sum the digits of the original number ; Return the answer ; Function to check if X and Y are a Smith Brother Pair ; Function to find pairs from array ; Iterate through all pairs ; Increment count if there is a smith brother pair ; Driver code ; Preprocessing ; Input ; Function call | from math import sqrt NEW_LINE MAX = 10000 NEW_LINE primes = [ ] NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ 0 for i in range ( MAX // 2 + 100 ) ] NEW_LINE j = 0 NEW_LINE for i in range ( 1 , int ( ( sqrt ( MAX ) - 1 ) / 2 ) + 1 , 1 ) : NEW_LINE INDENT for j in range ( ( i * ( i + 1 ) ) << 1 , MAX // 2 + 1 , j + 2 * i + 1 ) : NEW_LINE INDENT marked [ j ] = True NEW_LINE DEDENT DEDENT primes . append ( 2 ) NEW_LINE for i in range ( 1 , MAX // 2 + 1 , 1 ) : NEW_LINE INDENT if ( marked [ i ] == False ) : NEW_LINE INDENT primes . append ( 2 * i + 1 ) NEW_LINE DEDENT DEDENT DEDENT def isSmith ( n ) : NEW_LINE INDENT original_no = n NEW_LINE pDigitSum = 0 NEW_LINE i = 0 NEW_LINE while ( primes [ i ] <= n // 2 ) : NEW_LINE INDENT while ( n % primes [ i ] == 0 ) : NEW_LINE INDENT p = primes [ i ] NEW_LINE n = n // p NEW_LINE while ( p > 0 ) : NEW_LINE INDENT pDigitSum += ( p % 10 ) NEW_LINE p = p // 10 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT if ( n != 1 and n != original_no ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT pDigitSum = pDigitSum + n % 10 NEW_LINE n = n // 10 NEW_LINE DEDENT DEDENT sumDigits = 0 NEW_LINE while ( original_no > 0 ) : NEW_LINE INDENT sumDigits = sumDigits + original_no % 10 NEW_LINE original_no = original_no // 10 NEW_LINE DEDENT return ( pDigitSum == sumDigits ) NEW_LINE DEDENT def isSmithBrotherPair ( X , Y ) : NEW_LINE INDENT return ( isSmith ( X ) and isSmith ( Y ) and abs ( X - Y ) == 1 ) NEW_LINE DEDENT def countSmithBrotherPairs ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N , 1 ) : NEW_LINE INDENT if ( isSmithBrotherPair ( A [ i ] , A [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sieveSundaram ( ) NEW_LINE A = [ 728 , 729 , 28 , 2964 , 2965 ] NEW_LINE N = len ( A ) NEW_LINE print ( countSmithBrotherPairs ( A , N ) ) NEW_LINE DEDENT |
Count pair sums that are factors of the sum of the array | Function to find the number of pairs whose sums divides the sum of array ; Initialize the totalSum and count as 0 ; Calculate the total sum of array ; Generate all possible pairs ; If the sum is a factor of totalSum or not ; Increment count by 1 ; Print the total count obtained ; Driver Code | def countPairs ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE totalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N , 1 ) : NEW_LINE INDENT if ( totalSum % ( arr [ i ] + arr [ j ] ) == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT |
Maximize average of the ratios of N pairs by M increments | Function to find the change in the ratio in pair after applying operation ; Stores the current ratio ; Stores the new ratio ; Stores the increase in ratio ; Returns the change ; Function to find the maximum average of the ratio of the pairs by applying M increments ; Stores the required result ; Declare a priority queue for storing the increments ; Store the increase in the ratio after applying one operation ; Push the increased value and index value in priority queue ; Store the ratio ; Update the value of sum ; Iterate while M > 0 ; Add the maximum change to the sum ; Remove the element from the priority queue ; Increase the pairs elements by 1 on which operation is applied ; Push the updated change of the pair in priority queue ; Decrease the operation count ; Update the value of the sum by dividing it by N ; Return the result ; Driver Code | def change ( pas , total ) : NEW_LINE INDENT currentPassRatio = pas / total NEW_LINE newPassRatio = ( pas + 1 ) / ( total + 1 ) NEW_LINE increase = newPassRatio - currentPassRatio NEW_LINE return increase NEW_LINE DEDENT def maximumAverage ( v , M , N ) : NEW_LINE INDENT sum = 0 NEW_LINE increase , average = 0 , 0 NEW_LINE pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT increase = change ( v [ i ] [ 0 ] , v [ i ] [ 1 ] ) NEW_LINE pq . append ( [ increase , i ] ) NEW_LINE average = v [ i ] [ 0 ] * 1.0 / v [ i ] [ 1 ] NEW_LINE sum += average NEW_LINE DEDENT pq = sorted ( pq ) NEW_LINE while ( M > 0 ) : NEW_LINE INDENT sum += pq [ - 1 ] [ 0 ] NEW_LINE i = pq [ - 1 ] [ 1 ] NEW_LINE del pq [ - 1 ] NEW_LINE v [ i ] [ 0 ] += 1 NEW_LINE v [ i ] [ 1 ] += 1 NEW_LINE pq . append ( [ change ( v [ i ] [ 0 ] , v [ i ] [ 1 ] ) , i ] ) NEW_LINE M -= 1 NEW_LINE pq = sorted ( pq ) NEW_LINE DEDENT ans = sum / N NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = [ [ 1 , 2 ] , [ 3 , 5 ] , [ 2 , 2 ] ] NEW_LINE M = 2 NEW_LINE N = len ( V ) NEW_LINE print ( round ( maximumAverage ( V , M , N ) , 6 ) ) NEW_LINE DEDENT |
Print all numbers that are divisors of N and are co | python 3 program for the above approach ; Function to print all numbers that are divisors of N and are co - prime with the quotient of their division ; Iterate upto square root of N ; If divisors are equal and gcd is 1 , then print only one of them ; Otherwise print both ; Driver Code | from math import sqrt , gcd NEW_LINE def printUnitaryDivisors ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i and gcd ( i , n // i ) == 1 ) : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( gcd ( i , n // i ) == 1 ) : NEW_LINE INDENT print ( i , n // i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE printUnitaryDivisors ( N ) NEW_LINE DEDENT |
Maximize K to make given array Palindrome when each element is replaced by its remainder with K | utility function to calculate the GCD of two numbers ; Function to calculate the largest K , replacing all elements of an array A by their modulus with K , makes A a palindromic array ; check if A is palindrome ; A is not palindromic ; K can be infitely large in this case ; variable to store the largest K that makes A palindromic ; return the required answer ; Driver code ; Input ; Function call | def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def largestK ( A , N ) : NEW_LINE INDENT l , r , flag = 0 , N - 1 , 0 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( A [ l ] != A [ r ] ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT if ( flag == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT K = abs ( A [ 0 ] - A [ N - 1 ] ) NEW_LINE for i in range ( 1 , N // 2 ) : NEW_LINE INDENT K = gcd ( K , abs ( A [ i ] - A [ N - i - 1 ] ) ) NEW_LINE DEDENT return K NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 2 , 1 ] NEW_LINE N = len ( A ) NEW_LINE print ( largestK ( A , N ) ) NEW_LINE DEDENT |
Check if N can be represented as sum of distinct powers of 3 | Function to try all permutations of distinct powers ; Base Case ; If the distinct powers sum is obtained ; Otherwise ; If current element not selected in power [ ] ; If current element selected in power [ ] ; Return 1 if any permutation found ; Function to check the N can be represented as the sum of the distinct powers of 3 ; Stores the all distincts powers of three to [ 0 , 15 ] ; Function Call ; Print ; Driver Code | def PermuteAndFind ( power , idx , SumSoFar , target ) : NEW_LINE INDENT if ( idx == len ( power ) ) : NEW_LINE INDENT if ( SumSoFar == target ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT select = PermuteAndFind ( power , idx + 1 , SumSoFar , target ) NEW_LINE notselect = PermuteAndFind ( power , idx + 1 , SumSoFar + power [ idx ] , target ) NEW_LINE return ( select or notselect ) NEW_LINE DEDENT def DistinctPowersOf3 ( N ) : NEW_LINE INDENT power = [ 0 for x in range ( 16 ) ] NEW_LINE power [ 0 ] = 1 NEW_LINE for i in range ( 1 , 16 ) : NEW_LINE INDENT power [ i ] = 3 * power [ i - 1 ] NEW_LINE DEDENT found = PermuteAndFind ( power , 0 , 0 , N ) NEW_LINE if ( found == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT N = 91 NEW_LINE DistinctPowersOf3 ( N ) NEW_LINE |
Check if N can be represented as sum of distinct powers of 3 | Function to check whether the given N can be represented as the sum of the distinct powers of 3 ; Iterate until N is non - zero ; Termination Condition ; Right shift ternary bits by 1 for the next digit ; If N can be expressed as the sum of perfect powers of 3 ; Driver Code | def DistinctPowersOf3 ( N ) : NEW_LINE INDENT while ( N > 0 ) : NEW_LINE INDENT if ( N % 3 == 2 ) : NEW_LINE INDENT cout << " No " NEW_LINE return NEW_LINE DEDENT N //= 3 NEW_LINE DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 91 NEW_LINE DistinctPowersOf3 ( N ) NEW_LINE DEDENT |
Generate an N | Function to print permutation of size N with absolute difference of adjacent elements in range [ 2 , 4 ] ; If N is less than 4 ; Check if N is even ; Traverse through odd integers ; Update the value of i ; Traverse through even integers ; Driver Code | def getPermutation ( N ) : NEW_LINE INDENT if ( N <= 3 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT i = N NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT while ( i >= 1 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE i -= 2 NEW_LINE DEDENT print ( 4 , 2 , end = " β " ) NEW_LINE i = 6 NEW_LINE while ( i <= N ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE i += 2 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE getPermutation ( N ) NEW_LINE DEDENT |
Count of distinct values till C formed by adding or subtracting A , B , or 0 any number of times | Function to calculate gcd ; Function to find number of possible final values ; Find the gcd of two numbers ; Calculate number of distinct values ; Return values ; Driver Code | def gcd ( A , B ) : NEW_LINE INDENT if ( B == 0 ) : NEW_LINE INDENT return A ; NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( B , A % B ) ; NEW_LINE DEDENT DEDENT def getDistinctValues ( A , B , C ) : NEW_LINE INDENT g = gcd ( A , B ) ; NEW_LINE num_values = C / g ; NEW_LINE return int ( num_values ) ; NEW_LINE DEDENT A = 2 ; NEW_LINE B = 3 ; NEW_LINE C = 10 ; NEW_LINE print ( getDistinctValues ( A , B , C ) ) ; NEW_LINE |
Find array whose elements are XOR of adjacent elements in given array | Function to reconstruct the array arr [ ] with xor of adjacent elements ; Iterate through each element ; Store the xor of current and next element in arr [ i ] ; Function to print array ; Driver Code ; Inputs ; Length of the array given ; Function call to reconstruct the arr [ ] ; Function call to prarr [ ] | def game_with_number ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i ] ^ arr [ i + 1 ] NEW_LINE DEDENT return arr NEW_LINE DEDENT def printt ( arr , n ) : NEW_LINE INDENT print ( * arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 11 , 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE new_arr = game_with_number ( arr , n ) ; NEW_LINE printt ( new_arr , n ) NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.