text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Count tiles of dimensions 2 * 1 that can be placed in an M * N rectangular board that satisfies the given conditions | Function to count tiles of dimensions 2 x 1 that can be placed in a grid of dimensions M * N as per given conditions ; Number of tiles required ; Driver Code
def numberOfTiles ( N , M ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( N * M ) // 2 NEW_LINE DEDENT N = 2 NEW_LINE M = 4 NEW_LINE print ( numberOfTiles ( N , M ) ) NEW_LINE
Check if an array can be converted to another given array by swapping pairs of unequal elements | Function to check if arr1 [ ] can be converted to arr2 [ ] by swapping pair ( i , j ) such that i < j and arr [ i ] is 1 and arr [ j ] is 0 ; Stores the differences of prefix sum of arr1 and arr2 ; Stores the count of 1 and zero of arr1 ; Stores the count of 1 and zero of arr2 ; Iterate in the range [ 0 , N - 1 ] ; If arr1 [ i ] is 1 , then increment arr1_one by one ; Otherwise increment arr1_zero by one ; If arr2 [ i ] is 1 , then increment arr2_one by one ; Otherwise increment arr2_zero by one ; Check if number of 1 s and 0 s of arr1 is equal to number of 1 s and 0 s of arr2 respectievly ; Iterate over the range [ 0 , N - 1 ] ; Increment count by differences arr1 [ i ] and arr2 [ i ] ; Check if number of 1 's in arr2 are more than arr1 and then print "No" ; Finally , print " Yes " ; Driver Code ; Given input a ; Size of the array ; Function Call
def canMakeEqual ( arr1 , arr2 , N ) : NEW_LINE INDENT count = 0 NEW_LINE arr1_one = 0 NEW_LINE arr1_zero = 0 NEW_LINE arr2_one = 0 NEW_LINE arr2_zero = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr1 [ i ] == 1 ) : NEW_LINE INDENT arr1_one += 1 NEW_LINE DEDENT elif ( arr1 [ i ] == 0 ) : NEW_LINE INDENT arr1_zero += 1 NEW_LINE DEDENT if ( arr2 [ i ] == 1 ) : NEW_LINE INDENT arr2_one += 1 NEW_LINE DEDENT elif ( arr2 [ i ] == 0 ) : NEW_LINE INDENT arr2_zero += 1 NEW_LINE DEDENT DEDENT if ( arr1_one != arr2_one or arr1_zero != arr2_zero ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT count = count + ( arr1 [ i ] - arr2 [ i ] ) NEW_LINE if ( count < 0 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 0 , 1 , 1 , 0 ] NEW_LINE arr2 = [ 0 , 0 , 1 , 1 ] NEW_LINE N = len ( arr1 ) NEW_LINE canMakeEqual ( arr1 , arr2 , N ) NEW_LINE DEDENT
Check for each subarray whether it consists of all natural numbers up to its length or not | Function to check if a subarray of size i exists that contain all the numbers in the range [ 1 , i ] ; Store the position of each element of arr [ ] ; Traverse the array ; Insert the position of arr [ i ] ; Store position of each element from the range [ 1 , N ] ; Iterate over the range [ 1 , N ] ; Insert the index of i into st ; Find the smallest element of st ; Find the largest element of st ; If distance between the largest and smallest element of arr [ ] till i - th index is equal to i ; Driver Code
def checksubarrayExist1_N ( arr , N ) : NEW_LINE INDENT pos = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT pos [ arr [ i ] ] = i NEW_LINE DEDENT st = { } NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT st [ pos [ i ] ] = 1 NEW_LINE Min = sorted ( list ( st . keys ( ) ) ) [ 0 ] NEW_LINE Max = sorted ( list ( st . keys ( ) ) ) [ - 1 ] NEW_LINE if ( Max - Min + 1 == i ) : NEW_LINE INDENT print ( " True " , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 3 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE checksubarrayExist1_N ( arr , N ) NEW_LINE DEDENT
Check if a pair of integers A and B can coincide by shifting them by distances arr [ ( A % N + N ) % N ] and arr [ ( B % N + N ) % N ] | Function to check if two integers coincide at a point ; Store the final position of integers A and B ; Iterate over the range [ 0 , n ] ; Store the final position of the integer i ; If temp is present in the Map ; Print Yes and return ; Mark its final position as visited ; If every integer stored in the Map is unique ; Driver Code
def checkSamePosition ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = ( ( i + arr [ i ] ) % n + n ) % n NEW_LINE if temp in mp : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT if ( temp in mp ) : NEW_LINE INDENT mp [ temp ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ temp ] = mp . get ( temp , 0 ) + 1 NEW_LINE DEDENT DEDENT print ( " No " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE checkSamePosition ( arr , N ) NEW_LINE DEDENT
Sum of Fibonacci Numbers | Set 2 | Python program for the above approach ; Function to find the sum of first N + 1 fibonacci numbers ; Apply the formula ; Prthe result ; Driver Code
import math NEW_LINE def sumFib ( N ) : NEW_LINE INDENT num = round ( pow ( ( pow ( 5 , 1 / 2 ) + 1 ) \ / 2.0 , N + 2 ) / pow ( 5 , 1 / 2 ) ) ; NEW_LINE print ( num - 1 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 ; NEW_LINE sumFib ( N ) ; NEW_LINE DEDENT
Sum of Fibonacci Numbers | Set 2 | Pyhton3 program for the above approach ; Function to find the sum of first N + 1 fibonacci numbers ; Apply the formula ; Print the result ; Driver Code ; Function Call
import math NEW_LINE def sumFib ( N ) : NEW_LINE INDENT num = ( 1 - math . sqrt ( 5 ) ) / 2 NEW_LINE val = round ( abs ( 1 / ( pow ( num , N + 2 ) + pow ( num , N + 1 ) + pow ( num , N ) + pow ( num , N - 1 ) ) ) - 1 ) NEW_LINE print ( val ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE sumFib ( N ) NEW_LINE DEDENT
Minimum number of pigs required to find the poisonous bucket | Python program for the above approach ; Function to find the minimum number of pigs required to find the poisonous bucket ; Prthe result ; Driver Code
import math NEW_LINE def poorPigs ( buckets , minutesToDie , minutesToTest ) : NEW_LINE INDENT print ( math . ceil ( math . log ( buckets ) // math . log ( ( minutesToTest \ // minutesToDie ) + 1 ) ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1000 ; NEW_LINE M = 15 ; NEW_LINE P = 60 ; NEW_LINE poorPigs ( N , M , P ) ; NEW_LINE DEDENT
Maximum product of the remaining pair after repeatedly replacing pairs of adjacent array elements with their sum | Python program for the above approach ; Function to find the maximum product possible after repeatedly replacing pairs of adjacent array elements with their sum ; Store the maximum product ; Store the prefix sum ; Store the total sum of array ; Traverse the array to find the total sum ; Iterate in the range [ 0 , N - 2 ] ; Add arr [ i ] to prefix_sum ; Store the value of prefix_sum ; Store the value of ( total sum - prefix sum ) ; Update the maximum product ; Print the answer ; Driver Code
import sys NEW_LINE def maxProduct ( arr , N ) : NEW_LINE INDENT max_product = - sys . maxsize ; NEW_LINE prefix_sum = 0 ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT prefix_sum += arr [ i ] ; NEW_LINE X = prefix_sum ; NEW_LINE Y = sum - prefix_sum ; NEW_LINE max_product = max ( max_product , X * Y ) ; NEW_LINE DEDENT print ( max_product ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 6 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE maxProduct ( arr , N ) ; NEW_LINE DEDENT
Find array elements with rightmost set bit at the position of the rightmost set bit in K | Function to find the mask for finding rightmost set bit in K ; Function to find all array elements with rightmost set bit same as that in K ; Stores mask of K ; Store position of rightmost set bit ; Traverse the array ; Check if rightmost set bit of current array element is same as position of rightmost set bit in K ; Driver Code ; Input ; Function call to find the elements having same rightmost set bit as of K
def findMask ( K ) : NEW_LINE INDENT mask = 1 ; NEW_LINE while ( ( K & mask ) == 0 ) : NEW_LINE INDENT mask = mask << 1 ; NEW_LINE DEDENT return mask ; NEW_LINE DEDENT def sameRightSetBitPos ( arr , N , K ) : NEW_LINE INDENT mask = findMask ( K ) ; NEW_LINE pos = ( K & mask ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ( arr [ i ] & mask ) == pos ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 6 , 7 , 9 , 12 , 15 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 7 ; NEW_LINE sameRightSetBitPos ( arr , N , K ) ; NEW_LINE DEDENT
Count Pronic numbers from a given range | Python3 program for the above approach ; Function to check if x is a Pronic Number or not ; Check for Pronic Number by multiplying consecutive numbers ; Function to count pronic numbers in the range [ A , B ] ; Initialise count ; Iterate from A to B ; If i is pronic ; Increment count ; Prcount ; Driver Code ; Function call to count pronic numbers in the range [ A , B ]
import math NEW_LINE def checkPronic ( x ) : NEW_LINE INDENT for i in range ( int ( math . sqrt ( x ) ) + 1 ) : NEW_LINE INDENT if ( x == i * ( i + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def countPronic ( A , B ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( A , B + 1 ) : NEW_LINE INDENT if ( checkPronic ( i ) != 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT A = 3 NEW_LINE B = 20 NEW_LINE countPronic ( A , B ) NEW_LINE
Count Pronic numbers from a given range | Function to count pronic numbers in the range [ A , B ] ; Check upto sqrt N ; If product of consecutive numbers are less than equal to num ; Return N - 1 ; Function to count pronic numbers in the range [ A , B ] ; Subtract the count of pronic numbers which are <= ( A - 1 ) from the count f pronic numbers which are <= B ; Driver Code ; Function call to count pronic numbers in the range [ A , B ]
def pronic ( num ) : NEW_LINE INDENT N = int ( num ** ( 1 / 2 ) ) ; NEW_LINE if ( N * ( N + 1 ) <= num ) : NEW_LINE INDENT return N ; NEW_LINE DEDENT return N - 1 ; NEW_LINE DEDENT def countPronic ( A , B ) : NEW_LINE INDENT return pronic ( B ) - pronic ( A - 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 3 ; NEW_LINE B = 20 ; NEW_LINE print ( countPronic ( A , B ) ) ; NEW_LINE DEDENT
Count integers from a given range with no odd divisors | Function to count integers in the range 1 to N having no odd divisors ; Traverse the array ; Stores the nearest power of two less than arr [ i ] ; Stores the count of integers with no odd divisor for each query ; Iterate until powerOfTwo is less then or equal to arr [ i ] ; Print the answer for the current element ; Driver Code ; Given array ; Size of the array
def oddDivisors ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT powerOfTwo = 2 ; NEW_LINE count = 0 ; NEW_LINE while ( powerOfTwo <= arr [ i ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE powerOfTwo = 2 * powerOfTwo ; NEW_LINE DEDENT print ( count , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 15 , 16 , 20 , 35 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE oddDivisors ( arr , N ) ; NEW_LINE DEDENT
Check if all array elements can be reduced to 0 by repeatedly reducing pairs of consecutive elements by their minimum | Function to check if it is possible to convert the array ; Traverse the array range [ 1 , N - 1 ] ; If arr [ i ] < arr [ i - 1 ] ; Otherwise ; Decrement arr [ i ] by arr [ i - 1 ] ; If arr [ n - 1 ] is not equal to zero ; Otherwise ; Driver Code ; Function Call
def checkPossible ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE return ; NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] -= arr [ i - 1 ] ; NEW_LINE arr [ i - 1 ] = 0 ; NEW_LINE DEDENT DEDENT if ( arr [ n - 1 ] == 0 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 3 , 4 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE checkPossible ( arr , N ) ; NEW_LINE DEDENT
Nearest smaller power of 2 for every digit of a number | Python 3 program for the above approach ; Function to find the nearest power of two for every digit of a given number ; Converting number to string ; Traverse the array ; Calculate log base 2 of the current digit s [ i ] ; Highest power of 2 <= s [ i ] ; ASCII conversion ; Driver Code
import math NEW_LINE def highestPowerOfTwo ( num ) : NEW_LINE INDENT s = str ( num ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT print ( "0" ) NEW_LINE continue NEW_LINE DEDENT lg = int ( math . log2 ( ord ( s [ i ] ) - 48 ) ) NEW_LINE p = pow ( 2 , lg ) NEW_LINE print ( chr ( p + 48 ) , end = " " ) NEW_LINE DEDENT DEDENT num = 4317 NEW_LINE highestPowerOfTwo ( num ) NEW_LINE
Maximum prefix sum after K reversals of a given array | Python3 program for the above approach ; Function to find the maximum prefix sum after K reversals of the array ; Stores the required sum ; If K is odd , reverse the array ; Store current prefix sum of array ; Traverse the array arr [ ] ; Add arr [ i ] to currsum ; Update maximum prefix sum till now ; Prthe answer ; Driver Code ; Function Call
import sys NEW_LINE def maxSumAfterKReverse ( arr , K , N ) : NEW_LINE INDENT sum = - sys . maxsize - 1 NEW_LINE if ( K & 1 ) : NEW_LINE INDENT arr . reverse ( ) NEW_LINE DEDENT currsum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT currsum += arr [ i ] NEW_LINE sum = max ( sum , currsum ) NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT arr = [ 1 , 5 , 8 , 9 , 11 , 2 ] NEW_LINE K = 1 NEW_LINE N = len ( arr ) NEW_LINE maxSumAfterKReverse ( arr , K , N ) NEW_LINE
Print all submasks of a given mask | Function to print the submasks of N ; Driven Code
def SubMasks ( N ) : NEW_LINE INDENT S = N NEW_LINE while S > 0 : NEW_LINE INDENT print ( S , end = ' ▁ ' ) NEW_LINE S = ( S - 1 ) & N NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE SubMasks ( N ) NEW_LINE DEDENT
Count pairs from a given range having equal Bitwise OR and XOR values | Function to calculate ( x ^ y ) % MOD ; Initialize result ; Update x if it is more than or equal to MOD ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Return ( x ^ y ) % MOD ; Function to count total pairs ; The upper bound is 2 ^ N ; Stores the count of pairs ; Generate all possible pairs ; Find XOR of both integers ; Find OR of both integers ; If both are equal ; Increment count ; Print count % MOD ; Driver Code ; Function Call
def power ( x , y ) : NEW_LINE INDENT MOD = 1000000007 NEW_LINE 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 countPairs ( N ) : NEW_LINE INDENT MOD = 1000000007 NEW_LINE high = power ( 2 , N ) NEW_LINE count = 0 NEW_LINE for i in range ( high ) : NEW_LINE INDENT for j in range ( high ) : NEW_LINE INDENT X = ( i ^ j ) NEW_LINE Y = ( i j ) NEW_LINE if ( X == Y ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count % MOD ) NEW_LINE DEDENT N = 10 NEW_LINE countPairs ( N ) NEW_LINE
Count pairs from a given range having equal Bitwise OR and XOR values | Python program for the above approach ; Function to find the value of ( x ^ y ) % MOD ; Initialize result ; Update x if it is more than or equal to MOD ; If y is odd , multiply x with result ; y must be even now , then update y / 2 ; Return ( x ^ y ) % MOD ; Function to count total pairs ; Finding 3 ^ N % 10 ^ 9 + 7 ; Driver Code ; Function Call
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 % 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 countPairs ( N ) : NEW_LINE INDENT print ( power ( 3 , N ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 ; NEW_LINE countPairs ( N ) ; NEW_LINE DEDENT
Minimize swaps required to place largest and smallest array elements at first and last array indices | Python 3 program for the above approach ; Function to find the minimum count of adjacent swaps to move largest and smallest element at the first and the last index of the array , respectively ; Stores the smallest array element ; Stores the smallest array element ; Stores the last occurrence of the smallest array element ; Stores the first occurrence of the largest array element ; Traverse the array arr [ ] ; If a [ i ] is less than min_element ; Update min_element ; Update min_ind ; If a [ i ] is greater than max_element ; Update max_element ; Update max_ind ; If max_ind is equal to min_ind ; Return 0 ; If max_ind is greater than min_ind ; Otherwise ; Driver Code ; Input ; Print the result
import sys NEW_LINE def minimumMoves ( a , n ) : NEW_LINE INDENT min_element = sys . maxsize NEW_LINE max_element = - sys . maxsize - 1 NEW_LINE min_ind = - 1 NEW_LINE max_ind = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] <= min_element ) : NEW_LINE INDENT min_element = a [ i ] NEW_LINE min_ind = i NEW_LINE DEDENT if ( a [ i ] > max_element ) : NEW_LINE INDENT max_element = a [ i ] NEW_LINE max_ind = i NEW_LINE DEDENT DEDENT if ( max_ind == min_ind ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( max_ind > min_ind ) : NEW_LINE INDENT return max_ind + ( n - min_ind - 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return max_ind + n - min_ind - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 35 , 46 , 17 , 23 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimumMoves ( arr , N ) ) NEW_LINE DEDENT
Find the index of the smallest element to be removed to make sum of array divisible by K | Function to find index of the smallest array element required to be removed to make sum divisible by K ; Stores sum of array elements ; Stores index of the smallest element removed from the array to make sum divisible by K ; Stores the smallest element removed from the array to make sum divisible by K ; Traverse the array , arr [ ] ; Update sum ; Traverse the array arr [ ] ; Calculate remaining sum ; If sum is divisible by K ; If res == - 1 or mini is greater than arr [ i ] ; Update res and mini ; Driver Code
def findIndex ( arr , n , K ) : NEW_LINE INDENT sum = 0 NEW_LINE res = - 1 NEW_LINE mini = 1e9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT temp = sum - arr [ i ] NEW_LINE if ( temp % K == 0 ) : NEW_LINE INDENT if ( res == - 1 or mini > arr [ i ] ) : NEW_LINE INDENT res = i + 1 NEW_LINE mini = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return res ; NEW_LINE DEDENT arr = [ 14 , 7 , 8 , 2 , 4 ] NEW_LINE K = 7 NEW_LINE N = len ( arr ) NEW_LINE print ( findIndex ( arr , N , K ) ) NEW_LINE
Count subarrays having a single distinct element that can be obtained from a given array | python 3 program for the above approach ; Function to count subarrays of single distinct element into which given array can be split ; Stores the count ; Stores frequency of array elements ; Traverse the array ; Traverse the map ; Increase count of subarrays by ( frequency - 1 ) ; Driver Code
from collections import defaultdict NEW_LINE def divisionalArrays ( arr , N ) : NEW_LINE INDENT sum = N NEW_LINE mp = defaultdict ( int ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT for x in mp : NEW_LINE INDENT if ( mp [ x ] > 1 ) : NEW_LINE INDENT sum += mp [ x ] - 1 NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE divisionalArrays ( arr , N ) NEW_LINE DEDENT
Count inversions in a sequence generated by appending given array K times | Function to count the number of inversions in K copies of given array ; Stores count of inversions in the given array ; Stores the count of pairs of distinct array elements ; Traverse the array ; Generate each pair ; Check for each pair , if the condition is satisfied or not ; If pairs consist of distinct elements ; Count inversiosn in the sequence ; Prthe answer ; Given array ; Given K ; Size of the array
def totalInversions ( arr , K , N ) : NEW_LINE INDENT inv = 0 NEW_LINE X = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and i < j ) : NEW_LINE INDENT inv += 1 NEW_LINE DEDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT X += 1 NEW_LINE DEDENT DEDENT DEDENT totalInv = X * K * ( K - 1 ) // 2 + inv * K NEW_LINE print ( totalInv ) NEW_LINE DEDENT arr = [ 2 , 1 , 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE totalInversions ( arr , K , N ) NEW_LINE
Count ways to generate an array having distinct elements at M consecutive indices | Modular function to calculate factorial ; Stores factorial of N ; Iterate over the range [ 1 , N ] ; Update result ; Function to count ways to replace array elements having 0 s with non - zero elements such that any M consecutive elements are distinct ; Store m consecutive distinct elements such that arr [ i ] is equal to B [ i % M ] ; Stores frequency of array elements ; Traverse the array arr ; If arr [ i ] is non - zero ; If B [ i % M ] is equal to 0 ; Update B [ i % M ] ; Update frequency of arr [ i ] ; If a duplicate element found in M consecutive elements ; Handling the case of inequality ; Stores count of 0 s in B ; Traverse the array , B ; If B [ i ] is 0 ; Update cnt ; Calculate factorial ; Driver Code ; Given M ; Given array ; Size of the array ; Function Call
def Fact ( N ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT result = ( result * i ) NEW_LINE DEDENT return result NEW_LINE DEDENT def numberOfWays ( M , arr , N ) : NEW_LINE INDENT B = [ 0 ] * ( M ) NEW_LINE counter = [ 0 ] * ( M + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT if ( B [ i % M ] == 0 ) : NEW_LINE INDENT B [ i % M ] = arr [ i ] NEW_LINE counter [ arr [ i ] ] += 1 NEW_LINE if ( counter [ arr [ i ] ] > 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT DEDENT elif ( B [ i % M ] != arr [ i ] ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT if ( B [ i ] == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT print ( Fact ( cnt ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 4 NEW_LINE arr = [ 1 , 0 , 3 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE numberOfWays ( M , arr , N ) NEW_LINE DEDENT
Maximize sum by traversing diagonally from each cell of a given Matrix | Function to find the maximum sum ; Loop to traverse through the upper triangular matrix and update the maximum sum to ans ; Traverse through the lower triangular matrix ; Driver Code ; Given matrix ; Given dimension
def MaximumSum ( arr , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT x , y , sum = 0 , i , 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum , x , y = sum + arr [ x ] [ y ] , x + 1 , y + 1 NEW_LINE DEDENT if ( sum > ans ) : NEW_LINE INDENT ans = sum NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT x , y , sum = i , 0 , 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum , x , y = sum + arr [ x ] [ y ] , x + 1 , y + 1 NEW_LINE DEDENT if ( sum > ans ) : NEW_LINE INDENT ans = sum NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 3 , 5 , 10 ] , [ 1 , 3 , 5 ] ] NEW_LINE n = len ( arr ) NEW_LINE print ( MaximumSum ( arr , n ) ) NEW_LINE DEDENT
Count array elements exceeding all previous elements as well as the next array element | Function to count array elements satisfying the given condition ; If there is only one array element ; Traverse the array ; Update the maximum element encountered so far ; Count the number of array elements strictly greater than all previous and immediately next elements ; Print the count ; Given array ; Size of the array
def numberOfIntegers ( arr , N ) : NEW_LINE INDENT cur_max = 0 NEW_LINE count = 0 NEW_LINE if ( N == 1 ) : NEW_LINE INDENT count = 1 NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] > cur_max ) : NEW_LINE INDENT cur_max = arr [ i ] NEW_LINE if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT if ( arr [ N - 1 ] > cur_max ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT arr = [ 1 , 2 , 0 , 7 , 2 , 0 , 2 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE numberOfIntegers ( arr , N ) NEW_LINE
Count ways to represent N as sum of powers of 2 | Python3 program for above implementation ; Base Cases ; Check if 2 ^ k can be used as one of the numbers or not ; Otherwise ; Count number of ways to N using 2 ^ k - 1 ; Driver Code
from math import log2 NEW_LINE def numberOfWays ( n , k ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n >= pow ( 2 , k ) ) : NEW_LINE INDENT curr_val = pow ( 2 , k ) NEW_LINE return numberOfWays ( n - curr_val , k ) + numberOfWays ( n , k - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return numberOfWays ( n , k - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE k = log2 ( n ) NEW_LINE print ( numberOfWays ( n , k ) ) NEW_LINE DEDENT
Count ways to obtain triplets with positive product consisting of at most one negative element | Function to calculate possible number of triplets ; counting frequency of positive numbers in array ; If current array element is positive ; Increment frequency ; Select a triplet from freq elements such that i < j < k . ; Driver Code
def possibleTriplets ( arr , N ) : NEW_LINE INDENT freq = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT freq += 1 NEW_LINE DEDENT DEDENT return ( freq * ( freq - 1 ) * ( freq - 2 ) ) // 6 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 5 , - 9 , - 3 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( possibleTriplets ( arr , N ) ) NEW_LINE DEDENT
Maximize difference between sum of even and odd | Function to find the maximum possible difference between sum of even and odd indices ; Convert arr [ ] o 1 - based indexing ; Reverse the array ; Convert arr [ ] o 1 based index ; Reverse the array ; Stores maximum difference between sum of even and odd indexed elements ; Traverse the array ; If arr [ i ] is local maxima ; Update maxDiff ; If arr [ i ] is local minima ; Update maxDiff ; Driver Code ; Size of array ; Function Call
def maxPossibleDiff ( arr , N ) : NEW_LINE INDENT arr . append ( - 1 ) NEW_LINE arr = arr [ : : - 1 ] NEW_LINE arr . append ( - 1 ) NEW_LINE arr = arr [ : : - 1 ] NEW_LINE maxDiff = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] and arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT maxDiff += arr [ i ] NEW_LINE DEDENT if ( arr [ i ] < arr [ i - 1 ] and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT maxDiff -= arr [ i ] NEW_LINE DEDENT DEDENT print ( maxDiff ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 4 , 5 , 2 , 1 , 7 , 8 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE maxPossibleDiff ( arr , N ) NEW_LINE DEDENT
Reverse all elements of given circular array starting from index K | Function to print array arr [ ] ; Print the array ; Function to reverse elements of given circular array starting from index k ; Initialize two variables as start = k and end = k - 1 ; Initialize count = N / 2 ; Loop while count > 0 ; Swap the elements at index ( start % N ) and ( end % N ) ; Update the start and end ; If end equals to - 1 set end = N - 1 ; Print the circular array ; Driver Code ; Function Call
def printArray ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def reverseCircularArray ( arr , N , K ) : NEW_LINE INDENT start , end = K , K - 1 NEW_LINE count = N // 2 NEW_LINE while ( count ) : NEW_LINE INDENT temp = arr [ start % N ] NEW_LINE arr [ start % N ] = arr [ end % N ] NEW_LINE arr [ end % N ] = temp NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE if ( end == - 1 ) : NEW_LINE INDENT end = N - 1 NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT printArray ( arr , N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 2 , 4 , 1 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE reverseCircularArray ( arr , N , K ) NEW_LINE DEDENT
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix | Function to find the matrix , A [ ] [ ] satisfying the given conditions ; Store the final matrix ; Initialize all the elements of the matrix A with 1 ; Traverse the matrix B [ ] [ ] row - wise ; If B [ i ] [ j ] is equal to 0 ; Mark all the elements of ith row of A [ ] [ ] as 0 ; Mark all the elements of jth column of A [ ] [ ] as 0 ; Check if the matrix B [ ] [ ] can be made using matrix A [ ] [ ] ; Store the bitwise OR of all elements of A [ ] [ ] in ith row and jth column ; Traverse through ith row ; Traverse through jth column ; If B [ i ] [ j ] is not equal to c , pr " Not ▁ Possible " ; Print the final matrix A [ ] [ ] ; Driver Code ; Function Call
def findOriginalMatrix ( B , N , M ) : NEW_LINE INDENT A = [ [ 0 ] * M ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT A [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( B [ i ] [ j ] == 0 ) : NEW_LINE INDENT for k in range ( M ) : NEW_LINE INDENT A [ i ] [ k ] = 0 NEW_LINE DEDENT for k in range ( N ) : NEW_LINE INDENT A [ k ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT c = 0 NEW_LINE for k in range ( M ) : NEW_LINE INDENT if ( c == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT c += A [ i ] [ k ] NEW_LINE DEDENT for k in range ( N ) : NEW_LINE INDENT if ( c == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT c += A [ k ] [ j ] NEW_LINE DEDENT if ( c != B [ i ] [ j ] ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( A [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT B = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] NEW_LINE N = len ( B ) NEW_LINE M = len ( B [ 0 ] ) NEW_LINE findOriginalMatrix ( B , N , M ) NEW_LINE
Minimize cost to make X and Y equal by given increments | Function to find gcd of x and y ; Function to find lcm of x and y ; Function to find minimum Cost ; Subtracted initial cost of x ; Subtracted initial cost of y ; Driver Code ; Returns the minimum cost required
def gcd ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return x NEW_LINE DEDENT return gcd ( y , x % y ) NEW_LINE DEDENT def lcm ( x , y ) : NEW_LINE INDENT return ( x * y ) // gcd ( x , y ) NEW_LINE DEDENT def minimumCost ( x , y ) : NEW_LINE INDENT lcm_ = lcm ( x , y ) NEW_LINE costx = ( lcm_ - x ) // x NEW_LINE costy = ( lcm_ - y ) // y NEW_LINE return costx + costy NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 5 NEW_LINE y = 17 NEW_LINE print ( minimumCost ( x , y ) ) NEW_LINE DEDENT
Find GCD between the sum of two given integers raised to the power of N and their difference | Python program for the above approach ; Function to find the value of ( a ^ n ) % d ; Stores the value of ( a ^ n ) % d ; Calculate the value of ( a ^ n ) % d ; If n is odd ; Update res ; Update a ; Update n ; Function to find the GCD of ( p ^ n + q ^ n ) and p - q mod d ; If p and q are equal ; Stores GCD of ( p ^ n + q ^ n ) and ( p - q ) mod d ; Stores the value of ( p - q ) ; Stores square root of num ; Find the divisors of num . ; If i divides num ; Stores power of ( p ^ n ) mod i ; Stores power of ( q ^ n ) mod i ; Stores power of ( p ^ n + q ^ n ) mod i ; If ( p ^ n + q ^ n ) is divisible by i ; Calculate the largest divisor . ; If i divides num , ( num / i ) also divides num . Hence , calculate temp . ; If ( p ^ n + q ^ n ) is divisible by ( num / i ) ; Calculate the largest divisor . ; Driver code ; Given p , q and n ; Function Call
import math NEW_LINE mod = 1000000007 ; NEW_LINE def power ( a , n , d ) : NEW_LINE INDENT res = 1 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( ( n % 2 ) != 0 ) : NEW_LINE INDENT res = ( ( res % d ) * ( a % d ) ) % d ; NEW_LINE DEDENT a = ( ( a % d ) * ( a % d ) ) % d ; NEW_LINE n /= 2 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def gcd ( p , q , n ) : NEW_LINE INDENT if ( p == q ) : NEW_LINE INDENT return ( power ( p , n , mod ) + power ( q , n , mod ) ) % mod ; NEW_LINE DEDENT candidate = 1 ; NEW_LINE num = p - q ; NEW_LINE sq = ( int ) ( math . sqrt ( num ) ) ; NEW_LINE for i in range ( 1 , sq ) : NEW_LINE INDENT if ( num % i == 0 ) : NEW_LINE INDENT X = power ( p , n , i ) ; NEW_LINE Y = power ( q , n , i ) ; NEW_LINE temp = ( X + Y ) % i ; NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT candidate = max ( candidate , i ) ; NEW_LINE DEDENT temp = ( power ( p , n , num / i ) + power ( q , n , num / i ) ) % ( num / i ) ; NEW_LINE if ( temp == 0 ) : NEW_LINE INDENT candidate = max ( candidate , num / i ) ; NEW_LINE DEDENT DEDENT DEDENT return candidate % mod ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 10 ; NEW_LINE q = 6 ; NEW_LINE n = 5 ; NEW_LINE print ( ( int ) ( gcd ( p , q , n ) ) ) ; NEW_LINE DEDENT
Split given isosceles triangle of height H into N equal parts | Function to divide the isosceles triangle in equal parts by making N - 1 cuts parallel to the base ; Iterate over the range [ 1 , n - 1 ] ; Driver Code ; Given N ; Given H ; Function call
def findPoint ( n , h ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT print ( " { 0 : . 2f } " . format ( ( ( i / n ) ** 0.5 ) * h ) , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE h = 2 NEW_LINE findPoint ( n , h ) NEW_LINE DEDENT
Count all possible values of K less than Y such that GCD ( X , Y ) = GCD ( X + K , Y ) | Function to find the gcd of a and b ; Function to find the number of Ks ; Find gcd ; Calculating value of totient function for n ; Driver Code ; Given X and Y
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 calculateK ( x , y ) : NEW_LINE INDENT g = gcd ( x , y ) NEW_LINE n = y // g NEW_LINE res = n NEW_LINE i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT res -= ( res // i ) NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n //= i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT if ( n != 1 ) : NEW_LINE INDENT res -= ( res // n ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 3 NEW_LINE y = 15 NEW_LINE print ( calculateK ( x , y ) ) NEW_LINE DEDENT
Check if a Float value is equivalent to an Integer value | Function to check if N is equivalent to an integer ; Convert float value of N to integer ; If N is not equivalent to any integer ; Driver Code
def isInteger ( N ) : NEW_LINE INDENT X = int ( N ) NEW_LINE temp2 = N - X NEW_LINE if ( temp2 > 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 1.5 NEW_LINE if ( isInteger ( N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Find the nearest power of 2 for every array element | Python program to implement the above approach ; Function to find the nearest power of two for every array element ; Traverse the array ; Calculate log of current array element ; Find the nearest ; Driver Code
import math NEW_LINE def nearestPowerOfTwo ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT lg = ( int ) ( math . log2 ( arr [ i ] ) ) NEW_LINE a = ( int ) ( math . pow ( 2 , lg ) ) NEW_LINE b = ( int ) ( math . pow ( 2 , lg + 1 ) ) NEW_LINE if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) : NEW_LINE INDENT print ( a , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( b , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 2 , 7 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE nearestPowerOfTwo ( arr , N ) NEW_LINE
Flip bits of the sum of count of set bits of two given numbers | Python3 program for the above approach ; Function to count number of set bits in integer ; Variable for counting set bits ; Function to invert bits of a number ; Calculate number of bits of N - 1 ; ; Function to invert the sum of set bits in A and B ; Stores sum of set bits ; Driver Code
import math NEW_LINE def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT n &= ( n - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def invertBits ( n ) : NEW_LINE INDENT x = ( int ) ( math . log ( n ) / math . log ( 2 ) ) NEW_LINE m = 1 << x NEW_LINE m = m | m - 1 NEW_LINE n = n ^ m NEW_LINE return n NEW_LINE DEDENT def invertSum ( A , B ) : NEW_LINE INDENT temp = countSetBits ( A ) + countSetBits ( B ) NEW_LINE print ( invertBits ( temp ) ) NEW_LINE DEDENT A = 5 NEW_LINE B = 7 NEW_LINE invertSum ( A , B ) NEW_LINE
Sum of Bitwise XOR of each array element with all other array elements | Function to calculate for each array element , sum of its Bitwise XOR with all other array elements ; Declare an array of size 64 to store count of each bit ; Traversing the array ; Check if bit is present of not ; Increase the bit position ; Reduce the number to half ; Traverse the array ; Stores the bit position ; Stores the sum of Bitwise XOR ; Check if bit is present of not ; Reduce the number to its half ; Print the sum for A [ i ] ; Given arr1 [ ] ; Size of N ; Function Call
def XOR_for_every_i ( A , N ) : NEW_LINE INDENT frequency_of_bits = [ 0 ] * 32 NEW_LINE for i in range ( N ) : NEW_LINE INDENT bit_position = 0 NEW_LINE M = A [ i ] NEW_LINE while ( M ) : NEW_LINE INDENT if ( M & 1 != 0 ) : NEW_LINE INDENT frequency_of_bits [ bit_position ] += 1 NEW_LINE DEDENT bit_position += 1 NEW_LINE M >>= 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT M = A [ i ] NEW_LINE value_at_that_bit = 1 NEW_LINE XOR_sum = 0 NEW_LINE for bit_position in range ( 32 ) : NEW_LINE INDENT if ( M & 1 != 0 ) : NEW_LINE INDENT XOR_sum += ( ( N - frequency_of_bits [ bit_position ] ) * value_at_that_bit ) NEW_LINE DEDENT else : NEW_LINE INDENT XOR_sum += ( ( frequency_of_bits [ bit_position ] ) * value_at_that_bit ) NEW_LINE DEDENT M >>= 1 NEW_LINE value_at_that_bit <<= 1 NEW_LINE DEDENT print ( XOR_sum , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT A = [ 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE XOR_for_every_i ( A , N ) NEW_LINE
Minimize the maximum difference of any pair by doubling odd elements and reducing even elements by half | Function to minimize the maximum difference between any pair of elements of the array by the given operations ; Traverse the array ; If current element is even ; Insert it into even ; Otherwise ; Make it even by multiplying by 2 and insert it into set ; Calculate difference between first and the last element of the set ; Iterate until difference is minimized ; Erase the current element ; Reduce current element by half and insert it into the Set ; Update difference ; Return the resultant difference ; Driver Code
def minimumMaxDiff ( nums ) : NEW_LINE INDENT s = { } NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT if ( nums [ i ] % 2 == 0 ) : NEW_LINE INDENT s [ nums [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ nums [ i ] * 2 ] = 1 NEW_LINE DEDENT DEDENT sr = list ( s . keys ( ) ) NEW_LINE res = sr [ - 1 ] - sr [ 0 ] NEW_LINE while ( list ( s . keys ( ) ) [ - 1 ] % 2 == 0 ) : NEW_LINE INDENT r = list ( s . keys ( ) ) NEW_LINE x = r [ - 1 ] NEW_LINE del s [ x ] NEW_LINE s [ x // 2 ] = 1 NEW_LINE rr = list ( s . keys ( ) ) NEW_LINE res = min ( res , rr [ - 1 ] - r [ 0 ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 9 ] NEW_LINE print ( minimumMaxDiff ( arr ) ) NEW_LINE DEDENT
XOR of all even numbers from a given range | Function to calculate XOR of numbers in the range [ 1 , n ] ; If n is divisible by 4 ; If n mod 4 is equal to 1 ; If n mod 4 is equal to 2 ; Function to find XOR of even numbers in the range [ l , r ] ; Update xor_r ; Update xor_l ; Driver Code
def bitwiseXorRange ( n ) : NEW_LINE INDENT if ( n % 4 == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( n % 4 == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n % 4 == 2 ) : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def evenXorRange ( l , r ) : NEW_LINE INDENT xor_r = 2 * bitwiseXorRange ( r // 2 ) NEW_LINE xor_l = 2 * bitwiseXorRange ( ( l - 1 ) // 2 ) NEW_LINE return xor_l ^ xor_r NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 10 NEW_LINE r = 20 NEW_LINE print ( evenXorRange ( l , r ) ) NEW_LINE DEDENT
Program to calculate Variance of first N Natural Numbers | Function to calculate Variance of first N natural numbers ; Driver Code
def find_Variance ( n ) : NEW_LINE INDENT numerator = n * n - 1 NEW_LINE ans = ( numerator * 1.0 ) / 12 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE a = find_Variance ( N ) NEW_LINE print ( " { 0 : . 6f } " . format ( a ) ) NEW_LINE DEDENT
Count digits present in each element of a given Matrix | Python3 program for the above approach ; Function to count the number of digits in each element of the given matrix ; Traverse each row of arr [ ] [ ] ; Traverse each column of arr [ ] [ ] ; Store the current matrix element ; Count the number of digits ; Print the result ; Driver Code ; Given matrix
from math import floor , log10 NEW_LINE M = 3 NEW_LINE N = 3 NEW_LINE def countDigit ( arr ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT X = arr [ i ] [ j ] NEW_LINE d = floor ( log10 ( X ) * 1.0 ) + 1 NEW_LINE print ( d , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 27 , 173 , 5 ] , [ 21 , 6 , 624 ] , [ 5 , 321 , 49 ] ] NEW_LINE countDigit ( arr ) NEW_LINE DEDENT
Difference between sum of odd and even frequent elements in an Array | Function to find the sum of all even and odd frequent elements in an array ; Stores the frequency of array elements ; Traverse the array ; Update frequency of current element ; Stores sum of odd and even frequent elements ; Traverse the map ; If frequency is odd ; Add sum of all occurrences of current element to sum_odd ; If frequency is even ; Add sum of all occurrences of current element to sum_even ; Calculate difference between their sum ; Return diff ; Driver code
def findSum ( arr , N ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( 0 , 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 sum_odd , sum_even = 0 , 0 NEW_LINE for itr in mp : NEW_LINE INDENT if ( mp [ itr ] % 2 != 0 ) : NEW_LINE INDENT sum_odd += ( itr ) * ( mp [ itr ] ) NEW_LINE DEDENT if ( mp [ itr ] % 2 == 0 ) : NEW_LINE INDENT sum_even += ( itr ) * ( mp [ itr ] ) NEW_LINE DEDENT DEDENT diff = sum_even - sum_odd NEW_LINE return diff NEW_LINE DEDENT arr = [ 1 , 5 , 5 , 2 , 4 , 3 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findSum ( arr , N ) ) NEW_LINE
Count N | Function to find the number of arrays following the given condition ; Initialize answer ; Calculate nPm ; Print ans ; Driver Code ; Given N and M ; Function Call
def noOfArraysPossible ( N , M ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans = ans * ( M - i ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE M = 3 NEW_LINE noOfArraysPossible ( N , M ) NEW_LINE DEDENT
Permutations of an array having sum of Bitwise AND of adjacent elements at least K | Python3 program for the above approach ; Function to print all permutations of arr [ ] such that the sum of Bitwise AND of all adjacent element is at least K ; To check if any permutation exists or not ; Sort the given array ; Find all possible permutations ; Stores the sum of bitwise AND of adjacent elements of the current permutation ; Traverse the current permutation of arr [ ] ; Update the sum ; If the sum is at least K , then print the current permutation ; Set the flag variable ; Print the current permutation ; If flag is unset , then print - 1 ; Driver Code ; Function Call
def next_permutation ( a ) : NEW_LINE INDENT for i in reversed ( range ( len ( a ) - 1 ) ) : NEW_LINE INDENT if a [ i ] < a [ i + 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT j = next ( j for j in reversed ( range ( i + 1 , len ( a ) ) ) if a [ i ] < a [ j ] ) NEW_LINE a [ i ] , a [ j ] = a [ j ] , a [ i ] NEW_LINE a [ i + 1 : ] = reversed ( a [ i + 1 : ] ) NEW_LINE return True NEW_LINE DEDENT def printPermutation ( arr , n , k ) : NEW_LINE INDENT flag = False NEW_LINE arr . sort ( ) NEW_LINE while True : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT sum += arr [ i ] & arr [ i + 1 ] NEW_LINE DEDENT if ( sum >= k ) : NEW_LINE INDENT flag = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if ( next_permutation ( arr ) == False ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE K = 8 NEW_LINE N = len ( arr ) NEW_LINE printPermutation ( arr , N , K ) NEW_LINE
Positive integers up to N that are not present in given Array | Function to find positive integers from 1 to N that are not present in the array ; Declare bitset ; Iterate from 0 to M - 1 ; Iterate from 0 to n - 1 ; Iterate from bset . _Find_first ( ) to bset . size ( ) - 1 ; Driver Code
def findMissingNumbers ( arr , n ) : NEW_LINE INDENT M = 15 NEW_LINE bset = [ 0 ] * M NEW_LINE for i in range ( M ) : NEW_LINE INDENT bset [ i ] = i NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT bset [ arr [ i ] - 1 ] = 0 NEW_LINE DEDENT bset = [ i for i in bset if i != 0 ] NEW_LINE for i in range ( len ( bset ) ) : NEW_LINE INDENT if ( bset [ i ] + 1 > n ) : NEW_LINE INDENT break NEW_LINE DEDENT print ( bset [ i ] + 1 ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 6 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE findMissingNumbers ( arr , n ) NEW_LINE DEDENT
Sum of the first N terms of XOR Fibonacci series | Function to calculate the sum of the first N terms of XOR Fibonacci Series ; Base case ; Stores the sum of the first N terms ; Iterate from [ 0 , n - 3 ] ; Store XOR of last 2 elements ; Update sum ; Update the first element ; Update the second element ; Print the final sum ; Driver code ; Function call
def findSum ( a , b , N ) : NEW_LINE INDENT if N == 1 : NEW_LINE INDENT print ( a ) NEW_LINE return NEW_LINE DEDENT s = a + b NEW_LINE for i in range ( 0 , N - 2 ) : NEW_LINE INDENT x = a ^ b NEW_LINE s += x NEW_LINE a = b NEW_LINE b = x NEW_LINE DEDENT print ( s ) NEW_LINE return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 2 NEW_LINE b = 5 NEW_LINE N = 8 NEW_LINE findSum ( a , b , N ) NEW_LINE DEDENT
Sum of the first N terms of XOR Fibonacci series | Function to calculate sum of the first N terms of XOR Fibonacci Series ; Store the sum of first n terms ; Store xor of a and b ; Case 1 : If n is divisible by 3 ; Case 2 : If n % 3 leaves remainder 1 ; Case 3 : If n % 3 leaves remainder 2 on division by 3 ; Print the final sum ; Driver code ; Function call
def findSum ( a , b , N ) : NEW_LINE INDENT sum = 0 NEW_LINE x = a ^ b NEW_LINE if N % 3 == 0 : NEW_LINE INDENT sum = ( N // 3 ) * ( a + b + x ) NEW_LINE DEDENT elif N % 3 == 1 : NEW_LINE INDENT sum = ( N // 3 ) * ( a + b + x ) + a NEW_LINE DEDENT else : NEW_LINE INDENT sum = ( N // 3 ) * ( a + b + x ) + a + b NEW_LINE DEDENT print ( sum ) NEW_LINE return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 2 NEW_LINE b = 5 NEW_LINE N = 8 NEW_LINE findSum ( a , b , N ) NEW_LINE DEDENT
Length of the longest subarray whose Bitwise XOR is K | Function to find the length of the longest subarray whose bitwise XOR is equal to K ; Stores prefix XOR of the array ; Stores length of longest subarray having bitwise XOR equal to K ; Stores index of prefix XOR of the array ; Insert 0 into the map ; Traverse the array ; Update prefixXOR ; If ( prefixXOR ^ K ) present in the map ; Update maxLen ; If prefixXOR not present in the Map ; Insert prefixXOR into the map ; Driver Code
def LongestLenXORK ( arr , N , K ) : NEW_LINE INDENT prefixXOR = 0 NEW_LINE maxLen = 0 NEW_LINE mp = { } NEW_LINE mp [ 0 ] = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT prefixXOR ^= arr [ i ] NEW_LINE if ( prefixXOR ^ K ) in mp : NEW_LINE INDENT maxLen = max ( maxLen , ( i - mp [ prefixXOR ^ K ] ) ) NEW_LINE DEDENT else : NEW_LINE INDENT mp [ prefixXOR ] = i NEW_LINE DEDENT DEDENT return maxLen NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 7 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE K = 1 NEW_LINE print ( LongestLenXORK ( arr , N , K ) ) NEW_LINE DEDENT
Two Dimensional Difference Array | Python3 Program to implement the above approach ; Function to initialize the difference array ; Function to add k to the specified submatrix ( r1 , c1 ) to ( r2 , c2 ) ; Function to print the modified array ; Function to perform the given queries ; Difference array ; Function to initialize the difference array ; Count of queries ; Perform Queries ; Driver Code ; Given Matrix ; Given Queries
N = 3 NEW_LINE M = 3 NEW_LINE def intializeDiff ( D , A ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT D [ i ] [ 0 ] = A [ i ] [ 0 ] ; NEW_LINE D [ i ] [ M ] = 0 ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT D [ i ] [ j ] = A [ i ] [ j ] - A [ i ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT DEDENT def update ( D , k , r1 , c1 , r2 , c2 ) : NEW_LINE INDENT for i in range ( r1 , r2 + 1 ) : NEW_LINE INDENT D [ i ] [ c1 ] += k ; NEW_LINE D [ i ] [ c2 + 1 ] -= k ; NEW_LINE DEDENT DEDENT def printArray ( A , D ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT A [ i ] [ j ] = D [ i ] [ j ] ; NEW_LINE DEDENT else : NEW_LINE INDENT A [ i ] [ j ] = D [ i ] [ j ] + A [ i ] [ j - 1 ] ; NEW_LINE DEDENT print ( A [ i ] [ j ] , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def performQueries ( A , Queries ) : NEW_LINE INDENT D = [ [ 0 for j in range ( M + 1 ) ] for i in range ( N ) ] NEW_LINE intializeDiff ( D , A ) ; NEW_LINE Q = len ( Queries ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT update ( D , Queries [ i ] [ 0 ] , Queries [ i ] [ 1 ] , Queries [ i ] [ 2 ] , Queries [ i ] [ 3 ] , Queries [ i ] [ 4 ] ) ; NEW_LINE DEDENT printArray ( A , D ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 1 , 2 , 3 ] , [ 1 , 1 , 0 ] , [ 4 , - 2 , 2 ] ] ; NEW_LINE Queries = [ [ 2 , 0 , 0 , 1 , 1 ] , [ - 1 , 1 , 0 , 2 , 2 ] ] ; NEW_LINE performQueries ( A , Queries ) ; NEW_LINE DEDENT
Minimum value to be added to maximize Bitwise XOR of the given array | Python program for the above approach ; Function to find complement of an integer ; Count the number of bits of maxElement ; Return 1 's complement ; Function to find the value required to be added to maximize XOR of the given array ; Stores the required value to be added to the array ; Stores the maximum array element ; Traverse the array ; Update XOR of the array ; Find maximum element in array ; Calculate 1 s ' complement ; Return the answer ; Driver Code
import math NEW_LINE def onesComplement ( n , maxElement ) : NEW_LINE INDENT bits = math . floor ( math . log2 ( maxElement ) ) + 1 NEW_LINE return ( ( 1 << bits ) - 1 ) ^ n NEW_LINE DEDENT def findNumber ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE maxElement = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = res ^ arr [ i ] NEW_LINE if ( maxElement < arr [ i ] ) : NEW_LINE INDENT maxElement = arr [ i ] NEW_LINE DEDENT DEDENT res = onesComplement ( res , maxElement ) NEW_LINE return ( res ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findNumber ( arr , N ) ) NEW_LINE
Count ways to select K array elements lying in a given range | Function to calculate factorial of all the numbers up to N ; Factorial of 0 is 1 ; Calculate factorial of all the numbers upto N ; Calculate factorial of i ; Function to find count of ways to select at least K elements whose values in range [ L , R ] ; Stores count of ways to select at leas K elements whose values in range [ L , R ] ; Stores count of numbers having Value lies in the range [ L , R ] ; Traverse the array ; Check if the array elements Lie in the given range ; Update cntNum ; Stores factorial of numbers upto N ; Calculate total ways to select at least K elements whose values Lies in [ L , R ] ; Update cntWays ; Driver code
def calculateFactorial ( N ) : NEW_LINE INDENT fact = [ 0 ] * ( N + 1 ) NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT return fact NEW_LINE DEDENT def cntWaysSelection ( arr , N , K , L , R ) : NEW_LINE INDENT cntWays = 0 NEW_LINE cntNum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] >= L and arr [ i ] <= R ) : NEW_LINE INDENT cntNum += 1 NEW_LINE DEDENT DEDENT fact = list ( calculateFactorial ( cntNum ) ) NEW_LINE for i in range ( K , cntNum + 1 ) : NEW_LINE INDENT cntWays += fact [ cntNum ] // ( fact [ i ] * fact [ cntNum - i ] ) NEW_LINE DEDENT return cntWays NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 4 , 6 , 13 , 5 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE L = 4 NEW_LINE R = 10 NEW_LINE print ( cntWaysSelection ( arr , N , K , L , R ) ) NEW_LINE DEDENT
Bitwise AND of all unordered pairs from a given array | Function to calculate bitwise AND of all pairs from the given array ; Stores bitwise AND of all possible pairs ; Generate all possible pairs ; Calculate bitwise AND of each pair ; Driver Code
def TotalAndPair ( arr , N ) : NEW_LINE INDENT totalAND = ( 1 << 30 ) - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT totalAND &= ( arr [ i ] & arr [ j ] ) NEW_LINE DEDENT DEDENT return totalAND NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 12 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE print ( TotalAndPair ( arr , N ) ) NEW_LINE DEDENT
Modify N by adding its smallest positive divisor exactly K times | Python 3 program to implement the above approach ; Function to find the smallest divisor of N greater than 1 ; If i is a divisor of N ; If N is a prime number ; Function to find the value of N by performing the operations K times ; Iterate over the range [ 1 , K ] ; Update N ; Driver Code
import math NEW_LINE def smallestDivisorGr1 ( N ) : NEW_LINE INDENT for i in range ( 2 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return N NEW_LINE DEDENT def findValOfNWithOperat ( N , K ) : NEW_LINE INDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT N += smallestDivisorGr1 ( N ) NEW_LINE DEDENT return N NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE K = 4 NEW_LINE print ( findValOfNWithOperat ( N , K ) ) NEW_LINE DEDENT
Sum of all possible triplet products from given ranges | Python3 program to implement the above approach ; Function to find the sum of all possible triplet products ( i * j * k ) ; Stores sum required sum ; Iterate over all possible values of i ; Iterate over all possible values of j ; Iterate over all possible values of k ; Stores the product of ( i * j * k ) ; Update sum ; Driver Code
M = 1000000007 NEW_LINE def findTripleSum ( A , B , C ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , A + 1 ) : NEW_LINE INDENT for j in range ( 1 , B + 1 ) : NEW_LINE INDENT for k in range ( 1 , C + 1 ) : NEW_LINE INDENT prod = ( ( ( i % M ) * ( j % M ) ) % M * ( k % M ) ) % M NEW_LINE sum = ( sum + prod ) % M NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 10 NEW_LINE B = 100 NEW_LINE C = 1000 NEW_LINE print ( findTripleSum ( A , B , C ) ) NEW_LINE DEDENT
Sum of all possible triplet products from given ranges | Python3 implementation to implement the above approach ; Function to find the value of power ( X , N ) % M ; Stores the value of ( X ^ N ) % M ; Calculate the value of power ( x , N ) % M ; If N is odd ; Update res ; Update x ; Update N ; Function to find modulo multiplicative inverse of X under modulo M ; Function to find the sum of all possible triplet products ( i * j * k ) ; Stores modulo multiplicative inverse of 8 ; Stores the sum of all possible values of ( i * j * k ) ; Update res ; Driver Code
M = 1000000007 NEW_LINE def power ( x , N ) : NEW_LINE INDENT global M NEW_LINE res = 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT res = ( res * x ) % M NEW_LINE DEDENT x = ( x * x ) % M NEW_LINE N = N >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def modinv ( X ) : NEW_LINE INDENT return power ( X , M - 2 ) NEW_LINE DEDENT def findTripleSum ( A , B , C ) : NEW_LINE INDENT global M NEW_LINE MMI = modinv ( 8 ) NEW_LINE res = 0 NEW_LINE res = ( ( ( ( A % M * ( A + 1 ) % M ) % M * ( B % M * ( B + 1 ) % M ) % M ) % M * ( C % M * ( C + 1 ) % M ) % M ) % M * MMI ) % M NEW_LINE return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 10 NEW_LINE B = 100 NEW_LINE C = 1000 NEW_LINE print ( findTripleSum ( A , B , C ) ) NEW_LINE DEDENT
Maximize minimum of array generated by maximums of same indexed elements of two rows of a given Matrix | Python3 program for the above approach ; Function to find the maximum of minimum of array constructed from any two rows of the given matrix ; Initialize global max as INT_MIN ; Iterate through the rows ; Iterate through remaining rows ; Initialize row_min as INT_MAX ; Iterate through the column values of two rows ; Find max of two elements ; Update the row_min ; Update the global_max ; Print the global max ; Driver Code ; Given matrix mat [ ] [ ] ; Given number of rows and columns ; Function Call
import sys NEW_LINE def getMaximum ( N , M , mat ) : NEW_LINE INDENT global_max = - 1 * ( sys . maxsize ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT row_min = sys . maxsize NEW_LINE for k in range ( 0 , M ) : NEW_LINE INDENT m = max ( mat [ i ] [ k ] , mat [ j ] [ k ] ) NEW_LINE row_min = min ( row_min , m ) NEW_LINE DEDENT global_max = max ( global_max , row_min ) NEW_LINE DEDENT DEDENT return global_max NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 5 , 0 , 3 , 1 , 2 ] , [ 1 , 8 , 9 , 1 , 3 ] , [ 1 , 2 , 3 , 4 , 5 ] , [ 9 , 1 , 0 , 3 , 7 ] , [ 2 , 3 , 0 , 6 , 3 ] , [ 6 , 4 , 1 , 7 , 0 ] ] NEW_LINE N = 6 NEW_LINE M = 5 NEW_LINE print ( getMaximum ( N , M , mat ) ) NEW_LINE DEDENT
Maximize sum of MEX values of each node in an N | Function to create an N - ary Tree ; Traverse the edges ; Add edges ; Function to get the maximum sum of MEX values of tree rooted at 1 ; Initialize mex ; Iterate through all children of node ; Recursively find maximum sum of MEX values of each node in tree rooted at u ; Store the maximum sum of MEX of among all subtrees ; Increase the size of tree rooted at current node ; Resulting MEX for the current node of the recursive call ; Driver Code ; Given N nodes ; Given N - 1 edges ; Stores the tree ; Generates the tree ; Returns maximum sum of MEX values of each node
def makeTree ( tree , edges , N ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] NEW_LINE v = edges [ i ] [ 1 ] NEW_LINE tree [ u ] . append ( v ) NEW_LINE DEDENT return tree NEW_LINE DEDENT def dfs ( node , tree ) : NEW_LINE INDENT mex = 0 NEW_LINE size = 1 NEW_LINE for u in tree [ node ] : NEW_LINE INDENT temp = dfs ( u , tree ) NEW_LINE mex = max ( mex , temp [ 0 ] ) NEW_LINE size += temp [ 1 ] NEW_LINE DEDENT return [ mex + size , size ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 NEW_LINE edges = [ [ 1 , 4 ] , [ 1 , 5 ] , [ 5 , 2 ] , [ 5 , 3 ] , [ 4 , 7 ] , [ 7 , 6 ] ] NEW_LINE tree = [ [ ] for i in range ( N + 1 ) ] NEW_LINE tree = makeTree ( tree , edges , N ) NEW_LINE print ( dfs ( 1 , tree ) [ 0 ] ) NEW_LINE DEDENT
Minimum value exceeding X whose count of divisors has different parity with count of divisors of X | Function to count divisors of n ; Function to find the minimum value exceeding x whose count of divisors has different parity with count of divisors of X ; Divisor count of x ; Iterate from x + 1 and check for each element ; Driver Code ; Given X ; Function call
def divisorCount ( n ) : NEW_LINE INDENT x = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i == n // i ) : NEW_LINE INDENT x += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT x += 2 ; NEW_LINE DEDENT DEDENT if ( i * i > n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return x ; NEW_LINE DEDENT def minvalue_y ( x ) : NEW_LINE INDENT a = divisorCount ( x ) ; NEW_LINE y = x + 1 ; NEW_LINE while ( ( a & 1 ) == ( divisorCount ( y ) & 1 ) ) : NEW_LINE INDENT y += 1 ; NEW_LINE DEDENT return y ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 5 ; NEW_LINE print ( minvalue_y ( x ) ) ; NEW_LINE DEDENT
Minimum value exceeding X whose count of divisors has different parity with count of divisors of X | Function to find the minimum value exceeding x whose count of divisors has different parity with count of divisors of X ; Check if x is perfect square ; Driver Code
def minvalue_y ( x ) : NEW_LINE INDENT n = int ( pow ( x , 1 / 2 ) ) NEW_LINE if ( n * n == x ) : NEW_LINE INDENT return x + 1 NEW_LINE DEDENT return ( pow ( n + 1 , 2 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 5 NEW_LINE print ( minvalue_y ( x ) ) NEW_LINE DEDENT
Sum of first N natural numbers with alternate signs | Function to find the sum of first N natural numbers with alternate signs ; Stores sum of alternate sign of first N natural numbers ; If N is an even number ; Update alternateSum ; If N is an odd number ; Update alternateSum ; Driver Code
def alternatingSumOfFirst_N ( N ) : NEW_LINE INDENT alternateSum = 0 ; NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT alternateSum = ( - N ) // 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT alternateSum = ( N + 1 ) // 2 ; NEW_LINE DEDENT return alternateSum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 ; NEW_LINE print ( alternatingSumOfFirst_N ( N ) ) ; NEW_LINE DEDENT
Minimum value to be added to the prefix sums at each array indices to make them positive | Function to find minimum startValue for positive prefix sum at each index ; Store the minimum prefix sum ; Stores prefix sum at each index ; Traverse over the array ; Update the prefix sum ; Update the minValue ; Return the positive start value ; Driver Code ; Function Call
def minStartValue ( nums ) : NEW_LINE INDENT minValue = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT sum += nums [ i ] NEW_LINE minValue = min ( minValue , sum ) NEW_LINE DEDENT startValue = 1 - minValue NEW_LINE return startValue NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT nums = [ - 3 , 2 , - 3 , 4 , 2 ] NEW_LINE print ( minStartValue ( nums ) ) NEW_LINE DEDENT
Count ways to split array into two equal sum subarrays by replacing each array element to 0 once | Function to find number of ways to split array into 2 subarrays having equal sum by changing element to 0 once ; Stores the count of elements in prefix and suffix of array elements ; Stores the sum of array ; Traverse the array ; Increase the frequency of current element in suffix ; Stores prefix sum upto index i ; Stores sum of suffix of index i ; Stores the desired result ; Traverse the array ; Modify prefix sum ; Add arr [ i ] to prefix map ; Calculate suffix sum by subtracting prefix sum from total sum of elements ; Remove arr [ i ] from suffix map ; Store the difference between the subarrays ; Count number of ways to split the array at index i such that subarray sums are equal ; Update the final result ; Return the result ; Driver Code ; Function Call
def countSubArrayRemove ( arr , N ) : NEW_LINE INDENT prefix_element_count = { } NEW_LINE suffix_element_count = { } NEW_LINE total_sum_of_elements = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT total_sum_of_elements += arr [ i ] NEW_LINE suffix_element_count [ arr [ i ] ] = suffix_element_count . get ( arr [ i ] , 0 ) + 1 NEW_LINE i -= 1 NEW_LINE DEDENT prefix_sum = 0 NEW_LINE suffix_sum = 0 NEW_LINE count_subarray_equal_sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT prefix_sum += arr [ i ] NEW_LINE prefix_element_count [ arr [ i ] ] = prefix_element_count . get ( arr [ i ] , 0 ) + 1 NEW_LINE suffix_sum = total_sum_of_elements - prefix_sum NEW_LINE suffix_element_count [ arr [ i ] ] = suffix_element_count . get ( arr [ i ] , 0 ) - 1 NEW_LINE difference = prefix_sum - suffix_sum NEW_LINE number_of_subarray_at_i_split = ( prefix_element_count . get ( difference , 0 ) + suffix_element_count . get ( - difference , 0 ) ) NEW_LINE count_subarray_equal_sum += number_of_subarray_at_i_split NEW_LINE DEDENT return count_subarray_equal_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countSubArrayRemove ( arr , N ) ) NEW_LINE DEDENT
Count set bits in Bitwise XOR of all adjacent elements upto N | Function to count of set bits in Bitwise XOR of adjacent elements up to N ; Stores count of set bits by Bitwise XOR on adjacent elements of [ 0 , N ] ; Stores all possible values on right most set bit over [ 0 , N ] ; Iterate over the range [ 0 , N ] ; Update N ; Update bit_Position ; Driver Code
def countXORSetBitsAdjElemRange1_N ( N ) : NEW_LINE INDENT total_set_bits = 0 NEW_LINE bit_Position = 1 NEW_LINE while ( N ) : NEW_LINE INDENT total_set_bits += ( ( N + 1 ) // 2 * bit_Position ) NEW_LINE N -= ( N + 1 ) // 2 NEW_LINE bit_Position += 1 NEW_LINE DEDENT return total_set_bits NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( countXORSetBitsAdjElemRange1_N ( N ) ) NEW_LINE DEDENT
Check if a right | Python3 program to implement the above approach ; Function to check if N is a perfect square number or not ; If N is a non positive integer ; Stores square root of N ; Check for perfect square ; If N is not a perfect square number ; Function to check if given two sides of a triangle forms a right - angled triangle ; If the value of ( A * A + B * B ) is a perfect square number ; Update checkTriangle ; If the value of ( A * A - B * B ) is a perfect square number ; Update checkTriangle ; If the value of ( B * B - A * A ) is a perfect square number ; Update checkTriangle ; Driver Code ; If the given two sides of a triangle forms a right - angled triangle ; Otherwise
from math import sqrt , floor , ceil NEW_LINE def checkPerfectSquare ( N ) : NEW_LINE INDENT if ( N <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sq = sqrt ( N ) NEW_LINE if ( floor ( sq ) == ceil ( sq ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def checktwoSidesareRighTriangle ( A , B ) : NEW_LINE INDENT checkTriangle = False NEW_LINE if ( checkPerfectSquare ( A * A + B * B ) ) : NEW_LINE INDENT checkTriangle = True NEW_LINE DEDENT if ( checkPerfectSquare ( A * A - B * B ) ) : NEW_LINE INDENT checkTriangle = True NEW_LINE DEDENT if ( checkPerfectSquare ( B * B - A * A ) ) : NEW_LINE INDENT checkTriangle = True NEW_LINE DEDENT return checkTriangle NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 3 NEW_LINE B = 4 NEW_LINE if ( checktwoSidesareRighTriangle ( A , B ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimize increments or decrements required to make sum and product of array elements non | Function to find the sum of array ; Return the sum ; Function that counts the minimum operations required to make the sum and product of array non - zero ; Stores count of zero elements ; Iterate over the array to count zero elements ; Sum of elements of the array ; Print result ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
def array_sum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT def countOperations ( arr , N ) : NEW_LINE INDENT count_zeros = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT count_zeros += 1 NEW_LINE DEDENT DEDENT sum = array_sum ( arr , N ) NEW_LINE if ( count_zeros ) : NEW_LINE INDENT return count_zeros NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 1 , - 1 , 0 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countOperations ( arr , N ) ) NEW_LINE DEDENT
Bitwise OR of all unordered pairs from a given array | Function to find the bitwise OR of all possible pairs of the array ; Stores bitwise OR of all possible pairs of arr ; Traverse the array arr ; Update totalOR ; Return bitwise OR of all possible pairs of arr ; Driver Code
def TotalBitwiseORPair ( arr , N ) : NEW_LINE INDENT totalOR = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalOR |= arr [ i ] ; NEW_LINE DEDENT return totalOR ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 12 , 15 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( TotalBitwiseORPair ( arr , N ) ) ; NEW_LINE DEDENT
Difference between lexicographical ranks of two given permutations | Function the print the difference between the lexicographical ranks ; Store the permutations in lexicographic order ; Initial permutation ; Initial variables ; Check permutation ; Initialize second permutation ; Check permutation ; Print difference ; Given array P [ ] ; Given array Q [ ] ; Given size ; Function call
def findDifference ( p , q , N ) : NEW_LINE INDENT A = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT A [ i ] = i + 1 NEW_LINE DEDENT IsCorrect = False NEW_LINE a , b = 1 , 1 NEW_LINE while True : NEW_LINE INDENT IsCorrect = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != p [ i ] ) : NEW_LINE INDENT IsCorrect = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( IsCorrect ) : NEW_LINE INDENT break NEW_LINE DEDENT a += 1 NEW_LINE if ( not next_permutation ( A ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT A [ i ] = i + 1 NEW_LINE DEDENT while True : NEW_LINE INDENT IsCorrect = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != q [ i ] ) : NEW_LINE INDENT IsCorrect = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( IsCorrect ) : NEW_LINE INDENT break NEW_LINE DEDENT b += 1 NEW_LINE if ( not next_permutation ( A ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( abs ( a - b ) ) NEW_LINE DEDENT def next_permutation ( p ) : NEW_LINE INDENT for a in range ( len ( p ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( p [ a ] < p [ a + 1 ] ) : NEW_LINE INDENT b = len ( p ) - 1 NEW_LINE while True : NEW_LINE INDENT if ( p [ b ] > p [ a ] ) : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b = len ( p ) - 1 NEW_LINE while a < b : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT b -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT p = [ 1 , 3 , 2 ] NEW_LINE q = [ 3 , 1 , 2 ] NEW_LINE n = len ( p ) NEW_LINE findDifference ( p , q , n ) NEW_LINE
Count of packets placed in each box after performing given operations | Function to print final array after performing all the operations ; Initialize variables ; Traverse through all operations ; Operation Type ; Move left ; Move right ; Pick a packet ; Drop a packet ; Exit ; Print final array ; Driver Code ; Given capacity ; Given array with initial values ; Array size ; Operations ; Number of operations ; Function call
def printFinalArray ( a , n , operations , p , capacity ) : NEW_LINE INDENT curr = 0 NEW_LINE picked = False NEW_LINE for i in range ( p ) : NEW_LINE INDENT s = operations [ i ] NEW_LINE flag = False NEW_LINE if ( curr != 0 ) : NEW_LINE INDENT curr -= 1 NEW_LINE break NEW_LINE DEDENT if ( curr != n - 1 ) : NEW_LINE INDENT curr += 1 NEW_LINE break NEW_LINE DEDENT if ( picked == False and a [ curr ] != 0 ) : NEW_LINE INDENT picked = True NEW_LINE a [ curr ] -= 1 NEW_LINE break NEW_LINE DEDENT if ( picked == True and a [ curr ] != capacity ) : NEW_LINE INDENT picked = False NEW_LINE a [ curr ] += 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE DEDENT if ( flag == True ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT capacity = 5 NEW_LINE a = [ 2 , 5 , 2 ] NEW_LINE N = len ( a ) NEW_LINE operations = [ 3 , 2 , 4 , 1 , 4 , 5 ] NEW_LINE M = len ( operations ) NEW_LINE printFinalArray ( a , N , operations , M , capacity ) NEW_LINE DEDENT
Check if sum of count of digits of array elements is Prime or not | Python3 program for the above approach ; Function to check whether a number is prime or not ; Corner cases ; If given number is a multiple of 2 or 3 ; Function to check if sum of count of digits of all array elements is prime or not ; Initialize sum with 0 ; Traverse over the array ; Convert array element to string ; Add the count of digits to sum ; Print the result ; Drive Code ; Function call
import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( math . sqrt ( n ) + 1 ) , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def CheckSumPrime ( A , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT s = str ( A [ i ] ) NEW_LINE sum += len ( s ) NEW_LINE DEDENT if ( isPrime ( sum ) == True ) : 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 = [ 1 , 11 , 12 ] NEW_LINE N = len ( A ) NEW_LINE CheckSumPrime ( A , N ) NEW_LINE DEDENT
Probability of obtaining Prime Numbers as product of values obtained by throwing N dices | Function to find the value of power ( X , N ) ; Stores the value of ( X ^ N ) ; Calculate the value of power ( x , N ) ; If N is odd ; Update res ; Update x ; Update N ; Function to find the probability of obtaining a prime number as the product of N thrown dices ; Stores count of favorable outcomes ; Stores count of sample space ; Prthe required probability ; Driver code
def power ( x , N ) : NEW_LINE INDENT res = 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT res = ( res * x ) NEW_LINE DEDENT x = ( x * x ) NEW_LINE N = N >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def probablityPrimeprod ( N ) : NEW_LINE INDENT N_E = 3 * N NEW_LINE N_S = power ( 6 , N ) NEW_LINE print ( N_E , " ▁ / ▁ " , N_S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE probablityPrimeprod ( N ) NEW_LINE DEDENT
Smaller palindromic number closest to N | Function to check if a number is palindrome or not ; Stores reverse of N ; Stores the value of N ; Calculate reverse of N ; Update rev ; Update N ; Update N ; If N is equal to rev of N ; Function to find the closest smaller palindromic number to N ; Calculate closest smaller palindromic number to N ; Update N ; Driver Code
def checkPalindrome ( N ) : NEW_LINE INDENT rev = 0 NEW_LINE temp = N NEW_LINE while ( N != 0 ) : NEW_LINE INDENT rev = rev * 10 + N % 10 NEW_LINE N = N // 10 NEW_LINE DEDENT N = temp NEW_LINE if ( N == rev ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def closestSmallerPalindrome ( N ) : NEW_LINE INDENT while N >= 0 and not checkPalindrome ( N ) : NEW_LINE INDENT N -= 1 NEW_LINE DEDENT return N NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4000 NEW_LINE print ( closestSmallerPalindrome ( N ) ) NEW_LINE DEDENT
Minimize increments or decrements by 2 to convert given value to a perfect square | Function to find the minimum number of operations required to make N a perfect square ; Stores count of operations by performing decrements ; Stores value of N ; Decrement the value of temp ; Stores square root of temp ; If temp is a perfect square ; Update temp ; Store count of operations by performing increments ; Increment the value of N ; Stores sqrt of N ; If N is a perfect square ; Update temp ; Return the minimum count ; Driver code
def MinimumOperationReq ( N ) : NEW_LINE INDENT cntDecr = 0 ; NEW_LINE temp = N ; NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT X = int ( pow ( temp , 1 / 2 ) ) NEW_LINE if ( X * X == temp ) : NEW_LINE INDENT break ; NEW_LINE DEDENT temp = temp - 2 ; NEW_LINE cntDecr += 1 ; NEW_LINE DEDENT cntIncr = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT X = int ( pow ( N , 1 / 2 ) ) NEW_LINE if ( X * X == N ) : NEW_LINE INDENT break ; NEW_LINE DEDENT N = N + 2 ; NEW_LINE cntIncr += 1 ; NEW_LINE DEDENT return min ( cntIncr , cntDecr ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 ; NEW_LINE print ( MinimumOperationReq ( N ) ) ; NEW_LINE DEDENT
First term from given Nth term of the equation F ( N ) = ( 2 * F ( N | Python3 program to implement the above approach ; Function to find the value of power ( X , N ) % M ; Stores the value of ( X ^ N ) % M ; Calculate the value of power ( x , N ) % M ; If N is odd ; Update res ; Update x ; Update N ; Function to find modulo multiplicative inverse of X under modulo M ; Function to find the value of F ( 1 ) ; Stores power ( 2 , N - 1 ) ; Stores modulo multiplicative inverse of P_2 under modulo M ; Stores the value of F ( 1 ) ; Update res ; Driver code
M = 1000000007 NEW_LINE def power ( x , N ) : NEW_LINE INDENT res = 1 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT res = ( res * x ) % M NEW_LINE DEDENT x = ( x * x ) % M NEW_LINE N = N >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def moduloInverse ( X ) : NEW_LINE INDENT return power ( X , M - 2 ) NEW_LINE DEDENT def F_1 ( N , F_N ) : NEW_LINE INDENT P_2 = power ( 2 , N - 1 ) NEW_LINE modInv = moduloInverse ( P_2 ) NEW_LINE res = 0 NEW_LINE res = ( ( modInv % M ) * ( F_N % M ) ) % M NEW_LINE return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE F_N = 6 NEW_LINE print ( F_1 ( N , F_N ) ) NEW_LINE DEDENT
Queries to replace every array element by its XOR with a given value with updates | Function to insert an element into the array ; Function to update every array element a [ i ] by a [ i ] ^ x ; Function to compute the final results after the operations ; Driver Code ; Queries ; Function call
def add ( arr , x ) : NEW_LINE INDENT arr . append ( x ) NEW_LINE DEDENT def update ( effect , x ) : NEW_LINE INDENT effect = effect ^ x NEW_LINE return effect NEW_LINE DEDENT def computeResults ( arr , effect ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT arr [ i ] = arr [ i ] ^ effect NEW_LINE print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 ] NEW_LINE effect = 0 NEW_LINE add ( arr , 5 ) NEW_LINE effect = update ( effect , 2 ) NEW_LINE computeResults ( arr , effect ) NEW_LINE DEDENT
Check if a subarray of size K exists whose elements form a number divisible by 3 | Function to find the K size subarray ; Check if the first K elements forms a number which is divisible by 3 ; Using Sliding window technique ; Calculate sum of next K size subarray ; Check if sum is divisible by 3 ; Update the indices of the subarray ; If no such subarray is found ; Print the subarray ; Driver code ; Given array and K ; Function call
def findSubArray ( arr , k ) : NEW_LINE INDENT ans = [ ( 0 , 0 ) ] NEW_LINE sm = 0 NEW_LINE i = 0 NEW_LINE found = 0 NEW_LINE while ( i < k ) : NEW_LINE INDENT sm += arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT if ( sm % 3 == 0 ) : NEW_LINE INDENT ans = [ ( 0 , i - 1 ) ] NEW_LINE found = 1 NEW_LINE DEDENT for j in range ( i , len ( arr ) , 1 ) : NEW_LINE INDENT if ( found == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT sm = sm + arr [ j ] - arr [ j - k ] NEW_LINE if ( sm % 3 == 0 ) : NEW_LINE INDENT ans = [ ( j - k + 1 , j ) ] NEW_LINE found = 1 NEW_LINE DEDENT DEDENT if ( found == 0 ) : NEW_LINE INDENT ans = [ ( - 1 , 0 ) ] NEW_LINE DEDENT if ( ans [ 0 ] [ 0 ] == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( ans [ 0 ] [ 0 ] , ans [ 0 ] [ 1 ] + 1 , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 84 , 23 , 45 , 12 , 56 , 82 ] NEW_LINE K = 3 NEW_LINE findSubArray ( arr , K ) NEW_LINE DEDENT
Count permutations of given array that generates the same Binary Search Tree ( BST ) | Function to precompute the factorial of 1 to N ; Function to get the value of nCr ; nCr = fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; Function to count the number of ways to rearrange the array to obtain same BST ; Store the size of the array ; Base case ; Store the elements of the left subtree of BST ; Store the elements of the right subtree of BST ; Store the root node ; Push all the elements of the left subtree ; Push all the elements of the right subtree ; Store the size of leftSubTree ; Store the size of rightSubTree ; Recurrence relation ; Driver Code ; Store the size of arr ; Store the factorial up to N ; Precompute the factorial up to N
def calculateFact ( fact : list , N : int ) -> None : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT def nCr ( fact : list , N : int , R : int ) -> int : NEW_LINE INDENT if ( R > N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = fact [ N ] // fact [ R ] NEW_LINE res //= fact [ N - R ] NEW_LINE return res NEW_LINE DEDENT def countWays ( arr : list , fact : list ) -> int : NEW_LINE INDENT N = len ( arr ) NEW_LINE if ( N <= 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT leftSubTree = [ ] NEW_LINE rightSubTree = [ ] NEW_LINE root = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] < root ) : NEW_LINE INDENT leftSubTree . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT rightSubTree . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT N1 = len ( leftSubTree ) NEW_LINE N2 = len ( rightSubTree ) NEW_LINE countLeft = countWays ( leftSubTree , fact ) NEW_LINE countRight = countWays ( rightSubTree , fact ) NEW_LINE return ( nCr ( fact , N - 1 , N1 ) * countLeft * countRight ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 5 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE fact = [ 0 ] * N NEW_LINE calculateFact ( fact , N ) NEW_LINE print ( countWays ( arr , fact ) ) NEW_LINE DEDENT
Sum of all ordered pair | Function to calculate the sum of all pair - products ; Stores sum of array ; Update sum of the array ; Driver Code
def sumOfProd ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum * sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 5 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( sumOfProd ( arr , N ) ) NEW_LINE DEDENT
Check if a given number is one less than twice its reverse | Iterative function to reverse digits of num ; Loop to extract all digits of the number ; Function to check if N satisfies given equation ; Driver Code
def rev ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = ( rev_num * 10 + num % 10 ) NEW_LINE num = num // 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def check ( n ) : NEW_LINE INDENT return ( 2 * rev ( n ) == n + 1 ) NEW_LINE DEDENT n = 73 NEW_LINE if ( check ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Check if a given number is one less than twice its reverse | Python3 program to implement the above approach ; Function to check y is a power of x ; logarithm function to calculate value ; Compare to the result1 or result2 both are equal ; Function to check if N satisfies the equation 2 * reverse ( n ) = n + 1 ; Driver Code
import math NEW_LINE def isPower ( x , y ) : NEW_LINE INDENT res1 = math . log ( y ) // math . log ( x ) NEW_LINE res2 = math . log ( y ) // math . log ( x ) NEW_LINE return ( res1 == res2 ) NEW_LINE DEDENT def check ( n ) : NEW_LINE INDENT x = ( n + 7 ) // 8 NEW_LINE if ( ( n + 7 ) % 8 == 0 and isPower ( 10 , x ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT n = 73 NEW_LINE if ( check ( n ) != 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Nth term of a recurrence relation generated by two given arrays | Python3 program for the above approach ; Function to calculate Nth term of general recurrence relations ; Stores the generated sequence ; Current term is sum of previous k terms ; Print the nth term ; Driver code ; Given Array F [ ] and C [ ] ; Given N and K ; Function call
mod = 1e9 + 7 NEW_LINE def NthTerm ( F , C , K , n ) : NEW_LINE INDENT ans = [ 0 ] * ( n + 1 ) NEW_LINE i = 0 NEW_LINE while i < K : NEW_LINE INDENT ans [ i ] = F [ i ] NEW_LINE i += 1 NEW_LINE DEDENT i = K NEW_LINE while i <= n : NEW_LINE INDENT j = i - K NEW_LINE while j < i : NEW_LINE INDENT ans [ i ] += ans [ j ] NEW_LINE ans [ i ] %= mod NEW_LINE j += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( int ( ans [ n ] ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT F = [ 0 , 1 ] NEW_LINE C = [ 1 , 1 ] NEW_LINE K = 2 NEW_LINE N = 10 NEW_LINE NthTerm ( F , C , K , N ) NEW_LINE DEDENT
Mode of frequencies of given array elements | Python3 program of the above approach ; Function to find the mode of the frequency of the array ; Stores the frequencies of array elements ; Traverse through array elements and count frequencies ; Stores the frequencies 's of frequencies of array elements ; Stores the minimum value ; Find the Mode in 2 nd map ; search for this Mode ; When mode is find then return to main function . ; If mode is not found ; Driver Code
from collections import defaultdict NEW_LINE import sys NEW_LINE def countFreq ( arr , n ) : NEW_LINE INDENT mp1 = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp1 [ arr [ i ] ] += 1 NEW_LINE mp2 = defaultdict ( int ) NEW_LINE for it in mp1 : NEW_LINE mp2 [ mp1 [ it ] ] += 1 NEW_LINE M = - sys . maxsize - 1 NEW_LINE for it in mp2 : NEW_LINE INDENT M = max ( M , mp2 [ it ] ) NEW_LINE for it in mp2 : NEW_LINE if ( M == mp2 [ it ] ) : NEW_LINE INDENT return it NEW_LINE DEDENT return 0 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 10 , 3 , 10 , 8 , 3 , 6 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countFreq ( arr , n ) ) NEW_LINE DEDENT
Maximize count of nodes disconnected from all other nodes in a Graph | Function which returns the maximum number of isolated nodes ; Used nodes ; Remaining edges ; Count nodes used ; If given edges are non - zero ; Driver Code ; Given N and E ; Function call
def maxDisconnected ( N , E ) : NEW_LINE INDENT curr = 1 NEW_LINE rem = E NEW_LINE while ( rem > 0 ) : NEW_LINE INDENT rem = rem - min ( curr , rem ) NEW_LINE curr += 1 NEW_LINE DEDENT if ( curr > 1 ) : NEW_LINE INDENT return N - curr NEW_LINE DEDENT else : NEW_LINE INDENT return N NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE E = 1 NEW_LINE print ( maxDisconnected ( N , E ) ) NEW_LINE DEDENT
Check if number is palindrome or not in base B | Function to check if N in base B is palindrome or not ; Stores the reverse of N ; Stores the value of N ; Extract all the digits of N ; Generate its reverse ; Driver code
def checkPalindromeB ( N , B ) : NEW_LINE INDENT rev = 0 ; NEW_LINE N1 = N ; NEW_LINE while ( N1 > 0 ) : NEW_LINE INDENT rev = rev * B + N1 % B ; NEW_LINE N1 = N1 // B ; NEW_LINE DEDENT return N == rev ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; B = 2 ; NEW_LINE if ( checkPalindromeB ( N , B ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Product of all numbers up to N that are co | Function to return gcd of a and b ; Base Case ; Recursive GCD ; Function to find the product of all the numbers till N that are relatively prime to N ; Stores the resultant product ; Iterate over [ 2 , N ] ; If gcd is 1 , then find the product with result ; Return the final product ; Driver Code
def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def findProduct ( N ) : NEW_LINE INDENT result = 1 ; NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( gcd ( i , N ) == 1 ) : NEW_LINE INDENT result *= i ; NEW_LINE DEDENT DEDENT return result ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE print ( findProduct ( N ) ) ; NEW_LINE DEDENT
Maximize count of equal numbers in Array of numbers upto N by replacing pairs with their sum | Function to count maximum number of array elements equal ; Driver Code ; Function call
def countEqual ( n ) : NEW_LINE INDENT return ( n + 1 ) // 2 NEW_LINE DEDENT lst = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( lst ) NEW_LINE print ( countEqual ( n ) ) NEW_LINE
Minimize count of unequal elements at corresponding indices between given arrays | Function that count of the mismatched pairs in bot the array ; Create a parent array and initialize it ; Preprocessing of the given pairs of indices ; 1 - based indexing ; If both indices doesn 't belong to same component ; Insert the indices in same component ; HashMap to get the indices of array A ; If current element is not present in array B then count this as mismatched ; Get the index of the element in array B ; Check if both indices belong to same connected component if not increment the count ; Return answer ; Function that gives the connected component of each index ; Function that creates the connected components ; Find parent of a and b recursively ; Update the parent of a ; Driver Code ; Given arrays A [ ] , B [ ] ; List of indices ; Function call
def countPairs ( A , B , N , M , List ) : NEW_LINE INDENT count = 0 NEW_LINE par = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT par [ i ] = i NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT index1 = find ( par , List [ i ] [ 0 ] - 1 ) NEW_LINE index2 = find ( par , List [ i ] [ 1 ] - 1 ) NEW_LINE if ( index1 != index2 ) : NEW_LINE INDENT union ( par , index1 , index2 ) NEW_LINE DEDENT DEDENT map = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT map [ A [ i ] ] = i NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE INDENT if ( B [ i ] not in map . keys ( ) ) : NEW_LINE INDENT count += 1 NEW_LINE continue NEW_LINE DEDENT j = map [ B [ i ] ] NEW_LINE if ( find ( par , i ) != find ( par , j ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT def find ( par , x ) : NEW_LINE INDENT if ( par [ x ] == x ) : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT par [ x ] = find ( par , par [ x ] ) NEW_LINE return par [ x ] NEW_LINE DEDENT DEDENT def union ( par , a , b ) : NEW_LINE INDENT a = find ( par , a ) NEW_LINE b = find ( par , b ) NEW_LINE if ( a == b ) : NEW_LINE INDENT return NEW_LINE DEDENT par [ a ] = b NEW_LINE DEDENT N = 5 NEW_LINE M = 4 NEW_LINE A = [ 1 , 5 , 9 , 2 , 3 ] NEW_LINE B = [ 2 , 4 , 5 , 1 , 3 ] NEW_LINE List = [ [ 1 , 4 ] , [ 2 , 3 ] , [ 3 , 5 ] , [ 2 , 5 ] ] NEW_LINE print ( countPairs ( A , B , N , M , List ) ) NEW_LINE
Maximum value of expression ( arr [ i ] + arr [ j ] * arr [ k ] ) formed from a valid Triplet | Function that generate all valid triplets and calculate the value of the valid triplets ; Generate all triplets ; Check whether the triplet is valid or not ; Update the value ; Print the maximum value ; Driver Code ; Given array arr ; Function call
def max_valid_triplet ( A , n ) : NEW_LINE INDENT ans = - 1 ; NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( A [ i ] < A [ j ] and A [ j ] < A [ k ] ) : NEW_LINE INDENT value = A [ i ] + A [ j ] * A [ k ] ; NEW_LINE if ( value > ans ) : NEW_LINE INDENT ans = value ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 9 , 3 , 8 , 11 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE max_valid_triplet ( arr , n ) ; NEW_LINE DEDENT
Product of proper divisors of a number for Q queries | Python3 implementation of the above approach ; Function to precompute the product of proper divisors of a number at it 's corresponding index ; Returning the pre - computed values ; Driver code
mod = 1000000007 NEW_LINE ans = [ 1 ] * ( 100002 ) NEW_LINE def preCompute ( ) : NEW_LINE INDENT for i in range ( 2 , 100000 // 2 + 1 ) : NEW_LINE INDENT for j in range ( 2 * i , 100001 , i ) : NEW_LINE INDENT ans [ j ] = ( ans [ j ] * i ) % mod NEW_LINE DEDENT DEDENT DEDENT def productOfProperDivi ( num ) : NEW_LINE INDENT return ans [ num ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT preCompute ( ) NEW_LINE queries = 5 NEW_LINE a = [ 4 , 6 , 8 , 16 , 36 ] NEW_LINE for i in range ( queries ) : NEW_LINE INDENT print ( productOfProperDivi ( a [ i ] ) , end = " , ▁ " ) NEW_LINE DEDENT DEDENT
Highest power of 2 that divides the LCM of first N Natural numbers . | Function to find LCM of first N natural numbers ; Initialize result ; Ans contains LCM of 1 , 2 , 3 , . . i after i 'th iteration ; Function to find the highest power of 2 which divides LCM of first n natural numbers ; Find lcm of first N natural numbers ; To store the highest required power of 2 ; Counting number of consecutive zeros from the end in the given binary String ; Driver code
def findlcm ( n ) : NEW_LINE INDENT ans = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = ( ( ( i * ans ) ) // ( __gcd ( i , ans ) ) ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def highestPower ( n ) : NEW_LINE INDENT lcm = findlcm ( n ) ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT x = int ( pow ( 2 , i ) ) ; NEW_LINE if ( lcm % x == 0 ) : NEW_LINE INDENT ans = i ; NEW_LINE DEDENT if ( x > n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 ; NEW_LINE print ( highestPower ( n ) ) ; NEW_LINE DEDENT
Highest power of 2 that divides the LCM of first N Natural numbers . | Python3 implementation of the approach ; Function to find the highest power of 2 which divides LCM of first n natural numbers ; Driver code
import math NEW_LINE def highestPower ( n ) : NEW_LINE INDENT return int ( ( math . log ( n ) // math . log ( 2 ) ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 15 ; NEW_LINE print ( highestPower ( n ) ) ; NEW_LINE DEDENT
Check if number can be made prime by deleting a single digit | Function to check if N is prime from builtins import range ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function to delete character at index i from given String str ; Deletes character at position 4 ; Function to check if a number becomes prime by deleting any digit ; Converting the number to String ; length of String ; number should not be of single digit ; Loop to find all numbers after deleting a single digit ; Deleting ith character from the String ; converting String to int ; Driver Code
def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 5 , int ( n ** 1 / 2 ) , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def deleteIth ( str , i ) : NEW_LINE INDENT str = str [ 0 : i ] + str [ i + 1 : ] ; NEW_LINE return str ; NEW_LINE DEDENT def isPrimePossible ( N ) : NEW_LINE INDENT s = str ( N ) ; NEW_LINE l = len ( s ) ; NEW_LINE if ( l < 2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( l ) : NEW_LINE INDENT str1 = deleteIth ( s , i ) ; NEW_LINE num = int ( str1 ) ; NEW_LINE if ( isPrime ( num ) ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 610 ; NEW_LINE if ( isPrimePossible ( N ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Check if a number has an odd count of odd divisors and even count of even divisors | Function to find the count of even and odd factors of N ; Loop runs till square root ; Condition to check if the even factors of the number N is is even and count of odd factors is odd ; Driver Code
def checkFactors ( N ) : NEW_LINE INDENT ev_count = 0 ; od_count = 0 ; NEW_LINE for i in range ( 1 , int ( pow ( N , 1 / 2 ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i == N / i ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT ev_count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT od_count += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT ev_count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT od_count += 1 ; NEW_LINE DEDENT if ( ( N / i ) % 2 == 0 ) : NEW_LINE INDENT ev_count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT od_count += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( ev_count % 2 == 0 and od_count % 2 == 1 ) : NEW_LINE INDENT print ( " Yes " + " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " + " " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 36 ; NEW_LINE checkFactors ( N ) ; NEW_LINE DEDENT
Count of distinct permutations of length N having no similar adjacent characters | Function to print the number of permutations possible ; Driver Code
def countofPermutations ( N ) : NEW_LINE INDENT return int ( ( 3 * pow ( 2 , N - 1 ) ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE print ( countofPermutations ( N ) ) ; NEW_LINE DEDENT
Find two distinct numbers such that their LCM lies in given range | Function to find two distinct numbers X and Y s . t . their LCM lies between L and R and X , Y are minimum possible ; Check if 2 * L lies in range L , R ; Print the answer ; Given value of ranges ; Function call
def answer ( L , R ) : NEW_LINE INDENT if ( 2 * L <= R ) : NEW_LINE INDENT print ( L , " , " , 2 * L ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT L = 3 NEW_LINE R = 8 NEW_LINE answer ( L , R ) NEW_LINE
Maximum count of pairwise co | Function to find the gcd of two numbers ; Function to of pairwise co - prime and common divisors of two numbers ; Initialize answer with 1 , to include 1 in the count ; Count of primes of gcd ( N , M ) ; Finding prime factors of gcd ; Increment count if it is divisible by i ; Return the total count ; Function Call for each pair to calculate the count of pairwise co - prime divisors ; Driver Code ; Given array of pairs ; Function Call
def gcd ( x , y ) : NEW_LINE INDENT if ( x % y == 0 ) : NEW_LINE INDENT return y NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( y , x % y ) NEW_LINE DEDENT DEDENT def countPairwiseCoprime ( N , M ) : NEW_LINE INDENT answer = 1 NEW_LINE g = gcd ( N , M ) NEW_LINE temp = g NEW_LINE for i in range ( 2 , g + 1 ) : NEW_LINE INDENT if i * i > g : NEW_LINE INDENT break NEW_LINE DEDENT if ( temp % i == 0 ) : NEW_LINE INDENT answer += 1 NEW_LINE while ( temp % i == 0 ) : NEW_LINE INDENT temp //= i NEW_LINE DEDENT DEDENT DEDENT if ( temp != 1 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT return answer NEW_LINE DEDENT def countCoprimePair ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( countPairwiseCoprime ( arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 12 , 18 ] , [ 420 , 660 ] ] NEW_LINE N = len ( arr ) NEW_LINE countCoprimePair ( arr , N ) NEW_LINE DEDENT
Product of absolute difference of every pair in given Array | Function to return the product of abs diff of all pairs ( x , y ) ; To store product ; Iterate all possible pairs ; Find the product ; Return product ; Driver Code ; Given array arr [ ] ; Function Call
def getProduct ( a , n ) : NEW_LINE INDENT p = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT p *= abs ( a [ i ] - a [ j ] ) NEW_LINE DEDENT DEDENT return p NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getProduct ( arr , N ) ) NEW_LINE DEDENT
Check whether a number can be represented as difference of two consecutive cubes | Python3 program for the above approach ; Function to print the two consecutive numbers whose difference is N ; Iterate in the range [ 0 , 10 ^ 5 ] ; Function to check if N is a perfect cube ; Find floating povalue of square root of x . ; If square root is an integer ; Function to check whether a number can be represented as difference of two consecutive cubes ; Check if 12 * N - 3 is a perfect square or not ; Given number N
import math NEW_LINE def printt ( N ) : NEW_LINE INDENT for i in range ( 100000 ) : NEW_LINE INDENT if ( pow ( i + 1 , 3 ) - pow ( i , 3 ) == N ) : NEW_LINE INDENT print ( i , ' ' , i + 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def diffCube ( N ) : NEW_LINE INDENT return isPerfectSquare ( 12 * N - 3 ) NEW_LINE DEDENT N = 19 NEW_LINE if ( diffCube ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE printt ( N ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Sum of bit differences for numbers from 0 to N | Set 2 | Recursive function to find sum of different bits between consecutive numbers from 0 to N ; Base case ; Calculate the Nth term ; Given number ; Function call
def totalCountDifference ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return n + totalCountDifference ( n // 2 ) NEW_LINE DEDENT N = 5 NEW_LINE print ( totalCountDifference ( N ) ) NEW_LINE
Sum of elements of a Geometric Progression ( GP ) in a given range | Function to find sum in the given range ; Find the value of k ; Find the common difference ; Find the sum ; Driver code
def findSum ( arr , n , left , right ) : NEW_LINE INDENT k = right - left + 1 NEW_LINE d = arr [ 1 ] // arr [ 0 ] NEW_LINE ans = arr [ left - 1 ] NEW_LINE if d == 1 : NEW_LINE INDENT ans = ans * d * k NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans * ( d ** k - 1 ) // ( d - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 8 , 16 , 32 , 64 , 128 , 256 ] NEW_LINE queries = 3 NEW_LINE q = [ [ 2 , 4 ] , [ 2 , 6 ] , [ 5 , 8 ] ] NEW_LINE n = len ( arr ) NEW_LINE for i in range ( queries ) : NEW_LINE INDENT print ( findSum ( arr , n , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT