text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Maximize difference between odd and even indexed array elements by swapping unequal adjacent bits in their binary representations | Python program for the above approach ; Function to count total number of bits present in a number ; Function to count total set bits in a number ; Stores the count of set bits ; Right shi... | import math NEW_LINE def countBit ( n ) : NEW_LINE INDENT return int ( math . log ( n , 2 ) ) + 1 NEW_LINE DEDENT def countSetBit ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while n : NEW_LINE INDENT ans += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def maximize ( n ) : NEW_LINE INDENT bits = countB... |
Sum of numbers obtained by the count of set and non | Functino to find the number after processing the diagonal elements ; Store the required number ; Checking for each position ; Store the number of set bits & non - set bits at position i ; Traverse the diagonal elements ; Update count of S if current element is set a... | def processDiagonal ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE getBit = 1 NEW_LINE for i in range ( 32 ) : NEW_LINE INDENT S = 0 NEW_LINE NS = 0 NEW_LINE for j in arr : NEW_LINE if getBit & j : NEW_LINE INDENT S += 1 NEW_LINE DEDENT else : NEW_LINE INDENT NS += 1 NEW_LINE DEDENT if S > NS : NEW_LINE ans += 2 ** i NEW_L... |
Minimize difference between two sequences obtained by splitting first N powers of 2 | Function to partition first N powers of 2 into two subsequences with minimum difference between their sum ; Largest element in the first part ; Place N / 2 - 1 smallest elements in the first sequence ; Place remaining N / 2 elements i... | def minimumDifference ( N ) : NEW_LINE INDENT sum1 = ( 1 << N ) NEW_LINE sum2 = 0 NEW_LINE for i in range ( 1 , N // 2 ) : NEW_LINE INDENT sum1 += ( 1 << i ) NEW_LINE DEDENT for i in range ( N // 2 , N ) : NEW_LINE INDENT sum2 += ( 1 << i ) NEW_LINE DEDENT print ( sum1 - sum2 ) NEW_LINE DEDENT N = 4 NEW_LINE minimumDif... |
Check whether N can be a Perfect Cube after adding or subtracting K | Function to check if a number is a perfect Cube or not ; Driver code | def isPerfectCube ( x ) : NEW_LINE INDENT cr = int ( x ** ( 1 / 3 ) ) ; NEW_LINE return ( cr * cr * cr == x ) ; NEW_LINE DEDENT def canBePerfectCube ( N , K ) : NEW_LINE INDENT if ( isPerfectCube ( N + K ) or isPerfectCube ( N - K ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ... |
Floor square root without using sqrt ( ) function : Recursive | Function to find the square root of the number N using BS ; If the range is still valid ; Find the mid - value of the range ; Base Case ; Condition to check if the left search space is useless ; Driver Code | def sqrtSearch ( low , high , N ) : NEW_LINE INDENT if ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 ; NEW_LINE if ( ( mid * mid <= N ) and ( ( mid + 1 ) * ( mid + 1 ) > N ) ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT elif ( mid * mid < N ) : NEW_LINE INDENT return sqrtSearch ( mid + 1 , high , N ) ;... |
Common divisors of N numbers | Function to calculate gcd of two numbers ; Function to prall the common divisors ; Variable to find the gcd of N numbers ; Set to store all the common divisors ; Finding GCD of the given N numbers ; Finding divisors of the HCF of n numbers ; Prall the divisors ; Driver 's Code ; Function ... | 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 printAllDivisors ( arr , N ) : NEW_LINE INDENT g = arr [ 0 ] NEW_LINE divisors = dict ( ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT g = gcd ( arr [ i ] , g ) NEW_LINE DEDEN... |
Recursive Program to print multiplication table of a number | Function that print the table of a given number using recursion ; Base Case ; Print the table for current iteration ; Recursive call to next iteration ; Input number whose table is to print ; Function call to print the table | def mul_table ( N , i ) : NEW_LINE INDENT if ( i > 10 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( N , " * " , i , " = " , N * i ) NEW_LINE return mul_table ( N , i + 1 ) NEW_LINE DEDENT N = 8 NEW_LINE mul_table ( N , 1 ) NEW_LINE |
Find the largest composite number that divides N but is strictly lesser than N | Python3 program to find the largest composite number that divides N which is less than N ; Function to check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function that find the largest composite number which div... | import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def getSmallestPrimefactor ( n ) : NEW_LINE INDENT fo... |
Check if N and M can be made equal by increasing N by A and decreasing M by B | Function to whether the numbers can be made equal or not ; Check whether the numbers can reach an equal point or not ; M and N cannot be made equal by increasing M and decreasing N when M is already greater than N ; Driver code | def checkEqualNo ( m , n , a , b ) : NEW_LINE INDENT if ( m <= n ) : NEW_LINE INDENT if ( ( n - m ) % ( a + b ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ "... |
XOR and OR of all N | Function to check if a number is palindrome or not ; Convert the num n to string ; Iterate over string to check whether it is palindromic or not ; Function to find XOR of all N - digits palindrome number ; To store the XOR and OR of all palindromic number ; Starting N - digit palindromic number ; ... | def ispalin ( num ) : NEW_LINE INDENT s = str ( num ) ; NEW_LINE st = 0 ; NEW_LINE ed = len ( s ) - 1 ; NEW_LINE while ( st <= ed ) : NEW_LINE INDENT if ( s [ st ] != s [ ed ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT st += 1 ; NEW_LINE ed -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def CalculateXORan... |
Sum of all palindromic numbers lying in the range [ L , R ] for Q queries | pref [ ] array to precompute the sum of all palindromic number ; Function that return number num if num is palindromic else return 0 ; Convert num to string ; Function to precompute the sum of all palindrome numbers upto 100000 ; checkPalindrom... | pref = [ 0 ] * 100001 NEW_LINE def checkPalindrome ( num ) : NEW_LINE INDENT strr = str ( num ) NEW_LINE l = 0 NEW_LINE r = len ( strr ) - 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( strr [ l ] != strr [ r ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT return num NEW_LINE DE... |
Sum of alternating sign Squares of first N natural numbers | Function to calculate the alternating sign sum ; Variable to store the sum ; Loop to iterate each number from 1 to N ; The alternating sign is put by checking if the number is even or odd ; Add the square with the sign ; Add the square with the sign ; Driver ... | def summation ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 1 ) : NEW_LINE INDENT sum += ( i * i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT sum -= ( i * i ) ; NEW_LINE DEDENT DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N... |
Sum of alternating sign Squares of first N natural numbers | Function to calculate the alternating sign sum ; Variable to store the absolute sum ; Variable to store the sign ; Variable to store the resultant sum ; Driver code | def summation ( n ) : NEW_LINE INDENT abs_sum = n * ( n + 1 ) // 2 ; NEW_LINE sign = 1 if ( ( n + 1 ) % 2 == 0 ) else - 1 ; NEW_LINE result_sum = sign * abs_sum ; NEW_LINE return result_sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 ; NEW_LINE print ( summation ( N ) ) ; NEW_LINE DEDENT |
Count pairs from 1 to N such that their Sum is divisible by their XOR | Function to count pairs ; variable to store count ; Generate all possible pairs such that 1 <= x < y < n ; Driver code | def countPairs ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for x in range ( 1 , n ) : NEW_LINE INDENT for y in range ( x + 1 , n + 1 ) : NEW_LINE INDENT if ( ( y + x ) % ( y ^ x ) == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LI... |
Count pairs in array such that one element is power of another | Python3 program to count pairs in array such that one element is power of another ; Function to check if given number number y is power of x ; log function to calculate value ; compare to the result1 or result2 both are equal ; Function to find pairs from... | from math import log NEW_LINE def isPower ( x , y ) : NEW_LINE INDENT res1 = log ( y ) // log ( x ) ; NEW_LINE res2 = log ( y ) / log ( x ) ; NEW_LINE return ( res1 == res2 ) ; NEW_LINE DEDENT def countPower ( arr , n ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ,... |
Find the original Array using XOR values of all adjacent elements | XOR of all elements from 1 to N ; Function to find the Array from the XOR Array ; Take a vector to store the permutation ; XOR of N natural numbers ; Loop to find the XOR of adjacent elements of the XOR Array ; Loop to find the other elements of the pe... | def xor_all_elements ( n ) : NEW_LINE INDENT if n & 3 == 0 : NEW_LINE INDENT return n NEW_LINE DEDENT elif n & 3 == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif n & 3 == 2 : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def findArray ( xorr , n ) : NEW_LINE IND... |
Sum of non | Function to return a vector which consists the sum of four portions of the matrix ; Iterating through the matrix ; Condition for selecting all values before the second diagonal of metrics ; Top portion of the matrix ; Left portion of the matrix ; Bottom portion of the matrix ; Right portion of the matrix ;... | def sumOfParts ( arr , N ) : NEW_LINE INDENT sum_part1 , sum_part2 , sum_part3 , sum_part4 = 0 , 0 , 0 , 0 NEW_LINE totalsum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if i + j < N - 1 : NEW_LINE INDENT if ( i < j and i != j and i + j ) : NEW_LINE INDENT sum_part1 += arr ... |
Check if X and Y can be made zero by using given operation any number of times | Function to check if X and Y can be made equal to zero by using given operation any number of times ; Check for the two conditions ; Driver code | def ifPossible ( X , Y ) : NEW_LINE INDENT if ( X > Y ) : NEW_LINE INDENT X , Y = Y , X NEW_LINE DEDENT if ( ( X + Y ) % 5 == 0 and 3 * X >= 2 * Y ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT X = 33 NEW_LINE Y = 27 NEW_LINE ifPossible ( X , Y ) NEW... |
Largest Even and Odd N | Function to print the largest n - digit even and odd numbers in hexadecimal number system ; Append ' F ' ( N - 1 ) times ; Append ' E ' for an even number ; Append ' F ' for an odd number ; Driver code | def findNumbers ( n ) : NEW_LINE INDENT ans = ' F ' * ( n - 1 ) ; NEW_LINE even = ans + ' E ' ; NEW_LINE odd = ans + ' F ' ; NEW_LINE print ( " Even : β " , even ) ; NEW_LINE print ( " Odd : β " , odd ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE findNumbers ( n ) ; NEW_LINE DED... |
Program to compute log a to any base b ( logb a ) | Python3 program to find log ( a ) on any base b ; Driver code | from math import log NEW_LINE def log_a_to_base_b ( a , b ) : NEW_LINE INDENT return log ( a ) // log ( b ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; NEW_LINE b = 2 ; NEW_LINE print ( log_a_to_base_b ( a , b ) ) ; NEW_LINE a = 256 ; NEW_LINE b = 4 ; NEW_LINE print ( log_a_to_base_b ( a... |
Program to compute log a to any base b ( logb a ) | Recursive function to compute log a to the base b ; Driver code | def log_a_to_base_b ( a , b ) : NEW_LINE INDENT rslt = ( 1 + log_a_to_base_b ( a // b , b ) ) if ( a > ( b - 1 ) ) else 0 ; NEW_LINE return rslt ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 3 ; NEW_LINE b = 2 ; NEW_LINE print ( log_a_to_base_b ( a , b ) ) ; NEW_LINE a = 256 ; NEW_LINE b = 4 ;... |
Largest and Smallest N | Function to return the largest N - digit number in Hexa - Decimal Number System ; Append ' F ' N times ; Function to return the smallest N - digit number in Hexa - Decimal Number System ; Append '0' ( N - 1 ) times to 1 ; Function to print the largest and smallest N - digit Hexa - Decimal numbe... | def findLargest ( N ) : NEW_LINE INDENT largest = ' F ' * N NEW_LINE return largest ; NEW_LINE DEDENT def findSmallest ( N ) : NEW_LINE INDENT smallest = '1' + '0' * ( N - 1 ) NEW_LINE return smallest ; NEW_LINE DEDENT def printAns ( largest ) : NEW_LINE INDENT print ( " Largest : β " , findLargest ( largest ) ) ; NEW_... |
Highest and Smallest power of K less than and greater than equal to N respectively | Python3 implementation of the approach ; Function to return the highest power of k less than or equal to n ; Function to return the smallest power of k greater than or equal to n ; Function to print the result ; Driver code | import math NEW_LINE def prevPowerofK ( n , k ) : NEW_LINE INDENT p = int ( math . log ( n ) / math . log ( k ) ) NEW_LINE return int ( math . pow ( k , p ) ) NEW_LINE DEDENT def nextPowerOfK ( n , k ) : NEW_LINE INDENT return prevPowerofK ( n , k ) * k NEW_LINE DEDENT def printResult ( n , k ) : NEW_LINE INDENT print ... |
Check if all elements of the given array can be made 0 by decrementing value in pairs | Function to check if all the elements can be made 0 in an array ; Variable to store sum and maximum element in an array ; Loop to calculate the sum and max value of the given array ; If n is 1 or sum is odd or sum - max element < ma... | def canMake ( n , ar ) : NEW_LINE INDENT sum = 0 ; maxx = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ar [ i ] ; NEW_LINE maxx = max ( maxx , ar [ i ] ) ; NEW_LINE DEDENT if ( n == 1 or sum % 2 == 1 or sum - maxx < maxx ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print... |
Sum of all Perfect Squares lying in the range [ L , R ] for Q queries | Python3 program to find the sum of all perfect squares in the given range ; Array to precompute the sum of squares from 1 to 100010 so that for every query , the answer can be returned in O ( 1 ) . ; Function to check if a number is a perfect squar... | from math import sqrt , floor NEW_LINE pref = [ 0 ] * 100010 ; NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = sqrt ( x ) ; NEW_LINE rslt = x if ( sr - floor ( sr ) == 0 ) else 0 ; NEW_LINE return rslt ; NEW_LINE DEDENT def compute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 ) : NEW_LINE INDENT pref [ i... |
Program to find all Factors of a Number using recursion | Recursive function to prfactors of a number ; Checking if the number is less than N ; Calling the function recursively for the next number ; Driver code | def factors ( n , i ) : NEW_LINE INDENT if ( i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE DEDENT factors ( n , i + 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 16 ; NEW_LINE factors ( N , 1 ) ; NEW_LINE DEDENT |
Maximize value of ( a + b ) such that ( a * a | Function to maximize the value of ( a + b ) such that ( a * a - b * b = n ) ; Driver code | def maxValue ( n ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1 ; NEW_LINE print ( maxValue ( n ) ) ; NEW_LINE DEDENT |
Maximum number of edges that N | Function to find the maximum number of edges in a N - vertex graph . ; According to the Mantel 's theorem the maximum number of edges will be floor of [(n^2)/4] ; Driver Function | def solve ( n ) : NEW_LINE INDENT ans = ( n * n // 4 ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( solve ( n ) ) NEW_LINE DEDENT |
Multiplication table till N rows where every Kth row is table of K upto Kth term | Function to pr the multiplication table upto K - th term ; For loop to iterate from 1 to N where i serves as the value of K ; Inner loop which at every iteration goes till i ; Printing the table value for i ; New line after every row ; D... | def prMultiples ( N ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT print ( ( i * j ) , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE prMultiples ( N ) NEW_LINE DEDENT |
Boundary Value Analysis : Nature of Roots of a Quadratic equation | BVA for nature of roots of a quadratic equation ; If a = 0 , D / 2 a will yield exception Hence it is not a valid Quadratic Equation ; If D > 0 , it will be Real Roots ; If D == 0 , it will be Equal Roots ; If D < 0 , it will be Imaginary Roots ; Funct... | def nature_of_roots ( a , b , c ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT print ( " Not β a β Quadratic β Equation " ) ; NEW_LINE return ; NEW_LINE DEDENT D = b * b - 4 * a * c ; NEW_LINE if ( D > 0 ) : NEW_LINE INDENT print ( " Real β Roots " ) ; NEW_LINE DEDENT elif ( D == 0 ) : NEW_LINE INDENT print ( " Eq... |
Find if the Vacation can be taken or not | Function to find if the Vacation is possible or not ; Find the required number of hours of study ; find the hours of study that can be done if the vacation is taken ; check if the required hours are less than or equal to the hours of study that can be done if the vacation is t... | def isPossible ( N , S , C , H , L , T ) : NEW_LINE INDENT total_time_required = S * C * H NEW_LINE available_time_after_vacation = ( N - L ) * T NEW_LINE if ( available_time_after_vacation >= total_time_required ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT N = 12 NEW_LINE S = 5 NEW_LINE C = 8 ... |
Find Maximum and Minimum of two numbers using Absolute function | Function to return maximum among the two numbers ; Function to return minimum among the two numbers ; Driver code ; Displaying the maximum value ; Displaying the minimum value | def maximum ( x , y ) : NEW_LINE INDENT return ( ( x + y + abs ( x - y ) ) // 2 ) NEW_LINE DEDENT def minimum ( x , y ) : NEW_LINE INDENT return ( ( x + y - abs ( x - y ) ) // 2 ) NEW_LINE DEDENT x = 99 NEW_LINE y = 18 NEW_LINE print ( " Maximum : " , maximum ( x , y ) ) NEW_LINE print ( " Minimum : " , minimum ( x , y... |
Find an array of size N having exactly K subarrays with sum S | Function to find array with K subarrays with sum S ; Driver Code ; Function call | def SubarraysWithSumS ( n , k , s ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT print ( s , end = " β " ) NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT print ( s + 1 , end = " β " ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE k = 2 NEW_LINE s = 3 NEW_LINE SubarraysWithSumS ( n , k , s ) NEW_LINE |
Minimum number of cuts required to pay salary from N length Gold Bar | Python Implementation to find the minimum number of cuts to pay the worker . ; Function to find the minimum number of cuts to pay the worker . ; Nearest Integer to the Log value of the number N ; Driver Code ; Cuts Required in the Length of 15 | import math NEW_LINE def pay ( n ) : NEW_LINE INDENT cuts = int ( math . log ( n , 2 ) ) NEW_LINE return cuts NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE cuts = pay ( n ) NEW_LINE print ( cuts ) NEW_LINE n = 15 NEW_LINE cuts = pay ( n ) NEW_LINE print ( cuts ) NEW_LINE DEDENT |
Sum of Maximum and Minimum prime factor of every number in the Array | Python3 implementation of the approach ; max_prime [ i ] represent maximum prime number that divides the number i ; min_prime [ i ] represent minimum prime number that divides the number i ; Function to store the minimum prime factor and the maximum... | MAX = 100000 NEW_LINE max_prime = [ 0 ] * ( MAX + 1 ) NEW_LINE min_prime = [ 0 ] * ( MAX + 1 ) NEW_LINE def sieve ( n ) : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( min_prime [ i ] > 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT min_prime [ i ] = i NEW_LINE max_prime [ i ] = i NEW_LINE j = i +... |
Pair of integers ( a , b ) which satisfy the given equations | Function to count valid pairs ; Driver code | def pairCount ( n , m ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for b in range ( int ( pow ( m , 1 / 2 ) ) ) : NEW_LINE INDENT a = m - b * b ; NEW_LINE if ( a * a + b == n ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 9 ; NEW_LINE m... |
Largest Divisor for each element in an array other than 1 and the number itself | Python3 implementation of the approach ; Divisors array to keep track of the maximum divisor ; Function to pre - compute the prime numbers and largest divisors ; Visited array to keep track of prime numbers ; 0 and 1 are not prime numbers... | maxin = 100001 ; NEW_LINE divisors = [ 0 ] * ( maxin + 1 ) ; NEW_LINE def Calc_Max_Div ( arr , n ) : NEW_LINE INDENT vis = [ 1 ] * ( maxin + 1 ) ; NEW_LINE vis [ 0 ] = vis [ 1 ] = 0 ; NEW_LINE for i in range ( 1 , maxin + 1 ) : NEW_LINE INDENT divisors [ i ] = i ; NEW_LINE DEDENT for i in range ( 4 , maxin + 1 , 2 ) : ... |
Given a number N in decimal base , find the sum of digits in any base B | Function to compute sum of Digits of Number N in base B ; Initialize sum with 0 ; Compute unit digit of the number ; Add unit digit in sum ; Update value of Number ; Driver code | def sumOfDigit ( n , b ) : NEW_LINE INDENT unitDigit = 0 NEW_LINE sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT unitDigit = n % b NEW_LINE sum += unitDigit NEW_LINE n = n // b NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 50 NEW_LINE b = 2 NEW_LINE print ( sumOfDigit ( n , b ) ) NEW_LINE |
Find the Nth digit from right in base B of the given number in Decimal base | Function to compute Nth digit from right in base B ; Skip N - 1 Digits in Base B ; Nth Digit from right in Base B ; Driver Code | def nthDigit ( a , n , b ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT a = a // b NEW_LINE DEDENT return a % b NEW_LINE DEDENT a = 100 NEW_LINE n = 3 NEW_LINE b = 4 NEW_LINE print ( nthDigit ( a , n , b ) ) NEW_LINE |
Find three prime numbers with given sum | Python3 implementation of the approach ; The vector primes holds the prime numbers ; Function to generate prime numbers ; Initialize the array elements to 0 s ; Set the non - primes to true ; Fill the vector primes with prime numbers which are marked as false in the numbers arr... | from math import sqrt NEW_LINE MAX = 100001 ; NEW_LINE primes = [ ] ; NEW_LINE def initialize ( ) : NEW_LINE INDENT numbers = [ 0 ] * ( MAX + 1 ) ; NEW_LINE n = MAX ; NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( not numbers [ i ] ) : NEW_LINE INDENT for j in range ( i * i , n + 1 , i ) ... |
Print all maximal increasing contiguous sub | Function to print each of maximal contiguous increasing subarray ; Loop to iterate through the array and print the maximal contiguous increasing subarray . ; Condition to check whether the element at i , is greater than its next neighbouring element or not . ; Driver functi... | def printmaxSubseq ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] ) ; NEW_LINE DEDENT DEDENT print ( arr [ n - 1 ] ) ; NEW_LINE DEDENT if __name__ == ... |
Count of non decreasing arrays of length N formed with values in range L to R | Function to return the count of different arrays ; No such combination exists ; Arrays formed with single elements ; Driver code | def countSum ( N , L , R ) : NEW_LINE INDENT if ( L > R ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT return R - L + 1 ; NEW_LINE DEDENT if ( N > 1 ) : NEW_LINE INDENT return ( N - 2 ) * ( R - L ) + 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LIN... |
Minimum decrement operations to make Array elements equal by only decreasing K each time | Python3 implementation of the above approach ; Finding the minimum element ; Loop over all the elements and find the difference ; Solution found and returned ; Driver code | import sys NEW_LINE def solve ( arr , n , k ) : NEW_LINE INDENT minx = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT minx = min ( minx , arr [ i ] ) ; NEW_LINE DEDENT decrements = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( arr [ i ] - minx ) % k != 0 ) : NEW_LINE INDENT return - 1 ; NE... |
Count non decreasing subarrays of size N from N Natural numbers | Returns value of Binomial Coefficient C ( n , k ) ; Since nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Function to find the count of required subarrays ; The required count is the binomial coefficient as explained in the approa... | def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 ] * ( k + 1 ) ; NEW_LINE C [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] ; NEW_LINE DEDENT DEDENT return C [ k ] ; NEW_LINE DEDENT def count_of_subarra... |
Length of Smallest subarray in range 1 to N with sum greater than a given value | Function to do a binary search on a given range . ; Total sum is the sum of N numbers . ; Sum until mid ; If remaining sum is < the required value , then the required number is in the right half ; Driver code | def usingBinarySearch ( start , end , N , S ) : NEW_LINE INDENT if ( start >= end ) : NEW_LINE INDENT return start ; NEW_LINE DEDENT mid = start + ( end - start ) // 2 ; NEW_LINE totalSum = ( N * ( N + 1 ) ) // 2 ; NEW_LINE midSum = ( mid * ( mid + 1 ) ) // 2 ; NEW_LINE if ( ( totalSum - midSum ) <= S ) : NEW_LINE INDE... |
Distribution of a Number in Array within a Range | Function for the distribution of the number ; Distribute the number among k elements ; If there is some remaining sum to distribute ; If there are elements remaining to distribute i . e . ( n - k ) ; Divide the remaining sum into n - k elements ; Print the distribution... | def distribution ( n , k , l , r , S , Sk ) : NEW_LINE INDENT a = [ 0 ] * n ; NEW_LINE len = k ; NEW_LINE temp , rem , s = 0 , 0 , 0 ; NEW_LINE diff = S - Sk ; NEW_LINE for i in range ( len ) : NEW_LINE INDENT temp = Sk / k ; NEW_LINE rem = Sk % k ; NEW_LINE if ( temp + rem >= l and temp + rem <= r ) : NEW_LINE INDENT ... |
Number of valid indices in the permutation of first N natural numbers | Python3 implementation of the approach ; Function to return the number of i 's such that Pi <= Pj for all 1 <= j <= i in the permutation of first N natural numbers ; To store the count of such indices ; Store the mini value ; For all the elements ;... | import sys NEW_LINE INT_MAX = sys . maxsize NEW_LINE def min_index ( p , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE mini = INT_MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] <= mini ) : NEW_LINE INDENT mini = p [ i ] ; NEW_LINE DEDENT if ( mini == p [ i ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT... |
Check if Sum and XOR of all elements of array is equal | Function to Check if Sum and XOR of all elements of array is equal ; Sum and XOR of all elements ; Checking Sum and XOR to be equal ; Driver Function ; Check Sum and XOR is equal | def equal_xor_sum ( arr , n ) : NEW_LINE INDENT Sum = 0 ; NEW_LINE Xor = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum = Sum + arr [ i ] ; NEW_LINE Xor = Xor ^ arr [ i ] ; NEW_LINE DEDENT if ( Sum == Xor ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE... |
Count of odd length contiguous Palindromic sequences in a Matrix | Python code to Count the odd length contiguous Palindromic sequences in the matrix ; Function to count the number of contiguous palindromic sequences in the matrix ; Add the total number of elements in the matrix to the count ; Length of possible sequen... | MAX = 10 ; NEW_LINE def countPalindromes ( n , m , matrix ) : NEW_LINE INDENT count = n * m ; NEW_LINE length_of_sequence_row = 0 ; NEW_LINE length_of_sequence_column = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT length_of_sequence_row = min ( j , m - 1 - j ) ; NEW_LINE le... |
Reduce a number to 1 by performing given operations | Set 2 | Function to return the number of set bits in n ; Function to return the minimum steps required to reach 1 ; If n is even then divide it by 2 ; If n is 3 or the number of set bits in ( n - 1 ) is less than the number of set bits in ( n + 1 ) ; Increment the n... | def set_bits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n % 2 NEW_LINE n //= 2 NEW_LINE DEDENT return count NEW_LINE DEDENT def minSteps ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( n != 1 ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT n //= 2 NEW_LINE DEDENT elif ( n... |
Minimum integer that can be obtained by swapping adjacent digits of different parity | Function to return the minimum number ; Store the elements which are divisible by two in stack1 ; Store the elements which are not divisible by two in stack2 . ; Concatenate the answer with smaller value of the topmost elements of bo... | def minimumNo ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE stack1 = [ ] NEW_LINE stack2 = [ ] NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % 10 NEW_LINE if ( r % 2 == 0 ) : NEW_LINE INDENT stack1 . append ( r ) NEW_LINE DEDENT else : NEW_LINE INDENT stack2 . append ( r ) NEW_LINE DEDENT n = n // 10 NEW_LINE DEDENT whi... |
Count of possible arrays from prefix | Function to find power of a number . ; Function to find factorial of a number . ; Function to print no of arrays ; c variable counts the no of pairs ; Map to store the frequency of each element ; Sum of all elements of the array ; Variable to check if it is possible to make any ar... | def power ( a , b ) : NEW_LINE INDENT result = 1 ; NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT result = result * a ; NEW_LINE DEDENT a = a * a ; NEW_LINE b = b // 2 ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def factorial ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in ran... |
Find two numbers with the given LCM and minimum possible difference | Python3 implementation of the approach ; Function to return the LCM of a and b ; Function to find and print the two numbers ; To find the factors ; To check if i is a factor of x and the minimum possible number satisfying the given conditions ; Drive... | from math import gcd as __gcd , sqrt , ceil NEW_LINE def lcm ( a , b ) : NEW_LINE INDENT return ( a // __gcd ( a , b ) * b ) NEW_LINE DEDENT def findNums ( x ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , ceil ( sqrt ( x ) ) ) : NEW_LINE INDENT if ( x % i == 0 and lcm ( i , x // i ) == x ) : NEW_LINE INDENT ... |
Find an integer that is common in the maximum number of given arithmetic progressions | Python implementation of the approach ; Function to return element common in maximum number of APs ; Initialize the count variable ; Increment count for every element of an AP ; Find the index with maximum count ; Return the maximum... | MAXN = 1000000 NEW_LINE def maxCommonElement ( A , D , N ) : NEW_LINE INDENT cnt = [ 0 ] * MAXN NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( A [ i ] , MAXN , D [ i ] ) : NEW_LINE INDENT cnt [ j ] += 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE com = 0 NEW_LINE for i in range ( MAXN ) : NEW_LINE INDENT ... |
Number of trailing zeros in N * ( N | Function to return the count of trailing 0 s in the given function ; If n is odd ; If n is even ; Find the trailing zeros in n / 2 factorial ; Return the required answer ; Driver code | def findTrailingZeros ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT ans = 0 NEW_LINE n //= 2 NEW_LINE while ( n ) : NEW_LINE INDENT ans += n // 5 NEW_LINE n //= 5 NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT n = 12 NEW_LINE print ( findTrailingZeros ( n ) ) ... |
Divide N into K unique parts such that gcd of those parts is maximum | Python3 implementation of the approach ; Function to calculate maximum GCD ; Minimum possible sum for K unique positive integers ; It is not possible to divide N into K unique parts ; All the factors greater than sqrt ( N ) are complementary of the ... | from math import sqrt , ceil , floor NEW_LINE def maxGCD ( N , K ) : NEW_LINE INDENT minSum = ( K * ( K + 1 ) ) / 2 NEW_LINE if ( N < minSum ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = ceil ( sqrt ( N ) ) NEW_LINE res = 1 NEW_LINE while ( i >= 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i >= m... |
Radius of the inscribed circle within three tangent circles | Python3 implementation of the approach ; Radius of the 3 given circles ; Calculation of area of a triangle by Heron 's formula ; Applying binary search to find the radius r4 of the required circle ; Area of main triangle ; Loop runs until l and h becomes app... | import math NEW_LINE r1 = 0 NEW_LINE r2 = 0 NEW_LINE r3 = 0 NEW_LINE def area ( a , b , c ) : NEW_LINE INDENT p = ( a + b + c ) / 2 NEW_LINE return ( ( math . sqrt ( p ) ) * ( math . sqrt ( p - a ) ) * ( math . sqrt ( p - b ) ) * ( math . sqrt ( p - c ) ) ) NEW_LINE DEDENT def binary_search ( ) : NEW_LINE INDENT global... |
Radius of the inscribed circle within three tangent circles | Python3 implementation of the approach ; Taking r1 , r2 , r3 as input ; Calculation of r4 using formula given above | from math import sqrt NEW_LINE r1 = 1 NEW_LINE r2 = 2 NEW_LINE r3 = 3 NEW_LINE r4 = ( r1 * r2 * r3 ) / ( r1 * r2 + r2 * r3 + r1 * r3 + 2.0 * sqrt ( r1 * r2 * r3 * ( r1 + r2 + r3 ) ) ) NEW_LINE print ( round ( r4 , 6 ) ) NEW_LINE |
Make all elements zero by decreasing any two elements by one at a time | Function that returns true if all the array elements can be made 0 with the given operation ; Find the maximum element and the sum ; Check the required condition ; Driver code | def checkZeroArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE maximum = - 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE maximum = max ( maximum , arr [ i ] ) NEW_LINE DEDENT if ( sum % 2 == 0 and maximum <= sum // 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return Fals... |
Subarray permutation that satisfies the given condition | Function that returns true if the required subarray exists in the given array ; Map to store the positions of each integer in the original permutation ; To store the address of each entry in arr [ n ] but with 1 - based indexing ; To track minimum position sumcu... | def subArray ( arr , n , m ) : NEW_LINE INDENT i = 0 NEW_LINE mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] = i + 1 NEW_LINE DEDENT sumcur = 0 NEW_LINE p = 10 ** 9 NEW_LINE ans = [ ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT sumcur += mp [ i ] NEW_LINE p = min ( p , mp [ i... |
Sum of all N digit palindrome numbers | Python program for the above approach ; Function to check palindrome ; Function to calculate the sum of n - digit palindrome ; Run a loop to check all possible palindrome ; If palindrome append sum ; Driver code | import math NEW_LINE def isPalindrome ( s ) : NEW_LINE INDENT left = 0 NEW_LINE right = len ( s ) - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT if ( s [ left ] != s [ right ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT left = left + 1 NEW_LINE right = right - 1 NEW_LINE DEDENT return True NEW_LINE DEDENT ... |
Sum of all N digit palindrome numbers | Function to calculate sum of n digit number ; Corner case ; Using above approach ; Driver code | def getSum ( n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT sum = 45.0 ; NEW_LINE DEDENT else : NEW_LINE INDENT sum = ( 99.0 / 2.0 ) * pow ( 10 , n - 1 ) * pow ( 10 , ( n - 1 ) / 2 ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LI... |
Count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | Function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Increment count if condition satisfy ; Return count of pairs ; Driver code ; Get and print count of pairs | def countPairs ( arr , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] * arr [ j ] == arr [ i ] + arr [ j ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _... |
Count number of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] | Function to return the count of pairs ( i , j ) such that arr [ i ] * arr [ j ] = arr [ i ] + arr [ j ] ; Count number of 0 ' s β and β 2' s in the array ; Total pairs due to occurrence of 0 's ; Total pairs due to occurrence of ... | def countPairs ( arr , n ) : NEW_LINE INDENT countZero = 0 ; NEW_LINE countTwo = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT countZero += 1 ; NEW_LINE DEDENT elif ( arr [ i ] == 2 ) : NEW_LINE INDENT countTwo += 1 ; NEW_LINE DEDENT DEDENT pair0 = ( countZero * ( countZero... |
Number of subsequences with positive product | Python 3 implementation of the approach ; Function to return the count of all the subsequences with positive product ; To store the count of positive elements in the array ; To store the count of negative elements in the array ; If the current element is positive ; If the ... | import math NEW_LINE def cntSubSeq ( arr , n ) : NEW_LINE INDENT pos_count = 0 ; NEW_LINE neg_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos_count += 1 NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT neg_count += 1 NEW_LINE DEDENT DEDENT result = int ( math .... |
Smallest number dividing minimum number of elements in the array | Set 2 | Function to return the smallest number that divides minimum number of elements in the given array ; m stores the maximum in the array ; Frequency array ; Sieve ; Incrementing j ; If no multiples of j are in the array ; Driver code | def findMin ( arr , n ) : NEW_LINE INDENT m = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m = max ( m , arr [ i ] ) NEW_LINE DEDENT freq = [ 0 ] * ( m + 2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 1 , m + 2 ) : NEW_LINE INDENT j = i NEW_LINE cnt = 0... |
Smallest number dividing minimum number of elements in the Array | Function to return the smallest number that divides minimum number of elements ; m stores the maximum in the array ; Frequency table ; Loop to factorize ; sqrt factorization of the numbers ; Finding the smallest number with zero multiples ; Driver code | def findMin ( arr , n ) : NEW_LINE INDENT m = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT m = max ( m , arr [ i ] ) NEW_LINE DEDENT cnt = [ 0 ] * ( m + 2 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 1 NEW_LINE while j * j <= arr [ i ] : NEW_LINE INDENT if ( arr [ i ] % j == 0 ) : NEW_LINE INDENT if ( j *... |
Remove two consecutive integers from 1 to N to make sum equal to S | Function to find the numbers to be removed ; typecast appropriately so that answer is float ; return the obtained result ; Convert i to integer ; If i is an integer is 0 then answer is Yes ; Driver code | def findNumber ( N , S ) : NEW_LINE INDENT i = ( ( ( N ) * ( N + 1 ) ) / 4 ) - ( ( S + 1 ) / 2 ) ; NEW_LINE return i ; NEW_LINE DEDENT def check ( N , S ) : NEW_LINE INDENT i = findNumber ( N , S ) ; NEW_LINE integerI = int ( i ) ; NEW_LINE if ( i - integerI == 0 ) : NEW_LINE INDENT print ( " Yes : " , integerI , " , "... |
Remove all the prime numbers from the given array | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to pr the elements of the array ; Function to remove all the prime numbers ; Generate primes ; Traverse the array ; If the current element is prime ; Shift all the elements on the r... | sz = 10 ** 5 NEW_LINE isPrime = [ True for i in range ( sz + 1 ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i < sz : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , sz , i ) : NEW_LINE INDENT isPrime [ j ] = False NE... |
Remove one element to get minimum OR value | Function to return the minimized OR after removing an element from the array ; Base case ; Prefix and suffix OR array ; Computing prefix / suffix OR arrays ; To store the final answer ; Finding the final answer ; Returning the final answer ; Driver code | def minOR ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT pre = [ 0 ] * n NEW_LINE suf = [ 0 ] * n NEW_LINE pre [ 0 ] = arr [ 0 ] NEW_LINE suf [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = ( pre [ i - 1 ] arr [ i ] ) NEW_LINE DEDENT for ... |
Check if there exists a prime number which gives Y after being repeatedly subtracted from X | Function that returns true if any prime number satisfies the given conditions ; No such prime exists ; Driver code | def isPossible ( x , y ) : NEW_LINE INDENT if ( ( x - y ) == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT x = 100 NEW_LINE y = 98 NEW_LINE if ( isPossible ( x , y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find number of square of area Z which can be built in a matrix having blocked regions | Python3 implementation of the approach ; Function to calculate the number of square areas of size K * K ; Row array and column array to store the lengths of differences between consecutive rows / columns ; Fill the conrow vector ; F... | from math import sqrt NEW_LINE def subgrids ( N , Z , row , col , r , d ) : NEW_LINE INDENT conrow = [ ] ; NEW_LINE concol = [ ] ; NEW_LINE K = int ( sqrt ( Z ) ) ; NEW_LINE conrow . append ( row [ 0 ] - 0 - 1 ) NEW_LINE conrow . append ( N + 1 - row [ r - 1 ] - 1 ) NEW_LINE for i in range ( 1 , r ) : NEW_LINE INDENT c... |
Count of numbers whose sum of increasing powers of digits is equal to the number itself | Function to return the count of digits of n ; Function to return the sum of increasing powers of N ; To store the required answer ; Count of digits in n which will be the power of the last digit ; While there are digits left ; Get... | def countDigits ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE n //= 10 NEW_LINE DEDENT return cnt NEW_LINE DEDENT def digitPowSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE pw = countDigits ( n ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 10 NEW_LINE sum += pow ( d ,... |
Print all perfect squares from the given range | Function to print all the perfect squares from the given range ; For every element from the range ; If current element is a perfect square ; Driver code | def perfectSquares ( l , r ) : NEW_LINE INDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( i ** ( .5 ) == int ( i ** ( .5 ) ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT l = 2 NEW_LINE r = 24 NEW_LINE perfectSquares ( l , r ) NEW_LINE |
Print all perfect squares from the given range | Python3 implementation of the approach ; Function to print all the perfect squares from the given range ; Getting the very first number ; First number 's square ; Next number is at the difference of ; While the perfect squares are from the range ; Print the perfect squar... | from math import ceil , sqrt NEW_LINE def perfectSquares ( l , r ) : NEW_LINE INDENT number = ceil ( sqrt ( l ) ) ; NEW_LINE n2 = number * number ; NEW_LINE number = ( number * 2 ) + 1 ; NEW_LINE while ( ( n2 >= l and n2 <= r ) ) : NEW_LINE INDENT print ( n2 , end = " β " ) ; NEW_LINE n2 = n2 + number ; NEW_LINE number... |
Find the value of N XOR 'ed to itself K times | Function to return n ^ n ^ ... k times ; Find the result ; Driver code | def xorK ( n , k ) : NEW_LINE INDENT res = n NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT res = ( res ^ n ) NEW_LINE DEDENT return n NEW_LINE DEDENT n = 123 NEW_LINE k = 3 NEW_LINE print ( xorK ( n , k ) ) NEW_LINE |
Find all the possible remainders when N is divided by all positive integers from 1 to N + 1 | Python3 implementation of the approach ; Function to find all the distinct remainders when n is divided by all the elements from the range [ 1 , n + 1 ] ; Set will be used to store the remainders in order to eliminate duplicat... | from math import ceil , floor , sqrt NEW_LINE def findRemainders ( n ) : NEW_LINE INDENT vc = dict ( ) NEW_LINE for i in range ( 1 , ceil ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT vc [ n // i ] = 1 NEW_LINE DEDENT for i in range ( n // ceil ( sqrt ( n ) ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT vc [ i ] = 1 NEW_LINE DEDENT fo... |
Count of primes below N which can be expressed as the sum of two primes | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to retur... | MAX = 100005 NEW_LINE prime = [ True for i in range ( MAX ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( MAX ) : NEW_LINE INDENT if ( p * p > MAX ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in... |
Print all palindrome dates between the given years | Python 3 implementation of the approach ; Returns true if given year is valid ; Return true if year is a multiple pf 4 and not multiple of 100. OR year is multiple of 400. ; Returns true if given year is valid or not . ; If year , month and day are not in given range... | MAX_VALID_YR = 9999 NEW_LINE MIN_VALID_YR = 1800 NEW_LINE def isLeap ( year ) : NEW_LINE INDENT return ( ( ( year % 4 == 0 ) and ( year % 100 != 0 ) ) or ( year % 400 == 0 ) ) NEW_LINE DEDENT def isValidDate ( d , m , y ) : NEW_LINE INDENT if ( y > MAX_VALID_YR or y < MIN_VALID_YR ) : NEW_LINE INDENT return False NEW_L... |
Find an integer in the given range that satisfies the given conditions | Python3 implementation of the approach ; Function that returns true if x contains all distinct digits ; Last digit of x ; If current digit has appeared before ; Mark the current digit to present ; Remove the last digit ; Function to return the req... | import sys NEW_LINE MAX = 10 NEW_LINE def distinctDigits ( x ) : NEW_LINE INDENT present = [ False for i in range ( MAX ) ] NEW_LINE while ( x > 0 ) : NEW_LINE INDENT digit = x % 10 NEW_LINE if ( present [ digit ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT present [ digit ] = True NEW_LINE x = x // 10 NEW_LINE DE... |
Convert Decimal To Hexa | Function to convert decimal no . to hexadecimal number ; map for decimal to hexa , 0 - 9 are straightforward , alphabets a - f used for 10 to 15. ; string to be returned ; check if num is 0 and directly return "0" ; if num > 0 , use normal technique as discussed in other post ; if num < 0 , we... | def Hex ( num ) : NEW_LINE INDENT m = dict . fromkeys ( range ( 16 ) , 0 ) ; NEW_LINE digit = ord ( '0' ) ; NEW_LINE c = ord ( ' a ' ) ; NEW_LINE for i in range ( 16 ) : NEW_LINE INDENT if ( i < 10 ) : NEW_LINE INDENT m [ i ] = chr ( digit ) ; NEW_LINE digit += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT m [ i ] = chr (... |
Find the player who will win the Coin game | Function to check the wining player ; As discussed in the above approach ; Driver Code | def findWinner ( n ) : NEW_LINE INDENT if ( ( n - 1 ) % 6 == 0 ) : NEW_LINE INDENT print ( " Second β Player β wins β the β game " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " First β Player β wins β the β game " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 ; NEW_LINE findW... |
Find ways to arrange K green balls among N balls such that exactly i moves is needed to collect all K green balls | Python3 implementation of the approach ; To store the factorial and the factorial mod inverse of a number ; Function to find ( a ^ m1 ) % mod ; Function to find factorial of all the numbers ; Function to ... | N = 100005 NEW_LINE mod = ( int ) ( 1e9 + 7 ) NEW_LINE factorial = [ 0 ] * N ; NEW_LINE modinverse = [ 0 ] * N ; NEW_LINE def power ( a , m1 ) : NEW_LINE INDENT if ( m1 == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( m1 == 1 ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT elif ( m1 == 2 ) : NEW_LINE INDENT re... |
Minimum inversions required so that no two adjacent elements are same | Function to return the minimum inversions required so that no two adjacent elements are same ; To store the inversions required to make the array { 1 , 0 , 1 , 0 , 1 , 0 , 1 , ... } and { 0 , 1 , 0 , 1 , 0 , 1 , 0 , ... } respectively ; Find all th... | def min_changes ( a , n ) : NEW_LINE INDENT ans_a = 0 ; NEW_LINE ans_b = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans_a += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans_b += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a [ i... |
Sum of all the numbers present at given level in Modified Pascal β s triangle | Function to calculate sum ; Driver Code | def ans ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( "1" , end = " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( "0" , end = " " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE ans ( n ) ; NEW_LINE DEDENT |
Find if there exists multiple ways to draw line through ( x , y ) to cut rectangle in equal halfs | Function that returns true if multiple lines are possible passing through ( x , y ) that divide the given rectangle into two equal parts ; If the point ( x , y ) is the centre of the rectangle ; Driver code | def isPossible ( w , h , x , y ) : NEW_LINE INDENT if ( x * 2 == w and y * 2 == h ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT w = 1 NEW_LINE h = 2 NEW_LINE x = 1 NEW_LINE y = 2 NEW_LINE if ( isPossible ( w , h , x , y ) ) : NEW_LINE INDE... |
Minimize the number by changing at most K digits | Function to return the minimized number ; Total digits in the number ; If the string is empty or there are no operations to perform ; "0" is a valid number ; If the first digit is not already 1 then update it to 1 and decrement k ; While there are operations left and t... | def minNum ( num , k ) : NEW_LINE INDENT len_ = len ( num ) NEW_LINE if len_ == 0 or k == 0 : NEW_LINE INDENT return num NEW_LINE DEDENT if len_ == 1 : NEW_LINE INDENT return "0" NEW_LINE DEDENT if num [ 0 ] != '1' : NEW_LINE INDENT num = '1' + num [ 1 : ] NEW_LINE k -= 1 NEW_LINE DEDENT i = 1 NEW_LINE while k > 0 and ... |
Form N by adding 1 or 2 in minimum number of operations X where X is divisible by M | Function to calculate the minimum number of steps required total steps taken is divisible by m and only 1 or 2 steps can be taken at a time ; If m > n ans is - 1 ; else discussed above approach ; Driver code | def minsteps ( n , m ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( ( n + 1 ) // 2 + m - 1 ) // m * m ; NEW_LINE DEDENT DEDENT n = 17 NEW_LINE m = 4 NEW_LINE ans = minsteps ( n , m ) NEW_LINE print ( ans ) NEW_LINE |
Compare numbers represented by Linked Lists | Structure for a linked list node ; A helper function to remove zeros from the start of the linked list ; A helper function to find the length of linked list ; Given a reference ( pointer to pointer ) to the head of a list and an int , push a new node on the front of the lis... | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def removeLeadingZeros ( a ) : NEW_LINE INDENT if ( a != None and a . data == 0 ) : NEW_LINE INDENT return removeLeadingZeros ( a . next ) ; NEW_LINE DEDENT else : NEW_LINE INDENT retu... |
Sum of the updated array after performing the given operation | Utility function to return the sum of the array ; Function to return the sum of the modified array ; Find the sum of the subarray arr [ i + 1. . . n - 1 ] ; Subtract the subarray sum ; Return the sum of the modified array ; Driver code | def sumArr ( 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 sumModArr ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT subSum = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT subSum +=... |
Find the minimum possible health of the winning player | Python3 implementation of the approach ; Function to return the minimum possible health of the last player ; Find the GCD of the array elements ; Driver code | from math import gcd NEW_LINE def minHealth ( health , n ) : NEW_LINE INDENT __gcd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT __gcd = gcd ( __gcd , health [ i ] ) ; NEW_LINE DEDENT return __gcd ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT health = [ 5 , 6 , 1 , 2 , 3 , 4 ] ; NEW_LINE n... |
Construct an array from its pair | Python3 implementation of the approach ; Utility function to print the array ; Function to generate the original array from the pair - product array ; First element of the resulting array ; Find all the other elements ; Print the elements of the generated array ; Driver code | from math import sqrt NEW_LINE def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT DEDENT def constructArr ( pair , n ) : NEW_LINE INDENT size = int ( ( 1 + sqrt ( 1 + 8 * n ) ) // 2 ) ; NEW_LINE arr = [ 0 ] * ( size ) ; NEW_LINE arr [ 0 ... |
Count of odd and even sum pairs in an array | Function to find the count of pairs with odd sum and the count of pairs with even sum ; To store the count of even and odd number from the array ; If the current element is even ; If it is odd ; To store the count of pairs with even sum ; All the even elements will make pai... | def findPairs ( arr , n ) : NEW_LINE INDENT cntEven = 0 ; cntOdd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT cntEven += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT cntOdd += 1 ; NEW_LINE DEDENT DEDENT evenPairs = 0 ; NEW_LINE evenPairs += ( ( cntEven * ( cntEven - 1 ... |
Number of ways to distribute N Paper Set among M students | Python3 implementation of the approach ; Function to return n ! % 1000000007 ; To store the factorial ; Find the factorial ; Function to return the count of possible ways ; Driver code | MOD = 1000000007 ; NEW_LINE def factMod ( n ) : NEW_LINE INDENT fact = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT fact *= ( i % MOD ) ; NEW_LINE fact %= MOD ; NEW_LINE DEDENT return fact ; NEW_LINE DEDENT def countWays ( n , m ) : NEW_LINE INDENT return factMod ( m ) ; NEW_LINE DEDENT if __name__ == " ... |
Program for nth Fuss β Catalan Number | Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth FussCatalan number in O ( n ) time ; Calculate ... | def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 ; NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) ; NEW_LINE res //= ( i + 1 ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def Fuss_catalan ( n ) : NEW_LINE INDENT c = binomialCoeff (... |
Check if a number is Euler Pseudoprime | Python3 program for nth FussCatalan Number ; Function that returns true if n is composite ; Check if there is any divisor of n . we only need check divisor till sqrt ( n ) because if there is divisor which is greater than sqrt ( n ) then there must be a divisor which is less tha... | from math import gcd , sqrt NEW_LINE def isComposite ( n ) : NEW_LINE INDENT for i in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT def Power ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NE... |
Minimum difference between any two primes from the given range | Python3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to return the minimum difference between any two prime numbers from the given range [ L , R ] ; Find the first prime from the range ; Find the second prime from the ran... | from math import sqrt NEW_LINE sz = int ( 1e5 ) ; NEW_LINE isPrime = [ True ] * ( sz + 1 ) ; NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False ; NEW_LINE for i in range ( 2 , int ( sqrt ( sz ) ) + 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , sz , i )... |
Number of non | Function to return the required count ; To store the final result ; Two pointer loop ; Initialising j ; Looping till the subarray increases ; Update ret ; Update i ; Return ret ; Driver code | def findCnt ( arr , n , k ) : NEW_LINE INDENT ret = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i + 1 ; NEW_LINE while ( j < n and arr [ j ] >= arr [ j - 1 ] ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT x = max ( 0 , j - i - k ) ; NEW_LINE ret += ( x * ( x + 1 ) ) / 2 ; NEW_LINE i = j ; NEW_LINE... |
Count of elements which are second smallest among three consecutive elements | Function to return the count of elements P [ i ] such that P [ i ] is the second smallest among P [ i 1 ] , P [ i ] and P [ i + 1 ] ; To store the required answer ; Traverse from the second element to the second last element ; Return the req... | def countElements ( p , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( p [ i - 1 ] > p [ i ] and p [ i ] > p [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT elif ( p [ i - 1 ] < p [ i ] and p [ i ] < p [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT... |
Count integers in the range [ A , B ] that are not divisible by C and D | Python3 implementation of the approach ; Function to return the count of integers from the range [ a , b ] that are not divisible by c and d ; Numbers which are divisible by c ; Numbers which are divisible by d ; Find lowest common factor of c an... | from math import gcd NEW_LINE def countNums ( a , b , c , d ) : NEW_LINE INDENT x = b // c - ( a - 1 ) // c ; NEW_LINE y = b // d - ( a - 1 ) // d ; NEW_LINE k = ( c * d ) // gcd ( c , d ) ; NEW_LINE z = b // k - ( a - 1 ) // k ; NEW_LINE return ( b - a + 1 - x - y + z ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.