text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Maximize score of same | Function to calculate the score of same - indexed subarrays selected from the arrays a [ ] and b [ ] ; Traverse the current subarray ; Finding the score without reversing the subarray ; Calculating the score of the reversed subarray ; Return the score of subarray ; Function to find the subarray with the maximum score ; Stores the maximum score and the starting and the ending point of subarray with maximum score ; Traverse all the subarrays ; Store the score of the current subarray ; Update the maximum score ; Prthe maximum score ; Driver Code | def currSubArrayScore ( a , b , l , r ) : NEW_LINE INDENT straightScore = 0 NEW_LINE reverseScore = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT straightScore += a [ i ] * b [ i ] NEW_LINE reverseScore += a [ r - ( i - l ) ] * b [ i ] NEW_LINE DEDENT return max ( straightScore , reverseScore ) NEW_LINE DEDENT def maxScoreSubArray ( a , b , n ) : NEW_LINE INDENT res = 0 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT currScore = currSubArrayScore ( a , b , i , j ) NEW_LINE if ( currScore > res ) : NEW_LINE INDENT res = currScore NEW_LINE start = i NEW_LINE end = j NEW_LINE DEDENT DEDENT DEDENT print ( res ) NEW_LINE DEDENT A = [ 13 , 4 , 5 ] NEW_LINE B = [ 10 , 22 , 2 ] NEW_LINE N = len ( A ) NEW_LINE maxScoreSubArray ( A , B , N ) NEW_LINE |
Maximize score of same | Function to calculate the score of same - indexed subarrays selected from the arrays a [ ] and b [ ] ; Store the required result ; Iterate in the range [ 0 , N - 1 ] ; Consider the case of odd length subarray ; Update the maximum score ; Expanding the subarray in both directions with equal length so that mid poremains same ; Update both the scores ; Consider the case of even length subarray ; Update both the scores ; Print the result ; Driver Code | def maxScoreSubArray ( a , b , n ) : NEW_LINE INDENT res = 0 NEW_LINE for mid in range ( n ) : NEW_LINE INDENT straightScore = a [ mid ] * b [ mid ] NEW_LINE reverseScore = a [ mid ] * a [ mid ] NEW_LINE prev = mid - 1 NEW_LINE next = mid + 1 NEW_LINE res = max ( res , max ( straightScore , reverseScore ) ) NEW_LINE while ( prev >= 0 and next < n ) : NEW_LINE INDENT straightScore += ( a [ prev ] * b [ prev ] + a [ next ] * b [ next ] ) NEW_LINE reverseScore += ( a [ prev ] * b [ next ] + a [ next ] * b [ prev ] ) NEW_LINE res = max ( res , max ( straightScore , reverseScore ) ) NEW_LINE prev -= 1 NEW_LINE next += 1 NEW_LINE DEDENT straightScore = 0 NEW_LINE reverseScore = 0 NEW_LINE prev = mid - 1 NEW_LINE next = mid NEW_LINE while ( prev >= 0 and next < n ) : NEW_LINE INDENT straightScore += ( a [ prev ] * b [ prev ] + a [ next ] * b [ next ] ) NEW_LINE reverseScore += ( a [ prev ] * b [ next ] + a [ next ] * b [ prev ] ) NEW_LINE res = max ( res , max ( straightScore , reverseScore ) ) NEW_LINE prev -= 1 NEW_LINE next += 1 NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 13 , 4 , 5 ] NEW_LINE B = [ 10 , 22 , 2 ] NEW_LINE N = len ( A ) NEW_LINE maxScoreSubArray ( A , B , N ) NEW_LINE DEDENT |
Length of the smallest subarray with maximum possible sum | Function to find the minimum length of the subarray whose sum is maximum ; Stores the starting and the ending index of the resultant subarray ; Traverse the array until a non - zero element is encountered ; If the array contains only of 0 s ; Traverse the array in reverse until a non - zero element is encountered ; Return the resultant size of the subarray ; Driver Code | def minimumSizeSubarray ( arr , N ) : NEW_LINE INDENT i , j = 0 , N - 1 NEW_LINE while ( i < N and arr [ i ] == 0 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( i == N ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT while ( j >= 0 and arr [ j ] == 0 ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT return ( j - i + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 2 , 0 , 0 , 12 , 0 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimumSizeSubarray ( arr , N ) ) NEW_LINE DEDENT |
Count ways to represent N as XOR of distinct integers not exceeding N | Python program for the above approach ; Function to count number of ways to represent N as the Bitwise XOR of distinct integers ; Count number of subsets using above - mentioned formula ; Print the resultant count ; Driver Code | from math import * NEW_LINE def countXorPartition ( N ) : NEW_LINE INDENT a = 2 ** floor ( N - log ( N + 1 ) / log ( 2 ) ) NEW_LINE print ( int ( a ) ) NEW_LINE DEDENT N = 5 NEW_LINE countXorPartition ( N ) NEW_LINE |
Count numbers less than N whose modulo with A is equal to B | Function to count numbers less than N , whose modulo with A gives B ; If the value of B at least A ; If the value of B is 0 or not ; Stores the resultant count of numbers less than N ; Update the value of ans ; Print the value of ans ; Driver Code | def countValues ( A , B , C ) : NEW_LINE INDENT if ( B >= A ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT if ( B == 0 ) : NEW_LINE INDENT print ( C // A ) NEW_LINE return NEW_LINE DEDENT ans = C // A NEW_LINE if ( ans * A + B <= C ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 6 NEW_LINE B = 3 NEW_LINE N = 15 NEW_LINE countValues ( A , B , N ) NEW_LINE DEDENT |
Maximum sum of a subsequence whose Bitwise AND is non | Function to find the maximum sum of a subsequence whose Bitwise AND is non - zero ; Stores the resultant maximum sum of the subsequence ; Iterate over all the bits ; Stores the sum of array elements whose i - th bit is set ; Traverse the array elements ; If the bit is set , then add its value to the sum ; Update the resultant maximum sum ; Return the maximum sum ; Driver Code | def maximumSum ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for bit in range ( 32 ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] & ( 1 << bit ) ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT ans = max ( ans , sum ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 1 , 7 , 11 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumSum ( arr , N ) ) NEW_LINE DEDENT |
Check if an array can be reduced to at most length K by removal of distinct elements | Function to check if it is possible to reduce the size of the array to K by removing the set of the distinct array elements ; Stores all distinct elements present in the array arr [ ] ; Traverse the given array ; Insert array elements into the set ; Condition for reducing size of the array to at most K ; Driver Code | def maxCount ( arr , N , K ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT st . add ( arr [ i ] ) NEW_LINE DEDENT if ( N - len ( st ) <= K ) : 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 = [ 2 , 2 , 2 , 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE maxCount ( arr , N , K ) NEW_LINE DEDENT |
Maximum element present in the array after performing queries to add K to range of indices [ L , R ] | Function to find the max sum after processing q queries ; Store the cumulative sum ; Store the maximum sum ; Iterate over the range 0 to q ; Variables to extract values from vector ; Iterate over the range [ 1 , n ] ; Calculate cumulative sum ; Calculate maximum sum ; Return the maximum sum after q queries ; Stores the size of array and number of queries ; Stores the sum ; Storing input queries ; Function call to find the maximum sum | def max_sum ( a , v , q , n ) : NEW_LINE INDENT x = 0 ; NEW_LINE m = - 10 ** 9 ; NEW_LINE for i in range ( q ) : NEW_LINE INDENT p = v [ i ] [ 0 ] [ 0 ] ; NEW_LINE q = v [ i ] [ 0 ] [ 1 ] ; NEW_LINE k = v [ i ] [ 1 ] ; NEW_LINE a [ p ] += k ; NEW_LINE if ( q + 1 <= n ) : NEW_LINE INDENT a [ q + 1 ] -= k ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x += a [ i ] ; NEW_LINE m = max ( m , x ) ; NEW_LINE DEDENT return m ; NEW_LINE DEDENT n = 10 NEW_LINE q = 3 ; NEW_LINE a = [ 0 ] * ( n + 5 ) ; NEW_LINE v = [ [ [ 0 for i in range ( 2 ) ] for x in range ( 2 ) ] for z in range ( q ) ] NEW_LINE v [ 0 ] [ 0 ] [ 0 ] = 1 ; NEW_LINE v [ 0 ] [ 0 ] [ 1 ] = 5 ; NEW_LINE v [ 0 ] [ 1 ] = 3 ; NEW_LINE v [ 1 ] [ 0 ] [ 0 ] = 4 ; NEW_LINE v [ 1 ] [ 0 ] [ 1 ] = 8 ; NEW_LINE v [ 1 ] [ 1 ] = 7 ; NEW_LINE v [ 2 ] [ 0 ] [ 0 ] = 6 ; NEW_LINE v [ 2 ] [ 0 ] [ 1 ] = 9 ; NEW_LINE v [ 2 ] [ 1 ] = 1 ; NEW_LINE print ( max_sum ( a , v , q , n ) ) ; NEW_LINE |
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges | Function to check if there exists any pair ( P , Q ) whose Bitwise XOR is greater than the Bitwise XOR of X and Y ; Stores the Bitwise XOR of X & Y ; Traverse all possible pairs ; If a pair exists ; If a pair is found ; Driver Code | def findWinner ( X , Y ) : NEW_LINE INDENT playerA = ( X ^ Y ) NEW_LINE flag = False NEW_LINE for i in range ( 1 , X + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , Y + 1 , 1 ) : NEW_LINE INDENT val = ( i ^ j ) NEW_LINE if ( val > playerA ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 2 NEW_LINE B = 4 NEW_LINE findWinner ( A , B ) NEW_LINE DEDENT |
Check if a pair of integers from two ranges exists such that their Bitwise XOR exceeds both the ranges | Function to check if there exists any pair ( P , Q ) whose Bitwise XOR is greater than the Bitwise XOR of X and Y ; Check for the invalid condition ; Otherwise , ; Driver Code | def findWinner ( X , Y ) : NEW_LINE INDENT first = ( X ^ Y ) NEW_LINE second = ( X + Y ) NEW_LINE if ( first == second ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B = 2 , 4 NEW_LINE findWinner ( A , B ) NEW_LINE DEDENT |
Smallest number required to be added to M to make it divisible by N | Function to find the smallest number greater than or equal to N , that is divisible by k ; Function to find the smallest number required to be added to to M to make it divisible by N ; Stores the smallest multiple of N , greater than or equal to M ; Return the result ; Driver Code ; Given Input ; Function Call | def findNum ( N , K ) : NEW_LINE INDENT rem = ( N + K ) % K NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return N NEW_LINE DEDENT else : NEW_LINE INDENT return N + K - rem NEW_LINE DEDENT DEDENT def findSmallest ( M , N ) : NEW_LINE INDENT x = findNum ( M , N ) NEW_LINE return x - M NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 100 NEW_LINE N = 28 NEW_LINE print ( findSmallest ( M , N ) ) NEW_LINE DEDENT |
Prefix Factorials of a Prefix Sum Array | Function to find the factorial of prefix sum at every possible index ; Find the prefix sum array ; Stores the factorial of all the element till the sum of array ; Find the factorial array ; Find the factorials of each array element ; Print the resultant array ; Driver code | def prefixFactorialArray ( A , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] += A [ i - 1 ] NEW_LINE DEDENT fact = [ 0 for x in range ( A [ N - 1 ] + 1 ) ] NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , A [ N - 1 ] + 1 ) : NEW_LINE INDENT fact [ i ] = i * fact [ i - 1 ] NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT A [ i ] = fact [ A [ i ] ] NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE prefixFactorialArray ( arr , N ) NEW_LINE |
Maximum frequency of any array element possible by at most K increments | Function to find the maximum possible frequency of a most frequent element after at most K increment operations ; Sort the input array ; Stores the sum of sliding window and the maximum possible frequency of any array element ; Traverse the array ; Add the current element to the window ; If it is not possible to make the array elements in the window equal ; Update the value of sum ; Increment the value of start ; Update the maximum possible frequency ; Print the frequency of the most frequent array element after K increments ; Driver code | def maxFrequency ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE sum = 0 NEW_LINE res = 0 NEW_LINE for end in range ( N ) : NEW_LINE INDENT sum += arr [ end ] NEW_LINE while ( ( end - start + 1 ) * arr [ end ] - sum > K ) : NEW_LINE INDENT sum -= arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT res = max ( res , end - start + 1 ) NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 8 , 13 ] NEW_LINE N = 4 NEW_LINE K = 5 NEW_LINE maxFrequency ( arr , N , K ) NEW_LINE DEDENT |
Count pairs ( i , j ) from an array such that i < j and arr [ j ] | Function to count the number of pairs ( i , j ) such that i < j and arr [ i ] - arr [ j ] = X * ( j - i ) ; Stores the count of all such pairs that satisfies the condition . ; Stores count of distinct values of arr [ i ] - x * i ; Iterate over the Map ; Increase count of pairs ; Print the count of such pairs ; Driver Code | def countPairs ( arr , n , x ) : NEW_LINE INDENT count = 0 NEW_LINE mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] - x * i ) in mp ) : NEW_LINE INDENT mp [ arr [ i ] - x * i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] - x * i ] = 1 NEW_LINE DEDENT DEDENT for key , value in mp . items ( ) : NEW_LINE INDENT n = value NEW_LINE count += ( n * ( n - 1 ) ) // 2 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE x = 3 NEW_LINE arr = [ 5 , 4 , 8 , 11 , 13 , 16 ] NEW_LINE countPairs ( arr , n , x ) NEW_LINE DEDENT |
Check if a triplet of buildings can be selected such that the third building is taller than the first building and smaller than the second building | Function to check if it is possible to select three buildings that satisfy the given condition ; Stores prefix min array ; Iterate over the range [ 1 , N - 1 ] ; Stores the element from the ending in increasing order ; Iterate until j is greater than or equal to 0 ; If current array element is greater than the prefix min upto j ; Iterate while stack is not empty and top element is less than or equal to preMin [ j ] ; Remove the top element ; If stack is not empty and top element of the stack is less than the current element ; Push the arr [ j ] in stack ; If none of the above case satisfy then return " No " ; Driver code ; Input | def recreationalSpot ( arr , N ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT preMin = [ 0 ] * N NEW_LINE preMin [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT preMin [ i ] = min ( preMin [ i - 1 ] , arr [ i ] ) NEW_LINE DEDENT stack = [ ] NEW_LINE for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ j ] > preMin [ j ] ) : NEW_LINE INDENT while ( len ( stack ) > 0 and stack [ - 1 ] <= preMin [ j ] ) : NEW_LINE INDENT del stack [ - 1 ] NEW_LINE DEDENT if ( len ( stack ) > 0 and stack [ - 1 ] < arr [ j ] ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT stack . append ( arr [ j ] ) NEW_LINE DEDENT DEDENT return " No " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 7 , 11 , 5 , 13 , 2 ] NEW_LINE size = len ( arr ) NEW_LINE print ( recreationalSpot ( arr , size ) ) NEW_LINE DEDENT |
Check if a number N can be expressed as the sum of powers of X or not | Function to check if the number N can be expressed as the sum of different powers of X or not ; While n is a positive number ; Find the remainder ; If rem is at least 2 , then representation is impossible ; Divide the value of N by x ; Driver Code | def ToCheckPowerofX ( n , x ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT rem = n % x NEW_LINE if ( rem >= 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = n // x NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE X = 3 NEW_LINE if ( ToCheckPowerofX ( N , X ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Find the maximum between N and the number formed by reversing 32 | Function that obtains the number using said operations from N ; Stores the binary representation of the number N ; Find the binary representation of the number N ; Check for the set bits ; Reverse the string S ; Stores the obtained number ; Calculating the decimal value ; Check for set bits ; Function to find the maximum value between N and the obtained number ; Driver Code | def reverseBin ( N ) : NEW_LINE INDENT S = " " NEW_LINE i = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT if ( N & ( 1 << i ) ) : NEW_LINE INDENT S += '1' NEW_LINE DEDENT else : NEW_LINE INDENT S += '0' NEW_LINE DEDENT DEDENT S = list ( S ) NEW_LINE S = S [ : : - 1 ] NEW_LINE S = ' ' . join ( S ) NEW_LINE M = 0 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT M += ( 1 << i ) NEW_LINE DEDENT DEDENT return M NEW_LINE DEDENT def maximumOfTwo ( N ) : NEW_LINE INDENT M = reverseBin ( N ) NEW_LINE return max ( N , M ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE print ( maximumOfTwo ( N ) ) NEW_LINE DEDENT |
Sum of Euler Totient Functions obtained for each divisor of N | Function to find the sum of Euler Totient Function of divisors of N ; Return the value of N ; Driver Code | def sumOfDivisors ( N ) : NEW_LINE INDENT return N NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( sumOfDivisors ( N ) ) NEW_LINE DEDENT |
Square root of two Complex Numbers | Python3 program for the above approach ; Function to find the square root of a complex number ; Stores all the square roots ; Stores the first square root ; Push the square root in the ans ; Stores the second square root ; If X2 is not 0 ; Push the square root in the array ans [ ] ; Stores the third square root ; If X3 is greater than 0 ; Push the square root in the array ans [ ] ; Stores the fourth square root ; Push the square root in the array ans [ ] ; Prints the square roots ; Driver Code | from math import sqrt NEW_LINE def complexRoot ( A , B ) : NEW_LINE INDENT ans = [ ] NEW_LINE X1 = abs ( sqrt ( ( A + sqrt ( A * A + B * B ) ) / 2 ) ) NEW_LINE Y1 = B / ( 2 * X1 ) NEW_LINE ans . append ( [ X1 , Y1 ] ) NEW_LINE X2 = - 1 * X1 NEW_LINE Y2 = B / ( 2 * X2 ) NEW_LINE if ( X2 != 0 ) : NEW_LINE INDENT ans . append ( [ X2 , Y2 ] ) NEW_LINE DEDENT X3 = ( A - sqrt ( A * A + B * B ) ) / 2 NEW_LINE if ( X3 > 0 ) : NEW_LINE INDENT X3 = abs ( sqrt ( X3 ) ) NEW_LINE Y3 = B / ( 2 * X3 ) NEW_LINE ans . append ( [ X3 , Y3 ] ) NEW_LINE X4 = - 1 * X3 NEW_LINE Y4 = B / ( 2 * X4 ) NEW_LINE if ( X4 != 0 ) : NEW_LINE INDENT ans . append ( [ X4 , Y4 ] ) NEW_LINE DEDENT DEDENT print ( " The β Square β roots β are : β " ) NEW_LINE for p in ans : NEW_LINE INDENT print ( round ( p [ 0 ] , 6 ) , end = " " ) NEW_LINE if ( p [ 1 ] > 0 ) : NEW_LINE INDENT print ( " + " , end = " " ) NEW_LINE DEDENT if ( p [ 1 ] ) : NEW_LINE INDENT print ( str ( round ( p [ 1 ] , 6 ) ) + " * i " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B = 0 , 1 NEW_LINE complexRoot ( A , B ) NEW_LINE DEDENT |
Minimum time required to schedule K processes | Function to find minimum required time to schedule all process ; Stores max element from A [ ] ; Find the maximum element ; Stores frequency of each element ; Stores minimum time required to schedule all process ; Count frequencies of elements ; Find the minimum time ; Decrease the value of K ; Increment tmp [ i / 2 ] ; Increment the count ; Return count , if all process are scheduled ; Increment count ; Return the count ; If it is not possible to schedule all process ; Driver code | def minTime ( A , n , K ) : NEW_LINE INDENT max_ability = A [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT max_ability = max ( max_ability , A [ i ] ) NEW_LINE DEDENT tmp = [ 0 for i in range ( max_ability + 1 ) ] NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT tmp [ A [ i ] ] += 1 NEW_LINE DEDENT i = max_ability NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( tmp [ i ] != 0 ) : NEW_LINE INDENT if ( tmp [ i ] * i < K ) : NEW_LINE INDENT K -= ( i * tmp [ i ] ) NEW_LINE tmp [ i // 2 ] += tmp [ i ] NEW_LINE count += tmp [ i ] NEW_LINE if ( K <= 0 ) : NEW_LINE INDENT return count NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( K % i != 0 ) : NEW_LINE INDENT count += ( K // i ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += ( K // i ) NEW_LINE DEDENT return count NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 7 , 2 , 4 ] NEW_LINE N = 5 NEW_LINE K = 15 NEW_LINE print ( minTime ( arr , N , K ) ) NEW_LINE DEDENT |
Minimum length of a rod that can be split into N equal parts that can further be split into given number of equal parts | Function to find GCD of two numbers a and b ; Base Case ; Find GCD recursively ; Function to find the LCM of the resultant array ; Initialize a variable ans as the first element ; Traverse the array ; Update LCM ; Return the minimum length of the rod ; Function to find the minimum length of the rod that can be divided into N equals parts and each part can be further divided into arr [ i ] equal parts ; Print the result ; Driver Code | 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 findlcm ( arr , n ) : NEW_LINE INDENT ans = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = ( ( ( arr [ i ] * ans ) ) / ( gcd ( arr [ i ] , ans ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def minimumRod ( A , N ) : NEW_LINE INDENT print ( int ( N * findlcm ( A , N ) ) ) NEW_LINE DEDENT arr = [ 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minimumRod ( arr , N ) NEW_LINE |
Check if N can be represented as sum of positive integers containing digit D at least once | Function to check if N contains digit D in it ; Iterate until N is positive ; Find the last digit ; If the last digit is the same as digit D ; Return false ; Function to check if the value of N can be represented as sum of integers having digit d in it ; Iterate until N is positive ; Check if N contains digit D or not ; Subtracting D from N ; Return false ; Driver Code | def findDigit ( N , D ) : NEW_LINE INDENT while ( N > 0 ) : NEW_LINE INDENT a = N % 10 NEW_LINE if ( a == D ) : NEW_LINE INDENT return True NEW_LINE DEDENT N /= 10 NEW_LINE DEDENT return False NEW_LINE DEDENT def check ( N , D ) : NEW_LINE INDENT while ( N > 0 ) : NEW_LINE INDENT if ( findDigit ( N , D ) == True ) : NEW_LINE INDENT return True NEW_LINE DEDENT N -= D NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 24 NEW_LINE D = 7 NEW_LINE if ( check ( N , D ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Number of relations that are neither Reflexive nor Irreflexive on a Set | Python program for the above approach ; Function to calculate x ^ y modulo 10 ^ 9 + 7 in O ( log y ) ; Stores the result of ( x ^ y ) ; Update x , if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with res ; Divide y by 2 ; Update the value of x ; Return the value of x ^ y ; Function to count the number of relations that are neither reflexive nor irreflexive ; Return the resultant count ; Driver Code | mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % mod NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( y > 0 ) : NEW_LINE INDENT if ( y % 2 == 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def countRelations ( N ) : NEW_LINE INDENT print ( ( power ( 2 , N ) - 2 ) * power ( 2 , N * N - N ) ) NEW_LINE DEDENT N = 2 NEW_LINE countRelations ( N ) NEW_LINE |
Minimum operations required to make all elements in an array of first N odd numbers equal | Function to find the minimum number of operations required to make the array elements equal ; Stores the array elements ; Stores the sum of the array ; Iterate over the range [ 0 , N ] ; Update the value arr [ i ] ; Increment the sum by the value arr [ i ] ; Stores the middle element ; If N is even ; Otherwise ; Stores the result ; Traverse the range [ 0 , N / 2 ] ; Update the value of ans ; Return the result ; Driver Code | def minOperations ( N ) : NEW_LINE INDENT arr = [ 0 ] * N NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr [ i ] = ( 2 * i ) + 1 NEW_LINE sum = sum + arr [ i ] NEW_LINE DEDENT mid = 0 NEW_LINE if N % 2 == 0 : NEW_LINE INDENT mid = sum / N NEW_LINE DEDENT else : NEW_LINE INDENT mid = arr [ int ( N / 2 ) ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( int ( N / 2 ) ) : NEW_LINE INDENT ans += mid - arr [ i ] NEW_LINE DEDENT return int ( ans ) NEW_LINE DEDENT N = 6 NEW_LINE print ( minOperations ( N ) ) NEW_LINE |
Minimum operations required to make all elements in an array of first N odd numbers equal | Function to find the minimum number of operations required to make the array elements equal ; If the value of N is even ; Return the value ; Otherwise , N is odd ; Return the value ; Driver Code | def minOperation ( N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT return ( N / 2 ) * ( N / 2 ) NEW_LINE DEDENT k = ( N - 1 ) / 2 NEW_LINE return ( k * ( k + 1 ) ) NEW_LINE DEDENT N = 6 NEW_LINE print ( int ( minOperation ( N ) ) ) NEW_LINE |
Bitwise XOR of Bitwise AND of all pairs from two given arrays | Function to find the Bitwise XOR of Bitwise AND of all pairs from the arrays arr1 [ ] and arr2 [ ] ; Stores the result ; Iterate over the range [ 0 , N - 1 ] ; Iterate over the range [ 0 , M - 1 ] ; Stores Bitwise AND of the pair { arr1 [ i ] , arr2 [ j ] } ; Update res ; Return the res ; Driver Code ; Input | def findXORS ( arr1 , arr2 , N , M ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT temp = arr1 [ i ] & arr2 [ j ] NEW_LINE res ^= temp NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 , 3 ] NEW_LINE arr2 = [ 6 , 5 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE print ( findXORS ( arr1 , arr2 , N , M ) ) NEW_LINE DEDENT |
Bitwise XOR of Bitwise AND of all pairs from two given arrays | Function to find the Bitwise XOR of Bitwise AND of all pairs from the arrays arr1 [ ] and arr2 [ ] ; Stores XOR of array arr1 [ ] ; Stores XOR of array arr2 [ ] ; Traverse the array arr1 [ ] ; Traverse the array arr2 [ ] ; Return the result ; Driver Code ; Input | def findXORS ( arr1 , arr2 , N , M ) : NEW_LINE INDENT XORS1 = 0 NEW_LINE XORS2 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT XORS1 ^= arr1 [ i ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT XORS2 ^= arr2 [ i ] NEW_LINE DEDENT return XORS1 and XORS2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 , 3 ] NEW_LINE arr2 = [ 6 , 5 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE print ( findXORS ( arr1 , arr2 , N , M ) ) NEW_LINE DEDENT |
Count numbers up to N that cannot be expressed as sum of at least two consecutive positive integers | Function to check if a number can be expressed as a power of 2 ; if N is power of two ; Function to count numbers that cannot be expressed as sum of two or more consecutive + ve integers ; Stores the resultant count of integers ; Iterate over the range [ 1 , N ] ; Check if i is power of 2 ; Increment the count if i is not power of 2 ; Print the value of count ; Driver Code | def isPowerof2 ( n ) : NEW_LINE INDENT return ( ( n & ( n - 1 ) ) and n ) NEW_LINE DEDENT def countNum ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT flag = isPowerof2 ( i ) NEW_LINE if ( not flag ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 100 NEW_LINE countNum ( N ) NEW_LINE DEDENT |
Count numbers up to N that cannot be expressed as sum of at least two consecutive positive integers | Python 3 program for the above approach ; Function to count numbers that cannot be expressed as sum of two or more consecutive + ve integers ; Stores the count of such numbers ; Driver Code | import math NEW_LINE def countNum ( N ) : NEW_LINE INDENT ans = int ( math . log2 ( N ) ) + 1 NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 100 NEW_LINE countNum ( N ) NEW_LINE DEDENT |
Replace array elements that contains K as a digit with the nearest power of K | Python3 program for the above approach ; Function to calculate the power of base nearest to x ; Stores logX to the base K ; Function to replace array elements with nearest power of K ; Traverse the array ; Convert integer into a string ; If K is found , then replace with the nearest power of K ; Print the array ; Given array ; Given value of K ; Function call to replace array elements with nearest power of K | import math NEW_LINE def nearestPow ( x , base ) : NEW_LINE INDENT k = int ( math . log ( x , base ) ) NEW_LINE if abs ( base ** k - x ) < abs ( base ** ( k + 1 ) - x ) : NEW_LINE INDENT return base ** k NEW_LINE DEDENT else : NEW_LINE INDENT return base ** ( k + 1 ) NEW_LINE DEDENT DEDENT def replaceWithNearestPowerOfK ( arr , K ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT strEle = str ( arr [ i ] ) NEW_LINE for c in strEle : NEW_LINE INDENT if int ( c ) == K : NEW_LINE INDENT arr [ i ] = nearestPow ( arr [ i ] , K ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( arr ) NEW_LINE DEDENT arr = [ 432 , 953 , 232 , 333 ] NEW_LINE K = 3 NEW_LINE replaceWithNearestPowerOfK ( arr , K ) NEW_LINE |
Difference between ceil of array sum divided by K and sum of ceil of array elements divided by K | Python3 program for the above approach ; Function to find absolute difference between array sum divided by x and sum of ceil of array elements divided by x ; Stores the total sum ; Stores the sum of ceil of array elements divided by x ; Traverse the array ; Adding each array element ; Add the value ceil of arr [ i ] / x ; Find the ceil of the total sum divided by x ; Return absolute difference ; Driver Code | from math import ceil NEW_LINE def ceilDifference ( arr , n , x ) : NEW_LINE INDENT totalSum = 0 NEW_LINE perElementSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE perElementSum += ceil ( arr [ i ] / x ) NEW_LINE DEDENT totalCeilSum = ceil ( totalSum / x ) NEW_LINE return abs ( perElementSum - totalCeilSum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE print ( ceilDifference ( arr , N , K ) ) NEW_LINE DEDENT |
Remove trailing zeros from the sum of two numbers ( Using Stack ) | Function to remove trailing zeros from the sum of two numbers ; Stores the sum of A and B ; Stores the digits ; Stores the equivalent string of integer N ; Traverse the string ; Push the digit at i in the stack ; While top element is '0 ; Pop the top element ; Stores the resultant number without tailing 0 's ; While s is not empty ; Append top element of S in res ; Pop the top element of S ; Reverse the string res ; Driver Code ; Input ; Function Call | def removeTailing ( A , B ) : NEW_LINE INDENT N = A + B NEW_LINE s = [ ] NEW_LINE strsum = str ( N ) NEW_LINE for i in range ( len ( strsum ) ) : NEW_LINE INDENT s . append ( strsum [ i ] ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT while ( s [ - 1 ] == '0' ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT res = " " NEW_LINE while ( len ( s ) != 0 ) : NEW_LINE INDENT res = res + ( s [ - 1 ] ) NEW_LINE s . pop ( ) NEW_LINE DEDENT res = list ( res ) NEW_LINE res . reverse ( ) NEW_LINE res = ' ' . join ( res ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 130246 NEW_LINE B = 450164 NEW_LINE print ( removeTailing ( A , B ) ) NEW_LINE DEDENT |
Count number of triplets with product not exceeding a given number | Function to count the number of triplets whose product is at most N ; Stores the count of triplets ; Iterate over the range [ 0 , N ] ; Iterate over the range [ 0 , N ] ; If the product of pairs exceeds N ; Increment the count of possible triplets ; Return the total count ; Driver Code | def countTriplets ( N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i * j > N ) : NEW_LINE INDENT break NEW_LINE DEDENT ans += N // ( i * j ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE print ( countTriplets ( N ) ) NEW_LINE DEDENT |
Sum of an Infinite Geometric Progression ( GP ) | Function to calculate the sum of an infinite Geometric Progression ; Case for Infinite Sum ; Store the sum of GP Series ; Print the value of sum ; Driver Code | def findSumOfGP ( a , r ) : NEW_LINE INDENT if ( abs ( r ) >= 1 ) : NEW_LINE INDENT print ( " Infinite " ) NEW_LINE return NEW_LINE DEDENT sum = a / ( 1 - r ) NEW_LINE print ( int ( sum ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , R = 1 , 0.5 NEW_LINE findSumOfGP ( A , R ) NEW_LINE DEDENT |
Number of Relations that are both Irreflexive and Antisymmetric on a Set | Python 3 program for the above approach ; Function to calculate x ^ y % mod in O ( log y ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the value of x ^ y ; Function to count relations that are irreflexive and antisymmetric in a set consisting of N elements ; Return the resultant count ; Driver Code | mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % mod NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def numberOfRelations ( N ) : NEW_LINE INDENT return power ( 3 , ( N * N - N ) // 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE print ( numberOfRelations ( N ) ) NEW_LINE DEDENT |
Count of numbers up to N having at least one prime factor common with N | Python 3 program for the above approach ; Function to count all the numbers in the range [ 1 , N ] having common factor with N other than 1 ; Stores the count of numbers having more than 1 factor with N ; Iterate over the range [ 1 , N ] ; If gcd is not 1 then increment the count ; Print the resultant count ; Driver Code | import math NEW_LINE def countNumbers ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( math . gcd ( i , N ) != 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE countNumbers ( N ) NEW_LINE DEDENT |
Count of numbers up to N having at least one prime factor common with N | Function to calculate the value of Euler 's totient function ; Initialize result with N ; Find all prime factors of N and subtract their multiples ; Check if p is a prime factor ; If found to be true , then update N and result ; If N has a prime factor greater than sqrt ( N ) , then there can be at - most one such prime factor ; Function to count all the numbers in the range [ 1 , N ] having common factor with N other than 1 ; Stores the resultant count ; Print the count ; Driver Code | def phi ( N ) : NEW_LINE INDENT result = N NEW_LINE for p in range ( 2 , int ( pow ( N , 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( N % p == 0 ) : NEW_LINE INDENT while ( N % p == 0 ) : NEW_LINE INDENT N = N / p NEW_LINE DEDENT result -= result // p NEW_LINE DEDENT DEDENT if ( N > 1 ) : NEW_LINE INDENT result -= result // N NEW_LINE DEDENT return result NEW_LINE DEDENT def countNumbers ( N ) : NEW_LINE INDENT count = N - phi ( N ) NEW_LINE print ( count ) NEW_LINE DEDENT N = 5 NEW_LINE countNumbers ( N ) NEW_LINE |
Queries to update array by adding or multiplying array elements and print the element present at specified index | Function to modify the array by performing given queries ; Stores the multiplication of all integers of type 1 ; Stores the value obtained after performing queries of type 1 & 2 ; Iterate over the queries ; Query of type 0 ; Update the value of add ; Query of type 1 ; Update the value of mul ; Update the value of add ; Otherwise ; Store the element at index Q [ i ] [ 1 ] ; Prthe result for the current query ; Driver Code | def Query ( arr , N , Q ) : NEW_LINE INDENT mul = 1 NEW_LINE add = 0 NEW_LINE for i in range ( len ( Q ) ) : NEW_LINE INDENT if ( Q [ i ] [ 0 ] == 0 ) : NEW_LINE INDENT add = add + Q [ i ] [ 1 ] NEW_LINE DEDENT elif ( Q [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT mul = mul * Q [ i ] [ 1 ] NEW_LINE add = add * Q [ i ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT ans = arr [ Q [ i ] [ 1 ] ] * mul + add NEW_LINE print ( ans , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 1 , 23 , 45 , 100 ] NEW_LINE N = len ( arr ) NEW_LINE Q = [ [ 1 , 2 ] , [ 0 , 10 ] , [ 2 , 3 ] , [ 1 , 5 ] , [ 2 , 4 ] ] NEW_LINE Query ( arr , N , Q ) NEW_LINE DEDENT |
Minimize cost of converting all array elements to Fibonacci Numbers | Python program for the above approach ; Function to find the N - th Fibonacci Number ; Find the value of a , b , and r ; Find the N - th Fibonacci ; Return the result ; Function to find the Fibonacci number which is nearest to X ; Calculate the value of n for X ; Return the nearest Fibonacci Number ; Function to find the minimum cost to convert all array elements to Fibonacci Numbers ; Stores the total minimum cost ; Traverse the given array arr [ ] ; Find the nearest Fibonacci Number ; Add the cost ; Return the final cost ; Driver Code | import math NEW_LINE def nthFibo ( n ) : NEW_LINE INDENT a = ( 5 ** ( 1 / 2 ) + 1 ) / 2 NEW_LINE b = ( - 5 ** ( 1 / 2 ) + 1 ) / 2 NEW_LINE r = 5 ** ( 1 / 2 ) NEW_LINE ans = ( a ** n - b ** n ) / r NEW_LINE return int ( ans ) NEW_LINE DEDENT def nearFibo ( X ) : NEW_LINE INDENT a = ( 5 ** ( 1 / 2 ) + 1 ) / 2 NEW_LINE n = int ( math . log ( ( 5 ** ( 1 / 2 ) ) * X ) / math . log ( a ) ) NEW_LINE nth = nthFibo ( n ) NEW_LINE nplus = nthFibo ( n + 1 ) NEW_LINE if abs ( X - nth ) < abs ( X - nplus ) : NEW_LINE INDENT return nth NEW_LINE DEDENT else : NEW_LINE INDENT return nplus NEW_LINE DEDENT DEDENT def getCost ( arr ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in arr : NEW_LINE INDENT fibo = nearFibo ( i ) NEW_LINE cost += abs ( i - fibo ) NEW_LINE DEDENT return cost NEW_LINE DEDENT arr = [ 56 , 34 , 23 , 98 , 7 ] NEW_LINE print ( getCost ( arr ) ) NEW_LINE |
Maximum sum of pairs that are at least K distance apart in an array | Function to find the largest sum pair that are K distant apart ; Stores the prefix maximum array ; Base Case ; Traverse the array and update the maximum value upto index i ; Stores the maximum sum of pairs ; Iterate over the range [ K , N ] ; Find the maximum value of the sum of valid pairs ; Return the resultant sum ; Driver Code | def getMaxPairSum ( arr , N , K ) : NEW_LINE INDENT preMax = [ 0 ] * N NEW_LINE preMax [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT preMax [ i ] = max ( preMax [ i - 1 ] , arr [ i ] ) NEW_LINE DEDENT res = - 10 ** 8 NEW_LINE for i in range ( K , N ) : NEW_LINE INDENT res = max ( res , arr [ i ] + preMax [ i - K ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 6 , 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( getMaxPairSum ( arr , N , K ) ) NEW_LINE DEDENT |
Program to calculate sum of an Infinite Arithmetic | Function to find the sum of the infinite AGP ; Stores the sum of infinite AGP ; Print the required sum ; Driver Code | def sumOfInfiniteAGP ( a , d , r ) : NEW_LINE INDENT ans = a / ( 1 - r ) + ( d * r ) / ( 1 - r * r ) ; NEW_LINE print ( round ( ans , 6 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , d , r = 0 , 1 , 0.5 NEW_LINE sumOfInfiniteAGP ( a , d , r ) NEW_LINE DEDENT |
Count pairs from an array having GCD equal to the minimum element in the pair | Function to count pairs from an array having GCD equal to minimum element of that pair ; Stores the resultant count ; Iterate over the range [ 0 , N - 2 ] ; Iterate over the range [ i + 1 , N ] ; If arr [ i ] % arr [ j ] is 0 or arr [ j ] % arr [ i ] is 0 ; Increment count by 1 ; Return the resultant count ; Driver Code | 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 [ i ] % arr [ j ] == 0 or arr [ j ] % arr [ i ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT |
Count pairs from an array having GCD equal to the minimum element in the pair | Python3 program for the above approach ; Function to count pairs from an array having GCD equal to minimum element of that pair ; Stores the resultant count ; Stores the frequency of each array element ; Traverse the array arr [ ] ; Iterate over the Map mp ; Stores the array element ; Stores the count of array element x ; If x is 1 ; Increment res by N - 1 ; Increment res by yC2 ; Iterate over the range [ 2 , sqrt ( x ) ] ; If x is divisible by j ; Increment the value of res by mp [ j ] ; If j is not equal to x / j ; Increment res by mp [ x / j ] ; Return the resultant count ; Driver Code | from math import sqrt NEW_LINE def CountPairs ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] in mp ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT for key , value in mp . items ( ) : NEW_LINE INDENT x = key NEW_LINE y = value NEW_LINE if ( x == 1 ) : NEW_LINE INDENT res += N - 1 NEW_LINE continue NEW_LINE DEDENT res += ( y * ( y - 1 ) ) // 2 NEW_LINE for j in range ( 2 , int ( sqrt ( x ) ) + 1 , 1 ) : NEW_LINE INDENT if ( x % j == 0 ) : NEW_LINE INDENT res += mp [ j ] NEW_LINE if ( j != x // j ) : NEW_LINE INDENT res += mp [ x // j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( CountPairs ( arr , N ) ) NEW_LINE DEDENT |
Product of count of set bits present in binary representations of elements in an array | Function to count the set bits in an integer ; Stores the count of set bits ; Iterate while N is not equal to 0 ; Increment count by 1 ; Divide N by 2 ; Return the total count obtained ; Function to find the product of count of set bits present in each element of an array ; Stores the resultant product ; Traverse the array arr [ ] ; Stores the count of set bits of arr [ i ] ; Update the product ; Return the resultant product ; Driver Code | def countbits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT n = n // 2 NEW_LINE DEDENT return count NEW_LINE DEDENT def BitProduct ( arr , N ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT bits = countbits ( arr [ i ] ) NEW_LINE product *= bits NEW_LINE DEDENT return product NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 1 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( BitProduct ( arr , N ) ) NEW_LINE DEDENT |
Queries to calculate sum of array elements consisting of odd number of divisors | Python3 program for the above approach ; Function to find the sum of elements having odd number of divisors in index range [ L , R ] for Q queries ; Initialize the dp [ ] array ; Traverse the array , arr [ ] ; If a [ i ] is a perfect square , then update value of DP [ i ] to a [ i ] ; Find the prefix sum of DP [ ] array ; Iterate through all the queries ; Find the sum for each query ; Driver Code | from math import sqrt NEW_LINE def OddDivisorsSum ( n , q , a , Query ) : NEW_LINE INDENT DP = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = sqrt ( a [ i ] ) NEW_LINE if ( x * x == a [ i ] ) : NEW_LINE INDENT DP [ i ] = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT DP [ i ] = DP [ i - 1 ] + DP [ i ] NEW_LINE DEDENT for i in range ( q ) : NEW_LINE INDENT l = Query [ i ] [ 0 ] NEW_LINE r = Query [ i ] [ 1 ] NEW_LINE if ( l == 0 ) : NEW_LINE INDENT print ( DP [ r ] , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( DP [ r ] - DP [ l - 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 5 , 6 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE Q = 3 NEW_LINE Query = [ [ 0 , 2 ] , [ 1 , 3 ] , [ 1 , 4 ] ] NEW_LINE OddDivisorsSum ( N , Q , arr , Query ) NEW_LINE DEDENT |
Smallest subset of maximum sum possible by splitting array into two subsets | Python 3 program for the above approach ; Function to split array elements into two subsets having sum of the smaller subset maximized ; Stores the size of the array ; Stores the frequency of array elements ; Stores the total sum of the array ; Stores the sum of the resultant set ; Stores if it is possible to split the array that satisfies the conditions ; Stores the elements of the first subseta ; Traverse the array arr [ ] ; Increment total sum ; Increment count of arr [ i ] ; Sort the array arr [ ] ; Stores the index of the last element of the array ; Traverse the array arr [ ] ; Stores the frequency of arr [ i ] ; If frq + ans . size ( ) is at most remaining size ; Append arr [ i ] to ans ; Decrement totSum by arr [ i ] ; Increment s by arr [ i ] ; Otherwise , decrement i by frq ; If s is greater than totSum ; Mark flag 1 ; If flag is equal to 1 ; Print the arrList ans ; Otherwise , print " - 1" ; Driver Code | from collections import defaultdict NEW_LINE def findSubset ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE mp = defaultdict ( int ) NEW_LINE totSum = 0 NEW_LINE s = 0 NEW_LINE flag = 0 NEW_LINE ans = [ ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT totSum += arr [ i ] NEW_LINE mp [ arr [ i ] ] = mp [ arr [ i ] ] + 1 NEW_LINE DEDENT arr . sort ( ) NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT frq = mp [ arr [ i ] ] NEW_LINE if ( ( frq + len ( ans ) ) < ( N - ( frq + len ( ans ) ) ) ) : NEW_LINE INDENT for k in range ( frq ) : NEW_LINE INDENT ans . append ( arr [ i ] ) NEW_LINE totSum -= arr [ i ] NEW_LINE s += arr [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT i -= frq NEW_LINE DEDENT if ( s > totSum ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT for i in range ( len ( ans ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 2 , 4 , 1 , 2 ] NEW_LINE findSubset ( arr ) NEW_LINE DEDENT |
Minimize Bitwise XOR of array elements with 1 required to make sum of array at least K | Function to find minimum number of Bitwise XOR of array elements with 1 required to make sum of the array at least K ; Stores the count of even array elements ; Stores sum of the array ; Traverse the array arr [ ] ; Increment sum ; If array element is even ; Increase count of even ; If S is at least K ; If S + E is less than K ; Otherwise , moves = K - S ; Driver Code | def minStepK ( arr , N , K ) : NEW_LINE INDENT E = 0 NEW_LINE S = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT S += arr [ i ] NEW_LINE if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT E += 1 NEW_LINE DEDENT DEDENT if ( S >= K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( S + E < K ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return K - S NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 0 , 1 , 1 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE print ( minStepK ( arr , N , K ) ) NEW_LINE DEDENT |
Maximize difference between odd and even | Function to find maximum and minimum value of a number that can be obtained by rotating bits ; Stores the value of N ; Stores the maximum value ; Stores the minimum value ; If temp is odd ; Update the maximum and the minimum value ; If flag is 1 , then return the maximum value ; Otherwise , return the maximum value ; Function to find the maximum difference between the sum of odd and even - indexed array elements possible by rotating bits ; Stores the maximum difference ; Stores the sum of elements present at odd indices ; Stores the sum of elements present at even indices ; Traverse the given array ; If the index is even ; Update the caseOne ; Stores the maximum difference ; Stores the sum of elements placed at odd positions ; Stores the sum of elements placed at even positions ; Traverse the array ; If the index is even ; Update the caseTwo ; Return the maximum of caseOne and caseTwo ; Driver Code | def Rotate ( n , f ) : NEW_LINE INDENT temp = n NEW_LINE maxi = n NEW_LINE mini = n NEW_LINE for idx in range ( 7 ) : NEW_LINE INDENT if temp & 1 : NEW_LINE INDENT temp >>= 1 NEW_LINE temp += 2 ** 7 NEW_LINE DEDENT else : NEW_LINE INDENT temp >>= 1 NEW_LINE DEDENT mini = min ( mini , temp ) NEW_LINE maxi = max ( maxi , temp ) NEW_LINE DEDENT if ( f ) : NEW_LINE INDENT return ( maxi ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( mini ) NEW_LINE DEDENT DEDENT def calcMinDiff ( arr ) : NEW_LINE INDENT caseOne = 0 NEW_LINE sumOfodd = 0 NEW_LINE sumOfeven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT sumOfodd += Rotate ( arr [ i ] , 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT sumOfeven += Rotate ( arr [ i ] , 1 ) NEW_LINE DEDENT DEDENT caseOne = abs ( sumOfodd - sumOfeven ) NEW_LINE caseTwo = 0 NEW_LINE sumOfodd = 0 NEW_LINE sumOfeven = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE INDENT sumOfodd += Rotate ( arr [ i ] , 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT sumOfeven += Rotate ( arr [ i ] , 0 ) NEW_LINE DEDENT DEDENT caseTwo = abs ( sumOfodd - sumOfeven ) NEW_LINE return max ( caseOne , caseTwo ) NEW_LINE DEDENT arr = [ 123 , 86 , 234 , 189 ] NEW_LINE print ( calcMinDiff ( arr ) ) NEW_LINE |
Array element with minimum sum of absolute differences | Set 2 | Function to find the element with minimum sum of differences between any elements in the array ; Stores the required X and sum of absolute differences ; Calculate sum of array elements ; The sum of absolute differences can 't be greater than sum ; Update res that gives the minimum sum ; If the current difference is less than the previous difference ; Update min_diff and res ; Print the resultant value ; Driver Code | def minimumDiff ( arr , N ) : NEW_LINE INDENT res = arr [ 0 ] NEW_LINE sum1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum1 += arr [ i ] NEW_LINE DEDENT min_diff = sum1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( abs ( sum1 - ( arr [ i ] * N ) ) < min_diff ) : NEW_LINE INDENT min_diff = abs ( sum1 - ( arr [ i ] * N ) ) NEW_LINE res = arr [ i ] NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE minimumDiff ( arr , N ) NEW_LINE DEDENT |
Sum of array elements possible by appending arr [ i ] / K to the end of the array K times for array elements divisible by K | Function to calculate sum of array elements after adding arr [ i ] / K to the end of the array if arr [ i ] is divisible by K ; Stores the sum of the array ; Stores the array elements ; Traverse the array ; Stores if the operation should be formed or not ; Traverse the vector V ; If flag is false and if v [ i ] is divisible by K ; Otherwise , set flag as true ; Increment the sum by v [ i % N ] ; Return the resultant sum ; Driver Code | def Sum ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE v = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT flag = False NEW_LINE i = 0 NEW_LINE lenn = len ( v ) NEW_LINE while ( i < lenn ) : NEW_LINE INDENT if ( flag == False and ( v [ i ] % K == 0 ) ) : NEW_LINE INDENT v . append ( v [ i ] // K ) NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE DEDENT sum += v [ i % N ] NEW_LINE i += 1 NEW_LINE lenn = len ( v ) NEW_LINE DEDENT return sum NEW_LINE DEDENT arr = [ 4 , 6 , 8 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( Sum ( arr , N , K ) ) NEW_LINE |
Count array elements whose count of divisors is a prime number | Function to count the array elements whose count of divisors is prime ; Stores the maximum element ; Find the maximum element ; Store if i - th element is prime ( 0 ) or non - prime ( 1 ) ; Base Case ; If i is a prime number ; Mark all multiples of i as non - prime ; Stores the count of divisors ; Base Case ; Iterate to count factors ; Stores the count of array elements whose count of divisors is a prime number ; Traverse the array arr [ ] ; If count of divisors is prime ; Return the resultant count ; Driver Code | def primeDivisors ( arr , N ) : NEW_LINE INDENT K = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT K = max ( K , arr [ i ] ) NEW_LINE DEDENT prime = [ 0 ] * ( K + 1 ) NEW_LINE prime [ 0 ] = 1 NEW_LINE prime [ 1 ] = 1 NEW_LINE for i in range ( 2 , K + 1 ) : NEW_LINE INDENT if ( not prime [ i ] ) : NEW_LINE INDENT for j in range ( 2 * i , K + 1 , i ) : NEW_LINE INDENT prime [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT factor = [ 0 ] * ( K + 1 ) NEW_LINE factor [ 0 ] = 0 NEW_LINE factor [ 1 ] = 1 NEW_LINE for i in range ( 2 , K + 1 ) : NEW_LINE INDENT factor [ i ] += 1 NEW_LINE for j in range ( i , K + 1 , i ) : NEW_LINE INDENT factor [ j ] += 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( prime [ factor [ arr [ i ] ] ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 13 , 17 , 25 ] NEW_LINE N = len ( arr ) NEW_LINE print ( primeDivisors ( arr , N ) ) NEW_LINE DEDENT |
Count prime numbers up to N that can be represented as a sum of two prime numbers | Function to store all prime numbers up to N using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is prime ; Set all multiples of p as non - prime ; Function to count prime numbers up to N that can be represented as the sum of two prime numbers ; Stores all the prime numbers ; Update the prime array ; Create a dp array of size n + 1 ; Update dp [ 1 ] = 0 ; Iterate over the range [ 2 , N ] ; Add the previous count value ; Increment dp [ i ] by 1 if i and ( i - 2 ) are both prime ; Print the result ; Driver Code | def SieveOfEratosthenes ( n , prime ) : NEW_LINE INDENT prime [ 0 ] = 0 NEW_LINE prime [ 1 ] = 0 NEW_LINE p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def countPrime ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) NEW_LINE SieveOfEratosthenes ( n , prime ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 1 ] = 0 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] += dp [ i - 1 ] NEW_LINE if ( prime [ i ] == 1 and prime [ i - 2 ] == 1 ) : NEW_LINE INDENT dp [ i ] += 1 NEW_LINE DEDENT DEDENT print ( dp [ n ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE countPrime ( N ) NEW_LINE DEDENT |
Minimize sum of an array having Bitwise AND of all its pairs present in a given matrix | Function to find the minimum sum of the array such that Bitwise AND of arr [ i ] ana arr [ j ] is mat [ i ] [ j ] ; Stores the minimum possible sum ; Traverse the range [ 0 , N - 1 ] ; Stores the Bitwise OR of all the element of a row ; Traverse the range [ 0 , N - 1 ] ; If i not equal to j ; Update the value of res ; Increment the sum by res ; Return minimum possible sum ; Driver code | def findMinSum ( mat , N ) : NEW_LINE INDENT sum1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT res = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT res |= mat [ i ] [ j ] NEW_LINE DEDENT DEDENT sum1 += res NEW_LINE DEDENT return sum1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ - 1 , 2 , 3 ] , [ 9 , - 1 , 7 ] , [ 4 , 5 , - 1 ] ] NEW_LINE N = 3 NEW_LINE print ( findMinSum ( mat , N ) ) NEW_LINE DEDENT |
LCM of unique elements present in an array | Python3 program for the above approach ; Function to find GCD of two numbers ; Base Case ; Recursively find the GCD ; Function to find LCM of two numbers ; Function to find LCM of unique elements present in the array ; Stores the frequency of each number of the array ; Store the frequency of each element of the array ; Store the required result ; Traverse the map freq ; If the frequency of the current element is 1 , then update ans ; If there is no unique element , set lcm to - 1 ; Print the result ; Driver Code ; Function Call | from collections import defaultdict NEW_LINE def findGCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return findGCD ( b , a % b ) NEW_LINE DEDENT def findLCM ( a , b ) : NEW_LINE INDENT return ( a * b ) // findGCD ( a , b ) NEW_LINE DEDENT def uniqueElementsLCM ( arr , N ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT lcm = 1 NEW_LINE for i in freq : NEW_LINE INDENT if ( freq [ i ] == 1 ) : NEW_LINE INDENT lcm = findLCM ( lcm , i ) NEW_LINE DEDENT DEDENT if ( lcm == 1 ) : NEW_LINE INDENT lcm = - 1 NEW_LINE DEDENT print ( lcm ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 3 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE uniqueElementsLCM ( arr , N ) NEW_LINE DEDENT |
Minimize maximum difference between adjacent elements possible by removing a single array element | Python3 program to implement the above approach ; Function to find maximum difference between adjacent array elements ; Store the maximum difference ; Traverse the array ; Update maximum difference ; Function to calculate the minimum of maximum difference between adjacent array elements possible by removing a single array element ; Stores the required minimum ; Stores the updated array ; Skip the i - th element ; Update MinValue ; return MinValue ; Driver Code | import sys NEW_LINE def maxAdjacentDifference ( A ) : NEW_LINE INDENT diff = 0 NEW_LINE for i in range ( 1 , len ( A ) , 1 ) : NEW_LINE INDENT diff = max ( diff , A [ i ] - A [ i - 1 ] ) NEW_LINE DEDENT return diff NEW_LINE DEDENT def MinimumValue ( arr , N ) : NEW_LINE INDENT MinValue = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT new_arr = [ ] NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT new_arr . append ( arr [ j ] ) NEW_LINE DEDENT MinValue = min ( MinValue , maxAdjacentDifference ( new_arr ) ) NEW_LINE DEDENT return MinValue NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinimumValue ( arr , N ) ) NEW_LINE DEDENT |
Number of Antisymmetric Relations on a set of N elements | Python3 program for the above approach ; Function to calculate the value of x ^ y % mod in O ( log y ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the resultant value of x ^ y ; Function to count the number of antisymmetric relations in a set consisting of N elements ; Print the count of antisymmetric relations ; Driver Code | mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % mod NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def antisymmetricRelation ( N ) : NEW_LINE INDENT return ( power ( 2 , N ) * power ( 3 , ( N * N - N ) // 2 ) ) % mod NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE print ( antisymmetricRelation ( N ) ) NEW_LINE DEDENT |
Number of Asymmetric Relations on a set of N elements | Python3 program for the above approach ; Function to calculate x ^ y modulo ( 10 ^ 9 + 7 ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the final value of x ^ y ; Function to count the number of asymmetric relations in a set consisting of N elements ; Return the resultant count ; Driver Code | mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE x = x % mod 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 ) % mod ; NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def asymmetricRelation ( N ) : NEW_LINE INDENT return power ( 3 , ( N * N - N ) // 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( asymmetricRelation ( N ) ) NEW_LINE DEDENT |
Check if two vectors are collinear or not | Function to calculate cross product of two vectors ; Update cross_P [ 0 ] ; Update cross_P [ 1 ] ; Update cross_P [ 2 ] ; Function to check if two given vectors are collinear or not ; Store the first and second vectors ; Store their cross product ; Calculate their cross product ; Check if their cross product is a NULL Vector or not ; Driver Code ; Given coordinates of the two vectors | def crossProduct ( vect_A , vect_B , cross_P ) : NEW_LINE INDENT cross_P [ 0 ] = ( vect_A [ 1 ] * vect_B [ 2 ] - vect_A [ 2 ] * vect_B [ 1 ] ) NEW_LINE cross_P [ 1 ] = ( vect_A [ 2 ] * vect_B [ 0 ] - vect_A [ 0 ] * vect_B [ 2 ] ) NEW_LINE cross_P [ 2 ] = ( vect_A [ 0 ] * vect_B [ 1 ] - vect_A [ 1 ] * vect_B [ 0 ] ) NEW_LINE DEDENT def checkCollinearity ( x1 , y1 , z1 , x2 , y2 , z2 ) : NEW_LINE INDENT A = [ x1 , y1 , z1 ] NEW_LINE B = [ x2 , y2 , z2 ] NEW_LINE cross_P = [ 0 for i in range ( 3 ) ] NEW_LINE crossProduct ( A , B , cross_P ) NEW_LINE if ( cross_P [ 0 ] == 0 and cross_P [ 1 ] == 0 and cross_P [ 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 x1 = 4 NEW_LINE y1 = 8 NEW_LINE z1 = 12 NEW_LINE x2 = 8 NEW_LINE y2 = 16 NEW_LINE z2 = 24 NEW_LINE checkCollinearity ( x1 , y1 , z1 , x2 , y2 , z2 ) NEW_LINE DEDENT |
Program to calculate Kinetic Energy and Potential Energy | Function to calculate Kinetic Energy ; Stores the Kinetic Energy ; Function to calculate Potential Energy ; Stores the Potential Energy ; Driver Code | def kineticEnergy ( M , V ) : NEW_LINE INDENT KineticEnergy = 0.5 * M * V * V NEW_LINE return KineticEnergy NEW_LINE DEDENT def potentialEnergy ( M , H ) : NEW_LINE INDENT PotentialEnergy = M * 9.8 * H NEW_LINE return PotentialEnergy NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT M = 5.5 NEW_LINE H = 23.5 NEW_LINE V = 10.5 NEW_LINE print ( " Kinetic β Energy β = β " , kineticEnergy ( M , V ) ) NEW_LINE print ( " Potential β Energy β = β " , potentialEnergy ( M , H ) ) NEW_LINE DEDENT |
Count pairs with odd Bitwise XOR that can be removed and replaced by their Bitwise OR | Function to count the number of pairs required to be removed from the array and replaced by their Bitwise OR values ; Stores the count of even array elements ; Traverse the given array ; Increment the count of even array elements ; If the array contains at least one odd array element ; Otherwise , print 0 ; Driver Code | def countPairs ( arr , N ) : NEW_LINE INDENT even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT even += 1 NEW_LINE DEDENT DEDENT if ( N - even >= 1 ) : NEW_LINE INDENT print ( even ) NEW_LINE return NEW_LINE DEDENT print ( 0 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 7 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT |
Distribute M objects starting from Sth person such that every ith person gets arr [ i ] objects | Function to find distribution of M objects among all array elements ; Stores the distribution of M objects ; Stores the indices of distribution ; Stores the remaining objects ; Iterate until rem is positive ; If the number of remaining objects exceeds required the number of objects ; Increase the number of objects for the index ptr by arr [ ptr ] ; Decrease remaining objects by arr [ ptr ] ; Increase the number of objects for the index ptr by rem ; Decrease remaining objects to 0 ; Increase ptr by 1 ; Print the final distribution ; Driver Code | def distribute ( N , K , M , arr ) : NEW_LINE INDENT distribution = [ 0 ] * N NEW_LINE ptr = K - 1 NEW_LINE rem = M NEW_LINE while ( rem > 0 ) : NEW_LINE INDENT if ( rem >= arr [ ptr ] ) : NEW_LINE INDENT distribution [ ptr ] += arr [ ptr ] NEW_LINE rem -= arr [ ptr ] NEW_LINE DEDENT else : NEW_LINE INDENT distribution [ ptr ] += rem NEW_LINE rem = 0 NEW_LINE DEDENT ptr = ( ptr + 1 ) % N NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( distribution [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 2 , 1 , 4 ] NEW_LINE M = 11 NEW_LINE S = 2 NEW_LINE N = len ( arr ) NEW_LINE distribute ( N , S , M , arr ) NEW_LINE |
Sum of squares of differences between all pairs of an array | Function to calculate sum of squares of differences of all possible pairs ; Stores the final sum ; Stores temporary values ; Traverse the array ; Final sum ; Prthe answer ; Driver Code ; Given array ; Size of the array ; Function call to find sum of square of differences of all possible pairs | def sumOfSquaredDifferences ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE sumA , sumB = 0 , 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sumA += ( arr [ i ] * arr [ i ] ) NEW_LINE sumB += arr [ i ] NEW_LINE DEDENT sumA = N * sumA NEW_LINE sumB = ( sumB * sumB ) NEW_LINE ans = sumA - sumB NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 8 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE sumOfSquaredDifferences ( arr , N ) NEW_LINE DEDENT |
Count ways to remove objects such that exactly M equidistant objects remain | Function to count the number of ways of removing objects such that after removal , exactly M equidistant objects remain ; Store the resultant number of arrangements ; Base Case : When only 1 object is left ; Print the result and return ; Iterate until len <= n and increment the distance in each iteration ; Total length if adjacent objects are d distance apart ; If length > n ; Update the number of ways ; Print the result ; Driver Code | def waysToRemove ( n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( m == 1 ) : NEW_LINE INDENT print ( n ) NEW_LINE return NEW_LINE DEDENT d = 0 NEW_LINE while d >= 0 : NEW_LINE INDENT length = m + ( m - 1 ) * d NEW_LINE if ( length > n ) : NEW_LINE INDENT break NEW_LINE DEDENT ans += ( n - length ) + 1 NEW_LINE d += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE M = 3 NEW_LINE waysToRemove ( N , M ) NEW_LINE DEDENT |
Count unique stairs that can be reached by moving given number of steps forward or backward | Python3 program for the above approach ; Function to count the number of unique stairs visited ; Checks whether the current stair is visited or not ; Store the possible moves from the current position ; Initialize a queue ; Push the starting position ; Mark the starting position S as visited ; Iterate until queue is not empty ; Store the current stair number ; Check for all possible moves from the current stair ; Store the new stair number ; If it is valid and unvisited ; Push it into queue ; Mark the stair as visited ; Store the result ; Count the all visited stairs ; Print the result ; Driver Code | from collections import deque NEW_LINE def countStairs ( n , x , a , b ) : NEW_LINE INDENT vis = [ 0 ] * ( n + 1 ) NEW_LINE moves = [ + a , - a , + b , - b ] NEW_LINE q = deque ( ) NEW_LINE q . append ( x ) NEW_LINE vis [ x ] = 1 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT currentStair = q . popleft ( ) NEW_LINE for j in range ( 4 ) : NEW_LINE INDENT newStair = currentStair + moves [ j ] NEW_LINE if ( newStair > 0 and newStair <= n and ( not vis [ newStair ] ) ) : NEW_LINE INDENT q . append ( newStair ) NEW_LINE vis [ newStair ] = 1 NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( vis [ i ] == 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT print ( cnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , S , A , B = 10 , 2 , 5 , 7 NEW_LINE countStairs ( N , S , A , B ) NEW_LINE DEDENT |
Count smaller elements present in the array for each array element | Function to count for each array element , the number of elements that are smaller than that element ; Traverse the array ; Stores the count ; Traverse the array ; Increment count ; Print the count of smaller elements for the current element ; Driver Code | def smallerNumbers ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( arr [ j ] < arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 4 , 1 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE smallerNumbers ( arr , N ) NEW_LINE DEDENT |
Minimize divisions by 2 , 3 , or 5 required to make two given integers equal | Function to calculate GCD of two numbers ; Base Case ; Calculate GCD recursively ; Function to count the minimum number of divisions required to make X and Y equal ; Calculate GCD of X and Y ; Divide X and Y by their GCD ; Stores the number of divisions ; Iterate until X != Y ; Maintain the order X <= Y ; If X is divisible by 2 , then divide X by 2 ; If X is divisible by 3 , then divide X by 3 ; If X is divisible by 5 , then divide X by 5 ; If X is not divisible by 2 , 3 , or 5 , then pr - 1 ; Increment count by 1 ; Print the value of count as the minimum number of operations ; Driver Code | 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 minimumOperations ( X , Y ) : NEW_LINE INDENT GCD = gcd ( X , Y ) NEW_LINE X = X // GCD NEW_LINE Y = Y // GCD NEW_LINE count = 0 NEW_LINE while ( X != Y ) : NEW_LINE INDENT if ( Y > X ) : NEW_LINE INDENT X , Y = Y , X NEW_LINE DEDENT if ( X % 2 == 0 ) : NEW_LINE INDENT X = X // 2 NEW_LINE DEDENT elif ( X % 3 == 0 ) : NEW_LINE INDENT X = X // 3 NEW_LINE DEDENT elif ( X % 5 == 0 ) : NEW_LINE INDENT X = X // 5 NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT count += 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X , Y = 15 , 20 NEW_LINE minimumOperations ( X , Y ) NEW_LINE DEDENT |
Minimum increments or decrements required to convert a sorted array into a power sequence | Function to find the minimum number of increments or decrements required to convert array into a power sequence ; Initialize the count to f ( X ) for X = 1 ; Calculate the value of f ( X ) X ^ ( n - 1 ) <= f ( 1 ) + a [ n - 1 ] ; Calculate F ( x ) ; Check if X ^ ( n - 1 ) > f ( 1 ) + a [ n - 1 ] ; Update ans to store the minimum of ans and F ( x ) ; Return the minimum number of operations required ; Driver Code | def minOperations ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += a [ i ] NEW_LINE DEDENT ans -= n NEW_LINE x = 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT curPow = 1 NEW_LINE curCost = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curCost += abs ( a [ i ] - curPow ) NEW_LINE curPow *= x NEW_LINE DEDENT if ( curPow / x > ans + a [ n - 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = min ( ans , curCost ) NEW_LINE x += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N ) ) NEW_LINE DEDENT |
Find the absolute difference between the nearest powers of two given integers for every array element | Python3 program for the above approach ; Function to print the array ; Traverse the array ; Function to modify array elements by absolute difference of the nearest perfect power of a and b ; Traverse the array arr [ ] ; Find the log a of arr [ i ] ; Find the power of a less than and greater than a ; Find the log b of arr [ i ] ; Find the power of b less than and greater than b ; Update arr [ i ] with absolute difference of log_a & log _b ; Print the modified array ; Driver Code | import math NEW_LINE def printArray ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def nearestPowerDiff ( arr , N , a , b ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT log_a = int ( math . log ( arr [ i ] ) / math . log ( a ) ) NEW_LINE A = int ( pow ( a , log_a ) ) NEW_LINE B = int ( pow ( a , log_a + 1 ) ) NEW_LINE if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) : NEW_LINE INDENT log_a = A NEW_LINE DEDENT else : NEW_LINE INDENT log_a = B NEW_LINE DEDENT log_b = int ( math . log ( arr [ i ] ) / math . log ( b ) ) NEW_LINE A = int ( pow ( b , log_b ) ) NEW_LINE B = int ( pow ( b , log_b + 1 ) ) NEW_LINE if ( ( arr [ i ] - A ) < ( B - arr [ i ] ) ) : NEW_LINE INDENT log_b = A NEW_LINE DEDENT else : NEW_LINE INDENT log_b = B NEW_LINE DEDENT arr [ i ] = abs ( log_a - log_b ) NEW_LINE DEDENT printArray ( arr , N ) NEW_LINE DEDENT arr = [ 5 , 12 , 25 ] NEW_LINE A = 2 NEW_LINE B = 3 NEW_LINE N = len ( arr ) NEW_LINE nearestPowerDiff ( arr , N , A , B ) NEW_LINE |
Count subarrays having even Bitwise OR | Function to count the number of subarrays having even Bitwise OR ; Store number of subarrays having even bitwise OR ; Store the length of the current subarray having even numbers ; Traverse the array ; If the element is even ; Increment size of the current continuous sequence of even array elements ; If arr [ i ] is odd ; If length is non zero ; Adding contribution of subarrays consisting only of even numbers ; Make length of subarray as 0 ; Add contribution of previous subarray ; Return total count of subarrays ; Driver Code ; Function Call | def bitOr ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE length = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT length += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( length != 0 ) : NEW_LINE INDENT count += ( ( length ) * ( length + 1 ) ) // 2 NEW_LINE DEDENT length = 0 NEW_LINE DEDENT DEDENT count += ( ( length ) * ( length + 1 ) ) // 2 NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 4 , 2 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( bitOr ( arr , N ) ) NEW_LINE DEDENT |
Generate an array having sum of Bitwise OR of same | Function to print the resultant array ; Stores the sum of the array ; Calculate sum of the array ; If sum > K ; Not possible to construct the array ; Update K ; Stores the resultant array ; Traverse the array ; Stores the current element ; If jth bit is not set and value of 2 ^ j is less than K ; Update curr ; Update K ; Push curr into B ; If K is greater than 0 ; Print the vector B ; Otherwise ; Driver Code ; Input ; Size of the array ; Given input ; Function call to print the required array | def constructArr ( A , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT if ( sum > K ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT K -= sum NEW_LINE B = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr = A [ i ] NEW_LINE j = 32 NEW_LINE while ( j >= 0 and K > 0 ) : NEW_LINE INDENT if ( ( curr & ( 1 << j ) ) == 0 and ( 1 << j ) <= K ) : NEW_LINE INDENT curr |= ( 1 << j ) NEW_LINE K -= ( 1 << j ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT B . append ( curr ) NEW_LINE DEDENT if ( K == 0 ) : NEW_LINE INDENT for it in B : NEW_LINE INDENT print ( it , end = " β " ) NEW_LINE DEDENT print ( " " , end β = β " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE K = 32 NEW_LINE constructArr ( arr , N , K ) NEW_LINE DEDENT |
Find all pairs raised to power K differs by exactly N | Function to prpairs whose difference raised to the power K is X ; Stores the count of valid pairs ; Iterate over the range [ - 1000 , 1000 ] ; Iterate over the range [ - 1000 , 1000 ] ; If the current pair satisfies the given condition ; Increment the count by 1 ; If no such pair exists ; Driver Code | def ValidPairs ( X , K ) : NEW_LINE INDENT count = 0 NEW_LINE for A in range ( - 1000 , 1001 , 1 ) : NEW_LINE INDENT for B in range ( - 1000 , 1001 , 1 ) : NEW_LINE INDENT if ( pow ( A , K ) - pow ( B , K ) == X ) : NEW_LINE INDENT count += 1 NEW_LINE print ( A , B ) NEW_LINE DEDENT DEDENT DEDENT if ( count == 0 ) : NEW_LINE INDENT cout << " - 1" NEW_LINE DEDENT DEDENT X = 33 NEW_LINE K = 5 NEW_LINE ValidPairs ( X , K ) NEW_LINE |
Connect a graph by M edges such that the graph does not contain any cycle and Bitwise AND of connected vertices is maximum | Function to find the maximum Bitwise AND of connected components possible by connecting a graph using M edges ; Stores total number of ways to connect the graph ; Stores the maximum Bitwise AND ; Iterate over the range [ 0 , 2 ^ n ] ; Store the Bitwise AND of the connected vertices ; Store the count of the connected vertices ; Check for all the bits ; If i - th bit is set ; If the first vertex is added ; Set andans equal to arr [ i ] ; Calculate Bitwise AND of arr [ i ] with andans ; Increase the count of connected vertices ; If number of connected vertices is ( m + 1 ) , no cycle is formed ; Find the maximum Bitwise AND value possible ; Return the maximum Bitwise AND possible ; Driver Code | def maximumAND ( arr , n , m ) : NEW_LINE INDENT tot = 1 << n NEW_LINE mx = 0 NEW_LINE for bm in range ( tot ) : NEW_LINE INDENT andans = 0 NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( bm >> i ) & 1 ) : NEW_LINE INDENT if ( count == 0 ) : NEW_LINE INDENT andans = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT andans = andans & arr [ i ] NEW_LINE DEDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == ( m + 1 ) ) : NEW_LINE INDENT mx = max ( mx , andans ) NEW_LINE DEDENT DEDENT return mx NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE M = 2 NEW_LINE print ( maximumAND ( arr , N , M ) ) NEW_LINE DEDENT |
Calculate sum of the array generated by given operations | Function to find the sum of the array formed by performing given set of operations while traversing the array ops [ ] ; If the size of array is 0 ; Stores the required sum ; Traverse the array ops [ ] ; If the character is C , remove the top element from the stack ; If the character is D , then push 2 * top element into stack ; If the character is + , add sum of top two elements from the stack ; Otherwise , push x and add it to ans ; Print the resultant sum ; Driver Code | def findTotalSum ( ops ) : NEW_LINE INDENT if ( len ( ops ) == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT pts = [ ] NEW_LINE ans = 0 NEW_LINE for i in range ( len ( ops ) ) : NEW_LINE INDENT if ( ops [ i ] == " C " ) : NEW_LINE INDENT ans -= pts [ - 1 ] NEW_LINE pts . pop ( ) NEW_LINE DEDENT elif ( ops [ i ] == " D " ) : NEW_LINE INDENT pts . append ( pts [ - 1 ] * 2 ) NEW_LINE ans += pts [ - 1 ] NEW_LINE DEDENT elif ( ops [ i ] == " + " ) : NEW_LINE INDENT a = pts [ - 1 ] NEW_LINE pts . pop ( ) NEW_LINE b = pts [ - 1 ] NEW_LINE pts . append ( a ) NEW_LINE ans += ( a + b ) NEW_LINE pts . append ( a + b ) NEW_LINE DEDENT else : NEW_LINE INDENT n = int ( ops [ i ] ) NEW_LINE ans += n NEW_LINE pts . append ( n ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ "5" , " - 2" , " C " , " D " , " + " ] NEW_LINE findTotalSum ( arr ) NEW_LINE DEDENT |
XOR of major diagonal elements of a 3D Matrix | Function to calculate Bitwise XOR of major diagonal elements of 3D matrix ; Stores the Bitwise XOR of the major diagonal elements ; If element is part of major diagonal ; Print the resultant Bitwise XOR ; Driver Code | def findXOR ( mat , N ) : NEW_LINE INDENT XOR = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT for k in range ( N ) : NEW_LINE INDENT if ( ( i == j and j == k ) ) : NEW_LINE INDENT XOR ^= mat [ i ] [ j ] [ k ] NEW_LINE XOR ^= mat [ i ] [ j ] [ N - k - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( XOR ) NEW_LINE DEDENT mat = [ [ [ 1 , 2 ] , [ 3 , 4 ] ] , [ [ 5 , 6 ] , [ 7 , 8 ] ] ] NEW_LINE N = len ( mat ) NEW_LINE findXOR ( mat , N ) NEW_LINE |
XOR of major diagonal elements of a 3D Matrix | Function to find the Bitwise XOR of both diagonal elements of 3D matrix ; Stores the Bitwise XOR of the major diagonal elements ; Print the resultant Bitwise XOR ; Driver Code | def findXOR ( mat , N ) : NEW_LINE INDENT XOR = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT XOR ^= mat [ i ] [ i ] [ i ] NEW_LINE XOR ^= mat [ i ] [ i ] [ N - i - 1 ] NEW_LINE DEDENT print ( XOR ) NEW_LINE DEDENT mat = [ [ [ 1 , 2 ] , [ 3 , 4 ] ] , [ [ 5 , 6 ] , [ 7 , 8 ] ] ] NEW_LINE N = len ( mat ) NEW_LINE findXOR ( mat , N ) NEW_LINE |
Count of subtrees possible from an N | Python3 program of the above approach ; Adjacency list to represent the graph ; Stores the count of subtrees possible from given N - ary Tree ; Utility function to count the number of subtrees possible from given N - ary Tree ; Stores the count of subtrees when cur node is the root ; Traverse the adjacency list ; Iterate over every ancestor ; Calculate product of the number of subtrees for each child node ; Update the value of ans ; Return the resultant count ; Function to count the number of subtrees in the given tree ; Initialize an adjacency matrix ; Add the edges ; Function Call to count the number of subtrees possible ; Prcount of subtrees ; Driver Code | MAX = 300004 NEW_LINE graph = [ [ ] for i in range ( MAX ) ] NEW_LINE mod = 10 ** 9 + 7 NEW_LINE ans = 0 NEW_LINE def countSubtreesUtil ( cur , par ) : NEW_LINE INDENT global mod , ans NEW_LINE res = 1 NEW_LINE for i in range ( len ( graph [ cur ] ) ) : NEW_LINE INDENT v = graph [ cur ] [ i ] NEW_LINE if ( v == par ) : NEW_LINE INDENT continue NEW_LINE DEDENT res = ( res * ( countSubtreesUtil ( v , cur ) + 1 ) ) % mod NEW_LINE DEDENT ans = ( ans + res ) % mod NEW_LINE return res NEW_LINE DEDENT def countSubtrees ( N , adj ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT a = adj [ i ] [ 0 ] NEW_LINE b = adj [ i ] [ 1 ] NEW_LINE graph [ a ] . append ( b ) NEW_LINE graph [ b ] . append ( a ) NEW_LINE DEDENT countSubtreesUtil ( 1 , 1 ) NEW_LINE print ( ans + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE adj = [ [ 0 , 1 ] , [ 1 , 2 ] ] NEW_LINE countSubtrees ( N , adj ) NEW_LINE DEDENT |
Find the player who wins the game of placing alternate + and | Function to check which player wins the game ; Stores the difference between + ve and - ve array elements ; Traverse the array ; Update diff ; Checks if diff is even ; Driver Code ; Given Input ; Function call to check which player wins the game | def checkWinner ( arr , N ) : NEW_LINE INDENT diff = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT diff -= arr [ i ] NEW_LINE DEDENT if ( diff % 2 == 0 ) : NEW_LINE INDENT print ( " A " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " B " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE checkWinner ( arr , N ) NEW_LINE DEDENT |
Generate an array having sum of Euler Totient Function of all elements equal to N | Python3 program for the above approach ; Function to construct the array such the sum of values of Euler Totient functions of all array elements is N ; Stores the resultant array ; Find divisors in sqrt ( N ) ; If N is divisible by i ; Push the current divisor ; If N is not a perfect square ; Push the second divisor ; Print the resultant array ; Driver Code ; Function Call | from math import sqrt NEW_LINE def constructArray ( N ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( 1 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT ans . append ( i ) NEW_LINE if ( N != ( i * i ) ) : NEW_LINE INDENT ans . append ( N / i ) NEW_LINE DEDENT DEDENT DEDENT for it in ans : NEW_LINE INDENT print ( int ( it ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE constructArray ( N ) NEW_LINE DEDENT |
Place N boys and M girls in different rows such that count of persons placed in each row is maximized | Function to calculate GCD of two numbers ; Function to count maximum persons that can be placed in a row ; Driver Code ; Input ; Function to count maximum persons that can be placed in a row | 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 maximumRowValue ( n , m ) : NEW_LINE INDENT return gcd ( n , m ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE M = 2 NEW_LINE print ( maximumRowValue ( N , M ) ) NEW_LINE DEDENT |
Program to generate an array having convolution of two given arrays | Python3 program for the above approach ; Function to generate a convolution array of two given arrays ; Stores the size of arrays ; Stores the final array ; Traverse the two given arrays ; Update the convolution array ; Print the convolution array c [ ] ; Driver Code | MOD = 998244353 NEW_LINE def findConvolution ( a , b ) : NEW_LINE INDENT global MOD NEW_LINE n , m = len ( a ) , len ( b ) NEW_LINE c = [ 0 ] * ( n + m - 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT c [ i + j ] += ( a [ i ] * b [ j ] ) % MOD NEW_LINE DEDENT DEDENT for k in range ( len ( c ) ) : NEW_LINE INDENT c [ k ] %= MOD NEW_LINE print ( c [ k ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 ] NEW_LINE B = [ 5 , 6 , 7 , 8 , 9 ] NEW_LINE findConvolution ( A , B ) NEW_LINE DEDENT |
Minimum number of 1 s present in a submatrix of given dimensions in a Binary Matrix | Python3 program for the above approach ; Function to count number of 1 s present in a sub matrix from ( start_i , start_j ) to ( end_i , end_j ) ; Stores the number of 1 s present in current submatrix ; Traverse the submatrix ; If mat [ x ] [ y ] is equal to 1 ; Increase count by 1 ; Return the total count of 1 s ; Function to find the minimum number of 1 s present in a sub - matrix of size A * B or B * A ; Stores the minimum count of 1 s ; Iterate i from 0 to N ; Iterate j from 0 to M ; If a valid sub matrix of size A * B from ( i , j ) is possible ; Count the number of 1 s present in the sub matrix of size A * B from ( i , j ) ; Update minimum if count is less than the current minimum ; If a valid sub matrix of size B * A from ( i , j ) is possible ; Count the number of 1 s in the sub matrix of size B * A from ( i , j ) ; Update minimum if count is less than the current minimum ; Return minimum as the final result ; Driver Code ; Given Input ; Function call to find the minimum number of 1 s in a submatrix of size A * B or B * A | P = 51 NEW_LINE def count1s ( start_i , start_j , end_i , end_j , mat ) : NEW_LINE INDENT count = 0 NEW_LINE for x in range ( start_i , end_i ) : NEW_LINE INDENT for y in range ( start_j , end_j ) : NEW_LINE INDENT if ( mat [ x ] [ y ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def findMinimumCount ( N , M , A , B , mat ) : NEW_LINE INDENT minimum = 1e9 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( i + A <= N and j + B <= M ) : NEW_LINE INDENT count = count1s ( i , j , i + A , j + B , mat ) NEW_LINE minimum = min ( count , minimum ) NEW_LINE DEDENT if ( i + B <= N and j + A <= M ) : NEW_LINE INDENT count = count1s ( i , j , i + B , j + A , mat ) NEW_LINE minimum = min ( count , minimum ) NEW_LINE DEDENT DEDENT DEDENT return minimum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 2 NEW_LINE B = 2 NEW_LINE N = 3 NEW_LINE M = 4 NEW_LINE mat = [ [ 1 , 0 , 1 , 0 ] , [ 0 , 1 , 0 , 1 ] , [ 1 , 0 , 1 , 0 ] ] NEW_LINE print ( findMinimumCount ( N , M , A , B , mat ) ) NEW_LINE DEDENT |
Program to check if a number can be expressed as an even power of 2 or not | Function to check if N can be expressed as an even power of 2 ; Iterate till x is N ; If x is even then return true ; Increment x ; If N is not a power of 2 ; Driver Code | def checkEvenPower ( n ) : NEW_LINE INDENT x = 0 NEW_LINE while ( x < n ) : NEW_LINE INDENT value = pow ( 2 , x ) NEW_LINE if ( value == n ) : NEW_LINE INDENT if ( x % 2 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT x += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE if checkEvenPower ( N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Program to check if a number can be expressed as an even power of 2 or not | Function to check if N can be expressed as an even power of 2 or not ; Iterate until low > high ; Calculate mid ; If 2 ^ mid is equal to n ; If mid is odd ; Update the value of low ; Update the value of high ; Otherwise ; Driver code | def checkEvenPower ( n ) : NEW_LINE INDENT low , high = 0 , n NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) / 2 NEW_LINE value = pow ( 2 , mid ) NEW_LINE if ( value == n ) : NEW_LINE INDENT if ( mid % 2 == 1 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT else : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT elif ( value < n ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return " No " NEW_LINE DEDENT N = 4 NEW_LINE print ( checkEvenPower ( N ) ) NEW_LINE |
Program to check if a number can be expressed as an even power of 2 or not | Function to check if N can be expressed as an even power of 2 or not ; If N is not a power of 2 ; Bitwise AND operation ; Driver Code | def checkEvenPower ( N ) : NEW_LINE INDENT if ( ( N & ( N - 1 ) ) != 0 ) : NEW_LINE INDENT return false NEW_LINE DEDENT N = N & 0x55555555 NEW_LINE return ( N > 0 ) NEW_LINE DEDENT N = 4 NEW_LINE print ( 1 if checkEvenPower ( N ) else 0 ) NEW_LINE |
Sum of quotients of division of N by powers of K not exceeding N | Function to calculate sum of quotients obtained by dividing N by powers of K <= N ; Store the required sum ; Iterate until i exceeds N ; Update sum ; Multiply i by K to obtain next power of K ; Prthe result ; Driver Code ; Given N and K | def findSum ( N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE i = 1 NEW_LINE while ( i <= N ) : NEW_LINE INDENT ans += N // i NEW_LINE i = i * K NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K = 10 , 2 NEW_LINE findSum ( N , K ) NEW_LINE DEDENT |
Count Arithmetic Progressions having sum S and common difference equal to D | Function to count the number of APs with sum S and common difference D ; Multiply S by 2 ; Stores the count of APs ; Iterate over the factors of 2 * S ; Check if i is the factor or not ; Conditions to check if AP can be formed using factor F ; Return the total count of APs ; Driver Code | def countAPs ( S , D ) : NEW_LINE INDENT S = S * 2 NEW_LINE answer = 0 NEW_LINE for i in range ( 1 , S ) : NEW_LINE INDENT if i * i > S : NEW_LINE INDENT break NEW_LINE DEDENT if ( S % i == 0 ) : NEW_LINE INDENT if ( ( ( S // i ) - D * i + D ) % 2 == 0 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT if ( ( D * i - ( S // i ) + D ) % 2 == 0 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , D = 12 , 1 NEW_LINE print ( countAPs ( S , D ) ) ; NEW_LINE DEDENT |
Minimize insertions to make sum of every pair of consecutive array elements at most K | Function to count minimum number of insertions required to make sum of every pair of adjacent elements at most K ; Stores if it is possible to make sum of each pair of adjacent elements at most K ; Stores the count of insertions ; Stores the previous value to index i ; Traverse the array ; If arr [ i ] is greater than or equal to K ; Mark possible 0 ; If last + arr [ i ] is greater than K ; Increment res by 1 ; Assign arr [ i ] to last ; If possible to make the sum of pairs of adjacent elements at most K ; Otherwise print " - 1" ; Driver Code | def minimumInsertions ( arr , N , K ) : NEW_LINE INDENT possible = 1 NEW_LINE res = 0 NEW_LINE last = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= K ) : NEW_LINE INDENT possible = 0 NEW_LINE break NEW_LINE DEDENT if ( last + arr [ i ] > K ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT last = arr [ i ] NEW_LINE DEDENT if ( possible ) : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE K = 6 NEW_LINE N = len ( arr ) NEW_LINE minimumInsertions ( arr , N , K ) NEW_LINE DEDENT |
Maximum sum of K | Function to count the number of distinct elements present in the array ; Insert all elements into the Set ; Return the size of set ; Function that finds the maximum sum of K - length subarray having same unique elements as arr [ ] ; Not possible to find a subarray of size K ; Initialize Set ; Calculate sum of the distinct elements ; If the set size is same as the count of distinct elements ; Update the maximum value ; Driver code ; Stores the count of distinct elements | def distinct ( arr , n ) : NEW_LINE INDENT mpp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mpp [ arr [ i ] ] = 1 NEW_LINE DEDENT return len ( mpp ) NEW_LINE DEDENT def maxSubSum ( arr , n , k , totalDistinct ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxm = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE st = set ( ) NEW_LINE for j in range ( i , i + k , 1 ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE st . add ( arr [ j ] ) NEW_LINE DEDENT if ( len ( st ) == totalDistinct ) : NEW_LINE INDENT maxm = max ( sum , maxm ) NEW_LINE DEDENT DEDENT return maxm NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ] NEW_LINE K = 6 NEW_LINE N = len ( arr ) NEW_LINE totalDistinct = distinct ( arr , N ) NEW_LINE print ( maxSubSum ( arr , N , K , totalDistinct ) ) NEW_LINE DEDENT |
Maximum sum of K | Function to count the number of distinct elements present in the array ; Insert array elements into set ; Return the st size ; Function to calculate maximum sum of K - length subarray having same unique elements as arr [ ] ; Not possible to find an subarray of length K from an N - sized array , if K > N ; Traverse the array ; Update the mp ; If i >= K , then decrement arr [ i - K ] element 's one occurence ; If frequency of any element is 0 then remove the element ; If mp size is same as the count of distinct elements of array arr [ ] then update maximum sum ; Function that finds the maximum sum of K - length subarray having same number of distinct elements as the original array ; Size of array ; Stores count of distinct elements ; Print maximum subarray sum ; Driver Code ; Function Call | def distinct ( arr , N ) : NEW_LINE INDENT st = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT st . add ( arr [ i ] ) NEW_LINE DEDENT return len ( st ) NEW_LINE DEDENT def maxSubarraySumUtil ( arr , N , K , totalDistinct ) : NEW_LINE INDENT if ( K > N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT mx = 0 NEW_LINE sum = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] in mp ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT sum += arr [ i ] NEW_LINE if ( i >= K ) : NEW_LINE INDENT if ( arr [ i - K ] in mp ) : NEW_LINE INDENT mp [ arr [ i - K ] ] -= 1 NEW_LINE sum -= arr [ i - K ] NEW_LINE DEDENT if ( arr [ i - K ] in mp and mp [ arr [ i - K ] ] == 0 ) : NEW_LINE INDENT mp . remove ( arr [ i - K ] ) NEW_LINE DEDENT DEDENT if ( len ( mp ) == totalDistinct ) : NEW_LINE INDENT mx = max ( mx , sum ) NEW_LINE DEDENT DEDENT return mx NEW_LINE DEDENT def maxSubarraySum ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE totalDistinct = distinct ( arr , N ) NEW_LINE print ( maxSubarraySumUtil ( arr , N , K , totalDistinct ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 7 , 2 , 4 , 2 , 7 , 4 , 6 , 6 , 6 ] NEW_LINE K = 6 NEW_LINE maxSubarraySum ( arr , K ) NEW_LINE DEDENT |
Number of Irreflexive Relations on a Set | Python3 program for the above approach ; Function to calculate x ^ y modulo 1000000007 in O ( log y ) ; Stores the result of x ^ y ; Update x if it exceeds mod ; If x is divisible by mod ; If y is odd , then multiply x with result ; Divide y by 2 ; Update the value of x ; Return the resultant value of x ^ y ; Function to count the number of irreflixive relations in a set consisting of N elements ; Return the resultant count ; Driver Code | mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT global mod NEW_LINE res = 1 NEW_LINE x = x % mod 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 ) % mod NEW_LINE DEDENT y = y >> 1 NEW_LINE x = ( x * x ) % mod NEW_LINE DEDENT return res NEW_LINE DEDENT def irreflexiveRelation ( N ) : NEW_LINE INDENT return power ( 2 , N * N - N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE print ( irreflexiveRelation ( N ) ) NEW_LINE DEDENT |
Count Arithmetic Progressions having sum N and common difference equal to 1 | Function to count all possible AP series with common difference 1 and sum of elements equal to N ; Stores the count of AP series ; Traverse through all factors of 2 * N ; Check for the given conditions ; Increment count ; Prcount - 1 ; Given value of N ; Function call to count required number of AP series | def countAPs ( N ) : NEW_LINE INDENT count = 0 NEW_LINE i = 1 NEW_LINE while ( i * i <= 2 * N ) : NEW_LINE INDENT res = 2 * N NEW_LINE if ( res % i == 0 ) : NEW_LINE INDENT op = res / i - i + 1 NEW_LINE if ( op % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( i * i != res and ( i - res / i + 1 ) % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT print ( count - 1 ) NEW_LINE DEDENT N = 963761198400 NEW_LINE countAPs ( N ) NEW_LINE |
Check if concatenation of first and last digits forms a prime number or not for each array element | Stores if i is prime ( 1 ) or non - prime ( 0 ) ; Function to build sieve array ; Inititalize all the values in sieve equals to 1 ; Sieve of Eratosthenes ; If current number is prime ; Set all multiples as non - prime ; Function to check if the numbers formed by combining first and last digits generates a prime number or not ; Check if any of the numbers formed is a prime number or not ; Traverse the array of queries ; Extract the last digit ; Extract the first digit ; If any of the two numbers is prime ; Otherwise ; Driver Code ; Computes and stores primes using Sieve ; Function call to perform queries | sieve = [ 0 for i in range ( 105 ) ] NEW_LINE def buildSieve ( ) : NEW_LINE INDENT global sieve NEW_LINE for i in range ( 2 , 100 ) : NEW_LINE INDENT sieve [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , 100 ) : NEW_LINE INDENT if ( sieve [ i ] == 1 ) : NEW_LINE INDENT for j in range ( i * i , 100 , i ) : NEW_LINE INDENT sieve [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT def isAnyPrime ( first , last ) : NEW_LINE INDENT global sieve NEW_LINE num1 = first * 10 + last NEW_LINE num2 = last * 10 + first NEW_LINE if ( sieve [ num1 ] == 1 or sieve [ num2 ] == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def performQueries ( q ) : NEW_LINE INDENT for i in range ( len ( q ) ) : NEW_LINE INDENT A = q [ i ] NEW_LINE last = A % 10 NEW_LINE first = 0 NEW_LINE while ( A >= 10 ) : NEW_LINE INDENT A = A // 10 NEW_LINE DEDENT first = A NEW_LINE if ( isAnyPrime ( first , last ) ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT q = [ 30 , 66 ] NEW_LINE buildSieve ( ) NEW_LINE performQueries ( q ) NEW_LINE DEDENT |
Check if a given number N has at least one odd divisor not exceeding N | Function to check whether N has at least one odd divisor not exceeding N - 1 or not ; Stores the value of N ; Reduce the given number N by dividing it by 2 ; If N is divisible by an odd divisor i ; Check if N is an odd divisor after reducing N by dividing it by 2 ; Otherwise ; Driver Code ; Function Call | def oddDivisor ( N ) : NEW_LINE INDENT X = N NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT N //= 2 NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i <= X ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT i += 2 NEW_LINE DEDENT if ( N != X ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT N = 10 NEW_LINE print ( oddDivisor ( N ) ) NEW_LINE |
Minimize steps required to make two values equal by repeated division by any of their prime factor which is less than M | Stores the prime factor of numbers ; Function to find GCD of a and b ; Base Case ; Otherwise , calculate GCD ; Function to precompute the prime numbers till 1000000 ; Initialize all the positions with their respective values ; Iterate over the range [ 2 , sqrt ( 10 ^ 6 ) ] ; If i is prime number ; Mark it as the factor ; Utility function to count the number of steps to make X and Y equal ; Initialise steps ; Iterate x is at most 1 ; Divide with the smallest prime factor ; If X and Y can 't be made equal ; Return steps ; Function to find the minimum number of steps required to make X and Y equal ; Generate all the prime factors ; Calculate GCD of x and y ; Divide the numbers by their gcd ; If not possible , then return - 1 ; Return the resultant number of steps ; Driver Code | primes = [ 0 ] * ( 1000006 ) NEW_LINE 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 preprocess ( ) : NEW_LINE INDENT for i in range ( 1 , 1000001 ) : NEW_LINE INDENT primes [ i ] = i NEW_LINE DEDENT i = 2 NEW_LINE while ( i * i <= 1000000 ) : NEW_LINE INDENT if ( primes [ i ] == i ) : NEW_LINE INDENT for j in range ( 2 * i , 1000001 , i ) : NEW_LINE INDENT if ( primes [ j ] == j ) : NEW_LINE INDENT primes [ j ] = i NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def Steps ( x , m ) : NEW_LINE INDENT steps = 0 NEW_LINE flag = False NEW_LINE while ( x > 1 ) : NEW_LINE INDENT if ( primes [ x ] > m ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT x //= primes [ x ] NEW_LINE steps += 1 NEW_LINE DEDENT if ( flag != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return steps NEW_LINE DEDENT def minimumSteps ( x , y , m ) : NEW_LINE INDENT preprocess ( ) NEW_LINE g = gcd ( x , y ) NEW_LINE x = x // g NEW_LINE y = y // g NEW_LINE x_steps = Steps ( x , m ) NEW_LINE y_steps = Steps ( y , m ) NEW_LINE if ( x_steps == - 1 or y_steps == - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return x_steps + y_steps NEW_LINE DEDENT X = 160 NEW_LINE Y = 180 NEW_LINE M = 10 NEW_LINE print ( minimumSteps ( X , Y , M ) ) NEW_LINE |
Length of longest subsequence consisting of Non | Python3 program for the above approach ; Function to check if n is a deficient number or not ; Stores sum of divisors ; Iterate over the range [ 1 , sqrt ( N ) ] ; If n is divisible by i ; If divisors are equal , add only one of them ; Otherwise add both ; Function to print the longest subsequence which does not contain any deficient numbers ; Stores the count of array elements which are non - deficient ; Traverse the array ; If element is non - deficient ; Return the answer ; Driver Code | import math NEW_LINE def isNonDeficient ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n // i == i ) : NEW_LINE INDENT sum = sum + i NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + i NEW_LINE sum = sum + ( n // i ) NEW_LINE DEDENT DEDENT DEDENT return sum >= 2 * n NEW_LINE DEDENT def LongestNonDeficientSubsequence ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isNonDeficient ( arr [ i ] ) ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 13 , 55 , 240 , 32 , 24 , 27 , 56 , 80 , 100 , 330 , 89 ] NEW_LINE N = len ( arr ) NEW_LINE print ( LongestNonDeficientSubsequence ( arr , N ) ) NEW_LINE DEDENT |
Number of subarrays consisting only of Pronic Numbers | Function to check if a number is pronic number or not ; Iterate over the range [ 1 , sqrt ( N ) ] ; Return true if N is pronic ; Otherwise , return false ; Function to count the number of subarrays consisting of pronic numbers ; Stores the count of subarrays ; Stores the number of consecutive array elements which are pronic ; Traverse the array ; If i is pronic ; Return the total count ; Driver Code | def isPronic ( n ) : NEW_LINE INDENT for i in range ( int ( n ** ( 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if i * ( i + 1 ) == n : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def countSub ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE ispro = 0 NEW_LINE for i in arr : NEW_LINE INDENT if isPronic ( i ) : NEW_LINE INDENT ispro += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ispro = 0 NEW_LINE DEDENT ans += ispro NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 6 , 12 , 3 , 4 ] NEW_LINE print ( countSub ( arr ) ) NEW_LINE |
Replace all array elements with the nearest power of its previous element | Python3 program for the above approach ; Function to calculate log x for given base ; Function to replace all array elements with the nearest power of previous adjacent nelement ; For the first element , set the last array element to its previous element ; Traverse the array ; Find K for which x ^ k is nearest to arr [ i ] ; Find the power to x nearest to arr [ i ] ; Update x ; Return the array ; Driver Code ; Function Call | import math NEW_LINE def LOG ( x , base ) : NEW_LINE INDENT return int ( math . log ( x ) / math . log ( base ) ) NEW_LINE DEDENT def repbyNP ( arr ) : NEW_LINE INDENT x = arr [ - 1 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT k = LOG ( arr [ i ] , x ) NEW_LINE temp = arr [ i ] NEW_LINE if abs ( x ** k - arr [ i ] ) < abs ( x ** ( k + 1 ) - arr [ i ] ) : NEW_LINE INDENT arr [ i ] = x ** k NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = x ** ( k + 1 ) NEW_LINE DEDENT x = temp NEW_LINE DEDENT return arr NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 3 , 11 ] NEW_LINE print ( repbyNP ( arr ) ) NEW_LINE |
Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element | Function to find the last remaining array element after performing the given operations repeatedly ; Stores the resultant sum ; Traverse the array ; Increment sum by arr [ i ] * coefficient of i - th term in ( x - y ) ^ ( N - 1 ) ; Update multiplier ; Return the resultant sum ; Driver Code | def lastElement ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE if n % 2 == 0 : NEW_LINE INDENT multiplier = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT multiplier = 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] * multiplier NEW_LINE multiplier = multiplier * ( n - 1 - i ) / ( i + 1 ) * ( - 1 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( int ( lastElement ( arr , N ) ) ) NEW_LINE DEDENT |
Maximize count of pairs whose bitwise XOR is even by replacing such pairs with their Bitwise XOR | Function to maximize the count of pairs with even XOR possible in an array by given operations ; Stores count of odd array elements ; Traverse the array ; If arr [ i ] is odd ; Stores the total number of even pairs ; Driver Code ; Input ; Function call to count the number of pairs whose XOR is even | def countPairs ( arr , N ) : NEW_LINE INDENT odd = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT DEDENT ans = ( N - odd + odd // 2 - 1 ) + odd // 2 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 6 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT |
Maximize count of pairs whose Bitwise AND exceeds Bitwise XOR by replacing such pairs with their Bitwise AND | Python3 program for the above approach ; Function to count the number of pairs whose Bitwise AND is greater than the Bitwise XOR ; Stores the frequency of MSB of array elements ; Traverse the array ; Increment count of numbers having MSB at log ( arr [ i ] ) ; Stores total number of pairs ; Traverse the Map ; Return total count of pairs ; Driver Code | from math import log2 NEW_LINE def countPairs ( arr , N ) : NEW_LINE INDENT freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = int ( log2 ( arr [ i ] ) ) NEW_LINE freq [ x ] = freq . get ( x , 0 ) + 1 NEW_LINE DEDENT pairs = 0 NEW_LINE for i in freq : NEW_LINE INDENT pairs += freq [ i ] - 1 NEW_LINE DEDENT return pairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 9 , 15 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE DEDENT |
Subsets and Splits