text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find the smallest positive number which can not be represented by given digits | Function to find the smallest positive number which can not be represented by given digits ; Storing the count of 0 digit or store the value at 0 th index ; Calculates the min value in the array starting from 1 st index and also store its ...
def expressDigit ( arr , n ) : NEW_LINE INDENT min = 9 NEW_LINE index = 0 NEW_LINE temp = 0 NEW_LINE temp = arr [ 0 ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE index = i NEW_LINE DEDENT DEDENT if ( temp < min ) : NEW_LINE INDENT print ( 1 , en...
Find the average of k digits from the beginning and l digits from the end of the given number | implementation of the approach ; Function to return the count of digits in num ; Function to return the sum of first n digits of num ; Remove the unnecessary digits ; Function to return the sum of the last n digits of num ; ...
from math import pow NEW_LINE def countDigits ( num ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE num //= 10 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def sumFromStart ( num , n , rem ) : NEW_LINE INDENT num //= pow ( 10 , rem ) NEW_LINE sum = 0 NEW_LINE while ( num > 0 ) :...
Print N terms of Withoff Sequence | Python3 program to find Wythoff array ; Function to find the n , k term of Wythoff array ; tau = ( sqrt ( 5 ) + 1 ) / 2 ; Already_stored ; T ( n , - 1 ) = n - 1. ; T ( n , 0 ) = floor ( n * tau ) . ; T ( n , k ) = T ( n , k - 1 ) + T ( n , k - 2 ) for k >= 1. ; Store ; Return the ans...
import math NEW_LINE def Wythoff ( mp , n , k ) : NEW_LINE INDENT tau = ( math . sqrt ( 5 ) + 1 ) / 2 NEW_LINE t_n_k = 0 NEW_LINE if ( ( n in mp ) and ( k in mp [ n ] ) ) : NEW_LINE INDENT return mp [ n ] [ k ] ; NEW_LINE DEDENT if ( k == - 1 ) : NEW_LINE INDENT return n - 1 ; NEW_LINE DEDENT elif ( k == 0 ) : NEW_LINE...
Sum of two numbers if the original ratio and new ratio obtained by adding a given number to each number is given | Function to return the sum of numbers which are in the ration a : b and after adding x to both the numbers the new ratio becomes c : d ; Driver code
def sum ( a , b , c , d , x ) : NEW_LINE INDENT ans = ( ( x * ( a + b ) * ( c - d ) ) / ( ( a * d ) - ( b * c ) ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b , c , d , x = 1 , 2 , 9 , 13 , 5 ; NEW_LINE print ( sum ( a , b , c , d , x ) ) ; NEW_LINE DEDENT
Triangle of numbers arising from Gilbreath 's conjecture | Python3 code for printing the Triangle of numbers arising from Gilbreath 's conjecture ; Check whether the number is prime or not ; Set the 0 th row of the matrix with c primes from 0 , 0 to 0 , c - 1 ; Find the n , k term of matrix of Gilbreath 's conjecture ;...
import math NEW_LINE def is_Prime ( n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , int ( math . sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def set_primes ( mp , has...
Roots of the quadratic equation when a + b + c = 0 without using Shridharacharya formula | Function to print the roots of the quadratic equation when a + b + c = 0 ; Driver code
def printRoots ( a , b , c ) : NEW_LINE INDENT print ( 1 , " , " , c / ( a * 1.0 ) ) NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE c = - 5 NEW_LINE printRoots ( a , b , c ) NEW_LINE
Longest alternative parity subsequence | Function to find the longest ; Marks the starting of odd number as sequence and alternatively changes ; Finding the longest odd / even sequence ; Find odd number ; Find even number ; Length of the longest even / odd sequence ; Find odd number ; Find even number ; Answer is maxim...
def longestAlternativeSequence ( a , n ) : NEW_LINE INDENT maxi1 = 0 NEW_LINE f1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( f1 == 0 ) : NEW_LINE INDENT if ( a [ i ] % 2 ) : NEW_LINE INDENT f1 = 1 NEW_LINE maxi1 += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i ] % 2 == 0 ) : NEW_LINE INDENT ma...
Nambiar Number Generator | Function to return the Nambiar number of the given number ; If there is no digit to choose ; Choose the first digit ; Chosen digit 's parity ; To store the sum of the consecutive digits starting from the chosen digit ; While there are digits to choose ; Update the sum ; If the parity differs ...
def nambiarNumber ( Str , i ) : NEW_LINE INDENT if ( i >= len ( Str ) ) : NEW_LINE INDENT return " " NEW_LINE DEDENT firstDigit = ord ( Str [ i ] ) - ord ( '0' ) NEW_LINE digitParity = firstDigit % 2 NEW_LINE sumDigits = 0 NEW_LINE while ( i < len ( Str ) ) : NEW_LINE INDENT sumDigits += ( ord ( Str [ i ] ) - ord ( '0'...
Program to find the Depreciation of Value | Python 3 program to find depreciation of the value initial value , rate and time are given ; Function to return the depreciation of value ; Driver Code
from math import pow NEW_LINE def Depreciation ( v , r , t ) : NEW_LINE INDENT D = v * pow ( ( 1 - r / 100 ) , t ) NEW_LINE return D NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V1 = 200 NEW_LINE R = 10 NEW_LINE T = 2 NEW_LINE print ( int ( Depreciation ( V1 , R , T ) ) ) NEW_LINE DEDENT
Program to find first N Fermat Numbers | Iterative Function to calculate ( x ^ y ) in O ( log y ) ; res = 1 Initialize result ; If y is odd , multiply x with the result ; n must be even now y = y >> 1 y = y / 2 x = x * x Change x to x ^ 2 ; Function to find nth fermat number ; 2 to the power i ; 2 to the power 2 ^ i ; ...
def power ( x , y ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def Fermat ( i ) : NEW_LINE INDENT power2_i = power ( 2 , i ) NEW_LINE power2_2_i = power ( 2 , power2_i ) NEW_LINE return power2_2_i + 1 NEW_LINE DEDENT...
Highly Totient Number | Function to find euler totient number ; Consider all prime factors of n and subtract their multiples from result ; Check if p is a prime factor . ; If yes , then update n and result ; If n has a prime factor greater than sqrt ( n ) ( There can be at - most one such prime factor ) ; Function to f...
def phi ( n ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( n % p == 0 ) : NEW_LINE INDENT while ( n % p == 0 ) : NEW_LINE INDENT n //= p ; NEW_LINE DEDENT result -= ( result // p ) ; NEW_LINE DEDENT p += 1 NEW_LINE DEDENT if ( n > 1 ) : NEW_LINE INDENT result -= ( result // n ) ; NEW_LIN...
Program to find the Speed of train as per speed of sound | Python3 implementation of the approach ; Function to find the Speed of train ; Driver code ; calling Function
from math import ceil NEW_LINE def speedOfTrain ( X , Y ) : NEW_LINE INDENT Speed = 0 NEW_LINE Speed = 1188 * ( ( X - Y ) / Y ) NEW_LINE return Speed NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 8 NEW_LINE Y = 7.2 NEW_LINE print ( ceil ( speedOfTrain ( X , Y ) ) , end = " ▁ km / hr " ) NEW_LINE...
Maximum value of division of two numbers in an Array | Function to maximum value of division of two numbers in an array ; Traverse through the array ; Return the required answer ; Driver code
def Division ( a , n ) : NEW_LINE INDENT maxi = - 10 ** 9 NEW_LINE mini = 10 ** 9 NEW_LINE for i in a : NEW_LINE INDENT maxi = max ( i , maxi ) NEW_LINE mini = min ( i , mini ) NEW_LINE DEDENT return maxi // mini NEW_LINE DEDENT a = [ 3 , 7 , 9 , 3 , 11 ] NEW_LINE n = len ( a ) NEW_LINE print ( Division ( a , n ) ) NEW...
Ramanujan Prime | Python3 program to find Ramanujan numbers ; FUnction to return a vector of primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ;...
from math import log , ceil NEW_LINE MAX = 1000000 NEW_LINE def addPrimes ( ) : NEW_LINE INDENT n = MAX NEW_LINE prime = [ True for i in range ( n + 1 ) ] NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if p * p > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in ra...
Quadruplet pair with XOR zero in the given Array | Python3 implementation of the approach ; Function that returns true if the array contains a valid quadruplet pair ; We can always find a valid quadruplet pair for array size greater than MAX ; For smaller size arrays , perform brute force ; Driver code
MAX = 130 NEW_LINE def validQuadruple ( arr , n ) : NEW_LINE INDENT if ( n >= MAX ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( ( arr...
Find the number of words of X vowels and Y consonants that can be formed from M vowels and N consonants | Function to returns factorial of n ; Function to find nCr ; Function to find the number of words of X vowels and Y consonants can be formed from M vowels and N consonants ; Driver code ; Function call
def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) // ( fact ( r ) * fact ( n - r ) ) NEW_LINE DEDENT def NumberOfWays ( X , Y , M , N ) : NEW_LINE INDENT retu...
Program for sum of cosh ( x ) series upto Nth term | function to return the factorial of a number ; function to return the Sum of the series ; Driver code
def fact ( n ) : NEW_LINE INDENT i , fac = 1 , 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fac = fac * i NEW_LINE DEDENT return fac NEW_LINE DEDENT def log_Expansion ( x , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum = Sum + pow ( x , 2 * i ) / fact ( 2 ...
Find prime numbers in the first half and second half of an array | Function to check if a number is prime or not ; Function to find whether elements are prime or not ; Traverse in the given range ; Check if a number is prime or not ; Function to print the prime numbers in the first half and second half of an array ; Dr...
def prime ( n ) : NEW_LINE INDENT for i in range ( 2 , n ) : NEW_LINE INDENT if i * i > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def prime_range ( start , end , a ) : NEW_LINE INDENT for i in range ( start , end ) : N...
Count of elements that can be deleted without disturbing the mean of the initial array | Function to find the elements which do not change the mean on removal ; To store the Sum of the array elements ; To store the initial mean ; to store the count of required elements ; Iterate over the array ; Finding the new mean ; ...
def countElements ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT mean = Sum / n NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT newMean = ( Sum - arr [ i ] ) / ( n - 1 ) NEW_LINE if ( newMean == mean ) : NEW_LINE INDENT cnt += 1 NE...
Find maximum xor of k elements in an array | Python implementation of the approach ; Function to return the maximum xor for a subset of size j from the given array ; If the subset is complete then return the xor value of the selected elements ; Return if already calculated for some mask and j at the i 'th index ; Initi...
MAX = 10000 NEW_LINE MAX_ELEMENT = 50 NEW_LINE dp = [ [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX_ELEMENT ) ] for k in range ( MAX_ELEMENT ) ] NEW_LINE def Max_Xor ( arr , i , j , mask , n ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT return mask NEW_LINE DEDENT else : NE...
Find the prime P using given four integers | Python3 program to possible prime number ; Function to check if a number is prime or not ; Function to find possible prime number ; Find a possible prime number ; Last condition ; Driver code ; Function call
from math import sqrt NEW_LINE def Prime ( n ) : NEW_LINE INDENT for j in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % j == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def find_prime ( x , xsqmodp , y , ysqmodp ) : NEW_LINE INDENT n = x * x - xsqmodp NEW_...
Time taken per hour for stoppage of Car | Python3 implementation of the approach ; Function to return the time taken per hour for stoppage ; Driver code
import math NEW_LINE def numberOfMinutes ( S , S1 ) : NEW_LINE INDENT Min = 0 ; NEW_LINE Min = ( ( S - S1 ) / math . floor ( S ) ) * 60 ; NEW_LINE return int ( Min ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , S1 = 30 , 10 ; NEW_LINE print ( numberOfMinutes ( S , S1 ) , " min " ) ; NEW_LINE ...
Removing a number from array without changing its arithmetic mean | Function to remove a number from the array without changing its arithmetic mean ; Find sum of all elements ; If mean is an integer ; Check if mean is present in the array or not ; Driver code
def FindElement ( a , n ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = s + a [ i ] NEW_LINE DEDENT if s % n == 0 : NEW_LINE INDENT m = s // n NEW_LINE for j in range ( n ) : NEW_LINE INDENT if a [ j ] == m : NEW_LINE INDENT return m NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT...
Sum of the Tan ( x ) expansion upto N terms | Function to find factorial of a number ; To store factorial of a number ; Return the factorial of a number ; Function to find tan ( x ) upto n terms ; To store value of the expansion ; This loops here calculate Bernoulli number which is further used to get the coefficient i...
def fac ( num ) : NEW_LINE INDENT if ( num == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT fact = 1 ; NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT fact = fact * i ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def Tanx_expansion ( terms , x ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , t...
Minimum elements to be inserted in Array to make adjacent differences equal | Function to find gcd of two numbers ; Function to calculate minimum numbers to be inserted to make equal differences between two consecutive elements ; Check if there is only one element in the array then answer will be 0 ; Calculate differen...
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 minimum_elements ( n , arr ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = 0 NEW_LINE diff = arr [ 1 ] - arr [ 0 ] NEW_LINE g = diff NEW_LINE for i ...
Check if a number is Fermat Pseudoprime | Python3 program to check if N is Fermat pseudoprime to the base A or not ; Function to check if the given number is composite ; Check if there is any divisor of n less than sqrt ( n ) ; Effectively calculate ( x ^ y ) modulo mod ; Initialize result ; If power is odd , then upda...
from math import sqrt NEW_LINE def checkcomposite ( n ) : NEW_LINE INDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def power ( x , y , mod ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y ) : NEW_LINE I...
Largest and smallest digit of a number | Function to the largest and smallest digit of a number ; Find the largest digit ; Find the smallest digit ; Driver code ; Function call
def Digits ( n ) : NEW_LINE INDENT largest = 0 NEW_LINE smallest = 9 NEW_LINE while ( n ) : NEW_LINE INDENT r = n % 10 NEW_LINE largest = max ( r , largest ) NEW_LINE smallest = min ( r , smallest ) NEW_LINE n = n // 10 NEW_LINE DEDENT print ( largest , smallest ) NEW_LINE DEDENT n = 2346 NEW_LINE Digits ( n ) NEW_LINE
Probability of distributing M items among X bags such that first bag contains N items | Function to find factorial of a number ; Function to find nCr ; Function to find probability of first bag to contain N items such that M items are distributed among X bags ; Driver code ; Function call
def factorial ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return n * factorial ( n - 1 ) ; NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return ( factorial ( n ) / ( factorial ( r ) * factorial ( n - r ) ) ) ; NEW_LINE DEDENT def Probability ( M , N , X ) : NEW_LINE INDENT r...
Count of N digit numbers possible which satisfy the given conditions | Function to return the factorial of n ; Function to return the count of numbers possible ; Driver code
def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def Count_number ( N ) : NEW_LINE INDENT return ( N * fact ( N ) ) NEW_LINE DEDENT N = 2 NEW_LINE print ( Count_number ( N ) ) NEW_LINE
Find the count of M character words which have at least one character repeated | Function to return the factorial of a number ; Function to return the value of nPr ; Function to return the total number of M length words which have at least a single character repeated more than once ; Driver code
def fact ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return n * fact ( n - 1 ) ; NEW_LINE DEDENT def nPr ( n , r ) : NEW_LINE INDENT return fact ( n ) // fact ( n - r ) ; NEW_LINE DEDENT def countWords ( N , M ) : NEW_LINE INDENT return pow ( N , M ) - nPr ( N , M ) ; NEW_LINE DED...
Minimum and maximum possible length of the third side of a triangle | Function to find the minimum and the maximum possible length of the third side of the given triangle ; Not a valid triangle ; Not a valid triangle ; Driver code
def find_length ( s1 , s2 ) : NEW_LINE INDENT if ( s1 <= 0 or s2 <= 0 ) : NEW_LINE INDENT print ( - 1 , end = " " ) ; NEW_LINE return ; NEW_LINE DEDENT max_length = s1 + s2 - 1 ; NEW_LINE min_length = max ( s1 , s2 ) - min ( s1 , s2 ) + 1 ; NEW_LINE if ( min_length > max_length ) : NEW_LINE INDENT print ( - 1 , end = "...
Number formed by the rightmost set bit in N | Function to return the integer formed by taking the rightmost set bit in n ; n & ( n - 1 ) unsets the first set bit from the right in n ; Take xor with the original number The position of the ' changed ▁ bit ' will be set and rest will be unset ; Driver code
def firstSetBit ( n ) : NEW_LINE INDENT x = n & ( n - 1 ) NEW_LINE return ( n ^ x ) NEW_LINE DEDENT n = 12 NEW_LINE print ( firstSetBit ( n ) ) NEW_LINE
Number of N length sequences whose product is M | Function to calculate the value of ncr effectively ; Initializing the result ; Multiply and divide simultaneously to avoid overflow ; Return the answer ; Function to return the number of sequences of length N such that their product is M ; Hashmap to store the prime fac...
def ncr ( n , r ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT res *= ( n - r + i ) NEW_LINE res //= i NEW_LINE DEDENT return res NEW_LINE DEDENT def NoofSequences ( N , M ) : NEW_LINE INDENT prime = { } NEW_LINE for i in range ( 2 , int ( M ** ( .5 ) ) + 1 ) : NEW_LINE INDENT while...
Number of hours after which the second person moves ahead of the first person if they travel at a given speed | Function to return the number of hours for the second person to move ahead ; Time taken to equalize ; Time taken to move ahead ; Driver code
def findHours ( a , b , k ) : NEW_LINE INDENT if ( a >= b ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT time = k // ( b - a ) NEW_LINE time = time + 1 NEW_LINE return time NEW_LINE DEDENT a = 4 NEW_LINE b = 5 NEW_LINE k = 1 NEW_LINE print ( findHours ( a , b , k ) ) NEW_LINE
Number of ways of distributing N identical objects in R distinct groups with no groups empty | Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the number of ways to distribute N identical objects in R distinct objects ; Driver c...
def ncr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans *= ( n - r + i ) NEW_LINE ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def NoOfDistributions ( N , R ) : NEW_LINE INDENT return ncr ( N - 1 , R - 1 ) NEW_LINE DEDENT N = 4 NEW_LINE R = 3 NEW_LINE print ( NoOf...
Number of ways of distributing N identical objects in R distinct groups | Function to return the value of ncr effectively ; Initialize the answer ; Divide simultaneously by i to avoid overflow ; Function to return the number of ways to distribute N identical objects in R distinct objects ; Driver code ; Function call
def ncr ( n , r ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans *= ( n - r + i ) NEW_LINE ans //= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def NoOfDistributions ( N , R ) : NEW_LINE INDENT return ncr ( N + R - 1 , R - 1 ) NEW_LINE DEDENT N = 4 NEW_LINE R = 3 NEW_LINE print ( ...
Smallest perfect cube in an array | Python3 implementation of the approach ; Function that returns true if n is a perfect cube ; Takes the sqrt of the number ; Checks if it is a perfect cube number ; Function to return the smallest perfect cube from the array ; Stores the minimum of all the perfect cubes from the array...
import sys NEW_LINE def checkPerfectcube ( n ) : NEW_LINE INDENT d = int ( n ** ( 1 / 3 ) ) ; NEW_LINE if ( d * d * d == n ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def smallestPerfectCube ( a , n ) : NEW_LINE INDENT mini = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE ...
Find two vertices of an isosceles triangle in which there is rectangle with opposite corners ( 0 , 0 ) and ( X , Y ) | Function to find two vertices of an isosceles triangle in which there is rectangle with opposite side ( 0 , 0 ) and ( x , y ) ; Required value ; ; print x1 and y1 ; print x2 and y3 ; Driver code ; Func...
def Vertices ( x , y ) : NEW_LINE INDENT val = abs ( x ) + abs ( y ) ; NEW_LINE if x < 0 : NEW_LINE INDENT x = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = 1 NEW_LINE DEDENT print ( val * x , "0" , end = " ▁ " ) ; NEW_LINE if y < 0 : NEW_LINE INDENT y = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT y = 1 NEW_LINE DEDENT...
Find a subarray whose sum is divisible by size of the array | Function to find a subarray whose sum is a multiple of N ; Prefix sum array to store cumulative sum ; Single state dynamic programming relation for prefix sum array ; Generating all sub - arrays ; If the sum of the sub - array [ i : j ] is a multiple of N ; ...
def CheckSubarray ( arr , N ) : NEW_LINE INDENT presum = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT presum [ i ] = presum [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 ) : NEW_LINE INDENT if ( ( presum [ j ...
Find a subarray whose sum is divisible by size of the array | Function to check is there exists a subarray whose sum is a multiple of N ; Prefix sum array to store cumulative sum ; Single state dynamic programming relation for prefix sum array ; Modulo class vector ; Storing the index value in the modulo class vector ;...
def CheckSubarray ( arr , N ) : NEW_LINE INDENT presum = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT presum [ i ] = presum [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT moduloclass = [ [ ] ] * N NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT moduloclass [ presum [ i ]...
Smallest number greater or equals to N such that it has no odd positioned bit set | Function to count the total bits ; Iterate and find the number of set bits ; Right shift the number by 1 ; Function to find the nearest number ; Count the total number of bits ; To get the position ; If the last set bit is at odd positi...
def countBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE n >>= 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def findNearestNumber ( n ) : NEW_LINE INDENT cnt = countBits ( n ) ; NEW_LINE cnt -= 1 ; NEW_LINE if ( cnt % 2 ) : NEW_LINE INDENT return 1 << ( cn...
Count of numbers whose 0 th and Nth bits are set | Function to return the count of n - bit numbers whose 0 th and nth bits are set ; Driver code
def countNum ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT count = pow ( 2 , n - 2 ) NEW_LINE return count NEW_LINE DEDENT n = 3 NEW_LINE print ( countNum ( n ) ) NEW_LINE
Find a number containing N | Function to return the generated by appending "10" n - 1 times ; Initialising as empty ; Function to return the decimal equivaLent of the given binary string ; Initializing base value to 1 i . e 2 ^ 0 ; Function that calls the constructString and binarytodecimal and returns the answer ; Dri...
def constructString ( n ) : NEW_LINE INDENT s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += "10" NEW_LINE DEDENT return s NEW_LINE DEDENT def binaryToDecimal ( n ) : NEW_LINE INDENT num = n NEW_LINE dec_value = 0 NEW_LINE base = 1 NEW_LINE Len = len ( num ) NEW_LINE for i in range ( Len - 1 , - 1 , - 1 ) :...
Bitonic point in the given linked list | Node for linked list ; Function to insert a node at the head of the linked list ; Function to return the bitonic of the given linked list ; If list is empty ; If list contains only a single node ; Invalid bitonic sequence ; If current node is the bitonic point ; Get to the next ...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , data ) : NEW_LINE INDENT new_node = Node ( data ) NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DED...
Find the minimum number of elements that should be removed to make an array good | Function to remove minimum elements to make the given array good ; To store count of each subsequence ; Increase the count of subsequence [ 0 ] ; If Previous element subsequence count is greater than zero then increment subsequence count...
def MinRemove ( a , n , k ) : NEW_LINE INDENT cnt = [ 0 ] * k NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT cnt [ 0 ] += 1 ; NEW_LINE DEDENT elif ( cnt [ a [ i ] - 1 ] > 0 ) : NEW_LINE INDENT cnt [ a [ i ] - 1 ] -= 1 ; NEW_LINE cnt [ a [ i ] ] += 1 ; NEW_LINE DEDENT DEDENT return...
Print first N Mosaic numbers | Function to return the nth mosaic number ; Iterate from 2 to the number ; If i is the factor of n ; Find the count where i ^ count is a factor of n ; Divide the number by i ; Increase the count ; Multiply the answer with count and i ; Return the answer ; Function to print first N Mosaic n...
def mosaic ( n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 and n > 0 ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n = n // i NEW_LINE count += 1 ; NEW_LINE DEDENT ans *= count * i ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DE...
Count of nodes which are at a distance X from root and leaves | Python3 implementation of the approach ; Function to find the count of the required nodes ; Height of the complete binary tree with n nodes ; If X > height then no node can be present at that level ; Corner case ; Maximum total nodes that are possible in c...
from math import log2 , ceil , floor NEW_LINE def countNodes ( N , X ) : NEW_LINE INDENT height = floor ( log2 ( N ) ) NEW_LINE if ( X > height ) : NEW_LINE INDENT print ( " 0 0 " ) NEW_LINE return NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT print ( " 1 1 " ) NEW_LINE return NEW_LINE DEDENT max_total_nodes = ( 1 <<...
Number of ways of writing N as a sum of 4 squares | Number of ways of writing n as a sum of 4 squares ; sum of odd and even factor ; iterate from 1 to the number ; if i is the factor of n ; if factor is even ; if factor is odd ; n / i is also a factor ; if factor is even ; if factor is odd ; if n is odd ; if n is even ...
def sum_of_4_squares ( n ) : NEW_LINE INDENT i , odd , even = 0 , 0 , 0 NEW_LINE for i in range ( 1 , int ( n ** ( .5 ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT even += i NEW_LINE DEDENT else : NEW_LINE INDENT odd += i NEW_LINE DEDENT if ( ( n // i ) != i ) : NEW...
Find the Nth Mosaic number | Function to return the nth mosaic number ; Iterate from 2 to the number ; If i is the factor of n ; Find the count where i ^ count is a factor of n ; Divide the number by i ; Increase the count ; Multiply the answer with count and i ; Return the answer ; Driver code
def mosaic ( n ) : NEW_LINE INDENT i = 0 NEW_LINE ans = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 and n > 0 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n //= i NEW_LINE count += 1 NEW_LINE DEDENT ans *= count * i NEW_LINE DEDENT DEDENT return ans NEW_LIN...
Seating arrangement of N boys sitting around a round table such that two particular boys sit together | Function to return the total count of ways ; Find ( n - 1 ) factorial ; Return ( n - 1 ) ! * 2 ! ; Driver code
def Total_Ways ( n ) : NEW_LINE INDENT fac = 1 ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT fac = fac * i ; NEW_LINE DEDENT return ( fac * 2 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 ; NEW_LINE print ( Total_Ways ( n ) ) ; NEW_LINE DEDENT
Find the maximum number of elements divisible by 3 | Function to find the maximum number of elements divisible by 3 ; To store frequency of each number ; Store modulo value ; Store frequency ; Add numbers with zero modulo to answer ; Find minimum of elements with modulo frequency one and zero ; Add k to the answer ; Re...
def MaxNumbers ( a , n ) : NEW_LINE INDENT fre = [ 0 for i in range ( 3 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] %= 3 NEW_LINE fre [ a [ i ] ] += 1 NEW_LINE DEDENT ans = fre [ 0 ] NEW_LINE k = min ( fre [ 1 ] , fre [ 2 ] ) NEW_LINE ans += k NEW_LINE fre [ 1 ] -= k NEW_LINE fre [ 2 ] -= k NEW_LINE ans...
Count pairs with set bits sum equal to K | Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Sum of set bits in both the integers ; If current pair satisfies the given condition ; Driver code
def countSetBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 NEW_LINE DEDENT return count ; NEW_LINE DEDENT def pairs ( arr , n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE ...
Count pairs with set bits sum equal to K | Python implementation of the approach ; Function to return the count of set bits in n ; Function to return the count of required pairs ; To store the count ; Frequency array ; If current pair satisfies the given condition ; ( arr [ i ] , arr [ i ] ) cannot be a valid pair ; Dr...
MAX = 32 NEW_LINE def countSetBits ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT def pairs ( arr , n , k ) : NEW_LINE INDENT count = 0 ; NEW_LINE f = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in rang...
Print Lower Hessenberg matrix of order N | Python3 implementation of the approach ; Function to print the Upper Hessenberg matrix of order n ; If element is below sub - diagonal then pr0 ; Pra random digit for every non - zero element ; Driver code
import random NEW_LINE def UpperHessenbergMatrix ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( j > i + 1 ) : NEW_LINE INDENT print ( '0' , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( random . randint ( 1 , 10 ) , end = " ▁ " )...
Print Upper Hessenberg matrix of order N | Python3 implementation of the approach ; Function to print the Upper Hessenberg matrix of order n ; If element is below sub - diagonal then pr0 ; Pra random digit for every non - zero element ; Driver code
import random NEW_LINE def UpperHessenbergMatrix ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i > j + 1 ) : NEW_LINE INDENT print ( '0' , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( random . randint ( 1 , 10 ) , end = " ▁ " )...
Find the total number of composite factor for a given number | Function to return the count of prime factors of n ; Initialise array with 0 ; Stored i value into an array ; Every non - zero value at a [ i ] denotes that i is a factor of n ; Find if i is prime ; If i is a factor of n and i is not prime ; Driver code
def composite_factors ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE a = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT a [ i ] = i ; NEW_LINE DEDENT DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT j = 2 ; NEW_LINE p = 1 ; NEW_LINE while ( j < a [ i ]...
Sum of all mersenne numbers present in an array | Function that returns true if n is a Mersenne number ; Function to return the sum of all the Mersenne numbers from the given array ; To store the required sum ; If current element is a Mersenne number ; Driver code
def isMersenne ( n ) : NEW_LINE INDENT while ( n != 0 ) : NEW_LINE INDENT r = n % 2 ; NEW_LINE if ( r == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT n //= 2 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def sumOfMersenne ( arr , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ...
Sum of all perfect numbers present in an array | Function to return the sum of all the proper factors of n ; f is the factor of n ; Function to return the required sum ; To store the sum ; If current element is non - zero and equal to the sum of proper factors of itself ; Driver code
def sumOfFactors ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for f in range ( 1 , n // 2 + 1 ) : NEW_LINE INDENT if ( n % f == 0 ) : NEW_LINE INDENT sum += f NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def getSum ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0...
Check if two numbers have same number of digits | Function that return true if A and B have same number of digits ; Both must be 0 now if they had same lengths ; Driver code
def sameLength ( A , B ) : NEW_LINE INDENT while ( A > 0 and B > 0 ) : NEW_LINE INDENT A = A / 10 ; NEW_LINE B = B / 10 ; NEW_LINE DEDENT if ( A == 0 and B == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT A = 21 ; B = 1 ; NEW_LINE if ( sameLength ( A , B ) ) : NEW_LINE INDENT print ...
Queries to check whether all the elements can be made positive by flipping signs exactly K times | To store the count of negative integers ; Check if zero exists ; Function to find the count of negative integers and check if zero exists in the array ; Function that returns true if array elements can be made positive by...
cnt_neg = 0 ; NEW_LINE exists_zero = None ; NEW_LINE def preProcess ( arr , n ) : NEW_LINE INDENT global cnt_neg NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cnt_neg += 1 ; NEW_LINE DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT exists_zero = True ; NEW_LINE DEDENT DEDENT DEDEN...
Sum of XOR of all sub | Sum of XOR of all K length sub - array of an array ; If the length of the array is less than k ; Array that will store xor values of subarray from 1 to i ; Traverse through the array ; If i is greater than zero , store xor of all the elements from 0 to i ; If it is the first element ; If i is gr...
def FindXorSum ( arr , k , n ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT x = [ 0 ] * n ; NEW_LINE result = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT x [ i ] = x [ i - 1 ] ^ arr [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT x [ i ] = arr [ i ] ;...
Count the number of digits of palindrome numbers in an array | Function to return the reverse of n ; Function that returns true if n is a palindrome ; Function to return the count of digits of n ; Function to return the count of digits in all the palindromic numbers of arr [ ] ; If arr [ i ] is a one digit number or it...
def reverse ( n ) : NEW_LINE INDENT rev = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 10 ; NEW_LINE rev = rev * 10 + d ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return rev ; NEW_LINE DEDENT def isPalin ( n ) : NEW_LINE INDENT return ( n == reverse ( n ) ) ; NEW_LINE DEDENT def countDigits ( n ) : NEW_LINE IND...
Sum of all palindrome numbers present in an Array | Function to reverse a number n ; Function to check if a number n is palindrome ; If n is equal to the reverse of n it is a palindrome ; Function to calculate sum of all array elements which are palindrome ; summation of all palindrome numbers present in array ; Driver...
def reverse ( n ) : NEW_LINE INDENT d = 0 ; s = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 10 ; NEW_LINE s = s * 10 + d ; NEW_LINE n = n // 10 ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT def isPalin ( n ) : NEW_LINE INDENT return n == reverse ( n ) ; NEW_LINE DEDENT def sumOfArray ( arr , n ) : NEW_LINE IN...
Queries for the difference between the count of composite and prime numbers in a given range | Python3 implementation of the approach ; Function to update prime [ ] such prime [ i ] stores the count of prime numbers <= i ; Initialization ; 0 and 1 are not primes ; Mark composite numbers as false and prime numbers as tr...
from math import sqrt NEW_LINE MAX = 1000000 NEW_LINE prime = [ 0 ] * ( MAX + 1 ) ; NEW_LINE def updatePrimes ( ) : NEW_LINE INDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT prime [ i ] = 1 ; NEW_LINE DEDENT prime [ 0 ] = prime [ 1 ] = 0 ; NEW_LINE for i in range ( 2 , int ( sqrt ( MAX ) + 1 ) ) : NEW_LINE INDEN...
Check if the given Prufer sequence is valid or not | Function that returns true if given Prufer sequence is valid ; Iterate in the Prufer sequence ; If out of range ; Driver code
def isValidSeq ( a , n ) : NEW_LINE INDENT nodes = n + 2 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] < 1 or a [ i ] > nodes ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 4 , 1 , 3 , 4 ] ; NEW_LINE n = le...
Program to Calculate e ^ x by Recursion ( using Taylor Series ) | Recursive Function global variables p and f ; Termination condition ; Recursive call ; Update the power of x ; Factorial ; Driver code
p = 1.0 NEW_LINE f = 1.0 NEW_LINE def e ( x , n ) : NEW_LINE INDENT global p , f NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT r = e ( x , n - 1 ) NEW_LINE p = p * x NEW_LINE f = f * n NEW_LINE return ( r + p / f ) NEW_LINE DEDENT x = 4 NEW_LINE n = 15 NEW_LINE print ( e ( x , n ) ) NEW_LINE
Check if each element of the given array is the product of exactly K prime numbers | Python3 program to check if each element of the given array is a product of exactly K prime factors ; initialise the global sieve array ; Function to generate Sieve ; NOTE : k value is necessarily more than 1 hence , 0 , 1 and any prim...
MAX = 1000000 NEW_LINE Sieve = [ 0 ] * ( MAX + 1 ) NEW_LINE def constructSieve ( ) : NEW_LINE INDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( Sieve [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , MAX + 1 , i ) : NEW_LINE INDENT temp = j ; NEW_LINE while ( temp > 1 and temp % i == 0 ) : NEW_LINE IND...
Fibonacci Power | ; Iterative function to compute modular power ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now ; Helper function that multiplies 2 matrices F and M of size 2 * 2 , and puts the multiplication result back to F [ ] [ ] ; Helper ...
mod = 1000000007 ; NEW_LINE def modularexpo ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p ; NEW_LINE DEDENT y = y >> 1 ; NEW_LINE x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def multiply...
Count number of ways to divide an array into two halves with same sum | Function to count the number of ways to divide an array into two halves with same sum ; if length of array is 1 answer will be 0 as we have to split it into two non - empty halves ; variables to store total sum , current sum and count ; finding tot...
def cntWays ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT tot_sum = 0 ; sum = 0 ; ans = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tot_sum += arr [ i ] ; NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE if ( sum == tot_sum...
Find N distinct numbers whose bitwise Or is equal to K | Pyhton 3 implementation of the approach ; Function to pre - calculate all the powers of 2 upto MAX ; Function to return the count of set bits in x ; To store the count of set bits ; Function to add num to the answer by setting all bit positions as 0 which are als...
MAX = 32 NEW_LINE pow2 = [ 0 for i in range ( MAX ) ] NEW_LINE visited = [ False for i in range ( MAX ) ] NEW_LINE ans = [ ] NEW_LINE def power_2 ( ) : NEW_LINE INDENT an = 1 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT pow2 [ i ] = an NEW_LINE an *= 2 NEW_LINE DEDENT DEDENT def countSetBits ( x ) : NEW_LINE INDEN...
Count of all possible values of X such that A % X = B | Function to return the count of all possible values for x such that ( A % x ) = B ; Case 1 ; Case 2 ; Case 3 ; Find the number of divisors of x which are greater than b ; Driver code
def countX ( a , b ) : NEW_LINE INDENT if ( b > a ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( a == b ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = a - b NEW_LINE ans = 0 NEW_LINE i = 1 NEW_LINE while i * i <= x : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT d1 = i NEW_LINE d2 ...
Find the Jaccard Index and Jaccard Distance between the two given sets | Function to return the intersection set of s1 and s2 ; Find the intersection of the two sets ; Function to return the Jaccard index of two sets ; Sizes of both the sets ; Get the intersection set ; Size of the intersection set ; Calculate the Jacc...
def intersection ( s1 , s2 ) : NEW_LINE INDENT intersect = s1 & s2 ; NEW_LINE return intersect ; NEW_LINE DEDENT def jaccard_index ( s1 , s2 ) : NEW_LINE INDENT size_s1 = len ( s1 ) ; NEW_LINE size_s2 = len ( s2 ) ; NEW_LINE intersect = intersection ( s1 , s2 ) ; NEW_LINE size_in = len ( intersect ) ; NEW_LINE jaccard_...
Find the sum of numbers from 1 to n excluding those which are powers of K | Function to return the sum of all the powers of k from the range [ 1 , n ] ; To store the sum of the series ; While current power of k <= n ; Add current power to the sum ; Next power of k ; Return the sum of the series ; Find to return the sum...
def sumPowersK ( n , k ) : NEW_LINE INDENT sum = 0 ; num = 1 ; NEW_LINE while ( num <= n ) : NEW_LINE INDENT sum += num ; NEW_LINE num *= k ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT def getSum ( n , k ) : NEW_LINE INDENT pwrK = sumPowersK ( n , k ) ; NEW_LINE sumAll = ( n * ( n + 1 ) ) / 2 ; NEW_LINE return ( sumA...
Maximum number of people that can be killed with strength P | Python3 implementation of the approach ; Function to return the maximum number of people that can be killed ; Loop will break when the ith person cannot be killed ; Driver code
from math import sqrt NEW_LINE def maxPeople ( p ) : NEW_LINE INDENT tmp = 0 ; count = 0 ; NEW_LINE for i in range ( 1 , int ( sqrt ( p ) ) + 1 ) : NEW_LINE INDENT tmp = tmp + ( i * i ) ; NEW_LINE if ( tmp <= p ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return...
Maximum number of people that can be killed with strength P | Python3 implementation of the approach ; Function to return the maximum number of people that can be killed ; Storing the sum beforehand so that it can be used in each query ; lower_bound returns an iterator pointing to the first element greater than or equa...
kN = 1000000 ; NEW_LINE def maxPeople ( p ) : NEW_LINE INDENT sums = [ 0 ] * kN ; NEW_LINE sums [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , kN ) : NEW_LINE INDENT sums [ i ] = ( i * i ) + sums [ i - 1 ] ; NEW_LINE DEDENT it = lower_bound ( sums , 0 , kN , p ) ; NEW_LINE if ( it > p ) : NEW_LINE INDENT it -= 1 ; NEW_LINE ...
Maximum number of people that can be killed with strength P | helper function which returns the sum of series ( 1 ^ 2 + 2 ^ 2 + ... + n ^ 2 ) ; maxPeople function which returns appropriate value using Binary Search in O ( logn ) ; Set the lower and higher values ; calculate the mid using low and high ; compare value wi...
def squareSeries ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) * ( 2 * n + 1 ) ) // 6 NEW_LINE DEDENT def maxPeople ( n ) : NEW_LINE INDENT low = 0 NEW_LINE high = 1000000000000000 NEW_LINE while low <= high : NEW_LINE INDENT mid = low + ( ( high - low ) // 2 ) NEW_LINE value = squareSeries ( mid ) NEW_LINE if value <...
Find the index which is the last to be reduced to zero after performing a given operation | Function that returns the index which will be the last to become zero after performing given operation ; Initialize the result ; Finding the ceil value of each index ; Finding the index with maximum ceil value ; Driver code
def findIndex ( a , n , k ) : NEW_LINE INDENT index = - 1 NEW_LINE max_ceil = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = ( a [ i ] + k - 1 ) // k NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] >= max_ceil ) : NEW_LINE INDENT max_ceil = a [ i ] NEW_LINE index = i NEW_LINE DE...
Queries to find the maximum Xor value between X and the nodes of a given level of a perfect binary tree | Python3 implementation of the approach ; Function to solve queries of the maximum xor value between the nodes in a given level L of a perfect binary tree and a given value X ; Initialize result ; Initialize array t...
MAXN = 60 NEW_LINE def solveQuery ( L , X ) : NEW_LINE INDENT res = 0 NEW_LINE a = [ 0 for i in range ( MAXN ) ] NEW_LINE b = [ 0 for i in range ( MAXN ) ] NEW_LINE ref = X NEW_LINE size_a = 0 NEW_LINE while ( ref > 0 ) : NEW_LINE INDENT a [ size_a ] = ref % 2 NEW_LINE ref //= 2 NEW_LINE size_a += 1 NEW_LINE DEDENT for...
Count index pairs which satisfy the given condition | Function to return the count of required index pairs ; To store the required count ; Array to store the left elements upto which current element is maximum ; Iterating through the whole permutation except first and last element ; If current element can be maximum in...
def Count_Segment ( p , n ) : NEW_LINE INDENT count = 0 NEW_LINE upto = [ False ] * ( n + 1 ) NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if p [ i ] > p [ i - 1 ] and p [ i ] > p [ i + 1 ] : NEW_LINE INDENT curr = p [ i ] NEW_LINE j = i - 1 NEW_LINE while j >= 0 and p [ j ] < curr : NEW_LINE INDENT upto [ p...
Check whether a number can be represented as sum of K distinct positive integers | Function that returns true if n can be represented as the sum of exactly k distinct positive integers ; If n can be represented as 1 + 2 + 3 + ... + ( k - 1 ) + ( k + x ) ; Driver code
def solve ( n , k ) : NEW_LINE INDENT if ( n >= ( k * ( k + 1 ) ) // 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE k = 4 NEW_LINE if ( solve ( n , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE ...
Check whether product of integers from a to b is positive , negative or zero | Function to check whether the product of integers of the range [ a , b ] is positive , negative or zero ; If both a and b are positive then the product will be positive ; If a is negative and b is positive then the product will be zero ; If ...
def solve ( a , b ) : NEW_LINE INDENT if ( a > 0 and b > 0 ) : NEW_LINE INDENT print ( " Positive " ) NEW_LINE DEDENT elif ( a <= 0 and b >= 0 ) : NEW_LINE INDENT print ( " Zero " ) NEW_LINE DEDENT else : NEW_LINE INDENT n = abs ( a - b ) + 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT print ( " Positive " ) NEW_LINE ...
Bitwise AND of sub | Function to return the minimum possible value of | K - X | where X is the bitwise AND of the elements of some sub - array ; Check all possible sub - arrays ; Find the overall minimum ; Driver code
def closetAND ( arr , n , k ) : NEW_LINE INDENT ans = 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT X = arr [ i ] NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT X &= arr [ j ] NEW_LINE ans = min ( ans , abs ( k - X ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 4 , 7 , 10 ] NEW_LINE n = le...
Program to find the rate percentage from compound interest of consecutive years | Function to return the required rate percentage ; Driver code
def Rate ( N1 , N2 ) : NEW_LINE INDENT rate = ( N2 - N1 ) * 100 // ( N1 ) ; NEW_LINE return rate NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N1 = 100 NEW_LINE N2 = 120 NEW_LINE print ( Rate ( N1 , N2 ) , " ▁ % " ) NEW_LINE DEDENT
Find prime number K in an array such that ( A [ i ] % K ) is maximum | Python 3 implementation of the approach ; Function to return the required prime number from the array ; Find maximum value in the array ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " ...
from math import sqrt NEW_LINE def getPrime ( arr , n ) : NEW_LINE INDENT max_val = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > max_val ) : NEW_LINE INDENT max_val = arr [ i ] NEW_LINE DEDENT DEDENT prime = [ True for i in range ( max_val + 1 ) ] NEW_LINE prime [ 0 ] = False NEW...
Minimum integer such that it leaves a remainder 1 on dividing with any element from the range [ 2 , N ] | Python3 implementation of the approach ; Function to return the smallest number which on dividing with any element from the range [ 2 , N ] leaves a remainder of 1 ; Find the LCM of the elements from the range [ 2 ...
from math import gcd NEW_LINE def getMinNum ( N ) : NEW_LINE INDENT lcm = 1 ; NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT lcm = ( ( i * lcm ) // ( gcd ( i , lcm ) ) ) ; NEW_LINE DEDENT return ( lcm + 1 ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( getMinNum (...
Maximum number of edges in Bipartite graph | Function to return the maximum number of edges possible in a Bipartite graph with N vertices ; Driver code
def maxEdges ( N ) : NEW_LINE INDENT edges = 0 ; NEW_LINE edges = ( N * N ) // 4 ; NEW_LINE return edges ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( maxEdges ( N ) ) ; NEW_LINE DEDENT
Check if the robot is within the bounds of the grid after given moves | Function that returns true if the robot is safe ; If current move is " L " then increase the counter of coll ; If value of coll is equal to column then break ; If current move is " R " then increase the counter of colr ; If value of colr is equal t...
def isSafe ( N , M , str ) : NEW_LINE INDENT coll = 0 NEW_LINE colr = 0 NEW_LINE rowu = 0 NEW_LINE rowd = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' L ' ) : NEW_LINE INDENT coll += 1 NEW_LINE if ( colr > 0 ) : NEW_LINE INDENT colr -= 1 NEW_LINE DEDENT if ( coll == M ) : NEW_LINE IND...
Find sub | Function to print the valid indices in the array ; Function to find sub - arrays from two different arrays with equal sum ; Map to store the indices in A and B which produce the given difference ; Find the smallest j such that b [ j ] >= a [ i ] ; Difference encountered for the second time ; b [ j ] - a [ i ...
def printAns ( x , y , num ) : NEW_LINE INDENT print ( " Indices ▁ in ▁ array " , num , " : " , end = " ▁ " ) NEW_LINE for i in range ( x , y ) : NEW_LINE INDENT print ( i , end = " , ▁ " ) NEW_LINE DEDENT print ( y ) NEW_LINE DEDENT def findSubarray ( N , a , b , swap ) : NEW_LINE INDENT index = { } NEW_LINE differenc...
Find permutation of first N natural numbers that satisfies the given condition | Function to find permutation ( p ) of first N natural numbers such that there are exactly K elements of permutation such that GCD ( p [ i ] , i ) > 1 ; First place all the numbers in their respective places ; Modify for first n - k integer...
def Permutation ( n , k ) : NEW_LINE INDENT p = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT p [ i ] = i NEW_LINE DEDENT for i in range ( 1 , n - k ) : NEW_LINE INDENT p [ i + 1 ] = i NEW_LINE DEDENT p [ 1 ] = n - k NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ...
Count number of 1 s in the array after N moves | Function to count number of 1 's in the array after performing N moves ; If index is multiple of move number ; arr [ j - 1 ] = 1 Convert 0 to 1 ; arr [ j - 1 ] = 0 Convert 1 to 0 ; Count number of 1 's ; count += 1 count number of 1 's ; Driver Code ; Initialize all elem...
def countOnes ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 , 1 ) : NEW_LINE INDENT if ( j % i == 0 ) : NEW_LINE INDENT if ( arr [ j - 1 ] == 0 ) : NEW_LINE else : NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( a...
Number of positions such that adding K to the element is greater than sum of all other elements | Function that will find out the valid position ; find sum of all the elements ; adding K to the element and check whether it is greater than sum of all other elements ; Driver code
def validPosition ( arr , N , K ) : NEW_LINE INDENT count = 0 ; sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( ( arr [ i ] + K ) > ( sum - arr [ i ] ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE...
Count unique numbers that can be generated from N by adding one and removing trailing zeros | Function to count the unique numbers ; If the number has already been visited ; Insert the number to the set ; First step ; Second step remove trailing zeros ; Recur again for the new number ; Driver code
def count_unique ( s , n ) : NEW_LINE INDENT if ( s . count ( n ) ) : NEW_LINE INDENT return ; NEW_LINE DEDENT s . append ( n ) ; NEW_LINE n += 1 ; NEW_LINE while ( n % 10 == 0 ) : NEW_LINE INDENT n = n // 10 ; NEW_LINE DEDENT count_unique ( s , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n ...
Find element with the maximum set bits in an array | Function to return the element from the array which has the maximum set bits ; To store the required element and the maximum set bits so far ; Count of set bits in the current element ; Update the max ; Driver code
def maxBitElement ( arr , n ) : NEW_LINE INDENT num = 0 NEW_LINE max = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT cnt = bin ( arr [ i ] ) . count ( '1' ) NEW_LINE if ( cnt > max ) : NEW_LINE INDENT max = cnt NEW_LINE num = arr [ i ] NEW_LINE DEDENT DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ ...
Count pairs with average present in the same array | Python 3 implementation of the approach ; Function to return the count of valid pairs ; Frequency array Twice the original size to hold negative elements as well ; Update the frequency of each of the array element ; If say x = - 1000 then we will place the frequency ...
N = 1000 NEW_LINE def countPairs ( arr , n ) : NEW_LINE INDENT size = ( 2 * N ) + 1 NEW_LINE freq = [ 0 for i in range ( size ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = arr [ i ] NEW_LINE freq [ x + N ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : ...
Smallest and Largest sum of two n | Function to return the smallest sum of 2 n - digit numbers ; Function to return the largest sum of 2 n - digit numbers ; Driver code
def smallestSum ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 2 * pow ( 10 , n - 1 ) ) NEW_LINE DEDENT def largestSum ( n ) : NEW_LINE INDENT return ( 2 * ( pow ( 10 , n ) - 1 ) ) NEW_LINE DEDENT n = 4 NEW_LINE print ( " Largest ▁ = ▁ " , largestSum ( n ) ) NEW_LINE print ( "...
Given two arrays count all pairs whose sum is an odd number | Function that returns the number of pairs ; Count of odd and even numbers ; Traverse in the first array and count the number of odd and evene numbers in them ; Traverse in the second array and count the number of odd and evene numbers in them ; Count the num...
def count_pairs ( a , b , n , m ) : NEW_LINE INDENT odd1 = 0 NEW_LINE even1 = 0 NEW_LINE odd2 = 0 NEW_LINE even2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 ) : NEW_LINE INDENT odd1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even1 += 1 NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE IND...
Print steps to make a number in form of 2 ^ X | Function to find the leftmost unset bit in a number . ; Function that perform the step ; Find the leftmost unset bit ; If the number has no bit unset , it means it is in form 2 ^ x - 1 ; Count the steps ; Iterate till number is of form 2 ^ x - 1 ; At even step increase by...
def find_leftmost_unsetbit ( n ) : NEW_LINE INDENT ind = - 1 ; NEW_LINE i = 1 ; NEW_LINE while ( n ) : NEW_LINE INDENT if ( ( n % 2 ) != 1 ) : NEW_LINE INDENT ind = i ; NEW_LINE DEDENT i += 1 ; NEW_LINE n >>= 1 ; NEW_LINE DEDENT return ind ; NEW_LINE DEDENT def perform_steps ( n ) : NEW_LINE INDENT left = find_leftmost...
Determine the position of the third person on regular N sided polygon | Function to find out the number of that vertices ; Another person can 't stand on vertex on which 2 children stand. ; calculating minimum jumps from each vertex . ; Calculate Sum of jumps . ; Driver code ; Calling function
def vertices ( N , A , B ) : NEW_LINE INDENT position = 0 NEW_LINE miniSum = 10 ** 9 NEW_LINE Sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i == A or i == B ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT x = abs ( i - A ) NEW_LINE y = abs ( i - B ) NEW_LINE Sum = x + y NEW_LI...
Find sum of factorials in an array | Function to return the factorial of n ; Function to return the sum of factorials of the array elements ; To store the required sum ; Add factorial of all the elements ; Driver code
def factorial ( n ) : NEW_LINE INDENT f = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT f *= i ; NEW_LINE DEDENT return f ; NEW_LINE DEDENT def sumFactorial ( arr , n ) : NEW_LINE INDENT s = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s += factorial ( arr [ i ] ) ; NEW_LINE DEDENT return s ; N...
Minimum steps to color the tree with given colors | To store the required answer ; To store the graph ; Function to add edges ; Dfs function ; When there is difference in colors ; For all it 's child nodes ; Here zero is for parent of node 1 ; Adding edges in the graph ; Dfs call ; Required answer
ans = 0 NEW_LINE gr = [ [ ] for i in range ( 100005 ) ] NEW_LINE def Add_Edge ( u , v ) : NEW_LINE INDENT gr [ u ] . append ( v ) NEW_LINE gr [ v ] . append ( u ) NEW_LINE DEDENT def dfs ( child , par , color ) : NEW_LINE INDENT global ans NEW_LINE if ( color [ child ] != color [ par ] ) : NEW_LINE INDENT ans += 1 NEW_...