diff --git "a/test.json" "b/test.json" new file mode 100644--- /dev/null +++ "b/test.json" @@ -0,0 +1,887 @@ +{"text":"Minimum sum possible by removing all occurrences of any array element | Function to find minimum sum after deletion ; Stores frequency of array elements ; Traverse the array ; Calculate sum ; Update frequency of the current element ; Stores the minimum sum required ; Traverse map ; Find the minimum sum obtained ; Return minimum sum ; Input array ; Size of array","code":"def minSum ( A , N ) : NEW_LINE INDENT mp = { } NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE if A [ i ] in mp : NEW_LINE INDENT mp [ A [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ A [ i ] ] = 1 NEW_LINE DEDENT DEDENT minSum = float ( ' inf ' ) NEW_LINE for it in mp : NEW_LINE INDENT minSum = min ( minSum , sum - ( it * mp [ it ] ) ) NEW_LINE DEDENT return minSum NEW_LINE DEDENT arr = [ 4 , 5 , 6 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minSum ( arr , N ) ) NEW_LINE"} +{"text":"Maximum difference between a pair of adjacent elements by excluding every element once | Function to calculate maximum difference between adjacent elements excluding every array element once ; Traverse the array ; Stores the maximum diff ; Check for maximum adjacent element ; Exclude current element ; pdate maximum difference ; Update previous value ; Append the result into a vector ; Print the result ; Driver Code","code":"def maxAdjacent ( arr , N ) : NEW_LINE INDENT res = [ ] NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT prev = arr [ 0 ] NEW_LINE maxi = - 1 * float ( ' inf ' ) NEW_LINE for j in range ( 1 , N ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT maxi = max ( maxi , abs ( arr [ j ] - prev ) ) NEW_LINE prev = arr [ j ] NEW_LINE DEDENT res . append ( maxi ) NEW_LINE DEDENT for x in res : NEW_LINE INDENT print ( x , end = ' \u2581 ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE maxAdjacent ( arr , N ) NEW_LINE"} +{"text":"Count 1 s present in a range of indices [ L , R ] in a given array | Function to find the size of the array if the array initially contains a single element ; Base case ; P \/ 2 -> findSize ( N 2 ) P % 2 -> 1 P \/ 2 -> findSize ( N \/ 2 ) ; Function to return the count of 1 s in the range [ L , R ] ; Base Case ; PART 1 -> N \/ 2 [ 1 , Siz_M ] ; Update the right end point of the range to min ( Siz_M , R ) ; PART 2 -> N % 2 [ SizM + 1 , Siz_M + 1 ] ; PART 3 -> N \/ 2 [ SizM + 2 , 2 * Siz_M - 1 ] Same as PART 1 Property of Symmetricity Shift the coordinates according to PART 1 Subtract ( Siz_M + 1 ) from both L , R ; Driver Code ; Input ; Counts the number of 1 's in the range [L, R]","code":"def findSize ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT Size = 2 * findSize ( N \/\/ 2 ) + 1 NEW_LINE return Size NEW_LINE DEDENT def CountOnes ( N , L , R ) : NEW_LINE INDENT if ( L > R ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N <= 1 ) : NEW_LINE INDENT return N NEW_LINE DEDENT ret = 0 NEW_LINE M = N \/\/ 2 NEW_LINE Siz_M = findSize ( M ) NEW_LINE if ( L <= Siz_M ) : NEW_LINE INDENT ret += CountOnes ( N \/\/ 2 , L , min ( Siz_M , R ) ) NEW_LINE DEDENT if ( L <= Siz_M + 1 and Siz_M + 1 <= R ) : NEW_LINE INDENT ret += N % 2 NEW_LINE DEDENT if ( Siz_M + 1 < R ) : NEW_LINE INDENT ret += CountOnes ( N \/\/ 2 , max ( 1 , L - Siz_M - 1 ) , R - Siz_M - 1 ) NEW_LINE DEDENT return ret NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 7 NEW_LINE L = 2 NEW_LINE R = 5 NEW_LINE print ( CountOnes ( N , L , R ) ) NEW_LINE DEDENT"} +{"text":"Find the pair ( a , b ) with minimum LCM such that their sum is equal to N | Function to check if number is prime or not ; As 1 is neither prime nor composite return false ; Check if it is divided by any number then it is not prime , return false ; Check if n is not divided by any number then it is prime and hence return true ; Function to find the pair ( a , b ) such that sum is N & LCM is minimum ; Check if the number is prime ; Now , if it is not prime then find the least divisior ; Check if divides n then it is a factor ; Required output is a = n \/ i & b = n \/ i * ( n - 1 ) ; Driver Code ; Function call","code":"def prime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : 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 minDivisior ( n ) : NEW_LINE INDENT if ( prime ( n ) ) : NEW_LINE INDENT print ( 1 , n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if i * i > n : NEW_LINE INDENT break NEW_LINE DEDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( n \/\/ i , n \/\/ i * ( i - 1 ) ) NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT N = 4 NEW_LINE minDivisior ( N ) NEW_LINE"} +{"text":"Find Landau 's function for a given number N | Python3 program for the above approach ; To store Landau 's function of the number ; Function to return gcd of 2 numbers ; Function to return LCM of two numbers ; Function to find max lcm value among all representations of n ; Calculate Landau 's value ; Recursive function to find different ways in which n can be written as sum of atleast one positive integers ; Check if sum becomes n , consider this representation ; Start from previous element in the representation till n ; Include current element from representation ; Call function again with reduced sum ; Backtrack - remove current element from representation ; Function to find the Landau 's function ; Using recurrence find different ways in which n can be written as a sum of atleast one + ve integers ; Print the result ; Given N ; Function call","code":"import sys NEW_LINE Landau = - sys . maxsize - 1 NEW_LINE 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 lcm ( a , b ) : NEW_LINE INDENT return ( a * b ) \/\/ gcd ( a , b ) NEW_LINE DEDENT def findLCM ( arr ) : NEW_LINE INDENT global Landau NEW_LINE nth_lcm = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT nth_lcm = lcm ( nth_lcm , arr [ i ] ) NEW_LINE DEDENT Landau = max ( Landau , nth_lcm ) NEW_LINE DEDENT def findWays ( arr , i , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT findLCM ( arr ) NEW_LINE DEDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT arr . append ( j ) NEW_LINE findWays ( arr , j , n - j ) NEW_LINE arr . pop ( ) NEW_LINE DEDENT DEDENT def Landau_function ( n ) : NEW_LINE INDENT arr = [ ] NEW_LINE findWays ( arr , 1 , n ) NEW_LINE print ( Landau ) NEW_LINE DEDENT N = 4 NEW_LINE Landau_function ( N ) NEW_LINE"} +{"text":"Check if the remainder of N | Function to check if a number holds the condition ( N - 1 ) ! % N = N - 1 ; Corner cases ; Number divisible by 2 or 3 are not prime ; Iterate from 5 and keep checking for prime ; Function to check the expression for the value N ; Driver code","code":"def isPrime ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( ( n % 2 == 0 ) or ( n % 3 == 0 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( ( n % i == 0 ) or ( n % ( i + 2 ) == 0 ) ) : NEW_LINE INDENT return False ; NEW_LINE i += 6 NEW_LINE DEDENT DEDENT return true ; NEW_LINE DEDENT def checkExpression ( n ) : NEW_LINE INDENT if ( isPrime ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE checkExpression ( N ) NEW_LINE DEDENT"} +{"text":"Check if it is possible to split given Array into K odd | Function to check if array can be split in required K subsets ; Store count of odd numbers ; Check if element is odd ; Check if split is possible ; Driver Code","code":"def checkArray ( n , k , arr ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt >= k and cnt % 2 == k % 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 7 , 5 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE if ( checkArray ( n , k , arr ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Sum of division of the possible pairs for the given Array | Python3 program to compute the sum of division of all the possible pairs for the given array ; Function to compute the sum ; Counting frequency of each term and finding maximum among it ; Making cumulative frequency ; Taking the ceil value ; nos . in [ ( n - 0.5 ) X , ( n + 0.5 ) X ) range will add n to the ans ; Return the final result ; Driver code","code":"from math import * NEW_LINE def func ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE maxx = 0 NEW_LINE freq = [ 0 ] * 100005 NEW_LINE temp = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE freq [ temp ] += 1 NEW_LINE maxx = max ( maxx , temp ) NEW_LINE DEDENT for i in range ( 1 , maxx + 1 ) : NEW_LINE INDENT freq [ i ] += freq [ i - 1 ] NEW_LINE DEDENT for i in range ( 1 , maxx + 1 ) : NEW_LINE INDENT if ( freq [ i ] ) : NEW_LINE INDENT value = 0 NEW_LINE cur = ceil ( 0.5 * i ) - 1.0 NEW_LINE j = 1.5 NEW_LINE while ( 1 ) : NEW_LINE INDENT val = min ( maxx , ( ceil ( i * j ) - 1.0 ) ) NEW_LINE times = ( freq [ i ] - freq [ i - 1 ] ) NEW_LINE con = j - 0.5 NEW_LINE ans += times * con * ( freq [ int ( val ) ] - freq [ int ( cur ) ] ) NEW_LINE cur = val NEW_LINE if ( val == maxx ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return int ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( func ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Count of elements to be inserted to make Array sum twice the XOR of Array | Function to find the minimum number of elements that need to be inserted such that the sum of the elements of the array is twice the XOR of the array ; Variable to store the Xor of all the elements ; Variable to store the sum of all elements ; Loop to find the Xor and the sum of the array ; If sum = 2 * Xor ; No need to insert more elements ; We insert one more element which is Sum ; We insert two more elements Sum + Xor and Xor . ; Print the number of elements inserted in the array ; Print the elements that are inserted in the array ; Driver code","code":"def insert_element ( a , n ) : NEW_LINE INDENT Xor = 0 NEW_LINE Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Xor ^= a [ i ] NEW_LINE Sum += a [ i ] NEW_LINE DEDENT if ( Sum == 2 * Xor ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT if ( Xor == 0 ) : NEW_LINE INDENT print ( 1 ) NEW_LINE print ( Sum ) NEW_LINE return NEW_LINE DEDENT num1 = Sum + Xor NEW_LINE num2 = Xor NEW_LINE print ( 2 ) NEW_LINE print ( num1 , num2 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE insert_element ( a , n ) NEW_LINE DEDENT"} +{"text":"Check if roots of a Quadratic Equation are reciprocal of each other or not | Function to check if the roots of a quadratic equation are reciprocal of each other or not ; Driver code","code":"def checkSolution ( a , b , c ) : NEW_LINE INDENT if ( a == c ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT DEDENT a = 2 ; b = 0 ; c = 2 ; NEW_LINE checkSolution ( a , b , c ) ; NEW_LINE"} +{"text":"Sunny Number | Python3 program for the above approach ; Function check whether x is a perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to check Sunny Number ; Check if ( N + 1 ) is a perfect square or not ; If ( N + 1 ) is not a perfect square ; Driver Code ; Given Number ; Function call","code":"from math import * NEW_LINE def isPerfectSquare ( x ) : NEW_LINE INDENT sr = sqrt ( x ) NEW_LINE return ( ( sr - floor ( sr ) ) == 0 ) NEW_LINE DEDENT def checkSunnyNumber ( N ) : NEW_LINE INDENT if ( isPerfectSquare ( N + 1 ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE checkSunnyNumber ( N ) NEW_LINE DEDENT"} +{"text":"Count the numbers which can convert N to 1 using given operation | Function to count the numbers which can convert N to 1 using the given operation ; Iterate through all the integers ; Check if N can be converted to 1 ; Incrementing the count if it can be converted ; Driver code","code":"def countValues ( n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT k = n NEW_LINE while ( k >= i ) : NEW_LINE INDENT if ( k % i == 0 ) : NEW_LINE INDENT k \/\/= i NEW_LINE DEDENT else : NEW_LINE INDENT k -= i NEW_LINE DEDENT DEDENT if ( k == 1 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE print ( countValues ( N ) ) NEW_LINE DEDENT"} +{"text":"Find K numbers with sum equal to N and sum of their squares maximized | Function that prints the required K numbers ; Print 1 , K - 1 times ; Print ( N - K + 1 ) ; Driver code","code":"def printKNumbers ( N , K ) : NEW_LINE INDENT for i in range ( K - 1 ) : NEW_LINE INDENT print ( 1 , end = ' \u2581 ' ) NEW_LINE DEDENT print ( N - K + 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ( N , K ) = ( 10 , 3 ) NEW_LINE printKNumbers ( N , K ) NEW_LINE DEDENT"} +{"text":"Print Nth Stepping or Autobiographical number | Function to find the Nth stepping natural number ; Declare the queue ; Enqueue 1 , 2 , ... , 9 in this order ; Perform K operation on queue ; Get the ith Stepping number ; Perform Dequeue from the Queue ; If x mod 10 is not equal to 0 ; then Enqueue 10 x + ( x mod 10 ) - 1 ; Enqueue 10 x + ( x mod 10 ) ; If x mod 10 is not equal to 9 ; then Enqueue 10 x + ( x mod 10 ) + 1 ; Return the dequeued number of the K - th operation as the Nth stepping number ; Driver Code ; initialise K","code":"def NthSmallest ( K ) : NEW_LINE INDENT Q = [ ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT Q . append ( i ) NEW_LINE DEDENT for i in range ( 1 , K + 1 ) : NEW_LINE INDENT x = Q [ 0 ] NEW_LINE Q . remove ( Q [ 0 ] ) NEW_LINE if ( x % 10 != 0 ) : NEW_LINE INDENT Q . append ( x * 10 + x % 10 - 1 ) NEW_LINE DEDENT Q . append ( x * 10 + x % 10 ) NEW_LINE if ( x % 10 != 9 ) : NEW_LINE INDENT Q . append ( x * 10 + x % 10 + 1 ) NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 16 NEW_LINE print ( NthSmallest ( N ) ) NEW_LINE DEDENT"} +{"text":"Least number to be added to or subtracted from N to make it a Perfect Square | Python3 implementation of the approach ; Function to return the Least number ; Get the perfect square before and after N ; Check which is nearest to N ; return the result ; Driver code","code":"from math import sqrt NEW_LINE def nearest ( n ) : NEW_LINE INDENT prevSquare = int ( sqrt ( n ) ) ; NEW_LINE nextSquare = prevSquare + 1 ; NEW_LINE prevSquare = prevSquare * prevSquare ; NEW_LINE nextSquare = nextSquare * nextSquare ; NEW_LINE ans = ( prevSquare - n ) if ( n - prevSquare ) < ( nextSquare - n ) else ( nextSquare - n ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 14 ; NEW_LINE print ( nearest ( n ) ) ; NEW_LINE n = 16 ; NEW_LINE print ( nearest ( n ) ) ; NEW_LINE n = 18 ; NEW_LINE print ( nearest ( n ) ) ; NEW_LINE DEDENT"} +{"text":"Value of Pi ( \u00ce ) up to 50 decimal places | Python3 program to calculate the value of pi up to n decimal places ; Function that prints the value of pi upto N decimal places ; Find value of pi upto using acos ( ) function ; Print value of pi upto N decimal places ; Driver Code ; Function that prints the value of pi","code":"from math import acos NEW_LINE def printValueOfPi ( N ) : NEW_LINE INDENT b = ' { : . ' + str ( N ) + ' f } ' NEW_LINE pi = b . format ( 2 * acos ( 0.0 ) ) NEW_LINE print ( pi ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 43 ; NEW_LINE printValueOfPi ( N ) ; NEW_LINE DEDENT"} +{"text":"Invert the Kth most significant bit of N | Python implementation of the approach ; Function to convert decimal number n to its binary representation stored as an array arr [ ] ; Function to convert the number represented as a binary array arr [ ] its decimal equivalent ; Function to concatenate the binary numbers and return the decimal result ; Number of bits in both the numbers ; Convert the bits in both the gers to the arrays a [ ] and b [ ] ; The number of bits in n are less than k ; Flip the kth bit ; Return the decimal equivalent of the number ; Driver code","code":"import math NEW_LINE def decBinary ( arr , n ) : NEW_LINE INDENT k = int ( math . log2 ( n ) ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT arr [ k ] = n % 2 NEW_LINE k = k - 1 NEW_LINE n = n \/\/ 2 NEW_LINE DEDENT DEDENT def binaryDec ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ans = ans + ( arr [ i ] << ( n - i - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getNum ( n , k ) : NEW_LINE INDENT l = int ( math . log2 ( n ) ) + 1 NEW_LINE a = [ 0 for i in range ( 0 , l ) ] NEW_LINE decBinary ( a , n ) NEW_LINE if ( k > l ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( a [ k - 1 ] == 0 ) : NEW_LINE INDENT a [ k - 1 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ k - 1 ] = 0 NEW_LINE DEDENT return binaryDec ( a , l ) NEW_LINE DEDENT n = 56 NEW_LINE k = 2 NEW_LINE print ( getNum ( n , k ) ) NEW_LINE"} +{"text":"Queries for the product of first N factorials | Python3 implementation of the approach ; Declare result array globally ; Function to precompute the product of factorials upto MAX ; Initialize base condition if n = 0 then factorial of 0 is equal to 1 and answer for n = 0 is 1 ; Iterate loop from 1 to MAX ; factorial ( i ) = factorial ( i - 1 ) * i ; Result for current n is equal to result [ i - 1 ] multiplied by the factorial of i ; Function to perform the queries ; Precomputing the result tiMAX ; Perform queries ; Driver code","code":"MAX = 1000000 NEW_LINE MOD = 10 ** 9 + 7 NEW_LINE result = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE fact = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE def preCompute ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE result [ 0 ] = 1 NEW_LINE for i in range ( 1 , MAX + 1 ) : NEW_LINE INDENT fact [ i ] = ( ( fact [ i - 1 ] % MOD ) * i ) % MOD NEW_LINE result [ i ] = ( ( result [ i - 1 ] % MOD ) * ( fact [ i ] % MOD ) ) % MOD NEW_LINE DEDENT DEDENT def performQueries ( q , n ) : NEW_LINE INDENT preCompute ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( result [ q [ i ] ] ) NEW_LINE DEDENT DEDENT q = [ 4 , 5 ] NEW_LINE n = len ( q ) NEW_LINE performQueries ( q , n ) NEW_LINE"} +{"text":"Nth number in a set of multiples of A , B or C | Python3 program to find nth term divisible by a , b or c ; Function to return gcd of a and b ; Function to return the count of integers from the range [ 1 , num ] which are divisible by either a , b or c ; Calculate the number of terms divisible by a , b and c then remove the terms which are divisible by both ( a , b ) or ( b , c ) or ( c , a ) and then add the numbers which are divisible by a , b and c ; Function for binary search to find the nth term divisible by a , b or c ; Set low to 1 and high to LONG_MAX ; If the current term is less than n then we need to increase low to mid + 1 ; If current term is greater than equal to n then high = mid ; Driver code","code":"import sys NEW_LINE 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 divTermCount ( a , b , c , num ) : NEW_LINE INDENT return ( ( num \/ a ) + ( num \/ b ) + ( num \/ c ) - ( num \/ ( ( a * b ) \/ gcd ( a , b ) ) ) - ( num \/ ( ( c * b ) \/ gcd ( c , b ) ) ) - ( num \/ ( ( a * c ) \/ gcd ( a , c ) ) ) + ( num \/ ( ( a * b * c ) \/ gcd ( gcd ( a , b ) , c ) ) ) ) ; NEW_LINE DEDENT def findNthTerm ( a , b , c , n ) : NEW_LINE INDENT low = 1 ; high = sys . maxsize ; mid = 0 ; NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low ) \/ 2 ; NEW_LINE if ( divTermCount ( a , b , c , mid ) < n ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid ; NEW_LINE DEDENT DEDENT return int ( low ) ; NEW_LINE DEDENT a = 2 ; b = 3 ; c = 5 ; n = 100 ; NEW_LINE print ( findNthTerm ( a , b , c , n ) ) ; NEW_LINE"} +{"text":"Angle between 3 given vertices in a n | Function that checks whether given angle can be created using any 3 sides ; Initialize x and y ; Calculate the number of vertices between i and j , j and k ; Calculate the angle subtended at the circumference ; Angle subtended at j can be found using the fact that the sum of angles of a triangle is equal to 180 degrees ; Driver code","code":"def calculate_angle ( n , i , j , k ) : NEW_LINE INDENT x , y = 0 , 0 NEW_LINE if ( i < j ) : NEW_LINE INDENT x = j - i NEW_LINE DEDENT else : NEW_LINE INDENT x = j + n - i NEW_LINE DEDENT if ( j < k ) : NEW_LINE INDENT y = k - j NEW_LINE DEDENT else : NEW_LINE INDENT y = k + n - j NEW_LINE DEDENT ang1 = ( 180 * x ) \/\/ n NEW_LINE ang2 = ( 180 * y ) \/\/ n NEW_LINE ans = 180 - ang1 - ang2 NEW_LINE return ans NEW_LINE DEDENT n = 5 NEW_LINE a1 = 1 NEW_LINE a2 = 2 NEW_LINE a3 = 5 NEW_LINE print ( calculate_angle ( n , a1 , a2 , a3 ) ) NEW_LINE"} +{"text":"Loss when two items are sold at same price and same percentage profit \/ loss | Function that will find loss ; Driver Code ; Calling Function","code":"def Loss ( SP , P ) : NEW_LINE INDENT loss = 0 NEW_LINE loss = ( ( 2 * P * P * SP ) \/ ( 100 * 100 - P * P ) ) NEW_LINE print ( \" Loss \u2581 = \" , round ( loss , 3 ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT SP , P = 2400 , 30 NEW_LINE Loss ( SP , P ) NEW_LINE DEDENT"} +{"text":"Check for an array element that is co | Python3 implementation of the approach ; Stores smallest prime factor for every number ; Hash to store prime factors count ; Function to calculate SPF ( SmallestPrime Factor ) for every number till MAXN ; Separately marking spf for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Marking spf [ j ] if it is not previously marked ; Function to store the prime factors after dividing by the smallest prime factor at every step ; Storing the count of prime factors in hash ; Function that returns true if there are no common prime factors between x and other numbers of the array ; Checking whether it common prime factor with other numbers ; Function that returns true if there is an element in the array which is coprime with all the other elements of the array ; Using sieve for generating prime factors ; Checking the common prime factors with other numbers ; Driver code","code":"MAXN = 1000001 NEW_LINE spf = [ i for i in range ( MAXN ) ] NEW_LINE hash1 = [ 0 for i in range ( MAXN ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , MAXN ) : NEW_LINE INDENT if i * i >= MAXN : NEW_LINE INDENT break NEW_LINE DEDENT if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def getFactorization ( x ) : NEW_LINE INDENT while ( x != 1 ) : NEW_LINE INDENT temp = spf [ x ] NEW_LINE if ( x % temp == 0 ) : NEW_LINE INDENT hash1 [ spf [ x ] ] += 1 NEW_LINE x = x \/\/ spf [ x ] NEW_LINE DEDENT while ( x % temp == 0 ) : NEW_LINE INDENT x = x \/\/ temp NEW_LINE DEDENT DEDENT DEDENT def check ( x ) : NEW_LINE INDENT while ( x != 1 ) : NEW_LINE INDENT temp = spf [ x ] NEW_LINE if ( x % temp == 0 and hash1 [ temp ] > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( x % temp == 0 ) : NEW_LINE INDENT x = x \/\/ temp NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def hasValidNum ( arr , n ) : NEW_LINE INDENT sieve ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT getFactorization ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( check ( arr [ i ] ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 2 , 8 , 4 , 10 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE if ( hasValidNum ( arr , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Ways to Remove Edges from a Complete Graph to make Odd Edges | Function to return the number of ways to remove edges from the graph so that odd number of edges are left in the graph ; Total number of edges ; Driver code","code":"def countWays ( N ) : NEW_LINE INDENT E = ( N * ( N - 1 ) ) \/ 2 NEW_LINE if ( N == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return int ( pow ( 2 , E - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( countWays ( N ) ) NEW_LINE DEDENT"} +{"text":"Calculate nCr using Pascal 's Triangle | Initialize the matrix with 0 ; 0 C0 = 1 ; Set every nCr = 1 where r = 0 ; Value for the current cell of Pascal 's triangle ; Function to return the value of nCr ; Return nCr ; Build the Pascal 's triangle","code":"l = [ [ 0 for i in range ( 1001 ) ] for j in range ( 1001 ) ] NEW_LINE def initialize ( ) : NEW_LINE INDENT l [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , 1001 ) : NEW_LINE INDENT l [ i ] [ 0 ] = 1 NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT l [ i ] [ j ] = ( l [ i - 1 ] [ j - 1 ] + l [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT def nCr ( n , r ) : NEW_LINE INDENT return l [ n ] [ r ] NEW_LINE DEDENT initialize ( ) NEW_LINE n = 8 NEW_LINE r = 3 NEW_LINE print ( nCr ( n , r ) ) NEW_LINE"} +{"text":"Closest sum partition ( into two subsets ) of numbers from 1 to n | Function to return the minimum required absolute difference ; Driver code","code":"def minAbsDiff ( n ) : NEW_LINE INDENT mod = n % 4 ; NEW_LINE if ( mod == 0 or mod == 3 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT return 1 ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 5 ; NEW_LINE print ( minAbsDiff ( n ) ) NEW_LINE DEDENT"} +{"text":"Check if the Xor of the frequency of all digits of a number N is zero or not | Python implementation of the above approach ; creating a frequency array ; Finding the last digit of the number ; Dividing the number by 10 to eliminate last digit ; counting frequency of each digit ; checking if the xor of all frequency is zero or not ; Driver code","code":"def check ( s ) : NEW_LINE INDENT freq = [ 0 ] * 10 NEW_LINE while ( s != 0 ) : NEW_LINE INDENT r = s % 10 NEW_LINE s = s \/\/ 10 NEW_LINE freq [ r ] += 1 NEW_LINE DEDENT xor = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT xor = xor ^ freq [ i ] NEW_LINE DEDENT if ( xor == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT s = 122233 NEW_LINE if ( check ( s ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Print N lines of 4 numbers such that every pair among 4 numbers has a GCD K | Function to print N lines ; Iterate N times to print N lines ; Driver code","code":"def printLines ( n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( k * ( 6 * i + 1 ) , k * ( 6 * i + 2 ) , k * ( 6 * i + 3 ) , k * ( 6 * i + 5 ) ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n , k = 2 , 2 NEW_LINE printLines ( n , k ) NEW_LINE DEDENT"} +{"text":"Sum of first n term of Series 3 , 5 , 9 , 17 , 33. ... | Python program to find sum of n terms of the series ; Sn = n * ( 4 * n * n + 6 * n - 1 ) \/ 3 ; number of terms for the sum ; find the Sn","code":"def calculateSum ( n ) : NEW_LINE INDENT return ( 2 ** ( n + 1 ) + n - 2 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( \" Sum \u2581 = \" , calculateSum ( n ) ) NEW_LINE"} +{"text":"Count the number of Special Strings of a given length N | Python3 program to count the number of special strings of a given length N ; Function to return count of special strings ; Stores the answer for a particular value of n ; For n = 0 we have empty string ; For n = 1 we have 2 special strings ; Calculate count of special string of length i ; fib [ n ] stores the count of special strings of length n ; Driver code ; Initialise n","code":"mod = 1000000007 NEW_LINE def count_special ( n ) : NEW_LINE INDENT fib = [ 0 for i in range ( n + 1 ) ] NEW_LINE fib [ 0 ] = 1 NEW_LINE fib [ 1 ] = 2 NEW_LINE for i in range ( 2 , n + 1 , 1 ) : NEW_LINE INDENT fib [ i ] = ( fib [ i - 1 ] % mod + fib [ i - 2 ] % mod ) % mod NEW_LINE DEDENT return fib [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE print ( count_special ( n ) ) NEW_LINE DEDENT"} +{"text":"Counts Path in an Array | Python3 implementation of the above approach ; Find the number of ways to reach the end ; Base case ; Recursive structure ; Driver code","code":"mod = 1e9 + 7 ; NEW_LINE def ways ( i , arr , n ) : NEW_LINE INDENT if ( i == n - 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT sum = 0 ; NEW_LINE for j in range ( 1 , arr [ i ] + 1 ) : NEW_LINE INDENT if ( i + j < n ) : NEW_LINE INDENT sum += ( ways ( i + j , arr , n ) ) % mod ; NEW_LINE sum %= mod ; NEW_LINE DEDENT DEDENT return int ( sum % mod ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 3 , 1 , 4 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( ways ( 0 , arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Counts Path in an Array | Python3 implementation of above approach ; find the number of ways to reach the end ; dp to store value ; base case ; Bottom up dp structure ; F [ i ] is dependent of F [ i + 1 ] to F [ i + k ] ; Return value of dp [ 0 ] ; Driver code","code":"mod = 10 ** 9 + 7 NEW_LINE def ways ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ n - 1 ] = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT dp [ i ] = 0 NEW_LINE j = 1 NEW_LINE while ( ( j + i ) < n and j <= arr [ i ] ) : NEW_LINE INDENT dp [ i ] += dp [ i + j ] NEW_LINE dp [ i ] %= mod NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return dp [ 0 ] % mod NEW_LINE DEDENT arr = [ 5 , 3 , 1 , 4 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( ways ( arr , n ) % mod ) NEW_LINE"} +{"text":"Number of Subsequences with Even and Odd Sum | Returns the count of odd and even subsequences ; Initialising count_even and count_odd to 0 since as there is no subsequence before the iteration with even or odd count . ; Find sum of all subsequences with even count and odd count and storing them as we iterate . ; if the number is even ; if the number is odd ; Driver code ; Calling the function","code":"def countSum ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE count_odd = 0 NEW_LINE count_even = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] % 2 == 0 ) : NEW_LINE INDENT count_even = count_even + count_even + 1 NEW_LINE count_odd = count_odd + count_odd NEW_LINE DEDENT else : NEW_LINE INDENT temp = count_even NEW_LINE count_even = count_even + count_odd NEW_LINE count_odd = count_odd + temp + 1 NEW_LINE DEDENT DEDENT return ( count_even , count_odd ) NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 3 ] ; NEW_LINE n = len ( arr ) NEW_LINE count_even , count_odd = countSum ( arr , n ) ; NEW_LINE print ( \" EvenSum \u2581 = \u2581 \" , count_even , \" \u2581 OddSum \u2581 = \u2581 \" , count_odd ) NEW_LINE"} +{"text":"Count of integers of length N and value less than K such that they contain digits only from the given set | Python3 implementation of the approach ; Function to convert a number into vector ; Push all the digits of N from the end one by one to the vector ; If the original number was 0 ; Reverse the vector elements ; Return the required vector ; Function to return the count of B length integers which are less than C and they contain digits from set A [ ] only ; Convert number to digit array ; Case 1 : No such number possible as the generated numbers will always be greater than C ; Case 2 : All integers of length B are valid as they all are less than C ; contain 0 ; Case 3 ; Update the lower [ ] array such that lower [ i ] stores the count of elements in A [ ] which are less than i ; For first index we can 't use 0 ; Whether ( i - 1 ) digit of generated number can be equal to ( i - 1 ) digit of C ; Is digit [ i - 1 ] present in A ? ; Driver code","code":"MAX = 10 NEW_LINE def numToVec ( N ) : NEW_LINE INDENT digit = [ ] NEW_LINE while ( N != 0 ) : NEW_LINE INDENT digit . append ( N % 10 ) NEW_LINE N = N \/\/ 10 NEW_LINE DEDENT if ( len ( digit ) == 0 ) : NEW_LINE INDENT digit . append ( 0 ) NEW_LINE DEDENT digit = digit [ : : - 1 ] NEW_LINE return digit NEW_LINE DEDENT def solve ( A , B , C ) : NEW_LINE INDENT d , d2 = 0 , 0 NEW_LINE digit = numToVec ( C ) NEW_LINE d = len ( A ) NEW_LINE if ( B > len ( digit ) or d == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( B < len ( digit ) ) : NEW_LINE INDENT if ( A [ 0 ] == 0 and B != 1 ) : NEW_LINE INDENT return ( d - 1 ) * pow ( d , B - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return pow ( d , B ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp = [ 0 for i in range ( B + 1 ) ] NEW_LINE lower = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( d ) : NEW_LINE INDENT lower [ A [ i ] + 1 ] = 1 NEW_LINE DEDENT for i in range ( 1 , MAX + 1 ) : NEW_LINE INDENT lower [ i ] = lower [ i - 1 ] + lower [ i ] NEW_LINE DEDENT flag = True NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , B + 1 ) : NEW_LINE INDENT d2 = lower [ digit [ i - 1 ] ] NEW_LINE dp [ i ] = dp [ i - 1 ] * d NEW_LINE if ( i == 1 and A [ 0 ] == 0 and B != 1 ) : NEW_LINE INDENT d2 = d2 - 1 NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT dp [ i ] += d2 NEW_LINE DEDENT flag = ( flag & ( lower [ digit [ i - 1 ] + 1 ] == lower [ digit [ i - 1 ] ] + 1 ) ) NEW_LINE DEDENT return dp [ B ] NEW_LINE DEDENT DEDENT A = [ 0 , 1 , 2 , 5 ] NEW_LINE N = 2 NEW_LINE k = 21 NEW_LINE print ( solve ( A , N , k ) ) NEW_LINE"} +{"text":"Number of Paths of Weight W in a K | Python 3 program to count the number of paths with weight W in a K - ary tree ; Function to return the number of ways having weight as wt in K - ary tree ; Return 0 if weight becomes less than zero ; Return one only if the current path has included edge weight of atleast M ; If the current edge weight is greater than or equal to M , set used as true ; Driver Code","code":"import numpy as np NEW_LINE def solve ( dp , wt , K , M , used ) : NEW_LINE INDENT if ( wt < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( wt == 0 ) : NEW_LINE INDENT if ( used ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ wt ] [ used ] != - 1 ) : NEW_LINE INDENT return dp [ wt ] [ used ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE INDENT if ( i >= M ) : NEW_LINE INDENT ans += solve ( dp , wt - i , K , M , used 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += solve ( dp , wt - i , K , M , used ) NEW_LINE DEDENT DEDENT dp [ wt ] [ used ] = ans NEW_LINE return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT W = 3 NEW_LINE K = 3 NEW_LINE M = 2 NEW_LINE dp = np . ones ( ( W + 1 , 2 ) ) ; NEW_LINE dp = - 1 * dp NEW_LINE print ( solve ( dp , W , K , M , 0 ) ) NEW_LINE DEDENT"} +{"text":"Ways to write N as sum of two or more positive integers | Set | Function to find the number of partitions of N ; Base case ; Driver code","code":"def partitions ( n ) : NEW_LINE INDENT p = [ 0 ] * ( n + 1 ) NEW_LINE p [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT k = 1 NEW_LINE while ( ( k * ( 3 * k - 1 ) ) \/ 2 <= i ) : NEW_LINE INDENT p [ i ] += ( ( 1 if k % 2 else - 1 ) * p [ i - ( k * ( 3 * k - 1 ) ) \/\/ 2 ] ) NEW_LINE if ( k > 0 ) : NEW_LINE INDENT k *= - 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = 1 - k NEW_LINE DEDENT DEDENT DEDENT return p [ n ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 20 NEW_LINE print ( partitions ( N ) ) NEW_LINE DEDENT"} +{"text":"Longest Increasing Path in Matrix | Python3 program to find longest increasing path in a matrix . ; Return the length of LIP in 2D matrix ; If value not calculated yet . ; If reach bottom left cell , return 1. ; If reach the corner of the matrix . ; If value greater than below cell . ; If value greater than left cell . ; Wrapper function ; Driver Code","code":"MAX = 20 NEW_LINE def LIP ( dp , mat , n , m , x , y ) : NEW_LINE INDENT if ( dp [ x ] [ y ] < 0 ) : NEW_LINE INDENT result = 0 NEW_LINE if ( x == n - 1 and y == m - 1 ) : NEW_LINE INDENT dp [ x ] [ y ] = 1 NEW_LINE return dp [ x ] [ y ] NEW_LINE DEDENT if ( x == n - 1 or y == m - 1 ) : NEW_LINE INDENT result = 1 NEW_LINE DEDENT if ( x + 1 < n and mat [ x ] [ y ] < mat [ x + 1 ] [ y ] ) : NEW_LINE INDENT result = 1 + LIP ( dp , mat , n , m , x + 1 , y ) NEW_LINE DEDENT if ( y + 1 < m and mat [ x ] [ y ] < mat [ x ] [ y + 1 ] ) : NEW_LINE INDENT result = max ( result , 1 + LIP ( dp , mat , n , m , x , y + 1 ) ) NEW_LINE DEDENT dp [ x ] [ y ] = result NEW_LINE DEDENT return dp [ x ] [ y ] NEW_LINE DEDENT def wrapper ( mat , n , m ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE return LIP ( dp , mat , n , m , 0 , 0 ) NEW_LINE DEDENT mat = [ [ 1 , 2 , 3 , 4 ] , [ 2 , 2 , 3 , 4 ] , [ 3 , 2 , 3 , 4 ] , [ 4 , 5 , 6 , 7 ] ] NEW_LINE n = 4 NEW_LINE m = 4 NEW_LINE print ( wrapper ( mat , n , m ) ) NEW_LINE"} +{"text":"Counts paths from a point to reach Origin | Recursive function to count number of paths ; If we reach bottom or top left , we are have only one way to reach ( 0 , 0 ) ; Else count sum of both ways ; Driver Code","code":"def countPaths ( n , m ) : NEW_LINE INDENT if ( n == 0 or m == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( countPaths ( n - 1 , m ) + countPaths ( n , m - 1 ) ) NEW_LINE DEDENT n = 3 NEW_LINE m = 2 NEW_LINE print ( \" \u2581 Number \u2581 of \u2581 Paths \u2581 \" , countPaths ( n , m ) ) NEW_LINE"} +{"text":"Gold Mine Problem | Python program to solve Gold Mine problem ; Returns maximum amount of gold that can be collected when journey started from first column and moves allowed are right , right - up and right - down ; Create a table for storing intermediate results and initialize all cells to 0. The first row of goldMineTable gives the maximum gold that the miner can collect when starts that row ; Gold collected on going to the cell on the right ( -> ) ; Gold collected on going to the cell to right up ( \/ ) ; Gold collected on going to the cell to right down ( \\ ) ; Max gold collected from taking either of the above 3 paths ; The max amount of gold collected will be the max value in first column of all rows ; Driver code","code":"MAX = 100 NEW_LINE def getMaxGold ( gold , m , n ) : NEW_LINE INDENT goldTable = [ [ 0 for i in range ( n ) ] for j in range ( m ) ] NEW_LINE for col in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for row in range ( m ) : NEW_LINE INDENT if ( col == n - 1 ) : NEW_LINE INDENT right = 0 NEW_LINE DEDENT else : NEW_LINE INDENT right = goldTable [ row ] [ col + 1 ] NEW_LINE DEDENT if ( row == 0 or col == n - 1 ) : NEW_LINE INDENT right_up = 0 NEW_LINE DEDENT else : NEW_LINE INDENT right_up = goldTable [ row - 1 ] [ col + 1 ] NEW_LINE DEDENT if ( row == m - 1 or col == n - 1 ) : NEW_LINE INDENT right_down = 0 NEW_LINE DEDENT else : NEW_LINE INDENT right_down = goldTable [ row + 1 ] [ col + 1 ] NEW_LINE DEDENT goldTable [ row ] [ col ] = gold [ row ] [ col ] + max ( right , right_up , right_down ) NEW_LINE DEDENT DEDENT res = goldTable [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , m ) : NEW_LINE INDENT res = max ( res , goldTable [ i ] [ 0 ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT gold = [ [ 1 , 3 , 1 , 5 ] , [ 2 , 2 , 4 , 1 ] , [ 5 , 0 , 2 , 3 ] , [ 0 , 6 , 1 , 2 ] ] NEW_LINE m = 4 NEW_LINE n = 4 NEW_LINE print ( getMaxGold ( gold , m , n ) ) NEW_LINE"} +{"text":"Find minimum adjustment cost of an array | Python3 program to find minimum adjustment cost of an array ; Function to find minimum adjustment cost of an array ; dp [ i ] [ j ] stores minimal adjustment cost on changing A [ i ] to j ; handle first element of array separately ; do for rest elements of the array ; replace A [ i ] to j and calculate minimal adjustment cost dp [ i ] [ j ] ; initialize minimal adjustment cost to INT_MAX ; consider all k such that k >= max ( j - target , 0 ) and k <= min ( M , j + target ) and take minimum ; return minimum value from last row of dp table ; Driver Code","code":"M = 100 NEW_LINE def minAdjustmentCost ( A , n , target ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( M + 1 ) ] for i in range ( n ) ] NEW_LINE for j in range ( M + 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = abs ( j - A [ 0 ] ) NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( M + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = 100000000 NEW_LINE for k in range ( max ( j - target , 0 ) , min ( M , j + target ) + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ i - 1 ] [ k ] + abs ( A [ i ] - j ) ) NEW_LINE DEDENT DEDENT DEDENT res = 10000000 NEW_LINE for j in range ( M + 1 ) : NEW_LINE INDENT res = min ( res , dp [ n - 1 ] [ j ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 55 , 77 , 52 , 61 , 39 , 6 , 25 , 60 , 49 , 47 ] NEW_LINE n = len ( arr ) NEW_LINE target = 10 NEW_LINE print ( \" Minimum \u2581 adjustment \u2581 cost \u2581 is \" , minAdjustmentCost ( arr , n , target ) , sep = ' \u2581 ' ) NEW_LINE"} +{"text":"Count triplets from a given range having sum of two numbers of a triplet equal to the third number | Function to find the number of triplets from the range [ L , R ] having sum of two numbers from the triplet equal to the third number ; Stores the total number of triplets ; Find the difference of the range ; Case 1 : If triplets can 't be formed, then return 0 ; Otherwise ; Update the total number of triplets ; Return the count ; Driver Code","code":"def totalCombination ( L , R ) : NEW_LINE INDENT count = 0 NEW_LINE K = R - L NEW_LINE if ( K < L ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = K - L NEW_LINE count = ( ( ans + 1 ) * ( ans + 2 ) ) \/\/ 2 NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 2 , 6 NEW_LINE print ( totalCombination ( L , R ) ) NEW_LINE DEDENT"} +{"text":"Construct two N | Function to generate two arrays satisfying the given conditions ; Declare the two arrays A and B ; Iterate from range [ 1 , 2 * n ] ; Assign consecutive numbers to same indices of the two arrays ; Print the first array ; Print the second array , B ; Driver Code ; Function Call","code":"def printArrays ( n ) : NEW_LINE INDENT A , B = [ ] , [ ] ; NEW_LINE for i in range ( 1 , 2 * n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT A . append ( i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT B . append ( i ) ; NEW_LINE DEDENT DEDENT print ( \" { \u2581 \" , end = \" \" ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( A [ i ] , end = \" \" ) ; NEW_LINE if ( i != n - 1 ) : NEW_LINE INDENT print ( \" , \u2581 \" , end = \" \" ) ; NEW_LINE DEDENT DEDENT print ( \" } \" ) ; NEW_LINE print ( \" { \u2581 \" , end = \" \" ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( B [ i ] , end = \" \" ) ; NEW_LINE if ( i != n - 1 ) : NEW_LINE INDENT print ( \" , \" , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT print ( \" \u2581 } \" , end = \" \" ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 5 ; NEW_LINE printArrays ( N ) ; NEW_LINE DEDENT"} +{"text":"Numbers formed by flipping common set bits in two given integers | Function to flip bits of A and B which are set in both of them ; Iterate all possible bits of A and B ; If ith bit is set in both A and B ; Clear i - th bit of A ; Clear i - th bit of B ; Print A and B ; Driver Code","code":"def flipBitsOfAandB ( A , B ) : NEW_LINE INDENT for i in range ( 0 , 32 ) : NEW_LINE INDENT if ( ( A & ( 1 << i ) ) and ( B & ( 1 << i ) ) ) : NEW_LINE INDENT A = A ^ ( 1 << i ) NEW_LINE B = B ^ ( 1 << i ) NEW_LINE DEDENT DEDENT print ( A , B ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = 7 NEW_LINE B = 4 NEW_LINE flipBitsOfAandB ( A , B ) NEW_LINE DEDENT"} +{"text":"Count of distinct pair sum between two 1 to N value Arrays | Function to find the distinct sums ; Driver code","code":"def findDistinctSums ( N ) : NEW_LINE INDENT return ( 2 * N - 1 ) NEW_LINE DEDENT N = 3 NEW_LINE print ( findDistinctSums ( N ) ) NEW_LINE"} +{"text":"Count of substrings from given Ternary strings containing characters at least once | Function to count the number of substrings consists of 0 , 1 , and 2 ; Initialize frequency array of size 3 ; Stores the resultant count ; Traversing string str ; Update frequency array ; If all the characters are present counting number of substrings possible ; Update number of substrings ; Return the number of substrings ; Driver Code","code":"def countSubstrings ( str ) : NEW_LINE INDENT freq = [ 0 ] * 3 NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE for j in range ( 0 , len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ j ] ) - ord ( '0' ) ] += 1 NEW_LINE while ( freq [ 0 ] > 0 and freq [ 1 ] > 0 and freq [ 2 ] > 0 ) : NEW_LINE INDENT i += 1 NEW_LINE freq [ ord ( str [ i ] ) - ord ( '0' ) ] -= 1 NEW_LINE DEDENT count += i NEW_LINE DEDENT return count NEW_LINE DEDENT str = \"00021\" NEW_LINE count = countSubstrings ( str ) NEW_LINE print ( count ) NEW_LINE"} +{"text":"Minimum flips to remove any consecutive 3 0 s or 1 s in given Binary string | Function to find the minimum number of flips to make all three pairs of consecutive characters different ; Stores resultant count of pairs ; Base Case ; Iterate over the range [ 0 , N - 2 ] ; If the consecutive 3 numbers are the same then increment the count and the counter ; Return the answer ; Driver Code","code":"def minFlips ( st ) : NEW_LINE INDENT count = 0 NEW_LINE if ( len ( st ) <= 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( len ( st ) - 2 ) : NEW_LINE INDENT if ( st [ i ] == st [ i + 1 ] and st [ i + 2 ] == st [ i + 1 ] ) : NEW_LINE INDENT i = i + 3 NEW_LINE count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S = \"0011101\" NEW_LINE print ( minFlips ( S ) ) NEW_LINE DEDENT"} +{"text":"Encrypt the string | Function to convert Decimal to Hex ; Function to encrypt the string ; Iterate the characters of the string ; Iterate until S [ i ] is equal to ch ; Update count and i ; Decrement i by 1 ; Convert count to hexadecimal representation ; Append the character ; Append the characters frequency in hexadecimal representation ; Reverse the obtained answer ; Return required answer ; Driver Code ; Given Input ; Function Call","code":"def convertToHex ( num ) : NEW_LINE INDENT temp = \" \" NEW_LINE while ( num != 0 ) : NEW_LINE INDENT rem = num % 16 NEW_LINE c = 0 NEW_LINE if ( rem < 10 ) : NEW_LINE INDENT c = rem + 48 NEW_LINE DEDENT else : NEW_LINE INDENT c = rem + 87 NEW_LINE DEDENT temp += chr ( c ) NEW_LINE num = num \/\/ 16 NEW_LINE DEDENT return temp NEW_LINE DEDENT def encryptString ( S , N ) : NEW_LINE INDENT ans = \" \" NEW_LINE for i in range ( N ) : NEW_LINE INDENT ch = S [ i ] NEW_LINE count = 0 NEW_LINE while ( i < N and S [ i ] == ch ) : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE hex = convertToHex ( count ) NEW_LINE ans += ch NEW_LINE ans += hex NEW_LINE DEDENT ans = ans [ : : - 1 ] NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" abc \" NEW_LINE N = len ( S ) NEW_LINE print ( encryptString ( S , N ) ) NEW_LINE DEDENT"} +{"text":"Count of Binary Strings of length N such that frequency of 1 ' s \u2581 exceeds \u2581 frequency \u2581 of \u2581 0' s | Function to calculate and return the value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate the value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] \/ [ k * ( k - 1 ) * -- - * 1 ] ; Function to return the count of binary strings of length N such that frequency of 1 ' s \u2581 exceed \u2581 that \u2581 of \u2581 0' s ; Count of N - length binary strings ; Count of N - length binary strings having equal count of 0 ' s \u2581 and \u2581 1' s ; For even length strings ; Driver Code","code":"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 countOfString ( N ) : NEW_LINE INDENT Stotal = pow ( 2 , N ) NEW_LINE Sequal = 0 NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT Sequal = binomialCoeff ( N , N \/\/ 2 ) NEW_LINE DEDENT S1 = ( Stotal - Sequal ) \/\/ 2 NEW_LINE return S1 NEW_LINE DEDENT N = 3 NEW_LINE print ( countOfString ( N ) ) NEW_LINE"} +{"text":"Remove all occurrences of a character in a string | Recursive approach | Function to remove all occurrences of a character in the string ; Base Case ; Check the first character of the given string ; Pass the rest of the string to recursion Function call ; Add the first character of str and string from recursion ; Given String ; Given character ; Function call","code":"def removeCharRecursive ( str , X ) : NEW_LINE INDENT if ( len ( str ) == 0 ) : NEW_LINE INDENT return \" \" NEW_LINE DEDENT if ( str [ 0 ] == X ) : NEW_LINE INDENT return removeCharRecursive ( str [ 1 : ] , X ) NEW_LINE DEDENT return str [ 0 ] + removeCharRecursive ( str [ 1 : ] , X ) NEW_LINE DEDENT str = \" geeksforgeeks \" NEW_LINE X = ' e ' NEW_LINE str = removeCharRecursive ( str , X ) NEW_LINE print ( str ) NEW_LINE"} +{"text":"Maximum time such that absolute difference between hour and minute lies in given range | Function checks whether given time is correct ; To check minute value of time ; To check hour value of time ; Changes in value is not allowed at position where ' ? ' is not present ; Function checks whether the absolute difference between hour and minute value is within [ L , R ] ; Checks if the difference is outside the give range ; Displays time in proper 24 - hour format ; Function find the desired value of time whose difference lies in the range [ L , R ] ; Decrease hour value from 23 to 0 ; Check if the hour value is valid if not valid then no need to change minute value , since time will still remain in valid , to check hour value flag is set to 1. ; Decrease minute value from 59 to 0 ; Check if the minute value is valid , if not valid then skip the current iteration , to check ' minute ' value flag is set to 0. ; Input time ; Difference range","code":"def isValid ( a1 , a2 , strr , flag ) : NEW_LINE INDENT v1 , v2 = 0 , 0 NEW_LINE if ( flag == 0 ) : NEW_LINE INDENT v1 = strr [ 4 ] NEW_LINE v2 = strr [ 3 ] NEW_LINE DEDENT else : NEW_LINE INDENT v1 = strr [ 1 ] NEW_LINE v2 = strr [ 0 ] NEW_LINE DEDENT if ( v1 != a1 and v1 != ' ? ' ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( v2 != a2 and v2 != ' ? ' ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def inRange ( hh , mm , L , R ) : NEW_LINE INDENT a = abs ( hh - mm ) NEW_LINE if ( a < L or a > R ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def displayTime ( hh , mm ) : NEW_LINE INDENT if ( hh > 10 ) : NEW_LINE INDENT print ( hh , end = \" : \" ) NEW_LINE DEDENT elif ( hh < 10 ) : NEW_LINE INDENT print ( \"0\" , hh , end = \" : \" ) NEW_LINE DEDENT if ( mm > 10 ) : NEW_LINE INDENT print ( mm ) NEW_LINE DEDENT elif ( mm < 10 ) : NEW_LINE INDENT print ( \"0\" , mm ) NEW_LINE DEDENT DEDENT def maximumTimeWithDifferenceInRange ( strr , L , R ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE h1 , h2 , m1 , m2 = 0 , 0 , 0 , 0 NEW_LINE for i in range ( 23 , - 1 , - 1 ) : NEW_LINE INDENT h1 = i % 10 NEW_LINE h2 = i \/\/ 10 NEW_LINE if ( not isValid ( chr ( h1 ) , chr ( h2 ) , strr , 1 ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( 59 , - 1 , - 1 ) : NEW_LINE INDENT m1 = j % 10 NEW_LINE m2 = j \/\/ 10 NEW_LINE if ( not isValid ( chr ( m1 ) , chr ( m2 ) , strr , 0 ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( inRange ( i , j , L , R ) ) : NEW_LINE INDENT displayTime ( i , j ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT if ( inRange ( i , j , L , R ) ) : NEW_LINE INDENT displayTime ( i , j ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT timeValue = \" ? ? : ? ? \" NEW_LINE L = 20 NEW_LINE R = 39 NEW_LINE maximumTimeWithDifferenceInRange ( timeValue , L , R ) NEW_LINE"} +{"text":"Check if a string can be split into even length palindromic substrings | Function to check string str can be split a string into even length palindromic substrings ; Initialize a stack ; Iterate the string ; If the i - th character is same as that at the top of the stack then pop the top element ; Else push the current charactor into the stack ; If the stack is empty , then even palindromic substrings are possible ; Else not - possible ; Given string ; Function Call","code":"def check ( s , n ) : NEW_LINE INDENT st = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( st ) != 0 and st [ len ( st ) - 1 ] == s [ i ] ) : NEW_LINE INDENT st . pop ( ) ; NEW_LINE DEDENT else : NEW_LINE INDENT st . append ( s [ i ] ) ; NEW_LINE DEDENT DEDENT if ( len ( st ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT str = \" aanncddc \" ; NEW_LINE n = len ( str ) NEW_LINE if ( check ( str , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Number of strings in two array satisfy the given conditions | Python3 program for the above approach ; To store the frequency of string after bitmasking ; To store result for each string in arr2 [ ] ; Traverse the arr1 [ ] and bitmask each string in it ; Bitmasking for each string s ; Update the frequency of string with it 's bitmasking value ; Traverse the arr2 [ ] ; Bitmasking for each string s ; Check if temp is present in an unordered_map or not ; Check for next set bit ; Push the count for current string in resultant array ; Print the count for each string ; Driver Code ; Function call","code":"from collections import defaultdict NEW_LINE def findNumOfValidWords ( w , p ) : NEW_LINE INDENT m = defaultdict ( int ) NEW_LINE res = [ ] NEW_LINE for s in w : NEW_LINE INDENT val = 0 NEW_LINE for c in s : NEW_LINE INDENT val = val | ( 1 << ( ord ( c ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT m [ val ] += 1 NEW_LINE DEDENT for s in p : NEW_LINE INDENT val = 0 NEW_LINE for c in s : NEW_LINE INDENT val = val | ( 1 << ( ord ( c ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT temp = val NEW_LINE first = ord ( s [ 0 ] ) - ord ( ' a ' ) NEW_LINE count = 0 NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT if ( ( ( temp >> first ) & 1 ) == 1 ) : NEW_LINE INDENT if ( temp in m ) : NEW_LINE INDENT count += m [ temp ] NEW_LINE DEDENT DEDENT temp = ( temp - 1 ) & val NEW_LINE DEDENT res . append ( count ) NEW_LINE DEDENT for it in res : NEW_LINE INDENT print ( it ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr1 = [ \" aaaa \" , \" asas \" , \" able \" , \" ability \" , \" actt \" , \" actor \" , \" access \" ] NEW_LINE arr2 = [ \" aboveyz \" , \" abrodyz \" , \" absolute \" , \" absoryz \" , \" actresz \" , \" gaswxyz \" ] NEW_LINE findNumOfValidWords ( arr1 , arr2 ) NEW_LINE DEDENT"} +{"text":"Maximize the decimal equivalent by flipping only a contiguous set of 0 s | Function to print the binary number ; Check if the current number is 0 ; Find the continuous 0 s ; Replace initially occurring 0 with 1 ; return the string and break the loop ; Driver code","code":"def flip ( s ) : NEW_LINE INDENT s = list ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT while ( s [ i ] == '0' ) : NEW_LINE INDENT s [ i ] = '1' NEW_LINE i += 1 NEW_LINE DEDENT s = ' ' . join ( map ( str , s ) ) NEW_LINE return s NEW_LINE DEDENT DEDENT DEDENT s = \"100010001\" NEW_LINE print ( flip ( s ) ) NEW_LINE"} +{"text":"Sentence Case of a given Camel cased string | Function to return the original string after converting it back from camelCase ; Print the first character as it is ; Traverse the rest of the characters one by one ; If current character is uppercase prspace followed by the current character in lowercase ; Else print the current character ; Driver code","code":"def getOrgString ( s ) : NEW_LINE INDENT print ( s [ 0 ] , end = \" \" ) NEW_LINE i = 1 NEW_LINE while ( i < len ( s ) ) : NEW_LINE INDENT if ( ord ( s [ i ] ) >= ord ( ' A ' ) and ord ( s [ i ] ) <= ord ( ' Z ' ) ) : NEW_LINE INDENT print ( \" \u2581 \" , s [ i ] . lower ( ) , end = \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ i ] , end = \" \" ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT s = \" ILoveGeeksForGeeks \" NEW_LINE getOrgString ( s ) NEW_LINE"} +{"text":"Count occurrences of a character in a repeated string | Function to count the character 'a ; atleast k repetition are required ; if n is not the multiple of the string size check for the remaining repeating character . ; Driver code","code":"' NEW_LINE def countChar ( str , x ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == x ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT n = 10 NEW_LINE repetitions = n \/\/ len ( str ) NEW_LINE count = count * repetitions NEW_LINE l = n % len ( str ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( str [ i ] == x ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT str = \" abcac \" NEW_LINE print ( countChar ( str , ' a ' ) ) NEW_LINE"} +{"text":"Frequency Measuring Techniques for Competitive Programming | Python3 program to count frequencies of array items having small values . ; Create an array to store counts . The size of array is limit + 1 and all values are initially 0 ; Traverse through array elements and count frequencies ( assuming that elements are limited by limit ) ; Driver Code","code":"def countFreq ( arr , n , limit ) : NEW_LINE INDENT count = [ 0 for i in range ( limit + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( limit + 1 ) : NEW_LINE INDENT if ( count [ i ] > 0 ) : NEW_LINE INDENT print ( i , count [ i ] ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 5 , 6 , 6 , 5 , 6 , 1 , 2 , 3 , 10 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE limit = 10 NEW_LINE countFreq ( arr , n , limit ) NEW_LINE"} +{"text":"Check if a string has m consecutive 1 ' s \u2581 or \u2581 0' s | Function that checks if the binary string contains m consecutive 1 ' s \u2581 or \u2581 0' s ; length of binary string ; counts zeros ; counts 1 's ; count consecutive 0 's ; count consecutive 1 's ; Driver Code ; function call","code":"def check ( s , m ) : NEW_LINE INDENT l = len ( s ) ; NEW_LINE c1 = 0 ; NEW_LINE c2 = 0 ; NEW_LINE for i in range ( 0 , l - 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT c2 = 0 ; NEW_LINE c1 = c1 + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT c1 = 0 ; NEW_LINE c2 = c2 + 1 ; NEW_LINE DEDENT if ( c1 == m or c2 == m ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT s = \"001001\" ; NEW_LINE m = 2 ; NEW_LINE if ( check ( s , m ) ) : NEW_LINE INDENT print ( \" YES \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) ; NEW_LINE DEDENT"} +{"text":"Product of nodes at k | Function to find product of digits of elements at k - th level ; Initialize result ; increasing level number ; decreasing level number ; check if current level is the desired level or not ; required product ; Driver program","code":"def productAtKthLevel ( tree , k ) : NEW_LINE INDENT level = - 1 NEW_LINE product = 1 NEW_LINE n = len ( tree ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( tree [ i ] == ' ( ' ) : NEW_LINE INDENT level += 1 NEW_LINE DEDENT elif ( tree [ i ] == ' ) ' ) : NEW_LINE INDENT level -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( level == k ) : NEW_LINE INDENT product *= ( int ( tree [ i ] ) - int ( '0' ) ) NEW_LINE DEDENT DEDENT DEDENT return product NEW_LINE DEDENT tree = \" ( 0(5(6 ( ) ( ) ) ( 4 ( ) (9 ( ) ( ) ) ) ) ( 7(1 ( ) ( ) ) ( 3 ( ) ( ) ) ) ) \" NEW_LINE k = 2 NEW_LINE print ( productAtKthLevel ( tree , k ) ) NEW_LINE"} +{"text":"Removing row or column wise duplicates from matrix of characters | Function to check duplicates in row and column ; Create an array isPresent and initialize all entries of it as false . The value of isPresent [ i ] [ j ] is going to be true if s [ i ] [ j ] is present in its row or column . ; Checking every row for duplicates of a [ i ] [ j ] ; Checking every row for duplicates of a [ i ] [ j ] ; If the character is unique in its row and column ; Driver Code ; character array ; Calling function","code":"def findDuplicates ( a , n , m ) : NEW_LINE INDENT isPresent = [ [ False for i in range ( n ) ] for j in range ( m ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT if i != k and a [ i ] [ j ] == a [ k ] [ j ] : NEW_LINE INDENT isPresent [ i ] [ j ] = True NEW_LINE isPresent [ k ] [ j ] = True NEW_LINE DEDENT DEDENT for k in range ( m ) : NEW_LINE INDENT if j != k and a [ i ] [ j ] == a [ i ] [ k ] : NEW_LINE INDENT isPresent [ i ] [ j ] = True NEW_LINE isPresent [ i ] [ k ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if not isPresent [ i ] [ j ] : NEW_LINE INDENT print ( a [ i ] [ j ] , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 2 NEW_LINE m = 2 NEW_LINE a = [ \" zx \" , \" xz \" ] NEW_LINE findDuplicates ( a , n , m ) NEW_LINE DEDENT"} +{"text":"Program to check for ISBN | Python code to check if a given ISBN is valid or not . ; check for length ; Computing weighted sum of first 9 digits ; Checking last digit ; If last digit is ' X ' , add 10 to sum , else add its value . ; Return true if weighted sum of digits is divisible by 11 ; Driver Code","code":"def isValidISBN ( isbn ) : NEW_LINE INDENT if len ( isbn ) != 10 : NEW_LINE INDENT return False NEW_LINE DEDENT _sum = 0 NEW_LINE for i in range ( 9 ) : NEW_LINE INDENT if 0 <= int ( isbn [ i ] ) <= 9 : NEW_LINE INDENT _sum += int ( isbn [ i ] ) * ( 10 - i ) NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( isbn [ 9 ] != ' X ' and 0 <= int ( isbn [ 9 ] ) <= 9 ) : NEW_LINE INDENT return False NEW_LINE DEDENT _sum += 10 if isbn [ 9 ] == ' X ' else int ( isbn [ 9 ] ) NEW_LINE return ( _sum % 11 == 0 ) NEW_LINE DEDENT isbn = \"007462542X \" NEW_LINE if isValidISBN ( isbn ) : NEW_LINE INDENT print ( ' Valid ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Invalid \" ) NEW_LINE DEDENT"} +{"text":"Reverse vowels in a given string | utility function to check for vowel ; Function to reverse order of vowels ; Storing the vowels separately ; Placing the vowels in the reverse order in the string ; Driver Code","code":"def isVowel ( c ) : NEW_LINE INDENT if ( c == ' a ' or c == ' A ' or c == ' e ' or c == ' E ' or c == ' i ' or c == ' I ' or c == ' o ' or c == ' O ' or c == ' u ' or c == ' U ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def reverserVowel ( string ) : NEW_LINE INDENT j = 0 NEW_LINE vowel = [ 0 ] * len ( string ) NEW_LINE string = list ( string ) NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if isVowel ( string [ i ] ) : NEW_LINE INDENT vowel [ j ] = string [ i ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT for i in range ( len ( string ) ) : NEW_LINE INDENT if isVowel ( string [ i ] ) : NEW_LINE INDENT j -= 1 NEW_LINE string [ i ] = vowel [ j ] NEW_LINE DEDENT DEDENT return ' ' . join ( string ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" hello \u2581 world \" NEW_LINE print ( reverserVowel ( string ) ) NEW_LINE DEDENT"} +{"text":"String containing first letter of every word in a given string with spaces | Function to find string which has first character of each word . ; Traverse the string . ; If it is space , set v as true . ; Else check if v is true or not . If true , copy character in output string and set v as false . ; Driver Code","code":"def firstLetterWord ( str ) : NEW_LINE INDENT result = \" \" NEW_LINE v = True NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' \u2581 ' ) : NEW_LINE INDENT v = True NEW_LINE DEDENT elif ( str [ i ] != ' \u2581 ' and v == True ) : NEW_LINE INDENT result += ( str [ i ] ) NEW_LINE v = False NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeks \u2581 for \u2581 geeks \" NEW_LINE print ( firstLetterWord ( str ) ) NEW_LINE DEDENT"} +{"text":"Unique paths covering every non | Function for dfs . i , j == > Current cell indexes vis == > To mark visited cells ans == > Result z == > Current count 0 s visited z_count == > Total 0 s present ; Mark the block as visited ; Update the count ; If end block reached ; If path covered all the non - obstacle blocks ; Up ; Down ; Left ; Right ; Unmark the block ( unvisited ) ; Function to return the count of the unique paths ; Total 0 s present ; Count non - obstacle blocks ; Starting position ; Driver code","code":"def dfs ( i , j , grid , vis , ans , z , z_count ) : NEW_LINE INDENT n = len ( grid ) NEW_LINE m = len ( grid [ 0 ] ) NEW_LINE vis [ i ] [ j ] = 1 NEW_LINE if ( grid [ i ] [ j ] == 0 ) : NEW_LINE INDENT z += 1 NEW_LINE DEDENT if ( grid [ i ] [ j ] == 2 ) : NEW_LINE INDENT if ( z == z_count ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT vis [ i ] [ j ] = 0 NEW_LINE return grid , vis , ans NEW_LINE DEDENT if ( i >= 1 and not vis [ i - 1 ] [ j ] and grid [ i - 1 ] [ j ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i - 1 , j , grid , vis , ans , z , z_count ) NEW_LINE DEDENT if ( i < n - 1 and not vis [ i + 1 ] [ j ] and grid [ i + 1 ] [ j ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i + 1 , j , grid , vis , ans , z , z_count ) NEW_LINE DEDENT if ( j >= 1 and not vis [ i ] [ j - 1 ] and grid [ i ] [ j - 1 ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i , j - 1 , grid , vis , ans , z , z_count ) NEW_LINE DEDENT if ( j < m - 1 and not vis [ i ] [ j + 1 ] and grid [ i ] [ j + 1 ] != - 1 ) : NEW_LINE INDENT grid , vis , ans = dfs ( i , j + 1 , grid , vis , ans , z , z_count ) NEW_LINE DEDENT vis [ i ] [ j ] = 0 NEW_LINE return grid , vis , ans NEW_LINE DEDENT def uniquePaths ( grid ) : NEW_LINE INDENT z_count = 0 NEW_LINE n = len ( grid ) NEW_LINE m = len ( grid [ 0 ] ) NEW_LINE ans = 0 NEW_LINE vis = [ [ 0 for j in range ( m ) ] for i in range ( n ) ] NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if grid [ i ] [ j ] == 0 : NEW_LINE INDENT z_count += 1 NEW_LINE DEDENT elif ( grid [ i ] [ j ] == 1 ) : NEW_LINE INDENT x = i NEW_LINE y = j NEW_LINE DEDENT DEDENT DEDENT grid , vis , ans = dfs ( x , y , grid , vis , ans , 0 , z_count ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 ] , [ 0 , 0 , 2 , - 1 ] ] NEW_LINE print ( uniquePaths ( grid ) ) NEW_LINE DEDENT"} +{"text":"Count of unordered pairs ( x , y ) of Array which satisfy given equation | Return the number of unordered pairs satisfying the conditions ; ans stores the number of unordered pairs ; Making each value of array to positive ; Sort the array ; For each index calculating the right boundary for the unordered pairs ; Return the final result ; Driver code","code":"def numPairs ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = abs ( a [ i ] ) NEW_LINE DEDENT a . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT index = 0 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( 2 * a [ i ] >= a [ j - 1 ] and 2 * a [ i ] < a [ j ] ) : NEW_LINE INDENT index = j NEW_LINE DEDENT DEDENT if index == 0 : NEW_LINE INDENT index = n NEW_LINE DEDENT ans += index - i - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 3 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( numPairs ( a , n ) ) NEW_LINE"} +{"text":"Area of a Square | Using Side , Diagonal and Perimeter | Function to find the area of a square ; Use above formula ; Driver Code ; Given Side of square ; Function call","code":"def areaOfSquare ( S ) : NEW_LINE INDENT area = S * S NEW_LINE return area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = 5 NEW_LINE print ( areaOfSquare ( S ) ) NEW_LINE DEDENT"} +{"text":"Maximum points of intersections possible among X circles and Y straight lines | Python3 program to implement the above approach ; Number of circles ; Number of straight lines ; Function Call","code":"def maxPointOfIntersection ( x , y ) : NEW_LINE INDENT k = y * ( y - 1 ) \/\/ 2 NEW_LINE k = k + x * ( 2 * y + x - 1 ) NEW_LINE return k NEW_LINE DEDENT x = 3 NEW_LINE y = 4 NEW_LINE print ( maxPointOfIntersection ( x , y ) ) NEW_LINE"} +{"text":"Icosihenagonal Number | Function to find icosihenagonal number ; Formula to calculate nth icosihenagonal number ; Driver Code","code":"def Icosihenagonal_num ( n ) : NEW_LINE INDENT return ( 19 * n * n - 17 * n ) \/ 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( Icosihenagonal_num ( n ) ) ) NEW_LINE n = 10 NEW_LINE print ( int ( Icosihenagonal_num ( n ) ) ) NEW_LINE"} +{"text":"Find the centroid of a non | Python3 program to implement the above approach ; For all vertices ; Calculate value of A using shoelace formula ; Calculating coordinates of centroid of polygon ; Coordinate of the vertices","code":"def find_Centroid ( v ) : NEW_LINE INDENT ans = [ 0 , 0 ] NEW_LINE n = len ( v ) NEW_LINE signedArea = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT x0 = v [ i ] [ 0 ] NEW_LINE y0 = v [ i ] [ 1 ] NEW_LINE x1 = v [ ( i + 1 ) % n ] [ 0 ] NEW_LINE y1 = v [ ( i + 1 ) % n ] [ 1 ] NEW_LINE A = ( x0 * y1 ) - ( x1 * y0 ) NEW_LINE signedArea += A NEW_LINE ans [ 0 ] += ( x0 + x1 ) * A NEW_LINE ans [ 1 ] += ( y0 + y1 ) * A NEW_LINE DEDENT signedArea *= 0.5 NEW_LINE ans [ 0 ] = ( ans [ 0 ] ) \/ ( 6 * signedArea ) NEW_LINE ans [ 1 ] = ( ans [ 1 ] ) \/ ( 6 * signedArea ) NEW_LINE return ans NEW_LINE DEDENT vp = [ [ 1 , 2 ] , [ 3 , - 4 ] , [ 6 , - 7 ] ] NEW_LINE ans = find_Centroid ( vp ) NEW_LINE print ( round ( ans [ 0 ] , 12 ) , ans [ 1 ] ) NEW_LINE"} +{"text":"Program to find the angles of a quadrilateral | Driver code ; according to formula derived above ; print all the angles","code":"d = 10 NEW_LINE a = 0.0 NEW_LINE a = ( 360 - ( 6 * d ) ) \/ 4 NEW_LINE print ( a , \" , \" , a + d , \" , \" , a + 2 * d , \" , \" , a + 3 * d , sep = ' \u2581 ' ) NEW_LINE"} +{"text":"Distance between two parallel Planes in 3 | Python program to find the Distance between two parallel Planes in 3 D . ; Function to find distance ; Driver Code","code":"import math NEW_LINE def distance ( a1 , b1 , c1 , d1 , a2 , b2 , c2 , d2 ) : NEW_LINE INDENT if ( a1 \/ a2 == b1 \/ b2 and b1 \/ b2 == c1 \/ c2 ) : NEW_LINE INDENT x1 = y1 = 0 NEW_LINE z1 = - d1 \/ c1 NEW_LINE d = abs ( ( c2 * z1 + d2 ) ) \/ ( math . sqrt ( a2 * a2 + b2 * b2 + c2 * c2 ) ) NEW_LINE print ( \" Perpendicular \u2581 distance \u2581 is \" ) , d NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Planes \u2581 are \u2581 not \u2581 parallel \" ) NEW_LINE DEDENT DEDENT a1 = 1 NEW_LINE b1 = 2 NEW_LINE c1 = - 1 NEW_LINE d1 = 1 NEW_LINE a2 = 3 NEW_LINE b2 = 6 NEW_LINE c2 = - 3 NEW_LINE d2 = - 4 NEW_LINE distance ( a1 , b1 , c1 , d1 , a2 , b2 , c2 , d2 ) NEW_LINE"} +{"text":"Count of ways to form 2 necklace from N beads containing N \/ 2 beads each | Function to calculate factorial ; Function to count number of ways to make 2 necklace having exactly N \/ 2 beads if each bead is considered different ; Number of ways to choose N \/ 2 beads from N beads ; Number of ways to permute N \/ 2 beads ; Divide ans by 2 to remove repetitions ; Return ans ; Driver Code ; Given Input ; Function Call","code":"def factorial ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return n * factorial ( n - 1 ) NEW_LINE DEDENT def numOfNecklace ( N ) : NEW_LINE INDENT ans = factorial ( N ) \/\/ ( factorial ( N \/\/ 2 ) * factorial ( N \/\/ 2 ) ) NEW_LINE ans = ans * factorial ( N \/\/ 2 - 1 ) NEW_LINE ans = ans * factorial ( N \/\/ 2 - 1 ) NEW_LINE ans \/\/= 2 NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( numOfNecklace ( N ) ) NEW_LINE DEDENT"} +{"text":"Check if a number S can be made divisible by D by repeatedly adding the remainder to S | Function to check if S is divisible by D while changing S to ( S + S % D ) ; V ( 0 ) = S % D ; Stores the encountered values ; V ( i ) = ( V ( i - 1 ) + V ( i - 1 ) % D ) % D ; Check if the value has already been encountered ; Edge Case ; Otherwise , insert it into the hashmap ; Driver Code","code":"def isDivisibleByDivisor ( S , D ) : NEW_LINE INDENT S %= D NEW_LINE hashMap = set ( ) NEW_LINE hashMap . add ( S ) NEW_LINE for i in range ( D + 1 ) : NEW_LINE INDENT S += ( S % D ) NEW_LINE S %= D NEW_LINE if ( S in hashMap ) : NEW_LINE INDENT if ( S == 0 ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT return \" No \" NEW_LINE DEDENT else : NEW_LINE INDENT hashMap . add ( S ) NEW_LINE DEDENT DEDENT return \" Yes \" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = 3 NEW_LINE D = 6 NEW_LINE print ( isDivisibleByDivisor ( S , D ) ) NEW_LINE DEDENT"} +{"text":"Minimum number of given moves required to reach ( 1 , 1 ) from ( X , Y ) | Function to count the number of steps required to convert ( x , y ) to ( 1 , 1 ) ; Store the required result ; Iterate while both x and y are not equal to 0 ; If x is greater than y ; Update count and value of x ; Otherwise ; Update count and value of y ; If both x and y > 1 ; Print the result ; Driver Code ; Given X and Y","code":"def minimumSteps ( x , y ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( x != 0 and y != 0 ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT cnt += x \/ y NEW_LINE x %= y NEW_LINE DEDENT else : NEW_LINE INDENT cnt += y \/ x NEW_LINE y %= x NEW_LINE DEDENT DEDENT cnt -= 1 NEW_LINE if ( x > 1 or y > 1 ) : NEW_LINE INDENT cnt = - 1 NEW_LINE DEDENT print ( int ( cnt ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 3 NEW_LINE y = 1 NEW_LINE minimumSteps ( x , y ) NEW_LINE DEDENT"} +{"text":"Minimum number of bracket reversals needed to make an expression balanced | Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; After this loop , stack contains unbalanced part of expression , i . e . , expression of the form \" . . . . \" ; Length of the reduced expression red_len = ( m + n ) ; count opening brackets at the end of stack ; return ceil ( m \/ 2 ) + ceil ( n \/ 2 ) which is actually equal to ( m + n ) \/ 2 + n % 2 when m + n is even . ; Driver Code","code":"def countMinReversals ( expr ) : NEW_LINE INDENT lenn = len ( expr ) NEW_LINE if ( lenn % 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT s = [ ] NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( expr [ i ] == ' ' and len ( s ) ) : NEW_LINE INDENT if ( s [ 0 ] == ' ' ) : NEW_LINE INDENT s . pop ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT s . insert ( 0 , expr [ i ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT s . insert ( 0 , expr [ i ] ) NEW_LINE DEDENT DEDENT red_len = len ( s ) NEW_LINE n = 0 NEW_LINE while ( len ( s ) and s [ 0 ] == ' ' ) : NEW_LINE INDENT s . pop ( 0 ) NEW_LINE n += 1 NEW_LINE DEDENT return ( red_len \/\/ 2 + n % 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT expr = \" } } { { \" NEW_LINE print ( countMinReversals ( expr . strip ( ) ) ) NEW_LINE DEDENT"} +{"text":"Form minimum number from given sequence | Prints the minimum number that can be formed from input sequence of I ' s \u2581 and \u2581 D ' s ; Initialize current_max ( to make sure that we don 't use repeated character ; Initialize last_entry ( Keeps track for last printed digit ) ; Iterate over input array ; Initialize ' noOfNextD ' to get count of next D 's available ; If letter is ' I ' Calculate number of next consecutive D 's available ; If ' I ' is first letter , print incremented sequence from 1 ; Set max digit reached ; If not first letter Get next digit to print ; Print digit for I ; For all next consecutive ' D ' print decremented sequence ; If letter is 'D ; If ' D ' is first letter in sequence Find number of Next D 's available ; Calculate first digit to print based on number of consecutive D 's ; Print twice for the first time ; Store last entry ; If current ' D ' is not first letter Decrement last_entry ; Driver code","code":"def PrintMinNumberForPattern ( arr ) : NEW_LINE INDENT curr_max = 0 NEW_LINE last_entry = 0 NEW_LINE i = 0 NEW_LINE while i < len ( arr ) : NEW_LINE INDENT noOfNextD = 0 NEW_LINE if arr [ i ] == \" I \" : NEW_LINE INDENT j = i + 1 NEW_LINE while j < len ( arr ) and arr [ j ] == \" D \" : NEW_LINE INDENT noOfNextD += 1 NEW_LINE j += 1 NEW_LINE DEDENT if i == 0 : NEW_LINE INDENT curr_max = noOfNextD + 2 NEW_LINE last_entry += 1 NEW_LINE print ( \" \" , last_entry , end = \" \" ) NEW_LINE print ( \" \" , curr_max , end = \" \" ) NEW_LINE last_entry = curr_max NEW_LINE DEDENT else : NEW_LINE INDENT curr_max += noOfNextD + 1 NEW_LINE last_entry = curr_max NEW_LINE print ( \" \" , last_entry , end = \" \" ) NEW_LINE DEDENT for k in range ( noOfNextD ) : NEW_LINE INDENT last_entry -= 1 NEW_LINE print ( \" \" , last_entry , end = \" \" ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT elif arr [ i ] == \" D \" : NEW_LINE INDENT if i == 0 : NEW_LINE INDENT j = i + 1 NEW_LINE while j < len ( arr ) and arr [ j ] == \" D \" : NEW_LINE INDENT noOfNextD += 1 NEW_LINE j += 1 NEW_LINE DEDENT curr_max = noOfNextD + 2 NEW_LINE print ( \" \" , curr_max , curr_max - 1 , end = \" \" ) NEW_LINE last_entry = curr_max - 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" \" , last_entry - 1 , end = \" \" ) NEW_LINE last_entry -= 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT PrintMinNumberForPattern ( \" IDID \" ) NEW_LINE PrintMinNumberForPattern ( \" I \" ) NEW_LINE PrintMinNumberForPattern ( \" DD \" ) NEW_LINE PrintMinNumberForPattern ( \" II \" ) NEW_LINE PrintMinNumberForPattern ( \" DIDI \" ) NEW_LINE PrintMinNumberForPattern ( \" IIDDD \" ) NEW_LINE PrintMinNumberForPattern ( \" DDIDDIID \" ) NEW_LINE DEDENT"} +{"text":"Form minimum number from given sequence | Python3 program to print minimum number that can be formed from a given sequence of Is and Ds ; min_avail represents the minimum number which is still available for inserting in the output vector . pos_of_I keeps track of the most recent index where ' I ' was encountered w . r . t the output vector ; Vector to store the output ; Cover the base cases ; Traverse rest of the input ; Print the number ; Driver code","code":"def printLeast ( arr ) : NEW_LINE INDENT min_avail = 1 NEW_LINE pos_of_I = 0 NEW_LINE v = [ ] NEW_LINE if ( arr [ 0 ] == ' I ' ) : NEW_LINE INDENT v . append ( 1 ) NEW_LINE v . append ( 2 ) NEW_LINE min_avail = 3 NEW_LINE pos_of_I = 1 NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( 2 ) NEW_LINE v . append ( 1 ) NEW_LINE min_avail = 3 NEW_LINE pos_of_I = 0 NEW_LINE DEDENT for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] == ' I ' ) : NEW_LINE INDENT v . append ( min_avail ) NEW_LINE min_avail += 1 NEW_LINE pos_of_I = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( v [ i ] ) NEW_LINE for j in range ( pos_of_I , i + 1 ) : NEW_LINE INDENT v [ j ] += 1 NEW_LINE DEDENT min_avail += 1 NEW_LINE DEDENT DEDENT print ( * v , sep = ' \u2581 ' ) NEW_LINE DEDENT printLeast ( \" IDID \" ) NEW_LINE printLeast ( \" I \" ) NEW_LINE printLeast ( \" DD \" ) NEW_LINE printLeast ( \" II \" ) NEW_LINE printLeast ( \" DIDI \" ) NEW_LINE printLeast ( \" IIDDD \" ) NEW_LINE printLeast ( \" DDIDDIID \" ) NEW_LINE"} +{"text":"Form minimum number from given sequence | Function to decode the given sequence to construct minimum number without repeated digits ; String for storing result ; Take a List to work as Stack ; run n + 1 times where n is length of input sequence , As length of result string is always 1 greater ; Push number i + 1 into the stack ; If all characters of the input sequence are processed or current character is 'I ; Run While Loop Untill stack is empty ; pop the element on top of stack And store it in result String ; Driver Code","code":"def PrintMinNumberForPattern ( Strr ) : NEW_LINE INDENT res = ' ' NEW_LINE stack = [ ] NEW_LINE for i in range ( len ( Strr ) + 1 ) : NEW_LINE INDENT stack . append ( i + 1 ) NEW_LINE if ( i == len ( Strr ) or Strr [ i ] == ' I ' ) : NEW_LINE INDENT while len ( stack ) > 0 : NEW_LINE INDENT res += str ( stack . pop ( ) ) NEW_LINE res += ' \u2581 ' NEW_LINE DEDENT DEDENT DEDENT print ( res ) NEW_LINE DEDENT PrintMinNumberForPattern ( \" IDID \" ) NEW_LINE PrintMinNumberForPattern ( \" I \" ) NEW_LINE PrintMinNumberForPattern ( \" DD \" ) NEW_LINE PrintMinNumberForPattern ( \" II \" ) NEW_LINE PrintMinNumberForPattern ( \" DIDI \" ) NEW_LINE PrintMinNumberForPattern ( \" IIDDD \" ) NEW_LINE PrintMinNumberForPattern ( \" DDIDDIID \" ) NEW_LINE"} +{"text":"Form minimum number from given sequence | Returns minimum number made from given sequence without repeating digits ; The loop runs for each input character as well as one additional time for assigning rank to remaining characters ; Driver Code","code":"def getMinNumberForPattern ( seq ) : NEW_LINE INDENT n = len ( seq ) NEW_LINE if ( n >= 9 ) : NEW_LINE INDENT return \" - 1\" NEW_LINE DEDENT result = [ None ] * ( n + 1 ) NEW_LINE count = 1 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( i == n or seq [ i ] == ' I ' ) : NEW_LINE INDENT for j in range ( i - 1 , - 2 , - 1 ) : NEW_LINE INDENT result [ j + 1 ] = int ( '0' + str ( count ) ) NEW_LINE count += 1 NEW_LINE if ( j >= 0 and seq [ j ] == ' I ' ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT inputs = [ \" IDID \" , \" I \" , \" DD \" , \" II \" , \" DIDI \" , \" IIDDD \" , \" DDIDDIID \" ] NEW_LINE for Input in inputs : NEW_LINE INDENT print ( * ( getMinNumberForPattern ( Input ) ) ) NEW_LINE DEDENT DEDENT"} +{"text":"Check if the first and last digit of the smallest number forms a prime | Python3 implementation of above approach ; function to check prime ; Function to generate smallest possible number with given digits ; Declare a Hash array of size 10 and initialize all the elements to zero ; store the number of occurrences of the digits in the given array into the Hash table ; Traverse the Hash in ascending order to print the required number ; Print the number of times a digits occurs ; extracting the first digit ; extracting the last digit ; printing the prime combinations ; Driver code","code":"import math as mt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT i , c = 0 , 0 NEW_LINE for i in range ( 1 , n \/\/ 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def findMinNum ( arr , n ) : NEW_LINE INDENT first , last = 0 , 0 NEW_LINE Hash = [ 0 for i in range ( 10 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT Hash [ arr [ i ] ] += 1 NEW_LINE DEDENT print ( \" Minimum \u2581 number : \u2581 \" , end = \" \" ) NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT for j in range ( Hash [ i ] ) : NEW_LINE INDENT print ( i , end = \" \" ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( Hash [ i ] != 0 ) : NEW_LINE INDENT first = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( 9 , - 1 , - 1 ) : NEW_LINE INDENT if ( Hash [ i ] != 0 ) : NEW_LINE INDENT last = i NEW_LINE break NEW_LINE DEDENT DEDENT num = first * 10 + last NEW_LINE rev = last * 10 + first NEW_LINE print ( \" Prime \u2581 combinations : \u2581 \" , end = \" \" ) NEW_LINE if ( isPrime ( num ) and isPrime ( rev ) ) : NEW_LINE INDENT print ( num , \" \u2581 \" , rev ) NEW_LINE DEDENT elif ( isPrime ( num ) ) : NEW_LINE INDENT print ( num ) NEW_LINE DEDENT elif ( isPrime ( rev ) ) : NEW_LINE INDENT print ( rev ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 combinations \u2581 exist \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 4 , 7 , 8 ] NEW_LINE findMinNum ( arr , 5 ) NEW_LINE"} +{"text":"Finding a Non Transitive Co | Function to return gcd of a and b ; function to check for gcd ; a and b are coprime if their gcd is 1. ; Checks if any possible triplet ( a , b , c ) satifying the condition that ( a , b ) is coprime , ( b , c ) is coprime but ( a , c ) isnt ; Generate and check for all possible triplets between L and R ; if we find any such triplets set flag to true ; flag = True indicates that a pair exists between L and R ; finding possible Triplet between 2 and 10 ; finding possible Triplet between 23 and 46","code":"def gcd ( a , b ) : NEW_LINE INDENT if ( a == 0 ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT return gcd ( b % a , a ) ; NEW_LINE DEDENT def coprime ( a , b ) : NEW_LINE INDENT return ( gcd ( a , b ) == 1 ) ; NEW_LINE DEDENT def possibleTripletInRange ( L , R ) : NEW_LINE INDENT flag = False ; NEW_LINE possibleA = 0 ; NEW_LINE possibleB = 0 ; NEW_LINE possibleC = 0 ; NEW_LINE for a in range ( L , R + 1 ) : NEW_LINE INDENT for b in range ( a + 1 , R + 1 ) : NEW_LINE INDENT for c in range ( b + 1 , R + 1 ) : NEW_LINE INDENT if ( coprime ( a , b ) and coprime ( b , c ) and coprime ( a , c ) == False ) : NEW_LINE INDENT flag = True ; NEW_LINE possibleA = a ; NEW_LINE possibleB = b ; NEW_LINE possibleC = c ; NEW_LINE break ; NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( flag == True ) : NEW_LINE INDENT print ( \" ( \" , possibleA , \" , \" , possibleB , \" , \" , possibleC , \" ) \u2581 is \u2581 one \u2581 such \" , \" possible \u2581 triplet \u2581 between \" , L , \" and \" , R ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 Such \u2581 Triplet \u2581 exists \u2581 between \" , L , \" and \" , R ) ; NEW_LINE DEDENT DEDENT L = 2 ; NEW_LINE R = 10 ; NEW_LINE possibleTripletInRange ( L , R ) ; NEW_LINE L = 23 ; NEW_LINE R = 46 ; NEW_LINE possibleTripletInRange ( L , R ) ; NEW_LINE"} +{"text":"Reach A and B by multiplying them with K and K ^ 2 at every step | Python 3 program to determine if A and B can be reached starting from 1 , 1 following the given steps . ; function to check is it is possible to reach A and B starting from 1 and 1 ; find the cuberoot of the number ; divide the number by cuberoot ; if it is a perfect cuberoot and divides a and b ; Driver Code","code":"import numpy as np NEW_LINE def possibleToReach ( a , b ) : NEW_LINE INDENT c = np . cbrt ( a * b ) NEW_LINE re1 = a \/\/ c NEW_LINE re2 = b \/\/ c NEW_LINE if ( ( re1 * re1 * re2 == a ) and ( re2 * re2 * re1 == b ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = 60 NEW_LINE B = 450 NEW_LINE if ( possibleToReach ( A , B ) ) : NEW_LINE INDENT print ( \" yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" no \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Undulating numbers | Python3 program to check whether a number is undulating or not ; Considering the definition with restriction that there should be at least 3 digits ; Check if all alternate digits are same or not . ; Driver Code","code":"def isUndulating ( n ) : NEW_LINE INDENT if ( len ( n ) <= 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , len ( n ) ) : NEW_LINE INDENT if ( n [ i - 2 ] != n [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT n = \"1212121\" NEW_LINE if ( isUndulating ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Program to find the sum of a Series ( 1 * 1 ) + ( 2 * 2 ) + ( 3 * 3 ) + ( 4 * 4 ) + ( 5 * 5 ) + ... + ( n * n ) | Function to calculate the following series ; Driver Code","code":"def Series ( n ) : NEW_LINE INDENT sums = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sums += ( i * i ) ; NEW_LINE DEDENT return sums NEW_LINE DEDENT n = 3 NEW_LINE res = Series ( n ) NEW_LINE print ( res ) NEW_LINE"} +{"text":"Count numbers with unit digit k in given range | Efficient python program to count numbers with last digit as k in given range . ; Returns count of numbers with k as last digit . ; Driver Code","code":"import math NEW_LINE def counLastDigitK ( low , high , k ) : NEW_LINE INDENT mlow = 10 * math . ceil ( low \/ 10.0 ) NEW_LINE mhigh = 10 * int ( high \/ 10.0 ) NEW_LINE count = ( mhigh - mlow ) \/ 10 NEW_LINE if ( high % 10 >= k ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( low % 10 <= k and ( low % 10 ) > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return int ( count ) NEW_LINE DEDENT low = 3 NEW_LINE high = 35 NEW_LINE k = 3 NEW_LINE print ( counLastDigitK ( low , high , k ) ) NEW_LINE"} +{"text":"Sum of all numbers divisible by 6 in a given range | function to calculate the sum of all numbers divisible by 6 in range L - R . . ; no of multiples of 6 upto r ; no of multiples of 6 upto l - 1 ; summation of all multiples of 6 upto r ; summation of all multiples of 6 upto l - 1 ; returns the answer ; driver code","code":"sdef sumDivisible ( L , R ) : NEW_LINE INDENT p = int ( R \/ 6 ) NEW_LINE q = int ( ( L - 1 ) \/ 6 ) NEW_LINE sumR = 3 * ( p * ( p + 1 ) ) NEW_LINE sumL = ( q * ( q + 1 ) ) * 3 NEW_LINE return sumR - sumL NEW_LINE DEDENT L = 1 NEW_LINE R = 20 NEW_LINE print ( sumDivisible ( L , R ) ) NEW_LINE"} +{"text":"Largest smaller number possible using only one swap operation | Python3 program to find the largest smaller number by swapping one digit . ; Returns largest possible number with one swap such that the number is smaller than str . It is assumed that there are leading 0 s . ; Traverse from right until we find a digit which is greater than its next digit . For example , in 34125 , our index is 4. ; We can also use binary search here as digits after index are sorted in increasing order . Find the biggest digit in the right of arr [ index ] which is smaller than arr [ index ] ; If index is - 1 i . e . digits are in increasing order . ; Swap both values ; Driver Code","code":"import sys NEW_LINE def prevNum ( string , n ) : NEW_LINE INDENT index = - 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if int ( string [ i ] ) > int ( string [ i + 1 ] ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT smallGreatDgt = - 1 NEW_LINE for i in range ( n - 1 , index , - 1 ) : NEW_LINE INDENT if ( smallGreatDgt == - 1 and int ( string [ i ] ) < int ( string [ index ] ) ) : NEW_LINE INDENT smallGreatDgt = i NEW_LINE DEDENT elif ( index > - 1 and int ( string [ i ] ) >= int ( string [ smallGreatDgt ] ) and int ( string [ i ] ) < int ( string [ index ] ) ) : NEW_LINE INDENT smallGreatDgt = i NEW_LINE DEDENT DEDENT if index == - 1 : NEW_LINE INDENT return \" \" . join ( \" - 1\" ) NEW_LINE DEDENT else : NEW_LINE INDENT ( string [ index ] , string [ smallGreatDgt ] ) = ( string [ smallGreatDgt ] , string [ index ] ) NEW_LINE DEDENT return \" \" . join ( string ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n_str = \"34125\" NEW_LINE ans = prevNum ( list ( n_str ) , len ( n_str ) ) NEW_LINE print ( ans ) NEW_LINE DEDENT"} +{"text":"Sgn value of a polynomial | returns value of poly [ 0 ] x ( n - 1 ) + poly [ 1 ] x ( n - 2 ) + . . + poly [ n - 1 ] ; Initialize result ; Evaluate value of polynomial using Horner 's method ; Returns sign value of polynomial ; Let us evaluate value of 2 x3 - 6 x2 + 2 x - 1 for x = 3","code":"def horner ( poly , n , x ) : NEW_LINE INDENT result = poly [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT result = ( result * x + poly [ i ] ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT def findSign ( poly , n , x ) : NEW_LINE INDENT result = horner ( poly , n , x ) ; NEW_LINE if ( result > 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT elif ( result < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT poly = [ 2 , - 6 , 2 , - 1 ] ; NEW_LINE x = 3 ; NEW_LINE n = len ( poly ) ; NEW_LINE print ( \" Sign \u2581 of \u2581 polynomial \u2581 is \u2581 \" , findSign ( poly , n , x ) ) ; NEW_LINE"} +{"text":"Insert minimum number in array so that sum of array becomes prime | Python3 program to find minimum number to insert in array so their sum is prime ; function to calculate prime using sieve of eratosthenes ; Find prime number greater than a number ; find prime greater than n ; check if num is prime ; Increment num ; To find number to be added so sum of array is prime ; call sieveOfEratostheneses to calculate primes ; To find sum of array elements ; If sum is already prime return 0 ; To find prime number greater than sum ; Return difference of sum and num ; Driver code","code":"isPrime = [ 1 ] * 100005 NEW_LINE def sieveOfEratostheneses ( ) : NEW_LINE INDENT isPrime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i < 100005 : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT j = 2 * i NEW_LINE while j < 100005 : NEW_LINE INDENT isPrime [ j ] = False NEW_LINE j += i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return NEW_LINE DEDENT def findPrime ( n ) : NEW_LINE INDENT num = n + 1 NEW_LINE while ( num ) : NEW_LINE INDENT if isPrime [ num ] : NEW_LINE INDENT return num NEW_LINE DEDENT num += 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def minNumber ( arr ) : NEW_LINE INDENT sieveOfEratostheneses ( ) NEW_LINE s = 0 NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT s += arr [ i ] NEW_LINE DEDENT if isPrime [ s ] == True : NEW_LINE INDENT return 0 NEW_LINE DEDENT num = findPrime ( s ) NEW_LINE return num - s NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 8 , 12 ] NEW_LINE print ( minNumber ( arr ) ) NEW_LINE"} +{"text":"Sum of all Subarrays | Set 1 | Computes sum all sub - array ; Pick starting point ; Pick ending point ; sum subarray between current starting and ending points ; driver program","code":"def SubArraySum ( arr , n ) : NEW_LINE INDENT temp , result = 0 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT temp = 0 ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT temp += arr [ j ] NEW_LINE result += temp NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Sum \u2581 of \u2581 SubArray \u2581 : \" , SubArraySum ( arr , n ) ) NEW_LINE"} +{"text":"Highest power of 2 less than or equal to given number | Python3 program to find highest power of 2 smaller than or equal to n . ; Driver code","code":"import math NEW_LINE def highestPowerof2 ( n ) : NEW_LINE INDENT p = int ( math . log ( n , 2 ) ) ; NEW_LINE return int ( pow ( 2 , p ) ) ; NEW_LINE DEDENT n = 10 ; NEW_LINE print ( highestPowerof2 ( n ) ) ; NEW_LINE"} +{"text":"Find ( a ^ b ) % m where ' a ' is very large | Python program to find ( a ^ b ) mod m for a large 'a ; utility function to calculate a % m ; convert string s [ i ] to integer which gives the digit value and form the number ; Returns find ( a ^ b ) % m ; Find a % m ; now multiply ans by b - 1 times and take mod with m ; Driver program to run the case","code":"' NEW_LINE def aModM ( s , mod ) : NEW_LINE INDENT number = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT number = ( number * 10 + int ( s [ i ] ) ) NEW_LINE number = number % m NEW_LINE DEDENT return number NEW_LINE DEDENT def ApowBmodM ( a , b , m ) : NEW_LINE INDENT ans = aModM ( a , m ) NEW_LINE mul = ans NEW_LINE for i in range ( 1 , b ) : NEW_LINE INDENT ans = ( ans * mul ) % m NEW_LINE DEDENT return ans NEW_LINE DEDENT a = \"987584345091051645734583954832576\" NEW_LINE b , m = 3 , 11 NEW_LINE print ApowBmodM ( a , b , m ) NEW_LINE"} +{"text":"Lagrange 's Interpolation | To represent a data point corresponding to x and y = f ( x ) ; function to interpolate the given data points using Lagrange 's formula xi -> corresponds to the new data point whose value is to be obtained n -> represents the number of known data points ; Initialize result ; Compute individual terms of above formula ; Add current term to result ; Driver Code ; creating an array of 4 known data points ; Using the interpolate function to obtain a data point corresponding to x = 3","code":"class Data : NEW_LINE INDENT def __init__ ( self , x , y ) : NEW_LINE INDENT self . x = x NEW_LINE self . y = y NEW_LINE DEDENT DEDENT def interpolate ( f : list , xi : int , n : int ) -> float : NEW_LINE INDENT result = 0.0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT term = f [ i ] . y NEW_LINE for j in range ( n ) : NEW_LINE INDENT if j != i : NEW_LINE INDENT term = term * ( xi - f [ j ] . x ) \/ ( f [ i ] . x - f [ j ] . x ) NEW_LINE DEDENT DEDENT result += term NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT f = [ Data ( 0 , 2 ) , Data ( 1 , 3 ) , Data ( 2 , 12 ) , Data ( 5 , 147 ) ] NEW_LINE print ( \" Value \u2581 of \u2581 f ( 3 ) \u2581 is \u2581 : \" , interpolate ( f , 3 , 4 ) ) NEW_LINE DEDENT"} +{"text":"Sieve of Sundaram to print all primes smaller than n | Prints all prime numbers smaller ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than n , we reduce n to half ; This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j Initialize all elements as not marked ; Main logic of Sundaram . Mark all numbers of the form i + j + 2 ij as true where 1 <= i <= j ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Driver Code","code":"def SieveOfSundaram ( n ) : NEW_LINE INDENT nNew = int ( ( n - 1 ) \/ 2 ) ; NEW_LINE marked = [ 0 ] * ( nNew + 1 ) ; NEW_LINE for i in range ( 1 , nNew + 1 ) : NEW_LINE INDENT j = i ; NEW_LINE while ( ( i + j + 2 * i * j ) <= nNew ) : NEW_LINE INDENT marked [ i + j + 2 * i * j ] = 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT print ( 2 , end = \" \u2581 \" ) ; NEW_LINE DEDENT for i in range ( 1 , nNew + 1 ) : NEW_LINE INDENT if ( marked [ i ] == 0 ) : NEW_LINE INDENT print ( ( 2 * i + 1 ) , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT DEDENT n = 20 ; NEW_LINE SieveOfSundaram ( n ) ; NEW_LINE"} +{"text":"Construct original array starting with K from an array of XOR of all elements except elements at same index | Function to construct an array with each element equal to XOR of all array elements except the element at the same index ; Original array ; Stores Bitwise XOR of array ; Calculate XOR of all array elements ; Print the original array B ; Driver Code ; Function Call","code":"def constructArray ( A , N , K ) : NEW_LINE INDENT B = [ 0 ] * N ; NEW_LINE totalXOR = A [ 0 ] ^ K ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT B [ i ] = totalXOR ^ A [ i ] ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( B [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 13 , 14 , 10 , 6 ] ; NEW_LINE K = 2 ; NEW_LINE N = len ( A ) ; NEW_LINE constructArray ( A , N , K ) ; NEW_LINE DEDENT"} +{"text":"Find extra element in the second array | Function to return the extra element in B [ ] ; To store the result ; Find the XOR of all the element of array A [ ] and array B [ ] ; Driver code","code":"def extraElement ( A , B , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans ^= A [ i ] ; NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT ans ^= B [ i ] ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT A = [ 10 , 15 , 5 ] ; NEW_LINE B = [ 10 , 100 , 15 , 5 ] ; NEW_LINE n = len ( A ) ; NEW_LINE print ( extraElement ( A , B , n ) ) ; NEW_LINE"} +{"text":"Hamming distance between two Integers | Function to calculate hamming distance ; Driver code","code":"def hammingDistance ( n1 , n2 ) : NEW_LINE INDENT x = n1 ^ n2 NEW_LINE setBits = 0 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT setBits += x & 1 NEW_LINE x >>= 1 NEW_LINE DEDENT return setBits NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 9 NEW_LINE n2 = 14 NEW_LINE print ( hammingDistance ( 9 , 14 ) ) NEW_LINE DEDENT"} +{"text":"Print bitwise AND set of a number N | function to find bitwise subsets Naive approach ; Driver code","code":"def printSubsets ( n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT if ( ( n & i ) == i ) : NEW_LINE INDENT print ( i , \" \u2581 \" , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT n = 9 NEW_LINE printSubsets ( n ) NEW_LINE"} +{"text":"Find most significant set bit of a number | Python program to find MSB number for given n . ; To find the position of the most significant set bit ; To return the value of the number with set bit at k - th position ; Driver code","code":"import math NEW_LINE def setBitNumber ( n ) : NEW_LINE INDENT k = int ( math . log ( n , 2 ) ) NEW_LINE return 1 << k NEW_LINE DEDENT n = 273 NEW_LINE print ( setBitNumber ( n ) ) NEW_LINE"} +{"text":"Minimum number of subsets with distinct elements | function to count subsets such that all subsets have distinct elements . ; take input and initialize res = 0 ; sort the array ; traverse the input array and find maximum frequency ; for each number find its repetition \/ frequency ; update res ; Driver code","code":"def subset ( ar , n ) : NEW_LINE INDENT res = 0 NEW_LINE ar . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ar [ i ] == ar [ i + 1 ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT res = max ( res , count ) NEW_LINE DEDENT return res NEW_LINE DEDENT ar = [ 5 , 6 , 9 , 3 , 4 , 3 , 4 ] NEW_LINE n = len ( ar ) NEW_LINE print ( subset ( ar , n ) ) NEW_LINE"} +{"text":"Minimum number of subsets with distinct elements | Function to count subsets such that all subsets have distinct elements . ; Traverse the input array and store frequencies of elements ; Find the maximum value in map . ; Driver code","code":"def subset ( arr , n ) : NEW_LINE INDENT mp = { i : 0 for i in range ( 10 ) } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT res = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT res = max ( res , value ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 9 , 3 , 4 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( subset ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Count ways to represent a number as sum of perfect squares | ''Store perfect squares less than or equal to N ; ''Utility function to calculate perfect squares less than or equal to N ; ''Function to find the number of ways to represent a number as sum of perfect squares ; '' Handle the base cases ; '' Include the i-th index element ; '' Exclude the i-th index element ; '' Return the result ; ''Driver Code ; '' Given Input ; '' Precalculate perfect squares <= N ; '' Function Call","code":"psquare = [ ] NEW_LINE def calcPsquare ( N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT psquare . append ( i * i ) NEW_LINE DEDENT DEDENT def countWays ( index , target ) : NEW_LINE INDENT if ( target == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( index < 0 or target < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT inc = countWays ( index , target - psquare [ index ] ) NEW_LINE exc = countWays ( index - 1 , target ) NEW_LINE return inc + exc NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE calcPsquare ( N ) NEW_LINE print ( countWays ( len ( psquare ) - 1 , N ) ) NEW_LINE DEDENT"} +{"text":"Sum of distances of all nodes from a given node | ''Stores the sum of distances of all nodes from the given node ; ''Structure of a binary tree node ; ''Function to count the number of nodes in the left and right subtrees ; '' Initialize a pair that stores the pair {number of nodes, depth} ; '' Finding the number of nodes in the left subtree ; '' Find the number of nodes in the right subtree ; '' Filling up size field ; ''Function to find the total distance ; '' If target node matches with the current node ; '' If root.left is not null ; '' Update sum ; '' Recur for the left subtree ; '' If root.right is not null ; '' Apply the formula given in the approach ; '' Recur for the right subtree ; ''Driver Code ; '' Input tree ; '' Total number of nodes ; '' Print the sum of distances","code":"sum = 0 NEW_LINE class TreeNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . size = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumofsubtree ( root ) : NEW_LINE INDENT p = [ 1 , 0 ] NEW_LINE if ( root . left ) : NEW_LINE INDENT ptemp = sumofsubtree ( root . left ) NEW_LINE p [ 1 ] += ptemp [ 0 ] + ptemp [ 1 ] NEW_LINE p [ 0 ] += ptemp [ 0 ] NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT ptemp = sumofsubtree ( root . right ) NEW_LINE p [ 1 ] += ptemp [ 0 ] + ptemp [ 1 ] NEW_LINE p [ 0 ] += ptemp [ 0 ] NEW_LINE DEDENT root . size = p [ 0 ] NEW_LINE return p NEW_LINE DEDENT def distance ( root , target , distancesum , n ) : NEW_LINE INDENT global sum NEW_LINE if ( root . data == target ) : NEW_LINE INDENT sum = distancesum NEW_LINE DEDENT if ( root . left ) : NEW_LINE INDENT tempsum = ( distancesum - root . left . size + ( n - root . left . size ) ) NEW_LINE distance ( root . left , target , tempsum , n ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT tempsum = ( distancesum - root . right . size + ( n - root . right . size ) ) NEW_LINE distance ( root . right , target , tempsum , n ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 1 ) NEW_LINE root . left = TreeNode ( 2 ) NEW_LINE root . right = TreeNode ( 3 ) NEW_LINE root . left . left = TreeNode ( 4 ) NEW_LINE root . left . right = TreeNode ( 5 ) NEW_LINE root . right . left = TreeNode ( 6 ) NEW_LINE root . right . right = TreeNode ( 7 ) NEW_LINE root . left . left . left = TreeNode ( 8 ) NEW_LINE root . left . left . right = TreeNode ( 9 ) NEW_LINE target = 3 NEW_LINE p = sumofsubtree ( root ) NEW_LINE totalnodes = p [ 0 ] NEW_LINE distance ( root , target , p [ 1 ] , totalnodes ) NEW_LINE print ( sum ) NEW_LINE DEDENT"} +{"text":"Rearrange array such that sum of same indexed elements is atmost K | ''Function to rearrange array such that sum of similar indexed elements does not exceed K ; '' Sort the array B[] in descending order ; '' If condition fails ; '' Print the array ; ''Driver Code ; '' Given arrays","code":"def rearrangeArray ( A , B , N , K ) : NEW_LINE INDENT B . sort ( reverse = True ) NEW_LINE flag = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] + B [ i ] > K ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( B [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 2 ] NEW_LINE B = [ 1 , 2 , 3 , 1 , 1 ] NEW_LINE N = len ( A ) NEW_LINE K = 5 ; NEW_LINE rearrangeArray ( A , B , N , K ) NEW_LINE DEDENT"} +{"text":"Count rows with sum exceeding sum of the remaining Matrix | ''Function to count the number of rows whose sum exceeds the sum of elements of the remaining matrix ; '' Stores the matrix dimensions ; '' To store the result ; '' Stores the total sum of the matrix elements ; '' Calculate the total sum ; '' Traverse to check for each row ; '' Stores the sum of elements of the current row ; '' Calculate the sum of elements of the current row ; '' If sum of current row exceeds the sum of rest of the matrix ; '' Increase count ; '' Print the result ; ''Driver Code ; '' Given matrix ; '' Function call","code":"def countRows ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE count = 0 NEW_LINE totalSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT totalSum += mat [ i ] [ j ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT currSum = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT currSum += mat [ i ] [ j ] NEW_LINE DEDENT if ( currSum > totalSum - currSum ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 2 , - 1 , 5 ] , [ - 3 , 0 , - 2 ] , [ 5 , 1 , 2 ] ] NEW_LINE countRows ( mat ) NEW_LINE DEDENT"} +{"text":"Check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; Sort the array ; After sorting , check if current element is either same as previous or is one more . ; Driver code","code":"def areElementsContiguous ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] > 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if areElementsContiguous ( arr , n ) : print ( \" Yes \" ) NEW_LINE else : print ( \" No \" ) NEW_LINE"} +{"text":"Check if array contains contiguous integers with duplicates allowed | function to check whether the array contains a set of contiguous integers ; Find maximum and minimum elements . ; There should be at least m elements in array to make them contiguous . ; Create a visited array and initialize fals ; Mark elements as true . ; If any element is not marked , all elements are not contiguous . ; Driver program","code":"def areElementsContiguous ( arr , n ) : NEW_LINE INDENT max1 = max ( arr ) NEW_LINE min1 = min ( arr ) NEW_LINE m = max1 - min1 + 1 NEW_LINE if ( m > n ) : NEW_LINE INDENT return False NEW_LINE DEDENT visited = [ 0 ] * m NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT visited [ arr [ i ] - min1 ] = True NEW_LINE DEDENT for i in range ( 0 , m ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( areElementsContiguous ( arr , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Check if array contains contiguous integers with duplicates allowed | Function to check whether the array contains a set of contiguous integers ; Storing elements of ' arr [ ] ' in a hash table 'us ; As arr [ 0 ] is present in 'us ; Starting with previous smaller element of arr [ 0 ] ; If ' curr _ ele ' is present in 'us ; Increment count ; Update 'curr_ele\" ; Starting with next greater element of arr [ 0 ] ; If ' curr _ ele ' is present in 'us ; Increment count ; Update 'curr_ele\" ; Returns true if array contains a set of contiguous integers else returns false ; Driver code","code":"def areElementsContiguous ( arr ) : NEW_LINE INDENT us = set ( ) NEW_LINE for i in arr : us . add ( i ) NEW_LINE count = 1 NEW_LINE curr_ele = arr [ 0 ] - 1 NEW_LINE while curr_ele in us : NEW_LINE INDENT count += 1 NEW_LINE curr_ele -= 1 NEW_LINE DEDENT curr_ele = arr [ 0 ] + 1 NEW_LINE while curr_ele in us : NEW_LINE INDENT count += 1 NEW_LINE curr_ele += 1 NEW_LINE DEDENT return ( count == len ( us ) ) NEW_LINE DEDENT arr = [ 5 , 2 , 3 , 6 , 4 , 4 , 6 , 6 ] NEW_LINE if areElementsContiguous ( arr ) : print ( \" Yes \" ) NEW_LINE else : print ( \" No \" ) NEW_LINE"} +{"text":"Longest subarray not having more than K distinct elements | function to print the longest sub - array ; mark the element visited ; if its visited first time , then increase the counter of distinct elements by 1 ; When the counter of distinct elements increases from k , then reduce it to k ; from the left , reduce the number of time of visit ; if the reduced visited time element is not present in further segment then decrease the count of distinct elements ; increase the subsegment mark ; check length of longest sub - segment when greater then previous best then change it ; print the longest sub - segment ; Driver Code","code":"import collections NEW_LINE def longest ( a , n , k ) : NEW_LINE INDENT freq = collections . defaultdict ( int ) NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE now = 0 NEW_LINE l = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE if ( freq [ a [ i ] ] == 1 ) : NEW_LINE INDENT now += 1 NEW_LINE DEDENT while ( now > k ) : NEW_LINE INDENT freq [ a [ l ] ] -= 1 NEW_LINE if ( freq [ a [ l ] ] == 0 ) : NEW_LINE INDENT now -= 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT if ( i - l + 1 >= end - start + 1 ) : NEW_LINE INDENT end = i NEW_LINE start = l NEW_LINE DEDENT DEDENT for i in range ( start , end + 1 ) : NEW_LINE INDENT print ( a [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 6 , 5 , 1 , 2 , 3 , 2 , 1 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE longest ( a , n , k ) NEW_LINE DEDENT"} +{"text":"Check if any K ranges overlap at any point | Function that returns true if any k segments overlap at any point ; Vector to store the starting point and the ending point ; Starting points are marked by - 1 and ending points by + 1 ; Sort the vector by first element ; Stack to store the overlaps ; Get the current element ; If it is the starting point ; Push it in the stack ; It is the ending point ; Pop an element from stack ; If more than k ranges overlap ; Driver Code","code":"def kOverlap ( pairs : list , k ) : NEW_LINE INDENT vec = list ( ) NEW_LINE for i in range ( len ( pairs ) ) : NEW_LINE INDENT vec . append ( ( pairs [ 0 ] , - 1 ) ) NEW_LINE vec . append ( ( pairs [ 1 ] , 1 ) ) NEW_LINE DEDENT vec . sort ( key = lambda a : a [ 0 ] ) NEW_LINE st = list ( ) NEW_LINE for i in range ( len ( vec ) ) : NEW_LINE INDENT cur = vec [ i ] NEW_LINE if cur [ 1 ] == - 1 : NEW_LINE INDENT st . append ( cur ) NEW_LINE DEDENT else : NEW_LINE INDENT st . pop ( ) NEW_LINE DEDENT if len ( st ) >= k : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT pairs = list ( ) NEW_LINE pairs . append ( ( 1 , 3 ) ) NEW_LINE pairs . append ( ( 2 , 4 ) ) NEW_LINE pairs . append ( ( 3 , 5 ) ) NEW_LINE pairs . append ( ( 7 , 10 ) ) NEW_LINE n = len ( pairs ) NEW_LINE k = 3 NEW_LINE if kOverlap ( pairs , k ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Find smallest range containing elements from k lists | Python3 program to finds out smallest range that includes elements from each of the given sorted lists . ; array for storing the current index of list i ; This function takes an k sorted lists in the form of 2D array as an argument . It finds out smallest range that includes elements from each of the k lists . ; initializing to 0 index ; for maintaining the index of list containing the minimum element ; iterating over all the list ; if every element of list [ i ] is traversed then break the loop ; find minimum value among all the list elements pointing by the ptr [ ] array ; update the index of the list ; find maximum value among all the list elements pointing by the ptr [ ] array ; if any list exhaust we will not get any better answer , so break the while loop ; updating the minrange ; Driver code","code":"N = 5 NEW_LINE ptr = [ 0 for i in range ( 501 ) ] NEW_LINE def findSmallestRange ( arr , n , k ) : NEW_LINE INDENT i , minval , maxval , minrange , minel , maxel , flag , minind = 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 NEW_LINE for i in range ( k + 1 ) : NEW_LINE INDENT ptr [ i ] = 0 NEW_LINE DEDENT minrange = 10 ** 9 NEW_LINE while ( 1 ) : NEW_LINE INDENT minind = - 1 NEW_LINE minval = 10 ** 9 NEW_LINE maxval = - 10 ** 9 NEW_LINE flag = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( ptr [ i ] == n ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT if ( ptr [ i ] < n and arr [ i ] [ ptr [ i ] ] < minval ) : NEW_LINE INDENT minind = i NEW_LINE minval = arr [ i ] [ ptr [ i ] ] NEW_LINE DEDENT if ( ptr [ i ] < n and arr [ i ] [ ptr [ i ] ] > maxval ) : NEW_LINE INDENT maxval = arr [ i ] [ ptr [ i ] ] NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT break NEW_LINE DEDENT ptr [ minind ] += 1 NEW_LINE if ( ( maxval - minval ) < minrange ) : NEW_LINE INDENT minel = minval NEW_LINE maxel = maxval NEW_LINE minrange = maxel - minel NEW_LINE DEDENT DEDENT print ( \" The \u2581 smallest \u2581 range \u2581 is \u2581 [ \" , minel , maxel , \" ] \" ) NEW_LINE DEDENT arr = [ [ 4 , 7 , 9 , 12 , 15 ] , [ 0 , 8 , 10 , 14 , 20 ] , [ 6 , 12 , 16 , 30 , 50 ] ] NEW_LINE k = len ( arr ) NEW_LINE findSmallestRange ( arr , N , k ) NEW_LINE"} +{"text":"Find largest d in array such that a + b + c = d | function to find largest d ; sort the array in ascending order ; iterating from backwards to find the required largest d ; since all four a , b , c , d should be distinct ; if the current combination of j , k , l in the set is equal to S [ i ] return this value as this would be the largest d since we are iterating in descending order ; Driver Code","code":"def findLargestd ( S , n ) : NEW_LINE INDENT found = False NEW_LINE S . sort ( ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( i == k ) : NEW_LINE INDENT continue NEW_LINE DEDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( i == l ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( S [ i ] == S [ j ] + S [ k ] + S [ l ] ) : NEW_LINE INDENT found = True NEW_LINE return S [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if ( found == False ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT S = [ 2 , 3 , 5 , 7 , 12 ] NEW_LINE n = len ( S ) NEW_LINE ans = findLargestd ( S , n ) NEW_LINE if ( ans == - 1 ) : NEW_LINE INDENT print ( \" No \u2581 Solution \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Largest \u2581 d \u2581 such \u2581 that \u2581 a \u2581 + \u2581 b \u2581 + \" , \" c \u2581 = \u2581 d \u2581 is \" , ans ) NEW_LINE DEDENT"} +{"text":"Find largest d in array such that a + b + c = d | The function finds four elements with given sum X ; Store sums ( a + b ) of all pairs ( a , b ) in a hash table ; Traverse through all pairs and find ( d - c ) is present in hash table ; If d - c is present in hash table , ; Making sure that all elements are distinct array elements and an element is not considered more than once . ; Driver Code","code":"def findFourElements ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT mp [ arr [ i ] + arr [ j ] ] = ( i , j ) NEW_LINE DEDENT DEDENT d = - 10 ** 9 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT abs_diff = abs ( arr [ i ] - arr [ j ] ) NEW_LINE if abs_diff in mp . keys ( ) : NEW_LINE INDENT p = mp [ abs_diff ] NEW_LINE if ( p [ 0 ] != i and p [ 0 ] != j and p [ 1 ] != i and p [ 1 ] != j ) : NEW_LINE INDENT d = max ( d , max ( arr [ i ] , arr [ j ] ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return d NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 7 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE res = findFourElements ( arr , n ) NEW_LINE if ( res == - 10 ** 9 ) : NEW_LINE INDENT print ( \" No \u2581 Solution . \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT"} +{"text":"Maximize count of elements that can be selected having minimum difference between their sum and K | Function to count maximum number of elements that can be selected ; Sort he array ; Traverse the array ; Add current element to the sum ; IF sum exceeds k ; Increment count ; Return the count ; Driver code ; Function call","code":"def CountMaximum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE Sum , count = 0 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE if ( Sum > k ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 30 , 30 , 10 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE k = 50 NEW_LINE print ( CountMaximum ( arr , n , k ) ) NEW_LINE"} +{"text":"Program for array rotation | Function to left Rotate arr [ ] of size n by 1 ; Function to left rotate arr [ ] of size n by d ; utility function to print an array ; Driver program to test above functions","code":"def leftRotatebyOne ( arr , n ) : NEW_LINE INDENT temp = arr [ 0 ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i + 1 ] NEW_LINE DEDENT arr [ n - 1 ] = temp NEW_LINE DEDENT def leftRotate ( arr , d , n ) : NEW_LINE INDENT for i in range ( d ) : NEW_LINE INDENT leftRotatebyOne ( arr , n ) NEW_LINE DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( \" % \u2581 d \" % arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE leftRotate ( arr , 2 , 7 ) NEW_LINE printArray ( arr , 7 ) NEW_LINE"} +{"text":"Sort the array in a given index range | Function to sort the elements of the array from index a to index b ; Variables to store start and end of the index range ; Temporary array ; Sort the temporary array ; Modifying original array with temporary array elements ; Print the modified array ; Driver code ; length of the array","code":"def partSort ( arr , N , a , b ) : NEW_LINE INDENT l = min ( a , b ) NEW_LINE r = max ( a , b ) NEW_LINE temp = [ 0 for i in range ( r - l + 1 ) ] NEW_LINE j = 0 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT temp [ j ] = arr [ i ] NEW_LINE j += 1 NEW_LINE DEDENT temp . sort ( reverse = False ) NEW_LINE j = 0 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT arr [ i ] = temp [ j ] NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( 0 , N , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 4 , 5 , 2 ] NEW_LINE a = 1 NEW_LINE b = 4 NEW_LINE N = len ( arr ) NEW_LINE partSort ( arr , N , a , b ) NEW_LINE DEDENT"} +{"text":"Sorting rows of matrix in descending order followed by columns in ascending order | Python 3 implementation to sort the rows of matrix in descending order followed by sorting the columns in ascending order ; function to sort each row of the matrix according to the order specified by descending . ; function to find transpose of the matrix ; swapping element at index ( i , j ) by element at index ( j , i ) ; function to sort the matrix row - wise and column - wise ; sort rows of mat [ ] [ ] in descending order ; get transpose of mat [ ] [ ] ; again sort rows of mat [ ] [ ] in ascending order . ; again get transpose of mat [ ] [ ] ; function to print the matrix ; Driver code","code":"MAX_SIZE = 10 NEW_LINE def sortByRow ( mat , n , descending ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( descending == True ) : NEW_LINE INDENT mat [ i ] . sort ( reverse = True ) NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] . sort ( ) NEW_LINE DEDENT DEDENT DEDENT def transpose ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT mat [ i ] [ j ] , mat [ j ] [ i ] = mat [ j ] [ i ] , mat [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT def sortMatRowAndColWise ( mat , n ) : NEW_LINE INDENT sortByRow ( mat , n , True ) NEW_LINE transpose ( mat , n ) NEW_LINE sortByRow ( mat , n , False ) NEW_LINE transpose ( mat , n ) ; NEW_LINE DEDENT def printMat ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 NEW_LINE mat = [ [ 3 , 2 , 1 ] , [ 9 , 8 , 7 ] , [ 6 , 5 , 4 ] ] NEW_LINE print ( \" Original \u2581 Matrix : \u2581 \" ) NEW_LINE printMat ( mat , n ) NEW_LINE sortMatRowAndColWise ( mat , n ) NEW_LINE print ( \" Matrix \u2581 After \u2581 Sorting : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE DEDENT"} +{"text":"Move all zeroes to end of array | Function which pushes all zeros to end of an array . ; Count of non - zero elements ; Traverse the array . If element encountered is non - zero , then replace the element at index ' count ' with this element ; here count is incremented ; Now all non - zero elements have been shifted to front and ' count ' is set as index of first 0. Make all elements 0 from count to end . ; Driver code","code":"def pushZerosToEnd ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] != 0 : NEW_LINE INDENT arr [ count ] = arr [ i ] NEW_LINE count += 1 NEW_LINE DEDENT DEDENT while count < n : NEW_LINE INDENT arr [ count ] = 0 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 9 , 8 , 4 , 0 , 0 , 2 , 7 , 0 , 6 , 0 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE pushZerosToEnd ( arr , n ) NEW_LINE print ( \" Array \u2581 after \u2581 pushing \u2581 all \u2581 zeros \u2581 to \u2581 end \u2581 of \u2581 array : \" ) NEW_LINE print ( arr ) NEW_LINE"} +{"text":"Move all zeroes to end of array | Set | function to move all zeroes at the end of array ; Count of non - zero elements ; Traverse the array . If arr [ i ] is non - zero , then swap the element at index ' count ' with the element at index 'i ; function to print the array elements ; Driver program to test above","code":"def moveZerosToEnd ( arr , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT arr [ count ] , arr [ i ] = arr [ i ] , arr [ count ] NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 0 , 1 , 9 , 8 , 4 , 0 , 0 , 2 , 7 , 0 , 6 , 0 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Original \u2581 array : \" , end = \" \u2581 \" ) NEW_LINE printArray ( arr , n ) NEW_LINE moveZerosToEnd ( arr , n ) NEW_LINE print ( \" Modified array : \" , \u2581 end = \" \" ) NEW_LINE printArray ( arr , n ) NEW_LINE"} +{"text":"Double the first element and move zero to end | function which pushes all zeros to end of an array . ; Count of non - zero elements ; Traverse the array . If element encountered is non - zero , then replace the element at index ' count ' with this element ; here count is incremented ; Now all non - zero elements have been shifted to front and ' count ' is set as index of first 0. Make all elements 0 from count to end . ; function to rearrange the array elements after modification ; if ' arr [ ] ' contains a single element only ; traverse the array ; if true , perform the required modification ; double current index value ; put 0 in the next index ; increment by 1 so as to move two indexes ahead during loop iteration ; push all the zeros at the end of 'arr[] ; function to print the array elements ; Driver program to test above","code":"def pushZerosToEnd ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] != 0 : NEW_LINE INDENT arr [ count ] = arr [ i ] NEW_LINE count += 1 NEW_LINE DEDENT DEDENT while ( count < n ) : NEW_LINE INDENT arr [ count ] = 0 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT def modifyAndRearrangeArr ( ar , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) and ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT arr [ i ] = 2 * arr [ i ] NEW_LINE arr [ i + 1 ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT pushZerosToEnd ( arr , n ) NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 0 , 2 , 2 , 2 , 0 , 6 , 6 , 0 , 0 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Original \u2581 array : \" , end = \" \u2581 \" ) NEW_LINE printArray ( arr , n ) NEW_LINE modifyAndRearrangeArr ( arr , n ) NEW_LINE print ( \" Modified array : \" , end = \" \" ) NEW_LINE printArray ( arr , n ) NEW_LINE"} +{"text":"Double the first element and move zero to end | shift all zero to left side of an array ; Maintain last index with positive value ; If Element is non - zero ; swap current index , with lastSeen non - zero ; next element will be last seen non - zero","code":"def shiftAllZeroToLeft ( arr , n ) : NEW_LINE INDENT lastSeenNonZero = 0 NEW_LINE for index in range ( 0 , n ) : NEW_LINE INDENT if ( array [ index ] != 0 ) : NEW_LINE INDENT array [ index ] , array [ lastSeenNonZero ] = array [ lastSeenNonZero ] , array [ index ] NEW_LINE lastSeenNonZero += 1 NEW_LINE DEDENT DEDENT DEDENT"} +{"text":"Rearrange positive and negative numbers with constant extra space | A utility function to print an array of size n ; Function to Rearrange positive and negative numbers in a array ; if current element is positive do nothing ; if current element is negative , shift positive elements of arr [ 0. . i - 1 ] , to one position to their right ; Put negative element at its right position ; Driver Code","code":"def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def RearrangePosNeg ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT key = arr [ i ] NEW_LINE if ( key > 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT j = i - 1 NEW_LINE while ( j >= 0 and arr [ j ] > 0 ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT arr [ j + 1 ] = key NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE RearrangePosNeg ( arr , n ) NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT"} +{"text":"Rearrange positive and negative numbers with constant extra space | Function to print an array ; Function to reverse an array . An array can be reversed in O ( n ) time and O ( 1 ) space . ; Merges two subarrays of arr [ ] . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] ; Initial index of 1 st subarray ; Initial index of IInd ; arr [ i . . m ] is positive ; arr [ j . . r ] is positive reverse positive part of left sub - array ( arr [ i . . m ] ) ; reverse negative part of right sub - array ( arr [ m + 1. . j - 1 ] ) ; reverse arr [ i . . j - 1 ] ; Function to Rearrange positive and negative numbers in a array ; Same as ( l + r ) \/ 2 , but avoids overflow for large l and h ; Sort first and second halves ; Driver Code","code":"def printArray ( A , size ) : NEW_LINE INDENT for i in range ( 0 , size ) : NEW_LINE INDENT print ( A [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def reverse ( arr , l , r ) : NEW_LINE INDENT if l < r : NEW_LINE INDENT arr [ l ] , arr [ r ] = arr [ r ] , arr [ l ] NEW_LINE l , r = l + 1 , r - 1 NEW_LINE reverse ( arr , l , r ) NEW_LINE DEDENT DEDENT def merge ( arr , l , m , r ) : NEW_LINE INDENT i = l NEW_LINE j = m + 1 NEW_LINE while i <= m and arr [ i ] < 0 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while j <= r and arr [ j ] < 0 : NEW_LINE INDENT j += 1 NEW_LINE DEDENT reverse ( arr , i , m ) NEW_LINE reverse ( arr , m + 1 , j - 1 ) NEW_LINE reverse ( arr , i , j - 1 ) NEW_LINE DEDENT def RearrangePosNeg ( arr , l , r ) : NEW_LINE INDENT if l < r : NEW_LINE INDENT m = l + ( r - l ) \/\/ 2 NEW_LINE RearrangePosNeg ( arr , l , m ) NEW_LINE RearrangePosNeg ( arr , m + 1 , r ) NEW_LINE merge ( arr , l , m , r ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ] NEW_LINE arr_size = len ( arr ) NEW_LINE RearrangePosNeg ( arr , 0 , arr_size - 1 ) NEW_LINE printArray ( arr , arr_size ) NEW_LINE DEDENT"} +{"text":"Rearrange positive and negative numbers with constant extra space | Python implementation of the above approach ; Loop until arr [ i ] < 0 and still inside the array ; Loop until arr [ j ] > 0 and still inside the array ; if i is less than j ; Driver Code","code":"def RearrangePosNeg ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while ( True ) : NEW_LINE INDENT while ( arr [ i ] < 0 and i < n ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( arr [ j ] > 0 and j >= 0 ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( i < j ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT arr = [ - 12 , 11 , - 13 , - 5 , 6 , - 7 , 5 , - 3 , - 6 ] NEW_LINE n = len ( arr ) NEW_LINE RearrangePosNeg ( arr , n ) NEW_LINE print ( * arr ) NEW_LINE"} +{"text":"Find the player to be able to replace the last element that can be replaced by its divisors | Function to find the winner of the game played based on given conditions ; A wins if size of array is odd ; Otherwise , B wins ; Driver Code ; Input array ; Size of the array","code":"def winner ( arr , N ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT print ( \" A \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" B \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 24 , 45 , 45 , 24 ] NEW_LINE N = len ( arr ) NEW_LINE winner ( arr , N ) NEW_LINE DEDENT"} +{"text":"Queries to calculate sum of array elements present at every Yth index starting from the index X | python program for the above approach ; Function to sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all possible values of X and Y , where Y is less than or equal to sqrt ( N ) . ; Iterate over all possible values of X ; Precompute for all possible values of an expression such that y <= sqrt ( N ) ; If i + j less than N ; Update dp [ i ] [ j ] ; Update dp [ i ] [ j ] ; Function to Find the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all queries ; dp [ x ] [ y ] : Stores sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; Traverse the query array , Q [ ] [ ] ; If y is less than or equal to sqrt ( N ) ; Stores the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; Traverse the array , arr [ ] ; Update sum ; Update x ; Driver Code","code":"import math NEW_LINE sz = 20 NEW_LINE sqr = int ( math . sqrt ( sz ) ) + 1 NEW_LINE def precomputeExpressionForAllVal ( arr , N , dp ) : NEW_LINE INDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( 1 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( i + j < N ) : NEW_LINE INDENT dp [ i ] [ j ] = arr [ i ] + dp [ i + j ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def querySum ( arr , N , Q , M ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( sz ) ] for x in range ( sqr ) ] NEW_LINE precomputeExpressionForAllVal ( arr , N , dp ) NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT x = Q [ i ] [ 0 ] NEW_LINE y = Q [ i ] [ 1 ] NEW_LINE if ( y <= math . sqrt ( N ) ) : NEW_LINE INDENT print ( dp [ x ] [ y ] ) NEW_LINE continue NEW_LINE DEDENT sum = 0 NEW_LINE while ( x < N ) : NEW_LINE INDENT sum += arr [ x ] NEW_LINE x += y NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 7 , 5 , 4 ] NEW_LINE Q = [ [ 2 , 1 ] , [ 3 , 2 ] ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( Q [ 0 ] ) NEW_LINE querySum ( arr , N , Q , M ) NEW_LINE"} +{"text":"Find all elements in array which have at | Python3 program to find all elements in array which have at - least two greater elements itself . ; Pick elements one by one and count greater elements . If count is more than 2 , print that element . ; Driver code","code":"def findElements ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if arr [ j ] > arr [ i ] : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT if count >= 2 : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 2 , - 6 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findElements ( arr , n ) NEW_LINE"} +{"text":"Find all elements in array which have at | Sorting based Python 3 program to find all elements in array which have atleast two greater elements itself . ; Driven source","code":"def findElements ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 2 , - 6 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findElements ( arr , n ) NEW_LINE"} +{"text":"Find all elements in array which have at | Python3 program to find all elements in array which have atleast two greater elements itself . ; If current element is smaller than first then update both first and second ; If arr [ i ] is in between first and second then update second ; Driver code","code":"import sys NEW_LINE def findElements ( arr , n ) : NEW_LINE INDENT first = - sys . maxsize NEW_LINE second = - sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > second ) : NEW_LINE INDENT second = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] < second ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 2 , - 6 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findElements ( arr , n ) NEW_LINE"} +{"text":"Minimize count of increments of each element of subarrays required to make Array non | Function to find the minimum number of operations required to make the array non - increasing ; Stores the count of required operations ; If arr [ i ] > arr [ i + 1 ] , no increments required . Otherwise , add their difference to the answer ; Return the result res ; Driver Code","code":"def getMinOps ( arr ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT res += max ( arr [ i + 1 ] - arr [ i ] , 0 ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 1 , 2 ] NEW_LINE print ( getMinOps ( arr ) ) NEW_LINE"} +{"text":"Find the smallest missing number | function that returns smallest elements missing in a sorted array . ; Left half has all elements from 0 to mid ; driver program to test above function","code":"def findFirstMissing ( array , start , end ) : NEW_LINE INDENT if ( start > end ) : NEW_LINE INDENT return end + 1 NEW_LINE DEDENT if ( start != array [ start ] ) : NEW_LINE INDENT return start ; NEW_LINE DEDENT mid = int ( ( start + end ) \/ 2 ) NEW_LINE if ( array [ mid ] == mid ) : NEW_LINE INDENT return findFirstMissing ( array , mid + 1 , end ) NEW_LINE DEDENT return findFirstMissing ( array , start , mid ) NEW_LINE DEDENT arr = [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Smallest \u2581 missing \u2581 element \u2581 is \" , findFirstMissing ( arr , 0 , n - 1 ) ) NEW_LINE"} +{"text":"Find the smallest missing number | Function to find missing element ; Index matches with value at that index , means missing element cannot be upto that point ; Function to find Smallest Missing in Sorted Array ; Check if 0 is missing in the array ; Check is all numbers 0 to n - 1 are prsent in array ; Driver code ; Function Call","code":"def findFirstMissing ( arr , start , end , first ) : NEW_LINE INDENT if ( start < end ) : NEW_LINE INDENT mid = int ( ( start + end ) \/ 2 ) NEW_LINE if ( arr [ mid ] != mid + first ) : NEW_LINE INDENT return findFirstMissing ( arr , start , mid , first ) NEW_LINE DEDENT else : NEW_LINE INDENT return findFirstMissing ( arr , mid + 1 , end , first ) NEW_LINE DEDENT DEDENT return start + first NEW_LINE DEDENT def findSmallestMissinginSortedArray ( arr ) : NEW_LINE INDENT if ( arr [ 0 ] != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ - 1 ] == len ( arr ) - 1 ) : NEW_LINE INDENT return len ( arr ) NEW_LINE DEDENT first = arr [ 0 ] NEW_LINE return findFirstMissing ( arr , 0 , len ( arr ) - 1 , first ) NEW_LINE DEDENT arr = [ 0 , 1 , 2 , 3 , 4 , 5 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" First \u2581 Missing \u2581 element \u2581 is \u2581 : \" , findSmallestMissinginSortedArray ( arr ) ) NEW_LINE"} +{"text":"Maximum sum such that no two elements are adjacent | Function to return max sum such that no two elements are adjacent ; Current max excluding i ( No ternary in Python ) ; Current max including i ; return max of incl and excl ; Driver program to test above function","code":"def find_max_sum ( arr ) : NEW_LINE INDENT incl = 0 NEW_LINE excl = 0 NEW_LINE for i in arr : NEW_LINE INDENT new_excl = excl if excl > incl else incl NEW_LINE incl = excl + i NEW_LINE excl = new_excl NEW_LINE DEDENT return ( excl if excl > incl else incl ) NEW_LINE DEDENT arr = [ 5 , 5 , 10 , 100 , 10 , 5 ] NEW_LINE print find_max_sum ( arr ) NEW_LINE"} +{"text":"Minimum steps to convert all top left to bottom right paths in Matrix as palindrome | Set 2 | Function for counting minimum number of changes ; Distance of elements from ( 0 , 0 ) will is i range [ 0 , n + m - 2 ] ; Store frequencies of [ 0 , 9 ] at distance i Initialize all with zero ; Count frequencies of [ 0 , 9 ] ; Increment frequency of value matrix [ i ] [ j ] at distance i + j ; Find value with max frequency and count total cells at distance i from front end and rear end ; Change all values to the value with max frequency ; Return the answer ; Driver code ; Given matrix ; Function call","code":"def countChanges ( matrix , n , m ) : NEW_LINE INDENT dist = n + m - 1 NEW_LINE freq = [ [ 0 ] * 10 for i in range ( dist ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT freq [ i + j ] [ matrix [ i ] [ j ] ] += 1 NEW_LINE DEDENT DEDENT min_changes_sum = 0 NEW_LINE for i in range ( dist \/\/ 2 ) : NEW_LINE INDENT maximum = 0 NEW_LINE total_values = 0 NEW_LINE for j in range ( 10 ) : NEW_LINE INDENT maximum = max ( maximum , freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) NEW_LINE total_values += ( freq [ i ] [ j ] + freq [ n + m - 2 - i ] [ j ] ) NEW_LINE DEDENT min_changes_sum += ( total_values - maximum ) NEW_LINE DEDENT return min_changes_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 ] , [ 3 , 5 ] ] NEW_LINE print ( countChanges ( mat , 2 , 2 ) ) NEW_LINE DEDENT"} +{"text":"Sparse Table | Python3 program to do range minimum query using sparse table ; Fills lookup array lookup [ ] [ ] in bottom up manner . ; Initialize M for the intervals with length 1 ; Compute values from smaller to bigger intervals ; Compute minimum value for all intervals with size 2 ^ j ; For arr [ 2 ] [ 10 ] , we compare arr [ lookup [ 0 ] [ 7 ] ] and arr [ lookup [ 3 ] [ 10 ] ] ; Returns minimum of arr [ L . . R ] ; Find highest power of 2 that is smaller than or equal to count of elements in given range . For [ 2 , 10 ] , j = 3 ; Compute minimum of last 2 ^ j elements with first 2 ^ j elements in range . For [ 2 , 10 ] , we compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] , ; Driver Code","code":"import math NEW_LINE def buildSparseTable ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT lookup [ i ] [ 0 ] = arr [ i ] NEW_LINE DEDENT j = 1 NEW_LINE while ( 1 << j ) <= n : NEW_LINE INDENT i = 0 NEW_LINE while ( i + ( 1 << j ) - 1 ) < n : NEW_LINE INDENT if ( lookup [ i ] [ j - 1 ] < lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ) : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT def query ( L , R ) : NEW_LINE INDENT j = int ( math . log2 ( R - L + 1 ) ) NEW_LINE if lookup [ L ] [ j ] <= lookup [ R - ( 1 << j ) + 1 ] [ j ] : NEW_LINE INDENT return lookup [ L ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT return lookup [ R - ( 1 << j ) + 1 ] [ j ] NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 7 , 2 , 3 , 0 , 5 , 10 , 3 , 12 , 18 ] NEW_LINE n = len ( a ) NEW_LINE MAX = 500 NEW_LINE lookup = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE buildSparseTable ( a , n ) NEW_LINE print ( query ( 0 , 4 ) ) NEW_LINE print ( query ( 4 , 7 ) ) NEW_LINE print ( query ( 7 , 8 ) ) NEW_LINE DEDENT"} +{"text":"Sparse Table | Python3 program to do range minimum query using sparse table ; Fills lookup array lookup [ ] [ ] in bottom up manner . ; GCD of single element is element itself ; Build sparse table ; Returns minimum of arr [ L . . R ] ; Find highest power of 2 that is smaller than or equal to count of elements in given range . For [ 2 , 10 ] , j = 3 ; Compute GCD of last 2 ^ j elements with first 2 ^ j elements in range . For [ 2 , 10 ] , we find GCD of arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] , ; Driver Code","code":"import math NEW_LINE def buildSparseTable ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT table [ i ] [ 0 ] = arr [ i ] NEW_LINE DEDENT j = 1 NEW_LINE while ( 1 << j ) <= n : NEW_LINE INDENT i = 0 NEW_LINE while i <= n - ( 1 << j ) : NEW_LINE INDENT table [ i ] [ j ] = math . gcd ( table [ i ] [ j - 1 ] , table [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ) NEW_LINE i += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT def query ( L , R ) : NEW_LINE INDENT j = int ( math . log2 ( R - L + 1 ) ) NEW_LINE return math . gcd ( table [ L ] [ j ] , table [ R - ( 1 << j ) + 1 ] [ j ] ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 7 , 2 , 3 , 0 , 5 , 10 , 3 , 12 , 18 ] NEW_LINE n = len ( a ) NEW_LINE MAX = 500 NEW_LINE table = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE buildSparseTable ( a , n ) NEW_LINE print ( query ( 0 , 2 ) ) NEW_LINE print ( query ( 1 , 3 ) ) NEW_LINE print ( query ( 4 , 5 ) ) NEW_LINE DEDENT"} +{"text":"Lexicographically smallest array after at | Modifies arr [ 0. . n - 1 ] to lexicographically smallest with k swaps . ; Set the position where we we want to put the smallest integer ; If we exceed the Max swaps then terminate the loop ; Find the minimum value from i + 1 to max ( k or n ) ; Swap the elements from Minimum position we found till now to the i index ; Set the final value after swapping pos - i elements ; Driver Code ; ; Print the final Array","code":"def minimizeWithKSwaps ( arr , n , k ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT pos = i NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( j - i > k ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ j ] < arr [ pos ] ) : NEW_LINE INDENT pos = j NEW_LINE DEDENT DEDENT for j in range ( pos , i , - 1 ) : NEW_LINE INDENT arr [ j ] , arr [ j - 1 ] = arr [ j - 1 ] , arr [ j ] NEW_LINE DEDENT k -= pos - i NEW_LINE DEDENT DEDENT n , k = 5 , 3 NEW_LINE arr = [ 7 , 6 , 9 , 2 , 1 ] NEW_LINE \/ * Function calling * \/ NEW_LINE minimizeWithKSwaps ( arr , n , k ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT"} +{"text":"Find maximum average subarray of k length | Returns beginning index of maximum average subarray of length k ; Check if ' k ' is valid ; Create and fill array to store cumulative sum . csum [ i ] stores sum of arr [ 0 ] to arr [ i ] ; Initialize max_sm as sum of first subarray ; Find sum of other subarrays and update max_sum if required . ; Return starting index ; Driver program","code":"def findMaxAverage ( arr , n , k ) : NEW_LINE INDENT if k > n : NEW_LINE INDENT return - 1 NEW_LINE DEDENT csum = [ 0 ] * n NEW_LINE csum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT csum [ i ] = csum [ i - 1 ] + arr [ i ] ; NEW_LINE DEDENT max_sum = csum [ k - 1 ] NEW_LINE max_end = k - 1 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum = csum [ i ] - csum [ i - k ] NEW_LINE if curr_sum > max_sum : NEW_LINE INDENT max_sum = curr_sum NEW_LINE max_end = i NEW_LINE DEDENT DEDENT return max_end - k + 1 NEW_LINE DEDENT arr = [ 1 , 12 , - 5 , - 6 , 50 , 3 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( \" The \u2581 maximum \u2581 average \u2581 subarray \u2581 of \u2581 length \" , k , \" begins \u2581 at \u2581 index \" , findMaxAverage ( arr , n , k ) ) NEW_LINE"} +{"text":"Find maximum average subarray of k length | Returns beginning index of maximum average subarray of length k ; Check if ' k ' is valid ; Compute sum of first ' k ' elements ; Compute sum of remaining subarrays ; Return starting index ; Driver program","code":"def findMaxAverage ( arr , n , k ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT sum = arr [ 0 ] NEW_LINE for i in range ( 1 , k ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT max_sum = sum NEW_LINE max_end = k - 1 NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT sum = sum + arr [ i ] - arr [ i - k ] NEW_LINE if ( sum > max_sum ) : NEW_LINE INDENT max_sum = sum NEW_LINE max_end = i NEW_LINE DEDENT DEDENT return max_end - k + 1 NEW_LINE DEDENT arr = [ 1 , 12 , - 5 , - 6 , 50 , 3 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( \" The \u2581 maximum \u2581 average \u2581 subarray \u2581 of \u2581 length \" , k , \" begins \u2581 at \u2581 index \" , findMaxAverage ( arr , n , k ) ) NEW_LINE"} +{"text":"Minimum score possible for a player by selecting one or two consecutive array elements from given binary array | Stores the minimum score for each states as map < pair < pos , myturn > , ans > ; Function to find the minimum score after choosing element from array ; Return the stored state ; Base Case ; Player A 's turn ; Find the minimum score ; Store the current state ; Return the result ; Player B 's turn ; Find minimum score ; Store the current state ; Return the result ; Function that finds the minimum penality after choosing element from the given binary array ; Starting position of choosing element from array ; 0 denotes player A turn 1 denotes player B turn ; Function Call ; Print the answer for player A and B ; Minimum penalty ; Calculate sum of all arr elements ; Print the minimum score ; Driver Code","code":"m = dict ( ) NEW_LINE def findMinimum ( a , n , pos , myturn ) : NEW_LINE INDENT if ( pos , myturn ) in m : NEW_LINE INDENT return m [ ( pos , myturn ) ] ; NEW_LINE DEDENT if ( pos >= n - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( not myturn ) : NEW_LINE INDENT ans = min ( findMinimum ( a , n , pos + 1 , not myturn ) + a [ pos ] , findMinimum ( a , n , pos + 2 , not myturn ) + a [ pos ] + a [ pos + 1 ] ) ; NEW_LINE m [ ( pos , myturn ) ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT if ( myturn ) : NEW_LINE INDENT ans = min ( findMinimum ( a , n , pos + 1 , not myturn ) , findMinimum ( a , n , pos + 2 , not myturn ) ) ; NEW_LINE m [ ( pos , myturn ) ] = ans ; NEW_LINE return ans ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT def countPenality ( arr , N ) : NEW_LINE INDENT pos = 0 ; NEW_LINE turn = False ; NEW_LINE return findMinimum ( arr , N , pos , turn ) + 1 ; NEW_LINE DEDENT def printAnswer ( arr , N ) : NEW_LINE INDENT a = countPenality ( arr , N ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT print ( a ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 1 , 0 , 1 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE printAnswer ( arr , N ) ; NEW_LINE DEDENT"} +{"text":"Sum of prime numbers in range [ L , R ] from given Array for Q queries | Python3 program for the above approach ; Create a boolean array prime [ ] and initialize all entires it as true A value in prime [ i ] will finally be false if i is Not a prime ; Function to find prime numbers ; Check if prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked ; Function to get the middle index from corner indexes ; Function to get the sum of values in the given range of the array ; If segment of this node is a part of given range , then return the sum of the segment ; If segment of this node is outside the given range ; If a part of this segment overlaps with the given range ; Function to update the nodes which have the given index in their range ; If the input index lies outside the range of this segment ; If the input index is in range of this node , then update the value of the node and its children ; Function to update a value in input array and segment tree ; Check for errorneous imput index ; Get the difference between new value and old value ; Update the value in array ; Update the values of nodes in segment tree only if either previous value or new value or both are prime ; If only new value is prime ; If only old value is prime ; If both are prime ; Return sum of elements in range from index qs ( query start ) to qe ( query end ) . It mainly uses getSumUtil ( ) ; Check for erroneous input values ; Function that constructs the Segment Tree ; If there is one element in array , store it in current node of segment tree and return ; Only add those elements in segment tree which are prime ; If there are more than one elements , then recur for left and right subtrees and store the sum of values in this node ; Function to construct segment tree from given array ; Height of segment tree ; Maximum size of segment tree ; Allocate memory ; Fill the allocated memory st ; Return the constructed segment tree ; Driver code ; Function call ; Build segment tree from given array ; Print sum of values in array from index 1 to 3 ; Update : set arr [ 1 ] = 10 and update corresponding segment tree nodes ; Find sum after value is updated","code":"import math NEW_LINE MAX = 1000001 NEW_LINE prime = [ True ] * MAX NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT p = 2 NEW_LINE while p * p <= MAX : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( p * p , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def getMid ( s , e ) : NEW_LINE INDENT return s + ( e - s ) \/\/ 2 NEW_LINE DEDENT def getSumUtil ( st , ss , se , qs , qe , si ) : NEW_LINE INDENT if qs <= ss and qe >= se : NEW_LINE INDENT return st [ si ] NEW_LINE DEDENT if se < qs or ss > qe : NEW_LINE INDENT return 0 NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE return ( getSumUtil ( st , ss , mid , qs , qe , 2 * si + 1 ) + getSumUtil ( st , mid + 1 , se , qs , qe , 2 * si + 2 ) ) NEW_LINE DEDENT def updateValueUtil ( st , ss , se , i , diff , si ) : NEW_LINE INDENT if i < ss or i > se : NEW_LINE INDENT return NEW_LINE DEDENT st [ si ] = st [ si ] + diff NEW_LINE if se != ss : NEW_LINE INDENT mid = getMid ( ss , se ) NEW_LINE updateValueUtil ( st , ss , mid , i , diff , 2 * si + 1 ) NEW_LINE updateValueUtil ( st , mid + 1 , se , i , diff , 2 * si + 2 ) NEW_LINE DEDENT DEDENT def updateValue ( arr , st , n , i , new_val ) : NEW_LINE INDENT if i < 0 or i > n - 1 : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT diff = new_val - arr [ i ] NEW_LINE prev_val = arr [ i ] NEW_LINE arr [ i ] = new_val NEW_LINE if prime [ new_val ] or prime [ prev_val ] : NEW_LINE INDENT if not prime [ prev_val ] : NEW_LINE INDENT updateValueUtil ( st , 0 , n - 1 , i , new_val , 0 ) NEW_LINE DEDENT elif not prime [ new_val ] : NEW_LINE INDENT updateValueUtil ( st , 0 , n - 1 , i , - prev_val , 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT updateValueUtil ( st , 0 , n - 1 , i , diff , 0 ) NEW_LINE DEDENT DEDENT DEDENT def getSum ( st , n , qs , qe ) : NEW_LINE INDENT if qs < 0 or qe > n - 1 or qs > qe : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return getSumUtil ( st , 0 , n - 1 , qs , qe , 0 ) NEW_LINE DEDENT def constructSTUtil ( arr , ss , se , st , si ) : NEW_LINE INDENT if ss == se : NEW_LINE INDENT if prime [ arr [ ss ] ] : NEW_LINE INDENT st [ si ] = arr [ ss ] NEW_LINE DEDENT else : NEW_LINE INDENT st [ si ] = 0 NEW_LINE DEDENT return st [ si ] NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE st [ si ] = ( constructSTUtil ( arr , ss , mid , st , 2 * si + 1 ) + constructSTUtil ( arr , mid + 1 , se , st , 2 * si + 2 ) ) NEW_LINE return st [ si ] NEW_LINE DEDENT def constructST ( arr , n ) : NEW_LINE INDENT x = int ( math . ceil ( math . log2 ( n ) ) ) NEW_LINE max_size = 2 * int ( pow ( 2 , x ) ) - 1 NEW_LINE st = [ 0 ] * max_size NEW_LINE constructSTUtil ( arr , 0 , n - 1 , st , 0 ) NEW_LINE return st NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 7 , 9 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE Q = [ [ 1 , 1 , 3 ] , [ 2 , 1 , 10 ] , [ 1 , 1 , 3 ] ] NEW_LINE SieveOfEratosthenes ( ) NEW_LINE st = constructST ( arr , n ) NEW_LINE print ( getSum ( st , n , 1 , 3 ) ) NEW_LINE updateValue ( arr , st , n , 1 , 10 ) NEW_LINE print ( getSum ( st , n , 1 , 3 ) ) NEW_LINE"} +{"text":"Count the number of ways to construct the target string | Python 3 Program to Count the number of ways to construct the target string ; base case ; If current subproblem has been solved , use the value ; current character ; search through all the indiced at which the current character occurs . For each index greater than prev , take the index and move to the next position , and add to the answer . ; Store and return the solution for this subproblem ; preprocess the strings by storing for each character of every string , the index of their occurrence we will use a common list for all because of only the index matter in the string from which the character was picked ; we are storing j + 1 because the initial picked index in the recursive step will ne 0. This is just for ease of implementation ; initialise dp table . - 1 represents that the subproblem hasn 't been solve ; Driver Code","code":"mod = 1000000007 NEW_LINE dp = [ [ - 1 for i in range ( 1000 ) ] for j in range ( 1000 ) ] ; NEW_LINE def calculate ( pos , prev , s , index ) : NEW_LINE INDENT if ( pos == len ( s ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ pos ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ prev ] NEW_LINE DEDENT c = ord ( s [ pos ] ) - ord ( ' a ' ) ; NEW_LINE answer = 0 NEW_LINE for i in range ( len ( index ) ) : NEW_LINE INDENT if ( index [ i ] > prev ) : NEW_LINE INDENT answer = ( answer % mod + calculate ( pos + 1 , index [ i ] , s , index ) % mod ) % mod NEW_LINE DEDENT DEDENT dp [ pos ] [ prev ] = 4 NEW_LINE return dp [ pos ] [ prev ] NEW_LINE DEDENT def countWays ( a , s ) : NEW_LINE INDENT n = len ( a ) NEW_LINE index = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( len ( a [ i ] ) ) : NEW_LINE INDENT index [ ord ( a [ i ] [ j ] ) - ord ( ' a ' ) ] . append ( j + 1 ) ; NEW_LINE DEDENT DEDENT return calculate ( 0 , 0 , s , index [ 0 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ ] NEW_LINE A . append ( \" adc \" ) NEW_LINE A . append ( \" aec \" ) NEW_LINE A . append ( \" erg \" ) NEW_LINE S = \" ac \" NEW_LINE print ( countWays ( A , S ) ) NEW_LINE DEDENT"} +{"text":"Count of integers from the range [ 0 , N ] whose digit sum is a multiple of K | Python 3 implementation of the approach ; Function to return the count of numbers from the range [ 0 , n ] whose digit sum is a multiple of k using bottom - up dp ; The digit in this index can only be from [ 0 , num [ idx ] ] ; The digit in this index can be anything from [ 0 , 9 ] ; new_tight is the flag value for the next position ; res can 't be negative ; Function to process the string to a vector of digits from MSD to LSD ; Driver code ; For large input number n ; Total number of digits in n ; To store the states of the dp ; Process the string to a vector of digits from MSD to LSD","code":"MAX = 10005 NEW_LINE MOD = 1000000007 NEW_LINE def countNum ( idx , sum , tight , num , len1 , k ) : NEW_LINE INDENT if ( len1 == idx ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( dp [ idx ] [ sum ] [ tight ] != - 1 ) : NEW_LINE INDENT return dp [ idx ] [ sum ] [ tight ] NEW_LINE DEDENT res = 0 NEW_LINE if ( tight == 0 ) : NEW_LINE INDENT limit = num [ idx ] NEW_LINE DEDENT else : NEW_LINE INDENT limit = 9 NEW_LINE DEDENT for i in range ( limit + 1 ) : NEW_LINE INDENT new_tight = tight NEW_LINE if ( tight == 0 and i < limit ) : NEW_LINE INDENT new_tight = 1 NEW_LINE DEDENT res += countNum ( idx + 1 , ( sum + i ) % k , new_tight , num , len1 , k ) NEW_LINE res %= MOD NEW_LINE DEDENT if ( res < 0 ) : NEW_LINE INDENT res += MOD NEW_LINE DEDENT dp [ idx ] [ sum ] [ tight ] = res NEW_LINE return dp [ idx ] [ sum ] [ tight ] NEW_LINE DEDENT def process ( s ) : NEW_LINE INDENT num = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT num . append ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = \"98765432109876543210\" NEW_LINE len1 = len ( n ) NEW_LINE k = 58 NEW_LINE dp = [ [ [ - 1 for i in range ( 2 ) ] for j in range ( 101 ) ] for k in range ( MAX ) ] NEW_LINE num = process ( n ) NEW_LINE print ( countNum ( 0 , 0 , 0 , num , len1 , k ) ) NEW_LINE DEDENT"} +{"text":"Double Knapsack | Dynamic Programming | w1_r represents remaining capacity of 1 st knapsack w2_r represents remaining capacity of 2 nd knapsack i represents index of the array arr we are working on ; Base case ; Variables to store the result of three parts of recurrence relation ; Store the state in the 3D array ; Driver code ; Input array ; 3D array to store states of DP ; Number of elements in the array ; Capacity of knapsacks ; Function to be called","code":"def maxWeight ( arr , n , w1_r , w2_r , i ) : NEW_LINE INDENT if i == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ i ] [ w1_r ] [ w2_r ] != - 1 : NEW_LINE INDENT return dp [ i ] [ w1_r ] [ w2_r ] NEW_LINE DEDENT fill_w1 , fill_w2 , fill_none = 0 , 0 , 0 NEW_LINE if w1_r >= arr [ i ] : NEW_LINE INDENT fill_w1 = arr [ i ] + maxWeight ( arr , n , w1_r - arr [ i ] , w2_r , i + 1 ) NEW_LINE DEDENT if w2_r >= arr [ i ] : NEW_LINE INDENT fill_w2 = arr [ i ] + maxWeight ( arr , n , w1_r , w2_r - arr [ i ] , i + 1 ) NEW_LINE DEDENT fill_none = maxWeight ( arr , n , w1_r , w2_r , i + 1 ) NEW_LINE dp [ i ] [ w1_r ] [ w2_r ] = max ( fill_none , max ( fill_w1 , fill_w2 ) ) NEW_LINE return dp [ i ] [ w1_r ] [ w2_r ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 8 , 2 , 3 ] NEW_LINE maxN , maxW = 31 , 31 NEW_LINE dp = [ [ [ - 1 ] * maxW ] * maxW ] * maxN NEW_LINE n = len ( arr ) NEW_LINE w1 , w2 = 10 , 3 NEW_LINE print ( maxWeight ( arr , n , w1 , w2 , 0 ) ) NEW_LINE DEDENT"} +{"text":"Lexicographically largest prime path from top | Python3 implementation of above approach ; Depth First Search ; Return if cell contain non prime number or obstacle , or going out of matrix or already visited the cell or already found the lexicographical largest path ; marking cell is already visited ; storing the lexicographical largest path index ; if reached the end of the matrix ; updating the final number of steps in lexicographical largest path ; moving diagonal ( trying lexicographical largest path ) ; moving cell right to current cell ; moving cell down to current cell . ; Print lexicographical largest prime path ; To count the number of step in lexicographical largest prime path ; To store the lexicographical largest prime path index ; To mark if the cell is already traversed or not ; traversing by DFS ; printing the lexicographical largest prime path ; Return the number of prime path in ther matrix . ; for each cell ; If on the top row or leftmost column , there is no path there . ; If non prime number ; Finding the matrix mapping by considering non prime number as obstacle and prime number be valid path . ; Sieve ; If prime ; if non prime ; Driver code","code":"MAX = 105 NEW_LINE def sieve ( ) : NEW_LINE INDENT i = 2 NEW_LINE while ( i * i < MAX ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i * i , MAX , i ) : NEW_LINE INDENT prime [ j ] = 1 ; NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def dfs ( i , j , k , q , n , m ) : NEW_LINE INDENT if ( mappedMatrix [ i ] [ j ] == 0 or i > n or j > m or mark [ i ] [ j ] or q != 0 ) : NEW_LINE INDENT return q ; NEW_LINE DEDENT mark [ i ] [ j ] = 1 ; NEW_LINE ans [ k ] = [ i , j ] NEW_LINE if ( i == n and j == m ) : NEW_LINE INDENT q = k ; NEW_LINE return q ; NEW_LINE DEDENT q = dfs ( i + 1 , j + 1 , k + 1 , q , n , m ) ; NEW_LINE q = dfs ( i + 1 , j , k + 1 , q , n , m ) ; NEW_LINE q = dfs ( i , j + 1 , k + 1 , q , n , m ) ; NEW_LINE return q NEW_LINE DEDENT def lexicographicalPath ( n , m ) : NEW_LINE INDENT q = 0 ; NEW_LINE global ans , mark NEW_LINE ans = [ [ 0 , 0 ] for i in range ( MAX ) ] NEW_LINE mark = [ [ 0 for j in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE q = dfs ( 1 , 1 , 1 , q , n , m ) ; NEW_LINE for i in range ( 1 , q + 1 ) : NEW_LINE INDENT print ( str ( ans [ i ] [ 0 ] ) + ' \u2581 ' + str ( ans [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT def countPrimePath ( n , m ) : NEW_LINE INDENT global dp NEW_LINE dp = [ [ 0 for j in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE dp [ 1 ] [ 1 ] = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( i == 1 and j == 1 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] + dp [ i ] [ j - 1 ] + dp [ i - 1 ] [ j - 1 ] ) ; NEW_LINE if ( mappedMatrix [ i ] [ j ] == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT print ( dp [ n ] [ m ] ) NEW_LINE DEDENT def preprocessMatrix ( a , n , m ) : NEW_LINE INDENT global prime NEW_LINE prime = [ 0 for i in range ( MAX ) ] NEW_LINE sieve ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( prime [ a [ i ] [ j ] ] == 0 ) : NEW_LINE INDENT mappedMatrix [ i + 1 ] [ j + 1 ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT mappedMatrix [ i + 1 ] [ j + 1 ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 ; NEW_LINE m = 3 ; NEW_LINE a = [ [ 2 , 3 , 7 ] , [ 5 , 4 , 2 ] , [ 3 , 7 , 11 ] ] ; NEW_LINE mappedMatrix = [ [ 0 for j in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE preprocessMatrix ( a , n , m ) ; NEW_LINE countPrimePath ( n , m ) ; NEW_LINE lexicographicalPath ( n , m ) ; NEW_LINE DEDENT"} +{"text":"Maximum size subset with given sum | A Dynamic Programming solution for subset sum problem + maximal subset value . Returns size of maximum sized subset if there is a subset of set [ ] with sun equal to given sum . It returns - 1 if there is no subset with given sum . ; The value of subset [ i ] [ j ] will be true if there is a subset of set [ 0. . j - 1 ] with sum equal to i ; If sum is 0 , then answer is true ; If sum is not 0 and set is empty , then answer is false ; Fill the subset table in bottom up manner ; Driver code","code":"def isSubsetSum ( arr , n , sum ) : NEW_LINE INDENT subset = [ [ False for x in range ( n + 1 ) ] for y in range ( sum + 1 ) ] NEW_LINE count = [ [ 0 for x in range ( n + 1 ) ] for y in range ( sum + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = True NEW_LINE count [ 0 ] [ i ] = 0 NEW_LINE DEDENT for i in range ( 1 , sum + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = False NEW_LINE count [ i ] [ 0 ] = - 1 NEW_LINE DEDENT for i in range ( 1 , sum + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i ] [ j - 1 ] NEW_LINE count [ i ] [ j ] = count [ i ] [ j - 1 ] NEW_LINE if ( i >= arr [ j - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i ] [ j ] or subset [ i - arr [ j - 1 ] ] [ j - 1 ] ) NEW_LINE if ( subset [ i ] [ j ] ) : NEW_LINE INDENT count [ i ] [ j ] = ( max ( count [ i ] [ j - 1 ] , count [ i - arr [ j - 1 ] ] [ j - 1 ] + 1 ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return count [ sum ] [ n ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 10 ] NEW_LINE sum = 20 NEW_LINE n = 4 NEW_LINE print ( isSubsetSum ( arr , n , sum ) ) NEW_LINE DEDENT"} +{"text":"Print all longest common sub | Python3 program to find all LCS of two strings in sorted order . ; dp matrix to store result of sub calls for lcs ; A memoization based function that returns LCS of str1 [ i . . len1 - 1 ] and str2 [ j . . len2 - 1 ] ; base condition ; if lcs has been computed ; if characters are same return previous + 1 else max of two sequences after removing i ' th \u2581 and \u2581 j ' th char one by one ; Function to prall routes common sub - sequences of length lcslen ; if currlcs is equal to lcslen then prit ; if we are done with all the characters of both string ; here we have to prall sub - sequences lexicographically , that ' s \u2581 why \u2581 we \u2581 start \u2581 from \u2581 ' a ' to ' z ' if this character is present in both of them then append it in data[] and same remaining part ; done is a flag to tell that we have printed all the subsequences corresponding to current character ; if character ch is present in str1 then check if it is present in str2 ; if ch is present in both of them and remaining length is equal to remaining lcs length then add ch in sub - sequenece ; If we found LCS beginning with current character . ; This function prints all LCS of str1 and str2 in lexicographic order . ; Find lengths of both strings ; Find length of LCS ; Prall LCS using recursive backtracking data [ ] is used to store individual LCS . ; Driver program to run the case","code":"MAX = 100 NEW_LINE lcslen = 0 NEW_LINE dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def lcs ( str1 , str2 , len1 , len2 , i , j ) : NEW_LINE INDENT if ( i == len1 or j == len2 ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT ret = 0 NEW_LINE if ( str1 [ i ] == str2 [ j ] ) : NEW_LINE INDENT ret = 1 + lcs ( str1 , str2 , len1 , len2 , i + 1 , j + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT ret = max ( lcs ( str1 , str2 , len1 , len2 , i + 1 , j ) , lcs ( str1 , str2 , len1 , len2 , i , j + 1 ) ) NEW_LINE DEDENT dp [ i ] [ j ] = ret NEW_LINE return ret NEW_LINE DEDENT def printAll ( str1 , str2 , len1 , len2 , data , indx1 , indx2 , currlcs ) : NEW_LINE INDENT if ( currlcs == lcslen ) : NEW_LINE INDENT print ( \" \" . join ( data [ : currlcs ] ) ) NEW_LINE return NEW_LINE DEDENT if ( indx1 == len1 or indx2 == len2 ) : NEW_LINE INDENT return NEW_LINE DEDENT for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT done = False NEW_LINE for i in range ( indx1 , len1 ) : NEW_LINE INDENT if ( chr ( ch ) == str1 [ i ] ) : NEW_LINE for j in range ( indx2 , len2 ) : NEW_LINE INDENT if ( chr ( ch ) == str2 [ j ] and dp [ i ] [ j ] == lcslen - currlcs ) : NEW_LINE data [ currlcs ] = chr ( ch ) NEW_LINE printAll ( str1 , str2 , len1 , len2 , data , i + 1 , j + 1 , currlcs + 1 ) NEW_LINE done = True NEW_LINE break NEW_LINE DEDENT if ( done ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT DEDENT def prinlAllLCSSorted ( str1 , str2 ) : NEW_LINE INDENT global lcslen NEW_LINE len1 , len2 = len ( str1 ) , len ( str2 ) NEW_LINE lcslen = lcs ( str1 , str2 , len1 , len2 , 0 , 0 ) NEW_LINE data = [ ' a ' for i in range ( MAX ) ] NEW_LINE printAll ( str1 , str2 , len1 , len2 , data , 0 , 0 , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \" abcabcaa \" NEW_LINE str2 = \" acbacba \" NEW_LINE prinlAllLCSSorted ( str1 , str2 ) NEW_LINE DEDENT"} +{"text":"Check for Majority Element in a sorted array | Python3 Program to check for majority element in a sorted array ; get last index according to n ( even or odd ) ; search for first occurrence of x in arr [ ] ; check if x is present and is present more than n \/ 2 times ; Driver program to check above function","code":"def isMajority ( arr , n , x ) : NEW_LINE INDENT last_index = ( n \/\/ 2 + 1 ) if n % 2 == 0 else ( n \/\/ 2 ) NEW_LINE for i in range ( last_index ) : NEW_LINE INDENT if arr [ i ] == x and arr [ i + n \/\/ 2 ] == x : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 4 , 4 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE x = 4 NEW_LINE if ( isMajority ( arr , n , x ) ) : NEW_LINE INDENT print ( \" % \u2581 d \u2581 appears \u2581 more \u2581 than \u2581 % \u2581 d \u2581 times \u2581 in \u2581 arr [ ] \" % ( x , n \/\/ 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" % \u2581 d \u2581 does \u2581 not \u2581 appear \u2581 more \u2581 than \u2581 % \u2581 d \u2581 times \u2581 in \u2581 arr [ ] \" % ( x , n \/\/ 2 ) ) NEW_LINE DEDENT"} +{"text":"Check for Majority Element in a sorted array | If x is present in arr [ low ... high ] then returns the index of first occurrence of x , otherwise returns - 1 ; Check if arr [ mid ] is the first occurrence of x . arr [ mid ] is first occurrence if x is one of the following is true : ( i ) mid == 0 and arr [ mid ] = = x ( ii ) arr [ mid - 1 ] < x and arr [ mid ] == x ; This function returns true if the x is present more than n \/ 2 times in arr [ ] of size n ; Find the index of first occurrence of x in arr [ ] ; If element is not present at all , return false ; check if the element is present more than n \/ 2 times","code":"def _binarySearch ( arr , low , high , x ) : NEW_LINE INDENT if high >= low : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 NEW_LINE if ( mid == 0 or x > arr [ mid - 1 ] ) and ( arr [ mid ] == x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif x > arr [ mid ] : NEW_LINE INDENT return _binarySearch ( arr , ( mid + 1 ) , high , x ) NEW_LINE DEDENT else : NEW_LINE INDENT return _binarySearch ( arr , low , ( mid - 1 ) , x ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def isMajority ( arr , n , x ) : NEW_LINE INDENT i = _binarySearch ( arr , 0 , n - 1 , x ) NEW_LINE if i == - 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if ( ( i + n \/\/ 2 ) <= ( n - 1 ) ) and arr [ i + n \/\/ 2 ] == x : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT"} +{"text":"Check for Majority Element in a sorted array | ; Driver code","code":"def isMajorityElement ( arr , n , key ) : NEW_LINE INDENT if ( arr [ n \/\/ 2 ] == key ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 3 , 3 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE x = 3 NEW_LINE if ( isMajorityElement ( arr , n , x ) ) : NEW_LINE INDENT print ( x , \" \u2581 appears \u2581 more \u2581 than \u2581 \" , n \/\/ 2 , \" \u2581 times \u2581 in \u2581 arr [ ] \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( x , \" \u2581 does \u2581 not \u2581 appear \u2581 more \u2581 than \" , n \/\/ 2 , \" \u2581 times \u2581 in \u2581 arr [ ] \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Cutting a Rod | DP | A Dynamic Programming solution for Rod cutting problem ; Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Build the table val [ ] in bottom up manner and return the last entry from the table ; Driver program to test above functions","code":"INT_MIN = - 32767 NEW_LINE def cutRod ( price , n ) : NEW_LINE INDENT val = [ 0 for x in range ( n + 1 ) ] NEW_LINE val [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT max_val = INT_MIN NEW_LINE for j in range ( i ) : NEW_LINE INDENT max_val = max ( max_val , price [ j ] + val [ i - j - 1 ] ) NEW_LINE DEDENT val [ i ] = max_val NEW_LINE DEDENT return val [ n ] NEW_LINE DEDENT arr = [ 1 , 5 , 8 , 9 , 10 , 17 , 17 , 20 ] NEW_LINE size = len ( arr ) NEW_LINE print ( \" Maximum \u2581 Obtainable \u2581 Value \u2581 is \u2581 \" + str ( cutRod ( arr , size ) ) ) NEW_LINE"} +{"text":"Modify array to another given array by replacing array elements with the sum of the array | Function to check if the arr [ ] can be converted to target [ ] by replacing any element in arr [ ] by the sum of arr [ ] ; Store the maximum element ; Store the index of the maximum element ; Traverse the array target [ ] ; If current element is greater than max ; If max element is 1 ; Traverse the array , target [ ] ; If current index is not equal to maximum element index ; Update max ; If max is less than or equal to 0 , ; Update the maximum element ; Recursively call the function ; Driver Code","code":"def isPossible ( target ) : NEW_LINE INDENT max = 0 NEW_LINE index = 0 NEW_LINE for i in range ( len ( target ) ) : NEW_LINE INDENT if ( max < target [ i ] ) : NEW_LINE max = target [ i ] NEW_LINE index = i NEW_LINE DEDENT if ( max == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( len ( target ) ) : NEW_LINE INDENT if ( i != index ) : NEW_LINE max -= target [ i ] NEW_LINE if ( max <= 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT target [ index ] = max NEW_LINE return isPossible ( target ) NEW_LINE DEDENT target = [ 9 , 3 , 5 ] NEW_LINE res = isPossible ( target ) NEW_LINE if ( res ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} +{"text":"Sum of all products of the Binomial Coefficients of two numbers up to K | Function returns nCr i . e . Binomial Coefficient ; Initialize res with 1 ; Since C ( n , r ) = C ( n , n - r ) ; Evaluating expression ; Driver Code","code":"def nCr ( n , r ) : NEW_LINE INDENT res = 1 NEW_LINE if ( r > n - r ) : NEW_LINE INDENT r = n - r NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res \/\/= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE m = 2 NEW_LINE k = 2 NEW_LINE print ( nCr ( n + m , k ) ) NEW_LINE DEDENT"} +{"text":"Check if N can be obtained from 1 by repetitively multiplying by 10 or 20 | Python Program to check if N can be obtained from 1 by repetitive multiplication by 10 or 20 ; Function to check if N can be obtained or not ; Count and remove trailing zeroes ; Check if remaining N is a power of 2 ; To check the condition to print YES or NO ; Driver Program","code":"import math NEW_LINE def Is_possible ( N ) : NEW_LINE INDENT C = 0 NEW_LINE D = 0 NEW_LINE while ( N % 10 == 0 ) : NEW_LINE INDENT N = N \/ 10 NEW_LINE C += 1 NEW_LINE DEDENT if ( math . log ( N , 2 ) - int ( math . log ( N , 2 ) ) == 0 ) : NEW_LINE INDENT D = int ( math . log ( N , 2 ) ) NEW_LINE if ( C >= D ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT N = 2000000000000 NEW_LINE Is_possible ( N ) NEW_LINE"} +{"text":"Central polygonal numbers | Function to find N - th term in the series ; Driver code","code":"def findNthTerm ( n ) : NEW_LINE INDENT print ( n * n - n + 1 ) NEW_LINE DEDENT N = 4 NEW_LINE findNthTerm ( N ) NEW_LINE"} +{"text":"Program to print the series 1 , 3 , 4 , 8 , 15 , 27 , 50 \u00e2 \u20ac\u00a6 till N terms | Function to print the series ; Generate the ith term and print it ; Driver Code ; Function Call","code":"def printSeries ( n , a , b , c ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( a , end = \" \u2581 \" ) ; NEW_LINE return ; NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT print ( a , b , end = \" \u2581 \" ) ; NEW_LINE return ; NEW_LINE DEDENT print ( a , b , c , end = \" \u2581 \" ) ; NEW_LINE for i in range ( 4 , n + 1 ) : NEW_LINE INDENT d = a + b + c ; NEW_LINE print ( d , end = \" \u2581 \" ) ; NEW_LINE a = b ; NEW_LINE b = c ; NEW_LINE c = d ; NEW_LINE DEDENT DEDENT N = 7 ; a = 1 ; b = 3 ; NEW_LINE c = 4 ; NEW_LINE printSeries ( N , a , b , c ) ; NEW_LINE"} +{"text":"Diameter of a Binary Indexed Tree with N nodes | Function to find diameter of BIT with N + 1 nodes ; L is size of subtree just before subtree in which N lies ; H is the height of subtree just before subtree in which N lies ; Base Cases ; Size of subtree are power of 2 ; 3 Cases as explained in Approach ; Driver Code","code":"def diameter ( n ) : NEW_LINE INDENT L , H , templen = 0 , 0 , 0 ; NEW_LINE L = 1 ; NEW_LINE H = 0 ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return 2 ; NEW_LINE DEDENT if ( n == 3 ) : NEW_LINE INDENT return 3 ; NEW_LINE DEDENT while ( L * 2 <= n ) : NEW_LINE INDENT L *= 2 ; NEW_LINE H += 1 ; NEW_LINE DEDENT if ( n >= L * 2 - 1 ) : NEW_LINE INDENT return 2 * H + 1 ; NEW_LINE DEDENT elif ( n >= L + ( L \/ 2 ) - 1 ) : NEW_LINE INDENT return 2 * H ; NEW_LINE DEDENT return 2 * H - 1 ; NEW_LINE DEDENT n = 15 ; NEW_LINE print ( diameter ( n ) ) ; NEW_LINE"} +{"text":"Find the larger exponential among two exponentials | Python3 implementation of the approach ; Function to find whether a ^ b is greater or c ^ d ; Find b * log ( a ) ; Find d * log ( c ) ; Compare both values ; Driver code","code":"import math NEW_LINE def compareValues ( a , b , c , d ) : NEW_LINE INDENT log1 = math . log10 ( a ) NEW_LINE num1 = log1 * b NEW_LINE log2 = math . log10 ( c ) NEW_LINE num2 = log2 * d NEW_LINE if num1 > num2 : NEW_LINE INDENT print ( a , ' ^ ' , b ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( c , ' ^ ' , d ) NEW_LINE DEDENT DEDENT a = 8 NEW_LINE b = 29 NEW_LINE c = 60 NEW_LINE d = 59 NEW_LINE compareValues ( a , b , c , d ) NEW_LINE"} +{"text":"Sum of prime numbers without odd prime digits | Python3 program for above approach ; Find all prime numbers ; Store all prime numbers ; Function to check if a digit is odd prime or not ; Function to find sum ; To store required answer ; Get all prime numbers ; Traverse through all the prime numbers ; Flag stores 1 if a number does not contain any odd primes ; Find all digits of a number ; If number does not contain any odd primes ; Return the required answer ; Driver code ; Function call","code":"MAX = 100005 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 range ( 2 * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT ans = [ ] NEW_LINE for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT ans . append ( p ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def is_prime ( n ) : NEW_LINE INDENT if n in [ 3 , 5 , 7 ] : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def find_Sum ( n ) : NEW_LINE INDENT Sum = 0 NEW_LINE v = addPrimes ( ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT flag = 1 NEW_LINE a = v [ i ] NEW_LINE while ( a != 0 ) : NEW_LINE INDENT d = a % 10 ; NEW_LINE a = a \/\/ 10 ; NEW_LINE if ( is_prime ( d ) ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT n -= 1 NEW_LINE Sum = Sum + v [ i ] NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT n = 7 NEW_LINE print ( find_Sum ( n ) ) NEW_LINE"} +{"text":"Count the number of primes in the prefix sum array of the given array | Function to return the count of primes in the given 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 ] \" . A value in prime [ i ] will finally be False if i is Not a prime , else True . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Find all primes in arr [ ] ; Function to generate the prefix array ; Fill the prefix array ; Driver code ; Prefix array of arr [ ] ; Count of primes in the prefix array","code":"def primeCount ( arr , n ) : NEW_LINE INDENT max_val = max ( arr ) NEW_LINE prime = [ True ] * ( max_val + 1 ) NEW_LINE prime [ 0 ] = prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= max_val : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( p * 2 , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if prime [ arr [ i ] ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def getPrefixArray ( arr , n , pre ) : NEW_LINE INDENT pre [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + arr [ i ] NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 4 , 8 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE pre = [ None ] * n NEW_LINE getPrefixArray ( arr , n , pre ) NEW_LINE print ( primeCount ( pre , n ) ) NEW_LINE DEDENT"} +{"text":"Minimum value to be added to X such that it is at least Y percent of N | Python implementation of the approach ; Function to return the required value that must be added to x so that it is at least y percent of n ; Required value ; If x is already >= y percent of n ; Driver code","code":"import math NEW_LINE def minValue ( n , x , y ) : NEW_LINE INDENT val = ( y * n ) \/ 100 NEW_LINE if x >= val : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return math . ceil ( val ) - x NEW_LINE DEDENT DEDENT n = 10 ; x = 2 ; y = 40 NEW_LINE print ( minValue ( n , x , y ) ) NEW_LINE"} +{"text":"Check if N is a Factorial Prime | Python3 program to check if given number is a factorial prime ; Utility function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if n is a factorial prime ; If n is not prime then return false ; Calculate factorial ; If n is a factorial prime ; n is not a factorial prime ; Driver code","code":"from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 5 , int ( sqrt ( n ) ) + 1 , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isFactorialPrime ( n ) : NEW_LINE INDENT if ( not isPrime ( n ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT fact = 1 NEW_LINE i = 1 NEW_LINE while ( fact <= n + 1 ) : NEW_LINE INDENT fact = fact * i NEW_LINE if ( n + 1 == fact or n - 1 == fact ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 23 NEW_LINE if ( isFactorialPrime ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Seating arrangement of n boys and girls alternatively around a round table | Get n ; find fac1 = ( n - 1 ) ! ; Find fac2 = n ! ; Find total number of ways ; Print the total number of ways","code":"n = 5 NEW_LINE fac1 = 1 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT fac1 = fac1 * i NEW_LINE DEDENT fac2 = fac1 * n NEW_LINE totalWays = fac1 * fac2 NEW_LINE print ( totalWays ) NEW_LINE"} +{"text":"Check whether the given number is Euclid Number or not | Python 3 program to check Euclid Number ; Function to generate prime numbers ; 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 ; Update all multiples of p ; store all prime numbers to vector 'arr ; Function to check the number for Euclid Number ; Multiply next prime number and check if product + 1 = n holds or not ; Driver code ; Get the prime numbers ; Get n ; Check if n is Euclid Number ; Get n ; Check if n is Euclid Number","code":"MAX = 10000 NEW_LINE arr = [ ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime = [ True ] * MAX NEW_LINE p = 2 NEW_LINE while p * p < MAX : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for p in range ( 2 , MAX ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT arr . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def isEuclid ( n ) : NEW_LINE INDENT product = 1 NEW_LINE i = 0 NEW_LINE while ( product < n ) : NEW_LINE INDENT product = product * arr [ i ] NEW_LINE if ( product + 1 == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE n = 31 NEW_LINE if ( isEuclid ( n ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT n = 42 NEW_LINE if ( isEuclid ( n ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Perfect cube greater than a given number | Python 3 implementation of above approach ; Function to find the next perfect cube ; Driver code","code":"from math import * NEW_LINE def nextPerfectCube ( N ) : NEW_LINE INDENT nextN = floor ( N ** ( 1 \/ 3 ) ) + 1 NEW_LINE return nextN ** 3 NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 35 NEW_LINE print ( nextPerfectCube ( n ) ) NEW_LINE DEDENT"} +{"text":"Sum of all the prime divisors of a number | Python3 program to find sum of prime divisors of N ; Function to check if the number is prime or not . ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; function to find sum of prime divisors of N ; return type of sqrt function if float ; both factors are same ; both factors are not same ( i and n \/ i ) ; Driver code","code":"import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def SumOfPrimeDivisors ( n ) : NEW_LINE INDENT Sum = 0 NEW_LINE root_n = ( int ) ( math . sqrt ( n ) ) NEW_LINE for i in range ( 1 , root_n + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i == ( int ) ( n \/ i ) and isPrime ( i ) ) : NEW_LINE INDENT Sum += i NEW_LINE DEDENT else : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT Sum += i NEW_LINE DEDENT if ( isPrime ( ( int ) ( n \/ i ) ) ) : NEW_LINE INDENT Sum += ( int ) ( n \/ i ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return Sum NEW_LINE DEDENT n = 60 NEW_LINE print ( \" Sum \u2581 of \u2581 prime \u2581 divisors \u2581 of \u2581 60 \u2581 is \" , SumOfPrimeDivisors ( n ) ) NEW_LINE"} +{"text":"Position of n among the numbers made of 2 , 3 , 5 & 7 | Program position of n among the numbers made of 2 , 3 , 5 & 7 ; If number is 2 then it is on the position pos * 2 + 1 ; If number is 3 then it is on the position pos * 2 + 2 ; If number is 5 then it is on the position pos * 2 + 3 ; If number is 7 then it is on the position pos * 2 + 4 ; Driver code","code":"def findpos ( n ) : NEW_LINE INDENT pos = 0 NEW_LINE for i in n : NEW_LINE INDENT if i == '2' : NEW_LINE INDENT pos = pos * 4 + 1 NEW_LINE DEDENT elif i == '3' : NEW_LINE INDENT pos = pos * 4 + 2 NEW_LINE DEDENT elif i == '5' : NEW_LINE INDENT pos = pos * 4 + 3 NEW_LINE DEDENT elif i == '7' : NEW_LINE INDENT pos = pos * 4 + 4 NEW_LINE DEDENT DEDENT return pos NEW_LINE DEDENT n = \"777\" NEW_LINE print ( findpos ( n ) ) NEW_LINE"} +{"text":"Finding a Non Transitive Co | Checks if any possible triplet ( a , b , c ) satifying the condition that ( a , b ) is coprime , ( b , c ) is coprime but ( a , c ) isnt ; Case 1 : Less than 3 numbers between L and R ; Case 2 : More than 3 numbers between L and R ; triplets should always be of form ( 2 k , 2 k + 1 , 2 k + 2 ) ; Case 3.1 : Exactly 3 numbers in range of form ( 2 k , 2 k + 1 , 2 k + 2 ) ; Case 3.2 : Exactly 3 numbers in range of form ( 2 k - 1 , 2 k , 2 k + 1 ) ; flag = True indicates that a pair exists between L and R ; finding possible Triplet between 2 and 10 ; finding possible Triplet between 23 and 46","code":"def possibleTripletInRange ( L , R ) : NEW_LINE INDENT flag = False ; NEW_LINE possibleA = 0 ; NEW_LINE possibleB = 0 ; NEW_LINE possibleC = 0 ; NEW_LINE numbersInRange = ( R - L + 1 ) ; NEW_LINE if ( numbersInRange < 3 ) : NEW_LINE INDENT flag = False ; NEW_LINE DEDENT elif ( numbersInRange > 3 ) : NEW_LINE INDENT flag = True ; NEW_LINE if ( ( L % 2 ) > 0 ) : NEW_LINE INDENT L += 1 ; NEW_LINE DEDENT possibleA = L ; NEW_LINE possibleB = L + 1 ; NEW_LINE possibleC = L + 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( L % 2 ) == 0 ) : NEW_LINE INDENT flag = True ; NEW_LINE possibleA = L ; NEW_LINE possibleB = L + 1 ; NEW_LINE possibleC = L + 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT flag = False ; NEW_LINE DEDENT DEDENT if ( flag == True ) : NEW_LINE INDENT print ( \" ( \" , possibleA , \" , \" , possibleB , \" , \" , possibleC , \" ) \u2581 is \u2581 one \u2581 such \" , \" possible \u2581 triplet \u2581 between \" , L , \" and \" , R ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 Such \u2581 Triplet \u2581 exists \u2581 between \" , L , \" and \" , R ) ; NEW_LINE DEDENT DEDENT L = 2 ; NEW_LINE R = 10 ; NEW_LINE possibleTripletInRange ( L , R ) ; NEW_LINE L = 23 ; NEW_LINE R = 46 ; NEW_LINE possibleTripletInRange ( L , R ) ; NEW_LINE"} +{"text":"Count n digit numbers not having a particular digit | Python Implementation of above method ; Finding number of possible number with n digits excluding a particular digit ; Checking if number of digits is zero ; Checking if number of digits is one ; Checking if number of digits is odd ; Calling digitNumber function with ( digit - 1 ) \/ 2 digits ; Calling digitNumber function with n \/ 2 digits ; Calling digitNumber function Checking if excluding digit is zero or non - zero ; Initializing variables","code":"mod = 1000000007 NEW_LINE def digitNumber ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 9 NEW_LINE DEDENT if ( n % 2 != 0 ) : NEW_LINE INDENT temp = digitNumber ( ( n - 1 ) \/\/ 2 ) % mod NEW_LINE return ( 9 * ( temp * temp ) % mod ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT temp = digitNumber ( n \/\/ 2 ) % mod NEW_LINE return ( temp * temp ) % mod NEW_LINE DEDENT DEDENT def countExcluding ( n , d ) : NEW_LINE INDENT if ( d == 0 ) : NEW_LINE INDENT return ( 9 * digitNumber ( n - 1 ) ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT return ( 8 * digitNumber ( n - 1 ) ) % mod NEW_LINE DEDENT DEDENT d = 9 NEW_LINE n = 3 NEW_LINE print ( countExcluding ( n , d ) ) NEW_LINE"} +{"text":"Check if given number is Emirp Number or not | Returns true if n is prime . Else false . ; Corner case ; Check from 2 to n - 1 ; Function will check whether number is Emirp or not ; Check if n is prime ; Find reverse of n ; If both Original and Reverse are Prime , then it is an Emirp number ; Input number","code":"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 isEmirp ( n ) : NEW_LINE INDENT n = int ( n ) NEW_LINE if isPrime ( n ) == False : NEW_LINE INDENT return False NEW_LINE DEDENT rev = 0 NEW_LINE while n != 0 : NEW_LINE INDENT d = n % 10 NEW_LINE rev = rev * 10 + d NEW_LINE n = int ( n \/ 10 ) NEW_LINE DEDENT return isPrime ( rev ) NEW_LINE DEDENT n = 13 NEW_LINE if isEmirp ( n ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Program to Convert Radian to Degree | Function for convertion ; Driver Code","code":"def Convert ( radian ) : NEW_LINE INDENT pi = 3.14159 NEW_LINE degree = radian * ( 180 \/ pi ) NEW_LINE return degree NEW_LINE DEDENT radian = 5 NEW_LINE print ( \" degree \u2581 = \" , ( Convert ( radian ) ) ) NEW_LINE"} +{"text":"Find trace of matrix formed by adding Row | Return sum of first n integers of an AP ; Return the trace of sum of row - major matrix and column - major matrix ; Finding nth element in AP in case of Row major matrix . ; Finding sum of first n integers of AP in case of Row major matrix ; Finding nth element in AP in case of Row major matrix ; Finding sum of first n integers of AP in case of Column major matrix ; Driver Code","code":"def sn ( n , an ) : NEW_LINE INDENT return ( n * ( 1 + an ) ) \/ 2 ; NEW_LINE DEDENT def trace ( n , m ) : NEW_LINE INDENT an = 1 + ( n - 1 ) * ( m + 1 ) ; NEW_LINE rowmajorSum = sn ( n , an ) ; NEW_LINE an = 1 + ( n - 1 ) * ( n + 1 ) ; NEW_LINE colmajorSum = sn ( n , an ) ; NEW_LINE return int ( rowmajorSum + colmajorSum ) ; NEW_LINE DEDENT N = 3 ; NEW_LINE M = 3 ; NEW_LINE print ( trace ( N , M ) ) ; NEW_LINE"} +{"text":"Maximum of smallest possible area that can get with exactly k cut of given rectangular | Utility Function ; for the 1 st case ; for the second case ; print final result ; driver code","code":"def max_area ( n , m , k ) : NEW_LINE INDENT if ( k > ( n + m - 2 ) ) : NEW_LINE INDENT print ( \" Not \u2581 possible \" ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( k < max ( m , n ) - 1 ) : NEW_LINE INDENT result = max ( m * ( n \/ ( k + 1 ) ) , n * ( m \/ ( k + 1 ) ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT result = max ( m \/ ( k - n + 2 ) , n \/ ( k - m + 2 ) ) ; NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT DEDENT n = 3 NEW_LINE m = 4 NEW_LINE k = 1 NEW_LINE max_area ( n , m , k ) NEW_LINE"} +{"text":"Program to find the area of a Square | function to find the area ; Driver program","code":"def area_fun ( side ) : NEW_LINE INDENT area = side * side NEW_LINE return area NEW_LINE DEDENT side = 4 NEW_LINE area = area_fun ( side ) NEW_LINE print ( area ) NEW_LINE"} +{"text":"Count ways to express a number as sum of consecutive numbers | Utility method to compute number of ways in which N can be represented as sum of consecutive number ; constraint on values of L gives us the time Complexity as O ( N ^ 0.5 ) ; Driver code","code":"def countConsecutive ( N ) : NEW_LINE INDENT count = 0 NEW_LINE L = 1 NEW_LINE while ( L * ( L + 1 ) < 2 * N ) : NEW_LINE INDENT a = ( 1.0 * N - ( L * ( L + 1 ) ) \/ 2 ) \/ ( L + 1 ) NEW_LINE if ( a - int ( a ) == 0.0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT L += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT N = 15 NEW_LINE print countConsecutive ( N ) NEW_LINE N = 10 NEW_LINE print countConsecutive ( N ) NEW_LINE"} +{"text":"Automorphic Number | Function to check Automorphic number ; Store the square ; Start Comparing digits ; Return false , if any digit of N doesn ' t \u2581 \u2581 match \u2581 with \u2581 its \u2581 square ' s digits from last ; Reduce N and square ; Driver code","code":"def isAutomorphic ( N ) : NEW_LINE INDENT sq = N * N NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % 10 != sq % 10 ) : NEW_LINE INDENT return False NEW_LINE DEDENT N \/= 10 NEW_LINE sq \/= 10 NEW_LINE DEDENT return True NEW_LINE DEDENT N = 5 NEW_LINE if isAutomorphic ( N ) : NEW_LINE INDENT print \" Automorphic \" NEW_LINE DEDENT else : NEW_LINE INDENT print \" Not \u2581 Automorphic \" NEW_LINE DEDENT"} +{"text":"Number with maximum number of prime factors | Return smallest number having maximum prime factors . ; default value of boolean is false ; Sieve of eratosthenes ; Storing prime numbers . ; Generating number having maximum prime factors . ; Driver Code","code":"def maxPrimefactorNum ( N ) : NEW_LINE INDENT arr = [ True ] * ( N + 5 ) ; NEW_LINE i = 3 ; NEW_LINE while ( i * i <= N ) : NEW_LINE INDENT if ( arr [ i ] ) : NEW_LINE INDENT for j in range ( i * i , N + 1 , i ) : NEW_LINE INDENT arr [ j ] = False ; NEW_LINE DEDENT DEDENT i += 2 ; NEW_LINE DEDENT prime = [ ] ; NEW_LINE prime . append ( 2 ) ; NEW_LINE for i in range ( 3 , N + 1 , 2 ) : NEW_LINE INDENT if ( arr [ i ] ) : NEW_LINE INDENT prime . append ( i ) ; NEW_LINE DEDENT DEDENT i = 0 ; NEW_LINE ans = 1 ; NEW_LINE while ( ans * prime [ i ] <= N and i < len ( prime ) ) : NEW_LINE INDENT ans *= prime [ i ] ; NEW_LINE i += 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT N = 40 ; NEW_LINE print ( maxPrimefactorNum ( N ) ) ; NEW_LINE"} +{"text":"Find Square Root under Modulo p | Set 1 ( When p is in form of 4 * i + 3 ) | Utility function to do modular exponentiation . It returns ( x ^ y ) % p . ; res = 1 Initialize result x = x % p Update x if it is more than or equal to p ; If y is odd , multiply x with result ; y must be even now y = y >> 1 y = y \/ 2 ; Returns true if square root of n under modulo p exists . Assumption : p is of the form 3 * i + 4 where i >= 1 ; Try \" + ( n ^ ( ( p \u2581 + \u2581 1 ) \/ 4 ) ) \" ; Try \" - ( n \u2581 ^ \u2581 ( ( p \u2581 + \u2581 1 ) \/ 4 ) ) \" ; If none of the above two work , then square root doesn 't exist ; Driver Code","code":"def power ( x , y , p ) : NEW_LINE INDENT while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def squareRoot ( n , p ) : NEW_LINE INDENT if ( p % 4 != 3 ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return NEW_LINE DEDENT n = n % p NEW_LINE x = power ( n , ( p + 1 ) \/\/ 4 , p ) NEW_LINE if ( ( x * x ) % p == n ) : NEW_LINE INDENT print ( \" Square \u2581 root \u2581 is \u2581 \" , x ) NEW_LINE return NEW_LINE DEDENT x = p - x NEW_LINE if ( ( x * x ) % p == n ) : NEW_LINE INDENT print ( \" Square \u2581 root \u2581 is \u2581 \" , x ) NEW_LINE return NEW_LINE DEDENT print ( \" Square \u2581 root \u2581 doesn ' t \u2581 exist \u2581 \" ) NEW_LINE DEDENT p = 7 NEW_LINE n = 2 NEW_LINE squareRoot ( n , p ) NEW_LINE"} +{"text":"Primality Test | Set 3 ( Miller\u00e2 \u20ac\u201c Rabin ) | Python3 program Miller - Rabin primality test ; Utility function to do modular exponentiation . It returns ( x ^ y ) % p ; 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 y = y >> 1 ; y = y \/ 2 ; This function is called for all k trials . It returns false if n is composite and returns false if n is probably prime . d is an odd number such that d * 2 < sup > r < \/ sup > = n - 1 for some r >= 1 ; Pick a random number in [ 2. . n - 2 ] Corner cases make sure that n > 4 ; Compute a ^ d % n ; Keep squaring x while one of the following doesn 't happen (i) d does not reach n-1 (ii) (x^2) % n is not 1 (iii) (x^2) % n is not n-1 ; Return composite ; It returns false if n is composite and returns true if n is probably prime . k is an input parameter that determines accuracy level . Higher value of k indicates more accuracy . ; Corner cases ; Find r such that n = 2 ^ d * r + 1 for some r >= 1 ; Iterate given nber of ' k ' times ; Driver Code Number of iterations","code":"import random NEW_LINE def power ( 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 x = ( x * x ) % p ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def miillerTest ( d , n ) : NEW_LINE INDENT a = 2 + random . randint ( 1 , n - 4 ) ; NEW_LINE x = power ( a , d , n ) ; NEW_LINE if ( x == 1 or x == n - 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT while ( d != n - 1 ) : NEW_LINE INDENT x = ( x * x ) % n ; NEW_LINE d *= 2 ; NEW_LINE if ( x == 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( x == n - 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT def isPrime ( n , k ) : NEW_LINE INDENT if ( n <= 1 or n == 4 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT d = n - 1 ; NEW_LINE while ( d % 2 == 0 ) : NEW_LINE INDENT d \/\/= 2 ; NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT if ( miillerTest ( d , n ) == False ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT k = 4 ; NEW_LINE print ( \" All \u2581 primes \u2581 smaller \u2581 than \u2581 100 : \u2581 \" ) ; NEW_LINE for n in range ( 1 , 100 ) : NEW_LINE INDENT if ( isPrime ( n , k ) ) : NEW_LINE INDENT print ( n , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT"} +{"text":"Length of the Longest Consecutive 1 s in Binary Representation | Function to find length of the longest consecutive 1 s in binary representation of a number ; Initialize result ; Count the number of iterations to reach x = 0. ; This operation reduces length of every sequence of 1 s by one . ; Driver code","code":"def maxConsecutiveOnes ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT x = ( x & ( x << 1 ) ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT print ( maxConsecutiveOnes ( 14 ) ) NEW_LINE print ( maxConsecutiveOnes ( 222 ) ) NEW_LINE"} +{"text":"Subtract two numbers without using arithmetic operators | Python program to Subtract two numbers without using arithmetic operators ; Iterate till there is no carry ; borrow contains common set bits of y and unset bits of x ; Subtraction of bits of x and y where at least one of the bits is not set ; Borrow is shifted by one so that subtracting it from x gives the required sum ; Driver Code","code":"def subtract ( x , y ) : NEW_LINE INDENT while ( y != 0 ) : NEW_LINE INDENT borrow = ( ~ x ) & y NEW_LINE x = x ^ y NEW_LINE y = borrow << 1 NEW_LINE DEDENT return x NEW_LINE DEDENT x = 29 NEW_LINE y = 13 NEW_LINE print ( \" x \u2581 - \u2581 y \u2581 is \" , subtract ( x , y ) ) NEW_LINE"} +{"text":"Subtract two numbers without using arithmetic operators | Python Program to subtract two Number without using arithmetic operator Recursive implementation . ; Driver program","code":"def subtract ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return x NEW_LINE DEDENT return subtract ( x ^ y , ( ~ x & y ) << 1 ) NEW_LINE DEDENT x = 29 NEW_LINE y = 13 NEW_LINE print ( \" x \u2581 - \u2581 y \u2581 is \" , subtract ( x , y ) ) NEW_LINE"} +{"text":"Kth ancestor of all nodes in an N | Function to add an edge in the tree ; DFS to find the Kth ancestor of every node ; Pushing current node in the vector ; Traverse its neighbors ; If K ancestors are not found for current node ; Add the Kth ancestor for the node ; Function to find Kth ancestor of each node ; Building the tree ; Stores all parents of a node ; Store Kth ancestor of all nodes ; Print the ancestors ; Driver code ; Given N and K ; Given edges of n - ary tree ; Function call","code":"def addEdge ( v , x , y ) : NEW_LINE INDENT v [ x ] . append ( y ) NEW_LINE v [ y ] . append ( x ) NEW_LINE DEDENT def dfs ( tree , temp , ancestor , u , parent , k ) : NEW_LINE INDENT temp . append ( u ) NEW_LINE for i in tree [ u ] : NEW_LINE INDENT if ( i == parent ) : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( tree , temp , ancestor , i , u , k ) NEW_LINE DEDENT temp . pop ( ) NEW_LINE if ( len ( temp ) < k ) : NEW_LINE INDENT ancestor [ u ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ancestor [ u ] = temp [ len ( temp ) - k ] NEW_LINE DEDENT DEDENT def KthAncestor ( N , K , E , edges ) : NEW_LINE INDENT tree = [ [ ] for i in range ( N + 1 ) ] NEW_LINE for i in range ( E ) : NEW_LINE INDENT addEdge ( tree , edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) NEW_LINE DEDENT temp = [ ] NEW_LINE ancestor = [ 0 ] * ( N + 1 ) NEW_LINE dfs ( tree , temp , ancestor , 1 , 0 , K ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( ancestor [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE K = 2 NEW_LINE E = 8 NEW_LINE edges = [ [ 1 , 2 ] , [ 1 , 3 ] , [ 2 , 4 ] , [ 2 , 5 ] , [ 2 , 6 ] , [ 3 , 7 ] , [ 3 , 8 ] , [ 3 , 9 ] ] NEW_LINE KthAncestor ( N , K , E , edges ) NEW_LINE DEDENT"} +{"text":"Queries to count array elements greater than or equal to a given number with updates | Function to build a segment tree ; Check for base case ; Find mid point ; Recursively build the segment tree ; Function for push down operation on the segment tree ; Function to update the segment tree ; Complete overlap ; Find mid ; Perform push down operation on segment tree ; Recursively update the segment tree ; Function to process the queryy ; Base case ; Find mid ; Perform push down operation on segment tree ; Recursively calculate the result of the queryy ; Return the result ; Function to count the numbers which are greater than the given queryy ; Sort the input array ; Create segment tree of size 4 * n vector < int > sum , add , ans ; Build the segment tree ; Iterate over the queries ; Store result in array ; Update the elements in the given range ; Print the result of queries ; Driver Code ; Function call","code":"def build ( sum , a , l , r , rt ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT sum [ rt ] = a [ l - 1 ] NEW_LINE return NEW_LINE DEDENT m = ( l + r ) >> 1 NEW_LINE build ( sum , a , l , m , rt << 1 ) NEW_LINE build ( sum , a , m + 1 , r , rt << 1 1 ) NEW_LINE DEDENT def pushDown ( sum , add , rt , ln , rn ) : NEW_LINE INDENT if ( add [ rt ] ) : NEW_LINE INDENT add [ rt << 1 ] += add [ rt ] NEW_LINE add [ rt << 1 1 ] += add [ rt ] NEW_LINE sum [ rt << 1 ] += add [ rt ] * ln NEW_LINE sum [ rt << 1 1 ] += add [ rt ] * rn NEW_LINE add [ rt ] = 0 NEW_LINE DEDENT DEDENT def update ( sum , add , L , R , C , l , r , rt ) : NEW_LINE INDENT if ( L <= l and r <= R ) : NEW_LINE INDENT sum [ rt ] += C * ( r - l + 1 ) NEW_LINE add [ rt ] += C NEW_LINE return NEW_LINE DEDENT m = ( l + r ) >> 1 NEW_LINE pushDown ( sum , add , rt , m - l + 1 , r - m ) NEW_LINE if ( L <= m ) : NEW_LINE INDENT update ( sum , add , L , R , C , l , m , rt << 1 ) NEW_LINE DEDENT if ( R > m ) : NEW_LINE INDENT update ( sum , add , L , R , C , m + 1 , r , rt << 1 1 ) NEW_LINE DEDENT DEDENT def queryy ( sum , add , L , R , l , r , rt ) : NEW_LINE INDENT if ( L <= l and r <= R ) : NEW_LINE INDENT return sum [ rt ] NEW_LINE DEDENT m = ( l + r ) >> 1 NEW_LINE pushDown ( sum , add , rt , m - l + 1 , r - m ) NEW_LINE ans = 0 NEW_LINE if ( L <= m ) : NEW_LINE INDENT ans += queryy ( sum , add , L , R , l , m , rt << 1 ) NEW_LINE DEDENT if ( R > m ) : NEW_LINE INDENT ans += queryy ( sum , add , L , R , m + 1 , r , ( rt << 1 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def sequenceMaintenance ( n , q , a , b , m ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE sum = [ 0 ] * ( 4 * n ) NEW_LINE add = [ 0 ] * ( 4 * n ) NEW_LINE ans = [ ] NEW_LINE build ( sum , a , 1 , n , 1 ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT l = 1 NEW_LINE r = n NEW_LINE pos = - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) >> 1 NEW_LINE if ( queryy ( sum , add , m , m , 1 , n , 1 ) >= b [ i ] ) : NEW_LINE INDENT r = m - 1 NEW_LINE pos = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT if ( pos == - 1 ) : NEW_LINE INDENT ans . append ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans . append ( n - pos + 1 ) NEW_LINE update ( sum , add , pos , n , - m , 1 , n , 1 ) NEW_LINE DEDENT DEDENT for i in ans : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE Q = 3 NEW_LINE M = 1 NEW_LINE arr = [ 1 , 2 , 3 , 4 ] NEW_LINE query = [ 4 , 3 , 1 ] NEW_LINE sequenceMaintenance ( N , Q , arr , query , M ) NEW_LINE DEDENT"} +{"text":"Minimize Array length by repeatedly replacing co | Python3 program for the above approach ; Function to find the final array length by replacing coprime pair with 1 ; Iterate over all pairs of element ; Check if gcd is 1 ; If no coprime pair found return false ; Driver code ; Check if atleast one coprime pair exists in the array ; If no such pair exists","code":"import math NEW_LINE def hasCoprimePair ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( math . gcd ( arr [ i ] , arr [ j ] ) == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 NEW_LINE arr = [ 6 , 9 , 15 ] NEW_LINE if ( hasCoprimePair ( arr , n ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT"} +{"text":"Count of ways to split N into Triplets forming a Triangle | Function to return the required number of ways ; Check if a , b , c can form a triangle ; Return number of ways ; Driver code","code":"def Numberofways ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for a in range ( 1 , n ) : NEW_LINE INDENT for b in range ( 1 , n ) : NEW_LINE INDENT c = n - ( a + b ) NEW_LINE if ( a < b + c and b < a + c and c < a + b ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT n = 15 NEW_LINE print ( Numberofways ( n ) ) NEW_LINE"} +{"text":"Count of pairs having each element equal to index of the other from an Array | Function to print the count of pair ; Iterate over all the elements of the array ; Increment the count ; Print the result ; Driver Code","code":"def countPairs ( N , arr ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i == arr [ arr [ i ] - 1 ] - 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count \/\/ 2 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 1 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( N , arr ) NEW_LINE DEDENT"} +{"text":"Find length of longest Fibonacci like subsequence | Function to return the max Length of Fibonacci subsequence ; Store all array elements in a hash table ; check until next fib element is found ; next element of fib subseq ; Driver Code","code":"def LongestFibSubseq ( A , n ) : NEW_LINE INDENT S = set ( A ) NEW_LINE maxLen = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT x = A [ j ] NEW_LINE y = A [ i ] + A [ j ] NEW_LINE length = 2 NEW_LINE while y in S : NEW_LINE INDENT z = x + y NEW_LINE x = y NEW_LINE y = z NEW_LINE length += 1 NEW_LINE maxLen = max ( maxLen , length ) NEW_LINE DEDENT DEDENT DEDENT return maxLen if maxLen >= 3 else 0 NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] NEW_LINE n = len ( A ) NEW_LINE print ( LongestFibSubseq ( A , n ) ) NEW_LINE DEDENT"} +{"text":"Maximize count of elements that can be selected having minimum difference between their sum and K | Function to count maximum number of elements that can be selected ; Sort he array ; Traverse the array ; Add current element to the sum ; IF sum exceeds k ; Increment count ; Return the count ; Driver code ; Function call","code":"def CountMaximum ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE Sum , count = 0 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE if ( Sum > k ) : NEW_LINE INDENT break NEW_LINE DEDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 30 , 30 , 10 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE k = 50 NEW_LINE print ( CountMaximum ( arr , n , k ) ) NEW_LINE"} +{"text":"Maximum types of candies a person can eat if only N \/ 2 of them can be eaten | Function to find number of candy types ; Declare a hashset to store candies ; Traverse the given array and inserts element into set ; Return the result ; Function to find maximum number of types of candies a person can eat ; Store the number of candies allowed to eat ; Store the number of candy types ; Return the result ; Driver Code ; Given Input ; Function Call","code":"def num_candyTypes ( candies ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( len ( candies ) ) : NEW_LINE INDENT s . add ( candies [ i ] ) NEW_LINE DEDENT return len ( s ) NEW_LINE DEDENT def distribute_candies ( candies ) : NEW_LINE INDENT allowed = len ( candies ) \/ 2 NEW_LINE types = num_candyTypes ( candies ) NEW_LINE if ( types < allowed ) : NEW_LINE INDENT print ( int ( types ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( int ( allowed ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT candies = [ 4 , 4 , 5 , 5 , 3 , 3 ] NEW_LINE distribute_candies ( candies ) NEW_LINE DEDENT"} +{"text":"Length of diagonals of a Rhombus using length of Side and vertex Angle | Python Program to implement the above approach ; Function to calculate the length of diagonals of a rhombus using length of sides and vertex angle ; Driver Code","code":"import math NEW_LINE def Length_Diagonals ( a , theta ) : NEW_LINE INDENT p = a * math . sqrt ( 2 + ( 2 * math . cos ( math . radians ( theta ) ) ) ) NEW_LINE q = a * math . sqrt ( 2 - ( 2 * math . cos ( math . radians ( theta ) ) ) ) NEW_LINE return [ p , q ] NEW_LINE DEDENT A = 6 NEW_LINE theta = 45 NEW_LINE ans = Length_Diagonals ( A , theta ) NEW_LINE print ( round ( ans [ 0 ] , 2 ) , round ( ans [ 1 ] , 2 ) ) NEW_LINE"} +{"text":"Count of even and odd set bit with array element after XOR with K | Function to store EVEN and odd variable ; Store the count of even and odd set bit ; Count the set bit using in built function ; Count of set - bit of K ; If y is odd then , count of even and odd set bit will be interchanged ; Else it will remain same as the original array ; Driver 's Code ; Function call to count even and odd","code":"def countEvenOdd ( arr , n , K ) : NEW_LINE INDENT even = 0 ; odd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = bin ( arr [ i ] ) . count ( '1' ) ; NEW_LINE if ( x % 2 == 0 ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 ; NEW_LINE DEDENT DEDENT y = bin ( K ) . count ( '1' ) ; NEW_LINE if ( y & 1 ) : NEW_LINE INDENT print ( \" Even \u2581 = \" , odd , \" , \u2581 Odd \u2581 = \" , even ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Even \u2581 = \" , even , \" , \u2581 Odd \u2581 = \" , odd ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 4 , 2 , 15 , 9 , 8 , 8 ] ; NEW_LINE K = 3 ; NEW_LINE n = len ( arr ) ; NEW_LINE countEvenOdd ( arr , n , K ) ; NEW_LINE DEDENT"} +{"text":"Number of ways to choose a pair containing an even and an odd number from 1 to N | Driver code","code":"N = 6 NEW_LINE Even = N \/\/ 2 NEW_LINE Odd = N - Even NEW_LINE print ( Even * Odd ) NEW_LINE"} +{"text":"Longest subsequence from an array of pairs having first element increasing and second element decreasing . | Python 3 program for the above approach ; Recursive function to find the length of the longest subsequence of pairs whose first element is increasing and second is decreasing ; Base case ; Not include the current pair in the longest subsequence ; Including the current pair in the longest subsequence ; ; Driver Code ; Given Input ; Function Call","code":"import sys NEW_LINE def longestSubSequence ( A , N , ind = 0 , lastf = - sys . maxsize - 1 , lasts = sys . maxsize ) : NEW_LINE INDENT if ( ind == N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = longestSubSequence ( A , N , ind + 1 , lastf , lasts ) NEW_LINE if ( A [ ind ] [ 0 ] > lastf and A [ ind ] [ 1 ] < lasts ) : NEW_LINE INDENT ans = max ( ans , longestSubSequence ( A , N , ind + 1 , A [ ind ] [ 0 ] , A [ ind ] [ 1 ] ) + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT \/ * Function * \/ NEW_LINE public static int longestSubSequence ( int [ , ] A , int N ) NEW_LINE { return longestSubSequence ( A , N , 0 , 0 , 0 ) ; } NEW_LINE if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ [ 1 , 2 ] , [ 2 , 2 ] , [ 3 , 1 ] ] NEW_LINE N = len ( A ) NEW_LINE print ( longestSubSequence ( A , N ) ) NEW_LINE DEDENT"} +{"text":"Count triples with Bitwise AND equal to Zero | Function to find the number of triplets whose Bitwise AND is 0. ; Stores the count of triplets having bitwise AND equal to 0 ; Stores frequencies of all possible A [ i ] & A [ j ] ; Traverse the array ; Update frequency of Bitwise AND of all array elements with a ; Traverse the array ; Iterate the map ; If bitwise AND of triplet is zero , increment cnt ; Return the number of triplets whose Bitwise AND is 0. ; Driver Code ; Input Array ; Function Call","code":"def countTriplets ( A ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE tuples = { } ; NEW_LINE for a in A : NEW_LINE INDENT for b in A : NEW_LINE INDENT if ( a & b ) in tuples : NEW_LINE INDENT tuples [ a & b ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT tuples [ a & b ] = 1 ; NEW_LINE DEDENT DEDENT DEDENT for a in A : NEW_LINE INDENT for t in tuples : NEW_LINE INDENT if ( ( t & a ) == 0 ) : NEW_LINE INDENT cnt += tuples [ t ] ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 2 , 1 , 3 ] ; NEW_LINE print ( countTriplets ( A ) ) ; NEW_LINE DEDENT"} +{"text":"Count ways to reach a score using 1 and 2 with no consecutive 2 s | Bottom up approach for counting ways to reach a score using 1 and 2 with consecutive 2 allowed ; noOfWays [ i ] will store count for value i . 3 extra values are to take care of corner case n = 0 ; Loop till \" n + 1\" to compute value for \" n \" ; number of ways if first run is 1 + number of ways if first run is 2 and second run is 1 ; Driver Code","code":"def CountWays ( n ) : NEW_LINE INDENT noOfWays = [ 0 ] * ( n + 3 ) NEW_LINE noOfWays [ 0 ] = 1 NEW_LINE noOfWays [ 1 ] = 1 NEW_LINE noOfWays [ 2 ] = 1 + 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT noOfWays [ i ] = noOfWays [ i - 1 ] + noOfWays [ i - 3 ] NEW_LINE DEDENT return noOfWays [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( CountWays ( n ) ) NEW_LINE DEDENT"} +{"text":"Find the last player to be able to flip a character in a Binary String | Python3 program for the above approach ; Function to check if player A wins the game or not ; Stores size of the groups of 0 s ; Stores size of the group of 0 s ; Traverse the array ; Increment c by 1 if a [ i ] is 0 ; Otherwise , push the size in array and reset c to 0 ; If there is no substring of odd length consisting only of 0 s ; If there is only 1 substring of odd length consisting only of 0 s ; Otherwise ; Stores the size of the largest and second largest substrings of 0 s ; Traverse the array v [ ] ; If current element is greater than first , then update both first and second ; If arr [ i ] is in between first and second , then update second ; If the condition is satisfied ; Driver code","code":"import sys NEW_LINE def findWinner ( a , n ) : NEW_LINE INDENT v = [ ] NEW_LINE c = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( a [ i ] == '0' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( c != 0 ) : NEW_LINE INDENT v . append ( c ) NEW_LINE DEDENT c = 0 NEW_LINE DEDENT DEDENT if ( c != 0 ) : NEW_LINE INDENT v . append ( c ) NEW_LINE DEDENT if ( len ( v ) == 0 ) : NEW_LINE INDENT print ( \" Player \u2581 B \" , end = \" \" ) NEW_LINE return NEW_LINE DEDENT if ( len ( v ) == 1 ) : NEW_LINE INDENT if ( ( v [ 0 ] & 1 ) != 0 ) : NEW_LINE INDENT print ( \" Player \u2581 A \" , end = \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Player \u2581 B \" , end = \" \" ) NEW_LINE DEDENT return NEW_LINE DEDENT first = sys . minsize NEW_LINE second = sys . minsize NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( a [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = a [ i ] NEW_LINE DEDENT elif ( a [ i ] > second and a [ i ] != first ) : NEW_LINE INDENT second = a [ i ] NEW_LINE DEDENT DEDENT if ( ( ( first & 1 ) != 0 ) and ( first + 1 ) \/\/ 2 > second ) : NEW_LINE INDENT print ( \" Player \u2581 A \" , end = \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Player \u2581 B \" , end = \" \" ) NEW_LINE DEDENT DEDENT S = \"1100011\" NEW_LINE N = len ( S ) NEW_LINE findWinner ( S , N ) NEW_LINE"} +{"text":"Check if K palindromic strings can be formed from a given string | Function to check whether the is K palindrome or not ; map to frequency of character ; Check when k is given as same as length of string ; Storing the frequency of every character in map ; If K is greater than size of then return false ; Check that number of character having the odd frequency ; If k is less than number of odd frequency character then it is again false otherwise true ; Driver code","code":"def can_Construct ( S , K ) : NEW_LINE INDENT m = dict ( ) NEW_LINE p = 0 NEW_LINE if ( len ( S ) == K ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in S : NEW_LINE INDENT m [ i ] = m . get ( i , 0 ) + 1 NEW_LINE DEDENT if ( K > len ( S ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT for h in m : NEW_LINE INDENT if ( m [ h ] % 2 != 0 ) : NEW_LINE INDENT p = p + 1 NEW_LINE DEDENT DEDENT DEDENT if ( K < p ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" annabelle \" NEW_LINE K = 4 NEW_LINE if ( can_Construct ( S , K ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Check if two strings are same ignoring their cases | Function to compare two strings ignoring their cases ; Convert to lower case ; Comparing both ; if strings are equal , return true otherwise false ; Function to print the same or not same if strings are equal or not equal ; Driver Code","code":"def equalIgnoreCase ( str1 , str2 ) : NEW_LINE INDENT str1 = str1 . lower ( ) ; NEW_LINE str2 = str2 . lower ( ) ; NEW_LINE x = str1 == str2 ; NEW_LINE return x ; NEW_LINE DEDENT def equalIgnoreCaseUtil ( str1 , str2 ) : NEW_LINE INDENT res = equalIgnoreCase ( str1 , str2 ) ; NEW_LINE if ( res == True ) : NEW_LINE INDENT print ( \" Same \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Same \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" Geeks \" ; NEW_LINE str2 = \" geeks \" ; NEW_LINE equalIgnoreCaseUtil ( str1 , str2 ) ; NEW_LINE str1 = \" Geek \" ; NEW_LINE str2 = \" geeksforgeeks \" ; NEW_LINE equalIgnoreCaseUtil ( str1 , str2 ) ; NEW_LINE DEDENT"} +{"text":"Program to print Step Pattern | Python3 program to print Step Pattern ; function to print the steps ; declare a flag ; traverse through all the characters in the string ; if the x value is 0. . then we must increment till n ... set flag to true ; if the x value is n - 1 then we must decrement till 0 ... set flag as false ; print x * s ; checking whether to increment or decrement x ; Get the String and the number n ; calling the function","code":"import math as mt NEW_LINE def steps ( string , n ) : NEW_LINE INDENT flag = False NEW_LINE x = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT flag = True NEW_LINE DEDENT if ( x == n - 1 ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT for j in range ( x ) : NEW_LINE INDENT print ( \" * \" , end = \" \" ) NEW_LINE DEDENT print ( string [ i ] ) NEW_LINE if ( flag == True ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT x -= 1 NEW_LINE DEDENT DEDENT DEDENT n = 4 NEW_LINE string = \" GeeksForGeeks \" NEW_LINE print ( \" String : \u2581 \" , string ) NEW_LINE print ( \" Max \u2581 Length \u2581 of \u2581 Steps : \u2581 \" , n ) NEW_LINE steps ( string , n ) NEW_LINE"} +{"text":"Frequency Measuring Techniques for Competitive Programming | Python program to count frequencies of array items ; mark all array elements as not visited ; Traverse through array elements and count frequencies ; Skip this element if already processed ; count frequency ; Driver code","code":"def countFreq ( arr , n ) : NEW_LINE INDENT visited = [ False for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if visited [ i ] == True : NEW_LINE INDENT continue NEW_LINE DEDENT count = 1 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ i ] == arr [ j ] : NEW_LINE INDENT visited [ j ] = True NEW_LINE count += 1 NEW_LINE DEDENT DEDENT print ( arr [ i ] , count ) NEW_LINE DEDENT DEDENT a = [ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 ] NEW_LINE n = len ( a ) NEW_LINE countFreq ( a , n ) NEW_LINE"} +{"text":"Check divisibility of binary string by 2 ^ k | function to check whether given binary number is evenly divisible by 2 ^ k or not ; count of number of 0 from last ; if count = k , number is evenly divisible , so returns true else false ; first example ; Second example","code":"def isDivisible ( str , k ) : NEW_LINE INDENT n = len ( str ) NEW_LINE c = 0 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT if ( str [ n - i - 1 ] == '0' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT return ( c == k ) NEW_LINE DEDENT str1 = \"10101100\" NEW_LINE k = 2 NEW_LINE if ( isDivisible ( str1 , k ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT str2 = \"111010100\" NEW_LINE k = 2 NEW_LINE if ( isDivisible ( str2 , k ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Check if any anagram of a string is palindrome or not | Python program to Check if any anagram of a string is palindrome or not ; function to check whether characters of a string can form a palindrome ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; Count odd occurring characters ; Return true if odd count is 0 or 1 , ; Driver program to test to print printDups","code":"NO_OF_CHARS = 256 NEW_LINE def canFormPalindrome ( string ) : NEW_LINE INDENT count = [ 0 for i in range ( NO_OF_CHARS ) ] NEW_LINE for i in string : NEW_LINE INDENT count [ ord ( i ) ] += 1 NEW_LINE DEDENT odd = 0 NEW_LINE for i in range ( NO_OF_CHARS ) : NEW_LINE INDENT if ( count [ i ] & 1 ) : NEW_LINE INDENT odd += 1 NEW_LINE DEDENT if ( odd > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if ( canFormPalindrome ( \" geeksforgeeks \" ) ) : NEW_LINE INDENT print \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT print \" No \" NEW_LINE DEDENT if ( canFormPalindrome ( \" geeksogeeks \" ) ) : NEW_LINE INDENT print \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT print \" NO \" NEW_LINE DEDENT"} +{"text":"Program to check if input is an integer or a string | This function Returns true if s is a number else false ; Driver code ; Store the input in a str variable ; Function returns 1 if all elements are in range '0 \u2581 - \u2581 9' ; Function returns 0 if the input is not an integer","code":"def isNumber ( s ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] . isdigit ( ) != True : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \"6790\" NEW_LINE if isNumber ( str ) : NEW_LINE INDENT print ( \" Integer \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" String \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Print reverse of a string using recursion | Function to print reverse of the passed string ; Driver program to test above function","code":"def reverse ( string ) : NEW_LINE INDENT if len ( string ) == 0 : NEW_LINE INDENT return NEW_LINE DEDENT temp = string [ 0 ] NEW_LINE reverse ( string [ 1 : ] ) NEW_LINE print ( temp , end = ' ' ) NEW_LINE DEDENT string = \" Geeks \u2581 for \u2581 Geeks \" NEW_LINE reverse ( string ) NEW_LINE"} +{"text":"Probability of distributing given balls into two halves having equal count of distinct colors | Stores the count of distinct colors in box1 ; Stores the count of distinct colors in box2 ; Function to calculate the required probability ; Calculate factorial from [ 1 , 10 ] ; Assign all distinct balls to second box ; Total number of balls ; Calculate total number of balls ; If K is an odd number ; Total ways of distributing the balls in two equal halves ; Required number of ways ; Return the required probability ; Function to calculate total number of possible distributions which satisfies the given conditions ; If used balls is equal to K \/ 2 ; If box1 is equal to box2 ; Base condition ; Stores the number of ways of distributing remaining balls without including the current balls in box1 ; Increment box1 by one ; Iterate over the range [ 1 , balls [ i ] ] ; If all the balls goes to box1 , then decrease box2 by one ; Total number of ways of selecting j balls ; Increment res by total number of valid ways of distributing the remaining balls ; Decrement box1 by one ; Increment box2 by 1 ; Function to calculate factorial of N ; Base Case ; Iterate over the range [ 1 , N ] ; Function to calculate NcR ; Driver Code ; Print the result","code":"box1 = 0 NEW_LINE box2 = 0 NEW_LINE fact = [ 0 for i in range ( 11 ) ] NEW_LINE def getProbability ( balls ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE factorial ( 10 ) NEW_LINE box2 = len ( balls ) NEW_LINE K = 0 NEW_LINE for i in range ( len ( balls ) ) : NEW_LINE INDENT K += balls [ i ] NEW_LINE DEDENT if ( K % 2 == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT all = comb ( K , K \/\/ 2 ) NEW_LINE validPermutation = validPermutations ( K \/\/ 2 , balls , 0 , 0 ) NEW_LINE return validPermutation \/ all NEW_LINE DEDENT def validPermutations ( n , balls , usedBalls , i ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE if ( usedBalls == n ) : NEW_LINE INDENT if ( box1 == box2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( i >= len ( balls ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = validPermutations ( n , balls , usedBalls , i + 1 ) NEW_LINE box1 += 1 NEW_LINE for j in range ( 1 , balls [ i ] + 1 ) : NEW_LINE INDENT if ( j == balls [ i ] ) : NEW_LINE INDENT box2 -= 1 NEW_LINE DEDENT combinations = comb ( balls [ i ] , j ) NEW_LINE res += combinations * validPermutations ( n , balls , usedBalls + j , i + 1 ) NEW_LINE DEDENT box1 -= 1 NEW_LINE box2 += 1 NEW_LINE return res NEW_LINE DEDENT def factorial ( N ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT DEDENT def comb ( n , r ) : NEW_LINE INDENT global box1 , box2 , fact NEW_LINE res = fact [ n ] \/\/ fact [ r ] NEW_LINE res \/\/= fact [ n - r ] NEW_LINE return res NEW_LINE DEDENT arr = [ 2 , 1 , 1 ] NEW_LINE N = 4 NEW_LINE print ( getProbability ( arr ) ) NEW_LINE"} +{"text":"Area of a n | Python3 Program to find the area of a regular polygon with given radius ; Function to find the area of a regular polygon ; Side and radius cannot be negative ; Area degree converted to radians ; Driver code","code":"from math import sin NEW_LINE def polyarea ( n , r ) : NEW_LINE INDENT if ( r < 0 and n < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT A = ( ( ( r * r * n ) * sin ( ( 360 \/ n ) * 3.14159 \/ 180 ) ) \/ 2 ) ; NEW_LINE return round ( A , 3 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT r , n = 9 , 6 NEW_LINE print ( polyarea ( n , r ) ) NEW_LINE DEDENT"} +{"text":"Check if a line at 45 degree can divide the plane into two equal weight parts | ; Checking if a plane can be divide by a line at 45 degrees such that weight sum is equal ; Rotating each point by 45 degrees and calculating prefix sum . Also , finding maximum and minimum x coordinates ; storing weight sum upto x - y point ; Finding prefix sum ; Line passes through i , so it neither falls left nor right . ; Driven Program","code":"from collections import defaultdict NEW_LINE def is_partition_possible ( n , x , y , w ) : NEW_LINE INDENT weight_at_x = defaultdict ( int ) NEW_LINE max_x = - 2e3 NEW_LINE min_x = 2e3 NEW_LINE for i in range ( n ) : NEW_LINE INDENT new_x = x [ i ] - y [ i ] NEW_LINE max_x = max ( max_x , new_x ) NEW_LINE min_x = min ( min_x , new_x ) NEW_LINE weight_at_x [ new_x ] += w [ i ] NEW_LINE DEDENT sum_till = [ ] NEW_LINE sum_till . append ( 0 ) NEW_LINE for x in range ( min_x , max_x + 1 ) : NEW_LINE INDENT sum_till . append ( sum_till [ - 1 ] + weight_at_x [ x ] ) NEW_LINE DEDENT total_sum = sum_till [ - 1 ] NEW_LINE partition_possible = False NEW_LINE for i in range ( 1 , len ( sum_till ) ) : NEW_LINE INDENT if ( sum_till [ i ] == total_sum - sum_till [ i ] ) : NEW_LINE INDENT partition_possible = True NEW_LINE DEDENT if ( sum_till [ i - 1 ] == total_sum - sum_till [ i ] ) : NEW_LINE INDENT partition_possible = True NEW_LINE DEDENT DEDENT if partition_possible : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 NEW_LINE x = [ - 1 , - 2 , 1 ] NEW_LINE y = [ 1 , 1 , - 1 ] NEW_LINE w = [ 3 , 1 , 4 ] NEW_LINE is_partition_possible ( n , x , y , w ) NEW_LINE DEDENT"} +{"text":"Slope of perpendicular to line | Function to find the Slope of other line ; Driver code","code":"def findPCSlope ( m ) : NEW_LINE INDENT return - 1.0 \/ m NEW_LINE DEDENT m = 2.0 NEW_LINE print ( findPCSlope ( m ) ) NEW_LINE"} +{"text":"Program to find area of a Circular Segment | Python3 Program to find area of segment of a circle ; Function to find area of segment ; Calculating area of sector ; Calculating area of triangle ; Driver Code","code":"import math NEW_LINE pi = 3.14159 NEW_LINE def area_of_segment ( radius , angle ) : NEW_LINE INDENT area_of_sector = pi * NEW_LINE INDENT ( radius * radius ) NEW_LINE * ( angle \/ 360 ) NEW_LINE DEDENT area_of_triangle = 1 \/ 2 * NEW_LINE INDENT ( radius * radius ) * NEW_LINE math . sin ( ( angle * pi ) \/ 180 ) NEW_LINE DEDENT return area_of_sector - area_of_triangle ; NEW_LINE DEDENT radius = 10.0 NEW_LINE angle = 90.0 NEW_LINE print ( \" Area \u2581 of \u2581 minor \u2581 segment \u2581 = \" , area_of_segment ( radius , angle ) ) NEW_LINE print ( \" Area \u2581 of \u2581 major \u2581 segment \u2581 = \" , area_of_segment ( radius , ( 360 - angle ) ) ) NEW_LINE"} +{"text":"Area of a Circular Sector | Python program to find Area of a Sector ; Calculating area of the sector ; Driver code","code":"def SectorArea ( radius , angle ) : NEW_LINE INDENT pi = 22 \/ 7 NEW_LINE if angle >= 360 : NEW_LINE INDENT print ( \" Angle \u2581 not \u2581 possible \" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT sector = ( pi * radius ** 2 ) * ( angle \/ 360 ) NEW_LINE print ( sector ) NEW_LINE return NEW_LINE DEDENT DEDENT radius = 9 NEW_LINE angle = 60 NEW_LINE SectorArea ( radius , angle ) NEW_LINE"} +{"text":"Make two numbers equal by multiplying with their prime factors minimum number of times | Python program for the above approach ; Function to calculate total number of prime factor with their prime factor ; Iterate while the number is even ; Reduce to half ; Iterate up to sqrt ( N ) ; Iterate while N has factors of i ; Removing one factor of i ; Function to count the number of factors ; Find the GCD ; Find multiples left in X and Y ; Find prime factor of multiple left in X and Y ; Initialize ans ; Check if it possible to obtain X or not ; Check if it possible to obtain Y or not ; return main ans ; Driver Code ; Given Input ; Function Call","code":"import math NEW_LINE def PrimeFactor ( N ) : NEW_LINE INDENT ANS = dict ( ) NEW_LINE while N % 2 == 0 : NEW_LINE INDENT if 2 in ANS : NEW_LINE INDENT ANS [ 2 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ANS [ 2 ] = 1 NEW_LINE DEDENT N = N \/\/ 2 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( N ) ) + 1 , 2 ) : NEW_LINE INDENT while N % i == 0 : NEW_LINE INDENT if i in ANS : NEW_LINE INDENT ANS [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ANS [ i ] = 1 NEW_LINE DEDENT N = N \/\/ i NEW_LINE DEDENT DEDENT if 2 < N : NEW_LINE INDENT ANS [ N ] = 1 NEW_LINE DEDENT return ANS NEW_LINE DEDENT def CountToMakeEqual ( X , Y ) : NEW_LINE INDENT GCD = math . gcd ( X , Y ) NEW_LINE newY = X \/\/ GCD NEW_LINE newX = Y \/\/ GCD NEW_LINE primeX = PrimeFactor ( newX ) NEW_LINE primeY = PrimeFactor ( newY ) NEW_LINE ans = 0 NEW_LINE for factor in primeX : NEW_LINE INDENT if X % factor != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans += primeX [ factor ] NEW_LINE DEDENT for factor in primeY : NEW_LINE INDENT if Y % factor != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans += primeY [ factor ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT X = 36 NEW_LINE Y = 48 NEW_LINE ans = CountToMakeEqual ( X , Y ) NEW_LINE print ( ans ) NEW_LINE DEDENT"} +{"text":"Make given segments non | Python3 program for the above approach ; Function to check whether the graph is bipartite or not ; Mark source node as visited ; Push the source vertex in queue ; Get the front of the queue ; Assign the color to the popped node ; Traverse the adjacency list of the node u ; If any node is visited & a different colors has been assigned , then return false ; Set visited [ x ] ; Push the node x into the queue ; Update color of node ; If the graph is bipartite ; Function to add an edge between the nodes u and v ; Function to check if the assignment of direction can be possible to all the segments , such that they do not intersect after a long period of time ; Stores the adjacency list of the created graph ; Generate all possible pairs ; If segments do not overlap ; Otherwise , the segments overlap ; If both segments have same speed , then add an edge ; Keep the track of visited nodes ; Iterate for all possible nodes ; Check whether graph is bipartite or not ; If the graph is bipartite ; Driver Code","code":"from collections import deque NEW_LINE def check ( Adj , Src , N , visited ) : NEW_LINE INDENT color = [ 0 ] * N NEW_LINE visited = [ True ] * Src NEW_LINE q = deque ( ) NEW_LINE q . append ( Src ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT u = q . popleft ( ) NEW_LINE Col = color [ u ] NEW_LINE for x in Adj [ u ] : NEW_LINE INDENT if ( visited [ x ] == True and color [ x ] == Col ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( visited [ x ] == False ) : NEW_LINE INDENT visited [ x ] = True NEW_LINE q . append ( x ) NEW_LINE color [ x ] = 1 - Col NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def addEdge ( Adj , u , v ) : NEW_LINE INDENT Adj [ u ] . append ( v ) NEW_LINE Adj [ v ] . append ( u ) NEW_LINE return Adj NEW_LINE DEDENT def isPossible ( Arr , N ) : NEW_LINE INDENT Adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( Arr [ i ] [ 0 ] < Arr [ j ] [ 1 ] or Arr [ i ] [ 1 ] > Arr [ j ] [ 0 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( Arr [ i ] [ 2 ] == Arr [ j ] [ 2 ] ) : NEW_LINE INDENT Adj = addEdge ( Adj , i , j ) NEW_LINE DEDENT DEDENT DEDENT DEDENT visited = [ False ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( visited [ i ] == False and len ( Adj [ i ] ) > 0 ) : NEW_LINE INDENT if ( check ( Adj , i , N , visited ) == False ) : NEW_LINE INDENT print ( \" No \" ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( \" Yes \" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 5 , 7 , 2 ] , [ 4 , 6 , 1 ] , [ 1 , 5 , 2 ] , [ 6 , 5 , 1 ] ] NEW_LINE N = len ( arr ) NEW_LINE isPossible ( arr , N ) NEW_LINE DEDENT"} +{"text":"Generate all numbers up to N in Lexicographical Order | Python program for the above approach ; Driver code","code":"def lexNumbers ( n ) : NEW_LINE INDENT sol = [ ] NEW_LINE dfs ( 1 , n , sol ) NEW_LINE print ( \" [ \" , sol [ 0 ] , end = \" \" , sep = \" \" ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT print ( \" , \u2581 \" , sol [ i ] , end = \" \" , sep = \" \" ) print ( \" ] \" ) NEW_LINE DEDENT DEDENT def dfs ( temp , n , sol ) : NEW_LINE INDENT if ( temp > n ) : NEW_LINE INDENT return NEW_LINE DEDENT sol . append ( temp ) NEW_LINE dfs ( temp * 10 , n , sol ) NEW_LINE if ( temp % 10 != 9 ) : NEW_LINE INDENT dfs ( temp + 1 , n , sol ) NEW_LINE DEDENT DEDENT n = 15 NEW_LINE lexNumbers ( n ) NEW_LINE"} +{"text":"Minimum number of swaps required to sort an array of first N number | Function to find minimum swaps ; Initialise count variable ; If current element is not at the right position ; Swap current element with correct position of that element ; Increment for next index when current element is at correct position ; Driver code ; Function to find minimum swaps","code":"def minimumSwaps ( arr ) : NEW_LINE INDENT count = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] != i + 1 ) : NEW_LINE INDENT while ( arr [ i ] != i + 1 ) : NEW_LINE INDENT temp = 0 ; NEW_LINE temp = arr [ arr [ i ] - 1 ] ; NEW_LINE arr [ arr [ i ] - 1 ] = arr [ i ] ; NEW_LINE arr [ i ] = temp ; NEW_LINE count += 1 ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 1 , 5 ] ; NEW_LINE print ( minimumSwaps ( arr ) ) ; NEW_LINE DEDENT"} +{"text":"Merge K sorted Doubly Linked List in Sorted Order | A linked list node ; Given a reference ( pointer to pointer ) to the head Of a DLL and an int , appends a new node at the end ; Allocate node ; Put in the data ; This new node is going to be the last node , so make next of it as None ; If the Linked List is empty , then make the new node as head ; Else traverse till the last node ; Change the next of last node ; Make last node as previous of new node ; Function to print the list ; Run while loop unless node becomes None ; Function to merge two sorted doubly linked lists ; If any of the list is empty ; Comparison the data of two linked list ; Store head pointer before merge the list ; Changing of pointer between Two list for merging ; Changing of pointer between Two list for merging ; Condition to check if any anyone list not end ; Return head pointer of merged list ; Function to merge all sorted linked list in sorted order ; Function call to merge two sorted doubly linked list at a time ; Return final sorted doubly linked list ; Driver code ; Loop to initialize all the lists to empty ; Create first doubly linked List List1 . 1 <= > 5 <= > 9 ; Create second doubly linked List List2 . 2 <= > 3 <= > 7 <= > 12 ; Create third doubly linked List List3 . 8 <= > 11 <= > 13 <= > 18 ; Function call to merge all sorted doubly linked lists in sorted order ; Print final sorted list","code":"class Node : NEW_LINE INDENT def __init__ ( self , new_data ) : NEW_LINE INDENT self . data = new_data NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT def append ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE last = head_ref NEW_LINE new_node . data = new_data NEW_LINE new_node . next = None NEW_LINE if ( head_ref == None ) : NEW_LINE INDENT new_node . prev = None NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT while ( last . next != None ) : NEW_LINE INDENT last = last . next NEW_LINE DEDENT last . next = new_node NEW_LINE new_node . prev = last NEW_LINE return head_ref NEW_LINE DEDENT def printList ( node ) : NEW_LINE INDENT last = None NEW_LINE while ( node != None ) : NEW_LINE INDENT print ( node . data , end = \" \u2581 \" ) NEW_LINE last = node NEW_LINE node = node . next NEW_LINE DEDENT DEDENT def mergeList ( p , q ) : NEW_LINE INDENT s = None NEW_LINE if ( p == None or q == None ) : NEW_LINE INDENT if ( p == None ) : NEW_LINE INDENT return q NEW_LINE DEDENT else : NEW_LINE INDENT return p NEW_LINE DEDENT DEDENT if ( p . data < q . data ) : NEW_LINE INDENT p . prev = s NEW_LINE s = p NEW_LINE p = p . next NEW_LINE DEDENT else : NEW_LINE INDENT q . prev = s NEW_LINE s = q NEW_LINE q = q . next NEW_LINE DEDENT head = s NEW_LINE while ( p != None and q != None ) : NEW_LINE INDENT if ( p . data < q . data ) : NEW_LINE INDENT s . next = p NEW_LINE p . prev = s NEW_LINE s = s . next NEW_LINE p = p . next NEW_LINE DEDENT else : NEW_LINE INDENT s . next = q NEW_LINE q . prev = s NEW_LINE s = s . next NEW_LINE q = q . next NEW_LINE DEDENT DEDENT if ( p == None ) : NEW_LINE INDENT s . next = q NEW_LINE q . prev = s NEW_LINE DEDENT if ( q == None ) : NEW_LINE INDENT s . next = p NEW_LINE p . prev = s NEW_LINE DEDENT return head NEW_LINE DEDENT def mergeAllList ( head , k ) : NEW_LINE INDENT finalList = None NEW_LINE i = 0 NEW_LINE while ( i < k ) : NEW_LINE INDENT finalList = mergeList ( finalList , head [ i ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT return finalList NEW_LINE DEDENT k = 3 NEW_LINE head = [ 0 ] * k NEW_LINE i = 0 NEW_LINE while ( i < k ) : NEW_LINE INDENT head [ i ] = None NEW_LINE i = i + 1 NEW_LINE DEDENT head [ 0 ] = append ( head [ 0 ] , 1 ) NEW_LINE head [ 0 ] = append ( head [ 0 ] , 5 ) NEW_LINE head [ 0 ] = append ( head [ 0 ] , 9 ) NEW_LINE head [ 1 ] = append ( head [ 1 ] , 2 ) NEW_LINE head [ 1 ] = append ( head [ 1 ] , 3 ) NEW_LINE head [ 1 ] = append ( head [ 1 ] , 7 ) NEW_LINE head [ 1 ] = append ( head [ 1 ] , 12 ) NEW_LINE head [ 2 ] = append ( head [ 2 ] , 8 ) NEW_LINE head [ 2 ] = append ( head [ 2 ] , 11 ) NEW_LINE head [ 2 ] = append ( head [ 2 ] , 13 ) NEW_LINE head [ 2 ] = append ( head [ 2 ] , 18 ) NEW_LINE finalList = mergeAllList ( head , k ) NEW_LINE printList ( finalList ) NEW_LINE"} +{"text":"Recursive Selection Sort | Return minimum index ; Find minimum of remaining elements ; Return minimum of current and remaining . ; Recursive selection sort . n is size of a [ ] and index is index of starting element . ; Return when starting and size are same ; calling minimum index function for minimum index ; Swapping when index and minimum index are not same ; swap ; Recursively calling selection sort function ; Driver code ; Calling function ; printing sorted array","code":"def minIndex ( a , i , j ) : NEW_LINE INDENT if i == j : NEW_LINE INDENT return i NEW_LINE DEDENT k = minIndex ( a , i + 1 , j ) NEW_LINE return ( i if a [ i ] < a [ k ] else k ) NEW_LINE DEDENT def recurSelectionSort ( a , n , index = 0 ) : NEW_LINE INDENT if index == n : NEW_LINE INDENT return - 1 NEW_LINE DEDENT k = minIndex ( a , index , n - 1 ) NEW_LINE if k != index : NEW_LINE INDENT a [ k ] , a [ index ] = a [ index ] , a [ k ] NEW_LINE INDENT a [ k ] , a [ index ] = a [ index ] , a [ k ] NEW_LINE DEDENT DEDENT recurSelectionSort ( a , n , index + 1 ) NEW_LINE DEDENT arr = [ 3 , 1 , 5 , 2 , 7 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE recurSelectionSort ( arr , n ) NEW_LINE for i in arr : NEW_LINE INDENT print ( i , end = ' \u2581 ' ) NEW_LINE DEDENT"} +{"text":"Recursive Insertion Sort | Recursive function to sort an array using insertion sort ; base case ; Sort first n - 1 elements ; Insert last element at its correct position in sorted array . ; Move elements of arr [ 0. . i - 1 ] , that are greater than key , to one position ahead of their current position ; A utility function to print an array of size n ; Driver program to test insertion sort","code":"def insertionSortRecursive ( arr , n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return NEW_LINE DEDENT insertionSortRecursive ( arr , n - 1 ) NEW_LINE last = arr [ n - 1 ] NEW_LINE j = n - 2 NEW_LINE while ( j >= 0 and arr [ j ] > last ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT arr [ j + 1 ] = last NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT arr = [ 12 , 11 , 13 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE insertionSortRecursive ( arr , n ) NEW_LINE printArray ( arr , n ) NEW_LINE"} +{"text":"Maximum possible difference of sum of two subsets of an array | Set 2 | Python 3 Program for the above approach ; Stores the positive elements ; Stores the negative elements ; Stores the count of 0 s ; Sum of all positive numbers ; Sum of all negative numbers ; Iterate over the array ; Stores the difference ; Sort the positive numbers in ascending order ; Sort the negative numbers in decreasing order ; Case 1 : Include both positive and negative numbers ; Put all numbers in subset A and one 0 in subset B ; Put all numbers in subset A except the smallest positive number which is put in B ; Put all numbers in subset B and one 0 in subset A ; Place the largest negative number in subset A and remaining in B ; Driver code","code":"def maxSumAfterPartition ( arr , n ) : NEW_LINE INDENT pos = [ ] NEW_LINE neg = [ ] NEW_LINE zero = 0 NEW_LINE pos_sum = 0 NEW_LINE neg_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT pos . append ( arr [ i ] ) NEW_LINE pos_sum += arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < 0 ) : NEW_LINE INDENT neg . append ( arr [ i ] ) NEW_LINE neg_sum += arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE pos . sort ( ) NEW_LINE neg . sort ( reverse = True ) NEW_LINE if ( len ( pos ) > 0 and len ( neg ) > 0 ) : NEW_LINE INDENT ans = ( pos_sum - neg_sum ) NEW_LINE DEDENT elif ( len ( pos ) > 0 ) : NEW_LINE INDENT if ( zero > 0 ) : NEW_LINE INDENT ans = ( pos_sum ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( pos_sum - 2 * pos [ 0 ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( zero > 0 ) : NEW_LINE INDENT ans = ( - 1 * neg_sum ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( neg [ 0 ] - ( neg_sum - neg [ 0 ] ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , - 5 , - 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSumAfterPartition ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values | Function to find the bitwise OR of array elements ; Stores the resultant maximum value of Bitwise XOR ; Traverse the array arr [ ] ; Return the maximum value res ; Driver Code","code":"def MaxXOR ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT res |= arr [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MaxXOR ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Count number of common elements between a sorted array and a reverse sorted array | Function to count the number of elements common in both the arrays ; Used to traverse array A [ ] and B [ ] from the front and the back ; Stores the count of numbers common in both array ; If A [ first ] is less than B [ second ] ; Increment the value of first ; IF B [ second ] is less than A [ first ] ; Decrement the value of second ; A [ first ] is equal to B [ second ] ; Increment the value of count ; Increment the value of first ; Decrement the value of second ; Return the value of count ; Driver Code","code":"def countEqual ( A , B , N ) : NEW_LINE INDENT first = 0 NEW_LINE second = N - 1 NEW_LINE count = 0 NEW_LINE while ( first < N and second >= 0 ) : NEW_LINE INDENT if ( A [ first ] < B [ second ] ) : NEW_LINE INDENT first += 1 NEW_LINE DEDENT elif ( B [ second ] < A [ first ] ) : NEW_LINE INDENT second -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE first += 1 NEW_LINE second -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT A = [ 2 , 4 , 5 , 8 , 12 , 13 , 17 , 18 , 20 , 22 , 309 , 999 ] NEW_LINE B = [ 109 , 99 , 68 , 54 , 22 , 19 , 17 , 13 , 11 , 5 , 3 , 1 ] NEW_LINE N = len ( A ) NEW_LINE print ( countEqual ( A , B , N ) ) NEW_LINE"} +{"text":"Queries to count Palindrome Numbers from a range whose sum of digits is a Prime Number | Python 3 program for the above approach ; Function to check if the number N is palindrome or not ; Store the value of N ; Store the reverse of number N ; Reverse temp and store in res ; If N is the same as res , then return true ; Function to find the sum of the digits of the number N ; Stores the sum of the digits ; Add the last digit of the number N to the sum ; Remove the last digit from N ; Return the resultant sum ; Function to check if N is prime or not ; If i is 1 or 0 , then return false ; Check if i is divisible by any number in the range [ 2 , n \/ 2 ] ; If n is divisible by i ; Function to precompute all the numbers till 10 ^ 5 that are palindromic and whose sum of digits is prime numbers ; Iterate over the range 1 to 10 ^ 5 ; If i is a palindrome number ; Stores the sum of the digits in i ; If the sum of digits in i is a prime number ; Find the prefix sum of arr [ ] ; Function to count all the numbers in the given ranges that are palindromic and the sum of digits is prime numbers ; Function Call to precompute all the numbers till 10 ^ 5 ; Traverse the given queries Q [ ] ; Print the result for each query ; Driver Code ; Function Call","code":"arr = [ 0 for i in range ( 100005 ) ] NEW_LINE def isPalindrome ( N ) : NEW_LINE INDENT temp = N NEW_LINE res = 0 NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT rem = temp % 10 NEW_LINE res = res * 10 + rem NEW_LINE temp \/\/= 10 NEW_LINE DEDENT if ( res == N ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def sumOfDigits ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT sum += N % 10 NEW_LINE N \/\/= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , ( n \/\/ 2 ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def precompute ( ) : NEW_LINE INDENT for i in range ( 1 , 100001 , 1 ) : NEW_LINE INDENT if ( isPalindrome ( i ) ) : NEW_LINE INDENT sum = sumOfDigits ( i ) NEW_LINE if ( isPrime ( sum ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( 1 , 100001 , 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i ] + arr [ i - 1 ] NEW_LINE DEDENT DEDENT def countNumbers ( Q , N ) : NEW_LINE INDENT precompute ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ Q [ i ] [ 1 ] ] - arr [ Q [ i ] [ 0 ] - 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Q = [ [ 5 , 9 ] , [ 1 , 101 ] ] NEW_LINE N = len ( Q ) NEW_LINE countNumbers ( Q , N ) NEW_LINE DEDENT"} +{"text":"Smallest number greater than or equal to N having sum of digits not exceeding S | Function to calculate sum of digits of n ; Function to find the smallest possible integer satisfying the given condition ; If sum of digits is already smaller than s ; Initialize variables ; Find the k - th digit ; Add remaining ; If sum of digits does not exceed s ; Update K ; Given N and S ; Function call","code":"def sum ( n ) : NEW_LINE INDENT sm = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sm += n % 10 NEW_LINE n \/\/= 10 NEW_LINE DEDENT return sm NEW_LINE DEDENT def smallestNumber ( n , s ) : NEW_LINE INDENT if ( sum ( n ) <= s ) : NEW_LINE INDENT return n NEW_LINE DEDENT ans , k = n , 1 NEW_LINE for i in range ( 9 ) : NEW_LINE INDENT digit = ( ans \/\/ k ) % 10 NEW_LINE add = k * ( ( 10 - digit ) % 10 ) NEW_LINE ans += add NEW_LINE if ( sum ( ans ) <= s ) : NEW_LINE INDENT break NEW_LINE DEDENT k *= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT n , s = 3 , 2 NEW_LINE print ( smallestNumber ( n , s ) ) NEW_LINE"} +{"text":"Maximize count of Decreasing Consecutive Subsequences from an Array | Python program to implement the above approach ; Function to find the maximum number number of required subsequences ; Dictionary to store number of arrows available with height of arrow as key ; Stores the maximum count of possible subsequences ; Stores the count of possible subsequences ; Check if i - th element can be part of any of the previous subsequence ; Count of subsequences possible with arr [ i ] as the next element ; If more than one such subsequence exists ; Include arr [ i ] in a subsequence ; Otherwise ; Increase count of subsequence possible with arr [ i ] - 1 as the next element ; Start a new subsequence ; Increase count of subsequence possible with arr [ i ] - 1 as the next element ; Return the answer ; Driver Code","code":"from collections import defaultdict NEW_LINE def maxSubsequences ( arr , n ) -> int : NEW_LINE INDENT m = defaultdict ( int ) NEW_LINE maxCount = 0 NEW_LINE count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] in m . keys ( ) : NEW_LINE INDENT count = m [ arr [ i ] ] NEW_LINE if count > 1 : NEW_LINE INDENT m [ arr [ i ] ] = count - 1 NEW_LINE DEDENT else : NEW_LINE INDENT m . pop ( arr [ i ] ) NEW_LINE DEDENT if arr [ i ] - 1 > 0 : NEW_LINE INDENT m [ arr [ i ] - 1 ] += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT maxCount += 1 NEW_LINE DEDENT maxCount += 1 NEW_LINE INDENT if arr [ i ] - 1 > 0 : NEW_LINE INDENT m [ arr [ i ] - 1 ] += 1 NEW_LINE DEDENT DEDENT DEDENT return maxCount NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE arr = [ 4 , 5 , 2 , 1 , 4 ] NEW_LINE print ( maxSubsequences ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Remove the first and last occurrence of a given Character from a String | Function to remove first and last occurrence of a given character from the given string ; Traverse the given string from the beginning ; If ch is found ; Traverse the given string from the end ; If ch is found ; Driver Code","code":"def removeOcc ( s , ch ) : NEW_LINE INDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ch ) : NEW_LINE INDENT s = s [ 0 : i ] + s [ i + 1 : ] NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == ch ) : NEW_LINE INDENT s = s [ 0 : i ] + s [ i + 1 : ] NEW_LINE break NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT s = \" hello \u2581 world \" NEW_LINE ch = ' l ' NEW_LINE print ( removeOcc ( s , ch ) ) NEW_LINE"} +{"text":"Minimum steps for increasing and decreasing Array to reach either 0 or N | Python3 program for the above approach ; Function that finds the minimum steps to reach either 0 or N for given increasing and decreasing arrays ; Initialize variable to find the minimum element ; Find minimum element in increasing array ; Initialize variable to find the maximum element ; Find maximum element in decreasing array ; Find the minimum steps ; Prthe minimum steps ; Driver Code ; Given N ; Given increasing and decreasing array ; Function call","code":"import sys NEW_LINE def minSteps ( N , increasing , decreasing ) : NEW_LINE INDENT Min = sys . maxsize ; NEW_LINE for i in increasing : NEW_LINE INDENT if ( Min > i ) : NEW_LINE INDENT Min = i ; NEW_LINE DEDENT DEDENT Max = - sys . maxsize ; NEW_LINE for i in decreasing : NEW_LINE INDENT if ( Max < i ) : NEW_LINE INDENT Max = i ; NEW_LINE DEDENT DEDENT minSteps = max ( Max , N - Min ) ; NEW_LINE print ( minSteps ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 7 ; NEW_LINE increasing = [ 3 , 5 ] ; NEW_LINE decreasing = [ 6 ] ; NEW_LINE minSteps ( N , increasing , decreasing ) ; NEW_LINE DEDENT"} +{"text":"Minimum number of adjacent swaps required to convert a permutation to another permutation by given condition | Function to find the minimum number of swaps ; New array to convert to 1 - based indexing ; Keeps count of swaps ; Check if it is an ' X ' position ; Corner Case ; Swap ; Print the minimum swaps ; Given number N ; Given permutation of N numbers ; Function call","code":"def solve ( P , n ) : NEW_LINE INDENT arr = [ ] NEW_LINE arr . append ( 0 ) NEW_LINE for x in P : NEW_LINE INDENT arr . append ( x ) NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == i ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE cnt += 1 NEW_LINE DEDENT DEDENT if ( arr [ n ] == n ) : NEW_LINE INDENT arr [ n - 1 ] , arr [ n ] = arr [ n ] , arr [ n - 1 ] NEW_LINE cnt += 1 NEW_LINE DEDENT print ( cnt ) NEW_LINE DEDENT N = 9 NEW_LINE P = [ 1 , 2 , 4 , 9 , 5 , 8 , 7 , 3 , 6 ] NEW_LINE solve ( P , N ) NEW_LINE"} +{"text":"Count of interesting primes upto N | Function to find all prime numbers ; Create a boolean array \" prime [ 0 . . n ] \" and initialize all entries as true . A value in prime [ i ] will finally be false if i is Not a prime . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it ; Store all prime numbers ; Function to check if a number is perfect square or not ; To store all primes ; To store all interseting primes ; Store all perfect squares ; Store all perfect quadruples ; Store all interseting primes ; Return count of interseting primes ; Driver code","code":"def SieveOfEratosthenes ( n , allPrimes ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) NEW_LINE p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT allPrimes . add ( p ) NEW_LINE DEDENT DEDENT DEDENT def countInterestingPrimes ( n ) : NEW_LINE INDENT allPrimes = set ( ) NEW_LINE SieveOfEratosthenes ( n , allPrimes ) NEW_LINE interestingPrimes = set ( ) NEW_LINE squares , quadruples = [ ] , [ ] NEW_LINE i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT squares . append ( i * i ) NEW_LINE i += 1 NEW_LINE DEDENT i = 1 NEW_LINE while i * i * i * i <= n : NEW_LINE INDENT quadruples . append ( i * i * i * i ) NEW_LINE i += 1 NEW_LINE DEDENT for a in squares : NEW_LINE INDENT for b in quadruples : NEW_LINE INDENT if a + b in allPrimes : NEW_LINE INDENT interestingPrimes . add ( a + b ) NEW_LINE DEDENT DEDENT DEDENT return len ( interestingPrimes ) NEW_LINE DEDENT N = 10 NEW_LINE print ( countInterestingPrimes ( N ) ) NEW_LINE"} +{"text":"Check if an array is Wave Array | Function to check if array is wave array arr : input array n : size of array ; Check the wave form If arr [ 1 ] is greater than left and right . Same pattern will be followed by whole elements , else reverse pattern will be followed by array elements ; Check for last element ; Check for last element ; Driver Code ; Array","code":"def isWaveArray ( arr , n ) : NEW_LINE INDENT result = True NEW_LINE if ( arr [ 1 ] > arr [ 0 ] and arr [ 1 ] > arr [ 2 ] ) : NEW_LINE INDENT for i in range ( 1 , n - 1 , 2 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] and arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT result = True NEW_LINE DEDENT else : NEW_LINE INDENT result = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( result == True and n % 2 == 0 ) : NEW_LINE INDENT if ( arr [ n - 1 ] <= arr [ n - 2 ] ) : NEW_LINE INDENT result = False NEW_LINE DEDENT DEDENT DEDENT elif ( arr [ 1 ] < arr [ 0 ] and arr [ 1 ] < arr [ 2 ] ) : NEW_LINE INDENT for i in range ( 1 , n - 1 , 2 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT result = True NEW_LINE DEDENT else : NEW_LINE INDENT result = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( result == True and n % 2 == 0 ) : NEW_LINE INDENT if ( arr [ n - 1 ] >= arr [ n - 2 ] ) : NEW_LINE INDENT result = False NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE if ( isWaveArray ( arr , n ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times | Function to count number of sequences satisfying the given criteria ; Stores the index of the last occurrence of the element ; Initialize an array to store the number of different sequences that are possible of length i ; Base Case ; If no operation is applied on ith element ; If operation is applied on ith element ; Update the last occurrence of curEle ; Finally , prthe answer ; Driver Code","code":"def countPossiblities ( arr , n ) : NEW_LINE INDENT lastOccur = [ - 1 ] * 100000 NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT curEle = arr [ i - 1 ] NEW_LINE dp [ i ] = dp [ i - 1 ] NEW_LINE if ( lastOccur [ curEle ] != - 1 and lastOccur [ curEle ] < i - 1 ) : NEW_LINE INDENT dp [ i ] += dp [ lastOccur [ curEle ] ] NEW_LINE DEDENT lastOccur [ curEle ] = i NEW_LINE DEDENT print ( dp [ n ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE countPossiblities ( arr , N ) NEW_LINE DEDENT"} +{"text":"Maximum sum possible from given Matrix by performing given operations | Function to prthe maximum sum ; Dp table ; Base case ; Traverse each column ; Update answer for both rows ; Print the maximum sum ; Driver Code ; Given array ; Number of Columns ; Function calls","code":"def maxSum ( arr , n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for i in range ( 2 ) ] NEW_LINE dp [ 0 ] [ m - 1 ] = arr [ 0 ] [ m - 1 ] NEW_LINE dp [ 1 ] [ m - 1 ] = arr [ 1 ] [ m - 1 ] NEW_LINE for j in range ( m - 2 , - 1 , - 1 ) : NEW_LINE INDENT for i in range ( 2 ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( arr [ i ] [ j ] + dp [ 0 ] [ j + 1 ] , arr [ i ] [ j ] + dp [ 0 ] [ j + 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( arr [ i ] [ j ] + dp [ 1 ] [ j + 1 ] , arr [ i ] [ j ] + dp [ 1 ] [ j + 2 ] ) NEW_LINE DEDENT DEDENT DEDENT print ( max ( dp [ 0 ] [ 0 ] , dp [ 1 ] [ 0 ] ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 50 , 21 , 5 ] , [ 2 , 10 , 10 , 5 ] ] NEW_LINE N = len ( arr [ 0 ] ) NEW_LINE maxSum ( arr , 2 , N ) NEW_LINE DEDENT"} +{"text":"Maximum sum possible from given Matrix by performing given operations | Function to print the maximum sum possible by selecting at most one element from each column such that no consecutive pairs are selected from a single row ; Initialize variables ; Traverse each column ; Print answer ; Driver Code ; Numberof columns","code":"def maxSum ( arr , n ) : NEW_LINE INDENT r1 = r2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT r1 , r2 = max ( r1 , r2 + arr [ 0 ] [ i ] ) , max ( r2 , r1 + arr [ 1 ] [ i ] ) NEW_LINE DEDENT print ( max ( r1 , r2 ) ) NEW_LINE DEDENT arr = [ [ 1 , 50 , 21 , 5 ] , [ 2 , 10 , 10 , 5 ] ] NEW_LINE n = len ( arr [ 0 ] ) NEW_LINE maxSum ( arr , n ) NEW_LINE"} +{"text":"Count unimodal and non | Python3 program for the above approach ; Function to calculate the factorials up to a number ; Calculate the factorial ; Function to find power ( a , b ) ; Iterate until b exists ; If b is divisible by 2 ; Decrease the value of b ; Return the answer ; Function that counts the unimodal and non - unimodal permutations of a given integer N ; Function Call for finding factorials up to N ; Function to count unimodal permutations ; Non - unimodal permutation is N ! - unimodal permutations ; Driver Code Given number N ; Function call","code":"mod = 1e9 + 7 NEW_LINE mx = 1000000 NEW_LINE fact = [ 0 ] * ( mx + 1 ) NEW_LINE def Calculate_factorial ( ) : NEW_LINE INDENT fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , mx + 1 ) : NEW_LINE INDENT fact [ i ] = i * fact [ i - 1 ] NEW_LINE fact [ i ] %= mod NEW_LINE DEDENT DEDENT def UniModal_per ( a , b ) : NEW_LINE INDENT res = 1 NEW_LINE while ( b != 0 ) : NEW_LINE INDENT if ( b % 2 != 0 ) : NEW_LINE INDENT res = res * a NEW_LINE DEDENT res %= mod NEW_LINE a = a * a NEW_LINE a %= mod NEW_LINE b \/\/= 2 NEW_LINE DEDENT return res NEW_LINE DEDENT def countPermutations ( n ) : NEW_LINE INDENT Calculate_factorial ( ) NEW_LINE uni_modal = UniModal_per ( 2 , n - 1 ) NEW_LINE nonuni_modal = fact [ n ] - uni_modal NEW_LINE print ( int ( uni_modal ) , \" \" , int ( nonuni_modal ) ) NEW_LINE return NEW_LINE DEDENT N = 4 NEW_LINE countPermutations ( N ) NEW_LINE"} +{"text":"Largest Square in a Binary Matrix with at most K 1 s for multiple Queries | Python3 implementation to find the largest square in the matrix such that it contains at most K 1 's ; Function to calculate the largest square with atmost K 1 s for Q queries ; Loop to solve for each query ; Traversing the each sub square and counting total ; Breaks when exceeds the maximum count ; Driver Code","code":"MAX = 100 NEW_LINE def largestSquare ( matrix , R , C , q_i , q_j , K , Q ) : NEW_LINE INDENT for q in range ( Q ) : NEW_LINE INDENT i = q_i [ q ] NEW_LINE j = q_j [ q ] NEW_LINE min_dist = min ( min ( i , j ) , min ( R - i - 1 , C - j - 1 ) ) NEW_LINE ans = - 1 NEW_LINE for k in range ( min_dist + 1 ) : NEW_LINE INDENT count = 0 NEW_LINE for row in range ( i - k , i + k + 1 ) : NEW_LINE INDENT for col in range ( j - k , j + k + 1 ) : NEW_LINE INDENT count += matrix [ row ] [ col ] NEW_LINE DEDENT DEDENT if count > K : NEW_LINE INDENT break NEW_LINE DEDENT ans = 2 * k + 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT matrix = [ [ 1 , 0 , 1 , 0 , 0 ] , [ 1 , 0 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 1 , 0 ] ] NEW_LINE K = 9 NEW_LINE Q = 1 NEW_LINE q_i = [ 1 ] NEW_LINE q_j = [ 2 ] NEW_LINE largestSquare ( matrix , 4 , 5 , q_i , q_j , K , Q ) NEW_LINE"} +{"text":"Largest Square in a Binary Matrix with at most K 1 s for multiple Queries | Function to find the largest square in the matrix such that it contains atmost K 1 's ; Precomputing the countDP prefix sum of the matrix ; Loop to solve Queries ; Calculating the maximum possible distance of the centre from edge ; Calculating the number of 1 s in the submatrix ; Driver Code","code":"def largestSquare ( matrix , R , C , q_i , q_j , K , Q ) : NEW_LINE INDENT countDP = [ [ 0 for x in range ( C ) ] for x in range ( R ) ] NEW_LINE countDP [ 0 ] [ 0 ] = matrix [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , R ) : NEW_LINE INDENT countDP [ i ] [ 0 ] = ( countDP [ i - 1 ] [ 0 ] + matrix [ i ] [ 0 ] ) NEW_LINE DEDENT for j in range ( 1 , C ) : NEW_LINE INDENT countDP [ 0 ] [ j ] = ( countDP [ 0 ] [ j - 1 ] + matrix [ 0 ] [ j ] ) NEW_LINE DEDENT for i in range ( 1 , R ) : NEW_LINE INDENT for j in range ( 1 , C ) : NEW_LINE INDENT countDP [ i ] [ j ] = ( matrix [ i ] [ j ] + countDP [ i - 1 ] [ j ] + countDP [ i ] [ j - 1 ] - countDP [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT for q in range ( 0 , Q ) : NEW_LINE INDENT i = q_i [ q ] NEW_LINE j = q_j [ q ] NEW_LINE min_dist = min ( i , j , R - i - 1 , C - j - 1 ) NEW_LINE ans = - 1 NEW_LINE for k in range ( 0 , min_dist + 1 ) : NEW_LINE INDENT x1 = i - k NEW_LINE x2 = i + k NEW_LINE y1 = j - k NEW_LINE y2 = j + k NEW_LINE count = countDP [ x2 ] [ y2 ] ; NEW_LINE if ( x1 > 0 ) : NEW_LINE INDENT count -= countDP [ x1 - 1 ] [ y2 ] NEW_LINE DEDENT if ( y1 > 0 ) : NEW_LINE INDENT count -= countDP [ x2 ] [ y1 - 1 ] NEW_LINE DEDENT if ( x1 > 0 and y1 > 0 ) : NEW_LINE INDENT count += countDP [ x1 - 1 ] [ y1 - 1 ] NEW_LINE DEDENT if ( count > K ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = 2 * k + 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT matrix = [ [ 1 , 0 , 1 , 0 , 0 ] , [ 1 , 0 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 1 , 0 ] ] NEW_LINE K = 9 NEW_LINE Q = 1 NEW_LINE q_i = [ 1 ] NEW_LINE q_j = [ 2 ] NEW_LINE largestSquare ( matrix , 4 , 5 , q_i , q_j , K , Q ) NEW_LINE"} +{"text":"N consecutive ropes problem | Function to return the minimum cost to connect the given ropes ; dp [ i ] [ j ] = minimum cost in range ( i , j ) sum [ i ] [ j ] = sum of range ( i , j ) ; Initializing the sum table memset ( sum , 0 , sizeof ( 0 ) ) ; ; Computing minimum cost for all the possible interval ( i , j ) Left range ; Right range ; No cost for a single rope ; Driver code","code":"def MinCost ( arr , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 5 ) ] for i in range ( n + 5 ) ] NEW_LINE sum = [ [ 0 for i in range ( n + 5 ) ] for i in range ( n + 5 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT k = arr [ i ] NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT sum [ i ] [ j ] = k NEW_LINE DEDENT else : NEW_LINE INDENT k += arr [ j ] NEW_LINE sum [ i ] [ j ] = k NEW_LINE DEDENT DEDENT DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT dp [ i ] [ j ] = 10 ** 9 NEW_LINE if ( i == j ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k + 1 ] [ j ] + sum [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ 0 ] [ n - 1 ] NEW_LINE DEDENT arr = [ 7 , 6 , 8 , 6 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( MinCost ( arr , n ) ) NEW_LINE"} +{"text":"Length of the longest subsegment which is UpDown after inserting atmost one integer | Function to recursively fill the dp array ; If f ( i , state ) is already calculated then return the value ; Calculate f ( i , state ) according to the recurrence relation and store in dp [ ] [ ] ; Function that calls the resucrsive function to fill the dp array and then returns the result ; dp [ ] [ ] array for storing result of f ( i , 1 ) and f ( 1 , 2 ) Populating the array dp [ ] with - 1 ; Make sure that longest UD and DU sequence starting at each index is calculated ; Assume the answer to be - 1 This value will only increase ; y is the length of the longest UD sequence starting at i ; If length is even then add an integer and then a DU sequence starting at i + y ; If length is odd then add an integer and then a UD sequence starting at i + y ; Driver Code","code":"def f ( i , state , A , dp , N ) : NEW_LINE INDENT if i >= N : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif dp [ i ] [ state ] != - 1 : NEW_LINE INDENT return dp [ i ] [ state ] NEW_LINE DEDENT else : NEW_LINE INDENT if i == N - 1 : NEW_LINE INDENT dp [ i ] [ state ] = 1 NEW_LINE DEDENT elif state == 1 and A [ i ] > A [ i + 1 ] : NEW_LINE INDENT dp [ i ] [ state ] = 1 NEW_LINE DEDENT elif state == 2 and A [ i ] < A [ i + 1 ] : NEW_LINE INDENT dp [ i ] [ state ] = 1 NEW_LINE DEDENT elif state == 1 and A [ i ] <= A [ i + 1 ] : NEW_LINE INDENT dp [ i ] [ state ] = 1 + f ( i + 1 , 2 , A , dp , N ) NEW_LINE DEDENT elif state == 2 and A [ i ] >= A [ i + 1 ] : NEW_LINE INDENT dp [ i ] [ state ] = 1 + f ( i + 1 , 1 , A , dp , N ) NEW_LINE DEDENT return dp [ i ] [ state ] NEW_LINE DEDENT DEDENT def maxLenSeq ( A , N ) : NEW_LINE INDENT dp = [ [ - 1 , - 1 , - 1 ] for i in range ( 1000 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT tmp = f ( i , 1 , A , dp , N ) NEW_LINE tmp = f ( i , 2 , A , dp , N ) NEW_LINE DEDENT ans = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT y = dp [ i ] [ 1 ] NEW_LINE if ( i + y ) >= N : NEW_LINE INDENT ans = max ( ans , dp [ i ] [ 1 ] + 1 ) NEW_LINE DEDENT elif y % 2 == 0 : NEW_LINE INDENT ans = max ( ans , dp [ i ] [ 1 ] + 1 + dp [ i + y ] [ 2 ] ) NEW_LINE DEDENT elif y % 2 == 1 : NEW_LINE INDENT ans = max ( ans , dp [ i ] [ 1 ] + 1 + dp [ i + y ] [ 1 ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 10 , 3 , 20 , 25 , 24 ] NEW_LINE n = len ( A ) NEW_LINE print ( maxLenSeq ( A , n ) ) NEW_LINE DEDENT"} +{"text":"Remove an element to maximize the GCD of the given array | Python3 implementation of the above approach ; Function to return the maximized gcd after removing a single element from the given array ; Prefix and Suffix arrays ; Single state dynamic programming relation for storing gcd of first i elements from the left in Prefix [ i ] ; Initializing Suffix array ; Single state dynamic programming relation for storing gcd of all the elements having greater than or equal to i in Suffix [ i ] ; If first or last element of the array has to be removed ; If any other element is replaced ; Return the maximized gcd ; Driver code","code":"import math as mt NEW_LINE def MaxGCD ( a , n ) : NEW_LINE INDENT Prefix = [ 0 for i in range ( n + 2 ) ] NEW_LINE Suffix = [ 0 for i in range ( n + 2 ) ] NEW_LINE Prefix [ 1 ] = a [ 0 ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT Prefix [ i ] = mt . gcd ( Prefix [ i - 1 ] , a [ i - 1 ] ) NEW_LINE DEDENT Suffix [ n ] = a [ n - 1 ] NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT Suffix [ i ] = mt . gcd ( Suffix [ i + 1 ] , a [ i - 1 ] ) NEW_LINE DEDENT ans = max ( Suffix [ 2 ] , Prefix [ n - 1 ] ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT ans = max ( ans , mt . gcd ( Prefix [ i - 1 ] , Suffix [ i + 1 ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 14 , 17 , 28 , 70 ] NEW_LINE n = len ( a ) NEW_LINE print ( MaxGCD ( a , n ) ) NEW_LINE"} +{"text":"Maximum subarray sum by flipping signs of at most K array elements | Python3 implementation of the approach ; Function to find the maximum subarray sum with flips starting from index i ; If the number of flips have exceeded ; Complete traversal ; If the state has previously been visited ; Initially ; Use Kadane 's algorithm and call two states ; Memoize the answer and return it ; Utility function to call flips from index and return the answer ; Create DP array int dp [ n , k + 1 ] ; Iterate and call recursive function from every index to get the maximum subarray sum ; corner casae ; Driver Code","code":"import numpy as np NEW_LINE right = 3 ; NEW_LINE left = 6 ; NEW_LINE dp = np . ones ( ( left , right ) ) NEW_LINE dp = - 1 * dp NEW_LINE def findSubarraySum ( ind , flips , n , a , k ) : NEW_LINE INDENT if ( flips > k ) : NEW_LINE INDENT return - 1e9 ; NEW_LINE DEDENT if ( ind == n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ ind ] [ flips ] != - 1 ) : NEW_LINE INDENT return dp [ ind ] [ flips ] ; NEW_LINE DEDENT ans = 0 ; NEW_LINE ans = max ( 0 , a [ ind ] + findSubarraySum ( ind + 1 , flips , n , a , k ) ) ; NEW_LINE ans = max ( ans , - a [ ind ] + findSubarraySum ( ind + 1 , flips + 1 , n , a , k ) ) ; NEW_LINE dp [ ind ] [ flips ] = ans ; NEW_LINE return dp [ ind ] [ flips ] ; NEW_LINE DEDENT def findMaxSubarraySum ( a , n , k ) : NEW_LINE INDENT ans = - 1e9 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , findSubarraySum ( i , 0 , n , a , k ) ) ; NEW_LINE DEDENT if ans == 0 and k == 0 : NEW_LINE return max ( a ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ - 1 , - 2 , - 100 , - 10 ] ; NEW_LINE n = len ( a ) ; NEW_LINE k = 1 ; NEW_LINE print ( findMaxSubarraySum ( a , n , k ) ) ; NEW_LINE DEDENT"} +{"text":"Find the sum of first N odd Fibonacci numbers | Python3 program to Find the sum of first N odd Fibonacci numbers ; Function to calculate sum of first N odd Fibonacci numbers ; base values ; Driver code","code":"mod = 1000000007 ; NEW_LINE def sumOddFibonacci ( n ) : NEW_LINE INDENT Sum = [ 0 ] * ( n + 1 ) ; NEW_LINE Sum [ 0 ] = 0 ; NEW_LINE Sum [ 1 ] = 1 ; NEW_LINE Sum [ 2 ] = 2 ; NEW_LINE Sum [ 3 ] = 5 ; NEW_LINE Sum [ 4 ] = 10 ; NEW_LINE Sum [ 5 ] = 23 ; NEW_LINE for i in range ( 6 , n + 1 ) : NEW_LINE INDENT Sum [ i ] = ( ( Sum [ i - 1 ] + ( 4 * Sum [ i - 2 ] ) % mod - ( 4 * Sum [ i - 3 ] ) % mod + mod ) % mod + ( Sum [ i - 4 ] - Sum [ i - 5 ] + mod ) % mod ) % mod ; NEW_LINE DEDENT return Sum [ n ] ; NEW_LINE DEDENT n = 6 ; NEW_LINE print ( sumOddFibonacci ( n ) ) ; NEW_LINE"} +{"text":"Minimize the total number of teddies to be distributed | Python implementation of the above approach ; Initializing one tablet for each student ; if left adjacent is having higher marks review and change all the dp values assigned before until assigned dp values are found wrong according to given constrains ; if right adjacent is having higher marks add one in dp of left adjacent and assign to right one ; n number of students ; marks of students ; solution of problem","code":"def fun ( marks , n ) : NEW_LINE INDENT dp = [ 1 for i in range ( 0 , n ) ] NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if marks [ i ] > marks [ i + 1 ] : NEW_LINE INDENT temp = i NEW_LINE while True : NEW_LINE INDENT if marks [ temp ] > marks [ temp + 1 ] and temp >= 0 : NEW_LINE INDENT if dp [ temp ] > dp [ temp + 1 ] : NEW_LINE INDENT temp -= 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT dp [ temp ] = dp [ temp + 1 ] + 1 NEW_LINE temp -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT elif marks [ i ] < marks [ i + 1 ] : NEW_LINE INDENT dp [ i + 1 ] = dp [ i ] + 1 NEW_LINE DEDENT DEDENT return ( sum ( dp ) ) NEW_LINE DEDENT n = 6 NEW_LINE marks = [ 1 , 4 , 5 , 2 , 2 , 1 ] NEW_LINE print ( fun ( marks , n ) ) NEW_LINE"} +{"text":"Number of ways to reach Nth floor by taking at | Python3 program to reach N - th stair by taking a maximum of K leap ; elements of combo [ ] stores the no of possible ways to reach it by all combinations of k leaps or less ; assuming leap 0 exist and assigning its value to 1 for calculation ; loop to iterate over all possible leaps upto k ; ; in this loop we count all possible leaps to reach the jth stair with the help of ith leap or less ; if the leap is not more than the i - j ; calculate the value and store in combo [ j ] to reuse it for next leap calculation for the jth stair ; returns the no of possible number of leaps to reach the top of building of n stairs ; Driver Code ; N i the no of total stairs K is the value of the greatest leap","code":"def solve ( N , K ) : NEW_LINE INDENT combo = [ 0 ] * ( N + 1 ) NEW_LINE combo [ 0 ] = 1 NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE INDENT for j in range ( 0 , N + 1 ) : NEW_LINE INDENT if j >= i : NEW_LINE INDENT combo [ j ] += combo [ j - i ] NEW_LINE DEDENT DEDENT DEDENT return combo [ N ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N , K = 29 , 5 NEW_LINE print ( solve ( N , K ) ) NEW_LINE DEDENT"} +{"text":"Find the Longest Increasing Subsequence in Circular manner | Utility method to find LIS using Dynamic programming ; Initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Set j on the basis of current window i . e . first element of the current window ; Pick maximum of all LIS values ; Function to find Longest Increasing subsequence in Circular manner ; Make a copy of given array by appending same array elements to itself ; Perform LIS for each window of size n ; Driver code","code":"def computeLIS ( circBuff , start , end , n ) : NEW_LINE INDENT LIS = [ 0 for i in range ( end ) ] NEW_LINE for i in range ( start , end ) : NEW_LINE INDENT LIS [ i ] = 1 NEW_LINE DEDENT for i in range ( start + 1 , end ) : NEW_LINE INDENT for j in range ( start , i ) : NEW_LINE INDENT if ( circBuff [ i ] > circBuff [ j ] and LIS [ i ] < LIS [ j ] + 1 ) : NEW_LINE INDENT LIS [ i ] = LIS [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT res = - 100000 NEW_LINE for i in range ( start , end ) : NEW_LINE INDENT res = max ( res , LIS [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def LICS ( arr , n ) : NEW_LINE INDENT circBuff = [ 0 for i in range ( 2 * n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT circBuff [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( n , 2 * n ) : NEW_LINE INDENT circBuff [ i ] = arr [ i - n ] NEW_LINE DEDENT res = - 100000 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = max ( computeLIS ( circBuff , i , i + n , n ) , res ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 4 , 6 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Length \u2581 of \u2581 LICS \u2581 is \" , LICS ( arr , n ) ) NEW_LINE"} +{"text":"Counts paths from a point to reach Origin | Function to find binomial Coefficient ; Constructing Pascal 's Triangle ; Driver Code","code":"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 j = min ( i , k ) NEW_LINE while ( j > 0 ) : NEW_LINE INDENT C [ j ] = C [ j ] + C [ j - 1 ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT return C [ k ] NEW_LINE DEDENT n = 3 NEW_LINE m = 2 NEW_LINE print ( \" Number \u2581 of \u2581 Paths : \" , binomialCoeff ( n + m , n ) ) NEW_LINE"} +{"text":"Longest Common Increasing Subsequence ( LCS + LIS ) | Returns the length and the LCIS of two arrays arr1 [ 0. . n - 1 ] and arr2 [ 0. . m - 1 ] ; table [ j ] is going to store length of LCIS ending with arr2 [ j ] . We initialize it as 0 , ; Traverse all elements of arr1 [ ] ; Initialize current length of LCIS ; For each element of arr1 [ ] , traverse all elements of arr2 [ ] . ; If both the array have same elements . Note that we don 't break the loop here. ; Now seek for previous smaller common element for current element of arr1 ; The maximum value in table [ ] is out result ; Driver Code","code":"def LCIS ( arr1 , n , arr2 , m ) : NEW_LINE INDENT table = [ 0 ] * m NEW_LINE for j in range ( m ) : NEW_LINE INDENT table [ j ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT current = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if ( arr1 [ i ] == arr2 [ j ] ) : NEW_LINE INDENT if ( current + 1 > table [ j ] ) : NEW_LINE INDENT table [ j ] = current + 1 NEW_LINE DEDENT DEDENT if ( arr1 [ i ] > arr2 [ j ] ) : NEW_LINE INDENT if ( table [ j ] > current ) : NEW_LINE INDENT current = table [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT result = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( table [ i ] > result ) : NEW_LINE INDENT result = table [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr1 = [ 3 , 4 , 9 , 1 ] NEW_LINE arr2 = [ 5 , 3 , 8 , 9 , 10 , 2 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE print ( \" Length \u2581 of \u2581 LCIS \u2581 is \" , LCIS ( arr1 , n , arr2 , m ) ) NEW_LINE DEDENT"} +{"text":"Length of longest common prefix possible by rearranging strings in a given array | Python3 program to implement the above approach ; Function to get the length of the longest common prefix by rearranging the strings ; freq [ i ] [ j ] : stores the frequency of a character ( = j ) in a arr [ i ] ; Traverse the given array ; Stores length of current string ; Traverse current string of the given array ; Update the value of freq [ i ] [ arr [ i ] [ j ] ] ; Stores the length of longest common prefix ; Count the minimum frequency of each character in in all the strings of arr [ ] ; Stores minimum value in each row of freq [ ] [ ] ; Calculate minimum frequency of current character in all the strings . ; Update minRowVal ; Update maxLen ; Driver Code","code":"import sys NEW_LINE def longComPre ( arr , N ) : NEW_LINE INDENT freq = [ [ 0 for i in range ( 256 ) ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = len ( arr [ i ] ) NEW_LINE for j in range ( M ) : NEW_LINE INDENT freq [ i ] [ ord ( arr [ i ] [ j ] ) ] += 1 NEW_LINE DEDENT DEDENT maxLen = 0 NEW_LINE for j in range ( 256 ) : NEW_LINE INDENT minRowVal = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT minRowVal = min ( minRowVal , freq [ i ] [ j ] ) NEW_LINE DEDENT maxLen += minRowVal NEW_LINE DEDENT return maxLen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ \" aabdc \" , \" abcd \" , \" aacd \" ] NEW_LINE N = 3 NEW_LINE print ( longComPre ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Remove characters from a String that appears exactly K times | Python 3 program to remove characters from a String that appears exactly K times ; Function to reduce the string by removing the characters which appears exactly k times ; Hash table initialised to 0 ; Increment the frequency of the character ; To store answer ; Next index in reduced string ; Append the characters which appears exactly k times ; Driver code ; Function call","code":"MAX_CHAR = 26 NEW_LINE def removeChars ( arr , k ) : NEW_LINE INDENT hash = [ 0 ] * MAX_CHAR NEW_LINE n = len ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ ord ( arr [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = \" \" NEW_LINE index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( hash [ ord ( arr [ i ] ) - ord ( ' a ' ) ] != k ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeksforgeeks \" NEW_LINE k = 2 NEW_LINE print ( removeChars ( str , k ) ) NEW_LINE DEDENT"} +{"text":"Contiguous subsegments of a string having distinct subsequent characters | Function that prints the segments ; New array for every iteration ; Check if the character is in the array ; Driver code","code":"def sub_segments ( string , n ) : NEW_LINE INDENT l = len ( string ) NEW_LINE for x in range ( 0 , l , n ) : NEW_LINE INDENT newlist = string [ x : x + n ] NEW_LINE arr = [ ] NEW_LINE for y in newlist : NEW_LINE INDENT if y not in arr : NEW_LINE INDENT arr . append ( y ) NEW_LINE DEDENT DEDENT print ( ' ' . join ( arr ) ) NEW_LINE DEDENT DEDENT string = \" geeksforgeeksgfg \" NEW_LINE n = 4 NEW_LINE sub_segments ( string , n ) NEW_LINE"} +{"text":"Program to find the Encrypted word | Function to find the encrypted string ; to store the encrypted string ; after ' z ' , it should go to a . ; Driver code","code":"def findWord ( c , n ) : NEW_LINE INDENT co = 0 NEW_LINE s = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n \/ 2 ) : NEW_LINE INDENT co += 1 NEW_LINE DEDENT else : NEW_LINE INDENT co = n - i NEW_LINE DEDENT if ( ord ( c [ i ] ) + co <= 122 ) : NEW_LINE INDENT s [ i ] = chr ( ord ( c [ i ] ) + co ) NEW_LINE DEDENT else : NEW_LINE INDENT s [ i ] = chr ( ord ( c [ i ] ) + co - 26 ) NEW_LINE DEDENT DEDENT print ( * s , sep = \" \" ) NEW_LINE DEDENT s = \" abcd \" NEW_LINE findWord ( s , len ( s ) ) NEW_LINE"} +{"text":"Check if two strings are same ignoring their cases | Function to compare two strings ignoring their cases ; length of first string ; length of second string ; if length is not same simply return false since both string can not be same if length is not equal ; loop to match one by one all characters of both string ; if current characters of both string are same , increase value of i to compare next character ; if any character of first string is some special character or numeric character and not same as corresponding character of second string then return false ; do the same for second string ; this block of code will be executed if characters of both strings are of different cases ; compare characters by ASCII value ; if characters matched , increase the value of i to compare next char ; if all characters of the first string are matched with corresponding characters of the second string , then return true ; Function to print the same or not same if strings are equal or not equal ; Driver Code","code":"def equalIgnoreCase ( str1 , str2 ) : NEW_LINE INDENT i = 0 NEW_LINE len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE if ( len1 != len2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( i < len1 ) : NEW_LINE INDENT if ( str1 [ i ] == str2 [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( ( ( str1 [ i ] >= ' a ' and str1 [ i ] <= ' z ' ) or ( str1 [ i ] >= ' A ' and str1 [ i ] <= ' Z ' ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( ( ( str2 [ i ] >= ' a ' and str2 [ i ] <= ' z ' ) or ( str2 [ i ] >= ' A ' and str2 [ i ] <= ' Z ' ) ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT if ( str1 [ i ] >= ' a ' and str1 [ i ] <= ' z ' ) : NEW_LINE INDENT if ( ord ( str1 [ i ] ) - 32 != ord ( str2 [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT elif ( str1 [ i ] >= ' A ' and str1 [ i ] <= ' Z ' ) : NEW_LINE INDENT if ( ord ( str1 [ i ] ) + 32 != ord ( str2 [ i ] ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def equalIgnoreCaseUtil ( str1 , str2 ) : NEW_LINE INDENT res = equalIgnoreCase ( str1 , str2 ) NEW_LINE if ( res == True ) : NEW_LINE INDENT print ( \" Same \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Same \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \" Geeks \" NEW_LINE str2 = \" geeks \" NEW_LINE equalIgnoreCaseUtil ( str1 , str2 ) NEW_LINE str1 = \" Geek \" NEW_LINE str2 = \" geeksforgeeks \" NEW_LINE equalIgnoreCaseUtil ( str1 , str2 ) NEW_LINE DEDENT"} +{"text":"Maximize the value of A by replacing some of its digits with digits of B | Function to return the maximized value of A ; Sort digits in ascending order ; j points to largest digit in B ; If all the digits of b have been used ; Current digit has been used ; Return the maximized value ; Driver code","code":"def maxValue ( a , b ) : NEW_LINE INDENT b = sorted ( b ) NEW_LINE bi = [ i for i in b ] NEW_LINE ai = [ i for i in a ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE j = m - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( j < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( bi [ j ] > ai [ i ] ) : NEW_LINE INDENT ai [ i ] = bi [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT x = \" \" . join ( ai ) NEW_LINE return x NEW_LINE DEDENT a = \"1234\" NEW_LINE b = \"4321\" NEW_LINE print ( maxValue ( a , b ) ) NEW_LINE"} +{"text":"Count numbers in range such that digits in it and it 's product with q are unequal | Function to check if all of the digits in a number and it 's product with q are unequal or not ; convert first number into string ; Insert elements from 1 st number to hash ; Calculate corresponding product ; Convert the product to string ; Using the hash check if any digit of product matches with the digits of input number ; If yes , return false ; Return true ; Function to count numbers in the range [ l , r ] such that all of the digits of the number and it 's product with q are unequal ; check for every number between l and r ; Driver Code ; Function call","code":"def checkIfUnequal ( n , q ) : NEW_LINE INDENT s1 = str ( n ) NEW_LINE a = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( 0 , len ( s1 ) , 1 ) : NEW_LINE INDENT a [ ord ( s1 [ i ] ) - ord ( '0' ) ] += 1 NEW_LINE DEDENT prod = n * q NEW_LINE s2 = str ( prod ) NEW_LINE for i in range ( 0 , len ( s2 ) , 1 ) : NEW_LINE INDENT if ( a [ ord ( s2 [ i ] ) - ord ( '0' ) ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def countInRange ( l , r , q ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r + 1 , 1 ) : NEW_LINE INDENT if ( checkIfUnequal ( i , q ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 10 NEW_LINE r = 12 NEW_LINE q = 2 NEW_LINE print ( countInRange ( l , r , q ) ) NEW_LINE DEDENT"} +{"text":"Check if it is possible to rearrange a binary string with alternate 0 s and 1 s | function to check the binary string ; length of string ; count zero 's ; count one 's ; if length is even ; if length is odd ; Driver code","code":"def is_possible ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT one += 1 NEW_LINE DEDENT DEDENT if ( l % 2 == 0 ) : NEW_LINE INDENT return ( one == zero ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( abs ( one - zero ) == 1 ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"100110\" NEW_LINE if ( is_possible ( s ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Frequency Measuring Techniques for Competitive Programming | Python3 program to count frequencies of array items ; Create an array to store counts . The size of array is limit + 1 and all values are initially 0 ; Traverse through string characters and count frequencies ;","code":"limit = 255 NEW_LINE def countFreq ( Str ) : NEW_LINE INDENT count = [ 0 ] * ( limit + 1 ) NEW_LINE for i in range ( len ( Str ) ) : NEW_LINE INDENT count [ ord ( Str [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( limit + 1 ) : NEW_LINE if ( count [ i ] > 0 ) : NEW_LINE INDENT print ( chr ( i ) , count [ i ] ) NEW_LINE DEDENT DEDENT \/ * Driver Code * \/ NEW_LINE Str = \" GeeksforGeeks \" NEW_LINE countFreq ( Str ) NEW_LINE"} +{"text":"Count of even and odd set bit with array element after XOR with K | Function to store EVEN and odd variable ; Store the count of even and odd set bit ; Count the set bit using in built function ; Count of set - bit of K ; If y is odd then , count of even and odd set bit will be interchanged ; Else it will remain same as the original array ; Driver 's Code ; Function call to count even and odd","code":"def countEvenOdd ( arr , n , K ) : NEW_LINE INDENT even = 0 ; odd = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = bin ( arr [ i ] ) . count ( '1' ) ; NEW_LINE if ( x % 2 == 0 ) : NEW_LINE INDENT even += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT odd += 1 ; NEW_LINE DEDENT DEDENT y = bin ( K ) . count ( '1' ) ; NEW_LINE if ( y & 1 ) : NEW_LINE INDENT print ( \" Even \u2581 = \" , odd , \" , \u2581 Odd \u2581 = \" , even ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Even \u2581 = \" , even , \" , \u2581 Odd \u2581 = \" , odd ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 4 , 2 , 15 , 9 , 8 , 8 ] ; NEW_LINE K = 3 ; NEW_LINE n = len ( arr ) ; NEW_LINE countEvenOdd ( arr , n , K ) ; NEW_LINE DEDENT"} +{"text":"gOOGLE cASE of a given sentence | Python program to convert given sentence to camel case . ; Function to remove spaces and convert into camel case ; check for spaces in the sentence ; conversion into upper case ; If not space , copy character ; return string to main ; Driver code","code":"import math NEW_LINE def convert ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE s1 = \" \" NEW_LINE s1 = s1 + s [ 0 ] . lower ( ) NEW_LINE i = 1 NEW_LINE while i < n : NEW_LINE INDENT if ( s [ i ] == ' \u2581 ' and i <= n ) : NEW_LINE INDENT s1 = s1 + \" \u2581 \" + ( s [ i + 1 ] ) . lower ( ) NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT s1 = s1 + ( s [ i ] ) . upper ( ) NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT return s1 NEW_LINE DEDENT str = \" I \u2581 get \u2581 intern \u2581 at \u2581 geeksforgeeks \" NEW_LINE print ( convert ( str ) ) NEW_LINE"} +{"text":"Program to find the N | Python3 program to find n - th number containing only 3 and 5. ; If n is odd , append 3 and move to parent ; If n is even , append 5 and move to parent ; Reverse res and return . ; Driver code","code":"def reverse ( s ) : NEW_LINE INDENT if len ( s ) == 0 : NEW_LINE INDENT return s NEW_LINE DEDENT else : NEW_LINE INDENT return reverse ( s [ 1 : ] ) + s [ 0 ] NEW_LINE DEDENT DEDENT def findNthNo ( n ) : NEW_LINE INDENT res = \" \" ; NEW_LINE while ( n >= 1 ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT res = res + \"3\" ; NEW_LINE n = ( int ) ( ( n - 1 ) \/ 2 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT res = res + \"5\" ; NEW_LINE n = ( int ) ( ( n - 2 ) \/ 2 ) ; NEW_LINE DEDENT DEDENT return reverse ( res ) ; NEW_LINE DEDENT n = 5 ; NEW_LINE print ( findNthNo ( n ) ) ; NEW_LINE"} +{"text":"Nth non | Python3 program to find n - th non - square number . ; function to find the nth Non - Square Number ; conversion from int to long double is necessary in order to preserve decimal places after square root . ; calculating the result ; initializing the term number ; Print the result","code":"import math NEW_LINE def findNthNonSquare ( n ) : NEW_LINE INDENT x = n ; NEW_LINE ans = x + math . floor ( 0.5 + math . sqrt ( x ) ) ; NEW_LINE return int ( ans ) ; NEW_LINE DEDENT n = 16 ; NEW_LINE print ( \" The \" , n , \" th \u2581 Non - Square \u2581 number \u2581 is \" , findNthNonSquare ( n ) ) ; NEW_LINE"} +{"text":"Sum of series with alternate signed squares of AP | Function to calculate series sum ; Driver code","code":"def seiresSum ( n , a ) : NEW_LINE INDENT return ( n * ( a [ 0 ] * a [ 0 ] - a [ 2 * n - 1 ] * a [ 2 * n - 1 ] ) \/ ( 2 * n - 1 ) ) NEW_LINE DEDENT n = 2 NEW_LINE a = [ 1 , 2 , 3 , 4 ] NEW_LINE print ( int ( seiresSum ( n , a ) ) ) NEW_LINE"} +{"text":"Find nth number that contains the digit k or divisible by k . | Function for checking if digit k is in n or not ; finding remainder ; if digit found ; Function for finding nth number ; since k is the first which satisfy th criteria , so consider it in count making count = 1 and starting from i = k + 1 ; checking that the number contain k digit or divisible by k ; Driver code","code":"def checkdigit ( n , k ) : NEW_LINE INDENT while ( n ) : NEW_LINE INDENT rem = n % 10 NEW_LINE if ( rem == k ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT n = n \/ 10 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def findNthNumber ( n , k ) : NEW_LINE INDENT i = k + 1 NEW_LINE count = 1 NEW_LINE while ( count < n ) : NEW_LINE INDENT if ( checkdigit ( i , k ) or ( i % k == 0 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count == n ) : NEW_LINE INDENT return i NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT n = 10 NEW_LINE k = 2 NEW_LINE print ( findNthNumber ( n , k ) ) NEW_LINE"} +{"text":"Count of subarrays of size K which is a permutation of numbers from 1 to K | Python3 program to implement the above approach ; Save index of numbers of the array ; Update min and max index with the current index and check if it 's a valid permutation ; Driver code","code":"def find_permutations ( arr ) : NEW_LINE INDENT cnt = 0 NEW_LINE max_ind = - 1 NEW_LINE min_ind = 10000000 ; NEW_LINE n = len ( arr ) NEW_LINE index_of = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT index_of [ arr [ i ] ] = i + 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT max_ind = max ( max_ind , index_of [ i ] ) NEW_LINE min_ind = min ( min_ind , index_of [ i ] ) NEW_LINE if ( max_ind - min_ind + 1 == i ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT nums = [ ] NEW_LINE nums . append ( 2 ) NEW_LINE nums . append ( 3 ) NEW_LINE nums . append ( 1 ) NEW_LINE nums . append ( 5 ) NEW_LINE nums . append ( 4 ) NEW_LINE print ( find_permutations ( nums ) ) NEW_LINE DEDENT"} +{"text":"Count of integers that divide all the elements of the given array | Function to return the count of the required integers ; To store the gcd of the array elements ; To store the count of factors of the found gcd ; If g is a perfect square ; Factors appear in pairs ; Driver code","code":"from math import gcd as __gcd NEW_LINE def getCount ( a , n ) : NEW_LINE INDENT gcd = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT gcd = __gcd ( gcd , a [ i ] ) NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 1 , gcd + 1 ) : NEW_LINE INDENT if i * i > gcd : NEW_LINE INDENT break NEW_LINE DEDENT if ( gcd % i == 0 ) : NEW_LINE INDENT if ( i * i == gcd ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 2 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT a = [ 4 , 16 , 1024 , 48 ] NEW_LINE n = len ( a ) NEW_LINE print ( getCount ( a , n ) ) NEW_LINE"} +{"text":"Minimize cost of removals required to make all remaining characters of the string unique | Function to find the minimum cost of removing characters to make the string unique ; Stores the visited characters ; Stores the answer ; Traverse the string ; If already visited ; Stores the maximum cost of removing a particular character ; Store the total deletion cost of a particular character ; Mark the current character visited ; Traverse the indices of the string [ i , N - 1 ] ; If any duplicate is found ; Update the maximum cost and total cost ; Mark the current character visited ; Keep the character with maximum cost and delete the rest ; Return the minimum cost ; Driver code Given string ; input array ; input array ; Function Call","code":"def delCost ( s , cost ) : NEW_LINE INDENT visited = [ False ] * len ( s ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if visited [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT maxDel = 0 NEW_LINE totCost = 0 NEW_LINE visited [ i ] = True NEW_LINE for j in range ( i , len ( s ) ) : NEW_LINE INDENT if s [ i ] == s [ j ] : NEW_LINE INDENT maxDel = max ( maxDel , cost [ j ] ) NEW_LINE totCost += cost [ j ] NEW_LINE visited [ j ] = True NEW_LINE DEDENT DEDENT ans += totCost - maxDel NEW_LINE DEDENT return ans NEW_LINE DEDENT string = \" AAABBB \" NEW_LINE cost = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE string = \" AAABBB \" NEW_LINE print ( delCost ( string , cost ) ) NEW_LINE"} +{"text":"Make all array elements equal by replacing triplets with their Bitwise XOR | Function to find triplets such that replacing them with their XOR make all array elements equal ; If N is even ; Calculate xor of array elements ; Traverse the array ; Update xor ; If xor is not equal to 0 ; Selecting the triplets such that elements of the pairs ( arr [ 0 ] , arr [ 1 ] ) , ( arr [ 2 ] , arr [ 3 ] ) . . . can be made equal ; Selecting the triplets such that all array elements can be made equal to arr [ N - 1 ] ; Selecting the triplets such that elements of the pairs ( arr [ 0 ] , arr [ 1 ] ) , ( arr [ 2 ] , arr [ 3 ] ) . . . can be made equal ; Selecting the triplets such that all array elements can be made equal to arr [ N - 1 ] ; Driver code ; Given array ; Size of array ; Function call","code":"def checkXOR ( arr , N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT xro = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT xro ^= arr [ i ] ; NEW_LINE DEDENT if ( xro != 0 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE return ; NEW_LINE DEDENT for i in range ( 0 , N - 3 , 2 ) : NEW_LINE INDENT print ( i , \" \u2581 \" , ( i + 1 ) , \" \u2581 \" , ( i + 2 ) , end = \" \u2581 \" ) ; NEW_LINE DEDENT for i in range ( 0 , N - 3 , 2 ) : NEW_LINE INDENT print ( i , \" \u2581 \" , ( i + 1 ) , \" \u2581 \" , ( N - 1 ) , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 0 , N - 2 , 2 ) : NEW_LINE INDENT print ( i , \" \u2581 \" , ( i + 1 ) , \" \u2581 \" , ( i + 2 ) ) ; NEW_LINE DEDENT for i in range ( 0 , N - 2 , 2 ) : NEW_LINE INDENT print ( i , \" \u2581 \" , ( i + 1 ) , \" \u2581 \" , ( N - 1 ) ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 1 , 7 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE checkXOR ( arr , N ) ; NEW_LINE DEDENT"} +{"text":"Make all array elements even by replacing adjacent pair of array elements with their sum | Function to find minimum count of operations required to make all array elements even ; Stores minimum count of replacements to make all array elements even ; Stores the count of odd continuous numbers ; Traverse the array ; If arr [ i ] is an odd number ; Update odd_cont_seg ; If odd_cont_seg is even ; Update res ; Update res ; Reset odd_cont_seg = 0 ; If odd_cont_seg exceeds 0 ; If odd_cont_seg is even ; Update res ; Update res ; Prthe result ; Drivers Code","code":"def make_array_element_even ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE odd_cont_seg = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT odd_cont_seg += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( odd_cont_seg > 0 ) : NEW_LINE INDENT if ( odd_cont_seg % 2 == 0 ) : NEW_LINE INDENT res += odd_cont_seg \/\/ 2 NEW_LINE DEDENT else : NEW_LINE INDENT res += ( odd_cont_seg \/\/ 2 ) + 2 NEW_LINE DEDENT odd_cont_seg = 0 NEW_LINE DEDENT DEDENT DEDENT if ( odd_cont_seg > 0 ) : NEW_LINE INDENT if ( odd_cont_seg % 2 == 0 ) : NEW_LINE INDENT res += odd_cont_seg \/\/ 2 NEW_LINE DEDENT else : NEW_LINE INDENT res += odd_cont_seg \/\/ 2 + 2 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 2 , 4 , 5 , 11 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( make_array_element_even ( arr , N ) ) NEW_LINE"} +{"text":"Find a number K such that exactly K array elements are greater than or equal to K | Function to find K for which there are exactly K array elements greater than or equal to K ; Finding the largest array element ; Possible values of K ; Traverse the array ; If current array element is greater than or equal to i ; If i array elements are greater than or equal to i ; Otherwise ; Driver Code","code":"def zvalue ( nums ) : NEW_LINE INDENT m = max ( nums ) NEW_LINE cnt = 0 NEW_LINE for i in range ( 0 , m + 1 , 1 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for j in range ( 0 , len ( nums ) , 1 ) : NEW_LINE INDENT if ( nums [ j ] >= i ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt == i ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT nums = [ 7 , 8 , 9 , 0 , 0 , 1 ] NEW_LINE print ( zvalue ( nums ) ) NEW_LINE DEDENT"} +{"text":"Lexicographically smallest and largest anagrams of a string containing another string as its substring | Function to find the lexicographically smallest anagram of string which contains another string ; Initializing the dictionary and set ; Iterating over s1 ; Storing the frequency of characters present in s1 ; Storing the distinct characters present in s1 ; Decreasing the frequency of characters from M that are already present in s2 ; Traversing alphabets in sorted order ; If current character of set is not equal to current character of s2 ; If element is equal to current character of s2 ; Checking for second distinct character in s2 ; s2 [ j ] will store second distinct character ; Return the answer ; Function to find the lexicographically largest anagram of string which contains another string ; Getting the lexicographically smallest anagram ; d1 stores the prefix ; d2 stores the suffix ; Return the result ; Given two strings ; Function Calls","code":"def lexico_smallest ( s1 , s2 ) : NEW_LINE INDENT M = { } NEW_LINE S = [ ] NEW_LINE pr = { } NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if s1 [ i ] not in M : NEW_LINE INDENT M [ s1 [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT M [ s1 [ i ] ] += 1 NEW_LINE DEDENT S . append ( s1 [ i ] ) NEW_LINE DEDENT S = list ( set ( S ) ) NEW_LINE S . sort ( ) NEW_LINE for i in range ( len ( s2 ) ) : NEW_LINE INDENT if s2 [ i ] in M : NEW_LINE INDENT M [ s2 [ i ] ] -= 1 NEW_LINE DEDENT DEDENT c = s2 [ 0 ] NEW_LINE index = 0 NEW_LINE res = \" \" NEW_LINE for x in S : NEW_LINE INDENT if ( x != c ) : NEW_LINE INDENT for i in range ( 1 , M [ x ] + 1 ) : NEW_LINE INDENT res += x NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT j = 0 NEW_LINE index = len ( res ) NEW_LINE while ( s2 [ j ] == x ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( s2 [ j ] < c ) : NEW_LINE INDENT res += s2 NEW_LINE for i in range ( 1 , M [ x ] + 1 ) : NEW_LINE INDENT res += x NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 1 , M [ x ] + 1 ) : NEW_LINE INDENT res += x NEW_LINE DEDENT index += M [ x ] NEW_LINE res += s2 NEW_LINE DEDENT DEDENT DEDENT pr [ res ] = index NEW_LINE return pr NEW_LINE DEDENT def lexico_largest ( s1 , s2 ) : NEW_LINE INDENT Pr = dict ( lexico_smallest ( s1 , s2 ) ) NEW_LINE d1 = \" \" NEW_LINE key = [ * Pr ] [ 0 ] NEW_LINE for i in range ( Pr . get ( key ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT d1 += key [ i ] NEW_LINE DEDENT d2 = \" \" NEW_LINE for i in range ( len ( key ) - 1 , Pr [ key ] + len ( s2 ) - 1 , - 1 ) : NEW_LINE INDENT d2 += key [ i ] NEW_LINE DEDENT res = d2 + s2 + d1 NEW_LINE return res NEW_LINE DEDENT s1 = \" ethgakagmenpgs \" NEW_LINE s2 = \" geeks \" NEW_LINE print ( * lexico_smallest ( s1 , s2 ) ) NEW_LINE print ( lexico_largest ( s1 , s2 ) ) NEW_LINE"} +{"text":"Queries to find the count of shortest paths in a Tree that contains a given edge | Python3 implementation for the above approach ; Adjacency list to represent the tree ; Number of vertices ; Mark visited \/ unvisited vertices ; Stores the subtree size of the corresponding nodes ; Function to create an edge between two vertices ; Add a to b 's list ; Add b to a 's list ; Function to perform DFS ; Mark the vertex visited ; Include the node in the subtree ; Traverse all its children ; Function to print the required number of paths ; Driver Code ; Number of vertices ; Calling modified dfs function ; Count pairs of vertices in the tree","code":"sz = 100000 NEW_LINE tree = [ [ ] for i in range ( sz ) ] NEW_LINE n = 0 NEW_LINE vis = [ False ] * sz NEW_LINE subtreeSize = [ 0 for i in range ( sz ) ] NEW_LINE def addEdge ( a , b ) : NEW_LINE INDENT global tree NEW_LINE tree [ a ] . append ( b ) NEW_LINE tree [ b ] . append ( a ) NEW_LINE DEDENT def dfs ( x ) : NEW_LINE INDENT global vis NEW_LINE global subtreeSize NEW_LINE global tree NEW_LINE vis [ x ] = True NEW_LINE subtreeSize [ x ] = 1 NEW_LINE for i in tree [ x ] : NEW_LINE INDENT if ( vis [ i ] == False ) : NEW_LINE INDENT dfs ( i ) NEW_LINE subtreeSize [ x ] += subtreeSize [ i ] NEW_LINE DEDENT DEDENT DEDENT def countPairs ( a , b ) : NEW_LINE INDENT global subtreeSize NEW_LINE sub = min ( subtreeSize [ a ] , subtreeSize [ b ] ) NEW_LINE print ( sub * ( n - sub ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE addEdge ( 0 , 1 ) NEW_LINE addEdge ( 0 , 2 ) NEW_LINE addEdge ( 1 , 3 ) NEW_LINE addEdge ( 3 , 4 ) NEW_LINE addEdge ( 3 , 5 ) NEW_LINE dfs ( 0 ) NEW_LINE countPairs ( 1 , 3 ) NEW_LINE countPairs ( 0 , 2 ) NEW_LINE DEDENT"} +{"text":"Count of permutations of an Array having each element as a multiple or a factor of its index | Function to find the count of desired permutations ; Base case ; If i has not been inserted ; Backtrack ; Insert i ; Recur to find valid permutations ; Remove i ; Return the final count ; Driver Code","code":"def findPermutation ( arr , N ) : NEW_LINE INDENT pos = len ( arr ) + 1 NEW_LINE if ( pos > N ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i not in arr ) : NEW_LINE INDENT if ( i % pos == 0 or pos % i == 0 ) : NEW_LINE INDENT arr . add ( i ) NEW_LINE res += findPermutation ( arr , N ) NEW_LINE arr . remove ( i ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT N = 5 NEW_LINE arr = set ( ) NEW_LINE print ( findPermutation ( arr , N ) ) NEW_LINE"} +{"text":"Check if sum Y can be obtained from the Array by the given operations | Function to check if it is possible to obtain sum Y from a sequence of sum X from the array arr [ ] ; Store the difference ; Iterate over the array ; If diff reduced to 0 ; Driver Code","code":"def solve ( arr , n , X , Y ) : NEW_LINE INDENT diff = Y - X NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != 1 ) : NEW_LINE INDENT diff = diff % ( arr [ i ] - 1 ) NEW_LINE DEDENT DEDENT if ( diff == 0 ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 7 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE X , Y = 11 , 13 NEW_LINE solve ( arr , n , X , Y ) NEW_LINE"} +{"text":"Farthest distance of a Node from each Node of a Tree | Python3 program to implement the above approach ; Adjacency List to store the graph ; Stores the height of each node ; Stores the maximum distance of a node from its ancestors ; Function to add edge between two vertices ; Insert edge from u to v ; Insert edge from v to u ; Function to calculate height of each Node ; Iterate in the adjacency list of the current node ; Dfs for child node ; Calculate height of nodes ; Increase height ; Function to calculate the maximum distance of a node from its ancestor ; Iterate in the adjacency list of the current node ; Find two children with maximum heights ; Calculate the maximum distance with ancestor for every node ; Calculating for children ; Driver Code ; Calculate height of nodes of the tree ; Calculate the maximum distance with ancestors ; Print the maximum of the two distances from each node","code":"maxN = 100001 NEW_LINE adj = [ [ ] for i in range ( maxN ) ] NEW_LINE height = [ 0 for i in range ( maxN ) ] NEW_LINE dist = [ 0 for i in range ( maxN ) ] NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def dfs1 ( cur , par ) : NEW_LINE INDENT for u in adj [ cur ] : NEW_LINE INDENT if ( u != par ) : NEW_LINE INDENT dfs1 ( u , cur ) NEW_LINE height [ cur ] = max ( height [ cur ] , height [ u ] ) NEW_LINE DEDENT DEDENT height [ cur ] += 1 NEW_LINE DEDENT def dfs2 ( cur , par ) : NEW_LINE INDENT max1 = 0 NEW_LINE max2 = 0 NEW_LINE for u in adj [ cur ] : NEW_LINE INDENT if ( u != par ) : NEW_LINE INDENT if ( height [ u ] >= max1 ) : NEW_LINE INDENT max2 = max1 NEW_LINE max1 = height [ u ] NEW_LINE DEDENT elif ( height [ u ] > max2 ) : NEW_LINE INDENT max2 = height [ u ] NEW_LINE DEDENT DEDENT DEDENT sum = 0 NEW_LINE for u in adj [ cur ] : NEW_LINE INDENT if ( u != par ) : NEW_LINE INDENT sum = ( max2 if ( max1 == height [ u ] ) else max1 ) NEW_LINE if ( max1 == height [ u ] ) : NEW_LINE INDENT dist [ u ] = 1 + max ( 1 + max2 , dist [ cur ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dist [ u ] = 1 + max ( 1 + max1 , dist [ cur ] ) NEW_LINE DEDENT dfs2 ( u , cur ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 6 NEW_LINE addEdge ( 1 , 2 ) NEW_LINE addEdge ( 2 , 3 ) NEW_LINE addEdge ( 2 , 4 ) NEW_LINE addEdge ( 2 , 5 ) NEW_LINE addEdge ( 5 , 6 ) NEW_LINE dfs1 ( 1 , 0 ) NEW_LINE dfs2 ( 1 , 0 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( max ( dist [ i ] , height [ i ] ) - 1 , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT"} +{"text":"Middle of three using minimum comparisons | Python3 program to find middle of three distinct numbers ; Function to find the middle of three number ; Checking for b ; Checking for a ; Driver Code","code":"def middleOfThree ( a , b , c ) : NEW_LINE INDENT def middleOfThree ( a , b , c ) : NEW_LINE INDENT if ( ( a < b and b < c ) or ( c < b and b < a ) ) : NEW_LINE INDENT return b ; NEW_LINE DEDENT if ( ( b < a and a < c ) or ( c < a and a < b ) ) : NEW_LINE INDENT return a ; NEW_LINE DEDENT else : NEW_LINE INDENT return c NEW_LINE DEDENT DEDENT DEDENT a = 20 NEW_LINE b = 30 NEW_LINE c = 40 NEW_LINE print ( middleOfThree ( a , b , c ) ) NEW_LINE"} +{"text":"Difference between Insertion sort and Selection sort | Function to implement the selection sort ; One by one move boundary of unsorted subarray ; Find the minimum element in unsorted array ; Swap the found minimum element with the first element ; Function to print an array ; Driver Code ; Function Call ; Print the array","code":"def selectionSort ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT min_idx = i NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] < arr [ min_idx ] ) : NEW_LINE INDENT min_idx = j NEW_LINE DEDENT DEDENT arr [ min_idx ] , arr [ i ] = arr [ i ] , arr [ min_idx ] NEW_LINE DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 64 , 25 , 12 , 22 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE selectionSort ( arr , n ) NEW_LINE print ( \" Sorted \u2581 array : \u2581 \" ) NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT"} +{"text":"Check if a given string can be converted to another by given possible swaps | Python3 program to implement the above approach ; Stores length of str1 ; Stores length of str2 ; Stores distinct characters of str1 ; Stores distinct characters of str2 ; Stores frequency of each character of str1 ; Traverse the string str1 ; Update frequency of str1 [ i ] ; Traverse the string str1 ; Insert str1 [ i ] into st1 ; Traverse the string str2 ; Insert str1 [ i ] into st1 ; If distinct characters in str1 and str2 are not same ; Stores frequency of each character of str2 ; Traverse the string str2 ; Update frequency of str2 [ i ] ; Sort hash1 [ ] array ; Sort hash2 [ ] array ; Traverse hash1 [ ] and hash2 [ ] ; If hash1 [ i ] not equal to hash2 [ i ] ; Driver Code","code":"def checkStr1CanConStr2 ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE st1 = set ( [ ] ) NEW_LINE st2 = set ( [ ] ) NEW_LINE hash1 = [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT hash1 [ ord ( str1 [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT st1 . add ( str1 [ i ] ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT st2 . add ( str2 [ i ] ) NEW_LINE DEDENT if ( st1 != st2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT hash2 = [ 0 ] * 256 NEW_LINE for i in range ( M ) : NEW_LINE INDENT hash2 [ ord ( str2 [ i ] ) ] += 1 NEW_LINE DEDENT hash1 . sort ( ) NEW_LINE hash2 . sort ( ) NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( hash1 [ i ] != hash2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" xyyzzlll \" NEW_LINE str2 = \" yllzzxxx \" NEW_LINE if ( checkStr1CanConStr2 ( str1 , str2 ) ) : NEW_LINE INDENT print ( \" True \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" False \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Sort the array in a given index range | Function to sort the elements of the array from index a to index b ; Variables to store start and end of the index range ; Print the modified array ; Driver code","code":"def partSort ( arr , N , a , b ) : NEW_LINE INDENT l = min ( a , b ) NEW_LINE r = max ( a , b ) NEW_LINE arr = ( arr [ 0 : l ] + sorted ( arr [ l : r + 1 ] ) + arr [ r : N ] ) NEW_LINE for i in range ( 0 , N , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 8 , 4 , 5 , 2 ] NEW_LINE a = 1 NEW_LINE b = 4 NEW_LINE N = len ( arr ) NEW_LINE partSort ( arr , N , a , b ) NEW_LINE DEDENT"} +{"text":"Find the minimum cost to reach destination using a train | A Dynamic Programming based solution to find min cost to reach station N - 1 from station 0. ; This function returns the smallest possible cost to reach station N - 1 from station 0. ; dist [ i ] stores minimum cost to reach station i from station 0. ; Go through every station and check if using it as an intermediate station gives better path ; Driver program to test above function","code":"INF = 2147483647 NEW_LINE N = 4 NEW_LINE def minCost ( cost ) : NEW_LINE INDENT dist = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT dist [ i ] = INF NEW_LINE DEDENT dist [ 0 ] = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( dist [ j ] > dist [ i ] + cost [ i ] [ j ] ) : NEW_LINE INDENT dist [ j ] = dist [ i ] + cost [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return dist [ N - 1 ] NEW_LINE DEDENT cost = [ [ 0 , 15 , 80 , 90 ] , [ INF , 0 , 40 , 50 ] , [ INF , INF , 0 , 70 ] , [ INF , INF , INF , 0 ] ] NEW_LINE print ( \" The \u2581 Minimum \u2581 cost \u2581 to \u2581 reach \u2581 station \u2581 \" , N , \" \u2581 is \u2581 \" , minCost ( cost ) ) NEW_LINE"} +{"text":"Number of loops of size k starting from a specific node | Return the Number of ways from a node to make a loop of size K in undirected complete connected graph of N nodes ; Driver code","code":"def numOfways ( n , k ) : NEW_LINE INDENT p = 1 NEW_LINE if ( k % 2 ) : NEW_LINE INDENT p = - 1 NEW_LINE DEDENT return ( pow ( n - 1 , k ) + p * ( n - 1 ) ) \/ n NEW_LINE DEDENT n = 4 NEW_LINE k = 2 NEW_LINE print ( numOfways ( n , k ) ) NEW_LINE"} +{"text":"Program to find the largest and smallest ASCII valued characters in a string | Function that return the largest alphabet ; Initializing max alphabet to 'a ; Find largest alphabet ; Returning largest element ; Function that return the smallest alphabet ; Initializing smallest alphabet to 'z ; Find smallest alphabet ; Returning smallest alphabet ; Driver code ; Character array ; Calculating size of the string ; Calling functions and print returned value","code":"def largest_alphabet ( a , n ) : NEW_LINE ' NEW_LINE INDENT max = ' A ' NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > max ) : NEW_LINE INDENT max = a [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT def smallest_alphabet ( a , n ) : NEW_LINE ' NEW_LINE INDENT min = ' z ' ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] < min ) : NEW_LINE INDENT min = a [ i ] NEW_LINE DEDENT DEDENT return min NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = \" GeEksforGeeks \" NEW_LINE size = len ( a ) NEW_LINE print ( \" Largest \u2581 and \u2581 smallest \u2581 alphabet \u2581 is \u2581 : \u2581 \" , end = \" \" ) NEW_LINE print ( largest_alphabet ( a , size ) , end = \" \u2581 and \u2581 \" ) NEW_LINE print ( smallest_alphabet ( a , size ) ) NEW_LINE DEDENT ' NEW_LINE"} +{"text":"Make largest palindrome by changing at most K | Returns maximum possible palindrome using k changes ; Initialize l and r by leftmost and rightmost ends ; first try to make palindrome ; Replace left and right character by maximum of both ; If k is negative then we can 't make palindrome ; At mid character , if K > 0 then change it to 9 ; If character at lth ( same as rth ) is less than 9 ; If none of them is changed in the previous loop then subtract 2 from K and convert both to 9 ; If one of them is changed in the previous loop then subtract 1 from K ( 1 more is subtracted already ) and make them 9 ; Driver code","code":"def maximumPalinUsingKChanges ( strr , k ) : NEW_LINE INDENT palin = strr [ : : ] 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 palin [ l ] = palin [ r ] = NEW_LINE INDENT max ( strr [ l ] , strr [ r ] ) NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT if ( k < 0 ) : NEW_LINE INDENT return \" Not \u2581 possible \" NEW_LINE DEDENT l = 0 NEW_LINE r = len ( strr ) - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT if ( k > 0 ) : NEW_LINE INDENT palin [ l ] = '9' NEW_LINE DEDENT DEDENT if ( palin [ l ] < '9' ) : NEW_LINE INDENT if ( k >= 2 and palin [ l ] == strr [ l ] and palin [ r ] == strr [ r ] ) : NEW_LINE INDENT k -= 2 NEW_LINE palin [ l ] = palin [ r ] = '9' NEW_LINE DEDENT elif ( k >= 1 and ( palin [ l ] != strr [ l ] or palin [ r ] != strr [ r ] ) ) : NEW_LINE INDENT k -= 1 NEW_LINE palin [ l ] = palin [ r ] = '9' NEW_LINE DEDENT DEDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT return palin NEW_LINE DEDENT st = \"43435\" NEW_LINE strr = [ i for i in st ] NEW_LINE k = 3 NEW_LINE a = maximumPalinUsingKChanges ( strr , k ) NEW_LINE print ( \" \" . join ( a ) ) NEW_LINE"} +{"text":"Count triples with Bitwise AND equal to Zero | Function to find the number of triplets whose Bitwise AND is 0. ; Stores the count of triplets having bitwise AND equal to 0 ; Stores frequencies of all possible A [ i ] & A [ j ] ; Traverse the array ; Update frequency of Bitwise AND of all array elements with a ; Traverse the array ; Iterate the map ; If bitwise AND of triplet is zero , increment cnt ; Return the number of triplets whose Bitwise AND is 0. ; Driver Code ; Input Array ; Function Call","code":"def countTriplets ( A ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE tuples = { } ; NEW_LINE for a in A : NEW_LINE INDENT for b in A : NEW_LINE INDENT if ( a & b ) in tuples : NEW_LINE INDENT tuples [ a & b ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT tuples [ a & b ] = 1 ; NEW_LINE DEDENT DEDENT DEDENT for a in A : NEW_LINE INDENT for t in tuples : NEW_LINE INDENT if ( ( t & a ) == 0 ) : NEW_LINE INDENT cnt += tuples [ t ] ; NEW_LINE DEDENT DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 2 , 1 , 3 ] ; NEW_LINE print ( countTriplets ( A ) ) ; NEW_LINE DEDENT"} +{"text":"Minimize the count of adjacent pairs with different parity | Python3 implementation of above approach ; Recursive function to calculate minimum adjacent pairs with different parity ; If all the numbers are placed ; If replacement is not required ; If replacement is required ; backtracking ; backtracking ; Function to display the minimum number of adjacent elements with different parity ; Store no of even numbers not present in the array ; Store no of odd numbers not present in the array ; Erase exisiting numbers ; Store non - exisiting even and odd numbers ; Driver code","code":"mn = 1000 NEW_LINE def parity ( even , odd , v , i ) : NEW_LINE INDENT global mn NEW_LINE if ( i == len ( v ) or len ( even ) == 0 or len ( odd ) == 0 ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( len ( v ) - 1 ) : NEW_LINE INDENT if ( v [ j ] % 2 != v [ j + 1 ] % 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count < mn ) : NEW_LINE INDENT mn = count NEW_LINE DEDENT return NEW_LINE DEDENT if ( v [ i ] != - 1 ) : NEW_LINE INDENT parity ( even , odd , v , i + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( len ( even ) != 0 ) : NEW_LINE INDENT x = even [ len ( even ) - 1 ] NEW_LINE even . remove ( even [ len ( even ) - 1 ] ) NEW_LINE v [ i ] = x NEW_LINE parity ( even , odd , v , i + 1 ) NEW_LINE even . append ( x ) NEW_LINE DEDENT if ( len ( odd ) != 0 ) : NEW_LINE INDENT x = odd [ len ( odd ) - 1 ] NEW_LINE odd . remove ( odd [ len ( odd ) - 1 ] ) NEW_LINE v [ i ] = x NEW_LINE parity ( even , odd , v , i + 1 ) NEW_LINE odd . append ( x ) NEW_LINE DEDENT DEDENT DEDENT def mnDiffParity ( v , n ) : NEW_LINE INDENT global mn NEW_LINE even = [ ] NEW_LINE odd = [ ] NEW_LINE m = { i : 0 for i in range ( 100 ) } NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT m [ i ] = 1 NEW_LINE DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ i ] != - 1 ) : NEW_LINE INDENT m . pop ( v [ i ] ) NEW_LINE DEDENT DEDENT for key in m . keys ( ) : NEW_LINE INDENT if ( key % 2 == 0 ) : NEW_LINE INDENT even . append ( key ) NEW_LINE DEDENT else : NEW_LINE INDENT odd . append ( key ) NEW_LINE DEDENT DEDENT parity ( even , odd , v , 0 ) NEW_LINE print ( mn + 4 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 NEW_LINE v = [ 2 , 1 , 4 , - 1 , - 1 , 6 , - 1 , 8 ] NEW_LINE mnDiffParity ( v , n ) NEW_LINE DEDENT"} +{"text":"Find triplet such that number of nodes connecting these triplets is maximum | Python3 implementation of the approach ; To store the required nodes ; Parent array to retrace the nodes ; Visited array to prevent DFS in direction on Diameter path ; DFS function to find the startnode ; DFS function to find the endnode of diameter and maintain the parent array ; DFS function to find the end node of the Longest Branch to Diameter ; Function to find the required nodes ; To find start node of diameter ; To find end node of diameter ; x is the end node of diameter ; Mark all the nodes on diameter using back tracking ; Find the end node of longest branch to diameter ; Driver code","code":"MAX = 100005 NEW_LINE adjacent = [ [ ] for i in range ( MAX ) ] NEW_LINE visited = [ False ] * MAX NEW_LINE startnode = endnode = thirdnode = None NEW_LINE maxi , N = - 1 , None NEW_LINE parent = [ None ] * MAX NEW_LINE vis = [ False ] * MAX NEW_LINE def dfs ( u , count ) : NEW_LINE INDENT visited [ u ] = True NEW_LINE temp = 0 NEW_LINE global startnode , maxi NEW_LINE for i in range ( 0 , len ( adjacent [ u ] ) ) : NEW_LINE INDENT if not visited [ adjacent [ u ] [ i ] ] : NEW_LINE INDENT temp += 1 NEW_LINE dfs ( adjacent [ u ] [ i ] , count + 1 ) NEW_LINE DEDENT DEDENT if temp == 0 : NEW_LINE INDENT if maxi < count : NEW_LINE INDENT maxi = count NEW_LINE startnode = u NEW_LINE DEDENT DEDENT DEDENT def dfs1 ( u , count ) : NEW_LINE INDENT visited [ u ] = True NEW_LINE temp = 0 NEW_LINE global endnode , maxi NEW_LINE for i in range ( 0 , len ( adjacent [ u ] ) ) : NEW_LINE INDENT if not visited [ adjacent [ u ] [ i ] ] : NEW_LINE INDENT temp += 1 NEW_LINE parent [ adjacent [ u ] [ i ] ] = u NEW_LINE dfs1 ( adjacent [ u ] [ i ] , count + 1 ) NEW_LINE DEDENT DEDENT if temp == 0 : NEW_LINE INDENT if maxi < count : NEW_LINE INDENT maxi = count NEW_LINE endnode = u NEW_LINE DEDENT DEDENT DEDENT def dfs2 ( u , count ) : NEW_LINE INDENT visited [ u ] = True NEW_LINE temp = 0 NEW_LINE global thirdnode , maxi NEW_LINE for i in range ( 0 , len ( adjacent [ u ] ) ) : NEW_LINE INDENT if ( not visited [ adjacent [ u ] [ i ] ] and not vis [ adjacent [ u ] [ i ] ] ) : NEW_LINE INDENT temp += 1 NEW_LINE dfs2 ( adjacent [ u ] [ i ] , count + 1 ) NEW_LINE DEDENT DEDENT if temp == 0 : NEW_LINE INDENT if maxi < count : NEW_LINE INDENT maxi = count NEW_LINE thirdnode = u NEW_LINE DEDENT DEDENT DEDENT def findNodes ( ) : NEW_LINE INDENT dfs ( 1 , 0 ) NEW_LINE global maxi NEW_LINE for i in range ( 0 , N + 1 ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT maxi = - 1 NEW_LINE dfs1 ( startnode , 0 ) NEW_LINE for i in range ( 0 , N + 1 ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT x = endnode NEW_LINE vis [ startnode ] = True NEW_LINE while x != startnode : NEW_LINE INDENT vis [ x ] = True NEW_LINE x = parent [ x ] NEW_LINE DEDENT maxi = - 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if vis [ i ] : NEW_LINE INDENT dfs2 ( i , 0 ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 NEW_LINE adjacent [ 1 ] . append ( 2 ) NEW_LINE adjacent [ 2 ] . append ( 1 ) NEW_LINE adjacent [ 1 ] . append ( 3 ) NEW_LINE adjacent [ 3 ] . append ( 1 ) NEW_LINE adjacent [ 1 ] . append ( 4 ) NEW_LINE adjacent [ 4 ] . append ( 1 ) NEW_LINE findNodes ( ) NEW_LINE print ( \" ( { } , \u2581 { } , \u2581 { } ) \" . format ( startnode , endnode , thirdnode ) ) NEW_LINE DEDENT"} +{"text":"Percentage increase in volume of the sphere if radius is increased by a given percentage | Python3 program to find percentage increase in the volume of the sphere if radius is increased by a given percentage ; Driver code","code":"def newvol ( x ) : NEW_LINE INDENT print ( \" percentage \u2581 increase \u2581 in \u2581 the \" , pow ( x , 3 ) \/ 10000 + 3 * x + ( 3 * pow ( x , 2 ) ) \/ 100 , \" % \" ) DEDENT x = 10.0 NEW_LINE newvol ( x ) NEW_LINE"} +{"text":"Length of the chord of the circle whose radius and the angle subtended at the center by the chord is given | Python3 program to find the length chord of the circle whose radius and the angle subtended at the centre is also given ; Function to find the length of the chord ; Driver code","code":"import math as mt NEW_LINE def length_of_chord ( r , x ) : NEW_LINE INDENT print ( \" The \u2581 length \u2581 of \u2581 the \u2581 chord \" , \" \u2581 of \u2581 the \u2581 circle \u2581 is \u2581 \" , 2 * r * mt . sin ( x * ( 3.14 \/ 180 ) ) ) NEW_LINE DEDENT r = 4 NEW_LINE x = 63 ; NEW_LINE length_of_chord ( r , x ) NEW_LINE"} +{"text":"Area of a square inscribed in a circle which is inscribed in an equilateral triangle | Python3 Program to find the area of the square inscribed within the circle which in turn is inscribed in an equilateral triangle ; Function to find the area of the square ; a cannot be negative ; area of the square ; Driver code","code":"from math import * NEW_LINE def area ( a ) : NEW_LINE INDENT if a < 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT area = sqrt ( a ) \/ 6 NEW_LINE return area NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 10 NEW_LINE print ( round ( area ( a ) , 6 ) ) NEW_LINE DEDENT"} +{"text":"Length of longest rod that can fit into a cuboid | Python 3 program to find the longest rod that can fit in a cuboid ; Function to find the length ; temporary variable to hold the intermediate result ; length of longest rod is calculated using square root function ; Driver Code ; calling longestRodInCuboid ( ) function to get the length of longest rod","code":"from math import * NEW_LINE def longestRodInCuboid ( length , breadth , height ) : NEW_LINE INDENT temp = length * length + breadth * breadth + height * height NEW_LINE result = sqrt ( temp ) NEW_LINE return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT length , breadth , height = 12 , 9 , 8 NEW_LINE print ( longestRodInCuboid ( length , breadth , height ) ) NEW_LINE DEDENT"} +{"text":"Check whether a given point lies on or inside the rectangle | Set 3 | function to Check whether a given point lies inside or on the rectangle or not ; Driver code","code":"def LiesInsieRectangle ( a , b , x , y ) : NEW_LINE INDENT if ( x - y - b <= 0 and x - y + b >= 0 and x + y - 2 * a + b <= 0 and x + y - b >= 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a , b , x , y = 7 , 2 , 4 , 5 NEW_LINE if LiesInsieRectangle ( a , b , x , y ) : NEW_LINE INDENT print ( \" Given \u2581 point \u2581 lies \u2581 inside \" \" \u2581 the \u2581 rectangle \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Given \u2581 point \u2581 does \u2581 not \u2581 lie \" \" \u2581 on \u2581 the \u2581 rectangle \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Maximize volume of cuboid with given sum of sides | Return the maximum volume . ; for length ; for breadth ; for height ; calculating maximum volume . ; Driven Program","code":"def maxvolume ( s ) : NEW_LINE INDENT maxvalue = 0 NEW_LINE i = 1 NEW_LINE for i in range ( s - 1 ) : NEW_LINE INDENT j = 1 NEW_LINE for j in range ( s ) : NEW_LINE INDENT k = s - i - j NEW_LINE maxvalue = max ( maxvalue , i * j * k ) NEW_LINE DEDENT DEDENT return maxvalue NEW_LINE DEDENT s = 8 NEW_LINE print ( maxvolume ( s ) ) NEW_LINE"} +{"text":"Maximize volume of cuboid with given sum of sides | Return the maximum volume . ; finding length ; finding breadth ; finding height ; Driven Program","code":"def maxvolume ( s ) : NEW_LINE INDENT length = int ( s \/ 3 ) NEW_LINE s -= length NEW_LINE breadth = s \/ 2 NEW_LINE height = s - breadth NEW_LINE return int ( length * breadth * height ) NEW_LINE DEDENT s = 8 NEW_LINE print ( maxvolume ( s ) ) NEW_LINE"} +{"text":"Area of a Hexagon | Python3 program to find area of a Hexagon ; Function for calculating area of the hexagon . ; Driver code ; length of a side .","code":"import math NEW_LINE def hexagonArea ( s ) : NEW_LINE INDENT return ( ( 3 * math . sqrt ( 3 ) * ( s * s ) ) \/ 2 ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = 4 NEW_LINE print ( \" Area : \" , \" { 0 : . 4f } \" . format ( hexagonArea ( s ) ) ) NEW_LINE DEDENT"} +{"text":"Maximum number of squares that can fit in a right angle isosceles triangle | function for finding max squares ; return in O ( 1 ) with derived formula ; driver program","code":"def maxSquare ( b , m ) : NEW_LINE INDENT return ( b \/ m - 1 ) * ( b \/ m ) \/ 2 NEW_LINE DEDENT b = 10 NEW_LINE m = 2 NEW_LINE print ( int ( maxSquare ( b , m ) ) ) NEW_LINE"} +{"text":"Check if right triangle possible from given area and hypotenuse | Python program to check existence of right triangle . ; Prints three sides of a right triangle from given area and hypotenuse if triangle is possible , else prints - 1. ; Descriminant of the equation ; applying the linear equation formula to find both the roots ; Driver code Area is 6 and hypotenuse is 5.","code":"from math import sqrt NEW_LINE def findRightAngle ( A , H ) : NEW_LINE INDENT D = pow ( H , 4 ) - 16 * A * A NEW_LINE if D >= 0 : NEW_LINE INDENT root1 = ( H * H + sqrt ( D ) ) \/ 2 NEW_LINE root2 = ( H * H - sqrt ( D ) ) \/ 2 NEW_LINE a = sqrt ( root1 ) NEW_LINE b = sqrt ( root2 ) NEW_LINE if b >= a : NEW_LINE INDENT print a , b , H NEW_LINE DEDENT else : NEW_LINE INDENT print b , a , H NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print \" - 1\" NEW_LINE DEDENT DEDENT findRightAngle ( 6 , 5 ) NEW_LINE"} +{"text":"Maximum number of 2 x2 squares that can be fit inside a right isosceles triangle | Python3 program to count number of 2 x 2 squares in a right isosceles triangle ; removing the extra part we would always need ; Since each square has base of length of 2 ; Driver code","code":"def numberOfSquares ( base ) : NEW_LINE INDENT base = ( base - 2 ) NEW_LINE base = base \/\/ 2 NEW_LINE return base * ( base + 1 ) \/ 2 NEW_LINE DEDENT base = 8 NEW_LINE print ( numberOfSquares ( base ) ) NEW_LINE"} +{"text":"Bitwise OR of bitwise AND of all possible non | Function to find the Bitwise OR of Bitwise AND of all possible subarrays after performing the every query ; Traversing each pair of the query ; Stores the Bitwise OR ; Updating the array ; Find the Bitwise OR of new updated array ; Print the ans ; Driver Code","code":"def performQuery ( arr , Q ) : NEW_LINE INDENT for i in range ( 0 , len ( Q ) ) : NEW_LINE INDENT orr = 0 NEW_LINE x = Q [ i ] [ 0 ] NEW_LINE arr [ x - 1 ] = Q [ i ] [ 1 ] NEW_LINE for j in range ( 0 , len ( arr ) ) : NEW_LINE INDENT orr = orr | arr [ j ] NEW_LINE DEDENT print ( orr , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE Q = [ [ 1 , 4 ] , [ 3 , 0 ] ] NEW_LINE performQuery ( arr , Q ) NEW_LINE"} +{"text":"Smallest length of number divisible by K formed by using D only | Function to form the smallest number possible ; Array to mark the remainders counted already ; Iterate over the range ; If that remainder is already found , return - 1 ; Driver Code","code":"def smallest ( k , d ) : NEW_LINE INDENT cnt = 1 NEW_LINE m = d % k NEW_LINE v = [ 0 for i in range ( k ) ] ; NEW_LINE v [ m ] = 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( m == 0 ) : NEW_LINE INDENT return cnt NEW_LINE DEDENT m = ( ( ( m * ( 10 % k ) ) % k ) + ( d % k ) ) % k NEW_LINE if ( v [ m ] == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT v [ m ] = 1 NEW_LINE cnt += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT d = 1 NEW_LINE k = 41 NEW_LINE print ( smallest ( k , d ) ) NEW_LINE"} +{"text":"Fibonacci Cube Graph | Function to find fibonacci number ; Function for finding number of vertices in fibonacci cube graph ; return fibonacci number for f ( n + 2 ) ; Driver Code","code":"def fib ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return n NEW_LINE DEDENT return fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE DEDENT def findVertices ( n ) : NEW_LINE INDENT return fib ( n + 2 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 NEW_LINE print ( findVertices ( n ) ) NEW_LINE DEDENT"} +{"text":"Modify array such that the array does not contain any common divisors other than 1 | Python3 program for the above approach ; Function to check if it is possible to modify the array such that there is no common factor between array elements except 1 ; Stores GCD of the array ; Calculate GCD of the array ; If the current divisor is smaller than X ; Divide GCD by the current divisor ; If possible ; Print the modified array ; Otherwise ; Driver Code ; Given array ; Size of the array","code":"import math NEW_LINE def checkCommonDivisor ( arr , N , X ) : NEW_LINE INDENT G = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT G = math . gcd ( G , arr [ i ] ) NEW_LINE DEDENT copy_G = G NEW_LINE for divisor in range ( 2 , X + 1 ) : NEW_LINE INDENT while ( G % divisor == 0 ) : NEW_LINE INDENT G = G \/\/ divisor NEW_LINE DEDENT DEDENT if ( G <= X ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] \/\/ copy_G , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 6 , 15 , 6 ] NEW_LINE X = 6 NEW_LINE N = len ( arr ) NEW_LINE checkCommonDivisor ( arr , N , X ) NEW_LINE DEDENT"} +{"text":"Sort the biotonic doubly linked list | Node of a doubly linked list ; Function to reverse a Doubly Linked List ; swap next and prev for all nodes of doubly linked list ; Before changing head , check for the cases like empty list and list with only one node ; Function to merge two sorted doubly linked lists ; If first linked list is empty ; If second linked list is empty ; Pick the smaller value ; function to sort a biotonic doubly linked list ; if list is empty or if it contains a single node only ; if true , then ' current ' is the first node which is smaller than its previous node ; move to the next node ; if true , then list is already sorted ; spilt into two lists , one starting with ' head ' and other starting with ' current ' ; reverse the list starting with ' current ' ; merge the two lists and return the final merged doubly linked list ; Function to insert a node at the beginning of the Doubly Linked List ; allocate node ; put in the data ; since we are adding at the beginning , prev is always None ; link the old list off the new node ; change prev of head node to new node ; move the head to point to the new node ; Function to print nodes in a given doubly linked list ; if list is empty ; Driver Code ; Create the doubly linked list : 2 < .5 < .7 < .12 < .10 < .6 < .4 < .1 ; sort the biotonic DLL","code":"class Node : NEW_LINE INDENT def __init__ ( self , next = None , prev = None , data = None ) : NEW_LINE INDENT self . next = next NEW_LINE self . prev = prev NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def reverse ( head_ref ) : NEW_LINE INDENT temp = None NEW_LINE current = head_ref NEW_LINE while ( current != None ) : NEW_LINE INDENT temp = current . prev NEW_LINE current . prev = current . next NEW_LINE current . next = temp NEW_LINE current = current . prev NEW_LINE DEDENT if ( temp != None ) : NEW_LINE INDENT head_ref = temp . prev NEW_LINE return head_ref NEW_LINE DEDENT DEDENT def merge ( first , second ) : NEW_LINE INDENT if ( first == None ) : NEW_LINE INDENT return second NEW_LINE DEDENT if ( second == None ) : NEW_LINE INDENT return first NEW_LINE DEDENT if ( first . data < second . data ) : NEW_LINE INDENT first . next = merge ( first . next , second ) NEW_LINE first . next . prev = first NEW_LINE first . prev = None NEW_LINE return first NEW_LINE DEDENT else : NEW_LINE INDENT second . next = merge ( first , second . next ) NEW_LINE second . next . prev = second NEW_LINE second . prev = None NEW_LINE return second NEW_LINE DEDENT DEDENT def sort ( head ) : NEW_LINE INDENT if ( head == None or head . next == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT current = head . next NEW_LINE while ( current != None ) : NEW_LINE INDENT if ( current . data < current . prev . data ) : NEW_LINE INDENT break NEW_LINE DEDENT current = current . next NEW_LINE DEDENT if ( current == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT current . prev . next = None NEW_LINE current . prev = None NEW_LINE current = reverse ( current ) NEW_LINE return merge ( head , current ) NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . prev = None NEW_LINE new_node . next = ( head_ref ) NEW_LINE if ( ( head_ref ) != None ) : NEW_LINE INDENT ( head_ref ) . prev = new_node NEW_LINE DEDENT ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT print ( \" Doubly \u2581 Linked \u2581 list \u2581 empty \" ) NEW_LINE DEDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = \" \u2581 \" ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT head = None NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 10 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 7 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 2 ) NEW_LINE print ( \" Original \u2581 Doubly \u2581 linked \u2581 list : n \" ) NEW_LINE printList ( head ) NEW_LINE head = sort ( head ) NEW_LINE print ( \" Doubly linked list after sorting : \" ) NEW_LINE printList ( head ) NEW_LINE"} +{"text":"Arrange consonants and vowels nodes in a linked list | A linked list node ; Utility function to print the linked list ; Utility function for checking vowel ; function to arrange consonants and vowels nodes ; for keep track of vowel ; list is empty ; We need to discover the first vowel in the list . It is going to be the returned head , and also the initial latestVowel . ; first element is a vowel . It will also be the new head and the initial latestVowel ; First element is not a vowel . Iterate through the list until we find a vowel . Note that curr points to the element * before * the element with the vowel . ; This is an edge case where there are only consonants in the list . ; Set the initial latestVowel and the new head to the vowel item that we found . Relink the chain of consonants after that vowel item : old_head_consonant . consonant1 . consonant2 . vowel . rest_of_list becomes vowel . old_head_consonant . consonant1 . consonant2 . rest_of_list ; Now traverse the list . Curr is always the item * before * the one we are checking , so that we can use it to re - link . ; The next discovered item is a vowel ; If it comes directly after the previous vowel , we don 't need to move items around, just mark the new latestVowel and advance curr. ; But if it comes after an intervening chain of consonants , we need to chain the newly discovered vowel right after the old vowel . Curr is not changed as after the re - linking it will have a new next , that has not been checked yet , and we always keep curr at one before the next to check . ; Chain in new vowel ; Advance latestVowel ; Remove found vowel from previous place ; Re - link chain of consonants after latestVowel ; No vowel in the next element , advance curr . ; Driver code","code":"class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def printlist ( head ) : NEW_LINE INDENT if ( not head ) : NEW_LINE INDENT print ( \" Empty \u2581 List \" ) NEW_LINE return NEW_LINE DEDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = \" \u2581 \" ) NEW_LINE if ( head . next ) : NEW_LINE INDENT print ( end = \" - > \u2581 \" ) NEW_LINE DEDENT head = head . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def isVowel ( x ) : NEW_LINE INDENT return ( x == ' a ' or x == ' e ' or x == ' i ' or x == ' o ' or x == ' u ' or x == ' A ' or x == ' E ' or x == ' I ' or x == ' O ' or x == ' U ' ) NEW_LINE DEDENT def arrange ( head ) : NEW_LINE INDENT newHead = head NEW_LINE latestVowel = None NEW_LINE curr = head NEW_LINE if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT if ( isVowel ( head . data ) ) : NEW_LINE INDENT latestVowel = head NEW_LINE DEDENT else : NEW_LINE INDENT while ( curr . next != None and not isVowel ( curr . next . data ) ) : NEW_LINE INDENT curr = curr . next NEW_LINE DEDENT if ( curr . next == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT latestVowel = newHead = curr . next NEW_LINE curr . next = curr . next . next NEW_LINE latestVowel . next = head NEW_LINE DEDENT while ( curr != None and curr . next != None ) : NEW_LINE INDENT if ( isVowel ( curr . next . data ) ) : NEW_LINE INDENT if ( curr == latestVowel ) : NEW_LINE INDENT latestVowel = curr = curr . next NEW_LINE DEDENT else : NEW_LINE INDENT temp = latestVowel . next NEW_LINE latestVowel . next = curr . next NEW_LINE latestVowel = latestVowel . next NEW_LINE curr . next = curr . next . next NEW_LINE latestVowel . next = temp NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT curr = curr . next NEW_LINE DEDENT DEDENT return newHead NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = Node ( ' a ' ) NEW_LINE head . next = Node ( ' b ' ) NEW_LINE head . next . next = Node ( ' c ' ) NEW_LINE head . next . next . next = Node ( ' e ' ) NEW_LINE head . next . next . next . next = Node ( ' d ' ) NEW_LINE head . next . next . next . next . next = Node ( ' o ' ) NEW_LINE head . next . next . next . next . next . next = Node ( ' x ' ) NEW_LINE head . next . next . next . next . next . next . next = Node ( ' i ' ) NEW_LINE print ( \" Linked \u2581 list \u2581 before \u2581 : \" ) NEW_LINE printlist ( head ) NEW_LINE head = arrange ( head ) NEW_LINE print ( \" Linked \u2581 list \u2581 after \u2581 : \" ) NEW_LINE printlist ( head ) NEW_LINE DEDENT"} +{"text":"K 'th Largest element in BST using constant extra space | helper function to create a new Node ; count variable to keep count of visited Nodes ; if right child is None ; first increment count and check if count = k ; otherwise move to the left child ; find inorder successor of current Node ; set left child of successor to the current Node ; move current to its right ; restoring the tree back to original binary search tree removing threaded links ; move current to its left child ; Driver Code ; Constructed binary tree is 4 \/ \\ 2 7 \/ \\ \/ \\ 1 3 6 10","code":"class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . right = self . left = None NEW_LINE DEDENT DEDENT def KthLargestUsingMorrisTraversal ( root , k ) : NEW_LINE INDENT curr = root NEW_LINE Klargest = None NEW_LINE count = 0 NEW_LINE while ( curr != None ) : NEW_LINE INDENT if ( curr . right == None ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT Klargest = curr NEW_LINE DEDENT curr = curr . left NEW_LINE DEDENT else : NEW_LINE INDENT succ = curr . right NEW_LINE while ( succ . left != None and succ . left != curr ) : NEW_LINE INDENT succ = succ . left NEW_LINE DEDENT if ( succ . left == None ) : NEW_LINE INDENT succ . left = curr NEW_LINE curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT succ . left = None NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT Klargest = curr NEW_LINE DEDENT curr = curr . left NEW_LINE DEDENT DEDENT DEDENT return Klargest NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 4 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 7 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 10 ) NEW_LINE print ( \" Finding \u2581 K - th \u2581 largest \u2581 Node \u2581 in \u2581 BST \u2581 : \u2581 \" , KthLargestUsingMorrisTraversal ( root , 2 ) . data ) NEW_LINE DEDENT"} +{"text":"Sorting rows of matrix in ascending order followed by columns in descending order | Python implementation to sort the rows of matrix in ascending order followed by sorting the columns in descending order ; function to sort each row of the matrix according to the order specified by ascending . ; function to find transpose of the matrix ; swapping element at index ( i , j ) by element at index ( j , i ) ; function to sort the matrix row - wise and column - wise ; sort rows of mat [ ] [ ] ; get transpose of mat [ ] [ ] ; again sort rows of mat [ ] [ ] in descending order . ; again get transpose of mat [ ] [ ] ; function to print the matrix ; Driver code","code":"MAX_SIZE = 10 NEW_LINE def sortByRow ( mat , n , ascending ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( ascending ) : NEW_LINE INDENT mat [ i ] . sort ( ) NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] . sort ( reverse = True ) NEW_LINE DEDENT DEDENT DEDENT def transpose ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT temp = mat [ i ] [ j ] NEW_LINE mat [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE mat [ j ] [ i ] = temp NEW_LINE DEDENT DEDENT DEDENT def sortMatRowAndColWise ( mat , n ) : NEW_LINE INDENT sortByRow ( mat , n , True ) NEW_LINE transpose ( mat , n ) NEW_LINE sortByRow ( mat , n , False ) NEW_LINE transpose ( mat , n ) NEW_LINE DEDENT def printMat ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , \" \u2581 \" , end = \" \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 3 NEW_LINE mat = [ [ 3 , 2 , 1 ] , [ 9 , 8 , 7 ] , [ 6 , 5 , 4 ] ] NEW_LINE print ( \" Original \u2581 Matrix : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE sortMatRowAndColWise ( mat , n ) NEW_LINE print ( \" Matrix \u2581 After \u2581 Sorting : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE"} +{"text":"Sort the matrix row | Python 3 implementation to sort the matrix row - wise and column - wise ; function to sort each row of the matrix ; sorting row number 'i ; function to find transpose of the matrix ; swapping element at index ( i , j ) by element at index ( j , i ) ; function to sort the matrix row - wise and column - wise ; sort rows of mat [ ] [ ] ; get transpose of mat [ ] [ ] ; again sort rows of mat [ ] [ ] ; again get transpose of mat [ ] [ ] ; function to print the matrix ; Driver Code","code":"MAX_SIZE = 10 NEW_LINE def sortByRow ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT if mat [ i ] [ j ] > mat [ i ] [ j + 1 ] : NEW_LINE INDENT temp = mat [ i ] [ j ] NEW_LINE mat [ i ] [ j ] = mat [ i ] [ j + 1 ] NEW_LINE mat [ i ] [ j + 1 ] = temp NEW_LINE DEDENT DEDENT DEDENT DEDENT def transpose ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT t = mat [ i ] [ j ] NEW_LINE mat [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE mat [ j ] [ i ] = t NEW_LINE DEDENT DEDENT DEDENT def sortMatRowAndColWise ( mat , n ) : NEW_LINE INDENT sortByRow ( mat , n ) NEW_LINE transpose ( mat , n ) NEW_LINE sortByRow ( mat , n ) NEW_LINE transpose ( mat , n ) NEW_LINE DEDENT def printMat ( mat , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( str ( mat [ i ] [ j ] ) , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT mat = [ [ 4 , 1 , 3 ] , [ 9 , 6 , 8 ] , [ 5 , 2 , 7 ] ] NEW_LINE n = 3 NEW_LINE print ( \" Original \u2581 Matrix : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE sortMatRowAndColWise ( mat , n ) NEW_LINE print ( \" Matrix After Sorting : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE"} +{"text":"Magic Square | Even Order | Function for calculating Magic square ; 2 - D matrix with all entries as 0 ; Change value of array elements at fix location as per the rule ( n * n + 1 ) - arr [ i ] [ [ j ] Corners of order ( n \/ 4 ) * ( n \/ 4 ) Top left corner ; Top right corner ; Bottom Left corner ; Bottom Right corner ; Centre of matrix , order ( n \/ 2 ) * ( n \/ 2 ) ; Printing the square ; Driver Program ; Function call","code":"def DoublyEven ( n ) : NEW_LINE INDENT arr = [ [ ( n * y ) + x + 1 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( 0 , n \/ 4 ) : NEW_LINE INDENT for j in range ( 0 , n \/ 4 ) : NEW_LINE INDENT arr [ i ] [ j ] = ( n * n + 1 ) - arr [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( 0 , n \/ 4 ) : NEW_LINE INDENT for j in range ( 3 * ( n \/ 4 ) , n ) : NEW_LINE INDENT arr [ i ] [ j ] = ( n * n + 1 ) - arr [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( 3 * ( n \/ 4 ) , n ) : NEW_LINE INDENT for j in range ( 0 , n \/ 4 ) : NEW_LINE INDENT arr [ i ] [ j ] = ( n * n + 1 ) - arr [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( 3 * ( n \/ 4 ) , n ) : NEW_LINE INDENT for j in range ( 3 * ( n \/ 4 ) , n ) : NEW_LINE INDENT arr [ i ] [ j ] = ( n * n + 1 ) - arr [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( n \/ 4 , 3 * ( n \/ 4 ) ) : NEW_LINE INDENT for j in range ( n \/ 4 , 3 * ( n \/ 4 ) ) : NEW_LINE INDENT arr [ i ] [ j ] = ( n * n + 1 ) - arr [ i ] [ j ] ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ' % 2d \u2581 ' % ( arr [ i ] [ j ] ) , NEW_LINE DEDENT print NEW_LINE DEDENT DEDENT n = 8 NEW_LINE DoublyEven ( n ) NEW_LINE"} +{"text":"Kronecker Product of two matrices | rowa and cola are no of rows and columns of matrix A rowb and colb are no of rows and columns of matrix B ; Function to computes the Kronecker Product of two matrices ; i loops till rowa ; k loops till rowb ; j loops till cola ; l loops till colb ; Each element of matrix A is multiplied by whole Matrix B resp and stored as Matrix C ; Driver code .","code":"cola = 2 NEW_LINE rowa = 3 NEW_LINE colb = 3 NEW_LINE rowb = 2 NEW_LINE def Kroneckerproduct ( A , B ) : NEW_LINE INDENT C = [ [ 0 for j in range ( cola * colb ) ] for i in range ( rowa * rowb ) ] NEW_LINE for i in range ( 0 , rowa ) : NEW_LINE INDENT for k in range ( 0 , rowb ) : NEW_LINE INDENT for j in range ( 0 , cola ) : NEW_LINE INDENT for l in range ( 0 , colb ) : NEW_LINE INDENT C [ i + l + 1 ] [ j + k + 1 ] = A [ i ] [ j ] * B [ k ] [ l ] NEW_LINE print ( C [ i + l + 1 ] [ j + k + 1 ] , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT print ( \" \" ) NEW_LINE DEDENT DEDENT DEDENT A = [ [ 0 for j in range ( 2 ) ] for i in range ( 3 ) ] NEW_LINE B = [ [ 0 for j in range ( 3 ) ] for i in range ( 2 ) ] NEW_LINE A [ 0 ] [ 0 ] = 1 NEW_LINE A [ 0 ] [ 1 ] = 2 NEW_LINE A [ 1 ] [ 0 ] = 3 NEW_LINE A [ 1 ] [ 1 ] = 4 NEW_LINE A [ 2 ] [ 0 ] = 1 NEW_LINE A [ 2 ] [ 1 ] = 0 NEW_LINE B [ 0 ] [ 0 ] = 0 NEW_LINE B [ 0 ] [ 1 ] = 5 NEW_LINE B [ 0 ] [ 2 ] = 2 NEW_LINE B [ 1 ] [ 0 ] = 6 NEW_LINE B [ 1 ] [ 1 ] = 7 NEW_LINE B [ 1 ] [ 2 ] = 3 NEW_LINE Kroneckerproduct ( A , B ) NEW_LINE"} +{"text":"Program to check if matrix is lower triangular | Function to check matrix is in lower triangular ; Driver function . ; Function call","code":"def islowertriangular ( M ) : NEW_LINE INDENT for i in range ( 0 , len ( M ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( M ) ) : NEW_LINE INDENT if ( M [ i ] [ j ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT M = [ [ 1 , 0 , 0 , 0 ] , [ 1 , 4 , 0 , 0 ] , [ 4 , 6 , 2 , 0 ] , [ 0 , 4 , 7 , 6 ] ] NEW_LINE if islowertriangular ( M ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Program to check if matrix is upper triangular | Function to check matrix is in upper triangular ; Driver function .","code":"def isuppertriangular ( M ) : NEW_LINE INDENT for i in range ( 1 , len ( M ) ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if ( M [ i ] [ j ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT M = [ [ 1 , 3 , 5 , 3 ] , [ 0 , 4 , 6 , 2 ] , [ 0 , 0 , 2 , 5 ] , [ 0 , 0 , 0 , 6 ] ] NEW_LINE if isuppertriangular ( M ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Counting sets of 1 s and 0 s in a binary matrix | no of columns ; no of rows ; function to calculate the number of non empty sets of cell ; stores the final answer ; traverses row - wise ; traverses column wise ; at the end subtract n * m as no of single sets have been added twice . ; Driver program to test the above function .","code":"m = 3 NEW_LINE n = 2 NEW_LINE def countSets ( a ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT u = 0 NEW_LINE v = 0 NEW_LINE for j in range ( m ) : NEW_LINE INDENT if a [ i ] [ j ] : NEW_LINE INDENT u += 1 NEW_LINE DEDENT else : NEW_LINE INDENT v += 1 NEW_LINE DEDENT DEDENT res += pow ( 2 , u ) - 1 + pow ( 2 , v ) - 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT u = 0 NEW_LINE v = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if a [ j ] [ i ] : NEW_LINE INDENT u += 1 NEW_LINE DEDENT else : NEW_LINE INDENT v += 1 NEW_LINE DEDENT DEDENT res += pow ( 2 , u ) - 1 + pow ( 2 , v ) - 1 NEW_LINE DEDENT return res - ( n * m ) NEW_LINE DEDENT a = [ [ 1 , 0 , 1 ] , [ 0 , 1 , 0 ] ] NEW_LINE print ( countSets ( a ) ) NEW_LINE"} +{"text":"Program to check if a matrix is symmetric | Fills transpose of mat [ N ] [ N ] in tr [ N ] [ N ] ; Returns true if mat [ N ] [ N ] is symmetric , else false ; Driver code","code":"def transpose ( mat , tr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT tr [ i ] [ j ] = mat [ j ] [ i ] NEW_LINE DEDENT DEDENT DEDENT def isSymmetric ( mat , N ) : NEW_LINE INDENT tr = [ [ 0 for j in range ( len ( mat [ 0 ] ) ) ] for i in range ( len ( mat ) ) ] NEW_LINE transpose ( mat , tr , N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != tr [ i ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 1 , 3 , 5 ] , [ 3 , 2 , 4 ] , [ 5 , 4 , 1 ] ] NEW_LINE if ( isSymmetric ( mat , 3 ) ) : NEW_LINE INDENT print \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT print \" No \" NEW_LINE DEDENT"} +{"text":"Program to check if a matrix is symmetric | Returns true if mat [ N ] [ N ] is symmetric , else false ; Driver code","code":"def isSymmetric ( mat , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( mat [ i ] [ j ] != mat [ j ] [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT mat = [ [ 1 , 3 , 5 ] , [ 3 , 2 , 4 ] , [ 5 , 4 , 1 ] ] NEW_LINE if ( isSymmetric ( mat , 3 ) ) : NEW_LINE INDENT print \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT print \" No \" NEW_LINE DEDENT"} +{"text":"Program to find Normal and Trace of a matrix | Python3 program to find trace and normal of given matrix ; Size of given matrix ; Returns Normal of a matrix of size n x n ; Returns trace of a matrix of size n x n ; Driver Code","code":"import math NEW_LINE MAX = 100 ; NEW_LINE def findNormal ( mat , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT sum += mat [ i ] [ j ] * mat [ i ] [ j ] ; NEW_LINE DEDENT DEDENT return math . floor ( math . sqrt ( sum ) ) ; NEW_LINE DEDENT def findTrace ( mat , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += mat [ i ] [ i ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT mat = [ [ 1 , 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 , 3 ] , [ 4 , 4 , 4 , 4 , 4 ] , [ 5 , 5 , 5 , 5 , 5 ] ] ; NEW_LINE print ( \" Trace \u2581 of \u2581 Matrix \u2581 = \" , findTrace ( mat , 5 ) ) ; NEW_LINE print ( \" Normal \u2581 of \u2581 Matrix \u2581 = \" , findNormal ( mat , 5 ) ) ; NEW_LINE"} +{"text":"Maximum determinant of a matrix with every values either 0 or n | Function for maximum determinant ; Function to print resulatant matrix ; three position where 0 appears ; position where n appears ; Driver code","code":"def maxDet ( n ) : NEW_LINE INDENT return 2 * n * n * n NEW_LINE DEDENT def resMatrix ( n ) : NEW_LINE INDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if i == 0 and j == 2 : NEW_LINE INDENT print ( \"0\" , end = \" \u2581 \" ) NEW_LINE DEDENT elif i == 1 and j == 0 : NEW_LINE INDENT print ( \"0\" , end = \" \u2581 \" ) NEW_LINE DEDENT elif i == 2 and j == 1 : NEW_LINE INDENT print ( \"0\" , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT print ( \" \" ) NEW_LINE DEDENT DEDENT n = 15 NEW_LINE print ( \" Maximum \u2581 Detrminat = \" , maxDet ( n ) ) NEW_LINE print ( \" Resultant \u2581 Matrix : \" ) NEW_LINE resMatrix ( n ) NEW_LINE"} +{"text":"Count Negative Numbers in a Column | Python implementation of Naive method to count of negative numbers in M [ n ] [ m ] ; Follow the path shown using arrows above ; no more negative numbers in this row ; Driver code","code":"def countNegative ( M , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if M [ i ] [ j ] < 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT M = [ [ - 3 , - 2 , - 1 , 1 ] , [ - 2 , 2 , 3 , 4 ] , [ 4 , 5 , 7 , 8 ] ] NEW_LINE print ( countNegative ( M , 3 , 4 ) ) NEW_LINE"} +{"text":"Count Negative Numbers in a Column | Function to count negative number ; initialize result ; Start with top right corner ; Follow the path shown using arrows above ; j is the index of the last negative number in this row . So there must be ( j + 1 ) ; negative numbers in this row . ; move to the left and see if we can find a negative number there ; Driver code","code":"def countNegative ( M , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE i = 0 NEW_LINE j = m - 1 NEW_LINE while j >= 0 and i < n : NEW_LINE INDENT if M [ i ] [ j ] < 0 : NEW_LINE INDENT count += ( j + 1 ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT M = [ [ - 3 , - 2 , - 1 , 1 ] , [ - 2 , 2 , 3 , 4 ] , [ 4 , 5 , 7 , 8 ] ] NEW_LINE print ( countNegative ( M , 3 , 4 ) ) NEW_LINE"} +{"text":"Count Negative Numbers in a Column | Recursive binary search to get last negative value in a row between a start and an end ; Base case ; Get the mid for binary search ; If current element is negative ; If it is the rightmost negative element in the current row ; Check in the right half of the array ; Check in the left half of the array ; Function to return the count of negative numbers in the given matrix ; Initialize result ; To store the index of the rightmost negative element in the row under consideration ; Iterate over all rows of the matrix ; If the first element of the current row is positive then there will be no negatives in the matrix below or after it ; Run binary search only until the index of last negative Integer in the above row ; Driver code","code":"def getLastNegativeIndex ( array , start , end , n ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT return start NEW_LINE DEDENT mid = start + ( end - start ) \/\/ 2 NEW_LINE if ( array [ mid ] < 0 ) : NEW_LINE INDENT if ( mid + 1 < n and array [ mid + 1 ] >= 0 ) : NEW_LINE INDENT return mid NEW_LINE DEDENT return getLastNegativeIndex ( array , mid + 1 , end , n ) NEW_LINE DEDENT else : NEW_LINE INDENT return getLastNegativeIndex ( array , start , mid - 1 , n ) NEW_LINE DEDENT DEDENT def countNegative ( M , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE nextEnd = m - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( M [ i ] [ 0 ] >= 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT nextEnd = getLastNegativeIndex ( M [ i ] , 0 , nextEnd , 4 ) NEW_LINE count += nextEnd + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT M = [ [ - 3 , - 2 , - 1 , 1 ] , [ - 2 , 2 , 3 , 4 ] , [ 4 , 5 , 7 , 8 ] ] NEW_LINE r = 3 NEW_LINE c = 4 NEW_LINE print ( countNegative ( M , r , c ) ) NEW_LINE"} +{"text":"Find a specific pair in Matrix | A Naive method to find maximum value of mat [ d ] [ e ] - mat [ a ] [ b ] such that d > a and e > b ; The function returns maximum value A ( d , e ) - A ( a , b ) over all choices of indexes such that both d > a and e > b . ; stores maximum value ; Consider all possible pairs mat [ a ] [ b ] and mat [ d ] [ e ] ; Driver Code","code":"N = 5 NEW_LINE def findMaxValue ( mat ) : NEW_LINE INDENT maxValue = 0 NEW_LINE for a in range ( N - 1 ) : NEW_LINE INDENT for b in range ( N - 1 ) : NEW_LINE INDENT for d in range ( a + 1 , N ) : NEW_LINE INDENT for e in range ( b + 1 , N ) : NEW_LINE INDENT if maxValue < int ( mat [ d ] [ e ] - mat [ a ] [ b ] ) : NEW_LINE INDENT maxValue = int ( mat [ d ] [ e ] - mat [ a ] [ b ] ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return maxValue ; NEW_LINE DEDENT mat = [ [ 1 , 2 , - 1 , - 4 , - 20 ] , [ - 8 , - 3 , 4 , 2 , 1 ] , [ 3 , 8 , 6 , 1 , 3 ] , [ - 4 , - 1 , 1 , 7 , - 6 ] , [ 0 , - 4 , 10 , - 5 , 1 ] ] ; NEW_LINE print ( \" Maximum \u2581 Value \u2581 is \u2581 \" + str ( findMaxValue ( mat ) ) ) NEW_LINE"} +{"text":"Find a specific pair in Matrix | An efficient method to find maximum value of mat [ d ] - ma [ a ] [ b ] such that c > a and d > b ; The function returns maximum value A ( c , d ) - A ( a , b ) over all choices of indexes such that both c > a and d > b . ; stores maximum value ; maxArr [ i ] [ j ] stores max of elements in matrix from ( i , j ) to ( N - 1 , N - 1 ) ; last element of maxArr will be same 's as of the input matrix ; preprocess last row Initialize max ; preprocess last column Initialize max ; preprocess rest of the matrix from bottom ; Update maxValue ; set maxArr ( i , j ) ; Driver Code","code":"import sys NEW_LINE N = 5 NEW_LINE def findMaxValue ( mat ) : NEW_LINE INDENT maxValue = - sys . maxsize - 1 NEW_LINE maxArr = [ [ 0 for x in range ( N ) ] for y in range ( N ) ] NEW_LINE maxArr [ N - 1 ] [ N - 1 ] = mat [ N - 1 ] [ N - 1 ] NEW_LINE maxv = mat [ N - 1 ] [ N - 1 ] ; NEW_LINE for j in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ N - 1 ] [ j ] > maxv ) : NEW_LINE INDENT maxv = mat [ N - 1 ] [ j ] NEW_LINE DEDENT maxArr [ N - 1 ] [ j ] = maxv NEW_LINE DEDENT maxv = mat [ N - 1 ] [ N - 1 ] ; NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ N - 1 ] > maxv ) : NEW_LINE INDENT maxv = mat [ i ] [ N - 1 ] NEW_LINE DEDENT maxArr [ i ] [ N - 1 ] = maxv NEW_LINE DEDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( maxArr [ i + 1 ] [ j + 1 ] - mat [ i ] [ j ] > maxValue ) : NEW_LINE INDENT maxValue = ( maxArr [ i + 1 ] [ j + 1 ] - mat [ i ] [ j ] ) NEW_LINE DEDENT maxArr [ i ] [ j ] = max ( mat [ i ] [ j ] , max ( maxArr [ i ] [ j + 1 ] , maxArr [ i + 1 ] [ j ] ) ) NEW_LINE DEDENT DEDENT return maxValue NEW_LINE DEDENT mat = [ [ 1 , 2 , - 1 , - 4 , - 20 ] , [ - 8 , - 3 , 4 , 2 , 1 ] , [ 3 , 8 , 6 , 1 , 3 ] , [ - 4 , - 1 , 1 , 7 , - 6 ] , [ 0 , - 4 , 10 , - 5 , 1 ] ] NEW_LINE print ( \" Maximum \u2581 Value \u2581 is \" , findMaxValue ( mat ) ) NEW_LINE"} +{"text":"Print all elements in sorted order from row and column wise sorted matrix | Python 3 program to Print all elements in sorted order from row and column wise sorted matrix ; A utility function to youngify a Young Tableau . This is different from standard youngify . It assumes that the value at mat [ 0 ] [ 0 ] is infinite . ; Find the values at down and right sides of mat [ i ] [ j ] ; If mat [ i ] [ j ] is the down right corner element , return ; Move the smaller of two values ( downVal and rightVal ) to mat [ i ] [ j ] and recur for smaller value ; A utility function to extract minimum element from Young tableau ; This function uses extractMin ( ) to print elements in sorted order ; Driver Code","code":"import sys NEW_LINE INF = sys . maxsize NEW_LINE N = 4 NEW_LINE def youngify ( mat , i , j ) : NEW_LINE INDENT downVal = mat [ i + 1 ] [ j ] if ( i + 1 < N ) else INF NEW_LINE rightVal = mat [ i ] [ j + 1 ] if ( j + 1 < N ) else INF NEW_LINE if ( downVal == INF and rightVal == INF ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( downVal < rightVal ) : NEW_LINE INDENT mat [ i ] [ j ] = downVal NEW_LINE mat [ i + 1 ] [ j ] = INF NEW_LINE youngify ( mat , i + 1 , j ) NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = rightVal NEW_LINE mat [ i ] [ j + 1 ] = INF NEW_LINE youngify ( mat , i , j + 1 ) NEW_LINE DEDENT DEDENT def extractMin ( mat ) : NEW_LINE INDENT ret = mat [ 0 ] [ 0 ] NEW_LINE mat [ 0 ] [ 0 ] = INF NEW_LINE youngify ( mat , 0 , 0 ) NEW_LINE return ret NEW_LINE DEDENT def printSorted ( mat ) : NEW_LINE INDENT print ( \" Elements \u2581 of \u2581 matrix \u2581 in \u2581 sorted \u2581 order \u2581 n \" ) NEW_LINE i = 0 NEW_LINE while i < N * N : NEW_LINE INDENT print ( extractMin ( mat ) , end = \" \u2581 \" ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT mat = [ [ 10 , 20 , 30 , 40 ] , [ 15 , 25 , 35 , 45 ] , [ 27 , 29 , 37 , 48 ] , [ 32 , 33 , 39 , 50 ] ] NEW_LINE printSorted ( mat ) NEW_LINE DEDENT"} +{"text":"Given an n x n square matrix , find sum of all sub | size k x k Size of given matrix ; A simple function to find sum of all sub - squares of size k x k in a given square matrix of size n x n ; k must be smaller than or equal to n ; row number of first cell in current sub - square of size k x k ; column of first cell in current sub - square of size k x k ; Calculate and print sum of current sub - square ; Line separator for sub - squares starting with next row ; Driver Code","code":"n = 5 NEW_LINE def printSumSimple ( mat , k ) : NEW_LINE INDENT if ( k > n ) : NEW_LINE INDENT return NEW_LINE DEDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT for j in range ( n - k + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for p in range ( i , k + i ) : NEW_LINE INDENT for q in range ( j , k + j ) : NEW_LINE INDENT sum += mat [ p ] [ q ] NEW_LINE DEDENT DEDENT print ( sum , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT mat = [ [ 1 , 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 , 3 ] , [ 4 , 4 , 4 , 4 , 4 ] , [ 5 , 5 , 5 , 5 , 5 ] ] NEW_LINE k = 3 NEW_LINE printSumSimple ( mat , k ) NEW_LINE DEDENT"} +{"text":"Given an n x n square matrix , find sum of all sub | Size of given matrix ; A O ( n ^ 2 ) function to find sum of all sub - squares of size k x k in a given square matrix of size n x n ; k must be smaller than or equal to n ; 1 : PREPROCESSING To store sums of all strips of size k x 1 ; Go column by column ; Calculate sum of first k x 1 rectangle in this column ; Calculate sum of remaining rectangles ; 2 : CALCULATE SUM of Sub - Squares using stripSum [ ] [ ] ; Calculate and prsum of first subsquare in this row ; Calculate sum of remaining squares in current row by removing the leftmost strip of previous sub - square and adding a new strip ; Driver Code","code":"n = 5 NEW_LINE def printSumTricky ( mat , k ) : NEW_LINE INDENT global n NEW_LINE if k > n : NEW_LINE INDENT return NEW_LINE DEDENT stripSum = [ [ None ] * n for i in range ( n ) ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT Sum += mat [ i ] [ j ] NEW_LINE DEDENT stripSum [ 0 ] [ j ] = Sum NEW_LINE for i in range ( 1 , n - k + 1 ) : NEW_LINE INDENT Sum += ( mat [ i + k - 1 ] [ j ] - mat [ i - 1 ] [ j ] ) NEW_LINE stripSum [ i ] [ j ] = Sum NEW_LINE DEDENT DEDENT for i in range ( n - k + 1 ) : NEW_LINE INDENT Sum = 0 NEW_LINE for j in range ( k ) : NEW_LINE INDENT Sum += stripSum [ i ] [ j ] NEW_LINE DEDENT print ( Sum , end = \" \u2581 \" ) NEW_LINE for j in range ( 1 , n - k + 1 ) : NEW_LINE INDENT Sum += ( stripSum [ i ] [ j + k - 1 ] - stripSum [ i ] [ j - 1 ] ) NEW_LINE print ( Sum , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 , 3 ] , [ 4 , 4 , 4 , 4 , 4 ] , [ 5 , 5 , 5 , 5 , 5 ] ] NEW_LINE k = 3 NEW_LINE printSumTricky ( mat , k ) NEW_LINE"} +{"text":"Program to find transpose of a matrix | Python3 Program to find transpose of a matrix ; This function stores transpose of A [ ] [ ] in B [ ] [ ] ; driver code","code":"M = 3 NEW_LINE N = 4 NEW_LINE def transpose ( A , B ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT B [ i ] [ j ] = A [ j ] [ i ] NEW_LINE DEDENT DEDENT DEDENT A = [ [ 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 ] ] NEW_LINE B = [ [ 0 for x in range ( M ) ] for y in range ( N ) ] NEW_LINE transpose ( A , B ) NEW_LINE print ( \" Result \u2581 matrix \u2581 is \" ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( B [ i ] [ j ] , \" \u2581 \" , end = ' ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT"} +{"text":"Program to find transpose of a matrix | Python3 Program to find transpose of a matrix ; Finds transpose of A [ ] [ ] in - place ; driver code","code":"N = 4 NEW_LINE def transpose ( A ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT A [ i ] [ j ] , A [ j ] [ i ] = A [ j ] [ i ] , A [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT A = [ [ 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 ] , [ 4 , 4 , 4 , 4 ] ] NEW_LINE transpose ( A ) NEW_LINE print ( \" Modified \u2581 matrix \u2581 is \" ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( A [ i ] [ j ] , \" \u2581 \" , end = ' ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT"} +{"text":"Number of paths with exactly k coins | A Naive Recursive Python program to count paths with exactly ' k ' coins ; Recursive function to count paths with sum k from ( 0 , 0 ) to ( m , n ) ; Base cases ; ( m , n ) can be reached either through ( m - 1 , n ) or through ( m , n - 1 ) ; A wrapper over pathCountRec ( ) ; Driver Program","code":"R = 3 NEW_LINE C = 3 NEW_LINE def pathCountRec ( mat , m , n , k ) : NEW_LINE INDENT if m < 0 or n < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif m == 0 and n == 0 : NEW_LINE INDENT return k == mat [ m ] [ n ] NEW_LINE DEDENT return ( pathCountRec ( mat , m - 1 , n , k - mat [ m ] [ n ] ) + pathCountRec ( mat , m , n - 1 , k - mat [ m ] [ n ] ) ) NEW_LINE DEDENT def pathCount ( mat , k ) : NEW_LINE INDENT return pathCountRec ( mat , R - 1 , C - 1 , k ) NEW_LINE DEDENT k = 12 NEW_LINE mat = [ [ 1 , 2 , 3 ] , [ 4 , 6 , 5 ] , [ 3 , 2 , 1 ] ] NEW_LINE print ( pathCount ( mat , k ) ) NEW_LINE"} +{"text":"Number of paths with exactly k coins | A Dynamic Programming based Python3 program to count paths with exactly ' k ' coins ; Base cases ; If this subproblem is already solved ; ( m , n ) can be reached either through ( m - 1 , n ) or through ( m , n - 1 ) ; A wrapper over pathCountDPRecDP ( ) ; Driver Code","code":"R = 3 NEW_LINE C = 3 NEW_LINE MAX_K = 1000 NEW_LINE def pathCountDPRecDP ( mat , m , n , k ) : NEW_LINE INDENT if m < 0 or n < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif m == 0 and n == 0 : NEW_LINE INDENT return k == mat [ m ] [ n ] NEW_LINE DEDENT if ( dp [ m ] [ n ] [ k ] != - 1 ) : NEW_LINE INDENT return dp [ m ] [ n ] [ k ] NEW_LINE DEDENT dp [ m ] [ n ] [ k ] = ( pathCountDPRecDP ( mat , m - 1 , n , k - mat [ m ] [ n ] ) + pathCountDPRecDP ( mat , m , n - 1 , k - mat [ m ] [ n ] ) ) NEW_LINE return dp [ m ] [ n ] [ k ] NEW_LINE DEDENT def pathCountDP ( mat , k ) : NEW_LINE INDENT return pathCountDPRecDP ( mat , R - 1 , C - 1 , k ) NEW_LINE DEDENT k = 12 NEW_LINE dp = [ [ [ - 1 for col in range ( MAX_K ) ] for col in range ( C ) ] for row in range ( R ) ] NEW_LINE mat = [ [ 1 , 2 , 3 ] , [ 4 , 6 , 5 ] , [ 3 , 2 , 1 ] ] NEW_LINE print ( pathCountDP ( mat , k ) ) NEW_LINE"} +{"text":"Sort the given matrix | Python3 implementation to sort the given matrix ; Function to sort the given matrix ; Temporary matrix of size n ^ 2 ; Copy the elements of matrix one by one into temp [ ] ; sort temp [ ] ; copy the elements of temp [ ] one by one in mat [ ] [ ] ; Function to print the given matrix ; Driver program to test above","code":"SIZE = 10 NEW_LINE def sortMat ( mat , n ) : NEW_LINE INDENT temp = [ 0 ] * ( n * n ) NEW_LINE k = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT temp [ k ] = mat [ i ] [ j ] NEW_LINE k += 1 NEW_LINE DEDENT DEDENT temp . sort ( ) NEW_LINE k = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT mat [ i ] [ j ] = temp [ k ] NEW_LINE k += 1 NEW_LINE DEDENT DEDENT DEDENT def printMat ( mat , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT mat = [ [ 5 , 4 , 7 ] , [ 1 , 3 , 8 ] , [ 2 , 9 , 6 ] ] NEW_LINE n = 3 NEW_LINE print ( \" Original \u2581 Matrix : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE sortMat ( mat , n ) NEW_LINE print ( \" Matrix After Sorting : \" ) NEW_LINE printMat ( mat , n ) NEW_LINE"} +{"text":"Bubble Sort | An optimized version of Bubble Sort ; traverse the array from 0 to n - i - 1. Swap if the element found is greater than the next element ; IF no two elements were swapped by inner loop , then break ; Driver code to test above","code":"def bubbleSort ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT swapped = False NEW_LINE for j in range ( 0 , n - i - 1 ) : NEW_LINE INDENT if arr [ j ] > arr [ j + 1 ] : NEW_LINE INDENT arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ] NEW_LINE swapped = True NEW_LINE DEDENT DEDENT if swapped == False : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT arr = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ] NEW_LINE bubbleSort ( arr ) NEW_LINE print ( \" Sorted \u2581 array \u2581 : \" ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( \" % d \" % arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT"} +{"text":"Find k closest elements to a given value | Function to find the cross over point ( the point before which elements aresmaller than or equal to x and afterwhich greater than x ) ; Base cases x is greater than all ; x is smaller than all ; Find the middle point ; If x is same as middle element , then return mid ; If x is greater than arr [ mid ] , then either arr [ mid + 1 ] is ceiling of x or ceiling lies in arr [ mid + 1. . . high ] ; This function prints k closest elements to x in arr [ ] . n is the number of elements in arr [ ] ; Find the crossover point ; Right index to search ; To keep track of count of elements already printed ; If x is present in arr [ ] , then reduce left index . Assumption : all elements in arr [ ] are distinct ; Compare elements on left and right of crossover point to find the k closest elements ; If there are no more elements on right side , then print left elements ; If there are no more elements on left side , then print right elements ; Driver Code","code":"def findCrossOver ( arr , low , high , x ) : NEW_LINE INDENT if ( arr [ high ] <= x ) : NEW_LINE INDENT return high NEW_LINE DEDENT if ( arr [ low ] > x ) : NEW_LINE INDENT return low NEW_LINE DEDENT mid = ( low + high ) \/\/ 2 NEW_LINE if ( arr [ mid ] <= x and arr [ mid + 1 ] > x ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( arr [ mid ] < x ) : NEW_LINE INDENT return findCrossOver ( arr , mid + 1 , high , x ) NEW_LINE DEDENT return findCrossOver ( arr , low , mid - 1 , x ) NEW_LINE DEDENT def printKclosest ( arr , x , k , n ) : NEW_LINE INDENT l = findCrossOver ( arr , 0 , n - 1 , x ) NEW_LINE r = l + 1 NEW_LINE count = 0 NEW_LINE if ( arr [ l ] == x ) : NEW_LINE INDENT l -= 1 NEW_LINE DEDENT while ( l >= 0 and r < n and count < k ) : NEW_LINE INDENT if ( x - arr [ l ] < arr [ r ] - x ) : NEW_LINE INDENT print ( arr [ l ] , end = \" \u2581 \" ) NEW_LINE l -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ r ] , end = \" \u2581 \" ) NEW_LINE r += 1 NEW_LINE DEDENT count += 1 NEW_LINE DEDENT while ( count < k and l >= 0 ) : NEW_LINE INDENT print ( arr [ l ] , end = \" \u2581 \" ) NEW_LINE l -= 1 NEW_LINE count += 1 NEW_LINE DEDENT while ( count < k and r < n ) : NEW_LINE INDENT print ( arr [ r ] , end = \" \u2581 \" ) NEW_LINE r += 1 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 12 , 16 , 22 , 30 , 35 , 39 , 42 , 45 , 48 , 50 , 53 , 55 , 56 ] NEW_LINE n = len ( arr ) NEW_LINE x = 35 NEW_LINE k = 4 NEW_LINE printKclosest ( arr , x , 4 , n ) NEW_LINE DEDENT"} +{"text":"Insertion Sort for Singly Linked List | Pyhton implementation of above algorithm ; A utility function to insert a node at the beginning of linked list ; allocate node ; link the old list off the new node ; move the head to point to the new node ; function to sort a singly linked list using insertion sort ; Initialize sorted linked list ; Traverse the given linked list and insert every node to sorted ; Store next for next iteration ; insert current in sorted linked list ; Update current ; Update head_ref to point to sorted linked list ; function to insert a new_node in a list . Note that this function expects a pointer to head_ref as this can modify the head of the input linked list ( similar to push ( ) ) ; Special case for the head end ; Locate the node before the point of insertion ; BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert Function to print linked list ; Driver program to test above functions","code":"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 , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT def insertionSort ( head_ref ) : NEW_LINE INDENT sorted = None NEW_LINE current = head_ref NEW_LINE while ( current != None ) : NEW_LINE INDENT next = current . next NEW_LINE sorted = sortedInsert ( sorted , current ) NEW_LINE current = next NEW_LINE DEDENT head_ref = sorted NEW_LINE return head_ref NEW_LINE DEDENT def sortedInsert ( head_ref , new_node ) : NEW_LINE INDENT current = None NEW_LINE if ( head_ref == None or ( head_ref ) . data >= new_node . data ) : NEW_LINE INDENT new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE DEDENT else : NEW_LINE INDENT current = head_ref NEW_LINE while ( current . next != None and current . next . data < new_node . data ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT new_node . next = current . next NEW_LINE current . next = new_node NEW_LINE DEDENT return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( temp . data , end = \" \u2581 \" ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT a = None NEW_LINE a = push ( a , 5 ) NEW_LINE a = push ( a , 20 ) NEW_LINE a = push ( a , 4 ) NEW_LINE a = push ( a , 3 ) NEW_LINE a = push ( a , 30 ) NEW_LINE print ( \" Linked \u2581 List \u2581 before \u2581 sorting \u2581 \" ) NEW_LINE printList ( a ) NEW_LINE a = insertionSort ( a ) NEW_LINE print ( \" Linked List after sorting \" ) NEW_LINE printList ( a ) NEW_LINE"} +{"text":"Coin Change | DP | Returns the count of ways we can sum S [ 0. . . m - 1 ] coins to get sum n ; If n is 0 then there is 1 solution ( do not include any coin ) ; If n is less than 0 then no solution exists ; If there are no coins and n is greater than 0 , then no solution exist ; count is sum of solutions ( i ) including S [ m - 1 ] ( ii ) excluding S [ m - 1 ] ; Driver program to test above function","code":"def count ( S , m , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( m <= 0 and n >= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return count ( S , m - 1 , n ) + count ( S , m , n - S [ m - 1 ] ) ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE m = len ( arr ) NEW_LINE print ( count ( arr , m , 4 ) ) NEW_LINE"} +{"text":"Coin Change | DP | Dynamic Programming Python implementation of Coin Change problem ; table [ i ] will be storing the number of solutions for value i . We need n + 1 rows as the table is constructed in bottom up manner using the base case ( n = 0 ) Initialize all table values as 0 ; Base case ( If given value is 0 ) ; Pick all coins one by one and update the table [ ] values after the index greater than or equal to the value of the picked coin ; Driver program to test above function","code":"def count ( S , m , n ) : NEW_LINE INDENT table = [ 0 for k in range ( n + 1 ) ] NEW_LINE table [ 0 ] = 1 NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT for j in range ( S [ i ] , n + 1 ) : NEW_LINE INDENT table [ j ] += table [ j - S [ i ] ] NEW_LINE DEDENT DEDENT return table [ n ] NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE m = len ( arr ) NEW_LINE n = 4 NEW_LINE x = count ( arr , m , n ) NEW_LINE print ( x ) NEW_LINE"} +{"text":"Matrix Chain Multiplication | DP | Python program using memoization ; Function for matrix chain multiplication ; Driver Code","code":"import sys NEW_LINE dp = [ [ - 1 for i in range ( 100 ) ] for j in range ( 100 ) ] NEW_LINE def matrixChainMemoised ( p , i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT dp [ i ] [ j ] = sys . maxsize NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , matrixChainMemoised ( p , i , k ) + matrixChainMemoised ( p , k + 1 , j ) + p [ i - 1 ] * p [ k ] * p [ j ] ) NEW_LINE DEDENT return dp [ i ] [ j ] NEW_LINE DEDENT def MatrixChainOrder ( p , n ) : NEW_LINE INDENT i = 1 NEW_LINE j = n - 1 NEW_LINE return matrixChainMemoised ( p , i , j ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Minimum \u2581 number \u2581 of \u2581 multiplications \u2581 is \" , MatrixChainOrder ( arr , n ) ) NEW_LINE"} +{"text":"Matrix Chain Multiplication | DP | Dynamic Programming Python implementation of Matrix Chain Multiplication . See the Cormen book for details of the following algorithm ; Matrix Ai has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; For simplicity of the program , one extra row and one extra column are allocated in m [ ] [ ] . 0 th row and 0 th column of m [ ] [ ] are not used ; cost is zero when multiplying one matrix . ; L is chain length . ; q = cost \/ scalar multiplications ; Driver code","code":"import sys NEW_LINE def MatrixChainOrder ( p , n ) : NEW_LINE INDENT m = [ [ 0 for x in range ( n ) ] for x in range ( n ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT m [ i ] [ i ] = 0 NEW_LINE DEDENT for L in range ( 2 , n ) : NEW_LINE INDENT for i in range ( 1 , n - L + 1 ) : NEW_LINE INDENT j = i + L - 1 NEW_LINE m [ i ] [ j ] = sys . maxint NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT q = m [ i ] [ k ] + m [ k + 1 ] [ j ] + p [ i - 1 ] * p [ k ] * p [ j ] NEW_LINE if q < m [ i ] [ j ] : NEW_LINE INDENT m [ i ] [ j ] = q NEW_LINE DEDENT DEDENT DEDENT DEDENT return m [ 1 ] [ n - 1 ] NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE size = len ( arr ) NEW_LINE print ( \" Minimum \u2581 number \u2581 of \u2581 multiplications \u2581 is \u2581 \" + str ( MatrixChainOrder ( arr , size ) ) ) NEW_LINE"} +{"text":"Cutting a Rod | DP | A Naive recursive solution for Rod cutting problem ; A utility function to get the maximum of two integers ; Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Recursively cut the rod in different pieces and compare different configurations ; Driver code","code":"import sys NEW_LINE def max ( a , b ) : NEW_LINE INDENT return a if ( a > b ) else b NEW_LINE DEDENT def cutRod ( price , n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT max_val = - sys . maxsize - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT max_val = max ( max_val , price [ i ] + cutRod ( price , n - i - 1 ) ) NEW_LINE DEDENT return max_val NEW_LINE DEDENT arr = [ 1 , 5 , 8 , 9 , 10 , 17 , 17 , 20 ] NEW_LINE size = len ( arr ) NEW_LINE print ( \" Maximum \u2581 Obtainable \u2581 Value \u2581 is \" , cutRod ( arr , size ) ) NEW_LINE"} +{"text":"Cutting a Rod | DP | A Dynamic Programming solution for Rod cutting problem ; Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Build the table val [ ] in bottom up manner and return the last entry from the table ; Driver program to test above functions","code":"INT_MIN = - 32767 NEW_LINE def cutRod ( price , n ) : NEW_LINE INDENT val = [ 0 for x in range ( n + 1 ) ] NEW_LINE val [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT max_val = INT_MIN NEW_LINE for j in range ( i ) : NEW_LINE INDENT max_val = max ( max_val , price [ j ] + val [ i - j - 1 ] ) NEW_LINE DEDENT val [ i ] = max_val NEW_LINE DEDENT return val [ n ] NEW_LINE DEDENT arr = [ 1 , 5 , 8 , 9 , 10 , 17 , 17 , 20 ] NEW_LINE size = len ( arr ) NEW_LINE print ( \" Maximum \u2581 Obtainable \u2581 Value \u2581 is \u2581 \" + str ( cutRod ( arr , size ) ) ) NEW_LINE"} +{"text":"Multiply two integers without using multiplication , division and bitwise operators , and no loops | Function to multiply two numbers x and y ; 0 multiplied with anything gives 0 ; Add x one by one ; The case where y is negative ; Driver code","code":"def multiply ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( y > 0 ) : NEW_LINE INDENT return ( x + multiply ( x , y - 1 ) ) NEW_LINE DEDENT if ( y < 0 ) : NEW_LINE INDENT return - multiply ( x , - y ) NEW_LINE DEDENT DEDENT print ( multiply ( 5 , - 11 ) ) NEW_LINE"} +{"text":"Sieve of Eratosthenes | Python program to print all primes smaller than or equal to n using Sieve of Eratosthenes ; 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 ; Update all multiples of p ; Print all prime numbers ; Driver code","code":"def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT print p , NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 30 NEW_LINE print \" Following \u2581 are \u2581 the \u2581 prime \u2581 numbers \u2581 smaller \" , NEW_LINE print \" than \u2581 or \u2581 equal \u2581 to \" , n NEW_LINE SieveOfEratosthenes ( n ) NEW_LINE DEDENT"} +{"text":"Pascal 's Triangle | binomialCoeff ; A simple O ( n ^ 3 ) program for Pascal ' s \u2581 Triangle \u2581 Function \u2581 to \u2581 print \u2581 first \u2581 n \u2581 lines \u2581 of \u2581 Pascal ' s Triangle ; Iterate through every line and print entries in it ; Every line has number of integers equal to line number ; Driver program","code":"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 ( 0 , k ) : NEW_LINE INDENT res = res * ( n - i ) NEW_LINE res = res \/\/ ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def printPascal ( n ) : NEW_LINE INDENT for line in range ( 0 , n ) : NEW_LINE INDENT for i in range ( 0 , line + 1 ) : NEW_LINE INDENT print ( binomialCoeff ( line , i ) , \" \u2581 \" , end = \" \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 7 NEW_LINE printPascal ( n ) NEW_LINE"} +{"text":"Pascal 's Triangle | A O ( n ^ 2 ) time and O ( n ^ 2 ) extra space method for Pascal 's Triangle ; An auxiliary array to store generated pascal triangle values ; Iterate through every line and print integer ( s ) in it ; Every line has number of integers equal to line number ; First and last values in every row are 1 ; Other values are sum of values just above and left of above ; Driver Code","code":"def printPascal ( n : int ) : NEW_LINE INDENT arr = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for line in range ( 0 , n ) : NEW_LINE INDENT for i in range ( 0 , line + 1 ) : NEW_LINE INDENT if ( i == 0 or i == line ) : NEW_LINE INDENT arr [ line ] [ i ] = 1 NEW_LINE print ( arr [ line ] [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT arr [ line ] [ i ] = ( arr [ line - 1 ] [ i - 1 ] + arr [ line - 1 ] [ i ] ) NEW_LINE print ( arr [ line ] [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT print ( \" \" , \u2581 end \u2581 = \u2581 \" \" ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE printPascal ( n ) NEW_LINE"} +{"text":"Pascal 's Triangle | Python3 program for Pascal ' s \u2581 Triangle \u2581 A \u2581 O ( n ^ 2 ) \u2581 time \u2581 and \u2581 O ( 1 ) \u2581 extra \u2581 space \u2581 method \u2581 for \u2581 Pascal ' s Triangle Pascal function ; used to represent C ( line , i ) ; The first value in a line is always 1 ; Driver code","code":"def printPascal ( n ) : NEW_LINE INDENT for line in range ( 1 , n + 1 ) : NEW_LINE INDENT C = 1 ; NEW_LINE for i in range ( 1 , line + 1 ) : NEW_LINE INDENT print ( C , end = \" \u2581 \" ) ; NEW_LINE C = int ( C * ( line - i ) \/ i ) ; NEW_LINE DEDENT print ( \" \" ) ; NEW_LINE DEDENT DEDENT n = 5 ; NEW_LINE printPascal ( n ) ; NEW_LINE"} +{"text":"Add two numbers without using arithmetic operators | Python3 Program to add two numbers without using arithmetic operator ; Iterate till there is no carry ; carry now contains common set bits of x and y ; Sum of bits of x and y where at least one of the bits is not set ; Carry is shifted by one so that adding it to x gives the required sum ; Driver Code","code":"def Add ( x , y ) : NEW_LINE INDENT while ( y != 0 ) : NEW_LINE INDENT carry = x & y NEW_LINE x = x ^ y NEW_LINE y = carry << 1 NEW_LINE DEDENT return x NEW_LINE DEDENT print ( Add ( 15 , 32 ) ) NEW_LINE"} +{"text":"Add two numbers without using arithmetic operators |","code":"def Add ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return Add ( x ^ y , ( x & y ) << 1 ) NEW_LINE DEDENT DEDENT"} +{"text":"Compute modulus division by a power | This function will return n % d . d must be one of : 1 , 2 , 4 , 8 , 16 , 32 , ... ; Driver program to test above function ; d must be a power of 2","code":"def getModulo ( n , d ) : NEW_LINE INDENT return ( n & ( d - 1 ) ) NEW_LINE DEDENT n = 6 NEW_LINE d = 4 NEW_LINE print ( n , \" moduo \" , d , \" is \" , getModulo ( n , d ) ) NEW_LINE"} +{"text":"Count set bits in an integer | Function to get no of set bits in binary representation of positive integer n ; Program to test function countSetBits","code":"def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT i = 9 NEW_LINE print ( countSetBits ( i ) ) NEW_LINE"} +{"text":"Count set bits in an integer | recursive function to count set bits ; base case ; Get value from user ; function calling","code":"def countSetBits ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + countSetBits ( n & ( n - 1 ) ) NEW_LINE DEDENT DEDENT n = 9 NEW_LINE print ( countSetBits ( n ) ) NEW_LINE"} +{"text":"Count set bits in an integer | Lookup table ; Function to initialise the lookup table ; To initially generate the table algorithmically ; Function to return the count of set bits in n ; Initialise the lookup table","code":"BitsSetTable256 = [ 0 ] * 256 NEW_LINE def initialize ( ) : NEW_LINE INDENT BitsSetTable256 [ 0 ] = 0 NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT BitsSetTable256 [ i ] = ( i & 1 ) + BitsSetTable256 [ i \/\/ 2 ] NEW_LINE DEDENT DEDENT def countSetBits ( n ) : NEW_LINE INDENT return ( BitsSetTable256 [ n & 0xff ] + BitsSetTable256 [ ( n >> 8 ) & 0xff ] + BitsSetTable256 [ ( n >> 16 ) & 0xff ] + BitsSetTable256 [ n >> 24 ] ) NEW_LINE DEDENT initialize ( ) NEW_LINE n = 9 NEW_LINE print ( countSetBits ( n ) ) NEW_LINE"} +{"text":"Count set bits in an integer | Driver code","code":"print ( bin ( 4 ) . count ( '1' ) ) ; NEW_LINE print ( bin ( 15 ) . count ( '1' ) ) ; NEW_LINE"} +{"text":"Count set bits in an integer | Python3 program to count set bits by pre - storing count set bits in nibbles . ; Recursively get nibble of a given number and map them in the array ; Find last nibble ; Use pre - stored values to find count in last nibble plus recursively add remaining nibbles . ; Driver code","code":"num_to_bits = [ 0 , 1 , 1 , 2 , 1 , 2 , 2 , 3 , 1 , 2 , 2 , 3 , 2 , 3 , 3 , 4 ] ; NEW_LINE def countSetBitsRec ( num ) : NEW_LINE INDENT nibble = 0 ; NEW_LINE if ( 0 == num ) : NEW_LINE INDENT return num_to_bits [ 0 ] ; NEW_LINE DEDENT nibble = num & 0xf ; NEW_LINE return num_to_bits [ nibble ] + countSetBitsRec ( num >> 4 ) ; NEW_LINE DEDENT num = 31 ; NEW_LINE print ( countSetBitsRec ( num ) ) ; NEW_LINE"} +{"text":"Count set bits in an integer | Check each bit in a number is set or not and return the total count of the set bits ; ( 1 << i ) = pow ( 2 , i ) ; Driver code","code":"def countSetBits ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 4 * 8 ) : NEW_LINE INDENT if ( N & ( 1 << i ) ) : NEW_LINE count += 1 NEW_LINE return count NEW_LINE N = 15 NEW_LINE print ( countSetBits ( N ) ) NEW_LINE DEDENT DEDENT"} +{"text":"Program to find parity | Function to get parity of number n . It returns 1 if n has odd parity , and returns 0 if n has even parity ; Driver program to test getParity ( )","code":"def getParity ( n ) : NEW_LINE INDENT parity = 0 NEW_LINE while n : NEW_LINE INDENT parity = ~ parity NEW_LINE n = n & ( n - 1 ) NEW_LINE DEDENT return parity NEW_LINE DEDENT n = 7 NEW_LINE print ( \" Parity \u2581 of \u2581 no \u2581 \" , n , \" \u2581 = \u2581 \" , ( \" odd \" if getParity ( n ) else \" even \" ) ) NEW_LINE"} +{"text":"Program to find whether a no is power of two | Python3 Program to find whether a no is power of two ; Function to check Log base 2 ; Function to check if x is power of 2 ; Driver Code","code":"import math NEW_LINE def Log2 ( x ) : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return false ; NEW_LINE DEDENT return ( math . log10 ( x ) \/ math . log10 ( 2 ) ) ; NEW_LINE DEDENT def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( math . ceil ( Log2 ( n ) ) == math . floor ( Log2 ( n ) ) ) ; NEW_LINE DEDENT if ( isPowerOfTwo ( 31 ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT if ( isPowerOfTwo ( 64 ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT"} +{"text":"Program to find whether a no is power of two | Function to check if x is power of 2 ; Driver code","code":"def isPowerOfTwo ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT while ( n != 1 ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = n \/\/ 2 NEW_LINE DEDENT return True NEW_LINE DEDENT if ( isPowerOfTwo ( 31 ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT if ( isPowerOfTwo ( 64 ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT"} +{"text":"Program to find whether a no is power of two | function which checks whether a number is a power of 2 ; base cases '1' is the only odd number which is a power of 2 ( 2 ^ 0 ) ; all other odd numbers are not powers of 2 ; recursive function call ; Driver Code ; True ; False","code":"def powerof2 ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT elif n % 2 != 0 or n == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT return powerof2 ( n \/ 2 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT print ( powerof2 ( 64 ) ) NEW_LINE print ( powerof2 ( 12 ) ) NEW_LINE DEDENT"} +{"text":"Program to find whether a no is power of two | Function to check if x is power of 2 ; First x in the below expression is for the case when x is 0 ; Driver code","code":"def isPowerOfTwo ( x ) : NEW_LINE INDENT return ( x and ( not ( x & ( x - 1 ) ) ) ) NEW_LINE DEDENT if ( isPowerOfTwo ( 31 ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT if ( isPowerOfTwo ( 64 ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT"} +{"text":"Find the maximum repeating number in O ( n ) time and O ( 1 ) extra space | Returns maximum repeating element in arr [ 0. . n - 1 ] . The array elements are in range from 0 to k - 1 ; Iterate though input array , for every element arr [ i ] , increment arr [ arr [ i ] % k ] by k ; Find index of the maximum repeating element ; Return index of the maximum element ; Driver program to test above function","code":"def maxRepeating ( arr , n , k ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ arr [ i ] % k ] += k NEW_LINE DEDENT max = arr [ 0 ] NEW_LINE result = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] > max : NEW_LINE INDENT max = arr [ i ] NEW_LINE result = i NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 2 , 3 , 3 , 5 , 3 , 4 , 1 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE k = 8 NEW_LINE print ( \" The \u2581 maximum \u2581 repeating \u2581 number \u2581 is \" , maxRepeating ( arr , n , k ) ) NEW_LINE"} +{"text":"Range Query on array whose each element is XOR of index value and previous element | function return derived formula value . ; finding xor value of range [ y ... x ] ; function to solve query for l and r . ; if l or r is 0. ; finding x is divisible by 2 or not . ; Driver Code","code":"def fun ( x ) : NEW_LINE INDENT y = ( x \/\/ 4 ) * 4 NEW_LINE ans = 0 NEW_LINE for i in range ( y , x + 1 ) : NEW_LINE INDENT ans ^= i NEW_LINE DEDENT return ans NEW_LINE DEDENT def query ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT k = ( x + 1 ) \/\/ 2 NEW_LINE if x % 2 == 0 : NEW_LINE INDENT return ( ( fun ( k - 1 ) * 2 ) ^ ( k & 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( 2 * fun ( k ) ) NEW_LINE DEDENT DEDENT def allQueries ( q , l , r ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT print ( query ( r [ i ] ) ^ query ( l [ i ] - 1 ) ) NEW_LINE DEDENT DEDENT q = 3 NEW_LINE l = [ 2 , 2 , 5 ] NEW_LINE r = [ 4 , 8 , 9 ] NEW_LINE allQueries ( q , l , r ) NEW_LINE"} +{"text":"Queries on XOR of greatest odd divisor of the range | Precompute the prefix XOR of greatest odd divisor ; Finding the Greatest Odd divisor ; Finding prefix XOR ; Return XOR of the range ; Driver Code","code":"def prefixXOR ( arr , preXOR , n ) : NEW_LINE INDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT while ( arr [ i ] % 2 != 1 ) : NEW_LINE INDENT arr [ i ] = int ( arr [ i ] \/ 2 ) NEW_LINE DEDENT preXOR [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT preXOR [ i ] = preXOR [ i - 1 ] ^ preXOR [ i ] NEW_LINE DEDENT DEDENT def query ( preXOR , l , r ) : NEW_LINE INDENT if ( l == 0 ) : NEW_LINE INDENT return preXOR [ r ] NEW_LINE DEDENT else : NEW_LINE INDENT return preXOR [ r ] ^ preXOR [ l - 1 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE preXOR = [ 0 for i in range ( n ) ] NEW_LINE prefixXOR ( arr , preXOR , n ) NEW_LINE print ( query ( preXOR , 0 , 2 ) ) NEW_LINE print ( query ( preXOR , 1 , 2 ) ) NEW_LINE DEDENT"} +{"text":"Minimum adjacent swaps required to Sort Binary array | Function to find minimum swaps to sort an array of 0 s and 1 s . ; Array to store count of zeroes ; Count number of zeroes on right side of every one . ; Count total number of swaps by adding number of zeroes on right side of every one . ; Driver code","code":"def findMinSwaps ( arr , n ) : NEW_LINE INDENT noOfZeroes = [ 0 ] * n NEW_LINE count = 0 NEW_LINE noOfZeroes [ n - 1 ] = 1 - arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT noOfZeroes [ i ] = noOfZeroes [ i + 1 ] NEW_LINE if ( arr [ i ] == 0 ) : NEW_LINE INDENT noOfZeroes [ i ] = noOfZeroes [ i ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT count = count + noOfZeroes [ i ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinSwaps ( arr , n ) ) NEW_LINE"} +{"text":"Minimum adjacent swaps required to Sort Binary array | ; Driver Code","code":"def minswaps ( arr ) : NEW_LINE INDENT count = 0 NEW_LINE num_unplaced_zeros = 0 NEW_LINE for index in range ( len ( arr ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ index ] == 0 : NEW_LINE INDENT num_unplaced_zeros += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count += num_unplaced_zeros NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE print ( minswaps ( arr ) ) NEW_LINE"} +{"text":"Program to check if an array is sorted or not ( Iterative and Recursive ) | Function that returns true if array is sorted in non - decreasing order . ; Array has one or no element ; Unsorted pair found ; No unsorted pair found ; Driver code","code":"def arraySortedOrNot ( arr , n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i - 1 ] > arr [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 20 , 23 , 23 , 45 , 78 , 88 ] NEW_LINE n = len ( arr ) NEW_LINE if ( arraySortedOrNot ( arr , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Find the two numbers with odd occurrences in an unsorted array | Prints two numbers that occur odd number of times . The function assumes that the array size is at least 2 and there are exactly two numbers occurring odd number of times . ; Will hold XOR of two odd occurring elements ; Will have only single set bit of xor2 ; Get the xor of all elements in arr [ ] . The xor will basically be xor of two odd occurring elements ; Get one set bit in the xor2 . We get rightmost set bit in the following line as it is easy to get ; Now divide elements in two sets : 1 ) The elements having the corresponding bit as 1. 2 ) The elements having the corresponding bit as 0. ; XOR of first set is finally going to hold one odd occurring number x ; XOR of second set is finally going to hold the other odd occurring number y ; Driver Code","code":"def printTwoOdd ( arr , size ) : NEW_LINE INDENT xor2 = arr [ 0 ] NEW_LINE set_bit_no = 0 NEW_LINE n = size - 2 NEW_LINE x , y = 0 , 0 NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT xor2 = xor2 ^ arr [ i ] NEW_LINE DEDENT set_bit_no = xor2 & ~ ( xor2 - 1 ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( arr [ i ] & set_bit_no ) : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT print ( \" The \u2581 two \u2581 ODD \u2581 elements \u2581 are \" , x , \" & \" , y ) NEW_LINE DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printTwoOdd ( arr , arr_size ) NEW_LINE"} +{"text":"Find a pair with the given difference | The function assumes that the array is sorted ; Initialize positions of two elements ; Search for a pair ; Driver function to test above function","code":"def findPair ( arr , n ) : NEW_LINE INDENT size = len ( arr ) NEW_LINE i , j = 0 , 1 NEW_LINE while i < size and j < size : NEW_LINE INDENT if i != j and arr [ j ] - arr [ i ] == n : NEW_LINE INDENT print \" Pair \u2581 found \u2581 ( \" , arr [ i ] , \" , \" , arr [ j ] , \" ) \" NEW_LINE return True NEW_LINE DEDENT elif arr [ j ] - arr [ i ] < n : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT print \" No \u2581 pair \u2581 found \" NEW_LINE return False NEW_LINE DEDENT arr = [ 1 , 8 , 30 , 40 , 100 ] NEW_LINE n = 60 NEW_LINE findPair ( arr , n ) NEW_LINE"} +{"text":"Find k maximum elements of array in original order | Function to pr m Maximum elements ; vector to store the copy of the original array ; Sorting the vector in descending order . Please refer below link for details ; Traversing through original array and pring all those elements that are in first k of sorted vector . ; Driver code","code":"def printMax ( arr , k , n ) : NEW_LINE INDENT brr = arr . copy ( ) NEW_LINE brr . sort ( reverse = True ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] in brr [ 0 : k ] ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 50 , 8 , 45 , 12 , 25 , 40 , 84 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE printMax ( arr , k , n ) NEW_LINE"} +{"text":"Print n smallest elements from given array in their original order | Function for binary_search ; Function to print smallest n numbers ; Make copy of array ; Sort copy array ; For each arr [ i ] find whether it is a part of n - smallest with binary search ; Driver Code","code":"def binary_search ( arr , low , high , ele ) : NEW_LINE INDENT while low < high : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 NEW_LINE if arr [ mid ] == ele : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] > ele : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printSmall ( arr , asize , n ) : NEW_LINE INDENT copy_arr = arr . copy ( ) NEW_LINE copy_arr . sort ( ) NEW_LINE for i in range ( asize ) : NEW_LINE INDENT if binary_search ( copy_arr , low = 0 , high = n , ele = arr [ i ] ) > - 1 : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE asize = len ( arr ) NEW_LINE n = 5 NEW_LINE printSmall ( arr , asize , n ) NEW_LINE DEDENT"} +{"text":"Check whether Arithmetic Progression can be formed from the given array | Returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; Sort array ; After sorting , difference between consecutive elements must be same . ; Driver code","code":"def checkIsAP ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : return True NEW_LINE arr . sort ( ) NEW_LINE d = arr [ 1 ] - arr [ 0 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] != d ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 20 , 15 , 5 , 0 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Yes \" ) if ( checkIsAP ( arr , n ) ) else print ( \" No \" ) NEW_LINE"} +{"text":"Check whether Arithmetic Progression can be formed from the given array | Returns true if a permutation of arr [ 0. . n - 1 ] can form arithmetic progression ; Find the smallest and and update second smallest ; Find second smallest ; Check if the duplicate element found or not ; If duplicate found then return false ; Find the difference between smallest and second smallest ; As we have used smallest and second smallest , so we should now only check for n - 2 elements ; Driver code","code":"def checkIsAP ( arr , n ) : NEW_LINE INDENT hm = { } NEW_LINE smallest = float ( ' inf ' ) NEW_LINE second_smallest = float ( ' inf ' ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < smallest ) : NEW_LINE INDENT second_smallest = smallest NEW_LINE smallest = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] != smallest and arr [ i ] < second_smallest ) : NEW_LINE INDENT second_smallest = arr [ i ] NEW_LINE DEDENT if arr [ i ] not in hm : NEW_LINE INDENT hm [ arr [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT diff = second_smallest - smallest NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( second_smallest ) not in hm : NEW_LINE INDENT return False NEW_LINE DEDENT second_smallest += diff NEW_LINE DEDENT return True NEW_LINE DEDENT arr = [ 20 , 15 , 5 , 0 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkIsAP ( arr , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Count ways of choosing a pair with maximum difference | Python Code to find no . of Ways of choosing a pair with maximum difference ; To find minimum and maximum of the array ; to find the count of minimum and maximum elements ; Count variables ; condition for all elements equal ; Driver code","code":"def countPairs ( a , n ) : NEW_LINE INDENT mn = + 2147483647 NEW_LINE mx = - 2147483648 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mn = min ( mn , a [ i ] ) NEW_LINE mx = max ( mx , a [ i ] ) NEW_LINE DEDENT c1 = 0 NEW_LINE c2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == mn ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT if ( a [ i ] == mx ) : NEW_LINE INDENT c2 += 1 NEW_LINE DEDENT DEDENT if ( mn == mx ) : NEW_LINE INDENT return n * ( n - 1 ) \/\/ 2 NEW_LINE DEDENT else : NEW_LINE INDENT return c1 * c2 NEW_LINE DEDENT DEDENT a = [ 3 , 2 , 1 , 1 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( countPairs ( a , n ) ) NEW_LINE"} +{"text":"Rearrange a given linked list in | Python3 code to rearrange linked list in place ; Function for rearranging a linked list with high and low value ; Base case ; Two pointer variable ; Swap function for swapping data ; Swap function for swapping data ; Function to insert a node in the linked list at the beginning ; Function to display node of linked list ; Driver code ; Let create a linked list 9 . 6 . 8 . 3 . 7","code":"class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def rearrange ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return head NEW_LINE DEDENT prev , curr = head , head . next NEW_LINE while ( curr ) : NEW_LINE INDENT if ( prev . data > curr . data ) : NEW_LINE INDENT prev . data , curr . data = curr . data , prev . data NEW_LINE DEDENT if ( curr . next and curr . next . data > curr . data ) : NEW_LINE INDENT curr . next . data , curr . data = curr . data , curr . next . data NEW_LINE DEDENT prev = curr . next NEW_LINE if ( not curr . next ) : NEW_LINE INDENT break NEW_LINE DEDENT curr = curr . next . next NEW_LINE DEDENT return head NEW_LINE DEDENT def push ( head , k ) : NEW_LINE INDENT tem = Node ( k ) NEW_LINE tem . data = k NEW_LINE tem . next = head NEW_LINE head = tem NEW_LINE return head NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT curr = head NEW_LINE while ( curr != None ) : NEW_LINE INDENT print ( curr . data , end = \" \u2581 \" ) NEW_LINE curr = curr . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 7 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 9 ) NEW_LINE head = rearrange ( head ) NEW_LINE display ( head ) NEW_LINE DEDENT"} +{"text":"Rearrange a given linked list in | Python3 implementation ; ; Function to print the list ; Function to rearrange ; We set left = null , when we reach stop condition , so no processing required after that ; Stop condition : odd case : left = right , even case : left . next = right ; Stop condition , set null to left nodes ; Even case ; Odd case ; Driver code ; Print original list ; Modify the list ; Print modified list","code":"class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . next = None NEW_LINE DEDENT DEDENT left = None NEW_LINE def printlist ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = \" \u2581 \" ) NEW_LINE if ( head . next != None ) : NEW_LINE INDENT print ( \" - > \" , end = \" \" ) NEW_LINE DEDENT head = head . next NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def rearrange ( head ) : NEW_LINE INDENT global left NEW_LINE if ( head != None ) : NEW_LINE INDENT left = head NEW_LINE reorderListUtil ( left ) NEW_LINE DEDENT DEDENT def reorderListUtil ( right ) : NEW_LINE INDENT global left NEW_LINE if ( right == None ) : NEW_LINE INDENT return NEW_LINE DEDENT reorderListUtil ( right . next ) NEW_LINE if ( left == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( left != right and left . next != right ) : NEW_LINE INDENT temp = left . next NEW_LINE left . next = right NEW_LINE right . next = temp NEW_LINE left = temp NEW_LINE DEDENT else : NEW_LINE INDENT if ( left . next == right ) : NEW_LINE INDENT left . next . next = None NEW_LINE left = None NEW_LINE DEDENT else : NEW_LINE INDENT left . next = None NEW_LINE left = None NEW_LINE DEDENT DEDENT DEDENT head = Node ( 1 ) NEW_LINE head . next = Node ( 2 ) NEW_LINE head . next . next = Node ( 3 ) NEW_LINE head . next . next . next = Node ( 4 ) NEW_LINE head . next . next . next . next = Node ( 5 ) NEW_LINE printlist ( head ) NEW_LINE rearrange ( head ) NEW_LINE printlist ( head ) NEW_LINE"} +{"text":"Subtract Two Numbers represented as Linked Lists | A linked List Node ; A utility function to get length of linked list ; A Utility that padds zeros in front of the Node , with the given diff ; Subtract LinkedList Helper is a recursive function , move till the last Node , and subtract the digits and create the Node and return the Node . If d1 < d2 , we borrow the number from previous digit . ; if you have given the value value to next digit then reduce the d1 by 1 ; If d1 < d2 , then borrow the number from previous digit . Add 10 to d1 and set borrow = True ; subtract the digits ; Create a Node with sub value ; Set the Next pointer as Previous ; This API subtracts two linked lists and returns the linked list which shall have the subtracted result . ; Base Case . ; In either of the case , get the lengths of both Linked list . ; If lengths differ , calculate the smaller Node and padd zeros for smaller Node and ensure both larger Node and smaller Node has equal length . ; If both list lengths are equal , then calculate the larger and smaller list . If 5 - 6 - 7 & 5 - 6 - 8 are linked list , then walk through linked list at last Node as 7 < 8 , larger Node is 5 - 6 - 8 and smaller Node is 5 - 6 - 7. ; After calculating larger and smaller Node , call subtractLinkedListHelper which returns the subtracted linked list . ; A utility function to print linked list ; Driver program to test above functions","code":"class Node : NEW_LINE INDENT def __init__ ( self , new_data ) : NEW_LINE INDENT self . data = new_data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = data NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def getLength ( Node ) : NEW_LINE INDENT size = 0 NEW_LINE while ( Node != None ) : NEW_LINE INDENT Node = Node . next NEW_LINE size = size + 1 NEW_LINE DEDENT return size NEW_LINE DEDENT def paddZeros ( sNode , diff ) : NEW_LINE INDENT if ( sNode == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT zHead = newNode ( 0 ) NEW_LINE diff = diff - 1 NEW_LINE temp = zHead NEW_LINE while ( diff > 0 ) : NEW_LINE INDENT diff = diff - 1 NEW_LINE temp . next = newNode ( 0 ) NEW_LINE temp = temp . next NEW_LINE DEDENT temp . next = sNode NEW_LINE return zHead NEW_LINE DEDENT borrow = True NEW_LINE def subtractLinkedListHelper ( l1 , l2 ) : NEW_LINE INDENT global borrow NEW_LINE if ( l1 == None and l2 == None and not borrow ) : NEW_LINE INDENT return None NEW_LINE DEDENT l3 = None NEW_LINE l4 = None NEW_LINE if ( l1 != None ) : NEW_LINE INDENT l3 = l1 . next NEW_LINE DEDENT if ( l2 != None ) : NEW_LINE INDENT l4 = l2 . next NEW_LINE DEDENT previous = subtractLinkedListHelper ( l3 , l4 ) NEW_LINE d1 = l1 . data NEW_LINE d2 = l2 . data NEW_LINE sub = 0 NEW_LINE if ( borrow ) : NEW_LINE INDENT d1 = d1 - 1 NEW_LINE borrow = False NEW_LINE DEDENT if ( d1 < d2 ) : NEW_LINE INDENT borrow = True NEW_LINE d1 = d1 + 10 NEW_LINE DEDENT sub = d1 - d2 NEW_LINE current = newNode ( sub ) NEW_LINE current . next = previous NEW_LINE return current NEW_LINE DEDENT def subtractLinkedList ( l1 , l2 ) : NEW_LINE INDENT if ( l1 == None and l2 == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT len1 = getLength ( l1 ) NEW_LINE len2 = getLength ( l2 ) NEW_LINE lNode = None NEW_LINE sNode = None NEW_LINE temp1 = l1 NEW_LINE temp2 = l2 NEW_LINE if ( len1 != len2 ) : NEW_LINE INDENT if ( len1 > len2 ) : NEW_LINE INDENT lNode = l1 NEW_LINE DEDENT else : NEW_LINE INDENT lNode = l2 NEW_LINE DEDENT if ( len1 > len2 ) : NEW_LINE INDENT sNode = l2 NEW_LINE DEDENT else : NEW_LINE INDENT sNode = l1 NEW_LINE DEDENT sNode = paddZeros ( sNode , abs ( len1 - len2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT while ( l1 != None and l2 != None ) : NEW_LINE INDENT if ( l1 . data != l2 . data ) : NEW_LINE INDENT if ( l1 . data > l2 . data ) : NEW_LINE INDENT lNode = temp1 NEW_LINE DEDENT else : NEW_LINE INDENT lNode = temp2 NEW_LINE DEDENT if ( l1 . data > l2 . data ) : NEW_LINE INDENT sNode = temp2 NEW_LINE DEDENT else : NEW_LINE INDENT sNode = temp1 NEW_LINE DEDENT break NEW_LINE DEDENT l1 = l1 . next NEW_LINE l2 = l2 . next NEW_LINE DEDENT DEDENT global borrow NEW_LINE borrow = False NEW_LINE return subtractLinkedListHelper ( lNode , sNode ) NEW_LINE DEDENT def printList ( Node ) : NEW_LINE INDENT while ( Node != None ) : NEW_LINE INDENT print ( Node . data , end = \" \u2581 \" ) NEW_LINE Node = Node . next NEW_LINE DEDENT print ( \" \u2581 \" ) NEW_LINE DEDENT head1 = newNode ( 1 ) NEW_LINE head1 . next = newNode ( 0 ) NEW_LINE head1 . next . next = newNode ( 0 ) NEW_LINE head2 = newNode ( 1 ) NEW_LINE result = subtractLinkedList ( head1 , head2 ) NEW_LINE printList ( result ) NEW_LINE"} +{"text":"Insert node into the middle of the linked list | Node class ; constructor to create a new node ; function to insert node at the middle of linked list given the head ; if the list is empty ; create a new node for the value to be inserted ; calcualte the length of the linked list ; ' count ' the number of node after which the new node has to be inserted ; move ptr to the node after which the new node has to inserted ; insert the ' newNode ' and adjust links accordingly ; function to displat the linked list ; Creating the linked list 1.2 . 4.5 ; inserting 3 in the middle of the linked list .","code":"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 insertAtMid ( head , x ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT head = Node ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT newNode = Node ( x ) NEW_LINE ptr = head NEW_LINE length = 0 NEW_LINE while ( ptr != None ) : NEW_LINE INDENT ptr = ptr . next NEW_LINE length += 1 NEW_LINE DEDENT if ( length % 2 == 0 ) : NEW_LINE INDENT count = length \/ 2 NEW_LINE DEDENT else : NEW_LINE INDENT ( length + 1 ) \/ 2 NEW_LINE DEDENT ptr = head NEW_LINE while ( count > 1 ) : NEW_LINE INDENT count -= 1 NEW_LINE ptr = ptr . next NEW_LINE DEDENT newNode . next = ptr . next NEW_LINE ptr . next = newNode NEW_LINE DEDENT DEDENT def display ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT print ( str ( temp . data ) , end = \" \u2581 \" ) NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT head = Node ( 1 ) NEW_LINE head . next = Node ( 2 ) NEW_LINE head . next . next = Node ( 4 ) NEW_LINE head . next . next . next = Node ( 5 ) NEW_LINE print ( \" Linked \u2581 list \u2581 before \u2581 insertion : \u2581 \" , end = \" \" ) NEW_LINE display ( head ) NEW_LINE x = 3 NEW_LINE insertAtMid ( head , x ) NEW_LINE print ( \" Linked list after insertion : \" \u2581 , \u2581 end \u2581 = \u2581 \" \" ) NEW_LINE display ( head ) NEW_LINE"} +{"text":"Insertion Sort for Doubly Linked List | Node of a doubly linked list ; function to create and return a new node of a doubly linked list ; allocate node ; put in the data ; function to insert a new node in sorted way in a sorted doubly linked list ; if list is empty ; if the node is to be inserted at the beginning of the doubly linked list ; locate the node after which the new node is to be inserted ; Make the appropriate links ; if the new node is not inserted at the end of the list ; function to sort a doubly linked list using insertion sort ; Initialize ' sorted ' - a sorted doubly linked list ; Traverse the given doubly linked list and insert every node to 'sorted ; Store next for next iteration ; removing all the links so as to create ' current ' as a new node for insertion ; insert current in ' sorted ' doubly linked list ; Update current ; Update head_ref to point to sorted doubly linked list ; function to print the doubly linked list ; function to insert a node at the beginning of the doubly linked list ; allocate node ; put in the data ; Make next of new node as head and previous as None ; change prev of head node to new node ; move the head to point to the new node ; Driver Code ; start with the empty doubly linked list ; insert the following data","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . prev = None NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def getNode ( data ) : NEW_LINE INDENT newNode = Node ( 0 ) NEW_LINE newNode . data = data NEW_LINE newNode . prev = newNode . next = None NEW_LINE return newNode NEW_LINE DEDENT def sortedInsert ( head_ref , newNode ) : NEW_LINE INDENT current = None NEW_LINE if ( head_ref == None ) : NEW_LINE INDENT head_ref = newNode NEW_LINE DEDENT elif ( ( head_ref ) . data >= newNode . data ) : NEW_LINE INDENT newNode . next = head_ref NEW_LINE newNode . next . prev = newNode NEW_LINE head_ref = newNode NEW_LINE DEDENT else : NEW_LINE INDENT current = head_ref NEW_LINE while ( current . next != None and current . next . data < newNode . data ) : NEW_LINE INDENT current = current . next NEW_LINE DEDENT newNode . next = current . next NEW_LINE if ( current . next != None ) : NEW_LINE INDENT newNode . next . prev = newNode NEW_LINE DEDENT current . next = newNode NEW_LINE newNode . prev = current NEW_LINE DEDENT return head_ref ; NEW_LINE DEDENT def insertionSort ( head_ref ) : NEW_LINE INDENT sorted = None NEW_LINE current = head_ref NEW_LINE while ( current != None ) : NEW_LINE INDENT next = current . next NEW_LINE current . prev = current . next = None NEW_LINE sorted = sortedInsert ( sorted , current ) NEW_LINE current = next NEW_LINE DEDENT head_ref = sorted NEW_LINE return head_ref NEW_LINE DEDENT def printList ( head ) : NEW_LINE INDENT while ( head != None ) : NEW_LINE INDENT print ( head . data , end = \" \u2581 \" ) NEW_LINE head = head . next NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( 0 ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE new_node . prev = None NEW_LINE if ( ( head_ref ) != None ) : NEW_LINE INDENT ( head_ref ) . prev = new_node NEW_LINE DEDENT ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 9 ) NEW_LINE head = push ( head , 3 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 10 ) NEW_LINE head = push ( head , 12 ) NEW_LINE head = push ( head , 8 ) NEW_LINE print ( \" Doubly \u2581 Linked \u2581 List \u2581 Before \u2581 Sorting \" ) NEW_LINE printList ( head ) NEW_LINE head = insertionSort ( head ) NEW_LINE print ( \" Doubly Linked List After Sorting \" ) NEW_LINE printList ( head ) NEW_LINE DEDENT"} +{"text":"Print all possible rotations of a given Array | Function to reverse array between indices s and e ; Function to generate all possible rotations of array ; Driver Code","code":"def reverse ( arr , s , e ) : NEW_LINE INDENT while s < e : NEW_LINE INDENT tem = arr [ s ] NEW_LINE arr [ s ] = arr [ e ] NEW_LINE arr [ e ] = tem NEW_LINE s = s + 1 NEW_LINE e = e - 1 NEW_LINE DEDENT DEDENT def fun ( arr , k ) : NEW_LINE INDENT n = len ( arr ) - 1 NEW_LINE v = n - k NEW_LINE if v >= 0 : NEW_LINE INDENT reverse ( arr , 0 , v ) NEW_LINE reverse ( arr , v + 1 , n ) NEW_LINE reverse ( arr , 0 , n ) NEW_LINE return arr NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT count = 0 NEW_LINE p = fun ( arr , i ) NEW_LINE print ( p , end = \" \u2581 \" ) NEW_LINE DEDENT"} +{"text":"Find array sum using Bitwise OR after splitting given array in two halves after K circular shifts | Python3 program to find Bitwise OR of two equal halves of an array after performing K right circular shifts ; Array for storing the segment tree ; Function to build the segment tree ; Function to return the OR of elements in the range [ l , r ] ; Check for out of bound condition ; Find middle of the range ; Recurse for all the elements in array ; Function to find the OR sum ; Function to build the segment Tree ; Loop to handle q queries ; Effective number of right circular shifts ; OR of second half of the array [ n \/ 2 - i , n - 1 - i ] ; OR of first half of the array [ n - i , n - 1 ] OR [ 0 , n \/ 2 - 1 - i ] ; Print final answer to the query ; Driver Code","code":"MAX = 100005 NEW_LINE seg = [ 0 ] * ( 4 * MAX ) NEW_LINE def build ( node , l , r , a ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT seg [ node ] = a [ l ] NEW_LINE DEDENT else : NEW_LINE INDENT mid = ( l + r ) \/\/ 2 NEW_LINE build ( 2 * node , l , mid , a ) NEW_LINE build ( 2 * node + 1 , mid + 1 , r , a ) NEW_LINE seg [ node ] = ( seg [ 2 * node ] seg [ 2 * node + 1 ] ) NEW_LINE DEDENT DEDENT def query ( node , l , r , start , end , a ) : NEW_LINE INDENT if ( l > end or r < start ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( start <= l and r <= end ) : NEW_LINE INDENT return seg [ node ] NEW_LINE DEDENT mid = ( l + r ) \/\/ 2 NEW_LINE return ( ( query ( 2 * node , l , mid , start , end , a ) ) | ( query ( 2 * node + 1 , mid + 1 , r , start , end , a ) ) ) NEW_LINE DEDENT def orsum ( a , n , q , k ) : NEW_LINE INDENT build ( 1 , 0 , n - 1 , a ) NEW_LINE for j in range ( q ) : NEW_LINE INDENT i = k [ j ] % ( n \/\/ 2 ) NEW_LINE sec = query ( 1 , 0 , n - 1 , n \/\/ 2 - i , n - i - 1 , a ) NEW_LINE first = ( query ( 1 , 0 , n - 1 , 0 , n \/\/ 2 - 1 - i , a ) | query ( 1 , 0 , n - 1 , n - i , n - 1 , a ) ) NEW_LINE temp = sec + first NEW_LINE print ( temp ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 7 , 44 , 19 , 86 , 65 , 39 , 75 , 101 ] NEW_LINE n = len ( a ) NEW_LINE q = 2 NEW_LINE k = [ 4 , 2 ] NEW_LINE orsum ( a , n , q , k ) NEW_LINE DEDENT"} +{"text":"Maximize count of corresponding same elements in given Arrays by Rotation | Function that prints maximum equal elements ; List to store the index of elements of array b ; Storing the positions of array B ; Frequency array to keep count of elements with similar difference in distances ; Iterate through all element in arr1 [ ] ; Calculate number of shift required to make current element equal ; If d is less than 0 ; Store the frequency of current diff ; Compute the maximum frequency stored ; Printing the maximum number of equal elements ; Driver Code ; Given two arrays ; Function Call","code":"def maximumEqual ( a , b , n ) : NEW_LINE INDENT store = [ 0 ] * 10 ** 5 NEW_LINE for i in range ( n ) : NEW_LINE INDENT store [ b [ i ] ] = i + 1 NEW_LINE DEDENT ans = [ 0 ] * 10 ** 5 NEW_LINE for i in range ( n ) : NEW_LINE INDENT d = abs ( store [ a [ i ] ] - ( i + 1 ) ) NEW_LINE if ( store [ a [ i ] ] < i + 1 ) : NEW_LINE INDENT d = n - d NEW_LINE DEDENT ans [ d ] += 1 NEW_LINE DEDENT finalans = 0 NEW_LINE for i in range ( 10 ** 5 ) : NEW_LINE INDENT finalans = max ( finalans , ans [ i ] ) NEW_LINE DEDENT print ( finalans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 6 , 7 , 3 , 9 , 5 ] NEW_LINE B = [ 7 , 3 , 9 , 5 , 6 ] NEW_LINE size = len ( A ) NEW_LINE maximumEqual ( A , B , size ) NEW_LINE DEDENT"} +{"text":"Print array after it is right rotated K times | Function to rightRotate array ; If rotation is greater than size of array ; Printing rightmost kth elements ; Prints array after ' k ' elements ; Driver code","code":"def RightRotate ( a , n , k ) : NEW_LINE INDENT k = k % n ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( i < k ) : NEW_LINE INDENT print ( a [ n + i - k ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( a [ i - k ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT print ( \" \" ) ; NEW_LINE DEDENT Array = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE N = len ( Array ) ; NEW_LINE K = 2 ; NEW_LINE RightRotate ( Array , N , K ) ; NEW_LINE"} +{"text":"Sort a Rotated Sorted Array | Function to restore the Original Sort ; In reverse ( ) , the first parameter is iterator to beginning element and second parameter is iterator to last element plus one . ; Function to print the Array ; Driver code","code":"def restoreSortedArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT reverse ( arr , 0 , i ) ; NEW_LINE reverse ( arr , i + 1 , n ) ; NEW_LINE reverse ( arr , 0 , n ) ; NEW_LINE DEDENT DEDENT DEDENT def reverse ( arr , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT temp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = temp ; NEW_LINE i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \" ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 5 , 1 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE restoreSortedArray ( arr , n - 1 ) ; NEW_LINE printArray ( arr , n ) ; NEW_LINE DEDENT"} +{"text":"Sort a Rotated Sorted Array | Function to find start index of array ; Function to restore the Original Sort ; array is already sorted ; In reverse ( ) , the first parameter is iterator to beginning element and second parameter is iterator to last element plus one . ; Function to print the Array ; Driver code","code":"def findStartIndexOfArray ( arr , low , high ) : NEW_LINE INDENT if ( low > high ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( low == high ) : NEW_LINE INDENT return low ; NEW_LINE DEDENT mid = low + ( high - low ) \/ 2 ; NEW_LINE if ( arr [ mid ] > arr [ mid + 1 ] ) : NEW_LINE INDENT return mid + 1 ; NEW_LINE DEDENT if ( arr [ mid - 1 ] > arr [ mid ] ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT if ( arr [ low ] > arr [ mid ] ) : NEW_LINE INDENT return findStartIndexOfArray ( arr , low , mid - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return findStartIndexOfArray ( arr , mid + 1 , high ) ; NEW_LINE DEDENT DEDENT def restoreSortedArray ( arr , n ) : NEW_LINE INDENT if ( arr [ 0 ] < arr [ n - 1 ] ) : NEW_LINE INDENT return ; NEW_LINE DEDENT start = findStartIndexOfArray ( arr , 0 , n - 1 ) ; NEW_LINE reverse ( arr , 0 , start ) ; NEW_LINE reverse ( arr , start , n ) ; NEW_LINE reverse ( arr ) ; NEW_LINE DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \" ) ; NEW_LINE DEDENT DEDENT def reverse ( arr , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT temp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = temp ; NEW_LINE i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE restoreSortedArray ( arr , n ) ; NEW_LINE printArray ( arr , n ) ; NEW_LINE DEDENT"} +{"text":"Left Rotation and Right Rotation of a String | In - place rotates s towards left by d ; In - place rotates s towards right by d ; Driver code","code":"def leftrotate ( s , d ) : NEW_LINE INDENT tmp = s [ d : ] + s [ 0 : d ] NEW_LINE return tmp NEW_LINE DEDENT def rightrotate ( s , d ) : NEW_LINE INDENT return leftrotate ( s , len ( s ) - d ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" GeeksforGeeks \" NEW_LINE print ( leftrotate ( str1 , 2 ) ) NEW_LINE str2 = \" GeeksforGeeks \" NEW_LINE print ( rightrotate ( str2 , 2 ) ) NEW_LINE DEDENT"} +{"text":"Search an Element in Doubly Circular Linked List | Python3 program to illustrate inserting a Node in a Cicular Doubly Linked list in begging , end and middle ; Structure of a Node ; Function to insert a node at the end ; If the list is empty , create a single node circular and doubly list ; Find last node ; Create Node dynamically ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Function to display the circular doubly linked list ; Function to search the particular element from the list ; Declare the temp variable ; Declare other control variable for the searching ; If start is None return - 1 ; Move the temp pointer until , temp . next doesn 't move start address (Circular Fashion) ; Increment count for location ; If it is found raise the flag and break the loop ; Increment temp pointer ; Check whether last element in the list content the value if contain , raise a flag and increment count ; If flag is true , then element found , else not ; Driver code ; Start with the empty list ; Insert 4. So linked list becomes 4. None ; Insert 5. So linked list becomes 4.5 ; Insert 7. So linked list becomes 4.5 . 7 ; Insert 8. So linked list becomes 4.5 . 7.8 ; Insert 6. So linked list becomes 4.5 . 7.8 . 6","code":"import math NEW_LINE 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 insertNode ( start , value ) : NEW_LINE INDENT if ( start == None ) : NEW_LINE INDENT new_node = Node ( value ) NEW_LINE new_node . data = value NEW_LINE new_node . next = new_node NEW_LINE new_node . prev = new_node NEW_LINE start = new_node NEW_LINE return new_node NEW_LINE DEDENT last = start . prev NEW_LINE new_node = Node ( value ) NEW_LINE new_node . data = value NEW_LINE new_node . next = start NEW_LINE ( start ) . prev = new_node NEW_LINE new_node . prev = last NEW_LINE last . next = new_node NEW_LINE return start NEW_LINE DEDENT def displayList ( start ) : NEW_LINE INDENT temp = start NEW_LINE while ( temp . next != start ) : NEW_LINE INDENT print ( temp . data , end = \" \u2581 \" ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( temp . data ) NEW_LINE DEDENT def searchList ( start , search ) : NEW_LINE INDENT temp = start NEW_LINE count = 0 NEW_LINE flag = 0 NEW_LINE value = 0 NEW_LINE if ( temp == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT while ( temp . next != start ) : NEW_LINE INDENT count = count + 1 NEW_LINE if ( temp . data == search ) : NEW_LINE INDENT flag = 1 NEW_LINE count = count - 1 NEW_LINE break NEW_LINE DEDENT temp = temp . next NEW_LINE DEDENT if ( temp . data == search ) : NEW_LINE INDENT count = count + 1 NEW_LINE flag = 1 NEW_LINE DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( search , \" found \u2581 at \u2581 location \u2581 \" , count ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( search , \" \u2581 not \u2581 found \" ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT start = None NEW_LINE start = insertNode ( start , 4 ) NEW_LINE start = insertNode ( start , 5 ) NEW_LINE start = insertNode ( start , 7 ) NEW_LINE start = insertNode ( start , 8 ) NEW_LINE start = insertNode ( start , 6 ) NEW_LINE print ( \" Created \u2581 circular \u2581 doubly \u2581 linked \u2581 list \u2581 is : \u2581 \" , end = \" \" ) NEW_LINE displayList ( start ) NEW_LINE searchList ( start , 5 ) NEW_LINE DEDENT"} +{"text":"Reverse a doubly circular linked list | Python3 implementation to revesre a doubly circular linked list ; structure of a node of linked list ; function to create and return a new node ; Function to insert at the end ; If the list is empty , create a single node circular and doubly list ; Find last node ; Start is going to be next of new_node ; Make new node previous of start ; Make last preivous of new node ; Make new node next of old last ; Uitlity function to revesre a doubly circular linked list ; Initialize a new head pointer ; get pointer to the the last node ; set ' curr ' to last node ; traverse list in backward direction ; insert ' curr ' at the end of the list starting with the ' new _ head ' pointer ; head pointer of the reversed list ; function to display a doubly circular list in forward and backward direction ; Driver Code","code":"import math NEW_LINE 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 getNode ( data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE newNode . data = data NEW_LINE return newNode NEW_LINE DEDENT def insertEnd ( head , new_node ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT new_node . next = new_node NEW_LINE new_node . prev = new_node NEW_LINE head = new_node NEW_LINE return head NEW_LINE DEDENT last = head . prev NEW_LINE new_node . next = head NEW_LINE head . prev = new_node NEW_LINE new_node . prev = last NEW_LINE last . next = new_node NEW_LINE return head NEW_LINE DEDENT def reverse ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT new_head = None NEW_LINE last = head . prev NEW_LINE curr = last NEW_LINE while ( curr . prev != last ) : NEW_LINE INDENT prev = curr . prev NEW_LINE new_head = insertEnd ( new_head , curr ) NEW_LINE curr = prev NEW_LINE DEDENT new_head = insertEnd ( new_head , curr ) NEW_LINE return new_head NEW_LINE DEDENT def display ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return NEW_LINE DEDENT temp = head NEW_LINE print ( \" Forward \u2581 direction : \u2581 \" , end = \" \" ) NEW_LINE while ( temp . next != head ) : NEW_LINE INDENT print ( temp . data , end = \" \u2581 \" ) NEW_LINE temp = temp . next NEW_LINE DEDENT print ( temp . data ) NEW_LINE last = head . prev NEW_LINE temp = last NEW_LINE print ( \" Backward \u2581 direction : \u2581 \" , end = \" \" ) NEW_LINE while ( temp . prev != last ) : NEW_LINE INDENT print ( temp . data , end = \" \u2581 \" ) NEW_LINE temp = temp . prev NEW_LINE DEDENT print ( temp . data ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = insertEnd ( head , getNode ( 1 ) ) NEW_LINE head = insertEnd ( head , getNode ( 2 ) ) NEW_LINE head = insertEnd ( head , getNode ( 3 ) ) NEW_LINE head = insertEnd ( head , getNode ( 4 ) ) NEW_LINE head = insertEnd ( head , getNode ( 5 ) ) NEW_LINE print ( \" Current \u2581 list : \" ) NEW_LINE display ( head ) NEW_LINE head = reverse ( head ) NEW_LINE print ( \" Reversed list : \" ) NEW_LINE display ( head ) NEW_LINE DEDENT"} +{"text":"Sqrt ( or Square Root ) Decomposition | Set 2 ( LCA of Tree in O ( sqrt ( height ) ) time ) | Python3 implementation to find LCA in a tree ; stores depth for each node ; stores first parent for each node ; marking parent for each node ; marking depth for each node ; propogating marking down the tree ; a dummy node ; precalculating 1 ) depth . 2 ) parent . for each node ; Time Complexity : O ( Height of tree ) recursively jumps one node above till both the nodes become equal ; Driver code ; adding edges to the tree","code":"MAXN = 1001 NEW_LINE depth = [ 0 for i in range ( MAXN ) ] ; NEW_LINE parent = [ 0 for i in range ( MAXN ) ] ; NEW_LINE adj = [ [ ] for i in range ( MAXN ) ] NEW_LINE def addEdge ( u , v ) : NEW_LINE INDENT adj [ u ] . append ( v ) ; NEW_LINE adj [ v ] . append ( u ) ; NEW_LINE DEDENT def dfs ( cur , prev ) : NEW_LINE INDENT parent [ cur ] = prev ; NEW_LINE depth [ cur ] = depth [ prev ] + 1 ; NEW_LINE for i in range ( len ( adj [ cur ] ) ) : NEW_LINE INDENT if ( adj [ cur ] [ i ] != prev ) : NEW_LINE INDENT dfs ( adj [ cur ] [ i ] , cur ) ; NEW_LINE DEDENT DEDENT DEDENT def preprocess ( ) : NEW_LINE INDENT depth [ 0 ] = - 1 ; NEW_LINE dfs ( 1 , 0 ) ; NEW_LINE DEDENT def LCANaive ( u , v ) : NEW_LINE INDENT if ( u == v ) : NEW_LINE INDENT return u ; NEW_LINE DEDENT if ( depth [ u ] > depth [ v ] ) : NEW_LINE INDENT u , v = v , u NEW_LINE DEDENT v = parent [ v ] ; NEW_LINE return LCANaive ( u , v ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT addEdge ( 1 , 2 ) ; NEW_LINE addEdge ( 1 , 3 ) ; NEW_LINE addEdge ( 1 , 4 ) ; NEW_LINE addEdge ( 2 , 5 ) ; NEW_LINE addEdge ( 2 , 6 ) ; NEW_LINE addEdge ( 3 , 7 ) ; NEW_LINE addEdge ( 4 , 8 ) ; NEW_LINE addEdge ( 4 , 9 ) ; NEW_LINE addEdge ( 9 , 10 ) ; NEW_LINE addEdge ( 9 , 11 ) ; NEW_LINE addEdge ( 7 , 12 ) ; NEW_LINE addEdge ( 7 , 13 ) ; NEW_LINE preprocess ( ) ; NEW_LINE print ( ' LCA ( 11,8 ) \u2581 : \u2581 ' + str ( LCANaive ( 11 , 8 ) ) ) NEW_LINE print ( ' LCA ( 3,13 ) \u2581 : \u2581 ' + str ( LCANaive ( 3 , 13 ) ) ) NEW_LINE DEDENT"} +{"text":"Expected Number of Trials to get N Consecutive Heads | Driver code ; Formula for number of trails for N consecutive heads","code":"if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE print ( pow ( 2 , N + 1 ) - 2 ) NEW_LINE DEDENT"} +{"text":"Find and Count total factors of co | Function to return the count of numbers which are divisible by both A and B in the range [ 1 , N ] in constant time ; Compute the count of numbers divisible by A in the range [ 1 , N ] ; Compute the count of numbers divisible by B in the range [ 1 , N ] ; Adding the counts which are divisible by A and B ; The above value might contain repeated values which are divisible by both A and B . Therefore , the count of numbers which are divisible by both A and B are found ; The count computed above is subtracted to compute the final count ; Function to return the sum of numbers which are divisible by both A and B in the range [ 1 , N ] ; Set to store the numbers so that the numbers are not repeated ; For loop to find the numbers which are divisible by A and insert them into the set ; For loop to find the numbers which are divisible by A and insert them into the set ; For loop to iterate through the set and find the sum ; Driver code","code":"def countOfNum ( n , a , b ) : NEW_LINE INDENT cnt_of_a , cnt_of_b , cnt_of_ab , sum = 0 , 0 , 0 , 0 NEW_LINE cnt_of_a = n \/\/ a NEW_LINE cnt_of_b = n \/\/ b NEW_LINE sum = cnt_of_b + cnt_of_a NEW_LINE cnt_of_ab = n \/\/ ( a * b ) NEW_LINE sum = sum - cnt_of_ab NEW_LINE return sum NEW_LINE DEDENT def sumOfNum ( n , a , b ) : NEW_LINE INDENT i = 0 NEW_LINE sum = 0 NEW_LINE ans = dict ( ) NEW_LINE for i in range ( a , n + 1 , a ) : NEW_LINE INDENT ans [ i ] = 1 NEW_LINE DEDENT for i in range ( b , n + 1 , b ) : NEW_LINE INDENT ans [ i ] = 1 NEW_LINE DEDENT for it in ans : NEW_LINE INDENT sum = sum + it NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 88 NEW_LINE A = 11 NEW_LINE B = 8 NEW_LINE count = countOfNum ( N , A , B ) NEW_LINE sumofnum = sumOfNum ( N , A , B ) NEW_LINE print ( sumofnum % count ) NEW_LINE DEDENT"} +{"text":"Find Range Value of the Expression | Function to return the value of the given expression ; Value of the first term ; Value of the last term ; Driver code ; Get the result","code":"def get ( L , R ) : NEW_LINE INDENT x = 1.0 \/ L ; NEW_LINE y = 1.0 \/ ( R + 1.0 ) ; NEW_LINE return ( x - y ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT L = 6 ; R = 12 ; NEW_LINE ans = get ( L , R ) ; NEW_LINE print ( round ( ans , 2 ) ) ; NEW_LINE DEDENT"} +{"text":"Find next greater element with no consecutive 1 in it 's binary representation | Python3 implementation of the approach ; To store the pre - computed integers ; Function that returns true if the binary representation of x contains consecutive 1 s ; To store the previous bit ; Check whether the previous bit and the current bit are both 1 ; Update previous bit ; Go to the next bit ; Function to pre - compute the valid numbers from 0 to MAX ; Store all the numbers which do not have consecutive 1 s ; Function to return the minimum number greater than n which does not contain consecutive 1 s ; Search for the next greater element with no consecutive 1 s ; Function to perform the queries ; Driver code ; Pre - compute the numbers ; Perform the queries","code":"from bisect import bisect_right as upper_bound NEW_LINE MAX = 100000 NEW_LINE v = [ ] NEW_LINE def consecutiveOnes ( x ) : NEW_LINE INDENT p = 0 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT if ( x % 2 == 1 and p == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT p = x % 2 NEW_LINE x \/\/= 2 NEW_LINE DEDENT return False NEW_LINE DEDENT def preCompute ( ) : NEW_LINE INDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT if ( consecutiveOnes ( i ) == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def nextValid ( n ) : NEW_LINE INDENT it = upper_bound ( v , n ) NEW_LINE val = v [ it ] NEW_LINE return val NEW_LINE DEDENT def performQueries ( queries , q ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT print ( nextValid ( queries [ i ] ) ) NEW_LINE DEDENT DEDENT queries = [ 4 , 6 ] NEW_LINE q = len ( queries ) NEW_LINE preCompute ( ) NEW_LINE performQueries ( queries , q ) NEW_LINE"} +{"text":"Minimum given operations required to convert a given binary string to all 1 's | Function to return the number of operations required ; ctr will store the number of consecutive ones at the end of the given binary string ; Loop to find number of 1 s at the end of the string ; If the current character is 1 ; If we encounter the first 0 from the LSB position then we 'll break the loop ; Number of operations required is ( l - ctr ) ; Function to remove leading zeroes from the string ; Loop until s [ i ] becomes not equal to 1 ; If we reach the end of the string , it means that string contains only 0 's ; Return the string without leading zeros ; Driver code ; Removing the leading zeroes","code":"def changeToOnes ( string ) : NEW_LINE INDENT ctr = 0 ; NEW_LINE l = len ( string ) ; NEW_LINE for i in range ( l - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( string [ i ] == '1' ) : NEW_LINE INDENT ctr += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT return l - ctr ; NEW_LINE DEDENT def removeZeroesFromFront ( string ) : NEW_LINE INDENT s = \" \" ; NEW_LINE i = 0 ; NEW_LINE while ( i < len ( string ) and string [ i ] == '0' ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( i == len ( string ) ) : NEW_LINE INDENT s = \"0\" ; NEW_LINE DEDENT else : NEW_LINE INDENT s = string [ i : len ( string ) - i ] ; NEW_LINE DEDENT return s ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \"10010111\" ; NEW_LINE string = removeZeroesFromFront ( string ) ; NEW_LINE print ( changeToOnes ( string ) ) ; NEW_LINE DEDENT"} +{"text":"Minimum deletions required such that any number X will occur exactly X times | Function to return the minimum deletions required ; To store the frequency of the array elements ; Store frequency of each element ; To store the minimum deletions required ; Value ; It 's frequency ; If number less than or equal to it 's frequency ; Delete extra occurrences ; Delete every occurrence of x ; Driver code","code":"def MinDeletion ( a , n ) : NEW_LINE INDENT map = dict . fromkeys ( a , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT map [ a [ i ] ] += 1 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for key , value in map . items ( ) : NEW_LINE INDENT x = key ; NEW_LINE frequency = value ; NEW_LINE if ( x <= frequency ) : NEW_LINE INDENT ans += ( frequency - x ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ans += frequency ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 2 , 3 , 2 , 3 , 4 , 4 , 4 , 4 , 5 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( MinDeletion ( a , n ) ) ; NEW_LINE DEDENT"} +{"text":"Concatenate strings in any order to get Maximum Number of \" AB \" | Function to find maximum number of ABs ; variable A , B , AB for count strings that end with ' A ' but not end with ' B ' , ' B ' but does not end with ' A ' and ' B ' and ends with ' A ' respectively . ; ' AB ' is already present in string before concatenate them ; count of strings that begins with ' B ' and ends with 'A ; count of strings that begins with ' B ' but does not end with 'A ; count of strings that ends with ' A ' but not end with 'B ; updating the value of ans and add extra count of 'AB ; Driver Code","code":"def maxCountAB ( s , n ) : NEW_LINE INDENT A = 0 NEW_LINE B = 0 NEW_LINE BA = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT S = s [ i ] NEW_LINE L = len ( S ) NEW_LINE for j in range ( L - 1 ) : NEW_LINE INDENT if ( S [ j ] == ' A ' and S [ j + 1 ] == ' B ' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( S [ 0 ] == ' B ' and S [ L - 1 ] == ' A ' ) : NEW_LINE INDENT BA += 1 NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT elif ( S [ 0 ] == ' B ' ) : NEW_LINE INDENT B += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT elif ( S [ L - 1 ] == ' A ' ) : NEW_LINE INDENT A += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( BA == 0 ) : NEW_LINE INDENT ans += min ( B , A ) NEW_LINE DEDENT elif ( A + B == 0 ) : NEW_LINE INDENT ans += BA - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += BA + min ( B , A ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ \" ABCA \" , \" BOOK \" , \" BAND \" ] NEW_LINE n = len ( s ) NEW_LINE print ( maxCountAB ( s , n ) ) NEW_LINE DEDENT"} +{"text":"Minimum operations to make sum of neighbouring elements <= X | Function to return the minimum number of operations required ; To store total operations required ; First make all elements equal to x which are currenctly greater ; Left scan the array ; Update the current element such that neighbouring sum is < x ; Driver code","code":"def MinOperations ( n , x , arr ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > x ) : NEW_LINE INDENT difference = arr [ i ] - x NEW_LINE total = total + difference NEW_LINE arr [ i ] = x NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT LeftNeigbouringSum = arr [ i ] + arr [ i - 1 ] NEW_LINE if ( LeftNeigbouringSum > x ) : NEW_LINE INDENT current_diff = LeftNeigbouringSum - x NEW_LINE arr [ i ] = max ( 0 , arr [ i ] - current_diff ) NEW_LINE total = total + current_diff NEW_LINE DEDENT DEDENT return total NEW_LINE DEDENT X = 1 NEW_LINE arr = [ 1 , 6 , 1 , 2 , 0 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( MinOperations ( N , X , arr ) ) NEW_LINE"} +{"text":"Find the repeating and the missing number using two equations | Python3 implementation of the approach ; Function to print the required numbers ; Sum of first n natural numbers ; Sum of squares of first n natural numbers ; To store the sum and sum of squares of the array elements ; Driver code","code":"import math NEW_LINE def findNumbers ( arr , n ) : NEW_LINE INDENT sumN = ( n * ( n + 1 ) ) \/ 2 ; NEW_LINE sumSqN = ( n * ( n + 1 ) * ( 2 * n + 1 ) ) \/ 6 ; NEW_LINE sum = 0 ; NEW_LINE sumSq = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum = sum + arr [ i ] ; NEW_LINE sumSq = sumSq + ( math . pow ( arr [ i ] , 2 ) ) ; NEW_LINE DEDENT B = ( ( ( sumSq - sumSqN ) \/ ( sum - sumN ) ) + sumN - sum ) \/ 2 ; NEW_LINE A = sum - sumN + B ; NEW_LINE print ( \" A \u2581 = \u2581 \" , int ( A ) ) ; NEW_LINE print ( \" B \u2581 = \u2581 \" , int ( B ) ) ; NEW_LINE DEDENT arr = [ 1 , 2 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findNumbers ( arr , n ) ; NEW_LINE"} +{"text":"Lexicographically smallest string with given string as prefix | Function to find the whether the string temp starts with str or not ; Base Case ; Check for the corresponding characters in temp & str ; Function to find lexicographic smallest string consisting of the string str as prefix ; Sort the given array string arr [ ] ; If the i - th string contains given string as a prefix , then print the result ; If no string exists then return \" - 1\" ; Driver Code","code":"def is_prefix ( temp , str ) : NEW_LINE INDENT if ( len ( temp ) < len ( str ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] != temp [ i ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT DEDENT def lexicographicallyString ( input , n , str ) : NEW_LINE INDENT input . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp = input [ i ] NEW_LINE if ( is_prefix ( temp , str ) ) : NEW_LINE INDENT return temp NEW_LINE DEDENT DEDENT return \" - 1\" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ \" apple \" , \" appe \" , \" apl \" , \" aapl \" , \" appax \" ] NEW_LINE S = \" app \" NEW_LINE N = 5 NEW_LINE print ( lexicographicallyString ( arr , N , S ) ) NEW_LINE DEDENT"} +{"text":"Rearrange Array to find K using Binary Search algorithm without sorting | Function to rearrange the array ; Stores the rearranged array ; Stores whether the arrangement is possible or not ; Update K with the position of K ; Stores all elements lesser than and greater than in vector smaller and greater respectively ; Traverse the array arr [ ] ; If arr [ i ] is less than arr [ K ] ; Else ; Iterate unil low is less than or equal to high ; Stores mid point ; If mid is equal to K ; If mid is less than K ; If mid is greater than K ; If f is - 1 ; Iterate in the range [ 1 , N ] ; If ans [ i ] is equal to - 1 ; Print the rearranged array ; Driver Code ; Input ; Function Call","code":"def Rearrange ( arr , K , N ) : NEW_LINE INDENT ans = [ 0 ] * ( N + 1 ) NEW_LINE f = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans [ i ] = - 1 NEW_LINE DEDENT K = arr . index ( K ) NEW_LINE smaller = [ ] NEW_LINE greater = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] < arr [ K ] ) : NEW_LINE INDENT smaller . append ( arr [ i ] ) NEW_LINE DEDENT elif ( arr [ i ] > arr [ K ] ) : NEW_LINE INDENT greater . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT low = 0 NEW_LINE high = N - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 NEW_LINE if ( mid == K ) : NEW_LINE INDENT ans [ mid ] = arr [ K ] NEW_LINE f = 1 NEW_LINE break NEW_LINE DEDENT elif ( mid < K ) : NEW_LINE INDENT if ( len ( smaller ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT ans [ mid ] = smaller [ - 1 ] NEW_LINE smaller . pop ( ) NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( len ( greater ) == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT ans [ mid ] = greater [ - 1 ] NEW_LINE greater . pop ( ) NEW_LINE high = mid - 1 NEW_LINE DEDENT DEDENT if ( f == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( ans [ i ] == - 1 ) : NEW_LINE INDENT if ( len ( smaller ) ) : NEW_LINE INDENT ans [ i ] = smaller [ - 1 ] NEW_LINE smaller . pop ( ) NEW_LINE DEDENT elif ( len ( greater ) ) : NEW_LINE INDENT ans [ i ] = greater [ - 1 ] NEW_LINE greater . pop ( ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( ans [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 10 , 7 , 2 , 5 , 3 , 8 ] NEW_LINE K = 7 NEW_LINE N = len ( arr ) NEW_LINE Rearrange ( arr , K , N ) NEW_LINE DEDENT"} +{"text":"Minimize K to let Person A consume at least ceil ( N \/ ( M + 1 ) ) candies based on given rules | Python 3 program for the above approach ; Function to find minimum value of K such that the first person gets at least ( N \/ ( M + 1 ) ) candies ; Find the minimum required value of candies for the first person ; Iterate K from [ 1 , n ] ; Total number of candies ; Candies taken by Person 1 ; Candies taken by 1 st person is minimum of K and candies left ; Traverse the array arr [ ] ; Amount consumed by the person j ; Update the number of candies ; Good share of candies achieved ; Driver Code","code":"import math NEW_LINE def minimumK ( arr , M , N ) : NEW_LINE INDENT good = math . ceil ( ( N * 1.0 ) \/ ( ( M + 1 ) * 1.0 ) ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT K = i NEW_LINE candies = N NEW_LINE taken = 0 NEW_LINE while ( candies > 0 ) : NEW_LINE INDENT taken += min ( K , candies ) NEW_LINE candies -= min ( K , candies ) NEW_LINE for j in range ( M ) : NEW_LINE INDENT consume = ( arr [ j ] * candies ) \/ 100 NEW_LINE candies -= consume NEW_LINE DEDENT DEDENT if ( taken >= good ) : NEW_LINE print ( i ) NEW_LINE return NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 13 NEW_LINE M = 1 NEW_LINE arr = [ 50 ] NEW_LINE minimumK ( arr , M , N ) NEW_LINE DEDENT"} +{"text":"Total time required to travel a path denoted by a given string | Function to calculate time taken to travel the path ; Stores total time ; Initial position ; Stores visited segments ; Check whether segment is present in the set ; Increment the value of time by 2 ; Insert segment into the set ; Print the value of time ; Driver Code","code":"def calcTotalTime ( path ) : NEW_LINE INDENT time = 0 NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE s = set ( [ ] ) NEW_LINE for i in range ( len ( path ) ) : NEW_LINE INDENT p = x NEW_LINE q = y NEW_LINE if ( path [ i ] == ' N ' ) : NEW_LINE INDENT y += 1 NEW_LINE DEDENT elif ( path [ i ] == ' S ' ) : NEW_LINE INDENT y -= 1 NEW_LINE DEDENT elif ( path [ i ] == ' E ' ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT elif ( path [ i ] == ' W ' ) : NEW_LINE INDENT x -= 1 NEW_LINE DEDENT if ( p + x , q + y ) not in s : NEW_LINE INDENT time += 2 NEW_LINE s . add ( ( p + x , q + y ) ) NEW_LINE DEDENT else : NEW_LINE INDENT time += 1 NEW_LINE DEDENT DEDENT print ( time ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT path = \" NSE \" NEW_LINE calcTotalTime ( path ) NEW_LINE DEDENT"} +{"text":"Cost required to make all array elements equal to 1 | Function to calculate the cost required to make all array elements equal to 1 ; Stores the total cost ; Traverse the array arr [ ] ; If current element is 0 ; Convert 0 to 1 ; Add the cost ; Return the total cost ; Driver Code","code":"def findCost ( A , N ) : NEW_LINE INDENT totalCost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] == 0 ) : NEW_LINE INDENT A [ i ] = 1 NEW_LINE totalCost += i NEW_LINE DEDENT DEDENT return totalCost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findCost ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Find the peak index of a given array | Function to find the peak index for the given array ; Base Case ; Check for strictly increasing array ; If the strictly increasing condition is violated , then break ; Stores the value of i , which is a potential peak index ; Second traversal , for strictly decreasing array ; When the strictly decreasing condition is violated , then break ; If i = N - 1 , it means that ans is the peak index ; Otherwise , peak index doesn 't exist ; Driver Code","code":"def peakIndex ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE if ( len ( arr ) < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT i = 0 NEW_LINE while ( i + 1 < N ) : NEW_LINE INDENT if ( arr [ i + 1 ] < arr [ i ] or arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i == 0 or i == N - 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = i NEW_LINE while ( i < N - 1 ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i + 1 ] or arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i == N - 1 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 0 ] NEW_LINE print ( peakIndex ( arr ) ) NEW_LINE DEDENT"} +{"text":"Given an array A [ ] and a number x , check for pair in A [ ] with sum as x | Set 2 | Function to check if the array has 2 elements whose sum is equal to the given value ; Sort the array in increasing order ; Traverse the array , nums [ ] ; Store the required number to be found ; Perform binary search ; Store the mid value ; If nums [ mid ] is greater than x , then update high to mid - 1 ; If nums [ mid ] is less than x , then update low to mid + 1 ; Otherwise ; If mid is equal i , check mid - 1 and mid + 1 ; Otherwise , prthe pair and return ; If no such pair is found , then pr - 1 ; Driver Code ; Function Call","code":"def hasArrayTwoPairs ( nums , n , target ) : NEW_LINE INDENT nums = sorted ( nums ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = target - nums [ i ] NEW_LINE low , high = 0 , n - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( ( high - low ) \/\/ 2 ) NEW_LINE if ( nums [ mid ] > x ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT elif ( nums [ mid ] < x ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( mid == i ) : NEW_LINE INDENT if ( ( mid - 1 >= 0 ) and nums [ mid - 1 ] == x ) : NEW_LINE INDENT print ( nums [ i ] , end = \" , \u2581 \" ) NEW_LINE print ( nums [ mid - 1 ] ) NEW_LINE return NEW_LINE DEDENT if ( ( mid + 1 < n ) and nums [ mid + 1 ] == x ) : NEW_LINE INDENT print ( nums [ i ] , end = \" , \u2581 \" ) NEW_LINE print ( nums [ mid + 1 ] ) NEW_LINE return NEW_LINE DEDENT break NEW_LINE DEDENT else : NEW_LINE INDENT print ( nums [ i ] , end = \" , \u2581 \" ) NEW_LINE print ( nums [ mid ] ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 0 , - 1 , 2 , - 3 , 1 ] NEW_LINE X = - 2 NEW_LINE N = len ( A ) NEW_LINE hasArrayTwoPairs ( A , N , X ) NEW_LINE DEDENT"} +{"text":"Smallest divisor of N closest to X | Python3 program for the above approach ; Function to find the divisor of N closest to the target ; Iterate till square root of N ; Check if divisors are equal ; Check if i is the closest ; Check if i is the closest ; Check if n \/ i is the closest ; Prthe closest value ; Driver Code ; Given N & X ; Function Call","code":"from math import sqrt , floor , ceil NEW_LINE def findClosest ( N , target ) : NEW_LINE INDENT closest = - 1 NEW_LINE diff = 10 ** 18 NEW_LINE for i in range ( 1 , ceil ( sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( N \/\/ i == i ) : NEW_LINE INDENT if ( abs ( target - i ) < diff ) : NEW_LINE INDENT diff = abs ( target - i ) NEW_LINE closest = i NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( abs ( target - i ) < diff ) : NEW_LINE INDENT diff = abs ( target - i ) NEW_LINE closest = i NEW_LINE DEDENT if ( abs ( target - N \/\/ i ) < diff ) : NEW_LINE INDENT diff = abs ( target - N \/\/ i ) NEW_LINE closest = N \/\/ i NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( closest ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , X = 16 , 5 NEW_LINE findClosest ( N , X ) NEW_LINE DEDENT"} +{"text":"Find a pair ( a , b ) such that Aa + Bb = N | Function to calculate the minimum power of A and B greater than N ; Stores the power of A which is greater than N ; Increment count by 1 ; Divide N by A ; Function to find a pair ( a , b ) such that A ^ a + B ^ b = N ; Calculate the minimum power of A greater than N ; Calculate the minimum power of B greater than N ; Make copy of A and B ; Traverse for every pair ( i , j ) ; Check if B ^ j + A ^ i = N To overcome the overflow problem use B = N - A rather than B + A = N ; Increment power B by 1 ; Increment power A by 1 ; Finally pr - 1 if no pair is found ; Driver Code ; Given A , B and N ; Function Call","code":"def power ( A , N ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( A == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( N > 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE N \/\/= A ; NEW_LINE DEDENT return int ( count ) ; NEW_LINE DEDENT def Pairs ( N , A , B ) : NEW_LINE INDENT powerA , powerB = 0 , 0 ; NEW_LINE powerA = power ( A , N ) ; NEW_LINE powerB = power ( B , N ) ; NEW_LINE intialB = B ; NEW_LINE intialA = A ; NEW_LINE A = 1 ; NEW_LINE for i in range ( powerA + 1 ) : NEW_LINE INDENT B = 1 ; NEW_LINE for j in range ( powerB + 1 ) : NEW_LINE INDENT if ( B == N - A ) : NEW_LINE INDENT print ( i , \" \u2581 \" , j ) ; NEW_LINE return ; NEW_LINE DEDENT B *= intialB ; NEW_LINE DEDENT A *= intialA ; NEW_LINE DEDENT print ( \" - 1\" ) ; NEW_LINE return ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 106 ; NEW_LINE A = 3 ; NEW_LINE B = 5 ; NEW_LINE Pairs ( N , A , B ) ; NEW_LINE DEDENT"} +{"text":"Count numbers from a given range that are not divisible by any of the array elements | Function to find the non - multiples till k ; Stores all unique multiples ; Iterate the array ; For finding duplicates only once ; Inserting all multiples into the set ; Returning only the count of numbers that are not divisible by any of the array elements ; Function to count the total values in the range [ L , R ] ; Count all values in the range using exclusion principle ; Driver Code ; Function Call","code":"def findNonMultiples ( arr , n , k ) : NEW_LINE INDENT multiples = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in multiples ) : NEW_LINE INDENT for j in range ( 1 , k \/\/ arr [ i ] + 1 ) : NEW_LINE INDENT multiples . add ( arr [ i ] * j ) NEW_LINE DEDENT DEDENT DEDENT return k - len ( multiples ) NEW_LINE DEDENT def countValues ( arr , N , L , R ) : NEW_LINE INDENT return ( findNonMultiples ( arr , N , R ) - findNonMultiples ( arr , N , L - 1 ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE L = 1 NEW_LINE R = 20 NEW_LINE print ( countValues ( arr , N , L , R ) ) NEW_LINE DEDENT"} +{"text":"Minimum number of coins to be collected per hour to empty N piles in at most H hours | Function to find the minimum number of coins to be collected per hour to empty N piles in H hours ; Stores the minimum coins to be removed per hour ; Find the maximum array element ; Perform Binary Search ; Store the mid value of the range in K ; Find the total time taken to empty N piles by removing K coins per hour ; If total time does not exceed H ; Otherwise ; Prthe required result ; Driver Code ; Function Call","code":"def minCollectingSpeed ( piles , H ) : NEW_LINE INDENT ans = - 1 NEW_LINE low = 1 NEW_LINE high = max ( piles ) NEW_LINE while ( low <= high ) : NEW_LINE INDENT K = low + ( high - low ) \/\/ 2 NEW_LINE time = 0 NEW_LINE for ai in piles : NEW_LINE time += ( ai + K - 1 ) \/\/ K NEW_LINE if ( time <= H ) : NEW_LINE INDENT ans = K NEW_LINE high = K - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = K + 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 6 , 7 , 11 ] NEW_LINE H = 8 NEW_LINE minCollectingSpeed ( arr , H ) NEW_LINE DEDENT"} +{"text":"Count distinct pairs with given sum | Function to count distinct pairs in array whose sum equal to K ; Stores count of distinct pairs whose sum equal to K ; Sort the array ; Stores index of the left pointer ; Stores index of the right pointer ; Calculate count of distinct pairs whose sum equal to K ; If sum of current pair is equal to K ; Remove consecutive duplicate array elements ; Update i ; Remove consecutive duplicate array elements ; Update j ; Update cntPairs ; Update i ; Update j ; If sum of current pair less than K ; Update i ; Update j ; Driver Code","code":"def cntDisPairs ( arr , N , K ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] == K ) : NEW_LINE INDENT while ( i < j and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( i < j and arr [ j ] == arr [ j - 1 ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT cntPairs += 1 NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ i ] + arr [ j ] < K ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 5 , 7 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 13 NEW_LINE print ( cntDisPairs ( arr , N , K ) ) NEW_LINE DEDENT"} +{"text":"Count distinct pairs with given sum | Function to count distinct pairs in array whose sum equal to K ; Stores count of distinct pairs whose sum equal to K ; Store frequency of each distinct element of the array ; Update frequency of arr [ i ] ; Traverse the map ; Stores key value of the map ; If i is the half of K ; If frequency of i greater than 1 ; Update cntPairs ; Update cntPairs ; Driver Code","code":"def cntDisPairs ( arr , N , K ) : NEW_LINE INDENT cntPairs = 0 NEW_LINE cntFre = { } NEW_LINE for i in arr : NEW_LINE INDENT if i in cntFre : NEW_LINE INDENT cntFre [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntFre [ i ] = 1 NEW_LINE DEDENT DEDENT for key , value in cntFre . items ( ) : NEW_LINE INDENT i = key NEW_LINE if ( 2 * i == K ) : NEW_LINE INDENT if ( cntFre [ i ] > 1 ) : NEW_LINE INDENT cntPairs += 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( cntFre [ K - i ] ) : NEW_LINE INDENT cntPairs += 1 NEW_LINE DEDENT DEDENT DEDENT cntPairs = cntPairs \/ 2 NEW_LINE return cntPairs NEW_LINE DEDENT arr = [ 5 , 6 , 5 , 7 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 13 NEW_LINE print ( int ( cntDisPairs ( arr , N , K ) ) ) NEW_LINE"} +{"text":"Queries to find longest subsequence having no similar adjacent elements with updates | Function to find the length of the longest subsequence such that no two adjacent elements are equal ; Replace element at index x with y ; Since x is 1 - indexed , decrement x by 1 ; Keep track of number of elements in subsequence ; If previous element is not same as current element ; Print the desired count ; Driver Code ; Function Call","code":"def longestSubsequence ( N , Q , arr , Queries ) : NEW_LINE INDENT for i in range ( Q ) : NEW_LINE INDENT x = Queries [ i ] [ 0 ] NEW_LINE y = Queries [ i ] [ 1 ] NEW_LINE arr [ x - 1 ] = y NEW_LINE count = 1 NEW_LINE for j in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ j ] != arr [ j - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE Q = 2 NEW_LINE Queries = [ [ 1 , 3 ] , [ 4 , 2 ] ] NEW_LINE longestSubsequence ( N , Q , arr , Queries ) NEW_LINE DEDENT"} +{"text":"Queries to find longest subsequence having no similar adjacent elements with updates | Python3 program for the above approach ; Traverse the array arr [ ] ; If previous element is not same as current element ; Traverse the queries ; Replace element at index x with y ; Recalculate for index x ; Subtract contribution of element at index x ; Add contribution of y ; Recalculate for index x + 1 ; Subtract contribution of element at index x + 1 ; Adds contribution of y ; Replace the element ; Driver Code ; Function Call","code":"def longestSubsequence ( N , Q , arr , Queries ) : NEW_LINE INDENT count = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT for i in range ( Q ) : NEW_LINE INDENT x = Queries [ i ] [ 0 ] NEW_LINE y = Queries [ i ] [ 1 ] NEW_LINE if ( x > 1 ) : NEW_LINE INDENT if ( arr [ x - 1 ] != arr [ x - 2 ] ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( arr [ x - 2 ] != y ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( x < N ) : NEW_LINE INDENT if ( arr [ x ] != arr [ x - 1 ] ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( y != arr [ x ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = ' \u2581 ' ) NEW_LINE arr [ x - 1 ] = y NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE Q = 2 NEW_LINE Queries = [ [ 1 , 3 ] , [ 4 , 2 ] ] NEW_LINE longestSubsequence ( N , Q , arr , Queries ) NEW_LINE DEDENT"} +{"text":"Sum of absolute differences of indices of occurrences of each array element | Python3 program for the above approach ; Function to find sum of differences of indices of occurrences of each unique array element ; Stores indices of each array element ; Store the indices ; Stores the sums ; Traverse the array ; Find sum for each element ; Iterate over the Map ; Calculate sum of occurrences of arr [ i ] ; Store sum for current element ; Print answer for each element ; Driver code ; Given array ; Given size ; Function Call","code":"from collections import defaultdict NEW_LINE def sum_i ( arr , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] . append ( i ) NEW_LINE DEDENT ans = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for it in mp [ arr [ i ] ] : NEW_LINE INDENT sum += abs ( it - i ) NEW_LINE ans [ i ] = sum NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE sum_i ( arr , n ) NEW_LINE DEDENT"} +{"text":"Convert vowels into upper case character in a given string | Function to convert vowels into uppercase ; Stores the length of str ; Driver Code","code":"def conVowUpp ( str ) : NEW_LINE INDENT N = len ( str ) NEW_LINE str1 = \" \" NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str [ i ] == ' a ' or str [ i ] == ' e ' or str [ i ] == ' i ' or str [ i ] == ' o ' or str [ i ] == ' u ' ) : NEW_LINE INDENT c = ( str [ i ] ) . upper ( ) NEW_LINE str1 += c NEW_LINE DEDENT else : NEW_LINE INDENT str1 += str [ i ] NEW_LINE DEDENT DEDENT print ( str1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" eutopia \" NEW_LINE conVowUpp ( str ) NEW_LINE DEDENT"} +{"text":"Maximize number of days for which P chocolates can be distributed consecutively to N people | Stores the frequency of each type of chocolate ; Function to check if chocolates can be eaten for ' mid ' no . of days ; If cnt exceeds N , return true ; Function to find the maximum number of days for which chocolates can be eaten ; Store the frequency of each type of chocolate ; Initialize start and end with 0 and P respectively ; Calculate mid ; Check if chocolates can be distributed for mid days ; Check if chocolates can be distributed for more than mid consecutive days ; Driver code ; Function call","code":"mp = { } NEW_LINE N , P = 0 , 0 NEW_LINE def helper ( mid ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in mp : NEW_LINE INDENT temp = mp [ i ] NEW_LINE while ( temp >= mid ) : NEW_LINE INDENT temp -= mid NEW_LINE cnt += 1 NEW_LINE DEDENT DEDENT return cnt >= N NEW_LINE DEDENT def findMaximumDays ( arr ) : NEW_LINE INDENT for i in range ( P ) : NEW_LINE INDENT mp [ arr [ i ] ] = mp . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT start = 0 NEW_LINE end = P NEW_LINE ans = 0 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( ( end - start ) \/\/ 2 ) NEW_LINE if ( mid != 0 and helper ( mid ) ) : NEW_LINE INDENT ans = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT elif ( mid == 0 ) : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE P = 10 NEW_LINE arr = [ 1 , 2 , 2 , 1 , 1 , 3 , 3 , 3 , 2 , 4 ] NEW_LINE print ( findMaximumDays ( arr ) ) NEW_LINE DEDENT"} +{"text":"Count subarrays having sum modulo K same as the length of the subarray | Function that counts the subarrays having sum modulo k equal to the length of subarray ; Stores the count of subarrays ; Stores prefix sum of the array ; Calculate prefix sum array ; Generate all the subarrays ; Check if this subarray is a valid subarray or not ; Total count of subarrays ; Given arr [ ] ; Size of the array ; Given K ; Function call","code":"def countSubarrays ( a , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE pref = [ ] NEW_LINE pref . append ( 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT pref . append ( ( a [ i ] + pref [ i ] ) % k ) NEW_LINE DEDENT for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 , 1 ) : NEW_LINE INDENT if ( ( pref [ j ] - pref [ i - 1 ] + k ) % k == j - i + 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT print ( ans , end = ' \u2581 ' ) NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 3 , 1 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE countSubarrays ( arr , N , K ) NEW_LINE"} +{"text":"Count subarrays having sum modulo K same as the length of the subarray | Function that counts the subarrays s . t . sum of elements in the subarray modulo k is equal to size of subarray ; Stores the count of ( pref [ i ] - i ) % k ; Stores the count of subarray ; Stores prefix sum of the array ; Find prefix sum array ; Base Condition ; Remove the index at present after K indices from the current index ; Update the answer for subarrays ending at the i - th index ; Add the calculated value of current index to count ; Print the count of subarrays ; Given arr [ ] ; Size of the array ; Given K ; Function call","code":"def countSubarrays ( a , n , k ) : NEW_LINE INDENT cnt = { } NEW_LINE ans = 0 NEW_LINE pref = [ ] NEW_LINE pref . append ( 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT pref . append ( ( a [ i ] + pref [ i ] ) % k ) NEW_LINE DEDENT cnt [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT remIdx = i - k NEW_LINE if ( remIdx >= 0 ) : NEW_LINE INDENT if ( ( pref [ remIdx ] - remIdx % k + k ) % k in cnt ) : NEW_LINE INDENT cnt [ ( pref [ remIdx ] - remIdx % k + k ) % k ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ ( pref [ remIdx ] - remIdx % k + k ) % k ] = - 1 NEW_LINE DEDENT DEDENT if ( pref [ i ] - i % k + k ) % k in cnt : NEW_LINE INDENT ans += cnt [ ( pref [ i ] - i % k + k ) % k ] NEW_LINE DEDENT if ( pref [ i ] - i % k + k ) % k in cnt : NEW_LINE INDENT cnt [ ( pref [ i ] - i % k + k ) % k ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt [ ( pref [ i ] - i % k + k ) % k ] = 1 NEW_LINE DEDENT DEDENT print ( ans , end = ' \u2581 ' ) NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 3 , 1 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE countSubarrays ( arr , N , K ) NEW_LINE"} +{"text":"Check if all substrings of length K of a Binary String has equal count of 0 s and 1 s | Function to check if the substring of length K has equal 0 and 1 ; Traverse the string ; Check if every K - th character is the same or not ; Traverse substring of length K ; If current character is 0 ; Increment count ; Otherwise ; Decrement count ; Check for equal 0 s and 1 s ; Driver code","code":"def check ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( i , n , k ) : NEW_LINE INDENT if ( s [ i ] != s [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT c = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT else : NEW_LINE INDENT c -= 1 NEW_LINE DEDENT DEDENT if ( c == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT s = \"101010\" NEW_LINE k = 2 NEW_LINE if ( check ( s , k ) != 0 ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Check if characters of a given string can be used to form any N equal strings | Python3 program for the above approach ; Function to check if the freq of any character is divisible by N ; Stores the frequency of characters ; If frequency of a character is not divisible by n ; If no character has frequency at least N ; Driver Code ; Function call","code":"from collections import defaultdict NEW_LINE def isSame ( str , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT mp [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for it in mp . keys ( ) : NEW_LINE INDENT if ( mp [ it ] >= n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT str = \" ccabcba \" NEW_LINE n = 4 NEW_LINE if ( isSame ( str , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Find the root of given non decreasing function between A and B | Python3 program for the above approach ; Given function ; Function to find the root of the given non - decreasing Function ; To get the minimum possible answer for the root ; Find mid ; Search in [ low , x ] ; Search in [ x , high ] ; Return the required answer ; Function to find the roots of the given equation within range [ a , b ] ; If root doesn 't exists ; Else find the root upto 4 decimal places ; Driver code ; Given range ; Function call","code":"import math NEW_LINE eps = 1e-6 NEW_LINE def func ( a , b , c , x ) : NEW_LINE INDENT return a * x * x + b * x + c NEW_LINE DEDENT def findRoot ( a , b , c , low , high ) : NEW_LINE INDENT x = - 1 NEW_LINE while abs ( high - low ) > eps : NEW_LINE INDENT x = ( low + high ) \/ 2 NEW_LINE if ( func ( a , b , c , low ) * func ( a , b , c , x ) <= 0 ) : NEW_LINE INDENT high = x NEW_LINE DEDENT else : NEW_LINE INDENT low = x NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def solve ( a , b , c , A , B ) : NEW_LINE INDENT if ( func ( a , b , c , A ) * func ( a , b , c , B ) > 0 ) : NEW_LINE INDENT print ( \" No \u2581 solution \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" { : . 4f } \" . format ( findRoot ( a , b , c , A , B ) ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 2 NEW_LINE b = - 3 NEW_LINE c = - 2 NEW_LINE A = 0 NEW_LINE B = 3 NEW_LINE solve ( a , b , c , A , B ) NEW_LINE DEDENT"} +{"text":"Median of difference of all pairs from an Array | Function check if mid can be median index of the difference array ; Size of the array ; Total possible no of pair possible ; The index of the element in the difference of all pairs from the array ; Count the number of pairs having difference <= mid ; If the difference between end and first element is less then or equal to mid ; Checking for the no of element less than or equal to mid is greater than median or not ; Function to calculate the median of differences of all pairs from the array ; Size of the array ; Initialising the low and high ; Binary search ; Calculate mid ; If mid can be the median of the array ; Returning the median of the differences of pairs from the array ; Driver Code","code":"def possible ( mid , a ) : NEW_LINE INDENT n = len ( a ) ; NEW_LINE total = ( n * ( n - 1 ) ) \/\/ 2 ; NEW_LINE need = ( total + 1 ) \/\/ 2 ; NEW_LINE count = 0 ; NEW_LINE start = 0 ; end = 1 ; NEW_LINE while ( end < n ) : NEW_LINE INDENT if ( a [ end ] - a [ start ] <= mid ) : NEW_LINE INDENT end += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count += ( end - start - 1 ) ; NEW_LINE start += 1 ; NEW_LINE DEDENT DEDENT if ( end == n and start < end and a [ end - 1 ] - a [ start ] <= mid ) : NEW_LINE INDENT t = end - start - 1 ; NEW_LINE count += ( t * ( t + 1 ) \/\/ 2 ) ; NEW_LINE DEDENT if ( count >= need ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def findMedian ( a ) : NEW_LINE INDENT n = len ( a ) ; NEW_LINE low = 0 ; high = a [ n - 1 ] - a [ 0 ] ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 ; NEW_LINE if ( possible ( mid , a ) ) : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT DEDENT return high + 1 ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 7 , 5 , 2 ] ; NEW_LINE a . sort ( ) NEW_LINE print ( findMedian ( a ) ) ; NEW_LINE DEDENT"} +{"text":"Print all Strings from array A [ ] having all strings from array B [ ] as subsequence | Function to find strings from A [ ] having all strings in B [ ] as subsequence ; Calculate respective sizes ; Stores the answer ; Stores the frequency of each character in strings of A [ ] ; Compute the frequencies of characters of all strings ; Stores the frequency of each character in strings of B [ ] each character of a string in B [ ] ; If the frequency of a character in B [ ] exceeds that in A [ ] ; A string exists in B [ ] which is not a proper subset of A [ i ] ; If all strings in B [ ] are proper subset of A [ ] ; Push the string in resultant vector ; If any string is found ; Print those strings ; Otherwise ; Driver code","code":"def UniversalSubset ( A , B ) : NEW_LINE INDENT n1 = len ( A ) NEW_LINE n2 = len ( B ) NEW_LINE res = [ ] NEW_LINE A_freq = [ [ 0 for x in range ( 26 ) ] for y in range ( n1 ) ] NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT for j in range ( len ( A [ i ] ) ) : NEW_LINE INDENT A_freq [ i ] [ ord ( A [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT B_freq = [ 0 ] * 26 NEW_LINE for i in range ( n2 ) : NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE for j in range ( len ( B [ i ] ) ) : NEW_LINE INDENT arr [ ord ( B [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE B_freq [ ord ( B [ i ] [ j ] ) - ord ( ' a ' ) ] = max ( B_freq [ ord ( B [ i ] [ j ] ) - ord ( ' a ' ) ] , arr [ ord ( B [ i ] [ j ] ) - ord ( ' a ' ) ] ) NEW_LINE DEDENT DEDENT for i in range ( n1 ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT if ( A_freq [ i ] [ j ] < B_freq [ j ] ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT res . append ( A [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( res ) ) : NEW_LINE INDENT for i in range ( len ( res ) ) : NEW_LINE INDENT for j in range ( len ( res [ i ] ) ) : NEW_LINE INDENT print ( res [ i ] [ j ] , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 , end = \" \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ \" geeksforgeeks \" , \" topcoder \" , \" leetcode \" ] NEW_LINE B = [ \" geek \" , \" ee \" ] NEW_LINE UniversalSubset ( A , B ) NEW_LINE DEDENT"} +{"text":"Closest pair in an Array such that one number is multiple of the other | Python3 program for the above approach ; Function to find the minimum distance pair where one is the multiple of the other ; Initialize the variables ; Iterate for all the elements ; Loop to make pairs ; Check for minimum distance ; Check if one is a multiple of other ; Update the distance ; Store indexes ; If no such pair exists ; Print the answer ; Given array arr [ ] ; Function call","code":"import sys NEW_LINE def findPair ( a , n ) : NEW_LINE INDENT min_dist = sys . maxsize NEW_LINE index_a = - 1 NEW_LINE index_b = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( j - i < min_dist ) : NEW_LINE INDENT if ( ( a [ i ] % a [ j ] == 0 ) or ( a [ j ] % a [ i ] == 0 ) ) : NEW_LINE INDENT min_dist = j - i NEW_LINE index_a = i NEW_LINE index_b = j NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( index_a == - 1 ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" ( \" , a [ index_a ] , \" , \u2581 \" , a [ index_b ] , \" ) \" ) NEW_LINE DEDENT DEDENT a = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE findPair ( a , n ) NEW_LINE"} +{"text":"Print all numbers in given range having digits in strictly increasing order | Function to print all numbers in the range [ L , R ] having digits in strictly increasing order ; Iterate over the range ; Iterate over the digits ; Check if the current digit is >= the previous digit ; If the digits are in ascending order ; Given range L and R ; Function call","code":"def printNum ( L , R ) : NEW_LINE INDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT temp = i NEW_LINE c = 10 NEW_LINE flag = 0 NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( temp % 10 >= c ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT c = temp % 10 NEW_LINE temp \/\/= 10 NEW_LINE DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT L = 10 NEW_LINE R = 15 NEW_LINE printNum ( L , R ) NEW_LINE"} +{"text":"Find the missing number in unordered Arithmetic Progression | Python3 program for the above approach ; Function to find the missing element ; Fix left and right boundary for binary search ; Find index of middle element ; Check if the element just after the middle element is missing ; Check if the element just before mid is missing ; Check if the elements till mid follow the AP , then recur for right half ; Else recur for left half ; Function to find the missing element in AP series ; Sort the array arr [ ] ; Calculate Common Difference ; Binary search for the missing ; Given array arr [ ] ; Function call","code":"import sys NEW_LINE def findMissing ( arr , left , right , diff ) : NEW_LINE INDENT if ( right <= left ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT mid = left + ( right - left ) \/\/ 2 NEW_LINE if ( arr [ mid + 1 ] - arr [ mid ] != diff ) : NEW_LINE INDENT return ( arr [ mid ] + diff ) NEW_LINE DEDENT if ( mid > 0 and arr [ mid ] - arr [ mid - 1 ] != diff ) : NEW_LINE INDENT return ( arr [ mid - 1 ] + diff ) NEW_LINE DEDENT if ( arr [ mid ] == arr [ 0 ] + mid * diff ) : NEW_LINE INDENT return findMissing ( arr , mid + 1 , right , diff ) NEW_LINE DEDENT return findMissing ( arr , left , mid - 1 , diff ) NEW_LINE DEDENT def missingElement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE diff = ( arr [ n - 1 ] - arr [ 0 ] ) \/\/ n NEW_LINE return findMissing ( arr , 0 , n - 1 , diff ) NEW_LINE DEDENT arr = [ 2 , 8 , 6 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( missingElement ( arr , n ) ) NEW_LINE"} +{"text":"Floor value Kth root of a number using Recursive Binary Search | Function to calculate x raised to the power y in O ( logn ) ; Function to find the Kth root of the number N using BS ; If the range is still valid ; Find the mid - value of range ; Base Case ; Condition to check if the left search space is useless ; Given N and K ; Function Call","code":"def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT temp = power ( x , y \/\/ 2 ) ; NEW_LINE if ( y % 2 == 0 ) : NEW_LINE INDENT return temp * temp ; NEW_LINE DEDENT else : NEW_LINE INDENT return x * temp * temp ; NEW_LINE DEDENT DEDENT def nthRootSearch ( low , high , N , K ) : NEW_LINE INDENT if ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 ; NEW_LINE if ( ( power ( mid , K ) <= N ) and ( power ( mid + 1 , K ) > N ) ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT elif ( power ( mid , K ) < N ) : NEW_LINE INDENT return nthRootSearch ( mid + 1 , high , N , K ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return nthRootSearch ( low , mid - 1 , N , K ) ; NEW_LINE DEDENT DEDENT return low ; NEW_LINE DEDENT N = 16 ; K = 4 ; NEW_LINE print ( nthRootSearch ( 0 , N , N , K ) ) NEW_LINE"} +{"text":"Count of subsets having sum of min and max element less than K | Function that return the count of subset such that min ( S ) + max ( S ) < K ; Sorting the array ; ans stores total number of subsets ; Add all possible subsets between i and j ; Decrease the sum ; Driver code","code":"def get_subset_count ( arr , K , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE left = 0 ; NEW_LINE right = N - 1 ; NEW_LINE ans = 0 ; NEW_LINE while ( left <= right ) : NEW_LINE INDENT if ( arr [ left ] + arr [ right ] < K ) : NEW_LINE INDENT ans += 1 << ( right - left ) ; NEW_LINE left += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT right -= 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT arr = [ 2 , 4 , 5 , 7 ] ; NEW_LINE K = 8 ; NEW_LINE print ( get_subset_count ( arr , K , 4 ) ) NEW_LINE"} +{"text":"Minimize the maximum difference of adjacent elements after at most K insertions | Python3 program to find the minimum of maximum difference between adjacent elements after at most K insertions ; Calculate the maximum adjacent difference ; If the maximum adjacent difference is already zero ; best and worst specifies range of the maximum adjacent difference ; To store the no of insertions required for respective values of mid ; If the number of insertions required exceeds K ; Otherwise ; Driver code","code":"def minMaxDiff ( arr , n , k ) : NEW_LINE INDENT max_adj_dif = float ( ' - inf ' ) ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT max_adj_dif = max ( max_adj_dif , abs ( arr [ i ] - arr [ i + 1 ] ) ) ; NEW_LINE DEDENT if ( max_adj_dif == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT best = 1 ; NEW_LINE worst = max_adj_dif ; NEW_LINE while ( best < worst ) : NEW_LINE INDENT mid = ( best + worst ) \/\/ 2 ; NEW_LINE required = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT required += ( abs ( arr [ i ] - arr [ i + 1 ] ) - 1 ) \/\/ mid NEW_LINE DEDENT if ( required > k ) : NEW_LINE INDENT best = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT worst = mid NEW_LINE DEDENT DEDENT return worst NEW_LINE DEDENT arr = [ 3 , 12 , 25 , 50 ] NEW_LINE n = len ( arr ) NEW_LINE k = 7 NEW_LINE print ( minMaxDiff ( arr , n , k ) ) NEW_LINE"} +{"text":"Check if minimum element in array is less than or equals half of every other element | Python3 implementation to Check if the minimum element in the array is greater than or equal to half of every other element ; Function to Check if the minimum element in the array is greater than or equal to half of every other element ; Initialise the variables to store smallest and second smallest ; Check if current element is smaller than smallest , the current smallest will become secondSmallest and current element will be the new smallest ; Check if current element is smaller than secondSmallest simply update the latter ; Driver code","code":"import math NEW_LINE def checkMin ( arr , n ) : NEW_LINE INDENT smallest = math . inf NEW_LINE secondSmallest = math . inf NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < smallest ) : NEW_LINE INDENT secondSmallest = smallest NEW_LINE smallest = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < secondSmallest ) : NEW_LINE INDENT secondSmallest = arr [ i ] NEW_LINE DEDENT DEDENT if ( 2 * smallest <= secondSmallest ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE checkMin ( arr , n ) NEW_LINE DEDENT"} +{"text":"Largest and smallest Fibonacci numbers in an Array | Python 3 program to find minimum and maximum fibonacci number in given array ; Function to create hash table to check Fibonacci numbers ; Insert initial two numbers in the hash table ; Sum of previous two numbers ; Update the variable each time ; Function to find minimum and maximum fibonacci number in given array ; Find maximum value in the array ; Creating a set containing all Fibonacci numbers up to maximum value in the array ; For storing the Minimum and Maximum Fibonacci number ; Check if current element is a fibonacci number ; Update the maximum and minimum accordingly ; Driver code","code":"import sys NEW_LINE def createHash ( hash , maxElement ) : NEW_LINE INDENT prev = 0 NEW_LINE curr = 1 NEW_LINE hash . add ( prev ) NEW_LINE hash . add ( curr ) NEW_LINE while ( curr <= maxElement ) : NEW_LINE INDENT temp = curr + prev NEW_LINE hash . add ( temp ) NEW_LINE prev = curr NEW_LINE curr = temp NEW_LINE DEDENT DEDENT def fibonacci ( arr , n ) : NEW_LINE INDENT max_val = max ( arr ) NEW_LINE hash = set ( ) NEW_LINE createHash ( hash , max_val ) NEW_LINE minimum = sys . maxsize NEW_LINE maximum = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] in hash ) : NEW_LINE INDENT minimum = min ( minimum , arr [ i ] ) NEW_LINE maximum = max ( maximum , arr [ i ] ) NEW_LINE DEDENT DEDENT print ( minimum , end = \" , \u2581 \" ) NEW_LINE print ( maximum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE fibonacci ( arr , n ) NEW_LINE DEDENT"} +{"text":"Longest substring with K unique characters using Binary Search | Function that returns True if there is a sub of length len with <= k unique characters ; Size of the ; Map to store the characters and their frequency ; Update the map for the first sub ; Check for the rest of the subs ; Add the new character ; Remove the first character of the previous window ; Update the map ; Function to return the length of the longest sub which has K unique characters ; Check if the complete contains K unique characters ; Size of the ; Apply binary search ; Driver code","code":"def isValidLen ( s , lenn , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE mp = dict ( ) NEW_LINE right = 0 NEW_LINE while ( right < lenn ) : NEW_LINE INDENT mp [ s [ right ] ] = mp . get ( s [ right ] , 0 ) + 1 NEW_LINE right += 1 NEW_LINE DEDENT if ( len ( mp ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT while ( right < n ) : NEW_LINE INDENT mp [ s [ right ] ] = mp . get ( s [ right ] , 0 ) + 1 NEW_LINE mp [ s [ right - lenn ] ] -= 1 NEW_LINE if ( mp [ s [ right - lenn ] ] == 0 ) : NEW_LINE INDENT del mp [ s [ right - lenn ] ] NEW_LINE DEDENT if ( len ( mp ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT right += 1 NEW_LINE DEDENT return len ( mp ) <= k NEW_LINE DEDENT def maxLenSubStr ( s , k ) : NEW_LINE INDENT uni = dict ( ) NEW_LINE for x in s : NEW_LINE INDENT uni [ x ] = 1 NEW_LINE DEDENT if ( len ( uni ) < k ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT n = len ( s ) NEW_LINE lo = - 1 NEW_LINE hi = n + 1 NEW_LINE while ( hi - lo > 1 ) : NEW_LINE INDENT mid = lo + hi >> 1 NEW_LINE if ( isValidLen ( s , mid , k ) ) : NEW_LINE INDENT lo = mid NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid NEW_LINE DEDENT DEDENT return lo NEW_LINE DEDENT s = \" aabacbebebe \" NEW_LINE k = 3 NEW_LINE print ( maxLenSubStr ( s , k ) ) NEW_LINE"} +{"text":"Largest area square in an array when elements can be shuffled | Function that returns true if it is possible to make a square with side equal to l ; To store the count of elements greater than or equal to l ; Increment the count ; If the count becomes greater than or equal to l ; Function to return the maximum area of the square that can be obtained ; If square is possible with side length m ; Try to find a square with smaller side length ; Return the area ; Driver code","code":"def isSquarePossible ( arr , n , l ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] >= l : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if cnt >= l : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def maxArea ( arr , n ) : NEW_LINE INDENT l , r = 0 , n NEW_LINE len = 0 NEW_LINE while l <= r : NEW_LINE INDENT m = l + ( ( r - l ) \/\/ 2 ) NEW_LINE if isSquarePossible ( arr , n , m ) : NEW_LINE INDENT len = m NEW_LINE l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT return ( len * len ) NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 5 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxArea ( arr , n ) ) NEW_LINE"} +{"text":"Check duplicates in a stream of strings | Function to insert the names and check whether they appear for the first time ; To store the names of the employees ; If current name is appearing for the first time ; Driver code","code":"def insertNames ( arr , n ) : NEW_LINE INDENT string = set ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in string : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE string . add ( arr [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ \" geeks \" , \" for \" , \" geeks \" ] ; NEW_LINE n = len ( arr ) ; NEW_LINE insertNames ( arr , n ) ; NEW_LINE DEDENT"} +{"text":"Count the triplets such that A [ i ] < B [ j ] < C [ k ] | Function to return the count of elements in arr [ ] which are less than the given key ; Modified binary search ; Function to return the count of elements in arr [ ] which are greater than the given key ; Modified binary search ; Function to return the count of the required triplets ; Sort all three arrays ; Iterate for all the elements of array B ; Count of elements in A [ ] which are less than the chosen element from B [ ] ; Count of elements in C [ ] which are greater than the chosen element from B [ ] ; Update the count ; Driver code","code":"def countLessThan ( arr , n , key ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE index = - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) \/\/ 2 NEW_LINE if ( arr [ m ] < key ) : NEW_LINE INDENT l = m + 1 NEW_LINE index = m NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT return ( index + 1 ) NEW_LINE DEDENT def countGreaterThan ( arr , n , key ) : NEW_LINE INDENT l = 0 NEW_LINE r = n - 1 NEW_LINE index = - 1 NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) \/\/ 2 NEW_LINE if ( arr [ m ] <= key ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE index = m NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( n - index ) NEW_LINE DEDENT def countTriplets ( n , a , b , c ) : NEW_LINE INDENT a . sort NEW_LINE b . sort ( ) NEW_LINE c . sort ( ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT current = b [ i ] NEW_LINE a_index = - 1 NEW_LINE c_index = - 1 NEW_LINE low = countLessThan ( a , n , current ) NEW_LINE high = countGreaterThan ( c , n , current ) NEW_LINE count += ( low * high ) NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 5 ] NEW_LINE b = [ 2 , 4 ] NEW_LINE c = [ 3 , 6 ] NEW_LINE size = len ( a ) NEW_LINE print ( countTriplets ( size , a , b , c ) ) NEW_LINE DEDENT"} +{"text":"Cost to Balance the parentheses | Python 3 code to calculate the minimum cost to make the given parentheses balanced ; To store absolute count of balanced and unbalanced parenthesis ; o ( open bracket ) stores count of ' ( ' and c ( close bracket ) stores count of ') ; Driver code","code":"def costToBalance ( s ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT ans = 0 NEW_LINE DEDENT ' NEW_LINE INDENT o = 0 NEW_LINE c = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT o += 1 NEW_LINE DEDENT if ( s [ i ] == ' ) ' ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( o != c ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT a = [ 0 for i in range ( len ( s ) ) ] NEW_LINE if ( s [ 0 ] == ' ( ' ) : NEW_LINE INDENT a [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ 0 ] = - 1 NEW_LINE DEDENT if ( a [ 0 ] < 0 ) : NEW_LINE INDENT ans += abs ( a [ 0 ] ) NEW_LINE DEDENT for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] = a [ i - 1 ] - 1 NEW_LINE DEDENT if ( a [ i ] < 0 ) : NEW_LINE INDENT ans += abs ( a [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : s = \" ) ) ) ( ( ( \" NEW_LINE INDENT print ( costToBalance ( s ) ) s = \" ) ) ( ( \" NEW_LINE print ( costToBalance ( s ) ) NEW_LINE DEDENT"} +{"text":"Middle of three using minimum comparisons | Function to find the middle of three number ; x is positive if a is greater than b . x is negative if b is greater than a . ; Similar to x ; Similar to x and y . ; Checking if b is middle ( x and y both are positive ) ; Checking if c is middle ( x and z both are positive ) ; Driver Code","code":"def middleOfThree ( a , b , c ) : NEW_LINE INDENT x = a - b NEW_LINE y = b - c NEW_LINE z = a - c NEW_LINE if x * y > 0 : NEW_LINE INDENT return b NEW_LINE DEDENT elif ( x * z > 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT else : NEW_LINE INDENT return a NEW_LINE DEDENT DEDENT a = 20 NEW_LINE b = 30 NEW_LINE c = 40 NEW_LINE print ( middleOfThree ( a , b , c ) ) NEW_LINE"} +{"text":"Find four missing numbers in an array containing elements from 1 to N | Finds missing 4 numbers in O ( N ) time and O ( 1 ) auxiliary space . ; To keep track of 4 possible numbers greater than length of input array In Java , helper is automatically initialized as 0. ; Traverse the input array and mark visited elements either by marking them as negative in arr [ ] or in helper [ ] . ; If element is smaller than or equal to length , mark its presence in arr [ ] ; Mark presence in helper [ ] ; Print all those elements whose presence is not marked . ; Driver code","code":"def missing4 ( arr ) : NEW_LINE INDENT helper = [ 0 ] * 4 NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT temp = abs ( arr [ i ] ) NEW_LINE if ( temp <= len ( arr ) ) : NEW_LINE INDENT arr [ temp - 1 ] = arr [ temp - 1 ] * ( - 1 ) NEW_LINE DEDENT elif ( temp > len ( arr ) ) : NEW_LINE INDENT if ( temp % len ( arr ) ) : NEW_LINE INDENT helper [ temp % len ( arr ) - 1 ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT helper [ ( temp % len ( arr ) ) + len ( arr ) - 1 ] = - 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT print ( ( i + 1 ) , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( helper ) ) : NEW_LINE INDENT if ( helper [ i ] >= 0 ) : NEW_LINE INDENT print ( ( len ( arr ) + i + 1 ) , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 7 , 3 , 12 , 5 , 10 , 8 , 4 , 9 ] NEW_LINE missing4 ( arr ) NEW_LINE"} +{"text":"Permutation present at the middle of lexicographic ordering of permutations of at most length N made up integers up to K | Function that finds the middle the lexicographical smallest sequence ; If K is even ; First element is K \/ 2 ; Remaining elements of the sequence are all integer K ; Stores the sequence when K is odd ; Iterate over the range [ 0 , N \/ 2 ] ; Check if the sequence ends with in 1 or not ; Remove the sequence ending in 1 ; If it doesn 't end in 1 ; Decrement by 1 ; Insert K to the sequence till its size is N ; Prthe sequence stored in the vector ; Driver Code","code":"def lexiMiddleSmallest ( K , N ) : NEW_LINE INDENT if ( K % 2 == 0 ) : NEW_LINE INDENT print ( K \/\/ 2 , end = \" \u2581 \" ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT print ( K , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE return NEW_LINE DEDENT a = [ ( K + 1 ) \/\/ 2 ] * ( N ) NEW_LINE for i in range ( N \/\/ 2 ) : NEW_LINE INDENT if ( a [ - 1 ] == 1 ) : NEW_LINE INDENT del a [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT a [ - 1 ] -= 1 NEW_LINE while ( len ( a ) < N ) : NEW_LINE INDENT a . append ( K ) NEW_LINE DEDENT DEDENT DEDENT for i in a : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K , N = 2 , 4 NEW_LINE lexiMiddleSmallest ( K , N ) NEW_LINE DEDENT"} +{"text":"Remaining array element after repeated removal of the smallest element from pairs with absolute difference of 2 or 0 | Function to find the last remaining array element after repeatedly removing the smallest from pairs having absolute difference 2 or 0 ; Sort the given array in ascending order ; Traverse the array ; If difference between adjacent elements is not equal to 0 or 2 ; If operations can be performed ; Driver Code","code":"def findLastElement ( arr , N ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE i = 0 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] != 0 \\ and arr [ i ] - arr [ i - 1 ] != 2 ) : NEW_LINE INDENT print ( \" - 1\" ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT print ( arr [ N - 1 ] ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 8 , 0 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findLastElement ( arr , N ) ; NEW_LINE DEDENT"} +{"text":"Maximize count of subsets into which the given array can be split such that it satisfies the given condition | Function to count maximum subsets into which the given array can be split such that it satisfies the given condition ; Sort the array in decreasing order ; Stores count of subsets possible ; Stores count of elements in current subset ; Traverse the array arr [ ] ; Update size ; If product of the smallest element present in the current subset and size of current subset is >= K ; Update maxSub ; Update size ; Driver Code ; Given array ; Size of the array ; Given value of X","code":"def maxDivisions ( arr , N , X ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE maxSub = 0 ; NEW_LINE size = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT size += 1 ; NEW_LINE if ( arr [ i ] * size >= X ) : NEW_LINE INDENT maxSub += 1 ; NEW_LINE size = 0 ; NEW_LINE DEDENT DEDENT print ( maxSub ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE X = 3 ; NEW_LINE maxDivisions ( arr , N , X ) ; NEW_LINE DEDENT"} +{"text":"Maximize sum of second minimums in all quadruples of a given array | Function to find maximum possible sum of second minimums in each quadruple ; Sort the array ; Add the second minimum ; Print maximum possible sum ; Driver Code ; Given array ; Size of the array","code":"def maxPossibleSum ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE j = N - 3 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT sum += arr [ j ] NEW_LINE j -= 3 NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 7 , 4 , 5 , 2 , 3 , 1 , 5 , 9 ] NEW_LINE N = 8 NEW_LINE maxPossibleSum ( arr , N ) NEW_LINE DEDENT"} +{"text":"Difference between Insertion sort and Selection sort | Function to sort an array using insertion sort ; Move elements of arr [ 0. . i - 1 ] , that are greater than key to one position ahead of their current position ; Function to print an array of size N ; Print the array ; Driver Code ; Function Call","code":"def insertionSort ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE key = 0 NEW_LINE j = 0 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT key = arr [ i ] NEW_LINE j = i - 1 NEW_LINE while ( j >= 0 and arr [ j ] > key ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT arr [ j + 1 ] = key NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( \" \" , end \u2581 = \u2581 \" \" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 11 , 13 , 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE insertionSort ( arr , N ) NEW_LINE printArray ( arr , N ) NEW_LINE DEDENT"} +{"text":"Count pairs ( i , j ) from given array such that i K * arr [ j ] | Function to find the count required pairs ; Stores count of pairs ; Traverse the array ; Check if the condition is satisfied or not ; Driver Code ; Function Call","code":"def getPairs ( 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 INDENT if ( arr [ i ] > K * arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE getPairs ( arr , N , K ) NEW_LINE DEDENT"} +{"text":"Count pairs ( i , j ) from given array such that i K * arr [ j ] | Function to merge two sorted arrays ; i : index to left subarray ; j : index to right subarray ; Stores count of pairs that satisfy the given condition ; Traverse to check for the valid conditions ; If condition satisfies ; All elements in the right side of the left subarray also satisfies ; Sort the two given arrays and store in the resultant array ; Elements which are left in the left subarray ; Elements which are left in the right subarray ; Return the count obtained ; Function to partition array into two halves ; Same as ( l + r ) \/ 2 , but avoids overflow for large l and h ; Sort first and second halves ; Call the merging function ; Function to print the count of required pairs using Merge Sort ; Driver code ; Function Call","code":"def merge ( arr , temp , l , m , r , K ) : NEW_LINE INDENT i = l NEW_LINE j = m + 1 NEW_LINE cnt = 0 NEW_LINE for l in range ( m + 1 ) : NEW_LINE INDENT found = False NEW_LINE while ( j <= r ) : NEW_LINE INDENT if ( arr [ i ] >= K * arr [ j ] ) : NEW_LINE INDENT found = True NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( found ) : NEW_LINE INDENT cnt += j - ( m + 1 ) NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT k = l NEW_LINE i = l NEW_LINE j = m + 1 NEW_LINE while ( i <= m and j <= r ) : NEW_LINE INDENT if ( arr [ i ] <= arr [ j ] ) : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while ( i <= m ) : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( j <= r ) : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE DEDENT return cnt NEW_LINE DEDENT def mergeSortUtil ( arr , temp , l , r , K ) : NEW_LINE INDENT cnt = 0 NEW_LINE if ( l < r ) : NEW_LINE INDENT m = ( l + r ) \/\/ 2 NEW_LINE cnt += mergeSortUtil ( arr , temp , l , m , K ) NEW_LINE cnt += mergeSortUtil ( arr , temp , m + 1 , r , K ) NEW_LINE cnt += merge ( arr , temp , l , m , r , K ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT def mergeSort ( arr , N , K ) : NEW_LINE INDENT temp = [ 0 ] * N NEW_LINE print ( mergeSortUtil ( arr , temp , 0 , N - 1 , K ) ) NEW_LINE DEDENT arr = [ 5 , 6 , 2 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE mergeSort ( arr , N , K ) NEW_LINE"} +{"text":"Minimize consecutive removals of elements of the same type to empty given array | Function to count minimum consecutive removals of elements of the same type ; Sort the array ; Stores the maximum element present in the array ; stores the sum of array ; Calculate sum of array ; Driver Code ; Function call","code":"def minRemovals ( A , N ) : NEW_LINE INDENT A . sort ( ) NEW_LINE mx = A [ N - 1 ] NEW_LINE sum = 1 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT if ( ( sum - mx ) >= mx ) : NEW_LINE INDENT print ( 0 , end = \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 2 * mx - sum , end = \" \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 3 , 3 , 2 ] NEW_LINE N = len ( A ) NEW_LINE minRemovals ( A , N ) NEW_LINE DEDENT"} +{"text":"Rearrange given array such that no array element is same as its index | Function to rearrange the array a [ ] such that none of the array elements is same as its index ; Sort the array ; Traverse the indices [ 0 , N - 2 ] of the given array ; Check if the current element is equal to its index ; If found to be true , swap current element with the next element ; Check if the last element is same as its index ; If found to be true , swap current element with the previous element ; Prthe modified array ; Driver Code ; Function Call","code":"def rearrangeArray ( a , n ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] == i + 1 ) : NEW_LINE INDENT a [ i ] , a [ i + 1 ] = a [ i + 1 ] , a [ i ] NEW_LINE DEDENT DEDENT if ( a [ n - 1 ] == n ) : NEW_LINE INDENT a [ n - 1 ] , a [ n - 2 ] = a [ n - 2 ] , a [ n - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE rearrangeArray ( arr , N ) NEW_LINE DEDENT"} +{"text":"Count minimum number of moves to front or end to sort an array | Function that counts the minimum moves required to covert arr [ ] to brr [ ] ; Base Case ; If arr [ i ] < arr [ j ] ; Include the current element ; Otherwise , excluding the current element ; Function that counts the minimum moves required to sort the array ; If both the arrays are equal ; No moves required ; Otherwise ; Print minimum operations required ; Driver Code","code":"def minOperations ( arr1 , arr2 , i , j ) : NEW_LINE INDENT if arr1 == arr2 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if i >= len ( arr1 ) or j >= len ( arr2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if arr1 [ i ] < arr2 [ j ] : NEW_LINE INDENT return 1 + minOperations ( arr1 , arr2 , i + 1 , j + 1 ) NEW_LINE DEDENT return max ( minOperations ( arr1 , arr2 , i , j + 1 ) , minOperations ( arr1 , arr2 , i + 1 , j ) ) NEW_LINE DEDENT def minOperationsUtil ( arr ) : NEW_LINE INDENT brr = sorted ( arr ) ; NEW_LINE if ( arr == brr ) : NEW_LINE INDENT print ( \"0\" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( minOperations ( arr , brr , 0 , 0 ) ) NEW_LINE DEDENT DEDENT arr = [ 4 , 7 , 2 , 3 , 9 ] NEW_LINE minOperationsUtil ( arr ) NEW_LINE"} +{"text":"Check if a string can be transformed to another by sorting substrings | Function to check if str1 can be transformed to t by sorting substrings ; Occur [ i ] stores the indices of ( ' a ' + i ) in string s ; idx [ i ] stores the next available index of ( ' a ' + i ) in occur [ i ] ; If this is not available anymore ; Conversion not possible ; If one of the smaller characters is available and occurs before ; Conversion not possible ; Print the answer ; Driver Code","code":"def canTransform ( s , t ) : NEW_LINE INDENT n = len ( s ) NEW_LINE occur = [ [ ] for i in range ( 26 ) ] NEW_LINE for x in range ( n ) : NEW_LINE INDENT ch = ord ( s [ x ] ) - ord ( ' a ' ) NEW_LINE occur [ ch ] . append ( x ) NEW_LINE DEDENT idx = [ 0 ] * ( 26 ) NEW_LINE poss = True NEW_LINE for x in range ( n ) : NEW_LINE INDENT ch = ord ( t [ x ] ) - ord ( ' a ' ) NEW_LINE if ( idx [ ch ] >= len ( occur [ ch ] ) ) : NEW_LINE INDENT poss = False NEW_LINE break NEW_LINE DEDENT for small in range ( ch ) : NEW_LINE INDENT if ( idx [ small ] < len ( occur [ small ] ) and occur [ small ] [ idx [ small ] ] < occur [ ch ] [ idx [ ch ] ] ) : NEW_LINE INDENT poss = False NEW_LINE break NEW_LINE DEDENT DEDENT idx [ ch ] += 1 NEW_LINE DEDENT if ( poss ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" hdecb \" NEW_LINE t = \" cdheb \" NEW_LINE canTransform ( s , t ) NEW_LINE DEDENT"} +{"text":"Check whether two strings can be made equal by reversing substring of equal length from both strings | function to count inversion count of the string ; for storing frequency ; we 'll add all the characters which are less than the ith character before i. ; adding the count to inversion count ; updating the character in the frequency array ; function to check whether any of the string have a repeated character ; function to check whether the string S1 and S2 can be made equal by reversing sub strings ofsame size in both strings ; frequency array to check whether both string have same character or not ; adding the frequency ; ; if the character is not in S1 ; decrementing the frequency ; If both string does not have same characters or not ; finding inversion count of both strings ; If inversion count is same , or have same parity or if any of the string have a repeated character then the answer is Yes else No ; Driver Code","code":"def inversionCount ( s ) : NEW_LINE INDENT freq = [ 0 for _ in range ( 26 ) ] NEW_LINE inv = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT temp = 0 NEW_LINE for j in range ( ord ( s [ i ] ) - ord ( ' a ' ) ) : NEW_LINE INDENT temp += freq [ j ] NEW_LINE DEDENT inv += ( i - temp ) NEW_LINE freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return inv NEW_LINE DEDENT def haveRepeated ( S1 , S2 ) : NEW_LINE INDENT freq = [ 0 for _ in range ( 26 ) ] NEW_LINE for i in range ( len ( S1 ) ) : NEW_LINE INDENT if freq [ ord ( S1 [ i ] ) - ord ( ' a ' ) ] > 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT freq [ ord ( S1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT freq [ i ] = 0 NEW_LINE DEDENT for i in range ( len ( S2 ) ) : NEW_LINE INDENT if freq [ ord ( S2 [ i ] ) - ord ( ' a ' ) ] > 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT freq [ ord ( S2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def checkToMakeEqual ( S1 , S2 ) : NEW_LINE INDENT freq = [ 0 for _ in range ( 26 ) ] NEW_LINE for i in range ( len ( S1 ) ) : NEW_LINE INDENT freq [ ord ( S1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT flag = 0 NEW_LINE for i in range ( len ( S2 ) ) : NEW_LINE INDENT if freq [ ord ( S2 [ i ] ) - ord ( ' a ' ) ] == 0 : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT freq [ ord ( S2 [ i ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT if flag == 1 : NEW_LINE INDENT print ( \" No \" ) NEW_LINE return NEW_LINE DEDENT invCount1 = inversionCount ( S1 ) NEW_LINE invCount2 = inversionCount ( S2 ) NEW_LINE if ( ( invCount1 == invCount2 ) or ( ( invCount1 % 2 ) == ( invCount2 % 2 ) ) or haveRepeated ( S1 , S2 ) == 1 ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT S1 = \" abbca \" NEW_LINE S2 = \" acabb \" NEW_LINE checkToMakeEqual ( S1 , S2 ) NEW_LINE"} +{"text":"Sort a Bitonic Array | Python3 program for the above approach ; Function to sort bitonic array in constant space ; Initialize thevalue of k ; In each iteration compare elements k distance apart and swap it they are not in order ; k is reduced to half after every iteration ; Print the array elements ; Given array ; Function call","code":"import math NEW_LINE def sortArr ( a , n ) : NEW_LINE INDENT k = int ( math . log ( n , 2 ) ) NEW_LINE k = int ( pow ( 2 , k ) ) NEW_LINE while ( k > 0 ) : NEW_LINE INDENT i = 0 NEW_LINE while i + k < n : NEW_LINE INDENT if a [ i ] > a [ i + k ] : NEW_LINE INDENT a [ i ] , a [ i + k ] = a [ i + k ] , a [ i ] NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT k = k \/\/ 2 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT a = [ 5 , 20 , 30 , 40 , 36 , 33 , 25 , 15 , 10 ] NEW_LINE n = len ( a ) NEW_LINE sortArr ( a , n ) NEW_LINE"} +{"text":"Split array into K subsets to maximize their sum of maximums and minimums | Function that prints the maximum sum possible ; Find elements in each group ; Sort all elements in non - descending order ; Add K largest elements ; For sum of minimum elements from each subset ; Printing the maximum sum ; Driver code","code":"def maximumSum ( arr , n , k ) : NEW_LINE INDENT elt = n \/\/ k ; NEW_LINE sum = 0 ; NEW_LINE arr . sort ( ) ; NEW_LINE count = 0 ; NEW_LINE i = n - 1 ; NEW_LINE while ( count < k ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE i -= 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( count < k ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE i += elt - 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT print ( sum ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Arr = [ 1 , 13 , 7 , 17 , 6 , 5 ] ; NEW_LINE K = 2 ; NEW_LINE size = len ( Arr ) ; NEW_LINE maximumSum ( Arr , size , K ) ; NEW_LINE DEDENT"} +{"text":"Minimize sum of smallest elements from K subsequences of length L | Function to find the minimum sum ; Sort the array ; Calculate sum of smallest K elements ; Return the sum ; Driver code","code":"def findMinSum ( arr , K , L , size ) : NEW_LINE INDENT if ( K * L > size ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT minsum = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT minsum += arr [ i ] NEW_LINE DEDENT return minsum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 15 , 5 , 1 , 35 , 16 , 67 , 10 ] NEW_LINE K = 3 NEW_LINE L = 2 NEW_LINE length = len ( arr ) NEW_LINE print ( findMinSum ( arr , K , L , length ) ) NEW_LINE DEDENT"} +{"text":"Kth smallest or largest element in unsorted Array | Set 4 | Function to find the Kth smallest element in Unsorted Array ; Initialize the max Element as 0 ; Iterate arr [ ] and find the maximum element in it ; Frequency array to store the frequencies ; Counter variable ; Counting the frequencies ; Iterate through the freq [ ] ; Check if num is present in the array ; Increment the counter with the frequency of num ; Checking if we have reached the Kth smallest element ; Return the Kth smallest element ; Driver Code ; Given array ; Function Call","code":"def findKthSmallest ( arr , n , k ) : NEW_LINE INDENT max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > max ) : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT counter = [ 0 ] * ( max + 1 ) NEW_LINE smallest = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT counter [ arr [ i ] ] += 1 NEW_LINE DEDENT for num in range ( 1 , max + 1 ) : NEW_LINE INDENT if ( counter [ num ] > 0 ) : NEW_LINE INDENT smallest += counter [ num ] NEW_LINE DEDENT if ( smallest >= k ) : NEW_LINE INDENT return num NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 7 , 1 , 4 , 4 , 20 , 15 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE print ( findKthSmallest ( arr , N , K ) ) NEW_LINE DEDENT"} +{"text":"Generate all numbers up to N in Lexicographical Order | Function to print all the numbers up to n in lexicographical order ; Driver Code","code":"def lexNumbers ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s . append ( str ( i ) ) NEW_LINE DEDENT s . sort ( ) NEW_LINE ans = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans . append ( int ( s [ i ] ) ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 15 NEW_LINE lexNumbers ( n ) NEW_LINE DEDENT"} +{"text":"Sort Matrix in alternating ascending and descending order rowwise | Python3 implementation to print row of matrix in ascending or descending order alternatively ; Iterate matrix rowwise ; Sort even rows in ascending order ; Compare adjacent elements ; Swap adjacent element ; Sort even rows in descending order ; Compare adjacent elements ; Swap adjacent element ; Printing the final output ; Driver code","code":"N = 4 NEW_LINE def func ( a ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT for k in range ( j + 1 , N ) : NEW_LINE INDENT if a [ i ] [ j ] > a [ i ] [ k ] : NEW_LINE INDENT temp = a [ i ] [ j ] NEW_LINE a [ i ] [ j ] = a [ i ] [ k ] NEW_LINE a [ i ] [ k ] = temp NEW_LINE DEDENT DEDENT DEDENT DEDENT else : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT for k in range ( j + 1 , N ) : NEW_LINE INDENT if a [ i ] [ j ] < a [ i ] [ k ] : NEW_LINE INDENT temp = a [ i ] [ j ] NEW_LINE a [ i ] [ j ] = a [ i ] [ k ] NEW_LINE a [ i ] [ k ] = temp NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 5 , 7 , 3 , 4 ] , [ 9 , 5 , 8 , 2 ] , [ 6 , 3 , 8 , 1 ] , [ 5 , 8 , 9 , 3 ] ] NEW_LINE func ( a ) NEW_LINE DEDENT"} +{"text":"Find weight of MST in a complete graph with edge | To store the edges of the given graph ; A utility function to perform DFS Traversal ; Check those vertices which are stored in the set ; Vertices are included if the weight of edge is 0 ; A utility function to find the weight of Minimum Spanning Tree ; To count the connected components ; Inserting the initial vertices in the set ; Traversing vertices stored in the set and Run DFS Traversal for each vertices ; Incrementing the zero weight connected components ; DFS Traversal for every vertex remove ; Driver 's Code ; Insert edges ; Function call find the weight of Minimum Spanning Tree","code":"g = [ dict ( ) for i in range ( 200005 ) ] NEW_LINE s = set ( ) NEW_LINE ns = set ( ) NEW_LINE def dfs ( x ) : NEW_LINE INDENT global s , g , ns NEW_LINE v = [ ] NEW_LINE v . clear ( ) ; NEW_LINE ns . clear ( ) ; NEW_LINE for it in s : NEW_LINE INDENT if ( x in g and not g [ x ] [ it ] ) : NEW_LINE INDENT v . append ( it ) ; NEW_LINE DEDENT else : NEW_LINE INDENT ns . add ( it ) ; NEW_LINE DEDENT DEDENT s = ns ; NEW_LINE for i in v : NEW_LINE INDENT dfs ( i ) ; NEW_LINE DEDENT DEDENT def weightOfMST ( N ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT s . add ( i ) ; NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE t = list ( s ) [ 0 ] NEW_LINE s . discard ( t ) ; NEW_LINE dfs ( t ) ; NEW_LINE DEDENT print ( cnt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE M = 11 ; NEW_LINE edges = [ [ 1 , 3 ] , [ 1 , 4 ] , [ 1 , 5 ] , [ 1 , 6 ] , [ 2 , 3 ] , [ 2 , 4 ] , [ 2 , 5 ] , [ 2 , 6 ] , [ 3 , 4 ] , [ 3 , 5 ] , [ 3 , 6 ] ] ; NEW_LINE for i in range ( M ) : NEW_LINE INDENT u = edges [ i ] [ 0 ] ; NEW_LINE v = edges [ i ] [ 1 ] ; NEW_LINE g [ u ] [ v ] = 1 ; NEW_LINE g [ v ] [ u ] = 1 ; NEW_LINE DEDENT weightOfMST ( N ) ; NEW_LINE DEDENT"} +{"text":"Count of distinct possible pairs such that the element from A is greater than the element from B | Function to return the count of pairs ; Driver code","code":"def countPairs ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( A [ i ] > B [ ans ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 30 , 28 , 45 , 22 ] NEW_LINE B = [ 35 , 25 , 22 , 48 ] NEW_LINE print ( countPairs ( A , B ) ) NEW_LINE DEDENT"} +{"text":"Maximum possible remainder when an element is divided by other element in the array | Function to return the maximum mod value for any pair from the array ; Find the second maximum element from the array ; Driver code","code":"def maxMod ( arr , n ) : NEW_LINE INDENT maxVal = max ( arr ) NEW_LINE secondMax = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] < maxVal and arr [ i ] > secondMax ) : NEW_LINE INDENT secondMax = arr [ i ] NEW_LINE DEDENT DEDENT return secondMax NEW_LINE DEDENT arr = [ 2 , 4 , 1 , 5 , 3 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxMod ( arr , n ) ) NEW_LINE"} +{"text":"Choose X elements from A [ ] and Y elements from B [ ] which satisfy the given condition | Function to that returns true if it possible to choose the elements ; If elements can 't be chosen ; Sort both the arrays ; If xth smallest element of A [ ] is smaller than the yth greatest element of B [ ] ; Driver code","code":"def isPossible ( A , B , n , m , x , y ) : NEW_LINE INDENT if ( x > n or y > m ) : NEW_LINE INDENT return False NEW_LINE DEDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE if ( A [ x - 1 ] < B [ m - y ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT A = [ 1 , 1 , 1 , 1 , 1 ] NEW_LINE B = [ 2 , 2 ] NEW_LINE n = len ( A ) NEW_LINE m = len ( B ) NEW_LINE x = 3 NEW_LINE y = 1 NEW_LINE if ( isPossible ( A , B , n , m , x , y ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Find minimum changes required in an array for it to contain k distinct elements | Python 3 program to minimum changes required in an array for k distinct elements . ; Function to minimum changes required in an array for k distinct elements . ; Store the frequency of each element ; Store the frequency of elements ; Sort frequencies in descending order ; To store the required answer ; Return the required answer ; Driver code","code":"MAX = 100005 NEW_LINE def Min_Replace ( arr , n , k ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE freq = [ 0 for i in range ( MAX ) ] NEW_LINE p = 0 NEW_LINE freq [ p ] = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT freq [ p ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT p += 1 NEW_LINE freq [ p ] += 1 NEW_LINE DEDENT DEDENT freq . sort ( reverse = True ) NEW_LINE ans = 0 NEW_LINE for i in range ( k , p + 1 , 1 ) : NEW_LINE INDENT ans += freq [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 7 , 8 , 2 , 3 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( Min_Replace ( arr , n , k ) ) NEW_LINE DEDENT"} +{"text":"Maximum number of elements without overlapping in a Line | Function to find maximum number of elements without overlapping in a line ; If n = 1 , then answer is one ; We can always make 1 st element to cover left segment and nth the right segment ; If left segment for ith element doesnt overlap with i - 1 th element then do left ; else try towards right if possible ; update x [ i ] to right endpoof segment covered by it ; Return the required answer ; Driver code ; Function call","code":"def Segment ( x , l , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = 2 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( x [ i ] - l [ i ] > x [ i - 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT elif ( x [ i ] + l [ i ] < x [ i + 1 ] ) : NEW_LINE INDENT x [ i ] = x [ i ] + l [ i ] NEW_LINE ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT x = [ 1 , 3 , 4 , 5 , 8 ] NEW_LINE l = [ 10 , 1 , 2 , 2 , 5 ] NEW_LINE n = len ( x ) NEW_LINE print ( Segment ( x , l , n ) ) NEW_LINE"} +{"text":"Delete odd and even numbers at alternate step such that sum of remaining elements is minimized | Function to find the minimized sum ; If more odd elements ; Sort the elements ; Left - over elements ; Find the sum of leftover elements ; Return the sum ; If more even elements ; Sort the elements ; Left - over elements ; Find the sum of leftover elements ; Return the sum ; If same elements ; Driver code","code":"def MinimizeleftOverSum ( a , n ) : NEW_LINE INDENT v1 , v2 = [ ] , [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] % 2 ) : NEW_LINE INDENT v1 . append ( a [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT v2 . append ( a [ i ] ) ; NEW_LINE DEDENT DEDENT if ( len ( v1 ) > len ( v2 ) ) : NEW_LINE INDENT v1 . sort ( ) ; NEW_LINE v2 . sort ( ) ; NEW_LINE x = len ( v1 ) - len ( v2 ) - 1 ; NEW_LINE sum = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < x ) : NEW_LINE INDENT sum += v1 [ i ] ; NEW_LINE i += 1 NEW_LINE DEDENT return sum ; NEW_LINE DEDENT elif ( len ( v2 ) > len ( v1 ) ) : NEW_LINE INDENT v1 . sort ( ) ; NEW_LINE v2 . sort ( ) ; NEW_LINE x = len ( v2 ) - len ( v1 ) - 1 ; NEW_LINE sum = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < x ) : NEW_LINE INDENT sum += v2 [ i ] ; NEW_LINE i += 1 NEW_LINE DEDENT return sum ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 2 , 2 , 2 , 2 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( MinimizeleftOverSum ( a , n ) ) ; NEW_LINE DEDENT"} +{"text":"Minimum operations to make frequency of all characters equal K | Function to find the minimum number of operations to convert the given string ; Check if N is divisible by K ; Array to store frequency of characters in given string ; Two arrays with number of operations required ; Checking for all possibility ; Driver Code","code":"def minOperation ( S , N , K ) : NEW_LINE INDENT if N % K : NEW_LINE INDENT print ( \" Not \u2581 Possible \" ) NEW_LINE return NEW_LINE DEDENT count = [ 0 ] * 26 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT count [ ord ( S [ i ] ) - 97 ] += 1 NEW_LINE DEDENT E = N \/\/ K NEW_LINE greaterE = [ ] NEW_LINE lessE = [ ] NEW_LINE for i in range ( 0 , 26 ) : NEW_LINE INDENT if count [ i ] < E : NEW_LINE INDENT lessE . append ( E - count [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT greaterE . append ( count [ i ] - E ) NEW_LINE DEDENT DEDENT greaterE . sort ( ) NEW_LINE lessE . sort ( ) NEW_LINE mi = float ( ' inf ' ) NEW_LINE for i in range ( 0 , K + 1 ) : NEW_LINE INDENT set1 , set2 = i , K - i NEW_LINE if ( len ( greaterE ) >= set1 and len ( lessE ) >= set2 ) : NEW_LINE INDENT step1 , step2 = 0 , 0 NEW_LINE for j in range ( 0 , set1 ) : NEW_LINE INDENT step1 += greaterE [ j ] NEW_LINE DEDENT for j in range ( 0 , set2 ) : NEW_LINE INDENT step2 += lessE [ j ] NEW_LINE DEDENT mi = min ( mi , max ( step1 , step2 ) ) NEW_LINE DEDENT DEDENT print ( mi ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S = \" accb \" NEW_LINE N = len ( S ) NEW_LINE K = 2 NEW_LINE minOperation ( S , N , K ) NEW_LINE DEDENT"} +{"text":"Minimum range increment operations to Sort an array | Function to find minimum range increments to sort an array ; If current element is found greater than last element Increment all terms in range i + 1 to n - 1 ; mn = arr [ i ] Minimum in range i to n - 1 ; Driver Code","code":"def minMovesToSort ( arr , n ) : NEW_LINE INDENT moves = 0 NEW_LINE mn = arr [ n - 1 ] NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > mn ) : NEW_LINE INDENT moves += arr [ i ] - mn NEW_LINE DEDENT DEDENT return moves NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 3 , 5 , 2 , 8 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minMovesToSort ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Sort prime numbers of an array in descending order | Python3 implementation of the approach ; 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 that sorts all the prime numbers from the array in descending ; This vector will contain prime numbers to sort ; If the element is prime ; update the array elements ; Driver code ; print the results .","code":"def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= n : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def sortPrimes ( arr , n ) : NEW_LINE INDENT SieveOfEratosthenes ( 100005 ) NEW_LINE v = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if prime [ arr [ i ] ] : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( reverse = True ) NEW_LINE j = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if prime [ arr [ i ] ] : NEW_LINE INDENT arr [ i ] = v [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 4 , 3 , 2 , 6 , 100 , 17 ] NEW_LINE n = len ( arr ) NEW_LINE prime = [ True ] * 100006 NEW_LINE arr = sortPrimes ( arr , n ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Pair formation such that maximum pair sum is minimized | Python 3 Program to divide the array into N pairs such that maximum pair is minimized ; After Sorting Maintain two variables i and j pointing to start and end of array Such that smallest element of array pairs with largest element ; Driver Code","code":"def findOptimalPairs ( arr , N ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i <= j ) : NEW_LINE INDENT print ( \" ( \" , arr [ i ] , \" , \" , arr [ j ] , \" ) \" , end = \" \u2581 \" ) NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 9 , 6 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE findOptimalPairs ( arr , N ) NEW_LINE DEDENT"} +{"text":"Sort an array according to count of set bits | a utility function that returns total set bits count in an integer ; Function to simultaneously sort both arrays using insertion sort ( http : quiz . geeksforgeeks . org \/ insertion - sort \/ ) ; use 2 keys because we need to sort both arrays simultaneously ; Move elements of arr [ 0. . i - 1 ] and aux [ 0. . i - 1 ] , such that elements of aux [ 0. . i - 1 ] are greater than key1 , to one position ahead of their current position ; Function to sort according to bit count using an auxiliary array ; Create an array and store count of set bits in it . ; Sort arr [ ] according to values in aux [ ] ; Utility function to print an array ; Driver Code","code":"def countBits ( a ) : NEW_LINE INDENT count = 0 NEW_LINE while ( a ) : NEW_LINE INDENT if ( a & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT a = a >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def insertionSort ( arr , aux , n ) : NEW_LINE INDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT key1 = aux [ i ] NEW_LINE key2 = arr [ i ] NEW_LINE j = i - 1 NEW_LINE while ( j >= 0 and aux [ j ] < key1 ) : NEW_LINE INDENT aux [ j + 1 ] = aux [ j ] NEW_LINE arr [ j + 1 ] = arr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT aux [ j + 1 ] = key1 NEW_LINE arr [ j + 1 ] = key2 NEW_LINE DEDENT DEDENT def sortBySetBitCount ( arr , n ) : NEW_LINE INDENT aux = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT aux [ i ] = countBits ( arr [ i ] ) NEW_LINE DEDENT insertionSort ( arr , aux , n ) NEW_LINE DEDENT def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n , 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE sortBySetBitCount ( arr , n ) NEW_LINE printArr ( arr , n ) NEW_LINE DEDENT"} +{"text":"Sort an array according to count of set bits | a utility function that returns total set bits count in an integer ; Function to sort according to bit count This function assumes that there are 32 bits in an integer . ; Traverse through all bit counts ( Note that we sort array in decreasing order ) ; Utility function to pran array ; Driver Code","code":"def countBits ( a ) : NEW_LINE INDENT count = 0 NEW_LINE while ( a ) : NEW_LINE INDENT if ( a & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT a = a >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def sortBySetBitCount ( arr , n ) : NEW_LINE INDENT count = [ [ ] for i in range ( 32 ) ] NEW_LINE setbitcount = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT setbitcount = countBits ( arr [ i ] ) NEW_LINE count [ setbitcount ] . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT v1 = count [ i ] NEW_LINE for i in range ( len ( v1 ) ) : NEW_LINE INDENT arr [ j ] = v1 [ i ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT def printArr ( arr , n ) : NEW_LINE INDENT print ( * arr ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE sortBySetBitCount ( arr , n ) NEW_LINE printArr ( arr , n ) NEW_LINE"} +{"text":"Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1 s is always greater than 0 s from left | Function to find lexicographically smallest string having number of 1 s greater than number of 0 s ; C1s And C0s stores the count of 1 s and 0 s at every position ; Traverse the string S ; If the position is not divisible by k1 and k2 ; If C0s >= C1s and pos [ ] is empty then the string can 't be formed ; If pos [ ] is not empty then flip the bit of last position present in pos [ ] ; Print the result ; Driver Code","code":"def generateString ( k1 , k2 , s ) : NEW_LINE INDENT s = list ( s ) NEW_LINE C1s = 0 NEW_LINE C0s = 0 NEW_LINE flag = 0 NEW_LINE pos = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT C0s += 1 NEW_LINE if ( ( i + 1 ) % k1 != 0 and ( i + 1 ) % k2 != 0 ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT C1s += 1 NEW_LINE DEDENT if ( C0s >= C1s ) : NEW_LINE INDENT if ( len ( pos ) == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT k = pos [ len ( pos ) - 1 ] NEW_LINE s [ k ] = '1' NEW_LINE C0s -= 1 NEW_LINE C1s += 1 NEW_LINE pos = pos [ : - 1 ] NEW_LINE DEDENT DEDENT DEDENT s = ' ' . join ( s ) NEW_LINE if ( flag == 0 ) : NEW_LINE INDENT print ( s ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K1 = 2 NEW_LINE K2 = 4 NEW_LINE S = \"11000100\" NEW_LINE generateString ( K1 , K2 , S ) NEW_LINE DEDENT"} +{"text":"Find a pair of numbers with set bit count as at most that of N and whose Bitwise XOR is N | python 3 program for the above approach ; Function to find the pair ( X , Y ) such that X xor Y = N and the count of set bits in X and Y is less than count of set bit in N ; Stores MSB ( Most Significant Bit ) ; Stores the value of X ; \/ Stores the value of Y ; Traversing over all bits of N ; If ith bit of N is 0 ; \/ Set ith bit of X to 1 ; Set ith bit of Y to 1 ; Print Answer ; Driver Code","code":"import math NEW_LINE def maximizeProduct ( N ) : NEW_LINE INDENT MSB = ( int ) ( math . log2 ( N ) ) NEW_LINE X = 1 << MSB NEW_LINE Y = N - ( 1 << MSB ) NEW_LINE for i in range ( MSB ) : NEW_LINE INDENT if ( not ( N & ( 1 << i ) ) ) : NEW_LINE INDENT X += 1 << i NEW_LINE Y += 1 << i NEW_LINE DEDENT DEDENT print ( X , Y ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 45 NEW_LINE maximizeProduct ( N ) NEW_LINE DEDENT"} +{"text":"Count of numbers in range [ L , R ] having sum of digits of its square equal to square of sum of digits | python 3 program for the above approach ; Function to check if the number is valid ; Sum of digits of num ; Squared number ; Sum of digits of ( num * num ) ; Function to convert a string to an integer ; Function to generate all possible strings of length len ; Desired string ; Take only valid numbers ; Recurse for all possible digits ; Function to calculate unique numbers in range [ L , R ] ; Initialize a variable to store the answer ; Calculate the maximum possible length ; Set to store distinct valid numbers ; Generate all possible strings of length i ; Iterate the set to get the count of valid numbers in the range [ L , R ] ; Driver Code","code":"from math import log10 NEW_LINE def check ( num ) : NEW_LINE INDENT sm = 0 NEW_LINE num2 = num * num NEW_LINE while ( num ) : NEW_LINE INDENT sm += num % 10 NEW_LINE num \/\/= 10 NEW_LINE DEDENT sm2 = 0 NEW_LINE while ( num2 ) : NEW_LINE INDENT sm2 += num2 % 10 NEW_LINE num2 \/\/= 10 NEW_LINE DEDENT return ( ( sm * sm ) == sm2 ) NEW_LINE DEDENT def convert ( s ) : NEW_LINE INDENT val = 0 NEW_LINE s = s [ : : - 1 ] NEW_LINE cur = 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT val += ( ord ( s [ i ] ) - ord ( '0' ) ) * cur NEW_LINE cur *= 10 NEW_LINE DEDENT return val NEW_LINE DEDENT def generate ( s , len1 , uniq ) : NEW_LINE INDENT if ( len ( s ) == len1 ) : NEW_LINE INDENT if ( check ( convert ( s ) ) ) : NEW_LINE INDENT uniq . add ( convert ( s ) ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( 4 ) : NEW_LINE INDENT generate ( s + chr ( i + ord ( '0' ) ) , len1 , uniq ) NEW_LINE DEDENT DEDENT def totalNumbers ( L , R ) : NEW_LINE INDENT ans = 0 NEW_LINE max_len = int ( log10 ( R ) ) + 1 NEW_LINE uniq = set ( ) NEW_LINE for i in range ( 1 , max_len + 1 , 1 ) : NEW_LINE INDENT generate ( \" \" , i , uniq ) NEW_LINE DEDENT for x in uniq : NEW_LINE INDENT if ( x >= L and x <= R ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 22 NEW_LINE R = 22 NEW_LINE print ( totalNumbers ( L , R ) ) NEW_LINE DEDENT"} +{"text":"Convert X into Y by repeatedly multiplying X with 2 or appending 1 at the end | Function to check if X can be converted to Y by multiplying X by 2 or appending 1 at the end ; Iterate until Y is at least X ; If Y is even ; If the last digit of Y is 1 ; Otherwise ; Check if X is equal to Y ; Driver Code","code":"def convertXintoY ( X , Y ) : NEW_LINE INDENT while ( Y > X ) : NEW_LINE INDENT if ( Y % 2 == 0 ) : NEW_LINE INDENT Y \/\/= 2 NEW_LINE DEDENT elif ( Y % 10 == 1 ) : NEW_LINE INDENT Y \/\/= 10 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( X == Y ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X , Y = 100 , 40021 NEW_LINE convertXintoY ( X , Y ) NEW_LINE DEDENT"} +{"text":"Lexicographically smallest string of maximum length made up of first K alphabets that does not contain any repeating substring | Function to find the lexicographically smallest string of the first K lower case alphabets having unique substrings ; Stores the resultant string ; Iterate through all the characters ; Inner Loop for making pairs and adding them into string ; Adding first character so that substring consisting of the last the first alphabet is present ; Print the resultant string ; Driver Code","code":"def generateString ( K ) : NEW_LINE INDENT s = \" \" NEW_LINE for i in range ( 97 , 97 + K , 1 ) : NEW_LINE INDENT s = s + chr ( i ) ; NEW_LINE for j in range ( i + 1 , 97 + K , 1 ) : NEW_LINE INDENT s += chr ( i ) NEW_LINE s += chr ( j ) NEW_LINE DEDENT DEDENT s += chr ( 97 ) NEW_LINE print ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 4 NEW_LINE generateString ( K ) NEW_LINE DEDENT"} +{"text":"Generate Quadratic Equation having given sum and product of roots | Function to find the quadratic equation from the given sum and products of roots ; Print the coefficients ; Driver Code","code":"def findEquation ( S , M ) : NEW_LINE INDENT print ( \"1 \u2581 \" , ( ( - 1 ) * S ) , \" \u2581 \" , M ) NEW_LINE DEDENT S = 5 NEW_LINE M = 6 NEW_LINE findEquation ( S , M ) NEW_LINE"} +{"text":"Make all array elements equal by replacing adjacent pairs by their sum | Function to count the minimum number of pairs of adjacent elements required to be replaced by their sum to make all arrat elements equal ; Stores the prefix sum of the array ; Calculate the prefix sum array ; Stores the maximum number of subarrays into which the array can be split ; Iterate over all possible sums ; Traverse the array ; If the sum is equal to the current prefix sum ; Increment count of groups by 1 ; Otherwise discard this subgroup sum ; Update the maximum this of subarrays ; Return the minimum number of operations ; Driver Code ; Function Call","code":"def minSteps ( a , n ) : NEW_LINE INDENT prefix_sum = a [ : ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix_sum [ i ] += prefix_sum [ i - 1 ] NEW_LINE DEDENT mx = - 1 NEW_LINE for subgroupsum in prefix_sum : NEW_LINE INDENT sum = 0 NEW_LINE i = 0 NEW_LINE grp_count = 0 NEW_LINE while i < n : NEW_LINE INDENT sum += a [ i ] NEW_LINE if sum == subgroupsum : NEW_LINE INDENT grp_count += 1 NEW_LINE sum = 0 NEW_LINE DEDENT elif sum > subgroupsum : NEW_LINE INDENT grp_count = - 1 NEW_LINE break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if grp_count > mx : NEW_LINE INDENT mx = grp_count NEW_LINE DEDENT DEDENT return n - mx NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 , 2 , 1 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( minSteps ( A , N ) ) NEW_LINE DEDENT"} +{"text":"Most frequent character in a string after replacing all occurrences of X in a Binary String | Function to find the most frequent character after replacing X with either '0' or '1' according as per the given conditions ; Store the count of 0 s and 1 s in the S ; Count the frequency of 0 and 1 ; If the character is 1 ; If the character is 0 ; Stores first occurence of 1 ; Traverse the to count the number of X between two consecutive 1 s ; If the current character is not X ; If the current character is 1 , add the number of Xs to count1 and set prev to i ; Otherwise ; Find next occurence of 1 in the string ; If it is found , set i to prev ; Otherwise , break out of the loop ; Store the first occurence of 0 ; Repeat the same procedure to count the number of X between two consecutive 0 s ; If the current character is not X ; If the current character is 0 ; Add the count of Xs to count0 ; Set prev to i ; Otherwise ; Find the next occurence of 0 in the string ; If it is found , set i to prev ; Otherwise , break out of the loop ; Count number of X present in the starting of the string as XXXX1 ... ; Store the count of X ; Increment count1 by count if the condition is satisfied ; Count the number of X present in the ending of the as ... XXXX0 ; Store the count of X ; Increment count0 by count if the condition is satisfied ; If count of 1 is equal to count of 0 , prX ; Otherwise , if count of 1 is greater than count of 0 ; Otherwise , pr0 ; Driver Code","code":"def maxOccuringCharacter ( s ) : NEW_LINE INDENT count0 = 0 NEW_LINE count1 = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE count1 += 1 NEW_LINE elif ( s [ i ] == '0' ) : NEW_LINE count0 += 1 NEW_LINE DEDENT prev = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE prev = i NEW_LINE break NEW_LINE DEDENT for i in range ( prev + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != ' X ' ) : NEW_LINE if ( s [ i ] == '1' ) : NEW_LINE INDENT count1 += i - prev - 1 NEW_LINE prev = i NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE for j in range ( i + 1 , len ( s ) ) : NEW_LINE if ( s [ j ] == '1' ) : NEW_LINE INDENT flag = False NEW_LINE prev = j NEW_LINE break NEW_LINE DEDENT if ( flag == False ) : NEW_LINE i = prev NEW_LINE else : NEW_LINE i = len ( s ) NEW_LINE DEDENT DEDENT prev = - 1 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE prev = i NEW_LINE break NEW_LINE DEDENT for i in range ( prev + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != ' X ' ) : NEW_LINE if ( s [ i ] == '0' ) : NEW_LINE INDENT count0 += i - prev - 1 NEW_LINE prev = i NEW_LINE DEDENT else : NEW_LINE INDENT flag = True NEW_LINE for j in range ( i + 1 , len ( s ) ) : NEW_LINE if ( s [ j ] == '0' ) : NEW_LINE INDENT prev = j NEW_LINE flag = False NEW_LINE break NEW_LINE DEDENT if ( flag == False ) : NEW_LINE i = prev NEW_LINE else : NEW_LINE i = len ( s ) NEW_LINE DEDENT DEDENT if ( s [ 0 ] == ' X ' ) : NEW_LINE INDENT count = 0 NEW_LINE i = 0 NEW_LINE while ( s [ i ] == ' X ' ) : NEW_LINE count += 1 NEW_LINE i += 1 NEW_LINE if ( s [ i ] == '1' ) : NEW_LINE count1 += count NEW_LINE DEDENT if ( s [ ( len ( s ) - 1 ) ] == ' X ' ) : NEW_LINE INDENT count = 0 NEW_LINE i = len ( s ) - 1 NEW_LINE while ( s [ i ] == ' X ' ) : NEW_LINE count += 1 NEW_LINE i -= 1 NEW_LINE if ( s [ i ] == '0' ) : NEW_LINE count0 += count NEW_LINE DEDENT if ( count0 == count1 ) : NEW_LINE INDENT print ( \" X \" ) NEW_LINE DEDENT elif ( count0 > count1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT DEDENT S = \" XX10XX10XXX1XX \" NEW_LINE maxOccuringCharacter ( S ) NEW_LINE"} +{"text":"Maximize count of sheets possible by repeatedly reducing its area to half | Function to calculate the maximum number of sheets possible by given operations ; Initial count of sheets ; Keep dividing the sheets into half ; Reduce area by half ; Increase count by twice ; Driver Code","code":"def maxSheets ( A , B ) : NEW_LINE INDENT area = A * B NEW_LINE count = 1 NEW_LINE while ( area % 2 == 0 ) : NEW_LINE INDENT area \/\/= 2 NEW_LINE count *= 2 NEW_LINE DEDENT return count NEW_LINE DEDENT A = 5 NEW_LINE B = 10 NEW_LINE print ( maxSheets ( A , B ) ) NEW_LINE"} +{"text":"Minimum number of steps required to reach origin from a given point | function to find the minimum moves required to reach origin from ( a , b ) ; Stores the minimum number of moves ; Check if the absolute difference is 1 or 0 ; Store the minimum of a , b ; Store the maximum of a , b ; Prthe answer ; Driver Code ; Given co - ordinates ; Function Call","code":"def findMinMoves ( a , b ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( a == b or abs ( a - b ) == 1 ) : NEW_LINE INDENT ans = a + b NEW_LINE DEDENT else : NEW_LINE INDENT k = min ( a , b ) NEW_LINE j = max ( a , b ) NEW_LINE ans = 2 * k + 2 * ( j - k ) - 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a , b = 3 , 5 NEW_LINE findMinMoves ( a , b ) NEW_LINE DEDENT"} +{"text":"Count even sum pairs possible by selecting two integers from two given ranges respectively | Function to count even sum pairs in the given range ; Stores the count of even numbers between 1 to X ; Stores the count of odd numbers between 1 to X ; Stores the count of even numbers between 1 to Y ; Stores the count of odd numbers between 1 to Y ; Stores the count of pairs having even sum ; Returns the count of pairs having even sum ; Driver code","code":"def cntEvenSumPairs ( X , Y ) : NEW_LINE INDENT cntXEvenNums = X \/ 2 NEW_LINE cntXOddNums = ( X + 1 ) \/ 2 NEW_LINE cntYEvenNums = Y \/ 2 NEW_LINE cntYOddNums = ( Y + 1 ) \/ 2 NEW_LINE cntPairs = ( ( cntXEvenNums * cntYEvenNums ) + ( cntXOddNums * cntYOddNums ) ) NEW_LINE return cntPairs NEW_LINE DEDENT X = 2 NEW_LINE Y = 3 NEW_LINE print ( cntEvenSumPairs ( X , Y ) ) NEW_LINE"} +{"text":"Minimize array elements required to be incremented or decremented to convert given array into a Fibonacci Series | Python3 program for the above approach ; Function to calculate minimum number of moves to make the sequence a Fibonacci series ; If number of elements is less than 3 ; Initialize the value of the result ; Try all permutations of the first two elements ; Value of first element after operation ; Value of second element after operation ; Calculate number of moves for rest of the elements of the array ; Element at idx index ; If it is not possible to change the element in atmost one move ; Otherwise ; Update the answer ; Return the answer ; Driver Code","code":"import sys NEW_LINE def minMoves ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE if ( N <= 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for i in range ( - 1 , 2 ) : NEW_LINE INDENT for j in range ( - 1 , 2 ) : NEW_LINE INDENT num1 = arr [ 0 ] + i NEW_LINE num2 = arr [ 1 ] + j NEW_LINE flag = 1 NEW_LINE moves = abs ( i ) + abs ( j ) NEW_LINE for idx in range ( 2 , N ) : NEW_LINE INDENT num = num1 + num2 NEW_LINE if ( abs ( arr [ idx ] - num ) > 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT else : NEW_LINE INDENT moves += abs ( arr [ idx ] - num ) NEW_LINE DEDENT num1 = num2 NEW_LINE num2 = num NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT ans = min ( ans , moves ) NEW_LINE DEDENT DEDENT DEDENT if ( ans == sys . maxsize ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 4 , 8 , 9 , 17 , 27 ] NEW_LINE print ( minMoves ( arr ) ) NEW_LINE DEDENT"} +{"text":"Queries to calculate sum of array elements present at every Yth index starting from the index X | Function to Find the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... for all queries ; Iterate over each query ; Stores the sum of arr [ x ] + arr [ x + y ] + arr [ x + 2 * y ] + ... ; Traverse the array and calculate the sum of the expression ; Update sum ; Update x ; Driver Code","code":"def querySum ( arr , N , Q , M ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT x = Q [ i ] [ 0 ] NEW_LINE y = Q [ i ] [ 1 ] NEW_LINE sum = 0 NEW_LINE while ( x < N ) : NEW_LINE INDENT sum += arr [ x ] NEW_LINE x += y NEW_LINE DEDENT print ( sum , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 7 , 5 , 4 ] ; NEW_LINE Q = [ [ 2 , 1 ] , [ 3 , 2 ] ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( Q ) NEW_LINE querySum ( arr , N , Q , M ) NEW_LINE DEDENT"} +{"text":"Calculate Bitwise OR of two integers from their given Bitwise AND and Bitwise XOR values | Function to calculate Bitwise OR from given bitwise XOR and bitwise AND values ; Driver Code","code":"def findBitwiseORGivenXORAND ( X , Y ) : NEW_LINE INDENT return X + Y NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT X = 5 NEW_LINE Y = 2 NEW_LINE print ( findBitwiseORGivenXORAND ( X , Y ) ) NEW_LINE DEDENT"} +{"text":"Check if a given value can be reached from another value in a Circular Queue by K | Function to return GCD of two numbers a and b ; Base Case ; Recursively Find the GCD ; Function to check of B can be reaced from A with a jump of K elements in the circular queue ; Find GCD of N and K ; If A - B is divisible by gcd then prYes ; Otherwise ; Driver Code ; Function Call","code":"def GCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def canReach ( N , A , B , K ) : NEW_LINE INDENT gcd = GCD ( N , K ) NEW_LINE if ( abs ( A - B ) % gcd == 0 ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE A = 2 NEW_LINE B = 1 NEW_LINE K = 2 NEW_LINE canReach ( N , A , B , K ) NEW_LINE DEDENT"} +{"text":"Count of subarrays having sum equal to its length | Set 2 | Python3 program for the above approach ; Function that counts the subarrays with sum of its elements as its length ; Store count of elements upto current element with length i ; Stores the final count of subarray ; Stores the prefix sum ; If size of subarray is 1 ; Iterate the array ; Find the sum ; Update frequency in map ; Print the total count ; Driver code ; Given array ; Size of the array ; Function Call","code":"from collections import defaultdict NEW_LINE def countOfSubarray ( arr , N ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE answer = 0 NEW_LINE sum = 0 NEW_LINE mp [ 1 ] += 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE answer += mp [ sum - i ] NEW_LINE mp [ sum - i ] += 1 NEW_LINE DEDENT print ( answer ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 2 , 1 , 2 , - 2 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE countOfSubarray ( arr , N ) NEW_LINE DEDENT"} +{"text":"Split first N natural numbers into two sets with minimum absolute difference of their sums | Function to split the first N natural numbers into two sets having minimum absolute difference of their sums ; Stores the sum of elements of set1 ; Stores the sum of elements of set2 ; Traverse first N natural numbers ; Check if sum of elements of set1 is less than or equal to sum of elements of set2 ; Driver Code","code":"def minAbsDiff ( N ) : NEW_LINE INDENT sumSet1 = 0 NEW_LINE sumSet2 = 0 NEW_LINE for i in reversed ( range ( N + 1 ) ) : NEW_LINE INDENT if sumSet1 <= sumSet2 : NEW_LINE sumSet1 = sumSet1 + i NEW_LINE else : NEW_LINE sumSet2 = sumSet2 + i NEW_LINE DEDENT return abs ( sumSet1 - sumSet2 ) NEW_LINE DEDENT N = 6 NEW_LINE print ( minAbsDiff ( N ) ) NEW_LINE"} +{"text":"Check if a number is prime in Flipped Upside Down , Mirror Flipped and Mirror Flipped Upside Down | Function to check if N contains digits 0 , 1 , 2 , 5 , 8 only ; Extract digits of N ; Return false if any of these digits are present ; Function to check if N is prime or not ; Check for all factors ; Function to check if n is prime in all the desired forms ; Driver Code","code":"def checkDigits ( n ) : NEW_LINE INDENT while True : NEW_LINE INDENT r = n % 10 NEW_LINE if ( r == 3 or r == 4 or r == 6 or r == 7 or r == 9 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n \/\/= 10 NEW_LINE if n == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : 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 isAllPrime ( n ) : NEW_LINE INDENT return isPrime ( n ) and checkDigits ( n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 101 NEW_LINE if ( isAllPrime ( N ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Minimum Cost required to generate a balanced Bracket Sequence | Function to calculate the minimum cost required to generate a balanced bracket sequence ; Stores the count of unbalanced open brackets ; Stores the count of unbalanced closed brackets ; Stores the count of open brackets ; Stores the count of closed brackets ; If open brace is encountered ; Otherwise ; If no unbalanced open brackets are present ; Increase count of unbalanced closed brackets ; Otherwise ; Reduce count of unbalanced open brackets ; Increase count of closed brackets ; Calculate lower bound of minimum cost ; Reduce excess open or closed brackets to prevent counting them twice ; Update answer by adding minimum of removing both unbalanced open and closed brackets or inserting closed unbalanced brackets to end of String ; Prthe result ; Driver Code","code":"def minCost ( str , a , b ) : NEW_LINE INDENT openUnbalanced = 0 ; NEW_LINE closedUnbalanced = 0 ; NEW_LINE openCount = 0 ; NEW_LINE closedCount = 0 ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ' ( ' ) : NEW_LINE INDENT openUnbalanced += 1 ; NEW_LINE openCount += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( openUnbalanced == 0 ) : NEW_LINE INDENT closedUnbalanced += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT openUnbalanced -= 1 ; NEW_LINE DEDENT closedCount += 1 ; NEW_LINE DEDENT DEDENT result = a * ( abs ( openCount - closedCount ) ) ; NEW_LINE if ( closedCount > openCount ) : NEW_LINE INDENT closedUnbalanced -= ( closedCount - openCount ) ; NEW_LINE DEDENT if ( openCount > closedCount ) : NEW_LINE INDENT openUnbalanced -= ( openCount - closedCount ) ; NEW_LINE DEDENT result += min ( a * ( openUnbalanced + closedUnbalanced ) , b * closedUnbalanced ) ; NEW_LINE print ( result ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : str = \" ) ) ( ) ( ( ) ( ) ( \" ; NEW_LINE INDENT A = 1 ; B = 3 ; NEW_LINE minCost ( str , A , B ) ; NEW_LINE DEDENT"} +{"text":"Count of permutations such that sum of K numbers from given range is even | Function to return the number of all permutations such that sum of K numbers in range is even ; Find total count of even and odd number in given range ; Iterate loop k times and update even_sum & odd_sum using previous values ; Update the prev_even and odd_sum ; Even sum ; Odd sum ; Return even_sum ; Given ranges ; Length of permutation ; Function call","code":"def countEvenSum ( low , high , k ) : NEW_LINE INDENT even_count = high \/ 2 - ( low - 1 ) \/ 2 NEW_LINE odd_count = ( high + 1 ) \/ 2 - low \/ 2 NEW_LINE even_sum = 1 NEW_LINE odd_sum = 0 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT prev_even = even_sum NEW_LINE prev_odd = odd_sum NEW_LINE even_sum = ( ( prev_even * even_count ) + ( prev_odd * odd_count ) ) NEW_LINE odd_sum = ( ( prev_even * odd_count ) + ( prev_odd * even_count ) ) NEW_LINE DEDENT print ( int ( even_sum ) ) NEW_LINE DEDENT low = 4 ; NEW_LINE high = 5 ; NEW_LINE K = 3 ; NEW_LINE countEvenSum ( low , high , K ) ; NEW_LINE"} +{"text":"Count of N digit Numbers whose sum of every K consecutive digits is equal | Set 2 | Function to count the number of N - digit numbers such that sum of every K consecutive digits are equal ; Print the answer ; Driver Code","code":"def count ( n , k ) : NEW_LINE INDENT count = ( pow ( 10 , k ) - pow ( 10 , k - 1 ) ) ; NEW_LINE print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 ; NEW_LINE k = 1 ; NEW_LINE count ( n , k ) ; NEW_LINE DEDENT"} +{"text":"Sum of largest divisor of numbers upto N not divisible by given prime number P | Function to find the sum of largest divisors of numbers in range 1 to N not divisible by prime number P ; Total sum upto N ; If no multiple of P exist up to N ; If only P itself is in the range from 1 to N ; Sum of those that are divisible by P ; Recursively function call to find the sum for N \/ P ; Driver Code ; Given N and P ; Function call","code":"def func ( N , P ) : NEW_LINE INDENT sumUptoN = ( N * ( N + 1 ) \/ 2 ) ; NEW_LINE sumOfMultiplesOfP = 0 ; NEW_LINE if ( N < P ) : NEW_LINE INDENT return sumUptoN ; NEW_LINE DEDENT elif ( ( N \/ P ) == 1 ) : NEW_LINE INDENT return sumUptoN - P + 1 ; NEW_LINE DEDENT sumOfMultiplesOfP = ( ( ( N \/ P ) * ( 2 * P + ( N \/ P - 1 ) * P ) ) \/ 2 ) ; NEW_LINE return ( sumUptoN + func ( N \/ P , P ) - sumOfMultiplesOfP ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 ; NEW_LINE P = 5 ; NEW_LINE print ( func ( N , P ) ) ; NEW_LINE DEDENT"} +{"text":"Count of right shifts for each array element to be in its sorted position | Function to find the right shifts required for each element to reach its sorted array position in A [ ] ; Stores required number of shifts for each element ; If the element is at sorted position ; Otherwise ; Calculate right shift ; Print the respective shifts ; Driver Code","code":"def findShifts ( A , N ) : NEW_LINE INDENT shift = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i == A [ i ] - 1 ) : NEW_LINE INDENT shift [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT shift [ i ] = ( A [ i ] - 1 - i + N ) % N NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( shift [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 3 , 2 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE findShifts ( arr , N ) NEW_LINE DEDENT"} +{"text":"Construct a matrix with sum equal to the sum of diagonal elements | Function to construct matrix with diagonal sum equal to matrix sum ; If diagonal position ; Positive element ; Negative element ; Driver code","code":"def constructmatrix ( N ) : NEW_LINE INDENT check = bool ( True ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT print ( 1 , end = \" \u2581 \" ) NEW_LINE DEDENT elif ( check ) : NEW_LINE INDENT print ( 2 , end = \" \u2581 \" ) NEW_LINE check = bool ( False ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 2 , end = \" \u2581 \" ) NEW_LINE check = bool ( True ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE constructmatrix ( 5 ) NEW_LINE"} +{"text":"Minimum count of numbers required with unit digit X that sums up to N | Function to calculate and return the minimum number of times a number with unit digit X needs to be added to get a sum N ; Calculate the number of additions required to get unit digit of N ; If unit digit of N cannot be obtained ; Function to return the minimum number required to represent N ; Stores unit digit of N ; Stores minimum addition of X required to obtain unit digit of N ; If unit digit of N cannot be obtained ; Otherwise ; If N is greater than or equal to ( X * times ) ; Minimum count of numbers that needed to represent N ; Representation not possible ; Driver Code","code":"def check ( unit_digit , X ) : NEW_LINE INDENT for times in range ( 1 , 11 ) : NEW_LINE INDENT digit = ( X * times ) % 10 NEW_LINE if ( digit == unit_digit ) : NEW_LINE INDENT return times NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def getNum ( N , X ) : NEW_LINE INDENT unit_digit = N % 10 NEW_LINE times = check ( unit_digit , X ) NEW_LINE if ( times == - 1 ) : NEW_LINE INDENT return times NEW_LINE DEDENT else : NEW_LINE INDENT if ( N >= ( times * X ) ) : NEW_LINE INDENT return times NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT N = 58 NEW_LINE X = 7 NEW_LINE print ( getNum ( N , X ) ) NEW_LINE"} +{"text":"Minimum number of points required to cover all blocks of a 2 | Function to find the minimum number of Points required to cover a grid ; If number of block is even ; Return the minimum points ; Driver code ; Given size of grid ; Function call","code":"def minPoints ( n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( ( n % 2 != 0 ) and ( m % 2 != 0 ) ) : NEW_LINE INDENT ans = ( ( n * m ) \/\/ 2 ) + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( n * m ) \/\/ 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 7 NEW_LINE print ( minPoints ( N , M ) ) NEW_LINE DEDENT"} +{"text":"Largest lexicographical string with at most K consecutive elements | Function to find the largest lexicographical string with given constraints . ; Vector containing frequency of each character . ; Assigning frequency to ; Empty string of string class type ; Loop to iterate over maximum priority first . ; If frequency is greater than or equal to k . ; Temporary variable to operate in - place of k . ; concatenating with the resultant string ans . ; Handling k case by adjusting with just smaller priority element . ; Condition to verify if index j does have frequency greater than 0 ; ; if no such element is found than string can not be processed further . ; If frequency is greater than 0 and less than k . ; Here we don 't need to fix K consecutive element criteria. ; Otherwise check for next possible element . ; Driver code","code":"def getLargestString ( s , k ) : NEW_LINE INDENT frequency_array = [ 0 ] * 26 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT frequency_array [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = \" \" NEW_LINE i = 25 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( frequency_array [ i ] > k ) : NEW_LINE INDENT temp = k NEW_LINE st = chr ( i + ord ( ' a ' ) ) NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT ans += st NEW_LINE temp -= 1 NEW_LINE DEDENT frequency_array [ i ] -= k NEW_LINE j = i - 1 NEW_LINE while ( frequency_array [ j ] <= 0 and j >= 0 ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( frequency_array [ j ] > 0 and j >= 0 ) : NEW_LINE INDENT str1 = chr ( j + ord ( ' a ' ) ) NEW_LINE ans += str1 NEW_LINE frequency_array [ j ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( frequency_array [ i ] > 0 ) : NEW_LINE INDENT temp = frequency_array [ i ] NEW_LINE frequency_array [ i ] -= temp NEW_LINE st = chr ( i + ord ( ' a ' ) ) NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT ans += st NEW_LINE temp -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S = \" xxxxzza \" NEW_LINE k = 3 NEW_LINE print ( getLargestString ( S , k ) ) NEW_LINE DEDENT"} +{"text":"Minimum operations to make all elements equal using the second array | Function to find the minimum operations required to make all elements of the array equal ; Minimum element of A ; Traverse through all final values ; Variable indicating whether all elements can be converted to x or not ; Total operations ; Traverse through all array elements ; All elements can 't be converted to x ; Driver Code","code":"def minOperations ( a , b , n ) : NEW_LINE INDENT minA = min ( a ) ; NEW_LINE for x in range ( minA , - 1 , - 1 ) : NEW_LINE INDENT check = True ; NEW_LINE operations = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( x % b [ i ] == a [ i ] % b [ i ] ) : NEW_LINE INDENT operations += ( a [ i ] - x ) \/ b [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT check = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( check ) : NEW_LINE INDENT return operations ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE A = [ 5 , 7 , 10 , 5 , 15 ] ; NEW_LINE B = [ 2 , 2 , 1 , 3 , 5 ] ; NEW_LINE print ( int ( minOperations ( A , B , N ) ) ) ; NEW_LINE DEDENT"} +{"text":"Find the maximum sum ( a + b ) for a given input integer N satisfying the given condition | Function to return the maximum sum of a + b satisfying the given condition ; Initialize max_sum ; Consider all the possible pairs ; Check if the product is divisible by the sum ; Storing the maximum sum in the max_sum variable ; Return the max_sum value ; Driver code","code":"def getLargestSum ( N ) : NEW_LINE INDENT max_sum = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N + 1 , 1 ) : NEW_LINE INDENT if ( i * j % ( i + j ) == 0 ) : NEW_LINE INDENT max_sum = max ( max_sum , i + j ) NEW_LINE DEDENT DEDENT DEDENT return max_sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE max_sum = getLargestSum ( N ) NEW_LINE print ( max_sum ) NEW_LINE DEDENT"} +{"text":"Maximize the sum of array after multiplying a prefix and suffix by | Kadane 's algorithm to find the maximum subarray sum ; Loop to find the maximum subarray array sum in the given array ; Function to find the maximum sum of the array by multiplying the prefix and suffix by - 1 ; Total intital sum ; Loop to find the maximum sum of the array ; Maximum value ; Driver Code","code":"def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - 10 ** 9 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT def maxSum ( a , n ) : NEW_LINE INDENT S = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT S += a [ i ] NEW_LINE DEDENT X = maxSubArraySum ( a , n ) NEW_LINE return 2 * X - S NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ - 1 , - 2 , - 3 ] NEW_LINE n = len ( a ) NEW_LINE max_sum = maxSum ( a , n ) NEW_LINE print ( max_sum ) NEW_LINE DEDENT"} +{"text":"Count of interesting primes upto N | Python3 program to find the number of interesting primes up to N ; Function to check if a number is prime or not ; If n is divisible by any number between 2 and sqrt ( n ) , it is not prime ; Function to check if a number is perfect square or not ; Find floating povalue of square root of x . ; If square root is an integer ; Function to find the number of interesting primes less than equal to N . ; Check whether the number is prime or not ; Iterate for values of b ; Check condition for a ; Return the required answer ; Driver code","code":"import math NEW_LINE def isPrime ( n ) : NEW_LINE INDENT flag = 1 NEW_LINE i = 2 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( True if flag == 1 else False ) NEW_LINE DEDENT def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - math . floor ( sr ) ) == 0 ) NEW_LINE DEDENT def countInterestingPrimes ( n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( isPrime ( i ) ) : NEW_LINE INDENT j = 1 NEW_LINE while ( j * j * j * j <= i ) : NEW_LINE INDENT if ( isPerfectSquare ( i - j * j * j * j ) ) : NEW_LINE INDENT answer += 1 NEW_LINE break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( countInterestingPrimes ( N ) ) NEW_LINE DEDENT"} +{"text":"Maximize the number by flipping at most K bits | Python implementation of the approach ; Function to convert decimal number n to its binary representation stored as an array arr [ ] ; Function to convert the number represented as a binary array arr [ ] into its decimal equivalent ; Function to return the maximized number by flipping atmost k bits ; Number of bits in n ; Find the binary representation of n ; To count the number of 0 s flipped ; Return the decimal equivalent of the maximized number ; Driver code","code":"import math NEW_LINE def decBinary ( arr , n ) : NEW_LINE INDENT k = int ( math . log2 ( n ) ) NEW_LINE while ( n > 0 ) : NEW_LINE INDENT arr [ k ] = n % 2 NEW_LINE k = k - 1 NEW_LINE n = n \/\/ 2 NEW_LINE DEDENT DEDENT def binaryDec ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT ans = ans + ( arr [ i ] << ( n - i - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def maxNum ( n , k ) : NEW_LINE INDENT l = int ( math . log2 ( n ) ) + 1 NEW_LINE a = [ 0 for i in range ( 0 , l ) ] NEW_LINE decBinary ( a , n ) NEW_LINE cn = 0 NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT if ( a [ i ] == 0 and cn < k ) : NEW_LINE INDENT a [ i ] = 1 NEW_LINE cn = cn + 1 NEW_LINE DEDENT DEDENT return binaryDec ( a , l ) NEW_LINE DEDENT n = 4 NEW_LINE k = 1 NEW_LINE print ( maxNum ( n , k ) ) NEW_LINE"} +{"text":"Find the subsequence with given sum in a superincreasing sequence | Function to find the required subsequence ; Current element cannot be a part of the required subsequence ; Include current element in the required subsequence So update the sum ; Print the elements of the required subsequence ; If the current element was included in the subsequence ; Driver code","code":"def findSubSeq ( arr , n , sum ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( sum < arr [ i ] ) : NEW_LINE INDENT arr [ i ] = - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT sum -= arr [ i ] ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != - 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 17 , 25 , 46 , 94 , 201 , 400 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sum = 272 ; NEW_LINE findSubSeq ( arr , n , sum ) ; NEW_LINE DEDENT"} +{"text":"Find the most valued alphabet in the String | Python implementation of the approach ; Function to return the maximum valued alphabet ; Set the first and the last occurrence of all the characters to - 1 ; Update the occurrences of the characters ; Only set the first occurrence if it hasn 't already been set ; To store the result ; For every alphabet ; If current alphabet doesn 't appear in the given string ; If the current character has the highest value so far ; Driver code","code":"MAX = 26 NEW_LINE def maxAlpha ( str , len ) : NEW_LINE INDENT first = [ - 1 for x in range ( MAX ) ] NEW_LINE last = [ - 1 for x in range ( MAX ) ] NEW_LINE for i in range ( 0 , len ) : NEW_LINE INDENT index = ord ( str [ i ] ) - 97 NEW_LINE if ( first [ index ] == - 1 ) : NEW_LINE INDENT first [ index ] = i NEW_LINE DEDENT last [ index ] = i NEW_LINE DEDENT ans = - 1 NEW_LINE maxVal = - 1 NEW_LINE for i in range ( 0 , MAX ) : NEW_LINE INDENT if ( first [ i ] == - 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( ( last [ i ] - first [ i ] ) > maxVal ) : NEW_LINE INDENT maxVal = last [ i ] - first [ i ] ; NEW_LINE ans = i NEW_LINE DEDENT DEDENT return chr ( ans + 97 ) NEW_LINE DEDENT str = \" abbba \" NEW_LINE len = len ( str ) NEW_LINE print ( maxAlpha ( str , len ) ) NEW_LINE"} +{"text":"Queries for number of distinct elements from a given index till last index in an array | Python implementation of the approach ; Function to perform queries to find number of distinct elements from a given index till last index in an array ; Check if current element already visited or not ; If not visited store current counter and increment it and mark check as 1 ; Otherwise if visited simply store current counter ; Perform queries ; Driver code","code":"MAX = 100001 ; NEW_LINE def find_distinct ( a , n , q , queries ) : NEW_LINE INDENT check = [ 0 ] * MAX ; NEW_LINE idx = [ 0 ] * MAX ; NEW_LINE cnt = 1 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( check [ a [ i ] ] == 0 ) : NEW_LINE INDENT idx [ i ] = cnt ; NEW_LINE check [ a [ i ] ] = 1 ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT idx [ i ] = cnt - 1 ; NEW_LINE DEDENT DEDENT for i in range ( 0 , q ) : NEW_LINE INDENT m = queries [ i ] ; NEW_LINE print ( idx [ m ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 3 , 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( a ) ; NEW_LINE queries = [ 0 , 3 , 5 , 7 ] ; NEW_LINE q = len ( queries ) ; NEW_LINE find_distinct ( a , n , q , queries ) ; NEW_LINE"} +{"text":"Convert given integer X to the form 2 ^ N | Python3 implementation of the approach ; Function to return the count of operations required ; To store the powers of 2 ; Temporary variable to store x ; To store the index of smaller number larger than x ; To store the count of operations ; Stores the index of number in the form of 2 ^ n - 1 ; If x is already in the form 2 ^ n - 1 then no operation is required ; If number is less than x increase the index ; Calculate all the values ( x xor 2 ^ n - 1 ) for all possible n ; Only take value which is closer to the number ; If number is in the form of 2 ^ n - 1 then break ; Return the count of operations required to obtain the number ; Driver code","code":"MAX = 24 ; NEW_LINE def countOp ( x ) : NEW_LINE INDENT arr = [ 0 ] * MAX ; NEW_LINE arr [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , MAX ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] * 2 ; NEW_LINE DEDENT temp = x ; NEW_LINE flag = True ; NEW_LINE ans = 0 ; NEW_LINE operations = 0 ; NEW_LINE flag2 = False ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( arr [ i ] - 1 == x ) : NEW_LINE INDENT flag2 = True ; NEW_LINE DEDENT if ( arr [ i ] > x ) : NEW_LINE INDENT ans = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( flag ) : NEW_LINE INDENT if ( arr [ ans ] < x ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT operations += 1 ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT take = x ^ ( arr [ i ] - 1 ) ; NEW_LINE if ( take <= arr [ ans ] - 1 ) : NEW_LINE INDENT if ( take > temp ) : NEW_LINE INDENT temp = take ; NEW_LINE DEDENT DEDENT DEDENT if ( temp == arr [ ans ] - 1 ) : NEW_LINE INDENT flag = False ; NEW_LINE break ; NEW_LINE DEDENT temp += 1 ; NEW_LINE operations += 1 ; NEW_LINE x = temp ; NEW_LINE if ( x == arr [ ans ] - 1 ) : NEW_LINE INDENT flag = False ; NEW_LINE DEDENT DEDENT return operations ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x = 39 ; NEW_LINE print ( countOp ( x ) ) ; NEW_LINE DEDENT"} +{"text":"Minimum number of given operations required to reduce the array to 0 element | Function to return the minimum operations required ; Count the frequency of each element ; Maximum element from the array ; Find all the multiples of i ; Delete the multiples ; Increment the operations ; Driver code","code":"def minOperations ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE freq = [ 0 ] * 1000001 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT maxi = max ( arr ) NEW_LINE for i in range ( 1 , maxi + 1 ) : NEW_LINE INDENT if freq [ i ] != 0 : NEW_LINE INDENT for j in range ( i * 2 , maxi + 1 , i ) : NEW_LINE INDENT freq [ j ] = 0 NEW_LINE DEDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 4 , 2 , 4 , 4 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minOperations ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Minimum LCM and GCD possible among all possible sub | Python3 implementation of the approach ; Function to return minimum GCD among all subarrays ; Minimum GCD among all sub - arrays will be the GCD of all the elements of the array ; Function to return minimum LCM among all subarrays ; Minimum LCM among all sub - arrays will be the minimum element from the array ; Driver code","code":"from math import gcd NEW_LINE def minGCD ( arr , n ) : NEW_LINE INDENT minGCD = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT minGCD = gcd ( minGCD , arr [ i ] ) ; NEW_LINE DEDENT return minGCD ; NEW_LINE DEDENT def minLCM ( arr , n ) : NEW_LINE INDENT minLCM = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT minLCM = min ( minLCM , arr [ i ] ) ; NEW_LINE DEDENT return minLCM ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 66 , 14 , 521 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( \" LCM \u2581 = \u2581 \" , minLCM ( arr , n ) , \" , \u2581 GCD \u2581 = \" , minGCD ( arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Form lexicographically smallest string with minimum replacements having equal number of 0 s , 1 s and 2 s | Python3 implementation of the approach ; Function that returns the modified lexicographically smallest string after performing minimum number of given operations ; Stores the initial frequencies of characters 0 s , 1 s and 2 s ; Stores number of processed characters upto that point of each type ; Required number of characters of each type ; If the current type has already reqd number of characters , no need to perform any operation ; Process all 3 cases ; Check for 1 first ; Else 2 ; Here we need to check processed [ 1 ] only for 2 since 0 is less than 1 and we can replace it anytime ; Here we can replace 2 with 0 and 1 anytime ; keep count of processed characters of each type ; Driver Code","code":"import math NEW_LINE def formStringMinOperations ( ss ) : NEW_LINE INDENT count = [ 0 ] * 3 ; NEW_LINE s = list ( ss ) ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT count [ ord ( s [ i ] ) - ord ( '0' ) ] += 1 ; NEW_LINE DEDENT processed = [ 0 ] * 3 ; NEW_LINE reqd = math . floor ( len ( s ) \/ 3 ) ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( count [ ord ( s [ i ] ) - ord ( '0' ) ] == reqd ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( s [ i ] == '0' and count [ 0 ] > reqd and processed [ 0 ] >= reqd ) : NEW_LINE INDENT if ( count [ 1 ] < reqd ) : NEW_LINE INDENT s [ i ] = '1' ; NEW_LINE count [ 1 ] += 1 ; NEW_LINE count [ 0 ] -= 1 ; NEW_LINE DEDENT elif ( count [ 2 ] < reqd ) : NEW_LINE INDENT s [ i ] = '2' ; NEW_LINE count [ 2 ] += 1 ; NEW_LINE count [ 0 ] -= 1 ; NEW_LINE DEDENT DEDENT if ( s [ i ] == '1' and count [ 1 ] > reqd ) : NEW_LINE INDENT if ( count [ 0 ] < reqd ) : NEW_LINE INDENT s [ i ] = '0' ; NEW_LINE count [ 0 ] += 1 ; NEW_LINE count [ 1 ] -= 1 ; NEW_LINE DEDENT elif ( count [ 2 ] < reqd and processed [ 1 ] >= reqd ) : NEW_LINE INDENT s [ i ] = '2' ; NEW_LINE count [ 2 ] += 1 ; NEW_LINE count [ 1 ] -= 1 ; NEW_LINE DEDENT DEDENT if ( s [ i ] == '2' and count [ 2 ] > reqd ) : NEW_LINE INDENT if ( count [ 0 ] < reqd ) : NEW_LINE INDENT s [ i ] = '0' ; NEW_LINE count [ 0 ] += 1 ; NEW_LINE count [ 2 ] -= 1 ; NEW_LINE DEDENT elif ( count [ 1 ] < reqd ) : NEW_LINE INDENT s [ i ] = '1' ; NEW_LINE count [ 1 ] += 1 ; NEW_LINE count [ 2 ] -= 1 ; NEW_LINE DEDENT DEDENT processed [ ord ( s [ i ] ) - ord ( '0' ) ] += 1 ; NEW_LINE DEDENT return ' ' . join ( s ) ; NEW_LINE DEDENT s = \"011200\" ; NEW_LINE print ( formStringMinOperations ( s ) ) ; NEW_LINE"} +{"text":"Minimum number of adjacent swaps for arranging similar elements together | Function to find minimum swaps ; visited array to check if value is seen already ; If the arr [ i ] is seen first time ; stores the number of swaps required to find the correct position of current element 's partner ; Increment count only if the current element has not been visited yet ( if is visited , means it has already been placed at its correct position ) ; If current element 's partner is found ; Driver Code","code":"def findMinimumAdjacentSwaps ( arr , N ) : NEW_LINE INDENT visited = [ False ] * ( N + 1 ) NEW_LINE minimumSwaps = 0 NEW_LINE for i in range ( 2 * N ) : NEW_LINE INDENT if ( visited [ arr [ i ] ] == False ) : NEW_LINE INDENT visited [ arr [ i ] ] = True NEW_LINE count = 0 NEW_LINE for j in range ( i + 1 , 2 * N ) : NEW_LINE INDENT if ( visited [ arr [ j ] ] == False ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT elif ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT minimumSwaps += count NEW_LINE DEDENT DEDENT DEDENT DEDENT return minimumSwaps NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE N \/\/= 2 NEW_LINE print ( findMinimumAdjacentSwaps ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Largest palindromic number by permuting digits | Python3 program to print the largest palindromic number by permuting digits of a number ; Function to check if a number can be permuted to form a palindrome number ; counts the occurrence of number which is odd ; if occurrence is odd ; if number exceeds 1 ; Function to print the largest palindromic number by permuting digits of a number ; string length ; map that marks the occurrence of a number ; check the possibility of a palindromic number ; string array that stores the largest permuted palindromic number ; pointer of front ; greedily start from 9 to 0 and place the greater number in front and odd in the middle ; if the occurrence of number is odd ; place one odd occurring number in the middle ; decrease the count ; place the rest of numbers greedily ; if all numbers occur even times , then place greedily ; place greedily at front ; 2 numbers are placed , so decrease the count ; increase placing position ; print the largest string thus formed ; Driver Code","code":"from collections import defaultdict NEW_LINE def possibility ( m , length , s ) : NEW_LINE INDENT countodd = 0 NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if m [ int ( s [ i ] ) ] & 1 : NEW_LINE INDENT countodd += 1 NEW_LINE DEDENT if countodd > 1 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def largestPalindrome ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , l ) : NEW_LINE INDENT m [ int ( s [ i ] ) ] += 1 NEW_LINE DEDENT if possibility ( m , l , s ) == False : NEW_LINE INDENT print ( \" Palindrome \u2581 cannot \u2581 be \u2581 formed \" ) NEW_LINE return NEW_LINE DEDENT largest = [ None ] * l NEW_LINE front = 0 NEW_LINE for i in range ( 9 , - 1 , - 1 ) : NEW_LINE INDENT if m [ i ] & 1 : NEW_LINE INDENT largest [ l \/\/ 2 ] = chr ( i + 48 ) NEW_LINE m [ i ] -= 1 NEW_LINE while m [ i ] > 0 : NEW_LINE INDENT largest [ front ] = chr ( i + 48 ) NEW_LINE largest [ l - front - 1 ] = chr ( i + 48 ) NEW_LINE m [ i ] -= 2 NEW_LINE front += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while m [ i ] > 0 : NEW_LINE INDENT largest [ front ] = chr ( i + 48 ) NEW_LINE largest [ l - front - 1 ] = chr ( i + 48 ) NEW_LINE m [ i ] -= 2 NEW_LINE front += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , l ) : NEW_LINE INDENT print ( largest [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"313551\" NEW_LINE largestPalindrome ( s ) NEW_LINE DEDENT"} +{"text":"Minimum Swaps for Bracket Balancing | Function to calculate swaps required ; Keep track of '[ ; To count number of encountered ' [ ' ; To track position of next ' [ ' in pos ; To store result ; Increment count and move p to next position ; We have encountered an unbalanced part of string ; Increment sum by number of swaps required i . e . position of next ' [ ' - current position ; Reset count to 1 ; Driver code","code":"def swapCount ( s ) : NEW_LINE ' NEW_LINE INDENT pos = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' [ ' ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT DEDENT count = 0 NEW_LINE p = 0 NEW_LINE sum = 0 NEW_LINE s = list ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' [ ' ) : NEW_LINE INDENT count += 1 NEW_LINE p += 1 NEW_LINE DEDENT elif ( s [ i ] == ' ] ' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if ( count < 0 ) : NEW_LINE INDENT sum += pos [ p ] - i NEW_LINE s [ i ] , s [ pos [ p ] ] = ( s [ pos [ p ] ] , s [ i ] ) NEW_LINE p += 1 NEW_LINE count = 1 NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT s = \" [ ] ] [ ] [ \" NEW_LINE print ( swapCount ( s ) ) NEW_LINE s = \" [ [ ] [ ] ] \" NEW_LINE print ( swapCount ( s ) ) NEW_LINE"} +{"text":"Minimum Cost to cut a board into squares | Method returns minimum cost to break board into m * n squares ; sort the horizontal cost in reverse order ; sort the vertical cost in reverse order ; initialize current width as 1 ; loop until one or both cost array are processed ; increase current horizontal part count by 1 ; increase current vertical part count by 1 ; loop for horizontal array , if remains ; loop for vertical array , if remains ; Driver program","code":"def minimumCostOfBreaking ( X , Y , m , n ) : NEW_LINE INDENT res = 0 NEW_LINE X . sort ( reverse = True ) NEW_LINE Y . sort ( reverse = True ) NEW_LINE hzntl = 1 ; vert = 1 NEW_LINE i = 0 ; j = 0 NEW_LINE while ( i < m and j < n ) : NEW_LINE INDENT if ( X [ i ] > Y [ j ] ) : NEW_LINE INDENT res += X [ i ] * vert NEW_LINE hzntl += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res += Y [ j ] * hzntl NEW_LINE vert += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT total = 0 NEW_LINE while ( i < m ) : NEW_LINE INDENT total += X [ i ] NEW_LINE i += 1 NEW_LINE DEDENT res += total * vert NEW_LINE total = 0 NEW_LINE while ( j < n ) : NEW_LINE INDENT total += Y [ j ] NEW_LINE j += 1 NEW_LINE DEDENT res += total * hzntl NEW_LINE return res NEW_LINE DEDENT m = 6 ; n = 4 NEW_LINE X = [ 2 , 1 , 3 , 1 , 4 ] NEW_LINE Y = [ 4 , 1 , 2 ] NEW_LINE print ( minimumCostOfBreaking ( X , Y , m - 1 , n - 1 ) ) NEW_LINE"} +{"text":"Minimize the count of characters to be added or removed to make String repetition of same substring | Function to find the minimum of the three numbers ; Function to find the minimum number operations required to convert string str1 to str2 using the operations ; Stores the results of subproblems ; Fill dp [ ] [ ] in bottom up manner ; If str1 is empty , then insert all characters of string str2 ; Minimum operations is j ; If str2 is empty , then remove all characters of string str2 ; Minimum operations is i ; If the last characters are same , then ignore last character ; If the last character is different , then find the minimum ; Perform one of the insert , remove and the replace ; Return the minimum number of steps required ; Function to find the minimum number of steps to modify the string such that first half and second half becomes the same ; Stores the minimum number of operations required ; Traverse the given string S ; Find the minimum operations ; Update the ans ; Print the result ; Driver Code","code":"def getMin ( x , y , z ) : NEW_LINE INDENT return min ( min ( x , y ) , z ) NEW_LINE DEDENT def editDistance ( str1 , str2 , m , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE for i in range ( 0 , m + 1 ) : NEW_LINE INDENT for j in range ( 0 , n + 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = j NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = i NEW_LINE DEDENT elif ( str1 [ i - 1 ] == str2 [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 + getMin ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] , dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT def minimumSteps ( S , N ) : NEW_LINE INDENT ans = 10 ** 10 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT S1 = S [ : i ] NEW_LINE S2 = S [ i : ] NEW_LINE count = editDistance ( S1 , S2 , len ( S1 ) , len ( S2 ) ) NEW_LINE ans = min ( ans , count ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = \" aabb \" NEW_LINE N = len ( S ) NEW_LINE minimumSteps ( S , N ) NEW_LINE"} +{"text":"Minimize operations to reduce N to 2 by repeatedly reducing by 3 or dividing by 5 | Function to find the minimum number of operations to reduce N to 2 by dividing N by 5 or decrementing by 3 ; Initialize the dp array ; Initialize the array dp [ ] ; For N = 2 number of operations needed is zero ; Iterating over the range [ 1 , N ] ; If it 's not possible to create current N ; Multiply with 5 ; Adding the value 3 ; Checking if not possible to make the number as 2 ; Return the minimum number of operations ; Driver Code","code":"def minimumOperations ( N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT dp [ i ] = 1000000000 NEW_LINE DEDENT dp [ 2 ] = 0 NEW_LINE for i in range ( 2 , N + 1 , 1 ) : NEW_LINE INDENT if ( dp [ i ] == 1000000000 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i * 5 <= N ) : NEW_LINE INDENT dp [ i * 5 ] = min ( dp [ i * 5 ] , dp [ i ] + 1 ) NEW_LINE DEDENT if ( i + 3 <= N ) : NEW_LINE INDENT dp [ i + 3 ] = min ( dp [ i + 3 ] , dp [ i ] + 1 ) NEW_LINE DEDENT DEDENT if ( dp [ N ] == 1000000000 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return dp [ N ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 25 NEW_LINE print ( minimumOperations ( N ) ) NEW_LINE DEDENT"} +{"text":"Maximum profit after buying and selling the stocks with transaction fees | Set 2 | Function to find the maximum profit with transaction fee ; Traversing the stocks for each day ; Update buy and sell ; Return the maximum profit ; Driver code ; Given Input ; Function Call","code":"def MaxProfit ( arr , n , transactionFee ) : NEW_LINE INDENT buy = - arr [ 0 ] NEW_LINE sell = 0 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT temp = buy NEW_LINE buy = max ( buy , sell - arr [ i ] ) NEW_LINE sell = max ( sell , temp + arr [ i ] - transactionFee ) NEW_LINE DEDENT return max ( sell , buy ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 1 , 7 , 2 , 8 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE transactionFee = 2 NEW_LINE print ( MaxProfit ( arr , n , transactionFee ) ) NEW_LINE DEDENT"} +{"text":"Maximum path sum from top left to bottom right of a matrix passing through one of the given cells | Stores the maximum path sum from the cell ( 1 , 1 ) to ( N , M ) ; Stores the maximum path sum from the cell ( j , j ) to ( N , M ) ; Function to find the maximum path sum from the cell ( 1 , 1 ) to ( N , M ) ; Traverse the first row ; Traverse the first column ; Traverse the matrix ; Update the value of start [ i ] [ j ] ; Function to find the maximum path sum from the cell ( j , j ) to ( N , M ) ; Traverse the last row ; Traverse the last column ; Traverse the matrix ; Update the value of ending [ i ] [ j ] ; Function to find the maximum path sum from the top - left to the bottom right cell such that path contains one of the cells in the array coordinates [ ] [ ] ; Initialize the start and the end matrices ; Calculate the start matrix ; Calculate the end matrix ; Stores the maximum path sum ; Traverse the coordinates ; Update the value of ans ; Print the resultant maximum sum path value ; Driver Code","code":"start = [ [ 0 for i in range ( 3 ) ] for j in range ( 3 ) ] NEW_LINE ending = [ [ 0 for i in range ( 3 ) ] for j in range ( 3 ) ] NEW_LINE def calculateStart ( n , m ) : NEW_LINE INDENT for i in range ( 1 , m , 1 ) : NEW_LINE INDENT start [ 0 ] [ i ] += start [ 0 ] [ i - 1 ] NEW_LINE DEDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT start [ i ] [ 0 ] += start [ i - 1 ] [ 0 ] NEW_LINE DEDENT for i in range ( 1 , n , 1 ) : NEW_LINE INDENT for j in range ( 1 , m , 1 ) : NEW_LINE INDENT start [ i ] [ j ] += max ( start [ i - 1 ] [ j ] , start [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def calculateEnd ( n , m ) : NEW_LINE INDENT i = n - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT ending [ i ] [ m - 1 ] += ending [ i + 1 ] [ m - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT i = m - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT ending [ n - 1 ] [ i ] += ending [ n - 1 ] [ i + 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT i = n - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT j = m - 2 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT ending [ i ] [ j ] += max ( ending [ i + 1 ] [ j ] , ending [ i ] [ j + 1 ] ) NEW_LINE j -= 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT DEDENT def maximumPathSum ( mat , n , m , q , coordinates ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT start [ i ] [ j ] = mat [ i ] [ j ] NEW_LINE ending [ i ] [ j ] = mat [ i ] [ j ] NEW_LINE DEDENT DEDENT calculateStart ( n , m ) NEW_LINE calculateEnd ( n , m ) NEW_LINE ans = 0 NEW_LINE for i in range ( q ) : NEW_LINE INDENT X = coordinates [ i ] [ 0 ] - 1 NEW_LINE Y = coordinates [ i ] [ 1 ] - 1 NEW_LINE ans = max ( ans , start [ X ] [ Y ] + ending [ X ] [ Y ] - mat [ X ] [ Y ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE N = 3 NEW_LINE M = 3 NEW_LINE Q = 2 NEW_LINE coordinates = [ [ 1 , 2 ] , [ 2 , 2 ] ] NEW_LINE maximumPathSum ( mat , N , M , Q , coordinates ) NEW_LINE DEDENT"} +{"text":"Length of longest subset consisting of A 0 s and B 1 s from an array of strings | Set 2 | Function to find the length of the longest subset of an array of strings with at most A 0 s and B 1 s ; Initialize a 2D array with its entries as 0 ; Traverse the given array ; Store the count of 0 s and 1 s in the current string ; Iterate in the range [ A , zeros ] ; Iterate in the range [ B , ones ] ; Update the value of dp [ i ] [ j ] ; Print the result ; Driver Code","code":"def MaxSubsetlength ( arr , A , B ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( B + 1 ) ] for i in range ( A + 1 ) ] NEW_LINE for str in arr : NEW_LINE INDENT zeros = str . count ( '0' ) NEW_LINE ones = str . count ( '1' ) NEW_LINE for i in range ( A , zeros - 1 , - 1 ) : NEW_LINE INDENT for j in range ( B , ones - 1 , - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - zeros ] [ j - ones ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT return dp [ A ] [ B ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ \"1\" , \"0\" , \"0001\" , \"10\" , \"111001\" ] NEW_LINE A , B = 5 , 3 NEW_LINE print ( MaxSubsetlength ( arr , A , B ) ) NEW_LINE DEDENT"} +{"text":"Count ways to select N pairs of candies of distinct colors ( Dynamic Programming + Bitmasking ) | Function to count ways to select N distinct pairs of candies with different colours ; If n pairs are selected ; Stores count of ways to select the i - th pair ; Iterate over the range [ 0 , n ] ; If pair ( i , j ) is not included ; Driver Code","code":"def numOfWays ( a , n , i = 0 , blue = [ ] ) : NEW_LINE INDENT if i == n : NEW_LINE INDENT return 1 NEW_LINE DEDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if mat [ i ] [ j ] == 1 and j not in blue : NEW_LINE INDENT count += numOfWays ( mat , n , i + 1 , blue + [ j ] ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 NEW_LINE mat = [ [ 0 , 1 , 1 ] , [ 1 , 0 , 1 ] , [ 1 , 1 , 1 ] ] NEW_LINE print ( numOfWays ( mat , n ) ) NEW_LINE DEDENT"} +{"text":"Minimize cost to reach end of an array by two forward jumps or one backward jump in each move | Function to find the minimum cost to reach the end of an array ; Base Case : When N < 3 ; Store the results in table ; Initialize base cases ; Iterate over the range [ 2 , N - 2 ] to construct the dp array ; Handle case for the last index , i . e . N - 1 ; Print the answer ; Driver Code","code":"def minCost ( arr , n ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT print ( arr [ 0 ] ) NEW_LINE return NEW_LINE DEDENT dp = [ 0 ] * n NEW_LINE dp [ 0 ] = arr [ 0 ] NEW_LINE dp [ 1 ] = dp [ 0 ] + arr [ 1 ] + arr [ 2 ] NEW_LINE for i in range ( 2 , n - 1 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 2 ] + arr [ i ] , dp [ i - 1 ] + arr [ i ] + arr [ i + 1 ] ) NEW_LINE DEDENT dp [ n - 1 ] = min ( dp [ n - 2 ] , dp [ n - 3 ] + arr [ n - 1 ] ) NEW_LINE print ( dp [ n - 1 ] ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 9 , 4 , 6 , 8 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE minCost ( arr , N ) NEW_LINE DEDENT"} +{"text":"Calculate the value of 2 raised to the power of twice the binary representation of N | Python3 program to implement the above approach ; Function to find the value of power ( X , Y ) in O ( log Y ) ; Stores power ( X , Y ) ; Update X ; Base Case ; Calculate power ( X , Y ) ; If Y is an odd number ; Update res ; Update Y ; Update X ; Function to calculate ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; Stores binary representation of n ; Stores power of 10 ; Calculate the binary representation of n ; If n is an odd number ; Update X ; Update pow_10 ; Update n ; Double the value of X ; Stores the value of ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; Driver Code","code":"M = 1000000007 NEW_LINE def power ( X , Y ) : NEW_LINE INDENT res = 1 NEW_LINE X = X % M NEW_LINE if ( X == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( Y > 0 ) : NEW_LINE INDENT if ( Y & 1 ) : NEW_LINE INDENT res = ( res * X ) % M NEW_LINE DEDENT Y = Y >> 1 NEW_LINE X = ( X * X ) % M NEW_LINE DEDENT return res NEW_LINE DEDENT def findValue ( n ) : NEW_LINE INDENT X = 0 NEW_LINE pow_10 = 1 NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT X += pow_10 NEW_LINE DEDENT pow_10 *= 10 NEW_LINE n \/\/= 2 NEW_LINE DEDENT X = ( X * 2 ) % M NEW_LINE res = power ( 2 , X ) NEW_LINE return res NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 2 NEW_LINE print ( findValue ( n ) ) NEW_LINE DEDENT"} +{"text":"Calculate the value of 2 raised to the power of twice the binary representation of N | Python3 program to implement the above approach ; Function to find the value of power ( X , Y ) in O ( log Y ) ; Stores power ( X , Y ) ; Update X ; Base Case ; Calculate power ( X , Y ) ; If Y is an odd number ; Update res ; Update Y ; Update X ; Function to calculate ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; dp [ N ] * dp [ N ] : Stores value of ( 2 ^ ( 2 * x ) ) % ( 10 ^ 9 + 7 ) ; Base Case ; Iterate over the range [ 3 , N ] ; Stores rightmost bit of i ; Stores the value of ( i - y ) ; If x is power of 2 ; Update dp [ i ] ; Update dp [ i ] ; Driver Code","code":"M = 1000000007 ; NEW_LINE def power ( X , Y ) : NEW_LINE INDENT res = 1 ; NEW_LINE X = X % M ; NEW_LINE if ( X == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( Y > 0 ) : NEW_LINE INDENT if ( Y % 2 == 1 ) : NEW_LINE INDENT res = ( res * X ) % M ; NEW_LINE DEDENT Y = Y >> 1 ; NEW_LINE X = ( X * X ) % M ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def findValue ( N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) ; NEW_LINE dp [ 1 ] = 2 ; NEW_LINE dp [ 2 ] = 1024 ; NEW_LINE for i in range ( 3 , N + 1 ) : NEW_LINE INDENT y = ( i & ( - i ) ) ; NEW_LINE x = i - y ; NEW_LINE if ( x == 0 ) : NEW_LINE INDENT dp [ i ] = power ( dp [ i \/\/ 2 ] , 10 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = ( dp [ x ] * dp [ y ] ) % M ; NEW_LINE DEDENT DEDENT return ( dp [ N ] * dp [ N ] ) % M ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 150 ; NEW_LINE print ( findValue ( n ) ) ; NEW_LINE DEDENT"} +{"text":"Count ways to obtain given sum by repeated throws of a dice | Function to find the number of ways to get the sum N with throw of dice ; Base case ; Stores the count of total number of ways to get sum N ; Recur for all 6 states ; Return answer ; Driver Code ; Function call","code":"def findWays ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 1 , 7 ) : NEW_LINE INDENT if ( N - i >= 0 ) : NEW_LINE INDENT cnt = cnt + findWays ( N - i ) NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( findWays ( N ) ) NEW_LINE DEDENT"} +{"text":"Check if an array can be split into 3 subsequences of equal sum or not | Utility function to check array can be partition to 3 subsequences of equal sum or not ; Base case ; When element at index j is added to sm1 ; When element at index j is added to sm2 ; When element at index j is added to sm3 ; Return maximum value among all above 3 recursive call ; Function to check array can be partition to 3 subsequences of equal sum or not ; Initialise 3 sums to 0 ; Function call ; Given array arr [ ] ; Function call","code":"def checkEqualSumUtil ( arr , N , sm1 , sm2 , sm3 , j ) : NEW_LINE INDENT if j == N : NEW_LINE INDENT if sm1 == sm2 and sm2 == sm3 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT l = checkEqualSumUtil ( arr , N , sm1 + arr [ j ] , sm2 , sm3 , j + 1 ) NEW_LINE m = checkEqualSumUtil ( arr , N , sm1 , sm2 + arr [ j ] , sm3 , j + 1 ) NEW_LINE r = checkEqualSumUtil ( arr , N , sm1 , sm2 , sm3 + arr [ j ] , j + 1 ) NEW_LINE return max ( l , m , r ) NEW_LINE DEDENT DEDENT def checkEqualSum ( arr , N ) : NEW_LINE INDENT sum1 = sum2 = sum3 = 0 NEW_LINE if checkEqualSumUtil ( arr , N , sum1 , sum2 , sum3 , 0 ) == 1 : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT arr = [ 17 , 34 , 59 , 23 , 17 , 67 , 57 , 2 , 18 , 59 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE checkEqualSum ( arr , N ) NEW_LINE"} +{"text":"Check if an array can be split into 3 subsequences of equal sum or not | Python3 program for the above approach ; Function to check array can be partition into sum of 3 equal ; Base Case ; If value at particular index is not - 1 then return value at that index which ensure no more further calls ; When element at index j is added to sm1 ; When element at index j is added to sm2 ; When element at index j is added to sm3 ; Update the current state and return that value ; Function to check array can be partition to 3 subsequences of equal sum or not ; Initialise 3 sums to 0 ; Function Call ; Given array arr [ ] ; Function call","code":"dp = { } NEW_LINE def checkEqualSumUtil ( arr , N , sm1 , sm2 , sm3 , j ) : NEW_LINE INDENT s = str ( sm1 ) + \" _ \" + str ( sm2 ) + str ( j ) NEW_LINE if j == N : NEW_LINE INDENT if sm1 == sm2 and sm2 == sm3 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if s in dp : NEW_LINE INDENT return dp [ s ] NEW_LINE DEDENT l = checkEqualSumUtil ( arr , N , sm1 + arr [ j ] , sm2 , sm3 , j + 1 ) NEW_LINE m = checkEqualSumUtil ( arr , N , sm1 , sm2 + arr [ j ] , sm3 , j + 1 ) NEW_LINE r = checkEqualSumUtil ( arr , N , sm1 , sm2 , sm3 + arr [ j ] , j + 1 ) NEW_LINE dp [ s ] = max ( l , m , r ) NEW_LINE return dp [ s ] NEW_LINE DEDENT def checkEqualSum ( arr , N ) : NEW_LINE INDENT sum1 = sum2 = sum3 = 0 NEW_LINE if checkEqualSumUtil ( arr , N , sum1 , sum2 , sum3 , 0 ) == 1 : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT arr = [ 17 , 34 , 59 , 23 , 17 , 67 , 57 , 2 , 18 , 59 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE checkEqualSum ( arr , N ) NEW_LINE"} +{"text":"Smallest index in given range of indices which is not equal to X | Precompute the index of next different element in the array for every array element ; Default value ; Compute nextpos [ i ] using nextpos [ i + 1 ] ; Function to return the smallest index ; nextpos [ i ] will store the next position p where arr [ p ] != arr [ i ] ; If X is not present at l ; Otherwise ; Find the index which stores a value different from X ; If that index is within the range ; Driver code","code":"def precompute ( nextpos , arr , N ) : NEW_LINE INDENT nextpos [ N - 1 ] = N NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] == arr [ i + 1 ] : NEW_LINE INDENT nextpos [ i ] = nextpos [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT nextpos [ i ] = i + 1 NEW_LINE DEDENT DEDENT DEDENT def findIndex ( query , arr , N , Q ) : NEW_LINE INDENT nextpos = [ 0 ] * N NEW_LINE precompute ( nextpos , arr , N ) NEW_LINE for i in range ( Q ) : NEW_LINE INDENT l = query [ i ] [ 0 ] NEW_LINE r = query [ i ] [ 1 ] NEW_LINE x = query [ i ] [ 2 ] NEW_LINE ans = - 1 NEW_LINE if arr [ l ] != x : NEW_LINE INDENT ans = l NEW_LINE DEDENT else : NEW_LINE INDENT d = nextpos [ l ] NEW_LINE if d <= r : NEW_LINE INDENT ans = d NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT DEDENT N = 6 NEW_LINE Q = 3 NEW_LINE arr = [ 1 , 2 , 1 , 1 , 3 , 5 ] NEW_LINE query = [ [ 0 , 3 , 1 ] , [ 1 , 5 , 2 ] , [ 2 , 3 , 1 ] ] NEW_LINE findIndex ( query , arr , N , Q ) NEW_LINE"} +{"text":"Count number of ways to convert string S to T by performing K cyclic shifts | Python3 program for the above approach ; Function to count number of ways to convert string S to string T by performing K cyclic shifts ; Calculate length of string ; a is no . of good cyclic shifts b is no . of bad cyclic shifts ; Iterate in string ; Precompute the number of good and bad cyclic shifts ; dp2 [ i ] to store the no of ways to get to a bad shift in i moves ; Calculate good and bad shifts ; Return the required number of ways ; Given Strings ; Given K shifts required ; Function call","code":"mod = 1000000007 NEW_LINE def countWays ( s , t , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE a = 0 NEW_LINE b = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT p = s [ i : n - i + 1 ] + s [ : i + 1 ] NEW_LINE if ( p == t ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT else : NEW_LINE INDENT b += 1 NEW_LINE DEDENT DEDENT dp1 = [ 0 ] * ( k + 1 ) NEW_LINE dp2 = [ 0 ] * ( k + 1 ) NEW_LINE if ( s == t ) : NEW_LINE INDENT dp1 [ 0 ] = 1 NEW_LINE dp2 [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp1 [ 0 ] = 0 NEW_LINE dp2 [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , k + 1 ) : NEW_LINE INDENT dp1 [ i ] = ( ( dp1 [ i - 1 ] * ( a - 1 ) ) % mod + ( dp2 [ i - 1 ] * a ) % mod ) % mod NEW_LINE dp2 [ i ] = ( ( dp1 [ i - 1 ] * ( b ) ) % mod + ( dp2 [ i - 1 ] * ( b - 1 ) ) % mod ) % mod NEW_LINE DEDENT return ( dp1 [ k ] ) NEW_LINE DEDENT S = ' ab ' NEW_LINE T = ' ab ' NEW_LINE K = 2 NEW_LINE print ( countWays ( S , T , K ) ) NEW_LINE"} +{"text":"Minimize steps to reach K from 0 by adding 1 or doubling at each step | Function to find minimum operations ; dp is initialised to store the steps ; For all even numbers ; Driver Code","code":"def minOperation ( k ) : NEW_LINE INDENT dp = [ 0 ] * ( k + 1 ) NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 1 NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , dp [ i \/\/ 2 ] + 1 ) NEW_LINE DEDENT DEDENT return dp [ k ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 12 NEW_LINE print ( minOperation ( k ) ) NEW_LINE DEDENT"} +{"text":"Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum | Function to find the maximum subset sum ; Ignore the current element ; including element in partition 1 ; including element in partition 2 ; Driver code ; size of the array","code":"def maxSum ( p0 , p1 , a , pos , n ) : NEW_LINE INDENT if ( pos == n ) : NEW_LINE INDENT if ( p0 == p1 ) : NEW_LINE INDENT return p0 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT ans = maxSum ( p0 , p1 , a , pos + 1 , n ) ; NEW_LINE ans = max ( ans , maxSum ( p0 + a [ pos ] , p1 , a , pos + 1 , n ) ) ; NEW_LINE ans = max ( ans , maxSum ( p0 , p1 + a [ pos ] , a , pos + 1 , n ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 4 ; NEW_LINE a = [ 1 , 2 , 3 , 6 ] ; NEW_LINE print ( maxSum ( 0 , 0 , a , 0 , n ) ) ; NEW_LINE DEDENT"} +{"text":"Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum | Python3 implementation for the above mentioned Dynamic Programming approach ; Function to find the maximum subset sum ; sum of all elements ; bottom up lookup table ; ; initialising dp table with INT_MIN where , INT_MIN means no solution ; Case when diff is 0 ; Putting ith element in g0 ; Putting ith element in g1 ; Ignoring ith element ; Driver code","code":"import numpy as np NEW_LINE import sys NEW_LINE INT_MIN = - ( sys . maxsize - 1 ) NEW_LINE def maxSum ( a , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] ; NEW_LINE DEDENT limit = 2 * sum + 1 ; NEW_LINE dp = np . zeros ( ( n + 1 , limit ) ) ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( limit ) : NEW_LINE INDENT dp [ i ] [ j ] = INT_MIN ; NEW_LINE DEDENT DEDENT dp [ 0 ] [ sum ] = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( limit ) : NEW_LINE INDENT if ( ( j - a [ i - 1 ] ) >= 0 and dp [ i - 1 ] [ j - a [ i - 1 ] ] != INT_MIN ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j - a [ i - 1 ] ] + a [ i - 1 ] ) ; NEW_LINE DEDENT if ( ( j + a [ i - 1 ] ) < limit and dp [ i - 1 ] [ j + a [ i - 1 ] ] != INT_MIN ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j + a [ i - 1 ] ] ) ; NEW_LINE DEDENT if ( dp [ i - 1 ] [ j ] != INT_MIN ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i - 1 ] [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ sum ] ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 4 ; NEW_LINE a = [ 1 , 2 , 3 , 6 ] ; NEW_LINE print ( maxSum ( a , n ) ) ; NEW_LINE DEDENT"} +{"text":"Count of strings possible by replacing two consecutive same character with new character | Array to find the fibonacci sequence ; Function to find the fibonacci sequence ; Function to count all possible strings ; Initialize ans = 1 ; If two consecutive char are same increase cnt ; Else multiply the fib [ cnt ] to ans and initialize ans to 1 ; If str = abcdeeee , then for last \" eeee \" the count munst be updated ; Return the total count ; Driver 's Code ; Function to precompute all the fibonacci number ; Function call to find the count","code":"fib = [ 0 ] * 100005 ; NEW_LINE def computeFibonacci ( ) : NEW_LINE INDENT fib [ 0 ] = 1 ; NEW_LINE fib [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , 100005 ) : NEW_LINE INDENT fib [ i ] = fib [ i - 1 ] + fib [ i - 2 ] ; NEW_LINE DEDENT DEDENT def countString ( string ) : NEW_LINE INDENT ans = 1 ; NEW_LINE cnt = 1 ; NEW_LINE for i in range ( 1 , len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == string [ i - 1 ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans * fib [ cnt ] ; NEW_LINE cnt = 1 ; NEW_LINE DEDENT DEDENT ans = ans * fib [ cnt ] ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" abdllldefkkkk \" ; NEW_LINE computeFibonacci ( ) ; NEW_LINE print ( countString ( string ) ) ; NEW_LINE DEDENT"} +{"text":"Golomb Sequence | Set 2 | Python3 program to find the first N terms of Golomb Sequence ; Function to print the Golomb Sequence ; Initialise the array ; Initialise the cnt to 0 ; First and second element of Golomb Sequence is 0 , 1 ; Map to store the count of current element in Golomb Sequence ; Store the count of 2 ; Iterate over 2 to N ; If cnt is equals to 0 then we have new number for Golomb Sequence which is 1 + previous element ; Else the current element is the previous element in this Sequence ; Map the current index to current value in arr [ ] ; Print the Golomb Sequence ; Driver Code","code":"MAX = 100001 NEW_LINE def printGolombSequence ( N ) : NEW_LINE INDENT arr = [ 0 ] * MAX NEW_LINE cnt = 0 NEW_LINE arr [ 0 ] = 0 NEW_LINE arr [ 1 ] = 1 NEW_LINE M = dict ( ) NEW_LINE M [ 2 ] = 2 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( cnt == 0 ) : NEW_LINE INDENT arr [ i ] = 1 + arr [ i - 1 ] NEW_LINE cnt = M [ arr [ i ] ] NEW_LINE cnt -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] NEW_LINE cnt -= 1 NEW_LINE DEDENT M [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT N = 11 NEW_LINE printGolombSequence ( N ) NEW_LINE"} +{"text":"Count ways to reach Nth Stairs by taking 1 and 2 steps with exactly one 3 step | Function to find the number the number of ways to reach Nth stair ; Array including number of ways that includes 3 ; Array including number of ways that doesn 't includes 3 ; Initially to reach 3 stairs by taking 3 steps can be reached by 1 way ; Loop to find the number the number of ways to reach Nth stair ; Driver Code","code":"def number_of_ways ( n ) : NEW_LINE INDENT includes_3 = [ 0 ] * ( n + 1 ) NEW_LINE not_includes_3 = [ 0 ] * ( n + 1 ) NEW_LINE includes_3 [ 3 ] = 1 NEW_LINE not_includes_3 [ 1 ] = 1 NEW_LINE not_includes_3 [ 2 ] = 2 NEW_LINE not_includes_3 [ 3 ] = 3 NEW_LINE for i in range ( 4 , n + 1 ) : NEW_LINE INDENT includes_3 [ i ] = includes_3 [ i - 1 ] + includes_3 [ i - 2 ] + not_includes_3 [ i - 3 ] NEW_LINE not_includes_3 [ i ] = not_includes_3 [ i - 1 ] + not_includes_3 [ i - 2 ] NEW_LINE DEDENT return includes_3 [ n ] NEW_LINE DEDENT n = 7 NEW_LINE print ( number_of_ways ( n ) ) NEW_LINE"} +{"text":"Maximum number of multiples in an array before any element | Python3 implementation of the approach ; Map to store the divisor count ; Function to generate the divisors of all the array elements ; Function to find the maximum number of multiples in an array before it ; To store the maximum divisor count ; Update ans if more number of divisors are found ; Generating all the divisors of the next element of the array ; Driver code","code":"from math import ceil , sqrt NEW_LINE MAX = 100000 NEW_LINE divisors = [ 0 ] * MAX NEW_LINE def generateDivisors ( n ) : NEW_LINE INDENT for i in range ( 1 , ceil ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n \/\/ i == i ) : NEW_LINE INDENT divisors [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT divisors [ i ] += 1 NEW_LINE divisors [ n \/\/ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def findMaxMultiples ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( divisors [ arr [ i ] ] , ans ) NEW_LINE generateDivisors ( arr [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 8 , 1 , 28 , 4 , 2 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxMultiples ( arr , n ) ) NEW_LINE"} +{"text":"Number of ways to reach the end of matrix with non | Python3 implementation of the approach ; 3d array to store states of dp ; Array to determine whether a state has been solved before ; Function to return the count of required paths ; Base cases ; If a state has been solved before it won 't be evaluated again ; Recurrence relation ; Driver code","code":"n = 3 NEW_LINE maxV = 20 NEW_LINE dp = [ [ [ 0 for i in range ( maxV ) ] for i in range ( n ) ] for i in range ( n ) ] NEW_LINE v = [ [ [ 0 for i in range ( maxV ) ] for i in range ( n ) ] for i in range ( n ) ] NEW_LINE def countWays ( i , j , x , arr ) : NEW_LINE INDENT if ( i == n or j == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT x = ( x & arr [ i ] [ j ] ) NEW_LINE if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i == n - 1 and j == n - 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( v [ i ] [ j ] [ x ] ) : NEW_LINE INDENT return dp [ i ] [ j ] [ x ] NEW_LINE DEDENT v [ i ] [ j ] [ x ] = 1 NEW_LINE dp [ i ] [ j ] [ x ] = countWays ( i + 1 , j , x , arr ) + countWays ( i , j + 1 , x , arr ) ; NEW_LINE return dp [ i ] [ j ] [ x ] NEW_LINE DEDENT arr = [ [ 1 , 2 , 1 ] , [ 1 , 1 , 0 ] , [ 2 , 1 , 1 ] ] NEW_LINE print ( countWays ( 0 , 0 , arr [ 0 ] [ 0 ] , arr ) ) NEW_LINE"} +{"text":"Maximum sum from three arrays such that picking elements consecutively from same is not allowed | Function to return the maximum sum ; Base case ; Already visited ; If the element has been taken from first array in previous step ; If the element has been taken from second array in previous step ; If the element has been taken from third array in previous step ; Driver code ; Pick element from first array ; Pick element from second array ; Pick element from third array ; Print the maximum of them","code":"def FindMaximumSum ( ind , kon , a , b , c , n , dp ) : NEW_LINE INDENT if ind == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dp [ ind ] [ kon ] != - 1 : NEW_LINE INDENT return dp [ ind ] [ kon ] NEW_LINE DEDENT ans = - 10 ** 9 + 5 NEW_LINE if kon == 0 : NEW_LINE INDENT ans = max ( ans , b [ ind ] + FindMaximumSum ( ind + 1 , 1 , a , b , c , n , dp ) ) NEW_LINE ans = max ( ans , c [ ind ] + FindMaximumSum ( ind + 1 , 2 , a , b , c , n , dp ) ) NEW_LINE DEDENT elif kon == 1 : NEW_LINE INDENT ans = max ( ans , a [ ind ] + FindMaximumSum ( ind + 1 , 0 , a , b , c , n , dp ) ) NEW_LINE ans = max ( ans , c [ ind ] + FindMaximumSum ( ind + 1 , 2 , a , b , c , n , dp ) ) NEW_LINE DEDENT elif kon == 2 : NEW_LINE INDENT ans = max ( ans , a [ ind ] + FindMaximumSum ( ind + 1 , 1 , a , b , c , n , dp ) ) NEW_LINE ans = max ( ans , b [ ind ] + FindMaximumSum ( ind + 1 , 0 , a , b , c , n , dp ) ) NEW_LINE DEDENT dp [ ind ] [ kon ] = ans NEW_LINE return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 3 NEW_LINE a = [ 6 , 8 , 2 , 7 , 4 , 2 , 7 ] NEW_LINE b = [ 7 , 8 , 5 , 8 , 6 , 3 , 5 ] NEW_LINE c = [ 8 , 3 , 2 , 6 , 8 , 4 , 1 ] NEW_LINE n = len ( a ) NEW_LINE dp = [ [ - 1 for i in range ( N ) ] for j in range ( n ) ] NEW_LINE x = FindMaximumSum ( 0 , 0 , a , b , c , n , dp ) NEW_LINE y = FindMaximumSum ( 0 , 1 , a , b , c , n , dp ) NEW_LINE z = FindMaximumSum ( 0 , 2 , a , b , c , n , dp ) NEW_LINE print ( max ( x , y , z ) ) NEW_LINE DEDENT"} +{"text":"Number of ways to make binary string of length N such that 0 s always occur together in groups of size K | Python3 iimplementation of the above approach ; Function to return no of ways to build a binary string of length N such that 0 s always occur in groups of size K ; Driver Code","code":"mod = 1000000007 ; NEW_LINE def noOfBinaryStrings ( N , k ) : NEW_LINE INDENT dp = [ 0 ] * 100002 ; NEW_LINE for i in range ( 1 , K ) : NEW_LINE INDENT dp [ i ] = 1 ; NEW_LINE DEDENT dp [ k ] = 2 ; NEW_LINE for i in range ( k + 1 , N + 1 ) : NEW_LINE INDENT dp [ i ] = ( dp [ i - 1 ] + dp [ i - k ] ) % mod ; NEW_LINE DEDENT return dp [ N ] ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 ; NEW_LINE K = 2 ; NEW_LINE print ( noOfBinaryStrings ( N , K ) ) ; NEW_LINE DEDENT"} +{"text":"Number of ways to pair people | Function to find number of ways to pair people in party ; To store count of number of ways . ; Using the recurrence defined find count for different values of p . ; Driver code","code":"def findWays ( p ) : NEW_LINE INDENT dp = [ 0 ] * ( p + 1 ) NEW_LINE dp [ 1 ] = 1 NEW_LINE dp [ 2 ] = 2 NEW_LINE for i in range ( 3 , p + 1 ) : NEW_LINE INDENT dp [ i ] = ( dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ) NEW_LINE DEDENT return dp [ p ] NEW_LINE DEDENT p = 3 NEW_LINE print ( findWays ( p ) ) NEW_LINE"} +{"text":"Count ways to reach a score using 1 and 2 with no consecutive 2 s | A simple recursive implementation for counting ways to reach a score using 1 and 2 with consecutive 2 allowed ; base case ; For cases n > 2 ; Driver code","code":"def CountWays ( n ) : NEW_LINE INDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if n == 2 : NEW_LINE INDENT return 1 + 1 NEW_LINE DEDENT return CountWays ( n - 1 ) + CountWays ( n - 3 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( CountWays ( n ) ) NEW_LINE DEDENT"} +{"text":"Weird Number | Python 3 program to check if the number is weird or not ; code to find all the factors of the number excluding the number itself ; vector to store the factors ; note that this loop runs till sqrt ( n ) ; if the value of i is a factor ; condition to check the divisor is not the number itself ; return the vector ; Function to check if the number is abundant or not ; find the divisors using function ; sum all the factors ; check for abundant or not ; Function to check if the number is semi - perfect or not ; find the divisors ; sorting the vector ; subset to check if no is semiperfect ; initialising 1 st column to true ; initialing 1 st row except zero position to 0 ; loop to find whether the number is semiperfect ; calculation to check if the number can be made by summation of divisors ; if not possible to make the number by any combination of divisors ; Function to check for weird or not ; Driver Code","code":"from math import sqrt NEW_LINE def factors ( n ) : NEW_LINE INDENT v = [ ] NEW_LINE v . append ( 1 ) NEW_LINE for i in range ( 2 , int ( sqrt ( n ) ) + 1 , 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT v . append ( i ) ; NEW_LINE if ( int ( n \/ i ) != i ) : NEW_LINE INDENT v . append ( int ( n \/ i ) ) NEW_LINE DEDENT DEDENT DEDENT return v NEW_LINE DEDENT def checkAbundant ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE v = factors ( n ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT sum += v [ i ] NEW_LINE DEDENT if ( sum > n ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def checkSemiPerfect ( n ) : NEW_LINE INDENT v = factors ( n ) NEW_LINE v . sort ( reverse = False ) NEW_LINE r = len ( v ) NEW_LINE subset = [ [ 0 for i in range ( n + 1 ) ] for j in range ( r + 1 ) ] NEW_LINE for i in range ( r + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( 1 , r + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( j < v [ i - 1 ] ) : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i - 1 ] [ j ] or subset [ i - 1 ] [ j - v [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT if ( ( subset [ r ] [ n ] ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT def checkweird ( n ) : NEW_LINE INDENT if ( checkAbundant ( n ) == True and checkSemiPerfect ( n ) == False ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 70 NEW_LINE if ( checkweird ( n ) ) : NEW_LINE INDENT print ( \" Weird \u2581 Number \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Weird \u2581 Number \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Maximum subarray sum in an array created after repeated concatenation | Returns sum of maximum sum subarray created after concatenating a [ 0. . n - 1 ] k times . ; This is where it differs from Kadane 's algorithm. We use modular arithmetic to find next element. ; Driver program to test maxSubArraySum","code":"def maxSubArraySumRepeated ( a , n , k ) : NEW_LINE INDENT max_so_far = - 2147483648 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( n * k ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i % n ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT if ( max_ending_here < 0 ) : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT a = [ 10 , 20 , - 30 , - 1 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE print ( \" Maximum \u2581 contiguous \u2581 sum \u2581 is \u2581 \" , maxSubArraySumRepeated ( a , n , k ) ) NEW_LINE"} +{"text":"Longest Increasing Odd Even Subsequence | function to find the longest increasing odd even subsequence ; lioes [ i ] stores longest increasing odd even subsequence ending at arr [ i ] ; to store the length of longest increasing odd even subsequence ; Initialize LIOES values for all indexes ; Compute optimized LIOES values in bottom up manner ; Pick maximum of all LIOES values ; required maximum length ; Driver to test above","code":"def longOddEvenIncSeq ( arr , n ) : NEW_LINE INDENT lioes = list ( ) NEW_LINE maxLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT lioes . append ( 1 ) NEW_LINE DEDENT i = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and ( arr [ i ] + arr [ j ] ) % 2 != 0 and lioes [ i ] < lioes [ j ] + 1 ) : NEW_LINE INDENT lioes [ i ] = lioes [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if maxLen < lioes [ i ] : NEW_LINE INDENT maxLen = lioes [ i ] NEW_LINE DEDENT DEDENT return maxLen NEW_LINE DEDENT arr = [ 1 , 12 , 2 , 22 , 5 , 30 , 31 , 14 , 17 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Longest \u2581 Increasing \u2581 Odd \u2581 Even \u2581 \" + \" Subsequence : \u2581 \" , longOddEvenIncSeq ( arr , n ) ) NEW_LINE"} +{"text":"Minimum and Maximum values of an expression with * and + | Utility method to check whether a character is operator or not ; method prints minimum and maximum value obtainable from an expression ; store operator and numbers in different vectors ; storing last number in vector ; initializing minval and maxval 2D array ; initializing main diagonal by num values ; looping similar to matrix chain multiplication and updating both 2D arrays ; if current operator is ' + ' , updating tmp variable by addition ; if current operator is ' * ' , updating tmp variable by multiplication ; updating array values by tmp variables ; last element of first row will store the result ; Driver code","code":"def isOperator ( op ) : NEW_LINE INDENT return ( op == ' + ' or op == ' * ' ) NEW_LINE DEDENT def printMinAndMaxValueOfExp ( exp ) : NEW_LINE INDENT num = [ ] NEW_LINE opr = [ ] NEW_LINE tmp = \" \" NEW_LINE for i in range ( len ( exp ) ) : NEW_LINE INDENT if ( isOperator ( exp [ i ] ) ) : NEW_LINE INDENT opr . append ( exp [ i ] ) NEW_LINE num . append ( int ( tmp ) ) NEW_LINE tmp = \" \" NEW_LINE DEDENT else : NEW_LINE INDENT tmp += exp [ i ] NEW_LINE DEDENT DEDENT num . append ( int ( tmp ) ) NEW_LINE llen = len ( num ) NEW_LINE minVal = [ [ 0 for i in range ( llen ) ] for i in range ( llen ) ] NEW_LINE maxVal = [ [ 0 for i in range ( llen ) ] for i in range ( llen ) ] NEW_LINE for i in range ( llen ) : NEW_LINE INDENT for j in range ( llen ) : NEW_LINE INDENT minVal [ i ] [ j ] = 10 ** 9 NEW_LINE maxVal [ i ] [ j ] = 0 NEW_LINE if ( i == j ) : NEW_LINE INDENT minVal [ i ] [ j ] = maxVal [ i ] [ j ] = num [ i ] NEW_LINE DEDENT DEDENT DEDENT for L in range ( 2 , llen + 1 ) : NEW_LINE INDENT for i in range ( llen - L + 1 ) : NEW_LINE INDENT j = i + L - 1 NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT minTmp = 0 NEW_LINE maxTmp = 0 NEW_LINE if ( opr [ k ] == ' + ' ) : NEW_LINE INDENT minTmp = minVal [ i ] [ k ] + minVal [ k + 1 ] [ j ] NEW_LINE maxTmp = maxVal [ i ] [ k ] + maxVal [ k + 1 ] [ j ] NEW_LINE DEDENT elif ( opr [ k ] == ' * ' ) : NEW_LINE INDENT minTmp = minVal [ i ] [ k ] * minVal [ k + 1 ] [ j ] NEW_LINE maxTmp = maxVal [ i ] [ k ] * maxVal [ k + 1 ] [ j ] NEW_LINE DEDENT if ( minTmp < minVal [ i ] [ j ] ) : NEW_LINE INDENT minVal [ i ] [ j ] = minTmp NEW_LINE DEDENT if ( maxTmp > maxVal [ i ] [ j ] ) : NEW_LINE INDENT maxVal [ i ] [ j ] = maxTmp NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( \" Minimum \u2581 value \u2581 : \u2581 \" , minVal [ 0 ] [ llen - 1 ] , \" , \u2581 \\ \u2581 Maximum \u2581 value \u2581 : \u2581 \" , maxVal [ 0 ] [ llen - 1 ] ) NEW_LINE DEDENT expression = \"1 + 2*3 + 4*5\" NEW_LINE printMinAndMaxValueOfExp ( expression ) NEW_LINE"} +{"text":"Matrix Chain Multiplication | DP | A naive recursive implementation that simply follows the above optimal substructure property ; Matrix A [ i ] has dimension p [ i - 1 ] x p [ i ] for i = 1. . n ; place parenthesis at different places between first and last matrix , recursively calculate count of multiplications for each parenthesis placement and return the minimum count ; Return minimum count ; Driver code","code":"import sys NEW_LINE def MatrixChainOrder ( p , i , j ) : NEW_LINE INDENT if i == j : NEW_LINE INDENT return 0 NEW_LINE DEDENT _min = sys . maxsize NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT count = ( MatrixChainOrder ( p , i , k ) + MatrixChainOrder ( p , k + 1 , j ) + p [ i - 1 ] * p [ k ] * p [ j ] ) NEW_LINE if count < _min : NEW_LINE INDENT _min = count NEW_LINE DEDENT DEDENT return _min NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Minimum \u2581 number \u2581 of \u2581 multiplications \u2581 is \u2581 \" , MatrixChainOrder ( arr , 1 , n - 1 ) ) NEW_LINE"} +{"text":"Matrix Chain Multiplication | DP | Python program using memoization ; Function for matrix chain multiplication ; Driver Code","code":"import sys NEW_LINE dp = [ [ - 1 for i in range ( 100 ) ] for j in range ( 100 ) ] NEW_LINE def matrixChainMemoised ( p , i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT dp [ i ] [ j ] = sys . maxsize NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , matrixChainMemoised ( p , i , k ) + matrixChainMemoised ( p , k + 1 , j ) + p [ i - 1 ] * p [ k ] * p [ j ] ) NEW_LINE DEDENT return dp [ i ] [ j ] NEW_LINE DEDENT def MatrixChainOrder ( p , n ) : NEW_LINE INDENT i = 1 NEW_LINE j = n - 1 NEW_LINE return matrixChainMemoised ( p , i , j ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Minimum \u2581 number \u2581 of \u2581 multiplications \u2581 is \" , MatrixChainOrder ( arr , n ) ) NEW_LINE"} +{"text":"Numbers formed by flipping common set bits in two given integers | Function to flip bits of A and B which are set in both of them ; Clear the bits of A which are set in both A and B ; Clear the bits of B which are set in both A and B ; Print updated A and B ; Driver Code","code":"def flipBitsOfAandB ( A , B ) : NEW_LINE INDENT A = A ^ ( A & B ) NEW_LINE B = B ^ ( A & B ) NEW_LINE print ( A , B ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = 10 NEW_LINE B = 20 NEW_LINE flipBitsOfAandB ( A , B ) NEW_LINE DEDENT"} +{"text":"Sum of Hamming difference of consecutive numbers from 0 to N | Set 2 | Function to calculate and return the hamming distance between all consecutive numbers from 0 to N ; Driver Code","code":"def TotalHammingDistance ( n ) : NEW_LINE INDENT i = 1 NEW_LINE sum = 0 NEW_LINE while ( n \/\/ i > 0 ) : NEW_LINE INDENT sum = sum + n \/\/ i NEW_LINE i = i * 2 NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 9 NEW_LINE print ( TotalHammingDistance ( N ) ) NEW_LINE DEDENT"} +{"text":"Sum of all divisors from 1 to N | Set 3 | Python3 Program to implement the above approach ; Function to find the sum of all divisors of all numbers from 1 to N ; Stores the sum ; Marks the last poof occurence with same count ; Calculate the sum ; Return the result ; Driver Code","code":"import math NEW_LINE m = 1000000007 NEW_LINE def solve ( n ) : NEW_LINE INDENT s = 0 ; NEW_LINE l = 1 ; NEW_LINE while ( l < n + 1 ) : NEW_LINE INDENT r = ( int ) ( n \/ math . floor ( n \/ l ) ) ; NEW_LINE x = ( ( ( ( r % m ) * ( ( r + 1 ) % m ) ) \/ 2 ) % m ) ; NEW_LINE y = ( ( ( ( l % m ) * ( ( l - 1 ) % m ) ) \/ 2 ) % m ) ; NEW_LINE p = ( int ) ( ( n \/ l ) % m ) ; NEW_LINE s = ( ( s + ( ( ( x - y ) % m ) * p ) % m + m ) % m ) ; NEW_LINE s %= m ; NEW_LINE l = r + 1 ; NEW_LINE DEDENT print ( int ( ( s + m ) % m ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 ; NEW_LINE solve ( n ) ; NEW_LINE DEDENT"} +{"text":"Minimize number of cuts required to break N length stick into N unit length sticks | Python3 program to find minimum time required to split a stick of N length into unit pieces ; Function to return the minimum time required to split stick of N into length into unit pieces ; Return the minimum unit of time required ; Driver Code","code":"import math NEW_LINE def min_time_to_cut ( N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return int ( math . log2 ( N ) ) + 1 NEW_LINE DEDENT N = 100 NEW_LINE print ( min_time_to_cut ( N ) ) NEW_LINE"} +{"text":"Count of distinct pair sum between two 1 to N value Arrays | Function to find the distinct sums ; Set to store distinct sums ; Inserting every sum ; Returning distinct sums ; Driver code","code":"def findDistinctSums ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT s . add ( i + j ) NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT N = 3 NEW_LINE print ( findDistinctSums ( N ) ) NEW_LINE"} +{"text":"Print Triangle separated pattern | Function to print pattern recursively ; Base Case ; Conditions to print slash ; Condition to print forword slash ; Condition to print backward slash ; Else print '* ; Recursive call for rows ; Recursive call for changing the rows ; Driver Code ; Function Call","code":"def printPattern ( i , j , n ) : NEW_LINE INDENT if ( j >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i >= n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( j == i or j == n - 1 - i ) : NEW_LINE INDENT if ( i == n - 1 - j ) : NEW_LINE INDENT print ( \" \/ \" , end = \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" \\\\ \" , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT print ( \" * \" , end = \" \" ) NEW_LINE DEDENT if ( printPattern ( i , j + 1 , n ) == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT print ( ) NEW_LINE return printPattern ( i + 1 , 0 , n ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 9 NEW_LINE printPattern ( 0 , 0 , N ) NEW_LINE DEDENT"} +{"text":"Find starting index for every occurrence of given array B in array A using Z | Python3 implementation for pattern searching in an array using Z - Algorithm ; Function to calculate Z - Array ; Loop to calculate Z - Array ; Outside the Z - box ; Inside Z - box ; Helper function to merge two arrays and create a single array ; Array to store merged array ; Copying array B ; Adding a separator ; Copying array A ; Calling Z - function ; Function to help compute the Z array ; Printing indexes where array B occur ; Driver Code","code":"import sys ; NEW_LINE def zArray ( arr ) : NEW_LINE INDENT n = len ( arr ) ; NEW_LINE z = [ 0 ] * n ; NEW_LINE r = 0 ; NEW_LINE l = 0 ; NEW_LINE for k in range ( 1 , n ) : NEW_LINE INDENT if ( k > r ) : NEW_LINE INDENT r = l = k ; NEW_LINE while ( r < n and arr [ r ] == arr [ r - l ] ) : NEW_LINE INDENT r += 1 ; NEW_LINE DEDENT z [ k ] = r - l ; NEW_LINE r -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT k1 = k - l ; NEW_LINE if ( z [ k1 ] < r - k + 1 ) : NEW_LINE INDENT z [ k ] = z [ k1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT l = k ; NEW_LINE while ( r < n and arr [ r ] == arr [ r - l ] ) : NEW_LINE INDENT r += 1 ; NEW_LINE DEDENT z [ k ] = r - l ; NEW_LINE r -= 1 ; NEW_LINE DEDENT DEDENT DEDENT return z ; NEW_LINE DEDENT def mergeArray ( A , B ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE m = len ( B ) ; NEW_LINE c = [ 0 ] * ( n + m + 1 ) ; NEW_LINE for i in range ( m ) : NEW_LINE INDENT c [ i ] = B [ i ] ; NEW_LINE DEDENT c [ m ] = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT c [ m + i + 1 ] = A [ i ] ; NEW_LINE DEDENT z = zArray ( c ) ; NEW_LINE return z ; NEW_LINE DEDENT def findZArray ( A , B , n ) : NEW_LINE INDENT flag = 0 ; NEW_LINE z = mergeArray ( A , B ) ; NEW_LINE for i in range ( len ( z ) ) : NEW_LINE INDENT if ( z [ i ] == n ) : NEW_LINE INDENT print ( i - n - 1 , end = \" \u2581 \" ) ; NEW_LINE flag = 1 ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( \" Not \u2581 Found \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 2 , 3 , 2 , 3 , 2 ] ; NEW_LINE B = [ 2 , 3 ] ; NEW_LINE n = len ( B ) ; NEW_LINE findZArray ( A , B , n ) ; NEW_LINE DEDENT"} +{"text":"Check if a string can be repeated to make another string | Function to return the count of repetitions of string a to generate string b ; If b cannot be generated by repeating a ; Repeat a count number of times ; Driver code","code":"def getCount ( a , b ) : NEW_LINE INDENT if ( len ( b ) % len ( a ) != 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT count = int ( len ( b ) \/ len ( a ) ) NEW_LINE a = a * count NEW_LINE if ( a == b ) : NEW_LINE INDENT return count NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = ' geeks ' NEW_LINE b = ' geeksgeeks ' NEW_LINE print ( getCount ( a , b ) ) NEW_LINE DEDENT"} +{"text":"Check if a string can be formed from another string using given constraints | Python3 program to Check if a given string can be formed from another string using given constraints ; Function to check if S2 can be formed of S1 ; length of strings ; hash - table to store count ; store count of each character ; traverse and check for every character ; if the character of s2 is present in s1 ; if the character of s2 is not present in S1 , then check if previous two ASCII characters are present in S1 ; Driver Code ; Calling function to check","code":"from collections import defaultdict NEW_LINE def check ( S1 , S2 ) : NEW_LINE INDENT n1 = len ( S1 ) NEW_LINE n2 = len ( S2 ) NEW_LINE mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT mp [ S1 [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 0 , n2 ) : NEW_LINE INDENT if mp [ S2 [ i ] ] : NEW_LINE INDENT mp [ S2 [ i ] ] -= 1 NEW_LINE DEDENT elif ( mp [ chr ( ord ( S2 [ i ] ) - 1 ) ] and mp [ chr ( ord ( S2 [ i ] ) - 2 ) ] ) : NEW_LINE INDENT mp [ chr ( ord ( S2 [ i ] ) - 1 ) ] -= 1 NEW_LINE mp [ chr ( ord ( S2 [ i ] ) - 2 ) ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S1 = \" abbat \" NEW_LINE S2 = \" cat \" NEW_LINE if check ( S1 , S2 ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Count of occurrences of a \"1(0 + ) 1\" pattern in a string | Returns count of occurrences of \"1(0 + ) 1\" ; count = 0 Initialize result ; Check if encountered '1' forms a valid pattern as specified ; if 1 encountered for first time set oneSeen to 1 ; Check if there is any other character other than '0' or '1' . If so then set oneSeen to 0 to search again for new pattern ; Driver code","code":"def countPattern ( s ) : NEW_LINE INDENT length = len ( s ) NEW_LINE oneSeen = False NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( s [ i ] == '1' and oneSeen ) : NEW_LINE INDENT if ( s [ i - 1 ] == '0' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( s [ i ] == '1' and oneSeen == 0 ) : NEW_LINE INDENT oneSeen = True NEW_LINE DEDENT if ( s [ i ] != '0' and s [ i ] != '1' ) : NEW_LINE INDENT oneSeen = False NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT s = \"100001abc101\" NEW_LINE print countPattern ( s ) NEW_LINE"} +{"text":"Convert given Strings into T by replacing characters in between strings any number of times | Function to check if it possible to make all the strings equal to the T ; Stores the frequency of all the strings in the array arr [ ] ; Stores the frequency of the T ; Iterate over the characters of the T ; Iterate in the range [ 0 , N - 1 ] ; Iterate over the characters of the arr [ i ] ; If freqT [ i ] is 0 and freqS [ i ] is not 0 ; If freqS [ i ] is 0 and freqT [ i ] is not 0 ; If freqS [ i ] is not freqT [ i ] * N ; Otherwise , return \" Yes \" ; Driver Code","code":"def checkIfPossible ( N , arr , T ) : NEW_LINE INDENT freqS = [ 0 ] * 256 NEW_LINE freqT = [ 0 ] * 256 NEW_LINE for ch in T : NEW_LINE INDENT freqT [ ord ( ch ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT for ch in arr [ i ] : NEW_LINE INDENT freqS [ ord ( ch ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 256 ) : NEW_LINE INDENT if ( freqT [ i ] == 0 and freqS [ i ] != 0 ) : NEW_LINE INDENT return \" No \" NEW_LINE DEDENT elif ( freqS [ i ] == 0 and freqT [ i ] != 0 ) : NEW_LINE INDENT return \" No \" NEW_LINE DEDENT elif ( freqT [ i ] != 0 and freqS [ i ] != ( freqT [ i ] * N ) ) : NEW_LINE INDENT return \" No \" NEW_LINE DEDENT DEDENT return \" Yes \" NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ \" abc \" , \" abb \" , \" acc \" ] NEW_LINE T = \" abc \" NEW_LINE N = len ( arr ) NEW_LINE print ( checkIfPossible ( N , arr , T ) ) NEW_LINE DEDENT"} +{"text":"Palindromic strings of length 3 possible by using characters of a given string | Function to print all palindromic strings of length 3 that can be formed using characters of string S ; Stores the count of character ; Traverse the string S ; Stores all palindromic strings ; Iterate over the charchaters over the range [ ' a ' , ' z ' ] ; If Hash [ ch ] is equal to 2 ; Iterate over the characters over the range [ ' a ' , ' z ' ] ; Stores all the palindromic string ; Push the s into the set st ; If Hash [ i ] is greater than or equal to 3 ; Iterate over charchaters over the range [ ' a ' , ' z ' ] ; Stores all the palindromic string ; If Hash [ j ] is positive ; Push s into the set st ; Iterate over the set ; Driver Code","code":"def generatePalindrome ( S ) : NEW_LINE INDENT Hash = { } NEW_LINE for ch in S : NEW_LINE INDENT Hash [ ch ] = Hash . get ( ch , 0 ) + 1 NEW_LINE DEDENT st = { } NEW_LINE for i in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT if ( chr ( i ) in Hash and Hash [ chr ( i ) ] == 2 ) : NEW_LINE INDENT for j in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT s = \" \" NEW_LINE if ( chr ( j ) in Hash and i != j ) : NEW_LINE INDENT s += chr ( i ) NEW_LINE s += chr ( j ) NEW_LINE s += chr ( i ) NEW_LINE st [ s ] = 1 NEW_LINE DEDENT DEDENT DEDENT if ( ( chr ( i ) in Hash ) and Hash [ chr ( i ) ] >= 3 ) : NEW_LINE INDENT for j in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT s = \" \" NEW_LINE if ( chr ( j ) in Hash ) : NEW_LINE INDENT s += chr ( i ) NEW_LINE s += chr ( j ) NEW_LINE s += chr ( i ) NEW_LINE st [ s ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT for ans in st : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" ddabdac \" NEW_LINE generatePalindrome ( S ) NEW_LINE DEDENT"} +{"text":"Count occurrences of substring X before every occurrence of substring Y in a given string | Function to count occurrences of the string Y in the string S for every occurrence of X in S ; Stores the count of occurrences of X ; Stores the lengths of the three strings ; Traverse the string S ; If the current substring is Y , then increment the value of count by 1 ; If the current substring is X , then print the count ; Driver Code","code":"def countOccurrences ( S , X , Y ) : NEW_LINE INDENT count = 0 NEW_LINE N = len ( S ) NEW_LINE A = len ( X ) NEW_LINE B = len ( Y ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i : i + B ] == Y ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( S [ i : i + A ] == X ) : NEW_LINE INDENT print ( count , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT S = \" abcdefdefabc \" NEW_LINE X = \" abc \" NEW_LINE Y = \" def \" NEW_LINE countOccurrences ( S , X , Y ) NEW_LINE"} +{"text":"Program to construct DFA for Regular Expression C ( A + B ) + | Function to find whether the given is Accepted by the DFA ; If n <= 1 , then prNo ; To count the matched characters ; Check if the first character is C ; Traverse the rest of string ; If character is A or B , increment count by 1 ; If the first character is not C , pr - 1 ; If all characters matches ; Driver Code","code":"def DFA ( str , N ) : NEW_LINE INDENT if ( N <= 1 ) : NEW_LINE INDENT print ( \" No \" ) NEW_LINE return NEW_LINE DEDENT count = 0 NEW_LINE if ( str [ 0 ] == ' C ' ) : NEW_LINE INDENT count += 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( str [ i ] == ' A ' or str [ i ] == ' B ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE return NEW_LINE DEDENT if ( count == N ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" CAABBAAB \" NEW_LINE N = len ( str ) NEW_LINE DFA ( str , N ) NEW_LINE DEDENT"} +{"text":"Minimum and maximum number of digits required to be removed to make a given number divisible by 3 | Function to find the maximum and minimum number of digits to be removed to make str divisible by 3 ; Convert the string into array of digits ; Count of 0 s , 1 s , and 2 s ; Traverse the array ; Find the sum of digits % 3 ; Cases to find minimum number of digits to be removed ; Cases to find maximum number of digits to be removed ; Driver Code ; Function Call","code":"def minMaxDigits ( str , N ) : NEW_LINE INDENT arr = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr [ i ] = ( ord ( str [ i ] ) - ord ( '0' ) ) % 3 NEW_LINE DEDENT zero = 0 NEW_LINE one = 0 NEW_LINE two = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT if ( arr [ i ] == 2 ) : NEW_LINE INDENT two += 1 NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum = ( sum + arr [ i ] ) % 3 NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT print ( \"0\" , end = \" \u2581 \" ) NEW_LINE DEDENT if ( sum == 1 ) : NEW_LINE INDENT if ( one and N > 1 ) : NEW_LINE INDENT print ( \"1\" , end = \" \u2581 \" ) NEW_LINE DEDENT elif ( two > 1 and N > 2 ) : NEW_LINE INDENT print ( \"2\" , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" - 1\" , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if ( sum == 2 ) : NEW_LINE INDENT if ( two and N > 1 ) : NEW_LINE INDENT print ( \"1\" , end = \" \u2581 \" ) NEW_LINE DEDENT elif ( one > 1 and N > 2 ) : NEW_LINE INDENT print ( \"2\" , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" - 1\" , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if ( zero > 0 ) : NEW_LINE INDENT print ( N - 1 , end = \" \u2581 \" ) NEW_LINE DEDENT elif ( one > 0 and two > 0 ) : NEW_LINE INDENT print ( N - 2 , end = \" \u2581 \" ) NEW_LINE DEDENT elif ( one > 2 or two > 2 ) : NEW_LINE INDENT print ( N - 3 , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" - 1\" , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT str = \"12345\" NEW_LINE N = len ( str ) NEW_LINE minMaxDigits ( str , N ) NEW_LINE"} +{"text":"Minimum replacements required to obtain a K | Python3 program for the above approach ; Function to find the minimum number of changes to make the string K - periodic and palindrome ; Initialize ans with 0 ; Iterate from 0 to ( K + 1 ) \/ 2 ; Store frequency of character ; Iterate through all indices , i , i + K , i + 2 k ... . and store the frequency of character ; Increase the frequency of current character ; Iterate through all indices K - i , 2 K - i , 3 K - i ... . and store the frequency of character ; If K is odd & i is samw as K \/ 2 , break the loop ; Increase the frequency of current character ; Find the maximum frequency of a character among all visited characters ; If K is odd and i is same as K \/ 2 then , only N \/ K characters is visited ; Otherwise N \/ K * 2 characters has visited ; Return the result ; Driver Code ; Function Call","code":"import sys NEW_LINE def findMinimumChanges ( N , K , S ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( ( K + 1 ) \/\/ 2 ) : NEW_LINE INDENT mp = { } NEW_LINE for j in range ( i , N , K ) : NEW_LINE INDENT mp [ S [ j ] ] = mp . get ( S [ j ] , 0 ) + 1 NEW_LINE DEDENT j = N - i - 1 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( ( K & 1 ) and ( i == K \/\/ 2 ) ) : NEW_LINE INDENT break NEW_LINE DEDENT mp [ S [ j ] ] = mp . get ( S [ j ] , 0 ) + 1 NEW_LINE j -= K NEW_LINE DEDENT curr_max = - sys . maxsize - 1 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT curr_max = max ( curr_max , value ) NEW_LINE DEDENT if ( ( K & 1 ) and ( i == K \/\/ 2 ) ) : NEW_LINE INDENT ans += ( N \/\/ K - curr_max ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( N \/\/ K * 2 - curr_max ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" aabbcbbcb \" NEW_LINE N = len ( S ) NEW_LINE K = 3 NEW_LINE print ( findMinimumChanges ( N , K , S ) ) NEW_LINE DEDENT"} +{"text":"Check if a String contains any index with more than K active characters | Function to check if any index contains more than K active characters ; Store the last occurrence of each character ; Stores the active characters ; Insert the character ; If the size of set exceeds K ; Remove the character from set if i is the last index of the current character ; Driver code","code":"def checkString ( s , K ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dict = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT dict [ s [ i ] ] = i ; NEW_LINE DEDENT st = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT st . add ( s [ i ] ) NEW_LINE if len ( st ) > K : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE return NEW_LINE DEDENT if dict [ s [ i ] ] == i : NEW_LINE INDENT st . remove ( s [ i ] ) NEW_LINE DEDENT DEDENT print ( \" No \" ) NEW_LINE DEDENT s = \" aabbcdca \" NEW_LINE K = 2 NEW_LINE checkString ( s , K ) NEW_LINE"} +{"text":"Count the number of strings in an array whose distinct characters are less than equal to M | Function to count the strings whose distinct characters count is less than M ; Loop to iterate over all the strings of the array ; Distinct characters in the String with the help of set ; Checking if its less than or equal to M ; Driver Code","code":"def distinct ( S , M ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT c = len ( set ( [ d for d in S [ i ] ] ) ) NEW_LINE if ( c <= M ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = [ \" HERBIVORES \" , \" AEROPLANE \" , \" GEEKSFORGEEKS \" ] NEW_LINE M = 7 NEW_LINE distinct ( S , M ) NEW_LINE DEDENT"} +{"text":"Remove odd frequency characters from the string | Function to remove the characters which have odd frequencies in the string ; Create a map to store the frequency of each character ; To store the new string ; Remove the characters which have odd frequencies ; If the character has odd frequency then skip ; Else concatenate the character to the new string ; Return the modified string ; Driver code ; Remove the characters which have odd frequencies","code":"def removeOddFrequencyCharacters ( s ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in s : NEW_LINE INDENT m [ i ] = m . get ( i , 0 ) + 1 NEW_LINE DEDENT new_s = \" \" NEW_LINE for i in s : NEW_LINE INDENT if ( m [ i ] & 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT new_s += i NEW_LINE DEDENT return new_s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" geeksforgeeks \" NEW_LINE str = removeOddFrequencyCharacters ( str ) NEW_LINE print ( str ) NEW_LINE DEDENT"} +{"text":"Product of nodes at k | Recursive Function to find product of elements at k - th level ; if subtree is null , just like if root == NULL ; Consider only level k node to be part of the product ; Recur for Left Subtree ; Recur for Right Subtree ; Taking care of ' ) ' after left and right subtree ; Driver Code","code":"def productAtKthLevel ( tree , k , i , level ) : NEW_LINE INDENT if ( tree [ i [ 0 ] ] == ' ( ' ) : NEW_LINE INDENT i [ 0 ] += 1 NEW_LINE if ( tree [ i [ 0 ] ] == ' ) ' ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT product = 1 NEW_LINE if ( level == k ) : NEW_LINE INDENT product = int ( tree [ i [ 0 ] ] ) NEW_LINE DEDENT i [ 0 ] += 1 NEW_LINE leftproduct = productAtKthLevel ( tree , k , i , level + 1 ) NEW_LINE i [ 0 ] += 1 NEW_LINE rightproduct = productAtKthLevel ( tree , k , i , level + 1 ) NEW_LINE i [ 0 ] += 1 NEW_LINE return product * leftproduct * rightproduct NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT tree = \" ( 0(5(6 ( ) ( ) ) ( 4 ( ) (9 ( ) ( ) ) ) ) ( 7(1 ( ) ( ) ) ( 3 ( ) ( ) ) ) ) \" NEW_LINE k = 2 NEW_LINE i = [ 0 ] NEW_LINE print ( productAtKthLevel ( tree , k , i , 0 ) ) NEW_LINE DEDENT"} +{"text":"Print the most occurring character in an array of strings | Function to print the most occurring character ; Creating a hash of size 26 ; For loop to iterate through every string of the array ; For loop to iterate through every character of the string ; Incrementing the count of the character in the hash ; Finding the character with the maximum count ; Driver code ; Declaring Vector of String type","code":"def findMostOccurringChar ( string ) : NEW_LINE INDENT hash = [ 0 ] * 26 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT for j in range ( len ( string [ i ] ) ) : NEW_LINE INDENT hash [ ord ( string [ i ] [ j ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT DEDENT max = 0 ; NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT max = i if hash [ i ] > hash [ max ] else max ; NEW_LINE DEDENT print ( ( chr ) ( max + 97 ) ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = [ ] ; NEW_LINE string . append ( \" animal \" ) ; NEW_LINE string . append ( \" zebra \" ) ; NEW_LINE string . append ( \" lion \" ) ; NEW_LINE string . append ( \" giraffe \" ) ; NEW_LINE findMostOccurringChar ( string ) ; NEW_LINE DEDENT"} +{"text":"Check whether the given floating point number is a palindrome | Function that returns true if num is palindrome ; Convert the given floating point number into a string ; Pointers pointing to the first and the last character of the string ; Not a palindrome ; Update the pointers ; Driver code","code":"def isPalindrome ( num ) : NEW_LINE INDENT s = str ( num ) NEW_LINE low = 0 NEW_LINE high = len ( s ) - 1 NEW_LINE while ( low < high ) : NEW_LINE INDENT if ( s [ low ] != s [ high ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT low += 1 NEW_LINE high -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT n = 123.321 NEW_LINE if ( isPalindrome ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Maximum number of times str1 appears as a non | Python3 implementation of the approach ; Function to return the maximum number of times str1 can appear as a non - overlapping substring bin str2 ; str1 cannot never be substring of str2 ; Store the frequency of the characters of str1 ; Store the frequency of the characters of str2 ; To store the required count of substrings ; Current character doesn 't appear in str1 ; Frequency of the current character in str1 is greater than its frequency in str2 ; Update the count of possible substrings ; Driver code","code":"import sys NEW_LINE MAX = 26 ; NEW_LINE def maxSubStr ( str1 , len1 , str2 , len2 ) : NEW_LINE INDENT if ( len1 > len2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT freq1 = [ 0 ] * MAX ; NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT freq2 = [ 0 ] * MAX ; NEW_LINE for i in range ( len2 ) : NEW_LINE INDENT freq2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT minPoss = sys . maxsize ; NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( freq1 [ i ] == 0 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( freq1 [ i ] > freq2 [ i ] ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT minPoss = min ( minPoss , freq2 [ i ] \/ freq1 [ i ] ) ; NEW_LINE DEDENT return int ( minPoss ) ; NEW_LINE DEDENT str1 = \" geeks \" ; str2 = \" gskefrgoekees \" ; NEW_LINE len1 = len ( str1 ) ; NEW_LINE len2 = len ( str2 ) ; NEW_LINE print ( maxSubStr ( str1 , len1 , str2 , len2 ) ) ; NEW_LINE"} +{"text":"Number of ways to insert two pairs of parentheses into a string of N characters | Function to return the number of ways to insert the bracket pairs ; Driver code","code":"def cntWays ( string , n ) : NEW_LINE INDENT x = n + 1 ; NEW_LINE ways = x * x * ( x * x - 1 ) \/\/ 12 ; NEW_LINE return ways ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" ab \" ; NEW_LINE n = len ( string ) ; NEW_LINE print ( cntWays ( string , n ) ) ; NEW_LINE DEDENT"} +{"text":"Minimum number of substrings the given string can be splitted into that satisfy the given conditions | Python3 implementation of the approach ; Set to store all the strings from the given array ; To store the required count ; Recursive function to find the count of substrings that can be splitted starting from the index start such that all the substrings are present in the map ; All the chosen substrings are present in the map ; Update the minimum count of substrings ; Starting from the substrings of length 1 that start with the given index ; Get the substring ; If the substring is present in the set ; Recursive call for the rest of the string ; Function that inserts all the strings from the given array in a set and calls the recursive function to find the minimum count of substrings str can be splitted into that satisfy the given condition ; Insert all the strings from the given array in a set ; Find the required count ; Driver code","code":"import sys NEW_LINE uSet = set ( ) ; NEW_LINE minCnt = sys . maxsize ; NEW_LINE def findSubStr ( string , cnt , start ) : NEW_LINE INDENT global minCnt ; NEW_LINE if ( start == len ( string ) ) : NEW_LINE INDENT minCnt = min ( cnt , minCnt ) ; NEW_LINE DEDENT for length in range ( 1 , len ( string ) - start + 1 ) : NEW_LINE INDENT subStr = string [ start : start + length ] ; NEW_LINE if subStr in uSet : NEW_LINE INDENT findSubStr ( string , cnt + 1 , start + length ) ; NEW_LINE DEDENT DEDENT DEDENT def findMinSubStr ( arr , n , string ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT uSet . add ( arr [ i ] ) ; NEW_LINE DEDENT findSubStr ( string , 0 , 0 ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \"123456\" ; NEW_LINE arr = [ \"1\" , \"12345\" , \"2345\" , \"56\" , \"23\" , \"456\" ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findMinSubStr ( arr , n , string ) ; NEW_LINE print ( minCnt ) ; NEW_LINE DEDENT"} +{"text":"Number of substrings that start with \" geeks \" and end with \" for \" | Function to return the count of required substrings ; For every index of the string ; If the substring starting at the current index is \" geeks \" ; If the substring is \" for \" ; Driver code","code":"def countSubStr ( s , n ) : NEW_LINE INDENT c1 = 0 ; c2 = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i : i + 5 ] == \" geeks \" ) : NEW_LINE INDENT c1 += 1 ; NEW_LINE DEDENT if ( s [ i : i + 3 ] == \" for \" ) : NEW_LINE INDENT c2 = c2 + c1 ; NEW_LINE DEDENT DEDENT return c2 ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \" geeksforgeeksisforgeeks \" ; NEW_LINE n = len ( s ) ; NEW_LINE print ( countSubStr ( s , n ) ) ; NEW_LINE DEDENT"} +{"text":"InfyTQ 2019 : Find the position from where the parenthesis is not balanced | Defining the string ; Storing opening braces in list lst1 ; Storing closing braces in list lst2 ; Creating an empty list lst ; Creating dictionary to map closing braces to opening ones ; If first position of string contain any closing braces return 1 ; If characters of string are opening braces then append them in a list ; When size of list is 0 and new closing braces is encountered then print its index starting from 1 ; As we encounter closing braces we map them with theircorresponding opening braces using dictionary and check if it is same as last opened braces ( last element in list ) if yes then we delete that elememt from list ; Otherwise we return the index ( starting from 1 ) at which nesting is found wrong ; At end if the list is empty it means the string is perfectly nested","code":"string = \" { [ ( ) ] } [ ] \" NEW_LINE lst1 = [ ' { ' , ' ( ' , ' [ ' ] NEW_LINE lst2 = [ ' } ' , ' ) ' , ' ] ' ] NEW_LINE lst = [ ] NEW_LINE Dict = { ' ) ' : ' ( ' , ' } ' : ' { ' , ' ] ' : ' [ ' } NEW_LINE a = b = c = 0 NEW_LINE if string [ 0 ] in lst2 : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , len ( string ) ) : NEW_LINE INDENT if string [ i ] in lst1 : NEW_LINE INDENT lst . append ( string [ i ] ) NEW_LINE k = i + 2 NEW_LINE DEDENT else : NEW_LINE INDENT if len ( lst ) == 0 and ( string [ i ] in lst2 ) : NEW_LINE INDENT print ( i + 1 ) NEW_LINE c = 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT if Dict [ string [ i ] ] == lst [ len ( lst ) - 1 ] : NEW_LINE INDENT lst . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( i + 1 ) NEW_LINE a = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT if len ( lst ) == 0 and c == 0 : NEW_LINE INDENT print ( 0 ) NEW_LINE b = 1 NEW_LINE DEDENT if a == 0 and b == 0 and c == 0 : NEW_LINE INDENT print ( k ) NEW_LINE DEDENT DEDENT"} +{"text":"Encrypt the given string with the following operations | Python3 implementation of the above approach : ; Function to return the encrypted string ; Reduce x because rotation of length 26 is unnecessary ; calculate the frequency of characters ; If the frequency of current character is even then increment it by x ; Else decrement it by x ; Return the count ; Driver code","code":"MAX = 26 NEW_LINE def encryptstrr ( strr , n , x ) : NEW_LINE INDENT x = x % MAX NEW_LINE arr = list ( strr ) NEW_LINE freq = [ 0 ] * MAX NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( arr [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( freq [ ord ( arr [ i ] ) - ord ( ' a ' ) ] % 2 == 0 ) : NEW_LINE INDENT pos = ( ord ( arr [ i ] ) - ord ( ' a ' ) + x ) % MAX NEW_LINE arr [ i ] = chr ( pos + ord ( ' a ' ) ) NEW_LINE DEDENT else : NEW_LINE INDENT pos = ( ord ( arr [ i ] ) - ord ( ' a ' ) - x ) NEW_LINE if ( pos < 0 ) : NEW_LINE INDENT pos += MAX NEW_LINE DEDENT arr [ i ] = chr ( pos + ord ( ' a ' ) ) NEW_LINE DEDENT DEDENT return \" \" . join ( arr ) NEW_LINE DEDENT s = \" abcda \" NEW_LINE n = len ( s ) NEW_LINE x = 3 NEW_LINE print ( encryptstrr ( s , n , x ) ) NEW_LINE"} +{"text":"Rearrange characters in a string such that no two adjacent are same using hashing | Function that returns true if it is possible to rearrange the characters of the String such that no two consecutive characters are same ; To store the frequency of each of the character ; To store the maximum frequency so far ; If possible ; Driver code","code":"def isPossible ( Str ) : NEW_LINE INDENT freq = dict ( ) NEW_LINE max_freq = 0 NEW_LINE for j in range ( len ( Str ) ) : NEW_LINE INDENT freq [ Str [ j ] ] = freq . get ( Str [ j ] , 0 ) + 1 NEW_LINE if ( freq [ Str [ j ] ] > max_freq ) : NEW_LINE INDENT max_freq = freq [ Str [ j ] ] NEW_LINE DEDENT DEDENT if ( max_freq <= ( len ( Str ) - max_freq + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT Str = \" geeksforgeeks \" NEW_LINE if ( isPossible ( Str ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Find uncommon characters of the two strings | Set 2 | Function to print the uncommon characters in the given string in sorted order ; Converting character to ASCII code ; Bit operation ; Converting character to ASCII code ; Bit operation ; XOR operation leaves only uncommon characters in the ans variable ; Driver code","code":"def printUncommon ( str1 , str2 ) : NEW_LINE INDENT a1 = 0 ; a2 = 0 ; NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT ch = ord ( str1 [ i ] ) - ord ( ' a ' ) ; NEW_LINE a1 = a1 | ( 1 << ch ) ; NEW_LINE DEDENT for i in range ( len ( str2 ) ) : NEW_LINE INDENT ch = ord ( str2 [ i ] ) - ord ( ' a ' ) ; NEW_LINE a2 = a2 | ( 1 << ch ) ; NEW_LINE DEDENT ans = a1 ^ a2 ; NEW_LINE i = 0 ; NEW_LINE while ( i < 26 ) : NEW_LINE INDENT if ( ans % 2 == 1 ) : NEW_LINE INDENT print ( chr ( ord ( ' a ' ) + i ) , end = \" \" ) ; NEW_LINE DEDENT ans = ans \/\/ 2 ; NEW_LINE i += 1 ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" geeksforgeeks \" ; NEW_LINE str2 = \" geeksquiz \" ; NEW_LINE printUncommon ( str1 , str2 ) ; NEW_LINE DEDENT"} +{"text":"Minimum number of bracket reversals needed to make an expression balanced | Set | Returns count of minimum reversals for making expr balanced . Returns - 1 if expr cannot be balanced . ; length of expression must be even to make it balanced by using reversals . ; To store number of reversals required . ; To store number of unbalanced opening brackets . ; To store number of unbalanced closing brackets . ; If current bracket is open then increment open count . ; If current bracket is close , check if it balances opening bracket . If yes then decrement count of unbalanced opening bracket else increment count of closing bracket . ; For the case : \" \" or when one closing and one opening bracket remains for pairing , then both need to be reversed . ; Driver Code","code":"def countMinReversals ( expr ) : NEW_LINE INDENT length = len ( expr ) NEW_LINE if length % 2 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = 0 NEW_LINE open = 0 NEW_LINE close = 0 NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT if expr [ i ] == \" \" : NEW_LINE INDENT open += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if not open : NEW_LINE INDENT close += 1 NEW_LINE DEDENT else : NEW_LINE INDENT open -= 1 NEW_LINE DEDENT DEDENT DEDENT ans = ( close \/\/ 2 ) + ( open \/\/ 2 ) NEW_LINE close %= 2 NEW_LINE open %= 2 NEW_LINE if close > 0 : NEW_LINE INDENT ans += 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT expr = \" } } { { \" NEW_LINE print ( countMinReversals ( expr ) ) NEW_LINE DEDENT"} +{"text":"Character pairs from two strings with even sum | Function to return the total number of valid pairs ; Count total number of even and odd ascii values for string s1 ; Count total number of even and odd ascii values for string s2 ; Return total valid pairs ; Driver code","code":"def totalPairs ( s1 , s2 ) : NEW_LINE INDENT a1 = 0 ; b1 = 0 ; NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( ord ( s1 [ i ] ) % 2 != 0 ) : NEW_LINE INDENT a1 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT b1 += 1 ; NEW_LINE DEDENT DEDENT a2 = 0 ; b2 = 0 ; NEW_LINE for i in range ( len ( s2 ) ) : NEW_LINE INDENT if ( ord ( s2 [ i ] ) % 2 != 0 ) : NEW_LINE INDENT a2 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT b2 += 1 ; NEW_LINE DEDENT DEDENT return ( ( a1 * a2 ) + ( b1 * b2 ) ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s1 = \" geeks \" ; NEW_LINE s2 = \" for \" ; NEW_LINE print ( totalPairs ( s1 , s2 ) ) ; NEW_LINE DEDENT"} +{"text":"Maximum occurrence of prefix in the Array | Function to return the count of the required prefix ; Find the frequency of first character of str1ing ; Driver code","code":"def prefixOccurrences ( str1 ) : NEW_LINE INDENT c = str1 [ 0 ] NEW_LINE countc = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] == c ) : NEW_LINE INDENT countc += 1 NEW_LINE DEDENT DEDENT return countc NEW_LINE DEDENT str1 = \" abbcdabbcd \" NEW_LINE print ( prefixOccurrences ( str1 ) ) NEW_LINE"} +{"text":"Minimum number of given operations required to convert a string to another string | Function to return the minimum operations of the given type required to convert string s to string t ; Characters are already equal ; Increment count of 0 s ; Increment count of 1 s ; Driver code","code":"def minOperations ( s , t , n ) : NEW_LINE INDENT ct0 = 0 NEW_LINE ct1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == t [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT ct0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ct1 += 1 NEW_LINE DEDENT DEDENT return max ( ct0 , ct1 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"010\" NEW_LINE t = \"101\" NEW_LINE n = len ( s ) NEW_LINE print ( minOperations ( s , t , n ) ) NEW_LINE DEDENT"} +{"text":"Decrypt a string encrypted by repeating i | Function to return the decrypted string ; Initial jump will be 1 ; Increment jump by 1 with every character ; Driver code","code":"def decryptString ( str , n ) : NEW_LINE INDENT i = 0 NEW_LINE jump = 1 NEW_LINE decryptedStr = \" \" NEW_LINE while ( i < n ) : NEW_LINE INDENT decryptedStr += str [ i ] ; NEW_LINE i += jump NEW_LINE jump += 1 NEW_LINE DEDENT return decryptedStr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" geeeeekkkksssss \" NEW_LINE n = len ( str ) NEW_LINE print ( decryptString ( str , n ) ) NEW_LINE DEDENT"} +{"text":"Find Bit whose minimum sequence flips makes all bits same | Function to check which bit is to be flipped ; variable to store first and last character of string ; Check if first and last characters are equal , if yes , then return the character which is not at last ; else return last ; Driver Code","code":"def bitToBeFlipped ( s ) : NEW_LINE INDENT last = s [ len ( s ) - 1 ] NEW_LINE first = s [ 0 ] NEW_LINE if ( last == first ) : NEW_LINE INDENT if ( last == '0' ) : NEW_LINE INDENT return '1' NEW_LINE DEDENT else : NEW_LINE INDENT return '0' NEW_LINE DEDENT DEDENT elif ( last != first ) : NEW_LINE INDENT return last NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"1101011000\" NEW_LINE print ( bitToBeFlipped ( s ) ) NEW_LINE DEDENT"} +{"text":"Sum and Product of Prime Frequencies of Characters in a String | Function to create Sieve to check primes ; 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 find the sum of prime frequencies of the characters of the given string ; map is used to store character frequencies ; Traverse the map ; If the frequency is prime ; Driver code","code":"def SieveofEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , p_size + 1 ) : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def sumProdOfPrimeFreq ( s ) : NEW_LINE INDENT prime = [ True ] * ( len ( s ) + 2 ) NEW_LINE SieveofEratosthenes ( prime , len ( s ) + 1 ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT m [ s [ i ] ] = ( m [ s [ i ] ] + 1 ) if s [ i ] in m else 1 NEW_LINE DEDENT s = 0 NEW_LINE product = 1 NEW_LINE for it in m : NEW_LINE INDENT if prime [ m [ it ] ] : NEW_LINE INDENT s += m [ it ] NEW_LINE product *= m [ it ] NEW_LINE DEDENT DEDENT print ( \" Sum \u2581 = \" , s ) NEW_LINE print ( \" Product \u2581 = \" , product ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \" geeksforgeeks \" NEW_LINE sumProdOfPrimeFreq ( s ) NEW_LINE DEDENT"} +{"text":"Check if frequency of character in one string is a factor or multiple of frequency of same character in other string | Python3 implementation of above approach ; Function that checks if the frequency of character are a factor or multiple of each other ; map store frequency of each character ; if any frequency is 0 , then continue as condition is satisfied ; if factor or multiple , then condition satisfied ; if condition not satisfied ; Driver code","code":"from collections import defaultdict NEW_LINE def multipleOrFactor ( s1 , s2 ) : NEW_LINE INDENT m1 = defaultdict ( lambda : 0 ) NEW_LINE m2 = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , len ( s1 ) ) : NEW_LINE INDENT m1 [ s1 [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 0 , len ( s2 ) ) : NEW_LINE INDENT m2 [ s2 [ i ] ] += 1 NEW_LINE DEDENT for it in m1 : NEW_LINE INDENT if it not in m2 : NEW_LINE INDENT continue NEW_LINE DEDENT if ( m2 [ it ] % m1 [ it ] == 0 or m1 [ it ] % m2 [ it ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s1 = \" geeksforgeeks \" NEW_LINE s2 = \" geeks \" NEW_LINE if multipleOrFactor ( s1 , s2 ) : print ( \" YES \" ) NEW_LINE else : print ( \" NO \" ) NEW_LINE DEDENT"} +{"text":"Remove even frequency characters from the string | Function that removes the characters which have even frequencies in the string ; create a map to store the frequency of each character ; to store the new string ; remove the characters which have even frequencies ; if the character has even frequency then skip ; else concatenate the character to the new string ; display the modified string ; Driver code ; remove the characters which have even frequencies","code":"def solve ( s ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] = m [ s [ i ] ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT new_string = \" \" NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if m [ s [ i ] ] % 2 == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT new_string = new_string + s [ i ] NEW_LINE DEDENT print ( new_string ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" aabbbddeeecc \" NEW_LINE solve ( s ) NEW_LINE DEDENT"} +{"text":"Sum of all subsequences of a number | Returns numeric value of a subsequence of s . The subsequence to be picked is decided using bit pattern of num ( We pick all thosedigits for which there is a set bit in num ) ; Initialize the result ; till n != 0 ; if i - th bit is set then add this number ; right shift i ; function to find combined sum of all individual subsequence sum ; length of string ; stores the combined ; 2 ^ n - 1 subsequences ; loop for all subsequences ; returns the combined sum ; driver code","code":"def findSubSequence ( s , num ) : NEW_LINE INDENT res = 0 NEW_LINE i = 0 NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT res += ord ( s [ i ] ) - ord ( '0' ) NEW_LINE DEDENT i += 1 NEW_LINE num = num >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def combinedSum ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE c_sum = 0 NEW_LINE ran = ( 1 << n ) - 1 NEW_LINE for i in range ( ran + 1 ) : NEW_LINE INDENT c_sum += findSubSequence ( s , i ) NEW_LINE DEDENT return c_sum NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"123\" NEW_LINE print ( combinedSum ( s ) ) NEW_LINE DEDENT"} +{"text":"Longest subsequence where each character occurs at least k times | Python Program to find the subsequence with each character occurring at least k times in string s ; Function to find the subsequence ; Taking an extra array to keep record for character count in s ; Counting occurrences of all characters in str [ ] ; Printing characters with count >= k in same order as they appear in str . ; Driver code","code":"MAX_CHAR = 26 NEW_LINE def findSubsequence ( stri , k ) : NEW_LINE INDENT a = [ 0 ] * MAX_CHAR ; NEW_LINE for i in range ( len ( stri ) ) : NEW_LINE INDENT a [ ord ( stri [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( len ( stri ) ) : NEW_LINE INDENT if a [ ord ( stri [ i ] ) - ord ( ' a ' ) ] >= k : NEW_LINE INDENT print ( stri [ i ] , end = ' ' ) NEW_LINE DEDENT DEDENT DEDENT k = 2 NEW_LINE findSubsequence ( \" geeksforgeeks \" , k ) NEW_LINE"} +{"text":"gOOGLE cASE of a given sentence | Python3 program to convert a sentence to gOOGLE cASE . ; empty strings ; convert input string to upper case ; checki if character is not a space and adding it to string w ; converting first character to lower case and subsequent initial letter of another word to lower case ; Driver code","code":"def convert ( str ) : NEW_LINE INDENT w = \" \" NEW_LINE z = \" \" ; NEW_LINE str = str . upper ( ) + \" \u2581 \" ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT ch = str [ i ] ; NEW_LINE if ( ch != ' \u2581 ' ) : NEW_LINE INDENT w = w + ch ; NEW_LINE DEDENT else : NEW_LINE INDENT z = ( z + ( w [ 0 ] ) . lower ( ) + w [ 1 : len ( w ) ] + \" \u2581 \" ) ; NEW_LINE w = \" \" ; NEW_LINE DEDENT DEDENT return z ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" I \u2581 got \u2581 intern \u2581 at \u2581 geeksforgeeks \" ; NEW_LINE print ( convert ( str ) ) ; NEW_LINE DEDENT"} +{"text":"Encrypt string with product of number of vowels and consonants in substring of size k | isVowel ( ) is a function that returns true for a vowel and false otherwise . ; function to Encrypt the string ; cv to count vowel cc to count consonants ; Counting prefix count of vowel and prefix count of consonants ; generating the encrypted string . ; Driver Code","code":"def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def encryptString ( s , n , k ) : NEW_LINE INDENT cv = [ 0 for i in range ( n ) ] NEW_LINE cc = [ 0 for i in range ( n ) ] NEW_LINE if ( isVowel ( s [ 0 ] ) ) : NEW_LINE INDENT cv [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT cc [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT cv [ i ] = cv [ i - 1 ] + isVowel ( s [ i ] ) NEW_LINE cc [ i ] = cc [ i - 1 ] + ( isVowel ( s [ i ] ) == False ) NEW_LINE DEDENT ans = \" \" NEW_LINE prod = 0 NEW_LINE prod = cc [ k - 1 ] * cv [ k - 1 ] NEW_LINE ans += str ( prod ) NEW_LINE for i in range ( k , len ( s ) ) : NEW_LINE INDENT prod = ( ( cc [ i ] - cc [ i - k ] ) * ( cv [ i ] - cv [ i - k ] ) ) NEW_LINE ans += str ( prod ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" hello \" NEW_LINE n = len ( s ) NEW_LINE k = 2 NEW_LINE print ( encryptString ( s , n , k ) ) NEW_LINE DEDENT"} +{"text":"Count occurrences of a word in string | Python program to count the number of occurrence of a word in the given string ; split the string by spaces in a ; search for pattern in a ; if match found increase count ; Driver code","code":"def countOccurrences ( str , word ) : NEW_LINE INDENT a = str . split ( \" \u2581 \" ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , len ( a ) ) : NEW_LINE INDENT if ( word == a [ i ] ) : NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT str = \" GeeksforGeeks \u2581 A \u2581 computer \u2581 science \u2581 portal \u2581 for \u2581 geeks \u2581 \" NEW_LINE word = \" portal \" NEW_LINE print ( countOccurrences ( str , word ) ) NEW_LINE"} +{"text":"Program to find the initials of a name . | Python3 program to print initials of a name ; Split the string using ' space ' and print the first character of every word ; Driver code","code":"def printInitials ( name ) : NEW_LINE INDENT if ( len ( name ) == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT words = name . split ( \" \u2581 \" ) NEW_LINE for word in words : NEW_LINE INDENT print ( word [ 0 ] . upper ( ) , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT name = \" prabhat \u2581 kumar \u2581 singh \" NEW_LINE printInitials ( name ) NEW_LINE DEDENT"} +{"text":"Permute a string by changing case | Function to generate permutations ; Number of permutations is 2 ^ n ; Converting string to lower case ; Using all subsequences and permuting them ; If j - th bit is set , we convert it to upper case ; Printing current combination ; Driver code","code":"def permute ( inp ) : NEW_LINE INDENT n = len ( inp ) NEW_LINE mx = 1 << n NEW_LINE inp = inp . lower ( ) NEW_LINE for i in range ( mx ) : NEW_LINE INDENT combination = [ k for k in inp ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ( ( i >> j ) & 1 ) == 1 ) : NEW_LINE INDENT combination [ j ] = inp [ j ] . upper ( ) NEW_LINE DEDENT DEDENT temp = \" \" NEW_LINE for i in combination : NEW_LINE INDENT temp += i NEW_LINE DEDENT print temp , NEW_LINE DEDENT DEDENT permute ( \" ABC \" ) NEW_LINE"} +{"text":"Print the string after the specified character has occurred given no . of times | Function to print the string ; If given count is 0 print the given string and return ; Start traversing the string ; Increment occ if current char is equal to given character ; Break the loop if given character has been occurred given no . of times ; Print the string after the occurrence of given character given no . of times ; Otherwise string is empty ; Driver code","code":"def printString ( str , ch , count ) : NEW_LINE INDENT occ , i = 0 , 0 NEW_LINE if ( count == 0 ) : NEW_LINE INDENT print ( str ) NEW_LINE DEDENT for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] == ch ) : NEW_LINE INDENT occ += 1 NEW_LINE DEDENT if ( occ == count ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i < len ( str ) - 1 ) : NEW_LINE INDENT print ( str [ i + 1 : len ( str ) - i + 2 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Empty \u2581 string \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" geeks \u2581 for \u2581 geeks \" NEW_LINE printString ( str , ' e ' , 2 ) NEW_LINE DEDENT"} +{"text":"Reverse vowels in a given string | utility function to check for vowel ; Function to reverse order of vowels ; Start two indexes from two corners and move toward each other ; swapping ; Driver function","code":"def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' A ' or c == ' e ' or c == ' E ' or c == ' i ' or c == ' I ' or c == ' o ' or c == ' O ' or c == ' u ' or c == ' U ' ) NEW_LINE DEDENT def reverseVowel ( str ) : NEW_LINE INDENT i = 0 NEW_LINE j = len ( str ) - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if not isVowel ( str [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE continue NEW_LINE DEDENT if ( not isVowel ( str [ j ] ) ) : NEW_LINE INDENT j -= 1 NEW_LINE continue NEW_LINE DEDENT str [ i ] , str [ j ] = str [ j ] , str [ i ] NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return str NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" hello \u2581 world \" NEW_LINE print ( * reverseVowel ( list ( str ) ) , sep = \" \" ) NEW_LINE DEDENT"} +{"text":"Minimum number of palindromic subsequences to be removed to empty a binary string | A function to check if a string str is palindrome ; Start from leftmost and rightmost corners of str ; Keep comparing characters while they are same ; Returns count of minimum palindromic subseuqnces to be removed to make string empty ; If string is empty ; If string is palindrome ; If string is not palindrome ; Driver code","code":"def isPalindrome ( str ) : NEW_LINE INDENT l = 0 NEW_LINE h = len ( str ) - 1 NEW_LINE while ( h > l ) : NEW_LINE INDENT if ( str [ l ] != str [ h ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l = l + 1 NEW_LINE h = h - 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def minRemovals ( str ) : NEW_LINE INDENT if ( str [ 0 ] == ' ' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( isPalindrome ( str ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 2 NEW_LINE DEDENT print ( minRemovals ( \"010010\" ) ) NEW_LINE print ( minRemovals ( \"0100101\" ) ) NEW_LINE"} +{"text":"Find the value of XXXX ... . . ( N times ) % M where N is large | Iterative function to calculate ( x ^ y ) % p in O ( log y ) ; Initialize result ; Update x if it is >= p ; If y is odd , multiply x with result ; y must be even now y = y 2 ; Function to return XXX ... . . ( N times ) % M ; Return the mod by M of smaller numbers ; Creating a string of N X 's ; Converting the string to int and calculating the modulo ; Checking the parity of N ; Dividing the number into equal half ; Utilizing the formula for even N ; Dividing the number into equal half ; Utilizing the formula for odd N ; Driver code ; Print XXX ... ( N times ) % M","code":"def power ( x , y , p ) : NEW_LINE INDENT res = 1 ; NEW_LINE x = x % p ; NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y and 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 findModuloByM ( X , N , M ) : NEW_LINE INDENT if ( N < 6 ) : NEW_LINE INDENT temp = chr ( 48 + X ) * N NEW_LINE res = int ( temp ) % M ; NEW_LINE return res ; NEW_LINE DEDENT if ( N % 2 == 0 ) : NEW_LINE INDENT half = findModuloByM ( X , N \/\/ 2 , M ) % M ; NEW_LINE res = ( half * power ( 10 , N \/\/ 2 , M ) + half ) % M ; NEW_LINE return res ; NEW_LINE DEDENT else : NEW_LINE INDENT half = findModuloByM ( X , N \/\/ 2 , M ) % M ; NEW_LINE res = ( half * power ( 10 , N \/\/ 2 + 1 , M ) + half * 10 + X ) % M ; NEW_LINE return res ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT X = 6 ; N = 14 ; M = 9 ; NEW_LINE print ( findModuloByM ( X , N , M ) ) ; NEW_LINE DEDENT"} +{"text":"Check if two circles intersect such that the third circle passes through their points of intersections and centers | Python3 program for the above approach ; Structure of the circle ; Utility function to check if given circles satisfy required criteria ; Stores the distance between the centres of C1 and C2 ; Stores the status if the given given criteria is satisfied or not ; If C1C2 is less than the sum of the radii of the first 2 circles ; If C3 is the midpoint of the centres at C1 and C2 ; Mark flag true ; Return flag ; Function to check if the given circles satisfy required criteria ; Check for the current combination of circles ; Check for the next combination ; Driver Code","code":"from math import sqrt NEW_LINE class circle : NEW_LINE INDENT def __init__ ( self , a , b , c ) : NEW_LINE INDENT self . x = a NEW_LINE self . y = b NEW_LINE self . r = c NEW_LINE DEDENT DEDENT def check ( C ) : NEW_LINE INDENT C1C2 = sqrt ( ( C [ 1 ] . x - C [ 0 ] . x ) * ( C [ 1 ] . x - C [ 0 ] . x ) + ( C [ 1 ] . y - C [ 0 ] . y ) * ( C [ 1 ] . y - C [ 0 ] . y ) ) NEW_LINE flag = 0 NEW_LINE if ( C1C2 < ( C [ 0 ] . r + C [ 1 ] . r ) ) : NEW_LINE INDENT if ( ( C [ 0 ] . x + C [ 1 ] . x ) == 2 * C [ 2 ] . x and ( C [ 0 ] . y + C [ 1 ] . y ) == 2 * C [ 2 ] . y ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT return flag NEW_LINE DEDENT def IsFairTriplet ( c ) : NEW_LINE INDENT f = False NEW_LINE f |= check ( c ) NEW_LINE for i in range ( 2 ) : NEW_LINE INDENT c [ 0 ] , c [ 2 ] = c [ 2 ] , c [ 0 ] NEW_LINE f |= check ( c ) NEW_LINE DEDENT return f NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT C = [ circle ( 0 , 0 , 0 ) for i in range ( 3 ) ] NEW_LINE C [ 0 ] = circle ( 0 , 0 , 8 ) NEW_LINE C [ 1 ] = circle ( 0 , 10 , 6 ) NEW_LINE C [ 2 ] = circle ( 0 , 5 , 5 ) NEW_LINE if ( IsFairTriplet ( C ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Program to find the Eccentricity of a Hyperbola | Python3 program for the above approach ; Function to find the eccentricity of a hyperbola ; Stores the squared ratio of major axis to minor axis ; Increment r by 1 ; Return the square root of r ; Driver Code","code":"import math NEW_LINE def eccHyperbola ( A , B ) : NEW_LINE INDENT r = B * B \/ A * A NEW_LINE r += 1 NEW_LINE return math . sqrt ( r ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = 3.0 NEW_LINE B = 2.0 NEW_LINE print ( eccHyperbola ( A , B ) ) NEW_LINE DEDENT"} +{"text":"Calculate area of a cyclic quadrilateral with given side lengths | Python3 program for the above approach ; Function to find the area of cyclic quadrilateral ; Stores the value of half of the perimeter ; Stores area of cyclic quadrilateral ; Return the resultant area ; Driver Code","code":"from math import sqrt NEW_LINE def calculateArea ( A , B , C , D ) : NEW_LINE INDENT S = ( A + B + C + D ) \/\/ 2 NEW_LINE area = sqrt ( ( S - A ) * ( S - B ) * ( S - C ) * ( S - D ) ) NEW_LINE return area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 10 NEW_LINE B = 15 NEW_LINE C = 20 NEW_LINE D = 25 NEW_LINE print ( round ( calculateArea ( A , B , C , D ) , 3 ) ) NEW_LINE DEDENT"} +{"text":"Calculate ratio of area of a triangle inscribed in an Ellipse and the triangle formed by corresponding points on auxiliary circle | Function to calculate ratio of a triangle inscribed in an ellipse to the triangle on the auxiliary circle ; Stores the ratio of the semi - major to semi - minor axes ; Print the ratio ; Driver Code","code":"def triangleArea ( a , b ) : NEW_LINE INDENT ratio = b \/ a NEW_LINE print ( ratio ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 1 NEW_LINE b = 2 NEW_LINE triangleArea ( a , b ) NEW_LINE DEDENT"} +{"text":"Program to find the Excenters of a Triangle | Python3 program for the above approach ; Function to calculate the distance between a pair of points ; Function to calculate the coordinates of the excenters of a triangle ; Length of the sides of the triangle ; Stores the coordinates of the excenters of the triangle ; For I1 ; For I2 ; For I3 ; Print the excenters of the triangle ; Driver Code","code":"from math import sqrt NEW_LINE def distance ( m , n , p , q ) : NEW_LINE INDENT return ( sqrt ( pow ( n - m , 2 ) + pow ( q - p , 2 ) * 1.0 ) ) NEW_LINE DEDENT def Excenters ( x1 , y1 , x2 , y2 , x3 , y3 ) : NEW_LINE INDENT a = distance ( x2 , x3 , y2 , y3 ) NEW_LINE b = distance ( x3 , x1 , y3 , y1 ) NEW_LINE c = distance ( x1 , x2 , y1 , y2 ) NEW_LINE excenter = [ [ 0 , 0 ] for i in range ( 4 ) ] NEW_LINE excenter [ 1 ] [ 0 ] = ( ( - ( a * x1 ) + ( b * x2 ) + ( c * x3 ) ) \/\/ ( - a + b + c ) ) NEW_LINE excenter [ 1 ] [ 1 ] = ( ( - ( a * y1 ) + ( b * y2 ) + ( c * y3 ) ) \/\/ ( - a + b + c ) ) NEW_LINE excenter [ 2 ] [ 0 ] = ( ( ( a * x1 ) - ( b * x2 ) + ( c * x3 ) ) \/\/ ( a - b + c ) ) NEW_LINE excenter [ 2 ] [ 1 ] = ( ( ( a * y1 ) - ( b * y2 ) + ( c * y3 ) ) \/\/ ( a - b + c ) ) NEW_LINE excenter [ 3 ] [ 0 ] = ( ( ( a * x1 ) + ( b * x2 ) - ( c * x3 ) ) \/\/ ( a + b - c ) ) NEW_LINE excenter [ 3 ] [ 1 ] = ( ( ( a * y1 ) + ( b * y2 ) - ( c * y3 ) ) \/\/ ( a + b - c ) ) NEW_LINE for i in range ( 1 , 4 ) : NEW_LINE INDENT print ( int ( excenter [ i ] [ 0 ] ) , int ( excenter [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x1 = 0 NEW_LINE x2 = 3 NEW_LINE x3 = 0 NEW_LINE y1 = 0 NEW_LINE y2 = 0 NEW_LINE y3 = 4 NEW_LINE Excenters ( x1 , y1 , x2 , y2 , x3 , y3 ) NEW_LINE DEDENT"} +{"text":"Program to find height of a Trapezoid | Python3 program to implement the above approach ; Function to calculate height of the trapezoid ; Apply Heron 's formula ; Calculate the area ; Calculate height of trapezoid ; Prthe height ; Given a , b , p1 and p2","code":"import math NEW_LINE def findHeight ( p1 , p2 , b , c ) : NEW_LINE INDENT a = max ( p1 , p2 ) - min ( p1 , p2 ) NEW_LINE s = ( a + b + c ) \/\/ 2 NEW_LINE area = math . sqrt ( s * ( s - a ) * ( s - b ) * ( s - c ) ) NEW_LINE height = ( area * 2 ) \/ a NEW_LINE print ( \" Height \u2581 is : \u2581 \" , height ) NEW_LINE DEDENT p1 = 25 NEW_LINE p2 = 10 NEW_LINE a = 14 NEW_LINE b = 13 NEW_LINE findHeight ( p1 , p2 , a , b ) NEW_LINE"} +{"text":"Icositetragonal Number | Function to find Icositetragonal number ; Formula to calculate nth Icositetragonal number ; Driver Code","code":"def Icositetragonal_num ( n ) : NEW_LINE INDENT return ( 22 * n * n - 20 * n ) \/ 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( Icositetragonal_num ( n ) ) ) NEW_LINE n = 10 NEW_LINE print ( int ( Icositetragonal_num ( n ) ) ) NEW_LINE"} +{"text":"Area of circle inscribed in a Isosceles Trapezoid | Function to find area of circle inscribed in a trapezoid having non - parallel sides m , n ; radius of circle by the formula i . e . root ( m * n ) \/ 2 area of circle = ( 3.141 ) * ( R * * 2 ) ; Driver Code","code":"def area_of_circle ( m , n ) : NEW_LINE INDENT square_of_radius = ( m * n ) \/ 4 NEW_LINE area = ( 3.141 * square_of_radius ) NEW_LINE return area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE m = 30 NEW_LINE print ( area_of_circle ( m , n ) ) NEW_LINE DEDENT"} +{"text":"Area of Equilateral triangle inscribed in a Circle of radius R | Function to find the area of equilateral triangle inscribed in a circle of radius R ; Base and Height of equilateral triangle ; Area using Base and Height ; Driver Code","code":"def area ( R ) : NEW_LINE INDENT base = 1.732 * R NEW_LINE height = ( 3 \/ 2 ) * R NEW_LINE area = ( ( 1 \/ 2 ) * base * height ) NEW_LINE return area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT R = 7 NEW_LINE print ( area ( R ) ) NEW_LINE DEDENT"} +{"text":"Area of largest Circle that can be inscribed in a SemiCircle | Function to find the area of the circle ; Radius cannot be negative ; Area of the largest circle ; Driver code","code":"def circlearea ( R ) : NEW_LINE INDENT if ( R < 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT a = ( 3.14 * R * R ) \/ 4 ; NEW_LINE return a ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT R = 2 ; NEW_LINE print ( circlearea ( R ) ) ; NEW_LINE DEDENT"} +{"text":"Number of pairs of lines having integer intersection points | Count number of pairs of lines having eger ersection po ; Initialize arrays to store counts ; Count number of odd and even Pi ; Count number of odd and even Qi ; Return the count of pairs ; Driver code","code":"def countPairs ( P , Q , N , M ) : NEW_LINE INDENT A = [ 0 ] * 2 NEW_LINE B = [ 0 ] * 2 NEW_LINE for i in range ( N ) : NEW_LINE INDENT A [ P [ i ] % 2 ] += 1 NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT B [ Q [ i ] % 2 ] += 1 NEW_LINE DEDENT return ( A [ 0 ] * B [ 0 ] + A [ 1 ] * B [ 1 ] ) NEW_LINE DEDENT P = [ 1 , 3 , 2 ] NEW_LINE Q = [ 3 , 0 ] NEW_LINE N = len ( P ) NEW_LINE M = len ( Q ) NEW_LINE print ( countPairs ( P , Q , N , M ) ) NEW_LINE"} +{"text":"Maximum number of line intersections formed through intersection of N planes | Function to count maximum number of intersections possible ; Driver Code","code":"def countIntersections ( n ) : NEW_LINE INDENT return n * ( n - 1 ) \/\/ 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( countIntersections ( n ) ) NEW_LINE"} +{"text":"Area of a Regular Pentagram | Python3 implementation of the approach ; Function to return the area of triangle BCD ; Using Golden ratio ; Calculate area of triangle BCD ; Return area of all 5 triangles are the same ; Function to return the area of regular pentagon ; Calculate the area of regular pentagon using above formula ; Return area of regular pentagon ; Function to return the area of pentagram ; Area of a pentagram is equal to the area of regular pentagon and five times the area of Triangle ; Driver code","code":"import math NEW_LINE PI = 3.14159 NEW_LINE def areaOfTriangle ( d ) : NEW_LINE INDENT c = 1.618 * d NEW_LINE s = ( d + c + c ) \/ 2 NEW_LINE area = math . sqrt ( s * ( s - c ) * ( s - c ) * ( s - d ) ) NEW_LINE return 5 * area NEW_LINE DEDENT def areaOfRegPentagon ( d ) : NEW_LINE INDENT global PI NEW_LINE cal = 4 * math . tan ( PI \/ 5 ) NEW_LINE area = ( 5 * d * d ) \/ cal NEW_LINE return area NEW_LINE DEDENT def areaOfPentagram ( d ) : NEW_LINE INDENT return areaOfRegPentagon ( d ) + areaOfTriangle ( d ) NEW_LINE DEDENT d = 5 NEW_LINE print ( areaOfPentagram ( d ) ) NEW_LINE"} +{"text":"Angle subtended by the chord to center of the circle when the angle subtended by the another equal chord of a congruent circle is given | Python 3 program to find the angle subtended by the chord to the centre of the circle when the angle subtended by another equal chord of a congruent circle is given ; Driver code","code":"def anglequichord ( z ) : NEW_LINE INDENT print ( \" The \u2581 angle \u2581 is \u2581 \" , z , \" \u2581 degrees \" ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT z = 48 NEW_LINE anglequichord ( z ) NEW_LINE DEDENT"} +{"text":"Program to print ASCII Value of all digits of a given number | Function to convert digits of N to respective ASCII values ; Driver Code","code":"def convertToASCII ( N ) : NEW_LINE INDENT num = str ( N ) NEW_LINE i = 0 NEW_LINE for ch in num : NEW_LINE INDENT print ( ch , \" ( \" , ord ( ch ) , \" ) \" ) NEW_LINE DEDENT DEDENT N = 36 NEW_LINE convertToASCII ( N ) NEW_LINE"} +{"text":"A Product Array Puzzle | Set 3 | Python 3 program for the above approach ; Function to form product array with O ( n ) time and O ( 1 ) space ; Stores the product of array ; Stores the count of zeros ; Traverse the array ; If arr [ i ] is not zero ; If arr [ i ] is zero then increment count of z by 1 ; Stores the absolute value of the product ; If Z is equal to 1 ; If arr [ i ] is not zero ; Else ; If count of 0 s at least 2 ; Assign arr [ i ] = 0 ; Store absolute value of arr [ i ] ; Find the value of a \/ b ; If arr [ i ] and product both are less than zero ; If arr [ i ] and product both are greater than zero ; Else ; Traverse the array arr [ ] ; Driver Code ; Function Call","code":"import math NEW_LINE def productExceptSelf ( arr , N ) : NEW_LINE INDENT product = 1 NEW_LINE z = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT product *= arr [ i ] NEW_LINE DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT z += 1 NEW_LINE DEDENT DEDENT a = abs ( product ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( z == 1 ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = product NEW_LINE DEDENT continue NEW_LINE DEDENT elif ( z > 1 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE continue NEW_LINE DEDENT b = abs ( arr [ i ] ) NEW_LINE curr = round ( math . exp ( math . log ( a ) - math . log ( b ) ) ) NEW_LINE if ( arr [ i ] < 0 and product < 0 ) : NEW_LINE INDENT arr [ i ] = curr NEW_LINE DEDENT elif ( arr [ i ] > 0 and product > 0 ) : NEW_LINE INDENT arr [ i ] = curr NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = - 1 * curr NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 10 , 3 , 5 , 6 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE productExceptSelf ( arr , N ) NEW_LINE"} +{"text":"Count subarrays made up of single | Function to count of subarrays made up of single digit integers only ; Stores count of subarrays ; Stores the count of consecutive single digit numbers in the array ; Traverse the array ; Increment size of block by 1 ; Increment res by count ; Assign count = 0 ; Driver Code ; Given array ; Size of the array","code":"def singleDigitSubarrayCount ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] <= 9 ) : NEW_LINE INDENT count += 1 NEW_LINE res += count NEW_LINE DEDENT else : NEW_LINE INDENT count = 0 NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 14 , 2 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE singleDigitSubarrayCount ( arr , N ) NEW_LINE DEDENT"} +{"text":"Count integers up to N which can be represented as sum of two or more consecutive numbers | Function to check if the number N can be expressed as sum of 2 or more consecutive numbers or not ; Function to count integers in the range [ 1 , N ] that can be expressed as sum of 2 or more consecutive numbers ; Stores the required count ; Driver Code","code":"def isPossible ( N ) : NEW_LINE INDENT return ( ( N & ( N - 1 ) ) and N ) NEW_LINE DEDENT def countElements ( N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( isPossible ( i ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 NEW_LINE countElements ( N ) NEW_LINE DEDENT"} +{"text":"Count integers up to N which can be represented as sum of two or more consecutive numbers | Function to count integers in the range [ 1 , N ] that can be expressed as sum of 2 or more consecutive numbers ; Count powers of 2 up to N ; Increment count ; Update current power of 2 ; Driver Code","code":"def countElements ( N ) : NEW_LINE INDENT Cur_Ele = 1 NEW_LINE Count = 0 NEW_LINE while ( Cur_Ele <= N ) : NEW_LINE INDENT Count += 1 NEW_LINE Cur_Ele = Cur_Ele * 2 NEW_LINE DEDENT print ( N - Count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 NEW_LINE countElements ( N ) NEW_LINE DEDENT"} +{"text":"Maximum difference between a pair of adjacent elements by excluding every element once | Python 3 program for the above approach ; Function to calculate maximum difference between adjacent elements excluding every array element once ; Compute maximum adjacent difference for whole array ; Store the maximum between arr_max and curr_max ; Append the result into a vector ; Print the result ; Driver Code","code":"import sys NEW_LINE def maxAdjacent ( arr , N ) : NEW_LINE INDENT res = [ ] NEW_LINE arr_max = - sys . maxsize - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT arr_max = max ( arr_max , abs ( arr [ i - 1 ] - arr [ i ] ) ) NEW_LINE DEDENT for i in range ( 1 , N - 1 ) : NEW_LINE INDENT curr_max = abs ( arr [ i - 1 ] - arr [ i + 1 ] ) NEW_LINE ans = max ( curr_max , arr_max ) NEW_LINE res . append ( ans ) NEW_LINE DEDENT for x in res : NEW_LINE INDENT print ( x , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 7 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE maxAdjacent ( arr , N ) NEW_LINE DEDENT"} +{"text":"Minimize increments required to make count of even and odd array elements equal | Function to find min operations to make even and odd count equal ; Odd size will never make odd and even counts equal ; Stores the count of even numbers in the array arr [ ] ; Stores count of odd numbers in the array arr [ ] ; Traverse the array arr [ ] ; If arr [ i ] is an even number ; Update cntEven ; Odd numbers in arr [ ] ; Return absolute difference divided by 2 ; Driver Code ; Function call","code":"def minimumIncrement ( arr , N ) : NEW_LINE INDENT if ( N % 2 != 0 ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE return NEW_LINE DEDENT cntEven = 0 NEW_LINE 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 DEDENT cntOdd = N - cntEven NEW_LINE return abs ( cntEven - cntOdd ) \/\/ 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimumIncrement ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Count ways to construct array with even product from given array such that absolute difference of same indexed elements is at most 1 | Function to find count the ways to construct an array , B [ ] such that abs ( A [ i ] - B [ i ] ) <= 1 and product of elements of B [ ] is even ; Stores count of arrays B [ ] such that abs ( A [ i ] - B [ i ] ) <= 1 ; Stores count of arrays B [ ] whose product of elements is not even ; Traverse the array ; Update total ; If A [ i ] is an even number ; Update oddArray ; Print 3 ^ N - 2 ^ X ; Driver Code","code":"def cntWaysConsArray ( A , N ) : NEW_LINE INDENT total = 1 ; NEW_LINE oddArray = 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT total = total * 3 ; NEW_LINE if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT oddArray *= 2 ; NEW_LINE DEDENT DEDENT print ( total - oddArray ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 2 , 4 ] ; NEW_LINE N = len ( A ) ; NEW_LINE cntWaysConsArray ( A , N ) ; NEW_LINE DEDENT"} +{"text":"Count numbers up to N whose rightmost set bit is K | Function to count the numbers in the range [ 1 , N ] whose rightmost set bit is K ; Stores the number whose rightmost set bit is K ; Numbers whose rightmost set bit is i ; Subtracting the number whose rightmost set bit is i , from N ; Since i = k , then the number whose rightmost set bit is K is stored ; Driver Code","code":"def countNumberHavingKthBitSet ( N , K ) : NEW_LINE INDENT numbers_rightmost_setbit_K = 0 NEW_LINE for i in range ( 1 , K + 1 ) : NEW_LINE INDENT numbers_rightmost_bit_i = ( N + 1 ) \/\/ 2 NEW_LINE N -= numbers_rightmost_bit_i NEW_LINE if ( i == K ) : NEW_LINE INDENT numbers_rightmost_setbit_K = numbers_rightmost_bit_i NEW_LINE DEDENT DEDENT print ( numbers_rightmost_setbit_K ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 NEW_LINE K = 2 NEW_LINE countNumberHavingKthBitSet ( N , K ) NEW_LINE DEDENT"} +{"text":"Count odd and even Binomial Coefficients of N | Function to count set bits in binary representation of number N ; Count set bits in N ; Return the final count ; Driver Code ; Print odd Binomial coefficients ; Print even Binomial coefficients","code":"def countSetBits ( N : int ) -> int : NEW_LINE INDENT count = 0 NEW_LINE while ( N ) : NEW_LINE INDENT N = N & ( N - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 NEW_LINE bits = countSetBits ( N ) NEW_LINE print ( \" Odd \u2581 : \u2581 { } \" . format ( pow ( 2 , bits ) ) ) NEW_LINE print ( \" Even \u2581 : \u2581 { } \" . format ( N + 1 - pow ( 2 , bits ) ) ) NEW_LINE DEDENT"} +{"text":"Make all array elements even by replacing any pair of array elements with their sum | Function to find the minimum number of replacements required to make all array elements even ; Stores the count of odd elements ; Traverse the array ; Increase count of odd elements ; Store number of replacements required ; Two extra moves will be required to make the last odd element even ; Prthe minimum replacements ; Driver Code ; Function call","code":"def minMoves ( arr , N ) : NEW_LINE INDENT odd_element_cnt = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 != 0 ) : NEW_LINE INDENT odd_element_cnt += 1 ; NEW_LINE DEDENT DEDENT moves = ( odd_element_cnt ) \/\/ 2 ; NEW_LINE if ( odd_element_cnt % 2 != 0 ) : NEW_LINE INDENT moves += 2 ; NEW_LINE DEDENT print ( moves ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 6 , 3 , 7 , 20 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE minMoves ( arr , N ) ; NEW_LINE DEDENT"} +{"text":"Split squares of first N natural numbers into two sets with minimum absolute difference of their sums | Function to partition squares of N natural number in two subset ; Store the count of blocks of size 8 ; Partition of block of 8 element ; Store the minimum subset difference ; Partition of N elements to minimize their subset sum difference ; Store elements of subset A and B ; If element is of type A ; If the element is of type B ; Print the minimum subset difference ; Print the first subset ; Print the second subset ; Driver Code ; Function call","code":"def minimumSubsetDifference ( N ) : NEW_LINE INDENT blockOfSize8 = N \/\/ 8 NEW_LINE str = \" ABBABAAB \" NEW_LINE subsetDifference = 0 NEW_LINE partition = \" \" NEW_LINE while blockOfSize8 != 0 : NEW_LINE INDENT partition = partition + str NEW_LINE blockOfSize8 = blockOfSize8 - 1 NEW_LINE DEDENT A = [ ] NEW_LINE B = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if partition [ i ] == ' A ' : NEW_LINE INDENT A . append ( ( i + 1 ) * ( i + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT B . append ( ( i + 1 ) * ( i + 1 ) ) NEW_LINE DEDENT DEDENT print ( subsetDifference ) NEW_LINE for i in A : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE for i in B : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT N = 8 NEW_LINE minimumSubsetDifference ( N ) NEW_LINE"} +{"text":"Largest divisor of a number not divisible by another given number | Python3 program to implement the above approach ; Function to find the largest number X such that it divides P but is not divisible by Q ; Stores the frequency count of of all Prime Factors ; Increment the frequency of the current prime factor ; If Q is a prime factor ; Stores the desired result ; Iterate through all divisors of Q ; Stores the frequency count of current prime divisor on dividing P ; Count the frequency of the current prime factor ; If cur is less than frequency then P is the final result ; Iterate to get temporary answer ; Update current answer ; Print the desired result ; Driver Code ; Given P and Q ; Function Call","code":"from collections import defaultdict NEW_LINE def findTheGreatestX ( P , Q ) : NEW_LINE INDENT divisiors = defaultdict ( int ) NEW_LINE i = 2 NEW_LINE while i * i <= Q : NEW_LINE INDENT while ( Q % i == 0 and Q > 1 ) : NEW_LINE INDENT Q \/\/= i NEW_LINE divisiors [ i ] += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( Q > 1 ) : NEW_LINE INDENT divisiors [ Q ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in divisiors : NEW_LINE INDENT frequency = divisiors [ i ] NEW_LINE temp = P NEW_LINE cur = 0 NEW_LINE while ( temp % i == 0 ) : NEW_LINE INDENT temp \/\/= i NEW_LINE cur += 1 NEW_LINE DEDENT if ( cur < frequency ) : NEW_LINE INDENT ans = P NEW_LINE break NEW_LINE DEDENT temp = P NEW_LINE for j in range ( cur , frequency - 1 , - 1 ) : NEW_LINE INDENT temp \/\/= i NEW_LINE DEDENT ans = max ( temp , ans ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT P = 10 NEW_LINE Q = 4 NEW_LINE findTheGreatestX ( P , Q ) NEW_LINE DEDENT"} +{"text":"Check if rows of a Matrix can be rearranged to make Bitwise XOR of first column non | Function to check if there is any row where number of unique elements are greater than 1 ; Iterate over the matrix ; Function to check if it is possible to rearrange mat [ ] [ ] such that XOR of its first column is non - zero ; Find bitwise XOR of the first column of mat [ ] [ ] ; If bitwise XOR of the first column of mat [ ] [ ] is non - zero ; Otherwise check rearrangements ; Driver Code ; Given Matrix mat [ ] [ ] ; Function Call","code":"def checkRearrangements ( mat , N , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , M ) : NEW_LINE INDENT if ( mat [ i ] [ 0 ] != mat [ i ] [ j ] ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT DEDENT DEDENT return \" No \" NEW_LINE DEDENT def nonZeroXor ( mat , N , M ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT res = res ^ mat [ i ] [ 0 ] NEW_LINE DEDENT if ( res != 0 ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT return checkRearrangements ( mat , N , M ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT mat = [ [ 1 , 1 , 2 ] , [ 2 , 2 , 2 ] , [ 3 , 3 , 3 ] ] NEW_LINE N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE print ( nonZeroXor ( mat , N , M ) ) NEW_LINE DEDENT"} +{"text":"Maximize Bitwise AND of first element with complement of remaining elements for any permutation of given Array | Function to maximize the value for the given function and the array elements ; Vector array to maintain which bit is set for which integer in the given array by saving index of that integer ; Check if j - th bit is set for i - th integer ; Push the index of that integer in setBit [ j ] ; Find the element having highest significant set bit unset in other elements ; Place that integer at 0 - th index ; Store the maximum AND value ; Return the answer ; Driver Code ; Function call","code":"def functionMax ( arr , n ) : NEW_LINE INDENT setBit = [ [ ] for i in range ( 32 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 32 ) : NEW_LINE INDENT if ( arr [ i ] & ( 1 << j ) ) : NEW_LINE INDENT setBit [ j ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT i = 31 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( len ( setBit [ i ] ) == 1 ) : NEW_LINE INDENT temp = arr [ 0 ] NEW_LINE arr [ 0 ] = arr [ setBit [ i ] [ 0 ] ] NEW_LINE arr [ setBit [ i ] [ 0 ] ] = temp NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT maxAnd = arr [ 0 ] NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT maxAnd = ( maxAnd & ( ~ arr [ i ] ) ) NEW_LINE DEDENT return maxAnd NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE print ( functionMax ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Sum of all products of the Binomial Coefficients of two numbers up to K | Function returns nCr i . e . Binomial Coefficient ; Initialize res with 1 ; Since C ( n , r ) = C ( n , n - r ) ; Evaluating expression ; Function to calculate and return the sum of the products ; Initialize sum to 0 ; Traverse from 0 to k ; Driver code","code":"def nCr ( n , r ) : NEW_LINE INDENT res = 1 NEW_LINE if r > n - r : NEW_LINE INDENT r = n - r NEW_LINE DEDENT for i in range ( r ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res \/= ( i + 1 ) NEW_LINE DEDENT return res ; NEW_LINE DEDENT def solve ( n , m , k ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( k + 1 ) : NEW_LINE INDENT sum += nCr ( n , i ) * nCr ( m , k - i ) NEW_LINE DEDENT return int ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE m = 2 NEW_LINE k = 2 ; NEW_LINE print ( solve ( n , m , k ) ) NEW_LINE DEDENT"} +{"text":"Fast Exponention using Bit Manipulation | Function to return a ^ n ; Stores final answer ; Check if current LSB is set ; Right shift ; Driver code","code":"def powerOptimised ( a , n ) : NEW_LINE INDENT ans = 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT last_bit = ( n & 1 ) NEW_LINE if ( last_bit ) : NEW_LINE INDENT ans = ans * a NEW_LINE DEDENT a = a * a NEW_LINE n = n >> 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 3 NEW_LINE n = 5 NEW_LINE print ( powerOptimised ( a , n ) ) NEW_LINE DEDENT"} +{"text":"Find M such that GCD of M and given number N is maximum | Function to find the integer M such that gcd ( N , M ) is maximum ; Initialize variables ; Find all the divisors of N and return the maximum divisor ; Check if i is divisible by N ; Update max_gcd ; Return the maximum value ; Driver Code ; Given number ; Function call","code":"def findMaximumGcd ( n ) : NEW_LINE INDENT max_gcd = 1 NEW_LINE i = 1 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if ( i > max_gcd ) : NEW_LINE INDENT max_gcd = i NEW_LINE DEDENT if ( ( n \/ i != i ) and ( n \/ i != n ) and ( ( n \/ i ) > max_gcd ) ) : NEW_LINE INDENT max_gcd = n \/ i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return ( int ( max_gcd ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE print ( findMaximumGcd ( n ) ) NEW_LINE DEDENT"} +{"text":"First element of every K sets having consecutive elements with exactly K prime factors less than N | Python3 program for the above approach ; For storing smallest prime factor ; Function construct smallest prime factor array ; Mark smallest prime factor for every number to be itself ; separately mark spf for every even number as 2 ; Check if i is prime ; Mark SPF for all numbers divisible by i ; Mark spf [ i ] if it is not previously marked ; Function for counts total number of prime factors ; Function to print elements of sets of K consecutive elements having K prime factors ; To store the result ; Count number of prime factors of number ; If number has exactly K factors puch in result [ ] ; Iterate till we get K consecutive elements in result [ ] ; Count sequence until K ; Print the element if count >= K ; Driver Code ; To construct spf [ ] ; Given N and K ; Function call","code":"x = 2000021 NEW_LINE v = [ 0 ] * x NEW_LINE def sieve ( ) : NEW_LINE INDENT v [ 1 ] = 1 NEW_LINE for i in range ( 2 , x ) : NEW_LINE INDENT v [ i ] = i NEW_LINE DEDENT for i in range ( 4 , x , 2 ) : NEW_LINE INDENT v [ i ] = 2 NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i < x ) : NEW_LINE INDENT if ( v [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , x , i ) : NEW_LINE INDENT if ( v [ j ] == j ) : NEW_LINE INDENT v [ j ] = i NEW_LINE DEDENT DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def prime_factors ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE while ( n != 1 ) : NEW_LINE INDENT s . add ( v [ n ] ) NEW_LINE n = n \/\/ v [ n ] NEW_LINE DEDENT return len ( s ) NEW_LINE DEDENT def distinctPrimes ( m , k ) : NEW_LINE INDENT result = [ ] NEW_LINE for i in range ( 14 , m + k ) : NEW_LINE INDENT count = prime_factors ( i ) NEW_LINE if ( count == k ) : NEW_LINE INDENT result . append ( i ) NEW_LINE DEDENT DEDENT p = len ( result ) NEW_LINE for index in range ( p - 1 ) : NEW_LINE INDENT element = result [ index ] NEW_LINE count = 1 NEW_LINE z = index NEW_LINE while ( z < p - 1 and count <= k and result [ z ] + 1 == result [ z + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE z += 1 NEW_LINE DEDENT if ( count >= k ) : NEW_LINE INDENT print ( element , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sieve ( ) NEW_LINE N = 1000 NEW_LINE K = 3 NEW_LINE distinctPrimes ( N , K ) NEW_LINE DEDENT"} +{"text":"Product of Complex Numbers using three Multiplication Operation | Function to multiply Complex Numbers with just three multiplications ; Find value of prod1 , prod2 and prod3 ; Real part ; Imaginary part ; Print the result ; Given four numbers ; Function call","code":"def print_product ( a , b , c , d ) : NEW_LINE INDENT prod1 = a * c NEW_LINE prod2 = b * d NEW_LINE prod3 = ( a + b ) * ( c + d ) NEW_LINE real = prod1 - prod2 NEW_LINE imag = prod3 - ( prod1 + prod2 ) NEW_LINE print ( real , \" \u2581 + \u2581 \" , imag , \" i \" ) NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE c = 4 NEW_LINE d = 5 NEW_LINE print_product ( a , b , c , d ) NEW_LINE"} +{"text":"Insolite Numbers | Function to check if a number is an Insolite numbers ; To store sum of squares of digits ; To store product of squares of digits ; extracting digit ; Driver Code ; Function Call","code":"def isInsolite ( n ) : NEW_LINE INDENT N = n ; NEW_LINE sum = 0 ; NEW_LINE product = 1 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT r = n % 10 ; NEW_LINE sum = sum + r * r ; NEW_LINE product = product * r * r ; NEW_LINE n = n \/\/ 10 ; NEW_LINE DEDENT return ( ( N % sum == 0 ) and ( N % product == 0 ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 111 ; NEW_LINE if ( isInsolite ( N ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT DEDENT"} +{"text":"D Numbers | Python3 implementation for the above approach ; Function to find the N - th icosikaipentagon number ; number should be greater than 3 ; Check every k in range 2 to n - 1 ; condition for D - Number ; Driver code","code":"import math NEW_LINE def isDNum ( n ) : NEW_LINE INDENT if n < 4 : NEW_LINE INDENT return False NEW_LINE DEDENT for k in range ( 2 , n ) : NEW_LINE INDENT numerator = pow ( k , n - 2 ) - k NEW_LINE hcf = math . gcd ( n , k ) NEW_LINE if ( hcf == 1 and ( numerator % n ) != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT n = 15 NEW_LINE if isDNum ( n ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Ruth | Function to find prime divisors of all numbers from 1 to N ; If the number is prime ; Add this prime to all it 's multiples ; Function to check Ruth - Aaron number ; Driver code","code":"def Sum ( N ) : NEW_LINE INDENT SumOfPrimeDivisors = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( SumOfPrimeDivisors [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i , N + 1 , i ) : NEW_LINE INDENT SumOfPrimeDivisors [ j ] += i NEW_LINE DEDENT DEDENT DEDENT return SumOfPrimeDivisors [ N ] NEW_LINE DEDENT def RuthAaronNumber ( n ) : NEW_LINE INDENT if ( Sum ( n ) == Sum ( n + 1 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT N = 714 NEW_LINE if ( RuthAaronNumber ( N ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Maximize sum of absolute difference between adjacent elements in Array with sum K | Function for maximising the sum ; Difference is 0 when only one element is present in array ; Difference is K when two elements are present in array ; Otherwise ; Driver code","code":"def maxAdjacentDifference ( N , K ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return K ; NEW_LINE DEDENT return 2 * K ; NEW_LINE DEDENT N = 6 ; NEW_LINE K = 11 ; NEW_LINE print ( maxAdjacentDifference ( N , K ) ) ; NEW_LINE"} +{"text":"Sum of all divisors from 1 to N | Set 2 | Python3 program for the above approach ; Functions returns sum of numbers from 1 to n ; Functions returns sum of numbers from a + 1 to b ; Function returns total sum of divisors ; Stores total sum ; Finding numbers and its occurence ; Sum of product of each number and its occurence ; Driver code","code":"mod = 1000000007 NEW_LINE def linearSum ( n ) : NEW_LINE INDENT return n * ( n + 1 ) \/\/ 2 % mod NEW_LINE DEDENT def rangeSum ( b , a ) : NEW_LINE INDENT return ( linearSum ( b ) - ( linearSum ( a ) ) ) % mod NEW_LINE DEDENT def totalSum ( n ) : NEW_LINE INDENT result = 0 NEW_LINE i = 1 NEW_LINE while True : NEW_LINE INDENT result += rangeSum ( n \/\/ i , n \/\/ ( i + 1 ) ) * ( i % mod ) % mod ; NEW_LINE result %= mod ; NEW_LINE if i == n : NEW_LINE INDENT break NEW_LINE DEDENT i = n \/\/ ( n \/\/ ( i + 1 ) ) NEW_LINE DEDENT return result NEW_LINE DEDENT N = 4 NEW_LINE print ( totalSum ( N ) ) NEW_LINE N = 12 NEW_LINE print ( totalSum ( N ) ) NEW_LINE"} +{"text":"Nontrivial undulant Numbers | Function to check if a string is double string or not ; a and b should not be equal ; Condition to check if length is odd make length even ; First half of s ; Second half of s ; Double string if first and last half are equal ; Function to check if N is an Nontrivial undulant number ; Driver Code","code":"def isDouble ( num ) : NEW_LINE INDENT s = str ( num ) NEW_LINE l = len ( s ) NEW_LINE if ( s [ 0 ] == s [ 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( l % 2 == 1 ) : NEW_LINE INDENT s = s + s [ 1 ] NEW_LINE l += 1 NEW_LINE DEDENT s1 = s [ : l \/\/ 2 ] NEW_LINE s2 = s [ l \/\/ 2 : ] NEW_LINE return s1 == s2 NEW_LINE DEDENT def isNontrivialUndulant ( N ) : NEW_LINE INDENT return N > 100 and isDouble ( N ) NEW_LINE DEDENT n = 121 NEW_LINE if ( isNontrivialUndulant ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Megagon number | Function to find the nth Megagon Number ; Driver Code","code":"def MegagonNum ( n ) : NEW_LINE INDENT return ( 999998 * n * n - 999996 * n ) \/\/ 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( MegagonNum ( n ) ) ; NEW_LINE"} +{"text":"Product of all the pairs from the given array | Python3 implementation to find the product of all the pairs from the given array ; Function to return the product of the elements of all possible pairs from the array ; To store the required product ; Nested loop to calculate all possible pairs ; Multiply the product of the elements of the current pair ; Return the final result ; Driver code","code":"mod = 1000000007 ; NEW_LINE def productPairs ( arr , n ) : NEW_LINE INDENT product = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT product *= ( arr [ i ] % mod * arr [ j ] % mod ) % mod ; NEW_LINE product = product % mod ; NEW_LINE DEDENT DEDENT return product % mod ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( productPairs ( arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Product of all the pairs from the given array | Python3 implementation to Find the product of all the pairs from the given array ; Function to calculate ( x ^ y ) % 1000000007 ; Initialize result ; Update x if it is more than or equal to p ; If y is odd , multiply x with result ; Return the final result ; Function to return the product of the elements of all possible pairs from the array ; To store the required product ; Iterate for every element of the array ; Each element appears ( 2 * n ) times ; Driver code","code":"mod = 1000000007 NEW_LINE def power ( x , y ) : NEW_LINE INDENT p = 1000000007 NEW_LINE res = 1 NEW_LINE x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( ( y & 1 ) != 0 ) : 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 productPairs ( arr , n ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT product = ( product % mod * ( int ) ( power ( arr [ i ] , ( 2 * n ) ) ) % mod ) % mod NEW_LINE DEDENT return ( product % mod ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( productPairs ( arr , n ) ) NEW_LINE"} +{"text":"Construct an Array such that cube sum of all element is a perfect square | Function to create and print the array ; Initialise the array of size N ; Print the array ; Driver code","code":"def constructArray ( N ) : NEW_LINE INDENT arr = [ 0 ] * N NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT arr [ i - 1 ] = i ; NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = \" , \u2581 \" ) NEW_LINE DEDENT DEDENT N = 6 ; NEW_LINE constructArray ( N ) ; NEW_LINE"} +{"text":"Count of all subsequence whose product is a Composite number | Function to check whether a number is prime or not ; Function to find number of subsequences whose product is a composite number ; Find total non empty subsequence ; Find count of prime number and ones ; Calculate the non empty one subsequence ; Find count of composite subsequence ; Driver code","code":"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 countSubsequences ( arr , n ) : NEW_LINE INDENT totalSubsequence = ( int ) ( pow ( 2 , n ) - 1 ) ; NEW_LINE countPrime = 0 ; NEW_LINE countOnes = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT countOnes += 1 ; NEW_LINE DEDENT elif ( isPrime ( arr [ i ] ) ) : NEW_LINE INDENT countPrime += 1 ; NEW_LINE DEDENT DEDENT compositeSubsequence = 0 ; NEW_LINE onesSequence = ( int ) ( pow ( 2 , countOnes ) - 1 ) ; NEW_LINE compositeSubsequence = ( totalSubsequence - countPrime - onesSequence - onesSequence * countPrime ) ; NEW_LINE return compositeSubsequence ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countSubsequences ( arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Find K consecutive integers such that their sum is N | Function to check if a number can be expressed as the sum of k consecutive ; Finding the first term of AP ; Checking if first term is an integer ; Loop to print the K consecutive integers ; Driver Code","code":"def checksum ( n , k ) : NEW_LINE INDENT first_term = ( ( 2 * n ) \/ k + ( 1 - k ) ) \/ 2.0 NEW_LINE if ( first_term - int ( first_term ) == 0 ) : NEW_LINE INDENT for i in range ( int ( first_term ) , int ( first_term ) + k ) : NEW_LINE INDENT print ( i , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( ' - 1' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ( n , k ) = ( 33 , 6 ) NEW_LINE checksum ( n , k ) NEW_LINE DEDENT"} +{"text":"Represent N as sum of K even numbers | Function to print the representation ; N must be greater than equal to 2 * K and must be even ; Driver Code","code":"def sumEvenNumbers ( N , K ) : NEW_LINE INDENT check = N - 2 * ( K - 1 ) NEW_LINE if ( check > 0 and check % 2 == 0 ) : NEW_LINE INDENT for i in range ( K - 1 ) : NEW_LINE INDENT print ( \"2 \u2581 \" , end = \" \" ) NEW_LINE DEDENT print ( check ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT DEDENT N = 8 NEW_LINE K = 2 NEW_LINE sumEvenNumbers ( N , K ) NEW_LINE"} +{"text":"Count of contiguous subarrays possible for every index by including the element at that index | Function to find the number of subarrays including the element at every index of the array ; Creating an array of size N ; The loop is iterated till half the length of the array ; Condition to avoid overwriting the middle element for the array with even length . ; Computing the number of subarrays ; The ith element from the beginning and the ending have the same number of possible subarrays ; Function to print the vector ; Driver code","code":"def calculateWays ( N ) : NEW_LINE INDENT x = 0 ; NEW_LINE v = [ ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT v . append ( 0 ) ; NEW_LINE DEDENT for i in range ( N \/\/ 2 + 1 ) : NEW_LINE INDENT if ( N % 2 == 0 and i == N \/\/ 2 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT x = N * ( i + 1 ) - ( i + 1 ) * i ; NEW_LINE v [ i ] = x ; NEW_LINE v [ N - i - 1 ] = x ; NEW_LINE DEDENT return v ; NEW_LINE DEDENT def printArray ( v ) : NEW_LINE INDENT for i in range ( len ( v ) ) : NEW_LINE INDENT print ( v [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT v = calculateWays ( 4 ) ; NEW_LINE printArray ( v ) ; NEW_LINE DEDENT"} +{"text":"Smallest number greater than or equal to X whose sum of digits is divisible by Y | Python3 program to find the smallest number greater than or equal to X and divisible by Y ; Function that returns the sum of digits of a number ; Initialize variable to store the sum ; Add the last digit of the number ; Remove the last digit from the number ; Function that returns the smallest number greater than or equal to X and divisible by Y ; Initialize result variable ; Loop through numbers greater than equal to X ; Calculate sum of digits ; Check if sum of digits is divisible by Y ; Driver code","code":"MAXN = 10000000 NEW_LINE def sumOfDigits ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum += n % 10 NEW_LINE n \/\/= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def smallestNum ( X , Y ) : NEW_LINE INDENT res = - 1 ; NEW_LINE for i in range ( X , MAXN ) : NEW_LINE INDENT sum_of_digit = sumOfDigits ( i ) NEW_LINE if sum_of_digit % Y == 0 : NEW_LINE INDENT res = i NEW_LINE break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT ( X , Y ) = ( 5923 , 13 ) NEW_LINE print ( smallestNum ( X , Y ) ) NEW_LINE DEDENT"} +{"text":"Count the numbers which can convert N to 1 using given operation | Function to count the numbers which can convert N to 1 using the given operation ; Store all the divisors of N ; If i is a divisor ; If i is not equal to N \/ i ; Iterate through all the divisors of N - 1 and count them in answer ; Check if N - 1 is a divisor or not ; Iterate through all divisors and check for N mod d = 1 or ( N - 1 ) mod d = 0 ; Driver code","code":"def countValues ( N ) : NEW_LINE INDENT div = [ ] NEW_LINE i = 2 NEW_LINE while ( ( i * i ) <= N ) : NEW_LINE INDENT if ( N % i == 0 ) : NEW_LINE INDENT div . append ( i ) NEW_LINE if ( N != i * i ) : NEW_LINE INDENT div . append ( N \/\/ i ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT answer = 0 NEW_LINE i = 1 NEW_LINE while ( ( i * i ) <= N - 1 ) : NEW_LINE INDENT if ( ( N - 1 ) % i == 0 ) : NEW_LINE INDENT if ( i * i == N - 1 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT else : NEW_LINE INDENT answer += 2 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT for d in div : NEW_LINE INDENT K = N NEW_LINE while ( K % d == 0 ) : NEW_LINE INDENT K \/\/= d NEW_LINE DEDENT if ( ( K - 1 ) % d == 0 ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 6 NEW_LINE print ( countValues ( N ) ) NEW_LINE DEDENT"} +{"text":"Maximum possible prime divisors that can exist in numbers having exactly N divisors | Function to find the maximum possible prime divisors of a number can have with N divisors ; Number of time number divided by 2 ; Divide by other prime numbers ; If the last number of also prime then also include it ; Driver Code ; Function Call","code":"def findMaxPrimeDivisor ( n ) : NEW_LINE INDENT max_possible_prime = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT max_possible_prime += 1 NEW_LINE n = n \/\/ 2 NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT max_possible_prime += 1 NEW_LINE n = n \/\/ i NEW_LINE DEDENT i = i + 2 NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT max_possible_prime += 1 NEW_LINE DEDENT print ( max_possible_prime ) NEW_LINE DEDENT n = 4 NEW_LINE findMaxPrimeDivisor ( n ) NEW_LINE"} +{"text":"Count ways to express a number as sum of exactly two numbers | Function returns the count of ways express a number as sum of two numbers . ; Driver code","code":"def CountWays ( n ) : NEW_LINE INDENT ans = ( n - 1 ) \/\/ 2 NEW_LINE return ans NEW_LINE DEDENT N = 8 NEW_LINE print ( CountWays ( N ) ) NEW_LINE"} +{"text":"Divide array in two maximum equal length arrays of similar and dissimilar elements | Function to find the max - size to which an array can be divided into 2 equal parts ; Vector to find the frequency of each element of list ; Find the maximum frequency element present in list arr ; Find total unique elements present in list arr ; Find the Max - Size to which an array arr [ ] can be splitted ; Find the first array containing same elements ; Find the second array containing unique elements ; Driver code ; Initialise n ; Array declaration ; Size of array","code":"def Solve ( arr , size , n ) : NEW_LINE INDENT v = [ 0 ] * ( n + 1 ) ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT v [ arr [ i ] ] += 1 NEW_LINE DEDENT max1 = max ( set ( arr ) , key = v . count ) NEW_LINE diff1 = n + 1 - v . count ( 0 ) NEW_LINE max_size = max ( min ( v [ max1 ] - 1 , diff1 ) , min ( v [ max1 ] , diff1 - 1 ) ) NEW_LINE print ( \" Maximum \u2581 size \u2581 is \u2581 : \" , max_size ) NEW_LINE print ( \" The \u2581 First \u2581 Array \u2581 Is \u2581 : \u2581 \" ) NEW_LINE for i in range ( max_size ) : NEW_LINE INDENT print ( max1 , end = \" \u2581 \" ) NEW_LINE v [ max1 ] -= 1 NEW_LINE DEDENT print ( ) NEW_LINE print ( \" The \u2581 Second \u2581 Array \u2581 Is \u2581 : \u2581 \" ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( v [ i ] > 0 ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE max_size -= 1 NEW_LINE DEDENT if ( max_size < 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 7 NEW_LINE arr = [ 1 , 2 , 1 , 5 , 1 , 6 , 7 , 2 ] NEW_LINE size = len ( arr ) NEW_LINE Solve ( arr , size , n ) NEW_LINE DEDENT"} +{"text":"Find sum of xor of all unordered triplets of the array | Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; 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 y = y >> 1 y = y \/ 2 ; Returns n ^ ( - 1 ) mod p ; Returns nCr % p using Fermat 's little theorem. ; Base case ; Fill factorial array so that we can find all factorial of r , n and n - r ; Function returns sum of xor of all unordered triplets of the array ; Iterating over the bits ; Number of elements whith k 'th bit 1 and 0 respectively ; Checking if k 'th bit is 1 ; Adding this bit 's part to the answer ; Drivers code","code":"def power ( 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 x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def modInverse ( n , p ) : NEW_LINE INDENT return power ( n , p - 2 , p ) NEW_LINE DEDENT def nCrModPFermat ( n , r , p ) : NEW_LINE INDENT if ( r == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n < r ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT fac = [ 0 ] * ( n + 1 ) NEW_LINE fac [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fac [ i ] = fac [ i - 1 ] * i % p NEW_LINE DEDENT return ( fac [ n ] * modInverse ( fac [ r ] , p ) % p * modInverse ( fac [ n - r ] , p ) % p ) % p NEW_LINE DEDENT def SumOfXor ( a , n ) : NEW_LINE INDENT mod = 10037 NEW_LINE answer = 0 NEW_LINE for k in range ( 32 ) : NEW_LINE INDENT x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] & ( 1 << k ) ) : NEW_LINE INDENT x += 1 NEW_LINE DEDENT else : NEW_LINE INDENT y += 1 NEW_LINE DEDENT DEDENT answer += ( ( 1 << k ) % mod * ( nCrModPFermat ( x , 3 , mod ) + x * nCrModPFermat ( y , 2 , mod ) ) % mod ) % mod NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE A = [ 3 , 5 , 2 , 18 , 7 ] NEW_LINE print ( SumOfXor ( A , n ) ) NEW_LINE DEDENT"} +{"text":"Probability of not getting two consecutive heads together in N tosses of coin | Python3 implementation to find the probability of not getting two consecutive heads together when N coins are tossed ; Function to compute the N - th Fibonacci number in the sequence where a = 2 and b = 3 ; The first two numbers in the sequence are initialized ; Base cases ; Loop to compute the fibonacci sequence based on the first two initialized numbers ; Function to find the probability of not getting two consecutive heads when N coins are tossed ; Computing the number of favourable cases ; Computing the number of all possible outcomes for N tosses ; Driver code","code":"import math NEW_LINE def probability ( N ) : NEW_LINE INDENT a = 2 NEW_LINE b = 3 NEW_LINE if N == 1 : NEW_LINE INDENT return a NEW_LINE DEDENT elif N == 2 : NEW_LINE INDENT return b NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 3 , N + 1 ) : NEW_LINE INDENT c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT return b NEW_LINE DEDENT DEDENT def operations ( N ) : NEW_LINE INDENT x = probability ( N ) NEW_LINE y = math . pow ( 2 , N ) NEW_LINE return round ( x \/ y , 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( operations ( N ) ) NEW_LINE DEDENT"} +{"text":"Check if number formed by joining two Numbers is Perfect Cube | Function to check if a number is a perfect Cube or not ; Function to check if concatenation of two numbers is a perfect cube or not ; Convert numbers to string using to_string ( ) ; Concatenate the numbers and convert it into integer ; Check if concatenated value is perfect cube or not ; Driver Code","code":"def isPerfectCube ( x ) : NEW_LINE INDENT x = abs ( x ) NEW_LINE return int ( round ( x ** ( 1. \/ 3 ) ) ) ** 3 == x NEW_LINE DEDENT def checkCube ( a , b ) : NEW_LINE INDENT s1 = str ( a ) NEW_LINE s2 = str ( b ) NEW_LINE c = int ( s1 + s2 ) NEW_LINE if ( isPerfectCube ( c ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 6 NEW_LINE b = 4 NEW_LINE checkCube ( a , b ) NEW_LINE DEDENT"} +{"text":"Largest number in given Array formed by repeatedly combining two same elements | Function to return the largest sum ; Variable to store the largest sum ; Map to store the frequencies of each element ; Store the Frequencies ; Loop to combine duplicate elements and update the sum in the map ; If j is a duplicate element ; Update the frequency of 2 * j ; If the new sum is greater than maximum value , Update the maximum ; Returns the largest sum ; Driver Code ; Function Calling","code":"def largest_sum ( arr , n ) : NEW_LINE INDENT maximum = - 1 NEW_LINE m = dict ( ) NEW_LINE for i in arr : NEW_LINE INDENT m [ i ] = m . get ( i , 0 ) + 1 NEW_LINE DEDENT for j in list ( m ) : NEW_LINE INDENT if ( ( j in m ) and m [ j ] > 1 ) : NEW_LINE INDENT x , y = 0 , 0 NEW_LINE if 2 * j in m : NEW_LINE INDENT m [ 2 * j ] = m [ 2 * j ] + m [ j ] \/\/ 2 NEW_LINE DEDENT else : NEW_LINE INDENT m [ 2 * j ] = m [ j ] \/\/ 2 NEW_LINE DEDENT if ( 2 * j > maximum ) : NEW_LINE INDENT maximum = 2 * j NEW_LINE DEDENT DEDENT DEDENT return maximum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 4 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( largest_sum ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Check if it is possible to make x and y zero at same time with given operation | Function to check if it is possible to make x and y can become 0 at same time ; Check the given conditions ; Driver Code ; Function Call","code":"def canBeReduced ( x , y ) : NEW_LINE INDENT maxi = max ( x , y ) NEW_LINE mini = min ( x , y ) NEW_LINE if ( ( ( x + y ) % 3 ) == 0 and maxi <= 2 * mini ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 6 NEW_LINE y = 9 NEW_LINE canBeReduced ( x , y ) NEW_LINE DEDENT"} +{"text":"Wheel Factorization Algorithm | Python3 program to check if the given number is prime using Wheel Factorization Method ; Function to check if a given number x is prime or not ; The Wheel for checking prime number ; Base Case ; Check for the number taken as basis ; Check for Wheel Here i , acts as the layer of the wheel ; Check for the list of Sieve in arr [ ] ; If number is greater than sqrt ( N ) break ; Check if N is a multiple of prime number in the wheel ; If at any iteration isPrime is false , break from the loop ; Driver 's Code ; Function call for primality check","code":"import math NEW_LINE def isPrime ( N ) : NEW_LINE INDENT isPrime = True ; NEW_LINE arr = [ 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 ] NEW_LINE if ( N < 2 ) : NEW_LINE INDENT isPrime = False NEW_LINE DEDENT if ( N % 2 == 0 or N % 3 == 0 or N % 5 == 0 ) : NEW_LINE INDENT isPrime = False NEW_LINE DEDENT for i in range ( 0 , int ( math . sqrt ( N ) ) , 30 ) : NEW_LINE INDENT for c in arr : NEW_LINE INDENT if ( c > int ( math . sqrt ( N ) ) ) : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT if ( N % ( c + i ) == 0 ) : NEW_LINE INDENT isPrime = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( not isPrime ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if ( isPrime ) : NEW_LINE INDENT print ( \" Prime \u2581 Number \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 a \u2581 Prime \u2581 Number \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 121 NEW_LINE isPrime ( N ) NEW_LINE DEDENT"} +{"text":"Find all Pairs possible from the given Array | Function to prall possible pairs from the array ; Nested loop for all possible pairs ; Driver code","code":"def printPairs ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( \" ( \" , arr [ i ] , \" , \" , arr [ j ] , \" ) \" , end = \" , \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE printPairs ( arr , n ) NEW_LINE"} +{"text":"Sum of cubes of all Subsets of given Array | Python3 implementation of the approach ; Function to return ( 2 ^ P % mod ) ; Function to return the sum of cubes of subsets ; cubing the elements and adding it to ans ; Driver code","code":"mod = int ( 1e9 ) + 7 ; NEW_LINE def power ( p ) : NEW_LINE INDENT res = 1 ; NEW_LINE for i in range ( 1 , p + 1 ) : NEW_LINE INDENT res *= 2 ; NEW_LINE res %= mod ; NEW_LINE DEDENT return res % mod ; NEW_LINE DEDENT def subset_cube_sum ( A ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE ans = 0 ; NEW_LINE for i in A : NEW_LINE INDENT ans += ( i * i * i ) % mod ; NEW_LINE ans %= mod ; NEW_LINE DEDENT return ( ans * power ( n - 1 ) ) % mod ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 2 ] ; NEW_LINE print ( subset_cube_sum ( A ) ) ; NEW_LINE DEDENT"} +{"text":"Check if a circle lies inside another circle or not | Python3 program to check if one circle lies inside another circle or not . ; Driver code","code":"def circle ( x1 , y1 , x2 , y2 , r1 , r2 ) : NEW_LINE INDENT distSq = ( ( ( x1 - x2 ) * ( x1 - x2 ) ) + ( ( y1 - y2 ) * ( y1 - y2 ) ) ) ** ( .5 ) NEW_LINE if ( distSq + r2 == r1 ) : NEW_LINE INDENT print ( \" The \u2581 smaller \u2581 circle \u2581 lies \u2581 completely \" \" \u2581 inside \u2581 the \u2581 bigger \u2581 circle \u2581 with \u2581 \" \" touching \u2581 each \u2581 other \u2581 \" \" at \u2581 a \u2581 point \u2581 of \u2581 circumference . \u2581 \" ) NEW_LINE DEDENT elif ( distSq + r2 < r1 ) : NEW_LINE INDENT print ( \" The \u2581 smaller \u2581 circle \u2581 lies \u2581 completely \" \" \u2581 inside \u2581 the \u2581 bigger \u2581 circle \u2581 without \" \" \u2581 touching \u2581 each \u2581 other \u2581 \" \" at \u2581 a \u2581 point \u2581 of \u2581 circumference . \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" The \u2581 smaller \u2581 does \u2581 not \u2581 lies \u2581 inside \" \" \u2581 the \u2581 bigger \u2581 circle \u2581 completely . \" ) NEW_LINE DEDENT DEDENT x1 , y1 = 10 , 8 NEW_LINE x2 , y2 = 1 , 2 NEW_LINE r1 , r2 = 30 , 10 NEW_LINE circle ( x1 , y1 , x2 , y2 , r1 , r2 ) NEW_LINE"} +{"text":"Length of direct common tangent between two intersecting Circles | Function to find the length of the direct common tangent ; Driver code","code":"def lengtang ( r1 , r2 , d ) : NEW_LINE INDENT print ( \" The \u2581 length \u2581 of \u2581 the \u2581 direct \u2581 common \u2581 tangent \u2581 is \u2581 \" , ( ( d ** 2 ) - ( ( r1 - r2 ) ** 2 ) ) ** ( 1 \/ 2 ) ) ; NEW_LINE DEDENT r1 = 4 ; r2 = 6 ; d = 3 ; NEW_LINE lengtang ( r1 , r2 , d ) ; NEW_LINE"} +{"text":"Radius of the circle when the width and height of an arc is given | Function to find the radius ; Driver code","code":"def rad ( d , h ) : NEW_LINE INDENT print ( \" The \u2581 radius \u2581 of \u2581 the \u2581 circle \u2581 is \" , ( ( d * d ) \/ ( 8 * h ) + h \/ 2 ) ) NEW_LINE DEDENT d = 4 ; h = 1 ; NEW_LINE rad ( d , h ) ; NEW_LINE"} +{"text":"Shortest distance from the centre of a circle to a chord | Function to find the shortest distance ; Driver code","code":"def shortdis ( r , d ) : NEW_LINE INDENT print ( \" The \u2581 shortest \u2581 distance \u2581 \" , end = \" \" ) ; NEW_LINE print ( \" from \u2581 the \u2581 chord \u2581 to \u2581 centre \u2581 \" , end = \" \" ) ; NEW_LINE print ( ( ( r * r ) - ( ( d * d ) \/ 4 ) ) ** ( 1 \/ 2 ) ) ; NEW_LINE DEDENT r = 4 ; NEW_LINE d = 3 ; NEW_LINE shortdis ( r , d ) ; NEW_LINE"} +{"text":"Length of direct common tangent between the two non | Python3 program to find the length of the direct common tangent between two circles which do not touch each other ; Function to find the length of the direct common tangent ; Driver code","code":"import math NEW_LINE def lengtang ( r1 , r2 , d ) : NEW_LINE INDENT print ( \" The \u2581 length \u2581 of \u2581 the \u2581 direct \u2581 common \u2581 tangent \u2581 is \" , ( ( ( d ** 2 ) - ( ( r1 - r2 ) ** 2 ) ) ** ( 1 \/ 2 ) ) ) ; NEW_LINE DEDENT r1 = 4 ; r2 = 6 ; d = 12 ; NEW_LINE lengtang ( r1 , r2 , d ) ; NEW_LINE"} +{"text":"Biggest Square that can be inscribed within an Equilateral triangle | Function to find the side of the square ; the side cannot be negative ; side of the square ; Driver code","code":"def square ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT x = 0.464 * a NEW_LINE return x NEW_LINE DEDENT a = 5 NEW_LINE print ( square ( a ) ) NEW_LINE"} +{"text":"Apothem of a n | Python 3 Program to find the apothem of a regular polygon with given side length ; Function to find the apothem of a regular polygon ; Side and side length cannot be negative ; Degree converted to radians ; Driver code","code":"from math import tan NEW_LINE def polyapothem ( n , a ) : NEW_LINE INDENT if ( a < 0 and n < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return a \/ ( 2 * tan ( ( 180 \/ n ) * 3.14159 \/ 180 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 9 NEW_LINE n = 6 NEW_LINE print ( ' { 0 : . 6 } ' . format ( polyapothem ( n , a ) ) ) NEW_LINE DEDENT"} +{"text":"Area of a n | Python 3 Program to find the area of a regular polygon with given side length ; Function to find the area of a regular polygon ; Side and side length cannot be negative ; Area degree converted to radians ; Driver code","code":"from math import tan NEW_LINE def polyarea ( n , a ) : NEW_LINE INDENT if ( a < 0 and n < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT A = ( a * a * n ) \/ ( 4 * tan ( ( 180 \/ n ) * 3.14159 \/ 180 ) ) NEW_LINE return A NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 9 NEW_LINE n = 6 NEW_LINE print ( ' { 0 : . 6 } ' . format ( polyarea ( n , a ) ) ) NEW_LINE DEDENT"} +{"text":"Side of a regular n | Python 3 implementation of the approach ; Function to calculate the side of the polygon circumscribed in a circle ; Driver Code ; Total sides of the polygon ; Radius of the circumscribing circle","code":"from math import sin NEW_LINE def calculateSide ( n , r ) : NEW_LINE INDENT theta = 360 \/ n NEW_LINE theta_in_radians = theta * 3.14 \/ 180 NEW_LINE return 2 * r * sin ( theta_in_radians \/ 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE r = 5 NEW_LINE print ( ' { 0 : . 5 } ' . format ( calculateSide ( n , r ) ) ) NEW_LINE DEDENT"} +{"text":"Largest right circular cylinder within a frustum | Function to find the biggest right circular cylinder ; radii and height cannot be negative ; radius of right circular cylinder ; height of right circular cylinder ; volume of right circular cylinder ; Driver code","code":"def cyl ( r , R , h ) : NEW_LINE INDENT if ( h < 0 and r < 0 and R < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT r1 = r NEW_LINE h1 = h NEW_LINE V = 3.14 * pow ( r1 , 2 ) * h1 NEW_LINE return round ( V , 2 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT r , R , h = 7 , 11 , 6 NEW_LINE print ( cyl ( r , R , h ) ) NEW_LINE DEDENT"} +{"text":"Program to find the Perimeter of a Regular Polygon | Function to calculate the perimeter ; Calculate Perimeter ; driver code ; Get the number of sides ; Get the length of side ; find perimeter","code":"def Perimeter ( s , n ) : NEW_LINE INDENT perimeter = 1 NEW_LINE perimeter = n * s NEW_LINE return perimeter NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE s = 2.5 NEW_LINE peri = Perimeter ( s , n ) NEW_LINE print ( \" Perimeter \u2581 of \u2581 Regular \u2581 Polygon \u2581 with \" , n , \" sides \u2581 of \u2581 length \" , s , \" = \" , peri ) NEW_LINE DEDENT"} +{"text":"Area of the biggest possible rhombus that can be inscribed in a rectangle | Function to find the area of the biggest rhombus ; the length and breadth cannot be negative ; area of the rhombus ; Driver code","code":"def rhombusarea ( l , b ) : NEW_LINE INDENT if ( l < 0 or b < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( l * b ) \/ 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 16 NEW_LINE b = 6 NEW_LINE print ( rhombusarea ( l , b ) ) NEW_LINE DEDENT"} +{"text":"Check if a point lies inside a rectangle | Set | function to find if given point lies inside a given rectangle or not . ; Driver code ; bottom - left and top - right corners of rectangle . use multiple assignment ; given point ; function call","code":"def FindPoint ( x1 , y1 , x2 , y2 , x , y ) : NEW_LINE INDENT if ( x > x1 and x < x2 and y > y1 and y < y2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x1 , y1 , x2 , y2 = 0 , 0 , 10 , 8 NEW_LINE x , y = 1 , 5 NEW_LINE if FindPoint ( x1 , y1 , x2 , y2 , x , y ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Distance between a point and a Plane in 3 D | Python program to find the Perpendicular ( shortest ) distance between a point and a Plane in 3 D . ; Function to find distance ; Driver Code ; Function call","code":"import math NEW_LINE def shortest_distance ( x1 , y1 , z1 , a , b , c , d ) : NEW_LINE INDENT d = abs ( ( a * x1 + b * y1 + c * z1 + d ) ) NEW_LINE e = ( math . sqrt ( a * a + b * b + c * c ) ) NEW_LINE print ( \" Perpendicular \u2581 distance \u2581 is \" , d \/ e ) NEW_LINE DEDENT x1 = 4 NEW_LINE y1 = - 4 NEW_LINE z1 = 3 NEW_LINE a = 2 NEW_LINE b = - 2 NEW_LINE c = 5 NEW_LINE d = 8 NEW_LINE shortest_distance ( x1 , y1 , z1 , a , b , c , d ) NEW_LINE"} +{"text":"Program to find the Volume of a Triangular Prism | function to find the Volume of triangular prism ; formula to find Volume ; Driver Code ; function calling","code":"def findVolume ( l , b , h ) : NEW_LINE INDENT return ( ( l * b * h ) \/ 2 ) NEW_LINE DEDENT l = 18 NEW_LINE b = 12 NEW_LINE h = 9 NEW_LINE print ( \" Volume \u2581 of \u2581 triangular \u2581 prism : \u2581 \" , findVolume ( l , b , h ) ) NEW_LINE"} +{"text":"Check if given four integers ( or sides ) make rectangle | Function to check if the given integers value make a rectangle ; check all sides of rectangle combinations ; Driver code","code":"def isRectangle ( a , b , c , d ) : NEW_LINE INDENT if ( a == b and d == c ) or ( a == c and b == d ) or ( a == d and b == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT a , b , c , d = 1 , 2 , 3 , 4 NEW_LINE print ( \" Yes \" if isRectangle ( a , b , c , d ) else \" No \" ) NEW_LINE"} +{"text":"Program to find the mid | Function to find the midpoint of a line ; Driver Code","code":"def midpoint ( x1 , x2 , y1 , y2 ) : NEW_LINE INDENT print ( ( x1 + x2 ) \/\/ 2 , \" \u2581 , \u2581 \" , ( y1 + y2 ) \/\/ 2 ) NEW_LINE DEDENT x1 , y1 , x2 , y2 = - 1 , 2 , 3 , - 6 NEW_LINE midpoint ( x1 , x2 , y1 , y2 ) NEW_LINE"} +{"text":"Arc length from given Angle | Python3 code to calculate length of an arc ; function to calculate arc length ; Driver Code","code":"import math NEW_LINE def arcLength ( diameter , angle ) : NEW_LINE INDENT if angle >= 360 : NEW_LINE INDENT print ( \" Angle \u2581 cannot \u2581 be \u2581 formed \" ) NEW_LINE return 0 NEW_LINE DEDENT else : NEW_LINE INDENT arc = ( 3.142857142857143 * diameter ) * ( angle \/ 360.0 ) NEW_LINE return arc NEW_LINE DEDENT DEDENT diameter = 25.0 NEW_LINE angle = 45.0 NEW_LINE arc_len = arcLength ( diameter , angle ) NEW_LINE print ( arc_len ) NEW_LINE"} +{"text":"Check if a line touches or intersects a circle | python program to check if a line touches or intersects or outside a circle . ; Finding the distance of line from center . ; Checking if the distance is less than , greater than or equal to radius . ; Driven Program","code":"import math NEW_LINE def checkCollision ( a , b , c , x , y , radius ) : NEW_LINE INDENT dist = ( ( abs ( a * x + b * y + c ) ) \/ math . sqrt ( a * a + b * b ) ) NEW_LINE if ( radius == dist ) : NEW_LINE INDENT print ( \" Touch \" ) NEW_LINE DEDENT elif ( radius > dist ) : NEW_LINE INDENT print ( \" Intersect \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Outside \" ) NEW_LINE DEDENT DEDENT radius = 5 NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE a = 3 NEW_LINE b = 4 NEW_LINE c = 25 NEW_LINE checkCollision ( a , b , c , x , y , radius ) NEW_LINE"} +{"text":"Program to find Circumcenter of a Triangle | Function to find the line given two points ; Function which converts the input line to its perpendicular bisector . It also inputs the points whose mid - point lies on the bisector ; c = - bx + ay ; Returns the intersection point of two lines ; The lines are parallel . This is simplified by returning a pair of ( 10.0 ) * * 19 ; Line PQ is represented as ax + by = c ; Line QR is represented as ex + fy = g ; Converting lines PQ and QR to perpendicular vbisectors . After this , L = ax + by = c M = ex + fy = g ; The point of intersection of L and M gives the circumcenter ; Driver code .","code":"def lineFromPoints ( P , Q , a , b , c ) : NEW_LINE INDENT a = Q [ 1 ] - P [ 1 ] NEW_LINE b = P [ 0 ] - Q [ 0 ] NEW_LINE c = a * ( P [ 0 ] ) + b * ( P [ 1 ] ) NEW_LINE return a , b , c NEW_LINE DEDENT def perpendicularBisectorFromLine ( P , Q , a , b , c ) : NEW_LINE INDENT mid_point = [ ( P [ 0 ] + Q [ 0 ] ) \/\/ 2 , ( P [ 1 ] + Q [ 1 ] ) \/\/ 2 ] NEW_LINE c = - b * ( mid_point [ 0 ] ) + a * ( mid_point [ 1 ] ) NEW_LINE temp = a NEW_LINE a = - b NEW_LINE b = temp NEW_LINE return a , b , c NEW_LINE DEDENT def lineLineIntersection ( a1 , b1 , c1 , a2 , b2 , c2 ) : NEW_LINE INDENT determinant = a1 * b2 - a2 * b1 NEW_LINE if ( determinant == 0 ) : NEW_LINE INDENT return [ ( 10.0 ) ** 19 , ( 10.0 ) ** 19 ] NEW_LINE DEDENT else : NEW_LINE INDENT x = ( b2 * c1 - b1 * c2 ) \/\/ determinant NEW_LINE y = ( a1 * c2 - a2 * c1 ) \/\/ determinant NEW_LINE return [ x , y ] NEW_LINE DEDENT DEDENT def findCircumCenter ( P , Q , R ) : NEW_LINE INDENT a , b , c = 0.0 , 0.0 , 0.0 NEW_LINE a , b , c = lineFromPoints ( P , Q , a , b , c ) NEW_LINE e , f , g = 0.0 , 0.0 , 0.0 NEW_LINE e , f , g = lineFromPoints ( Q , R , e , f , g ) NEW_LINE a , b , c = perpendicularBisectorFromLine ( P , Q , a , b , c ) NEW_LINE e , f , g = perpendicularBisectorFromLine ( Q , R , e , f , g ) NEW_LINE circumcenter = lineLineIntersection ( a , b , c , e , f , g ) NEW_LINE if ( circumcenter [ 0 ] == ( 10.0 ) ** 19 and circumcenter [ 1 ] == ( 10.0 ) ** 19 ) : NEW_LINE INDENT print ( \" The \u2581 two \u2581 perpendicular \u2581 bisectors \u2581 found \u2581 come \u2581 parallel \" ) NEW_LINE print ( \" Thus , \u2581 the \u2581 given \u2581 points \u2581 do \u2581 not \u2581 form \u2581 a \u2581 triangle \u2581 and \u2581 are \u2581 collinear \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" The \u2581 circumcenter \u2581 of \u2581 the \u2581 triangle \u2581 PQR \u2581 is : \u2581 \" , end = \" \" ) NEW_LINE print ( \" ( \" , circumcenter [ 0 ] , \" , \" , circumcenter [ 1 ] , \" ) \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT P = [ 6 , 0 ] NEW_LINE Q = [ 0 , 0 ] NEW_LINE R = [ 0 , 8 ] NEW_LINE findCircumCenter ( P , Q , R ) NEW_LINE DEDENT"} +{"text":"Program to find area of a triangle | ( X [ i ] , Y [ i ] ) are coordinates of i 'th point. ; Initialize area ; Calculate value of shoelace formula ; Return absolute value ; Driver program to test above function","code":"def polygonArea ( X , Y , n ) : NEW_LINE INDENT area = 0.0 NEW_LINE j = n - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT area = area + ( X [ j ] + X [ i ] ) * ( Y [ j ] - Y [ i ] ) NEW_LINE DEDENT return abs ( area \/\/ 2.0 ) NEW_LINE DEDENT X = [ 0 , 2 , 4 ] NEW_LINE Y = [ 1 , 3 , 7 ] NEW_LINE n = len ( X ) NEW_LINE print ( polygonArea ( X , Y , n ) ) NEW_LINE"} +{"text":"Maximize sum of LSBs of Bitwise OR of all possible N \/ 2 pairs from given Array | Function top get LSB value of v ; Binary conversion ; Function to find the sum of LSBs of all possible pairs of the given array ; Stores the LSB of array elements ; Storing the LSB values ; Sort the array lab_arr [ ] ; Taking pairwise sum to get the maximum sum of LSB ; Print the result ; Driver Code ; Function Call","code":"def chk ( v ) : NEW_LINE INDENT v = list ( bin ( v ) [ 2 : ] ) NEW_LINE v . reverse ( ) NEW_LINE if ( '1' in v ) : NEW_LINE INDENT v = v . index ( '1' ) NEW_LINE return ( 2 ** v ) NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def sumOfLSB ( arr , N ) : NEW_LINE INDENT lsb_arr = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT lsb_arr . append ( chk ( arr [ i ] ) ) NEW_LINE DEDENT lsb_arr . sort ( reverse = True ) NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , N - 1 , 2 ) : NEW_LINE INDENT ans += ( lsb_arr [ i + 1 ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT N = 5 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE sumOfLSB ( arr , N ) NEW_LINE"} +{"text":"Count of subsequences having odd Bitwise AND values in the given array | Function to find count of subsequences having odd bitwise AND value ; Stores count of odd elements ; Traverse the array arr [ ] ; If x is odd increment count ; Return Answer ; Driver Code ; Function Call","code":"def countSubsequences ( arr ) : NEW_LINE INDENT odd = 0 NEW_LINE for x in arr : NEW_LINE INDENT if ( x & 1 ) : NEW_LINE INDENT odd = odd + 1 NEW_LINE DEDENT DEDENT return ( 1 << odd ) - 1 NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 3 , 3 ] NEW_LINE print ( countSubsequences ( arr ) ) NEW_LINE DEDENT"} +{"text":"Count pairs from an array with absolute difference not less than the minimum element in the pair | Function to find the number of pairs ( i , j ) such that abs ( a [ i ] - a [ j ] ) is at least the minimum of ( a [ i ] , a [ j ] ) ; Stores the resultant count of pairs ; Iterate over the range [ 0 , n ] ; Iterate from arr [ i ] - ( i % arr [ i ] ) till n with an increment of arr [ i ] ; Count the possible pairs ; Return the total count ; Driver Code","code":"def getPairsCount ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( arr [ i ] - ( i % arr [ i ] ) , n , arr [ i ] ) : NEW_LINE INDENT if ( i < j and abs ( arr [ i ] - arr [ j ] ) >= min ( arr [ i ] , arr [ j ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getPairsCount ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Minimum steps to change N to 1 by changing it to 2 * N or N \/ 10 at any step | Function to check if N can be changed to 1 or not . ; Count the number of 2 in the prime factorisation of N ; Count the number of 5 in the prime factorisation of N ; Driver Code","code":"def check ( N ) : NEW_LINE INDENT twos = 0 NEW_LINE fives = 0 NEW_LINE while ( N % 2 == 0 ) : NEW_LINE INDENT N \/= 2 NEW_LINE twos += 1 NEW_LINE DEDENT while ( N % 5 == 0 ) : NEW_LINE INDENT N \/= 5 NEW_LINE fives += 1 NEW_LINE DEDENT if ( N == 1 and twos <= fives ) : NEW_LINE INDENT print ( 2 * fives - twos ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 50 NEW_LINE check ( N ) NEW_LINE DEDENT"} +{"text":"Sum of elements in given range from Array formed by infinitely concatenating given array | Function to find the sum of elements in a given range of an infinite array ; Stores the sum of array elements from L to R ; Traverse from L to R ; Print the resultant sum ; Driver Code","code":"def rangeSum ( arr , N , L , R ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( L - 1 , R , 1 ) : NEW_LINE INDENT sum += arr [ i % N ] NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 6 , 9 ] NEW_LINE L = 10 NEW_LINE R = 13 NEW_LINE N = len ( arr ) NEW_LINE rangeSum ( arr , N , L , R ) NEW_LINE DEDENT"} +{"text":"Sum of elements in given range from Array formed by infinitely concatenating given array | Function to find the sum of elements in a given range of an infinite array ; Stores the prefix sum ; Calculate the prefix sum ; Stores the sum of elements from 1 to L - 1 ; Stores the sum of elements from 1 to R ; Print the resultant sum ; Driver Code","code":"def rangeSum ( arr , N , L , R ) : NEW_LINE INDENT prefix = [ 0 for i in range ( N + 1 ) ] NEW_LINE prefix [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT leftsum = ( ( L - 1 ) \/\/ N ) * prefix [ N ] + prefix [ ( L - 1 ) % N ] NEW_LINE rightsum = ( R \/\/ N ) * prefix [ N ] + prefix [ R % N ] NEW_LINE print ( rightsum - leftsum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 2 , 6 , 9 ] NEW_LINE L = 10 NEW_LINE R = 13 NEW_LINE N = len ( arr ) NEW_LINE rangeSum ( arr , N , L , R ) NEW_LINE DEDENT"} +{"text":"Exponential factorial of N | Function to find exponential factorial of a given number ; Stores the exponetial factor of N ; Iterare over the range [ 2 , N ] ; Update res ; Return res ; Input ; Function call","code":"def ExpoFactorial ( N ) : NEW_LINE INDENT res = 1 NEW_LINE mod = ( int ) ( 1000000007 ) NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT res = pow ( i , res , mod ) NEW_LINE DEDENT return res NEW_LINE DEDENT N = 4 NEW_LINE print ( ExpoFactorial ( N ) ) NEW_LINE"} +{"text":"Maximum subarray sum in an array created after repeated concatenation | Set | Function to find contiguous subarray with maximum sum if array is repeated K times ; Store the sum of the array arr [ ] ; Traverse the array and find sum ; Store the answer ; If K = 1 ; Apply Kadane algorithm to find sum ; Return the answer ; Stores the twice repeated array ; Traverse the range [ 0 , 2 * N ] ; Stores the maximum suffix sum ; Stores the maximum prefix sum ; Apply Kadane algorithm for 2 repetition of the array ; If the sum of the array is greater than 0 ; Return the answer ; Driver Code ; Given Input ; Function Call","code":"def maxSubArraySumRepeated ( arr , N , K ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT curr = arr [ 0 ] NEW_LINE ans = arr [ 0 ] NEW_LINE if ( K == 1 ) : NEW_LINE INDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT curr = max ( arr [ i ] , curr + arr [ i ] ) NEW_LINE ans = max ( ans , curr ) NEW_LINE DEDENT return ans NEW_LINE DEDENT V = [ ] NEW_LINE for i in range ( 2 * N ) : NEW_LINE INDENT V . append ( arr [ i % N ] ) NEW_LINE DEDENT maxSuf = V [ 0 ] NEW_LINE maxPref = V [ 2 * N - 1 ] NEW_LINE curr = V [ 0 ] NEW_LINE for i in range ( 1 , 2 * N , 1 ) : NEW_LINE INDENT curr += V [ i ] NEW_LINE maxPref = max ( maxPref , curr ) NEW_LINE DEDENT curr = V [ 2 * N - 1 ] NEW_LINE i = 2 * N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT curr += V [ i ] NEW_LINE maxSuf = max ( maxSuf , curr ) NEW_LINE i -= 1 NEW_LINE DEDENT curr = V [ 0 ] NEW_LINE for i in range ( 1 , 2 * N , 1 ) : NEW_LINE INDENT curr = max ( V [ i ] , curr + V [ i ] ) NEW_LINE ans = max ( ans , curr ) NEW_LINE DEDENT if ( sum > 0 ) : NEW_LINE INDENT temp = sum * ( K - 2 ) NEW_LINE ans = max ( ans , max ( temp + maxPref , temp + maxSuf ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 20 , - 30 , - 1 , 40 ] NEW_LINE N = len ( arr ) NEW_LINE K = 10 NEW_LINE print ( maxSubArraySumRepeated ( arr , N , K ) ) NEW_LINE DEDENT"} +{"text":"Count of subarrays with largest element at least twice the largest of remaining elements | Function to find count of subarrays which have max element greater than twice maximum of all other elements ; Stores the count of subarrays ; Generate all possible subarrays ; Stores the maximum element of the subarray ; Stores the maximum of all other elements ; Find the maximum element in the subarray [ i , j ] ; Find the maximum of all other elements ; If the maximum of subarray is greater than twice the maximum of other elements ; Print the maximum value obtained ; Driver Code","code":"def countSubarray ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n , 1 ) : NEW_LINE INDENT mxSubarray = 0 NEW_LINE mxOther = 0 NEW_LINE for k in range ( i , j + 1 , 1 ) : NEW_LINE INDENT mxSubarray = max ( mxSubarray , arr [ k ] ) NEW_LINE DEDENT for k in range ( 0 , i , 1 ) : NEW_LINE INDENT mxOther = max ( mxOther , arr [ k ] ) NEW_LINE DEDENT for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT mxOther = max ( mxOther , arr [ k ] ) NEW_LINE DEDENT if ( mxSubarray > ( 2 * mxOther ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 6 , 10 , 9 , 7 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE countSubarray ( arr , N ) NEW_LINE DEDENT"} +{"text":"Count of subarrays with largest element at least twice the largest of remaining elements | Function to find count of subarrays which have max element greater than twice maximum of all other elements ; Stores the maximum element of the array ; Traverse the given array ; If the value of 2 * arr [ i ] is greater than mx ; Update the value of L and break out of loop ; If the value 2 * arr [ i ] is greater than mx ; Update the value of R and break out of loop ; Print the final answer ; Driver Code","code":"def countSubarray ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE L = 0 NEW_LINE R = 0 NEW_LINE mx = max ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] * 2 > mx ) : NEW_LINE INDENT L = i NEW_LINE break NEW_LINE DEDENT DEDENT i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( arr [ i ] * 2 > mx ) : NEW_LINE INDENT R = i NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( ( L + 1 ) * ( n - R ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 6 , 10 , 9 , 7 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE countSubarray ( arr , N ) NEW_LINE DEDENT"} +{"text":"Find Prime number just less than and just greater each element of given Array | Python3 program for the above approach ; Utility function to check for primality of a number X by checking whether X haACCs any factors other than 1 and itself . ; Factor found ; Function to print primes just less than and just greater than of each element in an array ; Traverse the array ; Traverse for finding prime just less than A [ i ] ; Prime just less than A [ i ] found ; Traverse for finding prime just greater than A [ i ] ; Prime just greater than A [ i ] found ; Driver code ; Input ; Function call","code":"from math import sqrt NEW_LINE def isPrime ( X ) : NEW_LINE INDENT for i in range ( 2 , int ( sqrt ( X ) ) + 1 , 1 ) : NEW_LINE INDENT if ( X % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def printPrimes ( A , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT j = A [ i ] - 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( isPrime ( j ) ) : NEW_LINE INDENT print ( j , end = \" \u2581 \" ) NEW_LINE break NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT j = A [ i ] + 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( isPrime ( j ) ) : NEW_LINE INDENT print ( j , end = \" \u2581 \" ) NEW_LINE break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT print ( \" \" , \u2581 end \u2581 = \u2581 \" \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 17 , 28 ] NEW_LINE N = len ( A ) NEW_LINE printPrimes ( A , N ) NEW_LINE DEDENT"} +{"text":"Kth smallest element in an array that contains A [ i ] exactly B [ i ] times | Function to find the Kth smallest element that contains A [ i ] exactly B [ i ] times ; Traverse the given array ; Stores the frequency of every elements ; Traverse the given array ; Initialize a variable to store the prefix sums ; Iterate over the range [ 0 , M ] ; Increment sum by freq [ i ] ; If sum is greater than or equal to K ; Return the current element as answer ; Return - 1 ; Driver Code ; Given Input ; Function call","code":"def KthSmallest ( A , B , N , K ) : NEW_LINE INDENT M = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = max ( A [ i ] , M ) NEW_LINE DEDENT freq = [ 0 ] * ( M + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ A [ i ] ] += B [ i ] NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( M + 1 ) : NEW_LINE INDENT sum += freq [ i ] NEW_LINE if ( sum >= K ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 3 , 4 , 5 ] NEW_LINE B = [ 2 , 1 , 3 ] NEW_LINE N = len ( A ) NEW_LINE K = 4 NEW_LINE print ( KthSmallest ( A , B , N , K ) ) NEW_LINE DEDENT"} +{"text":"Bitwise OR of Bitwise AND of all subarrays of an array | Function to find the Bitwise OR of Bitwise AND of all subarrays ; Stores the required result ; Generate all the subarrays ; Store the current element ; Find the Bitwise OR ; Update the result ; Print the result ; Driver Code","code":"def findbitwiseOR ( a , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sub_array = a [ i ] NEW_LINE res = res | curr_sub_array NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT curr_sub_array = curr_sub_array & a [ j ] NEW_LINE res = res | curr_sub_array NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE findbitwiseOR ( A , N ) NEW_LINE DEDENT"} +{"text":"Bitwise OR of Bitwise AND of all subarrays of an array | Function to find the Bitwise OR of Bitwise AND of all consecutive subsets of the array ; Stores the required result ; Traverse the given array ; Print the result ; Driver Code","code":"def findbitwiseOR ( a , n ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = res | a [ i ] NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 3 ] NEW_LINE N = len ( A ) NEW_LINE findbitwiseOR ( A , N ) NEW_LINE DEDENT"} +{"text":"Check if sum of digits of a number exceeds the product of digits of that number | Function to check if the sum of the digits of N is strictly greater than the product of the digits of N or not ; Stores the sum and the product of the digits of N ; Stores the last digit if N ; Increment the value of sumOfDigits ; Update the prodOfDigit ; Divide N by 10 ; Print the result ; Driver Code","code":"def check ( n ) : NEW_LINE INDENT sumOfDigit = 0 NEW_LINE prodOfDigit = 1 NEW_LINE while n > 0 : NEW_LINE INDENT rem = n % 10 NEW_LINE sumOfDigit += rem NEW_LINE prodOfDigit *= rem NEW_LINE n = n \/\/ 10 NEW_LINE DEDENT if sumOfDigit > prodOfDigit : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT N = 1234 NEW_LINE check ( N ) NEW_LINE"} +{"text":"Print all distinct even and odd prefix Bitwise XORs of first N natural numbers | Print all distinct even & odd prefix Bitwise XORs from 1 to N ; Print the even number ; Print the odd number ; Driver Code","code":"def evenOddBitwiseXOR ( N ) : NEW_LINE INDENT print ( \" Even : \u2581 \" , 0 , end = \" \u2581 \" ) NEW_LINE for i in range ( 4 , N + 1 , 4 ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE print ( \" Odd : \u2581 \" , 1 , end = \" \u2581 \" ) NEW_LINE for i in range ( 4 , N + 1 , 4 ) : NEW_LINE INDENT print ( i - 1 , end = \" \u2581 \" ) NEW_LINE DEDENT if ( N % 4 == 2 ) : NEW_LINE INDENT print ( N + 1 ) NEW_LINE DEDENT elif ( N % 4 == 3 ) : NEW_LINE INDENT print ( N ) NEW_LINE DEDENT DEDENT N = 6 NEW_LINE evenOddBitwiseXOR ( N ) NEW_LINE"} +{"text":"Lexicographically largest permutation possible by a swap that is smaller than a given array | Function to lexicographic largest permutation possible by a swap that is smaller than given array ; Find the index of first element such that arr [ i ] > arr [ i + 1 ] ; If the array is sorted in increasing order ; Find the index of first element which is smaller than arr [ i ] ; If arr [ j ] = = arr [ j - 1 ] ; Decrement j ; Swap the element ; Pr the array arr [ ] ; Driver Code","code":"def findPermutation ( arr ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 and arr [ i ] <= arr [ i + 1 ] ) : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE return NEW_LINE DEDENT j = N - 1 NEW_LINE while ( j > i and arr [ j ] >= arr [ i ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT while ( j > i and arr [ j ] == arr [ j - 1 ] ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT temp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = temp ; NEW_LINE for it in arr : NEW_LINE INDENT print ( it , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 5 , 3 , 4 , 6 ] NEW_LINE findPermutation ( arr ) NEW_LINE"} +{"text":"Absolute difference between the count of odd and even factors of N | Function to find the smallest prime factor of all the numbers using Sieve Of Eratosthenes ; Stores whether any number is prime or not ; Initialize smallest factor as 2 for all the even numbers ; Iterate over the range [ 3 , N ] ; If i is prime ; Iterate all multiples of i ; i is the smallest prime factor of i * j ; Function to find the absolute difference between the count of odd and even factors of N ; Stores the smallest prime factor of i ; Fill values in s [ ] using sieve of eratosthenes ; Stores the total number of factors and the total number of odd and even factors ; Store the current prime factor of the number N ; Store the power of current prime factor ; Loop while N is greater than 1 ; If N also has smallest prime factor as curr , then increment cnt by 1 ; Update only total number of factors if curr is 2 ; Update total number of factors and total number of odd factors ; Update current prime factor as s [ N ] and count as 1 ; Calculate the number of even factors ; Print the difference ; Driver Code","code":"def sieveOfEratosthenes ( N , s ) : NEW_LINE INDENT prime = [ False ] * ( N + 1 ) NEW_LINE for i in range ( 2 , N + 1 , 2 ) : NEW_LINE INDENT s [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , N , 2 ) : NEW_LINE INDENT if ( prime [ i ] == False ) : NEW_LINE INDENT s [ i ] = i NEW_LINE for j in range ( i , N , 2 ) : NEW_LINE INDENT if j * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( not prime [ i * j ] ) : NEW_LINE INDENT prime [ i * j ] = True NEW_LINE s [ i * j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def findDifference ( N ) : NEW_LINE INDENT s = [ 0 ] * ( N + 1 ) NEW_LINE sieveOfEratosthenes ( N , s ) NEW_LINE total , odd , even = 1 , 1 , 0 NEW_LINE curr = s [ N ] NEW_LINE cnt = 1 NEW_LINE while ( N > 1 ) : NEW_LINE INDENT N \/\/= s [ N ] NEW_LINE if ( curr == s [ N ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE continue NEW_LINE DEDENT if ( curr == 2 ) : NEW_LINE INDENT total = total * ( cnt + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT total = total * ( cnt + 1 ) NEW_LINE odd = odd * ( cnt + 1 ) NEW_LINE DEDENT curr = s [ N ] NEW_LINE cnt = 1 NEW_LINE DEDENT even = total - odd NEW_LINE print ( abs ( even - odd ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE findDifference ( N ) NEW_LINE DEDENT"} +{"text":"Calculate Median from given values of Mean and Mode | Function to find the median of a group of data with given mean and mode ; Calculate the median ; Print the median ; Driver code","code":"def findMedian ( Mean , Mode ) : NEW_LINE INDENT Median = ( 2 * Mean + Mode ) \/\/ 3 NEW_LINE print ( Median ) NEW_LINE DEDENT Mode = 6 NEW_LINE Mean = 3 NEW_LINE findMedian ( Mean , Mode ) NEW_LINE"} +{"text":"Program to find the Magnitude of a Vector | Python3 program for the above approach ; Function to calculate magnitude of a 3 dimensional vector ; Stores the sum of squares of coordinates of a vector ; Return the magnitude ; Driver code","code":"from math import sqrt NEW_LINE def vectorMagnitude ( x , y , z ) : NEW_LINE INDENT sum = x * x + y * y + z * z NEW_LINE return sqrt ( sum ) NEW_LINE DEDENT x = 1 NEW_LINE y = 2 NEW_LINE z = 3 NEW_LINE print ( vectorMagnitude ( x , y , z ) ) NEW_LINE"} +{"text":"Program to find the product of a number with a Mersenne Number | Python3 program for the above approach ; Function to find prodcut of a Mersenne number with another number ; Stores the power of 2 of integer M + 1 ; Return the product ; Driver Code","code":"import math NEW_LINE def multiplyByMersenne ( N , M ) : NEW_LINE INDENT x = int ( math . log2 ( M + 1 ) ) NEW_LINE return ( ( N << x ) - N ) NEW_LINE DEDENT N = 4 NEW_LINE M = 15 NEW_LINE print ( multiplyByMersenne ( N , M ) ) NEW_LINE"} +{"text":"Nearest power of 2 of nearest perfect squares of non | Python3 program for the above approach ; Function to find nearest perfect square of num ; Calculate square root of num ; Calculate perfect square ; Find the nearest perfect square ; Function to find the power of 2 nearest to the number num ; Calculate log base 2 of num ; Highest power of 2 which is <= num ; Function to find the nearest perfect square and the nearest power of 2 of every array element whose occurrence is 1 ; Stores frequency of array elements ; Traverse the array and update frequency of current array element ; Traverse the map freq ; If the frequency is 1 ; Find nearest perfect square ; Print the nearest power of 2 ; If the any does not contain any non - repeating elements ; Driver Code","code":"from math import sqrt , log2 , pow NEW_LINE def perfectSquare ( num ) : NEW_LINE INDENT sr = int ( sqrt ( num ) ) NEW_LINE a = sr * sr NEW_LINE b = ( sr + 1 ) * ( sr + 1 ) NEW_LINE if ( ( num - a ) < ( b - num ) ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT def powerOfTwo ( num ) : NEW_LINE INDENT lg = int ( log2 ( num ) ) NEW_LINE p = int ( pow ( 2 , lg ) ) NEW_LINE return p NEW_LINE DEDENT def uniqueElement ( arr , N ) : NEW_LINE INDENT ans = True NEW_LINE freq = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] in freq ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT res = [ ] NEW_LINE for key , value in freq . items ( ) : NEW_LINE INDENT if ( value == 1 ) : NEW_LINE INDENT ans = False NEW_LINE ps = perfectSquare ( key ) NEW_LINE res . append ( powerOfTwo ( ps ) ) NEW_LINE DEDENT DEDENT res . sort ( reverse = False ) NEW_LINE for x in res : NEW_LINE print ( x , end = \" \u2581 \" ) NEW_LINE if ( ans ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 11 , 4 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE uniqueElement ( arr , N ) NEW_LINE DEDENT"} +{"text":"Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray | Python3 program for the above approach ; Function to partition the array into two non - empty subarrays which satisfies the given condition ; Stores the suffix Min array ; Stores the Minimum of a suffix ; Traverse the array in reverse ; Update Minimum ; Store the Minimum ; Stores the Maximum value of a prefix ; Stores the index of the partition ; Update Max ; If Max is less than Min [ i + 1 ] ; Store the index of partition ; break ; If ind is not - 1 ; Print first subarray ; Print second subarray ; Otherwise ; Driver Code","code":"import sys NEW_LINE def partitionArray ( a , n ) : NEW_LINE INDENT Min = [ 0 ] * n NEW_LINE Mini = sys . maxsize NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT Mini = min ( Mini , a [ i ] ) NEW_LINE Min [ i ] = Mini NEW_LINE DEDENT Maxi = - sys . maxsize - 1 NEW_LINE ind = - 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT Maxi = max ( Maxi , a [ i ] ) NEW_LINE if ( Maxi < Min [ i + 1 ] ) : NEW_LINE ind = i NEW_LINE break NEW_LINE DEDENT if ( ind != - 1 ) : NEW_LINE INDENT for i in range ( ind + 1 ) : NEW_LINE print ( a [ i ] , end = \" \u2581 \" ) NEW_LINE print ( ) NEW_LINE for i in range ( ind + 1 , n , 1 ) : NEW_LINE print ( a [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Impossible \" ) NEW_LINE DEDENT DEDENT arr = [ 5 , 3 , 2 , 7 , 9 ] NEW_LINE N = 5 NEW_LINE partitionArray ( arr , N ) NEW_LINE"} +{"text":"Check if a number can be represented as sum of K positive integers out of which at least K | Python3 program for the above approach ; Function to count all prime factors of a given number ; Count the number of 2 s that divides n ; Since n is odd at this point , skip one element ; While i divides n , count i and divide n ; If n is a prime number greater than 2 ; Function to find the sum of first n nearly prime numbers ; Store the required sum ; Add this number if it is satisfies the condition ; Increment count of nearly prime numbers ; Function to check if N can be represented as sum of K different positive integers out of which at least K - 1 of them are nearly prime ; Store the sum of first K - 1 nearly prime numbers ; If sum is great than or equal to n ; Otherwise , prYes ; Driver Code","code":"import math NEW_LINE def countPrimeFactors ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n \/\/ 2 NEW_LINE count += 1 NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) + 1 ) , 2 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT n = n \/\/ i NEW_LINE count += 1 NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return ( count ) NEW_LINE DEDENT def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE i = 1 NEW_LINE num = 2 NEW_LINE while ( i <= n ) : NEW_LINE INDENT if ( countPrimeFactors ( num ) == 2 ) : NEW_LINE INDENT sum += num NEW_LINE i += 1 NEW_LINE DEDENT num += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT def check ( n , k ) : NEW_LINE INDENT s = findSum ( k - 1 ) NEW_LINE if ( s >= n ) : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT DEDENT n = 100 NEW_LINE k = 6 NEW_LINE check ( n , k ) NEW_LINE"} +{"text":"Count ways to represent an integer as an exponent | Python3 program for the above approach ; Function to calculate GCD of a and b using Euclidean Algorithm ; Iterate until b is non - zero ; Return the GCD ; Function to count the number of ways N can be expressed as x ^ y ; Base Case ; Stores the gcd of powers ; Calculate the degree of 2 in N ; Calculate the degree of prime numbers in N ; Calculate the degree of prime ' i ' in N ; If N is a prime , g becomes 1. ; Stores the number of ways to represent N as x ^ y ; Find the number of Factors of g ; Update the count of ways ; Iterate to find rest of the prime numbers ; Find the power of i ; Update the count of ways ; If g is prime ; Return the total number of ways ; Driver Code","code":"import math NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT while ( b > 0 ) : NEW_LINE INDENT rem = a % b NEW_LINE a = b NEW_LINE b = rem NEW_LINE DEDENT return a NEW_LINE DEDENT def countNumberOfWays ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT g = 0 NEW_LINE power = 0 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT power += 1 NEW_LINE n \/\/= 2 NEW_LINE DEDENT g = gcd ( g , power ) NEW_LINE for i in range ( 3 , int ( math . sqrt ( g ) ) + 1 , 2 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT power += 1 NEW_LINE n \/\/= i NEW_LINE DEDENT g = gcd ( g , power ) NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT g = gcd ( g , 1 ) NEW_LINE DEDENT ways = 1 NEW_LINE power = 0 NEW_LINE while ( g % 2 == 0 ) : NEW_LINE INDENT g \/\/= 2 NEW_LINE power += 1 NEW_LINE DEDENT ways *= ( power + 1 ) NEW_LINE for i in range ( 3 , int ( math . sqrt ( g ) ) + 1 , 2 ) : NEW_LINE INDENT power = 0 NEW_LINE while ( g % i == 0 ) : NEW_LINE INDENT power += 1 NEW_LINE g \/= i NEW_LINE DEDENT ways *= ( power + 1 ) NEW_LINE DEDENT if ( g > 2 ) : NEW_LINE INDENT ways *= 2 NEW_LINE DEDENT return ways NEW_LINE DEDENT N = 64 NEW_LINE print ( countNumberOfWays ( N ) ) NEW_LINE"} +{"text":"Highest power of 2 less than or equal to given Integer | Python3 implementation of the above approach ; Function to return the lowest power of 2 close to given positive number ; Floor function is used to determine the value close to the number ; Function to return the lowest power of 2 close to given negative number ; Ceil function is used for negative numbers as - 1 > - 4. It would be opposite to positive numbers where 1 < 4 ; Function to find the highest power of 2 ; To check if the given number is positive or negative ; If the number is negative , then the ceil of the positive number is calculated and negative sign is added ; Driver code","code":"from math import floor , ceil , log2 NEW_LINE def powOfPositive ( n ) : NEW_LINE INDENT pos = floor ( log2 ( n ) ) ; NEW_LINE return 2 ** pos ; NEW_LINE DEDENT def powOfNegative ( n ) : NEW_LINE INDENT pos = ceil ( log2 ( n ) ) ; NEW_LINE return ( - 1 * pow ( 2 , pos ) ) ; NEW_LINE DEDENT def highestPowerOf2 ( n ) : NEW_LINE INDENT if ( n > 0 ) : NEW_LINE INDENT print ( powOfPositive ( n ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT n = - n ; NEW_LINE print ( powOfNegative ( n ) ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = - 24 ; NEW_LINE highestPowerOf2 ( n ) ; NEW_LINE DEDENT"} +{"text":"Number of cards needed build a House of Cards of a given level N | Function to find number of cards needed ; Driver Code","code":"def noOfCards ( n ) : NEW_LINE INDENT return n * ( 3 * n + 1 ) \/\/ 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( noOfCards ( n ) ) NEW_LINE"} +{"text":"Find smallest possible Number from a given large Number with same count of digits | Function for finding the smallest possible number after swapping the digits any number of times ; Variable to store the final answer ; Array to store the count of occurrence of each digit ; Loop to calculate the number of occurrences of every digit ; Loop to get smallest number ; Returning the answer ; Driver code","code":"def smallestPoss ( s , n ) : NEW_LINE INDENT ans = \" \" ; NEW_LINE arr = [ 0 ] * 10 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ ord ( s [ i ] ) - 48 ] += 1 ; NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT for j in range ( arr [ i ] ) : NEW_LINE INDENT ans = ans + str ( i ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 ; NEW_LINE K = \"325343273113434\" ; NEW_LINE print ( smallestPoss ( K , N ) ) ; NEW_LINE DEDENT"} +{"text":"Count the subarray with sum strictly greater than the sum of remaining elements | Function to count the number of sub - arrays with sum strictly greater than the remaining elements of array ; For loop for beginning point of a subarray ; For loop for ending point of the subarray ; Initialise subarray_sum and remaining_sum to 0 ; For loop to calculate the sum of generated subarray ; For loop to calculate the sum remaining array element ; Checking for condition when subarray sum is strictly greater than remaining sum of array element ; Driver code","code":"def Count_subarray ( arr , n ) : NEW_LINE INDENT subarray_sum , remaining_sum , count = 0 , 0 , 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT subarray_sum = 0 ; NEW_LINE remaining_sum = 0 ; NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT subarray_sum += arr [ k ] ; NEW_LINE DEDENT for l in range ( i ) : NEW_LINE INDENT remaining_sum += arr [ l ] ; NEW_LINE DEDENT for l in range ( j + 1 , n ) : NEW_LINE INDENT remaining_sum += arr [ l ] ; NEW_LINE DEDENT if ( subarray_sum > remaining_sum ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 9 , 12 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( Count_subarray ( arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Count the subarray with sum strictly greater than the sum of remaining elements | Python3 implementation of the above approach ; Calculating total sum of given array ; For loop for beginning point of a subarray ; initialise subarray_sum to 0 ; For loop for calculating subarray_sum and remaining_sum ; Calculating subarray_sum and corresponding remaining_sum ; Checking for the condition when subarray sum is strictly greater than the remaining sum of the array element ; Driver code","code":"def Count_subarray ( arr , n ) : NEW_LINE INDENT total_sum = 0 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT total_sum += arr [ i ] ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT subarray_sum = 0 ; NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT subarray_sum += arr [ j ] ; NEW_LINE remaining_sum = total_sum - subarray_sum ; NEW_LINE if ( subarray_sum > remaining_sum ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 10 , 9 , 12 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( Count_subarray ( arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Remove one element to get maximum XOR | Function to return the maximized XOR after removing an element from the array ; Find XOR of the complete array ; To store the final answer ; Iterating through the array to find the final answer ; Return the final answer ; Driver code","code":"def maxXOR ( arr , n ) : NEW_LINE INDENT xorArr = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT xorArr ^= arr [ i ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , ( xorArr ^ arr [ i ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxXOR ( arr , n ) ) NEW_LINE"} +{"text":"Count of numbers from the range [ L , R ] which contains at least one digit that divides K | Function that returns true if num contains at least one digit that divides k ; Get the last digit ; If the digit is non - zero and it divides k ; Remove the last digit ; There is no digit in num that divides k ; Function to return the required count of elements from the given range which contain at least one digit that divides k ; To store the result ; For every number from the range ; If any digit of the current number divides k ; Driver code","code":"def digitDividesK ( num , k ) : NEW_LINE INDENT while ( num ) : NEW_LINE INDENT d = num % 10 NEW_LINE if ( d != 0 and k % d == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT num = num \/\/ 10 NEW_LINE DEDENT return False NEW_LINE DEDENT def findCount ( l , r , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT if ( digitDividesK ( i , k ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT l = 20 NEW_LINE r = 35 NEW_LINE k = 45 NEW_LINE print ( findCount ( l , r , k ) ) NEW_LINE"} +{"text":"Check if a given number is factorial of any number | Function to check if the given number is a factorial of any number ; Driver Code","code":"def isFactorial ( n ) : NEW_LINE INDENT i = 1 ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT n \/\/= i ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 24 ; NEW_LINE ans = isFactorial ( n ) ; NEW_LINE if ( ans == 1 ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT DEDENT"} +{"text":"Remove an element to minimize the LCM of the given array | Python3 implementation of the above approach ; Function to return the LCM of two numbers ; Function to return the minimum LCM after removing a single element from the given array ; Prefix and Suffix arrays ; Single state dynamic programming relation for storing LCM of first i elements from the left in Prefix [ i ] ; Initializing Suffix array ; Single state dynamic programming relation for storing LCM of all the elements having index greater than or equal to i in Suffix [ i ] ; If first or last element of the array has to be removed ; If any other element is replaced ; Return the minimum LCM ; Driver code","code":"from math import gcd NEW_LINE def lcm ( a , b ) : NEW_LINE INDENT GCD = gcd ( a , b ) ; NEW_LINE return ( a * b ) \/\/ GCD ; NEW_LINE DEDENT def MinLCM ( a , n ) : NEW_LINE INDENT Prefix = [ 0 ] * ( n + 2 ) ; NEW_LINE Suffix = [ 0 ] * ( n + 2 ) ; NEW_LINE Prefix [ 1 ] = a [ 0 ] ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT Prefix [ i ] = lcm ( Prefix [ i - 1 ] , a [ i - 1 ] ) ; NEW_LINE DEDENT Suffix [ n ] = a [ n - 1 ] ; NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT Suffix [ i ] = lcm ( Suffix [ i + 1 ] , a [ i - 1 ] ) ; NEW_LINE DEDENT ans = min ( Suffix [ 2 ] , Prefix [ n - 1 ] ) ; NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT ans = min ( ans , lcm ( Prefix [ i - 1 ] , Suffix [ i + 1 ] ) ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 5 , 15 , 9 , 36 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( MinLCM ( a , n ) ) ; NEW_LINE DEDENT"} +{"text":"Number of coloured 0 's in an N | Function to return the count of coloured 0 s in an n - level hexagon ; Driver code","code":"def count ( n ) : NEW_LINE INDENT return n * ( 3 * n - 1 ) \/\/ 2 ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 ; NEW_LINE print ( count ( n ) ) ; NEW_LINE DEDENT"} +{"text":"Minimum value to be assigned to the elements so that sum becomes greater than initial sum | Function to return the minimum required value ; Find the sum of the array elements ; Return the required value ; Driver code","code":"def findMinValue ( 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 \/\/ n ) + 1 NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 10 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMinValue ( arr , n ) ) NEW_LINE"} +{"text":"Color all boxes in line such that every M consecutive boxes are unique | Python3 implementation of the approach ; Function to return ( m ! % MOD ) ; Driver code","code":"MOD = 1000000007 NEW_LINE def modFact ( n , m ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT result = ( result * i ) % MOD NEW_LINE DEDENT return result NEW_LINE DEDENT n = 3 NEW_LINE m = 2 NEW_LINE print ( modFact ( n , m ) ) NEW_LINE"} +{"text":"Sum of squares of all Subsets of given Array | Python3 implementation of the approach ; Function to return ( 2 ^ P % mod ) ; Function to return the sum of squares of subsets ; Squaring the elements and adding it to ans ; Driver code","code":"mod = 10 ** 9 + 7 NEW_LINE def power ( p ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , p + 1 ) : NEW_LINE INDENT res *= 2 NEW_LINE res %= mod NEW_LINE DEDENT return res % mod NEW_LINE DEDENT def subset_square_sum ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE ans = 0 NEW_LINE for i in A : NEW_LINE INDENT ans += i * i % mod NEW_LINE ans %= mod NEW_LINE DEDENT return ans * power ( n - 1 ) % mod NEW_LINE DEDENT A = [ 3 , 7 ] NEW_LINE print ( subset_square_sum ( A ) ) NEW_LINE"} +{"text":"Find the number of pairs such that their gcd is equals to 1 | Python3 program to find the number of pairs such that gcd equals to 1 ; Function to calculate least prime factor of each number ; If it is a prime number ; For all multiples which are not visited yet . ; Function to find the value of Mobius function for all the numbers from 1 to n ; If number is one ; If number has a squared prime factor ; Multiply - 1 with the previous number ; Function to find the number of pairs such that gcd equals to 1 ; To store maximum number ; To store frequency of each number ; Find frequency and maximum number ; To store number of pairs with gcd equals to 1 ; Traverse through the all possible elements ; Return the number of pairs ; Driver code ; Function call","code":"N = 100050 NEW_LINE lpf = [ 0 for i in range ( N ) ] NEW_LINE mobius = [ 0 for i in range ( N ) ] NEW_LINE def least_prime_factor ( ) : NEW_LINE INDENT for i in range ( 2 , N ) : NEW_LINE INDENT if ( lpf [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i , N , i ) : NEW_LINE INDENT if ( lpf [ j ] == 0 ) : NEW_LINE INDENT lpf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def Mobius ( ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT mobius [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( lpf [ ( i \/\/ lpf [ i ] ) ] == lpf [ i ] ) : NEW_LINE INDENT mobius [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT mobius [ i ] = - 1 * mobius [ i \/\/ lpf [ i ] ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def gcd_pairs ( a , n ) : NEW_LINE INDENT maxi = 0 NEW_LINE fre = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT fre [ a [ i ] ] += 1 NEW_LINE maxi = max ( a [ i ] , maxi ) NEW_LINE DEDENT least_prime_factor ( ) NEW_LINE Mobius ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , maxi + 1 ) : NEW_LINE INDENT if ( mobius [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT temp = 0 NEW_LINE for j in range ( i , maxi + 1 , i ) : NEW_LINE INDENT temp += fre [ j ] NEW_LINE DEDENT ans += temp * ( temp - 1 ) \/\/ 2 * mobius [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( gcd_pairs ( a , n ) ) NEW_LINE"} +{"text":"Comparing X ^ Y and Y ^ X for very large values of X and Y | Python3 implementation of the approach ; Function to compare x ^ y and y ^ x ; Storing values OF x ^ y AND y ^ x ; Comparing values ; Driver code","code":"from math import log NEW_LINE def compareVal ( x , y ) : NEW_LINE INDENT a = y * log ( x ) ; NEW_LINE b = x * log ( y ) ; NEW_LINE if ( a > b ) : NEW_LINE INDENT print ( x , \" ^ \" , y , \" > \" , y , \" ^ \" , x ) ; NEW_LINE DEDENT elif ( a < b ) : NEW_LINE INDENT print ( x , \" ^ \" , y , \" < \" , y , \" ^ \" , x ) ; NEW_LINE DEDENT elif ( a == b ) : NEW_LINE INDENT print ( x , \" ^ \" , y , \" = \" , y , \" ^ \" , x ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x = 4 ; y = 5 ; NEW_LINE compareVal ( x , y ) ; NEW_LINE DEDENT"} +{"text":"Euler zigzag numbers ( Alternating Permutation ) | Function to prfirst n zigzag numbers ; To store factorial and n 'th zig zag number ; Initialize factorial upto n ; Set first two zig zag numbers ; Print first two zig zag number ; Print the rest zig zag numbers ; Binomial ( n , k ) * a ( k ) * a ( n - k ) ; Store the value ; Print the number ; Driver code ; Function call","code":"def ZigZag ( n ) : NEW_LINE INDENT fact = [ 0 for i in range ( n + 1 ) ] NEW_LINE zig = [ 0 for i in range ( n + 1 ) ] NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT zig [ 0 ] = 1 NEW_LINE zig [ 1 ] = 1 NEW_LINE print ( \" zig \u2581 zag \u2581 numbers : \u2581 \" , end = \" \u2581 \" ) NEW_LINE print ( zig [ 0 ] , zig [ 1 ] , end = \" \u2581 \" ) NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for k in range ( 0 , i ) : NEW_LINE INDENT sum += ( ( fact [ i - 1 ] \/\/ ( fact [ i - 1 - k ] * fact [ k ] ) ) * zig [ k ] * zig [ i - 1 - k ] ) NEW_LINE DEDENT zig [ i ] = sum \/\/ 2 NEW_LINE print ( sum \/\/ 2 , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT n = 10 NEW_LINE ZigZag ( n ) NEW_LINE"} +{"text":"Gijswijt 's Sequence | if the sequence is a ( 1 ) a ( 2 ) a ( 3 ) . . a ( n - 1 ) check if the sequence can be represented as x * ( y ^ k ) find the largest value of k ; count ; pattern of elements of size i from the end of sequence ; count ; extract the pattern in a reverse order ; check how many times the pattern is repeated ; if the element dosent match ; if the end of pattern is reached set value of k = 0 and increase the count ; return the max count ; print first n terms of Gijswijt 's sequence ; set the count ; stoes the element ; print the first n terms of the sequence ; push the element ; find the count for next number ; Driver Code","code":"def find_count ( ele ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( ele ) ) : NEW_LINE INDENT p = [ ] NEW_LINE c = 0 NEW_LINE j = len ( ele ) - 1 NEW_LINE while j >= ( len ( ele ) - 1 - i ) and j >= 0 : NEW_LINE INDENT p . append ( ele [ j ] ) NEW_LINE j -= 1 NEW_LINE DEDENT j = len ( ele ) - 1 NEW_LINE k = 0 NEW_LINE while j >= 0 : NEW_LINE INDENT if ele [ j ] != p [ k ] : NEW_LINE INDENT break NEW_LINE DEDENT j -= 1 NEW_LINE k += 1 NEW_LINE if k == len ( p ) : NEW_LINE INDENT c += 1 NEW_LINE k = 0 NEW_LINE DEDENT DEDENT count = max ( count , c ) NEW_LINE DEDENT return count NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT count = 1 NEW_LINE ele = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( count , end = \" \u2581 \" ) NEW_LINE ele . append ( count ) NEW_LINE count = find_count ( ele ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 10 NEW_LINE solve ( n ) NEW_LINE DEDENT"} +{"text":"Wedderburn \u2013 Etherington number | Stores the Wedderburn Etherington numbers ; Function to return the nth Wedderburn Etherington numbers ; Base case ; If n is even n = 2 x ; get x ; a ( 2 x ) = a ( 1 ) a ( 2 x - 1 ) + a ( 2 ) a ( 2 x - 2 ) + ... + a ( x - 1 ) a ( x + 1 ) ; a ( x ) ( a ( x ) + 1 ) \/ 2 ; Store the ans ; Return the required answer ; If n is odd ; a ( 2 x - 1 ) = a ( 1 ) a ( 2 x - 2 ) + a ( 2 ) a ( 2 x - 3 ) + ... + a ( x - 1 ) a ( x ) , ; Store the ans ; Return the required answer ; Function to prfirst N Wedderburn Etherington numbers ; Store first 3 numbers ; PrN terms ; Driver code ; function call","code":"store = dict ( ) NEW_LINE def Wedderburn ( n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT return store [ n ] NEW_LINE DEDENT elif ( n % 2 == 0 ) : NEW_LINE INDENT x = n \/\/ 2 NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , x ) : NEW_LINE INDENT ans += store [ i ] * store [ n - i ] NEW_LINE DEDENT ans += ( store [ x ] * ( store [ x ] + 1 ) ) \/\/ 2 NEW_LINE store [ n ] = ans NEW_LINE return ans NEW_LINE DEDENT else : NEW_LINE INDENT x = ( n + 1 ) \/\/ 2 NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , x ) : NEW_LINE INDENT ans += store [ i ] * store [ n - i ] NEW_LINE DEDENT store [ n ] = ans NEW_LINE return ans NEW_LINE DEDENT DEDENT def Wedderburn_Etherington ( n ) : NEW_LINE INDENT store [ 0 ] = 0 NEW_LINE store [ 1 ] = 1 NEW_LINE store [ 2 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( Wedderburn ( i ) , end = \" \" ) NEW_LINE if ( i != n - 1 ) : NEW_LINE INDENT print ( end = \" , \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT n = 10 NEW_LINE Wedderburn_Etherington ( n ) NEW_LINE"} +{"text":"Maximum value after merging all elements in the array | Function to maximum value after merging all elements in the array ; To check if positive and negative elements present or not ; Check for positive integer ; Check for negative integer ; If both positive and negative elements are present ; To store maximum value possible ; To find minimum value ; Remove minimum element ; Replace with absolute values ; To find minimum value ; Remove minimum element ; Return the required sum ; Driver code ; Function call","code":"def Max_sum ( a , n ) : NEW_LINE INDENT pos = 0 NEW_LINE neg = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > 0 ) : NEW_LINE INDENT pos = 1 NEW_LINE DEDENT elif ( a [ i ] < 0 ) : NEW_LINE INDENT neg = 1 NEW_LINE DEDENT if ( pos == 1 and neg == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE if ( pos == 1 and neg == 1 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT sum += abs ( a [ i ] ) NEW_LINE DEDENT DEDENT elif ( pos == 1 ) : NEW_LINE INDENT mini = a [ 0 ] NEW_LINE sum = a [ 0 ] NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT mini = min ( mini , a [ i ] ) NEW_LINE sum += a [ i ] NEW_LINE DEDENT sum -= 2 * mini NEW_LINE DEDENT elif ( neg == 1 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT a [ i ] = abs ( a [ i ] ) NEW_LINE DEDENT mini = a [ 0 ] NEW_LINE sum = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT mini = min ( mini , a [ i ] ) NEW_LINE sum += a [ i ] NEW_LINE DEDENT sum -= 2 * mini NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 3 , 5 , - 2 , - 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( Max_sum ( a , n ) ) NEW_LINE DEDENT"} +{"text":"Decimal to Binary using recursion and without using power operator | Recursive function to convert n to its binary equivalent ; Base case ; Recursive call ; Driver code","code":"def decimalToBinary ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT print ( \"0\" , end = \" \" ) ; NEW_LINE return ; NEW_LINE DEDENT decimalToBinary ( n \/\/ 2 ) ; NEW_LINE print ( n % 2 , end = \" \" ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 13 ; NEW_LINE decimalToBinary ( n ) ; NEW_LINE DEDENT"} +{"text":"Find minimum possible values of A , B and C when two of the ( A + B ) , ( A + C ) and ( B + C ) are given | Function to find A , B and C ; Keep minimum number in x ; Find the numbers ; Driver code ; Function call","code":"def MinimumValue ( x , y ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT x , y = y , x NEW_LINE DEDENT a = 1 NEW_LINE b = x - 1 NEW_LINE c = y - b NEW_LINE print ( a , b , c ) NEW_LINE DEDENT x = 123 NEW_LINE y = 13 NEW_LINE MinimumValue ( x , y ) NEW_LINE"} +{"text":"Check whether it is possible to convert A into B | Function that returns true if A can be converted to B with the given operations ; If the current number ends with 1 ; If the current number is divisible by 2 ; If the above two conditions fail ; If it is possible to convert A to B ; Driver code","code":"def canConvert ( a , b ) : NEW_LINE INDENT while ( b > a ) : NEW_LINE INDENT if ( b % 10 == 1 ) : NEW_LINE INDENT b \/\/= 10 ; NEW_LINE continue ; NEW_LINE DEDENT if ( b % 2 == 0 ) : NEW_LINE INDENT b \/= 2 ; NEW_LINE continue ; NEW_LINE DEDENT return false ; NEW_LINE DEDENT if ( b == a ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = 2 ; B = 82 ; NEW_LINE if ( canConvert ( A , B ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT DEDENT"} +{"text":"Count Distinct Rectangles in N * N Chessboard | Function to return the count of distinct rectangles ; Driver Code","code":"def count ( N ) : NEW_LINE INDENT a = 0 ; NEW_LINE a = ( N * ( N + 1 ) ) \/ 2 ; NEW_LINE return int ( a ) ; NEW_LINE DEDENT N = 4 ; NEW_LINE print ( count ( N ) ) ; NEW_LINE"} +{"text":"Total number of days taken to complete the task if after certain days one person leaves | Function to return the number of days required ; Driver code","code":"def numberOfDays ( a , b , n ) : NEW_LINE INDENT Days = b * ( n + a ) \/\/ ( a + b ) NEW_LINE return Days NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 10 NEW_LINE b = 20 NEW_LINE n = 5 NEW_LINE print ( numberOfDays ( a , b , n ) ) NEW_LINE DEDENT"} +{"text":"Find average of two numbers using bit operation | Function to return the average of x and y using bit operations ; Calculate the average Floor value of ( x + y ) \/ 2 ; Driver code","code":"def getAverage ( x , y ) : NEW_LINE INDENT avg = ( x & y ) + ( ( x ^ y ) >> 1 ) ; NEW_LINE return avg NEW_LINE DEDENT x = 10 NEW_LINE y = 9 NEW_LINE print ( getAverage ( x , y ) ) NEW_LINE"} +{"text":"Smallest index such that there are no 0 or 1 to its right | Function to find the smallest index such that there are no 0 or 1 to its right ; Initially ; Traverse in the array ; Check if array element is 1 ; a [ i ] = 0 ; Return minimum of both ; Driver code","code":"def smallestIndex ( a , n ) : NEW_LINE INDENT right1 = 0 NEW_LINE right0 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT right1 = i NEW_LINE DEDENT else : NEW_LINE INDENT right0 = i NEW_LINE DEDENT DEDENT return min ( right1 , right0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( smallestIndex ( a , n ) ) NEW_LINE DEDENT"} +{"text":"Total position where king can reach on a chessboard in exactly M moves | Set 2 | Function to return the count of squares that can be visited by king in m moves ; To store the count of squares ; Check all squares of the chessboard ; Check if square ( i , j ) is at a distance <= m units from king 's current position ; Return count of squares ; Driver code","code":"def countSquares ( r , c , m ) : NEW_LINE INDENT squares = 0 NEW_LINE for i in range ( 1 , 9 ) : NEW_LINE INDENT for j in range ( 1 , 9 ) : NEW_LINE INDENT if ( max ( abs ( i - r ) , abs ( j - c ) ) <= m ) : NEW_LINE INDENT squares = squares + 1 NEW_LINE DEDENT DEDENT DEDENT return squares NEW_LINE DEDENT r = 4 NEW_LINE c = 4 NEW_LINE m = 1 NEW_LINE print ( countSquares ( r , c , m ) ) ; NEW_LINE"} +{"text":"Number of quadruples where the first three terms are in AP and last three terms are in GP | Function to return the count of quadruples ; Hash table to count the number of occurrences ; Traverse and increment the count ; Run two nested loop for second and third element ; If they are same ; Initially decrease the count ; Find the first element using common difference ; Find the fourth element using GP y ^ 2 = x * z property ; If it is an integer ; If not equal ; Same elements ; Later increase the value for future calculations ; Driver code","code":"def countQuadruples ( a , n ) : NEW_LINE INDENT mpp = dict . fromkeys ( a , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mpp [ a [ i ] ] += 1 ; NEW_LINE DEDENT count = 0 ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT for k in range ( n ) : NEW_LINE INDENT if ( j == k ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT mpp [ a [ j ] ] -= 1 ; NEW_LINE mpp [ a [ k ] ] -= 1 ; NEW_LINE first = a [ j ] - ( a [ k ] - a [ j ] ) ; NEW_LINE if first not in mpp : NEW_LINE INDENT mpp [ first ] = 0 ; NEW_LINE DEDENT fourth = ( a [ k ] * a [ k ] ) \/\/ a [ j ] ; NEW_LINE if fourth not in mpp : NEW_LINE INDENT mpp [ fourth ] = 0 ; NEW_LINE DEDENT if ( ( a [ k ] * a [ k ] ) % a [ j ] == 0 ) : NEW_LINE INDENT if ( a [ j ] != a [ k ] ) : NEW_LINE INDENT count += mpp [ first ] * mpp [ fourth ] ; NEW_LINE DEDENT else : NEW_LINE INDENT count += ( mpp [ first ] * ( mpp [ fourth ] - 1 ) ) ; NEW_LINE DEDENT DEDENT mpp [ a [ j ] ] += 1 ; NEW_LINE mpp [ a [ k ] ] += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 2 , 6 , 4 , 9 , 2 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( countQuadruples ( a , n ) ) ; NEW_LINE DEDENT"} +{"text":"Numbers in a Range with given Digital Root | Function to return the count of required numbers ; Count of numbers present in given range ; Number of groups of 9 elements starting from L ; Left over elements not covered in factor 9 ; One Number in each group of 9 ; To check if any number in rem satisfy the property ; Driver code","code":"def countNumbers ( L , R , K ) : NEW_LINE INDENT if ( K == 9 ) : NEW_LINE INDENT K = 0 NEW_LINE DEDENT totalnumbers = R - L + 1 NEW_LINE factor9 = totalnumbers \/\/ 9 NEW_LINE rem = totalnumbers % 9 NEW_LINE ans = factor9 NEW_LINE for i in range ( R , R - rem , - 1 ) : NEW_LINE INDENT rem1 = i % 9 NEW_LINE if ( rem1 == K ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT L = 10 NEW_LINE R = 22 NEW_LINE K = 3 NEW_LINE print ( countNumbers ( L , R , K ) ) NEW_LINE"} +{"text":"Sum of even values and update queries on an array | Function to return the sum of even elements after updating value at given index ; Add given value to A [ index ] ; To store the sum of even elements ; If current element is even ; Function to print result for every query ; Resultant vector that stores the result for every query ; Get sum of even elements after updating value at given index ; Store sum for each query ; Print the result for every query ; Driver code","code":"def EvenSum ( A , index , value ) : NEW_LINE INDENT A [ index ] = A [ index ] + value NEW_LINE sum = 0 NEW_LINE for i in A : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT sum = sum + i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT def BalanceArray ( A , Q ) : NEW_LINE INDENT ANS = [ ] NEW_LINE i , sum = 0 , 0 NEW_LINE for i in range ( len ( Q ) ) : NEW_LINE INDENT index = Q [ i ] [ 0 ] NEW_LINE value = Q [ i ] [ 1 ] NEW_LINE sum = EvenSum ( A , index , value ) NEW_LINE ANS . append ( sum ) NEW_LINE DEDENT for i in ANS : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT A = [ 1 , 2 , 3 , 4 ] NEW_LINE Q = [ [ 0 , 1 ] , [ 1 , - 3 ] , [ 0 , - 4 ] , [ 3 , 2 ] ] NEW_LINE BalanceArray ( A , Q ) NEW_LINE"} +{"text":"Sum of even values and update queries on an array | Function to print the result for every query ; If current element is even ; If element is even then remove it from sum ; If the value becomes even after updating ; Store sum for each query ; Print the result for every query ; Driver code","code":"def BalanceArray ( A , Q ) : NEW_LINE INDENT ANS = [ ] NEW_LINE sum = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT sum += A [ i ] ; NEW_LINE DEDENT DEDENT for i in range ( len ( Q ) ) : NEW_LINE INDENT index = Q [ i ] [ 0 ] ; NEW_LINE value = Q [ i ] [ 1 ] ; NEW_LINE if ( A [ index ] % 2 == 0 ) : NEW_LINE INDENT sum -= A [ index ] ; NEW_LINE DEDENT A [ index ] += value ; NEW_LINE if ( A [ index ] % 2 == 0 ) : NEW_LINE INDENT sum += A [ index ] ; NEW_LINE DEDENT ANS . append ( sum ) ; NEW_LINE DEDENT for i in range ( len ( ANS ) ) : NEW_LINE INDENT print ( ANS [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 ] ; NEW_LINE Q = [ [ 0 , 1 ] , [ 1 , - 3 ] , [ 0 , - 4 ] , [ 3 , 2 ] ] ; NEW_LINE BalanceArray ( A , Q ) ; NEW_LINE DEDENT"} +{"text":"Number of Hamiltonian cycle | Python3 program for implementation of the above program ; Function that calculates number of Hamiltonian cycle ; Calculating factorial ; Driver code","code":"import math as mt NEW_LINE def Cycles ( N ) : NEW_LINE INDENT fact = 1 NEW_LINE result = N - 1 NEW_LINE i = result NEW_LINE while ( i > 0 ) : NEW_LINE INDENT fact = fact * i NEW_LINE i -= 1 NEW_LINE DEDENT return fact \/\/ 2 NEW_LINE DEDENT N = 5 NEW_LINE Number = Cycles ( N ) NEW_LINE print ( \" Hamiltonian \u2581 cycles \u2581 = \u2581 \" , Number ) NEW_LINE"} +{"text":"Smallest integer greater than n such that it consists of digit m exactly k times | Function that returns true if n contains digit m exactly k times ; Function to return the smallest integer > n with digit m occurring exactly k times ; Driver code","code":"def digitWell ( n , m , k ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n % 10 == m ) : NEW_LINE INDENT cnt = cnt + 1 ; NEW_LINE DEDENT n = ( int ) ( n \/ 10 ) ; NEW_LINE DEDENT return cnt == k ; NEW_LINE DEDENT def findInt ( n , m , k ) : NEW_LINE INDENT i = n + 1 ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( digitWell ( i , m , k ) ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT i = i + 1 ; NEW_LINE DEDENT DEDENT n = 111 ; m = 2 ; k = 2 ; NEW_LINE print ( findInt ( n , m , k ) ) ; NEW_LINE"} +{"text":"Composite XOR and Coprime AND | Function to return the count of odd numbers in the array ; Variable to count odd numbers ; Odd number ; Function to return the count of valid pairs ; Driver Code","code":"def countOdd ( arr , n ) : NEW_LINE INDENT odd = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 1 ) : NEW_LINE INDENT odd = odd + 1 ; NEW_LINE DEDENT DEDENT return odd ; NEW_LINE DEDENT def countValidPairs ( arr , n ) : NEW_LINE INDENT odd = countOdd ( arr , n ) ; NEW_LINE return ( odd * ( odd - 1 ) ) \/ 2 ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( int ( countValidPairs ( arr , n ) ) ) ; NEW_LINE"} +{"text":"Smallest perfect Cube divisible by all elements of an array | Function to return the gcd of two numbers ; Function to return the lcm of all the elements of the array ; To calculate lcm of two numbers multiply them and divide the result by gcd of both the numbers ; Return the LCM of the array elements ; Function to return the smallest perfect cube divisible by all the elements of arr [ ] ; LCM of all the elements of arr [ ] ; If 2 divides lcm cnt number of times ; Check all the numbers that divide lcm ; Return the answer ; Driver code","code":"def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def lcmOfArray ( arr , n ) : NEW_LINE INDENT if ( n < 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT lcm = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT lcm = ( lcm * arr [ i ] ) \/\/ gcd ( lcm , arr [ i ] ) ; NEW_LINE DEDENT return lcm NEW_LINE DEDENT def minPerfectCube ( arr , n ) : NEW_LINE INDENT lcm = lcmOfArray ( arr , n ) NEW_LINE minPerfectCube = lcm NEW_LINE cnt = 0 NEW_LINE while ( lcm > 1 and lcm % 2 == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE lcm \/\/= 2 NEW_LINE DEDENT if ( cnt % 3 == 2 ) : NEW_LINE INDENT minPerfectCube *= 2 NEW_LINE DEDENT elif ( cnt % 3 == 1 ) : NEW_LINE INDENT minPerfectCube *= 4 NEW_LINE DEDENT i = 3 NEW_LINE while ( lcm > 1 ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( lcm % i == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE lcm \/\/= i NEW_LINE DEDENT if ( cnt % 3 == 1 ) : NEW_LINE INDENT minPerfectCube *= i * i NEW_LINE DEDENT elif ( cnt % 3 == 2 ) : NEW_LINE INDENT minPerfectCube *= i NEW_LINE DEDENT i += 2 NEW_LINE DEDENT return minPerfectCube NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 10 , 125 , 14 , 42 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minPerfectCube ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Check if N is Strong Prime | Python 3 program to check if given number is strong prime ; Utility function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if n is a strong prime ; If n is not a prime number or n is the first prime then return false ; Initialize previous_prime to n - 1 and next_prime to n + 1 ; Find next prime number ; Find previous prime number ; Arithmetic mean ; If n is a strong prime ; Driver code","code":"from math import sqrt NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT k = int ( sqrt ( n ) ) + 1 NEW_LINE for i in range ( 5 , k , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isStrongPrime ( n ) : NEW_LINE INDENT if ( isPrime ( n ) == False or n == 2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT previous_prime = n - 1 NEW_LINE next_prime = n + 1 NEW_LINE while ( isPrime ( next_prime ) == False ) : NEW_LINE INDENT next_prime += 1 NEW_LINE DEDENT while ( isPrime ( previous_prime ) == False ) : NEW_LINE INDENT previous_prime -= 1 NEW_LINE DEDENT mean = ( previous_prime + next_prime ) \/ 2 NEW_LINE if ( n > mean ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 11 NEW_LINE if ( isStrongPrime ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Minimum removals in a number to be divisible by 10 power raised to K | function to return the required number of digits to be removed ; Converting the given number into string ; variable to store number of digits to be removed ; variable to denote if atleast one zero has been found ; zero found ; return size - 1 if K is not zero and atleast one zero is present , otherwise result ; Driver Code","code":"def countDigitsToBeRemoved ( N , K ) : NEW_LINE INDENT s = str ( N ) ; NEW_LINE res = 0 ; NEW_LINE f_zero = 0 ; NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( K == 0 ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT f_zero = 1 ; NEW_LINE K -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT res += 1 ; NEW_LINE DEDENT DEDENT if ( K == 0 ) : NEW_LINE INDENT return res ; NEW_LINE DEDENT elif ( f_zero > 0 ) : NEW_LINE INDENT return len ( s ) - 1 ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT N = 10904025 ; NEW_LINE K = 2 ; NEW_LINE print ( countDigitsToBeRemoved ( N , K ) ) ; NEW_LINE N = 1000 ; NEW_LINE K = 5 ; NEW_LINE print ( countDigitsToBeRemoved ( N , K ) ) ; NEW_LINE N = 23985 ; NEW_LINE K = 2 ; NEW_LINE print ( countDigitsToBeRemoved ( N , K ) ) ; NEW_LINE"} +{"text":"Program to find the sum of the series ( 1 \/ a + 2 \/ a ^ 2 + 3 \/ a ^ 3 + ... + n \/ a ^ n ) | Python 3 program to find the sum of the given series ; Function to return the sum of the series ; variable to store the answer ; Math . pow ( x , y ) returns x ^ y ; Driver code ; Print the sum of the series","code":"import math NEW_LINE def getSum ( a , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += ( i \/ math . pow ( a , i ) ) ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT a = 3 ; n = 3 ; NEW_LINE print ( getSum ( a , n ) ) ; NEW_LINE"} +{"text":"Check if a number is an Unusual Number or not | Python Program to check Unusual number ; Utility function to find largest prime factor of a number ; Initialize the maximum prime factor variable with the lowest one ; Print the number of 2 s that divide n ; n must be odd at this point , thus skip the even numbers and iterate only for odd integers ; This condition is to handle the case when n is a prime number greater than 2 ; Function to check Unusual number ; Get the largest Prime Factor of the number ; Check if largest prime factor is greater than sqrt ( n ) ; Driver Code","code":"from math import sqrt NEW_LINE def largestPrimeFactor ( n ) : NEW_LINE INDENT max = - 1 NEW_LINE while n % 2 == 0 : NEW_LINE INDENT max = 2 ; NEW_LINE DEDENT for i in range ( 3 , int ( sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT while n % i == 0 : NEW_LINE INDENT max = i ; NEW_LINE n = n \/ i ; NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT max = n NEW_LINE DEDENT return max NEW_LINE DEDENT def checkUnusual ( n ) : NEW_LINE INDENT factor = largestPrimeFactor ( n ) NEW_LINE if factor > sqrt ( n ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 14 NEW_LINE if checkUnusual ( n ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Check if at least half array is reducible to zero by performing some operations | Function to print the desired result after computation ; Driver Code","code":"def isHalfReducible ( arr , n , m ) : NEW_LINE INDENT frequencyHash = [ 0 ] * ( m + 1 ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT frequencyHash [ ( arr [ i ] % ( m + 1 ) ) ] += 1 ; NEW_LINE i += 1 ; NEW_LINE DEDENT i = 0 ; NEW_LINE while ( i <= m ) : NEW_LINE INDENT if ( frequencyHash [ i ] >= ( n \/ 2 ) ) : NEW_LINE INDENT break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT if ( i <= m ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT DEDENT arr = [ 8 , 16 , 32 , 3 , 12 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE m = 7 ; NEW_LINE isHalfReducible ( arr , n , m ) ; NEW_LINE"} +{"text":"Check if the given number is Ore number or not | Python3 program to check if the given number is Ore number ; Function that returns harmonic mean ; Note that this loop runs till square root ; If divisors are equal , store 'i ; Otherwise store ' i ' and ' n \/ i ' both ; Utility function to calculate harmonic mean of the divisors ; Declare sum variables and initialize with zero . ; calculate denominator ; Calculate harmonic mean and return ; Function to check if a number is ore number ; Calculate Harmonic mean of divisors of n ; Check if harmonic mean is an integer or not ; Driver Code","code":"arr = [ ] NEW_LINE def generateDivisors ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( n ** ( 0.5 ) ) + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if n \/\/ i == i : NEW_LINE INDENT arr . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT arr . append ( i ) NEW_LINE arr . append ( n \/\/ i ) NEW_LINE DEDENT DEDENT def harmonicMean ( n ) : NEW_LINE INDENT generateDivisors ( n ) NEW_LINE Sum = 0 NEW_LINE length = len ( arr ) NEW_LINE for i in range ( 0 , length ) : NEW_LINE INDENT Sum = Sum + ( n \/ arr [ i ] ) NEW_LINE DEDENT Sum = Sum \/ n NEW_LINE return length \/ Sum NEW_LINE DEDENT def isOreNumber ( n ) : NEW_LINE INDENT mean = harmonicMean ( n ) NEW_LINE if mean - int ( mean ) == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 28 NEW_LINE if isOreNumber ( n ) == True : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Check whether the given number is Euclid Number or not | Python3 program to check Euclid Number ; Function to generate the Prime numbers and store their products ; 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 ; Update all multiples of p ; store prefix product of prime numbers to unordered_set 's ; update product by multiplying next prime ; insert ' produc + 1' to set ; Function to check the number for Euclid Number ; Check if number exist in unordered set or not If exist , return true ; Driver code ; Get the prime numbers ; Get n ; Check if n is Euclid Number ; Get n ; Check if n is Euclid Number","code":"MAX = 10000 NEW_LINE s = set ( ) NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime = [ True ] * ( MAX ) NEW_LINE prime [ 0 ] , prime [ 1 ] = False , False NEW_LINE for p in range ( 2 , 100 ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( p * 2 , MAX , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT ' NEW_LINE INDENT product = 1 NEW_LINE for p in range ( 2 , MAX ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT product = product * p NEW_LINE s . add ( product + 1 ) NEW_LINE DEDENT DEDENT DEDENT def isEuclid ( n ) : NEW_LINE INDENT if n in s : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE n = 31 NEW_LINE if isEuclid ( n ) == True : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT n = 42 NEW_LINE if isEuclid ( n ) == True : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Check whether the given number is Wagstaff prime or not | Utility function to check if a number is prime or not ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Utility function to Check power of two ; Driver Code ; Check if number is prime and of the form ( 2 ^ q + 1 ) \/ 3","code":"def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def isPowerOfTwo ( n ) : NEW_LINE INDENT return ( n and ( not ( n & ( n - 1 ) ) ) ) NEW_LINE DEDENT n = 43 NEW_LINE if ( isPrime ( n ) and isPowerOfTwo ( n * 3 - 1 ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} +{"text":"Area of a square inscribed in a circle which is inscribed in a hexagon | Python 3 Program to find the area of the square inscribed within the circle which in turn is inscribed in a hexagon ; Function to find the area of the square ; side of hexagon cannot be negative ; area of the square ; Driver code","code":"from math import pow , sqrt NEW_LINE def area ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT area = pow ( ( a * sqrt ( 3 ) ) \/ ( sqrt ( 2 ) ) , 2 ) NEW_LINE return area NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 5 NEW_LINE print ( \" { 0 : . 3 } \" . format ( area ( a ) ) ) NEW_LINE DEDENT"} +{"text":"Program to find Nth term of series 1 , 6 , 17 , 34 , 56 , 86 , 121 , 162 , ... ... . | calculate Nth term of series ; Driver code","code":"def nthTerm ( n ) : NEW_LINE INDENT return 3 * pow ( n , 2 ) - 4 * n + 2 NEW_LINE DEDENT N = 4 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE"} +{"text":"Sum of the first N terms of the series 2 , 10 , 30 , 68 , ... . | Function to calculate the sum ; number of terms to be included in the sum ; find the Sum","code":"def calculateSum ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) \/\/ 2 + pow ( ( n * ( n + 1 ) \/\/ 2 ) , 2 ) ) NEW_LINE DEDENT n = 3 NEW_LINE print ( \" Sum \u2581 = \u2581 \" , calculateSum ( n ) ) NEW_LINE"} +{"text":"Check if two arrays are permutations of each other using Mathematical Operation | Function to check if arrays are permutations of each other ; Calculating sum and multiply of first array ; Calculating sum and multiply of second array ; If sum and mul of both arrays are equal , return true , else return false . ; Driver code","code":"def arePermutations ( a , b , n , m ) : NEW_LINE INDENT sum1 , sum2 , mul1 , mul2 = 0 , 0 , 1 , 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum1 += a [ i ] NEW_LINE mul1 *= a [ i ] NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT sum2 += b [ i ] NEW_LINE mul2 *= b [ i ] NEW_LINE DEDENT return ( ( sum1 == sum2 ) and ( mul1 == mul2 ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 3 , 2 ] NEW_LINE b = [ 3 , 1 , 2 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE if arePermutations ( a , b , n , m ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Program to find the head start in a race | Function to find the B start to C ; When B completed it 's 100 meter then Completed meters by C is ; Driver Code ; When A completed it 's 100 meter Then completed meters of B and C is","code":"def Race ( B , C ) : NEW_LINE INDENT result = 0 ; NEW_LINE result = ( ( C * 100 ) \/\/ B ) NEW_LINE return 100 - result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT B = 10 NEW_LINE C = 28 NEW_LINE B = 100 - B ; NEW_LINE C = 100 - C ; NEW_LINE print ( str ( Race ( B , C ) ) + \" \u2581 meters \" ) NEW_LINE DEDENT"} +{"text":"Minimum time required to fill a cistern using N pipes | Function to calculate the time ; Driver Code","code":"def Time ( arr , n , Emptypipe ) : NEW_LINE INDENT fill = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT fill += ( 1 \/ arr [ i ] ) NEW_LINE DEDENT fill = fill - ( 1 \/ float ( Emptypipe ) ) NEW_LINE return int ( 1 \/ fill ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 14 ] NEW_LINE Emptypipe = 30 NEW_LINE n = len ( arr ) NEW_LINE print ( ( Time ( arr , n , Emptypipe ) ) , \" Hours \" ) NEW_LINE DEDENT"} +{"text":"Check if Decimal representation of an Octal number is divisible by 7 | Function to check Divisibility ; Sum of all individual digits ; Condition ; Driver Code ; Octal number","code":"def check ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while n != 0 : NEW_LINE INDENT sum += n % 10 NEW_LINE n = n \/\/ 10 NEW_LINE DEDENT if sum % 7 == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 25 NEW_LINE print ( ( \" YES \" ) if check ( n ) == 1 else print ( \" NO \" ) ) NEW_LINE DEDENT"} +{"text":"Sum of all the prime divisors of a number | Python 3 program to find sum of prime divisors of N ; Function to check if the number is prime or not . ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; function to find sum of prime divisors of N ; Driver code","code":"N = 1000005 NEW_LINE def isPrime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return True NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def SumOfPrimeDivisors ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT if isPrime ( i ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT n = 60 NEW_LINE print ( \" Sum \u2581 of \u2581 prime \u2581 divisors \u2581 of \u2581 60 \u2581 is \u2581 \" + str ( SumOfPrimeDivisors ( n ) ) ) NEW_LINE"} +{"text":"Sum of all the prime divisors of a number | function to find prime divisors of all numbers from 1 to n ; if the number is prime ; add this prime to all it 's multiples ; Driver code","code":"def Sum ( N ) : NEW_LINE INDENT SumOfPrimeDivisors = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if ( SumOfPrimeDivisors [ i ] == 0 ) : NEW_LINE INDENT for j in range ( i , N + 1 , i ) : NEW_LINE INDENT SumOfPrimeDivisors [ j ] += i NEW_LINE DEDENT DEDENT DEDENT return SumOfPrimeDivisors [ N ] NEW_LINE DEDENT N = 60 NEW_LINE print ( \" Sum \u2581 of \u2581 prime \" , \" divisors \u2581 of \u2581 60 \u2581 is \" , Sum ( N ) ) ; NEW_LINE"} +{"text":"Find ( a ^ b ) % m where ' b ' is very large | Function to find power ; Update x if it is more than or equal to p ; If y is odd , multiply x with the result ; y must be even now y = y >> 1 y = y \/ 2 ; Driver Code ; String input as b is very large ; Reduce the number B to a small number using Fermat Little","code":"def power ( x , y , p ) : NEW_LINE INDENT x = x % p NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT a = 3 NEW_LINE b = \"100000000000000000000000000\" NEW_LINE remainderB = 0 NEW_LINE MOD = 1000000007 NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT remainderB = ( ( remainderB * 10 + ord ( b [ i ] ) - 48 ) % ( MOD - 1 ) ) NEW_LINE DEDENT print ( power ( a , remainderB , MOD ) ) NEW_LINE"} +{"text":"Squares of numbers with repeated single digits | Set 1 ( 3 , 6 and 9 ) | Function to find the square of 333. . .333 , 666. . .666 and 999. . .999 ; if the number is 333. . .333 ; if the number is 666. . .666 ; if the number is 999. . .999 ; variable for hold result ; find the no of digit ; add size - 1 time a in result ; add one time b in result ; add size - 1 time c in result ; add one time d in result ; return result ; Drivers code Your Python 3 Code ; find square of 33. .33 ; find square of 66. .66 ; find square of 66. .66","code":"def find_Square_369 ( num ) : NEW_LINE INDENT if ( num [ 0 ] == '3' ) : NEW_LINE INDENT a = '1' NEW_LINE b = '0' NEW_LINE c = '8' NEW_LINE d = '9' NEW_LINE DEDENT elif ( num [ 0 ] == '6' ) : NEW_LINE INDENT a = '4' NEW_LINE b = '3' NEW_LINE c = '5' NEW_LINE d = '6' NEW_LINE DEDENT else : NEW_LINE INDENT a = '9' NEW_LINE b = '8' NEW_LINE c = '0' NEW_LINE d = '1' NEW_LINE DEDENT result = \" \" NEW_LINE size = len ( num ) NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT result += a NEW_LINE DEDENT result += b NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT result += c NEW_LINE DEDENT result += d NEW_LINE return result NEW_LINE DEDENT num_3 = \"3333\" NEW_LINE num_6 = \"6666\" NEW_LINE num_9 = \"9999\" NEW_LINE result = \" \" NEW_LINE result = find_Square_369 ( num_3 ) NEW_LINE print ( \" Square \u2581 of \u2581 \" + num_3 + \" \u2581 is \u2581 : \u2581 \" + result ) ; NEW_LINE result = find_Square_369 ( num_6 ) NEW_LINE print ( \" Square \u2581 of \u2581 \" + num_6 + \" \u2581 is \u2581 : \u2581 \" + result ) ; NEW_LINE result = find_Square_369 ( num_9 ) NEW_LINE print ( \" Square \u2581 of \u2581 \" + num_9 + \" \u2581 is \u2581 : \u2581 \" + result ) ; NEW_LINE"} +{"text":"Trick for modular division ( ( x1 * x2 ... . xn ) \/ b ) mod ( m ) | Python3 program to implement the above approach To run this code , we need to copy modular inverse from below post . https : www . geeksforgeeks . org \/ multiplicative - inverse - under - modulo - m \/ ; naive method - calculating the result in a single line ; modular_inverse ( ) is a user defined function that calculates inverse of a number ; it will use extended Eucledian algorithm or Fermat 's Little Theorem for calculation. MMI of 120 under division by 1000000007 will be 808333339","code":"if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT naive_answer = ( ( ( 55555 * 55554 * 55553 * 55552 * 55551 ) \/\/ 120 ) % 1000000007 ) NEW_LINE ans = 1 NEW_LINE i = modular_inverse ( 120 , 10000007 ) NEW_LINE for i in range ( 5 ) : NEW_LINE INDENT ans = ( ( ans * ( 55555 - i ) ) % 1000000007 ) NEW_LINE DEDENT ans = ( ans * i ) % 1000000007 NEW_LINE print ( \" Answer \u2581 using \u2581 naive \u2581 method : \" , naive_answer ) NEW_LINE print ( \" Answer \u2581 using \u2581 multiplicative \" + \" modular \u2581 inverse \u2581 concept : \" , ans ) NEW_LINE DEDENT"} +{"text":"Trick for modular division ( ( x1 * x2 ... . xn ) \/ b ) mod ( m ) |","code":"ans = 1 NEW_LINE mod = 1000000007 * 120 NEW_LINE for i in range ( 0 , 5 ) : NEW_LINE INDENT ans = ( ans * ( 55555 - i ) ) % mod NEW_LINE DEDENT ans = int ( ans \/ 120 ) NEW_LINE print ( \" Answer \u2581 using \u2581 shortcut : \u2581 \" , ans ) NEW_LINE"} +{"text":"Ways to multiply n elements with an associative operation | Function to find the required factorial ; Function to find nCr ; function to find the number of ways ; Driver code","code":"def fact ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans = ans * i ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT Nr = n ; Dr = 1 ; ans = 1 ; NEW_LINE for i in range ( 1 , r + 1 ) : NEW_LINE INDENT ans = int ( ( ans * Nr ) \/ ( Dr ) ) ; NEW_LINE Nr = Nr - 1 ; NEW_LINE Dr = Dr + 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def solve ( n ) : NEW_LINE INDENT N = 2 * n - 2 ; NEW_LINE R = n - 1 ; NEW_LINE return ( nCr ( N , R ) * fact ( n - 1 ) ) ; NEW_LINE DEDENT n = 6 ; NEW_LINE print ( solve ( n ) ) ; NEW_LINE"} +{"text":"Pythagorean Triplet with given sum | Python3 program to find Pythagorean Triplet of given sum . ; Considering triplets in sorted order . The value of first element in sorted triplet can be at - most n \/ 3. ; The value of second element must be less than equal to n \/ 2 ; Driver Code","code":"def pythagoreanTriplet ( n ) : NEW_LINE INDENT for i in range ( 1 , int ( n \/ 3 ) + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , int ( n \/ 2 ) + 1 ) : NEW_LINE INDENT k = n - i - j NEW_LINE if ( i * i + j * j == k * k ) : NEW_LINE INDENT print ( i , \" , \u2581 \" , j , \" , \u2581 \" , k , sep = \" \" ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( \" No \u2581 Triplet \" ) NEW_LINE DEDENT n = 12 NEW_LINE pythagoreanTriplet ( n ) NEW_LINE"} +{"text":"Program to print binomial expansion series | function to calculate factorial of a number ; Function to print the series ; calculating the value of n ! ; loop to display the series ; For calculating the value of nCr ; calculating the value of A to the power k and X to the power k ; display the series ; Driver Code","code":"def factorial ( n ) : NEW_LINE INDENT f = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT f *= i NEW_LINE DEDENT return f NEW_LINE DEDENT def series ( A , X , n ) : NEW_LINE INDENT nFact = factorial ( n ) NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT niFact = factorial ( n - i ) NEW_LINE iFact = factorial ( i ) NEW_LINE aPow = pow ( A , n - i ) NEW_LINE xPow = pow ( X , i ) NEW_LINE print ( int ( ( nFact * aPow * xPow ) \/ ( niFact * iFact ) ) , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT A = 3 ; X = 4 ; n = 5 NEW_LINE series ( A , X , n ) NEW_LINE"} +{"text":"Sum of series with alternate signed squares of AP | Function to calculate series sum ; Driver code","code":"def seiresSum ( n , a ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( 0 , 2 * n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT res += a [ i ] * a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT res -= a [ i ] * a [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT n = 2 NEW_LINE a = [ 1 , 2 , 3 , 4 ] NEW_LINE print ( seiresSum ( n , a ) ) NEW_LINE"} +{"text":"Power of a prime number \u2018 r \u2019 in n ! | Function to return power of a no . ' r ' in factorial of n ; Keep dividing n by powers of ' r ' and update count ; Driver Code","code":"def power ( n , r ) : NEW_LINE INDENT count = 0 ; i = r NEW_LINE while ( ( n \/ i ) >= 1 ) : NEW_LINE INDENT count += n \/ i NEW_LINE i = i * r NEW_LINE DEDENT return int ( count ) NEW_LINE DEDENT n = 6 ; r = 3 NEW_LINE print ( power ( n , r ) ) NEW_LINE"} +{"text":"Average of first n odd naturals numbers | Returns the Avg of first n odd numbers ; sum of first n odd number ; Average of first n odd numbers ; Driver Code","code":"def avg_of_odd_num ( n ) : NEW_LINE INDENT sm = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sm = sm + ( 2 * i + 1 ) NEW_LINE DEDENT return sm \/\/ n NEW_LINE DEDENT n = 20 NEW_LINE print ( avg_of_odd_num ( n ) ) NEW_LINE"} +{"text":"Average of first n odd naturals numbers | Return the average of sum of first n odd numbers ; Driver Code","code":"def avg_of_odd_num ( n ) : NEW_LINE INDENT return n NEW_LINE DEDENT n = 8 NEW_LINE print ( avg_of_odd_num ( n ) ) NEW_LINE"} +{"text":"Program to print Fibonacci Triangle | function to fill Fibonacci Numbers in f [ ] ; 1 st and 2 nd number of the series are 1 and 1 ; Add the previous 2 numbers in the series and store it ; Fill Fibonacci numbers in f [ ] using fib ( ) . We need N = n * ( n + 1 ) \/ 2 Fibonacci numbers to make a triangle of height n ; To store next Fibonacci Number to print ; for loop to keep track of number of lines ; For loop to keep track of numbers in each line ; Driver code","code":"def fib ( f , N ) : NEW_LINE INDENT f [ 1 ] = 1 NEW_LINE f [ 2 ] = 1 NEW_LINE for i in range ( 3 , N + 1 ) : NEW_LINE INDENT f [ i ] = f [ i - 1 ] + f [ i - 2 ] NEW_LINE DEDENT DEDENT def fiboTriangle ( n ) : NEW_LINE INDENT N = n * ( n + 1 ) \/\/ 2 NEW_LINE f = [ 0 ] * ( N + 1 ) NEW_LINE fib ( f , N ) NEW_LINE fiboNum = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT print ( f [ fiboNum ] , \" \u2581 \" , end = \" \" ) NEW_LINE fiboNum = fiboNum + 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE fiboTriangle ( n ) NEW_LINE"} +{"text":"Average of odd numbers till a given odd number | Function to calculate the average of odd numbers ; count odd numbers ; store the sum of odd numbers ; Driver function","code":"def averageOdd ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return - 1 NEW_LINE DEDENT sm = 0 NEW_LINE count = 0 NEW_LINE while ( n >= 1 ) : NEW_LINE INDENT count = count + 1 NEW_LINE sm = sm + n NEW_LINE n = n - 2 NEW_LINE DEDENT return sm \/\/ count NEW_LINE DEDENT n = 15 NEW_LINE print ( averageOdd ( n ) ) NEW_LINE"} +{"text":"Average of odd numbers till a given odd number | Function to calculate the average of odd numbers ; driver function","code":"def averageOdd ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return - 1 NEW_LINE DEDENT return ( n + 1 ) \/\/ 2 NEW_LINE DEDENT n = 15 NEW_LINE print ( averageOdd ( n ) ) NEW_LINE"} +{"text":"Find max of two Rational numbers | Python program to find max between two Rational numbers ; Get lcm of two number 's ; Get max rational number ; Find the LCM of first -> denominator and sec -> denominator ; Declare nume1 and nume2 for get the value of first numerator and second numerator ; Driver Code","code":"import math NEW_LINE def lcm ( a , b ) : NEW_LINE INDENT return ( a * b ) \/\/ ( math . gcd ( a , b ) ) NEW_LINE DEDENT def maxRational ( first , sec ) : NEW_LINE INDENT k = lcm ( first [ 1 ] , sec [ 1 ] ) NEW_LINE nume1 = first [ 0 ] NEW_LINE nume2 = sec [ 0 ] NEW_LINE nume1 *= k \/\/ ( first [ 1 ] ) NEW_LINE nume2 *= k \/\/ ( sec [ 1 ] ) NEW_LINE return first if ( nume2 < nume1 ) else sec NEW_LINE DEDENT first = [ 3 , 2 ] NEW_LINE sec = [ 3 , 4 ] NEW_LINE res = maxRational ( first , sec ) NEW_LINE print ( res [ 0 ] , \" \/ \" , res [ 1 ] , sep = \" \" ) NEW_LINE"} +{"text":"Trinomial Triangle | Function to find the trinomial triangle value . ; base case ; base cas ; recursive step . ; Function to print Trinomial Triangle of height n . ; printing n rows . ; printing first half of triangle ; printing second half of triangle . ; Driven Code","code":"def TrinomialValue ( n , k ) : NEW_LINE INDENT if n == 0 and k == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if k < - n or k > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( TrinomialValue ( n - 1 , k - 1 ) + TrinomialValue ( n - 1 , k ) + TrinomialValue ( n - 1 , k + 1 ) ) NEW_LINE DEDENT def printTrinomial ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( - i , 1 ) : NEW_LINE INDENT print ( TrinomialValue ( i , j ) , end = \" \u2581 \" ) NEW_LINE DEDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT print ( TrinomialValue ( i , j ) , end = \" \u2581 \" ) NEW_LINE DEDENT print ( \" \" , end = ' ' ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE printTrinomial ( n ) NEW_LINE"} +{"text":"Trinomial Triangle | Function to find the trinomial triangle value . ; Using property of trinomial triangle . ; If value already calculated , return that . ; base case ; base case ; recursive step and storing the value . ; Function to print Trinomial Triangle of height n . ; printing n rows . ; printing first half of triangle ; printing second half of triangle . ; Driven Program","code":"def TrinomialValue ( dp , n , k ) : NEW_LINE INDENT if k < 0 : NEW_LINE INDENT k = - k NEW_LINE DEDENT if dp [ n ] [ k ] != 0 : NEW_LINE INDENT return dp [ n ] [ k ] NEW_LINE DEDENT if n == 0 and k == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT if k < - n or k > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( TrinomialValue ( dp , n - 1 , k - 1 ) + TrinomialValue ( dp , n - 1 , k ) + TrinomialValue ( dp , n - 1 , k + 1 ) ) NEW_LINE DEDENT def printTrinomial ( n ) : NEW_LINE INDENT dp = [ [ 0 ] * 10 ] * 10 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( - i , 1 ) : NEW_LINE INDENT print ( TrinomialValue ( dp , i , j ) , end = \" \u2581 \" ) NEW_LINE DEDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT print ( TrinomialValue ( dp , i , j ) , end = \" \u2581 \" ) NEW_LINE DEDENT print ( \" \" , end = ' ' ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE printTrinomial ( n ) NEW_LINE"} +{"text":"Sum of largest prime factor of each number less than equal to n | function to find sum of largest prime factor of each number less than equal to n ; Create an integer array \" prime [ 0 . . n ] \" and initialize all entries of it as 0. A value in prime [ i ] will finally be 0 if ' i ' is a prime , else it will contain the largest prime factor of ' i ' . ; If prime [ p ] is '0' , then it is a prime number ; Update all multiples of p ; Sum up the largest prime factor of all the numbers ; if ' p ' is a non - prime number then prime [ p ] gives its largesr prime factor ; ' p ' is a prime number ; required sum ; Driver code to test above function","code":"def sumOfLargePrimeFactor ( n ) : NEW_LINE INDENT prime = [ 0 ] * ( n + 1 ) NEW_LINE sum = 0 NEW_LINE max = int ( n \/ 2 ) NEW_LINE for p in range ( 2 , max + 1 ) : NEW_LINE INDENT if prime [ p ] == 0 : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = p NEW_LINE DEDENT DEDENT DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if prime [ p ] : NEW_LINE INDENT sum += prime [ p ] NEW_LINE DEDENT else : NEW_LINE INDENT sum += p NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT n = 12 NEW_LINE print ( \" Sum \u2581 = \" , sumOfLargePrimeFactor ( n ) ) NEW_LINE"} +{"text":"Sum of multiples of a number up to N | Calculates sum of multiples of a number upto N ; Number of multiples ; sum of first m natural numbers ; sum of multiples ; Driver Code","code":"def calculate_sum ( a , N ) : NEW_LINE INDENT m = N \/ a NEW_LINE sum = m * ( m + 1 ) \/ 2 NEW_LINE ans = a * sum NEW_LINE print ( \" Sum \u2581 of \u2581 multiples \u2581 of \u2581 \" , a , \" \u2581 up \u2581 to \u2581 \" , N , \" \u2581 = \u2581 \" , ans ) NEW_LINE DEDENT calculate_sum ( 7 , 49 ) NEW_LINE"} +{"text":"Given a HUGE number check if it 's a power of two. | returns 1 when str is power of 2 return 0 when str is not a power of 2 ; sum stores the intermediate dividend while dividing . ; if the input is \"1\" then return 0 because 2 ^ k = 1 where k >= 1 and here k = 0 ; Divide the number until it gets reduced to 1 if we are successfully able to reduce the number to 1 it means input string is power of two if in between an odd number appears at the end it means string is not divisible by two hence not a power of 2. ; if the last digit is odd then string is not divisible by 2 hence not a power of two return 0. ; divide the whole string by 2. i is used to track index in current number . j is used to track index for next iteration . ; if num < 2 then we have to take another digit to the right of A [ i ] to make it bigger than A [ i ] . E . g . 214 \/ 2 -- > 107 ; if it 's not the first index. E.g 214 then we have to include 0. ; for eg . \"124\" we will not write 064 so if it is the first index just ignore ; After every division by 2 the length of string is changed . ; if the string reaches to 1 then the str is a power of 2. ; Driver code .","code":"def isPowerOf2 ( sttr ) : NEW_LINE INDENT len_str = len ( sttr ) ; NEW_LINE sttr = list ( sttr ) ; NEW_LINE num = 0 ; NEW_LINE if ( len_str == 1 and sttr [ len_str - 1 ] == '1' ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT while ( len_str != 1 or sttr [ len_str - 1 ] != '1' ) : NEW_LINE INDENT if ( ( ord ( sttr [ len_str - 1 ] ) - ord ( '0' ) ) % 2 == 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT j = 0 ; NEW_LINE for i in range ( len_str ) : NEW_LINE INDENT num = num * 10 + ( ord ( sttr [ i ] ) - ord ( '0' ) ) ; NEW_LINE if ( num < 2 ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT sttr [ j ] = '0' ; NEW_LINE j += 1 ; NEW_LINE DEDENT continue ; NEW_LINE DEDENT sttr [ j ] = chr ( ( num \/\/ 2 ) + ord ( '0' ) ) ; NEW_LINE j += 1 ; NEW_LINE num = ( num ) - ( num \/\/ 2 ) * 2 ; NEW_LINE DEDENT len_str = j ; NEW_LINE DEDENT return 1 ; NEW_LINE DEDENT str1 = \"124684622466842024680246842024662202000002\" ; NEW_LINE str2 = \"1\" ; NEW_LINE str3 = \"128\" ; NEW_LINE print ( \" \" , isPowerOf2 ( str1 ) , \" \" , isPowerOf2 ( str2 ) , \" \" , isPowerOf2 ( str3 ) ) ; NEW_LINE"} +{"text":"Given a HUGE number check if it 's a power of two. | Function to check whether a number is power of 2 or not ; Driver function","code":"def ispowerof2 ( num ) : NEW_LINE INDENT if ( ( num & ( num - 1 ) ) == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = 549755813888 NEW_LINE print ( ispowerof2 ( num ) ) NEW_LINE DEDENT"} +{"text":"Count divisors of array multiplication | To count number of factors in a number ; Initialize count with 0 ; Increment count for every factor of the given number X . ; Return number of factors ; Returns number of divisors in array multiplication ; Multipliying all elements of the given array . ; Calling function which count number of factors of the number ; Driver code","code":"def counDivisors ( X ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , X + 1 ) : NEW_LINE INDENT if ( X % i == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def countDivisorsMult ( arr , n ) : NEW_LINE INDENT mul = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT mul *= arr [ i ] NEW_LINE DEDENT return counDivisors ( mul ) NEW_LINE DEDENT arr = [ 2 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDivisorsMult ( arr , n ) ) NEW_LINE"} +{"text":"Count divisors of array multiplication | Python 3 program to count divisors in array multiplication . ; Create a boolean array \" isPrime [ 0 . . n ] \" and initialize all entries it as true . A value in isPrime [ i ] will finally be false if i is Not a isPrime , else true . ; If isPrime [ p ] is not changed , then it is a isPrime ; Update all multiples of p ; Print all isPrime numbers ; Returns number of divisors in array multiplication ; Find all prime numbers smaller than the largest element . ; Find counts of occurrences of each prime factor ; Compute count of all divisors using counts prime factors . ; Driver code","code":"from collections import defaultdict NEW_LINE def SieveOfEratosthenes ( largest , prime ) : NEW_LINE INDENT isPrime = [ True ] * ( largest + 1 ) NEW_LINE p = 2 NEW_LINE while p * p <= largest : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , largest + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , largest + 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT prime . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def countDivisorsMult ( arr , n ) : NEW_LINE INDENT largest = max ( arr ) NEW_LINE prime = [ ] NEW_LINE SieveOfEratosthenes ( largest , prime ) NEW_LINE mp = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( len ( prime ) ) : NEW_LINE INDENT while ( arr [ i ] > 1 and arr [ i ] % prime [ j ] == 0 ) : NEW_LINE INDENT arr [ i ] \/\/= prime [ j ] NEW_LINE mp [ prime [ j ] ] += 1 NEW_LINE DEDENT DEDENT if ( arr [ i ] != 1 ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT DEDENT res = 1 NEW_LINE for it in mp . values ( ) : NEW_LINE INDENT res *= ( it + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDivisorsMult ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"K distant prime pairs in a given range | Python3 program for the above approach ; Function to generate prime numbers in the given range [ L , R ] ; Store all value in the range ; Erase 1 as its non - prime ; Perform Sieve of Eratosthenes ; Find current multiple ; Erase as it is a non - prime ; Increment multiple ; Function to print all the prime pairs in the given range that differs by K ; Generate all prime number ; Traverse the Map M ; If it . first & ( it . first + K ) is prime then print this pair ; Driver Code ; Given range ; Given K ; Function Call","code":"from math import sqrt NEW_LINE def findPrimeNos ( L , R , M ) : NEW_LINE INDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT M [ i ] = M . get ( i , 0 ) + 1 NEW_LINE DEDENT if ( 1 in M ) : NEW_LINE INDENT M . pop ( 1 ) NEW_LINE DEDENT for i in range ( 2 , int ( sqrt ( R ) ) + 1 , 1 ) : NEW_LINE INDENT multiple = 2 NEW_LINE while ( ( i * multiple ) <= R ) : NEW_LINE INDENT if ( ( i * multiple ) in M ) : NEW_LINE INDENT M . pop ( i * multiple ) NEW_LINE DEDENT multiple += 1 NEW_LINE DEDENT DEDENT DEDENT def getPrimePairs ( L , R , K ) : NEW_LINE INDENT M = { } NEW_LINE findPrimeNos ( L , R , M ) NEW_LINE for key , values in M . items ( ) : NEW_LINE INDENT if ( ( key + K ) in M ) : NEW_LINE INDENT print ( \" ( \" , key , \" , \" , key + K , \" ) \" , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 1 NEW_LINE R = 19 NEW_LINE K = 6 NEW_LINE getPrimePairs ( L , R , K ) NEW_LINE DEDENT"} +{"text":"Enneacontahexagon numbers | Function to find the Nth Enneacontahexagon Number ; Driver Code","code":"def EnneacontahexagonNum ( n ) : NEW_LINE INDENT return ( 94 * n * n - 92 * n ) \/\/ 2 ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( EnneacontahexagonNum ( n ) ) ; NEW_LINE"} +{"text":"Find two Composite Numbers such that there difference is N | Function to find the two composite numbers ; Driver code","code":"def find_composite_nos ( n ) : NEW_LINE INDENT print ( 9 * n , 8 * n ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 4 ; NEW_LINE find_composite_nos ( n ) ; NEW_LINE DEDENT"} +{"text":"Count the number of pairs ( i , j ) such that either arr [ i ] is divisible by arr [ j ] or arr [ j ] is divisible by arr [ i ] | Function to find number of unordered pairs ; Maximum element from the array ; Array to store the frequency of each element ; Stores the number of unordered pairs ; Store the frequency of each element ; Find the number of unordered pairs ; If the number j divisible by ith element is present in the array ; If the ith element of the array has frequency more than one ; Driver code","code":"def freqPairs ( arr , n ) : NEW_LINE INDENT max = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if arr [ i ] > max : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT freq = [ 0 for i in range ( max + 1 ) ] NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( 2 * arr [ i ] , max + 1 , arr [ i ] ) : NEW_LINE INDENT if ( freq [ j ] >= 1 ) : NEW_LINE INDENT count += freq [ j ] NEW_LINE DEDENT DEDENT if ( freq [ arr [ i ] ] > 1 ) : NEW_LINE INDENT count += freq [ arr [ i ] ] - 1 NEW_LINE freq [ arr [ i ] ] -= 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 2 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( freqPairs ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Find the Nth term of the series 1 + 2 + 6 + 15 + 31 + 56 + ... | calculate Nth term of given series ; Driver code","code":"def Nth_Term ( n ) : NEW_LINE INDENT return ( 2 * pow ( n , 3 ) - 3 * pow ( n , 2 ) + n + 6 ) \/\/ 6 NEW_LINE DEDENT N = 8 NEW_LINE print ( Nth_Term ( N ) ) NEW_LINE"} +{"text":"Program to find N | Return n - th number in series made of 3 and 5 ; create an array of size ( n + 1 ) ; If i is odd ; Driver code","code":"def printNthElement ( n ) : NEW_LINE INDENT arr = [ 0 ] * ( n + 1 ) ; NEW_LINE arr [ 1 ] = 3 NEW_LINE arr [ 2 ] = 5 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT arr [ i ] = arr [ i \/\/ 2 ] * 10 + 3 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = arr [ ( i \/\/ 2 ) - 1 ] * 10 + 5 NEW_LINE DEDENT DEDENT return arr [ n ] NEW_LINE DEDENT n = 6 NEW_LINE print ( printNthElement ( n ) ) NEW_LINE"} +{"text":"Program to find Nth term of the series 3 , 6 , 18 , 24 , ... | function to calculate Nth term of series ; By using above formula ; get the value of N ; Calculate and print the Nth term","code":"def nthTerm ( N ) : NEW_LINE INDENT return ( N * ( ( N \/\/ 2 ) + ( ( N % 2 ) * 2 ) + N ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE print ( \" Nth \u2581 term \u2581 for \u2581 N \u2581 = \u2581 \" , N , \" \u2581 : \u2581 \" , nthTerm ( N ) ) NEW_LINE DEDENT"} +{"text":"Program to print binomial expansion series | Function to print the series ; Calculating and printing first term ; Computing and printing remaining terms ; Find current term using previous terms We increment power of X by 1 , decrement power of A by 1 and compute nCi using previous term by multiplying previous term with ( n - i + 1 ) \/ i ; Driver Code","code":"def series ( A , X , n ) : NEW_LINE INDENT term = pow ( A , n ) NEW_LINE print ( term , end = \" \u2581 \" ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT term = int ( term * X * ( n - i + 1 ) \/ ( i * A ) ) NEW_LINE print ( term , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT A = 3 ; X = 4 ; n = 5 NEW_LINE series ( A , X , n ) NEW_LINE"} +{"text":"Check if a number is divisible by 8 using bitwise operators | Python program to check whether the number is divisible by 8 or not using bitwise operator ; function to check number is div by 8 or not using bitwise operator ; driver code","code":"import math NEW_LINE def Div_by_8 ( n ) : NEW_LINE INDENT return ( ( ( n >> 3 ) << 3 ) == n ) NEW_LINE DEDENT n = 16 NEW_LINE if ( Div_by_8 ( n ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} +{"text":"Average of even numbers till a given even number | Function to calculate the average of even numbers ; count even numbers ; store the sum of even numbers ; driver function","code":"def averageEven ( n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return - 1 NEW_LINE DEDENT sm = 0 NEW_LINE count = 0 NEW_LINE while ( n >= 2 ) : NEW_LINE INDENT count = count + 1 NEW_LINE sm = sm + n NEW_LINE n = n - 2 NEW_LINE DEDENT return sm \/\/ count NEW_LINE DEDENT n = 16 NEW_LINE print ( averageEven ( n ) ) NEW_LINE"} +{"text":"Average of even numbers till a given even number | Function to calculate the average of even numbers ; Driver function","code":"def averageEven ( n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return - 1 NEW_LINE DEDENT return ( n + 2 ) \/\/ 2 NEW_LINE DEDENT n = 16 NEW_LINE print ( averageEven ( n ) ) NEW_LINE"} +{"text":"Largest number that divides x and is co | Recursive function to return gcd of a and b ; Everything divides 0 ; base case ; a is greater ; function to find largest coprime divisor ; divisor code","code":"def gcd ( a , b ) : NEW_LINE INDENT if a == 0 or b == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if a == b : NEW_LINE INDENT return a NEW_LINE DEDENT if a > b : NEW_LINE INDENT return gcd ( a - b , b ) NEW_LINE DEDENT return gcd ( a , b - a ) NEW_LINE DEDENT def cpFact ( x , y ) : NEW_LINE INDENT while gcd ( x , y ) != 1 : NEW_LINE INDENT x = x \/ gcd ( x , y ) NEW_LINE DEDENT return int ( x ) NEW_LINE DEDENT x = 15 NEW_LINE y = 3 NEW_LINE print ( cpFact ( x , y ) ) NEW_LINE x = 14 NEW_LINE y = 28 NEW_LINE print ( cpFact ( x , y ) ) NEW_LINE x = 7 NEW_LINE y = 3 NEW_LINE print ( cpFact ( x , y ) ) NEW_LINE"} +{"text":"Count numbers with unit digit k in given range | Returns count of numbers with k as last digit . ; Driver Program","code":"def counLastDigitK ( low , high , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( low , high + 1 ) : NEW_LINE INDENT if ( i % 10 == k ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT low = 3 NEW_LINE high = 35 NEW_LINE k = 3 NEW_LINE print ( counLastDigitK ( low , high , k ) ) NEW_LINE"} +{"text":"Taxicab Numbers | Python3 implementation to print first N Taxicab ( 2 ) numbers ; Starting from 1 , check every number if it is Taxicab until count reaches N . ; Try all possible pairs ( j , k ) whose cube sums can be i . ; Taxicab ( 2 ) found ; Driver code","code":"import math NEW_LINE def printTaxicab2 ( N ) : NEW_LINE INDENT i , count = 1 , 0 NEW_LINE while ( count < N ) : NEW_LINE INDENT int_count = 0 NEW_LINE for j in range ( 1 , math . ceil ( pow ( i , 1.0 \/ 3 ) ) + 1 ) : NEW_LINE INDENT for k in range ( j + 1 , math . ceil ( pow ( i , 1.0 \/ 3 ) ) + 1 ) : NEW_LINE INDENT if ( j * j * j + k * k * k == i ) : NEW_LINE INDENT int_count += 1 NEW_LINE DEDENT DEDENT DEDENT if ( int_count == 2 ) : NEW_LINE INDENT count += 1 NEW_LINE print ( count , \" \u2581 \" , i ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT N = 5 NEW_LINE printTaxicab2 ( N ) NEW_LINE"} +{"text":"Composite Number | A optimized school method based Python program to check if a number is composite . ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Driver Program to test above function","code":"def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return False NEW_LINE DEDENT print ( \" true \" ) if ( isComposite ( 11 ) ) else print ( \" false \" ) NEW_LINE print ( \" true \" ) if ( isComposite ( 15 ) ) else print ( \" false \" ) NEW_LINE"} +{"text":"Insert minimum number in array so that sum of array becomes prime | function to check if a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Find prime number greater than a number ; find prime greater than n ; check if num is prime ; Increment num ; To find number to be added so sum of array is prime ; To find sum of array elements ; If sum is already prime return 0 ; To find prime number greater than sum ; Return difference of sum and num ; Driver code","code":"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 findPrime ( n ) : NEW_LINE INDENT num = n + 1 NEW_LINE while ( num ) : NEW_LINE INDENT if isPrime ( num ) : NEW_LINE INDENT return num NEW_LINE DEDENT num += 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def minNumber ( arr ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT s += arr [ i ] NEW_LINE DEDENT if isPrime ( s ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT num = findPrime ( s ) NEW_LINE return num - s NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 8 , 12 ] NEW_LINE print ( minNumber ( arr ) ) NEW_LINE"} +{"text":"Sum of divisors of factorial of a number | function to calculate factorial ; function to calculate sum of divisor ; Returns sum of divisors of n ! ; Driver Code","code":"def fact ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return n * fact ( n - 1 ) NEW_LINE DEDENT def div ( x ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 1 , x + 1 ) : NEW_LINE INDENT if ( x % i == 0 ) : NEW_LINE INDENT ans += i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def sumFactDiv ( n ) : NEW_LINE INDENT return div ( fact ( n ) ) NEW_LINE DEDENT n = 4 NEW_LINE print ( sumFactDiv ( n ) ) NEW_LINE"} +{"text":"Sum of divisors of factorial of a number | allPrimes [ ] stores all prime numbers less than or equal to n . ; Fills above vector allPrimes [ ] for a given n ; 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 . ; Loop to update prime [ ] ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Store primes in the vector allPrimes ; Function to find all result of factorial number ; Initialize result ; find exponents of all primes which divides n and less than n ; Current divisor ; Find the highest power ( stored in exp ) ' \u2581 \u2581 of \u2581 allPrimes [ i ] \u2581 that \u2581 divides \u2581 n \u2581 using \u2581 \u2581 Legendre ' s formula . ; Using the divisor function to calculate the sum ; return total divisors ; Driver Code","code":"allPrimes = [ ] ; NEW_LINE def sieve ( n ) : NEW_LINE INDENT prime = [ True ] * ( n + 1 ) ; NEW_LINE p = 2 ; NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT p += 1 ; NEW_LINE DEDENT for p in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT allPrimes . append ( p ) ; NEW_LINE DEDENT DEDENT DEDENT def factorialDivisors ( n ) : NEW_LINE INDENT result = 1 ; NEW_LINE for i in range ( len ( allPrimes ) ) : NEW_LINE INDENT p = allPrimes [ i ] ; NEW_LINE exp = 0 ; NEW_LINE while ( p <= n ) : NEW_LINE INDENT exp = exp + int ( n \/ p ) ; NEW_LINE p = p * allPrimes [ i ] ; NEW_LINE DEDENT result = int ( result * ( pow ( allPrimes [ i ] , exp + 1 ) - 1 ) \/ ( allPrimes [ i ] - 1 ) ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT print ( factorialDivisors ( 4 ) ) ; NEW_LINE"} +{"text":"Pandigital number in a given base | Return true if n is pandigit else return false . ; Checking length is less than base ; Traversing each digit of the number . ; If digit is integer ; If digit is alphabet ; Checking hash array , if any index is unmarked . ; Driver Code","code":"def checkPandigital ( b , n ) : NEW_LINE INDENT if ( len ( n ) < b ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT hash = [ 0 ] * b ; NEW_LINE for i in range ( len ( n ) ) : NEW_LINE INDENT if ( n [ i ] >= '0' and n [ i ] <= '9' ) : NEW_LINE INDENT hash [ ord ( n [ i ] ) - ord ( '0' ) ] = 1 ; NEW_LINE DEDENT elif ( ord ( n [ i ] ) - ord ( ' A ' ) <= b - 11 ) : NEW_LINE INDENT hash [ ord ( n [ i ] ) - ord ( ' A ' ) + 10 ] = 1 ; NEW_LINE DEDENT DEDENT for i in range ( b ) : NEW_LINE INDENT if ( hash [ i ] == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return 1 ; NEW_LINE DEDENT b = 13 ; NEW_LINE n = \"1298450376ABC \" ; NEW_LINE if ( checkPandigital ( b , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT"} +{"text":"Convert a number m to n using minimum number of given operations | Function to find minimum number of given operations to convert m to n ; only way is to do - 1 ( m - n ) : times ; not possible ; n is greater and n is odd ; perform ' - 1' on m ( or + 1 on n ) : ; n is even ; perform ' * 2' on m ( or n \/ 2 on n ) : ; Driver code","code":"def conver ( m , n ) : NEW_LINE INDENT if ( m == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( m > n ) : NEW_LINE INDENT return m - n NEW_LINE DEDENT if ( m <= 0 and n > 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT return 1 + conver ( m , n + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return 1 + conver ( m , n \/ 2 ) NEW_LINE DEDENT DEDENT m = 3 NEW_LINE n = 11 NEW_LINE print ( \" Minimum \u2581 number \u2581 of \u2581 operations \u2581 : \" , conver ( m , n ) ) NEW_LINE"} +{"text":"Seeds ( Or Seed Roots ) of a number | Python3 program to find Seed of a number ; Stores product of digits of x in prodDig [ x ] ; If x has single digit ; If digit product is already computed ; If digit product is not computed before . ; Prints all seeds of n ; Find all seeds using prodDig [ ] ; If there was no seed ; Print seeds ; Driver code","code":"MAX = 10000 ; NEW_LINE prodDig = [ 0 ] * MAX ; NEW_LINE def getDigitProduct ( x ) : NEW_LINE INDENT if ( x < 10 ) : NEW_LINE INDENT return x ; NEW_LINE DEDENT if ( prodDig [ x ] != 0 ) : NEW_LINE INDENT return prodDig [ x ] ; NEW_LINE DEDENT prod = ( int ( x % 10 ) * getDigitProduct ( int ( x \/ 10 ) ) ) ; NEW_LINE prodDig [ x ] = prod ; NEW_LINE return prod ; NEW_LINE DEDENT def findSeed ( n ) : NEW_LINE INDENT res = [ ] ; NEW_LINE for i in range ( 1 , int ( n \/ 2 + 2 ) ) : NEW_LINE INDENT if ( i * getDigitProduct ( i ) == n ) : NEW_LINE INDENT res . append ( i ) ; NEW_LINE DEDENT DEDENT if ( len ( res ) == 0 ) : NEW_LINE INDENT print ( \" NO \u2581 seed \u2581 exists \" ) ; NEW_LINE return ; NEW_LINE DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT n = 138 ; NEW_LINE findSeed ( n ) ; NEW_LINE"} +{"text":"Number with maximum number of prime factors | Python 3 program to find integer having maximum number of prime factor in first N natural numbers . ; Return smallest number having maximum prime factors . ; Sieve of eratosthenes method to count number of prime factors . ; Finding number having maximum number of prime factor . ; Driver Code","code":"from math import sqrt NEW_LINE def maxPrimefactorNum ( N ) : NEW_LINE INDENT arr = [ 0 for i in range ( N + 5 ) ] NEW_LINE for i in range ( 2 , int ( sqrt ( N ) ) + 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT for j in range ( 2 * i , N + 1 , i ) : NEW_LINE INDENT arr [ j ] += 1 NEW_LINE DEDENT DEDENT arr [ i ] = 1 NEW_LINE DEDENT maxval = 0 NEW_LINE maxint = 1 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] > maxval ) : NEW_LINE INDENT maxval = arr [ i ] NEW_LINE maxint = i NEW_LINE DEDENT DEDENT return maxint NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 40 NEW_LINE print ( maxPrimefactorNum ( N ) ) NEW_LINE DEDENT"} +{"text":"Sum of all Subarrays | Set 1 | function compute sum all sub - array ; computing sum of subarray using formula ; return all subarray sum ; driver program","code":"def SubArraySum ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT result += ( arr [ i ] * ( i + 1 ) * ( n - i ) ) NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Sum \u2581 of \u2581 SubArray \u2581 : \u2581 \" , SubArraySum ( arr , n ) ) NEW_LINE"} +{"text":"Highest power of 2 less than or equal to given number | Python3 program to find highest power of 2 smaller than or equal to n . ; If i is a power of 2 ; Driver code","code":"def highestPowerof2 ( n ) : NEW_LINE INDENT res = 0 ; NEW_LINE for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( ( i & ( i - 1 ) ) == 0 ) : NEW_LINE INDENT res = i ; NEW_LINE break ; NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT n = 10 ; NEW_LINE print ( highestPowerof2 ( n ) ) ; NEW_LINE"} +{"text":"Find Cube Pairs | Set 2 ( A n ^ ( 1 \/ 3 ) Solution ) | Python3 program to find pairs that can represent the given number as sum of two cubes ; Function to find pairs that can represent the given number as sum of two cubes ; find cube root of n ; create a array of size of size 'cubeRoot ; for index i , cube [ i ] will contain i ^ 3 ; Find all pairs in above sorted array cube [ ] whose sum is equal to n ; Driver code","code":"import math NEW_LINE def findPairs ( n ) : NEW_LINE INDENT cubeRoot = int ( math . pow ( n , 1.0 \/ 3.0 ) ) ; NEW_LINE DEDENT ' NEW_LINE INDENT cube = [ 0 ] * ( cubeRoot + 1 ) ; NEW_LINE for i in range ( 1 , cubeRoot + 1 ) : NEW_LINE INDENT cube [ i ] = i * i * i ; NEW_LINE DEDENT l = 1 ; NEW_LINE r = cubeRoot ; NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( cube [ l ] + cube [ r ] < n ) : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT elif ( cube [ l ] + cube [ r ] > n ) : NEW_LINE INDENT r -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" ( \" , l , \" , \u2581 \" , math . floor ( r ) , \" ) \" , end = \" \" ) ; NEW_LINE print ( ) ; NEW_LINE l += 1 ; NEW_LINE r -= 1 ; NEW_LINE DEDENT DEDENT DEDENT n = 20683 ; NEW_LINE findPairs ( n ) ; NEW_LINE"} +{"text":"Find Cube Pairs | Set 1 ( A n ^ ( 2 \/ 3 ) Solution ) | Function to find pairs that can represent the given number as sum of two cubes ; Find cube root of n ; Create an empty map ; Consider all pairs such with values less than cuberoot ; Find sum of current pair ( x , y ) ; Do nothing if sum is not equal to given number ; If sum is seen before , we found two pairs ; If sum is seen for the first time ; Driver code","code":"def findPairs ( n ) : NEW_LINE INDENT cubeRoot = pow ( n , 1.0 \/ 3.0 ) ; NEW_LINE s = { } NEW_LINE for x in range ( int ( cubeRoot ) ) : NEW_LINE INDENT for y in range ( x + 1 , int ( cubeRoot ) + 1 ) : NEW_LINE INDENT sum = x * x * x + y * y * y ; NEW_LINE if ( sum != n ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if sum in s . keys ( ) : NEW_LINE INDENT print ( \" ( \" + str ( s [ sum ] [ 0 ] ) + \" , \u2581 \" + str ( s [ sum ] [ 1 ] ) + \" ) \u2581 and \u2581 ( \" + str ( x ) + \" , \u2581 \" + str ( y ) + \" ) \" + \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT s [ sum ] = [ x , y ] NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 13832 NEW_LINE findPairs ( n ) NEW_LINE DEDENT"} +{"text":"Find the minimum difference between Shifted tables of two numbers | python3 program to find the minimum difference between any two terms of two tables ; Utility function to find GCD of a and b ; Returns minimum difference between any two terms of shifted tables of ' a ' and ' b ' . ' x ' is shift in table of ' a ' and ' y ' is shift in table of ' b ' . ; Calculate gcd of a nd b ; Calculate difference between x and y ; Driver Code","code":"import math as mt NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT while ( b != 0 ) : NEW_LINE INDENT t = b NEW_LINE b = a % b NEW_LINE a = t NEW_LINE DEDENT return a NEW_LINE DEDENT def findMinDiff ( a , b , x , y ) : NEW_LINE INDENT g = gcd ( a , b ) NEW_LINE diff = abs ( x - y ) % g NEW_LINE return min ( diff , g - diff ) NEW_LINE DEDENT a , b , x , y = 20 , 52 , 5 , 7 NEW_LINE print ( findMinDiff ( a , b , x , y ) ) NEW_LINE"} +{"text":"Find all divisors of a natural number | Set 2 | A O ( sqrt ( n ) ) java program that prints all divisors in sorted order ; Method to print the divisors ; List to store half of the divisors ; Check if divisors are equal ; Otherwise print both ; The list will be printed in reverse ; Driver method","code":"import math NEW_LINE def printDivisors ( n ) : NEW_LINE INDENT list = [ ] NEW_LINE for i in range ( 1 , int ( math . sqrt ( n ) + 1 ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n \/ i == i ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE list . append ( int ( n \/ i ) ) NEW_LINE DEDENT DEDENT DEDENT for i in list [ : : - 1 ] : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT print ( \" The \u2581 divisors \u2581 of \u2581 100 \u2581 are : \u2581 \" ) NEW_LINE printDivisors ( 100 ) NEW_LINE"} +{"text":"Find all divisors of a natural number | Set 2 | A O ( sqrt ( n ) ) program that prints all divisors in sorted order ; Function to print the divisors ; Driver Code","code":"from math import * NEW_LINE def printDivisors ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while ( i * i < n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT for i in range ( int ( sqrt ( n ) ) , 0 , - 1 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print ( n \/\/ i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT print ( \" The \u2581 divisors \u2581 of \u2581 100 \u2581 are : \u2581 \" ) NEW_LINE printDivisors ( 100 ) NEW_LINE"} +{"text":"Find all factors of a natural number | Set 1 | method to print the divisors ; Driver method","code":"def printDivisors ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i <= n : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT print i , NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT DEDENT print \" The \u2581 divisors \u2581 of \u2581 100 \u2581 are : \u2581 \" NEW_LINE printDivisors ( 100 ) NEW_LINE"} +{"text":"Find all factors of a natural number | Set 1 | A Better ( than Naive ) Solution to find all divisiors ; method to print the divisors ; Note that this loop runs till square root ; If divisors are equal , print only one ; Otherwise print both ; Driver method","code":"import math NEW_LINE def printDivisors ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i <= math . sqrt ( n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n \/ i == i ) : NEW_LINE INDENT print i , NEW_LINE DEDENT else : NEW_LINE INDENT print i , n \/ i , NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT DEDENT print \" The \u2581 divisors \u2581 of \u2581 100 \u2581 are : \u2581 \" NEW_LINE printDivisors ( 100 ) NEW_LINE"} +{"text":"Sieve of Atkin | Python 3 program for implementation of Sieve of Atkin ; 2 and 3 are known to be prime ; Initialise the sieve array with False values ; Mark sieve [ n ] is True if one of the following is True : a ) n = ( 4 * x * x ) + ( y * y ) has odd number of solutions , i . e . , there exist odd number of distinct pairs ( x , y ) that satisfy the equation and n % 12 = 1 or n % 12 = 5. b ) n = ( 3 * x * x ) + ( y * y ) has odd number of solutions and n % 12 = 7 c ) n = ( 3 * x * x ) - ( y * y ) has odd number of solutions , x > y and n % 12 = 11 ; Main part of Sieve of Atkin ; Mark all multiples of squares as non - prime ; Print primes using sieve [ ] ; Driver Code","code":"def SieveOfAtkin ( limit ) : NEW_LINE INDENT if ( limit > 2 ) : NEW_LINE INDENT print ( 2 , end = \" \u2581 \" ) NEW_LINE DEDENT if ( limit > 3 ) : NEW_LINE INDENT print ( 3 , end = \" \u2581 \" ) NEW_LINE DEDENT sieve = [ False ] * limit NEW_LINE for i in range ( 0 , limit ) : NEW_LINE INDENT sieve [ i ] = False NEW_LINE DEDENT x = 1 NEW_LINE while ( x * x < limit ) : NEW_LINE INDENT y = 1 NEW_LINE while ( y * y < limit ) : NEW_LINE INDENT n = ( 4 * x * x ) + ( y * y ) NEW_LINE if ( n <= limit and ( n % 12 == 1 or n % 12 == 5 ) ) : NEW_LINE INDENT sieve [ n ] ^= True NEW_LINE DEDENT n = ( 3 * x * x ) + ( y * y ) NEW_LINE if ( n <= limit and n % 12 == 7 ) : NEW_LINE INDENT sieve [ n ] ^= True NEW_LINE DEDENT n = ( 3 * x * x ) - ( y * y ) NEW_LINE if ( x > y and n <= limit and n % 12 == 11 ) : NEW_LINE INDENT sieve [ n ] ^= True NEW_LINE DEDENT y += 1 NEW_LINE DEDENT x += 1 NEW_LINE DEDENT r = 5 NEW_LINE while ( r * r < limit ) : NEW_LINE INDENT if ( sieve [ r ] ) : NEW_LINE INDENT for i in range ( r * r , limit , r * r ) : NEW_LINE INDENT sieve [ i ] = False NEW_LINE DEDENT DEDENT DEDENT for a in range ( 5 , limit ) : NEW_LINE INDENT if ( sieve [ a ] ) : NEW_LINE INDENT print ( a , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT limit = 20 NEW_LINE SieveOfAtkin ( limit ) NEW_LINE"} +{"text":"Find if a point lies inside a Circle | Python3 program to check if a point lies inside a circle or not ; Compare radius of circle with distance of its center from given point ; Driver Code","code":"def isInside ( circle_x , circle_y , rad , x , y ) : NEW_LINE INDENT if ( ( x - circle_x ) * ( x - circle_x ) + ( y - circle_y ) * ( y - circle_y ) <= rad * rad ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT x = 1 ; NEW_LINE y = 1 ; NEW_LINE circle_x = 0 ; NEW_LINE circle_y = 1 ; NEW_LINE rad = 2 ; NEW_LINE if ( isInside ( circle_x , circle_y , rad , x , y ) ) : NEW_LINE INDENT print ( \" Inside \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Outside \" ) ; NEW_LINE DEDENT"} +{"text":"Program to check if a given number is Lucky ( all digits are different ) | python program to check if a given number is lucky ; This function returns true if n is lucky ; Create an array of size 10 and initialize all elements as false . This array is used to check if a digit is already seen or not . ; Traverse through all digits of given number ; Find the last digit ; If digit is already seen , return false ; Mark this digit as seen ; REmove the last digit from number ; Driver program to test above function .","code":"import math NEW_LINE def isLucky ( n ) : NEW_LINE INDENT ar = [ 0 ] * 10 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit = math . floor ( n % 10 ) NEW_LINE if ( ar [ digit ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ar [ digit ] = 1 NEW_LINE n = n \/ 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT arr = [ 1291 , 897 , 4566 , 1232 , 80 , 700 ] NEW_LINE n = len ( arr ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT k = arr [ i ] NEW_LINE if ( isLucky ( k ) ) : NEW_LINE INDENT print ( k , \" \u2581 is \u2581 Lucky \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( k , \" \u2581 is \u2581 not \u2581 Lucky \u2581 \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Print squares of first n natural numbers without using * , \/ and | Python3 program to print squares of first ' n ' natural numbers wothout using * , \/ and - ; Initialize ' square ' and first odd number ; Calculate and print squares ; Print square ; Update ' square ' and 'odd ; Driver Code","code":"def printSquares ( n ) : NEW_LINE INDENT square = 0 NEW_LINE odd = 1 NEW_LINE for x in range ( 0 , n ) : NEW_LINE INDENT print ( square , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT square = square + odd NEW_LINE odd = odd + 2 NEW_LINE DEDENT n = 5 ; NEW_LINE printSquares ( n ) NEW_LINE"} +{"text":"Write a program to reverse digits of a number | Python 3 program to reverse digits of a number ; Recursive function to reverse digits of num ; Driver Code","code":"rev_num = 0 NEW_LINE base_pos = 1 NEW_LINE def reversDigits ( num ) : NEW_LINE INDENT global rev_num NEW_LINE global base_pos NEW_LINE if ( num > 0 ) : NEW_LINE INDENT reversDigits ( ( int ) ( num \/ 10 ) ) NEW_LINE rev_num += ( num % 10 ) * base_pos NEW_LINE base_pos *= 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT num = 4562 NEW_LINE print ( \" Reverse \u2581 of \u2581 no . \u2581 is \u2581 \" , reversDigits ( num ) ) NEW_LINE"} +{"text":"Find a number such that maximum in array is minimum possible after XOR | Recursive function that find the minimum value after exclusive - OR ; Condition if ref size is zero or bit is negative then return 0 ; Condition if current bit is off then push current value in curr_off vector ; Condition if current bit is on then push current value in curr_on vector ; Condition if curr_off is empty then call recursive function on curr_on vector ; Condition if curr_on is empty then call recursive function on curr_off vector ; Return the minimum of curr_off and curr_on and add power of 2 of current bit ; Function that print the minimum value after exclusive - OR ; Pushing values in vector ; Printing answer ; Driver Code","code":"def RecursiveFunction ( ref , bit ) : NEW_LINE INDENT if ( len ( ref ) == 0 or bit < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT curr_on = [ ] NEW_LINE curr_off = [ ] NEW_LINE for i in range ( len ( ref ) ) : NEW_LINE INDENT if ( ( ( ref [ i ] >> bit ) & 1 ) == 0 ) : NEW_LINE INDENT curr_off . append ( ref [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT curr_on . append ( ref [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( curr_off ) == 0 ) : NEW_LINE INDENT return RecursiveFunction ( curr_on , bit - 1 ) NEW_LINE DEDENT if ( len ( curr_on ) == 0 ) : NEW_LINE INDENT return RecursiveFunction ( curr_off , bit - 1 ) NEW_LINE DEDENT return ( min ( RecursiveFunction ( curr_off , bit - 1 ) , RecursiveFunction ( curr_on , bit - 1 ) ) + ( 1 << bit ) ) NEW_LINE DEDENT def PrintMinimum ( a , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT v . append ( a [ i ] ) NEW_LINE DEDENT print ( RecursiveFunction ( v , 30 ) ) NEW_LINE DEDENT arr = [ 3 , 2 , 1 ] NEW_LINE size = len ( arr ) NEW_LINE PrintMinimum ( arr , size ) NEW_LINE"} +{"text":"Count of elements which are equal to the XOR of the next two elements | Function to return the count of elements which are equal to the XOR of the next two elements ; To store the required count ; For every element of the array such that it has at least two elements appearing after it in the array ; If current element is equal to the XOR of the next two elements in the array ; Driver code","code":"def cntElements ( arr , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( arr [ i ] == ( arr [ i + 1 ] ^ arr [ i + 2 ] ) ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 3 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( cntElements ( arr , n ) ) NEW_LINE"} +{"text":"Number of triplets in array having subarray xor equal | Function to return the count ; Initialise result ; Pick 1 st element of the triplet ; Pick 2 nd element of the triplet ; Pick 3 rd element of the triplet ; Taking xor in the first subarray ; Taking xor in the second subarray ; If both xor is equal ; Driver Code ; Function Calling","code":"def xor_triplet ( arr , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j , n ) : NEW_LINE INDENT xor1 = 0 ; xor2 = 0 ; NEW_LINE for x in range ( i , j ) : NEW_LINE INDENT xor1 ^= arr [ x ] ; NEW_LINE DEDENT for x in range ( j , k + 1 ) : NEW_LINE INDENT xor2 ^= arr [ x ] ; NEW_LINE DEDENT if ( xor1 == xor2 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( xor_triplet ( arr , n ) ) ; NEW_LINE DEDENT"} +{"text":"Find the number of pair of Ideal nodes in a given tree | Python3 implementation of the approach ; Adjacency list ; bit : bit array i and j are starting and ending index INCLUSIVE ; bit : bit array n : size of bit array i is the index to be updated diff is ( new_val - old_val ) ; DFS function to find ideal pairs ; Function for initialisation ; Function to add an edge ; Function to find number of ideal pairs ; Find root of the tree ; Driver code ; Add edges ; Function call","code":"N = 100005 NEW_LINE Ideal_pair = 0 NEW_LINE al = [ [ ] for i in range ( 100005 ) ] NEW_LINE bit = [ 0 for i in range ( N ) ] NEW_LINE root_node = [ 0 for i in range ( N ) ] NEW_LINE def bit_q ( i , j ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( j > 0 ) : NEW_LINE INDENT sum += bit [ j ] NEW_LINE j -= ( j & ( j * - 1 ) ) NEW_LINE DEDENT i -= 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT sum -= bit [ i ] NEW_LINE i -= ( i & ( i * - 1 ) ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def bit_up ( i , diff ) : NEW_LINE INDENT while ( i <= n ) : NEW_LINE INDENT bit [ i ] += diff NEW_LINE i += i & - i NEW_LINE DEDENT DEDENT def dfs ( node , x ) : NEW_LINE INDENT Ideal_pair = x NEW_LINE Ideal_pair += bit_q ( max ( 1 , node - k ) , min ( n , node + k ) ) NEW_LINE bit_up ( node , 1 ) NEW_LINE for i in range ( len ( al [ node ] ) ) : NEW_LINE INDENT Ideal_pair = dfs ( al [ node ] [ i ] , Ideal_pair ) NEW_LINE DEDENT bit_up ( node , - 1 ) NEW_LINE return Ideal_pair NEW_LINE DEDENT def initialise ( ) : NEW_LINE INDENT Ideal_pair = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT root_node [ i ] = True NEW_LINE bit [ i ] = 0 NEW_LINE DEDENT DEDENT def Add_Edge ( x , y ) : NEW_LINE INDENT al [ x ] . append ( y ) NEW_LINE root_node [ y ] = False NEW_LINE DEDENT def Idealpairs ( ) : NEW_LINE INDENT r = - 1 NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT if ( root_node [ i ] ) : NEW_LINE INDENT r = i NEW_LINE break NEW_LINE DEDENT DEDENT Ideal_pair = dfs ( r , 0 ) NEW_LINE return Ideal_pair NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE k = 3 NEW_LINE initialise ( ) NEW_LINE Add_Edge ( 1 , 2 ) NEW_LINE Add_Edge ( 1 , 3 ) NEW_LINE Add_Edge ( 3 , 4 ) NEW_LINE Add_Edge ( 3 , 5 ) NEW_LINE Add_Edge ( 3 , 6 ) NEW_LINE print ( Idealpairs ( ) ) NEW_LINE DEDENT"} +{"text":"Print bitwise AND set of a number N | function to find bitwise subsets Efficient approach ; Driver Code","code":"def printSubsets ( n ) : NEW_LINE INDENT i = n NEW_LINE while ( i != 0 ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE i = ( i - 1 ) & n NEW_LINE DEDENT print ( \"0\" ) NEW_LINE DEDENT n = 9 NEW_LINE printSubsets ( n ) NEW_LINE"} +{"text":"Check if a number is divisible by 17 using bitwise operators | function to check recursively if the number is divisible by 17 or not ; if n = 0 or n = 17 then yes ; if n is less then 17 , not divisible by 17 ; reducing the number by floor ( n \/ 16 ) - n % 16 ; driver code to check the above function","code":"def isDivisibleby17 ( n ) : NEW_LINE INDENT if ( n == 0 or n == 17 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n < 17 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return isDivisibleby17 ( ( int ) ( n >> 4 ) - ( int ) ( n & 15 ) ) NEW_LINE DEDENT n = 35 NEW_LINE if ( isDivisibleby17 ( n ) ) : NEW_LINE INDENT print ( n , \" is \u2581 divisible \u2581 by \u2581 17\" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n , \" is \u2581 not \u2581 divisible \u2581 by \u2581 17\" ) NEW_LINE DEDENT"} +{"text":"Largest number with binary representation is m 1 's and m | Python3 program to find largest number smaller than equal to n with m set bits then m - 1 0 bits . ; Returns largest number with m set bits then m - 1 0 bits . ; Start with 2 bits . ; initial answer is 1 which meets the given condition ; check for all numbers ; compute the number ; if less then N ; increment m to get the next number ; Driver Code","code":"import math NEW_LINE def answer ( n ) : NEW_LINE INDENT m = 2 ; NEW_LINE ans = 1 ; NEW_LINE r = 1 ; NEW_LINE while r < n : NEW_LINE INDENT r = ( int ) ( ( pow ( 2 , m ) - 1 ) * ( pow ( 2 , m - 1 ) ) ) ; NEW_LINE if r < n : NEW_LINE INDENT ans = r ; NEW_LINE DEDENT m = m + 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT print ( answer ( 7 ) ) ; NEW_LINE"} +{"text":"Find most significant set bit of a number | Simple Python3 program to find MSB number for given n . ; Driver code","code":"def setBitNumber ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT msb = 0 ; NEW_LINE n = int ( n \/ 2 ) ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = int ( n \/ 2 ) ; NEW_LINE msb += 1 ; NEW_LINE DEDENT return ( 1 << msb ) ; NEW_LINE DEDENT n = 0 ; NEW_LINE print ( setBitNumber ( n ) ) ; NEW_LINE"} +{"text":"Find most significant set bit of a number | Python program to find MSB number for given n . ; Suppose n is 273 ( binary is 100010001 ) . It does following 100010001 | 010001000 = 110011001 ; This makes sure 4 bits ( From MSB and including MSB ) are set . It does following 110011001 | 001100110 = 111111111 ; Increment n by 1 so that there is only one set bit which is just before original MSB . n now becomes 1000000000 ; Return original MSB after shifting . n now becomes 100000000 ; Driver code","code":"def setBitNumber ( n ) : NEW_LINE INDENT n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE n = n + 1 NEW_LINE return ( n >> 1 ) NEW_LINE DEDENT n = 273 NEW_LINE print ( setBitNumber ( n ) ) NEW_LINE"} +{"text":"Count trailing zero bits using lookup table | Python 3 code for counting trailing zeros in binary representation of a number ; Driver Code","code":"def countTrailingZero ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( ( x & 1 ) == 0 ) : NEW_LINE INDENT x = x >> 1 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( countTrailingZero ( 11 ) ) NEW_LINE DEDENT"} +{"text":"Count trailing zero bits using lookup table | Python3 code for counting trailing zeros in binary representation of a number ; Map a bit value mod 37 to its position ; Only difference between ( x and - x ) is the value of signed magnitude ( leftmostbit ) negative numbers signed bit is 1 ; Driver Code","code":"def countTrailingZero ( x ) : NEW_LINE INDENT lookup = [ 32 , 0 , 1 , 26 , 2 , 23 , 27 , 0 , 3 , 16 , 24 , 30 , 28 , 11 , 0 , 13 , 4 , 7 , 17 , 0 , 25 , 22 , 31 , 15 , 29 , 10 , 12 , 6 , 0 , 21 , 14 , 9 , 5 , 20 , 8 , 19 , 18 ] NEW_LINE return lookup [ ( - x & x ) % 37 ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT print ( countTrailingZero ( 48 ) ) NEW_LINE DEDENT"} +{"text":"Calculate 7 n \/ 8 without using division and multiplication operators | Python program to evaluate ceil ( 7 n \/ 8 ) without using * and \/ ; Note the inner bracket here . This is needed because precedence of ' - ' operator is higher than '<< ; Driver program to test above function","code":"def multiplyBySevenByEight ( n ) : NEW_LINE ' NEW_LINE INDENT return ( n - ( n >> 3 ) ) NEW_LINE DEDENT n = 9 NEW_LINE print ( multiplyBySevenByEight ( n ) ) NEW_LINE"} +{"text":"Calculate 7 n \/ 8 without using division and multiplication operators | Python3 program to evaluate 7 n \/ 8 without using * and \/ ; Step 1 ) First multiply number by 7 i . e . 7 n = ( n << 3 ) - n Step 2 ) Divide result by 8 ; Driver code","code":"def multiplyBySevenByEight ( n ) : NEW_LINE INDENT return ( ( n << 3 ) - n ) >> 3 ; NEW_LINE DEDENT n = 15 ; NEW_LINE print ( multiplyBySevenByEight ( n ) ) ; NEW_LINE"} +{"text":"Longest set of Palindrome Numbers from the range [ L , R ] with at most K difference between its maximum and minimum | Function to find the maximum size of group of palindrome numbers having difference between maximum and minimum element at most K ; Stores the all the palindromic numbers in the range [ L , R ] ; Traverse over the range [ L , R ] ; If i is a palindrome ; Append the number in the list ; Stores count of maximum palindromic numbers ; Iterate each element in the list ; Calculate rightmost index in the list < current element + K ; Check if there is rightmost index from the current index ; Return the count ; Function to search the rightmost index of given number ; Store the rightmost index ; Calculate the mid ; If given number <= num ; Assign ans = mid ; Update low ; Update high ; return ans ; Function to check if the given number is palindrome or not ; Generate reverse of the given number ; If n is a palindrome ; Driver Code","code":"def countNumbers ( L , R , K ) : NEW_LINE INDENT list = [ ] NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( isPalindrome ( i ) ) : NEW_LINE INDENT list . append ( i ) NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( len ( list ) ) : NEW_LINE INDENT right_index = search ( list , list [ i ] + K - 1 ) NEW_LINE if ( right_index != - 1 ) : NEW_LINE INDENT count = max ( count , right_index - i + 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def search ( list , num ) : NEW_LINE INDENT low , high = 0 , len ( list ) - 1 NEW_LINE ans = - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) \/\/ 2 NEW_LINE if ( list [ mid ] <= num ) : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def isPalindrome ( n ) : NEW_LINE INDENT rev = 0 NEW_LINE temp = n NEW_LINE while ( n > 0 ) : NEW_LINE INDENT rev = rev * 10 + n % 10 NEW_LINE n \/\/= 10 NEW_LINE DEDENT return rev == temp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R = 98 , 112 NEW_LINE K = 13 NEW_LINE print ( countNumbers ( L , R , K ) ) NEW_LINE DEDENT"} +{"text":"Maximize Sum possible by subtracting same value from all elements of a Subarray of the given Array | Function to find the maximum sum by subtracting same value from all elements of a Subarray ; Stores previous smaller element ; Stores next smaller element ; Calculate contribution of each element ; Return answer ; Function to generate previous smaller element for each array element ; The first element has no previous smaller ; Stack to keep track of elements that have occurred previously ; Push the first index ; Pop all the elements until the previous element is smaller than current element ; Store the previous smaller element ; Push the index of the current element ; Return the array ; Function to generate next smaller element for each array element ; Stack to keep track of elements that have occurring next ; Iterate in reverse order for calculating next smaller ; Pop all the elements until the next element is smaller than current element ; Store the next smaller element ; Push the index of the current element ; Return the array ; Driver code","code":"def findMaximumSum ( a , n ) : NEW_LINE INDENT prev_smaller = findPrevious ( a , n ) NEW_LINE next_smaller = findNext ( a , n ) NEW_LINE max_value = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_value = max ( max_value , a [ i ] * ( next_smaller [ i ] - prev_smaller [ i ] - 1 ) ) NEW_LINE DEDENT return max_value NEW_LINE DEDENT def findPrevious ( a , n ) : NEW_LINE INDENT ps = [ 0 ] * n NEW_LINE ps [ 0 ] = - 1 NEW_LINE stack = [ ] NEW_LINE stack . append ( 0 ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while len ( stack ) > 0 and a [ stack [ - 1 ] ] >= a [ i ] : NEW_LINE INDENT stack . pop ( ) NEW_LINE DEDENT ps [ i ] = stack [ - 1 ] if len ( stack ) > 0 else - 1 NEW_LINE stack . append ( i ) NEW_LINE DEDENT return ps NEW_LINE DEDENT def findNext ( a , n ) : NEW_LINE INDENT ns = [ 0 ] * n NEW_LINE ns [ n - 1 ] = n NEW_LINE stack = [ ] NEW_LINE stack . append ( n - 1 ) NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT while ( len ( stack ) > 0 and a [ stack [ - 1 ] ] >= a [ i ] ) : NEW_LINE INDENT stack . pop ( ) NEW_LINE DEDENT ns [ i ] = stack [ - 1 ] if len ( stack ) > 0 else n NEW_LINE stack . append ( i ) NEW_LINE DEDENT return ns NEW_LINE DEDENT n = 3 NEW_LINE a = [ 80 , 48 , 82 ] NEW_LINE print ( findMaximumSum ( a , n ) ) NEW_LINE"} +{"text":"Check if the given string is shuffled substring of another string | ''This function returns true if contents of arr1[] and arr2[] are same, otherwise false. ; This function search for all permutations of pat [ ] in txt [ ] ; countP [ ] : Store count of all characters of pattern countTW [ ] : Store count of current window of text ; Traverse through remaining characters of pattern ; Compare counts of current window of text with counts of pattern [ ] ; Add current character to current window ; Remove the first character of previous window ; Check for the last window in text ; Driver code","code":"MAX = 256 NEW_LINE def compare ( arr1 , arr2 ) : NEW_LINE INDENT global MAX NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE countP = [ 0 for i in range ( MAX ) ] NEW_LINE countTW = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT countP [ ord ( pat [ i ] ) ] += 1 NEW_LINE countTW [ ord ( txt [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( M , N ) : NEW_LINE INDENT if ( compare ( countP , countTW ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT countTW [ ord ( txt [ i ] ) ] += 1 NEW_LINE countTW [ ord ( txt [ i - M ] ) ] -= 1 NEW_LINE DEDENT if ( compare ( countP , countTW ) ) : NEW_LINE INDENT return True NEW_LINE return False NEW_LINE DEDENT DEDENT txt = \" BACDGABCDA \" NEW_LINE pat = \" ABCD \" NEW_LINE if ( search ( pat , txt ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Maximize the median of the given array after adding K elements to the same array | Function to return the maximized median ; Sort the array ; If size is even ; If size is odd ; Driver code","code":"def getMaxMedian ( arr , n , k ) : NEW_LINE INDENT size = n + k NEW_LINE arr . sort ( reverse = False ) NEW_LINE if ( size % 2 == 0 ) : NEW_LINE INDENT median = ( arr [ int ( size \/ 2 ) - 1 ] + arr [ int ( size \/ 2 ) ] ) \/ 2 NEW_LINE return median NEW_LINE DEDENT median = arr [ int ( size \/ 2 ) ] NEW_LINE return median NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( getMaxMedian ( arr , n , k ) ) NEW_LINE DEDENT"} +{"text":"Sort 3 Integers without using if condition or using only max ( ) function | Python3 program to print three numbers in sorted order using max function ; Find maximum element ; Find minimum element ; Driver Code","code":"def printSorted ( a , b , c ) : NEW_LINE INDENT get_max = max ( a , max ( b , c ) ) NEW_LINE get_min = - max ( - a , max ( - b , - c ) ) NEW_LINE get_mid = ( a + b + c ) - ( get_max + get_min ) NEW_LINE print ( get_min , \" \u2581 \" , get_mid , \" \u2581 \" , get_max ) NEW_LINE DEDENT a , b , c = 4 , 1 , 9 NEW_LINE printSorted ( a , b , c ) NEW_LINE"} +{"text":"Binary Insertion Sort | iterative implementation ; Function to sort an array a [ ] of size 'n ; find location where selected should be inseretd ; Move all elements after location to create space ; Driver Code","code":"def binarySearch ( a , item , low , high ) : NEW_LINE INDENT while ( low <= high ) : NEW_LINE INDENT mid = low + ( high - low ) \/\/ 2 NEW_LINE if ( item == a [ mid ] ) : NEW_LINE INDENT return mid + 1 NEW_LINE DEDENT elif ( item > a [ mid ] ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT ' NEW_LINE def insertionSort ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT j = i - 1 NEW_LINE selected = a [ i ] NEW_LINE loc = binarySearch ( a , selected , 0 , j ) NEW_LINE while ( j >= loc ) : NEW_LINE INDENT a [ j + 1 ] = a [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT a [ j + 1 ] = selected NEW_LINE DEDENT DEDENT a = [ 37 , 23 , 0 , 17 , 12 , 72 , 31 , 46 , 100 , 88 , 54 ] NEW_LINE n = len ( a ) NEW_LINE insertionSort ( a , n ) NEW_LINE print ( \" Sorted \u2581 array : \u2581 \" ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT"} +{"text":"Insertion Sort | Function to do insertion sort ; Move elements of arr [ 0. . i - 1 ] , that are greater than key , to one position ahead of their current position ; Driver code to test above","code":"def insertionSort ( arr ) : NEW_LINE INDENT for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT key = arr [ i ] NEW_LINE j = i - 1 NEW_LINE while j >= 0 and key < arr [ j ] : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT arr [ j + 1 ] = key NEW_LINE DEDENT DEDENT arr = [ 12 , 11 , 13 , 5 , 6 ] NEW_LINE insertionSort ( arr ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( \" % \u2581 d \" % arr [ i ] ) NEW_LINE DEDENT"} +{"text":"Count of distinct permutation of a String obtained by swapping only unequal characters | Function to calculate total number of valid permutations ; Creating count which is equal to the Total number of characters present and ans that will store the number of unique permutations ; Storing frequency of each character present in the string ; Adding count of characters by excluding characters equal to current char ; Reduce the frequency of the current character and count by 1 , so that it cannot interfere with the calculations of the same elements present to the right of it . ; Return ans + 1 ( Because the given string is also a unique permutation ) ; Driver Code","code":"def validPermutations ( str ) : NEW_LINE INDENT m = { } NEW_LINE count = len ( str ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if ( str [ i ] in m ) : NEW_LINE INDENT m [ str [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ str [ i ] ] = 1 NEW_LINE DEDENT DEDENT for i in range ( len ( str ) ) : NEW_LINE INDENT ans += count - m [ str [ i ] ] NEW_LINE m [ str [ i ] ] -= 1 NEW_LINE count -= 1 NEW_LINE DEDENT return ans + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" sstt \" NEW_LINE print ( validPermutations ( str ) ) NEW_LINE DEDENT"} +{"text":"Counts paths from a point to reach Origin | Recursive function to count number of paths ; If we reach bottom or top left , we are have only one way to reach ( 0 , 0 ) ; Else count sum of both ways ; Driver Code","code":"def countPaths ( n , m ) : NEW_LINE INDENT if ( n == 0 or m == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( countPaths ( n - 1 , m ) + countPaths ( n , m - 1 ) ) NEW_LINE DEDENT n = 3 NEW_LINE m = 2 NEW_LINE print ( \" Number \u2581 of \u2581 Paths \" , countPaths ( n , m ) ) NEW_LINE"} +{"text":"Coin Change | DP | Returns the count of ways we can sum S [ 0. . . m - 1 ] coins to get sum n ; If n is 0 then there is 1 solution ( do not include any coin ) ; If n is less than 0 then no solution exists ; If there are no coins and n is greater than 0 , then no solution exist ; count is sum of solutions ( i ) including S [ m - 1 ] ( ii ) excluding S [ m - 1 ] ; Driver program to test above function","code":"def count ( S , m , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( m <= 0 and n >= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return count ( S , m - 1 , n ) + count ( S , m , n - S [ m - 1 ] ) ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE m = len ( arr ) NEW_LINE print ( count ( arr , m , 4 ) ) NEW_LINE"} +{"text":"Check if two strings are same ignoring their cases | Function to compare two strings ignoring their cases ; Convert to uppercase ; if strings are equal , return true otherwise false ; Function to print the same or not same if strings are equal or not equal ; Driver Code","code":"def equalIgnoreCase ( str1 , str2 ) : NEW_LINE INDENT str1 = str1 . upper ( ) ; NEW_LINE str2 = str2 . upper ( ) ; NEW_LINE x = str1 == str2 ; NEW_LINE return x ; NEW_LINE DEDENT def equalIgnoreCaseUtil ( str1 , str2 ) : NEW_LINE INDENT res = equalIgnoreCase ( str1 , str2 ) ; NEW_LINE if ( res == True ) : NEW_LINE INDENT print ( \" Same \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Same \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" Geeks \" ; NEW_LINE str2 = \" geeks \" ; NEW_LINE equalIgnoreCaseUtil ( str1 , str2 ) ; NEW_LINE str1 = \" Geek \" ; NEW_LINE str2 = \" geeksforgeeks \" ; NEW_LINE equalIgnoreCaseUtil ( str1 , str2 ) ; NEW_LINE DEDENT"} +{"text":"Replace every consonant sequence with its length in the given string | Function to return the converted string after replacing every consonant sequence with its length ; To store the resultant string ; Checking each character for consonant sequence ; Count the length of consonants sequence ; Add the length in the string ; Add the vowel ; Check for the last consonant sequence in the string ; Return the resultant string ; Driver code","code":"def replaceConsonants ( string ) : NEW_LINE INDENT res = \" \" ; NEW_LINE i = 0 ; count = 0 ; NEW_LINE while ( i < len ( string ) ) : NEW_LINE INDENT if ( string [ i ] != ' a ' and string [ i ] != ' e ' and string [ i ] != ' i ' and string [ i ] != ' o ' and string [ i ] != ' u ' ) : NEW_LINE INDENT i += 1 ; NEW_LINE count += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( count > 0 ) : NEW_LINE INDENT res += str ( count ) ; NEW_LINE DEDENT res += string [ i ] ; NEW_LINE i += 1 NEW_LINE count = 0 ; NEW_LINE DEDENT DEDENT if ( count > 0 ) : NEW_LINE INDENT res += str ( count ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" abcdeiop \" ; NEW_LINE print ( replaceConsonants ( string ) ) ; NEW_LINE DEDENT"} +{"text":"Encrypt string with product of number of vowels and consonants in substring of size k | isVowel ( ) is a function that returns true for a vowel and false otherwise . ; function to Encrypt the dtring ; for each substring ; substring of size k ; counting number of vowels and consonants ; append product to answer ; Driver Code","code":"def isVowel ( c ) : NEW_LINE INDENT return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) NEW_LINE DEDENT def encryptString ( s , n , k ) : NEW_LINE INDENT countVowels = 0 NEW_LINE countConsonants = 0 NEW_LINE ans = \" \" NEW_LINE for l in range ( n - k + 1 ) : NEW_LINE INDENT countVowels = 0 NEW_LINE countConsonants = 0 NEW_LINE for r in range ( l , l + k ) : NEW_LINE INDENT if ( isVowel ( s [ r ] ) == True ) : NEW_LINE INDENT countVowels += 1 NEW_LINE DEDENT else : NEW_LINE INDENT countConsonants += 1 NEW_LINE DEDENT DEDENT ans += ( str ) ( countVowels * countConsonants ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" hello \" NEW_LINE n = len ( s ) NEW_LINE k = 2 NEW_LINE print ( encryptString ( s , n , k ) ) NEW_LINE DEDENT"} +{"text":"String containing first letter of every word in a given string with spaces | An efficient Python3 implementation of above approach ; we are splitting the input based on spaces ( s ) + : this regular expression will handle scenarios where we have words separated by multiple spaces ; charAt ( 0 ) will pick only the first character from the string and append to buffer ; Driver Code","code":"charBuffer = [ ] NEW_LINE def processWords ( input ) : NEW_LINE INDENT s = input . split ( \" \u2581 \" ) NEW_LINE for values in s : NEW_LINE INDENT charBuffer . append ( values [ 0 ] ) NEW_LINE DEDENT return charBuffer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = \" geeks \u2581 for \u2581 geeks \" NEW_LINE print ( * processWords ( input ) , sep = \" \" ) NEW_LINE DEDENT"} +{"text":"Generate all binary strings without consecutive 1 's | A utility function generate all string without consecutive 1 'sof size K ; print binary string without consecutive 1 's ; terminate binary string ; if previous character is '1' then we put only 0 at end of string example str = \"01\" then new string be \"000\" ; if previous character is '0' than we put both '1' and '0' at end of string example str = \"00\" then new string \"001\" and \"000\" ; function generate all binary string without consecutive 1 's ; Base case ; One by one stores every binary string of length K ; Generate all Binary string starts with '0 ; Generate all Binary string starts with '1 ; Driver code","code":"def generateAllStringsUtil ( K , str , n ) : NEW_LINE INDENT if ( n == K ) : NEW_LINE INDENT print ( * str [ : n ] , sep = \" \" , end = \" \u2581 \" ) NEW_LINE return NEW_LINE DEDENT if ( str [ n - 1 ] == '1' ) : NEW_LINE INDENT str [ n ] = '0' NEW_LINE generateAllStringsUtil ( K , str , n + 1 ) NEW_LINE DEDENT if ( str [ n - 1 ] == '0' ) : NEW_LINE INDENT str [ n ] = '0' NEW_LINE generateAllStringsUtil ( K , str , n + 1 ) NEW_LINE str [ n ] = '1' NEW_LINE generateAllStringsUtil ( K , str , n + 1 ) NEW_LINE DEDENT DEDENT def generateAllStrings ( K ) : NEW_LINE INDENT if ( K <= 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT str = [ 0 ] * K NEW_LINE DEDENT ' NEW_LINE INDENT str [ 0 ] = '0' NEW_LINE generateAllStringsUtil ( K , str , 1 ) NEW_LINE DEDENT ' NEW_LINE INDENT str [ 0 ] = '1' NEW_LINE generateAllStringsUtil ( K , str , 1 ) NEW_LINE DEDENT K = 3 NEW_LINE generateAllStrings ( K ) NEW_LINE"} +{"text":"Largest right circular cylinder within a cube | Function to find the biggest right circular cylinder ; side cannot be negative ; radius of right circular cylinder ; height of right circular cylinder ; volume of right circular cylinder ; Driver code","code":"def findVolume ( a ) : NEW_LINE INDENT if ( a < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT r = a \/ 2 NEW_LINE h = a NEW_LINE V = 3.14 * pow ( r , 2 ) * h NEW_LINE return V NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 5 NEW_LINE print ( findVolume ( a ) ) NEW_LINE DEDENT"} +{"text":"Program for volume of Pyramid | Function to calculate Volume of Triangular Pyramid ; Function To calculate Volume of Square Pyramid ; Function To calculate Volume of Pentagonal Pyramid ; Function To calculate Volume of Hexagonal Pyramid ; Driver Code","code":"def volumeTriangular ( a , b , h ) : NEW_LINE INDENT return ( 0.1666 ) * a * b * h NEW_LINE DEDENT def volumeSquare ( b , h ) : NEW_LINE INDENT return ( 0.33 ) * b * b * h NEW_LINE DEDENT def volumePentagonal ( a , b , h ) : NEW_LINE INDENT return ( 0.83 ) * a * b * h NEW_LINE DEDENT def volumeHexagonal ( a , b , h ) : NEW_LINE INDENT return a * b * h NEW_LINE DEDENT b = float ( 4 ) NEW_LINE h = float ( 9 ) NEW_LINE a = float ( 4 ) NEW_LINE print ( \" Volume \u2581 of \u2581 triangular \u2581 base \u2581 pyramid \u2581 is \u2581 \" , volumeTriangular ( a , b , h ) ) NEW_LINE print ( \" Volume \u2581 of \u2581 square \u2581 base \u2581 pyramid \u2581 is \u2581 \" , volumeSquare ( b , h ) ) NEW_LINE print ( \" Volume \u2581 of \u2581 pentagonal \u2581 base \u2581 pyramid \u2581 is \u2581 \" , volumePentagonal ( a , b , h ) ) NEW_LINE print ( \" Volume \u2581 of \u2581 Hexagonal \u2581 base \u2581 pyramid \u2581 is \u2581 \" , volumeHexagonal ( a , b , h ) ) NEW_LINE"} +{"text":"Program to find area of a Trapezoid | Function for the area ; Driver Code","code":"def Area ( b1 , b2 , h ) : NEW_LINE INDENT return ( ( b1 + b2 ) \/ 2 ) * h NEW_LINE DEDENT base1 = 8 ; base2 = 10 ; height = 6 NEW_LINE area = Area ( base1 , base2 , height ) NEW_LINE print ( \" Area \u2581 is : \" , area ) NEW_LINE"} +{"text":"Find number of diagonals in n sided convex polygon | ''Python3 program to find number of diagonals in n sided convex polygon ; ''driver code to test above function","code":"def numberOfDiagonals ( n ) : NEW_LINE INDENT return n * ( n - 3 ) \/ 2 NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT n = 5 NEW_LINE print ( n , \" \u2581 sided \u2581 convex \u2581 polygon \u2581 have \u2581 \" ) NEW_LINE print ( numberOfDiagonals ( n ) , \" \u2581 diagonals \" ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT"} +{"text":"Area of the largest Rectangle without a given point | Function to find the maximum area such that it does not contains any hole ; Area for all the possible positions of the cut ; Find the maximum area among the above rectangles ; Driver Code ; Function call","code":"def maximumArea ( l , b , x , y ) : NEW_LINE INDENT left , right , above , below = 0 , 0 , 0 , 0 NEW_LINE left = x * b NEW_LINE right = ( l - x - 1 ) * b NEW_LINE above = l * y NEW_LINE below = ( b - y - 1 ) * l NEW_LINE print ( max ( max ( left , right ) , max ( above , below ) ) ) NEW_LINE DEDENT l = 8 NEW_LINE b = 8 NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE maximumArea ( l , b , x , y ) NEW_LINE"} +{"text":"Minimize cost of removals required to make all remaining characters of the string unique | Function to find the minimum cost of removing characters to make the string unique ; Store the minimum cost required ; Create a dictionary to store the maximum cost of removal a character ; Create a dictionary to store the total deletion cost of a character ; Traverse the string , S ; Keep track of maximum cost of each character ; Update the maximum deletion cost ; Keep track of the total cost of each character ; Update the total deletion cost ; Traverse through all the unique characters ; Keep the maximum cost character and delete the rest ; Return the answer ; Given string ; Given cost array ; Function Call","code":"def delCost ( s , cost ) : NEW_LINE INDENT ans = 0 NEW_LINE forMax = { } NEW_LINE forTot = { } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] not in forMax : NEW_LINE INDENT forMax [ s [ i ] ] = cost [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT forMax [ s [ i ] ] = max ( cost [ i ] , forMax [ s [ i ] ] ) NEW_LINE DEDENT if s [ i ] not in forTot : NEW_LINE INDENT forTot [ s [ i ] ] = cost [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT forTot [ s [ i ] ] += cost [ i ] NEW_LINE DEDENT DEDENT for i in forMax : NEW_LINE INDENT ans += forTot [ i ] - forMax [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT string = \" AAABBB \" NEW_LINE cost = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE print ( delCost ( string , cost ) ) NEW_LINE"} +{"text":"Smallest divisor of N closest to X | Python3 program for the above approach ; Stores divisors for all numbers in the vector divisors ; i is the divisor and j is the multiple ; Function to compare the closeness of the given target ; Function to find the element closest to target in divisors vector ; Corner cases ; Perform binary search ; Check if target is less than the array element then search in left half ; Check if target is greater than previous to mid , return closest of two ; Repeat for left half ; Check if target is greater than mid ; Update i ; Only single element left after search ; Function to print the divisor of N closest to X ; Function call to calculate and stores divisors of all numbers in a vector ; Stores the closest value to target ; Print the answer ; Driver Code ; Given N & X ; Function Call","code":"MAX = 10000 NEW_LINE divisors = [ [ ] for i in range ( MAX + 1 ) ] NEW_LINE def computeDivisors ( ) : NEW_LINE INDENT global divisors NEW_LINE global MAX NEW_LINE for i in range ( 1 , MAX + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , MAX + 1 , i ) : NEW_LINE INDENT divisors [ j ] . append ( i ) NEW_LINE DEDENT DEDENT DEDENT def getClosest ( val1 , val2 , target ) : NEW_LINE INDENT if ( target - val1 >= val2 - target ) : NEW_LINE INDENT return val2 NEW_LINE DEDENT else : NEW_LINE INDENT return val1 NEW_LINE DEDENT DEDENT def findClosest ( arr , n , target ) : NEW_LINE INDENT if ( target <= arr [ 0 ] ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT if ( target >= arr [ n - 1 ] ) : NEW_LINE INDENT return arr [ n - 1 ] NEW_LINE DEDENT i = 0 NEW_LINE j = n NEW_LINE mid = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT mid = ( i + j ) \/\/ 2 NEW_LINE if ( arr [ mid ] == target ) : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if ( target < arr [ mid ] ) : NEW_LINE INDENT if ( mid > 0 and target > arr [ mid - 1 ] ) : NEW_LINE INDENT return getClosest ( arr [ mid - 1 ] , arr [ mid ] , target ) NEW_LINE DEDENT j = mid NEW_LINE DEDENT else : NEW_LINE INDENT if ( mid < n - 1 and target < arr [ mid + 1 ] ) : NEW_LINE INDENT return getClosest ( arr [ mid ] , arr [ mid + 1 ] , target ) NEW_LINE DEDENT i = mid + 1 NEW_LINE DEDENT DEDENT return arr [ mid ] NEW_LINE DEDENT def printClosest ( N , X ) : NEW_LINE INDENT global divisors NEW_LINE computeDivisors ( ) NEW_LINE ans = findClosest ( divisors [ N ] , len ( divisors [ N ] ) , X ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 16 NEW_LINE X = 5 NEW_LINE printClosest ( N , X ) NEW_LINE DEDENT"} +{"text":"Count elements of same value placed at same indices of two given arrays | Function to count maximum matched elements from the arrays A [ ] and B [ ] ; Stores position of elements of array A [ ] in the array B [ ] ; Keep track of difference between the indices ; Traverse the array A [ ] ; Traverse the array B [ ] ; If difference is negative , add N to it ; Keep track of the number of shifts required to place elements at same indices ; Return the max matches ; Driver Code ; Returns the count of matched elements","code":"def maxMatch ( A , B ) : NEW_LINE INDENT Aindex = { } NEW_LINE diff = { } NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT Aindex [ A [ i ] ] = i NEW_LINE DEDENT for i in range ( len ( B ) ) : NEW_LINE INDENT if i - Aindex [ B [ i ] ] < 0 : NEW_LINE INDENT if len ( A ) + i - Aindex [ B [ i ] ] not in diff : NEW_LINE INDENT diff [ len ( A ) + i - Aindex [ B [ i ] ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT diff [ len ( A ) + i - Aindex [ B [ i ] ] ] += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if i - Aindex [ B [ i ] ] not in diff : NEW_LINE INDENT diff [ i - Aindex [ B [ i ] ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT diff [ i - Aindex [ B [ i ] ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT return max ( diff . values ( ) ) NEW_LINE DEDENT A = [ 5 , 3 , 7 , 9 , 8 ] NEW_LINE B = [ 8 , 7 , 3 , 5 , 9 ] NEW_LINE print ( maxMatch ( A , B ) ) NEW_LINE"} +{"text":"Check if given Sudoku solution is valid or not | Function to check if all elements of the board [ ] [ ] array store value in the range [ 1 , 9 ] ; Traverse board [ ] [ ] array ; Check if board [ i ] [ j ] lies in the range ; Function to check if the solution of sudoku puzzle is valid or not ; Check if all elements of board [ ] [ ] stores value in the range [ 1 , 9 ] ; Stores unique value from 1 to N ; Traverse each row of the given array ; Initialize unique [ ] array to false ; Traverse each column of current row ; Stores the value of board [ i ] [ j ] ; Check if current row stores duplicate value ; Traverse each column of the given array ; Initialize unique [ ] array to false ; Traverse each row of current column ; Stores the value of board [ j ] [ i ] ; Check if current column stores duplicate value ; Traverse each block of size 3 * 3 in board [ ] [ ] array ; j stores first column of each 3 * 3 block ; Initialize unique [ ] array to false ; Traverse current block ; Stores row number of current block ; Stores column number of current block ; Stores the value of board [ X ] [ Y ] ; Check if current block stores duplicate value ; If all conditions satisfied ; Driver Code","code":"def isinRange ( board ) : NEW_LINE INDENT N = 9 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE if ( ( board [ i ] [ j ] <= 0 ) or ( board [ i ] [ j ] > 9 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isValidSudoku ( board ) : NEW_LINE INDENT N = 9 NEW_LINE if ( isinRange ( board ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT unique = [ False ] * ( N + 1 ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for m in range ( 0 , N + 1 ) : NEW_LINE unique [ m ] = False NEW_LINE for j in range ( 0 , N ) : NEW_LINE Z = board [ i ] [ j ] NEW_LINE if ( unique [ Z ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT unique [ Z ] = True NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT for m in range ( 0 , N + 1 ) : NEW_LINE unique [ m ] = False NEW_LINE for j in range ( 0 , N ) : NEW_LINE Z = board [ j ] [ i ] NEW_LINE if ( unique [ Z ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT unique [ Z ] = True NEW_LINE DEDENT for i in range ( 0 , N - 2 , 3 ) : NEW_LINE INDENT for j in range ( 0 , N - 2 , 3 ) : NEW_LINE for m in range ( 0 , N + 1 ) : NEW_LINE INDENT unique [ m ] = False NEW_LINE DEDENT for k in range ( 0 , 3 ) : NEW_LINE INDENT for l in range ( 0 , 3 ) : NEW_LINE X = i + k NEW_LINE Y = j + l NEW_LINE Z = board [ X ] [ Y ] NEW_LINE if ( unique [ Z ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT unique [ Z ] = True NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT board = [ [ 7 , 9 , 2 , 1 , 5 , 4 , 3 , 8 , 6 ] , [ 6 , 4 , 3 , 8 , 2 , 7 , 1 , 5 , 9 ] , [ 8 , 5 , 1 , 3 , 9 , 6 , 7 , 2 , 4 ] , [ 2 , 6 , 5 , 9 , 7 , 3 , 8 , 4 , 1 ] , [ 4 , 8 , 9 , 5 , 6 , 1 , 2 , 7 , 3 ] , [ 3 , 1 , 7 , 4 , 8 , 2 , 9 , 6 , 5 ] , [ 1 , 3 , 6 , 7 , 4 , 8 , 5 , 9 , 2 ] , [ 9 , 7 , 4 , 2 , 1 , 5 , 6 , 3 , 8 ] , [ 5 , 2 , 8 , 6 , 3 , 9 , 4 , 1 , 7 ] ] NEW_LINE if ( isValidSudoku ( board ) ) : NEW_LINE INDENT print ( \" Valid \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Valid \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Subarray of length K whose concatenation forms a palindrome | Function to check if a number is Palindrome or not here i is the starting index and j is the last index of the subarray ; If the integer at i is not equal to j then the subarray is not palindrome ; Otherwise ; all a [ i ] is equal to a [ j ] then the subarray is palindrome ; Function to find a subarray whose concatenation forms a palindrome and return its starting index ; Iterating over subarray of length k and checking if that subarray is palindrome ; If no subarray is palindrome ; Driver code","code":"def palindrome ( a , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( a [ i ] != a [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def findSubArray ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT if ( palindrome ( arr , i , i + k - 1 ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 1 , 3 ] NEW_LINE k = 4 NEW_LINE ans = findSubArray ( arr , k ) NEW_LINE if ( ans == - 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( ans , ans + k ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Check if a sequence of path visits any coordinate twice or not | Function to check if the man crosses previous visited coordinate or not ; Stores the count of crossed vertex ; Stores ( x , y ) coordinates ; The coordinates for the origin ; Iterate over the string ; Condition to increment X or Y co - ordinates respectively ; Check if ( x , y ) is already visited ; Print the result ; Given string ; Function call","code":"def isCrossed ( path ) : NEW_LINE INDENT if ( len ( path ) == 0 ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT ans = bool ( False ) NEW_LINE Set = set ( ) NEW_LINE x , y = 0 , 0 NEW_LINE Set . add ( ( x , y ) ) NEW_LINE for i in range ( len ( path ) ) : NEW_LINE INDENT if ( path [ i ] == ' N ' ) : NEW_LINE INDENT Set . add ( ( x , y ) ) NEW_LINE y = y + 1 NEW_LINE DEDENT if ( path [ i ] == ' S ' ) : NEW_LINE INDENT Set . add ( ( x , y ) ) NEW_LINE y = y - 1 NEW_LINE DEDENT if ( path [ i ] == ' E ' ) : NEW_LINE INDENT Set . add ( ( x , y ) ) NEW_LINE x = x + 1 NEW_LINE DEDENT if ( path [ i ] == ' W ' ) : NEW_LINE INDENT Set . add ( ( x , y ) ) NEW_LINE x = x - 1 NEW_LINE DEDENT if ( x , y ) in Set : NEW_LINE INDENT ans = bool ( True ) NEW_LINE break NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT print ( \" Crossed \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Crossed \" ) NEW_LINE DEDENT DEDENT path = \" NESW \" NEW_LINE isCrossed ( path ) NEW_LINE"} +{"text":"Maximum width of an N | Python3 program to implement the above approach ; Function to find the maximum width of . he tree using level order traversal ; Store the edges of the tree ; Stores maximum width of the tree ; Stores the nodes of each level ; Insert root node ; Perform level order traversal on the tree ; Stores the size of the queue ; Update maximum width ; Push the nodes of the next level and pop the elements of the current level ; Get element from the front the Queue ; Push all nodes of the next level . ; Return the result . ; Driver Code ; Constructed tree is : 1 \/ | \\ 2 - 1 3 \/ \\ \\ 4 5 8 \/ \/ | \\ 2 6 12 7","code":"from collections import deque NEW_LINE def maxWidth ( N , M , cost , s ) : NEW_LINE INDENT adj = [ [ ] for i in range ( N ) ] NEW_LINE for i in range ( M ) : NEW_LINE INDENT adj [ s [ i ] [ 0 ] ] . append ( s [ i ] [ 1 ] ) NEW_LINE DEDENT result = 0 NEW_LINE q = deque ( ) NEW_LINE q . append ( 0 ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT count = len ( q ) NEW_LINE result = max ( count , result ) NEW_LINE while ( count > 0 ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE for i in adj [ temp ] : NEW_LINE INDENT q . append ( i ) NEW_LINE DEDENT count -= 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 NEW_LINE M = 10 NEW_LINE edges = [ ] NEW_LINE edges . append ( [ 0 , 1 ] ) NEW_LINE edges . append ( [ 0 , 2 ] ) NEW_LINE edges . append ( [ 0 , 3 ] ) NEW_LINE edges . append ( [ 1 , 4 ] ) NEW_LINE edges . append ( [ 1 , 5 ] ) NEW_LINE edges . append ( [ 3 , 6 ] ) NEW_LINE edges . append ( [ 4 , 7 ] ) NEW_LINE edges . append ( [ 6 , 1 ] ) NEW_LINE edges . append ( [ 6 , 8 ] ) NEW_LINE edges . append ( [ 6 , 9 ] ) NEW_LINE cost = [ 1 , 2 , - 1 , 3 , 4 , 5 , 8 , 2 , 6 , 12 , 7 ] NEW_LINE print ( maxWidth ( N , M , cost , edges ) ) NEW_LINE DEDENT"} +{"text":"Minimize sum of prime numbers added to make an array non | Pthon3 Program to implement the above approach ; Stores if an index is a prime \/ non - prime value ; Stores the prime ; Function to generate all prime numbers ; If current element is prime ; Set all its multiples non - prime ; Store all prime numbers ; Function to find the closest prime to a particular number ; Applying binary search on primes vector ; If the prime added makes the elements equal ; Return this as the closest prime ; If the array remains non - decreasing ; Search for a bigger prime number ; Otherwise ; Check if a smaller prime can make array non - decreasing or not ; Return closest number ; Function to find the minimum cost ; Find all primes ; Store the result ; Iterate over the array ; Current element is less than the previous element ; Find the closest prime which makes the array non decreasing ; Add to overall cost ; Update current element ; Return the minimum cost ; Driver Code ; Given array ; Function Call","code":"MAX = 10000000 NEW_LINE isPrime = [ True ] * ( MAX + 1 ) NEW_LINE primes = [ ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT global isPrime NEW_LINE p = 2 NEW_LINE while p * p <= MAX : NEW_LINE INDENT if ( isPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , MAX + 1 , p ) : NEW_LINE INDENT isPrime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT primes . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def prime_search ( primes , diff ) : NEW_LINE INDENT low = 0 NEW_LINE high = len ( primes ) - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 NEW_LINE if ( primes [ mid ] == diff ) : NEW_LINE INDENT return primes [ mid ] NEW_LINE DEDENT elif ( primes [ mid ] < diff ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT res = primes [ mid ] NEW_LINE high = mid - 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def minCost ( arr , n ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE res = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT diff = arr [ i - 1 ] - arr [ i ] NEW_LINE closest_prime = prime_search ( primes , diff ) NEW_LINE res += closest_prime NEW_LINE arr [ i ] += closest_prime NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 1 , 5 , 4 , 3 ] NEW_LINE n = 5 NEW_LINE print ( minCost ( arr , n ) ) NEW_LINE DEDENT"} +{"text":"Count ways to split a Binary String into three substrings having equal count of zeros | Function to return ways to split a string into three parts with the equal number of 0 ; Store total count of 0 s ; Count total no . of 0 s character in given string ; If total count of 0 character is not divisible by 3 ; Initialize map to store frequency of k ; Traverse string to find ways to split string ; Increment count if 0 appears ; Increment result if sum equal to 2 * k and k exists in map ; Insert sum in map ; Return result ; Driver Code ; Given string ; Function call","code":"def count ( s ) : NEW_LINE INDENT cnt = 0 NEW_LINE for c in s : NEW_LINE INDENT if c == '0' : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt % 3 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE k = cnt \/\/ 3 NEW_LINE sum = 0 NEW_LINE mp = { } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] == '0' : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT if ( sum == 2 * k and k in mp and i < len ( s ) - 1 and i > 0 ) : NEW_LINE INDENT res += mp [ k ] NEW_LINE DEDENT if sum in mp : NEW_LINE INDENT mp [ sum ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ sum ] = 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT st = \"01010\" NEW_LINE print ( count ( st ) ) NEW_LINE DEDENT"} +{"text":"Check if a string can be converted to another by swapping of adjacent characters of given type | Function to check if it is possible to transform start to end ; Check the sequence of A , B in both strings str1 and str2 ; If both the strings are not equal ; Traverse the strings ; Check for indexes of A and B ; Driver Code ; Function call","code":"def canTransform ( str1 , str2 ) : NEW_LINE INDENT s1 = \" \" NEW_LINE s2 = \" \" NEW_LINE for c in str1 : NEW_LINE INDENT if ( c != ' C ' ) : NEW_LINE INDENT s1 += c NEW_LINE DEDENT DEDENT for c in str2 : NEW_LINE INDENT if ( c != ' C ' ) : NEW_LINE INDENT s2 += c NEW_LINE DEDENT DEDENT if ( s1 != s2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE n = len ( str1 ) NEW_LINE while ( i < n and j < n ) : NEW_LINE INDENT if ( str1 [ i ] == ' C ' ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( str2 [ j ] == ' C ' ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( str1 [ i ] == ' A ' and i < j ) or ( str1 [ i ] == ' B ' and i > j ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \" BCCABCBCA \" NEW_LINE str2 = \" CBACCBBAC \" NEW_LINE if ( canTransform ( str1 , str2 ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Longest Substring having equal count of Vowels and Consonants | Function to return the length of the longest substring having equal number of vowel and consonant ; Generate the array ; Initialize variable to store result ; Stores the sum of subarray ; Map to store indices of the sum ; Loop through the array ; If sum is 0 ; Count of vowels and consonants are equal ; Update the maximum length of substring in HashMap ; Store the index of the sum ; Return the maximum length of required substring ; Driver Code","code":"def maxsubstringLength ( S , N ) : NEW_LINE INDENT arr = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == ' a ' or S [ i ] == ' e ' or S [ i ] == ' i ' or S [ i ] == ' o ' or S [ i ] == ' u ' ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = - 1 NEW_LINE DEDENT DEDENT maxLen = 0 NEW_LINE curr_sum = 0 NEW_LINE hash = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE if ( curr_sum == 0 ) : NEW_LINE INDENT maxLen = max ( maxLen , i + 1 ) NEW_LINE DEDENT if ( curr_sum in hash . keys ( ) ) : NEW_LINE INDENT maxLen = max ( maxLen , i - hash [ curr_sum ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hash [ curr_sum ] = i NEW_LINE DEDENT DEDENT return maxLen NEW_LINE DEDENT S = \" geeksforgeeks \" NEW_LINE n = len ( S ) NEW_LINE print ( maxsubstringLength ( S , n ) ) NEW_LINE"} +{"text":"Minimum Distance from a given Cell to all other Cells of a Matrix | Python3 program to implement the above approach ; Stores the accessible directions ; Function to find the minimum distance from a given cell to all other cells in the matrix ; Stores the accessible cells from current cell ; Insert pair ( x , y ) ; Iterate untill queue is empty ; Extract the pair ; Pop them ; Checking boundary condition ; If the cell is not visited ; Assign the minimum distance ; Insert the traversed neighbour into the queue ; Driver Code ; Print the required distances","code":"mat = [ [ 0 for x in range ( 1001 ) ] for y in range ( 1001 ) ] NEW_LINE dx = [ 0 , - 1 , - 1 , - 1 , 0 , 1 , 1 , 1 ] NEW_LINE dy = [ 1 , 1 , 0 , - 1 , - 1 , - 1 , 0 , 1 ] NEW_LINE def FindMinimumDistance ( ) : NEW_LINE INDENT global x , y , r , c NEW_LINE q = [ ] NEW_LINE q . append ( [ x , y ] ) NEW_LINE mat [ x ] [ y ] = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT x = q [ 0 ] [ 0 ] NEW_LINE y = q [ 0 ] [ 1 ] NEW_LINE q . pop ( 0 ) NEW_LINE for i in range ( 8 ) : NEW_LINE INDENT a = x + dx [ i ] NEW_LINE b = y + dy [ i ] NEW_LINE if ( a < 0 or a >= r or b >= c or b < 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( mat [ a ] [ b ] == 0 ) : NEW_LINE INDENT mat [ a ] [ b ] = mat [ x ] [ y ] + 1 NEW_LINE q . append ( [ a , b ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT r = 5 NEW_LINE c = 5 NEW_LINE x = 1 NEW_LINE y = 1 NEW_LINE t = x NEW_LINE l = y NEW_LINE mat [ x ] [ y ] = 0 NEW_LINE FindMinimumDistance ( ) NEW_LINE mat [ t ] [ l ] = 0 NEW_LINE for i in range ( r ) : NEW_LINE INDENT for j in range ( c ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT"} +{"text":"Minimum flips required to convert given string into concatenation of equal substrings of length K | Function that returns the minimum number of flips to convert the s into a concatenation of K - length sub - string ; Stores the result ; Iterate through string index ; Stores count of 0 s & 1 s ; Iterate making K jumps ; Count 0 's ; Count 1 's ; Add minimum flips for index i ; Return minimum number of flips ; Driver code","code":"def minOperations ( S , K ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT zero , one = 0 , 0 NEW_LINE for j in range ( i , len ( S ) , K ) : NEW_LINE INDENT if ( S [ j ] == '0' ) : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT one += 1 NEW_LINE DEDENT DEDENT ans += min ( zero , one ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \"110100101\" NEW_LINE K = 3 NEW_LINE print ( minOperations ( s , K ) ) NEW_LINE DEDENT"} +{"text":"Find the missing number in unordered Arithmetic Progression | Function to get the missing element ; For maximum element in the array ; For minimum Element in the array ; For xor of all elements ; Common difference of AP series ; Find maximum and minimum element ; Calculating common difference ; Calculate the XOR of all elements ; Perform XOR with actual AP series resultant x will be the ans ; Return the missing element ; Driver Code ; Given array ; Function Call ; Print the missing element","code":"def missingElement ( arr , n ) : NEW_LINE INDENT max_ele = arr [ 0 ] NEW_LINE min_ele = arr [ 0 ] NEW_LINE x = 0 NEW_LINE d = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > max_ele ) : NEW_LINE INDENT max_ele = arr [ i ] NEW_LINE DEDENT if ( arr [ i ] < min_ele ) : NEW_LINE INDENT min_ele = arr [ i ] NEW_LINE DEDENT DEDENT d = ( max_ele - min_ele ) \/\/ n NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT x = x ^ ( min_ele + ( i * d ) ) NEW_LINE DEDENT return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 3 , 6 , 15 , 18 ] NEW_LINE n = len ( arr ) NEW_LINE element = missingElement ( arr , n ) NEW_LINE print ( element ) NEW_LINE DEDENT"} +{"text":"Given a string and an integer k , find the kth sub | Function to prints kth sub - string ; Total sub - strings possible ; If k is greater than total number of sub - strings ; To store number of sub - strings starting with ith character of the string ; Compute the values ; substring [ i - 1 ] is added to store the cumulative sum ; Binary search to find the starting index of the kth sub - string ; To store the ending index of the kth sub - string ; Print the sub - string ; Driver code","code":"def Printksubstring ( str1 , n , k ) : NEW_LINE INDENT total = int ( ( n * ( n + 1 ) ) \/ 2 ) NEW_LINE if ( k > total ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE return NEW_LINE DEDENT substring = [ 0 for i in range ( n + 1 ) ] NEW_LINE substring [ 0 ] = 0 NEW_LINE temp = n NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT substring [ i ] = substring [ i - 1 ] + temp NEW_LINE temp -= 1 NEW_LINE DEDENT l = 1 NEW_LINE h = n NEW_LINE start = 0 NEW_LINE while ( l <= h ) : NEW_LINE INDENT m = int ( ( l + h ) \/ 2 ) NEW_LINE if ( substring [ m ] > k ) : NEW_LINE INDENT start = m NEW_LINE h = m - 1 NEW_LINE DEDENT elif ( substring [ m ] < k ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = m NEW_LINE break NEW_LINE DEDENT DEDENT end = n - ( substring [ start ] - k ) NEW_LINE for i in range ( start - 1 , end ) : NEW_LINE INDENT print ( str1 [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \" abc \" NEW_LINE k = 4 NEW_LINE n = len ( str1 ) NEW_LINE Printksubstring ( str1 , n , k ) NEW_LINE DEDENT"} +{"text":"Lower Insertion Point | Function to return the lower insertion point of an element in a sorted array ; Base cases ; Final check for the remaining elements which are < X ; Driver code","code":"def LowerInsertionPoint ( arr , n , X ) : NEW_LINE INDENT if ( X < arr [ 0 ] ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT elif ( X > arr [ n - 1 ] ) : NEW_LINE INDENT return n NEW_LINE DEDENT lowerPnt = 0 NEW_LINE i = 1 NEW_LINE while ( i < n and arr [ i ] < X ) : NEW_LINE INDENT lowerPnt = i NEW_LINE i = i * 2 NEW_LINE DEDENT while ( lowerPnt < n and arr [ lowerPnt ] < X ) : NEW_LINE INDENT lowerPnt += 1 NEW_LINE DEDENT return lowerPnt NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 4 , 5 , 6 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE X = 4 NEW_LINE print ( LowerInsertionPoint ( arr , n , X ) ) NEW_LINE DEDENT"} +{"text":"Number of positions with Same address in row major and column major order | Returns count of required positions ; horizontal 1D array ; vertical 1D array ; iterating for all possible i ; checking if j is integer ; checking if j lies b \/ w 1 to N ; iterating for all possible j ; checking if i is integer ; checking if i lies b \/ w 1 to M ; Driver Code","code":"def getCount ( M , N ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( M == 1 ) : NEW_LINE INDENT return N ; NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT return M ; NEW_LINE DEDENT if ( N > M ) : NEW_LINE INDENT for i in range ( 1 , M + 1 ) : NEW_LINE INDENT numerator = N * i - N + M - i ; NEW_LINE denominator = M - 1 ; NEW_LINE if ( numerator % denominator == 0 ) : NEW_LINE INDENT j = numerator \/ denominator ; NEW_LINE if ( j >= 1 and j <= N ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT else : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT numerator = M * j - M + N - j ; NEW_LINE denominator = N - 1 ; NEW_LINE if ( numerator % denominator == 0 ) : NEW_LINE INDENT i = numerator \/ denominator ; NEW_LINE if ( i >= 1 and i <= M ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M , N = 3 , 5 ; NEW_LINE print ( getCount ( M , N ) ) ; NEW_LINE DEDENT"} +{"text":"Maximum in an array that can make another array sorted | Python3 program to make array sorted ; Function to check whether there is any swappable element present to make the first array sorted ; wrongIdx is the index of the element which is making the first array unsorted ; Find the maximum element which satisfies the above mentioned neighboring conditions ; if res is true then swap the element and make the first array sorted ; Function to print the sorted array if elements are swapped . ; Driver code","code":"import sys NEW_LINE def swapElement ( arr1 , arr2 , n ) : NEW_LINE INDENT wrongIdx = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr1 [ i ] < arr1 [ i - 1 ] ) : NEW_LINE INDENT wrongIdx = i NEW_LINE DEDENT DEDENT maximum = - ( sys . maxsize - 1 ) NEW_LINE maxIdx = - 1 NEW_LINE res = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr2 [ i ] > maximum and arr2 [ i ] >= arr1 [ wrongIdx - 1 ] ) : NEW_LINE INDENT if ( wrongIdx + 1 <= n - 1 and arr2 [ i ] <= arr1 [ wrongIdx + 1 ] ) : NEW_LINE INDENT maximum = arr2 [ i ] NEW_LINE maxIdx = i NEW_LINE res = True NEW_LINE DEDENT DEDENT DEDENT if ( res ) : NEW_LINE INDENT ( arr1 [ wrongIdx ] , arr2 [ maxIdx ] ) = ( arr2 [ maxIdx ] , arr1 [ wrongIdx ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def getSortedArray ( arr1 , arr2 , n ) : NEW_LINE INDENT if ( swapElement ( arr1 , arr2 , n ) ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr1 [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Possible \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr1 = [ 1 , 3 , 7 , 4 , 10 ] NEW_LINE arr2 = [ 2 , 1 , 6 , 8 , 9 ] NEW_LINE n = len ( arr1 ) NEW_LINE getSortedArray ( arr1 , arr2 , n ) NEW_LINE DEDENT"} +{"text":"Middle of three using minimum comparisons | Function to find the middle of three numbers ; Compare each three number to find middle number . Enter only if a > b ; Decided a is not greater than b . ; Driver Code","code":"def middleOfThree ( a , b , c ) : NEW_LINE INDENT if a > b : NEW_LINE INDENT if ( b > c ) : NEW_LINE INDENT return b NEW_LINE DEDENT elif ( a > c ) : NEW_LINE INDENT return c NEW_LINE DEDENT else : NEW_LINE INDENT return a NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( a > c ) : NEW_LINE INDENT return a NEW_LINE DEDENT elif ( b > c ) : NEW_LINE INDENT return c NEW_LINE DEDENT else : NEW_LINE INDENT return b NEW_LINE DEDENT DEDENT DEDENT a = 20 NEW_LINE b = 30 NEW_LINE c = 40 NEW_LINE print ( middleOfThree ( a , b , c ) ) NEW_LINE"} +{"text":"Sort the matrix column | Function to find the transpose of the matrix mat [ ] ; Stores the transpose of matrix mat [ ] [ ] ; Traverse each row of the matrix ; Traverse each column of the matrix ; Transpose matrix elements ; Function to sort the given matrix in row wise manner ; Traverse the row ; Row - Wise Sorting ; Function to print the matrix in column wise sorted manner ; Function call to find transpose of the the matrix mat [ ] [ ] ; Sorting the matrix row - wise ; Calculate transpose of B [ ] [ ] ; Print the matrix mat [ ] [ ] ; Driver Code ; Input ; Function call to print the matrix in column wise sorted manner","code":"def transpose ( mat , row , col ) : NEW_LINE INDENT tr = [ [ 0 for i in range ( row ) ] for i in range ( col ) ] NEW_LINE for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT tr [ j ] [ i ] = mat [ i ] [ j ] NEW_LINE DEDENT DEDENT return tr NEW_LINE DEDENT def RowWiseSort ( B ) : NEW_LINE INDENT for i in range ( len ( B ) ) : NEW_LINE INDENT B [ i ] = sorted ( B [ i ] ) NEW_LINE DEDENT return B NEW_LINE DEDENT def sortCol ( mat , N , M ) : NEW_LINE INDENT B = transpose ( mat , N , M ) NEW_LINE B = RowWiseSort ( B ) NEW_LINE mat = transpose ( B , M , N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 6 , 10 ] , [ 8 , 5 , 9 ] , [ 9 , 4 , 15 ] , [ 7 , 3 , 60 ] ] NEW_LINE N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE sortCol ( mat , N , M ) NEW_LINE DEDENT"} +{"text":"Largest area possible after removal of a series of horizontal & vertical bars | Function to find the largest area when a series of horizontal & vertical bars are removed ; Stores all bars ; Insert horizontal bars ; Insert vertictal bars ; Remove horizontal separators from s1 ; Remove vertical separators from s2 ; Stores left out horizontal and vertical separators ; Sort both list in ascending order ; Find maximum difference of neighbors of list1 ; Find max difference of neighbors of list2 ; Print largest volume ; Driver code ; Given value of N & M ; Given arrays ; Function call to find the largest area when a series of horizontal & vertical bars are removed","code":"def largestArea ( N , M , H , V , h , v ) : NEW_LINE INDENT s1 = set ( [ ] ) ; NEW_LINE s2 = set ( [ ] ) ; NEW_LINE for i in range ( 1 , N + 2 ) : NEW_LINE INDENT s1 . add ( i ) ; NEW_LINE DEDENT for i in range ( 1 , M + 2 ) : NEW_LINE INDENT s2 . add ( i ) ; NEW_LINE DEDENT for i in range ( h ) : NEW_LINE INDENT s1 . remove ( H [ i ] ) ; NEW_LINE DEDENT for i in range ( v ) : NEW_LINE INDENT s2 . remove ( V [ i ] ) ; NEW_LINE DEDENT list1 = [ 0 ] * len ( s1 ) NEW_LINE list2 = [ 0 ] * len ( s2 ) ; NEW_LINE i = 0 ; NEW_LINE for it1 in s1 : NEW_LINE INDENT list1 [ i ] = it1 ; NEW_LINE i += 1 NEW_LINE DEDENT i = 0 ; NEW_LINE for it2 in s2 : NEW_LINE INDENT list2 [ i ] = it2 NEW_LINE i += 1 NEW_LINE DEDENT list1 . sort ( ) ; NEW_LINE list2 . sort ( ) ; NEW_LINE maxH = 0 NEW_LINE p1 = 0 NEW_LINE maxV = 0 NEW_LINE p2 = 0 ; NEW_LINE for j in range ( len ( s1 ) ) : NEW_LINE INDENT maxH = max ( maxH , list1 [ j ] - p1 ) ; NEW_LINE p1 = list1 [ j ] ; NEW_LINE DEDENT for j in range ( len ( s2 ) ) : NEW_LINE INDENT maxV = max ( maxV , list2 [ j ] - p2 ) ; NEW_LINE p2 = list2 [ j ] ; NEW_LINE DEDENT print ( ( maxV * maxH ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 3 NEW_LINE M = 3 ; NEW_LINE H = [ 2 ] NEW_LINE V = [ 2 ] ; NEW_LINE h = len ( H ) NEW_LINE v = len ( V ) ; NEW_LINE largestArea ( N , M , H , V , h , v ) ; NEW_LINE DEDENT"} +{"text":"Check if an array can be sorted by swapping pairs from indices consisting of unequal elements in another array | Function to check if array , A [ ] can be converted into sorted array by swapping ( A [ i ] , A [ j ] ) if B [ i ] not equal to B [ j ] ; Stores if array A [ ] is sorted in descending order or not ; Traverse the array A [ ] ; If A [ i ] is greater than A [ i + 1 ] ; Update flag ; If array is sorted in ascending order ; count = 2 : Check if 0 s and 1 s both present in the B [ ] ; Traverse the array ; If current element is 0 ; Update count ; Traverse the array B [ ] ; If current element is 1 ; If both 0 s and 1 s are present in the array ; Input array A [ ] ; Input array B [ ] ; Function call ; If true , print YES ; Else print NO","code":"def checkifSorted ( A , B , N ) : NEW_LINE INDENT flag = False NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] > A [ i + 1 ] ) : NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT if ( not flag ) : NEW_LINE INDENT return True NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( B [ i ] == 0 ) : NEW_LINE count += 1 NEW_LINE break NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if B [ i ] : NEW_LINE count += 1 NEW_LINE break NEW_LINE DEDENT if ( count == 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT A = [ 3 , 1 , 2 ] NEW_LINE B = [ 0 , 1 , 1 ] NEW_LINE N = len ( A ) NEW_LINE check = checkifSorted ( A , B , N ) NEW_LINE if ( check ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} +{"text":"Minimum swaps required between two strings to make one string strictly greater than the other | Function to find the minimum number of steps to make A > B ; If all character are same and M <= N ; If there lies any character in B which is greater than B [ 0 ] ; If there lies any character in A which is smaller than A [ 0 ] ; If there lies a character which is in A and greater than A [ 0 ] ; If there lies a character which is in B and less than B [ 0 ] ; Otherwise ; Driver Code","code":"def minSteps ( A , B , M , N ) : NEW_LINE INDENT if ( A [ 0 ] > B [ 0 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( B [ 0 ] > A [ 0 ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( M <= N and A [ 0 ] == B [ 0 ] and A . count ( A [ 0 ] ) == M and B . count ( B [ 0 ] ) == N ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( B [ i ] > B [ 0 ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , M ) : NEW_LINE INDENT if ( A [ i ] < A [ 0 ] ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , M ) : NEW_LINE INDENT if ( A [ i ] > A [ 0 ] ) : NEW_LINE INDENT A [ 0 ] , B [ i ] = B [ i ] , A [ 0 ] NEW_LINE A [ 0 ] , B [ 0 ] = B [ 0 ] , A [ 0 ] NEW_LINE return 2 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( B [ i ] < B [ 0 ] ) : NEW_LINE INDENT A [ 0 ] , B [ i ] = B [ i ] , A [ 0 ] NEW_LINE A [ 0 ] , B [ 0 ] = B [ 0 ] , A [ 0 ] NEW_LINE return 2 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = \" adsfd \" NEW_LINE B = \" dffff \" NEW_LINE M = len ( A ) NEW_LINE N = len ( B ) NEW_LINE print ( minSteps ( A , B , M , N ) ) NEW_LINE DEDENT"} +{"text":"Maximize sum of pairwise products generated from the given Arrays | Python3 program for the above approach ; Variables which represent the size of the array ; Stores the results ; Function to return the maximum possible sum ; Stores the count of arrays processed ; If more than two arrays have been processed ; If an already computed subproblem occurred ; Explore all the possible pairs ; Recursive function call ; Memoize the maximum ; Returning the value ; Function to return the maximum sum of products of pairs possible ; Initialising the dp array to - 1 ; Sort the arrays in descending order ; Driver Code","code":"maxN = 201 ; NEW_LINE n1 , n2 , n3 = 0 , 0 , 0 ; NEW_LINE dp = [ [ [ 0 for i in range ( maxN ) ] for j in range ( maxN ) ] for j in range ( maxN ) ] ; NEW_LINE def getMaxSum ( i , j , k , arr1 , arr2 , arr3 ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE if ( i >= n1 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT if ( j >= n2 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT if ( k >= n3 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT if ( cnt >= 2 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ i ] [ j ] [ k ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] [ k ] ; NEW_LINE DEDENT ans = 0 ; NEW_LINE if ( i < n1 and j < n2 ) : NEW_LINE INDENT ans = max ( ans , getMaxSum ( i + 1 , j + 1 , k , arr1 , arr2 , arr3 ) + arr1 [ i ] * arr2 [ j ] ) ; NEW_LINE DEDENT if ( i < n1 and k < n3 ) : NEW_LINE INDENT ans = max ( ans , getMaxSum ( i + 1 , j , k + 1 , arr1 , arr2 , arr3 ) + arr1 [ i ] * arr3 [ k ] ) ; NEW_LINE DEDENT if ( j < n2 and k < n3 ) : NEW_LINE INDENT ans = max ( ans , getMaxSum ( i , j + 1 , k + 1 , arr1 , arr2 , arr3 ) + arr2 [ j ] * arr3 [ k ] ) ; NEW_LINE DEDENT dp [ i ] [ j ] [ k ] = ans ; NEW_LINE return dp [ i ] [ j ] [ k ] ; NEW_LINE DEDENT def reverse ( tmp ) : NEW_LINE INDENT i , k , t = 0 , 0 , 0 ; NEW_LINE n = len ( tmp ) ; NEW_LINE for i in range ( n \/\/ 2 ) : NEW_LINE INDENT t = tmp [ i ] ; NEW_LINE tmp [ i ] = tmp [ n - i - 1 ] ; NEW_LINE tmp [ n - i - 1 ] = t ; NEW_LINE DEDENT DEDENT def maxProductSum ( arr1 , arr2 , arr3 ) : NEW_LINE INDENT for i in range ( len ( dp ) ) : NEW_LINE INDENT for j in range ( len ( dp [ 0 ] ) ) : NEW_LINE INDENT for k in range ( len ( dp [ j ] [ 0 ] ) ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] = - 1 ; NEW_LINE DEDENT DEDENT DEDENT arr1 . sort ( ) ; NEW_LINE reverse ( arr1 ) ; NEW_LINE arr2 . sort ( ) ; NEW_LINE reverse ( arr2 ) ; NEW_LINE arr3 . sort ( ) ; NEW_LINE reverse ( arr3 ) ; NEW_LINE return getMaxSum ( 0 , 0 , 0 , arr1 , arr2 , arr3 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 2 ; NEW_LINE arr1 = [ 3 , 5 ] ; NEW_LINE n2 = 2 ; NEW_LINE arr2 = [ 2 , 1 ] ; NEW_LINE n3 = 3 ; NEW_LINE arr3 = [ 4 , 3 , 5 ] ; NEW_LINE print ( maxProductSum ( arr1 , arr2 , arr3 ) ) ; NEW_LINE DEDENT"} +{"text":"Largest lexicographic triplet from a given Array that forms a triangle | Function to find lexicographically largest triplet that forms a triangle in the given array ; Sort the array ; Iterate from the end of the array ; If the triplet forms a triangle ; If triplet found ; Print the triplet ; Otherwise ; Driver Code","code":"def findTriplet ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = N - 1 NEW_LINE while i - 2 >= 0 : NEW_LINE INDENT if ( arr [ i - 2 ] + arr [ i - 1 ] > arr [ i ] ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT print ( arr [ i - 2 ] , arr [ i - 1 ] , arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 10 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE findTriplet ( arr , N ) NEW_LINE DEDENT"} +{"text":"Count of all pairs in an Array with minimum absolute difference | Function to return the count of all pairs having minimal absolute difference ; Stores the count of pairs ; Sort the array ; Stores the minimum difference between adjacent pairs ; Update the minimum difference between pairs ; Increase count of pairs with difference equal to that of minimum difference ; Return the final count ; Driver code ; Given array arr [ ] ; Function call","code":"def numberofpairs ( arr , N ) : NEW_LINE INDENT answer = 0 NEW_LINE arr . sort ( ) NEW_LINE minDiff = 10000000 NEW_LINE for i in range ( 0 , N - 1 ) : NEW_LINE INDENT minDiff = min ( minDiff , arr [ i + 1 ] - arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , N - 1 ) : NEW_LINE INDENT if arr [ i + 1 ] - arr [ i ] == minDiff : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( numberofpairs ( arr , N ) ) NEW_LINE DEDENT"} +{"text":"Maximum size subset with given sum using Backtracking | Initialise maximum possible length of subsequence ; Store elements to compare max_length with its size and change the value of max_length accordingly ; Store the elements of the longest subsequence ; Function to find the length of longest subsequence ; Update max_length ; Store the subsequence elements ; Recursively proceed with obtained sum ; poping elements from back of vector store ; if sum > 0 then we don 't required thatsubsequence so return and continue with earlier elements ; Sort the given array ; Traverse the array ; If max_length is already greater than or equal than remaining length ; Driver code","code":"max_length = 0 NEW_LINE store = [ ] NEW_LINE ans = [ ] NEW_LINE def find_max_length ( arr , index , sum , k ) : NEW_LINE INDENT global max_length NEW_LINE sum = sum + arr [ index ] NEW_LINE store . append ( arr [ index ] ) NEW_LINE if ( sum == k ) : NEW_LINE INDENT if ( max_length < len ( store ) ) : NEW_LINE INDENT max_length = len ( store ) NEW_LINE ans = store NEW_LINE DEDENT DEDENT for i in range ( index + 1 , len ( arr ) ) : NEW_LINE INDENT if ( sum + arr [ i ] <= k ) : NEW_LINE INDENT find_max_length ( arr , i , sum , k ) NEW_LINE store . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT return NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT def longestSubsequence ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max_length >= n - i ) : NEW_LINE INDENT break NEW_LINE DEDENT store . clear ( ) NEW_LINE find_max_length ( arr , i , 0 , k ) NEW_LINE DEDENT return max_length NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ - 3 , 0 , 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 1 NEW_LINE print ( longestSubsequence ( arr , n , k ) ) NEW_LINE DEDENT"} +{"text":"Sort decreasing permutation of N using triple swaps | Function to sort array ; Check if possible to sort array ; Swapping to bring element at required position Bringing at least one element at correct position ; Tracing changes in Array ; Print the sorted array ; If not possible to sort ; Driver code","code":"def sortArray ( A , N ) : NEW_LINE INDENT if ( N % 4 == 0 or N % 4 == 1 ) : NEW_LINE INDENT for i in range ( N \/\/ 2 ) : NEW_LINE INDENT x = i NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT y = N - i - 2 NEW_LINE z = N - i - 1 NEW_LINE DEDENT A [ z ] = A [ y ] NEW_LINE A [ y ] = A [ x ] NEW_LINE A [ x ] = x + 1 NEW_LINE DEDENT print ( \" Sorted \u2581 Array : \u2581 \" , end = \" \" ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT DEDENT A = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE N = len ( A ) NEW_LINE sortArray ( A , N ) NEW_LINE"} +{"text":"Find K such that changing all elements of the Array greater than K to K will make array sum N | Function to return K such that changing all elements greater than K to K will make array sum N otherwise return - 1 ; Sorting the array in increasing order ; Loop through all the elements of the array ; Checking if sum of array equals N ; Driver code","code":"def findK ( arr , size , N ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE temp_sum = 0 NEW_LINE for i in range ( size ) : NEW_LINE INDENT temp_sum += arr [ i ] NEW_LINE if ( N - temp_sum == arr [ i ] * ( size - i - 1 ) ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 3 , 1 , 10 , 4 , 8 ] NEW_LINE size = len ( arr ) NEW_LINE N = 16 NEW_LINE print ( findK ( arr , size , N ) ) NEW_LINE"} +{"text":"Find three element from given three arrays such that their sum is X | Set 2 | Function that returns True if there exists a triplet with sum x ; Sorting arrays such that a represents smallest array ; Iterating the smallest array ; Two pointers on second and third array ; If a valid triplet is found ; Driver code","code":"def existsTriplet ( a , b , c , x , l1 , l2 , l3 ) : NEW_LINE INDENT if ( l2 <= l1 and l2 <= l3 ) : NEW_LINE INDENT l1 , l2 = l2 , l1 NEW_LINE a , b = b , a NEW_LINE DEDENT elif ( l3 <= l1 and l3 <= l2 ) : NEW_LINE INDENT l1 , l3 = l3 , l1 NEW_LINE a , c = c , a NEW_LINE DEDENT for i in range ( l1 ) : NEW_LINE INDENT j = 0 NEW_LINE k = l3 - 1 NEW_LINE while ( j < l2 and k >= 0 ) : NEW_LINE INDENT if ( a [ i ] + b [ j ] + c [ k ] == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( a [ i ] + b [ j ] + c [ k ] < x ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT a = [ 2 , 7 , 8 , 10 , 15 ] NEW_LINE b = [ 1 , 6 , 7 , 8 ] NEW_LINE c = [ 4 , 5 , 5 ] NEW_LINE l1 = len ( a ) NEW_LINE l2 = len ( b ) NEW_LINE l3 = len ( c ) NEW_LINE x = 14 NEW_LINE if ( existsTriplet ( a , b , c , x , l1 , l2 , l3 ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Arrange given numbers to form the smallest number | Utility function to print the contents of an array ; A comparison function that return true if ' AB ' is smaller than ' BA ' when we concatenate two numbers ' A ' and ' B ' For example , it will return true if we pass 12 and 24 as arguments . This function will be used by sort ( ) function ; Convert first number to string format ; Convert second number to string format ; Check if ' AB ' is smaller or ' BA ' and return bool value since comparison operator ' < = ' returns true or false ; ; Function to print the arrangement with the smallest value ; If we pass the name of the comparison function it will sort the array according to the compare function ; Print the sorted array ; Driver code","code":"def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT def compare ( num1 , num2 ) : NEW_LINE INDENT A = str ( num1 ) NEW_LINE B = str ( num2 ) NEW_LINE return int ( A + B ) <= int ( B + A ) NEW_LINE DEDENT def sort ( arr ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT if compare ( arr [ i ] , arr [ j ] ) == False : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def printSmallest ( N , arr ) : NEW_LINE INDENT sort ( arr ) NEW_LINE printArr ( arr , N ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 5 , 6 , 2 , 9 , 21 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE printSmallest ( N , arr ) NEW_LINE DEDENT"} +{"text":"Stable Selection Sort | Python3 program for modifying Selection Sort so that it becomes stable . ; Traverse through all array elements ; Find the minimum element in remaining unsorted array ; Move minimum element at current i ; Driver Code","code":"def stableSelectionSort ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT min_idx = i NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if a [ min_idx ] > a [ j ] : NEW_LINE INDENT min_idx = j NEW_LINE DEDENT DEDENT key = a [ min_idx ] NEW_LINE while min_idx > i : NEW_LINE INDENT a [ min_idx ] = a [ min_idx - 1 ] NEW_LINE min_idx -= 1 NEW_LINE DEDENT a [ i ] = key NEW_LINE DEDENT DEDENT def printArray ( a , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( \" % d \" % a [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT a = [ 4 , 5 , 3 , 2 , 4 , 1 ] NEW_LINE n = len ( a ) NEW_LINE stableSelectionSort ( a , n ) NEW_LINE printArray ( a , n ) NEW_LINE"} +{"text":"Permute two arrays such that sum of every pair is greater or equal to K | Check whether any permutation exists which satisfy the condition . ; Sort the array a [ ] in decreasing order . ; Sort the array b [ ] in increasing order . ; Checking condition on each index . ; Driver code","code":"def isPossible ( a , b , n , k ) : NEW_LINE INDENT a . sort ( reverse = True ) NEW_LINE b . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] + b [ i ] < k ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT a = [ 2 , 1 , 3 ] NEW_LINE b = [ 7 , 8 , 9 ] NEW_LINE k = 10 NEW_LINE n = len ( a ) NEW_LINE if ( isPossible ( a , b , n , k ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} +{"text":"Sort an array according to count of set bits | Function to count setbits ; Function to sort By SetBitCount ; Iterate over all values and insert into multimap ; Driver Code","code":"def setBitCount ( num ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT num = num >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def sortBySetBitCount ( arr , n ) : NEW_LINE INDENT count = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count . append ( [ ( - 1 ) * setBitCount ( arr [ i ] ) , arr [ i ] ] ) NEW_LINE DEDENT count . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for i in range ( len ( count ) ) : NEW_LINE INDENT print ( count [ i ] [ 1 ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE sortBySetBitCount ( arr , n ) NEW_LINE"} +{"text":"Check if end of given Binary string can be reached by choosing jump value in between given range | Function to check if it is possible to reach the end of the binary string using the given jumps ; Stores the DP states ; Initial state ; Stores count of indices from which it is possible to reach index i ; Traverse the given string ; Update the values of pre accordingly ; If the jump size is out of the range [ L , R ] ; Return answer ; Driver Code","code":"def canReach ( s , L , R ) : NEW_LINE INDENT dp = [ 0 for _ in range ( len ( s ) ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE pre = 0 NEW_LINE for i in range ( 1 , len ( s ) ) : NEW_LINE INDENT if ( i >= L ) : NEW_LINE INDENT pre += dp [ i - L ] NEW_LINE DEDENT if ( i > R ) : NEW_LINE INDENT pre -= dp [ i - R - 1 ] NEW_LINE DEDENT dp [ i ] = ( pre > 0 ) and ( s [ i ] == '0' ) NEW_LINE DEDENT return dp [ len ( s ) - 1 ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S = \"01101110\" NEW_LINE L = 2 NEW_LINE R = 3 NEW_LINE if canReach ( S , L , R ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} +{"text":"Split an array into subarrays with maximum Bitwise XOR of their respective Bitwise OR values | Recursive function to find all the possible breaking of arrays o subarrays and find the maximum Bitwise XOR ; If the value of N is 0 ; Stores the result if the new group is formed with the first element as arr [ i ] ; Stores if the result if the arr [ i ] is included in the last group ; Returns the maximum of x and y ; Function to find the maximum possible Bitwise XOR of all possible values of the array after breaking the arrays o subarrays ; Return the result ; Driver Code","code":"def maxXORUtil ( arr , N , xrr , orr ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return xrr ^ orr NEW_LINE DEDENT x = maxXORUtil ( arr , N - 1 , xrr ^ orr , arr [ N - 1 ] ) NEW_LINE y = maxXORUtil ( arr , N - 1 , xrr , orr arr [ N - 1 ] ) NEW_LINE return max ( x , y ) NEW_LINE DEDENT def maximumXOR ( arr , N ) : NEW_LINE INDENT return maxXORUtil ( arr , N , 0 , 0 ) NEW_LINE DEDENT arr = 1 , 5 , 7 NEW_LINE N = len ( arr ) NEW_LINE print ( maximumXOR ( arr , N ) ) NEW_LINE"} +{"text":"Construct an N | Python3 program to implement the above approach ; Keep track of visited nodes ; Function to construct a tree such that there are no two adjacent nodes with the same weight ; If minimum and maximum elements are equal , i . e . array contains one distinct element ; Tree cannot be constructed ; Otherwise ; Tree can be constructed ; Choose weights [ 0 ] as root ; First Node is visited ; Traverse the array ; Otherwise , make an edge ; Mark this node as visited ; Find a weight not same as the root & make edges with that node ; Join non - roots with remaining nodes ; Check if current node ' s \u2581 weight \u2581 \u2581 is \u2581 same \u2581 as \u2581 root \u2581 node ' s weight and if it is not visited or not ; Driver Code ; Function Call","code":"N = 10 ** 5 + 5 NEW_LINE visited = [ 0 ] * N NEW_LINE def construct_tree ( weights , n ) : NEW_LINE INDENT minimum = min ( weights ) NEW_LINE maximum = max ( weights ) NEW_LINE if ( minimum == maximum ) : NEW_LINE INDENT print ( \" No \" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT root = weights [ 0 ] NEW_LINE visited [ 1 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( weights [ i ] != root and visited [ i + 1 ] == 0 ) : NEW_LINE INDENT print ( 1 , i + 1 ) NEW_LINE visited [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT notroot = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( weights [ i ] != root ) : NEW_LINE INDENT notroot = i + 1 NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( weights [ i ] == root and visited [ i + 1 ] == 0 ) : NEW_LINE INDENT print ( notroot , i + 1 ) NEW_LINE visited [ i + 1 ] = 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT weights = [ 1 , 2 , 1 , 2 , 5 ] NEW_LINE N = len ( weights ) NEW_LINE construct_tree ( weights , N ) NEW_LINE DEDENT"} +{"text":"Minimize cost to convert given string into concatenation of equal substrings of length K | Python3 program for the above approach ; Function to find minimum cost to convert given string into string of K length same substring ; Stores length of string ; Stores the minimum cost ; Traverse left substring of k length ; Stores the frequency ; Stores minimum cost for sequence of S [ i ] % k indices ; Check for optimal character ; Find sum of distance ' a ' + ch from character S [ i ] % k indices ; Choose minimum cost for each index i ; Increment ans ; Print minimum cost to convert string ; Given string S ; Function call","code":"import sys NEW_LINE def minCost ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT a = [ 0 ] * 26 NEW_LINE for j in range ( i , n , k ) : NEW_LINE INDENT a [ ord ( s [ j ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT min_cost = sys . maxsize - 1 NEW_LINE for ch in range ( 26 ) : NEW_LINE INDENT cost = 0 NEW_LINE for tr in range ( 26 ) : NEW_LINE INDENT cost += abs ( ch - tr ) * a [ tr ] NEW_LINE DEDENT min_cost = min ( min_cost , cost ) NEW_LINE DEDENT ans += min_cost NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = \" abcdefabc \" NEW_LINE K = 3 NEW_LINE minCost ( S , K ) NEW_LINE"} +{"text":"Split first N natural numbers into two sets with minimum absolute difference of their sums | Function to split the first N natural numbers into two sets having minimum absolute difference of their sums ; Driver Code","code":"def minAbsDiff ( N ) : NEW_LINE INDENT if ( N % 4 == 0 or N % 4 == 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 NEW_LINE DEDENT N = 6 NEW_LINE print ( minAbsDiff ( N ) ) NEW_LINE"} +{"text":"Find maximum matching in a given Binary Tree | Python3 program for the above approach ; Adjacency list to store edges ; Add an edge between U and V in tree ; Edge from u to v ; Edge from V to U ; Function that finds the maximum matching of the DFS ; Go further as we are not allowed to go towards its parent ; If U and its parent P is not taken then we must take & mark them as taken ; Increment size of edge set ; Function to find the maximum matching in a graph ; Taking 1 as a root of the tree ; Print maximum Matching ; Driver Code ; Joining edge between two nodes in tree ; Function Call","code":"N = 10000 NEW_LINE adj = { } NEW_LINE used = [ 0 for i in range ( N ) ] NEW_LINE max_matching = 0 NEW_LINE def AddEdge ( u , v ) : NEW_LINE INDENT if u not in adj : NEW_LINE INDENT adj [ u ] = [ ] NEW_LINE DEDENT if v not in adj : NEW_LINE INDENT adj [ v ] = [ ] NEW_LINE DEDENT adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def Matching_dfs ( u , p ) : NEW_LINE INDENT global max_matching NEW_LINE for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( adj [ u ] [ i ] != p ) : NEW_LINE INDENT Matching_dfs ( adj [ u ] [ i ] , u ) NEW_LINE DEDENT DEDENT if ( not used [ u ] and not used [ p ] and p != 0 ) : NEW_LINE INDENT max_matching += 1 NEW_LINE used [ u ] = 1 NEW_LINE used [ p ] = 1 NEW_LINE DEDENT DEDENT def maxMatching ( ) : NEW_LINE INDENT Matching_dfs ( 1 , 0 ) NEW_LINE print ( max_matching ) NEW_LINE DEDENT n = 5 NEW_LINE AddEdge ( 1 , 2 ) NEW_LINE AddEdge ( 1 , 3 ) NEW_LINE AddEdge ( 3 , 4 ) NEW_LINE AddEdge ( 3 , 5 ) NEW_LINE maxMatching ( ) NEW_LINE"} +{"text":"Minimize cost to Swap two given Arrays | Python3 program to implement the above approach ; Function to calculate and return the minimum cost required to swap two arrays ; Return the total minimum cost ; Driver Code","code":"import sys NEW_LINE def getMinCost ( A , B , N ) : NEW_LINE INDENT mini = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT mini = min ( mini , min ( A [ i ] , B [ i ] ) ) NEW_LINE DEDENT return mini * ( 2 * N - 1 ) NEW_LINE DEDENT N = 3 NEW_LINE A = [ 1 , 4 , 2 ] NEW_LINE B = [ 10 , 6 , 12 ] NEW_LINE print ( getMinCost ( A , B , N ) ) NEW_LINE"} +{"text":"Print all possible ways to write N as sum of two or more positive integers | Function to print the values stored in vector arr ; Traverse the vector arr ; Recursive function to prdifferent ways in which N can be written as a sum of at 2 or more positive integers ; If n is zero then prthis ways of breaking numbers ; Start from previous element in the representation till n ; Include current element from representation ; Call function again with reduced sum ; Backtrack to remove current element from representation ; Driver Code ; Given sum N ; To store the representation of breaking N ; Function Call","code":"def printVector ( arr ) : NEW_LINE INDENT if ( len ( arr ) != 1 ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def findWays ( arr , i , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT printVector ( arr ) NEW_LINE DEDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT arr . append ( j ) NEW_LINE findWays ( arr , j , n - j ) NEW_LINE del arr [ - 1 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE arr = [ ] NEW_LINE findWays ( arr , 1 , n ) NEW_LINE DEDENT"} +{"text":"Check if a string can be split into two strings with same number of K | Function to print the arrangement of characters ; Stores frequency of characters ; Count the character having frequency K ; Count the character having frequency greater than K and not equal to 2 K ; Case 1 ; Case 2 ; Case 3 ; If all cases fail ; Driver Code","code":"def DivideString ( s , n , k ) : NEW_LINE INDENT c = 0 NEW_LINE no = 1 NEW_LINE c1 = 0 NEW_LINE c2 = 0 NEW_LINE fr = [ 0 ] * 26 NEW_LINE ans = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT fr [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( fr [ i ] == k ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if ( fr [ i ] > k and fr [ i ] != 2 * k ) : NEW_LINE INDENT c1 += 1 NEW_LINE ch = chr ( ord ( ' a ' ) + i ) NEW_LINE DEDENT if ( fr [ i ] == 2 * k ) : NEW_LINE INDENT c2 += 1 NEW_LINE ch1 = chr ( ord ( ' a ' ) + i ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT ans . append ( \"1\" ) NEW_LINE DEDENT mp = { } NEW_LINE if ( c % 2 == 0 or c1 > 0 or c2 > 0 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( fr [ ord ( s [ i ] ) - ord ( ' a ' ) ] == k ) : NEW_LINE INDENT if ( s [ i ] in mp ) : NEW_LINE INDENT ans [ i ] = '2' NEW_LINE DEDENT else : NEW_LINE INDENT if ( no <= ( c \/\/ 2 ) ) : NEW_LINE INDENT ans [ i ] = '2' NEW_LINE no += 1 NEW_LINE mp [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( c % 2 == 1 and c1 > 0 ) : NEW_LINE INDENT no = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ch and no <= k ) : NEW_LINE INDENT ans [ i ] = '2' NEW_LINE no += 1 NEW_LINE DEDENT DEDENT DEDENT if ( c % 2 == 1 and c1 == 0 ) : NEW_LINE INDENT no = 1 NEW_LINE flag = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == ch1 and no <= k ) : NEW_LINE INDENT ans [ i ] = '2' NEW_LINE no += 1 NEW_LINE DEDENT if ( fr [ s [ i ] - ' a ' ] == k and flag == 0 and ans [ i ] == '1' ) : NEW_LINE INDENT ans [ i ] = '2' NEW_LINE flag = 1 NEW_LINE DEDENT DEDENT DEDENT print ( \" \" . join ( ans ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" abbbccc \" NEW_LINE N = len ( S ) NEW_LINE K = 1 NEW_LINE DivideString ( S , N , K ) NEW_LINE DEDENT"} +{"text":"Check if two items can be selected from two different categories without exceeding price | Function to check if two items can be selected from two different categories without exceeding the total price ; Loop to choose two different pairs using two nested loops ; Condition to check if the price of these two elements is less than S ; Driver Code ; Function Call","code":"def check ( S , prices , type1 , n ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( ( type1 [ j ] == 0 and type1 [ k ] == 1 ) or ( type1 [ j ] == 1 and type1 [ k ] == 0 ) ) : NEW_LINE INDENT if ( prices [ j ] + prices [ k ] <= S ) : NEW_LINE INDENT return \" Yes \" ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return \" No \" ; NEW_LINE DEDENT prices = [ 3 , 8 , 6 , 5 ] ; NEW_LINE type1 = [ 0 , 1 , 1 , 0 ] ; NEW_LINE S = 10 ; NEW_LINE n = 4 ; NEW_LINE print ( check ( S , prices , type1 , n ) ) ; NEW_LINE"} +{"text":"Find the maximum sum ( a + b ) for a given input integer N satisfying the given condition | Function to return the maximum sum of a + b satisfying the given condition ; Consider all possible pairs and check the sum divides product property ; To find the largest factor k ; Check if the product is divisible by the sum ; Storing the maximum sum in the max_sum variable ; Return the max_sum value ; Driver code","code":"def getLargestSum ( N ) : NEW_LINE INDENT for i in range ( 1 , int ( N ** ( 1 \/ 2 ) ) + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , int ( N ** ( 1 \/ 2 ) ) + 1 ) : NEW_LINE INDENT k = N \/\/ j ; NEW_LINE a = k * i ; NEW_LINE b = k * j ; NEW_LINE if ( a <= N and b <= N and a * b % ( a + b ) == 0 ) : NEW_LINE INDENT max_sum = max ( max_sum , a + b ) ; NEW_LINE DEDENT DEDENT DEDENT return max_sum ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 25 ; NEW_LINE max_sum = getLargestSum ( N ) ; NEW_LINE print ( max_sum ) ; NEW_LINE DEDENT"} +{"text":"Encrypt a string by repeating i | Function to return the encrypted string ; Number of times the current character will be repeated ; Repeat the current character in the encrypted string ; Driver code","code":"def encryptString ( string , n ) : NEW_LINE INDENT i , cnt = 0 , 0 NEW_LINE encryptedStr = \" \" NEW_LINE while i < n : NEW_LINE INDENT cnt = i + 1 NEW_LINE while cnt > 0 : NEW_LINE INDENT encryptedStr += string [ i ] NEW_LINE cnt -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return encryptedStr NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" geeks \" NEW_LINE n = len ( string ) NEW_LINE print ( encryptString ( string , n ) ) NEW_LINE DEDENT"} +{"text":"Minimize the difference between the maximum and minimum values of the modified array | Function to return required minimum difference ; finding minimum and maximum values ; returning minimum possible difference ; Driver program ; function to return the answer","code":"def minDiff ( n , x , A ) : NEW_LINE INDENT mn = A [ 0 ] NEW_LINE mx = A [ 0 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT mn = min ( mn , A [ i ] ) NEW_LINE mx = max ( mx , A [ i ] ) NEW_LINE DEDENT return max ( 0 , mx - mn - 2 * x ) NEW_LINE DEDENT n = 3 NEW_LINE x = 3 NEW_LINE A = [ 1 , 3 , 6 ] NEW_LINE print ( minDiff ( n , x , A ) ) NEW_LINE"} +{"text":"Minimum Swaps for Bracket Balancing | Python3 program to count swaps required to balance string ; Stores total number of left and right brackets encountered ; Swap stores the number of swaps required imbalance maintains the number of imbalance pair ; Increment count of left bracket ; Swaps count is last swap count + total number imbalanced brackets ; Imbalance decremented by 1 as it solved only one imbalance of left and right ; Increment count of right bracket ; Imbalance is reset to current difference between left and right brackets ; Driver code","code":"def swapCount ( s ) : NEW_LINE INDENT chars = s NEW_LINE countLeft = 0 NEW_LINE countRight = 0 NEW_LINE swap = 0 NEW_LINE imbalance = 0 ; NEW_LINE for i in range ( len ( chars ) ) : NEW_LINE INDENT if chars [ i ] == ' [ ' : NEW_LINE INDENT countLeft += 1 NEW_LINE if imbalance > 0 : NEW_LINE INDENT swap += imbalance NEW_LINE imbalance -= 1 NEW_LINE DEDENT DEDENT elif chars [ i ] == ' ] ' : NEW_LINE INDENT countRight += 1 NEW_LINE imbalance = ( countRight - countLeft ) NEW_LINE DEDENT DEDENT return swap NEW_LINE DEDENT s = \" [ ] ] [ ] [ \" ; NEW_LINE print ( swapCount ( s ) ) NEW_LINE s = \" [ [ ] [ ] ] \" ; NEW_LINE print ( swapCount ( s ) ) NEW_LINE"} +{"text":"Longest subsequence from an array of pairs having first element increasing and second element decreasing . | Function to find the length of the longest subsequence of pairs whose first element is increasing and second is decreasing ; dp [ i ] : Stores the longest subsequence upto i ; Base case ; When the conditions hold ; Finally , prthe required answer ; Driver Code ; Given Input ; Function Call","code":"def longestSubSequence ( A , N ) : NEW_LINE INDENT dp = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( A [ j ] [ 0 ] < A [ i ] [ 0 ] and A [ j ] [ 1 ] > A [ i ] [ 1 ] ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT print ( dp [ N - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 1 , 2 ] , [ 2 , 2 ] , [ 3 , 1 ] ] NEW_LINE N = len ( A ) NEW_LINE longestSubSequence ( A , N ) NEW_LINE DEDENT"} +{"text":"Count ways to obtain given sum by repeated throws of a dice | Function to calculate the total number of ways to have sum N ; Base Case ; Return already stored result ; Recur for all 6 states ; Return the result ; Driver Code ; Given sum N ; Initialize the dp array ; Function Call","code":"def findWays ( N , dp ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ N ] != - 1 ) : NEW_LINE INDENT return dp [ N ] NEW_LINE DEDENT cnt = 0 NEW_LINE for i in range ( 1 , 7 ) : NEW_LINE INDENT if ( N - i >= 0 ) : NEW_LINE INDENT cnt = ( cnt + findWays ( N - i , dp ) ) NEW_LINE DEDENT DEDENT dp [ N ] = cnt NEW_LINE return dp [ N ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 NEW_LINE dp = [ - 1 ] * ( N + 1 ) NEW_LINE print ( findWays ( N , dp ) ) NEW_LINE DEDENT"} +{"text":"Count ways to obtain given sum by repeated throws of a dice | Function to calculate the total number of ways to have sum N ; Initialize dp array ; Iterate over all the possible intermediate values to reach N ; Calculate the sum for all 6 faces ; Print total number of ways ; Driver Code ; Given sum N ; Function call","code":"def findWays ( N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) ; NEW_LINE dp [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT dp [ i ] = 0 ; NEW_LINE for j in range ( 1 , 7 ) : NEW_LINE INDENT if ( i - j >= 0 ) : NEW_LINE INDENT dp [ i ] = dp [ i ] + dp [ i - j ] ; NEW_LINE DEDENT DEDENT DEDENT print ( dp [ N ] ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; NEW_LINE findWays ( N ) ; NEW_LINE DEDENT"} +{"text":"Split the string into minimum parts such that each part is in the another string | Python3 implementation to split the string into minimum number of parts such that each part is also present in the another string ; Node of Trie ; Function to insert a node in the Trie Data Structure ; Inserting every character from idx till end to string into trie ; If there is no edge corresponding to the ith character , then make a new node ; Function to find the minimum number of parts such that each part is present into another string ; Making a new trie ; Inserting every substring of S2 in trie ; Creating dp array and init it with infinity ; Base Case ; Starting the cut from ith character taking temporary node pointer for checking whether the substring [ i , j ) is present in trie of not ; If the jth character is not in trie we 'll break ; Updating the the ending of jth character with dp [ i ] + 1 ; Descending the trie pointer ; Answer not possible ; Driver Code","code":"INF = 1e9 + 9 NEW_LINE class TrieNode ( ) : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . child = [ None ] * 26 NEW_LINE DEDENT DEDENT def insert ( idx , s , root ) : NEW_LINE INDENT temp = root NEW_LINE for i in range ( idx , len ( s ) ) : NEW_LINE INDENT if temp . child [ ord ( s [ i ] ) - ord ( ' a ' ) ] == None : NEW_LINE INDENT temp . child [ ord ( s [ i ] ) - ord ( ' a ' ) ] = TrieNode ( ) NEW_LINE DEDENT temp = temp . child [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE DEDENT DEDENT def minCuts ( S1 , S2 ) : NEW_LINE INDENT n1 = len ( S1 ) NEW_LINE n2 = len ( S2 ) NEW_LINE root = TrieNode ( ) NEW_LINE for i in range ( n2 ) : NEW_LINE INDENT insert ( i , S2 , root ) NEW_LINE DEDENT dp = [ INF ] * ( n1 + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT temp = root NEW_LINE for j in range ( i + 1 , n1 + 1 ) : NEW_LINE INDENT if temp . child [ ord ( S1 [ j - 1 ] ) - ord ( ' a ' ) ] == None : NEW_LINE INDENT break NEW_LINE DEDENT dp [ j ] = min ( dp [ j ] , dp [ i ] + 1 ) NEW_LINE temp = temp . child [ ord ( S1 [ j - 1 ] ) - ord ( ' a ' ) ] NEW_LINE DEDENT DEDENT if dp [ n1 ] >= INF : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return dp [ n1 ] NEW_LINE DEDENT DEDENT S1 = \" abcdab \" NEW_LINE S2 = \" dabc \" NEW_LINE print ( minCuts ( S1 , S2 ) ) NEW_LINE"} +{"text":"Largest Square in a Binary Matrix with at most K 1 s for multiple Queries | Function to find the largest square in the matrix such that it contains atmost K 1 's ; Precomputing the countDP prefix sum of the matrix ; Loop to solve Queries ; Calculating the maximum possible distance of the centre from edge ; Count total number of 1 s in the sub square considered ; If the count is less than or equals to the maximum move to right half ; Driver Code","code":"def largestSquare ( matrix , R , C , q_i , q_j , K , Q ) : NEW_LINE INDENT countDP = [ [ 0 for x in range ( C ) ] for x in range ( R ) ] NEW_LINE countDP [ 0 ] [ 0 ] = matrix [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , R ) : NEW_LINE INDENT countDP [ i ] [ 0 ] = ( countDP [ i - 1 ] [ 0 ] + matrix [ i ] [ 0 ] ) NEW_LINE DEDENT for j in range ( 1 , C ) : NEW_LINE INDENT countDP [ 0 ] [ j ] = ( countDP [ 0 ] [ j - 1 ] + matrix [ 0 ] [ j ] ) NEW_LINE DEDENT for i in range ( 1 , R ) : NEW_LINE INDENT for j in range ( 1 , C ) : NEW_LINE INDENT countDP [ i ] [ j ] = ( matrix [ i ] [ j ] + countDP [ i - 1 ] [ j ] + countDP [ i ] [ j - 1 ] - countDP [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT for q in range ( 0 , Q ) : NEW_LINE INDENT i = q_i [ q ] NEW_LINE j = q_j [ q ] NEW_LINE min_dist = min ( i , j , R - i - 1 , C - j - 1 ) NEW_LINE ans = - 1 NEW_LINE l = 0 NEW_LINE u = min_dist NEW_LINE while ( l <= u ) : NEW_LINE INDENT mid = int ( ( l + u ) \/ 2 ) NEW_LINE x1 = i - mid NEW_LINE x2 = i + mid NEW_LINE y1 = j - mid NEW_LINE y2 = j + mid NEW_LINE count = countDP [ x2 ] [ y2 ] NEW_LINE if ( x1 > 0 ) : NEW_LINE INDENT count -= countDP [ x1 - 1 ] [ y2 ] NEW_LINE DEDENT if ( y1 > 0 ) : NEW_LINE INDENT count -= countDP [ x2 ] [ y1 - 1 ] NEW_LINE DEDENT if ( x1 > 0 and y1 > 0 ) : NEW_LINE INDENT count += countDP [ x1 - 1 ] [ y1 - 1 ] NEW_LINE DEDENT if ( count <= K ) : NEW_LINE INDENT ans = 2 * mid + 1 NEW_LINE l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT u = mid - 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT DEDENT matrix = [ [ 1 , 0 , 1 , 0 , 0 ] , [ 1 , 0 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 ] , [ 1 , 0 , 0 , 1 , 0 ] ] NEW_LINE K = 9 NEW_LINE Q = 1 NEW_LINE q_i = [ 1 ] NEW_LINE q_j = [ 2 ] NEW_LINE largestSquare ( matrix , 4 , 5 , q_i , q_j , K , Q ) NEW_LINE"}