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 ... | 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... |
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... | 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... |
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 ... | 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 ; ... | 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 ( ... |
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 co... | 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 ) ... |
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... | 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_LI... |
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 ; Els... | 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... |
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 fir... | 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 retu... |
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 ... | 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 += ... |
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 ; ... | 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 s... |
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 un... | 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 ] ) ... |
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... | 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 ra... |
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 ... | 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 , ab... |
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 i... | 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_L... |
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 r... | 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... |
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 n... | 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 set... |
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 vali... | 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... |
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_... |
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 ;... | 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... |
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 ... | 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 DE... |
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... | 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 DED... |
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... | 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... |
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 n... |
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 Co... | 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 ... |
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 ... | 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... |
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 e... | 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 intCoun... |
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 ... | 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 )... |
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 ret... | 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 >... |
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... | 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... |
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 integ... | 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 ) * ( ... |
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... | 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 ( val... |
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 ... | 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 DEDEN... |
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 possi... | 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_LIN... |
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 ... | 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 (... |
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... | 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 ) ... |
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 DEDE... |
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 differ... | 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 ) : ... |
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 ... | 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... |
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... | 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... |
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 coun... | 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_LI... |
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... | 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_... |
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 ma... | 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 - ... |
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 nu... | 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_L... |
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 ,... |
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... | 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 ) ;... |
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... |
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 ; Prin... | 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 ; ... | 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 ) ... |
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... |
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... | 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 )... |
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... | 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 NE... |
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 ; Prin... | 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... |
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 a... | 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 ... |
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 = [ ... |
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 )... |
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 ... | 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 ( req... |
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 ... |
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 ;... | 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 ... |
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 , ... |
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... | 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 whil... |
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 ; Pri... | 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... |
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... | 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 <= a... |
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 co... | 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 ... |
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 e... | 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 =... |
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 ] ; ... | 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 ] [ ... |
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 ar... | 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_... |
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 displ... | 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 ... |
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 ... | 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 ] ... |
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 ,... |
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 t... | 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 isPerfectSq... |
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... | 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 ] [... |
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 cu... | 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... |
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 ; Tr... | 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 ... |
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... | 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_LI... |
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 num... | 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_... |
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 ; Driv... | 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 ... |
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 ... | 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 ... |
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 ... | 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... |
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... | 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 = le... |
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 I... |
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_L... |
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 ... | 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 ) : ... |
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 s... | 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 ) NE... |
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 consecutiv... | 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_ar... |
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 smit... | 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 ... |
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 tot... | 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 ... |
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 incre... | 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_... |
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... | 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 ,... |
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 ... | 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... |
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 ... | 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 ... |
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 o... | 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 ... |
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 = " β " ) NE... |
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 DE... |
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 ... | 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 , ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.