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 an... | 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 arr... |
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 ea... | 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 ( lis... |
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 ; I... | 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... |
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_LI... |
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 ; N... |
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 pref... | 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 ; ... |
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 ... | 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 ... |
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... | 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 , ... |
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... | 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_... |
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 ... | 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__ =... |
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 ] i... | 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 ] ==... |
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 co... | 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 prin... |
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 ... | 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 ( ... |
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... | 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_LIN... |
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 = 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 countPa... |
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 arr... | 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... |
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 ; Stor... | 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 ... |
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 ... | 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... |
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 th... | 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 DEDE... |
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 elemen... | 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... |
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... |
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 al... | 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 ] ... |
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 ) + numberOfW... |
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 . ; ... | 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 , -... |
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... | 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... |
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 element... | 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_... |
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 [ ] [... | 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 ... |
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 ... |
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 fin... | 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 re... |
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 ... |
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 el... |
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 IN... |
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 ; Sto... | 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 = ... |
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 ; Redu... | 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_LI... |
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 mu... | 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 ] -... |
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 * bitwise... |
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 th... | 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_L... |
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 fre... | 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... |
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... | 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 ] ) N... |
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... |
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 fina... | 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__ == ' _ _ m... |
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 f... | 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... |
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 ... | 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 DE... |
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 initi... | 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 - ... |
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 req... | 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 =... |
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 ] ; Stor... | 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 =... |
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 = [ ... |
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 rang... | 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_... |
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 ... | 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 ) %... |
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 ... | 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 retu... |
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 thr... | 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 ] [... |
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 ... | 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 [ ... |
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 elem... | 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 ... |
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... |
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 posit... | 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_LI... |
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... | 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 . g... |
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 ] ; Upd... | 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__ == ... |
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 - a... | 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 )... |
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 elem... | 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_... |
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 ( TotalBitwis... |
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 ; ... | 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... |
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 ca... | 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 IND... |
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 wi... | 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_... |
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 numbe... | 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... |
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 pa... | 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 ) :... |
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 pe... | 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 ... |
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 ... | 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 ( ... |
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 p... |
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... | 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 (... |
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 ... | 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... |
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 D... |
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 ) ) ... |
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... | 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 ) ) : ... |
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 a... | 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 ] N... |
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 mini... | 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 . ... |
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__ ==... |
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... |
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 ... | 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 DED... |
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 i... | 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 )... |
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 a... | 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 ] ; N... |
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 I... |
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 nu... | 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 ) : NE... |
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... | 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 == ... |
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_cou... |
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 t... | 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... |
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 ... |
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 . ;... | 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 (... |
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 DEDE... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.