{"text":"Program to convert Centimeters to Pixels | Function to convert centimeters to pixels ; Driver Code","code":"def Conversion ( centi ) : NEW_LINE INDENT pixels = ( 96 * centi ) \/ 2.54 NEW_LINE print ( round ( pixels , 2 ) ) NEW_LINE DEDENT centi = 15 NEW_LINE Conversion ( centi ) NEW_LINE"} {"text":"Kth array element after M replacements of array elements by XOR of adjacent pairs | Method that returns the corresponding output by taking the given inputs . ; If this condition is satisfied , value of M is invalid ; Check if index K is valid ; Loop to perform M operations ; Creating a temporary list ; Traversing the array ; Calculate XOR values of adjacent elements ; Adding this value to the temporary list ; Update the original array ; Getting value at index K ; Number of elements ; Given array arr [ ] ; Function Call","code":"def xor_operations ( N , arr , M , K ) : NEW_LINE INDENT if M < 0 or M >= N : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if K < 0 or K >= N - M : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for _ in range ( M ) : NEW_LINE INDENT temp = [ ] NEW_LINE for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT value = arr [ i ] ^ arr [ i + 1 ] NEW_LINE temp . append ( value ) NEW_LINE DEDENT arr = temp [ : ] NEW_LINE DEDENT ans = arr [ K ] NEW_LINE return ans NEW_LINE DEDENT N = 5 NEW_LINE arr = [ 1 , 4 , 5 , 6 , 7 ] NEW_LINE M = 1 NEW_LINE K = 2 NEW_LINE print ( xor_operations ( N , arr , M , K ) ) NEW_LINE"} {"text":"Check if N can be divided into K consecutive elements with a sum equal to N | Function to find the K consecutive elements with a sum equal to N ; Iterate over [ 2 , INF ] ; Store the sum ; If the sum exceeds N then break the loop ; Common difference should be divisible by number of terms ; Print value of i & return ; Print \" - 1\" if not possible to break N ; Given N ; Function call","code":"def canBreakN ( n ) : NEW_LINE INDENT for i in range ( 2 , n ) : NEW_LINE INDENT m = i * ( i + 1 ) \/\/ 2 NEW_LINE if ( m > n ) : NEW_LINE INDENT break NEW_LINE DEDENT k = n - m NEW_LINE if ( k % i ) : NEW_LINE INDENT continue NEW_LINE DEDENT print ( i ) NEW_LINE return NEW_LINE DEDENT print ( \" - 1\" ) NEW_LINE DEDENT N = 12 NEW_LINE canBreakN ( N ) NEW_LINE"} {"text":"Coprime divisors of a number | Python3 program to find two coprime divisors of a given number such that both are greater than 1 ; Function which finds the required pair of divisors of N ; We iterate upto sqrt ( N ) as we can find all the divisors of N in this time ; If x is a divisor of N keep dividing as long as possible ; We have found a required pair ; No such pair of divisors of N was found , hence print - 1 ; Sample example 1 ; Sample example 2","code":"import math NEW_LINE def findCoprimePair ( N ) : NEW_LINE INDENT for x in range ( 2 , int ( math . sqrt ( N ) ) + 1 ) : NEW_LINE INDENT if ( N % x == 0 ) : NEW_LINE INDENT while ( N % x == 0 ) : NEW_LINE INDENT N \/\/= x NEW_LINE DEDENT if ( N > 1 ) : NEW_LINE INDENT print ( x , N ) NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT print ( \" - 1\" ) NEW_LINE DEDENT N = 45 NEW_LINE findCoprimePair ( N ) NEW_LINE N = 25 NEW_LINE findCoprimePair ( N ) NEW_LINE"} {"text":"Wasteful Numbers | Python3 program for the above approach ; Array to store all prime less than and equal to MAX . ; Function for Sieve of Sundaram ; Boolean Array ; Mark all numbers which do not generate prime number by 2 * i + 1 ; Since 2 is a prime number ; Print remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function that returns true if n is a Wasteful number ; Count digits in original number ; Count all digits in prime factors of N pDigit is going to hold this value . ; Count powers of p in n ; If primes [ i ] is a prime factor , ; Count the power of prime factors ; Add its digits to pDigit ; Add digits of power of prime factors to pDigit . ; If n != 1 then one prime factor still to be summed up ; If digits in prime factors is more than digits in original number then return true . Else return false . ; Function to print Wasteful Number before N ; Iterate till N and check if i is wastefull or not ; Precompute prime numbers upto 10 ^ 6 ; Function Call","code":"import math NEW_LINE MAX = 10000 NEW_LINE primes = [ ] NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ False ] * ( ( MAX \/\/ 2 ) + 1 ) NEW_LINE for i in range ( 1 , ( ( int ( math . sqrt ( MAX ) ) - 1 ) \/\/ 2 ) + 1 ) : NEW_LINE INDENT j = ( i * ( i + 1 ) ) << 1 NEW_LINE while j <= ( MAX \/\/ 2 ) : NEW_LINE INDENT marked [ j ] = True NEW_LINE j = j + 2 * i + 1 NEW_LINE DEDENT DEDENT primes . append ( 2 ) NEW_LINE for i in range ( 1 , ( MAX \/\/ 2 ) + 1 ) : NEW_LINE INDENT if marked [ i ] == False : NEW_LINE INDENT primes . append ( 2 * i + 1 ) NEW_LINE DEDENT DEDENT DEDENT def isWasteful ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT original_no = n NEW_LINE sumDigits = 0 NEW_LINE while ( original_no > 0 ) : NEW_LINE INDENT sumDigits += 1 NEW_LINE original_no = original_no \/\/ 10 NEW_LINE DEDENT pDigit , count_exp , p = 0 , 0 , 0 NEW_LINE i = 0 NEW_LINE while ( primes [ i ] <= ( n \/\/ 2 ) ) : NEW_LINE INDENT while ( n % primes [ i ] == 0 ) : NEW_LINE INDENT p = primes [ i ] NEW_LINE n = n \/\/ p NEW_LINE count_exp += 1 NEW_LINE DEDENT while ( p > 0 ) : NEW_LINE INDENT pDigit += 1 NEW_LINE p = p \/\/ 10 NEW_LINE DEDENT while ( count_exp > 1 ) : NEW_LINE INDENT pDigit += 1 NEW_LINE count_exp = count_exp \/\/ 10 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( n != 1 ) : NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT pDigit += 1 NEW_LINE n = n \/\/ 10 NEW_LINE DEDENT DEDENT return bool ( pDigit > sumDigits ) NEW_LINE DEDENT def Solve ( N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( isWasteful ( i ) ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT sieveSundaram ( ) NEW_LINE N = 10 NEW_LINE Solve ( N ) NEW_LINE"} {"text":"Hexanacci Numbers | Function to print the Nth Hexanacci number ; Driver code","code":"def printhexaRec ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 or \\ n == 2 or n == 3 or \\ n == 4 or n == 5 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( n == 6 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( printhexaRec ( n - 1 ) + printhexaRec ( n - 2 ) + printhexaRec ( n - 3 ) + printhexaRec ( n - 4 ) + printhexaRec ( n - 5 ) + printhexaRec ( n - 6 ) ) NEW_LINE DEDENT DEDENT def printhexa ( n ) : NEW_LINE INDENT print ( printhexaRec ( n ) ) NEW_LINE DEDENT n = 11 NEW_LINE printhexa ( n ) NEW_LINE"} {"text":"Hexanacci Numbers | Function to print the Nth term of the Hexanacci number ; Initialize first five numbers to base cases ; declare a current variable ; Loop to add previous five numbers for each number starting from 5 and then assign first , second , third , fourth fifth to second , third , fourth , fifth and curr to sixth respectively ; Driver code","code":"def printhexa ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT first = 0 NEW_LINE second = 0 NEW_LINE third = 0 NEW_LINE fourth = 0 NEW_LINE fifth = 0 NEW_LINE sixth = 1 NEW_LINE curr = 0 NEW_LINE if ( n < 6 ) : NEW_LINE INDENT print ( first ) NEW_LINE DEDENT elif ( n == 6 ) : NEW_LINE INDENT print ( sixth ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 6 , n ) : NEW_LINE INDENT curr = first + second + third + fourth + fifth + sixth NEW_LINE first = second NEW_LINE second = third NEW_LINE third = fourth NEW_LINE fourth = fifth NEW_LINE fifth = sixth NEW_LINE sixth = curr NEW_LINE DEDENT DEDENT print ( curr ) NEW_LINE DEDENT n = 11 NEW_LINE printhexa ( n ) NEW_LINE"} {"text":"Find the smallest number whose sum of digits is N | Function to find the smallest number whose sum of digits is also N ; Driver code","code":"def smallestNumber ( N ) : NEW_LINE INDENT print ( ( N % 9 + 1 ) * pow ( 10 , ( N \/\/ 9 ) ) - 1 ) NEW_LINE DEDENT N = 10 NEW_LINE smallestNumber ( N ) NEW_LINE"} {"text":"Compositorial of a number | Function to check if a number is composite . ; Corner cases ; This is checked so that we can skip the middle five numbers in the below loop ; This function stores all Composite numbers less than N ; Function to calculate the Compositorial of n ; Multiply first n composite number ; Driver code ; Vector to store all the composite less than N","code":"def isComposite ( n ) : NEW_LINE INDENT 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 def Compositorial_list ( n ) : NEW_LINE INDENT l = 0 NEW_LINE for i in range ( 4 , 10 ** 6 ) : NEW_LINE INDENT if l < n : NEW_LINE INDENT if isComposite ( i ) : NEW_LINE INDENT compo . append ( i ) NEW_LINE l += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def calculateCompositorial ( n ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT result = result * compo [ i ] NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 5 NEW_LINE compo = [ ] NEW_LINE Compositorial_list ( n ) NEW_LINE print ( calculateCompositorial ( n ) ) NEW_LINE DEDENT"} {"text":"Distinct powers of a number N such that the sum is equal to K | Initializing the PowerArray with all 0 's ; Function to find the powers of N that add up to K ; Initializing the counter ; Executing the while loop until K is greater than 0 ; If K % N == 1 , then the power array is incremented by 1 ; Checking if any power is occurred more than once ; For any other value , the sum of powers cannot be added up to K ; Printing the powers of N that sum up to K ; Driver code","code":"b = [ 0 for i in range ( 50 ) ] NEW_LINE def PowerArray ( n , k ) : NEW_LINE INDENT count = 0 NEW_LINE while ( k ) : NEW_LINE INDENT if ( k % n == 0 ) : NEW_LINE INDENT k \/\/= n NEW_LINE count += 1 NEW_LINE DEDENT elif ( k % n == 1 ) : NEW_LINE INDENT k -= 1 NEW_LINE b [ count ] += 1 NEW_LINE if ( b [ count ] > 1 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE return 0 NEW_LINE DEDENT DEDENT for i in range ( 50 ) : NEW_LINE INDENT if ( b [ i ] ) : NEW_LINE INDENT print ( i , end = \" , \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 40 NEW_LINE PowerArray ( N , K ) NEW_LINE DEDENT"} {"text":"Program to find value of 1 ^ k + 2 ^ k + 3 ^ k + ... + n ^ k | Python 3 Program to find the value 1 ^ K + 2 ^ K + 3 ^ K + . . + N ^ K ; Function to find value of 1 ^ K + 2 ^ K + 3 ^ K + . . + N ^ K ; Initialise sum to 0 ; Find the value of pow ( i , 4 ) and then add it to the sum ; Return the sum ; Drives Code ; Function call to find the sum","code":"from math import pow NEW_LINE def findSum ( N , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT sum += pow ( i , k ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE k = 4 NEW_LINE print ( int ( findSum ( N , k ) ) ) NEW_LINE DEDENT"} {"text":"Count of indices in an array that satisfy the given condition | Function to return the count of indices that satisfy the given condition ; To store the result ; To store the current maximum Initialized to 0 since there are only positive elements in the array ; i is a valid index ; Update the maximum so far ; Increment the counter ; Driver code","code":"def countIndices ( arr , n ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE max = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countIndices ( arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Maximum frequency of a remainder modulo 2 i | Binary representation of the digits ; Function to return the maximum frequency of s modulo with a power of 2 ; Store the binary representation ; Convert the octal to binary ; Remove the LSB ; If there is 1 in the binary representation ; Find the number of zeroes in between two 1 's in the binary representation ; Driver code","code":"bin = [ \"000\" , \"001\" , \"010\" , \"011\" , \"100\" , \"101\" , \"110\" , \"111\" ] ; NEW_LINE def maxFreq ( s ) : NEW_LINE INDENT binary = \" \" ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT binary += bin [ ord ( s [ i ] ) - ord ( '0' ) ] ; NEW_LINE DEDENT binary = binary [ 0 : len ( binary ) - 1 ] ; NEW_LINE count = 1 ; prev = - 1 ; j = 0 ; NEW_LINE for i in range ( len ( binary ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( binary [ i ] == '1' ) : NEW_LINE INDENT count = max ( count , j - prev ) ; NEW_LINE prev = j ; NEW_LINE DEDENT j += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT octal = \"13\" ; NEW_LINE print ( maxFreq ( octal ) ) ; NEW_LINE DEDENT"} {"text":"Find all the prime numbers of given number of digits | Python 3 implementation of the approach ; Function for Sieve of Eratosthenes ; Function to print all the prime numbers with d digits ; Range to check integers ; For every integer in the range ; If the current integer is prime ; Driver code ; Generate primes","code":"from math import sqrt , pow NEW_LINE sz = 100005 NEW_LINE isPrime = [ True for i in range ( sz + 1 ) ] NEW_LINE def sieve ( ) : NEW_LINE INDENT isPrime [ 0 ] = isPrime [ 1 ] = False NEW_LINE for i in range ( 2 , int ( sqrt ( sz ) ) + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT for j in range ( i * i , sz , i ) : NEW_LINE INDENT isPrime [ j ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def findPrimesD ( d ) : NEW_LINE INDENT left = int ( pow ( 10 , d - 1 ) ) NEW_LINE right = int ( pow ( 10 , d ) - 1 ) NEW_LINE for i in range ( left , right + 1 , 1 ) : NEW_LINE INDENT if ( isPrime [ i ] ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT sieve ( ) NEW_LINE d = 1 NEW_LINE findPrimesD ( d ) NEW_LINE DEDENT"} {"text":"Find the number of cells in the table contains X | Function to find number of cells in the table contains X ; Driver Code ; Function call","code":"def Cells ( n , x ) : NEW_LINE INDENT if ( n <= 0 or x <= 0 or x > n * n ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT i = 1 NEW_LINE count = 0 NEW_LINE while ( i * i < x ) : NEW_LINE INDENT if ( x % i == 0 and x <= n * i ) : NEW_LINE INDENT count += 2 ; NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i * i == x ) : NEW_LINE INDENT return count + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return count NEW_LINE DEDENT DEDENT n = 6 NEW_LINE x = 12 NEW_LINE print ( Cells ( n , x ) ) NEW_LINE"} {"text":"Find the maximum possible value of the minimum value of modified array | Function to find the maximum possible value of the minimum value of the modified array ; To store minimum value of array ; To store sum of elements of array ; Solution is not possible ; zero is the possible value ; minimum possible value ; maximum possible value ; to store a required answer ; Binary Search ; If mid is possible then try to increase required answer ; If mid is not possible then decrease required answer ; Return required answer ; Driver Code","code":"def maxOfMin ( a , n , S ) : NEW_LINE INDENT mi = 10 ** 9 NEW_LINE s1 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s1 += a [ i ] NEW_LINE mi = min ( a [ i ] , mi ) NEW_LINE DEDENT if ( s1 < S ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( s1 == S ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT low = 0 NEW_LINE high = mi NEW_LINE ans = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 NEW_LINE if ( s1 - ( mid * n ) >= S ) : 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 a = [ 10 , 10 , 10 , 10 , 10 ] NEW_LINE S = 10 NEW_LINE n = len ( a ) NEW_LINE print ( maxOfMin ( a , n , S ) ) NEW_LINE"} {"text":"Program to print ' N ' alphabet using the number pattern from 1 to n | Function to print the desired Alphabet N Pattern ; Declaring the values of Right , Left and Diagonal values ; Main Loop for the rows ; For the left Values ; Spaces for the diagonals ; Condition for the diagonals ; Spaces for the Right Values ; For the right values ; Driver Code ; Size of the Pattern ; Calling the function to print the desired Pattern","code":"def Alphabet_N_Pattern ( N ) : NEW_LINE INDENT Right = 1 NEW_LINE Left = 1 NEW_LINE Diagonal = 2 NEW_LINE for index in range ( N ) : NEW_LINE INDENT print ( Left , end = \" \" ) NEW_LINE Left += 1 NEW_LINE for side_index in range ( 0 , 2 * ( index ) , 1 ) : NEW_LINE INDENT print ( \" \u2581 \" , end = \" \" ) NEW_LINE DEDENT if ( index != 0 and index != N - 1 ) : NEW_LINE INDENT print ( Diagonal , end = \" \" ) NEW_LINE Diagonal += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" \u2581 \" , end = \" \" ) NEW_LINE DEDENT for side_index in range ( 0 , 2 * ( N - index - 1 ) , 1 ) : NEW_LINE INDENT print ( \" \u2581 \" , end = \" \" ) NEW_LINE DEDENT print ( Right , end = \" \" ) NEW_LINE Right += 1 NEW_LINE print ( \" \" , \u2581 end \u2581 = \u2581 \" \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Size = 6 NEW_LINE Alphabet_N_Pattern ( Size ) NEW_LINE DEDENT"} {"text":"Check if the sum of digits of a number N divides it | Function to check if sum of digits of a number divides it ; Calculate sum of all of digits of N ; Driver Code","code":"def isSumDivides ( N ) : NEW_LINE INDENT temp = N NEW_LINE sum = 0 NEW_LINE while ( temp ) : NEW_LINE INDENT sum += temp % 10 NEW_LINE temp = int ( temp \/ 10 ) NEW_LINE DEDENT if ( N % sum == 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 = 12 NEW_LINE if ( isSumDivides ( N ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} {"text":"Sum of numbers from 1 to N which are divisible by 3 or 4 | Function to calculate the sum of numbers divisible by 3 or 4 ;","code":"def sum ( N ) : NEW_LINE INDENT global S1 , S2 , S3 NEW_LINE S1 = ( ( ( N \/\/ 3 ) ) * ( 2 * 3 + ( N \/\/ 3 - 1 ) * 3 ) \/\/ 2 ) NEW_LINE S2 = ( ( ( N \/\/ 4 ) ) * ( 2 * 4 + ( N \/\/ 4 - 1 ) * 4 ) \/\/ 2 ) NEW_LINE S3 = ( ( ( N \/\/ 12 ) ) * ( 2 * 12 + ( N \/\/ 12 - 1 ) * 12 ) \/\/ 2 ) NEW_LINE return int ( S1 + S2 - S3 ) NEW_LINE DEDENT \/ * Driver code * \/ NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE print ( sum ( N ) ) NEW_LINE DEDENT"} {"text":"Next greater number than N with exactly one bit different in binary representation of N | Function to find next greater number than N with exactly one bit different in binary representation of N ; It is guaranteed that there is a bit zero in the number ; If the shifted bit is zero then break ; increase the bit shift ; increase the power of 2 ; set the lowest bit of the number ; Driver code ; display the next number","code":"def nextGreater ( N ) : NEW_LINE INDENT power_of_2 = 1 ; NEW_LINE shift_count = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( ( ( N >> shift_count ) & 1 ) % 2 == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT shift_count += 1 ; NEW_LINE power_of_2 = power_of_2 * 2 ; NEW_LINE DEDENT return ( N + power_of_2 ) ; NEW_LINE DEDENT N = 11 ; NEW_LINE print ( \" The \u2581 next \u2581 number \u2581 is \u2581 = \" , nextGreater ( N ) ) ; NEW_LINE"} {"text":"Count number of ways to cover a distance | Set 2 | Function to return the count of the total number of ways to cover the distance with 1 , 2 and 3 steps ; Base conditions ; To store the last three stages ; Find the numbers of steps required to reach the distance i ; Return the required answer ; Driver code","code":"def countWays ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n <= 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT f0 = 1 NEW_LINE f1 = 1 NEW_LINE f2 = 2 NEW_LINE ans = 0 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT ans = f0 + f1 + f2 NEW_LINE f0 = f1 NEW_LINE f1 = f2 NEW_LINE f2 = ans NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 4 NEW_LINE print ( countWays ( n ) ) NEW_LINE"} {"text":"Maximize sum by choosing elements from different section of a matrix | Python3 program for the above approach ; Function to find the maximum value ; Dp table ; Fill the dp in bottom up manner ; Maximum of the three sections ; Maximum of the first section ; Maximum of the second section ; Maximum of the third section ; If we choose element from section 1 , we cannot have selection from same section in adjacent rows ; Print the maximum sum ; Driver code","code":"import numpy as np NEW_LINE n = 6 ; m = 6 ; NEW_LINE def maxSum ( arr ) : NEW_LINE INDENT dp = np . zeros ( ( n + 1 , 3 ) ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT m1 = 0 ; m2 = 0 ; m3 = 0 ; NEW_LINE for j in range ( m ) : NEW_LINE INDENT if ( ( j \/\/ ( m \/\/ 3 ) ) == 0 ) : NEW_LINE INDENT m1 = max ( m1 , arr [ i ] [ j ] ) ; NEW_LINE DEDENT elif ( ( j \/\/ ( m \/\/ 3 ) ) == 1 ) : NEW_LINE INDENT m2 = max ( m2 , arr [ i ] [ j ] ) ; NEW_LINE DEDENT elif ( ( j \/\/ ( m \/\/ 3 ) ) == 2 ) : NEW_LINE INDENT m3 = max ( m3 , arr [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 1 ] , dp [ i ] [ 2 ] ) + m1 ; NEW_LINE dp [ i + 1 ] [ 1 ] = max ( dp [ i ] [ 0 ] , dp [ i ] [ 2 ] ) + m2 ; NEW_LINE dp [ i + 1 ] [ 2 ] = max ( dp [ i ] [ 1 ] , dp [ i ] [ 0 ] ) + m3 ; NEW_LINE DEDENT print ( max ( max ( dp [ n ] [ 0 ] , dp [ n ] [ 1 ] ) , dp [ n ] [ 2 ] ) ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ [ 1 , 3 , 5 , 2 , 4 , 6 ] , [ 6 , 4 , 5 , 1 , 3 , 2 ] , [ 1 , 3 , 5 , 2 , 4 , 6 ] , [ 6 , 4 , 5 , 1 , 3 , 2 ] , [ 6 , 4 , 5 , 1 , 3 , 2 ] , [ 1 , 3 , 5 , 2 , 4 , 6 ] ] ; NEW_LINE maxSum ( arr ) ; NEW_LINE DEDENT"} {"text":"Total number of odd length palindrome sub | Function to find the total palindromic odd Length sub - sequences ; dp array to store the number of palindromic subsequences for 0 to i - 1 and j + 1 to n - 1 ; We will start with the largest distance between i and j ; For each Len , we fix our i ; For this i we will find our j ; Base cases ; If the characters are equal then look for out of bound index ; We have only 1 way that is to just pick these characters ; If the characters are not equal ; Subtract it as we have counted it twice ; We have just 1 palindrome sequence of Length 1 ; Else total ways would be sum of dp [ i - 1 ] [ i + 1 ] , that is number of palindrome sub - sequences from 1 to i - 1 + number of palindrome sub - sequences from i + 1 to n - 1 ; Driver code","code":"def solve ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for Len in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if i + Len >= n : NEW_LINE INDENT break NEW_LINE DEDENT j = i + Len NEW_LINE if ( i == 0 and j == n - 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 2 NEW_LINE DEDENT elif ( s [ i ] != s [ j ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j + 1 <= n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i ] [ j + 1 ] NEW_LINE DEDENT if ( i - 1 < 0 or j + 1 >= n ) : NEW_LINE INDENT dp [ i ] [ j ] += 1 NEW_LINE DEDENT DEDENT elif ( s [ i ] != s [ j ] ) : NEW_LINE INDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j ] NEW_LINE DEDENT if ( j + 1 <= n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i ] [ j + 1 ] NEW_LINE DEDENT if ( i - 1 >= 0 and j + 1 <= n - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] -= dp [ i - 1 ] [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT ways = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 or i == n - 1 ) : NEW_LINE INDENT ways . append ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT total = dp [ i - 1 ] [ i + 1 ] NEW_LINE ways . append ( total ) NEW_LINE DEDENT DEDENT for i in ways : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT s = \" xyxyx \" NEW_LINE solve ( s ) NEW_LINE"} {"text":"Find the number of Chicks in a Zoo at Nth day | Function to return the number of chicks on the nth day ; Size of dp [ ] has to be at least 6 ( 1 - based indexing ) ; Every day current population will be three times of the previous day ; Manually calculated value ; From 8 th day onwards ; Chick population decreases by 2 \/ 3 everyday . For 8 th day on [ i - 6 ] i . e 2 nd day population was 3 and so 2 new born die on the 6 th day and so on for the upcoming days ; Driver code","code":"def getChicks ( n ) : NEW_LINE INDENT size = max ( n , 7 ) ; NEW_LINE dp = [ 0 ] * size ; NEW_LINE dp [ 0 ] = 0 ; NEW_LINE dp [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , 7 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] * 3 ; NEW_LINE DEDENT dp [ 6 ] = 726 ; NEW_LINE for i in range ( 8 , n + 1 ) : NEW_LINE INDENT dp [ i ] = ( dp [ i - 1 ] - ( 2 * dp [ i - 6 ] \/\/ 3 ) ) * 3 ; NEW_LINE DEDENT return dp [ n ] ; NEW_LINE DEDENT n = 3 ; NEW_LINE print ( getChicks ( n ) ) ; NEW_LINE"} {"text":"Find the number of Chicks in a Zoo at Nth day | Function to return the number of chicks on the nth day ; Driver code","code":"def getChicks ( n ) : NEW_LINE INDENT chicks = pow ( 3 , n - 1 ) NEW_LINE return chicks NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 3 NEW_LINE print ( getChicks ( n ) ) NEW_LINE DEDENT"} {"text":"Find minimum steps required to reach the end of a matrix | Set 2 | Python3 implementation of the approach ; 2d array to store states of dp ; Array to determine whether a state has been solved before ; Function to return the minimum steps required ; Base cases ; If a state has been solved before it won 't be evaluated again ; Recurrence relation ; Driver code","code":"import numpy as np NEW_LINE n = 3 NEW_LINE dp = np . zeros ( ( n , n ) ) NEW_LINE v = np . zeros ( ( n , n ) ) ; NEW_LINE def minSteps ( i , j , arr ) : NEW_LINE INDENT if ( i == n - 1 and j == n - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i > n - 1 or j > n - 1 ) : NEW_LINE INDENT return 9999999 ; NEW_LINE DEDENT if ( v [ i ] [ j ] ) : NEW_LINE INDENT return dp [ i ] [ j ] ; NEW_LINE DEDENT v [ i ] [ j ] = 1 ; NEW_LINE dp [ i ] [ j ] = 9999999 ; NEW_LINE for k in range ( max ( 0 , arr [ i ] [ j ] + j - n + 1 ) , min ( n - i - 1 , arr [ i ] [ j ] ) + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , minSteps ( i + k , j + arr [ i ] [ j ] - k , arr ) ) ; NEW_LINE DEDENT dp [ i ] [ j ] += 1 ; NEW_LINE return dp [ i ] [ j ] ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ [ 4 , 1 , 2 ] , [ 1 , 1 , 1 ] , [ 2 , 1 , 1 ] ] ; NEW_LINE ans = minSteps ( 0 , 0 , arr ) ; NEW_LINE if ( ans >= 9999999 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) ; NEW_LINE DEDENT DEDENT"} {"text":"Find minimum steps required to reach the end of a matrix | Set | Python3 program to implement above approach ; 2d array to store states of dp ; array to determine whether a state has been solved before ; Function to find the minimum number of steps to reach the end of matrix ; base cases ; if a state has been solved before it won 't be evaluated again. ; recurrence relation ; Driver Code","code":"import numpy as np ; NEW_LINE n = 3 NEW_LINE dp = np . zeros ( ( n , n ) ) ; NEW_LINE v = np . zeros ( ( n , n ) ) ; NEW_LINE def minSteps ( i , j , arr ) : NEW_LINE INDENT if ( i == n - 1 and j == n - 1 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( i > n - 1 or j > n - 1 ) : NEW_LINE INDENT return 9999999 ; NEW_LINE DEDENT if ( v [ i ] [ j ] ) : NEW_LINE INDENT return dp [ i ] [ j ] ; NEW_LINE DEDENT v [ i ] [ j ] = 1 ; NEW_LINE dp [ i ] [ j ] = 1 + min ( minSteps ( i + arr [ i ] [ j ] , j , arr ) , minSteps ( i , j + arr [ i ] [ j ] , arr ) ) ; NEW_LINE return dp [ i ] [ j ] ; NEW_LINE DEDENT arr = [ [ 2 , 1 , 2 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] ; NEW_LINE ans = minSteps ( 0 , 0 , arr ) ; NEW_LINE if ( ans >= 9999999 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) ; NEW_LINE DEDENT"} {"text":"Treasure and Cities | A memoization based program to find maximum treasure that can be collected . ; k is current index and col is previous color . ; base case ; we have two options either visit current city or skip that ; check if color of this city is equal to prev visited city ; return max of both options ; Driver code","code":"MAX = 1001 NEW_LINE dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def MaxProfit ( treasure , color , n , k , col , A , B ) : NEW_LINE INDENT if ( k == n ) : NEW_LINE INDENT dp [ k ] [ col ] = 0 NEW_LINE return dp [ k ] [ col ] NEW_LINE DEDENT if ( dp [ k ] [ col ] != - 1 ) : NEW_LINE INDENT return dp [ k ] [ col ] NEW_LINE DEDENT summ = 0 NEW_LINE if ( col == color [ k ] ) : NEW_LINE INDENT summ += max ( A * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) NEW_LINE DEDENT else : NEW_LINE INDENT summ += max ( B * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) NEW_LINE DEDENT dp [ k ] [ col ] = summ NEW_LINE return dp [ k ] [ col ] NEW_LINE DEDENT A = - 5 NEW_LINE B = 7 NEW_LINE treasure = [ 4 , 8 , 2 , 9 ] NEW_LINE color = [ 2 , 2 , 6 , 2 ] NEW_LINE n = len ( color ) NEW_LINE print ( MaxProfit ( treasure , color , n , 0 , 0 , A , B ) ) NEW_LINE"} {"text":"Tetranacci Numbers | Function to print the N - th tetranacci number ; base cases ; Driver code","code":"def printTetra ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 5 ) ; NEW_LINE dp [ 0 ] = 0 ; NEW_LINE dp [ 1 ] = 1 ; NEW_LINE dp [ 2 ] = 1 ; NEW_LINE dp [ 3 ] = 2 ; NEW_LINE for i in range ( 4 , n + 1 ) : NEW_LINE INDENT dp [ i ] = ( dp [ i - 1 ] + dp [ i - 2 ] + dp [ i - 3 ] + dp [ i - 4 ] ) ; NEW_LINE DEDENT print ( dp [ n ] ) ; NEW_LINE DEDENT n = 10 ; NEW_LINE printTetra ( n ) ; NEW_LINE"} {"text":"Maximum sum in circular array such that no two elements are adjacent | Function to calculate the sum from 0 th position to ( n - 2 ) th position ; copy the element of original array to dp [ ] ; find the maximum element in the array ; start from 2 nd to n - 1 th pos ; traverse for all pairs bottom - up approach ; dp - condition ; find maximum sum ; return the maximum ; Function to find the maximum sum from 1 st position to n - 1 - th position ; Traverse from third to n - th pos ; bootom - up approach ; dp condition ; find max sum ; return max ; Driver Code","code":"def maxSum1 ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE maxi = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE if ( maxi < arr [ i ] ) : NEW_LINE INDENT maxi = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 2 , n - 1 ) : NEW_LINE INDENT for j in range ( i - 1 ) : NEW_LINE INDENT if ( dp [ i ] < dp [ j ] + arr [ i ] ) : NEW_LINE INDENT dp [ i ] = dp [ j ] + arr [ i ] NEW_LINE if ( maxi < dp [ i ] ) : NEW_LINE INDENT maxi = dp [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return maxi NEW_LINE DEDENT def maxSum2 ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE maxi = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE if ( maxi < arr [ i ] ) : NEW_LINE INDENT maxi = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 3 , n ) : NEW_LINE INDENT for j in range ( 1 , i - 1 ) : NEW_LINE INDENT if ( dp [ i ] < arr [ i ] + dp [ j ] ) : NEW_LINE INDENT dp [ i ] = arr [ i ] + dp [ j ] NEW_LINE if ( maxi < dp [ i ] ) : NEW_LINE INDENT maxi = dp [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return maxi NEW_LINE DEDENT def findMaxSum ( arr , n ) : NEW_LINE INDENT return max ( maxSum1 ( arr , n ) , maxSum2 ( arr , n ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxSum ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Permutation Coefficient | Returns value of Permutation Coefficient P ( n , k ) ; Calculate value of Permutation Coefficient in bottom up manner ; Base cases ; Calculate value using previously stored values ; This step is important as P ( i , j ) = 0 for j > i ; Driver Code","code":"def permutationCoeff ( n , k ) : NEW_LINE INDENT P = [ [ 0 for i in range ( k + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT P [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT P [ i ] [ j ] = P [ i - 1 ] [ j ] + ( j * P [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT if ( j < k ) : NEW_LINE INDENT P [ i ] [ j + 1 ] = 0 NEW_LINE DEDENT DEDENT DEDENT return P [ n ] [ k ] NEW_LINE DEDENT n = 10 NEW_LINE k = 2 NEW_LINE print ( \" Value \u2581 fo \u2581 P ( \" , n , \" , \u2581 \" , k , \" ) \u2581 is \u2581 \" , permutationCoeff ( n , k ) , sep = \" \" ) NEW_LINE"} {"text":"Permutation Coefficient | Returns value of Permutation Coefficient P ( n , k ) ; base case ; Calculate value factorials up to n ; P ( n , k ) = n ! \/ ( n - k ) ! ; Driver Code","code":"def permutationCoeff ( n , k ) : NEW_LINE INDENT fact = [ 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 ] = i * fact [ i - 1 ] NEW_LINE DEDENT return int ( fact [ n ] \/ fact [ n - k ] ) NEW_LINE DEDENT n = 10 NEW_LINE k = 2 NEW_LINE print ( \" Value \u2581 of \u2581 P ( \" , n , \" , \u2581 \" , k , \" ) \u2581 is \u2581 \" , permutationCoeff ( n , k ) , sep = \" \" ) NEW_LINE"} {"text":"Dynamic Programming | Returns true if there is a subset of set [ ] with sun equal to given sum ; Base Cases ; If last element is greater than sum , then ignore it ; else , check if sum can be obtained by any of the following ( a ) including the last element ( b ) excluding the last element ; Driver code","code":"def isSubsetSum ( set , n , sum ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( set [ n - 1 ] > sum ) : NEW_LINE INDENT return isSubsetSum ( set , n - 1 , sum ) NEW_LINE DEDENT return isSubsetSum ( set , n - 1 , sum ) or isSubsetSum ( set , n - 1 , sum - set [ n - 1 ] ) NEW_LINE DEDENT set = [ 3 , 34 , 4 , 12 , 5 , 2 ] NEW_LINE sum = 9 NEW_LINE n = len ( set ) NEW_LINE if ( isSubsetSum ( set , n , sum ) == True ) : NEW_LINE INDENT print ( \" Found \u2581 a \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Count of cyclic permutations having XOR with other binary string as 0 | Implementation of Z - algorithm for linear time pattern searching ; Function to get the count of the cyclic permutations of b that given 0 when XORed with a ; concatenate b with b ; new b now contains all the cyclic permutations of old b as it 's sub-strings ; concatenate pattern with text ; Fill z array used in Z algorithm ; pattern occurs at index i since z value of i equals pattern length ; Driver code","code":"def compute_z ( s , z ) : NEW_LINE INDENT l = 0 NEW_LINE r = 0 NEW_LINE n = len ( s ) NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( i > r ) : NEW_LINE INDENT l = i NEW_LINE r = i NEW_LINE while ( r < n and s [ r - l ] == s [ r ] ) : NEW_LINE INDENT r += 1 NEW_LINE DEDENT z [ i ] = r - l NEW_LINE r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = i - l NEW_LINE if ( z [ k ] < r - i + 1 ) : NEW_LINE INDENT z [ i ] = z [ k ] NEW_LINE DEDENT else : NEW_LINE INDENT l = i NEW_LINE while ( r < n and s [ r - l ] == s [ r ] ) : NEW_LINE INDENT r += 1 NEW_LINE DEDENT z [ i ] = r - l NEW_LINE r -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def countPermutation ( a , b ) : NEW_LINE INDENT b = b + b NEW_LINE b = b [ 0 : len ( b ) - 1 ] NEW_LINE ans = 0 NEW_LINE s = a + \" $ \" + b NEW_LINE n = len ( s ) NEW_LINE z = [ 0 for i in range ( n ) ] NEW_LINE compute_z ( s , z ) NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( z [ i ] == len ( a ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = \"101\" NEW_LINE b = \"101\" NEW_LINE print ( countPermutation ( a , b ) ) NEW_LINE DEDENT"} {"text":"Lexicographically smallest K | Function to find lexicographically smallest subsequence of size K ; Length of string ; Stores the minimum subsequence ; Traverse the string S ; If the stack is empty ; Iterate till the current character is less than the the character at the top of stack ; If stack size is < K ; Push the current character into it ; Stores the resultant string ; Iterate until stack is empty ; Reverse the string ; Print the string ; Driver Code","code":"def smallestSubsequence ( S , K ) : NEW_LINE INDENT N = len ( S ) NEW_LINE answer = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( len ( answer ) == 0 ) : NEW_LINE INDENT answer . append ( S [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT while ( len ( answer ) > 0 and ( S [ i ] < answer [ len ( answer ) - 1 ] ) and ( len ( answer ) - 1 + N - i >= K ) ) : NEW_LINE INDENT answer = answer [ : - 1 ] NEW_LINE DEDENT if ( len ( answer ) == 0 or len ( answer ) < K ) : NEW_LINE INDENT answer . append ( S [ i ] ) NEW_LINE DEDENT DEDENT DEDENT ret = [ ] NEW_LINE while ( len ( answer ) > 0 ) : NEW_LINE INDENT ret . append ( answer [ len ( answer ) - 1 ] ) NEW_LINE answer = answer [ : - 1 ] NEW_LINE DEDENT ret = ret [ : : - 1 ] NEW_LINE ret = ' ' . join ( ret ) NEW_LINE print ( ret ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" aabdaabc \" NEW_LINE K = 3 NEW_LINE smallestSubsequence ( S , K ) NEW_LINE DEDENT"} {"text":"Check if string is right to left diagonal or not | Python3 program to Check if the given is right to left diagonal or not ; Function to check if the given is right to left diagonal or not ; Iterate over string ; If character is not same as the first character then return false ; Driver Code ; Given String str ; Function Call","code":"from math import sqrt , floor , ceil NEW_LINE def is_rtol ( s ) : NEW_LINE INDENT tmp = floor ( sqrt ( len ( s ) ) ) - 1 NEW_LINE first = s [ tmp ] NEW_LINE for pos in range ( tmp , len ( s ) - 1 , tmp ) : NEW_LINE INDENT if ( s [ pos ] != first ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" abcxabxcaxbcxabc \" NEW_LINE if ( is_rtol ( str ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Split a given string into substrings of length K with equal sum of ASCII values | Function for checking string ; Check if the string can be split into substrings of K length only ; Compute the sum of first substring of length K ; Compute the sum of remaining substrings ; Check if sum is equal to that of the first substring ; Since all sums are not equal , return False ; All sums are equal , Return true ; All substrings cannot be of size K ; Driver code","code":"def check ( str , K ) : NEW_LINE INDENT if ( len ( str ) % K == 0 ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT sum += ord ( str [ i ] ) ; NEW_LINE DEDENT for j in range ( K , len ( str ) , K ) : NEW_LINE INDENT s_comp = 0 ; NEW_LINE for p in range ( j , j + K ) : NEW_LINE INDENT s_comp += ord ( str [ p ] ) ; NEW_LINE DEDENT if ( s_comp != sum ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT K = 3 ; NEW_LINE str = \" abdcbbdba \" ; NEW_LINE if ( check ( str , K ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} {"text":"Maximize count of 0 s in left and 1 s in right substring by splitting given Binary string | Function to maximize the sum of the count of zeros and ones in the left and right substring ; Count the total numbers of ones in str ; To store the count of zeros and ones while traversing string ; Iterate the given and update the maximum sum ; Update the maximum Sum ; Driver Code ; Given binary string ; Function call","code":"def maxSum ( str ) : NEW_LINE INDENT maximumSum = 0 NEW_LINE totalOnes = 0 NEW_LINE for i in str : NEW_LINE INDENT if i == '1' : NEW_LINE INDENT totalOnes += 1 NEW_LINE DEDENT DEDENT zero = 0 NEW_LINE ones = 0 NEW_LINE i = 0 NEW_LINE while i < len ( str ) : NEW_LINE INDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT maximumSum = max ( maximumSum , zero + ( totalOnes - ones ) ) NEW_LINE i += 1 NEW_LINE DEDENT return maximumSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \"011101\" NEW_LINE print ( maxSum ( str ) ) NEW_LINE DEDENT"} {"text":"Longest substring such that no three consecutive characters are same | Function to return the length of the longest substring such that no three consecutive characters are same ; If the length of the given string is less than 3 ; Initialize temporary and final ans to 2 as this is the minimum length of substring when length of the given string is greater than 2 ; Traverse the string from the third character to the last ; If no three consecutive characters are same then increment temporary count ; Else update the final ans and reset the temporary count ; Driver code","code":"def maxLenSubStr ( s ) : NEW_LINE INDENT if ( len ( s ) < 3 ) : NEW_LINE INDENT return len ( s ) NEW_LINE DEDENT temp = 2 NEW_LINE ans = 2 NEW_LINE for i in range ( 2 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != s [ i - 1 ] or s [ i ] != s [ i - 2 ] ) : NEW_LINE INDENT temp += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( temp , ans ) NEW_LINE temp = 2 NEW_LINE DEDENT DEDENT ans = max ( temp , ans ) NEW_LINE return ans NEW_LINE DEDENT s = \" baaabbabbb \" NEW_LINE print ( maxLenSubStr ( s ) ) NEW_LINE"} {"text":"Number of ways to remove a sub | Function to return the number of ways of removing a sub - string from s such that all the remaining characters are same ; To store the count of prefix and suffix ; Loop to count prefix ; Loop to count suffix ; First and last characters of the string are same ; Otherwise ; Driver Code","code":"def no_of_ways ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE count_left = 0 NEW_LINE count_right = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( s [ i ] == s [ 0 ] ) : NEW_LINE INDENT count_left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == s [ n - 1 ] ) : NEW_LINE INDENT count_right += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( s [ 0 ] == s [ n - 1 ] ) : NEW_LINE INDENT return ( ( count_left + 1 ) * ( count_right + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( count_left + count_right + 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" geeksforgeeks \" NEW_LINE print ( no_of_ways ( s ) ) NEW_LINE DEDENT"} {"text":"Count number of indices such that s [ i ] = s [ i + 1 ] : Range queries | Function to create prefix array ; Function to return the result of the query ; Driver Code ; Query 1 ; Query 2","code":"def preCompute ( n , s , pref ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] NEW_LINE if s [ i - 1 ] == s [ i ] : NEW_LINE INDENT pref [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def query ( pref , l , r ) : NEW_LINE INDENT return pref [ r ] - pref [ l ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \" ggggggg \" NEW_LINE n = len ( s ) NEW_LINE pref = [ 0 ] * n NEW_LINE preCompute ( n , s , pref ) NEW_LINE l = 1 NEW_LINE r = 2 NEW_LINE print ( query ( pref , l , r ) ) NEW_LINE l = 1 NEW_LINE r = 5 NEW_LINE print ( query ( pref , l , r ) ) NEW_LINE DEDENT"} {"text":"Find the direction from given string | Function to find the final direction ; if count is positive that implies resultant is clockwise direction ; if count is negative that implies resultant is anti - clockwise direction ; Driver code","code":"def findDirection ( s ) : NEW_LINE INDENT count = 0 NEW_LINE d = \" \" NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' L ' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( s [ i ] == ' R ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT if ( count > 0 ) : NEW_LINE INDENT if ( count % 4 == 0 ) : NEW_LINE INDENT d = \" N \" NEW_LINE DEDENT elif ( count % 4 == 10 ) : NEW_LINE INDENT d = \" E \" NEW_LINE DEDENT elif ( count % 4 == 2 ) : NEW_LINE INDENT d = \" S \" NEW_LINE DEDENT elif ( count % 4 == 3 ) : NEW_LINE INDENT d = \" W \" NEW_LINE DEDENT DEDENT if ( count < 0 ) : NEW_LINE INDENT count *= - 1 NEW_LINE if ( count % 4 == 0 ) : NEW_LINE INDENT d = \" N \" NEW_LINE DEDENT elif ( count % 4 == 1 ) : NEW_LINE INDENT d = \" W \" NEW_LINE DEDENT elif ( count % 4 == 2 ) : NEW_LINE INDENT d = \" S \" NEW_LINE DEDENT elif ( count % 4 == 3 ) : NEW_LINE INDENT d = \" E \" NEW_LINE DEDENT DEDENT return d NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" LLRLRRL \" NEW_LINE print ( findDirection ( s ) ) NEW_LINE s = \" LL \" NEW_LINE print ( findDirection ( s ) ) NEW_LINE DEDENT"} {"text":"Check if lowercase and uppercase characters are in same order | Function to check if both the case follow the same order ; Traverse the string ; Store both lowercase and uppercase in two different strings ; transfor lowerStr to uppercase ; Driver Code","code":"def isCheck ( str ) : NEW_LINE INDENT length = len ( str ) NEW_LINE lowerStr , upperStr = \" \" , \" \" NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( ord ( str [ i ] ) >= 65 and ord ( str [ i ] ) <= 91 ) : NEW_LINE INDENT upperStr = upperStr + str [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT lowerStr = lowerStr + str [ i ] NEW_LINE DEDENT DEDENT transformStr = lowerStr . upper ( ) NEW_LINE return transformStr == upperStr NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeGkEEsKS \" NEW_LINE if isCheck ( str ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Print all paths of the Binary Tree with maximum element in each path greater than or equal to K | A Binary Tree node ; A recursive function to print the paths whose maximum element is greater than or equal to K . ; If the current node value is greater than or equal to k , then all the subtrees following that node will get printed , flag = 1 indicates to print the required path ; If the leaf node is encountered , then the path is printed if the size of the path vector is greater than 0 ; Append the node to the path vector ; Recur left and right subtrees ; Backtracking to return the vector and print the path if the flag is 1 ; Function to initialize the variables and call the utility function to print the paths with maximum values greater than or equal to K ; Initialize flag ; ans is used to check empty condition ; Call function that print path ; If the path doesn 't exist ; Driver Code ; Constructing the following tree : 10 \/ \\ 5 8 \/ \\ \/ \\ 29 2 1 98 \/ \\ 20 50","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def findPathUtil ( root : Node , k : int , path : list , flag : int ) : NEW_LINE INDENT global ans NEW_LINE if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if root . data >= k : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT if flag : NEW_LINE INDENT ans = 1 NEW_LINE print ( \" ( \" , end = \" \" ) NEW_LINE for i in range ( len ( path ) ) : NEW_LINE INDENT print ( path [ i ] , end = \" , \u2581 \" ) NEW_LINE DEDENT print ( root . data , end = \" ) , \u2581 \" ) NEW_LINE DEDENT return NEW_LINE DEDENT path . append ( root . data ) NEW_LINE findPathUtil ( root . left , k , path , flag ) NEW_LINE findPathUtil ( root . right , k , path , flag ) NEW_LINE path . pop ( ) NEW_LINE DEDENT def findPath ( root : Node , k : int ) : NEW_LINE INDENT global ans NEW_LINE flag = 0 NEW_LINE ans = 0 NEW_LINE v = [ ] NEW_LINE findPathUtil ( root , k , v , flag ) NEW_LINE if ans == 0 : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT ans = 0 NEW_LINE k = 25 NEW_LINE root = Node ( 10 ) NEW_LINE root . left = Node ( 5 ) NEW_LINE root . right = Node ( 8 ) NEW_LINE root . left . left = Node ( 29 ) NEW_LINE root . left . right = Node ( 2 ) NEW_LINE root . right . right = Node ( 98 ) NEW_LINE root . right . left = Node ( 1 ) NEW_LINE root . right . right . right = Node ( 50 ) NEW_LINE root . left . left . left = Node ( 20 ) NEW_LINE findPath ( root , k ) NEW_LINE DEDENT"} {"text":"Tridecagonal Number | Function to find N - th tridecagonal number ; Formula to calculate nth tridecagonal number ; Driver Code","code":"def Tridecagonal_num ( n ) : NEW_LINE INDENT return ( 11 * n * n - 9 * n ) \/ 2 NEW_LINE DEDENT n = 3 NEW_LINE print ( int ( Tridecagonal_num ( n ) ) ) NEW_LINE n = 10 NEW_LINE print ( int ( Tridecagonal_num ( n ) ) ) NEW_LINE"} {"text":"Number of N digit integers with weight W | Function to find total possible numbers with n digits and weight w ; When Weight of an integer is Positive ; Subtract the weight from 9 ; When weight of an integer is negative ; add the weight to 10 to make it positive ; number of digits in an integer and w as weight ; print the total possible numbers with n digits and weight w","code":"def findNumbers ( n , w ) : NEW_LINE INDENT x = 0 ; NEW_LINE sum = 0 ; NEW_LINE if ( w >= 0 and w <= 8 ) : NEW_LINE INDENT x = 9 - w ; NEW_LINE DEDENT elif ( w >= - 9 and w <= - 1 ) : NEW_LINE INDENT x = 10 + w ; NEW_LINE DEDENT sum = pow ( 10 , n - 2 ) ; NEW_LINE sum = ( x * sum ) ; NEW_LINE return sum ; NEW_LINE DEDENT n = 3 ; NEW_LINE w = 4 ; NEW_LINE print ( findNumbers ( n , w ) ) ; NEW_LINE"} {"text":"Maximum height of triangular arrangement of array values | Python program to find the maximum height of Pyramidal Arrangement of array values ; Just checking whether ith level is possible or not if possible then we must have atleast ( i * ( i + 1 ) ) \/ 2 elements in the array ; updating the result value each time ; otherwise we have exceeded n value ; Driver Code","code":"def MaximumHeight ( a , n ) : NEW_LINE INDENT result = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT y = ( i * ( i + 1 ) ) \/ 2 NEW_LINE if ( y < n ) : NEW_LINE INDENT result = i NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 40 , 100 , 20 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE print ( MaximumHeight ( arr , n ) ) NEW_LINE"} {"text":"k | Python3 code to find k - th element in the Odd - Even sequence . ; insert all the odd numbers from 1 to n . ; insert all the even numbers from 1 to n . ; Driver code","code":"def findK ( n , k ) : NEW_LINE INDENT a = list ( ) NEW_LINE i = 1 NEW_LINE while i < n : NEW_LINE INDENT a . append ( i ) NEW_LINE i = i + 2 NEW_LINE DEDENT i = 2 NEW_LINE while i < n : NEW_LINE INDENT a . append ( i ) NEW_LINE i = i + 2 NEW_LINE DEDENT return ( a [ k - 1 ] ) NEW_LINE DEDENT n = 10 NEW_LINE k = 3 NEW_LINE print ( findK ( n , k ) ) NEW_LINE"} {"text":"One line function for factorial of a number | Python3 program to find factorial of given number ; single line to find factorial ; Driver Code","code":"def factorial ( n ) : NEW_LINE INDENT return 1 if ( n == 1 or n == 0 ) else n * factorial ( n - 1 ) ; NEW_LINE DEDENT num = 5 ; NEW_LINE print ( \" Factorial \u2581 of \" , num , \" is \" , factorial ( num ) ) ; NEW_LINE"} {"text":"Pell Number | calculate nth pell number ; driver function","code":"def pell ( n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT a = 1 NEW_LINE b = 2 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT c = 2 * b + a NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT return b NEW_LINE DEDENT n = 4 NEW_LINE print ( pell ( n ) ) NEW_LINE"} {"text":"An efficient way to check whether n | Returns true if n - th Fibonacci number is multiple of 10. ; Driver Code","code":"def isMultipleOf10 ( n ) : NEW_LINE INDENT return ( n % 15 == 0 ) NEW_LINE DEDENT n = 30 NEW_LINE if ( isMultipleOf10 ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT"} {"text":"Find politeness of a number | A function to count all odd prime factors of a given number n ; Eliminate all even prime factor of number of n ; n must be odd at this point , so iterate for only odd numbers till sqrt ( n ) ; if i divides n , then start counting of Odd divisors ; If n odd prime still remains then count it ; Driver program to test above function","code":"def countOddPrimeFactors ( n ) : NEW_LINE INDENT result = 1 ; NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n \/= 2 NEW_LINE DEDENT i = 3 NEW_LINE while i * i <= n : NEW_LINE INDENT divCount = 0 NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n \/= i NEW_LINE divCount = divCount + 1 NEW_LINE DEDENT result = result * divCount + 1 NEW_LINE i = i + 2 NEW_LINE DEDENT if ( n > 2 ) : NEW_LINE INDENT result = result * 2 NEW_LINE DEDENT return result NEW_LINE DEDENT def politness ( n ) : NEW_LINE INDENT return countOddPrimeFactors ( n ) - 1 ; NEW_LINE DEDENT n = 90 NEW_LINE print \" Politness \u2581 of \u2581 \" , n , \" \u2581 = \u2581 \" , politness ( n ) NEW_LINE n = 15 NEW_LINE print \" Politness \u2581 of \u2581 \" , n , \" \u2581 = \u2581 \" , politness ( n ) NEW_LINE"} {"text":"Nearest prime less than given number n | Python3 program to find the nearest prime to n . ; array to store all primes less than 10 ^ 6 ; Utility function of Sieve of Sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x ; This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; eliminate indexes which does not produce primes ; Since 2 is a prime number ; Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; modified binary search to find nearest prime less than N ; base condition is , if we are reaching at left corner or right corner of primes [ ] array then return that corner element because before or after that we don 't have any prime number in primes array ; now if n is itself a prime so it will be present in primes array and here we have to find nearest prime less than n so we will return primes [ mid - 1 ] ; now if primes [ mid ] < n and primes [ mid + 1 ] > n that means we reached at nearest prime ; Driver Code","code":"import math NEW_LINE MAX = 10000 ; NEW_LINE primes = [ ] ; NEW_LINE def Sieve ( ) : NEW_LINE INDENT n = MAX ; NEW_LINE nNew = int ( math . sqrt ( n ) ) ; NEW_LINE marked = [ 0 ] * ( int ( n \/ 2 + 500 ) ) ; NEW_LINE for i in range ( 1 , int ( ( nNew - 1 ) \/ 2 ) + 1 ) : NEW_LINE INDENT for j in range ( ( ( i * ( i + 1 ) ) << 1 ) , ( int ( n \/ 2 ) + 1 ) , ( 2 * i + 1 ) ) : NEW_LINE INDENT marked [ j ] = 1 ; NEW_LINE DEDENT DEDENT primes . append ( 2 ) ; NEW_LINE for i in range ( 1 , int ( n \/ 2 ) + 1 ) : NEW_LINE INDENT if ( marked [ i ] == 0 ) : NEW_LINE INDENT primes . append ( 2 * i + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT def binarySearch ( left , right , n ) : NEW_LINE INDENT if ( left <= right ) : NEW_LINE INDENT mid = int ( ( left + right ) \/ 2 ) ; NEW_LINE if ( mid == 0 or mid == len ( primes ) - 1 ) : NEW_LINE INDENT return primes [ mid ] ; NEW_LINE DEDENT if ( primes [ mid ] == n ) : NEW_LINE INDENT return primes [ mid - 1 ] ; NEW_LINE DEDENT if ( primes [ mid ] < n and primes [ mid + 1 ] > n ) : NEW_LINE INDENT return primes [ mid ] ; NEW_LINE DEDENT if ( n < primes [ mid ] ) : NEW_LINE INDENT return binarySearch ( left , mid - 1 , n ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( mid + 1 , right , n ) ; NEW_LINE DEDENT DEDENT return 0 ; NEW_LINE DEDENT Sieve ( ) ; NEW_LINE n = 17 ; NEW_LINE print ( binarySearch ( 0 , len ( primes ) - 1 , n ) ) ; NEW_LINE"} {"text":"Program for factorial of a number | Function to find factorial of given number ; Driver Code","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 num = 5 ; NEW_LINE print ( \" Factorial \u2581 of \" , num , \" is \" , factorial ( num ) ) NEW_LINE"} {"text":"Turn off the rightmost set bit | Set 2 | Unsets the rightmost set bit of n and returns the result ; Driver Code","code":"def FlipBits ( n ) : NEW_LINE INDENT n -= ( n & ( - n ) ) ; NEW_LINE return n ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 ; NEW_LINE print ( \" The \u2581 number \u2581 after \u2581 unsetting \u2581 the \" , end = \" \" ) ; NEW_LINE print ( \" \u2581 rightmost \u2581 set \u2581 bit : \u2581 \" , FlipBits ( N ) ) ; NEW_LINE DEDENT"} {"text":"Maximum value of XOR among all triplets of an array | function to count maximum XOR value for a triplet ; set is used to avoid repetitions ; store all possible unique XOR value of pairs ; store maximum value ; Driver code","code":"def Maximum_xor_Triplet ( n , a ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT s . add ( a [ i ] ^ a [ j ] ) NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in s : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT ans = max ( ans , i ^ a [ j ] ) NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 3 , 8 , 15 ] NEW_LINE n = len ( a ) NEW_LINE Maximum_xor_Triplet ( n , a ) NEW_LINE DEDENT"} {"text":"Find missing elements of a range | Python library for binary search ; Print all elements of range [ low , high ] that are not present in arr [ 0. . n - 1 ] ; Do binary search for ' low ' in sorted array and find index of first element which either equal to or greater than low . ; Start from the found index and linearly search every range element x after this index in arr [ ] ; If x doesn 't math with current element print it ; If x matches , move to next element in arr [ ] ; Move to next element in range [ low , high ] ; Print range elements thar are greater than the last element of sorted array . ; Driver code","code":"from bisect import bisect_left NEW_LINE def printMissing ( arr , n , low , high ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ptr = bisect_left ( arr , low ) NEW_LINE index = ptr NEW_LINE i = index NEW_LINE x = low NEW_LINE while ( i < n and x <= high ) : NEW_LINE INDENT if ( arr [ i ] != x ) : NEW_LINE INDENT print ( x , end = \" \u2581 \" ) NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT x = x + 1 NEW_LINE DEDENT while ( x <= high ) : NEW_LINE INDENT print ( x , end = \" \u2581 \" ) NEW_LINE x = x + 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE low = 1 NEW_LINE high = 10 NEW_LINE printMissing ( arr , n , low , high ) ; NEW_LINE"} {"text":"Find missing elements of a range | Print all elements of range [ low , high ] that are not present in arr [ 0. . n - 1 ] ; Create boolean list of size high - low + 1 , each index i representing wether ( i + low ) th element found or not . ; if ith element of arr is in range low to high then mark corresponding index as true in array ; Traverse through the range and print all elements whose value is false ; Driver Code","code":"def printMissing ( arr , n , low , high ) : NEW_LINE INDENT points_of_range = [ False ] * ( high - low + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( low <= arr [ i ] and arr [ i ] <= high ) : NEW_LINE INDENT points_of_range [ arr [ i ] - low ] = True NEW_LINE DEDENT DEDENT for x in range ( high - low + 1 ) : NEW_LINE INDENT if ( points_of_range [ x ] == False ) : NEW_LINE INDENT print ( low + x , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 3 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE low , high = 1 , 10 NEW_LINE printMissing ( arr , n , low , high ) NEW_LINE"} {"text":"Find missing elements of a range | Print all elements of range [ low , high ] that are not present in arr [ 0. . n - 1 ] ; Insert all elements of arr [ ] in set ; Traverse through the range and print all missing elements ; Driver Code","code":"def printMissing ( arr , n , low , high ) : NEW_LINE INDENT s = set ( arr ) NEW_LINE for x in range ( low , high + 1 ) : NEW_LINE INDENT if x not in s : NEW_LINE INDENT print ( x , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 3 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE low , high = 1 , 10 NEW_LINE printMissing ( arr , n , low , high ) NEW_LINE"} {"text":"k | Returns k - th missing element . It returns - 1 if no k is more than number of missing elements . ; insert all elements of given sequence b [ ] . ; Traverse through increasing sequence and keep track of count of missing numbers . ; Driver code","code":"def find ( a , b , k , n1 , n2 ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n2 ) : NEW_LINE INDENT s . add ( b [ i ] ) NEW_LINE DEDENT missing = 0 NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT if a [ i ] not in s : NEW_LINE INDENT missing += 1 NEW_LINE DEDENT if missing == k : NEW_LINE INDENT return a [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT a = [ 0 , 2 , 4 , 6 , 8 , 10 , 12 , 14 , 15 ] NEW_LINE b = [ 4 , 10 , 6 , 8 , 12 ] NEW_LINE n1 = len ( a ) NEW_LINE n2 = len ( b ) NEW_LINE k = 3 NEW_LINE print ( find ( a , b , k , n1 , n2 ) ) NEW_LINE"} {"text":"Minimize steps to form string S from any random string of length K using a fixed length subsequences | ''Function to find the minimum number of string required to generate the original string ; '' Stores the frequency of each character of String S ; '' Stores the frequency of each character of String S ; '' Count unique characters in S ; '' If unique characters is greater then N, then return -1 ; '' Otherwise ; '' Perform Binary Search ; '' Find the value of mid ; '' Iterate over the range [0, 26] ; '' If the amount[i] is greater than 0 ; '' Update the ranges ; '' Find the resultant string ; Generate the subsequence ; ' ' \u2581 If \u2581 the \u2581 length \u2581 of \u2581 resultant \u2581 \u2581 string \u2581 is \u2581 less \u2581 than \u2581 N \u2581 than \u2581 \u2581 add \u2581 a \u2581 character \u2581 ' a ' ; '' Print the string ; ''Driver code","code":"def findString ( S , N ) : NEW_LINE INDENT amounts = [ 0 ] * 26 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT amounts [ ord ( S [ i ] ) - 97 ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if amounts [ i ] > 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if count > N : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = \" \" NEW_LINE high = 100001 NEW_LINE low = 0 NEW_LINE while ( high - low ) > 1 : NEW_LINE INDENT total = 0 NEW_LINE mid = ( high + low ) \/\/ 2 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if amounts [ i ] > 0 : NEW_LINE INDENT total += ( amounts [ i ] - 1 ) \/\/ mid + 1 NEW_LINE DEDENT DEDENT if total <= N : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid NEW_LINE DEDENT DEDENT print ( high , end = \" \u2581 \" ) NEW_LINE total = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if amounts [ i ] > 0 : NEW_LINE INDENT total += ( amounts [ i ] - 1 ) \/\/ high + 1 NEW_LINE for j in range ( ( amounts [ i ] - 1 ) \/\/ high + 1 ) : NEW_LINE INDENT ans += chr ( i + 97 ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( total , N ) : NEW_LINE INDENT ans += ' a ' NEW_LINE DEDENT ans = ans [ : : - 1 ] NEW_LINE print ( ans ) NEW_LINE DEDENT DEDENT S = \" toffee \" NEW_LINE K = 4 NEW_LINE findString ( S , K ) NEW_LINE"} {"text":"Find the first repeating element in an array of integers | This function prints the first repeating element in arr [ ] ; Initialize index of first repeating element ; Creates an empty hashset ; Traverse the input array from right to left ; If element is already in hash set , update Min ; Else add element to hash set ; Print the result ; Driver Code","code":"def printFirstRepeating ( arr , n ) : NEW_LINE INDENT Min = - 1 NEW_LINE myset = dict ( ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] in myset . keys ( ) : NEW_LINE INDENT Min = i NEW_LINE DEDENT else : NEW_LINE INDENT myset [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT if ( Min != - 1 ) : NEW_LINE INDENT print ( \" The \u2581 first \u2581 repeating \u2581 element \u2581 is \" , arr [ Min ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" There \u2581 are \u2581 no \u2581 repeating \u2581 elements \" ) NEW_LINE DEDENT DEDENT arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printFirstRepeating ( arr , n ) NEW_LINE"} {"text":"Find the first repeating element in an array of integers | This function prints the first repeating element in arr [ ] ; This will set k = 1 , if any repeating element found ; max = maximum from ( all elements & n ) ; Array a is for storing 1 st time occurence of element initialized by 0 ; Store 1 in array b if element is duplicate initialized by 0 ; Duplicate element found ; Storing 1 st occurence of arr [ i ] ; Trace array a & find repeating element with min index ; Driver code","code":"def printFirstRepeating ( arr , n ) : NEW_LINE INDENT k = 0 NEW_LINE max = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT a = [ 0 for i in range ( max + 1 ) ] NEW_LINE b = [ 0 for i in range ( max + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ arr [ i ] ] ) : NEW_LINE INDENT b [ arr [ i ] ] = 1 NEW_LINE k = 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT a [ arr [ i ] ] = i NEW_LINE DEDENT DEDENT if ( k == 0 ) : NEW_LINE INDENT print ( \" No \u2581 repeating \u2581 element \u2581 found \" ) NEW_LINE DEDENT else : NEW_LINE INDENT min = max + 1 NEW_LINE for i in range ( max + 1 ) : NEW_LINE INDENT if ( a [ i ] and ( min > ( a [ i ] ) ) and b [ i ] ) : NEW_LINE INDENT min = a [ i ] NEW_LINE DEDENT DEDENT print ( arr [ min ] ) NEW_LINE DEDENT DEDENT arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printFirstRepeating ( arr , n ) NEW_LINE"} {"text":"k | Returns k - th distinct element in arr . ; Check if current element is present somewhere else . ; If element is unique ; Driver Code","code":"def printKDistinct ( arr , n , k ) : NEW_LINE INDENT dist_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = 0 NEW_LINE while j < n : NEW_LINE INDENT if ( i != j and arr [ j ] == arr [ i ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == n ) : NEW_LINE INDENT dist_count += 1 NEW_LINE DEDENT if ( dist_count == k ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT ar = [ 1 , 2 , 1 , 3 , 4 , 2 ] NEW_LINE n = len ( ar ) NEW_LINE k = 2 NEW_LINE print ( printKDistinct ( ar , n , k ) ) NEW_LINE"} {"text":"Count subarrays having an equal count of 0 s and 1 s segregated | ''Function to count subarrays having equal count of 0s and 1s with all 0s and all 1s grouped together ; '' Stores the count ; '' Initialize cur with first element ; '' If the next element is same as the current element ; '' Increment count ; '' Update curr ; '' Iterate over the array count ; '' Consider the minimum ; ; ''Given arr[] ; ''Function Call","code":"def countSubarrays ( A ) : NEW_LINE INDENT res = 0 NEW_LINE curr , cnt = A [ 0 ] , [ 1 ] NEW_LINE for c in A [ 1 : ] : NEW_LINE INDENT if c == curr : NEW_LINE INDENT cnt [ - 1 ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT curr = c NEW_LINE DEDENT cnt . append ( 1 ) NEW_LINE DEDENT for i in range ( 1 , len ( cnt ) ) : NEW_LINE INDENT res += min ( cnt [ i - 1 ] , cnt [ i ] ) NEW_LINE DEDENT print ( res - 1 ) NEW_LINE DEDENT \/ * Driver code * \/ NEW_LINE A = [ 1 , 1 , 0 , 0 , 1 , 0 ] NEW_LINE countSubarrays ( A ) NEW_LINE"} {"text":"Check if a Binary Tree is an Even | ''Tree node ; ''Function to return new tree node ; ''Function to check if the tree is even-odd tree ; '' Stores nodes of each level ; '' Store the current level of the binary tree ; '' Traverse until the queue is empty ; '' Stores the number of nodes present in the current level ; '' Check if the level is even or odd ; '' Add the nodes of the next level into the queue ; '' Increment the level count ; ''Driver code ; '' Construct a Binary Tree ; '' Check if the binary tree is even-odd tree or not","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = data NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp NEW_LINE DEDENT def isEvenOddBinaryTree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE level = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT size = len ( q ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( level % 2 == 0 ) : NEW_LINE INDENT if ( node . val % 2 == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT elif ( level % 2 == 1 ) : NEW_LINE INDENT if ( node . val % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT DEDENT level += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT root = None NEW_LINE root = newNode ( 2 ) NEW_LINE root . left = newNode ( 3 ) NEW_LINE root . right = newNode ( 9 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 10 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE if ( isEvenOddBinaryTree ( root ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} {"text":"Maximize minimum distance between repetitions from any permutation of the given Array | Python3 program to implement the above approach ; Size of the array ; Stores the frequency of array elements ; Find the highest frequency in the array ; Increase count of max frequent element ; If no repetition is present ; Find the maximum distance ; Return the max distance ; Driver Code","code":"import sys NEW_LINE def findMaxLen ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE freq = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT maxFreqElement = - sys . maxsize - 1 NEW_LINE maxFreqCount = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( freq [ i ] > maxFreqElement ) : NEW_LINE INDENT maxFreqElement = freq [ i ] NEW_LINE maxFreqCount = 1 NEW_LINE DEDENT elif ( freq [ i ] == maxFreqElement ) : NEW_LINE INDENT maxFreqCount += 1 NEW_LINE DEDENT DEDENT if ( maxFreqElement == 1 ) : NEW_LINE INDENT ans = 0 NEW_LINE DEDENT else : NEW_LINE INDENT ans = ( ( n - maxFreqCount ) \/\/ ( maxFreqElement - 1 ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT a = [ 1 , 2 , 1 , 2 ] NEW_LINE print ( findMaxLen ( a ) ) NEW_LINE"} {"text":"Queries to evaluate the given equation in a range [ L , R ] | Python3 program to implement the above approach ; Function to obtain the middle index of the range ; Recursive function to get the sum of values in the given range from the array . The following are parameters for this function . st . Pointer to segment tree node . Index of current node in the segment tree ss & se . Starting and ending indexes of the segment represented by current node , i . e . , st [ node ] l & r . Starting and ending indexes of range query ; If the segment of this node lies completely within the given range ; Return maximum in the segment ; If the segment of this node lies outside the given range ; If segment of this node lies partially in the given range ; Function to return the maximum in the range from [ l , r ] ; Check for erroneous input values ; Function to conSegment Tree for the subarray [ ss . . se ] ; For a single element ; Otherwise ; Recur for left subtree ; Recur for right subtree ; Function to conSegment Tree from the given array ; Height of Segment Tree ; Maximum size of Segment Tree ; Allocate memory ; Fill the allocated memory ; Return the constructed Segment Tree ; Driver Code ; Build the Segment Tree from the given array","code":"import math NEW_LINE def getMid ( s , e ) : NEW_LINE INDENT return ( s + ( e - s ) \/\/ 2 ) NEW_LINE DEDENT def MaxUtil ( st , ss , se , l , r , node ) : NEW_LINE INDENT if ( l <= ss and r >= se ) : NEW_LINE INDENT return st [ node ] NEW_LINE DEDENT if ( se < l or ss > r ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE return max ( MaxUtil ( st , ss , mid , l , r , 2 * node + 1 ) , MaxUtil ( st , mid + 1 , se , l , r , 2 * node + 2 ) ) NEW_LINE DEDENT def getMax ( st , n , l , r ) : NEW_LINE INDENT if ( l < 0 or r > n - 1 or l > r ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return - 1 NEW_LINE DEDENT return MaxUtil ( st , 0 , n - 1 , l , r , 0 ) NEW_LINE DEDENT def constructSTUtil ( arr , ss , se , st , si ) : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT st [ si ] = arr [ ss ] NEW_LINE return arr [ ss ] NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE st [ si ] = max ( constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) , constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 2 ) ) NEW_LINE return st [ si ] NEW_LINE DEDENT def constructST ( arr , n ) : NEW_LINE INDENT x = ( int ) ( math . ceil ( math . log ( 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 = [ 5 , 2 , 3 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE st = constructST ( arr , n ) NEW_LINE Q = [ [ 1 , 3 ] , [ 0 , 2 ] ] NEW_LINE for i in range ( len ( Q ) ) : NEW_LINE INDENT Max = getMax ( st , n , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) NEW_LINE ok = 0 NEW_LINE for j in range ( 30 , - 1 , - 1 ) : NEW_LINE INDENT if ( ( Max & ( 1 << j ) ) != 0 ) : NEW_LINE INDENT ok = 1 NEW_LINE DEDENT if ( ok <= 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT Max |= ( 1 << j ) NEW_LINE DEDENT print ( Max , end = \" \u2581 \" ) NEW_LINE DEDENT"} {"text":"Find number of pairs in an array such that their XOR is 0 | Function to calculate the count ; Sorting the list using built in function ; Traversing through the elements ; Counting frequncy of each elements ; Adding the contribution of the frequency to the answer ; Driver Code ; Print the count","code":"def calculate ( a ) : NEW_LINE INDENT a . sort ( ) NEW_LINE count = 1 NEW_LINE answer = 0 NEW_LINE for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT if a [ i ] == a [ i - 1 ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT answer = answer + count * ( count - 1 ) \/\/ 2 NEW_LINE count = 1 NEW_LINE DEDENT DEDENT answer = answer + count * ( count - 1 ) \/\/ 2 NEW_LINE return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 2 , 1 , 2 , 4 ] NEW_LINE print ( calculate ( a ) ) NEW_LINE DEDENT"} {"text":"Find number of pairs in an array such that their XOR is 0 | Function to calculate the answer ; Finding the maximum of the array ; Creating frequency array With initial value 0 ; Traversing through the array ; Counting frequency ; Traversing through the frequency array ; Calculating answer ; Driver Code ; Function calling","code":"def calculate ( a ) : NEW_LINE INDENT maximum = max ( a ) NEW_LINE frequency = [ 0 for x in range ( maximum + 1 ) ] NEW_LINE for i in a : NEW_LINE INDENT frequency [ i ] += 1 NEW_LINE DEDENT answer = 0 NEW_LINE for i in frequency : NEW_LINE INDENT answer = answer + i * ( i - 1 ) \/\/ 2 NEW_LINE DEDENT return answer NEW_LINE DEDENT a = [ 1 , 2 , 1 , 2 , 4 ] NEW_LINE print ( calculate ( a ) ) NEW_LINE"} {"text":"Largest subarray with equal number of 0 s and 1 s | This function Prints the starting and ending indexes of the largest subarray with equal number of 0 s and 1 s . Also returns the size of such subarray . ; Pick a starting point as i ; Consider all subarrays starting from i ; If this is a 0 sum subarray , then compare it with maximum size subarray calculated so far ; Driver program to test above functions","code":"def findSubArray ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE maxsize = - 1 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT sum = - 1 if ( arr [ i ] == 0 ) else 1 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = sum + ( - 1 ) if ( arr [ j ] == 0 ) else sum + 1 NEW_LINE if ( sum == 0 and maxsize < j - i + 1 ) : NEW_LINE INDENT maxsize = j - i + 1 NEW_LINE startindex = i NEW_LINE DEDENT DEDENT DEDENT if ( maxsize == - 1 ) : NEW_LINE INDENT print ( \" No \u2581 such \u2581 subarray \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( startindex , \" to \" , startindex + maxsize - 1 ) ; NEW_LINE DEDENT return maxsize NEW_LINE DEDENT arr = [ 1 , 0 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE size = len ( arr ) NEW_LINE findSubArray ( arr , size ) NEW_LINE"} {"text":"Maximum element in a sorted and rotated array | Function to return the maximum element ; If there is only one element left ; Find mid ; Check if mid reaches 0 , it is greater than next element or not ; Check if mid itself is maximum element ; Decide whether we need to go to the left half or the right half ; Driver code","code":"def findMax ( arr , low , high ) : NEW_LINE INDENT if ( high == low ) : NEW_LINE INDENT return arr [ low ] NEW_LINE DEDENT mid = low + ( high - low ) \/\/ 2 NEW_LINE if ( mid == 0 and arr [ mid ] > arr [ mid + 1 ] ) : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if ( mid < high and arr [ mid + 1 ] < arr [ mid ] and mid > 0 and arr [ mid ] > arr [ mid - 1 ] ) : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if ( arr [ low ] > arr [ mid ] ) : NEW_LINE INDENT return findMax ( arr , low , mid - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return findMax ( arr , mid + 1 , high ) NEW_LINE DEDENT DEDENT arr = [ 6 , 5 , 4 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMax ( arr , 0 , n - 1 ) ) NEW_LINE"} {"text":"Ternary Search | Function to perform Ternary Search ; Find mid1 and mid2 ; Check if key is at any mid ; Since key is not present at mid , Check in which region it is present Then repeat the search operation in that region ; key lies between l and mid1 ; key lies between mid2 and r ; key lies between mid1 and mid2 ; key not found ; Get the list Sort the list if not sorted ; Starting index ; Length of list ; Key to be searched in the list ; Search the key using ternary search ; Print the result ; Key to be searched in the list ; Search the key using ternary search ; Print the result","code":"def ternarySearch ( l , r , key , ar ) : NEW_LINE INDENT while r >= l : NEW_LINE INDENT mid1 = l + ( r - l ) \/\/ 3 NEW_LINE mid2 = r - ( r - l ) \/\/ 3 NEW_LINE if key == ar [ mid1 ] : NEW_LINE INDENT return mid1 NEW_LINE DEDENT if key == mid2 : NEW_LINE INDENT return mid2 NEW_LINE DEDENT if key < ar [ mid1 ] : NEW_LINE INDENT r = mid1 - 1 NEW_LINE DEDENT elif key > ar [ mid2 ] : NEW_LINE INDENT l = mid2 + 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = mid1 + 1 NEW_LINE r = mid2 - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT ar = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE l = 0 NEW_LINE r = 9 NEW_LINE key = 5 NEW_LINE p = ternarySearch ( l , r , key , ar ) NEW_LINE print ( \" Index \u2581 of \" , key , \" is \" , p ) NEW_LINE key = 50 NEW_LINE p = ternarySearch ( l , r , key , ar ) NEW_LINE print ( \" Index \u2581 of \" , key , \" is \" , p ) NEW_LINE"} {"text":"Majority Element | Set | function to print the majorityNumber ; Driver Code","code":"def majorityNumber ( nums ) : NEW_LINE INDENT num_count = { } NEW_LINE for num in nums : NEW_LINE INDENT if num in num_count : NEW_LINE INDENT num_count [ num ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT num_count [ num ] = 1 NEW_LINE DEDENT DEDENT for num in num_count : NEW_LINE INDENT if num_count [ num ] > len ( nums ) \/ 2 : NEW_LINE INDENT return num NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT a = [ 2 , 2 , 1 , 1 , 1 , 2 , 2 ] NEW_LINE print majorityNumber ( a ) NEW_LINE"} {"text":"Search an element in a sorted and rotated array | Returns index of key in arr [ l . . h ] if key is present , otherwise returns - 1 ; If arr [ l ... mid ] is sorted ; As this subarray is sorted , we can quickly check if key lies in half or other half ; If key not lies in first half subarray , Divide other half into two subarrays , such that we can quickly check if key lies in other half ; If arr [ l . . mid ] is not sorted , then arr [ mid ... r ] must be sorted ; Driver program","code":"def search ( arr , l , h , key ) : NEW_LINE INDENT if l > h : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( l + h ) \/\/ 2 NEW_LINE if arr [ mid ] == key : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ l ] <= arr [ mid ] : NEW_LINE INDENT if key >= arr [ l ] and key <= arr [ mid ] : NEW_LINE INDENT return search ( arr , l , mid - 1 , key ) NEW_LINE DEDENT return search ( arr , mid + 1 , h , key ) NEW_LINE DEDENT if key >= arr [ mid ] and key <= arr [ h ] : NEW_LINE INDENT return search ( a , mid + 1 , h , key ) NEW_LINE DEDENT return search ( arr , l , mid - 1 , key ) NEW_LINE DEDENT arr = [ 4 , 5 , 6 , 7 , 8 , 9 , 1 , 2 , 3 ] NEW_LINE key = 6 NEW_LINE i = search ( arr , 0 , len ( arr ) - 1 , key ) NEW_LINE if i != - 1 : NEW_LINE INDENT print ( \" Index : \u2581 % \u2581 d \" % i ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Key \u2581 not \u2581 found \" ) NEW_LINE DEDENT"} {"text":"Find the minimum element in a sorted and rotated array | Python program to find minimum element in a sorted and rotated array ; This condition is needed to handle the case when array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum element . Consider the cases like [ 3 , 4 , 5 , 1 , 2 ] ; Check if mid itself is minimum element ; Decide whether we need to go to left half or right half ; Driver program to test above functions","code":"def findMin ( arr , low , high ) : NEW_LINE INDENT if high < low : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT if high == low : NEW_LINE INDENT return arr [ low ] NEW_LINE DEDENT mid = int ( ( low + high ) \/ 2 ) NEW_LINE if mid < high and arr [ mid + 1 ] < arr [ mid ] : NEW_LINE INDENT return arr [ mid + 1 ] NEW_LINE DEDENT if mid > low and arr [ mid ] < arr [ mid - 1 ] : NEW_LINE INDENT return arr [ mid ] NEW_LINE DEDENT if arr [ high ] > arr [ mid ] : NEW_LINE INDENT return findMin ( arr , low , mid - 1 ) NEW_LINE DEDENT return findMin ( arr , mid + 1 , high ) NEW_LINE DEDENT arr1 = [ 5 , 6 , 1 , 2 , 3 , 4 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr1 , 0 , n1 - 1 ) ) ) NEW_LINE arr2 = [ 1 , 2 , 3 , 4 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr2 , 0 , n2 - 1 ) ) ) NEW_LINE arr3 = [ 1 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr3 , 0 , n3 - 1 ) ) ) NEW_LINE arr4 = [ 1 , 2 ] NEW_LINE n4 = len ( arr4 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr4 , 0 , n4 - 1 ) ) ) NEW_LINE arr5 = [ 2 , 1 ] NEW_LINE n5 = len ( arr5 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr5 , 0 , n5 - 1 ) ) ) NEW_LINE arr6 = [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ] NEW_LINE n6 = len ( arr6 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr6 , 0 , n6 - 1 ) ) ) NEW_LINE arr7 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] NEW_LINE n7 = len ( arr7 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr7 , 0 , n7 - 1 ) ) ) NEW_LINE arr8 = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 1 ] NEW_LINE n8 = len ( arr8 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr8 , 0 , n8 - 1 ) ) ) NEW_LINE arr9 = [ 3 , 4 , 5 , 1 , 2 ] NEW_LINE n9 = len ( arr9 ) NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" + str ( findMin ( arr9 , 0 , n9 - 1 ) ) ) NEW_LINE"} {"text":"Find the minimum element in a sorted and rotated array | Function to find minimum element ; Driver code","code":"def findMin ( arr , low , high ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT mid = low + ( high - low ) \/\/ 2 ; NEW_LINE if ( arr [ mid ] == arr [ high ] ) : NEW_LINE INDENT high -= 1 ; NEW_LINE DEDENT elif ( arr [ mid ] > arr [ high ] ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid ; NEW_LINE DEDENT DEDENT return arr [ high ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 5 , 6 , 1 , 2 , 3 , 4 ] ; NEW_LINE n1 = len ( arr1 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr1 , 0 , n1 - 1 ) ) ; NEW_LINE arr2 = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n2 = len ( arr2 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr2 , 0 , n2 - 1 ) ) ; NEW_LINE arr3 = [ 1 ] ; NEW_LINE n3 = len ( arr3 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr3 , 0 , n3 - 1 ) ) ; NEW_LINE arr4 = [ 1 , 2 ] ; NEW_LINE n4 = len ( arr4 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr4 , 0 , n4 - 1 ) ) ; NEW_LINE arr5 = [ 2 , 1 ] ; NEW_LINE n5 = len ( arr5 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr5 , 0 , n5 - 1 ) ) ; NEW_LINE arr6 = [ 5 , 6 , 7 , 1 , 2 , 3 , 4 ] ; NEW_LINE n6 = len ( arr6 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr6 , 0 , n6 - 1 ) ) ; NEW_LINE arr7 = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ; NEW_LINE n7 = len ( arr7 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr7 , 0 , n7 - 1 ) ) ; NEW_LINE arr8 = [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 1 ] ; NEW_LINE n8 = len ( arr8 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr8 , 0 , n8 - 1 ) ) ; NEW_LINE arr9 = [ 3 , 4 , 5 , 1 , 2 ] ; NEW_LINE n9 = len ( arr9 ) ; NEW_LINE print ( \" The \u2581 minimum \u2581 element \u2581 is \u2581 \" , findMin ( arr9 , 0 , n9 - 1 ) ) ; NEW_LINE DEDENT"} {"text":"k | Python3 program to find k - th absolute difference between two elements ; returns number of pairs with absolute difference less than or equal to mid . ; Upper bound returns pointer to position of next higher number than a [ i ] + mid in a [ i . . n - 1 ] . We subtract ( a + i + 1 ) from this position to count ; Returns k - th absolute difference ; Sort array ; Minimum absolute difference ; Maximum absolute difference ; Do binary search for k - th absolute difference ; Driver code","code":"from bisect import bisect as upper_bound NEW_LINE def countPairs ( a , n , mid ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += upper_bound ( a , a [ i ] + mid ) NEW_LINE DEDENT return res NEW_LINE DEDENT def kthDiff ( a , n , k ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE low = a [ 1 ] - a [ 0 ] NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT low = min ( low , a [ i + 1 ] - a [ i ] ) NEW_LINE DEDENT high = a [ n - 1 ] - a [ 0 ] NEW_LINE while ( low < high ) : NEW_LINE INDENT mid = ( low + high ) >> 1 NEW_LINE if ( countPairs ( a , n , mid ) < k ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT k = 3 NEW_LINE a = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( a ) NEW_LINE print ( kthDiff ( a , n , k ) ) NEW_LINE"} {"text":"Find the smallest and second smallest elements in an array | Python program to find smallest and second smallest elements ; Function to print first smallest and second smallest elements ; There should be atleast two elements ; 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 function to test above function","code":"import sys NEW_LINE def print2Smallest ( arr ) : NEW_LINE INDENT arr_size = len ( arr ) NEW_LINE if arr_size < 2 : NEW_LINE INDENT print \" Invalid \u2581 Input \" NEW_LINE return NEW_LINE DEDENT first = second = sys . maxint NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT if arr [ i ] < first : NEW_LINE INDENT second = first NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < second and arr [ i ] != first ) : NEW_LINE INDENT second = arr [ i ] ; NEW_LINE DEDENT DEDENT if ( second == sys . maxint ) : NEW_LINE INDENT print \" No \u2581 second \u2581 smallest \u2581 element \" NEW_LINE DEDENT else : NEW_LINE INDENT print ' The \u2581 smallest \u2581 element \u2581 is ' , first , ' and ' ' \u2581 second \u2581 smallest \u2581 element \u2581 is ' , second NEW_LINE DEDENT DEDENT arr = [ 12 , 13 , 1 , 10 , 34 , 1 ] NEW_LINE print2Smallest ( arr ) NEW_LINE"} {"text":"Range LCM Queries | LCM of given range queries using Segment Tree ; allocate space for tree ; declaring the array globally ; Function to return gcd of a and b ; utility function to find lcm ; Function to build the segment tree Node starts beginning index of current subtree . start and end are indexes in arr [ ] which is global ; If there is only one element in current subarray ; build left and right segments ; build the parent ; Function to make queries for array range ) l , r ) . Node is index of root of current segment in segment tree ( Note that indexes in segment tree begin with 1f or simplicity ) . start and end are indexes of subarray covered by root of current segment . ; Completely outside the segment , returning 1 will not affect the lcm ; ; completely inside the segment ; partially inside ; Driver Code ; initialize the array ; build the segment tree ; Now we can answer each query efficiently Print LCM of ( 2 , 5 ) ; Print LCM of ( 5 , 10 ) ; Print LCM of ( 0 , 10 )","code":"MAX = 1000 NEW_LINE tree = [ 0 ] * ( 4 * MAX ) NEW_LINE arr = [ 0 ] * MAX NEW_LINE def gcd ( a : int , b : int ) : 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 : int , b : int ) : NEW_LINE INDENT return ( a * b ) \/\/ gcd ( a , b ) NEW_LINE DEDENT def build ( node : int , start : int , end : int ) : NEW_LINE INDENT if start == end : NEW_LINE INDENT tree [ node ] = arr [ start ] NEW_LINE return NEW_LINE DEDENT mid = ( start + end ) \/\/ 2 NEW_LINE build ( 2 * node , start , mid ) NEW_LINE build ( 2 * node + 1 , mid + 1 , end ) NEW_LINE left_lcm = tree [ 2 * node ] NEW_LINE right_lcm = tree [ 2 * node + 1 ] NEW_LINE tree [ node ] = lcm ( left_lcm , right_lcm ) NEW_LINE DEDENT def query ( node : int , start : int , end : int , l : int , r : int ) : NEW_LINE INDENT if end < l or start > r : NEW_LINE INDENT return 1 NEW_LINE DEDENT if l <= start and r >= end : NEW_LINE INDENT return tree [ node ] NEW_LINE DEDENT mid = ( start + end ) \/\/ 2 NEW_LINE left_lcm = query ( 2 * node , start , mid , l , r ) NEW_LINE right_lcm = query ( 2 * node + 1 , mid + 1 , end , l , r ) NEW_LINE return lcm ( left_lcm , right_lcm ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr [ 0 ] = 5 NEW_LINE arr [ 1 ] = 7 NEW_LINE arr [ 2 ] = 5 NEW_LINE arr [ 3 ] = 2 NEW_LINE arr [ 4 ] = 10 NEW_LINE arr [ 5 ] = 12 NEW_LINE arr [ 6 ] = 11 NEW_LINE arr [ 7 ] = 17 NEW_LINE arr [ 8 ] = 14 NEW_LINE arr [ 9 ] = 1 NEW_LINE arr [ 10 ] = 44 NEW_LINE build ( 1 , 0 , 10 ) NEW_LINE print ( query ( 1 , 0 , 10 , 2 , 5 ) ) NEW_LINE print ( query ( 1 , 0 , 10 , 5 , 10 ) ) NEW_LINE print ( query ( 1 , 0 , 10 , 0 , 10 ) ) NEW_LINE DEDENT"} {"text":"Count possible decoding of a given digit sequence with hidden characters | Python program for the above approach ; check the first character of the string if it is ' * ' then 9 ways ; traverse the string ; If s [ i ] = = ' * ' there can be 9 possible values of * ; If previous character is 1 then words that can be formed are K ( 11 ) , L ( 12 ) , M ( 13 ) , N ( 14 ) O ( 15 ) , P ( 16 ) , Q ( 17 ) , R ( 18 ) , S ( 19 ) ; If previous character is 2 then the words that can be formed are U ( 21 ) , V ( 22 ) , W ( 23 ) , X ( 24 ) Y ( 25 ) , Z ( 26 ) ; If the previous digit is * then all 15 2 - digit characters can be formed ; taking the value from previous step ; If previous character is 1 then the i - 1 th character and ith character can be decoded in a single character therefore , adding dp [ i - 1 ] . ; If previous character is 2 and ith character is less than 6 then the i - 1 th character and ith character can be decoded in a single character therefore , adding dp [ i - 1 ] . ; If previous character is * then it will contain the above 2 cases ; Driver code","code":"M = 1000000007 NEW_LINE def waysOfDecoding ( s ) : NEW_LINE INDENT dp = [ 0 ] * ( len ( s ) + 1 ) NEW_LINE dp [ 0 ] = 1 NEW_LINE if s [ 0 ] == ' * ' : NEW_LINE INDENT dp [ 1 ] = 9 NEW_LINE DEDENT elif s [ 0 ] == '0' : NEW_LINE INDENT dp [ 1 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ 1 ] = 1 NEW_LINE DEDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' * ' ) : NEW_LINE INDENT dp [ i + 1 ] = 9 * dp [ i ] NEW_LINE if ( s [ i - 1 ] == '1' ) : NEW_LINE INDENT dp [ i + 1 ] = ( dp [ i + 1 ] + 9 * dp [ i - 1 ] ) % M NEW_LINE DEDENT elif ( s [ i - 1 ] == '2' ) : NEW_LINE INDENT dp [ i + 1 ] = ( dp [ i + 1 ] + 6 * dp [ i - 1 ] ) % M NEW_LINE DEDENT elif ( s [ i - 1 ] == ' * ' ) : NEW_LINE INDENT dp [ i + 1 ] = ( dp [ i + 1 ] + 15 * dp [ i - 1 ] ) % M NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if s [ i ] != '0' : NEW_LINE INDENT dp [ i + 1 ] = dp [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i + 1 ] = 0 NEW_LINE DEDENT if ( s [ i - 1 ] == '1' ) : NEW_LINE INDENT dp [ i + 1 ] = ( dp [ i + 1 ] + dp [ i - 1 ] ) % M NEW_LINE DEDENT elif ( s [ i - 1 ] == '2' and s [ i ] <= '6' ) : NEW_LINE INDENT dp [ i + 1 ] = ( dp [ i + 1 ] + dp [ i - 1 ] ) % M NEW_LINE DEDENT elif ( s [ i - 1 ] == ' * ' ) : NEW_LINE INDENT if ( s [ i ] <= '6' ) : NEW_LINE INDENT dp [ i + 1 ] = dp [ i + 1 ] + 2 * dp [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i + 1 ] = dp [ i + 1 ] + 1 * dp [ i - 1 ] NEW_LINE DEDENT dp [ i + 1 ] = dp [ i + 1 ] % M NEW_LINE DEDENT DEDENT DEDENT return dp [ len ( s ) ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"12\" NEW_LINE print ( waysOfDecoding ( s ) ) NEW_LINE DEDENT"} {"text":"Count ways to split array into two subsets having difference between their sum equal to K | Function to count the number of ways to divide the array into two subsets and such that the difference between their sums is equal to diff ; Store the sum of the set S1 ; Initializing the matrix ; Number of ways to get sum using 0 elements is 0 ; Number of ways to get sum 0 using i elements is 1 ; Traverse the 2D array ; If the value is greater than the sum store the value of previous state ; Return the result ; Driver Code ; Given Input ; Function Call","code":"def countSubset ( arr , n , diff ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT sum += diff NEW_LINE sum = sum \/\/ 2 NEW_LINE t = [ [ 0 for i in range ( sum + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for j in range ( sum + 1 ) : NEW_LINE INDENT t [ 0 ] [ j ] = 0 NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT t [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] > j ) : NEW_LINE INDENT t [ i ] [ j ] = t [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT t [ i ] [ j ] = t [ i - 1 ] [ j ] + t [ i - 1 ] [ j - arr [ i - 1 ] ] NEW_LINE DEDENT DEDENT DEDENT return t [ n ] [ sum ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT diff , n = 1 , 4 NEW_LINE arr = [ 1 , 1 , 2 , 3 ] NEW_LINE print ( countSubset ( arr , n , diff ) ) NEW_LINE DEDENT"} {"text":"Probability that the sum of all numbers obtained on throwing a dice N times lies between two given integers | Python3 program for above approach ; Function to calculate probability that the sum of numbers on N throws of dice lies between A and B ; Base case ; Add the probability for all the numbers between a and b ; Driver Code ; Print the answer","code":"dp = [ [ 0 for i in range ( 605 ) ] for j in range ( 105 ) ] NEW_LINE def find ( N , a , b ) : NEW_LINE INDENT probability = 0.0 NEW_LINE for i in range ( 1 , 7 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1.0 \/ 6 NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT for j in range ( i , ( 6 * i ) + 1 ) : NEW_LINE INDENT for k in range ( 1 , 7 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j ] + dp [ i - 1 ] [ j - k ] \/ 6 NEW_LINE DEDENT DEDENT DEDENT for Sum in range ( a , b + 1 ) : NEW_LINE INDENT probability = probability + dp [ N ] [ Sum ] NEW_LINE DEDENT return probability NEW_LINE DEDENT N , a , b = 4 , 13 , 17 NEW_LINE probability = find ( N , a , b ) NEW_LINE print ( ' % .6f ' % probability ) NEW_LINE"} {"text":"Maximum sum from a tree with adjacent levels not allowed | Python3 code for max sum with adjacent levels not allowed ; A BST node ; Recursive function to find the maximum sum returned for a root node and its grandchildren ; Returns maximum sum with adjacent levels not allowed . This function mainly uses getSumAlternate ( ) ; We compute sum of alternate levels starting first level and from second level . And return maximum of two values . ; Driver code","code":"from collections import deque as queue NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getSumAlternate ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = root . data NEW_LINE if ( root . left != None ) : NEW_LINE INDENT sum += getSum ( root . left . left ) NEW_LINE sum += getSum ( root . left . right ) NEW_LINE DEDENT if ( root . right != None ) : NEW_LINE INDENT sum += getSum ( root . right . left ) NEW_LINE sum += getSum ( root . right . right ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def getSum ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max ( getSumAlternate ( root ) , ( getSumAlternate ( root . left ) + getSumAlternate ( root . right ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . left . right = Node ( 5 ) NEW_LINE root . right . left . right . left = Node ( 6 ) NEW_LINE print ( getSum ( root ) ) NEW_LINE DEDENT"} {"text":"Subset Sum Problem in O ( sum ) space | Returns true if there exists a subset with given sum in arr [ ] ; The value of subset [ i % 2 ] [ j ] will be true if there exists a subset of sum j in arr [ 0 , 1 , ... . , i - 1 ] ; A subset with sum 0 is always possible ; If there exists no element no sum is possible ; Driver code","code":"def isSubsetSum ( arr , n , sum ) : NEW_LINE INDENT subset = [ [ False for j in range ( sum + 1 ) ] for i in range ( 3 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( sum + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT subset [ i % 2 ] [ j ] = True NEW_LINE DEDENT elif ( i == 0 ) : NEW_LINE INDENT subset [ i % 2 ] [ j ] = False NEW_LINE DEDENT elif ( arr [ i - 1 ] <= j ) : NEW_LINE INDENT subset [ i % 2 ] [ j ] = subset [ ( i + 1 ) % 2 ] [ j - arr [ i - 1 ] ] or subset [ ( i + 1 ) % 2 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT subset [ i % 2 ] [ j ] = subset [ ( i + 1 ) % 2 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return subset [ n % 2 ] [ sum ] NEW_LINE DEDENT arr = [ 6 , 2 , 5 ] NEW_LINE sum = 7 NEW_LINE n = len ( arr ) NEW_LINE if ( isSubsetSum ( arr , n , sum ) == True ) : NEW_LINE INDENT print ( \" There \u2581 exists \u2581 a \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 subset \u2581 exists \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Maximum equlibrium sum in an array | Python 3 program to find maximum equilibrium sum . ; Function to find maximum equilibrium sum . ; Driver Code","code":"import sys NEW_LINE def findMaxSum ( arr , n ) : NEW_LINE INDENT res = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum = arr [ i ] NEW_LINE for j in range ( i ) : NEW_LINE INDENT prefix_sum += arr [ j ] NEW_LINE DEDENT suffix_sum = arr [ i ] NEW_LINE j = n - 1 NEW_LINE while ( j > i ) : NEW_LINE INDENT suffix_sum += arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT if ( prefix_sum == suffix_sum ) : NEW_LINE INDENT res = max ( res , prefix_sum ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxSum ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Maximum equlibrium sum in an array | Function to find maximum equilibrium sum . ; Array to store prefix sum . ; Array to store suffix sum . ; Variable to store maximum sum . ; Calculate prefix sum . ; Calculate suffix sum and compare it with prefix sum . Update ans accordingly . ; Driver Code","code":"def findMaxSum ( arr , n ) : NEW_LINE INDENT preSum = [ 0 for i in range ( n ) ] NEW_LINE suffSum = [ 0 for i in range ( n ) ] NEW_LINE ans = - 10000000 NEW_LINE preSum [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT preSum [ i ] = preSum [ i - 1 ] + arr [ i ] NEW_LINE DEDENT suffSum [ n - 1 ] = arr [ n - 1 ] NEW_LINE if ( preSum [ n - 1 ] == suffSum [ n - 1 ] ) : NEW_LINE INDENT ans = max ( ans , preSum [ n - 1 ] ) NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffSum [ i ] = suffSum [ i + 1 ] + arr [ i ] NEW_LINE if ( suffSum [ i ] == preSum [ i ] ) : NEW_LINE INDENT ans = max ( ans , preSum [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxSum ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Maximum equlibrium sum in an array | Python3 program to find maximum equilibrium sum . ; Function to find maximum equilibrium sum . ; Driver code","code":"import sys NEW_LINE def findMaxSum ( arr , n ) : NEW_LINE INDENT ss = sum ( arr ) NEW_LINE prefix_sum = 0 NEW_LINE res = - sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum += arr [ i ] NEW_LINE if prefix_sum == ss : NEW_LINE INDENT res = max ( res , prefix_sum ) ; NEW_LINE DEDENT ss -= arr [ i ] ; NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ - 2 , 5 , 3 , 1 , 2 , 6 , - 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxSum ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Majority Element | Function to find Majority element in an array ; sentinels ; update maxCount if count of current element is greater ; if maxCount is greater than n \/ 2 return the corresponding element ; Driver code ; Function calling","code":"def findMajority ( arr , n ) : NEW_LINE INDENT maxCount = 0 NEW_LINE index = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > maxCount ) : NEW_LINE INDENT maxCount = count NEW_LINE index = i NEW_LINE DEDENT DEDENT if ( maxCount > n \/\/ 2 ) : NEW_LINE INDENT print ( arr [ index ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 Majority \u2581 Element \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE DEDENT"} {"text":"Majority Element | Function to find the candidate for Majority ; Function to check if the candidate occurs more than n \/ 2 times ; Function to print Majority Element ; Find the candidate for Majority ; Print the candidate if it is Majority ; Driver code ; Function call","code":"def findCandidate ( A ) : NEW_LINE INDENT maj_index = 0 NEW_LINE count = 1 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if A [ maj_index ] == A [ i ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT if count == 0 : NEW_LINE INDENT maj_index = i NEW_LINE count = 1 NEW_LINE DEDENT DEDENT return A [ maj_index ] NEW_LINE DEDENT def isMajority ( A , cand ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT if A [ i ] == cand : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if count > len ( A ) \/ 2 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def printMajority ( A ) : NEW_LINE INDENT cand = findCandidate ( A ) NEW_LINE if isMajority ( A , cand ) == True : NEW_LINE INDENT print ( cand ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 Majority \u2581 Element \" ) NEW_LINE DEDENT DEDENT A = [ 1 , 3 , 3 , 1 , 2 ] NEW_LINE printMajority ( A ) NEW_LINE"} {"text":"Majority Element | Python3 program for finding out majority element in an array ; Driver code ; Function calling","code":"def findMajority ( arr , size ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( size ) : NEW_LINE INDENT if arr [ i ] in m : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for key in m : NEW_LINE INDENT if m [ key ] > size \/ 2 : NEW_LINE INDENT count = 1 NEW_LINE print ( \" Majority \u2581 found \u2581 : - \" , key ) NEW_LINE break NEW_LINE DEDENT DEDENT if ( count == 0 ) : NEW_LINE INDENT print ( \" No \u2581 Majority \u2581 element \" ) NEW_LINE DEDENT DEDENT arr = [ 2 , 2 , 2 , 2 , 5 , 5 , 2 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE findMajority ( arr , n ) NEW_LINE"} {"text":"Majority Element | Function to find Majority element in an array it returns - 1 if there is no majority element ; sort the array in O ( nlogn ) ; increases the count if the same element occurs otherwise starts counting new element ; sets maximum count and stores maximum occured element so far if maximum count becomes greater than n \/ 2 it breaks out setting the flag ; returns maximum occured element if there is no such element , returns - 1 ; Driver code ; Function calling","code":"def majorityElement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count , max_ele , temp , f = 1 , - 1 , arr [ 0 ] , 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( temp == arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 1 NEW_LINE temp = arr [ i ] NEW_LINE DEDENT if ( max_ele < count ) : NEW_LINE INDENT max_ele = count NEW_LINE ele = arr [ i ] NEW_LINE if ( max_ele > ( n \/\/ 2 ) ) : NEW_LINE INDENT f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if f == 1 : NEW_LINE INDENT return ele NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 2 , 1 , 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( majorityElement ( arr , n ) ) NEW_LINE"} {"text":"Dynamic Programming | Returns true if there is a subset of set [ ] with sum equal to 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 ; uncomment this code to print table ; Driver code","code":"def isSubsetSum ( set , n , sum ) : NEW_LINE INDENT subset = ( [ [ False for i in range ( sum + 1 ) ] for i in range ( n + 1 ) ] ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , sum + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 ) : NEW_LINE INDENT if j < set [ i - 1 ] : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i - 1 ] [ j ] NEW_LINE DEDENT if j >= set [ i - 1 ] : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i - 1 ] [ j ] or subset [ i - 1 ] [ j - set [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE for j in range ( sum + 1 ) : NEW_LINE print ( subset [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE print ( ) NEW_LINE return subset [ n ] [ sum ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT set = [ 3 , 34 , 4 , 12 , 5 , 2 ] NEW_LINE sum = 9 NEW_LINE n = len ( set ) NEW_LINE if ( isSubsetSum ( set , n , sum ) == True ) : NEW_LINE INDENT print ( \" Found \u2581 a \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT DEDENT"} {"text":"Dynamic Programming | Taking the matrix as globally ; Check if possible subset with given sum is possible or not ; If the sum is zero it means we got our expected sum ; If the value is not - 1 it means it already call the function with the same value . it will save our from the repetition . ; if the value of a [ n - 1 ] is greater than the sum . we call for the next value ; Here we do two calls because we don ' t \u2581 know \u2581 which \u2581 value \u2581 is \u2581 \u2581 full - fill \u2581 our \u2581 criteria \u2581 \u2581 that ' s why we doing two calls ; Driver Code","code":"tab = [ [ - 1 for i in range ( 2000 ) ] for j in range ( 2000 ) ] NEW_LINE def subsetSum ( a , n , sum ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( tab [ n - 1 ] [ sum ] != - 1 ) : NEW_LINE INDENT return tab [ n - 1 ] [ sum ] NEW_LINE DEDENT if ( a [ n - 1 ] > sum ) : NEW_LINE INDENT tab [ n - 1 ] [ sum ] = subsetSum ( a , n - 1 , sum ) NEW_LINE return tab [ n - 1 ] [ sum ] NEW_LINE DEDENT else : NEW_LINE INDENT tab [ n - 1 ] [ sum ] = subsetSum ( a , n - 1 , sum ) NEW_LINE return tab [ n - 1 ] [ sum ] or subsetSum ( a , n - 1 , sum - a [ n - 1 ] ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE a = [ 1 , 5 , 3 , 7 , 4 ] NEW_LINE sum = 12 NEW_LINE if ( subsetSum ( a , n , sum ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} {"text":"Sum of bit differences for numbers from 0 to N | Python3 program for the above approach ; Function to implement fast exponentiation ; Function to return the value for powers of 2 ; Function to convert N into binary ; To store binary representation ; Iterate each digit of n ; Return binary representation ; Function to find difference in bits ; Get binary representation ; total number of bit differences from 0 to N ; Iterate over each binary bit ; If current bit is '1' then add the count of current bit ; Given Number ; Function Call","code":"from math import log NEW_LINE def binpow ( a , b ) : NEW_LINE INDENT res = 1 NEW_LINE while ( b > 0 ) : NEW_LINE INDENT if ( b % 2 == 1 ) : NEW_LINE INDENT res = res * a NEW_LINE DEDENT a = a * a NEW_LINE b \/\/= 2 NEW_LINE DEDENT return res NEW_LINE DEDENT def find ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT p = log ( x ) \/ log ( 2 ) NEW_LINE return binpow ( 2 , p + 1 ) - 1 NEW_LINE DEDENT def getBinary ( n ) : NEW_LINE INDENT ans = \" \" NEW_LINE while ( n > 0 ) : NEW_LINE INDENT dig = n % 2 NEW_LINE ans += str ( dig ) NEW_LINE n \/\/= 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT def totalCountDifference ( n ) : NEW_LINE INDENT ans = getBinary ( n ) NEW_LINE req = 0 NEW_LINE for i in range ( len ( ans ) ) : NEW_LINE INDENT if ( ans [ i ] == '1' ) : NEW_LINE INDENT req += find ( binpow ( 2 , i ) ) NEW_LINE DEDENT DEDENT return req NEW_LINE DEDENT N = 5 NEW_LINE print ( totalCountDifference ( N ) ) NEW_LINE"} {"text":"Find the maximum length of the prefix | Function to return the maximum length of the required prefix ; Array to store the frequency of each element of the array ; Iterating for all the elements ; Update the frequency of the current element i . e . v ; Sorted positive values from counts array ; If current prefix satisfies the given conditions ; Return the maximum length ; Driver code","code":"def Maximum_Length ( a ) : NEW_LINE INDENT counts = [ 0 ] * 11 NEW_LINE for index , v in enumerate ( a ) : NEW_LINE INDENT counts [ v ] += 1 NEW_LINE k = sorted ( [ i for i in counts if i ] ) NEW_LINE if len ( k ) == 1 or ( k [ 0 ] == k [ - 2 ] and k [ - 1 ] - k [ - 2 ] == 1 ) or ( k [ 0 ] == 1 and k [ 1 ] == k [ - 1 ] ) : NEW_LINE INDENT ans = index NEW_LINE DEDENT DEDENT return ans + 1 NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 1 , 1 , 2 , 2 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( Maximum_Length ( a ) ) NEW_LINE DEDENT"} {"text":"Online Queries for GCD of array after divide operations | Returns the gcd after all updates in the array ; Function to calculate gcd of onine queries ; Stores the gcd of the initial array elements ; calculates the gcd ; performing online queries ; index is 1 based ; divide the array element ; calculates the current gcd ; Print the gcd after each step ; Driver code","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 print_gcd_online ( n , m , query , arr ) : NEW_LINE INDENT max_gcd = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT max_gcd = gcd ( max_gcd , arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , m ) : NEW_LINE INDENT query [ i ] [ 0 ] -= 1 NEW_LINE arr [ query [ i ] [ 0 ] ] \/\/= query [ i ] [ 1 ] NEW_LINE max_gcd = gcd ( arr [ query [ i ] [ 0 ] ] , max_gcd ) NEW_LINE print ( max_gcd ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n , m = 3 , 3 NEW_LINE query = [ [ 1 , 3 ] , [ 3 , 12 ] , [ 2 , 4 ] ] NEW_LINE arr = [ 36 , 24 , 72 ] NEW_LINE print_gcd_online ( n , m , query , arr ) NEW_LINE DEDENT"} {"text":"Numbers in range [ L , R ] such that the count of their divisors is both even and prime | Python 3 implementation of the approach ; stores whether the number is prime or not ; stores the count of prime numbers less than or equal to the index ; create the sieve ; Create a boolean array \" prime [ 0 . . n ] \" and initialize all the entries 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 ; stores the prefix sum of number of primes less than or equal to 'i ; Driver code ; create the sieve ; ' l ' and ' r ' are the lower and upper bounds of the range ; get the value of count ; display the count","code":"MAX = 1000000 NEW_LINE prime = [ True ] * ( MAX + 1 ) NEW_LINE sum = [ 0 ] * ( MAX + 1 ) NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= MAX : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT i = p * 2 NEW_LINE while i <= MAX : NEW_LINE INDENT prime [ i ] = False NEW_LINE i += p NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( 1 , MAX + 1 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT sum [ i ] = 1 NEW_LINE DEDENT sum [ i ] += sum [ i - 1 ] NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE l = 3 NEW_LINE r = 9 NEW_LINE c = ( sum [ r ] - sum [ l - 1 ] ) NEW_LINE print ( \" Count : \" , c ) NEW_LINE DEDENT"} {"text":"Area of a circle inscribed in a rectangle which is inscribed in a semicircle | Python 3 Program to find the area of the circle inscribed within the rectangle which in turn is inscribed in a semicircle ; Function to find the area of the circle ; radius cannot be negative ; area of the circle ; Driver code","code":"from math import pow , sqrt NEW_LINE def area ( r ) : NEW_LINE INDENT if ( r < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT area = 3.14 * pow ( r \/ ( 2 * sqrt ( 2 ) ) , 2 ) ; NEW_LINE return area ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 5 NEW_LINE print ( \" { 0 : . 6 } \" . format ( area ( a ) ) ) NEW_LINE DEDENT"} {"text":"Find count of Almost Prime numbers from 1 to N | Python 3 program to count almost prime numbers from 1 to 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 . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to count almost prime numbers from 1 to n ; to store required answer ; 6 is first almost prime number ; to count prime factors ; if it is perfect square ; if I is almost prime number ; Driver Code","code":"from math import * NEW_LINE N = 100005 NEW_LINE prime = [ True ] * N NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( N ) ) ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( 2 * p , N , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def almostPrimes ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 6 , n + 1 ) : NEW_LINE INDENT c = 0 NEW_LINE for j in range ( 2 , int ( sqrt ( i ) ) + 1 ) : NEW_LINE INDENT if i % j == 0 : NEW_LINE INDENT if j * j == i : NEW_LINE INDENT if prime [ j ] : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if prime [ j ] : NEW_LINE INDENT c += 1 NEW_LINE DEDENT if prime [ i \/\/ j ] : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if c == 2 : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE n = 21 NEW_LINE print ( almostPrimes ( n ) ) NEW_LINE DEDENT"} {"text":"Divide a number into two parts such that sum of digits is maximum | Returns sum of digits of x ; Returns closest number to x in terms of 9 's ; Driver Code","code":"def sumOfDigitsSingle ( x ) : NEW_LINE INDENT ans = 0 NEW_LINE while x : NEW_LINE INDENT ans += x % 10 NEW_LINE x \/\/= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT def closest ( x ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( ans * 10 + 9 <= x ) : NEW_LINE INDENT ans = ans * 10 + 9 NEW_LINE DEDENT return ans NEW_LINE DEDENT def sumOfDigitsTwoParts ( N ) : NEW_LINE INDENT A = closest ( N ) NEW_LINE return sumOfDigitsSingle ( A ) + sumOfDigitsSingle ( N - A ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 35 NEW_LINE print ( sumOfDigitsTwoParts ( N ) ) NEW_LINE DEDENT"} {"text":"Primality Test | Set 5 ( Using Lucas | Function to check whether ( 2 ^ p - 1 ) is prime or not . ; generate the number ; First number of the series ; Generate the rest ( p - 2 ) terms of the series ; now if the ( p - 1 ) the term is 0 return true else false . ; Check whetherr 2 ^ ( p - 1 ) is prime or not .","code":"def isPrime ( p ) : NEW_LINE INDENT checkNumber = 2 ** p - 1 NEW_LINE nextval = 4 % checkNumber NEW_LINE for i in range ( 1 , p - 1 ) : NEW_LINE INDENT nextval = ( nextval * nextval - 2 ) % checkNumber NEW_LINE DEDENT if ( nextval == 0 ) : return True NEW_LINE else : return False NEW_LINE DEDENT p = 7 NEW_LINE checkNumber = 2 ** p - 1 NEW_LINE if isPrime ( p ) : NEW_LINE INDENT print ( checkNumber , ' is \u2581 Prime . ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( checkNumber , ' is \u2581 not \u2581 Prime ' ) NEW_LINE DEDENT"} {"text":"Sophie Germain Prime | Function to detect prime number here we have used sieve method https : www . geeksforgeeks . org \/ sieve - of - eratosthenes \/ to detect prime number ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; We have made array till 2 * n + 1 so that we can check prime number till that and conclude about sophie german prime . ; checking every i whether it is sophie german prime or not . ; Driver Code","code":"def sieve ( n , prime ) : NEW_LINE INDENT 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 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def printSophieGermanNumber ( n ) : NEW_LINE INDENT prime = [ True ] * ( 2 * n + 1 ) NEW_LINE sieve ( 2 * n + 1 , prime ) NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( prime [ i ] and prime [ 2 * i + 1 ] ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT n = 25 NEW_LINE printSophieGermanNumber ( n ) NEW_LINE"} {"text":"Bessel 's Interpolation | calculating u mentioned in the formula ; calculating factorial of given number n ; Number of values given ; y [ ] [ ] is used for difference table with y [ ] [ 0 ] used for input ; Calculating the central difference table ; Displaying the central difference table ; value to interpolate at ; Initializing u and sum ; k is origin thats is f ( 0 ) ; if ( ( n % 2 ) > 0 ) : origin for odd ; k = int ( n \/ 2 - 1 ) ; origin for even ; Solving using bessel 's formula","code":"def ucal ( u , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT temp = u ; NEW_LINE for i in range ( 1 , int ( n \/ 2 + 1 ) ) : NEW_LINE INDENT temp = temp * ( u - i ) ; NEW_LINE DEDENT for i in range ( 1 , int ( n \/ 2 ) ) : NEW_LINE INDENT temp = temp * ( u + i ) ; NEW_LINE DEDENT return temp ; NEW_LINE DEDENT def fact ( 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 n = 6 ; NEW_LINE x = [ 25 , 26 , 27 , 28 , 29 , 30 ] ; NEW_LINE y = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] ; NEW_LINE y [ 0 ] [ 0 ] = 4.000 ; NEW_LINE y [ 1 ] [ 0 ] = 3.846 ; NEW_LINE y [ 2 ] [ 0 ] = 3.704 ; NEW_LINE y [ 3 ] [ 0 ] = 3.571 ; NEW_LINE y [ 4 ] [ 0 ] = 3.448 ; NEW_LINE y [ 5 ] [ 0 ] = 3.333 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( n - i ) : NEW_LINE INDENT y [ j ] [ i ] = y [ j + 1 ] [ i - 1 ] - y [ j ] [ i - 1 ] ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n - i ) : NEW_LINE INDENT print ( y [ i ] [ j ] , \" TABSYMBOL \" , end = \" \u2581 \" ) ; NEW_LINE DEDENT print ( \" \" ) ; NEW_LINE DEDENT value = 27.4 ; NEW_LINE sum = ( y [ 2 ] [ 0 ] + y [ 3 ] [ 0 ] ) \/ 2 ; NEW_LINE k = 0 ; NEW_LINE INDENT k = int ( n \/ 2 ) ; NEW_LINE DEDENT else : NEW_LINE u = ( value - x [ k ] ) \/ ( x [ 1 ] - x [ 0 ] ) ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT sum = sum + ( ( u - 0.5 ) * ucal ( u , i - 1 ) * y [ k ] [ i ] ) \/ fact ( i ) ; NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + ( ucal ( u , i ) * ( y [ k ] [ i ] + y [ k - 1 ] [ i ] ) \/ ( fact ( i ) * 2 ) ) ; NEW_LINE k -= 1 ; NEW_LINE DEDENT DEDENT print ( \" Value \u2581 at \" , value , \" is \" , round ( sum , 5 ) ) ; NEW_LINE"} {"text":"An efficient way to check whether n | A simple Python 3 program to check if n - th Fibonacci number is multiple of 10. ; Returns true if n - th Fibonacci number is multiple of 10. ; Driver code","code":"def fibonacci ( n ) : NEW_LINE INDENT a = 0 NEW_LINE b = 1 NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT return c NEW_LINE DEDENT def isMultipleOf10 ( n ) : NEW_LINE INDENT f = fibonacci ( 30 ) NEW_LINE return ( f % 10 == 0 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 30 NEW_LINE if ( isMultipleOf10 ( n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Program to find whether a given number is power of 2 | 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 given number is power of 2 | 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":"Program to find whether a given number is power of 2 | 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 0 NEW_LINE DEDENT if ( ( n & ( ~ ( n - 1 ) ) ) == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( isPowerofTwo ( 30 ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT if ( isPowerofTwo ( 128 ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT"} {"text":"Smallest power of 2 which is greater than or equal to sum of array elements | Function to find the nearest power of 2 ; The number ; If already a power of 2 ; Find the next power of 2 ; Function to find the memory used ; Sum of array ; Traverse and find the sum of array ; Function call to find the nearest power of 2 ; Driver Code","code":"def nextPowerOf2 ( n ) : NEW_LINE INDENT p = 1 NEW_LINE if ( n and not ( n & ( n - 1 ) ) ) : NEW_LINE INDENT return n NEW_LINE DEDENT while ( p < n ) : NEW_LINE INDENT p <<= 1 NEW_LINE DEDENT return p NEW_LINE DEDENT def memoryUsed ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT nearest = nextPowerOf2 ( sum ) NEW_LINE return nearest NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( memoryUsed ( arr , n ) ) NEW_LINE"} {"text":"Toggling k | Python3 code to toggle k - th bit of n ; Driver code","code":"def toggleKthBit ( n , k ) : NEW_LINE INDENT return ( n ^ ( 1 << ( k - 1 ) ) ) NEW_LINE DEDENT n = 5 NEW_LINE k = 1 NEW_LINE print ( toggleKthBit ( n , k ) ) NEW_LINE"} {"text":"Smallest power of 2 greater than or equal to n | Python program to find smallest power of 2 greater than or equal to n ; First n in the below condition is for the case where n is 0 ; Driver Code","code":"def nextPowerOf2 ( n ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n and not ( n & ( n - 1 ) ) ) : NEW_LINE INDENT return n NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT n >>= 1 NEW_LINE count += 1 NEW_LINE DEDENT return 1 << count NEW_LINE DEDENT n = 0 NEW_LINE print ( nextPowerOf2 ( n ) ) NEW_LINE"} {"text":"Kth number from the set of multiples of numbers A , B and C | Function to return the GCD of A and B ; Function to return the LCM of A and B ; Function to return the Kth element from the required set if it a multiple of A ; Start and End for Binary Search ; If no answer found return - 1 ; Inclusion and Exclusion ; Multiple should be smaller ; Multiple should be bigger ; Function to return the Kth element from the required set if it a multiple of B ; Start and End for Binary Search ; If no answer found return - 1 ; Inclusion and Exclusion ; Multiple should be smaller ; Multiple should be bigger ; Function to return the Kth element from the required set if it a multiple of C ; Start and End for Binary Search ; If no answer found return - 1 ; Inclusion and Exclusion ; Multiple should be smaller ; Multiple should be bigger ; Function to return the Kth element from the set of multiples of A , B and C ; Apply binary search on the multiples of A ; If the required element is not a multiple of A then the multiples of B and C need to be checked ; If the required element is neither a multiple of A nor a multiple of B then the multiples of C need to be checked ; Driver code","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 lcm ( A , B ) : NEW_LINE INDENT return ( A * B ) \/\/ gcd ( A , B ) NEW_LINE DEDENT def checkA ( A , B , C , K ) : NEW_LINE INDENT start = 1 NEW_LINE end = K NEW_LINE ans = - 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) \/\/ 2 NEW_LINE value = A * mid NEW_LINE divA = mid - 1 NEW_LINE divB = value \/\/ B - 1 if ( value % B == 0 ) else value \/\/ B NEW_LINE divC = value \/\/ C - 1 if ( value % C == 0 ) else value \/\/ C NEW_LINE divAB = value \/\/ lcm ( A , B ) - 1 if ( value % lcm ( A , B ) == 0 ) else value \/\/ lcm ( A , B ) NEW_LINE divBC = value \/\/ lcm ( C , B ) - 1 if ( value % lcm ( C , B ) == 0 ) else value \/\/ lcm ( C , B ) NEW_LINE divAC = value \/\/ lcm ( A , C ) - 1 if ( value % lcm ( A , C ) == 0 ) else value \/\/ lcm ( A , C ) NEW_LINE divABC = value \/\/ lcm ( A , lcm ( B , C ) ) - 1 if ( value % lcm ( A , lcm ( B , C ) ) == 0 ) else value \/\/ lcm ( A , lcm ( B , C ) ) NEW_LINE elem = divA + divB + divC - divAC - divBC - divAB + divABC NEW_LINE if ( elem == ( K - 1 ) ) : NEW_LINE INDENT ans = value NEW_LINE break NEW_LINE DEDENT elif ( elem > ( K - 1 ) ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def checkB ( A , B , C , K ) : NEW_LINE INDENT start = 1 NEW_LINE end = K NEW_LINE ans = - 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) \/\/ 2 NEW_LINE value = B * mid NEW_LINE divB = mid - 1 NEW_LINE if ( value % A == 0 ) : NEW_LINE INDENT divA = value \/\/ A - 1 NEW_LINE DEDENT else : value \/\/ A NEW_LINE if ( value % C == 0 ) : NEW_LINE INDENT divC = value \/\/ C - 1 NEW_LINE DEDENT else : value \/\/ C NEW_LINE if ( value % lcm ( A , B ) == 0 ) : NEW_LINE INDENT divAB = value \/\/ lcm ( A , B ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( A , B ) NEW_LINE if ( value % lcm ( C , B ) == 0 ) : NEW_LINE INDENT divBC = value \/\/ lcm ( C , B ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( C , B ) NEW_LINE if ( value % lcm ( A , C ) == 0 ) : NEW_LINE INDENT divAC = value \/\/ lcm ( A , C ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( A , C ) NEW_LINE if ( value % lcm ( A , lcm ( B , C ) ) == 0 ) : NEW_LINE INDENT divABC = value \/\/ lcm ( A , lcm ( B , C ) ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( A , lcm ( B , C ) ) NEW_LINE elem = divA + divB + divC - divAC - divBC - divAB + divABC NEW_LINE if ( elem == ( K - 1 ) ) : NEW_LINE INDENT ans = value NEW_LINE break NEW_LINE DEDENT elif ( elem > ( K - 1 ) ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def checkC ( A , B , C , K ) : NEW_LINE INDENT start = 1 NEW_LINE end = K NEW_LINE ans = - 1 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) \/\/ 2 NEW_LINE value = C * mid NEW_LINE divC = mid - 1 NEW_LINE if ( value % B == 0 ) : NEW_LINE INDENT divB = value \/\/ B - 1 NEW_LINE DEDENT else : value \/\/ B NEW_LINE if ( value % A == 0 ) : NEW_LINE INDENT divA = value \/\/ A - 1 NEW_LINE DEDENT else : value \/\/ A NEW_LINE if ( value % lcm ( A , B ) == 0 ) : NEW_LINE INDENT divAB = value \/\/ lcm ( A , B ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( A , B ) NEW_LINE if ( value % lcm ( C , B ) == 0 ) : NEW_LINE INDENT divBC = value \/\/ lcm ( C , B ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( C , B ) NEW_LINE if ( value % lcm ( A , C ) == 0 ) : NEW_LINE INDENT divAC = value \/\/ lcm ( A , C ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( A , C ) NEW_LINE if ( value % lcm ( A , lcm ( B , C ) ) == 0 ) : NEW_LINE INDENT divABC = value \/\/ lcm ( A , lcm ( B , C ) ) - 1 NEW_LINE DEDENT else : value \/\/ lcm ( A , lcm ( B , C ) ) NEW_LINE elem = divA + divB + divC - divAC - divBC - divAB + divABC NEW_LINE if ( elem == ( K - 1 ) ) : NEW_LINE INDENT ans = value NEW_LINE break NEW_LINE DEDENT elif ( elem > ( K - 1 ) ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def findKthMultiple ( A , B , C , K ) : NEW_LINE INDENT res = checkA ( A , B , C , K ) NEW_LINE if ( res == - 1 ) : NEW_LINE INDENT res = checkB ( A , B , C , K ) NEW_LINE DEDENT if ( res == - 1 ) : NEW_LINE INDENT res = checkC ( A , B , C , K ) NEW_LINE DEDENT return res NEW_LINE DEDENT A = 2 NEW_LINE B = 4 NEW_LINE C = 5 NEW_LINE K = 5 NEW_LINE print ( findKthMultiple ( A , B , C , K ) ) NEW_LINE"} {"text":"Add elements in start to sort the array | Variation of Stalin Sort | Function to sort the array ; Iterator < Integer > index = arr . iterator ( ) ; ; Driver Code ; Function Call","code":"def variationStalinsort ( arr ) : NEW_LINE INDENT j = 0 NEW_LINE while True : NEW_LINE INDENT moved = 0 NEW_LINE for i in range ( len ( arr ) - 1 - j ) : NEW_LINE INDENT if arr [ i ] > arr [ i + 1 ] : NEW_LINE INDENT arr . insert ( moved , arr . pop ( i + 1 ) ) NEW_LINE moved += 1 NEW_LINE DEDENT DEDENT j += 1 NEW_LINE if moved == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 1 , 4 , 3 , 6 , 5 , 8 , 7 , 10 , 9 ] NEW_LINE print ( variationStalinsort ( arr ) ) NEW_LINE DEDENT"} {"text":"Sort an Array which contain 1 to N values in O ( N ) using Cycle Sort | Function to print array element ; Traverse the array ; Function to sort the array in O ( N ) ; Traverse the array ; If the current element is at correct position ; Else swap the current element with it 's correct position ; Swap the value of arr [ i ] and arr [ arr [ i ] - 1 ] ; Driver code ; Function call to sort the array ; Function call to print the array","code":"def printArray ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT def sortArray ( arr , N ) : NEW_LINE INDENT i = 0 NEW_LINE while i < N : NEW_LINE INDENT if arr [ i ] == i + 1 : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp1 = arr [ i ] NEW_LINE temp2 = arr [ arr [ i ] - 1 ] NEW_LINE arr [ i ] = temp2 NEW_LINE arr [ temp1 - 1 ] = temp1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 5 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE sortArray ( arr , N ) NEW_LINE printArray ( arr , N ) NEW_LINE DEDENT"} {"text":"Maximum sum of values of N items in 0 | Function to find the maximum value ; base condition ; K elements already reduced to half of their weight ; Dont include item ; If weight of the item is less than or equal to the remaining weight then include the item ; Return the maximum of both cases ; If the weight reduction to half is possible ; Skip the item ; Include item with full weight if weight of the item is less than the remaining weight ; Include item with half weight if half weight of the item is less than the remaining weight ; Return the maximum of all 3 cases ; Driver Code","code":"def maximum ( value , weight , weight1 , flag , K , index , val_len ) : NEW_LINE INDENT if ( index >= val_len ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( flag == K ) : NEW_LINE INDENT skip = maximum ( value , weight , weight1 , flag , K , index + 1 , val_len ) NEW_LINE full = 0 NEW_LINE if ( weight [ index ] <= weight1 ) : NEW_LINE INDENT full = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] , flag , K , index + 1 , val_len ) NEW_LINE DEDENT return max ( full , skip ) NEW_LINE DEDENT else : NEW_LINE INDENT skip = maximum ( value , weight , weight1 , flag , K , index + 1 , val_len ) NEW_LINE full = 0 NEW_LINE half = 0 NEW_LINE if ( weight [ index ] <= weight1 ) : NEW_LINE INDENT full = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] , flag , K , index + 1 , val_len ) NEW_LINE DEDENT if ( weight [ index ] \/ 2 <= weight1 ) : NEW_LINE INDENT half = value [ index ] + maximum ( value , weight , weight1 - weight [ index ] \/ 2 , flag , K , index + 1 , val_len ) NEW_LINE DEDENT return max ( full , max ( skip , half ) ) NEW_LINE DEDENT DEDENT value = [ 17 , 20 , 10 , 15 ] NEW_LINE weight = [ 4 , 2 , 7 , 5 ] NEW_LINE K = 1 NEW_LINE W = 4 NEW_LINE val_len = len ( value ) NEW_LINE print ( maximum ( value , weight , W , 0 , K , 0 , val_len ) ) NEW_LINE"} {"text":"d | Python3 program to find the size of the minimum dominating set of the tree ; Definition of a tree node ; Helper function that allocates a new node ; DP array to precompute and store the results ; minDominatingSettion to return the size of the minimum dominating set of the array ; Base case ; Setting the compulsory value if needed ; Check if the answer is already computed ; If it is compulsory to select the node ; Choose the node and set its children as covered ; If it is covered ; If the current node is neither covered nor needs to be selected compulsorily ; Store the result ; Driver code ; Constructing the tree","code":"N = 1005 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT node = Node ( data ) NEW_LINE return node NEW_LINE DEDENT dp = [ [ [ - 1 for i in range ( 5 ) ] for j in range ( 5 ) ] for k in range ( N ) ] ; NEW_LINE def minDominatingSet ( root , covered , compulsory ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( not root . left and not root . right and not covered ) : NEW_LINE INDENT compulsory = True ; NEW_LINE DEDENT if ( dp [ root . data ] [ covered ] [ compulsory ] != - 1 ) : NEW_LINE INDENT return dp [ root . data ] [ covered ] [ compulsory ] ; NEW_LINE DEDENT if ( compulsory ) : NEW_LINE INDENT dp [ root . data ] [ covered ] [ compulsory ] = 1 + minDominatingSet ( root . left , 1 , 0 ) + minDominatingSet ( root . right , 1 , 0 ) ; NEW_LINE return dp [ root . data ] [ covered ] [ compulsory ] NEW_LINE DEDENT if ( covered ) : NEW_LINE INDENT dp [ root . data ] [ covered ] [ compulsory ] = min ( 1 + minDominatingSet ( root . left , 1 , 0 ) + minDominatingSet ( root . right , 1 , 0 ) , minDominatingSet ( root . left , 0 , 0 ) + minDominatingSet ( root . right , 0 , 0 ) ) ; NEW_LINE return dp [ root . data ] [ covered ] [ compulsory ] NEW_LINE DEDENT ans = 1 + minDominatingSet ( root . left , 1 , 0 ) + minDominatingSet ( root . right , 1 , 0 ) ; NEW_LINE if ( root . left ) : NEW_LINE INDENT ans = min ( ans , minDominatingSet ( root . left , 0 , 1 ) + minDominatingSet ( root . right , 0 , 0 ) ) ; NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT ans = min ( ans , minDominatingSet ( root . left , 0 , 0 ) + minDominatingSet ( root . right , 0 , 1 ) ) ; NEW_LINE DEDENT dp [ root . data ] [ covered ] [ compulsory ] = ans ; NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) ; NEW_LINE root . left = newNode ( 2 ) ; NEW_LINE root . left . left = newNode ( 3 ) ; NEW_LINE root . left . right = newNode ( 4 ) ; NEW_LINE root . left . left . left = newNode ( 5 ) ; NEW_LINE root . left . left . left . left = newNode ( 6 ) ; NEW_LINE root . left . left . left . right = newNode ( 7 ) ; NEW_LINE root . left . left . left . right . right = newNode ( 10 ) ; NEW_LINE root . left . left . left . left . left = newNode ( 8 ) ; NEW_LINE root . left . left . left . left . right = newNode ( 9 ) ; NEW_LINE print ( minDominatingSet ( root , 0 , 0 ) ) NEW_LINE DEDENT"} {"text":"Number of subsets with zero sum | Python3 implementation of above approach ; variable to store states of dp ; To find the number of subsets with sum equal to 0. Since S can be negative , we will maxSum to it to make it positive ; Base cases ; Returns the value if a state is already solved ; If the state is not visited , then continue ; Recurrence relation ; Returning the value ; Driver Code","code":"import numpy as np NEW_LINE maxSum = 100 NEW_LINE arrSize = 51 NEW_LINE dp = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE visit = np . zeros ( ( arrSize , maxSum ) ) ; NEW_LINE def SubsetCnt ( i , s , arr , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( s == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( visit [ i ] [ s + arrSize ] ) : NEW_LINE INDENT return dp [ i ] [ s + arrSize ] ; NEW_LINE DEDENT visit [ i ] [ s + arrSize ] = 1 ; NEW_LINE dp [ i ] [ s + arrSize ] = ( SubsetCnt ( i + 1 , s + arr [ i ] , arr , n ) + SubsetCnt ( i + 1 , s , arr , n ) ) ; NEW_LINE return dp [ i ] [ s + arrSize ] ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 2 , 2 , - 4 , - 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( SubsetCnt ( 0 , 0 , arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Tetranacci Numbers | Function to print the N - th tetranacci number ; Initialize first four numbers to base cases ; declare a current variable ; Loop to add previous four numbers for each number starting from 4 and then assign first , second , third to second , third , fourth and curr to fourth respectively ; Driver code","code":"def printTetra ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT return ; NEW_LINE DEDENT first = 0 ; NEW_LINE second = 1 ; NEW_LINE third = 1 ; NEW_LINE fourth = 2 ; NEW_LINE curr = 0 ; NEW_LINE if ( n == 0 ) : NEW_LINE INDENT print ( first ) ; NEW_LINE DEDENT elif ( n == 1 or n == 2 ) : NEW_LINE INDENT print ( second ) ; NEW_LINE DEDENT elif ( n == 3 ) : NEW_LINE INDENT print ( fourth ) ; NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 4 , n + 1 ) : NEW_LINE INDENT curr = first + second + third + fourth ; NEW_LINE first = second ; NEW_LINE second = third ; NEW_LINE third = fourth ; NEW_LINE fourth = curr ; NEW_LINE DEDENT DEDENT print ( curr ) ; NEW_LINE DEDENT n = 10 ; NEW_LINE printTetra ( n ) ; NEW_LINE"} {"text":"Count ways to reach the nth stair using step 1 , 2 or 3 | A recursive function used by countWays ; Driver code","code":"def countWays ( n ) : NEW_LINE INDENT res = [ 0 ] * ( n + 2 ) NEW_LINE res [ 0 ] = 1 NEW_LINE res [ 1 ] = 1 NEW_LINE res [ 2 ] = 2 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT res [ i ] = res [ i - 1 ] + res [ i - 2 ] + res [ i - 3 ] NEW_LINE DEDENT return res [ n ] NEW_LINE DEDENT n = 4 NEW_LINE print ( countWays ( n ) ) NEW_LINE"} {"text":"Count ways to reach the nth stair using step 1 , 2 or 3 | A recursive function used by countWays ; declaring three variables and holding the ways for first three stairs ; d = 0 fourth variable ; starting from 4 as already counted for 3 stairs ; Driver program to test above functions","code":"def countWays ( n ) : NEW_LINE INDENT a = 1 NEW_LINE b = 2 NEW_LINE c = 4 NEW_LINE if ( n == 0 or n == 1 or n == 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( n == 3 ) : NEW_LINE INDENT return c NEW_LINE DEDENT for i in range ( 4 , n + 1 ) : NEW_LINE INDENT d = c + b + a NEW_LINE a = b NEW_LINE b = c NEW_LINE c = d NEW_LINE DEDENT return d NEW_LINE DEDENT n = 4 NEW_LINE print ( countWays ( n ) ) NEW_LINE"} {"text":"Subset Sum Problem in O ( sum ) space | ; initializing with 1 as sum 0 is always possible ; loop to go through every element of the elements array ; to change the value o all possible sum values to True ; If target is possible return True else False ; Driver code","code":"def isPossible ( elements , target ) : NEW_LINE INDENT dp = [ False ] * ( target + 1 ) NEW_LINE dp [ 0 ] = True NEW_LINE for ele in elements : NEW_LINE INDENT for j in range ( target , ele - 1 , - 1 ) : NEW_LINE INDENT if dp [ j - ele ] : NEW_LINE INDENT dp [ j ] = True NEW_LINE DEDENT DEDENT DEDENT return dp [ target ] NEW_LINE DEDENT arr = [ 6 , 2 , 5 ] NEW_LINE target = 7 NEW_LINE if isPossible ( arr , target ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT"} {"text":"Dynamic Programming | High | Returns maximum amount of task that can be done till day n ; If n is less than equal to 0 , then no solution exists ; Determines which task to choose on day n , then returns the maximum till that day ; Driver Code","code":"def maxTasks ( high , low , n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max ( high [ n - 1 ] + maxTasks ( high , low , ( n - 2 ) ) , low [ n - 1 ] + maxTasks ( high , low , ( n - 1 ) ) ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 5 ; NEW_LINE high = [ 3 , 6 , 8 , 7 , 6 ] NEW_LINE low = [ 1 , 5 , 4 , 5 , 3 ] NEW_LINE print ( maxTasks ( high , low , n ) ) ; NEW_LINE DEDENT"} {"text":"Kth character after replacing each character of String by its frequency exactly X times | Python3 program for the above approach ; Function to find the Kth character after X days ; Variable to store the KthChar ; Traverse the string ; Convert char into int ; Calculate characters ; If K is less than sum than ans = str [ i ] ; Return answer ; Given Input ; Function Call","code":"import math NEW_LINE def FindKthChar ( Str , K , X ) : NEW_LINE INDENT ans = ' \u2581 ' NEW_LINE Sum = 0 NEW_LINE for i in range ( len ( Str ) ) : NEW_LINE INDENT digit = ord ( Str [ i ] ) - 48 NEW_LINE Range = int ( math . pow ( digit , X ) ) NEW_LINE Sum += Range NEW_LINE if ( K <= Sum ) : NEW_LINE INDENT ans = Str [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT Str = \"123\" NEW_LINE K = 9 NEW_LINE X = 3 NEW_LINE ans = FindKthChar ( Str , K , X ) NEW_LINE print ( ans ) NEW_LINE"} {"text":"Total character pairs from two strings , with equal number of set bits in their ascii value | Function to get no of set bits in binary representation of positive integer n ; Function to return the count of valid pairs ; Store frequency of number of set bits for s1 ; Store frequency of number of set bits for s2 ; Calculate total pairs ; Return the count of valid pairs ; Driver code","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 def totalPairs ( s1 , s2 ) : NEW_LINE INDENT count = 0 ; NEW_LINE arr1 = [ 0 ] * 7 ; arr2 = [ 0 ] * 7 ; NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT set_bits = countSetBits ( ord ( s1 [ i ] ) ) NEW_LINE arr1 [ set_bits ] += 1 ; NEW_LINE DEDENT for i in range ( len ( s2 ) ) : NEW_LINE INDENT set_bits = countSetBits ( ord ( s2 [ i ] ) ) ; NEW_LINE arr2 [ set_bits ] += 1 ; NEW_LINE DEDENT for i in range ( 1 , 7 ) : NEW_LINE INDENT count += ( arr1 [ i ] * arr2 [ i ] ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s1 = \" geeks \" ; NEW_LINE s2 = \" forgeeks \" ; NEW_LINE print ( totalPairs ( s1 , s2 ) ) ; NEW_LINE DEDENT"} {"text":"Count words in a given string | Python3 program to count words in a given string ; Returns number of words in string ; word count ; Scan all characters one by one ; If next character is a separator , set the state as OUT ; If next character is not a word separator and state is OUT , then set the state as IN and increment word count ; Return the number of words ; Driver Code","code":"OUT = 0 NEW_LINE IN = 1 NEW_LINE def countWords ( string ) : NEW_LINE INDENT state = OUT NEW_LINE wc = 0 NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ' \u2581 ' or string [ i ] == ' ' \u2581 or \u2581 string [ i ] \u2581 = = \u2581 ' \t ' ) : NEW_LINE INDENT state = OUT NEW_LINE DEDENT elif state == OUT : NEW_LINE INDENT state = IN NEW_LINE wc += 1 NEW_LINE DEDENT DEDENT return wc NEW_LINE DEDENT string = \" One two three NEW_LINE INDENT four five \" NEW_LINE DEDENT print ( \" No . \u2581 of \u2581 words \u2581 : \u2581 \" + str ( countWords ( string ) ) ) NEW_LINE"} {"text":"Enneadecagonal number | Function to find nth Enneadecagonal number ; Formula to calculate nth Enneadecagonal number ; Driver Code","code":"def nthEnneadecagonal ( n ) : NEW_LINE INDENT return ( 17 * n * n - 15 * n ) \/\/ 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE print ( n , \" th \u2581 Enneadecagonal \u2581 number \u2581 : \" , nthEnneadecagonal ( n ) ) NEW_LINE DEDENT"} {"text":"Area of a Circumscribed Circle of a Square | Python3 Program to find the area of a circumscribed circle ; Utility Function ; Driver code","code":"PI = 3.14159265 NEW_LINE def areacircumscribed ( a ) : NEW_LINE INDENT return ( a * a * ( PI \/ 2 ) ) NEW_LINE DEDENT a = 6 NEW_LINE print ( \" \u2581 Area \u2581 of \u2581 an \u2581 circumscribed \u2581 circle \u2581 is \u2581 : \" , round ( areacircumscribed ( a ) , 2 ) ) NEW_LINE"} {"text":"Find Nth item distributed from infinite items of infinite types based on given conditions | Function to find the type of the item given out according to the given rules ; Stores the count of item given out at each step ; Iterate to find the Nth day present is given out ; Find the number of presents given on day is day * ( day + 1 ) \/ 2 ; Iterate over the type ; Return the resultant type ; Driver Code","code":"def itemType ( n ) : NEW_LINE INDENT count = 0 NEW_LINE day = 1 NEW_LINE while ( count + day * ( day + 1 ) \/\/ 2 < n ) : NEW_LINE INDENT count += day * ( day + 1 ) \/\/ 2 ; NEW_LINE day += 1 NEW_LINE DEDENT type = day NEW_LINE while ( type > 0 ) : NEW_LINE INDENT count += type NEW_LINE if ( count >= n ) : NEW_LINE INDENT return type NEW_LINE DEDENT type -= 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 10 NEW_LINE print ( itemType ( N ) ) NEW_LINE DEDENT"} {"text":"Check if linked list is sorted ( Iterative and Recursive ) | Linked list Node ; function to Check Linked List is sorted in descending order or not ; Traverse the list till last Node and return False if a Node is smaller than or equal its next . ; Driver Code","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data ; NEW_LINE self . next = next ; NEW_LINE DEDENT DEDENT def isSortedDesc ( head ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT while ( head . next != None ) : NEW_LINE INDENT t = head ; NEW_LINE if ( t . data <= t . next . data ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT head = head . next NEW_LINE DEDENT return True ; NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( 0 ) ; NEW_LINE temp . next = None ; NEW_LINE temp . data = data ; NEW_LINE return temp ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = newNode ( 7 ) ; NEW_LINE head . next = newNode ( 5 ) ; NEW_LINE head . next . next = newNode ( 4 ) ; NEW_LINE head . next . next . next = newNode ( 3 ) ; NEW_LINE if ( isSortedDesc ( head ) ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT DEDENT"} {"text":"Maximum length of consecutive 1 s or 0 s after flipping at most K characters | Function to find the maximum length continuos segment of character c after flipping at most K characters ; Stores the maximum length ; Stores the count of char 'c ; Start of window ; Remove the extra ' c ' from left ; Increment the value of the left ; Update the resultant maximum length of character ch ; Function to find the maximum length of consecutive 0 s or 1 s by flipping at most K characters of the string ; Print the maximum of the maximum length of 0 s or 1 s ; Driver Code","code":"def maxLength ( str , n , c , k ) : NEW_LINE INDENT ans = - 1 NEW_LINE DEDENT ' NEW_LINE INDENT cnt = 0 NEW_LINE left = 0 NEW_LINE for right in range ( 0 , n ) : NEW_LINE INDENT if ( str [ right ] == c ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT while ( cnt > k ) : NEW_LINE INDENT if ( str [ left ] == c ) : NEW_LINE INDENT cnt -= 1 NEW_LINE DEDENT left += 1 NEW_LINE DEDENT ans = max ( ans , right - left + 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def maxConsecutiveSegment ( S , K ) : NEW_LINE INDENT N = len ( S ) NEW_LINE return max ( maxLength ( S , N , '0' , K ) , maxLength ( S , N , '1' , K ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S = \"1001\" NEW_LINE K = 1 NEW_LINE print ( maxConsecutiveSegment ( S , K ) ) NEW_LINE DEDENT"} {"text":"Minimize coins required to obtain all possible values up to N | Function to find minimum count of { 1 , 2 , 5 } valued coins required to make a change of all values in the range [ 1 , N ] ; Number of 5 valueds coins required ; Number of 1 valued coins required ; Number of 2 valued coins required ; Driver Code","code":"def find ( N ) : NEW_LINE INDENT F = int ( ( N - 4 ) \/ 5 ) NEW_LINE if ( ( N - 5 * F ) % 2 ) == 0 : NEW_LINE INDENT O = 2 NEW_LINE DEDENT else : NEW_LINE INDENT O = 1 NEW_LINE DEDENT T = ( N - 5 * F - O ) \/\/ 2 NEW_LINE print ( \" Count \u2581 of \u2581 5 \u2581 valueds \u2581 coins : \u2581 \" , F ) NEW_LINE print ( \" Count \u2581 of \u2581 2 \u2581 valueds \u2581 coins : \u2581 \" , T ) NEW_LINE print ( \" Count \u2581 of \u2581 1 \u2581 valueds \u2581 coins : \u2581 \" , O ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE find ( N ) NEW_LINE DEDENT"} {"text":"Check if given string is a substring of string formed by repeated concatenation of z to a | Function checks if a given is valid or not and prints the output ; Boolean flag variable to mark if given is valid ; Traverse the given string ; If adjacent character differ by 1 ; If character ' a ' is followed by 4 ; Else flip the flag and break from the loop ; Output according to flag variable ; Driver Code ; Given string ; Function Call","code":"def checkInfinite ( s ) : NEW_LINE INDENT flag = 1 NEW_LINE N = len ( s ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( s [ i ] == chr ( ord ( s [ i + 1 ] ) + 1 ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( s [ i ] == ' a ' and s [ i + 1 ] == ' z ' ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" ecbaz \" NEW_LINE checkInfinite ( s ) NEW_LINE DEDENT"} {"text":"Minimum change in lanes required to cross all barriers | Function to find the minimum number of changes of lane required ; If there is a barrier , then add very large value ; Add the minimum value to move forword with or without crossing barrier ; Return the minimum value of dp [ 0 ] , dp [ 1 ] and dp [ 2 ] ; Driver Code","code":"def minChangeInLane ( barrier , n ) : NEW_LINE INDENT dp = [ 1 , 0 , 1 ] NEW_LINE for j in range ( n ) : NEW_LINE INDENT val = barrier [ j ] NEW_LINE if ( val > 0 ) : NEW_LINE INDENT dp [ val - 1 ] = 1000000 NEW_LINE DEDENT for i in range ( 3 ) : NEW_LINE INDENT if ( val != i + 1 ) : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , min ( dp [ ( i + 1 ) % 3 ] , dp [ ( i + 2 ) % 3 ] ) + 1 ) NEW_LINE DEDENT DEDENT DEDENT return min ( dp [ 0 ] , min ( dp [ 1 ] , dp [ 2 ] ) ) NEW_LINE DEDENT barrier = [ 0 , 1 , 2 , 3 , 0 ] NEW_LINE N = len ( barrier ) NEW_LINE print ( minChangeInLane ( barrier , N ) ) NEW_LINE"} {"text":"Queries to count groups of N students possible having sum of ratings within given range | Function to count number of ways to get given sum groups ; Initialise dp array ; Mark all 1 st row values as 1 since the mat [ 0 ] [ i ] is all possible sums in first row ; Fix the ith row ; Fix the sum ; Iterate through all values of ith row ; If sum can be obtained ; Find the prefix sum of last row ; Traverse each query ; No of ways to form groups ; Driver Code ; Given N batches and K students ; Given ratings ; Function Call","code":"def numWays ( ratings , queries , n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 10002 ) ] for j in range ( n ) ] ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT dp [ 0 ] [ ratings [ 0 ] [ i ] ] += 1 ; NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for sum in range ( 10001 ) : NEW_LINE INDENT for j in range ( k ) : NEW_LINE INDENT if ( sum >= ratings [ i ] [ j ] ) : NEW_LINE INDENT dp [ i ] [ sum ] += dp [ i - 1 ] [ sum - ratings [ i ] [ j ] ] ; NEW_LINE DEDENT DEDENT DEDENT DEDENT for sum in range ( 1 , 10001 ) : NEW_LINE INDENT dp [ n - 1 ] [ sum ] += dp [ n - 1 ] [ sum - 1 ] ; NEW_LINE DEDENT for q in range ( len ( queries ) ) : NEW_LINE INDENT a = queries [ q ] [ 0 ] ; NEW_LINE b = queries [ q ] [ 1 ] ; NEW_LINE print ( dp [ n - 1 ] [ b ] - dp [ n - 1 ] [ a - 1 ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 ; NEW_LINE K = 3 ; NEW_LINE ratings = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ; NEW_LINE queries = [ [ 6 , 6 ] , [ 1 , 6 ] ] ; NEW_LINE numWays ( ratings , queries , N , K ) ; NEW_LINE DEDENT"} {"text":"Number of permutation with K inversions | Set 2 | Function to count permutations with K inversions ; Store number of permutations with K inversions ; If N = 1 only 1 permutation with no inversion ; For K = 0 only 1 permutation with no inversion ; Otherwise Update each dp state as per the reccurrance relation formed ; Print final count ; Driver Code ; Given N and K ; Function Call","code":"def numberOfPermWithKInversion ( N , K ) : NEW_LINE INDENT dp = [ [ 0 ] * ( K + 1 ) ] * 2 NEW_LINE mod = 1000000007 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 0 , K + 1 ) : NEW_LINE INDENT if ( i == 1 ) : NEW_LINE INDENT dp [ i % 2 ] [ j ] = 1 if ( j == 0 ) else 0 NEW_LINE DEDENT elif ( j == 0 ) : NEW_LINE INDENT dp [ i % 2 ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT var = ( 0 if ( max ( j - ( i - 1 ) , 0 ) == 0 ) else dp [ 1 - i % 2 ] [ max ( j - ( i - 1 ) , 0 ) - 1 ] ) NEW_LINE dp [ i % 2 ] [ j ] = ( ( dp [ i % 2 ] [ j - 1 ] % mod + ( dp [ 1 - i % 2 ] [ j ] - ( var ) + mod ) % mod ) % mod ) NEW_LINE DEDENT DEDENT DEDENT print ( dp [ N % 2 ] [ K ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 2 NEW_LINE numberOfPermWithKInversion ( N , K ) NEW_LINE DEDENT"} {"text":"Treasure and Cities | k is current index and col is previous color . ; base case ; check if color of this city is equal to prev visited city ; return max of both options ; Driver Code ; Initially begin with color 0","code":"def MaxProfit ( treasure , color , n , k , col , A , B ) : NEW_LINE INDENT sum = 0 NEW_LINE if k == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if col == color [ k ] : NEW_LINE INDENT sum += max ( A * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) NEW_LINE DEDENT else : NEW_LINE INDENT sum += max ( B * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) NEW_LINE DEDENT return sum NEW_LINE DEDENT A = - 5 NEW_LINE B = 7 NEW_LINE treasure = [ 4 , 8 , 2 , 9 ] NEW_LINE color = [ 2 , 2 , 6 , 2 ] NEW_LINE n = len ( color ) NEW_LINE print ( MaxProfit ( treasure , color , n , 0 , 0 , A , B ) ) NEW_LINE"} {"text":"Tetranacci Numbers | Function to return the N - th tetranacci number ; base cases ; base cases ; base cases ; function to print the nth tetranacci number ; Driver code","code":"def printTetraRec ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( n == 1 or n == 2 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( n == 3 ) : NEW_LINE INDENT return 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT return ( printTetraRec ( n - 1 ) + printTetraRec ( n - 2 ) + printTetraRec ( n - 3 ) + printTetraRec ( n - 4 ) ) ; NEW_LINE DEDENT DEDENT def printTetra ( n ) : NEW_LINE INDENT print ( printTetraRec ( n ) , end = \" \u2581 \" ) ; NEW_LINE DEDENT n = 10 ; NEW_LINE printTetra ( n ) ; NEW_LINE"} {"text":"Sum of products of all combination taken ( 1 to n ) at a time | to store sum of every combination ; if we have reached sufficient depth ; find the product of combination ; add the product into sum ; recursion to produce different combination ; function to print sum of products of all combination taken 1 - N at a time ; creating temporary array for storing combination ; call combination with r = i for combination taken i at a time ; displaying sum ; Driver Code ; storing numbers from 1 - N in array ; calling allCombination","code":"def Combination ( a , combi , n , r , depth , index ) : NEW_LINE INDENT global Sum NEW_LINE if index == r : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( r ) : NEW_LINE INDENT product = product * combi [ i ] NEW_LINE DEDENT Sum += product NEW_LINE return NEW_LINE DEDENT for i in range ( depth , n ) : NEW_LINE INDENT combi [ index ] = a [ i ] NEW_LINE Combination ( a , combi , n , r , i + 1 , index + 1 ) NEW_LINE DEDENT DEDENT def allCombination ( a , n ) : NEW_LINE INDENT global Sum NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT combi = [ 0 ] * i NEW_LINE Combination ( a , combi , n , i , 0 , 0 ) NEW_LINE print ( \" f ( \" , i , \" ) \u2581 - - > \u2581 \" , Sum ) NEW_LINE Sum = 0 NEW_LINE DEDENT DEDENT Sum = 0 NEW_LINE n = 5 NEW_LINE a = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = i + 1 NEW_LINE DEDENT allCombination ( a , n ) NEW_LINE"} {"text":"Dynamic Programming | High | ; Returns maximum amount of task that can be done till day n ; An array task_dp that stores the maximum task done ; If n = 0 , no solution exists ; If n = 1 , high effort task on that day will be the solution ; Fill the entire array determining which task to choose on day i ; Driver code","code":"\/ * Returns the maximum among the 2 numbers * \/ NEW_LINE def max1 ( x , y ) : NEW_LINE INDENT return x if ( x > y ) else y ; NEW_LINE DEDENT def maxTasks ( high , low , n ) : NEW_LINE INDENT task_dp = [ 0 ] * ( n + 1 ) ; NEW_LINE task_dp [ 0 ] = 0 ; NEW_LINE task_dp [ 1 ] = high [ 0 ] ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT task_dp [ i ] = max ( high [ i - 1 ] + task_dp [ i - 2 ] , low [ i - 1 ] + task_dp [ i - 1 ] ) ; NEW_LINE DEDENT return task_dp [ n ] ; NEW_LINE DEDENT n = 5 ; NEW_LINE high = [ 3 , 6 , 8 , 7 , 6 ] ; NEW_LINE low = [ 1 , 5 , 4 , 5 , 3 ] ; NEW_LINE print ( maxTasks ( high , low , n ) ) ; NEW_LINE"} {"text":"Partition problem | DP | Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; calculate sum of all elements ; initialize top row as true ; initialize leftmost column , except part [ 0 ] [ 0 ] , as 0 ; fill the partition table in bottom up manner ; uncomment this part to print table ; Driver Code ; Function call","code":"def findPartition ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE i , j = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if sum % 2 != 0 : NEW_LINE INDENT return false NEW_LINE DEDENT part = [ [ True for i in range ( n + 1 ) ] for j in range ( sum \/\/ 2 + 1 ) ] NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT part [ 0 ] [ i ] = True NEW_LINE DEDENT for i in range ( 1 , sum \/\/ 2 + 1 ) : NEW_LINE INDENT part [ i ] [ 0 ] = False NEW_LINE DEDENT for i in range ( 1 , sum \/\/ 2 + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT part [ i ] [ j ] = part [ i ] [ j - 1 ] NEW_LINE if i >= arr [ j - 1 ] : NEW_LINE INDENT part [ i ] [ j ] = ( part [ i ] [ j ] or part [ i - arr [ j - 1 ] ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return part [ sum \/\/ 2 ] [ n ] NEW_LINE DEDENT arr = [ 3 , 1 , 1 , 2 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE if findPartition ( arr , n ) == True : NEW_LINE INDENT print ( \" Can \u2581 be \u2581 divided \u2581 into \u2581 two \" , \" subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Can \u2581 not \u2581 be \u2581 divided \u2581 into \u2581 \" , \" two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Minimum number of Appends of X or Y characters from the end to the front required to obtain given string | Function to find the minimum operations required to get the given string after appending m or n characters from the end to the front of the string in each operation ; Store the original string ; Stores the count of operations ; Traverse the string ; Cut m letters from end ; Add cut m letters to beginning ; Update j ; Check if strings are the same ; Cut n letters from end ; Add cut n letters to beginning ; Update j ; Check if strings are the same ; Update the turn ; Given string S ; Function Call","code":"def minimumOperations ( orig_str , m , n ) : NEW_LINE INDENT orig = orig_str NEW_LINE turn = 1 NEW_LINE j = 1 NEW_LINE for i in orig_str : NEW_LINE INDENT m_cut = orig_str [ - m : ] NEW_LINE orig_str = orig_str . replace ( ' \u2581 ' , ' ' ) [ : - m ] NEW_LINE orig_str = m_cut + orig_str NEW_LINE j = j + 1 NEW_LINE if orig != orig_str : NEW_LINE INDENT turn = turn + 1 NEW_LINE n_cut = orig_str [ - n : ] NEW_LINE orig_str = orig_str . replace ( ' \u2581 ' , ' ' ) [ : - n ] NEW_LINE orig_str = n_cut + orig_str NEW_LINE j = j + 1 NEW_LINE DEDENT if orig == orig_str : NEW_LINE INDENT break NEW_LINE DEDENT turn = turn + 1 NEW_LINE DEDENT print ( turn ) NEW_LINE DEDENT S = \" GeeksforGeeks \" NEW_LINE X = 5 NEW_LINE Y = 3 NEW_LINE minimumOperations ( S , X , Y ) NEW_LINE"} {"text":"Minimum rotations required to get the same String | Set | Prints occurrences of txt [ ] in pat [ ] ; Create lps [ ] that will hold the longest prefix suffix values for pattern ; Preprocess the pattern ( calculate lps [ ] array ) ; Index for txt [ ] , index for pat [ ] ; Mismatch after j matches ; Do not match lps [ 0. . lps [ j - 1 ] ] characters , they will match anyway ; Fills lps [ ] for given pattern pat [ 0. . M - 1 ] ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; The loop calculates lps [ i ] for i = 1 to M - 1 ; ( pat [ i ] != pat [ _len ] ) ; This is tricky . Consider the example . AAACAAAA and i = 7. The idea is similar to search step . ; Returns count of rotations to get the same string back ; Form a string excluding the first character and concatenating the string at the end ; Convert the string to character array ; Use the KMP search algorithm to find it in O ( N ) time ; Driver code","code":"def KMPSearch ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE lps = [ 0 ] * M NEW_LINE computeLPSArray ( pat , M , lps ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while i < N : NEW_LINE INDENT if pat [ j ] == txt [ i ] : NEW_LINE INDENT j += 1 NEW_LINE i += 1 NEW_LINE DEDENT if j == M : NEW_LINE INDENT return i - j NEW_LINE j = lps [ j - 1 ] NEW_LINE DEDENT elif i < N and pat [ j ] != txt [ i ] : NEW_LINE INDENT if j != 0 : NEW_LINE INDENT j = lps [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def computeLPSArray ( pat , M , lps ) : NEW_LINE INDENT _len = 0 NEW_LINE lps [ 0 ] = 0 NEW_LINE i = 1 NEW_LINE while i < M : NEW_LINE INDENT if pat [ i ] == pat [ _len ] : NEW_LINE INDENT _len += 1 NEW_LINE lps [ i ] = _len NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if _len != 0 : NEW_LINE INDENT _len = lps [ _len - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lps [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def countRotations ( s ) : NEW_LINE INDENT s1 = s [ 1 : len ( s ) ] + s NEW_LINE pat = s [ : ] NEW_LINE text = s1 [ : ] NEW_LINE return 1 + KMPSearch ( pat , text ) NEW_LINE DEDENT s1 = \" geeks \" NEW_LINE print ( countRotations ( s1 ) ) NEW_LINE"} {"text":"DFA for Strings not ending with \" THE \" | This function is for the starting state ( zeroth ) of DFA ; On receiving ' T ' or ' t ' goto first state ( 1 ) ; This function is for the first state of DFA ; On receiving ' T ' or ' t ' goto first state ( 1 ) ; On receiving ' H ' or ' h ' goto second state ( 2 ) ; else goto starting state ( 0 ) ; This function is for the second state of DFA ; On receiving ' E ' or ' e ' goto third state ( 3 ) else goto starting state ( 0 ) ; This function is for the third state of DFA ; On receiving ' T ' or ' t ' goto first state ( 1 ) else goto starting state ( 0 ) ; store length of stringing ; Driver Code","code":"def start ( c ) : NEW_LINE INDENT if ( c == ' t ' or c == ' T ' ) : NEW_LINE INDENT dfa = 1 NEW_LINE DEDENT DEDENT def state1 ( c ) : NEW_LINE INDENT if ( c == ' t ' or c == ' T ' ) : NEW_LINE INDENT dfa = 1 NEW_LINE DEDENT elif ( c == ' h ' or c == ' H ' ) : NEW_LINE INDENT dfa = 2 NEW_LINE DEDENT else : NEW_LINE INDENT dfa = 0 NEW_LINE DEDENT DEDENT def state2 ( c ) : NEW_LINE INDENT if ( c == ' e ' or c == ' E ' ) : NEW_LINE INDENT dfa = 3 NEW_LINE DEDENT else : NEW_LINE INDENT dfa = 0 NEW_LINE DEDENT DEDENT def state3 ( c ) : NEW_LINE INDENT if ( c == ' t ' or c == ' T ' ) : NEW_LINE INDENT dfa = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dfa = 0 NEW_LINE DEDENT DEDENT def isAccepted ( string ) : NEW_LINE INDENT length = len ( string ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( dfa == 0 ) : NEW_LINE INDENT start ( string [ i ] ) NEW_LINE DEDENT elif ( dfa == 1 ) : NEW_LINE INDENT state1 ( string [ i ] ) NEW_LINE DEDENT elif ( dfa == 2 ) : NEW_LINE INDENT state2 ( string [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT state3 ( string [ i ] ) NEW_LINE DEDENT DEDENT return ( dfa != 3 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" forTHEgeeks \" NEW_LINE DEDENT dfa = 0 NEW_LINE INDENT if isAccepted ( string ) : NEW_LINE INDENT print ( \" ACCEPTED \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NOT \u2581 ACCEPTED \" ) NEW_LINE DEDENT DEDENT"} {"text":"Check if one string can be converted to another | Python3 implementation of the above approach . ; Function for find from Disjoset algorithm ; Function for the union from Disjoset algorithm ; Function to check if one string can be converted to another . ; All the characters are checked whether it 's either not replaced or replaced by a similar character using a map. ; To check if there are cycles . If yes , then they are not convertible . Else , they are convertible . ; Function to initialize parent array for union and find algorithm . ; Driver code","code":"parent = [ 0 ] * 256 NEW_LINE def find ( x ) : NEW_LINE INDENT if ( x != parent [ x ] ) : NEW_LINE INDENT parent [ x ] = find ( parent [ x ] ) NEW_LINE return parent [ x ] NEW_LINE DEDENT return x NEW_LINE DEDENT def join ( x , y ) : NEW_LINE INDENT px = find ( x ) NEW_LINE pz = find ( y ) NEW_LINE if ( px != pz ) : NEW_LINE INDENT parent [ pz ] = px NEW_LINE DEDENT DEDENT def convertible ( s1 , s2 ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] in mp ) : NEW_LINE INDENT mp [ s1 [ i ] ] = s2 [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT if s1 [ i ] in mp and mp [ s1 [ i ] ] != s2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT for it in mp : NEW_LINE INDENT if ( it == mp [ it ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( find ( ord ( it ) ) == find ( ord ( it ) ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT join ( ord ( it ) , ord ( it ) ) NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def initialize ( ) : NEW_LINE INDENT for i in range ( 256 ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE DEDENT DEDENT s1 = \" abbcaa \" NEW_LINE s2 = \" bccdbb \" NEW_LINE initialize ( ) NEW_LINE if ( convertible ( s1 , s2 ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} {"text":"Print characters having prime frequencies in order of occurrence | Python 3 implementation of the approach ; 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 print the prime frequency characters in the order of their occurrence ; Function to create Sieve to check primes ; To store the frequency of each of the character of the string ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is prime ; Driver code","code":"SIZE = 26 NEW_LINE from math import sqrt NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( p_size ) ) , 1 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def printChar ( str , n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE SieveOfEratosthenes ( prime , len ( str ) + 1 ) NEW_LINE freq = [ 0 for i in range ( SIZE ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( prime [ freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] ] ) : NEW_LINE INDENT print ( str [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" geeksforgeeks \" NEW_LINE n = len ( str ) NEW_LINE printChar ( str , n ) NEW_LINE DEDENT"} {"text":"Print characters having prime frequencies in order of occurrence | Python code for the above approach ; Function to check primes ; Counting the frequency of all character using Counter function ; Traversing string ; Driver code ; passing string to checkString function","code":"from collections import Counter NEW_LINE import math NEW_LINE def prime ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT max_div = math . floor ( math . sqrt ( n ) ) NEW_LINE for i in range ( 2 , 1 + max_div ) : NEW_LINE INDENT if n % i == 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def checkString ( s ) : NEW_LINE INDENT freq = Counter ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if prime ( freq [ s [ i ] ] ) : NEW_LINE INDENT print ( s [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT s = \" geeksforgeeks \" NEW_LINE checkString ( s ) NEW_LINE"} {"text":"Print characters having even frequencies in order of occurrence | Python3 implementation of the approach ; Function to print the even frequency characters in the order of their occurrence ; To store the frequency of each of the character of the stringing Initialize all elements of freq [ ] to 0 ; Update the frequency of each character ; Traverse string character by character ; If frequency of current character is even ; Driver code","code":"SIZE = 26 NEW_LINE def printChar ( string , n ) : NEW_LINE INDENT freq = [ 0 ] * SIZE NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( freq [ ord ( string [ i ] ) - ord ( ' a ' ) ] % 2 == 0 ) : NEW_LINE INDENT print ( string [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT string = \" geeksforgeeks \" NEW_LINE n = len ( string ) NEW_LINE printChar ( string , n ) NEW_LINE DEDENT"} {"text":"Compare two strings considering only alphanumeric characters | Function to check alphanumeric equality of both strings ; variable declaration ; Length of first string ; Length of second string ; To check each and every character of both string ; If the current character of the first string is not an alphanumeric character , increase the pointer i ; If the current character of the second string is not an alphanumeric character , increase the pointer j ; if all alphanumeric characters of both strings are same , then return true ; if any alphanumeric characters of both strings are not same , then return false ; If current character matched , increase both pointers to check the next character ; If not same , then return false ; Function to print Equal or Unequal if strings are same or not ; check alphanumeric equality of both strings ; if both are alphanumeric equal , print Equal ; otherwise print Unequal ; Driver code","code":"def CompareAlphanumeric ( str1 , str2 ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE while ( i <= len1 and j <= len2 ) : NEW_LINE INDENT while ( i < len1 and ( ( ( str1 [ i ] >= ' a ' and str1 [ i ] <= ' z ' ) or ( str1 [ i ] >= ' A ' and str1 [ i ] <= ' Z ' ) or ( str1 [ i ] >= '0' and str1 [ i ] <= '9' ) ) == False ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( j < len2 and ( ( ( str2 [ j ] >= ' a ' and str2 [ j ] <= ' z ' ) or ( str2 [ j ] >= ' A ' and str2 [ j ] <= ' Z ' ) or ( str2 [ j ] >= '0' and str2 [ j ] <= '9' ) ) == False ) ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( i == len1 and j == len2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( str1 [ i ] != str2 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def CompareAlphanumericUtil ( str1 , str2 ) : NEW_LINE INDENT res = CompareAlphanumeric ( str1 , str2 ) NEW_LINE if ( res == True ) : NEW_LINE INDENT print ( \" Equal \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Unequal \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \" Ram , \u2581 Shyam \" NEW_LINE str2 = \" \u2581 Ram \u2581 - \u2581 Shyam . \" NEW_LINE CompareAlphanumericUtil ( str1 , str2 ) NEW_LINE str1 = \" abc123\" NEW_LINE str2 = \"123abc \" NEW_LINE CompareAlphanumericUtil ( str1 , str2 ) NEW_LINE DEDENT"} {"text":"Queries to print the character that occurs the maximum number of times in a given range | Function that answers all the queries ; Length of the String ; Number of queries ; Prefix array ; Iterate for all the characters ; Increase the count of the character ; Presum array for all 26 characters ; Update the prefix array ; Answer every query ; Range ; Iterate for all characters ; Times the lowercase character j occurs till r - th index ; Subtract the times it occurred till ( l - 1 ) th index ; Max times it occurs ; Print the answer ; Driver Code","code":"def solveQueries ( Str , query ) : NEW_LINE INDENT ll = len ( Str ) NEW_LINE Q = len ( query ) NEW_LINE pre = [ [ 0 for i in range ( 256 ) ] for i in range ( ll ) ] NEW_LINE for i in range ( ll ) : NEW_LINE INDENT pre [ i ] [ ord ( Str [ i ] ) ] += 1 NEW_LINE if ( i ) : NEW_LINE INDENT for j in range ( 256 ) : NEW_LINE INDENT pre [ i ] [ j ] += pre [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( Q ) : NEW_LINE INDENT l = query [ i ] [ 0 ] NEW_LINE r = query [ i ] [ 1 ] NEW_LINE maxi = 0 NEW_LINE c = ' a ' NEW_LINE for j in range ( 256 ) : NEW_LINE INDENT times = pre [ r ] [ j ] NEW_LINE if ( l ) : NEW_LINE INDENT times -= pre [ l - 1 ] [ j ] NEW_LINE DEDENT if ( times > maxi ) : NEW_LINE INDENT maxi = times NEW_LINE c = chr ( j ) NEW_LINE DEDENT DEDENT print ( \" Query \u2581 \" , i + 1 , \" : \u2581 \" , c ) NEW_LINE DEDENT DEDENT Str = \" striver \" NEW_LINE query = [ [ 0 , 1 ] , [ 1 , 6 ] , [ 5 , 6 ] ] NEW_LINE solveQueries ( Str , query ) NEW_LINE"} {"text":"Check whether given string can be generated after concatenating given strings | Function that return true if pre is a prefix of str ; While there are characters to match ; If characters differ at any position ; str starts with pre ; Function that return true if suff is a suffix of str ; While there are characters to match ; If characters differ at any position ; str ends with suff ; Function that returns true if str = a + b or str = b + a ; str cannot be generated by concatenating a and b ; If str starts with a i . e . a is a prefix of str ; Check if the rest of the characters are equal to b i . e . b is a suffix of str ; If str starts with b i . e . b is a prefix of str ; Check if the rest of the characters are equal to a i . e . a is a suffix of str ; Driver code","code":"def startsWith ( str , pre ) : NEW_LINE INDENT strLen = len ( str ) NEW_LINE preLen = len ( pre ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < strLen and j < preLen ) : NEW_LINE INDENT if ( str [ i ] != pre [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def endsWith ( str , suff ) : NEW_LINE INDENT i = len ( str ) - 1 NEW_LINE j = len ( suff ) - 1 NEW_LINE while ( i >= 0 and j >= 0 ) : NEW_LINE INDENT if ( str [ i ] != suff [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def checkString ( str , a , b ) : NEW_LINE INDENT if ( len ( str ) != len ( a ) + len ( b ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( startsWith ( str , a ) ) : NEW_LINE INDENT if ( endsWith ( str , b ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT if ( startsWith ( str , b ) ) : NEW_LINE INDENT if ( endsWith ( str , a ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT str = \" GeeksforGeeks \" NEW_LINE a = \" Geeksfo \" NEW_LINE b = \" rGeeks \" NEW_LINE if ( checkString ( str , a , b ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} {"text":"Print characters having odd frequencies in order of occurrence | Python3 implementation of the approach ; Function to print the odd frequency characters in the order of their occurrence ; To store the frequency of each of the character of the string and Initialize all elements of freq [ ] to 0 ; Update the frequency of each character ; Traverse str character by character ; If frequency of current character is odd ; Driver code","code":"import sys NEW_LINE import math NEW_LINE def printChar ( str_ , n ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( str_ [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( freq [ ord ( str_ [ i ] ) - ord ( ' a ' ) ] ) % 2 == 1 : NEW_LINE INDENT print ( \" { } \" . format ( str_ [ i ] ) , end = \" \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str_ = \" geeksforgeeks \" NEW_LINE n = len ( str_ ) NEW_LINE printChar ( str_ , n ) NEW_LINE DEDENT"} {"text":"Minimum number of operations to move all uppercase characters before all lower case characters | Function to return the minimum number of operations required ; To store the indices of the last uppercase and the first lowercase character ; Find the last uppercase character ; Find the first lowercase character ; If all the characters are either uppercase or lowercase ; Count of uppercase characters that appear after the first lowercase character ; Count of lowercase characters that appear before the last uppercase character ; Return the minimum operations required ; Driver Code","code":"def minOperations ( str , n ) : NEW_LINE INDENT lastUpper = - 1 NEW_LINE firstLower = - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( str [ i ] . isupper ( ) ) : NEW_LINE INDENT lastUpper = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] . islower ( ) ) : NEW_LINE INDENT firstLower = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( lastUpper == - 1 or firstLower == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT countUpper = 0 NEW_LINE for i in range ( firstLower , n ) : NEW_LINE INDENT if ( str [ i ] . isupper ( ) ) : NEW_LINE INDENT countUpper += 1 NEW_LINE DEDENT DEDENT countLower = 0 NEW_LINE for i in range ( lastUpper ) : NEW_LINE INDENT if ( str [ i ] . islower ( ) ) : NEW_LINE INDENT countLower += 1 NEW_LINE DEDENT DEDENT return min ( countLower , countUpper ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geEksFOrGEekS \" NEW_LINE n = len ( str ) NEW_LINE print ( minOperations ( str , n ) ) NEW_LINE DEDENT"} {"text":"Find the sum of all Betrothed numbers up to N | Python3 program to find the Sum of the all Betrothed numbers up to N ; Function to find the Sum of the all Betrothed numbers ; To store the Betrothed numbers ; Calculate sum of number_1 's divisors ; i = 2 because we don 't want to include 1 as a divisor. ; Sum all Betrothed numbers up to N ; Driver Code","code":"import math NEW_LINE def Betrothed_Sum ( n ) : NEW_LINE INDENT Set = [ ] NEW_LINE for number_1 in range ( 1 , n ) : NEW_LINE INDENT sum_divisor_1 = 1 NEW_LINE i = 2 NEW_LINE while i * i <= number_1 : NEW_LINE INDENT if ( number_1 % i == 0 ) : NEW_LINE INDENT sum_divisor_1 = sum_divisor_1 + i NEW_LINE if ( i * i != number_1 ) : NEW_LINE INDENT sum_divisor_1 += number_1 \/\/ i NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT if ( sum_divisor_1 > number_1 ) : NEW_LINE INDENT number_2 = sum_divisor_1 - 1 NEW_LINE sum_divisor_2 = 1 NEW_LINE j = 2 NEW_LINE while j * j <= number_2 : NEW_LINE INDENT if ( number_2 % j == 0 ) : NEW_LINE INDENT sum_divisor_2 += j NEW_LINE if ( j * j != number_2 ) : NEW_LINE INDENT sum_divisor_2 += number_2 \/\/ j NEW_LINE DEDENT DEDENT j = j + 1 NEW_LINE DEDENT if ( sum_divisor_2 == number_1 + 1 and number_1 <= n and number_2 <= n ) : NEW_LINE INDENT Set . append ( number_1 ) NEW_LINE Set . append ( number_2 ) NEW_LINE DEDENT DEDENT DEDENT Summ = 0 NEW_LINE for i in Set : NEW_LINE INDENT if i <= n : NEW_LINE INDENT Summ += i NEW_LINE DEDENT DEDENT return Summ NEW_LINE DEDENT n = 78 NEW_LINE print ( Betrothed_Sum ( n ) ) NEW_LINE"} {"text":"Probability of rain on N + 1 th day | Function to find the probability ; count occurence of 1 ; find probability ; Driver code","code":"def rainDayProbability ( a , n ) : NEW_LINE INDENT count = a . count ( 1 ) NEW_LINE m = count \/ n NEW_LINE return m NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( rainDayProbability ( a , n ) ) NEW_LINE DEDENT"} {"text":"Program to find the sum of a Series 1 + 1 \/ 2 ^ 2 + 1 \/ 3 ^ 3 + \u00e2 \u20ac\u00a6 . . + 1 \/ n ^ n | Function to calculate the following series ; Driver Code","code":"def Series ( n ) : NEW_LINE INDENT sums = 0.0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ser = 1 \/ ( i ** i ) NEW_LINE sums += ser NEW_LINE DEDENT return sums NEW_LINE DEDENT n = 3 NEW_LINE res = round ( Series ( n ) , 5 ) NEW_LINE print ( res ) NEW_LINE"} {"text":"Lexicographically largest string formed in minimum moves by replacing characters of given String | Function to print the lexicographically the largest string obtained in process of obtaining a string containing first N lower case english alphabtes ; Store the frequency of each character ; Traverse the string S ; Stores the characters which are not appearing in S ; Stores the index of the largest character in the array V , that need to be replaced ; Traverse the string , S ; If frequency of S [ i ] is greater than 1 or it is outside the range ; Decrement its frequency by 1 ; Update S [ i ] ; Decrement j by 1 ; Traverse the string , S ; Decrement its frequency by 1 ; Update S [ i ] ; Increment l by 1 ; Return S ; Given Input ; Function Call","code":"def lexicographicallyMaximum ( S , N ) : NEW_LINE INDENT M = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if S [ i ] in M : NEW_LINE M [ S [ i ] ] += 1 NEW_LINE else : NEW_LINE INDENT M [ S [ i ] ] = 1 NEW_LINE DEDENT DEDENT V = [ ] NEW_LINE for i in range ( ord ( ' a ' ) , ord ( ' a ' ) + min ( N , 25 ) ) : NEW_LINE INDENT if i not in M : NEW_LINE INDENT V . append ( chr ( i ) ) NEW_LINE DEDENT DEDENT j = len ( V ) - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ord ( S [ i ] ) >= ( ord ( ' a ' ) + min ( N , 25 ) ) or ( S [ i ] in M and M [ S [ i ] ] > 1 ) ) : NEW_LINE INDENT if ( ord ( V [ j ] ) < ord ( S [ i ] ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT M [ S [ i ] ] -= 1 NEW_LINE S = S [ 0 : i ] + V [ j ] + S [ ( i + 1 ) : ] NEW_LINE j -= 1 NEW_LINE DEDENT if ( j < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT l = 0 NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( l > j ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( ord ( S [ i ] ) >= ( ord ( ' a ' ) + min ( N , 25 ) ) or S [ i ] in M and M [ S [ i ] ] > 1 ) : NEW_LINE INDENT M [ S [ i ] ] -= 1 NEW_LINE S = S [ 0 : i ] + V [ l ] + S [ ( i + 1 ) : ] NEW_LINE l += 1 NEW_LINE DEDENT DEDENT s = list ( S ) NEW_LINE s [ len ( s ) - 1 ] = ' d ' NEW_LINE S = \" \" . join ( s ) NEW_LINE return S NEW_LINE DEDENT S = \" abccefghh \" NEW_LINE N = len ( S ) NEW_LINE print ( lexicographicallyMaximum ( S , N ) ) NEW_LINE"} {"text":"Check if any subarray can be made palindromic by replacing less than half of its elements | A Utility Function to check if a subarray can be palindromic by replacing less than half of the elements present in it ; Stores frequency of array elements ; Traverse the array ; Update frequency of each array element ; Iterator over the Map ; If frequency of any element exceeds 1 ; If no repetition is found ; Function to check and print if any subarray can be made palindromic by replacing less than half of its elements ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call","code":"def isConsistingSubarrayUtil ( arr , n ) : NEW_LINE INDENT mp = { } ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 ; NEW_LINE DEDENT DEDENT for it in mp : NEW_LINE INDENT if ( mp [ it ] > 1 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT def isConsistingSubarray ( arr , N ) : NEW_LINE INDENT if ( isConsistingSubarrayUtil ( arr , 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 arr = [ 1 , 2 , 3 , 4 , 5 , 1 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE isConsistingSubarray ( arr , N ) ; NEW_LINE DEDENT"} {"text":"Count composite fibonacci numbers from given array | Python3 program to implement the above approach ; Function to find all Fibonacci numbers up to Max ; Store all Fibonacci numbers upto Max ; Stores previous element of Fibonacci sequence ; Stores previous element of Fibonacci sequence ; Insert prev into hashmap ; Insert all the Fibonacci numbers up to Max ; Insert curr into hashmap ; Stores curr into temp ; Update curr ; Update prev ; Function to find all Composite numbers up to Max ; isPrime [ i ] : Stores if i is a prime number or not ; Calculate all prime numbers up to Max using Sieve of Eratosthenes ; If P is a prime number ; Set all multiple of P as non - prime ; Function to find the numbers which is both a composite and Fibonacci number ; Stores the largest element of the array ; Traverse the array arr [ ] ; Update Max ; isPrim [ i ] check i is a prime number or not ; Stores all the Fibonacci numbers ; Traverse the array arr [ ] ; Current element is not a composite number ; If current element is a Fibonacci and composite number ; Print current element ; Driver Code","code":"import math NEW_LINE def createhashmap ( Max ) : NEW_LINE INDENT hashmap = { \" \" } NEW_LINE curr = 1 NEW_LINE prev = 0 NEW_LINE hashmap . add ( prev ) NEW_LINE while ( curr <= Max ) : NEW_LINE INDENT hashmap . add ( curr ) NEW_LINE temp = curr NEW_LINE curr = curr + prev NEW_LINE prev = temp NEW_LINE DEDENT return hashmap NEW_LINE DEDENT def SieveOfEratosthenes ( Max ) : NEW_LINE INDENT isPrime = [ 1 for x in range ( Max + 1 ) ] NEW_LINE isPrime [ 0 ] = 0 NEW_LINE isPrime [ 1 ] = 0 NEW_LINE for p in range ( 0 , int ( math . sqrt ( Max ) ) ) : NEW_LINE INDENT if ( isPrime [ p ] ) : NEW_LINE INDENT for i in range ( 2 * p , Max , p ) : NEW_LINE INDENT isPrime [ i ] = 0 NEW_LINE DEDENT DEDENT DEDENT return isPrime NEW_LINE DEDENT def cntFibonacciPrime ( arr , N ) : NEW_LINE INDENT Max = arr [ 0 ] NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT Max = max ( Max , arr [ i ] ) NEW_LINE DEDENT isPrime = SieveOfEratosthenes ( Max ) NEW_LINE hashmap = createhashmap ( Max ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if arr [ i ] == 1 : NEW_LINE INDENT continue NEW_LINE DEDENT if ( ( arr [ i ] in hashmap ) and ( not ( isPrime [ arr [ i ] ] ) ) ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 13 , 55 , 7 , 3 , 5 , 21 , 233 , 144 , 89 ] NEW_LINE N = len ( arr ) NEW_LINE cntFibonacciPrime ( arr , N ) NEW_LINE"} {"text":"Reduce a given number to form a key by the given operations | Python3 program of the above approach ; Function to find the key of the given number ; Convert the integer to String ; Iterate the num - string to get the result ; Check if digit is even or odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes odd ; Add the result in ans ; Assign the digit index to num string ; If the number is odd ; Iterate until odd sum is obtained by adding consecutive digits ; Check if sum becomes even ; Add the result in ans ; assign the digit index to main numstring ; Check if all digits are visited or not ;","code":"import math NEW_LINE def key ( N ) : NEW_LINE INDENT num = \" \" + str ( N ) NEW_LINE ans = 0 NEW_LINE j = 0 NEW_LINE while j < len ( num ) : NEW_LINE INDENT if ( ( ord ( num [ j ] ) - 48 ) % 2 == 0 ) : NEW_LINE INDENT add = 0 NEW_LINE i = j NEW_LINE while j < len ( num ) : NEW_LINE INDENT add += ord ( num [ j ] ) - 48 NEW_LINE if ( add % 2 == 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( add == 0 ) : NEW_LINE INDENT ans *= 10 NEW_LINE DEDENT else : NEW_LINE INDENT digit = int ( math . floor ( math . log10 ( add ) + 1 ) ) NEW_LINE ans *= ( pow ( 10 , digit ) ) NEW_LINE ans += add NEW_LINE DEDENT i = j NEW_LINE DEDENT else : NEW_LINE INDENT add = 0 NEW_LINE i = j NEW_LINE while j < len ( num ) : NEW_LINE INDENT add += ord ( num [ j ] ) - 48 NEW_LINE if ( add % 2 == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( add == 0 ) : NEW_LINE INDENT ans *= 10 NEW_LINE DEDENT else : NEW_LINE INDENT digit = int ( math . floor ( math . log10 ( add ) + 1 ) ) NEW_LINE ans *= ( pow ( 10 , digit ) ) NEW_LINE ans += add NEW_LINE DEDENT i = j NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j + 1 ) >= len ( num ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT ans += ord ( num [ len ( num ) - 1 ] ) - 48 NEW_LINE return ans NEW_LINE DEDENT DEDENT \/ * Driver Code * \/ NEW_LINE N = 1667848271 NEW_LINE print ( key ( N ) ) NEW_LINE"} {"text":"Sentinel Linear Search | Python3 implementation of the approach Function to search key in the given array ; Function to search x in the given array ; Last element of the array ; Element to be searched is placed at the last index ; Put the last element back ; Driver code","code":"def sentinelSearch ( arr , n , key ) : NEW_LINE def sentinelSearch ( arr , n , key ) : NEW_LINE INDENT last = arr [ n - 1 ] NEW_LINE arr [ n - 1 ] = key NEW_LINE i = 0 NEW_LINE while ( arr [ i ] != key ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT arr [ n - 1 ] = last NEW_LINE if ( ( i < n - 1 ) or ( arr [ n - 1 ] == key ) ) : NEW_LINE INDENT print ( key , \" is \u2581 present \u2581 at \u2581 index \" , i ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Element \u2581 Not \u2581 found \" ) NEW_LINE DEDENT DEDENT arr = [ 10 , 20 , 180 , 30 , 60 , 50 , 110 , 100 , 70 ] NEW_LINE n = len ( arr ) NEW_LINE key = 180 NEW_LINE sentinelSearch ( arr , n , key ) NEW_LINE"} {"text":"Maximum possible middle element of the array after deleting exactly k elements | Function to calculate maximum possible middle value of the array after deleting exactly k elements ; Initialize answer as - 1 ; Calculate range of elements that can give maximum possible middle value of the array since index of maximum possible middle value after deleting exactly k elements from array will lie in between low and high ; Find maximum element of the array in range low and high ; since indexing is 1 based so check element at index i - 1 ; Return the maximum possible middle value of the array after deleting exactly k elements from the array ; Driver Code","code":"def maximum_middle_value ( n , k , arr ) : NEW_LINE INDENT ans = - 1 NEW_LINE low = ( n + 1 - k ) \/\/ 2 NEW_LINE high = ( n + 1 - k ) \/\/ 2 + k NEW_LINE for i in range ( low , high + 1 ) : NEW_LINE INDENT ans = max ( ans , arr [ i - 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n , k = 5 , 2 NEW_LINE arr = [ 9 , 5 , 3 , 7 , 10 ] NEW_LINE print ( maximum_middle_value ( n , k , arr ) ) NEW_LINE n , k = 9 , 3 NEW_LINE arr1 = [ 2 , 4 , 3 , 9 , 5 , 8 , 7 , 6 , 10 ] NEW_LINE print ( maximum_middle_value ( n , k , arr1 ) ) NEW_LINE DEDENT"} {"text":"Ternary Search | Python3 program to illustrate recursive approach to ternary search ; Function to perform Ternary Search ; Find the mid1 and mid2 ; Check if key is present at any mid ; Since key is not present at mid , check in which region it is present then repeat the Search operation in that region ; The key lies in between l and mid1 ; The key lies in between mid2 and r ; The key lies in between mid1 and mid2 ; Key not found ; Driver code ; Get the array Sort the array if not sorted ; Starting index ; length of array ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result ; Key to be searched in the array ; Search the key using ternarySearch ; Print the result","code":"import math as mt NEW_LINE def ternarySearch ( l , r , key , ar ) : NEW_LINE INDENT if ( r >= l ) : NEW_LINE INDENT mid1 = l + ( r - l ) \/\/ 3 NEW_LINE mid2 = r - ( r - l ) \/\/ 3 NEW_LINE if ( ar [ mid1 ] == key ) : NEW_LINE INDENT return mid1 NEW_LINE DEDENT if ( ar [ mid2 ] == key ) : NEW_LINE INDENT return mid2 NEW_LINE DEDENT if ( key < ar [ mid1 ] ) : NEW_LINE INDENT return ternarySearch ( l , mid1 - 1 , key , ar ) NEW_LINE DEDENT elif ( key > ar [ mid2 ] ) : NEW_LINE INDENT return ternarySearch ( mid2 + 1 , r , key , ar ) NEW_LINE DEDENT else : NEW_LINE INDENT return ternarySearch ( mid1 + 1 , mid2 - 1 , key , ar ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT l , r , p = 0 , 9 , 5 NEW_LINE ar = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE l = 0 NEW_LINE r = 9 NEW_LINE key = 5 NEW_LINE p = ternarySearch ( l , r , key , ar ) NEW_LINE print ( \" Index \u2581 of \" , key , \" is \" , p ) NEW_LINE key = 50 NEW_LINE p = ternarySearch ( l , r , key , ar ) NEW_LINE print ( \" Index \u2581 of \" , key , \" is \" , p ) NEW_LINE"} {"text":"Minimum number of points to be removed to get remaining points on one side of axis | Function to find the minimum number of points ; Number of points on the left of Y - axis . ; Number of points on the right of Y - axis . ; Number of points above X - axis . ; Number of points below X - axis . ; Driver Code","code":"def findmin ( p , n ) : NEW_LINE INDENT a , b , c , d = 0 , 0 , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] [ 0 ] <= 0 ) : NEW_LINE INDENT a += 1 NEW_LINE DEDENT elif ( p [ i ] [ 0 ] >= 0 ) : NEW_LINE INDENT b += 1 NEW_LINE DEDENT if ( p [ i ] [ 1 ] >= 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT elif ( p [ i ] [ 1 ] <= 0 ) : NEW_LINE INDENT d += 1 NEW_LINE DEDENT DEDENT return min ( [ a , b , c , d ] ) NEW_LINE DEDENT p = [ [ 1 , 1 ] , [ 2 , 2 ] , [ - 1 , - 1 ] , [ - 2 , 2 ] ] NEW_LINE n = len ( p ) NEW_LINE print ( findmin ( p , n ) ) NEW_LINE"} {"text":"Maximum number of pair reductions possible on a given triplet | Function to count the maximum number of pair reductions possible on a given triplet ; Convert them into an array ; Stores count of operations ; Sort the array ; If the first two array elements reduce to 0 ; Apply the operations ; Increment count ; Print the maximum count ; Given triplet","code":"def maxOps ( a , b , c ) : NEW_LINE INDENT arr = [ a , b , c ] NEW_LINE count = 0 NEW_LINE while True : NEW_LINE INDENT arr . sort ( ) NEW_LINE if not arr [ 0 ] and not arr [ 1 ] : NEW_LINE break NEW_LINE arr [ 1 ] -= 1 NEW_LINE arr [ 2 ] -= 1 NEW_LINE count += 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT a , b , c = 4 , 3 , 2 NEW_LINE maxOps ( a , b , c ) NEW_LINE"} {"text":"Case | Python3 implementation of the approach ; Function to return the sorted string ; To store the frequencies of the lowercase and the uppercase characters in the given string ; If current character is lowercase then increment its frequency in the lower [ ] array ; Else increment in the upper [ ] array ; Pointers that point to the smallest lowercase and the smallest uppercase characters respectively in the given string ; For every character in the given string ; If the current character is lowercase then replace it with the smallest lowercase character available ; Decrement the frequency of the used character ; Else replace it with the smallest uppercase character available ; Decrement the frequency of the used character ; Return the sorted string ; Driver code","code":"MAX = 26 NEW_LINE def getSortedString ( s , n ) : NEW_LINE INDENT lower = [ 0 ] * MAX ; NEW_LINE upper = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] . islower ( ) ) : NEW_LINE INDENT lower [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT elif ( s [ i ] . isupper ( ) ) : NEW_LINE INDENT upper [ ord ( s [ i ] ) - ord ( ' A ' ) ] += 1 ; NEW_LINE DEDENT DEDENT i = 0 ; j = 0 ; NEW_LINE while ( i < MAX and lower [ i ] == 0 ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT while ( j < MAX and upper [ j ] == 0 ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT for k in range ( n ) : NEW_LINE INDENT if ( s [ k ] . islower ( ) ) : NEW_LINE INDENT while ( lower [ i ] == 0 ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT s [ k ] = chr ( i + ord ( ' a ' ) ) ; NEW_LINE lower [ i ] -= 1 ; NEW_LINE DEDENT elif ( s [ k ] . isupper ( ) ) : NEW_LINE INDENT while ( upper [ j ] == 0 ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT s [ k ] = chr ( j + ord ( ' A ' ) ) ; NEW_LINE upper [ j ] -= 1 ; NEW_LINE DEDENT DEDENT return \" \" . join ( s ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \" gEeksfOrgEEkS \" ; NEW_LINE n = len ( s ) ; NEW_LINE print ( getSortedString ( list ( s ) , n ) ) ; NEW_LINE DEDENT"} {"text":"Print characters and their frequencies in order of occurrence | Python3 implementation to pr the character and its frequency in order of its occurrence ; Function to print the character and its frequency in order of its occurrence ; Size of the 'str ; Initialize all elements of freq [ ] to 0 ; Accumulate frequency of each character in 'str ; Traverse ' str ' from left to right ; if frequency of character str [ i ] is not equal to 0 ; print the character along with its frequency ; Update frequency of str [ i ] to 0 so that the same character is not printed again ; Driver Code","code":"import numpy as np NEW_LINE def prCharWithFreq ( str ) : NEW_LINE ' NEW_LINE INDENT n = len ( str ) NEW_LINE freq = np . zeros ( 26 , dtype = np . int ) NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] != 0 ) : NEW_LINE INDENT print ( str [ i ] , freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] , end = \" \u2581 \" ) NEW_LINE freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] = 0 NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeksforgeeks \" ; NEW_LINE prCharWithFreq ( str ) ; NEW_LINE DEDENT ' NEW_LINE"} {"text":"Reverse words in a given string | Python3 program to reverse a string s = input ( )","code":"s = \" i \u2581 like \u2581 this \u2581 program \u2581 very \u2581 much \" NEW_LINE words = s . split ( ' \u2581 ' ) NEW_LINE string = [ ] NEW_LINE for word in words : NEW_LINE INDENT string . insert ( 0 , word ) NEW_LINE DEDENT print ( \" Reversed \u2581 String : \" ) NEW_LINE print ( \" \u2581 \" . join ( string ) ) NEW_LINE"} {"text":"Segregate Prime and Non | Function to generate prime numbers using Sieve of Eratosthenes ; If prime [ p ] is unchanged , then it is a prime ; Update all multiples of p ; Function to segregate the primes and non - primes ; Generate all primes till 10 ^ 7 ; Initialize left and right ; Traverse the array ; Increment left while array element at left is prime ; Decrement right while array element at right is non - prime ; If left < right , then swap arr [ left ] and arr [ right ] ; Swap arr [ left ] and arr [ right ] ; Print segregated array ; Driver code ; Function Call","code":"def SieveOfEratosthenes ( prime , n ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT i = p * p NEW_LINE while ( i <= n ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE i += p NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def segregatePrimeNonPrime ( prime , arr , N ) : NEW_LINE INDENT SieveOfEratosthenes ( prime , 10000000 ) NEW_LINE left , right = 0 , N - 1 NEW_LINE while ( left < right ) : NEW_LINE INDENT while ( prime [ arr [ left ] ] ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT while ( not prime [ arr [ right ] ] ) : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT if ( left < right ) : NEW_LINE INDENT arr [ left ] , arr [ right ] = arr [ right ] , arr [ left ] NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT DEDENT for num in arr : NEW_LINE INDENT print ( num , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 4 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE prime = [ True ] * 10000001 NEW_LINE segregatePrimeNonPrime ( prime , arr , N ) NEW_LINE"} {"text":"Calculate depth of a full Binary tree from Preorder | function to return max of left subtree height or right subtree height ; calc height of left subtree ( In preorder left subtree is processed before right ) ; calc height of right subtree ; Wrapper over findDepthRec ( ) ; Driver program to test above functions","code":"def findDepthRec ( tree , n , index ) : NEW_LINE INDENT if ( index [ 0 ] >= n or tree [ index [ 0 ] ] == ' l ' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT index [ 0 ] += 1 NEW_LINE left = findDepthRec ( tree , n , index ) NEW_LINE index [ 0 ] += 1 NEW_LINE right = findDepthRec ( tree , n , index ) NEW_LINE return ( max ( left , right ) + 1 ) NEW_LINE DEDENT def findDepth ( tree , n ) : NEW_LINE INDENT index = [ 0 ] NEW_LINE return findDepthRec ( tree , n , index ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT tree = \" nlnnlll \" NEW_LINE n = len ( tree ) NEW_LINE print ( findDepth ( tree , n ) ) NEW_LINE DEDENT"} {"text":"Largest number in BST which is less than or equal to N | Constructor to create a new node ; To insert a new node in BST ; if tree is empty return new node ; if key is less then or greater then node value then recur down the tree ; return the ( unchanged ) node pointer ; function to find max value less then N ; Base cases ; If root 's value is smaller, try in right subtree ; If root 's key is greater, return value from left subtree. ; Driver code ; creating following BST 5 \/ \\ 2 12 \/ \\ \/ \\ 1 3 9 21 \/ \\ 19 25","code":"class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if node == None : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if key < node . key : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif key > node . key : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def findMaxforN ( root , N ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if root . key == N : NEW_LINE INDENT return N NEW_LINE DEDENT elif root . key < N : NEW_LINE INDENT k = findMaxforN ( root . right , N ) NEW_LINE if k == - 1 : NEW_LINE INDENT return root . key NEW_LINE DEDENT else : NEW_LINE INDENT return k NEW_LINE DEDENT DEDENT elif root . key > N : NEW_LINE INDENT return findMaxforN ( root . left , N ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE root = None NEW_LINE root = insert ( root , 25 ) NEW_LINE insert ( root , 2 ) NEW_LINE insert ( root , 1 ) NEW_LINE insert ( root , 3 ) NEW_LINE insert ( root , 12 ) NEW_LINE insert ( root , 9 ) NEW_LINE insert ( root , 21 ) NEW_LINE insert ( root , 19 ) NEW_LINE insert ( root , 25 ) NEW_LINE print ( findMaxforN ( root , N ) ) NEW_LINE DEDENT"} {"text":"Largest number in BST which is less than or equal to N | Python3 code to find the largest value smaller than or equal to N ; To create new BST Node ; To insert a new node in BST ; If tree is empty return new node ; If key is less then or greater then node value then recur down the tree ; Return the ( unchanged ) node pointer ; Function to find max value less then N ; Start from root and keep looking for larger ; If root is smaller go to right side ; If root is greater go to left side ; Driver code","code":"class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . key = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insert ( node , key ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return newNode ( key ) NEW_LINE DEDENT if ( key < node . key ) : NEW_LINE INDENT node . left = insert ( node . left , key ) NEW_LINE DEDENT elif ( key > node . key ) : NEW_LINE INDENT node . right = insert ( node . right , key ) NEW_LINE DEDENT return node NEW_LINE DEDENT def findMaxforN ( root , N ) : NEW_LINE INDENT while ( root != None and root . right != None ) : NEW_LINE INDENT if ( N > root . key and N >= root . right . key ) : NEW_LINE INDENT root = root . right NEW_LINE DEDENT elif ( N < root . key ) : NEW_LINE INDENT root = root . left NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( root == None or root . key > N ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( root . key ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 50 NEW_LINE root = None NEW_LINE root = insert ( root , 5 ) NEW_LINE insert ( root , 2 ) NEW_LINE insert ( root , 1 ) NEW_LINE insert ( root , 3 ) NEW_LINE insert ( root , 12 ) NEW_LINE insert ( root , 9 ) NEW_LINE insert ( root , 21 ) NEW_LINE insert ( root , 19 ) NEW_LINE insert ( root , 25 ) NEW_LINE findMaxforN ( root , N ) NEW_LINE DEDENT"} {"text":"Maximum element between two nodes of BST | Python 3 program to find maximum element in the path between two Nodes of Binary Search Tree . Create and return a pointer of new Node . ; Constructor to create a new node ; Insert a new Node in Binary Search Tree . ; Return the maximum element between a Node and its given ancestor . ; Traversing the path between ansector and Node and finding maximum element . ; Return maximum element in the path between two given Node of BST . ; Finding the LCA of Node x and Node y ; Checking if both the Node lie on the left side of the parent p . ; Checking if both the Node lie on the right side of the parent p . ; Return the maximum of maximum elements occur in path from ancestor to both Node . ; Driver Code ; Creating the root of Binary Search Tree ; Inserting Nodes in Binary Search Tree","code":"class createNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def insertNode ( root , x ) : NEW_LINE INDENT p , q = root , None NEW_LINE while p != None : NEW_LINE INDENT q = p NEW_LINE if p . data < x : NEW_LINE INDENT p = p . right NEW_LINE DEDENT else : NEW_LINE INDENT p = p . left NEW_LINE DEDENT DEDENT if q == None : NEW_LINE INDENT p = createNode ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT if q . data < x : NEW_LINE INDENT q . right = createNode ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT q . left = createNode ( x ) NEW_LINE DEDENT DEDENT DEDENT def maxelpath ( q , x ) : NEW_LINE INDENT p = q NEW_LINE mx = - 999999999999 NEW_LINE while p . data != x : NEW_LINE INDENT if p . data > x : NEW_LINE INDENT mx = max ( mx , p . data ) NEW_LINE p = p . left NEW_LINE DEDENT else : NEW_LINE INDENT mx = max ( mx , p . data ) NEW_LINE p = p . right NEW_LINE DEDENT DEDENT return max ( mx , x ) NEW_LINE DEDENT def maximumElement ( root , x , y ) : NEW_LINE INDENT p = root NEW_LINE while ( ( x < p . data and y < p . data ) or ( x > p . data and y > p . data ) ) : NEW_LINE INDENT if x < p . data and y < p . data : NEW_LINE INDENT p = p . left NEW_LINE DEDENT elif x > p . data and y > p . data : NEW_LINE INDENT p = p . right NEW_LINE DEDENT DEDENT return max ( maxelpath ( p , x ) , maxelpath ( p , y ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 18 , 36 , 9 , 6 , 12 , 10 , 1 , 8 ] NEW_LINE a , b = 1 , 10 NEW_LINE n = len ( arr ) NEW_LINE root = createNode ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT insertNode ( root , arr [ i ] ) NEW_LINE DEDENT print ( maximumElement ( root , a , b ) ) NEW_LINE DEDENT"} {"text":"Threaded Binary Tree | Insertion | Insertion in Threaded Binary Search Tree . ; True if left pointer points to predecessor in Inorder Traversal ; True if right pointer points to successor in Inorder Traversal ; Insert a Node in Binary Threaded Tree ; Searching for a Node with given value ; Parent of key to be inserted ; If key already exists , return ; Update parent pointer ; Moving on left subtree . ; Moving on right subtree . ; Create a new node ; Returns inorder successor using rthread ; If rthread is set , we can quickly find ; Else return leftmost child of right subtree ; Printing the threaded tree ; Reach leftmost node ; One by one print successors ; Driver Code","code":"class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . info = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . lthread = True NEW_LINE self . rthread = True NEW_LINE DEDENT DEDENT def insert ( root , ikey ) : NEW_LINE INDENT ptr = root NEW_LINE par = None NEW_LINE while ptr != None : NEW_LINE INDENT if ikey == ( ptr . info ) : NEW_LINE INDENT print ( \" Duplicate \u2581 Key \u2581 ! \" ) NEW_LINE return root NEW_LINE DEDENT par = ptr NEW_LINE if ikey < ptr . info : NEW_LINE INDENT if ptr . lthread == False : NEW_LINE INDENT ptr = ptr . left NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ptr . rthread == False : NEW_LINE INDENT ptr = ptr . right NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT tmp = newNode ( ikey ) NEW_LINE if par == None : NEW_LINE INDENT root = tmp NEW_LINE tmp . left = None NEW_LINE tmp . right = None NEW_LINE DEDENT elif ikey < ( par . info ) : NEW_LINE INDENT tmp . left = par . left NEW_LINE tmp . right = par NEW_LINE par . lthread = False NEW_LINE par . left = tmp NEW_LINE DEDENT else : NEW_LINE INDENT tmp . left = par NEW_LINE tmp . right = par . right NEW_LINE par . rthread = False NEW_LINE par . right = tmp NEW_LINE DEDENT return root NEW_LINE DEDENT def inorderSuccessor ( ptr ) : NEW_LINE INDENT if ptr . rthread == True : NEW_LINE INDENT return ptr . right NEW_LINE DEDENT ptr = ptr . right NEW_LINE while ptr . lthread == False : NEW_LINE INDENT ptr = ptr . left NEW_LINE DEDENT return ptr NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT print ( \" Tree \u2581 is \u2581 empty \" ) NEW_LINE DEDENT ptr = root NEW_LINE while ptr . lthread == False : NEW_LINE INDENT ptr = ptr . left NEW_LINE DEDENT while ptr != None : NEW_LINE INDENT print ( ptr . info , end = \" \u2581 \" ) NEW_LINE ptr = inorderSuccessor ( ptr ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = insert ( root , 20 ) NEW_LINE root = insert ( root , 10 ) NEW_LINE root = insert ( root , 30 ) NEW_LINE root = insert ( root , 5 ) NEW_LINE root = insert ( root , 16 ) NEW_LINE root = insert ( root , 14 ) NEW_LINE root = insert ( root , 17 ) NEW_LINE root = insert ( root , 13 ) NEW_LINE inorder ( root ) NEW_LINE DEDENT"} {"text":"Check horizontal and vertical symmetry in binary matrix | Python3 program to find if a matrix is symmetric . ; Initializing as both horizontal and vertical symmetric . ; Checking for Horizontal Symmetry . We compare first row with last row , second row with second last row and so on . ; Checking each cell of a column . ; check if every cell is identical ; Checking for Vertical Symmetry . We compare first column with last column , second xolumn with second last column and so on . ; Checking each cell of a row . ; check if every cell is identical ; Driver code","code":"MAX = 1000 NEW_LINE def checkHV ( arr , N , M ) : NEW_LINE INDENT horizontal = True NEW_LINE vertical = True NEW_LINE i = 0 NEW_LINE k = N - 1 NEW_LINE while ( i < N \/\/ 2 ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( arr [ i ] [ j ] != arr [ k ] [ j ] ) : NEW_LINE INDENT horizontal = False NEW_LINE break NEW_LINE DEDENT DEDENT i += 1 NEW_LINE k -= 1 NEW_LINE DEDENT i = 0 NEW_LINE k = M - 1 NEW_LINE while ( i < M \/\/ 2 ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( arr [ i ] [ j ] != arr [ k ] [ j ] ) : NEW_LINE INDENT vertical = False NEW_LINE break NEW_LINE DEDENT DEDENT i += 1 NEW_LINE k -= 1 NEW_LINE DEDENT if ( not horizontal and not vertical ) : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT elif ( horizontal and not vertical ) : NEW_LINE INDENT print ( \" HORIZONTAL \" ) NEW_LINE DEDENT elif ( vertical and not horizontal ) : NEW_LINE INDENT print ( \" VERTICAL \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" BOTH \" ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 0 , 1 ] , [ 0 , 0 , 0 ] , [ 1 , 0 , 1 ] ] NEW_LINE checkHV ( mat , 3 , 3 ) NEW_LINE"} {"text":"Replace every matrix element with maximum of GCD of row or column | Python3 program to replace each each element with maximum of GCD of row or column . ; returning the greatest common divisor of two number ; Finding GCD of each row and column and replacing with each element with maximum of GCD of row or column . ; Calculating GCD of each row and each column in O ( mn ) and store in arrays . ; Replacing matrix element ; Driver Code","code":"R = 3 NEW_LINE C = 4 NEW_LINE 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 replacematrix ( mat , n , m ) : NEW_LINE INDENT rgcd = [ 0 ] * R NEW_LINE cgcd = [ 0 ] * C NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT rgcd [ i ] = gcd ( rgcd [ i ] , mat [ i ] [ j ] ) NEW_LINE cgcd [ j ] = gcd ( cgcd [ j ] , mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT mat [ i ] [ j ] = max ( rgcd [ i ] , cgcd [ j ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT m = [ [ 1 , 2 , 3 , 3 ] , [ 4 , 5 , 6 , 6 ] , [ 7 , 8 , 9 , 9 ] ] NEW_LINE replacematrix ( m , R , C ) NEW_LINE for i in range ( R ) : NEW_LINE INDENT for j in range ( C ) : NEW_LINE INDENT print ( m [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT"} {"text":"Program for addition of two matrices | Python3 program for addition of two matrices ; This function adds A [ ] [ ] and B [ ] [ ] , and stores the result in C [ ] [ ] ; driver code","code":"N = 4 NEW_LINE def add ( A , B , C ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT C [ i ] [ j ] = A [ i ] [ j ] + B [ 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 B = [ [ 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 ] , [ 4 , 4 , 4 , 4 ] ] NEW_LINE C = A [ : ] [ : ] NEW_LINE add ( A , B , C ) NEW_LINE print ( \" Result \u2581 matrix \u2581 is \" ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( C [ i ] [ j ] , \" \u2581 \" , end = ' ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT"} {"text":"Program for subtraction of matrices | Python 3 program for subtraction of matrices ; This function returns 1 if A [ ] [ ] and B [ ] [ ] are identical otherwise returns 0 ; Driver Code","code":"N = 4 NEW_LINE def subtract ( A , B , C ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT C [ i ] [ j ] = A [ i ] [ j ] - B [ 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 B = [ [ 1 , 1 , 1 , 1 ] , [ 2 , 2 , 2 , 2 ] , [ 3 , 3 , 3 , 3 ] , [ 4 , 4 , 4 , 4 ] ] NEW_LINE C = A [ : ] [ : ] NEW_LINE subtract ( A , B , C ) NEW_LINE print ( \" Result \u2581 matrix \u2581 is \" ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( C [ i ] [ j ] , \" \u2581 \" , end = ' ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT"} {"text":"Find a Fixed Point ( Value equal to index ) in a given array | Python program to check fixed point in an array using linear search ; If no fixed point present then return - 1 ; Driver program to check above functions","code":"def linearSearch ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] is i : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ - 10 , - 1 , 0 , 3 , 10 , 11 , 30 , 50 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Fixed \u2581 Point \u2581 is \u2581 \" + str ( linearSearch ( arr , n ) ) ) NEW_LINE"} {"text":"Find a Fixed Point ( Value equal to index ) in a given array | Python program to check fixed point in an array using binary search ; ; Return - 1 if there is no Fixed Point ; Driver program to check above functions","code":"def binarySearch ( arr , low , high ) : NEW_LINE INDENT if high >= low : NEW_LINE INDENT mid = ( low + high ) \/\/ 2 NEW_LINE DEDENT if mid is arr [ mid ] : NEW_LINE INDENT return mid NEW_LINE DEDENT if mid > arr [ mid ] : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( arr , low , ( mid - 1 ) ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ - 10 , - 1 , 0 , 3 , 10 , 11 , 30 , 50 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Fixed \u2581 Point \u2581 is \u2581 \" + str ( binarySearch ( arr , 0 , n - 1 ) ) ) NEW_LINE"} {"text":"Maximum triplet sum in array | Python 3 code to find maximum triplet sum ; Initialize sum with INT_MIN ; Driven code","code":"def maxTripletSum ( arr , n ) : NEW_LINE INDENT sm = - 1000000 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( sm < ( arr [ i ] + arr [ j ] + arr [ k ] ) ) : NEW_LINE INDENT sm = arr [ i ] + arr [ j ] + arr [ k ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return sm NEW_LINE DEDENT arr = [ 1 , 0 , 8 , 6 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxTripletSum ( arr , n ) ) NEW_LINE"} {"text":"Maximum triplet sum in array | This function assumes that there are at least three elements in arr [ ] . ; sort the given array ; After sorting the array . Add last three element of the given array ; Driven code","code":"def maxTripletSum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE return ( arr [ n - 1 ] + arr [ n - 2 ] + arr [ n - 3 ] ) NEW_LINE DEDENT arr = [ 1 , 0 , 8 , 6 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxTripletSum ( arr , n ) ) NEW_LINE"} {"text":"Maximum triplet sum in array | This function assumes that there are at least three elements in arr [ ] . ; Initialize Maximum , second maximum and third maximum element ; Update Maximum , second maximum and third maximum element ; Update second maximum and third maximum element ; Update third maximum element ; Driven code","code":"def maxTripletSum ( arr , n ) : NEW_LINE INDENT maxA = - 100000000 NEW_LINE maxB = - 100000000 NEW_LINE maxC = - 100000000 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] > maxA ) : NEW_LINE INDENT maxC = maxB NEW_LINE maxB = maxA NEW_LINE maxA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxB ) : NEW_LINE INDENT maxC = maxB NEW_LINE maxB = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxC ) : NEW_LINE INDENT maxC = arr [ i ] NEW_LINE DEDENT DEDENT return ( maxA + maxB + maxC ) NEW_LINE DEDENT arr = [ 1 , 0 , 8 , 6 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxTripletSum ( arr , n ) ) NEW_LINE"} {"text":"Linear Search | Python3 code to linearly search x in arr [ ] . If x is present then return its location , otherwise return - 1 ; Driver Code ; Function call","code":"def search ( arr , n , x ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == x ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE x = 10 NEW_LINE n = len ( arr ) NEW_LINE result = search ( arr , n , x ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( \" Element \u2581 is \u2581 not \u2581 present \u2581 in \u2581 array \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Element \u2581 is \u2581 present \u2581 at \u2581 index \" , result ) NEW_LINE DEDENT"} {"text":"Linear Search | Python3 program for linear search ; Run loop from 0 to right ; If search_element is found with left variable ; If search_element is found with right variable ; If element not found ; Driver code ; Function call","code":"def search ( arr , search_Element ) : NEW_LINE INDENT left = 0 NEW_LINE length = len ( arr ) NEW_LINE position = - 1 NEW_LINE right = length - 1 NEW_LINE for left in range ( 0 , right , 1 ) : NEW_LINE INDENT if ( arr [ left ] == search_Element ) : NEW_LINE INDENT position = left NEW_LINE print ( \" Element \u2581 found \u2581 in \u2581 Array \u2581 at \u2581 \" , position + 1 , \" \u2581 Position \u2581 with \u2581 \" , left + 1 , \" \u2581 Attempt \" ) NEW_LINE break NEW_LINE DEDENT if ( arr [ right ] == search_Element ) : NEW_LINE INDENT position = right NEW_LINE print ( \" Element \u2581 found \u2581 in \u2581 Array \u2581 at \u2581 \" , position + 1 , \" \u2581 Position \u2581 with \u2581 \" , length - right , \" \u2581 Attempt \" ) NEW_LINE break NEW_LINE DEDENT left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT if ( position == - 1 ) : NEW_LINE INDENT print ( \" Not \u2581 found \u2581 in \u2581 Array \u2581 with \u2581 \" , left , \" \u2581 Attempt \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE search_element = 5 NEW_LINE search ( arr , search_element ) NEW_LINE"} {"text":"Counting Sort | The main function that sort the given string arr [ ] in alphabetical order ; The output character array that will have sorted arr ; Create a count array to store count of inidividul characters and initialize count array as 0 ; Store count of each character ; Change count [ i ] so that count [ i ] now contains actual position of this character in output array ; Build the output character array ; Copy the output array to arr , so that arr now contains sorted characters ; Driver program to test above function","code":"def countSort ( arr ) : NEW_LINE INDENT output = [ 0 for i in range ( len ( arr ) ) ] NEW_LINE count = [ 0 for i in range ( 256 ) ] NEW_LINE for i in arr : NEW_LINE INDENT count [ ord ( i ) ] += 1 NEW_LINE DEDENT for i in range ( 256 ) : NEW_LINE INDENT count [ i ] += count [ i - 1 ] NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT output [ count [ ord ( arr [ i ] ) ] - 1 ] = arr [ i ] NEW_LINE count [ ord ( arr [ i ] ) ] -= 1 NEW_LINE DEDENT ans = [ \" \" for _ in arr ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT ans [ i ] = output [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = \" geeksforgeeks \" NEW_LINE ans = countSort ( arr ) NEW_LINE print ( \" Sorted \u2581 character \u2581 array \u2581 is \u2581 % \u2581 s \" % ( \" \" . join ( ans ) ) ) NEW_LINE"} {"text":"Counting Sort | The function that sorts the given arr [ ] ; Driver program to test above function","code":"def count_sort ( arr ) : NEW_LINE INDENT max_element = int ( max ( arr ) ) NEW_LINE min_element = int ( min ( arr ) ) NEW_LINE range_of_elements = max_element - min_element + 1 NEW_LINE count_arr = [ 0 for _ in range ( range_of_elements ) ] NEW_LINE output_arr = [ 0 for _ in range ( len ( arr ) ) ] NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT count_arr [ arr [ i ] - min_element ] += 1 NEW_LINE DEDENT for i in range ( 1 , len ( count_arr ) ) : NEW_LINE INDENT count_arr [ i ] += count_arr [ i - 1 ] NEW_LINE DEDENT for i in range ( len ( arr ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT output_arr [ count_arr [ arr [ i ] - min_element ] - 1 ] = arr [ i ] NEW_LINE count_arr [ arr [ i ] - min_element ] -= 1 NEW_LINE DEDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT arr [ i ] = output_arr [ i ] NEW_LINE DEDENT return arr NEW_LINE DEDENT arr = [ - 5 , - 10 , 0 , - 3 , 8 , 5 , - 1 , 10 ] NEW_LINE ans = count_sort ( arr ) NEW_LINE print ( \" Sorted \u2581 character \u2581 array \u2581 is \u2581 \" + str ( ans ) ) NEW_LINE"} {"text":"Binomial Coefficient | DP | Returns value of Binomial Coefficient C ( n , k ) ; Base Cases ; Recursive Call ; Driver Program to test ht above function","code":"def binomialCoeff ( n , k ) : NEW_LINE INDENT if k > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if k == 0 or k == n : NEW_LINE INDENT return 1 NEW_LINE DEDENT return binomialCoeff ( n - 1 , k - 1 ) + binomialCoeff ( n - 1 , k ) NEW_LINE DEDENT n = 5 NEW_LINE k = 2 NEW_LINE print \" Value \u2581 of \u2581 C ( % d , % d ) \u2581 is \u2581 ( % d ) \" % ( n , k , binomialCoeff ( n , k ) ) NEW_LINE"} {"text":"Binomial Coefficient | DP | Python program for Optimized Dynamic Programming solution to Binomail Coefficient . This one uses the concept of pascal Triangle and less memory ; since nC0 is 1 ; Compute next row of pascal triangle using the previous row ; Driver Code","code":"def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ 0 for i in xrange ( 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 = 5 NEW_LINE k = 2 NEW_LINE print \" Value \u2581 of \u2581 C ( % d , % d ) \u2581 is \u2581 % d \" % ( n , k , binomialCoeff ( n , k ) ) NEW_LINE"} {"text":"Binomial Coefficient | DP | Python code for the above approach ; Base case ; C ( n , r ) = C ( n , n - r ) Complexity for this code is lesser for lower n - r ; set smallest prime factor of each number as itself ; set smallest prime factor of all even numbers as 2 ; Check if i is prime ; All multiples of i are composite ( and divisible by i ) so add i to their prime factorization getpow ( j , i ) times ; dictionary to store power of each prime in C ( n , r ) ; For numerator count frequency of each prime factor ; Recursive division to find prime factorization of i ; For denominator subtract the power of each prime factor ; Recursive division to find prime factorization of i ; ; Use ( a * b ) % mod = ( a % mod * b % mod ) % mod ; pow ( base , exp , mod ) is used to find ( base ^ exp ) % mod fast ; Driver code","code":"import math NEW_LINE class GFG : NEW_LINE INDENT def nCr ( self , n , r ) : NEW_LINE INDENT if r > n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n - r > r : NEW_LINE INDENT r = n - r NEW_LINE DEDENT SPF = [ i for i in range ( n + 1 ) ] NEW_LINE for i in range ( 4 , n + 1 , 2 ) : NEW_LINE INDENT SPF [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , n + 1 , 2 ) : NEW_LINE INDENT if i * i > n : NEW_LINE INDENT break NEW_LINE DEDENT if SPF [ i ] == i : NEW_LINE INDENT for j in range ( i * i , n + 1 , i ) : NEW_LINE INDENT if SPF [ j ] == j : NEW_LINE INDENT SPF [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT prime_pow = { } NEW_LINE for i in range ( r + 1 , n + 1 ) : NEW_LINE INDENT t = i NEW_LINE while t > 1 : NEW_LINE INDENT if not SPF [ t ] in prime_pow : NEW_LINE INDENT prime_pow [ SPF [ t ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prime_pow [ SPF [ t ] ] += 1 NEW_LINE DEDENT t \/\/= SPF [ t ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n - r + 1 ) : NEW_LINE INDENT t = i NEW_LINE while t > 1 : NEW_LINE INDENT prime_pow [ SPF [ t ] ] -= 1 NEW_LINE t \/\/= SPF [ t ] NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE for i in prime_pow : NEW_LINE INDENT ans = ( ans * pow ( i , prime_pow [ i ] , mod ) ) % mod NEW_LINE DEDENT return ans NEW_LINE DEDENT DEDENT n = 5 NEW_LINE k = 2 NEW_LINE ob = GFG ( ) NEW_LINE print ( \" Value \u2581 of \u2581 C ( \" + str ( n ) + \" , \u2581 \" + str ( k ) + \" ) \u2581 is \" , ob . nCr ( n , k ) ) NEW_LINE"} {"text":"Binomial Coefficient | DP | Function to find binomial coefficient ; Getting the modular inversion for all the numbers from 2 to r with respect to m here m = 1000000007 ; for 1 \/ ( r ! ) part ; for ( n ) * ( n - 1 ) * ( n - 2 ) * ... * ( n - r + 1 ) part ; Driver code","code":"def binomialCoeff ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT m = 1000000007 NEW_LINE inv = [ 0 for i in range ( r + 1 ) ] NEW_LINE inv [ 0 ] = 1 NEW_LINE if ( r + 1 >= 2 ) : NEW_LINE INDENT inv [ 1 ] = 1 NEW_LINE DEDENT for i in range ( 2 , r + 1 ) : NEW_LINE INDENT inv [ i ] = m - ( m \/\/ i ) * inv [ m % i ] % m NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 2 , r + 1 ) : NEW_LINE INDENT ans = ( ( ans % m ) * ( inv [ i ] % m ) ) % m NEW_LINE DEDENT for i in range ( n , n - r , - 1 ) : NEW_LINE INDENT ans = ( ( ans % m ) * ( i % m ) ) % m NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE r = 2 NEW_LINE print ( \" Value \u2581 of \u2581 C ( \" , n , \" , \u2581 \" , r , \" ) \u2581 is \u2581 \" , binomialCoeff ( n , r ) ) NEW_LINE"} {"text":"Partition problem | DP | Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; Calculate sum of all elements ; Initialze the part array as 0 ; Fill the partition table in bottom up manner ; the element to be included in the sum cannot be greater than the sum ; check if sum - arr [ i ] could be formed from a subset using elements before index i ; Drive code ; Function call","code":"def findPartiion ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT if ( Sum % 2 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT part = [ 0 ] * ( ( Sum \/\/ 2 ) + 1 ) NEW_LINE for i in range ( ( Sum \/\/ 2 ) + 1 ) : NEW_LINE INDENT part [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( Sum \/\/ 2 , arr [ i ] - 1 , - 1 ) : NEW_LINE INDENT if ( part [ j - arr [ i ] ] == 1 or j == arr [ i ] ) : NEW_LINE INDENT part [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT return part [ Sum \/\/ 2 ] NEW_LINE DEDENT arr = [ 1 , 3 , 3 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( findPartiion ( arr , n ) == 1 ) : NEW_LINE INDENT print ( \" Can \u2581 be \u2581 divided \u2581 into \u2581 two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Can \u2581 not \u2581 be \u2581 divided \u2581 into \u2581 two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Dynamic Programming | Returns true if there is a subset of set [ ] with sun equal to given sum ; Base Cases ; If last element is greater than sum , then ignore it ; else , check if sum can be obtained by any of the following ( a ) including the last element ( b ) excluding the last element ; Driver code","code":"def isSubsetSum ( set , n , sum ) : NEW_LINE INDENT if ( sum == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( set [ n - 1 ] > sum ) : NEW_LINE INDENT return isSubsetSum ( set , n - 1 , sum ) NEW_LINE DEDENT return isSubsetSum ( set , n - 1 , sum ) or isSubsetSum ( set , n - 1 , sum - set [ n - 1 ] ) NEW_LINE DEDENT set = [ 3 , 34 , 4 , 12 , 5 , 2 ] NEW_LINE sum = 9 NEW_LINE n = len ( set ) NEW_LINE if ( isSubsetSum ( set , n , sum ) == True ) : NEW_LINE INDENT print ( \" Found \u2581 a \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Dynamic Programming | Returns true if there is a subset of set [ ] with sun equal to 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 botton up manner ; print table ; Driver code","code":"def isSubsetSum ( set , n , sum ) : NEW_LINE INDENT subset = ( [ [ False for i in range ( sum + 1 ) ] for i in range ( n + 1 ) ] ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT subset [ i ] [ 0 ] = True NEW_LINE DEDENT for i in range ( 1 , sum + 1 ) : NEW_LINE INDENT subset [ 0 ] [ i ] = False NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , sum + 1 ) : NEW_LINE INDENT if j < set [ i - 1 ] : NEW_LINE INDENT subset [ i ] [ j ] = subset [ i - 1 ] [ j ] NEW_LINE DEDENT if j >= set [ i - 1 ] : NEW_LINE INDENT subset [ i ] [ j ] = ( subset [ i - 1 ] [ j ] or subset [ i - 1 ] [ j - set [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( sum + 1 ) : NEW_LINE INDENT print ( subset [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE print ( ) NEW_LINE DEDENT DEDENT return subset [ n ] [ sum ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT set = [ 3 , 34 , 4 , 12 , 5 , 2 ] NEW_LINE sum = 9 NEW_LINE n = len ( set ) NEW_LINE if ( isSubsetSum ( set , n , sum ) == True ) : NEW_LINE INDENT print ( \" Found \u2581 a \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \u2581 subset \u2581 with \u2581 given \u2581 sum \" ) NEW_LINE DEDENT DEDENT"} {"text":"How to print maximum number of A 's using given four keys | A recursive function that returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than ; Initialize result ; TRY ALL POSSIBLE BREAK - POINTS For any keystroke N , we need to loop from N - 3 keystrokes back to 1 keystroke to find a breakpoint ' b ' after which we will have Ctrl - A , Ctrl - C and then only Ctrl - V all the way . ; If the breakpoint is s at b 'th keystroke then the optimal string would have length (n-b-1)*screen[b-1]; ; Driver program ; for the rest of the array we will rely on the previous entries to compute new ones","code":"def findoptimal ( N ) : NEW_LINE INDENT if N <= 6 : NEW_LINE INDENT return N NEW_LINE DEDENT maxi = 0 NEW_LINE for b in range ( N - 3 , 0 , - 1 ) : NEW_LINE INDENT curr = ( N - b - 1 ) * findoptimal ( b ) NEW_LINE if curr > maxi : NEW_LINE INDENT maxi = curr NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT for n in range ( 1 , 21 ) : NEW_LINE INDENT print ( ' Maximum \u2581 Number \u2581 of \u2581 As \u2581 with \u2581 ' , n , ' keystrokes \u2581 is \u2581 ' , findoptimal ( n ) ) NEW_LINE DEDENT DEDENT"} {"text":"How to print maximum number of A 's using given four keys | this function returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than 7 ; An array to store result of subproblems ; Initializing the optimal lengths array for uptil 6 input strokes . ; Solve all subproblems in bottom manner ; Initialize length of optimal string for n keystrokes ; For any keystroke n , we need to loop from n - 3 keystrokes back to 1 keystroke to find a breakpoint ' b ' after which we will have ctrl - a , ctrl - c and then only ctrl - v all the way . ; if the breakpoint is at b 'th keystroke then the optimal string would have length (n-b-1)*screen[b-1]; ; Driver program ; for the rest of the array we will rely on the previous entries to compute new ones","code":"def findoptimal ( N ) : NEW_LINE INDENT if ( N <= 6 ) : NEW_LINE INDENT return N NEW_LINE DEDENT screen = [ 0 ] * N NEW_LINE for n in range ( 1 , 7 ) : NEW_LINE INDENT screen [ n - 1 ] = n NEW_LINE DEDENT for n in range ( 7 , N + 1 ) : NEW_LINE INDENT screen [ n - 1 ] = 0 NEW_LINE for b in range ( n - 3 , 0 , - 1 ) : NEW_LINE INDENT curr = ( n - b - 1 ) * screen [ b - 1 ] NEW_LINE if ( curr > screen [ n - 1 ] ) : NEW_LINE INDENT screen [ n - 1 ] = curr NEW_LINE DEDENT DEDENT DEDENT return screen [ N - 1 ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT for N in range ( 1 , 21 ) : NEW_LINE INDENT print ( \" Maximum \u2581 Number \u2581 of \u2581 A ' s \u2581 with \u2581 \" , N , \" \u2581 keystrokes \u2581 is \u2581 \" , findoptimal ( N ) ) NEW_LINE DEDENT DEDENT"} {"text":"How to print maximum number of A 's using given four keys | this function returns the optimal length string for N keystrokes ; The optimal string length is N when N is smaller than 7 ; An array to store result of subproblems ; Initializing the optimal lengths array for uptil 6 input strokes . ; Solve all subproblems in bottom manner ; for any keystroke n , we will need to choose between : - 1. pressing Ctrl - V once after copying the A ' s \u2581 obtained \u2581 by \u2581 n - 3 \u2581 keystrokes . \u2581 \u2581 2 . \u2581 pressing \u2581 Ctrl - V \u2581 twice \u2581 after \u2581 copying \u2581 the \u2581 A ' s obtained by n - 4 keystrokes . 3. pressing Ctrl - V thrice after copying the A 's obtained by n-5 keystrokes. ; Driver Code ; for the rest of the array we will rely on the previous entries to compute new ones","code":"def findoptimal ( N ) : NEW_LINE INDENT if ( N <= 6 ) : NEW_LINE INDENT return N NEW_LINE DEDENT screen = [ 0 ] * N NEW_LINE for n in range ( 1 , 7 ) : NEW_LINE INDENT screen [ n - 1 ] = n NEW_LINE DEDENT for n in range ( 7 , N + 1 ) : NEW_LINE INDENT screen [ n - 1 ] = max ( 2 * screen [ n - 4 ] , max ( 3 * screen [ n - 5 ] , 4 * screen [ n - 6 ] ) ) ; NEW_LINE DEDENT return screen [ N - 1 ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT for N in range ( 1 , 21 ) : NEW_LINE INDENT print ( \" Maximum \u2581 Number \u2581 of \u2581 A ' s \u2581 with \u2581 \" , N , \" \u2581 keystrokes \u2581 is \u2581 \" , findoptimal ( N ) ) NEW_LINE DEDENT DEDENT"} {"text":"Write a program to calculate pow ( x , n ) | Function to calculate x raised to the power y ; Driver Code","code":"def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : return 1 NEW_LINE elif ( int ( y % 2 ) == 0 ) : NEW_LINE INDENT return ( power ( x , int ( y \/ 2 ) ) * power ( x , int ( y \/ 2 ) ) ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( x * power ( x , int ( y \/ 2 ) ) * power ( x , int ( y \/ 2 ) ) ) NEW_LINE DEDENT DEDENT x = 2 ; y = 3 NEW_LINE print ( power ( x , y ) ) NEW_LINE"} {"text":"Write a program to calculate pow ( x , n ) | Function to calculate x raised to the power y in O ( logn )","code":"def power ( x , y ) : NEW_LINE INDENT temp = 0 NEW_LINE if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT temp = power ( x , int ( 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"} {"text":"Write a program to calculate pow ( x , n ) | Python3 code for extended version of power function that can work for float x and negative y ; Driver Code","code":"def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : return 1 NEW_LINE temp = power ( x , int ( y \/ 2 ) ) NEW_LINE if ( y % 2 == 0 ) : NEW_LINE INDENT return temp * temp NEW_LINE DEDENT else : NEW_LINE INDENT if ( y > 0 ) : return x * temp * temp NEW_LINE else : return ( temp * temp ) \/ x NEW_LINE DEDENT DEDENT x , y = 2 , - 3 NEW_LINE print ( ' % .6f ' % ( power ( x , y ) ) ) NEW_LINE"} {"text":"Write a program to calculate pow ( x , n ) | Python3 program for the above approach ; If x ^ 0 return 1 ; If we need to find of 0 ^ y ; For all other cases ; Driver Code","code":"def power ( x , y ) : NEW_LINE INDENT if ( y == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( x == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return x * power ( x , y - 1 ) NEW_LINE DEDENT x = 2 NEW_LINE y = 3 NEW_LINE print ( power ( x , y ) ) NEW_LINE"} {"text":"Babylonian method for square root | Returns the square root of n . Note that the function ; We are using n itself as initial approximation This can definitely be improved ; e decides the accuracy level ; Driver program to test above function","code":"def squareRoot ( n ) : NEW_LINE INDENT x = n NEW_LINE y = 1 NEW_LINE e = 0.000001 NEW_LINE while ( x - y > e ) : NEW_LINE INDENT x = ( x + y ) \/ 2 NEW_LINE y = n \/ x NEW_LINE DEDENT return x NEW_LINE DEDENT n = 50 NEW_LINE print ( \" Square \u2581 root \u2581 of \" , n , \" is \" , round ( squareRoot ( n ) , 6 ) ) NEW_LINE"} {"text":"Average of a stream of numbers | Returns the new average after including x ; Prints average of a stream of numbers ; Driver Code","code":"def getAvg ( prev_avg , x , n ) : NEW_LINE INDENT return ( ( prev_avg * n + x ) \/ ( n + 1 ) ) ; NEW_LINE DEDENT def streamAvg ( arr , n ) : NEW_LINE INDENT avg = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT avg = getAvg ( avg , arr [ i ] , i ) ; NEW_LINE print ( \" Average \u2581 of \u2581 \" , i + 1 , \" \u2581 numbers \u2581 is \u2581 \" , avg ) ; NEW_LINE DEDENT DEDENT arr = [ 10 , 20 , 30 , 40 , 50 , 60 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE streamAvg ( arr , n ) ; NEW_LINE"} {"text":"Average of a stream of numbers | Returns the new average after including x ; Prints average of a stream of numbers ; Driver Code","code":"def getAvg ( x , n , sum ) : NEW_LINE INDENT sum = sum + x ; NEW_LINE return float ( sum ) \/ n ; NEW_LINE DEDENT def streamAvg ( arr , n ) : NEW_LINE INDENT avg = 0 ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT avg = getAvg ( arr [ i ] , i + 1 , sum ) ; NEW_LINE sum = avg * ( i + 1 ) ; NEW_LINE print ( \" Average \u2581 of \u2581 \" , end = \" \" ) ; NEW_LINE print ( i + 1 , end = \" \" ) ; NEW_LINE print ( \" \u2581 numbers \u2581 is \u2581 \" , end = \" \" ) ; NEW_LINE print ( avg ) ; NEW_LINE DEDENT return ; NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 40 , 50 , 60 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE streamAvg ( arr , n ) ; NEW_LINE"} {"text":"Space and time efficient Binomial Coefficient | Returns value of Binomial Coefficient C ( n , k ) ; since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] \/ [ k * ( k - 1 ) * -- -- * 1 ] ; Driver program to test above function","code":"def binomialCoefficient ( 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 = res * ( n - i ) NEW_LINE res = res \/ ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT n = 8 NEW_LINE k = 2 NEW_LINE res = binomialCoefficient ( n , k ) NEW_LINE print ( \" Value \u2581 of \u2581 C ( % \u2581 d , \u2581 % \u2581 d ) \u2581 is \u2581 % \u2581 d \" % ( n , k , res ) ) NEW_LINE"} {"text":"Efficient program to print all prime factors of a given number | Python program to print prime factors ; A function to print all prime factors of a given number n ; Print the number of two 's that divide n ; n must be odd at this point so a skip of 2 ( i = i + 2 ) can be used ; while i divides n , print i ad divide n ; Condition if n is a prime number greater than 2 ; Driver Program to test above function","code":"import math NEW_LINE def primeFactors ( n ) : NEW_LINE INDENT while n % 2 == 0 : NEW_LINE INDENT print 2 , NEW_LINE 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 print i , NEW_LINE n = n \/ i NEW_LINE DEDENT DEDENT if n > 2 : NEW_LINE INDENT print n NEW_LINE DEDENT DEDENT n = 315 NEW_LINE primeFactors ( n ) NEW_LINE"} {"text":"Print all possible combinations of r elements in a given array of size n | The main function that prints all combinations of size r in arr [ ] of size n . This function mainly uses combinationUtil ( ) ; A temporary array to store all combination one by one ; Print all combination using temprary array 'data[] ; arr [ ] -- -> Input Array data [ ] -- -> Temporary array to store current combination start & end -- -> Staring and Ending indexes in arr [ ] index -- -> Current index in data [ ] r -- -> Size of a combination to be printed ; Current combination is ready to be printed , print it ; replace index with all possible elements . The condition \" end - i + 1 \u2581 > = \u2581 \u2581 r - index \" makes sure that including one element at index will make a combination with remaining elements at remaining positions ; Driver Code","code":"def printCombination ( arr , n , r ) : NEW_LINE INDENT data = [ 0 ] * r ; NEW_LINE combinationUtil ( arr , data , 0 , n - 1 , 0 , r ) ; NEW_LINE DEDENT def combinationUtil ( arr , data , start , end , index , r ) : NEW_LINE INDENT if ( index == r ) : NEW_LINE INDENT for j in range ( r ) : NEW_LINE INDENT print ( data [ j ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE return ; NEW_LINE DEDENT i = start ; NEW_LINE while ( i <= end and end - i + 1 >= r - index ) : NEW_LINE INDENT data [ index ] = arr [ i ] ; NEW_LINE combinationUtil ( arr , data , i + 1 , end , index + 1 , r ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE r = 3 ; NEW_LINE n = len ( arr ) ; NEW_LINE printCombination ( arr , n , r ) ; NEW_LINE"} {"text":"Print all possible combinations of r elements in a given array of size n | The main function that prints all combinations of size r in arr [ ] of size n . This function mainly uses combinationUtil ( ) ; A temporary array to store all combination one by one ; Print all combination using temprary array 'data[] ; arr [ ] -- -> Input Array n -- -> Size of input array r -- -> Size of a combination to be printed index -- -> Current index in data [ ] data [ ] -- -> Temporary array to store current combination i -- -> index of current element in arr [ ] ; Current cobination is ready , print it ; When no more elements are there to put in data [ ] ; current is included , put next at next location ; current is excluded , replace it with next ( Note that i + 1 is passed , but index is not changed ) ; Driver Code","code":"def printCombination ( arr , n , r ) : NEW_LINE INDENT data = [ 0 ] * r NEW_LINE combinationUtil ( arr , n , r , 0 , data , 0 ) NEW_LINE DEDENT def combinationUtil ( arr , n , r , index , data , i ) : NEW_LINE INDENT if ( index == r ) : NEW_LINE INDENT for j in range ( r ) : NEW_LINE INDENT print ( data [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE return NEW_LINE DEDENT if ( i >= n ) : NEW_LINE INDENT return NEW_LINE DEDENT data [ index ] = arr [ i ] NEW_LINE combinationUtil ( arr , n , r , index + 1 , data , i + 1 ) NEW_LINE combinationUtil ( arr , n , r , index , data , i + 1 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE r = 3 NEW_LINE n = len ( arr ) NEW_LINE printCombination ( arr , n , r ) NEW_LINE DEDENT"} {"text":"Count all possible groups of size 2 or 3 that have sum as multiple of 3 | Returns count of all possible groups that can be formed from elements of a [ ] . ; Create an array C [ 3 ] to store counts of elements with remainder 0 , 1 and 2. c [ i ] would store count of elements with remainder i ; To store the result ; Count elements with remainder 0 , 1 and 2 ; Case 3. a : Count groups of size 2 from 0 remainder elements ; Case 3. b : Count groups of size 2 with one element with 1 remainder and other with 2 remainder ; Case 4. a : Count groups of size 3 with all 0 remainder elements ; Case 4. b : Count groups of size 3 with all 1 remainder elements ; Case 4. c : Count groups of size 3 with all 2 remainder elements ; Case 4. c : Count groups of size 3 with different remainders ; Return total count stored in res ; Driver program","code":"def findgroups ( arr , n ) : NEW_LINE INDENT c = [ 0 , 0 , 0 ] NEW_LINE res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT c [ arr [ i ] % 3 ] += 1 NEW_LINE DEDENT res += ( ( c [ 0 ] * ( c [ 0 ] - 1 ) ) >> 1 ) NEW_LINE res += c [ 1 ] * c [ 2 ] NEW_LINE res += ( c [ 0 ] * ( c [ 0 ] - 1 ) * ( c [ 0 ] - 2 ) ) \/ 6 NEW_LINE res += ( c [ 1 ] * ( c [ 1 ] - 1 ) * ( c [ 1 ] - 2 ) ) \/ 6 NEW_LINE res += ( ( c [ 2 ] * ( c [ 2 ] - 1 ) * ( c [ 2 ] - 2 ) ) \/ 6 ) NEW_LINE res += c [ 0 ] * c [ 1 ] * c [ 2 ] NEW_LINE return res NEW_LINE DEDENT arr = [ 3 , 6 , 7 , 2 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Required \u2581 number \u2581 of \u2581 groups \u2581 are \" , int ( findgroups ( arr , n ) ) ) NEW_LINE"} {"text":"Smallest power of 2 greater than or equal to n | ; First n in the below condition is for the case where n is 0 ; Driver Code","code":"def nextPowerOf2 ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE if ( n and not ( n & ( n - 1 ) ) ) : NEW_LINE INDENT return n NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT n >>= 1 NEW_LINE count += 1 NEW_LINE DEDENT return 1 << count ; NEW_LINE DEDENT n = 0 NEW_LINE print ( nextPowerOf2 ( n ) ) NEW_LINE"} {"text":"Smallest power of 2 greater than or equal to n | ; Driver Code","code":"def nextPowerOf2 ( n ) : NEW_LINE INDENT p = 1 NEW_LINE if ( n and not ( n & ( n - 1 ) ) ) : NEW_LINE INDENT return n NEW_LINE DEDENT while ( p < n ) : NEW_LINE INDENT p <<= 1 NEW_LINE DEDENT return p ; NEW_LINE DEDENT n = 5 NEW_LINE print ( nextPowerOf2 ( n ) ) ; NEW_LINE"} {"text":"Smallest power of 2 greater than or equal to n | Finds next power of two for n . If n itself is a power of two then returns n ; Driver program to test above function","code":"def nextPowerOf2 ( n ) : NEW_LINE INDENT n -= 1 NEW_LINE 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 += 1 NEW_LINE return n NEW_LINE DEDENT n = 5 NEW_LINE print ( nextPowerOf2 ( n ) ) NEW_LINE"} {"text":"Segregate 0 s and 1 s in an array | Function to segregate 0 s and 1 s ; Counts the no of zeros in arr ; Loop fills the arr with 0 until count ; Loop fills remaining arr space with 1 ; Function to print segregated array ; Driver function","code":"def segregate0and1 ( 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 count = count + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , count ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT for i in range ( count , n ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT DEDENT def print_arr ( arr , n ) : NEW_LINE INDENT print ( \" Array \u2581 after \u2581 segregation \u2581 is \u2581 \" , end = \" \" ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT arr = [ 0 , 1 , 0 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE segregate0and1 ( arr , n ) NEW_LINE print_arr ( arr , n ) NEW_LINE"} {"text":"Segregate 0 s and 1 s in an array | Function to put all 0 s on left and all 1 s on right ; Initialize left and right indexes ; Increment left index while we see 0 at left ; Decrement right index while we see 1 at right ; If left is smaller than right then there is a 1 at left and a 0 at right . Exchange arr [ left ] and arr [ right ] ; driver program to test","code":"def segregate0and1 ( arr , size ) : NEW_LINE INDENT left , right = 0 , size - 1 NEW_LINE while left < right : NEW_LINE INDENT while arr [ left ] == 0 and left < right : NEW_LINE INDENT left += 1 NEW_LINE DEDENT while arr [ right ] == 1 and left < right : NEW_LINE INDENT right -= 1 NEW_LINE DEDENT if left < right : NEW_LINE INDENT arr [ left ] = 0 NEW_LINE arr [ right ] = 1 NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT arr = [ 0 , 1 , 0 , 1 , 1 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE print ( \" Array \u2581 after \u2581 segregation \" ) NEW_LINE print ( segregate0and1 ( arr , arr_size ) ) NEW_LINE"} {"text":"Segregate 0 s and 1 s in an array | Function to put all 0 s on left and all 1 s on right ; Driver Code","code":"def segregate0and1 ( arr , size ) : NEW_LINE INDENT type0 = 0 NEW_LINE type1 = size - 1 NEW_LINE while ( type0 < type1 ) : NEW_LINE INDENT if ( arr [ type0 ] == 1 ) : NEW_LINE INDENT ( arr [ type0 ] , arr [ type1 ] ) = ( arr [ type1 ] , arr [ type0 ] ) NEW_LINE type1 -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT type0 += 1 NEW_LINE DEDENT DEDENT DEDENT arr = [ 0 , 1 , 0 , 1 , 1 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE segregate0and1 ( arr , arr_size ) NEW_LINE print ( \" Array \u2581 after \u2581 segregation \u2581 is \" , end = \" \u2581 \" ) NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT"} {"text":"Distinct adjacent elements in an array | Python program to check if we can make neighbors distinct . ; dict used to count the frequency of each element occurring in the array ; In this loop we count the frequency of element through map m ; mx store the frequency of element which occurs most in array . ; In this loop we calculate the maximum frequency and store it in variable mx . ; By swapping we can adjust array only when the frequency of the element which occurs most is less than or equal to ( n + 1 ) \/ 2 . ; Driver Code","code":"def distantAdjacentElement ( a , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if a [ i ] in m : NEW_LINE INDENT m [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ a [ i ] ] = 1 NEW_LINE DEDENT DEDENT mx = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if mx < m [ a [ i ] ] : NEW_LINE INDENT mx = m [ a [ i ] ] NEW_LINE DEDENT DEDENT if mx > ( n + 1 ) \/\/ 2 : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 7 , 7 , 7 , 7 ] NEW_LINE n = len ( a ) NEW_LINE distantAdjacentElement ( a , n ) NEW_LINE DEDENT"} {"text":"Given an array arr [ ] , find the maximum j | For a given array arr [ ] , returns the maximum j a i such that arr [ j ] > arr [ i ] ; driver code","code":"def maxIndexDiff ( arr , n ) : NEW_LINE INDENT maxDiff = - 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT j = n - 1 NEW_LINE while ( j > i ) : NEW_LINE INDENT if arr [ j ] > arr [ i ] and maxDiff < ( j - i ) : NEW_LINE INDENT maxDiff = j - i NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT DEDENT return maxDiff NEW_LINE DEDENT arr = [ 9 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 18 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE maxDiff = maxIndexDiff ( arr , n ) NEW_LINE print ( maxDiff ) NEW_LINE"} {"text":"Given an array arr [ ] , find the maximum j | For a given array arr , calculates the maximum j a i such that arr [ j ] > arr [ i ] ; Create an array maxfromEnd ; We store this as current answer and look for further larger number to the right side ; Keeping a track of the maximum difference in indices","code":"if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT v = [ 34 , 8 , 10 , 3 , 2 , 80 , 30 , 33 , 1 ] ; NEW_LINE n = len ( v ) ; NEW_LINE maxFromEnd = [ - 38749432 ] * ( n + 1 ) ; NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT maxFromEnd [ i ] = max ( maxFromEnd [ i + 1 ] , v [ i ] ) ; NEW_LINE DEDENT result = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT low = i + 1 ; high = n - 1 ; ans = i ; NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = int ( ( low + high ) \/ 2 ) ; NEW_LINE if ( v [ i ] <= maxFromEnd [ mid ] ) : NEW_LINE INDENT ans = max ( ans , mid ) ; NEW_LINE low = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT DEDENT result = max ( result , ans - i ) ; NEW_LINE DEDENT print ( result , end = \" \" ) ; NEW_LINE DEDENT"} {"text":"Print sorted distinct elements of array | Python3 program to print sorted distinct elements . ; Create a set using array elements ; Print contents of the set . ; Driver code","code":"def printRepeating ( arr , size ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT if arr [ i ] not in s : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in s : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 2 , 1 ] NEW_LINE size = len ( arr ) NEW_LINE printRepeating ( arr , size ) NEW_LINE DEDENT"} {"text":"Minimum swaps to make two arrays identical | Function returns the minimum number of swaps required to sort the array This method is taken from below post https : www . geeksforgeeks . org \/ minimum - number - swaps - required - sort - array \/ ; Create an array of pairs where first element is array element and second element is position of first element ; Sort the array by array element values to get right position of every element as second element of pair . ; To keep track of visited elements . Initialize all elements as not visited or false . ; Initialize result ; Traverse array elements ; Already swapped and corrected or already present at correct pos ; Find out the number of node in this cycle and add in ans ; Move to next node ; Update answer by adding current cycle . ; Return result ; Method returns minimum number of swap to mak array B same as array A ; map to store position of elements in array B we basically store element to index mapping . ; now we 're storing position of array A elements in array B. ; Returing minimum swap for sorting in modified array B as final answer ; Driver code","code":"def minSwapsToSort ( arr , n ) : NEW_LINE INDENT arrPos = [ [ 0 for x in range ( 2 ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arrPos [ i ] [ 0 ] = arr [ i ] NEW_LINE arrPos [ i ] [ 1 ] = i NEW_LINE DEDENT arrPos . sort ( ) NEW_LINE vis = [ False ] * ( n ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] or arrPos [ i ] [ 1 ] == i ) : NEW_LINE INDENT continue NEW_LINE DEDENT cycle_size = 0 NEW_LINE j = i NEW_LINE while ( not vis [ j ] ) : NEW_LINE INDENT vis [ j ] = 1 NEW_LINE j = arrPos [ j ] [ 1 ] NEW_LINE cycle_size += 1 NEW_LINE DEDENT ans += ( cycle_size - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def minSwapToMakeArraySame ( a , b , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ b [ i ] ] = i NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT b [ i ] = mp [ a [ i ] ] NEW_LINE DEDENT return minSwapsToSort ( b , n ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 3 , 6 , 4 , 8 ] NEW_LINE b = [ 4 , 6 , 8 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( minSwapToMakeArraySame ( a , b , n ) ) NEW_LINE DEDENT"} {"text":"k | Function to find k - th missing element ; interating over the array ; check if i - th and ( i + 1 ) - th element are not consecutive ; save their difference ; check for difference and given k ; if found ; Input array ; k - th missing element to be found in the array ; calling function to find missing element","code":"def missingK ( a , k , n ) : NEW_LINE INDENT difference = 0 NEW_LINE ans = 0 NEW_LINE count = k NEW_LINE flag = 0 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT difference = 0 NEW_LINE if ( ( a [ i ] + 1 ) != a [ i + 1 ] ) : NEW_LINE INDENT difference += ( a [ i + 1 ] - a [ i ] ) - 1 NEW_LINE if ( difference >= count ) : NEW_LINE INDENT ans = a [ i ] + count NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT count -= difference NEW_LINE DEDENT DEDENT DEDENT if ( flag ) : NEW_LINE INDENT return ans NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT a = [ 1 , 5 , 11 , 19 ] NEW_LINE k = 11 NEW_LINE n = len ( a ) NEW_LINE missing = missingK ( a , k , n ) NEW_LINE print ( missing ) NEW_LINE"} {"text":"k | Function to find kth missing number ; If the total missing number count is equal to k we can iterate backwards for the first missing number and that will be the answer . ; To further optimize we check if the previous element ' s \u2581 \u2581 missing \u2581 number \u2581 count \u2581 is \u2581 equal \u2581 \u2581 to \u2581 k . \u2581 Eg : \u2581 arr \u2581 = \u2581 [ 4,5,6,7,8 ] \u2581 \u2581 If \u2581 you \u2581 observe \u2581 in \u2581 the \u2581 example \u2581 array , \u2581 \u2581 the \u2581 total \u2581 count \u2581 of \u2581 missing \u2581 numbers \u2581 for \u2581 all \u2581 \u2581 the \u2581 indices \u2581 are \u2581 same , \u2581 and \u2581 we \u2581 are \u2581 \u2581 aiming \u2581 to \u2581 narrow \u2581 down \u2581 the \u2581 \u2581 search \u2581 window \u2581 and \u2581 achieve \u2581 O ( logn ) \u2581 \u2581 time \u2581 complexity \u2581 which \u2581 \u2581 otherwise \u2581 would ' ve been O ( n ) . ; Else we return arr [ mid ] - 1. ; Here we appropriately narrow down the search window . ; In case the upper limit is - ve it means the missing number set is 1 , 2 , . . , k and hence we directly return k . ; Else we find the residual count of numbers which we 'd then add to arr[u] and get the missing kth number. ; Return arr [ u ] + k ; Driver Code ; Function Call","code":"def missingK ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE l = 0 NEW_LINE u = n - 1 NEW_LINE mid = 0 NEW_LINE while ( l <= u ) : NEW_LINE INDENT mid = ( l + u ) \/\/ 2 ; NEW_LINE numbers_less_than_mid = arr [ mid ] - ( mid + 1 ) ; NEW_LINE if ( numbers_less_than_mid == k ) : NEW_LINE if ( mid > 0 and ( arr [ mid - 1 ] - ( mid ) ) == k ) : NEW_LINE INDENT u = mid - 1 ; NEW_LINE continue ; NEW_LINE DEDENT return arr [ mid ] - 1 ; NEW_LINE if ( numbers_less_than_mid < k ) : NEW_LINE l = mid + 1 ; NEW_LINE elif ( k < numbers_less_than_mid ) : NEW_LINE u = mid - 1 ; NEW_LINE DEDENT if ( u < 0 ) : NEW_LINE INDENT return k ; NEW_LINE DEDENT less = arr [ u ] - ( u + 1 ) ; NEW_LINE k -= less ; NEW_LINE return arr [ u ] + k ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 7 , 11 ] ; NEW_LINE k = 5 ; NEW_LINE print ( \" Missing \u2581 kth \u2581 number \u2581 = \u2581 \" + str ( missingK ( arr , k ) ) ) NEW_LINE DEDENT"} {"text":"Alternate Odd and Even Nodes in a Singly Linked List | Link list node ; A utility function to print linked list ; Function to create newNode in a linkedlist ; Function to insert at beginning ; Function to rearrange the odd and even nodes ; Odd Value in Even Position Add pointer to current node in odd stack ; Even Value in Odd Position Add pointer to current node in even stack ; Swap Data at the top of two stacks ; Driver code","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT 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 ( \" \" ) NEW_LINE DEDENT def newNode ( key ) : NEW_LINE INDENT temp = Node ( 0 ) NEW_LINE temp . data = key NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def insertBeg ( head , val ) : NEW_LINE INDENT temp = newNode ( val ) NEW_LINE temp . next = head NEW_LINE head = temp NEW_LINE return head NEW_LINE DEDENT def rearrangeOddEven ( head ) : NEW_LINE INDENT odd = [ ] NEW_LINE even = [ ] NEW_LINE i = 1 NEW_LINE while ( head != None ) : NEW_LINE INDENT if ( head . data % 2 != 0 and i % 2 == 0 ) : NEW_LINE INDENT odd . append ( head ) NEW_LINE DEDENT elif ( head . data % 2 == 0 and i % 2 != 0 ) : NEW_LINE INDENT even . append ( head ) NEW_LINE DEDENT head = head . next NEW_LINE i = i + 1 NEW_LINE DEDENT while ( len ( odd ) != 0 and len ( even ) != 0 ) : NEW_LINE INDENT odd [ - 1 ] . data , even [ - 1 ] . data = even [ - 1 ] . data , odd [ - 1 ] . data NEW_LINE odd . pop ( ) NEW_LINE even . pop ( ) NEW_LINE DEDENT return head NEW_LINE DEDENT head = newNode ( 8 ) NEW_LINE head = insertBeg ( head , 7 ) NEW_LINE head = insertBeg ( head , 6 ) NEW_LINE head = insertBeg ( head , 5 ) NEW_LINE head = insertBeg ( head , 3 ) NEW_LINE head = insertBeg ( head , 2 ) NEW_LINE head = insertBeg ( head , 1 ) NEW_LINE print ( \" Linked \u2581 List : \" ) NEW_LINE printList ( head ) NEW_LINE rearrangeOddEven ( head ) NEW_LINE print ( \" Linked \u2581 List \u2581 after \u2581 \" , \" Rearranging : \" ) NEW_LINE printList ( head ) NEW_LINE"} {"text":"Alternate Odd and Even Nodes in a Singly Linked List | Structure node ; A utility function to print linked list ; Function to create newNode in a linkedlist ; Function to insert at beginning ; Function to rearrange the odd and even nodes ; Step 1 : Segregate even and odd nodes Step 2 : Split odd and even lists Step 3 : Merge even list into odd list ; Step 1 : Segregate Odd and Even Nodes ; Backup next pointer of temp ; If temp is odd move the node to beginning of list ; Advance Temp Pointer ; Step 2 Split the List into Odd and even ; End the odd List ( Make last node None ) ; Step 3 : Merge Even List into odd ; While both lists are not exhausted Backup next pointers of i and j ; ptr points to the latest node added ; Advance i and j pointers ; Odd list exhausts before even , append remainder of even list to odd . ; The case where even list exhausts before odd list is automatically handled since we merge the even list into the odd list ; Driver Code","code":"class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . next = None NEW_LINE DEDENT 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 def newNode ( key ) : NEW_LINE INDENT temp = Node ( ) NEW_LINE temp . data = key NEW_LINE temp . next = None NEW_LINE return temp NEW_LINE DEDENT def insertBeg ( head , val ) : NEW_LINE INDENT temp = newNode ( val ) NEW_LINE temp . next = head NEW_LINE head = temp NEW_LINE return head NEW_LINE DEDENT def rearrange ( head ) : NEW_LINE INDENT even = None NEW_LINE temp = None NEW_LINE prev_temp = None NEW_LINE i = None NEW_LINE j = None NEW_LINE k = None NEW_LINE l = None NEW_LINE ptr = None NEW_LINE temp = ( head ) . next NEW_LINE prev_temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT x = temp . next NEW_LINE if ( temp . data % 2 != 0 ) : NEW_LINE INDENT prev_temp . next = x NEW_LINE temp . next = ( head ) NEW_LINE ( head ) = temp NEW_LINE DEDENT else : NEW_LINE INDENT prev_temp = temp NEW_LINE DEDENT temp = x NEW_LINE DEDENT temp = ( head ) . next NEW_LINE prev_temp = ( head ) NEW_LINE while ( temp != None and temp . data % 2 != 0 ) : NEW_LINE INDENT prev_temp = temp NEW_LINE temp = temp . next NEW_LINE DEDENT even = temp NEW_LINE prev_temp . next = None NEW_LINE i = head NEW_LINE j = even NEW_LINE while ( j != None and i != None ) : NEW_LINE INDENT k = i . next NEW_LINE l = j . next NEW_LINE i . next = j NEW_LINE j . next = k NEW_LINE ptr = j NEW_LINE i = k NEW_LINE j = l NEW_LINE DEDENT if ( i == None ) : NEW_LINE INDENT ptr . next = j NEW_LINE DEDENT return head NEW_LINE DEDENT head = newNode ( 8 ) NEW_LINE head = insertBeg ( head , 7 ) NEW_LINE head = insertBeg ( head , 6 ) NEW_LINE head = insertBeg ( head , 3 ) NEW_LINE head = insertBeg ( head , 5 ) NEW_LINE head = insertBeg ( head , 1 ) NEW_LINE head = insertBeg ( head , 2 ) NEW_LINE head = insertBeg ( head , 10 ) NEW_LINE print ( \" Linked \u2581 List : \" ) NEW_LINE printList ( head ) NEW_LINE print ( \" Rearranged \u2581 List \" ) NEW_LINE head = rearrange ( head ) NEW_LINE printList ( head ) NEW_LINE"} {"text":"Rotate all Matrix elements except the diagonal K times by 90 degrees in clockwise direction | Function to print the matrix ; Iterate over the rows ; Iterate over the columns ; Print the value ; Function to perform the swapping of matrix elements in clockwise manner ; Stores the last row ; Stores the last column ; Perform the swaps ; Function to rotate non - diagonal elements of the matrix K times in clockwise direction ; Update K to K % 4 ; Iterate until K is positive ; Iterate each up to N \/ 2 - th row ; Iterate each column from i to N - i - 1 ; Check if the element at i , j is not a diagonal element ; Perform the swapping ; Print the matrix ; Driver Code","code":"def printMat ( mat ) : NEW_LINE INDENT for i in range ( len ( mat ) ) : NEW_LINE INDENT for j in range ( len ( mat [ 0 ] ) ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def performSwap ( mat , i , j ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE ei = N - 1 - i NEW_LINE ej = N - 1 - j NEW_LINE temp = mat [ i ] [ j ] NEW_LINE mat [ i ] [ j ] = mat [ ej ] [ i ] NEW_LINE mat [ ej ] [ i ] = mat [ ei ] [ ej ] NEW_LINE mat [ ei ] [ ej ] = mat [ j ] [ ei ] NEW_LINE mat [ j ] [ ei ] = temp NEW_LINE DEDENT def rotate ( mat , N , K ) : NEW_LINE INDENT K = K % 4 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT for i in range ( int ( N \/ 2 ) ) : NEW_LINE INDENT for j in range ( i , N - i - 1 ) : NEW_LINE INDENT if ( i != j and ( i + j ) != N - 1 ) : NEW_LINE INDENT performSwap ( mat , i , j ) NEW_LINE DEDENT DEDENT DEDENT K -= 1 NEW_LINE DEDENT printMat ( mat ) NEW_LINE DEDENT K = 5 NEW_LINE mat = [ [ 1 , 2 , 3 , 4 ] , [ 6 , 7 , 8 , 9 ] , [ 11 , 12 , 13 , 14 ] , [ 16 , 17 , 18 , 19 ] ] NEW_LINE N = len ( mat ) NEW_LINE rotate ( mat , N , K ) NEW_LINE"} {"text":"Minimum rotations required to get the same string | Returns count of rotations to get the same string back . ; tmp is the concatenated string . ; substring from i index of original string size . ; if substring matches with original string then we will come out of the loop . ; Driver code","code":"def findRotations ( str ) : NEW_LINE INDENT tmp = str + str NEW_LINE n = len ( str ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT substring = tmp [ i : i + n ] NEW_LINE if ( str == substring ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" abc \" NEW_LINE print ( findRotations ( str ) ) NEW_LINE DEDENT"} {"text":"Count of elements which are power of 2 in a given range subarray for Q queries | Python3 implementation to find elements that are a power of two ; prefix [ i ] is going to store the number of elements which are a power of two till i ( including i ) . ; Function to find the maximum range whose sum is divisible by M . ; Calculate the prefix sum ; Function to return the number of elements which are a power of two in a subarray ; Driver code","code":"MAX = 10000 NEW_LINE prefix = [ 0 ] * ( MAX + 1 ) NEW_LINE def isPowerOfTwo ( x ) : NEW_LINE INDENT if ( x and ( not ( x & ( x - 1 ) ) ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def computePrefix ( n , a ) : NEW_LINE INDENT if ( isPowerOfTwo ( a [ 0 ] ) ) : NEW_LINE INDENT prefix [ 0 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] NEW_LINE if ( isPowerOfTwo ( a [ i ] ) ) : NEW_LINE INDENT prefix [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT def query ( L , R ) : NEW_LINE INDENT return prefix [ R ] - prefix [ L - 1 ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 3 , 8 , 5 , 2 , 5 , 10 ] NEW_LINE N = len ( A ) NEW_LINE Q = 2 NEW_LINE computePrefix ( N , A ) NEW_LINE print ( query ( 0 , 4 ) ) NEW_LINE print ( query ( 3 , 5 ) ) NEW_LINE DEDENT"} {"text":"Count of integral coordinates that lies inside a Square | Function to calculate the integral points inside a square ; Driver Code","code":"def countIntgralPoints ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT print ( ( y2 - y1 - 1 ) * ( x2 - x1 - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x1 = 1 NEW_LINE y1 = 1 NEW_LINE x2 = 4 NEW_LINE y2 = 4 NEW_LINE countIntgralPoints ( x1 , y1 , x2 , y2 ) NEW_LINE DEDENT"} {"text":"Find Next number having distinct digits from the given number N | Function to find the next distinct digits number ; Loop to find the distinct digits using hash array and the number of digits ; Loop to find the most significant distinct digit of the next number ; Condition to check if the number is possible with the same number of digits count ; Condition to check if the desired most siginificant distinct digit is found ; Loop to find the minimum next digit which is not present in the number ; Computation of the number ; Condition to check if the number is greater than the given number ; Driver Code","code":"def findNextNumber ( n ) : NEW_LINE INDENT h = [ 0 for i in range ( 10 ) ] NEW_LINE i = 0 NEW_LINE msb = n NEW_LINE rem = 0 NEW_LINE next_num = - 1 NEW_LINE count = 0 NEW_LINE while ( msb > 9 ) : NEW_LINE INDENT rem = msb % 10 NEW_LINE h [ rem ] = 1 NEW_LINE msb \/\/= 10 NEW_LINE count += 1 NEW_LINE DEDENT h [ msb ] = 1 NEW_LINE count += 1 NEW_LINE for i in range ( msb + 1 , 10 , 1 ) : NEW_LINE INDENT if ( h [ i ] == 0 ) : NEW_LINE INDENT next_num = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( next_num == - 1 ) : NEW_LINE INDENT for i in range ( 1 , msb , 1 ) : NEW_LINE INDENT if ( h [ i ] == 0 ) : NEW_LINE INDENT next_num = i NEW_LINE count += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( next_num > 0 ) : NEW_LINE INDENT for i in range ( 0 , 10 , 1 ) : NEW_LINE INDENT if ( h [ i ] == 0 ) : NEW_LINE INDENT msb = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( 1 , count , 1 ) : NEW_LINE INDENT next_num = ( ( next_num * 10 ) + msb ) NEW_LINE DEDENT if ( next_num > n ) : NEW_LINE INDENT print ( next_num ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Possible \" ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( \" Not \u2581 Possible \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2019 NEW_LINE findNextNumber ( n ) NEW_LINE DEDENT"} {"text":"Find a triplet ( A , B , C ) such that 3 * A + 5 * B + 7 * C is equal to N | Function to find a triplet ( A , B , C ) such that 3 * A + 5 * B + 7 * C is N ; Iterate over the range [ 0 , N7 ] ; Iterate over the range [ 0 , N5 ] ; Find the value of A ; If A is greater than or equal to 0 and divisible by 3 ; Otherwise , print - 1 ; Driver Code","code":"def CalculateValues ( N ) : NEW_LINE INDENT for C in range ( 0 , N \/\/ 7 + 1 ) : NEW_LINE INDENT for B in range ( 0 , N \/\/ 5 + 1 ) : NEW_LINE INDENT A = N - 7 * C - 5 * B NEW_LINE if ( A >= 0 and A % 3 == 0 ) : NEW_LINE INDENT print ( \" A \u2581 = \" , A \/ 3 , \" , \u2581 B \u2581 = \" , B , \" , \u2581 \\ \u2581 C \u2581 = \" , C , sep = \" \u2581 \" ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 19 NEW_LINE CalculateValues ( 19 ) NEW_LINE DEDENT"} {"text":"Minimize total time taken by two persons to visit N cities such that none of them meet | Function to find the minimum time to visit all the cities such that both the person never meets ; Initialize sum as 0 ; Find the maximum element ; Traverse the array ; Increment sum by arr [ i ] ; Prmaximum of 2 * T and sum ; Driver Code ; Function Call","code":"def minimumTime ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE T = max ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT print ( max ( 2 * T , sum ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 8 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE minimumTime ( arr , N ) NEW_LINE DEDENT"} {"text":"Lexicographically largest string possible by reversing substrings having even number of 1 s | Function to find the lexicographically maximum string by reversing substrings having even numbers of 1 s ; Store size of string ; Traverse the string ; Count the number of 1 s ; Stores the starting index ; Stores the end index ; Increment count , when 1 is encountered ; Traverse the remaining string ; temp is for Reverse the string from starting and end index ; Printing the string ; Driver Code","code":"def lexicographicallyMax ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE beg = i NEW_LINE end = i NEW_LINE if ( s [ i ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( s [ j ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count % 2 == 0 and count != 0 ) : NEW_LINE INDENT end = j NEW_LINE break NEW_LINE DEDENT DEDENT temp = s [ beg : end + 1 ] NEW_LINE temp = temp [ : : - 1 ] NEW_LINE s = s [ 0 : beg ] + temp + s [ end + 1 : ] NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT S = \"0101\" NEW_LINE lexicographicallyMax ( S ) NEW_LINE"} {"text":"Count maximum possible pairs from an array having sum K | Function to count the maximum number of pairs from given array with sum K ; Sort array in increasing order ; Stores the final result ; Initialize the left and right pointers ; Traverse array until start < end ; Decrement right by 1 ; Increment left by 1 ; Increment result and left pointer by 1 and decrement right pointer by 1 ; Print the result ; Driver Code ; Function Call","code":"def maxPairs ( nums , k ) : NEW_LINE INDENT nums = sorted ( nums ) NEW_LINE result = 0 NEW_LINE start , end = 0 , len ( nums ) - 1 NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( nums [ start ] + nums [ end ] > k ) : NEW_LINE INDENT end -= 1 NEW_LINE DEDENT elif ( nums [ start ] + nums [ end ] < k ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT start += 1 NEW_LINE end -= 1 NEW_LINE result += 1 NEW_LINE DEDENT DEDENT print ( result ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 5 NEW_LINE maxPairs ( arr , K ) NEW_LINE DEDENT"} {"text":"Count maximum possible pairs from an array having sum K | Function to find the maximum number of pairs with a sum K such that same element can 't be used twice ; Initialize a hashm ; Store the final result ; Iterate over the array nums [ ] ; Decrement its frequency in m and increment the result by 1 ; Increment its frequency by 1 if it is already present in m . Otherwise , set its frequency to 1 ; Print the result ; Driver code ; Function Call","code":"def maxPairs ( nums , k ) : NEW_LINE INDENT m = { } NEW_LINE result = 0 NEW_LINE for i in nums : NEW_LINE INDENT if ( ( i in m ) and m [ i ] > 0 ) : NEW_LINE INDENT m [ i ] = m [ i ] - 1 NEW_LINE result += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if k - i in m : NEW_LINE INDENT m [ k - i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ k - i ] = 1 NEW_LINE DEDENT DEDENT DEDENT print ( result ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE K = 5 NEW_LINE maxPairs ( arr , K ) NEW_LINE"} {"text":"Print indices of array elements whose removal makes the sum of odd and even | Function to find indices of array elements whose removal makes the sum of odd and even indexed array elements equal ; Stores size of array ; Store prefix sum of odd index array elements ; Store prefix sum of even index array elements ; Update even [ 0 ] ; Traverse the given array ; Update odd [ i ] ; Update even [ i ] ; If the current index is an even number ; Update even [ i ] ; If the current index is an odd number ; Update odd [ i ] ; Check if at least one index found or not that satisfies the condition ; Store odd indices sum by removing 0 - th index ; Store even indices sum by removing 0 - th index ; If p and q are equal ; Traverse the array arr ; If i is an even number ; Update p by removing the i - th element ; Update q by removing the i - th element ; Update q by removing the i - th element ; Update p by removing the i - th element ; If odd index values sum is equal to even index values sum ; Set the find variable ; Print the current index ; If no index found ; Print not possible ; Driver Code","code":"def removeIndicesToMakeSumEqual ( arr ) : NEW_LINE INDENT N = len ( arr ) ; NEW_LINE odd = [ 0 ] * N ; NEW_LINE even = [ 0 ] * N ; NEW_LINE even [ 0 ] = arr [ 0 ] ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT odd [ i ] = odd [ i - 1 ] ; NEW_LINE even [ i ] = even [ i - 1 ] ; NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT even [ i ] += arr [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT odd [ i ] += arr [ i ] ; NEW_LINE DEDENT DEDENT find = False ; NEW_LINE p = odd [ N - 1 ] ; NEW_LINE q = even [ N - 1 ] - arr [ 0 ] ; NEW_LINE if ( p == q ) : NEW_LINE INDENT print ( \"0 \u2581 \" ) ; NEW_LINE find = True ; NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT p = even [ N - 1 ] - even [ i - 1 ] - arr [ i ] + odd [ i - 1 ] ; NEW_LINE q = odd [ N - 1 ] - odd [ i - 1 ] + even [ i - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT q = odd [ N - 1 ] - odd [ i - 1 ] - arr [ i ] + even [ i - 1 ] ; NEW_LINE p = even [ N - 1 ] - even [ i - 1 ] + odd [ i - 1 ] ; NEW_LINE DEDENT if ( p == q ) : NEW_LINE INDENT find = True ; NEW_LINE print ( i , end = \" \" ) ; NEW_LINE DEDENT DEDENT if ( find == False ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 1 , 6 , 2 ] ; NEW_LINE removeIndicesToMakeSumEqual ( arr ) ; NEW_LINE DEDENT"} {"text":"Minimum removals required to make a given array Bitonic | Function to coutnt minimum array elements required to be removed to make an array bitonic ; left [ i ] : Stores the length of LIS up to i - th index ; right [ i ] : Stores the length of decreasing subsequence over the range [ i , N ] ; Calculate the length of LIS up to i - th index ; Traverse the array upto i - th index ; If arr [ j ] is less than arr [ i ] ; Update left [ i ] ; Calculate the length of decreasing subsequence over the range [ i , N ] ; Traverse right [ ] array ; If arr [ i ] is greater than arr [ j ] ; Update right [ i ] ; Stores length of the longest bitonic array ; Traverse left [ ] and right [ ] array ; Update maxLen ; Function to prminimum removals required to make given array bitonic ; Driver Code","code":"def min_element_removal ( arr , N ) : NEW_LINE INDENT left = [ 1 ] * N NEW_LINE right = [ 1 ] * ( N ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ j ] < arr [ i ] ) : NEW_LINE INDENT left [ i ] = max ( left [ i ] , left [ j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( N - 1 , i , - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT right [ i ] = max ( right [ i ] , right [ j ] + 1 ) NEW_LINE DEDENT DEDENT DEDENT maxLen = 0 NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT maxLen = max ( maxLen , left [ i ] + right [ i ] - 1 ) NEW_LINE DEDENT print ( ( N - maxLen ) ) NEW_LINE DEDENT def makeBitonic ( arr , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT print ( \"0\" ) NEW_LINE return NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT if ( arr [ 0 ] != arr [ 1 ] ) : NEW_LINE INDENT print ( \"0\" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \"1\" ) NEW_LINE DEDENT return NEW_LINE DEDENT min_element_removal ( arr , N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 1 , 5 , 6 , 2 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE makeBitonic ( arr , N ) NEW_LINE DEDENT"} {"text":"Count subarrays having an equal count of 0 s and 1 s segregated | Function to count subarrays having equal count of 0 s and 1 s with all 0 s and all 1 s grouped together ; Stores the count of subarrays ; If current element is different from the next array element ; Increment count ; Count the frequency of 1 s and 0 s ; Increment count ; Print the final count ; Driver Code ; Function Call","code":"def countSubarrays ( A , N ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] != A [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE j = i - 1 ; k = i + 2 ; NEW_LINE while ( j >= 0 and k < N and A [ j ] == A [ i ] and A [ k ] == A [ i + 1 ] ) : NEW_LINE INDENT ans += 1 ; NEW_LINE j -= 1 ; NEW_LINE k += 1 ; NEW_LINE DEDENT DEDENT DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 1 , 0 , 0 , 1 , 0 ] ; NEW_LINE N = len ( A ) ; NEW_LINE countSubarrays ( A , N ) ; NEW_LINE DEDENT"} {"text":"Count quadruples of given type from given array | Python3 program of the above approach ; lcount [ i ] [ j ] : Stores the count of i on left of index j ; rcount [ i ] [ j ] : Stores the count of i on right of index j ; Function to count unique elements on left and right of any index ; Find the maximum array element ; Calculate prefix sum of counts of each value ; Calculate suffix sum of counts of each value ; Function to count quadruples of the required type ; Driver Code","code":"maxN = 2002 NEW_LINE lcount = [ [ 0 for i in range ( maxN ) ] for j in range ( maxN ) ] NEW_LINE rcount = [ [ 0 for i in range ( maxN ) ] for j in range ( maxN ) ] NEW_LINE def fill_counts ( a , n ) : NEW_LINE INDENT maxA = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > maxA ) : NEW_LINE INDENT maxA = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT lcount [ a [ i ] ] [ i ] = 1 NEW_LINE rcount [ a [ i ] ] [ i ] = 1 NEW_LINE DEDENT for i in range ( maxA + 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT lcount [ i ] [ j ] = ( lcount [ i ] [ j - 1 ] + lcount [ i ] [ j ] ) NEW_LINE DEDENT for j in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT rcount [ i ] [ j ] = ( rcount [ i ] [ j + 1 ] + rcount [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT def countSubsequence ( a , n ) : NEW_LINE INDENT fill_counts ( a , n ) NEW_LINE answer = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT answer += ( lcount [ a [ j ] ] [ i - 1 ] * rcount [ a [ i ] ] [ j + 1 ] ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT a = [ 1 , 2 , 3 , 2 , 1 , 3 , 2 ] NEW_LINE print ( countSubsequence ( a , 7 ) ) NEW_LINE"} {"text":"Reduce string by removing outermost parenthesis from each primitive substring | Function to remove the outermost parentheses of every primitive substring from the given string ; Stores the resultant string ; Stores the count of opened parentheses ; Traverse the string ; If opening parenthesis is encountered and their count exceeds 0 ; Include the character ; If closing parenthesis is encountered and their count is less than count of opening parentheses ; Include the character ; Return the resultant string ; Driver Code","code":"def removeOuterParentheses ( S ) : NEW_LINE INDENT res = \" \" NEW_LINE count = 0 NEW_LINE for c in S : NEW_LINE INDENT if ( c == ' ( ' and count > 0 ) : NEW_LINE INDENT res += c NEW_LINE DEDENT if ( c == ' ( ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( c == ' ) ' and count > 1 ) : NEW_LINE INDENT res += c NEW_LINE DEDENT if ( c == ' ) ' ) : NEW_LINE count -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = \" ( ( ) ( ) ) ( ( ) ) ( ) \" NEW_LINE print ( removeOuterParentheses ( S ) ) NEW_LINE DEDENT"} {"text":"Length of longest subarray with increasing contiguous elements | Function to find the longest subarray with increasing contiguous elements ; Stores the length of required longest subarray ; Stores the length of length of longest such subarray from ith index ; If consecutive elements are increasing and differ by 1 ; Otherwise ; Update the longest subarray obtained so far ; Return the length obtained ; Driver Code","code":"def maxiConsecutiveSubarray ( arr , N ) : NEW_LINE INDENT maxi = 0 ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT cnt = 1 ; NEW_LINE for j in range ( i , N - 1 ) : NEW_LINE INDENT if ( arr [ j + 1 ] == arr [ j ] + 1 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT maxi = max ( maxi , cnt ) ; NEW_LINE i = j ; NEW_LINE DEDENT return maxi ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 ; NEW_LINE arr = [ 1 , 3 , 4 , 2 , 3 , 4 , 2 , 3 , 5 , 6 , 7 ] ; NEW_LINE print ( maxiConsecutiveSubarray ( arr , N ) ) ; NEW_LINE DEDENT"} {"text":"Length of longest subsequence having sum of digits of each element as a Composite Number | Python3 implementation of the above approach ; Function to generate prime numbers using Sieve of Eratosthenes ; Set 0 and 1 as non - prime ; If p is a prime ; Set all multiples of p as non - prime ; Function to find the digit sum of a given number ; Stores the sum of digits ; Extract digits and add to the sum ; Return the sum of the digits ; Function to find the longest subsequence with sum of digits of each element equal to a composite number ; Calculate sum of digits of current array element ; If sum of digits equal to 1 ; If sum of digits is a prime ; Driver Code ; Function call","code":"N = 100005 NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= p_size : 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 p += 1 NEW_LINE DEDENT DEDENT def digitSum ( number ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( number > 0 ) : NEW_LINE INDENT sum += ( number % 10 ) NEW_LINE number \/\/= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def longestCompositeDigitSumSubsequence ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE prime = [ True ] * ( N + 1 ) NEW_LINE SieveOfEratosthenes ( prime , N ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT res = digitSum ( arr [ i ] ) NEW_LINE if ( res == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not prime [ res ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 13 , 55 , 7 , 3 , 5 , 1 , 10 , 21 , 233 , 144 , 89 ] NEW_LINE n = len ( arr ) NEW_LINE longestCompositeDigitSumSubsequence ( arr , n ) NEW_LINE DEDENT"} {"text":"Sum of specially balanced nodes from a given Binary Tree | Structure of Binary Tree ; Function to create a new node ; Return the created node ; Function to insert a node in the tree ; Left insertion ; Right insertion ; Return the root node ; Function to find sum of specially balanced nodes in the Tree ; Base Case ; Find the left subtree sum ; Find the right subtree sum ; Condition of specially balanced node ; Condition of specially balanced node ; Return the sum ; Function to build the binary tree ; Form root node of the tree ; Insert nodes into tree ; Create a new Node ; Insert the node ; Return the root of the Tree ; Function to find the sum of specially balanced nodes ; Build Tree ; Stores the sum of specially balanced node ; Function Call ; Print required sum ; Driver code ; Given nodes ; Given root ; Given path info of nodes from root ; Given node values ; Function Call","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newnode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp NEW_LINE DEDENT def insert ( s , i , N , root , temp ) : NEW_LINE INDENT if ( i == N ) : NEW_LINE INDENT return temp NEW_LINE DEDENT if ( s [ i ] == ' L ' ) : NEW_LINE INDENT root . left = insert ( s , i + 1 , N , root . left , temp ) NEW_LINE DEDENT else : NEW_LINE INDENT root . right = insert ( s , i + 1 , N , root . right , temp ) NEW_LINE DEDENT return root NEW_LINE DEDENT def SBTUtil ( root , sum ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return [ 0 , sum ] NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT return [ root . data , sum ] NEW_LINE DEDENT left , sum = SBTUtil ( root . left , sum ) NEW_LINE right , sum = SBTUtil ( root . right , sum ) NEW_LINE if ( root . left and root . right ) : NEW_LINE INDENT if ( ( left % 2 == 0 and right % 2 != 0 ) or ( left % 2 != 0 and right % 2 == 0 ) ) : NEW_LINE INDENT sum += root . data NEW_LINE DEDENT DEDENT return [ left + right + root . data , sum ] NEW_LINE DEDENT def build_tree ( R , N , str , values ) : NEW_LINE INDENT root = newnode ( R ) NEW_LINE for i in range ( 0 , N - 1 ) : NEW_LINE INDENT s = str [ i ] NEW_LINE x = values [ i ] NEW_LINE temp = newnode ( x ) NEW_LINE root = insert ( s , 0 , len ( s ) , root , temp ) NEW_LINE DEDENT return root NEW_LINE DEDENT def speciallyBalancedNodes ( R , N , str , values ) : NEW_LINE INDENT root = build_tree ( R , N , str , values ) NEW_LINE sum = 0 NEW_LINE tmp , sum = SBTUtil ( root , sum ) NEW_LINE print ( sum , end = ' \u2581 ' ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 7 NEW_LINE R = 12 NEW_LINE str = [ \" L \" , \" R \" , \" RL \" , \" RR \" , \" RLL \" , \" RLR \" ] NEW_LINE values = [ 17 , 16 , 4 , 9 , 2 , 3 ] NEW_LINE speciallyBalancedNodes ( R , N , str , values ) NEW_LINE DEDENT"} {"text":"Pair having all other given pairs lying between its minimum and maximum | Function to find the position of the pair that covers every pair in the array arr ; Stores the index of the resultant pair ; To count the occurences ; Iterate to check every pair ; Set count to 0 ; Condition to checked for overlapping of pairs ; If that pair can cover all other pairs then store its position ; If position not found ; Otherwise ; Driver Code ; Given array of pairs ; Function Call","code":"def position ( arr , N ) : NEW_LINE INDENT pos = - 1 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = 0 ; NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] <= arr [ j ] [ 0 ] and arr [ i ] [ 1 ] >= arr [ j ] [ 1 ] ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT if ( count == N ) : NEW_LINE INDENT pos = i ; NEW_LINE DEDENT DEDENT if ( pos == - 1 ) : NEW_LINE INDENT print ( pos ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( pos + 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 3 , 3 ] , [ 1 , 3 ] , [ 2 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] ] ; NEW_LINE N = len ( arr ) ; NEW_LINE position ( arr , N ) ; NEW_LINE DEDENT"} {"text":"Pair having all other given pairs lying between its minimum and maximum | Python3 program for the above approach ; Function to find the position of the pair that covers every pair in the array arr [ ] [ ] ; Position to store the index ; Stores the minimum second value ; Stores the maximum first value ; Iterate over the array of pairs ; Update right maximum ; Update left minimum ; Iterate over the array of pairs ; If any pair exists with value { left , right then store it ; Print the answer ; Driver Code ; Given array of pairs ; Function call","code":"import sys NEW_LINE def position ( arr , N ) : NEW_LINE INDENT pos = - 1 NEW_LINE right = - sys . maxsize - 1 NEW_LINE left = sys . maxsize NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] [ 1 ] > right ) : NEW_LINE INDENT right = arr [ i ] [ 1 ] NEW_LINE DEDENT if ( arr [ i ] [ 0 ] < left ) : NEW_LINE INDENT left = arr [ i ] [ 0 ] NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] == left and arr [ i ] [ 1 ] == right ) : NEW_LINE INDENT pos = i + 1 NEW_LINE DEDENT DEDENT print ( pos ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 3 , 3 ] , [ 1 , 3 ] , [ 2 , 2 ] , [ 2 , 3 ] , [ 1 , 2 ] ] NEW_LINE N = len ( arr ) NEW_LINE position ( arr , N ) NEW_LINE DEDENT"} {"text":"Minimize count of given operations required to make two given strings permutations of each other | Function to minimize the count of operations to make str1 and str2 permutations of each other ; Store the frequency of each character of str1 ; Store the frequency of each character of str2 ; Traverse the freq1 [ ] and freq2 [ ] ; If frequency of character in str1 is greater than str2 ; Otherwise ; Store sum of freq1 [ ] ; Store sum of freq2 [ ] ; Driver Code","code":"def ctMinEdits ( str1 , str2 ) : NEW_LINE INDENT N1 = len ( str1 ) NEW_LINE N2 = len ( str2 ) NEW_LINE freq1 = [ 0 ] * 256 NEW_LINE for i in range ( N1 ) : NEW_LINE INDENT freq1 [ ord ( str1 [ i ] ) ] += 1 NEW_LINE DEDENT freq2 = [ 0 ] * 256 NEW_LINE for i in range ( N2 ) : NEW_LINE INDENT freq2 [ ord ( str2 [ i ] ) ] += 1 NEW_LINE DEDENT for i in range ( 256 ) : NEW_LINE INDENT if ( freq1 [ i ] > freq2 [ i ] ) : NEW_LINE INDENT freq1 [ i ] = freq1 [ i ] - freq2 [ i ] NEW_LINE freq2 [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT freq2 [ i ] = freq2 [ i ] - freq1 [ i ] NEW_LINE freq1 [ i ] = 0 NEW_LINE DEDENT DEDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT sum1 += freq1 [ i ] NEW_LINE sum2 += freq2 [ i ] NEW_LINE DEDENT return max ( sum1 , sum2 ) NEW_LINE DEDENT str1 = \" geeksforgeeks \" NEW_LINE str2 = \" geeksforcoder \" NEW_LINE print ( ctMinEdits ( str1 , str2 ) ) NEW_LINE"} {"text":"Count pairs ( i , j ) from arrays arr [ ] & brr [ ] such that arr [ i ] | Function to count the pairs such that given condition is satisfied ; Stores the sum of element at each corresponding index ; Find the sum of each index of both array ; Stores frequency of each element present in sumArr ; Initialize number of pairs ; Add possible vaid pairs ; Return Number of Pairs ; Given array arr [ ] and brr [ ] ; Size of given array ; Function calling","code":"def CountPairs ( a , b , n ) : NEW_LINE INDENT C = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT C [ i ] = a [ i ] + b [ i ] NEW_LINE DEDENT freqCount = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if C [ i ] in freqCount . keys ( ) : NEW_LINE INDENT freqCount [ C [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freqCount [ C [ i ] ] = 1 NEW_LINE DEDENT DEDENT NoOfPairs = 0 NEW_LINE for x in freqCount : NEW_LINE INDENT y = freqCount [ x ] NEW_LINE NoOfPairs = ( NoOfPairs + y * ( y - 1 ) \/\/ 2 ) NEW_LINE DEDENT print ( NoOfPairs ) NEW_LINE DEDENT arr = [ 1 , 4 , 20 , 3 , 10 , 5 ] NEW_LINE brr = [ 9 , 6 , 1 , 7 , 11 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE CountPairs ( arr , brr , N ) NEW_LINE"} {"text":"Change in Median of given array after deleting given elements | Function to find the median change after removing elements from arr2 [ ] ; To store the median ; If N is odd ; If N is even ; Find the current element in arr1 ; Erase the element ; Decrement N ; If N is odd ; If N is even ; Print the corresponding difference of median ; Driver Code ; Given arrays ; Function Call","code":"def medianChange ( arr1 , arr2 ) : NEW_LINE INDENT N = len ( arr1 ) NEW_LINE median = [ ] NEW_LINE if ( N & 1 ) : NEW_LINE INDENT median . append ( arr1 [ N \/\/ 2 ] * 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT median . append ( ( arr1 [ N \/\/ 2 ] + arr1 [ ( N - 1 ) \/\/ 2 ] ) \/\/ 2 ) NEW_LINE DEDENT for x in arr2 : NEW_LINE INDENT it = arr1 . index ( x ) NEW_LINE arr1 . pop ( it ) NEW_LINE N -= 1 NEW_LINE if ( N & 1 ) : NEW_LINE INDENT median . append ( arr1 [ N \/\/ 2 ] * 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT median . append ( ( arr1 [ N \/\/ 2 ] + arr1 [ ( N - 1 ) \/\/ 2 ] ) \/\/ 2 ) NEW_LINE DEDENT DEDENT for i in range ( len ( median ) - 1 ) : NEW_LINE INDENT print ( median [ i + 1 ] - median [ i ] , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr1 = [ 2 , 4 , 6 , 8 , 10 ] NEW_LINE arr2 = [ 4 , 6 ] NEW_LINE medianChange ( arr1 , arr2 ) NEW_LINE DEDENT"} {"text":"NFA to accept strings that has atleast one character occurring in a multiple of 3 | NFA variable that keeps track of the state while transaction . ; This checks for invalid input . ; Function for the state Q2 ; State transitions ' a ' takes to Q4 , and ' b ' and ' c ' remain at Q2 ; Function for the state Q3 ; State transitions ' a ' takes to Q3 , and ' b ' and ' c ' remain at Q4 ; Function for the state Q4 ; State transitions ' a ' takes to Q2 , and ' b ' and ' c ' remain at Q3 ; Function for the state Q5 ; State transitions ' b ' takes to Q6 , and ' a ' and ' c ' remain at Q5 ; Function for the state Q6 ; State transitions ' b ' takes to Q7 , and ' a ' and ' c ' remain at Q7 ; Function for the state Q7 ; State transitions ' b ' takes to Q5 , and ' a ' and ' c ' remain at Q7 ; Function for the state Q8 ; State transitions ' c ' takes to Q9 , and ' a ' and ' b ' remain at Q8 ; Function for the state Q9 ; State transitions ' c ' takes to Q10 , and ' a ' and ' b ' remain at Q9 ; Function for the state Q10 ; State transitions ' c ' takes to Q8 , and ' a ' and ' b ' remain at Q10 ; Function to check for 3 a 's ; Function to check for 3 b 's ; Function to check for 3 c 's ; Driver Code ; If any of the states is True , that is , if either the number of a ' s \u2581 or \u2581 number \u2581 of \u2581 b ' s or number of c 's is a multiple of three, then the is accepted","code":"nfa = 1 NEW_LINE flag = 0 NEW_LINE def state1 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' a ' ) : NEW_LINE INDENT nfa = 2 NEW_LINE DEDENT elif ( c == ' b ' or c == ' c ' ) : NEW_LINE INDENT nfa = 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state2 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' a ' ) : NEW_LINE INDENT nfa = 3 NEW_LINE DEDENT elif ( c == ' b ' or c == ' c ' ) : NEW_LINE INDENT nfa = 2 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state3 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' a ' ) : NEW_LINE INDENT nfa = 1 NEW_LINE DEDENT elif ( c == ' b ' or c == ' c ' ) : NEW_LINE INDENT nfa = 3 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state4 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' b ' ) : NEW_LINE INDENT nfa = 5 NEW_LINE DEDENT elif ( c == ' a ' or c == ' c ' ) : NEW_LINE INDENT nfa = 4 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state5 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' b ' ) : NEW_LINE INDENT nfa = 6 NEW_LINE DEDENT elif ( c == ' a ' or c == ' c ' ) : NEW_LINE INDENT nfa = 5 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state6 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' b ' ) : NEW_LINE INDENT nfa = 4 NEW_LINE DEDENT elif ( c == ' a ' or c == ' c ' ) : NEW_LINE INDENT nfa = 6 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state7 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' c ' ) : NEW_LINE INDENT nfa = 8 NEW_LINE DEDENT elif ( c == ' b ' or c == ' a ' ) : NEW_LINE INDENT nfa = 7 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state8 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' c ' ) : NEW_LINE INDENT nfa = 9 NEW_LINE DEDENT elif ( c == ' b ' or c == ' a ' ) : NEW_LINE INDENT nfa = 8 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def state9 ( c ) : NEW_LINE INDENT global nfa , flag NEW_LINE if ( c == ' c ' ) : NEW_LINE INDENT nfa = 7 NEW_LINE DEDENT elif ( c == ' b ' or c == ' a ' ) : NEW_LINE INDENT nfa = 9 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT DEDENT def checkA ( s , x ) : NEW_LINE INDENT global nfa , flag NEW_LINE for i in range ( x ) : NEW_LINE INDENT if ( nfa == 1 ) : NEW_LINE INDENT state1 ( s [ i ] ) NEW_LINE DEDENT elif ( nfa == 2 ) : NEW_LINE INDENT state2 ( s [ i ] ) NEW_LINE DEDENT elif ( nfa == 3 ) : NEW_LINE INDENT state3 ( s [ i ] ) NEW_LINE DEDENT DEDENT if ( nfa == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT nfa = 4 NEW_LINE DEDENT DEDENT def checkB ( s , x ) : NEW_LINE INDENT global nfa , flag NEW_LINE for i in range ( x ) : NEW_LINE INDENT if ( nfa == 4 ) : NEW_LINE INDENT state4 ( s [ i ] ) NEW_LINE DEDENT elif ( nfa == 5 ) : NEW_LINE INDENT state5 ( s [ i ] ) NEW_LINE DEDENT elif ( nfa == 6 ) : NEW_LINE INDENT state6 ( s [ i ] ) NEW_LINE DEDENT DEDENT if ( nfa == 4 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT nfa = 7 NEW_LINE DEDENT DEDENT def checkC ( s , x ) : NEW_LINE INDENT global nfa , flag NEW_LINE for i in range ( x ) : NEW_LINE INDENT if ( nfa == 7 ) : NEW_LINE INDENT state7 ( s [ i ] ) NEW_LINE DEDENT elif ( nfa == 8 ) : NEW_LINE INDENT state8 ( s [ i ] ) NEW_LINE DEDENT elif ( nfa == 9 ) : NEW_LINE INDENT state9 ( s [ i ] ) NEW_LINE DEDENT DEDENT if ( nfa == 7 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT s = \" bbbca \" NEW_LINE x = 5 NEW_LINE if ( checkA ( s , x ) or checkB ( s , x ) or checkC ( s , x ) ) : NEW_LINE INDENT print ( \" ACCEPTED \" ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( flag == 0 ) : NEW_LINE INDENT print ( \" NOT \u2581 ACCEPTED \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" INPUT \u2581 OUT \u2581 OF \u2581 DICTIONARY . \" ) NEW_LINE DEDENT DEDENT"} {"text":"Count positions such that all elements before it are greater | Function to count positions such that all elements before it are greater ; Count is initially 1 for the first element ; Initial Minimum ; Traverse the array ; If current element is new minimum ; Update minimum ; Increment count ; Driver Code","code":"def getPositionCount ( a , n ) : NEW_LINE INDENT count = 1 ; NEW_LINE min = a [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] <= min ) : NEW_LINE INDENT min = a [ i ] ; NEW_LINE count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 5 , 4 , 6 , 1 , 3 , 1 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( getPositionCount ( a , n ) ) ; NEW_LINE DEDENT"} {"text":"Maximum length L such that the sum of all subarrays of length L is less than K | Function to return the maximum sum in a subarray of size k ; k must be greater ; Compute sum of first window of size k ; Compute sums of remaining windows by removing first element of previous window and adding last element of current window . ; Function to return the length of subarray Sum of all the subarray of this length is less than or equal to K ; Binary search from l to r as all the array elements are positive so that the maximum subarray sum is monotonically increasing ; Check if the subarray sum is greater than K or not ; Update the maximum length ; Driver code","code":"def maxSum ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT res = 0 ; NEW_LINE for i in range ( k ) : NEW_LINE INDENT res += arr [ i ] ; NEW_LINE DEDENT curr_sum = res ; NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum += arr [ i ] - arr [ i - k ] ; NEW_LINE res = max ( res , curr_sum ) ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def solve ( arr , n , k ) : NEW_LINE INDENT max_len = 0 ; l = 0 ; r = n ; NEW_LINE while ( l <= r ) : NEW_LINE INDENT m = ( l + r ) \/\/ 2 ; NEW_LINE if ( maxSum ( arr , n , m ) > k ) : NEW_LINE INDENT r = m - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 ; NEW_LINE max_len = m ; NEW_LINE DEDENT DEDENT return max_len ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 10 ; NEW_LINE print ( solve ( arr , n , k ) ) ; NEW_LINE DEDENT"} {"text":"Count of triplets in an array that satisfy the given conditions | Python3 implementation of the approach ; All possible solutions of the equation 1 \/ a + 1 \/ b + 1 \/ c = 1 ; Function to find the triplets ; Storing indices of the elements ; Check if y can act as the middle element of triplet with the given solution of 1 \/ a + 1 \/ b + 1 \/ c = 1 ; Binary search to find the number of possible values of the first element ; Binary search to find the number of possible values of the third element ; Contribution to the answer would be the multiplication of the possible values for the first and the third element ; Driver Code","code":"MAX = 100001 NEW_LINE ROW = 10 NEW_LINE COL = 3 NEW_LINE indices = [ 0 ] * MAX NEW_LINE test = [ [ 2 , 3 , 6 ] , [ 2 , 4 , 4 ] , [ 2 , 6 , 3 ] , [ 3 , 2 , 6 ] , [ 3 , 3 , 3 ] , [ 3 , 6 , 2 ] , [ 4 , 2 , 4 ] , [ 4 , 4 , 2 ] , [ 6 , 2 , 3 ] , [ 6 , 3 , 2 ] ] NEW_LINE def find_triplet ( array , n ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT indices [ i ] = [ ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT indices [ array [ i ] ] . append ( i ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT y = array [ i ] NEW_LINE for j in range ( ROW ) : NEW_LINE INDENT s = test [ j ] [ 1 ] * y NEW_LINE if s % test [ j ] [ 0 ] != 0 : NEW_LINE INDENT continue NEW_LINE DEDENT if s % test [ j ] [ 2 ] != 0 : NEW_LINE INDENT continue NEW_LINE DEDENT x = s \/\/ test [ j ] [ 0 ] NEW_LINE z = s \/\/ test [ j ] [ 2 ] NEW_LINE if x > MAX or z > MAX : NEW_LINE INDENT continue NEW_LINE DEDENT l = 0 NEW_LINE r = len ( indices [ x ] ) - 1 NEW_LINE first = - 1 NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) \/\/ 2 NEW_LINE if indices [ x ] [ m ] < i : NEW_LINE INDENT first = m NEW_LINE l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT l = 0 NEW_LINE r = len ( indices [ z ] ) - 1 NEW_LINE third = - 1 NEW_LINE while l <= r : NEW_LINE INDENT m = ( l + r ) \/\/ 2 NEW_LINE if indices [ z ] [ m ] > i : NEW_LINE INDENT third = m NEW_LINE r = m - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT if first != - 1 and third != - 1 : NEW_LINE INDENT answer += ( first + 1 ) * ( len ( indices [ z ] ) - third ) NEW_LINE DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT array = [ 2 , 4 , 5 , 6 , 7 ] NEW_LINE n = len ( array ) NEW_LINE print ( find_triplet ( array , n ) ) NEW_LINE DEDENT"} {"text":"Distinct adjacent elements in a binary array | Python3 implementation of the above approach ; if array has only one element , return 1 ; For first element compare with only next element ; For remaining elements compare with both prev and next elements ; For last element compare with only prev element ; Driver code","code":"def distinct ( arr ) : NEW_LINE INDENT count = 0 NEW_LINE if len ( arr ) == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( 0 , len ( arr ) - 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT elif ( i > 0 & i < len ( arr ) - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] or arr [ i ] != arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT if ( arr [ len ( arr ) - 1 ] != arr [ len ( arr ) - 2 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 0 , 0 , 0 , 0 , 0 , 1 , 0 ] NEW_LINE print ( distinct ( arr ) ) NEW_LINE"} {"text":"Check if an array of pairs can be sorted by swapping pairs with different first elements | Function to check if an array is sorted or not ; Traverse the array arr [ ] ; Return true ; Function to check if it is possible to sort the array w . r . t . first element ; Stores the ID of the first element ; Traverse the array arr [ ] ; If arr [ i ] [ 1 ] is not equal to that of the group ; If array is sorted ; Driver Code","code":"def isSorted ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] > arr [ i - 1 ] [ 0 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isPossibleToSort ( arr , N ) : NEW_LINE INDENT group = arr [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] [ 1 ] != group ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT DEDENT if ( isSorted ( arr , N ) ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT return \" No \" NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 340000 , 2 ] , [ 45000 , 1 ] , [ 30000 , 2 ] , [ 50000 , 4 ] ] NEW_LINE N = len ( arr ) NEW_LINE print ( isPossibleToSort ( arr , N ) ) NEW_LINE DEDENT"} {"text":"Find the Alpha Score of the Given Steps ( Using BST ) | Structure of a node ; Function to calculate and return the Alpha Score of the journey ; Traverse left subtree ; Calculate the alpha score of the current step ; Update alpha score of the journey ; Traverse right subtree ; Return ; Function to construct a BST from the sorted array arr [ ] ; Insert root ; Construct left subtree ; Construct right subtree ; Return root ; Driver code ; Sort the array ; Construct BST from the sorted array","code":"class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE total_sum = 0 NEW_LINE mod = 1000000007 NEW_LINE def getAlphaScore ( node ) : NEW_LINE INDENT global sum NEW_LINE global total_sum NEW_LINE if node . left != None : NEW_LINE INDENT getAlphaScore ( node . left ) NEW_LINE DEDENT sum = ( sum + node . data ) % mod NEW_LINE total_sum = ( total_sum + sum ) % mod NEW_LINE if node . right != None : NEW_LINE INDENT getAlphaScore ( node . right ) NEW_LINE DEDENT return total_sum NEW_LINE DEDENT def constructBST ( arr , start , end , root ) : NEW_LINE INDENT if start > end : NEW_LINE INDENT return None NEW_LINE DEDENT mid = ( start + end ) \/\/ 2 NEW_LINE if root == None : NEW_LINE INDENT root = Node ( arr [ mid ] ) NEW_LINE DEDENT root . left = constructBST ( arr , start , mid - 1 , root . left ) NEW_LINE root . right = constructBST ( arr , mid + 1 , end , root . right ) NEW_LINE return root NEW_LINE DEDENT arr = [ 10 , 11 , 12 ] NEW_LINE length = len ( arr ) NEW_LINE arr . sort ( ) NEW_LINE root = None NEW_LINE root = constructBST ( arr , 0 , length - 1 , root ) NEW_LINE print ( getAlphaScore ( root ) ) NEW_LINE"} {"text":"Sorting element of an array by frequency in decreasing order | Function that return the index upto all the array elements are updated . ; Initialise maxE = - 1 ; Find the maximum element of arr [ ] ; Create frequency array freq [ ] ; Update the frequency array as per the occurrence of element in arr [ ] ; Initialise cnt to 0 ; Traversing freq [ ] ; If freq of an element is greater than 0 update the value of arr [ ] at index cnt & increment cnt ; Return cnt ; Function that print array arr [ ] elements in sorted order ; Traversing arr [ ] till index cnt ; Find frequency of elements ; Find value at index i ; Traversing till frequency to print value at index i ; Driver code ; Size of array arr [ ] ; Function call to get cnt ; Sort the arr [ ] in decreasing order ; Function that prints elements in decreasing order","code":"def sortByFreq ( arr , n ) : NEW_LINE INDENT maxE = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxE = max ( maxE , arr [ i ] ) NEW_LINE DEDENT freq = [ 0 ] * ( maxE + 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE for i in range ( maxE + 1 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT value = 100000 - i ; NEW_LINE arr [ cnt ] = 100000 * freq [ i ] + value ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT def printSortedArray ( arr , cnt ) : NEW_LINE INDENT for i in range ( cnt ) : NEW_LINE INDENT frequency = arr [ i ] \/ 100000 ; NEW_LINE value = 100000 - ( arr [ i ] % 100000 ) ; NEW_LINE for j in range ( int ( frequency ) ) : NEW_LINE INDENT print ( value , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 4 , 5 , 6 , 4 , 2 , 2 , 8 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE cnt = sortByFreq ( arr , n ) ; NEW_LINE arr . sort ( reverse = True ) NEW_LINE printSortedArray ( arr , cnt ) ; NEW_LINE DEDENT"} {"text":"Check if N rectangles of equal area can be formed from ( 4 * N ) integers | Function to check whether we can make n rectangles of equal area ; Sort the array ; Find the area of any one rectangle ; Check whether we have two equal sides for each rectangle and that area of each rectangle formed is the same ; Update the answer to false if any condition fails ; If possible ; Driver code","code":"def checkRectangles ( arr , n ) : NEW_LINE INDENT ans = True NEW_LINE arr . sort ( ) NEW_LINE area = arr [ 0 ] * arr [ 4 * n - 1 ] NEW_LINE for i in range ( 0 , 2 * n , 2 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] or arr [ 4 * n - i - 1 ] != arr [ 4 * n - i - 2 ] or arr [ i ] * arr [ 4 * n - i - 1 ] != area ) : NEW_LINE INDENT ans = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( ans ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT arr = [ 1 , 8 , 2 , 1 , 2 , 4 , 4 , 8 ] NEW_LINE n = 2 NEW_LINE if ( checkRectangles ( arr , n ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} {"text":"Count of elements which are not at the correct position | Function to return the count of elements which are not in the correct position when sorted ; To store a copy of the original array ; Copy the elements of the given array to the new array ; To store the required count ; Sort the original array ; If current element was not at the right position ; Driver code","code":"def cntElements ( arr , n ) : NEW_LINE INDENT copy_arr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT copy_arr [ i ] = arr [ i ] NEW_LINE DEDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != copy_arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 2 , 6 , 2 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( cntElements ( arr , n ) ) NEW_LINE"} {"text":"Find k ordered pairs in array with minimum difference d | Function to find the required pairs ; There has to be atleast 2 * k elements ; To store the pairs ; Sort the given array ; For every possible pair ; If the current pair is valid ; Insert it into the pair vector ; If k pairs are not possible ; Print the pairs ; Driver code","code":"def findPairs ( arr , n , k , d ) : NEW_LINE INDENT if ( n < 2 * k ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE return NEW_LINE DEDENT pairs = [ ] NEW_LINE arr = sorted ( arr ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( arr [ n - k + i ] - arr [ i ] >= d ) : NEW_LINE INDENT pairs . append ( [ arr [ i ] , arr [ n - k + i ] ] ) NEW_LINE DEDENT DEDENT if ( len ( pairs ) < k ) : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE return NEW_LINE DEDENT for v in pairs : NEW_LINE INDENT print ( \" ( \" , v [ 0 ] , \" , \u2581 \" , v [ 1 ] , \" ) \" ) NEW_LINE DEDENT DEDENT arr = [ 4 , 6 , 10 , 23 , 14 , 7 , 2 , 20 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE d = 3 NEW_LINE findPairs ( arr , n , k , d ) NEW_LINE"} {"text":"Count pairs with given sum | Set 2 | Function to return the count of pairs from arr with the given sum ; To store the count of pairs ; Sort the given array ; Take two pointers ; If sum is greater ; If sum is lesser ; If sum is equal ; Find the frequency of arr [ i ] ; Find the frequency of arr [ j ] ; If arr [ i ] and arr [ j ] are same then remove the extra number counted ; Return the required answer ; Driver code","code":"def pairs_count ( arr , n , sum ) : NEW_LINE INDENT ans = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE i , j = 0 , n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] < sum ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( arr [ i ] + arr [ j ] > sum ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT x = arr [ i ] NEW_LINE xx = i NEW_LINE while ( i < j and arr [ i ] == x ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT y = arr [ j ] NEW_LINE yy = j NEW_LINE while ( j >= i and arr [ j ] == y ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( x == y ) : NEW_LINE INDENT temp = i - xx + yy - j - 1 NEW_LINE ans += ( temp * ( temp + 1 ) ) \/\/ 2 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( i - xx ) * ( yy - j ) NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 5 , 7 , 5 , - 1 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE print ( pairs_count ( arr , n , sum ) ) NEW_LINE"} {"text":"Check if the string contains consecutive letters and each letter occurs exactly once | Python3 program to implement the above approach ; For all the characters of the string ; Find the ascii value of the character ; Check if if its a valid character , if not then return false ; Calculate sum of all the characters ascii values ; Find minimum ascii value from the string ; Find maximum ascii value from the string ; To get the previous element of the minimum ASCII value ; Take the expected sum from the above equation ; Check if the expected sum is equals to the calculated sum or not ; Driver code ; 1 st example ; 2 nd example","code":"import sys NEW_LINE def check ( str ) : NEW_LINE INDENT min = sys . maxsize NEW_LINE max = - sys . maxsize - 1 NEW_LINE sum = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT ascii = str [ i ] NEW_LINE if ( ord ( ascii ) < 96 or ord ( ascii ) > 122 ) : NEW_LINE INDENT return False NEW_LINE DEDENT sum += ord ( ascii ) NEW_LINE if ( min > ord ( ascii ) ) : NEW_LINE INDENT min = ord ( ascii ) NEW_LINE DEDENT if ( max < ord ( ascii ) ) : NEW_LINE INDENT max = ord ( ascii ) NEW_LINE DEDENT DEDENT min -= 1 NEW_LINE eSum = ( ( ( max * ( max + 1 ) ) \/\/ 2 ) - ( ( min * ( min + 1 ) ) \/\/ 2 ) ) NEW_LINE return sum == eSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" dcef \" NEW_LINE if ( check ( str ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT str1 = \" xyza \" NEW_LINE if ( check ( str1 ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"k | Function to find the sum of minimum of all subarrays ; Insert all the elements in a set ; Find the maximum and minimum element ; Traverse from the minimum to maximum element ; Check if \" i \" is missing ; Check if it is kth missing ; If no kth element is missing ; Driver code","code":"def findKth ( arr , n , k ) : NEW_LINE INDENT missing = dict ( ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT missing [ arr [ i ] ] = 1 NEW_LINE DEDENT maxm = max ( arr ) NEW_LINE minm = min ( arr ) NEW_LINE for i in range ( minm + 1 , maxm ) : NEW_LINE INDENT if ( i not in missing . keys ( ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( count == k ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 10 , 9 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE print ( findKth ( arr , n , k ) ) NEW_LINE"} {"text":"Sort Linked List containing values from 1 to N | Python3 program to sort linked list containing values from 1 to N ; A linked list node ; Function to sort linked list ; Function to add a node at the beginning of Linked List ; allocate node ; put in the data ; link the old list off the new node ; move the head to po to the new node ; This function prs contents of linked list starting from the given node ; Driver Code ; The constructed linked list is : 3.5 . 4.6 .1 . 2","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 sortList ( head ) : NEW_LINE INDENT startVal = 1 NEW_LINE while ( head != None ) : NEW_LINE INDENT head . data = startVal NEW_LINE startVal = startVal + 1 NEW_LINE head = head . next NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) 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 prList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = \" \u2581 \" ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 3 ) NEW_LINE sortList ( head ) NEW_LINE prList ( head ) NEW_LINE DEDENT"} {"text":"Check if linked list is sorted ( Iterative and Recursive ) | Linked list node ; Function to Check Linked List is sorted in descending order or not ; Base cases ; Check first two nodes and recursively check remaining . ; Driver code","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 isSortedDesc ( head ) : NEW_LINE INDENT if ( head == None or head . next == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT return ( head . data > head . next . data and isSortedDesc ( head . next ) ) NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT head = newNode ( 7 ) NEW_LINE head . next = newNode ( 5 ) NEW_LINE head . next . next = newNode ( 4 ) NEW_LINE head . next . next . next = newNode ( 3 ) NEW_LINE if isSortedDesc ( head ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Rearrange an array to minimize sum of product of consecutive pair elements | Python 3 program to sort an array such that sum of product of alternate element is minimum . ; create evenArr [ ] and oddArr [ ] ; sort main array in ascending order ; Put elements in oddArr [ ] and evenArr [ ] as per desired value . ; sort evenArr [ ] in descending order ; merge both sub - array and calculate minimum sum of product of alternate elements ; Driver Code","code":"def minSum ( arr , n ) : NEW_LINE INDENT evenArr = [ ] NEW_LINE oddArr = [ ] NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < n \/\/ 2 ) : NEW_LINE INDENT oddArr . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT evenArr . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT evenArr . sort ( reverse = True ) NEW_LINE i = 0 NEW_LINE sum = 0 NEW_LINE for j in range ( len ( evenArr ) ) : NEW_LINE INDENT arr [ i ] = evenArr [ j ] NEW_LINE i += 1 NEW_LINE arr [ i ] = oddArr [ j ] NEW_LINE i += 1 NEW_LINE sum += evenArr [ j ] * oddArr [ j ] NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( \" Minimum \u2581 required \u2581 sum \u2581 = \" , minSum ( arr , n ) ) NEW_LINE print ( \" Sorted \u2581 array \u2581 in \u2581 required \u2581 format \u2581 : \u2581 \" , end = \" \" ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT"} {"text":"Minimum time required to print given string from a circular container based on given conditions | Function to calculate minimum time to print all characters in the string ; Current element where the pointer is pointing ; Find index of that element ; Calculate absolute difference between pointer index and character index as clockwise distance ; Subtract clockwise time from 26 to get anti - clockwise time ; Add minimum of both times to the answer ; Add one unit time to print the character ; Print the final answer ; Driver code ; Given string word ; Function call","code":"def minTime ( word ) : NEW_LINE INDENT ans = 0 NEW_LINE curr = 0 NEW_LINE for i in range ( len ( word ) ) : NEW_LINE INDENT k = ord ( word [ i ] ) - 97 NEW_LINE a = abs ( curr - k ) NEW_LINE b = 26 - abs ( curr - k ) NEW_LINE ans += min ( a , b ) NEW_LINE ans += 1 NEW_LINE curr = ord ( word [ i ] ) - 97 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \" zjpc \" NEW_LINE minTime ( str ) NEW_LINE DEDENT"} {"text":"Minimum decrements or division by a proper divisor required to reduce N to 1 | Function to find the minimum number of steps required to reduce N to 1 ; Stores the number of steps required ; If the value of N is equal to 2 or N is odd ; Decrement N by 1 ; Increment cnt by 1 ; If N is even ; Update N ; Increment cnt by 1 ; Return the number of steps obtained ; Driver Code","code":"def reduceToOne ( N ) : NEW_LINE INDENT cnt = 0 NEW_LINE while ( N != 1 ) : NEW_LINE INDENT if ( N == 2 or ( N % 2 == 1 ) ) : NEW_LINE INDENT N = N - 1 NEW_LINE cnt += 1 NEW_LINE DEDENT elif ( N % 2 == 0 ) : NEW_LINE INDENT N = N \/ ( N \/ 2 ) NEW_LINE cnt += 1 NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 35 NEW_LINE print ( reduceToOne ( N ) ) NEW_LINE DEDENT"} {"text":"Maximum number of diamonds that can be gained in K minutes | Function to find the maximum number of diamonds that can be gained in exactly K minutes ; Stores all the array elements ; Push all the elements to the priority queue ; Stores the required result ; Loop while the queue is not empty and K is positive ; Store the top element from the pq ; Pop it from the pq ; Add it to the answer ; Divide it by 2 and push it back to the pq ; Print the answer ; Driver Code","code":"def maxDiamonds ( A , N , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( A [ i ] ) NEW_LINE DEDENT pq . sort ( ) NEW_LINE ans = 0 NEW_LINE while ( len ( pq ) > 0 and K > 0 ) : NEW_LINE INDENT pq . sort ( ) NEW_LINE top = pq [ len ( pq ) - 1 ] NEW_LINE pq = pq [ 0 : len ( pq ) - 1 ] NEW_LINE ans += top NEW_LINE top = top \/\/ 2 ; NEW_LINE pq . append ( top ) NEW_LINE K -= 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 1 , 7 , 4 , 2 ] NEW_LINE K = 3 NEW_LINE N = len ( A ) NEW_LINE maxDiamonds ( A , N , K ) NEW_LINE DEDENT"} {"text":"Minimize cost of increments or decrements such that same indexed elements become multiple of each other | Function to find the minimum cost to make A [ i ] multiple of B [ i ] or vice - versa for every array element ; Stores the minimum cost ; Traverse the array ; Case 1 : Update A [ i ] ; Case 2 : Update B [ i ] ; Add the minimum of the above two cases ; Return the resultant cost ; Driver Code","code":"def MinimumCost ( A , B , N ) : NEW_LINE INDENT totalCost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT mod_A = B [ i ] % A [ i ] NEW_LINE totalCost_A = min ( mod_A , A [ i ] - mod_A ) NEW_LINE mod_B = A [ i ] % B [ i ] NEW_LINE totalCost_B = min ( mod_B , B [ i ] - mod_B ) NEW_LINE totalCost += min ( totalCost_A , totalCost_B ) NEW_LINE DEDENT return totalCost NEW_LINE DEDENT A = [ 3 , 6 , 3 ] NEW_LINE B = [ 4 , 8 , 13 ] NEW_LINE N = len ( A ) NEW_LINE print ( MinimumCost ( A , B , N ) ) NEW_LINE"} {"text":"Largest number divisible by 50 that can be formed from a given set of N digits consisting of 0 s and 7 s only | Print the largest number divisible by 50 ; Counting number of 0 s and 7 s ; If count of 7 is divisible by 50 ; If count of 7 is less than 5 ; If count of 7 is not divisible by 50 ; Count of groups of 5 in which count of 7 s can be grouped ; Driver Code ; Given array ; Size of the array","code":"def printLargestDivisible ( arr , N ) : NEW_LINE INDENT count0 = 0 ; count7 = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT count0 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT count7 += 1 ; NEW_LINE DEDENT DEDENT if ( count7 % 50 == 0 ) : NEW_LINE INDENT while ( count7 ) : NEW_LINE INDENT count7 -= 1 ; NEW_LINE print ( 7 , end = \" \" ) ; NEW_LINE DEDENT while ( count0 ) : NEW_LINE INDENT count0 -= 1 ; NEW_LINE print ( count0 , end = \" \" ) ; NEW_LINE DEDENT DEDENT elif ( count7 < 5 ) : NEW_LINE INDENT if ( count0 == 0 ) : NEW_LINE INDENT print ( \" No \" , end = \" \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \"0\" , end = \" \" ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT count7 = count7 - count7 % 5 ; NEW_LINE while ( count7 ) : NEW_LINE INDENT count7 -= 1 ; NEW_LINE print ( 7 , end = \" \" ) ; NEW_LINE DEDENT while ( count0 ) : NEW_LINE INDENT count0 -= 1 ; NEW_LINE print ( 0 , end = \" \" ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 0 , 7 , 0 , 7 , 7 , 7 , 7 , 0 , 0 , 0 , 0 , 0 , 0 , 7 , 7 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE printLargestDivisible ( arr , N ) ; NEW_LINE DEDENT"} {"text":"Rearrange array to maximize sum of GCD of array elements with their respective indices | Function to find the maximum sum of GCD ( arr [ i ] , i ) by rearranging the array ; Sort the array in ascending order ; Stores maximum sum of GCD ( arr [ i ] , i ) by rearranging the array elements ; Generate all possible permutations of the array ; Stores sum of GCD ( arr [ i ] , i ) ; Traverse the array ; Update sum ; Update res ; Driver code","code":"def findMaxValByRearrArr ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE res = 0 NEW_LINE while ( True ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT Sum += __gcd ( i + 1 , arr [ i ] ) NEW_LINE DEDENT res = max ( res , Sum ) NEW_LINE if ( not next_permutation ( arr ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def __gcd ( a , b ) : NEW_LINE INDENT if b == 0 : NEW_LINE INDENT return a NEW_LINE DEDENT else : NEW_LINE INDENT return __gcd ( b , a % b ) NEW_LINE DEDENT DEDENT def next_permutation ( p ) : NEW_LINE INDENT for a in range ( len ( p ) - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( p [ a ] < p [ a + 1 ] ) : NEW_LINE INDENT b = len ( p ) - 1 NEW_LINE while True : NEW_LINE INDENT if ( p [ b ] > p [ a ] ) : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b = len ( p ) - 1 NEW_LINE while a < b : NEW_LINE INDENT t = p [ a ] NEW_LINE p [ a ] = p [ b ] NEW_LINE p [ b ] = t NEW_LINE a += 1 NEW_LINE b -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT b -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaxValByRearrArr ( arr , N ) ) NEW_LINE"} {"text":"Minimum removals required to make frequency of each array element equal to its value | Function to find the minimum count of elements required to be removed such that frequency of arr [ i ] equal to arr [ i ] ; Stores frequency of each element of the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores minimum count of removals ; Traverse the map ; Stores key value of the map ; If frequency of i is less than i ; Update cntMinRem ; If frequency of i is greater than i ; Update cntMinRem ; Driver Code","code":"def min_elements ( arr , N ) : NEW_LINE INDENT mp = { } ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 ; NEW_LINE DEDENT DEDENT cntMinRem = 0 ; NEW_LINE for it in mp : NEW_LINE INDENT i = it ; NEW_LINE if ( mp [ i ] < i ) : NEW_LINE INDENT cntMinRem += mp [ i ] ; NEW_LINE DEDENT elif ( mp [ i ] > i ) : NEW_LINE INDENT cntMinRem += ( mp [ i ] - i ) ; NEW_LINE DEDENT DEDENT return cntMinRem ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 2 , 4 , 1 , 4 , 2 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( min_elements ( arr , N ) ) ; NEW_LINE DEDENT"} {"text":"Minimum increments to make all array elements equal with sum same as the given array after exactly one removal | Function to check if an array of equal elements with sum equal to the given array can be obtained or not ; Base case ; Stores sum of array elements ; Stores second largest array element ; Stores the largest array element ; Traverse the array ; Update secMax ; Update Max ; Update secMax ; Update totalSum ; If totalSum is less than secMax * ( N - 1 ) ) ; If totalSum is not divisible by ( N - 1 ) ; Driver Code","code":"def CheckAllarrayEqual ( arr , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT totalSum = arr [ 0 ] NEW_LINE secMax = - 10 ** 19 NEW_LINE Max = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] >= Max ) : NEW_LINE INDENT secMax = Max NEW_LINE Max = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > secMax ) : NEW_LINE INDENT secMax = arr [ i ] NEW_LINE DEDENT totalSum += arr [ i ] NEW_LINE DEDENT if ( ( secMax * ( N - 1 ) ) > totalSum ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( totalSum % ( N - 1 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 2 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE if ( CheckAllarrayEqual ( arr , N ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} {"text":"Count ways to make Bitwise XOR of odd and even indexed elements equal by removing an array element | Function to count ways to make Bitwise XOR of odd and even indexed elements equal by removing an array element ; Stores xor of odd and even indexed elements from the end ; Stores xor of odd and even indexed elements from the start ; Stores the required count ; Traverse the array in reverse ; If i is odd ; If i is even ; Traverse the array ; If i is odd ; If i is even ; Removing arr [ i ] , post_even stores XOR of odd indexed elements ; Removing arr [ i ] , post_odd stores XOR of even indexed elements ; Check if they are equal ; If i is odd , xor it with curr_odd ; If i is even , xor it with curr_even ; Finally print res ; Drivers Code ; Given array ; Given size ; Function call","code":"def Remove_one_element ( arr , n ) : NEW_LINE INDENT post_odd = 0 NEW_LINE post_even = 0 NEW_LINE curr_odd = 0 NEW_LINE curr_even = 0 NEW_LINE res = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT post_odd ^= arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT post_even ^= arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT post_odd ^= arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT post_even ^= arr [ i ] NEW_LINE DEDENT X = curr_odd ^ post_even NEW_LINE Y = curr_even ^ post_odd NEW_LINE if ( X == Y ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( i % 2 ) : NEW_LINE INDENT curr_odd ^= arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT curr_even ^= arr [ i ] NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE Remove_one_element ( arr , N ) NEW_LINE DEDENT"} {"text":"Count ways to make sum of odd and even indexed elements equal by removing an array element | Function to count array indices whose removal makes sum of odd and even indexed elements equal ; If size of the array is 1 ; If size of the array is 2 ; Stores sum of even - indexed elements of the given array ; Stores sum of odd - indexed elements of the given array ; Traverse the array ; If i is an even number ; Update sumEven ; If i is an odd number ; Update sumOdd ; Stores sum of even - indexed array elements till i - th index ; Stores sum of odd - indexed array elements till i - th index ; Stores count of indices whose removal makes sum of odd and even indexed elements equal ; Stores sum of even - indexed elements after removing the i - th element ; Stores sum of odd - indexed elements after removing the i - th element ; Traverse the array ; If i is an odd number ; Update currOdd ; Update newEvenSum ; Update newOddSum ; If i is an even number ; Update currEven ; Update newOddSum ; Update newEvenSum ; If newEvenSum is equal to newOddSum ; Increase the count ; If sum of even - indexed and odd - indexed elements is equal by removing the first element ; Increase the count ; If length of the array is an odd number ; If sum of even - indexed and odd - indexed elements is equal by removing the last element ; Increase the count ; If length of the array is an even number ; If sum of even - indexed and odd - indexed elements is equal by removing the last element ; Increase the count ; Driver Code","code":"def cntIndexesToMakeBalance ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sumEven = 0 NEW_LINE sumOdd = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT sumEven += arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sumOdd += arr [ i ] NEW_LINE DEDENT DEDENT currOdd = 0 NEW_LINE currEven = arr [ 0 ] NEW_LINE res = 0 NEW_LINE newEvenSum = 0 NEW_LINE newOddSum = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT currOdd += arr [ i ] NEW_LINE newEvenSum = ( currEven + sumOdd - currOdd ) NEW_LINE newOddSum = ( currOdd + sumEven - currEven - arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT currEven += arr [ i ] NEW_LINE newOddSum = ( currOdd + sumEven - currEven ) NEW_LINE newEvenSum = ( currEven + sumOdd - currOdd - arr [ i ] ) NEW_LINE DEDENT if ( newEvenSum == newOddSum ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT if ( sumOdd == sumEven - arr [ 0 ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( n % 2 == 1 ) : NEW_LINE INDENT if ( sumOdd == sumEven - arr [ n - 1 ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( sumEven == sumOdd - arr [ n - 1 ] ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( cntIndexesToMakeBalance ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Find two numbers from their sum and XOR | Set 2 | Function to find the value of A and B whose sum is X and xor is Y ; Initialize the two numbers ; Case 1 : X < Y ; Case 2 : X - Y is odd ; Case 3 : If both Sum and XOR are equal ; Case 4 : If above cases fails ; Update the value of A ; Check if A & Y value is 0 ; If True , update B ; Otherwise assign - 1 to A , - 1 to B ; Prthe numbers A and B ; Driver Code ; Given Sum and XOR of 2 numbers ; Function Call","code":"def findNums ( X , Y ) : NEW_LINE INDENT A = 0 ; NEW_LINE B = 0 ; NEW_LINE if ( X < Y ) : NEW_LINE INDENT A = - 1 ; NEW_LINE B = - 1 ; NEW_LINE DEDENT elif ( ( ( abs ( X - Y ) ) & 1 ) != 0 ) : NEW_LINE INDENT A = - 1 ; NEW_LINE B = - 1 ; NEW_LINE DEDENT elif ( X == Y ) : NEW_LINE INDENT A = 0 ; NEW_LINE B = Y ; NEW_LINE DEDENT else : NEW_LINE INDENT A = ( X - Y ) \/\/ 2 ; NEW_LINE if ( ( A & Y ) == 0 ) : NEW_LINE INDENT B = ( A + Y ) ; NEW_LINE DEDENT else : NEW_LINE INDENT A = - 1 ; NEW_LINE B = - 1 ; NEW_LINE DEDENT DEDENT print A ; NEW_LINE print B ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT X = 17 ; NEW_LINE Y = 13 ; NEW_LINE findNums ( X , Y ) ; NEW_LINE DEDENT"} {"text":"Queries to check if count of increasing and decreasing subarrays is same in given range | Function to check if given range have equal number of increasing as well as decreasing subarrays ; Traverse each query ; For 0 - based indexing ; Condition for same count of increasing & decreasing subarray ; Driver Code","code":"def checkCount ( A , Q , q ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE INDENT L = Q [ i ] [ 0 ] NEW_LINE R = Q [ i ] [ 1 ] NEW_LINE L -= 1 NEW_LINE R -= 1 NEW_LINE if ( ( A [ L ] < A [ L + 1 ] ) != ( A [ R - 1 ] < A [ R ] ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 13 , 12 , 14 ] NEW_LINE Q = [ [ 1 , 4 ] , [ 2 , 4 ] ] NEW_LINE q = len ( Q ) NEW_LINE checkCount ( arr , Q , q ) NEW_LINE DEDENT"} {"text":"Mean of array generated by products of all pairs of the given array | Function to find the mean of pair product array of arr ; Store product of pairs ; Generate all unordered pairs ; Store product of pairs ; Size of pairArray ; Store sum of pairArray ; Stores the mean of pairArray ; Find mean of pairArray ; Return the resultant mean ; Driver Code ; Given array arr ; Function Call","code":"def pairProductMean ( arr , N ) : NEW_LINE INDENT pairArray = [ ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT pairProduct = arr [ i ] * arr [ j ] ; NEW_LINE pairArray . append ( pairProduct ) ; NEW_LINE DEDENT DEDENT length = len ( pairArray ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( length ) : NEW_LINE INDENT sum += pairArray [ i ] ; NEW_LINE DEDENT mean = 0 ; NEW_LINE if ( length != 0 ) : NEW_LINE INDENT mean = sum \/ length ; NEW_LINE DEDENT else : NEW_LINE INDENT mean = 0 ; NEW_LINE DEDENT return mean ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( \" { 0 : . 2f } \" . format ( pairProductMean ( arr , N ) ) ) NEW_LINE DEDENT"} {"text":"Smallest number exceeding N whose Kth bit is set | Function to find the number greater than n whose Kth bit is set ; Iterate from N + 1 ; Check if Kth bit is set or not ; Increment M for next number ; Return the minimum value ; Driver Code ; Given N and K ; Function Call","code":"def find_next ( n , k ) : NEW_LINE INDENT M = n + 1 ; NEW_LINE while ( True ) : NEW_LINE INDENT if ( ( M & ( 1 << k ) ) > 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT M += 1 ; NEW_LINE DEDENT return M ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 15 ; K = 2 ; NEW_LINE print ( find_next ( N , K ) ) ; NEW_LINE DEDENT"} {"text":"Smallest number exceeding N whose Kth bit is set | Function to find the number greater than n whose Kth bit is set ; Stores the resultant number ; If Kth bit is not set ; cur will be the sum of all powers of 2 < k ; If the current bit is set ; Add Kth power of 2 to n and subtract the all powers of 2 less than K that are set ; If the kth bit is set ; First unset bit position ; Sum of bits that are set ; Add Kth power of 2 to n and subtract the all powers of 2 less than K that are set ; If Kth bit became unset then set it again ; Return the resultant number ; Driver code ; Print ans","code":"def find_next ( n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE if ( ( n & ( 1 << k ) ) == 0 ) : NEW_LINE INDENT cur = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( n & ( 1 << i ) ) : NEW_LINE INDENT cur += 1 << i NEW_LINE DEDENT DEDENT ans = n - cur + ( 1 << k ) NEW_LINE DEDENT else : NEW_LINE INDENT first_unset_bit , cur = - 1 , 0 NEW_LINE for i in range ( 64 ) : NEW_LINE INDENT if ( ( n & ( 1 << i ) ) == 0 ) : NEW_LINE INDENT first_unset_bit = i NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT cur += ( 1 << i ) NEW_LINE DEDENT DEDENT ans = n - cur + ( 1 << first_unset_bit ) NEW_LINE if ( ( ans & ( 1 << k ) ) == 0 ) : NEW_LINE INDENT ans += ( 1 << k ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT N , K = 15 , 2 NEW_LINE print ( find_next ( N , K ) ) NEW_LINE"} {"text":"Lexicographically largest possible String after removal of K characters | Python3 program to implement the above approach ; Final result string ; If the current char exceeds the character at the top of the stack ; Remove from the end of the string ; Decrease k for the removal ; Insert current character ; Perform remaining K deletions from the end of the string ; Return the string ; Driver code","code":"def largestString ( num , k ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT while ( len ( ans ) and ans [ - 1 ] < num [ i ] and k > 0 ) : NEW_LINE INDENT ans . pop ( ) NEW_LINE k -= 1 NEW_LINE DEDENT ans . append ( num [ i ] ) NEW_LINE DEDENT while ( len ( ans ) and k ) : NEW_LINE INDENT k -= 1 NEW_LINE ans . pop ( ) NEW_LINE DEDENT return ans NEW_LINE DEDENT str = \" zyxedcba \" NEW_LINE k = 1 NEW_LINE print ( * largestString ( str , k ) , sep = \" \" ) NEW_LINE"} {"text":"Maximum length of subarray consisting of same type of element on both halves of sub | Function that finds the maximum length of the sub - array that contains equal element on both halves of sub - array ; To store continuous occurence of the element ; To store continuous forward occurence ; To store continuous backward occurence ; To store the maximum length ; Find maximum length ; Print the result ; Given array ; Size of the array ; Function call","code":"def maxLengthSubArray ( A , N ) : NEW_LINE INDENT forward = [ 0 ] * N NEW_LINE backward = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT if i == 0 or A [ i ] != A [ i - 1 ] : NEW_LINE INDENT forward [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT forward [ i ] = forward [ i - 1 ] + 1 NEW_LINE DEDENT DEDENT for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if i == N - 1 or A [ i ] != A [ i + 1 ] : NEW_LINE INDENT backward [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT backward [ i ] = backward [ i + 1 ] + 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( A [ i ] != A [ i + 1 ] ) : NEW_LINE INDENT ans = max ( ans , min ( forward [ i ] , backward [ i + 1 ] ) * 2 ) ; NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 4 , 4 , 6 , 6 , 6 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE maxLengthSubArray ( arr , N ) NEW_LINE"} {"text":"Smallest N digit number divisible by all possible prime digits | Python3 implementation of the above approach ; Function to find the minimum number of n digits divisible by all prime digits . ; Driver Code","code":"from math import * NEW_LINE def minNum ( n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 210 * ( 10 ** ( n - 1 ) \/\/ 210 + 1 ) ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE minNum ( n ) NEW_LINE"} {"text":"Smallest number greater than Y with sum of digits equal to X | Function to return the minimum string of length d having the sum of digits s ; Return a string of length d ; Greedily put 9 's in the end ; Put remaining sum ; Function to find the smallest number greater than Y whose sum of digits is X ; Convert number y to string ; Maintain prefix sum of digits ; Iterate over Y from the back where k is current length of suffix ; Stores current digit ; Increase current digit ; Sum upto current prefix ; Return answer if remaining sum can be obtained in suffix ; Find suffix of length k having sum of digits x - r ; Append current character ; Return the result ; Driver Code ; Given Number and Sum ; Function Call","code":"def helper ( d , s ) : NEW_LINE INDENT ans = [ '0' ] * d NEW_LINE for i in range ( d - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( s >= 9 ) : NEW_LINE INDENT ans [ i ] = '9' NEW_LINE s -= 9 NEW_LINE DEDENT else : NEW_LINE INDENT c = chr ( s + ord ( '0' ) ) NEW_LINE ans [ i ] = c ; NEW_LINE s = 0 ; NEW_LINE DEDENT DEDENT return ' ' . join ( ans ) ; NEW_LINE DEDENT def findMin ( x , Y ) : NEW_LINE INDENT y = str ( Y ) ; NEW_LINE n = len ( y ) NEW_LINE p = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT p [ i ] = ( ord ( y [ i ] ) - ord ( '0' ) ) NEW_LINE if ( i > 0 ) : NEW_LINE INDENT p [ i ] += p [ i - 1 ] ; NEW_LINE DEDENT DEDENT n - 1 NEW_LINE k = 0 NEW_LINE while True : NEW_LINE INDENT d = 0 ; NEW_LINE if ( i >= 0 ) : NEW_LINE INDENT d = ( ord ( y [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT for j in range ( d + 1 , 10 ) : NEW_LINE INDENT r = ( ( i > 0 ) * p [ i - 1 ] + j ) ; NEW_LINE if ( x - r >= 0 and x - r <= 9 * k ) : NEW_LINE INDENT suf = helper ( k , x - r ) ; NEW_LINE pre = \" \" ; NEW_LINE if ( i > 0 ) : NEW_LINE INDENT pre = y [ 0 : i ] NEW_LINE DEDENT cur = chr ( j + ord ( '0' ) ) NEW_LINE pre += cur ; NEW_LINE return pre + suf ; NEW_LINE DEDENT DEDENT i -= 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x = 18 ; NEW_LINE y = 99 ; NEW_LINE print ( findMin ( x , y ) ) NEW_LINE DEDENT"} {"text":"Largest number made up of X and Y with count of X divisible by Y and of Y by X | Function to generate and return the largest number ; Store the smaller in Y ; Store the larger in X ; Stores respective counts ; If N is divisible by Y ; Append X , N times to the answer ; Reduce N to zero ; Reduce N by x ; Append Y , X times to the answer ; If number can be formed ; Otherwise ; Driver code","code":"def largestNumber ( n , X , Y ) : NEW_LINE INDENT maxm = max ( X , Y ) NEW_LINE Y = X + Y - maxm NEW_LINE X = maxm NEW_LINE Xs = 0 NEW_LINE Ys = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( n % Y == 0 ) : NEW_LINE INDENT Xs += n NEW_LINE n = 0 NEW_LINE DEDENT else : NEW_LINE INDENT n -= X NEW_LINE Ys += X NEW_LINE DEDENT DEDENT if ( n == 0 ) : NEW_LINE INDENT while ( Xs > 0 ) : NEW_LINE INDENT Xs -= 1 NEW_LINE print ( X , end = ' ' ) NEW_LINE DEDENT while ( Ys > 0 ) : NEW_LINE INDENT Ys -= 1 NEW_LINE print ( Y , end = ' ' ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT DEDENT n = 19 NEW_LINE X = 7 NEW_LINE Y = 5 NEW_LINE largestNumber ( n , X , Y ) NEW_LINE"} {"text":"Minimum flips required to generate continuous substrings of 0 \u00e2 \u20ac\u2122 s and 1 \u00e2 \u20ac\u2122 s | Python3 implementation of the above approach ; Traverse input string and store the count of 0 ; Traverse the input string again to find minimum number of flips ; Driver code","code":"def minChanges ( str , N ) : NEW_LINE INDENT count0 = 0 NEW_LINE count1 = 0 NEW_LINE for x in str : NEW_LINE INDENT count0 += ( x == '0' ) NEW_LINE DEDENT res = count0 NEW_LINE for x in str : NEW_LINE INDENT count0 -= ( x == '0' ) NEW_LINE count1 += ( x == '1' ) NEW_LINE res = min ( res , count1 + count0 ) NEW_LINE DEDENT return res NEW_LINE DEDENT N = 9 NEW_LINE str = \"000101001\" NEW_LINE print ( minChanges ( str , N ) ) NEW_LINE"} {"text":"Missing occurrences of a number in an array such that maximum absolute difference of adjacent elements is minimum | Python3 implementation of the missing number such that maximum absolute difference between adjacent element is minimum ; Function to find the missing number such that maximum absolute difference is minimum ; Loop to find the maximum and minimum adjacent element to missing number ; Driver Code ; Function call","code":"import sys NEW_LINE def missingnumber ( n , arr ) -> int : NEW_LINE INDENT mn = sys . maxsize ; NEW_LINE mx = - sys . maxsize - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i > 0 and arr [ i ] == - 1 and arr [ i - 1 ] != - 1 ) : NEW_LINE INDENT mn = min ( mn , arr [ i - 1 ] ) ; NEW_LINE mx = max ( mx , arr [ i - 1 ] ) ; NEW_LINE DEDENT if ( i < ( n - 1 ) and arr [ i ] == - 1 and arr [ i + 1 ] != - 1 ) : NEW_LINE INDENT mn = min ( mn , arr [ i + 1 ] ) ; NEW_LINE mx = max ( mx , arr [ i + 1 ] ) ; NEW_LINE DEDENT DEDENT res = ( mx + mn ) \/ 2 ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE arr = [ - 1 , 10 , - 1 , 12 , - 1 ] ; NEW_LINE res = missingnumber ( n , arr ) ; NEW_LINE print ( res ) ; NEW_LINE DEDENT"} {"text":"Maximize [ length ( X ) \/ 2 ^ ( XOR ( X , Y ) ) ] by choosing substrings X and Y from string A and B respectively | Function to find the length of the longest common substring of the string X and Y ; LCSuff [ i ] [ j ] stores the lengths of the longest common suffixes of substrings ; Itearate over strings A and B ; If first row or column ; If matching is found ; Otherwise , if matching is not found ; Finally , return the resultant maximum value LCS ; Driver Code ; Function Call","code":"def LCSubStr ( A , B , m , n ) : NEW_LINE INDENT LCSuff = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE result = 0 NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( A [ i - 1 ] == B [ j - 1 ] ) : NEW_LINE INDENT LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 NEW_LINE result = max ( result , LCSuff [ i ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = \"0110\" NEW_LINE B = \"1101\" NEW_LINE M = len ( A ) NEW_LINE N = len ( B ) NEW_LINE print ( LCSubStr ( A , B , M , N ) ) NEW_LINE DEDENT"} {"text":"Count ways to split array into pair of subsets with difference between their sum equal to K | Python program for the above approach ; To store the states of DP ; Function to find count of subsets with a given sum ; Base case ; If an already computed subproblem occurs ; Set the state as solved ; Recurrence relation ; Function to count ways to split array into pair of subsets with difference K ; Store the total sum of element of the array ; Traverse the array ; Calculate sum of array elements ; Store the required sum ; Prthe number of subsets with sum equal to S1 ; Driver Code ; Function Call","code":"maxN = 20 ; NEW_LINE maxSum = 50 ; NEW_LINE minSum = 50 ; NEW_LINE Base = 50 ; NEW_LINE dp = [ [ 0 for i in range ( maxSum + minSum ) ] for j in range ( maxN ) ] ; NEW_LINE v = [ [ False for i in range ( maxSum + minSum ) ] for j in range ( maxN ) ] ; NEW_LINE def findCnt ( arr , i , required_sum , n ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( required_sum == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT if ( v [ i ] [ required_sum + Base ] ) : NEW_LINE INDENT return dp [ i ] [ required_sum + Base ] ; NEW_LINE DEDENT v [ i ] [ required_sum + Base ] = True ; NEW_LINE dp [ i ] [ required_sum + Base ] = findCnt ( arr , i + 1 , required_sum , n ) + findCnt ( arr , i + 1 , required_sum - arr [ i ] , n ) ; NEW_LINE return dp [ i ] [ required_sum + Base ] ; NEW_LINE DEDENT def countSubsets ( arr , K , n ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE DEDENT S1 = ( sum + K ) \/\/ 2 ; NEW_LINE print ( findCnt ( arr , 0 , S1 , n ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 3 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 1 ; NEW_LINE countSubsets ( arr , K , N ) ; NEW_LINE DEDENT"} {"text":"Probability that the sum of all numbers obtained on throwing a dice N times lies between two given integers | Python program for above approach ; Function to calculate the probability for the given sum to be equal to sum in N throws of dice ; Base cases ; Driver Code ; Calculate probability of all sums from a to b ; Prthe answer","code":"dp = [ [ 0 for i in range ( 605 ) ] for j in range ( 105 ) ] ; NEW_LINE def find ( N , sum ) : NEW_LINE INDENT if ( N < 0 sum < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ N ] [ sum ] > 0 ) : NEW_LINE INDENT return dp [ N ] [ sum ] ; NEW_LINE DEDENT if ( sum > 6 * N or sum < N ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT if ( sum >= 1 and sum <= 6 ) : NEW_LINE INDENT return ( float ) ( 1.0 \/ 6 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT for i in range ( 1 , 7 ) : NEW_LINE INDENT dp [ N ] [ sum ] = dp [ N ] [ sum ] + find ( N - 1 , sum - i ) \/ 6 ; NEW_LINE DEDENT return dp [ N ] [ sum ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 ; a = 13 ; b = 17 ; NEW_LINE probability = 0.0 NEW_LINE f = 0 ; NEW_LINE for sum in range ( a , b + 1 ) : NEW_LINE INDENT probability = probability + find ( N , sum ) ; NEW_LINE DEDENT print ( \" % .6f \" % probability ) ; NEW_LINE DEDENT"} {"text":"Minimum steps to reduce N to 0 by given operations | Function to find the minimum number to steps to reduce N to 0 ; Dictionary for storing the precomputed sum ; Bases Cases ; Check if n is not in dp then only call the function so as to reduce no of recursive calls ; Return the answer ; Given Number N ; Function Call","code":"def count ( n ) : NEW_LINE INDENT dp = dict ( ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE if n not in dp : NEW_LINE INDENT dp [ n ] = 1 + min ( n % 2 + count ( n \/\/ 2 ) , n % 3 + count ( n \/\/ 3 ) ) NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT N = 6 NEW_LINE print ( str ( count ( N ) ) ) NEW_LINE"} {"text":"Minimum count of increment of K size subarrays required to form a given Array | Function to find the minimum number of operations required to change all the array of zeros such that every element is greater than the given array ; Declaring the difference array of size N ; Number of operations ; First update the D [ i ] value with the previous value ; The index i has to be incremented ; We have to perform ( b [ i ] - d [ i ] ) operations more ; Increment the range i to i + k by need ; Check if i + k is valid index ; Driver Code ; Function Call","code":"def find_minimum_operations ( n , b , k ) : NEW_LINE INDENT d = [ 0 for i in range ( n + 1 ) ] NEW_LINE operations = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT d [ i ] += d [ i - 1 ] NEW_LINE if b [ i ] > d [ i ] : NEW_LINE INDENT operations += ( b [ i ] - d [ i ] ) NEW_LINE need = ( b [ i ] - d [ i ] ) NEW_LINE d [ i ] += need NEW_LINE if i + k <= n : NEW_LINE INDENT d [ i + k ] -= need NEW_LINE DEDENT DEDENT DEDENT return operations NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 5 NEW_LINE b = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE k = 2 NEW_LINE print ( find_minimum_operations ( n , b , k ) ) NEW_LINE DEDENT"} {"text":"Number of ways of cutting a Matrix such that atleast one cell is filled in each part | Function to find the number of ways to cut the matrix into the K parts such that each part have atleast one filled cell ; Loop to find prefix sum of the given matrix ; dp ( r , c , 1 ) = 1 if preSum [ r ] else 0 ; Loop to iterate over the dp table of the given matrix ; Check if can cut horizontally at r1 , at least one apple in matrix ( r , c ) -> r1 , C - 1 ; Check if we can cut vertically at c1 , at least one apple in matrix ( r , c ) -> R - 1 , c1 ; Driver Code ; Function Call","code":"def ways ( arr , k ) : NEW_LINE INDENT R = len ( arr ) NEW_LINE C = len ( arr [ 0 ] ) NEW_LINE K = k NEW_LINE preSum = [ [ 0 for _ in range ( C ) ] \\ for _ in range ( R ) ] NEW_LINE for r in range ( R - 1 , - 1 , - 1 ) : NEW_LINE INDENT for c in range ( C - 1 , - 1 , - 1 ) : NEW_LINE INDENT preSum [ r ] = arr [ r ] NEW_LINE if r + 1 < R : NEW_LINE INDENT preSum [ r ] += preSum [ r + 1 ] NEW_LINE DEDENT if c + 1 < C : NEW_LINE INDENT preSum [ r ] += preSum [ r ] NEW_LINE DEDENT if r + 1 < R and c + 1 < C : NEW_LINE INDENT preSum [ r ] -= preSum [ r + 1 ] NEW_LINE DEDENT DEDENT DEDENT dp = [ [ [ 0 for _ in range ( C ) ] \\ for _ in range ( R ) ] \\ for _ in range ( K + 1 ) ] NEW_LINE for k in range ( 1 , K + 1 ) : NEW_LINE INDENT for r in range ( R - 1 , - 1 , - 1 ) : NEW_LINE INDENT for c in range ( C - 1 , - 1 , - 1 ) : NEW_LINE INDENT if k == 1 : NEW_LINE INDENT dp [ k ] [ r ] = 1 if preSum [ r ] > 0 else 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ k ] [ r ] = 0 NEW_LINE for r1 in range ( r + 1 , R ) : NEW_LINE INDENT if preSum [ r ] - preSum [ r1 ] > 0 : NEW_LINE INDENT dp [ k ] [ r ] += dp [ k - 1 ] [ r1 ] NEW_LINE DEDENT DEDENT for c1 in range ( c + 1 , C ) : NEW_LINE INDENT if preSum [ r ] - preSum [ r ] [ c1 ] > 0 : NEW_LINE INDENT dp [ k ] [ r ] += dp [ k - 1 ] [ r ] [ c1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return dp [ K ] [ 0 ] [ 0 ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ [ 1 , 0 , 0 ] , [ 1 , 1 , 1 ] , [ 0 , 0 , 0 ] ] NEW_LINE k = 3 NEW_LINE print ( ways ( arr , k ) ) NEW_LINE DEDENT"} {"text":"Product of all sorted subsets of size K using elements whose index divide K completely | Python3 implementation of the above approach ; Iterative Function to calculate ( x ^ y ) % p in O ( log y ) ; If y is odd , multiply x with result ; y must be even now ; Iterative Function to calculate ( nCr ) % p and save in f [ n ] [ r ] ; If j > i then C ( i , j ) = 0 ; If i is equal to j then C ( i , j ) = 1 ; Function calculate the Final answer ; Initialize ans ; x is count of occurence of arr [ i ] in different set such that index of arr [ i ] in those sets divides K completely . ; Finding the count of arr [ i ] by placing it at index which divides K completely ; By Fermat 's theorem ; Driver code","code":"p = 1000000007 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 y = y >> 1 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , p , f , m ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT f [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( j == 0 or j == i ) : NEW_LINE INDENT f [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT f [ i ] [ j ] = ( f [ i - 1 ] [ j ] + f [ i - 1 ] [ j - 1 ] ) % p NEW_LINE DEDENT DEDENT DEDENT DEDENT def ProductOfSubsets ( arr , n , m ) : NEW_LINE INDENT f = [ [ 0 for i in range ( 100 ) ] for j in range ( n + 1 ) ] NEW_LINE nCr ( n , p - 1 , f , m ) NEW_LINE arr . sort ( reverse = False ) NEW_LINE ans = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = 0 NEW_LINE for j in range ( 1 , m + 1 , 1 ) : NEW_LINE INDENT if ( m % j == 0 ) : NEW_LINE INDENT x = ( ( x + ( f [ n - i - 1 ] [ m - j ] * f [ i ] [ j - 1 ] ) % ( p - 1 ) ) % ( p - 1 ) ) NEW_LINE DEDENT DEDENT ans = ( ( ans * power ( arr [ i ] , x , p ) ) % p ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 7 , 9 , 3 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) ; NEW_LINE ProductOfSubsets ( arr , N , K ) NEW_LINE DEDENT"} {"text":"Number of ways to write N as a sum of K non | Function to count the number of ways to write N as sum of k non - negative integers ; Initialise dp [ ] [ ] array ; Only 1 way to choose the value with sum K ; Initialise sum ; Count the ways from previous states ; Update the sum ; Return the final count of ways ; Driver Code ; Function call","code":"def countWays ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( 2 , m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT sum = 0 NEW_LINE for k in range ( j + 1 ) : NEW_LINE INDENT sum += dp [ i - 1 ] [ k ] NEW_LINE DEDENT dp [ i ] [ j ] = sum NEW_LINE DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE K = 3 NEW_LINE print ( countWays ( N , K ) ) NEW_LINE DEDENT"} {"text":"Number of ways to write N as a sum of K non | Function to count the number of ways to write N as sum of k non - negative integers ; Initialise dp [ ] [ ] array ; Fill the dp [ ] [ ] with sum = m ; Iterate the dp [ ] [ ] to fill the dp [ ] [ ] array ; Condition for first column ; Else fill the dp [ ] [ ] with sum till ( i , j ) ; If reach the end , then return the value ; Update at current index ; Driver Code ; Function call","code":"def countWays ( n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ 1 ] [ i ] = 1 NEW_LINE if ( i != 0 ) : NEW_LINE INDENT dp [ 1 ] [ i ] += dp [ 1 ] [ i - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 2 , m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE if ( i == m and j == n ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT dp [ i ] [ j ] += dp [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT N = 2 NEW_LINE K = 3 NEW_LINE print ( countWays ( N , K ) ) NEW_LINE"} {"text":"Longest subsequence such that every element in the subsequence is formed by multiplying previous element with a prime | Python3 program to implement the above approach ; Function to pre - store primes ; Sieve method to check if prime or not ; Multiples ; Pre - store all the primes ; Function to find the longest subsequence ; Hash map ; Call the function to pre - store the primes ; Initialize last element with 1 as that is the longest possible ; Iterate from the back and find the longest ; Get the number ; Initialize dp [ i ] as 1 as the element will only me in the subsequence ; Iterate in all the primes and multiply to get the next element ; Next element if multiplied with it ; If exceeds the last element then break ; If the number is there in the array ; Get the maximum most element ; Hash the element ; Find the longest ; Driver Code","code":"from math import sqrt NEW_LINE def SieveOfEratosthenes ( MAX , primes ) : NEW_LINE INDENT prime = [ True ] * ( MAX + 1 ) ; NEW_LINE for p in range ( 2 , int ( sqrt ( MAX ) ) + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p ** 2 , MAX + 1 , p ) : NEW_LINE INDENT prime [ i ] = False ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT if ( prime [ i ] ) : NEW_LINE INDENT primes . append ( i ) ; NEW_LINE DEDENT DEDENT DEDENT def findLongest ( A , n ) : NEW_LINE INDENT mpp = { } ; NEW_LINE primes = [ ] ; NEW_LINE SieveOfEratosthenes ( A [ n - 1 ] , primes ) ; NEW_LINE dp = [ 0 ] * n ; NEW_LINE dp [ n - 1 ] = 1 ; NEW_LINE mpp [ A [ n - 1 ] ] = n - 1 ; NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT num = A [ i ] ; NEW_LINE dp [ i ] = 1 ; NEW_LINE maxi = 0 ; NEW_LINE for it in primes : NEW_LINE INDENT xx = num * it ; NEW_LINE if ( xx > A [ n - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT elif xx in mpp : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , 1 + dp [ mpp [ xx ] ] ) ; NEW_LINE DEDENT DEDENT mpp [ A [ i ] ] = i ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = [ 1 , 2 , 5 , 6 , 12 , 35 , 60 , 385 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( findLongest ( a , n ) ) ; NEW_LINE DEDENT"} {"text":"Number of Binary Strings of length N with K adjacent Set Bits | Function to find the number of Bit Strings of length N with K adjacent set bits ; Base Case when we form bit string of length n ; if f ( bit string ) = k , count this way ; Check if the last bit was set , if it was set then call for next index by incrementing the adjacent bit count else just call the next index with same value of adjacent bit count and either set the bit at current index or let it remain unset ; set the bit at currentIndex ; unset the bit at currentIndex ; Driver Code ; total ways = ( ways by placing 1 st bit as 1 + ways by placing 1 st bit as 0 )","code":"def waysToKAdjacentSetBits ( n , k , currentIndex , adjacentSetBits , lastBit ) : NEW_LINE INDENT if ( currentIndex == n ) : NEW_LINE INDENT if ( adjacentSetBits == k ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return 0 NEW_LINE DEDENT noOfWays = 0 NEW_LINE if ( lastBit == 1 ) : NEW_LINE INDENT noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits + 1 , 1 ) ; NEW_LINE noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits , 0 ) ; NEW_LINE DEDENT elif ( lastBit != 1 ) : NEW_LINE INDENT noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits , 1 ) ; NEW_LINE noOfWays += waysToKAdjacentSetBits ( n , k , currentIndex + 1 , adjacentSetBits , 0 ) ; NEW_LINE DEDENT return noOfWays ; NEW_LINE DEDENT n = 5 ; k = 2 ; NEW_LINE totalWays = ( waysToKAdjacentSetBits ( n , k , 1 , 0 , 1 ) + waysToKAdjacentSetBits ( n , k , 1 , 0 , 0 ) ) ; NEW_LINE print ( \" Number \u2581 of \u2581 ways \u2581 = \" , totalWays ) ; NEW_LINE"} {"text":"Sum of products of all combination taken ( 1 to n ) at a time | Find the postfix sum array ; Modify the array such that we don 't have to compute the products which are obtained before ; Finding sum of all combination taken 1 to N at a time ; sum taken 1 at time is simply sum of 1 - N ; for sum of products for all combination ; finding postfix array ; sum of products taken i + 1 at a time ; modify the array for overlapping problem ; Driver 's Code ; storing numbers from 1 to N ; calling allCombination","code":"def postfix ( a , n ) : NEW_LINE INDENT for i in range ( n - 1 , 1 , - 1 ) : NEW_LINE INDENT a [ i - 1 ] = a [ i - 1 ] + a [ i ] NEW_LINE DEDENT DEDENT def modify ( a , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT a [ i - 1 ] = i * a [ i ] ; NEW_LINE DEDENT DEDENT def allCombination ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT print ( \" f ( 1 ) \u2581 - - > \u2581 \" , sum ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT postfix ( a , n - i + 1 ) NEW_LINE sum = 0 NEW_LINE for j in range ( 1 , n - i + 1 ) : NEW_LINE INDENT sum += ( j * a [ j ] ) NEW_LINE DEDENT print ( \" f ( \" , i + 1 , \" ) \u2581 - - > \u2581 \" , sum ) NEW_LINE modify ( a , n ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 5 NEW_LINE a = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] = i + 1 NEW_LINE DEDENT allCombination ( a , n ) NEW_LINE DEDENT"} {"text":"Count ways to reach the nth stair using step 1 , 2 or 3 | Returns count of ways to reach n - th stair using 1 or 2 or 3 steps . ; Driver code","code":"def findStep ( n ) : NEW_LINE INDENT if ( n == 1 or n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( n == 2 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT else : NEW_LINE INDENT return findStep ( n - 3 ) + findStep ( n - 2 ) + findStep ( n - 1 ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE print ( findStep ( n ) ) NEW_LINE"} {"text":"Partition problem | DP | A utility function that returns true if there is a subset of arr [ ] with sun equal to given sum ; Base Cases ; If last element is greater than sum , then ignore it ; else , check if sum can be obtained by any of the following ( a ) including the last element ( b ) excluding the last element ; Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; Calculate sum of the elements in array ; If sum is odd , there cannot be two subsets with equal sum ; Find if there is subset with sum equal to half of total sum ; Driver code ; Function call","code":"def isSubsetSum ( arr , n , sum ) : NEW_LINE INDENT if sum == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT if n == 0 and sum != 0 : NEW_LINE INDENT return False NEW_LINE DEDENT if arr [ n - 1 ] > sum : NEW_LINE INDENT return isSubsetSum ( arr , n - 1 , sum ) NEW_LINE DEDENT return isSubsetSum ( arr , n - 1 , sum ) or isSubsetSum ( arr , n - 1 , sum - arr [ n - 1 ] ) NEW_LINE DEDENT def findPartion ( arr , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if sum % 2 != 0 : NEW_LINE INDENT return false NEW_LINE DEDENT return isSubsetSum ( arr , n , sum \/\/ 2 ) NEW_LINE DEDENT arr = [ 3 , 1 , 5 , 9 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE if findPartion ( arr , n ) == True : NEW_LINE INDENT print ( \" Can \u2581 be \u2581 divided \u2581 into \u2581 two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Can \u2581 not \u2581 be \u2581 divided \u2581 into \u2581 two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Partition problem | DP | Returns true if arr [ ] can be partitioned in two subsets of equal sum , otherwise false ; Calculate sum of all elements ; Initialize the part array as 0 ; Fill the partition table in bottom up manner ; the element to be included in the sum cannot be greater than the sum ; check if sum - arr [ i ] could be formed from a subset using elements before index i ; Drive code ; Function call","code":"def findPartiion ( arr , n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT if ( Sum % 2 != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT part = [ 0 ] * ( ( Sum \/\/ 2 ) + 1 ) NEW_LINE for i in range ( ( Sum \/\/ 2 ) + 1 ) : NEW_LINE INDENT part [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( Sum \/\/ 2 , arr [ i ] - 1 , - 1 ) : NEW_LINE INDENT if ( part [ j - arr [ i ] ] == 1 or j == arr [ i ] ) : NEW_LINE INDENT part [ j ] = 1 NEW_LINE DEDENT DEDENT DEDENT return part [ Sum \/\/ 2 ] NEW_LINE DEDENT arr = [ 1 , 3 , 3 , 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if ( findPartiion ( arr , n ) == 1 ) : NEW_LINE INDENT print ( \" Can \u2581 be \u2581 divided \u2581 into \u2581 two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Can \u2581 not \u2581 be \u2581 divided \u2581 into \u2581 two \u2581 subsets \u2581 of \u2581 equal \u2581 sum \" ) NEW_LINE DEDENT"} {"text":"Binomial Coefficient | DP | Function to find binomial coefficient ; Getting the modular inversion for all the numbers from 2 to r with respect to m here m = 1000000007 ; for 1 \/ ( r ! ) part ; for ( n ) * ( n - 1 ) * ( n - 2 ) * ... * ( n - r + 1 ) part ; Driver code","code":"def binomialCoeff ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT m = 1000000007 NEW_LINE inv = [ 0 for i in range ( r + 1 ) ] NEW_LINE inv [ 0 ] = 1 ; NEW_LINE if ( r + 1 >= 2 ) NEW_LINE inv [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , r + 1 ) : NEW_LINE INDENT inv [ i ] = m - ( m \/\/ i ) * inv [ m % i ] % m NEW_LINE DEDENT ans = 1 NEW_LINE for i in range ( 2 , r + 1 ) : NEW_LINE INDENT ans = ( ( ans % m ) * ( inv [ i ] % m ) ) % m NEW_LINE DEDENT for i in range ( n , n - r , - 1 ) : NEW_LINE INDENT ans = ( ( ans % m ) * ( i % m ) ) % m NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE r = 2 NEW_LINE print ( \" Value \u2581 of \u2581 C ( \" , n , \" , \u2581 \" , r , \" ) \u2581 is \u2581 \" , binomialCoeff ( n , r ) ) NEW_LINE"} {"text":"Check if it is possible to reach ( X , Y ) from ( 1 , 1 ) by given steps | Function to find the gcd of two numbers ; Base case ; Recurse ; Function to print the answer ; GCD of X and Y ; If GCD is power of 2 ; Driver code ; Given X and Y ; Function call","code":"def gcd ( a , b ) : NEW_LINE INDENT if ( a < b ) : NEW_LINE INDENT t = a NEW_LINE a = b NEW_LINE b = t NEW_LINE DEDENT if ( a % b == 0 ) : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def printAnswer ( x , y ) : NEW_LINE INDENT val = gcd ( x , y ) NEW_LINE if ( ( val & ( val - 1 ) ) == 0 ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x = 4 NEW_LINE y = 7 NEW_LINE printAnswer ( x , y ) NEW_LINE DEDENT"} {"text":"Find the element in the matrix generated by given rules | Function to return the element in the rth row and cth column from the required matrix ; Condition for lower half of matrix ; Condition if element is in first row ; Starting element of AP in row r ; Common difference of AP in row r ; Position of element to find in AP in row r ; Driver Code","code":"def getElement ( N , r , c ) : NEW_LINE INDENT if ( r > c ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( r == 1 ) : NEW_LINE INDENT return c ; NEW_LINE DEDENT a = ( r + 1 ) * pow ( 2 , r - 2 ) ; NEW_LINE d = pow ( 2 , r - 1 ) ; NEW_LINE c = c - r ; NEW_LINE element = a + d * c ; NEW_LINE return element ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 ; R = 3 ; C = 4 ; NEW_LINE print ( getElement ( N , R , C ) ) ; NEW_LINE DEDENT"} {"text":"Find smallest number formed by inserting given digit | Function to insert X in N and return the minimum value string ; Variable to store length of string N ; Variable to denote the position where X must be added ; If the given string N represent a negative value ; X must be place at the last index where is greater than N [ i ] ; For positive numbers , X must be placed at the last index where it is smaller than N [ i ] ; Insert X at that position ; Return the string ; Given Input ; Function Call","code":"def MinValue ( N , X ) : NEW_LINE INDENT N = list ( N ) ; NEW_LINE ln = len ( N ) NEW_LINE position = ln + 1 NEW_LINE if ( N [ 0 ] == ' - ' ) : NEW_LINE INDENT for i in range ( ln - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( ( ord ( N [ i ] ) - ord ( '0' ) ) < X ) : NEW_LINE INDENT position = i NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( ln - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( ( ord ( N [ i ] ) - ord ( '0' ) ) > X ) : NEW_LINE INDENT position = i NEW_LINE DEDENT DEDENT DEDENT c = chr ( X + ord ( '0' ) ) NEW_LINE str = N . insert ( position , c ) ; NEW_LINE return ' ' . join ( N ) NEW_LINE DEDENT N = \"89\" NEW_LINE X = 1 NEW_LINE print ( MinValue ( N , X ) ) NEW_LINE"} {"text":"Check if Decimal representation of given Binary String is divisible by K or not | Function to check the binary number is divisible by K ; Array poweroftwo will store pow ( 2 , i ) % k ; Initializing the first element in Array ; Storing every pow ( 2 , i ) % k value in the array ; To store the remaining ; Iterating till N ; If current bit is 1 ; Updating rem ; If completely divisible ; If not Completely divisible ; Driver Code ; Given Input ; length of string s ; Function Call","code":"def divisibleByk ( s , n , k ) : NEW_LINE INDENT poweroftwo = [ 0 for i in range ( n ) ] NEW_LINE poweroftwo [ 0 ] = 1 % k NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT poweroftwo [ i ] = ( poweroftwo [ i - 1 ] * ( 2 % k ) ) % k NEW_LINE DEDENT rem = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ n - i - 1 ] == '1' ) : NEW_LINE INDENT rem += ( poweroftwo [ i ] ) NEW_LINE rem %= k NEW_LINE DEDENT DEDENT if ( rem == 0 ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT else : NEW_LINE INDENT return \" No \" NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \"1010001\" NEW_LINE k = 9 NEW_LINE n = len ( s ) NEW_LINE print ( divisibleByk ( s , n , k ) ) NEW_LINE DEDENT"} {"text":"Count removal of pairs required to be empty all Balanced Parenthesis subsequences | Function to find the maximum count of pairs required to be removed such that subsequence of string does not contain any valid parenthesis ; Stores count of pairs of balanced parenthesis ; Stores count of curly balanced parenthesis ; Stores count of small balanced parenthesis ; Stores count of square balanced parenthesis ; Iterate over characters of the string ; Update cntCurly ; Update cntSml ; Update cntSqr ; Update cntCurly ; Update cntPairs ; Update cntSml ; Update cntPairs ; Update cntSml ; Update cntPairs ; Driver Code ; Given String ; Function call","code":"def cntBalancedParenthesis ( s , N ) : NEW_LINE INDENT cntPairs = 0 ; NEW_LINE cntCurly = 0 ; NEW_LINE cntSml = 0 ; NEW_LINE cntSqr = 0 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ord ( s [ i ] ) == ord ( ' { ' ) ) : NEW_LINE INDENT cntCurly += 1 ; NEW_LINE DEDENT elif ( ord ( s [ i ] ) == ord ( ' ( ' ) ) : NEW_LINE INDENT cntSml += 1 ; NEW_LINE DEDENT elif ( ord ( s [ i ] ) == ord ( ' [ ' ) ) : NEW_LINE INDENT cntSqr += 1 ; NEW_LINE DEDENT elif ( ord ( s [ i ] ) == ord ( ' } ' ) and cntCurly > 0 ) : NEW_LINE INDENT cntCurly -= 1 ; NEW_LINE cntPairs += 1 ; NEW_LINE DEDENT elif ( ord ( s [ i ] ) == ord ( ' ) ' ) and cntSml > 0 ) : NEW_LINE INDENT cntSml -= 1 ; NEW_LINE cntPairs += 1 ; NEW_LINE DEDENT elif ( ord ( s [ i ] ) == ord ( ' ] ' ) and cntSqr > 0 ) : NEW_LINE INDENT cntSqr -= 1 ; NEW_LINE cntPairs += 1 ; NEW_LINE DEDENT DEDENT print ( cntPairs ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" { ( } ) \" ; NEW_LINE N = len ( s ) ; NEW_LINE cntBalancedParenthesis ( s , N ) ; NEW_LINE DEDENT"} {"text":"Count of strings that does not contain Arc intersection | Function to check if there is arc intersection or not ; Traverse the string S ; Insert all the elements in the stack one by one ; Extract the top element ; Pop out the top element ; Check if the top element is same as the popped element ; Otherwise ; If the stack is empty ; Function to check if there is arc intersection or not for the given array of strings ; Stores count of string not having arc intersection ; Iterate through array ; Length of every string ; Function Call ; Print the desired count ; Driver Code ; Function Call","code":"def arcIntersection ( S , lenn ) : NEW_LINE INDENT stk = [ ] NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT stk . append ( S [ i ] ) NEW_LINE if ( len ( stk ) >= 2 ) : NEW_LINE INDENT temp = stk [ - 1 ] NEW_LINE del stk [ - 1 ] NEW_LINE if ( stk [ - 1 ] == temp ) : NEW_LINE INDENT del stk [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT stk . append ( temp ) NEW_LINE DEDENT DEDENT DEDENT if ( len ( stk ) == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def countString ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT lenn = len ( arr [ i ] ) NEW_LINE count += arcIntersection ( arr [ i ] , lenn ) NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ \"0101\" , \"0011\" , \"0110\" ] NEW_LINE N = len ( arr ) NEW_LINE countString ( arr , N ) NEW_LINE DEDENT"} {"text":"Check if decimal representation of Binary String is divisible by 9 or not | Function to convert the binary string into octal representation ; Stores binary representation of the decimal value [ 0 - 7 ] ; Stores the decimal values of binary strings [ 0 - 7 ] ; Stores length of S ; Update S ; Update S ; Update N ; Stores octal representation of the binary string ; Traverse the binary string ; Stores 3 consecutive characters of the binary string ; Append octal representation of temp ; Function to check if binary string is divisible by 9 or not ; Stores octal representation of S ; Stores sum of elements present at odd positions of oct ; Stores sum of elements present at odd positions of oct ; Stores length of oct ; Traverse the string oct ; Update oddSum ; Traverse the string oct ; Update evenSum ; Stores cotal representation of 9 ; If absolute value of ( oddSum - evenSum ) is divisible by Oct_9 ; Driver Code","code":"def ConvertequivalentBase8 ( S ) : NEW_LINE INDENT mp = { } NEW_LINE mp [ \"000\" ] = '0' NEW_LINE mp [ \"001\" ] = '1' NEW_LINE mp [ \"010\" ] = '2' NEW_LINE mp [ \"011\" ] = '3' NEW_LINE mp [ \"100\" ] = '4' NEW_LINE mp [ \"101\" ] = '5' NEW_LINE mp [ \"110\" ] = '6' NEW_LINE mp [ \"111\" ] = '7' NEW_LINE N = len ( S ) NEW_LINE if ( N % 3 == 2 ) : NEW_LINE INDENT S = \"0\" + S NEW_LINE DEDENT elif ( N % 3 == 1 ) : NEW_LINE INDENT S = \"00\" + S NEW_LINE DEDENT N = len ( S ) NEW_LINE octal = \" \" NEW_LINE for i in range ( 0 , N , 3 ) : NEW_LINE INDENT temp = S [ i : i + 3 ] NEW_LINE if temp in mp : NEW_LINE octal += ( mp [ temp ] ) NEW_LINE DEDENT return octal NEW_LINE DEDENT def binString_div_9 ( S , N ) : NEW_LINE INDENT octal = ConvertequivalentBase8 ( S ) NEW_LINE oddSum = 0 NEW_LINE evenSum = 0 NEW_LINE M = len ( octal ) NEW_LINE for i in range ( 0 , M , 2 ) : NEW_LINE INDENT oddSum += ord ( octal [ i ] ) - ord ( '0' ) NEW_LINE DEDENT for i in range ( 1 , M , 2 ) : NEW_LINE INDENT evenSum += ord ( octal [ i ] ) - ord ( '0' ) NEW_LINE DEDENT Oct_9 = 11 NEW_LINE if ( abs ( oddSum - evenSum ) % Oct_9 == 0 ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT return \" No \" NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT S = \"1010001\" NEW_LINE N = len ( S ) NEW_LINE print ( binString_div_9 ( S , N ) ) NEW_LINE DEDENT"} {"text":"Minimum cost to remove the spaces between characters of a String by rearranging the characters | Function to calculate the minimum cost ; Stores the minimum cost ; Stores the count of characters found ; Stores the count of blank spaces found ; Stores the count of total characters ; If the count of characters is equal to 1 ; Iterate over the string ; Consider the previous character together with current character ; If not together already ; Add the cost to group them together ; Increase count of characters found ; Otherwise ; Increase count of spaces found ; Return the total cost obtained ; Driver Code","code":"def min_cost ( S ) : NEW_LINE INDENT cost = 0 NEW_LINE F = 0 NEW_LINE B = 0 NEW_LINE n = len ( S ) - S . count ( ' \u2581 ' ) NEW_LINE if n == 1 : NEW_LINE INDENT return cost NEW_LINE DEDENT for char in S : NEW_LINE INDENT if char != ' \u2581 ' : NEW_LINE INDENT if B != 0 : NEW_LINE INDENT cost += min ( n - F , F ) * B NEW_LINE B = 0 NEW_LINE DEDENT F += 1 NEW_LINE DEDENT else : NEW_LINE INDENT B += 1 NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT S = \" \u2581 @ TABSYMBOL $ \" NEW_LINE print ( min_cost ( S ) ) NEW_LINE"} {"text":"Minimize cost to replace all the vowels of a given String by a single vowel | Function that return true if the given character is a vowel ; Function to return the minimum cost to convert all the vowels of a string to a single one ; Stores count of respective vowels ; Iterate through the string ; If a vowel is encountered ; Calculate the cost ; Return the minimum cost ; Driver code","code":"def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT def minCost ( S ) : NEW_LINE INDENT cA = 0 ; NEW_LINE cE = 0 ; NEW_LINE cI = 0 ; NEW_LINE cO = 0 ; NEW_LINE cU = 0 ; NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT if ( isVowel ( S [ i ] ) ) : NEW_LINE INDENT cA += abs ( ord ( S [ i ] ) - ord ( ' a ' ) ) ; NEW_LINE cE += abs ( ord ( S [ i ] ) - ord ( ' e ' ) ) ; NEW_LINE cI += abs ( ord ( S [ i ] ) - ord ( ' i ' ) ) ; NEW_LINE cO += abs ( ord ( S [ i ] ) - ord ( ' o ' ) ) ; NEW_LINE cU += abs ( ord ( S [ i ] ) - ord ( ' u ' ) ) ; NEW_LINE DEDENT DEDENT return min ( min ( min ( min ( cA , cE ) , cI ) , cO ) , cU ) ; NEW_LINE DEDENT S = \" geeksforgeeks \" ; NEW_LINE print ( minCost ( S ) ) NEW_LINE"} {"text":"Generate a string whose all K | Function to return the required required string ; Iterate the given string ; Append the first character of every substring of length K ; Consider all characters from the last substring ; Driver code","code":"def decode_String ( st , K ) : NEW_LINE INDENT ans = \" \" NEW_LINE for i in range ( 0 , len ( st ) , K ) : NEW_LINE INDENT ans += st [ i ] NEW_LINE DEDENT for i in range ( len ( st ) - ( K - 1 ) , len ( st ) ) : NEW_LINE INDENT ans += st [ i ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT K = 3 NEW_LINE st = \" abcbcscsesesesd \" NEW_LINE decode_String ( st , K ) NEW_LINE DEDENT"} {"text":"Lexicographically smallest K | Function that prints the lexicographically smallest K - length substring containing maximum number of vowels ; Store the length of the string ; Initialize a prefix sum array ; Loop through the string to create the prefix sum array ; Store 1 at the index if it is a vowel ; Otherwise , store 0 ; Process the prefix array ; Initialize the variable to store maximum count of vowels ; Initialize the variable to store substring with maximum count of vowels ; Loop through the prefix array ; Store the current count of vowels ; Update the result if current count is greater than maximum count ; Update lexicographically smallest substring if the current count is equal to the maximum count ; Return the result ; Driver code","code":"def maxVowelSubString ( str1 , K ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE pref = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str1 [ i ] == ' a ' or str1 [ i ] == ' e ' or str1 [ i ] == ' i ' or str1 [ i ] == ' o ' or str1 [ i ] == ' u ' ) : NEW_LINE INDENT pref [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT pref [ i ] = 0 NEW_LINE DEDENT if ( i ) : NEW_LINE INDENT pref [ i ] += pref [ i - 1 ] NEW_LINE DEDENT DEDENT maxCount = pref [ K - 1 ] NEW_LINE res = str1 [ 0 : K ] NEW_LINE for i in range ( K , N ) : NEW_LINE INDENT currCount = pref [ i ] - pref [ i - K ] NEW_LINE if ( currCount > maxCount ) : NEW_LINE INDENT maxCount = currCount NEW_LINE res = str1 [ i - K + 1 : i + 1 ] NEW_LINE DEDENT elif ( currCount == maxCount ) : NEW_LINE INDENT temp = str1 [ i - K + 1 : i + 1 ] NEW_LINE if ( temp < res ) : NEW_LINE INDENT res = temp NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \" ceebbaceeffo \" NEW_LINE K = 3 NEW_LINE print ( maxVowelSubString ( str1 , K ) ) NEW_LINE DEDENT"} {"text":"Decode the string encoded with the given algorithm | Function to decode and print the original string ; To store the decoded string ; Getting the mid element ; Storing the first element of the string at the median position ; If the length is even then store the second element also ; k represents the number of characters that are already stored in the c [ ] ; If string length is odd ; If it is even ; Print the decoded string ; Driver code","code":"def decodeStr ( str , len ) : NEW_LINE INDENT c = [ \" \" for i in range ( len ) ] NEW_LINE pos = 1 NEW_LINE if ( len % 2 == 1 ) : NEW_LINE INDENT med = int ( len \/ 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT med = int ( len \/ 2 - 1 ) NEW_LINE DEDENT c [ med ] = str [ 0 ] NEW_LINE if ( len % 2 == 0 ) : NEW_LINE INDENT c [ med + 1 ] = str [ 1 ] NEW_LINE DEDENT if ( len & 1 ) : NEW_LINE INDENT k = 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = 2 NEW_LINE DEDENT for i in range ( k , len , 2 ) : NEW_LINE INDENT c [ med - pos ] = str [ i ] NEW_LINE if ( len % 2 == 1 ) : NEW_LINE INDENT c [ med + pos ] = str [ i + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT c [ med + pos + 1 ] = str [ i + 1 ] NEW_LINE DEDENT pos += 1 NEW_LINE DEDENT print ( * c , sep = \" \" ) NEW_LINE DEDENT str = \" ofrsgkeeeekgs \" NEW_LINE len = len ( str ) NEW_LINE decodeStr ( str , len ) NEW_LINE"} {"text":"Count of distinct characters in a substring by given range for Q queries | Python3 program for Naive Approach ; Counter to count distinct char ; Initializing frequency array to count characters as the appear in substring S [ L : R ] ; Iterating over S [ L ] to S [ R ] ; Incrementing the count of s [ i ] character in frequency array ; If frequency of any character is > 0 then increment the counter ; Driver code","code":"def findCount ( s , L , R ) : NEW_LINE INDENT distinct = 0 NEW_LINE frequency = [ 0 for i in range ( 26 ) ] NEW_LINE for i in range ( L , R + 1 , 1 ) : NEW_LINE INDENT frequency [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if ( frequency [ i ] > 0 ) : NEW_LINE INDENT distinct += 1 NEW_LINE DEDENT DEDENT print ( distinct ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" geeksforgeeksisacomputerscienceportal \" NEW_LINE queries = 3 NEW_LINE Q = [ [ 0 , 10 ] , [ 15 , 18 ] , [ 12 , 20 ] ] NEW_LINE for i in range ( queries ) : NEW_LINE INDENT findCount ( s , Q [ i ] [ 0 ] , Q [ i ] [ 1 ] ) NEW_LINE DEDENT DEDENT"} {"text":"String obtained by reversing and complementing a Binary string K times | Function to perform K operations upon the string and find modified string ; Number of reverse operations ; Number of complement operations ; If rev is odd parity ; If complement is odd parity ; Complementing each position ; Return the modified string ; Driver Code ; Function call","code":"def ReverseComplement ( s , n , k ) : NEW_LINE INDENT rev = ( k + 1 ) \/\/ 2 NEW_LINE complement = k - rev NEW_LINE if ( rev % 2 ) : NEW_LINE INDENT s = s [ : : - 1 ] NEW_LINE DEDENT if ( complement % 2 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT s [ i ] = '1' NEW_LINE DEDENT else : NEW_LINE INDENT s [ i ] = '0' NEW_LINE DEDENT DEDENT DEDENT return s NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = \"10011\" NEW_LINE k = 5 NEW_LINE n = len ( str1 ) NEW_LINE print ( ReverseComplement ( str1 , n , k ) ) NEW_LINE DEDENT"} {"text":"Check if any permutation of string is a K times repeated string | Function to check that permutation of the given string is a K times repeating String ; If length of string is not divisible by K ; Frequency Array ; Initially frequency of each character is 0 ; Computing the frequency of each character in the string ; Loop to check that frequency of every character of the string is divisible by K ; Driver Code","code":"def repeatingString ( s , n , k ) : NEW_LINE INDENT if ( n % k != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT frequency = [ 0 for i in range ( 123 ) ] NEW_LINE for i in range ( 123 ) : NEW_LINE INDENT frequency [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT frequency [ s [ i ] ] += 1 NEW_LINE DEDENT repeat = n \/\/ k NEW_LINE for i in range ( 123 ) : NEW_LINE INDENT if ( frequency [ i ] % repeat != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" abcdcba \" NEW_LINE n = len ( s ) NEW_LINE k = 3 NEW_LINE if ( repeatingString ( s , n , k ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Find the last two missing digits of the given phone number | Function to find the last two digits of the number and print the complete number ; Sum of the first eight digits of the number ; if sum < 10 , then the two digits are '0' and the value of sum ; if sum > 10 , then the two digits are the value of sum ; Driver code","code":"def findPhoneNumber ( n ) : NEW_LINE INDENT temp = n NEW_LINE sum = 0 NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT sum += temp % 10 NEW_LINE temp = temp \/\/ 10 NEW_LINE DEDENT if ( sum < 10 ) : NEW_LINE INDENT print ( n , \"0\" , sum ) NEW_LINE DEDENT else : NEW_LINE INDENT n = str ( n ) NEW_LINE sum = str ( sum ) NEW_LINE n += sum NEW_LINE print ( n ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 98765432 NEW_LINE findPhoneNumber ( n ) NEW_LINE DEDENT"} {"text":"Number of ways to split a binary number such that every part is divisible by 2 | Function to return the required count ; If the splitting is not possible ; To store the count of zeroes ; Counting the number of zeroes ; Return the final answer ; Driver code","code":"def cntSplits ( s ) : NEW_LINE INDENT if ( s [ len ( s ) - 1 ] == '1' ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT c_zero = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT c_zero += ( s [ i ] == '0' ) ; NEW_LINE DEDENT return int ( pow ( 2 , c_zero - 1 ) ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \"10010\" ; NEW_LINE print ( cntSplits ( s ) ) ; NEW_LINE DEDENT"} {"text":"Count number of substrings of a string consisting of same characters | Function to return the number of substrings of same characters ; Size of the string ; Initialize count to 1 ; Initialize left to 0 and right to 1 to traverse the string ; Checking if consecutive characters are same and increment the count ; When we encounter a different characters ; Increment the result ; To repeat the whole process set left equals right and count variable to 1 ; Store the final value of result ; Driver code","code":"def findNumbers ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE count = 1 NEW_LINE result = 0 NEW_LINE left = 0 NEW_LINE right = 1 NEW_LINE while ( right < n ) : NEW_LINE INDENT if ( s [ left ] == s [ right ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT result += count * ( count + 1 ) \/\/ 2 NEW_LINE left = right NEW_LINE count = 1 NEW_LINE DEDENT right += 1 NEW_LINE DEDENT result += count * ( count + 1 ) \/\/ 2 NEW_LINE print ( result ) NEW_LINE DEDENT s = \" bbbcbb \" NEW_LINE findNumbers ( s ) NEW_LINE"} {"text":"Program to duplicate Vowels in String | Function to check for the Vowel ; Function to get the resultant String with vowels duplicated ; Another to store the resultant String ; Loop to check for each character ; Driver Code ; Print the original String ; Print the resultant String","code":"def isVowel ( ch ) : NEW_LINE INDENT ch = ch . upper ( ) NEW_LINE if ( ch == ' A ' or ch == ' E ' or ch == ' I ' or ch == ' O ' or ch == ' U ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def duplicateVowels ( S ) : NEW_LINE INDENT t = len ( S ) NEW_LINE res = \" \" NEW_LINE for i in range ( t ) : NEW_LINE INDENT if ( isVowel ( S [ i ] ) ) : NEW_LINE INDENT res += S [ i ] NEW_LINE DEDENT res += S [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT S = \" helloworld \" NEW_LINE print ( \" Original \u2581 String : \u2581 \" , S ) NEW_LINE res = duplicateVowels ( S ) NEW_LINE print ( \" String \u2581 with \u2581 Vowels \u2581 duplicated : \u2581 \" , res ) NEW_LINE"} {"text":"Convert a String to an Integer using Recursion | Recursive function to convert string to integer ; If the number represented as a string contains only a single digit then returns its value ; Recursive call for the sub - string starting at the second character ; First digit of the number ; First digit multiplied by the appropriate power of 10 and then add the recursive result For example , xy = ( ( x * 10 ) + y ) ; Driver code","code":"def stringToInt ( str ) : NEW_LINE INDENT if ( len ( str ) == 1 ) : NEW_LINE INDENT return ord ( str [ 0 ] ) - ord ( '0' ) ; NEW_LINE DEDENT y = stringToInt ( str [ 1 : ] ) ; NEW_LINE x = ord ( str [ 0 ] ) - ord ( '0' ) ; NEW_LINE x = x * ( 10 ** ( len ( str ) - 1 ) ) + y ; NEW_LINE return int ( x ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = \"1235\" ; NEW_LINE print ( stringToInt ( str ) ) ; NEW_LINE DEDENT"} {"text":"Longest subsequence with at least one character appearing in every string | Python3 implementation of the approach ; Function to return the length of the longest sub - sequence with at least one common character in every string ; count [ 0 ] will store the number of strings which contain ' a ' , count [ 1 ] will store the number of strings which contain ' b ' and so on . . ; For every string ; Hash array to set which character is present in the current string ; If current character appears in the string then update its count ; Driver code","code":"MAX = 26 NEW_LINE def largestSubSeq ( arr , n ) : NEW_LINE INDENT count = [ 0 ] * MAX NEW_LINE for i in range ( n ) : NEW_LINE INDENT string = arr [ i ] NEW_LINE _hash = [ False ] * MAX NEW_LINE for j in range ( len ( string ) ) : NEW_LINE INDENT _hash [ ord ( string [ j ] ) - ord ( ' a ' ) ] = True NEW_LINE DEDENT for j in range ( MAX ) : NEW_LINE INDENT if _hash [ j ] == True : NEW_LINE INDENT count [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT return max ( count ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ \" ab \" , \" bc \" , \" de \" ] NEW_LINE n = len ( arr ) NEW_LINE print ( largestSubSeq ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Generate number with given operation and check if it is palindrome | Function that returns true if str is a palindrome ; Function that returns true if the generated string is a palindrome ; sub contains N as a string ; Calculate the sum of the digits ; Repeat the substring until the length of the resultant string < sum ; If length of the resultant string exceeded sum then take substring from 0 to sum - 1 ; If the generated string is a palindrome ; Driver code","code":"def isPalindrome ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE for i in range ( l \/\/ 2 ) : NEW_LINE INDENT if ( s [ i ] != s [ l - 1 - i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def createStringAndCheckPalindrome ( N ) : NEW_LINE INDENT sub = \" \" + chr ( N ) NEW_LINE res_str = \" \" NEW_LINE sum = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT digit = N % 10 NEW_LINE sum += digit NEW_LINE N = N \/\/ 10 NEW_LINE DEDENT while ( len ( res_str ) < sum ) : NEW_LINE INDENT res_str += sub NEW_LINE DEDENT if ( len ( res_str ) > sum ) : NEW_LINE INDENT res_str = res_str [ 0 : sum ] NEW_LINE DEDENT if ( isPalindrome ( res_str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 10101 NEW_LINE if ( createStringAndCheckPalindrome ( N ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Minimize the length of string by removing occurrence of only one character | Function to find the minimum length ; Count the frequency of each alphabet ; Find the alphabets with maximum frequency ; Subtract the frequency of character from length of string ; Driver Code","code":"def minimumLength ( s ) : NEW_LINE INDENT maxOcc = 0 NEW_LINE n = len ( s ) NEW_LINE arr = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT if arr [ i ] > maxOcc : NEW_LINE INDENT maxOcc = arr [ i ] NEW_LINE DEDENT DEDENT return n - maxOcc NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" afddewqd \" NEW_LINE print ( minimumLength ( str ) ) NEW_LINE DEDENT"} {"text":"Remove all characters other than alphabets from string | function to remove characters and pr new string ; Finding the character whose ASCII value fall under this range ; erase function to erase the character ; Driver Code","code":"def removeSpecialCharacter ( s ) : NEW_LINE INDENT i = 0 NEW_LINE while i < len ( s ) : NEW_LINE INDENT if ( ord ( s [ i ] ) < ord ( ' A ' ) or ord ( s [ i ] ) > ord ( ' Z ' ) and ord ( s [ i ] ) < ord ( ' a ' ) or ord ( s [ i ] ) > ord ( ' z ' ) ) : NEW_LINE INDENT del s [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( \" \" . join ( s ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = \" $ Gee * k ; s . . fo , \u2581 r ' Ge ^ eks ? \" NEW_LINE s = [ i for i in s ] NEW_LINE removeSpecialCharacter ( s ) NEW_LINE DEDENT"} {"text":"Remove all characters other than alphabets from string | Function to remove special characters and store it in another variable ; Store only valid characters ; Driver code","code":"def removeSpecialCharacter ( s ) : NEW_LINE INDENT t = \" \" NEW_LINE for i in s : NEW_LINE INDENT if ( i >= ' A ' and i <= ' Z ' ) or ( i >= ' a ' and i <= ' z ' ) : NEW_LINE INDENT t += i NEW_LINE DEDENT DEDENT print ( t ) NEW_LINE DEDENT s = \" $ Gee * k ; s . . fo , \u2581 r ' Ge ^ eks ? \" NEW_LINE removeSpecialCharacter ( s ) NEW_LINE"} {"text":"Find repeated character present first in a string | Python3 program to find the first character that is repeated ; this is O ( N ^ 2 ) method ; Driver code","code":"def findRepeatFirstN2 ( s ) : NEW_LINE INDENT p = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == s [ j ] ) : NEW_LINE INDENT p = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( p != - 1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return p NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeksforgeeks \" NEW_LINE pos = findRepeatFirstN2 ( str ) NEW_LINE if ( pos == - 1 ) : NEW_LINE INDENT print ( \" Not \u2581 found \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( str [ pos ] ) NEW_LINE DEDENT DEDENT"} {"text":"Print characters and their frequencies in order of occurrence | Python3 implementation to print the characters and frequencies in order of its occurrence ; Store all characters and their frequencies in dictionary ; Print characters and their frequencies in same order of their appearance ; Print only if this character is not printed before . ; Driver Code","code":"def prCharWithFreq ( str ) : NEW_LINE INDENT d = { } NEW_LINE for i in str : NEW_LINE INDENT if i in d : NEW_LINE INDENT d [ i ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT d [ i ] = 1 NEW_LINE DEDENT DEDENT for i in str : NEW_LINE INDENT if d [ i ] != 0 : NEW_LINE INDENT print ( \" { } { } \" . format ( i , d [ i ] ) , end = \" \u2581 \" ) NEW_LINE d [ i ] = 0 NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeksforgeeks \" ; NEW_LINE prCharWithFreq ( str ) ; NEW_LINE DEDENT ' NEW_LINE"} {"text":"Count number of strings ( made of R , G and B ) using given combination | Function to calculate number of strings ; Store factorial of numbers up to n for further computation ; Find the remaining values to be added ; Make all possible combinations of R , B and G for the remaining value ; Compute permutation of each combination one by one and add them . ; Return total no . of strings \/ permutation ; Driver code","code":"def possibleStrings ( n , r , b , g ) : NEW_LINE INDENT fact = [ 0 for i in range ( n + 1 ) ] NEW_LINE fact [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT fact [ i ] = fact [ i - 1 ] * i NEW_LINE DEDENT left = n - ( r + g + b ) NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , left + 1 , 1 ) : NEW_LINE INDENT for j in range ( 0 , left - i + 1 , 1 ) : NEW_LINE INDENT k = left - ( i + j ) NEW_LINE sum = ( sum + fact [ n ] \/ ( fact [ i + r ] * fact [ j + b ] * fact [ k + g ] ) ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE r = 2 NEW_LINE b = 0 NEW_LINE g = 1 NEW_LINE print ( int ( possibleStrings ( n , r , b , g ) ) ) NEW_LINE DEDENT"} {"text":"Remove minimum number of characters so that two strings become anagram | Python 3 program to find minimum number of characters to be removed to make two strings anagram . ; function to calculate minimum numbers of characters to be removed to make two strings anagram ; make hash array for both string and calculate frequency of each character ; count frequency of each character in first string ; count frequency of each character in second string ; traverse count arrays to find number of characters to be removed ; Driver program to run the case","code":"CHARS = 26 NEW_LINE def remAnagram ( str1 , str2 ) : NEW_LINE INDENT count1 = [ 0 ] * CHARS NEW_LINE count2 = [ 0 ] * CHARS NEW_LINE i = 0 NEW_LINE while i < len ( str1 ) : NEW_LINE INDENT count1 [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE i += 1 NEW_LINE DEDENT i = 0 NEW_LINE while i < len ( str2 ) : NEW_LINE INDENT count2 [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE i += 1 NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT result += abs ( count1 [ i ] - count2 [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" bcadeh \" NEW_LINE str2 = \" hea \" NEW_LINE print ( remAnagram ( str1 , str2 ) ) NEW_LINE DEDENT"} {"text":"Check if a string has all characters with same frequency with one variation allowed | Assuming only lower case characters ; To check a string S can be converted to a valid string by removing less than or equal to one character . ; freq [ ] : stores the frequency of each character of a string ; Find first character with non - zero frequency ; Find a character with frequency different from freq1 . ; If we find a third non - zero frequency or count of both frequencies become more than 1 , then return false ; If we find a third non - zero freq ; If counts of both frequencies is more than 1 ; Return true if we reach here ; Driver code","code":"CHARS = 26 NEW_LINE def isValidString ( str ) : NEW_LINE INDENT freq = [ 0 ] * CHARS NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT freq [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT freq1 = 0 NEW_LINE count_freq1 = 0 NEW_LINE for i in range ( CHARS ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT freq1 = freq [ i ] NEW_LINE count_freq1 = 1 NEW_LINE break NEW_LINE DEDENT DEDENT freq2 = 0 NEW_LINE count_freq2 = 0 NEW_LINE for j in range ( i + 1 , CHARS ) : NEW_LINE INDENT if ( freq [ j ] != 0 ) : NEW_LINE INDENT if ( freq [ j ] == freq1 ) : NEW_LINE INDENT count_freq1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count_freq2 = 1 NEW_LINE freq2 = freq [ j ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT for k in range ( j + 1 , CHARS ) : NEW_LINE INDENT if ( freq [ k ] != 0 ) : NEW_LINE INDENT if ( freq [ k ] == freq1 ) : NEW_LINE INDENT count_freq1 += 1 NEW_LINE DEDENT if ( freq [ k ] == freq2 ) : NEW_LINE INDENT count_freq2 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if ( count_freq1 > 1 and count_freq2 > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" abcbc \" NEW_LINE if ( isValidString ( str ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} {"text":"Check if a string has all characters with same frequency with one variation allowed | To check a string S can be converted to a variation string ; Run loop form 0 to length of string ; declaration of variables ; if first is true than countOfVal1 increase ; if second is true than countOfVal2 increase ; Driver code","code":"def checkForVariation ( strr ) : NEW_LINE INDENT if ( len ( strr ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT mapp = { } NEW_LINE for i in range ( len ( strr ) ) : NEW_LINE INDENT if strr [ i ] in mapp : NEW_LINE INDENT mapp [ strr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mapp [ strr [ i ] ] = 1 NEW_LINE DEDENT DEDENT first = True NEW_LINE second = True NEW_LINE val1 = 0 NEW_LINE val2 = 0 NEW_LINE countOfVal1 = 0 NEW_LINE countOfVal2 = 0 NEW_LINE for itr in mapp : NEW_LINE INDENT i = itr NEW_LINE if ( first ) : NEW_LINE INDENT val1 = i NEW_LINE first = False NEW_LINE countOfVal1 += 1 NEW_LINE continue NEW_LINE DEDENT if ( i == val1 ) : NEW_LINE INDENT countOfVal1 += 1 NEW_LINE continue NEW_LINE DEDENT if ( second ) : NEW_LINE INDENT val2 = i NEW_LINE countOfVal2 += 1 NEW_LINE second = False NEW_LINE continue NEW_LINE DEDENT if ( i == val2 ) : NEW_LINE INDENT countOfVal2 += 1 NEW_LINE continue NEW_LINE DEDENT DEDENT if ( countOfVal1 > 1 and countOfVal2 > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT print ( checkForVariation ( \" abcbc \" ) ) NEW_LINE"} {"text":"Pairs of complete strings in two sets of strings | Returns count of complete pairs from set [ 0. . n - 1 ] and set2 [ 0. . m - 1 ] ; con_s1 [ i ] is going to store an integer whose set bits represent presence \/ absence of characters in set1 [ i ] . Similarly con_s2 [ i ] is going to store an integer whose set bits represent presence \/ absence of characters in set2 [ i ] ; Process all strings in set1 [ ] ; initializing all bits to 0 ; Setting the ascii code of char s [ i ] [ j ] to 1 in the compressed integer . ; Process all strings in set2 [ ] ; initializing all bits to 0 ; setting the ascii code of char s [ i ] [ j ] to 1 in the compressed integer . ; assigning a variable whose all 26 ( 0. . 25 ) bits are set to 1 ; Now consider every pair of integer in con_s1 [ ] and con_s2 [ ] and check if the pair is complete . ; if all bits are set , the strings are complete ! ; Driver code","code":"def countCompletePairs ( set1 , set2 , n , m ) : NEW_LINE INDENT result = 0 NEW_LINE con_s1 , con_s2 = [ 0 ] * n , [ 0 ] * m NEW_LINE for i in range ( n ) : NEW_LINE INDENT con_s1 [ i ] = 0 NEW_LINE for j in range ( len ( set1 [ i ] ) ) : NEW_LINE INDENT con_s1 [ i ] = con_s1 [ i ] | ( 1 << ( ord ( set1 [ i ] [ j ] ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT con_s2 [ i ] = 0 NEW_LINE for j in range ( len ( set2 [ i ] ) ) : NEW_LINE INDENT con_s2 [ i ] = con_s2 [ i ] | ( 1 << ( ord ( set2 [ i ] [ j ] ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT DEDENT complete = ( 1 << 26 ) - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( ( con_s1 [ i ] con_s2 [ j ] ) == complete ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT set1 = [ \" abcdefgh \" , \" geeksforgeeks \" , \" lmnopqrst \" , \" abc \" ] NEW_LINE set2 = [ \" ijklmnopqrstuvwxyz \" , \" abcdefghijklmnopqrstuvwxyz \" , \" defghijklmnopqrstuvwxyz \" ] NEW_LINE n = len ( set1 ) NEW_LINE m = len ( set2 ) NEW_LINE print ( countCompletePairs ( set1 , set2 , n , m ) ) NEW_LINE DEDENT"} {"text":"Find all strings that match specific pattern in a dictionary | Function to encode given string ; For each character in given string ; If the character is occurring for the first time , assign next unique number to that char ; Append the number associated with current character into the output string ; Function to print all the strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary ; len is length of the pattern ; Encode the string ; For each word in the dictionary array ; If size of pattern is same as size of current dictionary word and both pattern and the word has same hash , print the word ; Driver code","code":"def encodeString ( Str ) : NEW_LINE INDENT map = { } NEW_LINE res = \" \" NEW_LINE i = 0 NEW_LINE for ch in Str : NEW_LINE INDENT if ch not in map : NEW_LINE INDENT map [ ch ] = i NEW_LINE i += 1 NEW_LINE DEDENT res += str ( map [ ch ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def findMatchedWords ( dict , pattern ) : NEW_LINE INDENT Len = len ( pattern ) NEW_LINE hash = encodeString ( pattern ) NEW_LINE for word in dict : NEW_LINE INDENT if ( len ( word ) == Len and encodeString ( word ) == hash ) : NEW_LINE INDENT print ( word , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT dict = [ \" abb \" , \" abc \" , \" xyz \" , \" xyy \" ] NEW_LINE pattern = \" foo \" NEW_LINE findMatchedWords ( dict , pattern ) NEW_LINE"} {"text":"Find all strings that match specific pattern in a dictionary | Python3 program to print all the strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary ; Function to print all the strings that match the given pattern where every character in the pattern is uniquely mapped to a character in the dictionary ; len is length of the pattern ; For each word in the dictionary ; Driver code","code":"def check ( pattern , word ) : NEW_LINE INDENT if ( len ( pattern ) != len ( word ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT ch = [ 0 for i in range ( 128 ) ] NEW_LINE Len = len ( word ) NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( ch [ ord ( pattern [ i ] ) ] == 0 ) : NEW_LINE INDENT ch [ ord ( pattern [ i ] ) ] = word [ i ] NEW_LINE DEDENT elif ( ch [ ord ( pattern [ i ] ) ] != word [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findMatchedWords ( Dict , pattern ) : NEW_LINE INDENT Len = len ( pattern ) NEW_LINE for word in range ( len ( Dict ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( check ( pattern , Dict [ word ] ) ) : NEW_LINE INDENT print ( Dict [ word ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT Dict = [ \" abb \" , \" abc \" , \" xyz \" , \" xyy \" ] NEW_LINE pattern = \" foo \" NEW_LINE findMatchedWords ( Dict , pattern ) NEW_LINE"} {"text":"Count words in a given string | Function to count total number of words in the string ; Check if the string is null or empty then return zero ; Converting the given string into a character array ; Check if the character is a letter and index of character array doesn 't equal to end of line that means, it is a word and set isWord by true ; Check if the character is not a letter that means there is a space , then we increment the wordCount by one and set the isWord by false ; Check for the last word of the sentence and increment the wordCount by one ; Return the total number of words in the string ; Given String str ; Print the result","code":"def countWords ( Str ) : NEW_LINE INDENT if ( Str == None or len ( Str ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT wordCount = 0 NEW_LINE isWord = False NEW_LINE endOfLine = len ( Str ) - 1 NEW_LINE ch = list ( Str ) NEW_LINE for i in range ( len ( ch ) ) : NEW_LINE INDENT if ( ch [ i ] . isalpha ( ) and i != endOfLine ) : NEW_LINE INDENT isWord = True NEW_LINE DEDENT elif ( not ch [ i ] . isalpha ( ) and isWord ) : NEW_LINE INDENT wordCount += 1 NEW_LINE isWord = False NEW_LINE DEDENT elif ( ch [ i ] . isalpha ( ) and i == endOfLine ) : NEW_LINE INDENT wordCount += 1 NEW_LINE DEDENT DEDENT return wordCount NEW_LINE DEDENT Str = \" One two three NEW_LINE INDENT four five \" NEW_LINE DEDENT print ( \" No \u2581 of \u2581 words \u2581 : \" , countWords ( Str ) ) NEW_LINE"} {"text":"Reverse words in a given string | Reverse the string ; Check if number of words is even ; Find the middle word ; Starting from the middle start swapping words at jth position and l - 1 - j position ; Check if number of words is odd ; Find the middle word ; Starting from the middle start swapping the words at jth position and l - 1 - j position ; return the reversed sentence ; Driver Code","code":"def RevString ( s , l ) : NEW_LINE INDENT if l % 2 == 0 : NEW_LINE INDENT j = int ( l \/ 2 ) NEW_LINE while ( j <= l - 1 ) : NEW_LINE s [ j ] , s [ l - j - 1 ] = s [ l - j - 1 ] , s [ j ] NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j = int ( l \/ 2 + 1 ) NEW_LINE while ( j <= l - 1 ) : NEW_LINE s [ j ] , s [ l - 1 - j ] = s [ l - j - 1 ] , s [ j ] NEW_LINE j += 1 NEW_LINE return s ; NEW_LINE DEDENT DEDENT s = ' getting \u2581 good \u2581 at \u2581 coding \u2581 needs \u2581 a \u2581 lot \u2581 of \u2581 practice ' NEW_LINE string = s . split ( ' \u2581 ' ) NEW_LINE string = RevString ( string , len ( string ) ) NEW_LINE print ( \" \u2581 \" . join ( string ) ) NEW_LINE"} {"text":"Print path from root to all nodes in a Complete Binary Tree | Function to print path of all the nodes nth node represent as given node kth node represents as left and right node ; base condition if kth node value is greater then nth node then its means kth node is not valid so we not store it into the res simply we just return ; Storing node into res ; Print the path from root to node ; store left path of a tree So for left we will go node ( kThNode * 2 ) ; right path of a tree and for right we will go node ( kThNode * 2 + 1 ) ; Function to print path from root to all of the nodes ; res is for store the path from root to particulate node ; Print path from root to all node . third argument 1 because of we have to consider root node is 1 ; Driver Code ; Given Node ; Print path from root to all node .","code":"def printPath ( res , nThNode , kThNode ) : NEW_LINE INDENT if kThNode > nThNode : NEW_LINE INDENT return NEW_LINE DEDENT res . append ( kThNode ) NEW_LINE for i in range ( 0 , len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT print ( ) NEW_LINE printPath ( res [ : ] , nThNode , kThNode * 2 ) NEW_LINE printPath ( res [ : ] , nThNode , kThNode * 2 + 1 ) NEW_LINE DEDENT def printPathToCoverAllNodeUtil ( nThNode ) : NEW_LINE INDENT res = [ ] NEW_LINE printPath ( res , nThNode , 1 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT nThNode = 7 NEW_LINE printPathToCoverAllNodeUtil ( nThNode ) NEW_LINE DEDENT"} {"text":"Array Range Queries to find the Maximum Armstrong number with updates | Python code to implement above approach ; A utility function to get the middle index of given range . ; Function that return true if num is armstrong else return false ; A recursive function to get the sum of values in the given range of the array . The following are parameters for this function . st -> Pointer to segment tree node -> Index of current node in the segment tree . ss & se -> Starting and ending indexes of the segment represented by current node , i . e . , st [ node ] l & r -> Starting and ending indexes of range query ; If segment of this node is completely part of given range , then return the max of segment . ; If segment of this node does not belong to given range ; If segment of this node is partially the part of given range ; A recursive function to update the nodes which have the given the index in their range . The following are parameters st , ss and se are same as defined above index -> index of the element to be updated . ; update value in array and in segment tree ; Return max of elements in range from index l ( query start ) to r ( query end ) . ; Check for erroneous input values ; A recursive function that constructs Segment Tree for array [ ss . . se ] . si is index of current node in segment tree st ; If there is one element in array , store it in current node of segment tree and return ; If there are more than one elements , then recur for left and right subtrees and store the max of values in this node ; Function to construct a segment tree from given array . This function allocates memory for segment tree . ; Height of segment tree ; Maximum size of segment tree ; Allocate memory ; Fill the allocated memory st ; Return the constructed segment tree ; Driver code ; Build segment tree from given array ; Print max of values in array from index 1 to 3 ; Update : set arr [ 1 ] = 153 and update corresponding segment tree nodes . ; Find max after the value is updated","code":"import math NEW_LINE def getMid ( s : int , e : int ) -> int : NEW_LINE INDENT return s + ( e - s ) \/\/ 2 NEW_LINE DEDENT def isArmstrong ( x : int ) -> bool : NEW_LINE INDENT n = len ( str ( x ) ) NEW_LINE sum1 = 0 NEW_LINE temp = x NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT digit = temp % 10 NEW_LINE sum1 += pow ( digit , n ) NEW_LINE temp \/\/= 10 NEW_LINE DEDENT if ( sum1 == x ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def MaxUtil ( st , ss , se , l , r , node ) : NEW_LINE INDENT if ( l <= ss and r >= se ) : NEW_LINE INDENT return st [ node ] NEW_LINE DEDENT if ( se < l or ss > r ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE return max ( MaxUtil ( st , ss , mid , l , r , 2 * node + 1 ) , MaxUtil ( st , mid + 1 , se , l , r , 2 * node + 2 ) ) NEW_LINE DEDENT def updateValue ( arr , st , ss , se , index , value , node ) : NEW_LINE INDENT if ( index < ss or index > se ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return NEW_LINE DEDENT if ( ss == se ) : NEW_LINE INDENT arr [ index ] = value NEW_LINE if ( isArmstrong ( value ) ) : NEW_LINE INDENT st [ node ] = value NEW_LINE DEDENT else : NEW_LINE INDENT st [ node ] = - 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT mid = getMid ( ss , se ) NEW_LINE if ( index >= ss and index <= mid ) : NEW_LINE INDENT updateValue ( arr , st , ss , mid , index , value , 2 * node + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT updateValue ( arr , st , mid + 1 , se , index , value , 2 * node + 2 ) NEW_LINE DEDENT st [ node ] = max ( st [ 2 * node + 1 ] , st [ 2 * node + 2 ] ) NEW_LINE DEDENT return NEW_LINE DEDENT def getMax ( st , n , l , r ) : NEW_LINE INDENT if ( l < 0 or r > n - 1 or l > r ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) NEW_LINE return - 1 NEW_LINE DEDENT return MaxUtil ( st , 0 , n - 1 , l , r , 0 ) NEW_LINE DEDENT def constructSTUtil ( arr , ss , se , st , si ) : NEW_LINE INDENT if ( ss == se ) : NEW_LINE INDENT if ( isArmstrong ( arr [ ss ] ) ) : NEW_LINE INDENT st [ si ] = arr [ ss ] NEW_LINE DEDENT else : NEW_LINE INDENT st [ si ] = - 1 NEW_LINE DEDENT return st [ si ] NEW_LINE DEDENT mid = getMid ( ss , se ) NEW_LINE st [ si ] = max ( constructSTUtil ( arr , ss , mid , st , si * 2 + 1 ) , constructSTUtil ( arr , mid + 1 , se , st , si * 2 + 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 ( math . pow ( 2 , x ) ) - 1 NEW_LINE st = [ 0 for _ in range ( max_size ) ] NEW_LINE constructSTUtil ( arr , 0 , n - 1 , st , 0 ) NEW_LINE return st NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 192 , 113 , 535 , 7 , 19 , 111 ] NEW_LINE n = len ( arr ) NEW_LINE st = constructST ( arr , n ) NEW_LINE print ( \" Maximum \u2581 armstrong \u2581 number \u2581 in \u2581 given \u2581 range \u2581 = \u2581 { } \" . format ( getMax ( st , n , 1 , 3 ) ) ) NEW_LINE updateValue ( arr , st , 0 , n - 1 , 1 , 153 , 0 ) NEW_LINE print ( \" Updated \u2581 Maximum \u2581 armstrong \u2581 number \u2581 in \u2581 given \u2581 range \u2581 = \u2581 { } \" . format ( getMax ( st , n , 1 , 3 ) ) ) NEW_LINE DEDENT"} {"text":"Maximum number of region in which N non | Function to find the maximum number of regions on a plane ; print the maximum number of regions ; Driver code","code":"def maxRegions ( n ) : NEW_LINE INDENT num = n * ( n + 1 ) \/\/ 2 + 1 NEW_LINE print ( num ) NEW_LINE DEDENT n = 10 NEW_LINE maxRegions ( n ) NEW_LINE"} {"text":"Check whether jigsaw puzzle solveable or not | Function to check if the jigsaw Puzzle is solveable or not ; Base Case ; By placing the blank tabs as a chain ; Driver Code","code":"def checkSolveable ( n , m ) : NEW_LINE INDENT if n == 1 or m == 1 : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT elif m == 2 and n == 2 : 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 = 1 NEW_LINE m = 3 NEW_LINE checkSolveable ( n , m ) NEW_LINE DEDENT"} {"text":"Check if it is possible to reach ( X , Y ) from ( 1 , 0 ) by given steps | Function to find the GCD of two numbers a and b ; Base Case ; Recursively find the GCD ; Function to check if ( x , y ) can be reached from ( 1 , 0 ) from given moves ; If GCD is 1 , then pr \" Yes \" ; Driver Code ; Given X and Y ; Function call","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 check ( x , y ) : NEW_LINE INDENT if ( GCD ( x , y ) == 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 X = 2 NEW_LINE Y = 7 NEW_LINE check ( X , Y ) NEW_LINE DEDENT"} {"text":"Probability of Euler 's Totient Function in a range [L, R] to be divisible by M | Python3 program to implement the above approach ; Seieve of Erotosthenes to compute all primes ; If prime ; Mark all its multiples as non - prime ; Function to find the probability of Euler 's Totient Function in a given range ; Initializing two arrays with values from L to R for Euler 's totient ; Indexing from 0 ; If the current number is prime ; Checking if i is prime factor of numbers in range L to R ; Update all the numbers which has prime factor i ; If number in range has a prime factor > Math . sqrt ( number ) ; Count those which are divisible by M ; Return the result ; Driver code","code":"size = 1000001 NEW_LINE def seiveOfEratosthenes ( prime ) : NEW_LINE INDENT prime [ 0 ] = 1 NEW_LINE prime [ 1 ] = 0 NEW_LINE i = 2 NEW_LINE while ( i * i < 1000001 ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT j = i * i NEW_LINE while ( j < 1000001 ) : NEW_LINE INDENT prime [ j ] = 1 NEW_LINE j = j + i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def probabiltyEuler ( prime , L , R , M ) : NEW_LINE INDENT arr = [ 0 ] * size NEW_LINE eulerTotient = [ 0 ] * size NEW_LINE count = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT eulerTotient [ i - L ] = i NEW_LINE arr [ i - L ] = i NEW_LINE DEDENT for i in range ( 2 , 1000001 ) : NEW_LINE INDENT if ( prime [ i ] == 0 ) : NEW_LINE INDENT for j in range ( ( L \/\/ i ) * i , R + 1 , i ) : NEW_LINE INDENT if ( j - L >= 0 ) : NEW_LINE INDENT eulerTotient [ j - L ] = ( eulerTotient [ j - L ] \/\/ i * ( i - 1 ) ) NEW_LINE while ( arr [ j - L ] % i == 0 ) : NEW_LINE INDENT arr [ j - L ] = arr [ j - L ] \/\/ i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( arr [ i - L ] > 1 ) : NEW_LINE INDENT eulerTotient [ i - L ] = ( ( eulerTotient [ i - L ] \/\/ arr [ i - L ] ) * ( arr [ i - L ] - 1 ) ) NEW_LINE DEDENT DEDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( ( eulerTotient [ i - L ] % M ) == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return ( float ) ( 1.0 * count \/ ( R + 1 - L ) ) NEW_LINE DEDENT prime = [ 0 ] * size NEW_LINE seiveOfEratosthenes ( prime ) NEW_LINE L , R , M = 1 , 7 , 3 NEW_LINE print ( probabiltyEuler ( prime , L , R , M ) ) NEW_LINE"} {"text":"Largest odd divisor Game to check which player wins | Python3 implementation to find the Largest Odd Divisor Game to check which player wins ; Function to find the Largest Odd Divisor Game to check which player wins ; Check if n == 1 then player 2 will win ; Check if n == 2 or n is odd ; While n is greater than k and divisible by 2 keep incrementing tha val ; Loop to find greatest odd divisor ; Check if n is a power of 2 ; Check if cnt is not one then player 1 wins ; Driver code","code":"import math NEW_LINE def findWinner ( n , k ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT elif ( ( n & 1 ) or n == 2 ) : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT tmp = n ; NEW_LINE val = 1 ; NEW_LINE while ( tmp > k and tmp % 2 == 0 ) : NEW_LINE INDENT tmp \/\/= 2 ; NEW_LINE val *= 2 ; NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( tmp ) ) + 1 ) : NEW_LINE INDENT while ( tmp % i == 0 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE tmp \/\/= i ; NEW_LINE DEDENT DEDENT if ( tmp > 1 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT if ( val == n ) : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT elif ( n \/ tmp == 2 and cnt == 1 ) : NEW_LINE INDENT print ( \" No \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Yes \" ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 1 ; k = 1 ; NEW_LINE findWinner ( n , k ) ; NEW_LINE DEDENT"} {"text":"Find all numbers up to N which are both Pentagonal and Hexagonal | Python3 program of the above approach ; Function to print numbers upto N which are both pentagonal as well as hexagonal numbers ; Calculate i - th pentagonal number ; Check if the pentagonal number pn is hexagonal or not ; Driver Code","code":"import math NEW_LINE def pen_hex ( n ) : NEW_LINE INDENT pn = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pn = ( int ) ( i * ( 3 * i - 1 ) \/ 2 ) NEW_LINE if ( pn > n ) : NEW_LINE INDENT break NEW_LINE DEDENT seqNum = ( 1 + math . sqrt ( 8 * pn + 1 ) ) \/ 4 NEW_LINE if ( seqNum == ( int ) ( seqNum ) ) : NEW_LINE INDENT print ( pn , end = \" , \u2581 \" ) NEW_LINE DEDENT DEDENT DEDENT N = 1000000 NEW_LINE pen_hex ( N ) NEW_LINE"} {"text":"Check if row | Function to check if row - major order traversal of the matrix is is palindrome ; Loop to check if the matrix is matrix is palindrome or not ; Driver Code","code":"def isPal ( a , n , m ) : NEW_LINE INDENT for i in range ( 0 , n \/\/ 2 ) : NEW_LINE INDENT for j in range ( 0 , m - 1 ) : NEW_LINE INDENT if ( a [ i ] [ j ] != a [ n - 1 - i ] [ m - 1 - j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 ; NEW_LINE m = 3 ; NEW_LINE a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 4 ] , [ 3 , 2 , 1 ] ] ; NEW_LINE if ( isPal ( a , n , m ) ) : NEW_LINE INDENT print ( \" YES \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) ; NEW_LINE DEDENT DEDENT"} {"text":"Find the smallest number whose sum of digits is N | Function to get sum of digits ; Function to find the smallest number whose sum of digits is also N ; Checking if number has sum of digits = N ; Driver code","code":"def getSum ( n ) : NEW_LINE INDENT sum1 = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT sum1 = sum1 + n % 10 ; NEW_LINE n = n \/\/ 10 ; NEW_LINE DEDENT return sum1 ; NEW_LINE DEDENT def smallestNumber ( N ) : NEW_LINE INDENT i = 1 ; NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( getSum ( i ) == N ) : NEW_LINE INDENT print ( i ) ; NEW_LINE break ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT N = 10 ; NEW_LINE smallestNumber ( N ) ; NEW_LINE"} {"text":"Rare Numbers | Python3 implementation to check if N is a Rare number ; Iterative function to reverse digits of num ; Function to check if N is perfect square ; Find floating point value of square root of x . ; If square root is an integer ; Function to check if N is an Rare number ; Find reverse of N ; Number should be non - palindromic ; Driver Code","code":"import math NEW_LINE def reversDigits ( num ) : NEW_LINE INDENT rev_num = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 NEW_LINE num = num \/\/ 10 NEW_LINE DEDENT return rev_num NEW_LINE DEDENT def isPerfectSquare ( x ) : NEW_LINE INDENT sr = math . sqrt ( x ) NEW_LINE return ( ( sr - int ( sr ) ) == 0 ) NEW_LINE DEDENT def isRare ( N ) : NEW_LINE INDENT reverseN = reversDigits ( N ) NEW_LINE if ( reverseN == N ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( isPerfectSquare ( N + reverseN ) and isPerfectSquare ( N - reverseN ) ) NEW_LINE DEDENT N = 65 NEW_LINE if ( isRare ( N ) ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT"} {"text":"Count numbers from range whose prime factors are only 2 and 3 using Arrays | Set 2 | Function which will calculate the elements in the given range ; Store the current power of 2 ; Store the current power of 3 ; power23 [ ] will store pairwise product of elements of power2 and power3 that are <= r ; Insert in power23 ] [ ] only if mul <= r ; Store the required answer ; Print the result ; Driver code","code":"def calc_ans ( l , r ) : NEW_LINE INDENT power2 = [ ] ; power3 = [ ] ; NEW_LINE mul2 = 1 ; NEW_LINE while ( mul2 <= r ) : NEW_LINE INDENT power2 . append ( mul2 ) ; NEW_LINE mul2 *= 2 ; NEW_LINE DEDENT mul3 = 1 ; NEW_LINE while ( mul3 <= r ) : NEW_LINE INDENT power3 . append ( mul3 ) ; NEW_LINE mul3 *= 3 ; NEW_LINE DEDENT power23 = [ ] ; NEW_LINE for x in range ( len ( power2 ) ) : NEW_LINE INDENT for y in range ( len ( power3 ) ) : NEW_LINE INDENT mul = power2 [ x ] * power3 [ y ] ; NEW_LINE if ( mul == 1 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( mul <= r ) : NEW_LINE INDENT power23 . append ( mul ) ; NEW_LINE DEDENT DEDENT DEDENT ans = 0 ; NEW_LINE for x in power23 : NEW_LINE INDENT if ( x >= l and x <= r ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT print ( ans ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT l = 1 ; r = 10 ; NEW_LINE calc_ans ( l , r ) ; NEW_LINE DEDENT"} {"text":"Count of K length subsequence whose product is even | Function to calculate nCr ; Returns factorial of n ; Function for finding number of K length subsequences whose product is even number ; Counting odd numbers in the array ; Driver code","code":"def nCr ( n , r ) : NEW_LINE INDENT if ( r > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return fact ( n ) \/\/ ( fact ( r ) * fact ( n - r ) ) NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def countSubsequences ( arr , n , k ) : NEW_LINE INDENT countOdd = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT countOdd += 1 ; NEW_LINE DEDENT DEDENT ans = nCr ( n , k ) - nCr ( countOdd , k ) ; NEW_LINE return ans NEW_LINE DEDENT arr = [ 2 , 4 ] NEW_LINE K = 1 NEW_LINE N = len ( arr ) NEW_LINE print ( countSubsequences ( arr , N , K ) ) NEW_LINE"} {"text":"Find most significant bit of a number X in base Y | Python3 program to find the first digit of X in base Y ; Function to find the first digit of X in base Y ; Calculating number of digits of x in base y ; Finding first digit of x in base y ; Driver code","code":"import math NEW_LINE def first_digit ( x , y ) : NEW_LINE INDENT length = int ( math . log ( x ) \/ math . log ( y ) + 1 ) NEW_LINE first_digit = x \/ math . pow ( y , length - 1 ) NEW_LINE print ( int ( first_digit ) ) NEW_LINE DEDENT X = 55 NEW_LINE Y = 3 NEW_LINE first_digit ( X , Y ) NEW_LINE"} {"text":"Curzon Numbers | Function to check if a number is a Curzon number or not ; Find 2 ^ N + 1 ; Find 2 * N + 1 ; Check for divisibility ; Driver code","code":"def checkIfCurzonNumber ( N ) : NEW_LINE INDENT powerTerm , productTerm = 0 , 0 NEW_LINE powerTerm = pow ( 2 , N ) + 1 NEW_LINE productTerm = 2 * N + 1 NEW_LINE if ( powerTerm % productTerm == 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 checkIfCurzonNumber ( N ) NEW_LINE N = 10 NEW_LINE checkIfCurzonNumber ( N ) NEW_LINE DEDENT"} {"text":"Minimum count of numbers required ending with 7 to sum as a given number | Function to return the count of minimum numbers ending with 7 required such that the sum of these numbers is n ; hasharr [ i ] will store the minimum numbers ending with 7 so that it sums to number ending with digit i ; Its always possible to write numbers > 69 to write as numbers ending with 7 ; If the number is atleast equal to the sum of minimum numbers ending with 7 ; Driver code","code":"def minCount ( n ) : NEW_LINE INDENT hasharr = [ 10 , 3 , 6 , 9 , 2 , 5 , 8 , 1 , 4 , 7 ] NEW_LINE if ( n > 69 ) : NEW_LINE INDENT return hasharr [ n % 10 ] NEW_LINE DEDENT else : NEW_LINE INDENT if ( n >= hasharr [ n % 10 ] * 7 ) : NEW_LINE INDENT return hasharr [ n % 10 ] NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT n = 38 ; NEW_LINE print ( minCount ( n ) ) NEW_LINE"} {"text":"Program to print modified Binary triangle pattern | Function to print the modified binary pattern ; Loop to traverse the rows ; Loop to traverse the numbers in each row ; Check if j is 1 or i In either case print 1 ; Else print 0 ; Change the cursor to next line after each row ; Driver Code ; Function Call","code":"def modifiedBinaryPattern ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 , 1 ) : NEW_LINE INDENT if ( j == 1 or j == i ) : NEW_LINE INDENT print ( 1 , end = \" \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 , end = \" \" ) NEW_LINE DEDENT DEDENT print ( ' ' , end = \" \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE modifiedBinaryPattern ( n ) NEW_LINE DEDENT"} {"text":"Find the real and imaginary part of a Complex number | Function to find real and imaginary parts of a complex number ; string length stored in variable l ; variable for the index of the separator ; Storing the index of '+ ; else storing the index of '- ; Finding the real part of the complex number ; Finding the imaginary part of the complex number ; Driver code","code":"def findRealAndImag ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE i = 0 NEW_LINE DEDENT ' NEW_LINE INDENT if ( s . find ( ' + ' ) != - 1 ) : NEW_LINE INDENT i = s . find ( ' + ' ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT i = s . find ( ' - ' ) ; NEW_LINE DEDENT real = s [ : i ] NEW_LINE imaginary = s [ i + 1 : l - 1 ] NEW_LINE print ( \" Real \u2581 part : \" , real ) NEW_LINE print ( \" Imaginary \u2581 part : \" , imaginary ) NEW_LINE DEDENT s = \"3 + 4i \" ; NEW_LINE findRealAndImag ( s ) ; NEW_LINE"} {"text":"Distinct powers of a number N such that the sum is equal to K | Python 3 implementation to find distinct powers of N that add up to K ; Function to return the highest power of N not exceeding K ; Loop to find the highest power less than K ; Initializing the PowerArray with all 0 's. ; Function to print the distinct powers of N that add upto K ; Getting the highest power of n before k ; To check if the power is being used twice or not ; Print - 1 if power is being used twice ; If the power is not visited , then mark the power as visited ; Decrementing the value of K ; Printing the powers of N that sum up to K ; Driver code","code":"from math import pow NEW_LINE def highestPower ( n , k ) : NEW_LINE INDENT i = 0 NEW_LINE a = pow ( n , i ) NEW_LINE while ( a <= k ) : NEW_LINE INDENT i += 1 NEW_LINE a = pow ( n , i ) NEW_LINE DEDENT return i - 1 NEW_LINE DEDENT b = [ 0 for i in range ( 50 ) ] NEW_LINE def PowerArray ( n , k ) : NEW_LINE INDENT while ( k ) : NEW_LINE INDENT t = highestPower ( n , k ) NEW_LINE if ( b [ t ] ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return 0 NEW_LINE DEDENT else : NEW_LINE INDENT b [ t ] = 1 NEW_LINE DEDENT k -= pow ( n , t ) NEW_LINE DEDENT for i in range ( 50 ) : NEW_LINE INDENT if ( b [ i ] ) : NEW_LINE INDENT print ( i , end = ' , \u2581 ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE K = 40 NEW_LINE PowerArray ( N , K ) NEW_LINE DEDENT"} {"text":"Sum of elements in an array having composite frequency | Python3 program to find sum of elements in an array having composite frequency ; Function to create Sieve to check primes ; If composite [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to composite ; Function to return the sum of elements in an array having composite frequency ; Map is used to store element frequencies ; To store sum ; Traverse the map using iterators ; Count the number of elements having composite frequencies ; Driver code ; Function call","code":"N = 100005 NEW_LINE def SieveOfEratosthenes ( composite ) : NEW_LINE INDENT for p in range ( 2 , N ) : NEW_LINE INDENT if p * p > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( composite [ p ] == False ) : NEW_LINE INDENT for i in range ( 2 * p , N , p ) : NEW_LINE INDENT composite [ i ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT def sumOfElements ( arr , n ) : NEW_LINE INDENT composite = [ False ] * N NEW_LINE SieveOfEratosthenes ( composite ) NEW_LINE m = dict ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT sum = 0 NEW_LINE for it in m : NEW_LINE INDENT if ( composite [ m [ it ] ] ) : NEW_LINE INDENT sum += ( it ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 1 , 1 , 3 , 3 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumOfElements ( arr , n ) ) NEW_LINE DEDENT"} {"text":"Delete all odd frequency elements from an Array | Function that removes the elements which have odd frequencies in the array ; Create a map to store the frequency of each element ; Remove the elements which have odd frequencies ; If the element has odd frequency then skip ; Driver code ; Function call","code":"def remove ( arr , n ) : NEW_LINE INDENT m = dict . fromkeys ( arr , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ( m [ arr [ i ] ] & 1 ) ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT print ( arr [ i ] , end = \" , \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 3 , 3 , 3 , 2 , 2 , 4 , 7 , 7 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE remove ( arr , n ) ; NEW_LINE DEDENT"} {"text":"Maximize the first element of the array such that average remains constant | Maximum value of the first array element that can be attained ; Variable to store the sum ; Loop to find the sum of array ; Desired maximum value ; Driver Code","code":"def getmax ( arr , n , x ) : NEW_LINE INDENT s = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = s + arr [ i ] NEW_LINE DEDENT print ( min ( s , x ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE x = 5 NEW_LINE arr_size = len ( arr ) NEW_LINE getmax ( arr , arr_size , x ) NEW_LINE DEDENT"} {"text":"Minimum length of the shortest path of a triangle | function to get the minimum length of the shorter side of the triangle ; traversing through each points on the plane ; if sum of a points is greater than the previous one , the maximum gets replaced ; print the length ; Driver code ; initialize the number of points ; points on the plane","code":"def shortestLength ( n , x , y ) : NEW_LINE INDENT answer = 0 NEW_LINE i = 0 NEW_LINE while n > 0 : NEW_LINE INDENT if ( x [ i ] + y [ i ] > answer ) : NEW_LINE INDENT answer = x [ i ] + y [ i ] NEW_LINE DEDENT i += 1 NEW_LINE n -= 1 NEW_LINE DEDENT print ( \" Length \u2581 - > \u2581 \" + str ( answer ) ) NEW_LINE print ( \" Path \u2581 - > \u2581 \" + \" ( \u2581 1 , \u2581 \" + str ( answer ) + \" \u2581 ) \" + \" and \u2581 ( \u2581 \" + str ( answer ) + \" , \u2581 1 \u2581 ) \" ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 4 NEW_LINE x = [ 1 , 4 , 2 , 1 ] NEW_LINE y = [ 4 , 1 , 1 , 2 ] NEW_LINE shortestLength ( n , x , y ) NEW_LINE DEDENT"} {"text":"Intersecting rectangle when bottom | function to find intersection rectangle of given two rectangles . ; gives bottom - left point of intersection rectangle ; gives top - right point of intersection rectangle ; no intersection ; gives top - left point of intersection rectangle ; gives bottom - right point of intersection rectangle ; Driver code ; bottom - left and top - right corners of first rectangle ; bottom - left and top - right corners of first rectangle ; function call","code":"def FindPoints ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) : NEW_LINE INDENT x5 = max ( x1 , x3 ) NEW_LINE y5 = max ( y1 , y3 ) NEW_LINE x6 = min ( x2 , x4 ) NEW_LINE y6 = min ( y2 , y4 ) NEW_LINE if ( x5 > x6 or y5 > y6 ) : NEW_LINE INDENT print ( \" No \u2581 intersection \" ) NEW_LINE return NEW_LINE DEDENT print ( \" ( \" , x5 , \" , \u2581 \" , y5 , \" ) \u2581 \" , end = \" \u2581 \" ) NEW_LINE print ( \" ( \" , x6 , \" , \u2581 \" , y6 , \" ) \u2581 \" , end = \" \u2581 \" ) NEW_LINE x7 = x5 NEW_LINE y7 = y6 NEW_LINE print ( \" ( \" , x7 , \" , \u2581 \" , y7 , \" ) \u2581 \" , end = \" \u2581 \" ) NEW_LINE x8 = x6 NEW_LINE y8 = y5 NEW_LINE print ( \" ( \" , x8 , \" , \u2581 \" , y8 , \" ) \u2581 \" ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x1 = 0 NEW_LINE y1 = 0 NEW_LINE x2 = 10 NEW_LINE y2 = 8 NEW_LINE x3 = 2 NEW_LINE y3 = 3 NEW_LINE x4 = 7 NEW_LINE y4 = 9 NEW_LINE FindPoints ( x1 , y1 , x2 , y2 , x3 , y3 , x4 , y4 ) NEW_LINE DEDENT"} {"text":"Find Corners of Rectangle using mid points | Python3 program to find corner points of a rectangle using given length and middle points . ; Structure to represent a co - ordinate point ; This function receives two points and length of the side of rectangle and prints the 4 corner points of the rectangle ; Horizontal rectangle ; Vertical rectangle ; Slanted rectangle ; Calculate slope of the side ; Calculate displacements along axes ; Driver code","code":"import math NEW_LINE class Point : NEW_LINE INDENT def __init__ ( self , a = 0 , b = 0 ) : NEW_LINE INDENT self . x = a NEW_LINE self . y = b NEW_LINE DEDENT DEDENT def printCorners ( p , q , l ) : NEW_LINE INDENT a , b , c , d = Point ( ) , Point ( ) , Point ( ) , Point ( ) NEW_LINE if ( p . x == q . x ) : NEW_LINE INDENT a . x = p . x - ( l \/ 2.0 ) NEW_LINE a . y = p . y NEW_LINE d . x = p . x + ( l \/ 2.0 ) NEW_LINE d . y = p . y NEW_LINE b . x = q . x - ( l \/ 2.0 ) NEW_LINE b . y = q . y NEW_LINE c . x = q . x + ( l \/ 2.0 ) NEW_LINE c . y = q . y NEW_LINE DEDENT elif ( p . y == q . y ) : NEW_LINE INDENT a . y = p . y - ( l \/ 2.0 ) NEW_LINE a . x = p . x NEW_LINE d . y = p . y + ( l \/ 2.0 ) NEW_LINE d . x = p . x NEW_LINE b . y = q . y - ( l \/ 2.0 ) NEW_LINE b . x = q . x NEW_LINE c . y = q . y + ( l \/ 2.0 ) NEW_LINE c . x = q . x NEW_LINE DEDENT else : NEW_LINE INDENT m = ( p . x - q . x ) \/ ( q . y - p . y ) NEW_LINE dx = ( l \/ math . sqrt ( 1 + ( m * m ) ) ) * 0.5 NEW_LINE dy = m * dx NEW_LINE a . x = p . x - dx NEW_LINE a . y = p . y - dy NEW_LINE d . x = p . x + dx NEW_LINE d . y = p . y + dy NEW_LINE b . x = q . x - dx NEW_LINE b . y = q . y - dy NEW_LINE c . x = q . x + dx NEW_LINE c . y = q . y + dy NEW_LINE DEDENT print ( int ( a . x ) , \" , \u2581 \" , int ( a . y ) , sep = \" \" ) NEW_LINE print ( int ( b . x ) , \" , \u2581 \" , int ( b . y ) , sep = \" \" ) NEW_LINE print ( int ( c . x ) , \" , \u2581 \" , int ( c . y ) , sep = \" \" ) NEW_LINE print ( int ( d . x ) , \" , \u2581 \" , int ( d . y ) , sep = \" \" ) NEW_LINE print ( ) NEW_LINE DEDENT p1 = Point ( 1 , 0 ) NEW_LINE q1 = Point ( 1 , 2 ) NEW_LINE printCorners ( p1 , q1 , 2 ) NEW_LINE p = Point ( 1 , 1 ) NEW_LINE q = Point ( - 1 , - 1 ) NEW_LINE printCorners ( p , q , 2 * math . sqrt ( 2 ) ) NEW_LINE"} {"text":"Minimize cost to modify the Array such that even indices have even elements and vice versa | Function to find the minimum cost to modify the array according to the given criteria ; Count of wrong positioned odd and even elements ; Odd Count ; Even Count ; Swapping Cost ; Decrementing cost after swapping ; Only decrementing cost ; Return the minimum cost of the two cases ; Driver Code","code":"def minimumCost ( arr , N , X , Y ) : NEW_LINE INDENT even_count = 0 NEW_LINE odd_count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( ( arr [ i ] & 1 ) and ( i % 2 == 0 ) ) : NEW_LINE INDENT odd_count += 1 NEW_LINE DEDENT if ( ( arr [ i ] % 2 ) == 0 and ( i & 1 ) ) : NEW_LINE INDENT even_count += 1 NEW_LINE DEDENT DEDENT cost1 = X * min ( odd_count , even_count ) NEW_LINE cost2 = Y * ( max ( odd_count , even_count ) - min ( odd_count , even_count ) ) NEW_LINE cost3 = ( odd_count + even_count ) * Y NEW_LINE return min ( cost1 + cost2 , cost3 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 5 , 3 , 7 , 2 , 1 ] NEW_LINE X = 10 NEW_LINE Y = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( minimumCost ( arr , N , X , Y ) ) NEW_LINE DEDENT"} {"text":"Minimum product of maximum and minimum element over all possible subarrays | Function to find the minimum product of the minimum and maximum among all the possible subarrays ; Stores resultant minimum product ; Traverse the given array arr [ ] ; Min of product of all two pair of consecutive elements ; Return the resultant value ; Driver Code","code":"def findMinMax ( a ) : NEW_LINE INDENT min_val = 1000000000 NEW_LINE for i in range ( 1 , len ( a ) ) : NEW_LINE INDENT min_val = min ( min_val , a [ i ] * a [ i - 1 ] ) NEW_LINE DEDENT return min_val NEW_LINE DEDENT if __name__ == ( \" _ _ main _ _ \" ) : NEW_LINE INDENT arr = [ 6 , 4 , 5 , 6 , 2 , 4 , 1 ] NEW_LINE print ( findMinMax ( arr ) ) NEW_LINE DEDENT"} {"text":"Sum of all nodes with smaller values at a distance K from a given node in a BST | Structure of Tree ; A constructor to create a new node ; Function to add the node to the sum below the target node ; Base Case ; If Kth distant node is reached ; Recur for the left and the right subtrees ; Function to find the K distant nodes from target node , it returns - 1 if target node is not present in tree ; Base Case 1 ; If target is same as root . ; Recurr for the left subtree ; Tree is BST so reduce the search space ; Check if target node was found in left subtree ; If root is at distance k from the target ; Node less than target will be present in left ; When node is not present in the left subtree ; If Kth distant node is reached ; Node less than target at k distance maybe present in the left tree ; If target was not present in the left nor in right subtree ; Function to insert a node in BST ; If root is NULL ; Insert the data in right half ; Insert the data in left half ; Return the root node ; Function to find the sum of K distant nodes from the target node having value less than target node ; Stores the sum of nodes having values < target at K distance ; Print the resultant sum ; Driver Code ; Create the Tree","code":"sum = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def kDistanceDownSum ( root , k ) : NEW_LINE INDENT global sum NEW_LINE if ( root == None or k < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT sum += root . data NEW_LINE return NEW_LINE DEDENT kDistanceDownSum ( root . left , k - 1 ) NEW_LINE kDistanceDownSum ( root . right , k - 1 ) NEW_LINE DEDENT def kDistanceSum ( root , target , k ) : NEW_LINE INDENT global sum NEW_LINE if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( root . data == target ) : NEW_LINE INDENT kDistanceDownSum ( root . left , k - 1 ) NEW_LINE return 0 NEW_LINE DEDENT dl = - 1 NEW_LINE if ( target < root . data ) : NEW_LINE INDENT dl = kDistanceSum ( root . left , target , k ) NEW_LINE DEDENT if ( dl != - 1 ) : NEW_LINE INDENT if ( dl + 1 == k ) : NEW_LINE INDENT sum += root . data NEW_LINE DEDENT return - 1 NEW_LINE DEDENT dr = - 1 NEW_LINE if ( target > root . data ) : NEW_LINE INDENT dr = kDistanceSum ( root . right , target , k ) NEW_LINE DEDENT if ( dr != - 1 ) : NEW_LINE INDENT if ( dr + 1 == k ) : NEW_LINE INDENT sum += root . data NEW_LINE DEDENT else : NEW_LINE INDENT kDistanceDownSum ( root . left , k - dr - 2 ) NEW_LINE DEDENT return 1 + dr NEW_LINE DEDENT return - 1 NEW_LINE DEDENT def insertNode ( data , root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT node = Node ( data ) NEW_LINE return node NEW_LINE DEDENT elif ( data > root . data ) : NEW_LINE INDENT root . right = insertNode ( data , root . right ) NEW_LINE DEDENT elif ( data <= root . data ) : NEW_LINE INDENT root . left = insertNode ( data , root . left ) NEW_LINE DEDENT return root NEW_LINE DEDENT def findSum ( root , target , K ) : NEW_LINE INDENT kDistanceSum ( root , target , K ) NEW_LINE print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE N = 11 NEW_LINE tree = [ 3 , 1 , 7 , 0 , 2 , 5 , 10 , 4 , 6 , 9 , 8 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT root = insertNode ( tree [ i ] , root ) NEW_LINE DEDENT target = 7 NEW_LINE K = 2 NEW_LINE findSum ( root , target , K ) NEW_LINE DEDENT"} {"text":"Find Nth item distributed from infinite items of infinite types based on given conditions | Function to find the type of the item given out according to the given rules ; Stores the count of item given out at each step ; Iterate over the days from 1 ; Iterate over type of item on that day ; Count of items given out should exceed n ; Driver Code","code":"def itemType ( n ) : NEW_LINE INDENT count = 0 NEW_LINE day = 1 NEW_LINE while ( True ) : NEW_LINE INDENT for type in range ( day , 0 , - 1 ) : NEW_LINE INDENT count += type NEW_LINE if ( count >= n ) : NEW_LINE INDENT return type NEW_LINE DEDENT DEDENT DEDENT DEDENT N = 10 NEW_LINE print ( itemType ( N ) ) NEW_LINE"} {"text":"Find the sum of all array elements that are equidistant from two consecutive powers of 2 | Python3 program for the above approach ; Function to prthe sum of array elements that are equidistant from two consecutive powers of 2 ; Stores the resultant sum of the array elements ; Traverse the array arr [ ] ; Stores the power of 2 of the number arr [ i ] ; Stores the number which is power of 2 and lesser than or equal to arr [ i ] ; Stores the number which is power of 2 and greater than or equal to arr [ i ] ; If arr [ i ] - LesserValue is the same as LargerValue - arr [ i ] ; Increment res by arr [ i ] ; Return the resultant sum res ; Driver Code","code":"from math import log2 NEW_LINE def FindSum ( arr , N ) : NEW_LINE INDENT res = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT power = int ( log2 ( arr [ i ] ) ) NEW_LINE LesserValue = pow ( 2 , power ) NEW_LINE LargerValue = pow ( 2 , power + 1 ) NEW_LINE if ( ( arr [ i ] - LesserValue ) == ( LargerValue - arr [ i ] ) ) : NEW_LINE INDENT res += arr [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 24 , 17 , 3 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( FindSum ( arr , N ) ) NEW_LINE DEDENT"} {"text":"Find the person who will finish last | Function to find the person who will finish last ; To keep track of rows and columns having 1 ; Available rows and columns ; Minimum number of choices we have ; If number of choices are odd ; P1 will finish last ; Otherwise , P2 will finish last ; Given matrix","code":"def findLast ( mat ) : NEW_LINE INDENT m = len ( mat ) NEW_LINE n = len ( mat [ 0 ] ) NEW_LINE rows = set ( ) NEW_LINE cols = set ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if mat [ i ] [ j ] : NEW_LINE INDENT rows . add ( i ) NEW_LINE cols . add ( j ) NEW_LINE DEDENT DEDENT DEDENT avRows = m - len ( list ( rows ) ) NEW_LINE avCols = n - len ( list ( cols ) ) NEW_LINE choices = min ( avRows , avCols ) NEW_LINE if choices & 1 : NEW_LINE INDENT print ( ' P1' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' P2' ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 0 , 0 ] , [ 0 , 0 , 0 ] , [ 0 , 0 , 1 ] ] NEW_LINE findLast ( mat ) NEW_LINE"} {"text":"Sum of decimals that are binary representations of first N natural numbers | Python3 program for the above approach ; Function to find the sum of first N natural numbers represented in binary representation ; Stores the resultant sum ; Iterate until the value of N is greater than 0 ; If N is less than 2 ; Store the MSB position of N ; Iterate in the range [ 1 , x ] and add the contribution of the numbers from 1 to ( 2 ^ x - 1 ) ; Update the value of the cur and add ; Add the cur to ans ; Store the remaining numbers ; Add the contribution by MSB by the remaining numbers ; The next iteration will be repeated for 2 ^ x - 1 ; Print the result ; Driver Code","code":"from math import log2 , pow NEW_LINE MOD = 1000000007 NEW_LINE def sumOfBinaryNumbers ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE one = 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT ans = ( ans + n ) % MOD NEW_LINE break NEW_LINE DEDENT x = int ( log2 ( n ) ) NEW_LINE cur = 0 NEW_LINE add = ( one << ( x - 1 ) ) NEW_LINE for i in range ( 1 , x + 1 , 1 ) : NEW_LINE INDENT cur = ( cur + add ) % MOD NEW_LINE add = ( add * 10 % MOD ) NEW_LINE DEDENT ans = ( ans + cur ) % MOD NEW_LINE rem = n - ( one << x ) + 1 NEW_LINE p = pow ( 10 , x ) NEW_LINE p = ( p * ( rem % MOD ) ) % MOD NEW_LINE ans = ( ans + p ) % MOD NEW_LINE n = rem - 1 NEW_LINE DEDENT print ( int ( ans ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE sumOfBinaryNumbers ( N ) NEW_LINE DEDENT"} {"text":"Nearest Fibonacci Number to N | Function to find the Fibonacci number which is nearest to N ; Base Case ; Initialize the first & second terms of the Fibonacci series ; Store the third term ; Iterate until the third term is less than or equal to num ; Update the first ; Update the second ; Update the third ; Store the Fibonacci number having smaller difference with N ; Print the result ; Driver Code","code":"def nearestFibonacci ( num ) : NEW_LINE INDENT if ( num == 0 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT first = 0 NEW_LINE second = 1 NEW_LINE third = first + second NEW_LINE while ( third <= num ) : NEW_LINE INDENT first = second NEW_LINE second = third NEW_LINE third = first + second NEW_LINE DEDENT if ( abs ( third - num ) >= abs ( second - num ) ) : NEW_LINE INDENT ans = second NEW_LINE DEDENT else : NEW_LINE INDENT ans = third NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 17 NEW_LINE nearestFibonacci ( N ) NEW_LINE DEDENT"} {"text":"Permutation of first N natural numbers having given array as the prefix maximum array | Python3 program for the above approach ; Function to check if the maximum prefix array of ans [ ] is equal to array arr [ ] ; Initialize a variable , Max ; Traverse the array , ans [ ] ; Store the maximum value upto index i ; If it is not equal to a [ i ] , then return false ; Otherwise return false ; Function to find the permutation of the array whose prefix maximum array is same as the given array a [ ] ; Stores the required permutation ; Stores the index of first occurrence of elements ; Traverse the array a [ ] ; If a [ i ] is not present in um , then store it in um ; Update the ans [ i ] to a [ i ] ; Stores the unvisited numbers ; Fill the array , v [ ] ; Store the index ; Traverse the array , ans [ ] ; Fill v [ j ] at places where ans [ i ] is 0 ; Check if the current permutation maximum prefix array is same as the given array a [ ] ; If true , the print the permutation ; Otherwise , print - 1 ; Driver Code ; Function Call","code":"import sys NEW_LINE def checkPermutation ( ans , a , n ) : NEW_LINE INDENT Max = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT Max = max ( Max , ans [ i ] ) NEW_LINE if ( Max != a [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findPermutation ( a , n ) : NEW_LINE INDENT ans = [ 0 ] * n NEW_LINE um = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] not in um ) : NEW_LINE INDENT ans [ i ] = a [ i ] NEW_LINE um [ a [ i ] ] = i NEW_LINE DEDENT DEDENT v = [ ] NEW_LINE j = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i not in um ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ans [ i ] == 0 ) : NEW_LINE INDENT ans [ i ] = v [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT if ( checkPermutation ( ans , a , n ) ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( \" - 1\" ) NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 5 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE findPermutation ( arr , N ) NEW_LINE DEDENT"} {"text":"Count pairs of equal elements possible by excluding each array element once | Function to count the number of required pairs for every array element ; Initialize a map ; Update the frequency of every element ; Stores the count of pairs ; Traverse the map ; Count the number of ways to select pairs consisting of equal elements only ; Traverse the array ; Print the count for every array element ; Driver code ; Given array ; Size of the array","code":"def countEqualElementPairs ( arr , N ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT total = 0 NEW_LINE for key , value in mp . items ( ) : NEW_LINE INDENT total += ( value * ( value - 1 ) ) \/ 2 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( int ( total - ( mp [ arr [ i ] ] - 1 ) ) , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE countEqualElementPairs ( arr , N ) NEW_LINE DEDENT"} {"text":"Count of Octal numbers upto N digits | Function to return the count of natural octal numbers upto N digits ; Loop to iterate from 1 to N and calculating number of octal numbers for every ' i ' th digit . ; Driver code","code":"def count ( N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT sum += 7 * ( 8 ** ( i - 1 ) ) ; NEW_LINE DEDENT return int ( sum ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 ; NEW_LINE print ( count ( N ) ) ; NEW_LINE DEDENT"} {"text":"Palindromic divisors of a number | Python3 program to find all the palindromic divisors of a number ; Function to check is num is palindromic or not ; Convert n to string str ; Starting and ending index of string str ; If char at s and e are not equals then return false ; Function to find palindromic divisors ; To sore the palindromic divisors of number n ; If n is divisible by i ; Check if number is a perfect square ; Check divisor is palindromic , then store it ; Check if divisors are palindrome ; Check if n \/ divisors is palindromic or not ; Print all palindromic divisors in sorted order ; Driver code ; Function call to find all palindromic divisors","code":"from math import sqrt ; NEW_LINE def isPalindrome ( n ) : NEW_LINE INDENT string = str ( n ) ; NEW_LINE s = 0 ; e = len ( string ) - 1 ; NEW_LINE while ( s < e ) : NEW_LINE INDENT if ( string [ s ] != string [ e ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT s += 1 ; NEW_LINE e -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT def palindromicDivisors ( n ) : NEW_LINE INDENT PalindromDivisors = [ ] ; NEW_LINE for i in range ( 1 , int ( sqrt ( n ) ) ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( n \/\/ i == i ) : NEW_LINE INDENT if ( isPalindrome ( i ) ) : NEW_LINE INDENT PalindromDivisors . append ( i ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( isPalindrome ( i ) ) : NEW_LINE INDENT PalindromDivisors . append ( i ) ; NEW_LINE DEDENT if ( isPalindrome ( n \/\/ i ) ) : NEW_LINE INDENT PalindromDivisors . append ( n \/\/ i ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT PalindromDivisors . sort ( ) ; NEW_LINE for i in range ( len ( PalindromDivisors ) ) : NEW_LINE INDENT print ( PalindromDivisors [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 66 ; NEW_LINE palindromicDivisors ( n ) ; NEW_LINE DEDENT"} {"text":"Remove minimum numbers from the array to get minimum OR value | Python3 implementation of the approach ; Function to return the minimum deletions to get minimum OR ; To store the minimum element ; Find the minimum element from the array ; To store the frequency of the minimum element ; Find the frequency of the minimum element ; Return the final answer ; Driver code","code":"import sys NEW_LINE def findMinDel ( arr , n ) : NEW_LINE INDENT min_num = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT min_num = min ( arr [ i ] , min_num ) ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == min_num ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return n - cnt ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 3 , 3 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findMinDel ( arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Program to print prime numbers from 1 to N . | Function to print first N prime numbers ; Declare the variables ; Print display message ; Traverse each number from 1 to N with the help of for loop ; Skip 0 and 1 as they are neither prime nor composite ; flag variable to tell if i is prime or not ; flag = 1 means i is prime and flag = 0 means i is not prime ; Driver code","code":"def print_primes_till_N ( N ) : NEW_LINE INDENT i , j , flag = 0 , 0 , 0 ; NEW_LINE print ( \" Prime \u2581 numbers \u2581 between \u2581 1 \u2581 and \u2581 \" , N , \" \u2581 are : \" ) ; NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT if ( i == 1 or i == 0 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT flag = 1 ; NEW_LINE for j in range ( 2 , ( ( i \/\/ 2 ) + 1 ) , 1 ) : NEW_LINE INDENT if ( i % j == 0 ) : NEW_LINE INDENT flag = 0 ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( i , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT DEDENT N = 100 ; NEW_LINE print_primes_till_N ( N ) ; NEW_LINE"} {"text":"Maximize the expression ( A AND X ) * ( B AND X ) | Bit Manipulation | Python3 implementation of the approach ; Function to find X according to the given conditions ; int can have 32 bits ; Temporary ith bit ; Compute ith bit of X according to given conditions Expression below is the direct conclusion from the illustration we had taken earlier ; Add the ith bit of X to X ; Driver code","code":"MAX = 32 NEW_LINE def findX ( A , B ) : NEW_LINE INDENT X = 0 ; NEW_LINE for bit in range ( MAX ) : NEW_LINE INDENT tempBit = 1 << bit ; NEW_LINE bitOfX = A & B & tempBit ; NEW_LINE X += bitOfX ; NEW_LINE DEDENT return X ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = 11 ; B = 13 ; NEW_LINE print ( findX ( A , B ) ) ; NEW_LINE DEDENT"} {"text":"Number of subsets whose mean is maximum | Function to return the count of subsets with the maximum mean ; Maximum value from the array ; To store the number of times maximum element appears in the array ; Return the count of valid subsets ; Driver code","code":"def cntSubSets ( arr , n ) : NEW_LINE INDENT maxVal = max ( arr ) ; NEW_LINE cnt = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == maxVal ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT return ( ( 2 ** cnt ) - 1 ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 2 , 1 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( cntSubSets ( arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Probability that a random pair chosen from an array ( a [ i ] , a [ j ] ) has the maximum sum | Python3 implementation of the approach ; Function to return the probability of getting the maximum pair sum when a random pair is chosen from the given array ; Initialize the maximum sum , its count and the count of total pairs ; For every single pair ; Get the sum of the current pair ; If the sum is equal to the current maximum sum so far ; Increment its count ; If the sum is greater than the current maximum ; Update the current maximum and re - initialize the count to 1 ; Find the required probability ; Driver code","code":"import sys NEW_LINE def findProb ( arr , n ) : NEW_LINE INDENT maxSum = - ( sys . maxsize - 1 ) ; NEW_LINE maxCount = 0 ; NEW_LINE totalPairs = 0 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum = arr [ i ] + arr [ j ] ; NEW_LINE if ( sum == maxSum ) : NEW_LINE INDENT maxCount += 1 ; NEW_LINE DEDENT elif ( sum > maxSum ) : NEW_LINE INDENT maxSum = sum ; NEW_LINE maxCount = 1 ; NEW_LINE DEDENT totalPairs += 1 ; NEW_LINE DEDENT DEDENT prob = maxCount \/ totalPairs ; NEW_LINE return prob ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 2 , 2 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findProb ( arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Maximum count of common divisors of A and B such that all are co | Python3 implementation of the approach ; Function to return the count of common factors of a and b such that all the elements are co - prime to one another ; GCD of a and b ; Include 1 initially ; Find all the prime factors of the gcd ; If gcd is prime ; Return the required answer ; Driver code","code":"import math NEW_LINE def maxCommonFactors ( a , b ) : NEW_LINE INDENT gcd = math . gcd ( a , b ) NEW_LINE ans = 1 ; NEW_LINE i = 2 NEW_LINE while ( i * i <= gcd ) : NEW_LINE INDENT if ( gcd % i == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE while ( gcd % i == 0 ) : NEW_LINE INDENT gcd = gcd \/\/ i NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT if ( gcd != 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT a = 12 NEW_LINE b = 18 NEW_LINE print ( maxCommonFactors ( a , b ) ) NEW_LINE"} {"text":"Find the day number in the current year for the given date | Python3 implementation of the approach ; Function to return the day number of the year for the given date ; Extract the year , month and the day from the date string ; If current year is a leap year and the date given is after the 28 th of February then it must include the 29 th February ; Add the days in the previous months ; Driver code","code":"days = [ 31 , 28 , 31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31 ] ; NEW_LINE def dayOfYear ( date ) : NEW_LINE INDENT year = ( int ) ( date [ 0 : 4 ] ) ; NEW_LINE month = ( int ) ( date [ 5 : 7 ] ) ; NEW_LINE day = ( int ) ( date [ 8 : ] ) ; NEW_LINE if ( month > 2 and year % 4 == 0 and ( year % 100 != 0 or year % 400 == 0 ) ) : NEW_LINE INDENT day += 1 ; NEW_LINE DEDENT month -= 1 ; NEW_LINE while ( month > 0 ) : NEW_LINE INDENT day = day + days [ month - 1 ] ; NEW_LINE month -= 1 ; NEW_LINE DEDENT return day ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT date = \"2019-01-09\" ; NEW_LINE print ( dayOfYear ( date ) ) ; NEW_LINE DEDENT"} {"text":"Find the number of cells in the table contains X | Function to find number of cells in the table contains X ; Driver code ; Function call","code":"def Cells ( n , x ) : NEW_LINE INDENT ans = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( x % i == 0 and x \/ i <= n ) : NEW_LINE INDENT ans += 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 ; x = 12 ; NEW_LINE print ( Cells ( n , x ) ) ; NEW_LINE DEDENT"} {"text":"Smallest power of 4 greater than or equal to N | Python3 implementation of above approach ; Function to return the smallest power of 4 greater than or equal to n ; If n is itself is a power of 4 then return n ; Driver code","code":"import math NEW_LINE def nextPowerOfFour ( n ) : NEW_LINE INDENT x = math . floor ( ( n ** ( 1 \/ 2 ) ) ** ( 1 \/ 2 ) ) ; NEW_LINE if ( ( x ** 4 ) == n ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT else : NEW_LINE INDENT x = x + 1 ; NEW_LINE return ( x ** 4 ) ; NEW_LINE DEDENT DEDENT n = 122 ; NEW_LINE print ( nextPowerOfFour ( n ) ) ; NEW_LINE"} {"text":"Minimum operations required to convert X to Y by multiplying X with the given co | Function to return the minimum operations required ; Not possible ; To store the greatest power of p that divides d ; While divible by p ; To store the greatest power of q that divides d ; While divible by q ; If d > 1 ; Since , d = p ^ a * q ^ b ; Driver code","code":"def minOperations ( x , y , p , q ) : NEW_LINE INDENT if ( y % x != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT d = y \/\/ x NEW_LINE a = 0 NEW_LINE while ( d % p == 0 ) : NEW_LINE INDENT d \/\/= p NEW_LINE a += 1 NEW_LINE DEDENT b = 0 NEW_LINE while ( d % q == 0 ) : NEW_LINE INDENT d \/\/= q NEW_LINE b += 1 NEW_LINE DEDENT if ( d != 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return ( a + b ) NEW_LINE DEDENT x = 12 NEW_LINE y = 2592 NEW_LINE p = 2 NEW_LINE q = 3 NEW_LINE print ( minOperations ( x , y , p , q ) ) NEW_LINE"} {"text":"Number of Quadruples with GCD equal to K | Python3 implementation of the approach ; Function to calculate NC4 ; Base case to calculate NC4 ; Function to return the count of required quadruples using Inclusion Exclusion ; Effective N ; Iterate over 2 to M ; Number of divisors of i till M ; Count stores the number of prime divisors occurring exactly once ; To prevent repetition of prime divisors ; If repetition of prime divisors present ignore this number ; If prime divisor count is odd subtract it from answer else add ; Driver code","code":"from math import sqrt NEW_LINE def nCr ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT answer = n * ( n - 1 ) * ( n - 2 ) * ( n - 3 ) ; NEW_LINE answer \/\/= 24 ; NEW_LINE return answer ; NEW_LINE DEDENT def countQuadruples ( N , K ) : NEW_LINE INDENT M = N \/\/ K ; NEW_LINE answer = nCr ( M ) ; NEW_LINE for i in range ( 2 , M ) : NEW_LINE INDENT j = i ; NEW_LINE temp2 = M \/\/ i ; NEW_LINE count = 0 ; NEW_LINE check = 0 ; NEW_LINE temp = j ; NEW_LINE while ( j % 2 == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE j \/\/= 2 ; NEW_LINE if ( count >= 2 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( count >= 2 ) : NEW_LINE INDENT check = 1 ; NEW_LINE DEDENT for k in range ( 3 , int ( sqrt ( temp ) ) , 2 ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE while ( j % k == 0 ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE j \/\/= k ; NEW_LINE if ( cnt >= 2 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( cnt >= 2 ) : NEW_LINE INDENT check = 1 ; NEW_LINE break ; NEW_LINE DEDENT elif ( cnt == 1 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT if ( j > 2 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT if ( check ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( count % 2 == 1 ) : NEW_LINE INDENT answer -= nCr ( temp2 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT answer += nCr ( temp2 ) ; NEW_LINE DEDENT DEDENT DEDENT return answer ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 10 ; K = 2 ; NEW_LINE print ( countQuadruples ( N , K ) ) ; NEW_LINE DEDENT"} {"text":"Find the number which when added to the given ratio a : b , the ratio changes to c : d | Function to return the required number X ; Driver code","code":"def getX ( a , b , c , d ) : NEW_LINE INDENT X = ( b * c - a * d ) \/\/ ( d - c ) NEW_LINE return X NEW_LINE DEDENT a = 2 NEW_LINE b = 3 NEW_LINE c = 4 NEW_LINE d = 5 NEW_LINE print ( getX ( a , b , c , d ) ) NEW_LINE"} {"text":"Number of ways to arrange a word such that no vowels occur together | Function to check if a character is vowel or consonent ; Function to calculate factorial of a number ; Calculating no of ways for arranging vowels ; Iterate the map and count the number of vowels and calculate no of ways to arrange vowels ; calculating no of ways to arrange the given word such that vowels come together ; calculate no of ways to arrange vowels ; to store denominator of fraction ; count of consonents ; calculate the number of ways to arrange the word such that vowels come together ; To calculate total number of permutations ; To store length of the given word ; denominator of fraction ; return total number of permutations of the given word ; Function to calculate number of permutations such that no vowels come together ; to store frequency of character ; count frequency of acharacters ; calculate total number of permutations ; calculate total number of permutations such that vowels come together ; substrat vwl_tgthr from total to get the result ; return the result ; Driver code","code":"def isVowel ( ch ) : NEW_LINE INDENT if ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def fact ( n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return n * fact ( n - 1 ) NEW_LINE DEDENT def only_vowels ( freq ) : NEW_LINE INDENT denom = 1 NEW_LINE cnt_vwl = 0 NEW_LINE for itr in freq : NEW_LINE INDENT if ( isVowel ( itr ) ) : NEW_LINE INDENT denom *= fact ( freq [ itr ] ) NEW_LINE cnt_vwl += freq [ itr ] NEW_LINE DEDENT DEDENT return fact ( cnt_vwl ) \/\/ denom NEW_LINE DEDENT def all_vowels_together ( freq ) : NEW_LINE INDENT vow = only_vowels ( freq ) NEW_LINE denom = 1 NEW_LINE cnt_cnst = 0 NEW_LINE for itr in freq : NEW_LINE INDENT if ( isVowel ( itr ) == False ) : NEW_LINE INDENT denom *= fact ( freq [ itr ] ) NEW_LINE cnt_cnst += freq [ itr ] NEW_LINE DEDENT DEDENT ans = fact ( cnt_cnst + 1 ) \/\/ denom NEW_LINE return ( ans * vow ) NEW_LINE DEDENT def total_permutations ( freq ) : NEW_LINE INDENT cnt = 0 NEW_LINE denom = 1 NEW_LINE for itr in freq : NEW_LINE INDENT denom *= fact ( freq [ itr ] ) NEW_LINE cnt += freq [ itr ] NEW_LINE DEDENT return fact ( cnt ) \/\/ denom NEW_LINE DEDENT def no_vowels_together ( word ) : NEW_LINE INDENT freq = dict ( ) NEW_LINE for i in word : NEW_LINE INDENT ch = i . lower ( ) NEW_LINE freq [ ch ] = freq . get ( ch , 0 ) + 1 NEW_LINE DEDENT total = total_permutations ( freq ) NEW_LINE vwl_tgthr = all_vowels_together ( freq ) NEW_LINE res = total - vwl_tgthr NEW_LINE return res NEW_LINE DEDENT word = \" allahabad \" NEW_LINE ans = no_vowels_together ( word ) NEW_LINE print ( ans ) NEW_LINE word = \" geeksforgeeks \" NEW_LINE ans = no_vowels_together ( word ) NEW_LINE print ( ans ) NEW_LINE word = \" abcd \" NEW_LINE ans = no_vowels_together ( word ) NEW_LINE print ( ans ) NEW_LINE"} {"text":"Program to find the number of men initially | Function to return the number of men initially ; Driver code","code":"def numberOfMen ( D , m , d ) : NEW_LINE INDENT Men = ( m * ( D - d ) ) \/ d ; NEW_LINE return int ( Men ) ; NEW_LINE DEDENT D = 5 ; m = 4 ; d = 4 ; NEW_LINE print ( numberOfMen ( D , m , d ) ) ; NEW_LINE"} {"text":"Area of triangle formed by the axes of co | Function to find area ; Driver code","code":"def area ( a , b , c ) : NEW_LINE INDENT d = abs ( ( c * c ) \/ ( 2 * a * b ) ) NEW_LINE return d NEW_LINE DEDENT a = - 2 NEW_LINE b = 4 NEW_LINE c = 3 NEW_LINE print ( area ( a , b , c ) ) NEW_LINE"} {"text":"Sum of two numbers where one number is represented as array of digits | Function to return the vector containing the answer ; Vector v is to store each digits sum and vector ans is to store the answer ; No carry in the beginning ; Start loop from the end and take element one by one ; Array index and last digit of number ; Maintain carry of summation ; Push the digit value into the array ; K value is greater then 0 ; Push digits of K one by one in the array ; Also maintain carry with summation ; Reverse the elements of vector v and store it in vector ans ; Driver code ; Print the answer","code":"def addToArrayForm ( A , K ) : NEW_LINE INDENT v , ans = [ ] , [ ] NEW_LINE rem , i = 0 , 0 NEW_LINE for i in range ( len ( A ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT my = A [ i ] + ( K % 10 ) + rem NEW_LINE if my > 9 : NEW_LINE INDENT rem = 1 NEW_LINE v . append ( my % 10 ) NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( my ) NEW_LINE rem = 0 NEW_LINE DEDENT K = K \/\/ 10 NEW_LINE DEDENT while K > 0 : NEW_LINE INDENT my = ( K % 10 ) + rem NEW_LINE v . append ( my % 10 ) NEW_LINE if my \/\/ 10 > 0 : NEW_LINE INDENT rem = 1 NEW_LINE DEDENT else : NEW_LINE INDENT rem = 0 NEW_LINE DEDENT K = K \/\/ 10 NEW_LINE DEDENT if rem > 0 : NEW_LINE INDENT v . append ( rem ) NEW_LINE DEDENT for i in range ( len ( v ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT ans . append ( v [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 2 , 7 , 4 ] NEW_LINE K = 181 NEW_LINE ans = addToArrayForm ( A , K ) NEW_LINE for i in range ( 0 , len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT"} {"text":"Compute maximum of the function efficiently over all sub | Python3 implementation of the above approach ; Function to return maximum sum of a sub - array ; Function to return maximum value of function F ; Compute arrays B [ ] and C [ ] ; Find maximum sum sub - array of both of the arrays and take maximum among them ; Driver code","code":"MAX = 100005 ; NEW_LINE def kadaneAlgorithm ( ar , n ) : NEW_LINE INDENT sum = 0 ; maxSum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += ar [ i ] ; NEW_LINE if ( sum < 0 ) : NEW_LINE INDENT sum = 0 ; NEW_LINE DEDENT maxSum = max ( maxSum , sum ) ; NEW_LINE DEDENT return maxSum ; NEW_LINE DEDENT def maxFunction ( arr , n ) : NEW_LINE INDENT b = [ 0 ] * MAX ; NEW_LINE c = [ 0 ] * MAX ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( i & 1 ) : NEW_LINE INDENT b [ i ] = abs ( arr [ i + 1 ] - arr [ i ] ) ; NEW_LINE c [ i ] = - b [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT c [ i ] = abs ( arr [ i + 1 ] - arr [ i ] ) ; NEW_LINE b [ i ] = - c [ i ] ; NEW_LINE DEDENT DEDENT ans = kadaneAlgorithm ( b , n - 1 ) ; NEW_LINE ans = max ( ans , kadaneAlgorithm ( c , n - 1 ) ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 5 , 4 , 7 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( maxFunction ( arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Third last digit in 5 ^ N for given N | Function to find the element ; if n < 3 ; If n is even return 6 If n is odd return 1 ; Driver code","code":"def findThirdDigit ( n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 if n and 1 else 6 NEW_LINE DEDENT n = 7 NEW_LINE print ( findThirdDigit ( n ) ) NEW_LINE"} {"text":"Probability of A winning the match when individual probabilities of hitting the target given | Function to return the probability of A winning ; p and q store the values of fractions a \/ b and c \/ d ; To store the winning probability of A ; Driver code","code":"def getProbability ( a , b , c , d ) : NEW_LINE INDENT p = a \/ b ; NEW_LINE q = c \/ d ; NEW_LINE ans = p * ( 1 \/ ( 1 - ( 1 - q ) * ( 1 - p ) ) ) ; NEW_LINE return round ( ans , 5 ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 1 ; b = 2 ; c = 10 ; d = 11 ; NEW_LINE print ( getProbability ( a , b , c , d ) ) ; NEW_LINE DEDENT"} {"text":"Largest palindromic number in an array | Function to check if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digits are not same then return false ; Removing the leading and trailing digits from the number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function to find the largest palindromic number ; If a palindrome larger than the currentMax is found ; Return the largest palindromic number from the array ; Driver Code ; print required answer","code":"def isPalindrome ( n ) : NEW_LINE INDENT divisor = 1 NEW_LINE while ( int ( n \/ divisor ) >= 10 ) : NEW_LINE INDENT divisor *= 10 NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT leading = int ( n \/ divisor ) NEW_LINE trailing = n % 10 NEW_LINE if ( leading != trailing ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = int ( ( n % divisor ) \/ 10 ) NEW_LINE divisor = int ( divisor \/ 100 ) NEW_LINE DEDENT return True NEW_LINE DEDENT def largestPalindrome ( A , n ) : NEW_LINE INDENT currentMax = - 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( A [ i ] > currentMax and isPalindrome ( A [ i ] ) ) : NEW_LINE INDENT currentMax = A [ i ] NEW_LINE DEDENT DEDENT return currentMax NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 232 , 54545 , 999991 ] NEW_LINE n = len ( A ) NEW_LINE print ( largestPalindrome ( A , n ) ) NEW_LINE DEDENT"} {"text":"Reduce the array to a single element with the given operation | Function to return the final element ; Driver code","code":"def getFinalElement ( n ) : NEW_LINE INDENT finalNum = 2 NEW_LINE while finalNum * 2 <= n : NEW_LINE INDENT finalNum *= 2 NEW_LINE DEDENT return finalNum NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 12 NEW_LINE print ( getFinalElement ( N ) ) NEW_LINE DEDENT"} {"text":"Sum of elements in an array having prime frequency | Python3 program to find Sum of elements in an array having prime frequency ; 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 return the Sum of elements in an array having prime frequency ; Map is used to store element frequencies ; Traverse the map using iterators ; Count the number of elements having prime frequencies ; Driver code","code":"import math as mt NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , mt . ceil ( mt . sqrt ( 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 SumOfElements ( arr , n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 1 ) ] NEW_LINE SieveOfEratosthenes ( prime , n + 1 ) NEW_LINE i , j = 0 , 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in m . keys ( ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT Sum = 0 NEW_LINE for i in m : NEW_LINE INDENT if ( prime [ m [ i ] ] ) : NEW_LINE INDENT Sum += ( i ) NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT arr = [ 5 , 4 , 6 , 5 , 4 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( SumOfElements ( arr , n ) ) NEW_LINE"} {"text":"Sum of all odd length palindromic numbers within the range [ L , R ] | Function that returns true if the given number is a palindrome ; Here we are generating a new number ( reverse_num ) by reversing the digits of original input number ; If the original input number ( num ) is equal to its reverse ( reverse_num ) then its palindrome else it is not . ; Function that returns true if the given number is of odd length ; Function to return the sum of all odd length palindromic numbers within the given range ; if number is palindrome and of odd length ; Driver code","code":"def isPalindrome ( num ) : NEW_LINE INDENT reverse_num = 0 NEW_LINE temp = num NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT remainder = temp % 10 NEW_LINE reverse_num = reverse_num * 10 + remainder NEW_LINE temp = int ( temp \/ 10 ) NEW_LINE DEDENT if ( reverse_num == num ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def isOddLength ( num ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num > 0 ) : NEW_LINE INDENT num = int ( num \/ 10 ) NEW_LINE count += 1 NEW_LINE DEDENT if ( count % 2 != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def sumOfAllPalindrome ( L , R ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( L <= R ) : NEW_LINE INDENT for i in range ( L , R + 1 , 1 ) : NEW_LINE INDENT if ( isPalindrome ( i ) and isOddLength ( i ) ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 110 NEW_LINE R = 1130 NEW_LINE print ( sumOfAllPalindrome ( L , R ) ) NEW_LINE DEDENT"} {"text":"Number of ways to arrange a word such that all vowels occur together | Factorial of a number ; calculating ways for arranging consonants ; Ignore vowels ; calculating ways for arranging vowels ; Function to count total no . of ways ; Count vowels and consonant ; total no . of ways ; Driver code","code":"def fact ( n ) : NEW_LINE INDENT f = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT f = f * i NEW_LINE DEDENT return f NEW_LINE DEDENT def waysOfConsonants ( size1 , freq ) : NEW_LINE INDENT ans = fact ( size1 ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( i == 0 or i == 4 or i == 8 or i == 14 or i == 20 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT ans = ans \/\/ fact ( freq [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def waysOfVowels ( size2 , freq ) : NEW_LINE INDENT return ( fact ( size2 ) \/\/ ( fact ( freq [ 0 ] ) * fact ( freq [ 4 ] ) * fact ( freq [ 8 ] ) * fact ( freq [ 14 ] ) * fact ( freq [ 20 ] ) ) ) NEW_LINE DEDENT def countWays ( str1 ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT freq [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT vowel = 0 NEW_LINE consonant = 0 NEW_LINE for i in range ( len ( str1 ) ) : NEW_LINE INDENT if ( str1 [ i ] != ' a ' and str1 [ i ] != ' e ' and str1 [ i ] != ' i ' and str1 [ i ] != ' o ' and str1 [ i ] != ' u ' ) : NEW_LINE INDENT consonant += 1 NEW_LINE DEDENT else : NEW_LINE INDENT vowel += 1 NEW_LINE DEDENT DEDENT return ( waysOfConsonants ( consonant + 1 , freq ) * waysOfVowels ( vowel , freq ) ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str1 = \" geeksforgeeks \" NEW_LINE print ( countWays ( str1 ) ) NEW_LINE DEDENT"} {"text":"Sum of Fibonacci Numbers with alternate negatives | Computes value of first fibonacci numbers and stores their alternate sum ; Initialize result ; Add remaining terms ; For even terms ; For odd terms ; Return the alternating sum ; Driver program to test above function ; Get n ; Find the alternating sum","code":"def calculateAlternateSum ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT fibo = [ 0 ] * ( n + 1 ) NEW_LINE fibo [ 0 ] = 0 NEW_LINE fibo [ 1 ] = 1 NEW_LINE sum = pow ( fibo [ 0 ] , 2 ) + pow ( fibo [ 1 ] , 2 ) NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT fibo [ i ] = fibo [ i - 1 ] + fibo [ i - 2 ] NEW_LINE if ( i % 2 == 0 ) : NEW_LINE INDENT sum -= fibo [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT sum += fibo [ i ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 8 NEW_LINE print ( \" Alternating \u2581 Fibonacci \u2581 Sum \u2581 upto \u2581 \" , n , \" \u2581 terms : \u2581 \" , calculateAlternateSum ( n ) ) NEW_LINE DEDENT"} {"text":"Find nth Term of the Series 1 2 2 4 4 4 4 8 8 8 8 8 8 8 8 ... | Function that will return nth term ; Get n ; Get the value ; Get n ; Get the value","code":"def getValue ( n ) : NEW_LINE INDENT i = 0 ; NEW_LINE k = 1 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT i = i + k ; NEW_LINE k = k * 2 ; NEW_LINE DEDENT return int ( k \/ 2 ) ; NEW_LINE DEDENT n = 9 ; NEW_LINE print ( getValue ( n ) ) ; NEW_LINE n = 1025 ; NEW_LINE print ( getValue ( n ) ) ; NEW_LINE"} {"text":"Construct a frequency array of digits of the values obtained from x ^ 1 , x ^ 2 , ... ... . . , x ^ n | Python 3 implementation of above approach ; Function that traverses digits in a number and modifies frequency count array ; Array to keep count of digits ; Traversing through x ^ 1 to x ^ n ; For power function , both its parameters are to be in double ; calling countDigits function on x ^ i ; Printing count of digits 0 - 9 ; Driver code","code":"import math NEW_LINE def countDigits ( val , arr ) : NEW_LINE INDENT while ( val > 0 ) : NEW_LINE INDENT digit = val % 10 NEW_LINE arr [ int ( digit ) ] += 1 NEW_LINE val = val \/\/ 10 NEW_LINE DEDENT return ; NEW_LINE DEDENT def countFrequency ( x , n ) : NEW_LINE INDENT freq_count = [ 0 ] * 10 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT val = math . pow ( x , i ) NEW_LINE countDigits ( val , freq_count ) NEW_LINE DEDENT for i in range ( 10 ) : NEW_LINE INDENT print ( freq_count [ i ] , end = \" \u2581 \" ) ; NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x = 15 NEW_LINE n = 3 NEW_LINE countFrequency ( x , n ) NEW_LINE DEDENT"} {"text":"Number of values of b such that a = b + ( a ^ b ) | function to return the number of solutions ; check for every possible value ; Driver Code","code":"def countSolutions ( a ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( a + 1 ) : NEW_LINE INDENT if ( a == ( i + ( a ^ i ) ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 3 NEW_LINE print ( countSolutions ( a ) ) NEW_LINE DEDENT"} {"text":"Number of values of b such that a = b + ( a ^ b ) | function to return the number of solutions ; Driver Code","code":"def countSolutions ( a ) : NEW_LINE INDENT count = bin ( a ) . count ( '1' ) NEW_LINE return 2 ** count NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT a = 3 NEW_LINE print ( countSolutions ( a ) ) NEW_LINE DEDENT"} {"text":"Sum of Area of all possible square inside a rectangle | Function to calculate the sum of area of all possible squares that comes inside the rectangle ; Square with max size possible ; calculate total square of a given size ; calculate area of squares of a particular size ; total area ; increment size ; Driver Code","code":"def calculateAreaSum ( l , b ) : NEW_LINE INDENT size = 1 NEW_LINE maxSize = min ( l , b ) NEW_LINE totalArea = 0 NEW_LINE for i in range ( 1 , maxSize + 1 ) : NEW_LINE INDENT totalSquares = ( ( l - size + 1 ) * ( b - size + 1 ) ) NEW_LINE area = ( totalSquares * size * size ) NEW_LINE totalArea += area NEW_LINE size += 1 NEW_LINE DEDENT return totalArea NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT l = 4 NEW_LINE b = 3 NEW_LINE print ( calculateAreaSum ( l , b ) ) NEW_LINE DEDENT"} {"text":"Hyperfactorial of a number | function to calculate the value of hyperfactorial ; initialise the val to 1 ; returns the hyperfactorial of a number ; Driver code","code":"def boost_hyperfactorial ( num ) : NEW_LINE INDENT val = 1 ; NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT val = val * pow ( i , i ) ; NEW_LINE DEDENT return val ; NEW_LINE DEDENT num = 5 ; NEW_LINE print ( boost_hyperfactorial ( num ) ) ; NEW_LINE"} {"text":"Hyperfactorial of a number | function to calculate the value of hyperfactorial ; initialise the val to 1 ; 1 ^ 1 * 2 ^ 2 * 3 ^ 3. . . . ; returns the hyperfactorial of a number ; Driver code","code":"def boost_hyperfactorial ( num ) : NEW_LINE INDENT val = 1 ; NEW_LINE for i in range ( 1 , num + 1 ) : NEW_LINE INDENT for j in range ( 1 , i + 1 ) : NEW_LINE INDENT val *= i ; NEW_LINE DEDENT DEDENT return val ; NEW_LINE DEDENT num = 5 ; NEW_LINE print ( boost_hyperfactorial ( num ) ) ; NEW_LINE"} {"text":"Subtract 1 without arithmetic operators | Python 3 code to subtract one from a given number ; Flip all the set bits until we find a 1 ; flip the rightmost 1 bit ; Driver Code","code":"def subtractOne ( x ) : NEW_LINE INDENT m = 1 NEW_LINE while ( ( x & m ) == False ) : NEW_LINE INDENT x = x ^ m NEW_LINE m = m << 1 NEW_LINE DEDENT x = x ^ m NEW_LINE return x NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( subtractOne ( 13 ) ) NEW_LINE DEDENT"} {"text":"Find the mean vector of a Matrix | Python3 program to find mean vector of given matrix ; Function to find mean vector ; loop to traverse each column ; to calculate mean of each row ; to store sum of elements of a column ; Driver Code","code":"rows = 3 ; NEW_LINE cols = 3 ; NEW_LINE def meanVector ( mat ) : NEW_LINE INDENT print ( \" [ \u2581 \" , end = \" \" ) ; NEW_LINE for i in range ( rows ) : NEW_LINE INDENT mean = 0.00 ; NEW_LINE sum = 0 ; NEW_LINE for j in range ( cols ) : NEW_LINE INDENT sum = sum + mat [ j ] [ i ] ; mean = int ( sum \/ rows ) ; print ( mean , end = \" \u2581 \" ) ; print ( \" ] \" ) ; NEW_LINE DEDENT DEDENT DEDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] ; NEW_LINE meanVector ( mat ) ; NEW_LINE"} {"text":"Hoax Number | Python3 code to check if a number is a hoax number or not . ; Function to find distinct prime factors of given number n ; n is odd at this point , since it is no longer divisible by 2. So we can test only for the odd numbers , whether they are factors of n ; Check if i is prime factor ; This condition is to handle the case when n is a prime number greater than 2 ; Function to calculate sum of digits of distinct prime factors of given number n and sum of digits of number n and compare the sums obtained ; Distinct prime factors of n are being stored in vector pf ; If n is a prime number , it cannot be a hoax number ; Finding sum of digits of distinct prime factors of the number n ; Finding sum of digits in current prime factor pf [ i ] . ; Finding sum of digits of number n ; Comparing the two calculated sums ; Driver Method","code":"import math NEW_LINE def primeFactors ( n ) : NEW_LINE INDENT res = [ ] NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT n = int ( n \/ 2 ) NEW_LINE DEDENT res . append ( 2 ) NEW_LINE DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) , 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT n = int ( n \/ i ) NEW_LINE DEDENT res . append ( i ) NEW_LINE DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT res . append ( n ) NEW_LINE DEDENT return res NEW_LINE DEDENT def isHoax ( n ) : NEW_LINE INDENT pf = primeFactors ( n ) NEW_LINE if ( pf [ 0 ] == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT all_pf_sum = 0 NEW_LINE for i in range ( 0 , len ( pf ) ) : NEW_LINE INDENT pf_sum = 0 NEW_LINE while ( pf [ i ] > 0 ) : NEW_LINE INDENT pf_sum += pf [ i ] % 10 NEW_LINE pf [ i ] = int ( pf [ i ] \/ 10 ) NEW_LINE DEDENT all_pf_sum += pf_sum NEW_LINE DEDENT sum_n = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT sum_n += n % 10 NEW_LINE n = int ( n \/ 10 ) NEW_LINE DEDENT return sum_n == all_pf_sum NEW_LINE DEDENT n = 84 ; NEW_LINE if ( isHoax ( n ) ) : NEW_LINE INDENT print ( \" A Hoax Number \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Not a Hoax Number \" ) NEW_LINE DEDENT"} {"text":"Primality Test | Set 5 ( Using Lucas | Function to find out first n terms ( considering 4 as 0 th term ) of Lucas - Lehmer series . ; the 0 th term of the series is 4. ; create an array to store the terms . ; compute each term and add it to the array . ; print out the terms one by one . ; Driver program","code":"def LucasLehmer ( n ) : NEW_LINE INDENT current_val = 4 ; NEW_LINE series = [ ] NEW_LINE series . append ( current_val ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT current_val = current_val * current_val - 2 ; NEW_LINE series . append ( current_val ) ; NEW_LINE DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT print ( \" Term \" , i , \" : \" , series [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; NEW_LINE LucasLehmer ( n ) ; NEW_LINE DEDENT"} {"text":"Modular multiplicative inverse from 1 to n | A naive method to find modular multiplicative inverse of ' a ' under modulo 'prime ; Driver Program","code":"' NEW_LINE def modInverse ( a , prime ) : NEW_LINE INDENT a = a % prime NEW_LINE for x in range ( 1 , prime ) : NEW_LINE INDENT if ( ( a * x ) % prime == 1 ) : NEW_LINE INDENT return x NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printModIverses ( n , prime ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( modInverse ( i , prime ) , end = \" \u2581 \" ) NEW_LINE DEDENT DEDENT n = 10 NEW_LINE prime = 17 NEW_LINE printModIverses ( n , prime ) NEW_LINE"} {"text":"Convert to number with digits as 3 and 8 only | function for minimum operation ; remainder and operations count ; count digits not equal to 3 or 8 ; Driver code","code":"def minOp ( num ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num ) : NEW_LINE INDENT rem = num % 10 NEW_LINE if ( not ( rem == 3 or rem == 8 ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT num = num \/\/ 10 NEW_LINE DEDENT return count NEW_LINE DEDENT num = 234198 NEW_LINE print ( \" Minimum \u2581 Operations \u2581 = \" , minOp ( num ) ) NEW_LINE"} {"text":"Biggest integer which has maximum digit sum in range from 1 to n | function to calculate the sum of digits of a number . ; Returns the maximum number with maximum sum of digits . ; initializing b as 1 and initial max sum to be of n ; iterates from right to left in a digit ; while iterating this is the number from right to left ; calls the function to check if sum of cur is more then of ans ; reduces the number to one unit less ; driver program to test the above function","code":"def sumOfDigits ( a ) : NEW_LINE INDENT sm = 0 NEW_LINE while ( a != 0 ) : NEW_LINE INDENT sm = sm + a % 10 NEW_LINE a = a \/\/ 10 NEW_LINE DEDENT return sm NEW_LINE DEDENT def findMax ( x ) : NEW_LINE INDENT b = 1 NEW_LINE ans = x NEW_LINE while ( x != 0 ) : NEW_LINE INDENT cur = ( x - 1 ) * b + ( b - 1 ) NEW_LINE if ( sumOfDigits ( cur ) > sumOfDigits ( ans ) or ( sumOfDigits ( cur ) == sumOfDigits ( ans ) and cur > ans ) ) : NEW_LINE INDENT ans = cur NEW_LINE DEDENT x = x \/\/ 10 NEW_LINE b = b * 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 521 NEW_LINE print ( findMax ( n ) ) NEW_LINE"} {"text":"Interquartile Range ( IQR ) | Function to give index of the median ; Function to calculate IQR ; Index of median of entire data ; Median of first half ; Median of second half ; IQR calculation ; Driver Function","code":"def median ( a , l , r ) : NEW_LINE INDENT n = r - l + 1 NEW_LINE n = ( n + 1 ) \/\/ 2 - 1 NEW_LINE return n + l NEW_LINE DEDENT def IQR ( a , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE mid_index = median ( a , 0 , n ) NEW_LINE Q1 = a [ median ( a , 0 , mid_index ) ] NEW_LINE Q3 = a [ mid_index + median ( a , mid_index + 1 , n ) ] NEW_LINE return ( Q3 - Q1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 19 , 7 , 6 , 5 , 9 , 12 , 27 , 18 , 2 , 15 ] NEW_LINE n = len ( a ) NEW_LINE print ( IQR ( a , n ) ) NEW_LINE DEDENT"} {"text":"Largest palindromic number in an array | Function to check if n is palindrome ; Find the appropriate divisor to extract the leading digit ; If first and last digits are not same then return false ; Removing the leading and trailing digits from the number ; Reducing divisor by a factor of 2 as 2 digits are dropped ; Function to find the largest palindromic number ; Sort the array ; If number is palindrome ; If no palindromic number found ; Driver Code ; print required answer","code":"def isPalindrome ( n ) : NEW_LINE INDENT divisor = 1 NEW_LINE while ( n \/ divisor >= 10 ) : NEW_LINE INDENT divisor *= 10 NEW_LINE DEDENT while ( n != 0 ) : NEW_LINE INDENT leading = n \/\/ divisor NEW_LINE trailing = n % 10 NEW_LINE if ( leading != trailing ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = ( n % divisor ) \/\/ 10 NEW_LINE divisor = divisor \/\/ 100 NEW_LINE DEDENT return True NEW_LINE DEDENT def largestPalindrome ( A , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( isPalindrome ( A [ i ] ) ) : NEW_LINE INDENT return A [ i ] NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT A = [ 1 , 232 , 54545 , 999991 ] NEW_LINE n = len ( A ) NEW_LINE print ( largestPalindrome ( A , n ) ) NEW_LINE DEDENT"} {"text":"Sum of the multiples of two numbers below N | Function to return the sum of all the integers below N which are multiples of either A or B ; If i is a multiple of a or b ; Driver code","code":"def findSum ( n , a , b ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( i % a == 0 or i % b == 0 ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 10 NEW_LINE a = 3 NEW_LINE b = 5 NEW_LINE print ( findSum ( n , a , b ) ) NEW_LINE DEDENT"} {"text":"Subtract 1 without arithmetic operators | ''Driver code","code":"def subtractOne ( x ) : NEW_LINE INDENT return ( ( x << 1 ) + ( ~ x ) ) ; NEW_LINE DEDENT print ( subtractOne ( 13 ) ) ; NEW_LINE"} {"text":"Pell Number | Calculate nth pell number ; Driver function","code":"def pell ( n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return ( 2 * pell ( n - 1 ) + pell ( n - 2 ) ) NEW_LINE DEDENT n = 4 ; NEW_LINE print ( pell ( n ) ) NEW_LINE"} {"text":"Finding LCM of more than two ( or array ) numbers without using GCD | Returns LCM of arr [ 0. . n - 1 ] ; Find the maximum value in arr [ ] ; Initialize result ; Find all factors that are present in two or more array elements . x = 2 ; Current factor . ; To store indexes of all array elements that are divisible by x . ; If there are 2 or more array elements that are divisible by x . ; Reduce all array elements divisible by x . ; Then multiply all reduced array elements ; Driver code","code":"def LCM ( arr , n ) : NEW_LINE INDENT max_num = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max_num < arr [ i ] ) : NEW_LINE INDENT max_num = arr [ i ] ; NEW_LINE DEDENT DEDENT res = 1 ; NEW_LINE while ( x <= max_num ) : NEW_LINE INDENT indexes = [ ] ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( arr [ j ] % x == 0 ) : NEW_LINE INDENT indexes . append ( j ) ; NEW_LINE DEDENT DEDENT if ( len ( indexes ) >= 2 ) : NEW_LINE INDENT for j in range ( len ( indexes ) ) : NEW_LINE INDENT arr [ indexes [ j ] ] = int ( arr [ indexes [ j ] ] \/ x ) ; NEW_LINE DEDENT res = res * x ; NEW_LINE DEDENT else : NEW_LINE INDENT x += 1 ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT res = res * arr [ i ] ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 10 , 20 , 35 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( LCM ( arr , n ) ) ; NEW_LINE"} {"text":"Find politeness of a number | python program for the above approach ; Function to find politeness ; sqrt ( 2 * n ) as max length will be when the sum starts from 1 which follows the equation n ^ 2 - n - ( 2 * sum ) = 0 ; Driver program to test above function","code":"import math NEW_LINE def politness ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 2 , int ( math . sqrt ( 2 * n ) ) + 1 ) : NEW_LINE INDENT if ( ( 2 * n ) % i != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT a = 2 * n NEW_LINE a = a \/ i NEW_LINE a = a - ( i - 1 ) NEW_LINE if ( a % 2 != 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT a \/= 2 NEW_LINE if ( a > 0 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 90 NEW_LINE print \" Politness \u2581 of \u2581 \" , n , \" \u2581 = \u2581 \" , politness ( n ) NEW_LINE n = 15 NEW_LINE print \" Politness \u2581 of \u2581 \" , n , \" \u2581 = \u2581 \" , politness ( n ) NEW_LINE"} {"text":"Program for Goldbach\u00e2 \u20ac\u2122 s Conjecture ( Two Primes with given Sum ) | Python3 program to implement Goldbach 's conjecture ; Array to store all prime less than and equal to 10 ^ 6 ; Utility function for Sieve of Sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half . This array is used to separate numbers of the form i + j + 2 * i * j from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Function to perform Goldbach 's conjecture ; Return if number is not even or less than 3 ; Check only upto half of number ; find difference by subtracting current prime from n ; Search if the difference is also a prime number ; Express as a sum of primes ; Finding all prime numbers before limit ; Express number as a sum of two primes","code":"import math NEW_LINE MAX = 10000 ; NEW_LINE primes = [ ] ; NEW_LINE def sieveSundaram ( ) : NEW_LINE INDENT marked = [ False ] * ( int ( MAX \/ 2 ) + 100 ) ; NEW_LINE for i in range ( 1 , int ( ( math . sqrt ( MAX ) - 1 ) \/ 2 ) + 1 ) : NEW_LINE INDENT for j in range ( ( i * ( i + 1 ) ) << 1 , int ( MAX \/ 2 ) + 1 , 2 * i + 1 ) : NEW_LINE INDENT marked [ j ] = True ; NEW_LINE DEDENT DEDENT primes . append ( 2 ) ; NEW_LINE for i in range ( 1 , int ( MAX \/ 2 ) + 1 ) : NEW_LINE INDENT if ( marked [ i ] == False ) : NEW_LINE INDENT primes . append ( 2 * i + 1 ) ; NEW_LINE DEDENT DEDENT DEDENT def findPrimes ( n ) : NEW_LINE INDENT if ( n <= 2 or n % 2 != 0 ) : NEW_LINE INDENT print ( \" Invalid \u2581 Input \" ) ; NEW_LINE return ; NEW_LINE DEDENT i = 0 ; NEW_LINE while ( primes [ i ] <= n \/\/ 2 ) : NEW_LINE INDENT diff = n - primes [ i ] ; NEW_LINE if diff in primes : NEW_LINE INDENT print ( primes [ i ] , \" + \" , diff , \" = \" , n ) ; NEW_LINE return ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT DEDENT sieveSundaram ( ) ; NEW_LINE findPrimes ( 4 ) ; NEW_LINE findPrimes ( 38 ) ; NEW_LINE findPrimes ( 100 ) ; NEW_LINE"} {"text":"k | Python Program to print kth prime factor ; A function to generate prime factors of a given number n and return k - th prime factor ; Find the number of 2 's that divide k ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , store i and divide n ; This condition is to handle the case where n is a prime number greater than 2 ; Driver Program","code":"import math NEW_LINE def kPrimeFactor ( n , k ) : NEW_LINE INDENT while ( n % 2 == 0 ) : NEW_LINE INDENT k = k - 1 NEW_LINE n = n \/ 2 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT DEDENT i = 3 NEW_LINE while i <= math . sqrt ( n ) : NEW_LINE INDENT while ( n % i == 0 ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return i NEW_LINE DEDENT k = k - 1 NEW_LINE n = n \/ i NEW_LINE DEDENT i = i + 2 NEW_LINE DEDENT if ( n > 2 and k == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return - 1 NEW_LINE DEDENT n = 12 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k ) ) NEW_LINE n = 14 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k ) ) NEW_LINE"} {"text":"k | python3 program to find k - th prime factor using Sieve Of Eratosthenes . This program is efficient when we have a range of numbers . ; Using SieveOfEratosthenes to find smallest prime factor of all the numbers . For example , if MAX is 10 , s [ 2 ] = s [ 4 ] = s [ 6 ] = s [ 10 ] = 2 s [ 3 ] = s [ 9 ] = 3 s [ 5 ] = 5 s [ 7 ] = 7 ; Create a boolean array \" prime [ 0 . . MAX ] \" and initialize all entries in it as false . ; Initializing smallest factor equal to 2 for all the even numbers ; For odd numbers less then equal to n ; s ( i ) for a prime is the number itself ; For all multiples of current prime number ; i is the smallest prime factor for number \" i * j \" . ; Function to generate prime factors and return its k - th prime factor . s [ i ] stores least prime factor of i . ; Keep dividing n by least prime factor while either n is not 1 or count of prime factors is not k . ; To keep track of count of prime factors ; Divide n to find next prime factor ; s [ i ] is going to store prime factor of i .","code":"MAX = 10001 NEW_LINE def sieveOfEratosthenes ( s ) : NEW_LINE INDENT prime = [ False for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( 2 , MAX + 1 , 2 ) : NEW_LINE INDENT s [ i ] = 2 ; NEW_LINE DEDENT for i in range ( 3 , MAX , 2 ) : NEW_LINE INDENT if ( prime [ i ] == False ) : NEW_LINE INDENT s [ i ] = i NEW_LINE for j in range ( i , MAX + 1 , 2 ) : NEW_LINE INDENT if j * j > MAX : NEW_LINE INDENT break NEW_LINE DEDENT if ( prime [ i * j ] == False ) : NEW_LINE INDENT prime [ i * j ] = True NEW_LINE s [ i * j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def kPrimeFactor ( n , k , s ) : NEW_LINE INDENT while ( n > 1 ) : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return s [ n ] NEW_LINE DEDENT k -= 1 NEW_LINE n \/\/= s [ n ] NEW_LINE DEDENT return - 1 NEW_LINE DEDENT s = [ - 1 for i in range ( MAX + 1 ) ] NEW_LINE sieveOfEratosthenes ( s ) NEW_LINE n = 12 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k , s ) ) NEW_LINE n = 14 NEW_LINE k = 3 NEW_LINE print ( kPrimeFactor ( n , k , s ) ) NEW_LINE"} {"text":"Find sum of divisors of all the divisors of a natural number | Python3 program to find sum of divisors of all the divisors of a natural number . ; Returns sum of divisors of all the divisors of n ; Calculating powers of prime factors and storing them in a map mp [ ] . ; If n is a prime number ; For each prime factor , calculating ( p ^ ( a + 1 ) - 1 ) \/ ( p - 1 ) and adding it to answer . ; Driver Code","code":"import math as mt NEW_LINE def sumDivisorsOfDivisors ( n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for j in range ( 2 , mt . ceil ( mt . sqrt ( n ) ) ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n % j == 0 ) : NEW_LINE INDENT n \/\/= j NEW_LINE count += 1 NEW_LINE DEDENT if ( count ) : NEW_LINE INDENT mp [ j ] = count NEW_LINE DEDENT DEDENT if ( n != 1 ) : NEW_LINE INDENT mp [ n ] = 1 NEW_LINE DEDENT ans = 1 NEW_LINE for it in mp : NEW_LINE INDENT pw = 1 NEW_LINE summ = 0 NEW_LINE for i in range ( mp [ it ] + 1 , 0 , - 1 ) : NEW_LINE INDENT summ += ( i * pw ) NEW_LINE pw *= it NEW_LINE DEDENT ans *= summ NEW_LINE DEDENT return ans NEW_LINE DEDENT n = 10 NEW_LINE print ( sumDivisorsOfDivisors ( n ) ) NEW_LINE"} {"text":"Find Recurring Sequence in a Fraction | This function returns repeating sequence of a fraction . If repeating sequence doesn 't exits, then returns empty string ; Initialize result ; Create a map to store already seen remainders . Remainder is used as key and its position in result is stored as value . Note that we need position for cases like 1 \/ 6. In this case , the recurring sequence doesn 't start from first remainder. ; Find first remainder ; Keep finding remainder until either remainder becomes 0 or repeats ; Store this remainder ; Multiply remainder with 10 ; Append rem \/ denr to result ; Update remainder ; Driver code","code":"def fractionToDecimal ( numr , denr ) : NEW_LINE INDENT res = \" \" NEW_LINE mp = { } NEW_LINE rem = numr % denr NEW_LINE while ( ( rem != 0 ) and ( rem not in mp ) ) : NEW_LINE INDENT mp [ rem ] = len ( res ) NEW_LINE rem = rem * 10 NEW_LINE res_part = rem \/\/ denr NEW_LINE res += str ( res_part ) NEW_LINE rem = rem % denr NEW_LINE DEDENT if ( rem == 0 ) : NEW_LINE INDENT return \" \" NEW_LINE DEDENT else : NEW_LINE INDENT return res [ mp [ rem ] : ] NEW_LINE DEDENT DEDENT numr , denr = 50 , 22 NEW_LINE res = fractionToDecimal ( numr , denr ) NEW_LINE if ( res == \" \" ) : NEW_LINE INDENT print ( \" No \u2581 recurring \u2581 sequence \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" Recurring \u2581 sequence \u2581 is \" , res ) NEW_LINE DEDENT"} {"text":"Count numbers having 0 as a digit | Returns 1 if x has 0 , else 0 ; Traverse through all digits of x to check if it has 0. ; If current digit is 0 , return true ; Returns count of numbers from 1 to n with 0 as digit ; Initialize count of numbers having 0 as digit . ; Traverse through all numbers and for every number check if it has 0. ; Driver program","code":"def has0 ( x ) : NEW_LINE INDENT while ( x != 0 ) : NEW_LINE INDENT if ( x % 10 == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT x = x \/\/ 10 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def getCount ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT count = count + has0 ( i ) NEW_LINE DEDENT return count NEW_LINE DEDENT n = 107 NEW_LINE print ( \" Count \u2581 of \u2581 numbers \u2581 from \u2581 1\" , \" \u2581 to \u2581 \" , n , \" \u2581 is \u2581 \" , getCount ( n ) ) NEW_LINE"} {"text":"Euler 's criterion (Check if square root under modulo p exists) | Returns true if square root of n under modulo p exists ; One by one check all numbers from 2 to p - 1 ; Driver Code","code":"def squareRootExists ( n , p ) : NEW_LINE INDENT n = n % p NEW_LINE for x in range ( 2 , p , 1 ) : NEW_LINE INDENT if ( ( x * x ) % p == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT p = 7 NEW_LINE n = 2 NEW_LINE if ( squareRootExists ( n , p ) == True ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Legendre 's formula (Given p and n, find the largest x such that p^x divides n!) | Returns largest power of p that divides n ! ; Initialize result ; Calculate x = n \/ p + n \/ ( p ^ 2 ) + n \/ ( p ^ 3 ) + ... . ; Driver program","code":"def largestPower ( n , p ) : NEW_LINE INDENT x = 0 NEW_LINE while n : NEW_LINE INDENT n \/= p NEW_LINE x += n NEW_LINE DEDENT return x NEW_LINE DEDENT n = 10 ; p = 3 NEW_LINE print ( \" The largest power of % d that divides % d ! is % d \" % ( p , n , largestPower ( n , p ) ) ) NEW_LINE"} {"text":"Program for factorial of a number | Python 3 program to find factorial of given number ; single line to find factorial ; Driver Code","code":"def factorial ( n ) : NEW_LINE INDENT return 1 if ( n == 1 or n == 0 ) else n * factorial ( n - 1 ) NEW_LINE DEDENT num = 5 NEW_LINE print ( \" Factorial \u2581 of \" , num , \" is \" , factorial ( num ) ) NEW_LINE"} {"text":"All about Bit Manipulation | Function to get the bit at the ith position ; Return true if the bit is set . Otherwise return false","code":"def getBit ( num , i ) : NEW_LINE INDENT return ( ( num & ( 1 << i ) ) != 0 ) NEW_LINE DEDENT"} {"text":"All about Bit Manipulation | Function to clear the ith bit of the given number N ; Create the mask for the ith bit unset ; Return the update value","code":"def clearBit ( num , i ) : NEW_LINE INDENT mask = ~ ( 1 << i ) NEW_LINE return num & mask NEW_LINE DEDENT"} {"text":"Sum of Bitwise AND of each array element with the elements of another array | Function to compute the AND sum for each element of an array ; Declaring an array of size 32 for storing the count of each bit ; Traverse the array arr2 [ ] and store the count of a bit in frequency array ; Current bit position ; While num is greater than 0 ; Checks if ith bit is set or not ; Increment the count of bit by one ; Increment the bit position by one ; Right shift the num by one ; Traverse in the arr2 [ ] ; Store the ith bit value ; Total required sum ; Traverse in the range [ 0 , 31 ] ; Checks if current bit is set ; Increment the bitwise sum by frequency [ bit_position ] * value_at_that_bit ; Right shift num by one ; Left shift vale_at_that_bit by one ; Print sum obtained for ith number in arr1 [ ] ; Driver Code ; Given arr1 [ ] ; Given arr2 ; Size of arr1 [ ] ; Size of arr2 [ ] ; Function Call","code":"def Bitwise_AND_sum_i ( arr1 , arr2 , M , N ) : NEW_LINE INDENT frequency = [ 0 ] * 32 NEW_LINE for i in range ( N ) : NEW_LINE INDENT bit_position = 0 NEW_LINE num = arr1 [ i ] NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT frequency [ bit_position ] += 1 NEW_LINE DEDENT bit_position += 1 NEW_LINE num >>= 1 NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT num = arr2 [ i ] NEW_LINE value_at_that_bit = 1 NEW_LINE bitwise_AND_sum = 0 NEW_LINE for bit_position in range ( 32 ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT bitwise_AND_sum += frequency [ bit_position ] * value_at_that_bit NEW_LINE DEDENT num >>= 1 NEW_LINE value_at_that_bit <<= 1 NEW_LINE DEDENT print ( bitwise_AND_sum , end = \" \u2581 \" ) NEW_LINE DEDENT return NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 , 3 ] NEW_LINE arr2 = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE Bitwise_AND_sum_i ( arr1 , arr2 , M , N ) NEW_LINE DEDENT"} {"text":"Turn off the rightmost set bit | Set 2 | Unsets the rightmost set bit of n and returns the result ; Checking whether bit position is set or not ; If bit position is found set , we flip this bit by xoring given number and number with bit position set ; Driver code","code":"def FlipBits ( n ) : NEW_LINE INDENT for bit in range ( 32 ) : NEW_LINE INDENT if ( ( n >> bit ) & 1 ) : NEW_LINE INDENT n = n ^ ( 1 << bit ) NEW_LINE break NEW_LINE DEDENT DEDENT print ( \" The \u2581 number \u2581 after \u2581 unsetting \u2581 the \" , end = \" \u2581 \" ) NEW_LINE print ( \" rightmost \u2581 set \u2581 bit \" , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 ; NEW_LINE FlipBits ( N ) NEW_LINE DEDENT"} {"text":"Bitwise AND of all the odd numbers from 1 to N | Function to return the bitwise AND of all the odd integers from the range [ 1 , n ] ; Initialize result to 1 ; Starting from 3 , bitwise AND all the odd integers less than or equal to n ; Driver code","code":"def bitwiseAndOdd ( n ) : NEW_LINE INDENT result = 1 ; NEW_LINE for i in range ( 3 , n + 1 , 2 ) : NEW_LINE INDENT result = ( result & i ) ; NEW_LINE DEDENT return result ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 10 ; NEW_LINE print ( bitwiseAndOdd ( n ) ) ; NEW_LINE DEDENT"} {"text":"Bitwise AND of all the odd numbers from 1 to N | Function to return the bitwise AND of all the odd integers from the range [ 1 , n ] ; Driver code","code":"def bitwiseAndOdd ( n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT n = 10 NEW_LINE print ( bitwiseAndOdd ( n ) ) NEW_LINE"} {"text":"Ways to split array into two groups of same XOR value | Return the count of number of ways to split array into two groups such that each group has equal XOR value . ; We can split only if XOR is 0. Since XOR of all is 0 , we can consider all subsets as one group . ; Driver Program","code":"def countgroup ( a , n ) : NEW_LINE INDENT xs = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT xs = xs ^ a [ i ] NEW_LINE DEDENT if xs == 0 : NEW_LINE INDENT return ( 1 << ( n - 1 ) ) - 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT a = [ 1 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( countgroup ( a , n ) ) NEW_LINE"} {"text":"Extract ' k ' bits from a given position in a number . | Function to extract k bits from p position and returns the extracted value as integer ; number is from where ' k ' bits are extracted from p position","code":"def bitExtracted ( number , k , p ) : NEW_LINE INDENT return ( ( ( 1 << k ) - 1 ) & ( number >> ( p - 1 ) ) ) ; NEW_LINE DEDENT number = 171 NEW_LINE k = 5 NEW_LINE p = 2 NEW_LINE print \" The \u2581 extracted \u2581 number \u2581 is \u2581 \" , bitExtracted ( number , k , p ) NEW_LINE"} {"text":"Maximize a given unsigned number number by swapping bits at it 's extreme positions. | Python 3 program to find maximum number by swapping extreme bits . ; Traverse bits from both extremes ; Obtaining i - th and j - th bits ; Swapping the bits if lesser significant is greater than higher significant bit and accordingly modifying the number ; Driver code","code":"def findMax ( num ) : NEW_LINE INDENT num_copy = num NEW_LINE j = 4 * 8 - 1 ; NEW_LINE i = 0 NEW_LINE while ( i < j ) : NEW_LINE INDENT m = ( num_copy >> i ) & 1 NEW_LINE n = ( num_copy >> j ) & 1 NEW_LINE if ( m > n ) : NEW_LINE INDENT x = ( 1 << i 1 << j ) NEW_LINE num = num ^ x NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT num = 4 NEW_LINE print ( findMax ( num ) ) NEW_LINE DEDENT"} {"text":"Efficiently check whether n is a multiple of 4 or not | function to check whether ' n ' is a multiple of 4 or not ; if true , then ' n ' is a multiple of 4 ; else ' n ' is not a multiple of 4 ; Driver Code","code":"def isAMultipleOf4 ( n ) : NEW_LINE INDENT if ( ( n & 3 ) == 0 ) : NEW_LINE INDENT return \" Yes \" NEW_LINE DEDENT return \" No \" NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT n = 16 NEW_LINE print ( isAMultipleOf4 ( n ) ) NEW_LINE DEDENT"} {"text":"Calculate square of a number without using * , \/ and pow ( ) | Simple solution to calculate square without using * and pow ( ) ; handle negative input ; Initialize result ; Add n to res n - 1 times ; Driver Code","code":"def square ( n ) : NEW_LINE INDENT if ( n < 0 ) : NEW_LINE INDENT n = - n NEW_LINE DEDENT res = n NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res += n NEW_LINE DEDENT return res NEW_LINE DEDENT for n in range ( 1 , 6 ) : NEW_LINE INDENT print ( \" n \u2581 = \" , n , end = \" , \u2581 \" ) NEW_LINE print ( \" n ^ 2 \u2581 = \" , square ( n ) ) NEW_LINE DEDENT"} {"text":"Find a point that lies inside exactly K given squares | Python 3 implementation of the above approach ; Driver Code","code":"def PointInKSquares ( n , a , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE return a [ n - k ] NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT k = 2 NEW_LINE a = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( a ) NEW_LINE x = PointInKSquares ( n , a , k ) NEW_LINE print ( \" ( \" , x , \" , \" , x , \" ) \" ) NEW_LINE DEDENT"} {"text":"Number of n digit stepping numbers | Space optimized solution | function that calculates the answer ; dp [ j ] stores count of i digit stepping numbers ending with digit j . ; To store resu1lt of length i - 1 before updating dp [ j ] for length i . ; if n is 1 then answer will be 10. ; Initialize values for count of digits equal to 1. ; Compute values for count of digits more than 1. ; If ending digit is 0 ; If ending digit is 9 ; For other digits . ; stores the final answer ; Driver Code","code":"def answer ( n ) : NEW_LINE INDENT dp = [ 0 ] * 10 NEW_LINE prev = [ 0 ] * 10 NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 10 NEW_LINE DEDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT dp [ j ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT prev [ j ] = dp [ j ] NEW_LINE DEDENT for j in range ( 0 , 10 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT dp [ j ] = prev [ j + 1 ] NEW_LINE DEDENT elif ( j == 9 ) : NEW_LINE INDENT dp [ j ] = prev [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ j ] = prev [ j - 1 ] + prev [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT sum = 0 NEW_LINE for j in range ( 1 , 10 ) : NEW_LINE INDENT sum = sum + dp [ j ] NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 2 NEW_LINE print ( answer ( n ) ) NEW_LINE"} {"text":"Minimum changes required to make a Catalan Sequence | Python3 implementation of the approach ; To store first N Catalan numbers ; Function to find first n Catalan numbers ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Function to return the minimum changes required ; Find first n Catalan Numbers ; a and b are first two Catalan Sequence numbers ; Insert first n catalan elements to set ; If catalan element is present in the array then remove it from set ; Return the remaining number of elements in the set ; Driver code","code":"MAX = 100000 ; NEW_LINE catalan = [ 0 ] * MAX ; NEW_LINE def catalanDP ( n ) : NEW_LINE INDENT catalan [ 0 ] = catalan [ 1 ] = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT catalan [ i ] = 0 ; NEW_LINE for j in range ( i ) : NEW_LINE INDENT catalan [ i ] += ( catalan [ j ] * catalan [ i - j - 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT def CatalanSequence ( arr , n ) : NEW_LINE INDENT catalanDP ( n ) ; NEW_LINE s = set ( ) ; NEW_LINE a = 1 ; b = 1 ; NEW_LINE s . add ( a ) ; NEW_LINE if ( n >= 2 ) : NEW_LINE INDENT s . add ( b ) ; NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT s . add ( catalan [ i ] ) ; NEW_LINE DEDENT temp = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in s : NEW_LINE INDENT temp . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT s = s - temp ; NEW_LINE return len ( s ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 5 , 41 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( CatalanSequence ( arr , n ) ) ; NEW_LINE DEDENT"} {"text":"Sum of all the Composite Numbers from Odd indices of the given array | Function to print the sum of all composite numbers in the array ; Iterate for odd indices in the array ; Check if the number is composite then add it to sum ; return the sum ; Function to check for composite numbers ; Check if the factors are greater than 2 ; Check if the number is composite or not ; Driver code","code":"def odd_indices ( arr ) : NEW_LINE INDENT sum = 0 NEW_LINE for k in range ( 0 , len ( arr ) , 2 ) : NEW_LINE INDENT check = composite ( arr [ k ] ) NEW_LINE sum += arr [ k ] if check == 1 else 0 NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT def composite ( n ) : NEW_LINE INDENT flag = 0 NEW_LINE c = 0 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( n % j == 0 ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT if ( c >= 3 ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT return flag NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 13 , 5 , 8 , 16 , 25 ] NEW_LINE odd_indices ( arr ) NEW_LINE DEDENT"} {"text":"Queries on count of points lie inside a circle | Python 3 program to find number of points lie inside or on the circumference of circle for Q queries . ; Computing the x ^ 2 + y ^ 2 for each given points and sorting them . ; Return count of points lie inside or on circumference of circle using binary search on p [ 0. . n - 1 ] ; Driver Code ; Compute distances of all points and keep the distances sorted so that query can work in O ( logn ) using Binary Search . ; Print number of points in a circle of radius 3. ; Print number of points in a circle of radius 32.","code":"import math NEW_LINE def preprocess ( p , x , y , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT p [ i ] = x [ i ] * x [ i ] + y [ i ] * y [ i ] NEW_LINE DEDENT p . sort ( ) NEW_LINE DEDENT def query ( p , n , rad ) : NEW_LINE INDENT start = 0 NEW_LINE end = n - 1 NEW_LINE while ( ( end - start ) > 1 ) : NEW_LINE INDENT mid = ( start + end ) \/\/ 2 NEW_LINE tp = math . sqrt ( p [ mid ] ) NEW_LINE if ( tp > ( rad * 1.0 ) ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid NEW_LINE DEDENT DEDENT tp1 = math . sqrt ( p [ start ] ) NEW_LINE tp2 = math . sqrt ( p [ end ] ) NEW_LINE if ( tp1 > ( rad * 1.0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( tp2 <= ( rad * 1.0 ) ) : NEW_LINE INDENT return end + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return start + 1 NEW_LINE DEDENT DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT x = [ 1 , 2 , 3 , - 1 , 4 ] NEW_LINE y = [ 1 , 2 , 3 , - 1 , 4 ] NEW_LINE n = len ( x ) NEW_LINE p = [ 0 ] * n NEW_LINE preprocess ( p , x , y , n ) NEW_LINE print ( query ( p , n , 3 ) ) NEW_LINE print ( query ( p , n , 32 ) ) NEW_LINE DEDENT"} {"text":"Count of numbers of length N having prime numbers at odd indices and odd numbers at even indices | python program for above approach ; No of odd indices in N - digit number ; No of even indices in N - digit number ; No of ways of arranging prime number digits in odd indices ; No of ways of arranging odd number digits in even indices ; returning the total number of ways ; Driver code ; calling the function","code":"def count ( N ) : NEW_LINE INDENT odd_indices = N \/\/ 2 NEW_LINE even_indices = N \/\/ 2 + N % 2 NEW_LINE arrange_odd = 4 ** odd_indices NEW_LINE arrange_even = 5 ** even_indices NEW_LINE return arrange_odd * arrange_even NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 NEW_LINE print ( count ( N ) ) NEW_LINE DEDENT"} {"text":"Check if a given array is sorted in Spiral manner or not | Function to check if the array is spirally sorted or not ; Stores start index of the array ; Stores end index of an array ; If arr [ start ] greater than arr [ end ] ; Update start ; If arr [ end ] greater than arr [ start ] ; Update end ; Driver Code ; Function Call","code":"def isSpiralSorted ( arr , n ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = n - 1 ; NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( arr [ start ] > arr [ end ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT start += 1 ; NEW_LINE if ( arr [ end ] > arr [ start ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT end -= 1 ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 1 , 10 , 14 , 20 , 18 , 12 , 5 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE if ( isSpiralSorted ( arr , N ) ) : NEW_LINE INDENT print ( \" YES \" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) ; NEW_LINE DEDENT DEDENT"} {"text":"Print all strings from given array that can be typed using keys from a single row of a QWERTY keyboard | Function to print all strings that can be typed using keys of a single row in a QWERTY Keyboard ; Stores row number of all possible character of the strings ; Traverse the array ; If current string is not an empty string ; Sets true \/ false if a string can be typed using keys of a single row or not ; Stores row number of the first character of current string ; Stores length of word ; Traverse current string ; If current character can 't be typed using keys of rowNum only ; Update flag ; If current string can be typed using keys from rowNum only ; Print the string ; Driver Code","code":"def findWordsSameRow ( arr ) : NEW_LINE INDENT mp = { ' q ' : 1 , ' w ' : 1 , ' e ' : 1 , ' r ' : 1 , ' t ' : 1 , ' y ' : 1 , ' u ' : 1 , ' o ' : 1 , ' p ' : 1 , ' i ' : 1 , ' a ' : 2 , ' s ' : 2 , ' d ' : 2 , ' f ' : 2 , ' g ' : 2 , ' h ' : 2 , ' j ' : 2 , ' k ' : 2 , ' l ' : 2 , ' z ' : 3 , ' x ' : 3 , ' c ' : 3 , ' v ' : 3 , ' b ' : 3 , ' n ' : 3 , ' m ' : 3 } NEW_LINE for word in arr : NEW_LINE INDENT if ( len ( word ) != 0 ) : NEW_LINE INDENT flag = True NEW_LINE rowNum = mp [ word [ 0 ] . lower ( ) ] NEW_LINE M = len ( word ) NEW_LINE for i in range ( 1 , M ) : NEW_LINE INDENT if ( mp [ word [ i ] . lower ( ) ] != rowNum ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT print ( word , end = ' \u2581 ' ) NEW_LINE DEDENT DEDENT DEDENT DEDENT words = [ \" Yeti \" , \" Had \" , \" GFG \" , \" comment \" ] NEW_LINE findWordsSameRow ( words ) NEW_LINE"} {"text":"Count quadruples of given type from given array | Python3 program of the above approach ; Function to find the count of the subsequence of given type ; Stores the count of quadruples ; Generate all possible combinations of quadruples ; Check if 1 st element is equal to 3 rd element ; Check if 2 nd element is equal to 4 th element ; Driver Code","code":"maxN = 2002 NEW_LINE def countSubsequece ( a , n ) : NEW_LINE INDENT answer = 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 + 1 , n ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT if ( a [ j ] == a [ l ] and a [ i ] == a [ k ] ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 2 , 3 , 2 , 1 , 3 , 2 ] NEW_LINE print ( countSubsequece ( a , 7 ) ) NEW_LINE DEDENT"} {"text":"Smallest character in a string having minimum sum of distances between consecutive repetitions | Python3 program for the above approach ; Function to find the character repeats with minimum distance ; Stores the first and last index ; Intialize with - 1 ; Get the values of last and first occurence ; Update the first index ; Update the last index ; Intialize the min ; Get the minimum ; Values must not be same ; Update the minimum distance ; return ans ; Driver Code ; Function call","code":"import sys NEW_LINE def minDistChar ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE first = [ ] NEW_LINE last = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT first . append ( - 1 ) NEW_LINE last . append ( - 1 ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( first [ ord ( s [ i ] ) - ord ( ' a ' ) ] == - 1 ) : NEW_LINE INDENT first [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT last [ ord ( s [ i ] ) - ord ( ' a ' ) ] = i NEW_LINE DEDENT min = sys . maxsize NEW_LINE ans = '1' NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( last [ i ] == first [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( min > last [ i ] - first [ i ] ) : NEW_LINE INDENT min = last [ i ] - first [ i ] NEW_LINE ans = i + ord ( ' a ' ) NEW_LINE DEDENT DEDENT return chr ( ans ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT str = \" geeksforgeeks \" NEW_LINE print ( minDistChar ( str ) ) NEW_LINE DEDENT"} {"text":"Minimum steps required to reach the end of a matrix | Set 2 | Python 3 implementation of the approach ; Function to return the minimum steps required to reach the end of the matrix ; Array to determine whether a cell has been visited before ; Queue for bfs ; To store the depth of search ; BFS algorithm ; Current queue size ; Top - most element of queue ; To store index of cell for simplicity ; Base case ; If we reach ( n - 1 , n - 1 ) ; Marking the cell visited ; Pushing the adjacent cells in the queue that can be visited from the current cell ; Driver code","code":"n = 3 NEW_LINE def minSteps ( arr ) : NEW_LINE INDENT v = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE q = [ [ 0 , 0 ] ] NEW_LINE depth = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT x = len ( q ) NEW_LINE while ( x > 0 ) : NEW_LINE INDENT y = q [ 0 ] NEW_LINE i = y [ 0 ] NEW_LINE j = y [ 1 ] NEW_LINE q . remove ( q [ 0 ] ) NEW_LINE x -= 1 NEW_LINE if ( v [ i ] [ j ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( i == n - 1 and j == n - 1 ) : NEW_LINE INDENT return depth NEW_LINE DEDENT v [ i ] [ j ] = 1 NEW_LINE if ( i + arr [ i ] [ j ] < n ) : NEW_LINE INDENT q . append ( [ i + arr [ i ] [ j ] , j ] ) NEW_LINE DEDENT if ( j + arr [ i ] [ j ] < n ) : NEW_LINE INDENT q . append ( [ i , j + arr [ i ] [ j ] ] ) NEW_LINE DEDENT DEDENT depth += 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] , [ 1 , 1 , 1 ] ] NEW_LINE print ( minSteps ( arr ) ) NEW_LINE DEDENT"} {"text":"Largest gap in an array | A Python 3 program to find largest gap between two elements in an array . ; function to solve the given problem ; Driver Code","code":"import sys NEW_LINE def solve ( a , n ) : NEW_LINE INDENT max1 = - sys . maxsize - 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT for j in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( abs ( a [ i ] - a [ j ] ) > max1 ) : NEW_LINE INDENT max1 = abs ( a [ i ] - a [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return max1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 1 , 2 , 3 , - 4 , - 10 , 22 ] NEW_LINE size = len ( arr ) NEW_LINE print ( \" Largest \u2581 gap \u2581 is \u2581 : \" , solve ( arr , size ) ) NEW_LINE DEDENT"} {"text":"Largest gap in an array | function to solve the given problem ; finding maximum and minimum of an array ; Driver code","code":"def solve ( a , n ) : NEW_LINE INDENT min1 = a [ 0 ] NEW_LINE max1 = a [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > max1 ) : NEW_LINE INDENT max1 = a [ i ] NEW_LINE DEDENT if ( a [ i ] < min1 ) : NEW_LINE INDENT min1 = a [ i ] NEW_LINE DEDENT DEDENT return abs ( min1 - max1 ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ - 1 , 2 , 3 , 4 , - 10 ] NEW_LINE size = len ( arr ) NEW_LINE print ( \" Largest \u2581 gap \u2581 is \u2581 : \u2581 \" , solve ( arr , size ) ) NEW_LINE DEDENT"} {"text":"Print reverse string after removing vowels | Function for replacing the string ; initialize a string of length n ; Traverse through all characters of string ; assign the value to string r from last index of string s ; if s [ i ] is a consonant then print r [ i ] ; Driver Code","code":"def replaceOriginal ( s , n ) : NEW_LINE INDENT r = [ ' \u2581 ' ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT r [ i ] = s [ n - 1 - i ] NEW_LINE if ( s [ i ] != ' a ' and s [ i ] != ' e ' and s [ i ] != ' i ' and s [ i ] != ' o ' and s [ i ] != ' u ' ) : NEW_LINE INDENT print ( r [ i ] , end = \" \" ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT s = \" geeksforgeeks \" NEW_LINE n = len ( s ) NEW_LINE replaceOriginal ( s , n ) NEW_LINE DEDENT"} {"text":"Check if a string can be made equal to another string by swapping or replacement of characters | Function to find if given strings are same or not ; Base Condition ; Stores frequency of characters of the str1 and str2 ; Traverse strings str1 & str2 and store frequencies in a [ ] and b [ ] ; Check if both strings have same characters or not ; If a character is present in one and is not in another string , return false ; Sort the array a [ ] and b [ ] ; Check arrays a and b contain the same frequency or not ; If the frequencies are not the same after sorting ; At this point , str1 can be converted to str2 ; Driver Code","code":"def sameStrings ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE M = len ( str2 ) NEW_LINE if ( N != M ) : NEW_LINE INDENT return False NEW_LINE DEDENT a , b = [ 0 ] * 256 , [ 0 ] * 256 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a [ ord ( str1 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE b [ ord ( str2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT i = 0 NEW_LINE while ( i < 256 ) : NEW_LINE INDENT if ( ( a [ i ] == 0 and b [ i ] == 0 ) or ( a [ i ] != 0 and b [ i ] != 0 ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT a = sorted ( a ) NEW_LINE b = sorted ( b ) NEW_LINE for i in range ( 256 ) : NEW_LINE INDENT if ( a [ i ] != b [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 , S2 = \" cabbba \" , \" abbccc \" NEW_LINE if ( sameStrings ( S1 , S2 ) ) : NEW_LINE INDENT print ( \" YES \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" NO \" ) NEW_LINE DEDENT DEDENT"} {"text":"Reduce given three Numbers by decrementing in Pairs | Function to find the minimum number operations ; Insert the three numbers in array ; Sort the array ; Case 2 ; Case 1 ; Driver Code ; Given A , B , C ; Function Call","code":"def solution ( A , B , C ) : NEW_LINE INDENT arr = [ 0 ] * 3 NEW_LINE arr [ 0 ] = A NEW_LINE arr [ 1 ] = B NEW_LINE arr [ 2 ] = C NEW_LINE arr = sorted ( arr ) NEW_LINE if ( arr [ 2 ] < arr [ 0 ] + arr [ 1 ] ) : NEW_LINE INDENT return ( ( arr [ 0 ] + arr [ 1 ] + arr [ 2 ] ) \/\/ 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( arr [ 0 ] + arr [ 1 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 8 NEW_LINE B = 1 NEW_LINE C = 5 NEW_LINE print ( solution ( A , B , C ) ) NEW_LINE DEDENT"} {"text":"Search an element in a sorted and rotated array with duplicates | Function to return the index of the key in arr [ l . . h ] if the key is present otherwise return - 1 ; The tricky case , just update left and right ; If arr [ l ... mid ] is sorted ; As this subarray is sorted , we can quickly check if key lies in any of the halves ; If key does not lie in the first half subarray then divide the other half into two subarrays such that we can quickly check if key lies in the other half ; If arr [ l . . mid ] first subarray is not sorted then arr [ mid ... h ] must be sorted subarray ; Driver code","code":"def search ( arr , l , h , key ) : NEW_LINE INDENT if ( l > h ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT mid = ( l + h ) \/\/ 2 ; NEW_LINE if ( arr [ mid ] == key ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT if ( ( arr [ l ] == arr [ mid ] ) and ( arr [ h ] == arr [ mid ] ) ) : NEW_LINE INDENT l += 1 ; NEW_LINE h -= 1 ; NEW_LINE return search ( arr , l , h , key ) NEW_LINE DEDENT if ( arr [ l ] <= arr [ mid ] ) : NEW_LINE INDENT if ( key >= arr [ l ] and key <= arr [ mid ] ) : NEW_LINE INDENT return search ( arr , l , mid - 1 , key ) ; NEW_LINE DEDENT return search ( arr , mid + 1 , h , key ) ; NEW_LINE DEDENT if ( key >= arr [ mid ] and key <= arr [ h ] ) : NEW_LINE INDENT return search ( arr , mid + 1 , h , key ) ; NEW_LINE DEDENT return search ( arr , l , mid - 1 , key ) ; NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT arr = [ 3 , 3 , 1 , 2 , 3 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE key = 3 ; NEW_LINE print ( search ( arr , 0 , n - 1 , key ) ) ; NEW_LINE DEDENT"} {"text":"Case | Function to return the sorted string ; Vectors to store the lowercase and uppercase characters ; Sort both the vectors ; If current character is lowercase then pick the lowercase character from the sorted list ; Else pick the uppercase character ; Return the sorted string ; Driver code","code":"def getSortedString ( s , n ) : NEW_LINE INDENT v1 = [ ] NEW_LINE v2 = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] >= ' a ' and s [ i ] <= ' z ' ) : NEW_LINE INDENT v1 . append ( s [ i ] ) NEW_LINE DEDENT if ( s [ i ] >= ' A ' and s [ i ] <= ' Z ' ) : NEW_LINE INDENT v2 . append ( s [ i ] ) NEW_LINE DEDENT DEDENT v1 = sorted ( v1 ) NEW_LINE v2 = sorted ( v2 ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE for k in range ( n ) : NEW_LINE INDENT if ( s [ k ] >= ' a ' and s [ k ] <= ' z ' ) : NEW_LINE INDENT s [ k ] = v1 [ i ] NEW_LINE i += 1 NEW_LINE DEDENT elif ( s [ k ] >= ' A ' and s [ k ] <= ' Z ' ) : NEW_LINE INDENT s [ k ] = v2 [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return \" \" . join ( s ) NEW_LINE DEDENT s = \" gEeksfOrgEEkS \" NEW_LINE ss = [ i for i in s ] NEW_LINE n = len ( ss ) NEW_LINE print ( getSortedString ( ss , n ) ) NEW_LINE"} {"text":"Check if the string contains consecutive letters and each letter occurs exactly once | Function to check if the condition holds ; Get the length of the string ; sort the given string ; Iterate for every index and check for the condition ; If are not consecutive ; Driver code ; 1 st example ; 2 nd example","code":"def check ( s ) : NEW_LINE INDENT l = len ( s ) NEW_LINE s = ' ' . join ( sorted ( s ) ) NEW_LINE for i in range ( 1 , l ) : NEW_LINE INDENT if ord ( s [ i ] ) - ord ( s [ i - 1 ] ) != 1 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT string = \" dcef \" NEW_LINE if check ( string ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT string = \" xyza \" NEW_LINE if check ( string ) : NEW_LINE INDENT print ( \" Yes \" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT"} {"text":"Smallest subset with sum greater than all other elements | function to find minimum elements needed . ; calculating HALF of array sum ; sort the array in descending order . ; current sum greater than sum ; driver code","code":"def minElements ( arr , n ) : NEW_LINE INDENT halfSum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT halfSum = halfSum + arr [ i ] NEW_LINE DEDENT halfSum = int ( halfSum \/ 2 ) NEW_LINE arr . sort ( reverse = True ) NEW_LINE res = 0 NEW_LINE curr_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE res += 1 NEW_LINE if curr_sum > halfSum : NEW_LINE INDENT return res NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 1 , 7 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minElements ( arr , n ) ) NEW_LINE"} {"text":"Minimum increment and decrement by K of each pair elements required to make all array elements equal | Function to check if its possible to make all array elements equal or not ; Stores the sum of the array ; Traverse the array ; If sum is divisible by N ; Otherwise , not possible to make all array elements equal ; Given array ; Size of the array","code":"def arrayElementEqual ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % N == 0 ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( \" No \" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 5 , 6 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE arrayElementEqual ( arr , N ) NEW_LINE"} {"text":"Rearrange array to maximize sum of GCD of array elements with their respective indices | Function to find the maximum sum of GCD ( arr [ i ] , i ) by rearranging the array ; Stores maximum sum of GCD ( arr [ i ] , i ) by rearranging the array elements ; Update res ; Driver Code","code":"def findMaxValByRearrArr ( arr , N ) : NEW_LINE INDENT res = 0 ; NEW_LINE res = ( N * ( N + 1 ) ) \/\/ 2 ; NEW_LINE return res ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( findMaxValByRearrArr ( arr , N ) ) ; NEW_LINE DEDENT"} {"text":"Polygon with maximum sides that can be inscribed in an N | Function to find the maximum sided polygon that can be inscribed ; Base Case ; Return n \/ 2 if n is even Otherwise , return - 1 ; Driver Code ; Given N ; Function Call","code":"def MaximumSides ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT return n \/\/ 2 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE print ( MaximumSides ( N ) ) NEW_LINE DEDENT"} {"text":"Mean of array generated by products of all pairs of the given array | Function to find the mean of pair product array of arr [ ] ; Initializing suffix sum array ; Build suffix sum array ; Size of pairProductArray ; Stores sum of pairProductArray ; Store the mean ; Find mean of pairProductArray ; Return the resultant mean ; Driver Code ; Given array arr [ ] ; Function Call","code":"def pairProductMean ( arr , N ) : NEW_LINE INDENT suffixSumArray = [ 0 ] * N NEW_LINE suffixSumArray [ N - 1 ] = arr [ N - 1 ] NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffixSumArray [ i ] = suffixSumArray [ i + 1 ] + arr [ i ] NEW_LINE DEDENT length = ( N * ( N - 1 ) ) \/\/ 2 NEW_LINE res = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT res += arr [ i ] * suffixSumArray [ i + 1 ] NEW_LINE DEDENT mean = 0 NEW_LINE if ( length != 0 ) : NEW_LINE INDENT mean = res \/ length NEW_LINE DEDENT else : NEW_LINE INDENT mean = 0 NEW_LINE DEDENT return mean NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( round ( pairProductMean ( arr , N ) , 2 ) ) NEW_LINE DEDENT"} {"text":"Minimize count of unique paths from top left to bottom right of a Matrix by placing K 1 s | Function to 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 find the minimum count of paths from top left to bottom right by placing K 1 s in the matrix ; Count of ways without 1 s ; Count of paths from starting poto mid point ; Count of paths from mid poto end point ; Driver Code","code":"def ncr ( 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 countPath ( N , M , K ) : NEW_LINE INDENT answer = 0 NEW_LINE if ( K >= 2 ) : NEW_LINE INDENT answer = 0 NEW_LINE DEDENT elif ( K == 0 ) : NEW_LINE INDENT answer = ncr ( N + M - 2 , N - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT answer = ncr ( N + M - 2 , N - 1 ) NEW_LINE X = ( N - 1 ) \/\/ 2 + ( M - 1 ) \/\/ 2 NEW_LINE Y = ( N - 1 ) \/\/ 2 NEW_LINE midCount = ncr ( X , Y ) NEW_LINE X = ( ( N - 1 ) - ( N - 1 ) \/\/ 2 ) + NEW_LINE INDENT ( ( M - 1 ) - ( M - 1 ) \/\/ 2 ) NEW_LINE DEDENT Y = ( ( N - 1 ) - ( N - 1 ) \/\/ 2 ) NEW_LINE midCount *= ncr ( X , Y ) NEW_LINE answer -= midCount NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE M = 3 NEW_LINE K = 1 NEW_LINE print ( countPath ( N , M , K ) ) NEW_LINE DEDENT"} {"text":"Maximum number of operations required such that no pairs from a Matrix overlap | Function to find maximum count of operations ; Initialize count by 0 ; Iterate over remaining pairs ; Check if first operation is applicable ; Check if 2 nd operation is applicable ; Otherwise ; Return the count of operations ; Driver Code","code":"def find_max ( v , n ) : NEW_LINE INDENT count = 0 NEW_LINE if ( n >= 2 ) : NEW_LINE INDENT count = 2 NEW_LINE DEDENT else : NEW_LINE INDENT count = 1 NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( v [ i - 1 ] [ 0 ] > ( v [ i ] [ 0 ] + v [ i ] [ 1 ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT elif ( v [ i + 1 ] [ 0 ] > ( v [ i ] [ 0 ] + v [ i ] [ 1 ] ) ) : NEW_LINE INDENT count += 1 NEW_LINE v [ i ] [ 0 ] = v [ i ] [ 0 ] + v [ i ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 3 NEW_LINE v = [ ] NEW_LINE v . append ( [ 10 , 20 ] ) NEW_LINE v . append ( [ 15 , 10 ] ) NEW_LINE v . append ( [ 20 , 16 ] ) NEW_LINE print ( find_max ( v , n ) ) NEW_LINE"} {"text":"Count of substrings formed using a given set of characters only | Function to find the number of substrings that can be formed using given characters ; Boolean array for storing the available characters ; Mark indices of all available characters as 1 ; Initialize lastPos as - 1 ; Initialize ans with the total no of possible substrings ; Traverse the string from left to right ; If the current character is not present in B ; Subtract the total possible substrings ; Update the value of lastpos to current index ; Print the final answer ; Given String ; Given character array ; Function call","code":"def numberofsubstrings ( str , k , charArray ) : NEW_LINE INDENT N = len ( str ) NEW_LINE available = [ 0 ] * 26 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT available [ ord ( charArray [ i ] ) - ord ( ' a ' ) ] = 1 NEW_LINE DEDENT lastPos = - 1 NEW_LINE ans = ( N * ( N + 1 ) ) \/ 2 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( available [ ord ( str [ i ] ) - ord ( ' a ' ) ] == 0 ) : NEW_LINE INDENT ans -= ( ( i - lastPos ) * ( N - i ) ) NEW_LINE lastPos = i NEW_LINE DEDENT DEDENT print ( int ( ans ) ) NEW_LINE DEDENT str = \" abcb \" NEW_LINE k = 2 NEW_LINE charArray = [ ' a ' , ' b ' ] NEW_LINE numberofsubstrings ( str , k , charArray ) NEW_LINE"} {"text":"Minimum cost to reach a point N from 0 with two different operations allowed | Function to return minimum cost to reach destination ; Initialize cost to 0 ; going backwards until we reach initial position ; if 2 * X jump is better than X + 1 ; if X + 1 jump is better ; Driver program","code":"def minCost ( N , P , Q ) : NEW_LINE INDENT cost = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N & 1 ) : NEW_LINE INDENT cost += P NEW_LINE N -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp = N \/\/ 2 ; NEW_LINE if ( temp * P > Q ) : NEW_LINE INDENT cost += Q NEW_LINE DEDENT else : NEW_LINE INDENT cost += P * temp NEW_LINE DEDENT N \/\/= 2 NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT N = 9 NEW_LINE P = 5 NEW_LINE Q = 1 NEW_LINE print ( minCost ( N , P , Q ) ) NEW_LINE"} {"text":"Number of ways to reach at starting node after travelling through exactly K edges in a complete graph | Function to find number of ways to reach from node 1 to 1 again , after moving exactly K edges ; Initialize a dp [ ] array , where dp [ i ] stores number of ways to reach at a i node ; Base Case ; Iterate for the number of edges moved ; Sum will store number of ways to reach all the nodes ; Iterate for every possible state for the current step ; Update the value of the dp array after travelling each edge ; Print dp [ 0 ] as the answer ; Driver Code ; Given Input ; Function Call","code":"def numberOfWays ( n , k ) : NEW_LINE INDENT dp = [ 0 for i in range ( 1000 ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , k + 1 , 1 ) : NEW_LINE INDENT numWays = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT numWays += dp [ j ] NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT dp [ j ] = numWays - dp [ j ] NEW_LINE DEDENT DEDENT print ( dp [ 0 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE numberOfWays ( N , K ) NEW_LINE DEDENT"} {"text":"Minimum cost of purchasing at least X chocolates | Function to calculate minimum cost of buying least X chocolates ; Base Case ; Include the i - th box ; Exclude the i - th box ; Return the minimum of the above two cases ; Driver Code ; Given array and value of X ; Store the size of the array ; Print answer","code":"def findMinCost ( arr , X , n , i = 0 ) : NEW_LINE INDENT if ( X <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i >= n ) : NEW_LINE INDENT return 10 ** 8 NEW_LINE DEDENT inc = findMinCost ( arr , X - arr [ i ] [ 0 ] , n , i + 1 ) NEW_LINE if ( inc != 10 ** 8 ) : NEW_LINE INDENT inc += arr [ i ] [ 1 ] NEW_LINE DEDENT exc = findMinCost ( arr , X , n , i + 1 ) NEW_LINE return min ( inc , exc ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 4 , 3 ] , [ 3 , 2 ] , [ 2 , 4 ] , [ 1 , 3 ] , [ 4 , 2 ] ] NEW_LINE X = 7 NEW_LINE n = len ( arr ) NEW_LINE ans = findMinCost ( arr , X , n ) NEW_LINE if ( ans != 10 ** 8 ) : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT"} {"text":"Probability that the sum of all numbers obtained on throwing a dice N times lies between two given integers | Function to calculate the probability for the given sum to be equal to sum in N throws of dice ; Base cases ; Driver Code ; Print the answer","code":"def find ( N , sum ) : NEW_LINE INDENT if ( sum > 6 * N or sum < N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N == 1 ) : NEW_LINE INDENT if ( sum >= 1 and sum <= 6 ) : NEW_LINE INDENT return 1.0 \/ 6 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT s = 0 NEW_LINE for i in range ( 1 , 7 ) : NEW_LINE INDENT s = s + find ( N - 1 , sum - i ) \/ 6 NEW_LINE DEDENT return s NEW_LINE DEDENT if __name__ == \" _ _ main _ _ \" : NEW_LINE INDENT N = 4 NEW_LINE a = 13 NEW_LINE b = 17 NEW_LINE probability = 0.0 NEW_LINE for sum in range ( a , b + 1 ) : NEW_LINE INDENT probability = probability + find ( N , sum ) NEW_LINE DEDENT print ( round ( probability , 6 ) ) NEW_LINE DEDENT"} {"text":"Minimum steps to reduce N to 0 by given operations | Function to find the minimum number to steps to reduce N to 0 ; Base case ; Recursive Call to count the minimum steps needed ; Return the answer ; Given Number N ; Function Call","code":"def minDays ( n ) : NEW_LINE INDENT if n < 1 : NEW_LINE INDENT return n NEW_LINE DEDENT cnt = 1 + min ( n % 2 + minDays ( n \/\/ 2 ) , n % 3 + minDays ( n \/\/ 3 ) ) NEW_LINE return cnt NEW_LINE DEDENT N = 6 NEW_LINE print ( str ( minDays ( N ) ) ) NEW_LINE"}