text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Check if two people starting from different points ever meet | Python3 program to find if two people starting from different positions ever meet or not . ; If speed of a person at a position before other person is smaller , then return false . ; Making sure that x1 is greater ; checking if relative speed is a factor of relative distance or not ; ; Driver code | def everMeet ( x1 , x2 , v1 , v2 ) : NEW_LINE INDENT if ( x1 < x2 and v1 <= v2 ) : NEW_LINE INDENT return False ; NEW_LINE if ( x1 > x2 and v1 >= v2 ) : NEW_LINE INDENT return False ; NEW_LINE if ( x1 < x2 ) : NEW_LINE INDENT swap ( x1 , x2 ) NEW_LINE swap ( v1 , v2 ) NEW_LINE return ( ( x1 - x2 ) % ( v1 - v2 ) == 0 ) NEW_LINE def swap ( a , b ) : NEW_LINE INDENT t = a NEW_LINE a = b NEW_LINE b = t NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def main ( ) : NEW_LINE INDENT x1 , v1 , x2 , v2 = 5 , 8 , 4 , 7 NEW_LINE if ( everMeet ( x1 , x2 , v1 , v2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Count of distinct GCDs among all the non | Python 3 program for the above approach ; Function to calculate the number of distinct GCDs among all non - empty subsequences of an array ; variables to store the largest element in array and the required count ; Map to store whether a number is present in A ; calculate largest number in A and mapping A to Mp ; iterate over all possible values of GCD ; variable to check current GCD ; iterate over all multiples of i ; If j is present in A ; calculate gcd of all encountered multiples of i ; current GCD is possible ; return answer ; Driver code ; Input ; Function calling | from math import gcd NEW_LINE def distinctGCDs ( arr , N ) : NEW_LINE INDENT M = - 1 NEW_LINE ans = 0 NEW_LINE Mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT M = max ( M , arr [ i ] ) NEW_LINE Mp [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT currGcd = 0 NEW_LINE for j in range ( i , M + 1 , i ) : NEW_LINE INDENT if ( j in Mp ) : NEW_LINE INDENT currGcd = gcd ( currGcd , j ) NEW_LINE if ( currGcd == i ) : NEW_LINE INDENT ans += 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 11 , 14 , 6 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE print ( distinctGCDs ( arr , N ) ) NEW_LINE DEDENT |
Find ceil of a / b without using ceil ( ) function | Python3 program to find math . ceil ( a / b ) without using math . ceil ( ) function ; taking input 1 ; example of perfect division taking input 2 | import math NEW_LINE a = 4 ; NEW_LINE b = 3 ; NEW_LINE val = ( a + b - 1 ) / b ; NEW_LINE print ( " The β ceiling β value β of β 4/3 β is β " , math . floor ( val ) ) ; NEW_LINE a = 6 ; NEW_LINE b = 3 ; NEW_LINE val = ( a + b - 1 ) / b ; NEW_LINE print ( " The β ceiling β value β of β 6/3 β is β " , math . floor ( val ) ) ; NEW_LINE |
Sum of range in a series of first odd then even natural numbers | Python 3 program to find sum in the given range in the sequence 1 3 5 7 ... . . N 2 4 6. . . N - 1 ; Function that returns sum in the range 1 to x in the sequence 1 3 5 7. ... . N 2 4 6. . . N - 1 ; number of odd numbers ; number of extra even numbers required ; Driver code | import math NEW_LINE def sumTillX ( x , n ) : NEW_LINE INDENT odd = math . ceil ( n / 2.0 ) NEW_LINE if ( x <= odd ) : NEW_LINE INDENT return x * x ; NEW_LINE DEDENT even = x - odd ; NEW_LINE return ( ( odd * odd ) + ( even * even ) + even ) ; NEW_LINE DEDENT def rangeSum ( N , L , R ) : NEW_LINE INDENT return ( sumTillX ( R , N ) - sumTillX ( L - 1 , N ) ) ; NEW_LINE DEDENT N = 10 NEW_LINE L = 1 NEW_LINE R = 6 NEW_LINE print ( rangeSum ( N , L , R ) ) NEW_LINE |
Twin Prime Numbers between 1 and n | Python program to illustrate ... To print total number of twin prime using Sieve of Eratosthenes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; check twin prime numbers display the twin prime numbers ; driver program ; Calling the function | def printTwinPrime ( n ) : NEW_LINE INDENT prime = [ True for i in range ( n + 2 ) ] NEW_LINE p = 2 NEW_LINE while ( p * p <= n + 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * 2 , n + 2 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , n - 1 ) : NEW_LINE INDENT if prime [ p ] and prime [ p + 2 ] : NEW_LINE INDENT print ( " ( " , p , " , " , ( p + 2 ) , " ) " , end = ' ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 25 NEW_LINE printTwinPrime ( n ) NEW_LINE DEDENT |
Cube Free Numbers smaller than n | Python3 Program to print all cube free numbers smaller than or equal to n . ; Returns true if n is a cube free number , else returns false . ; check for all possible divisible cubes ; Print all cube free numbers smaller than n . ; Driver program | import math NEW_LINE def isCubeFree ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 2 , int ( n ** ( 1 / 3 ) + 1 ) ) : NEW_LINE INDENT if ( n % ( i * i * i ) == 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT def printCubeFree ( n ) : NEW_LINE INDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( isCubeFree ( i ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT n = 20 NEW_LINE printCubeFree ( n ) NEW_LINE |
Decimal Equivalent of Gray Code and its Inverse | Function to convert given decimal number of gray code into its inverse in decimal form ; Taking xor until n becomes zero ; Driver Code | def inversegrayCode ( n ) : NEW_LINE INDENT inv = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT inv = inv ^ n ; NEW_LINE n = n >> 1 ; NEW_LINE DEDENT return inv ; NEW_LINE DEDENT n = 15 ; NEW_LINE print ( inversegrayCode ( n ) ) ; NEW_LINE |
Product of unique prime factors of a number | Python program to find product of unique prime factors of a number ; A function to print all prime factors of a given number n ; Handle prime factor 2 explicitly so that can optimally handle other prime factors . ; n must be odd at this point . So we can skip one element ( Note i = i + 2 ) ; While i divides n , print i and divide n ; This condition is to handle the case when n is a prime number greater than 2 ; Driver Code | import math NEW_LINE def productPrimeFactors ( n ) : NEW_LINE INDENT product = 1 NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT product *= 2 NEW_LINE while ( n % 2 == 0 ) : NEW_LINE INDENT n = n / 2 NEW_LINE DEDENT DEDENT for i in range ( 3 , int ( math . sqrt ( n ) ) + 1 , 2 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT product = product * i NEW_LINE while ( n % i == 0 ) : NEW_LINE INDENT n = n / i NEW_LINE DEDENT DEDENT DEDENT if ( n > 2 ) : NEW_LINE INDENT product = product * n NEW_LINE DEDENT return product NEW_LINE DEDENT n = 44 NEW_LINE print ( int ( productPrimeFactors ( n ) ) ) NEW_LINE |
Maximizing Probability of one type from N containers | Returns the Maximum probability for Drawing 1 copy of number A from N containers with N copies each of numbers A and B ; Pmax = N / ( N + 1 ) ; 1. N = 1 ; 2. N = 2 ; 3. N = 10 | def calculateProbability ( N ) : NEW_LINE INDENT probability = N / ( N + 1 ) NEW_LINE return probability NEW_LINE DEDENT N = 1 NEW_LINE probabilityMax = calculateProbability ( N ) NEW_LINE print ( " Maximum β Probability β for β N β = β " , N , " is , β % .4f " % probabilityMax ) NEW_LINE N = 2 NEW_LINE probabilityMax = calculateProbability ( N ) ; NEW_LINE print ( " Maximum β Probability β for β N β = " , N , " is , β % .4f " % probabilityMax ) NEW_LINE N = 10 NEW_LINE probabilityMax = calculateProbability ( N ) ; NEW_LINE print ( " Maximum β Probability β for β N β = " , N , " is , β % .4f " % probabilityMax ) NEW_LINE |
Program to implement standard deviation of grouped data | Python Program to implement standard deviation of grouped data . ; Function to find mean of grouped data . ; Function to find standard deviation of grouped data . ; Formula to find standard deviation of grouped data . ; Declare and initialize the lower limit of interval . ; Declare and initialize the upper limit of interval . ; Calculating the size of array . | import math NEW_LINE def mean ( mid , freq , n ) : NEW_LINE INDENT sum = 0 NEW_LINE freqSum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum = sum + mid [ i ] * freq [ i ] NEW_LINE freqSum = freqSum + freq [ i ] NEW_LINE DEDENT return sum / freqSum NEW_LINE DEDENT def groupedSD ( lower_limit , upper_limit , freq , n ) : NEW_LINE INDENT mid = [ [ 0 ] for i in range ( 0 , n ) ] NEW_LINE sum = 0 NEW_LINE freqSum = 0 NEW_LINE sd = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT mid [ i ] = ( lower_limit [ i ] + upper_limit [ i ] ) / 2 NEW_LINE sum = sum + freq [ i ] * mid [ i ] * mid [ i ] NEW_LINE freqSum = freqSum + freq [ i ] NEW_LINE DEDENT sd = math . sqrt ( ( sum - freqSum * mean ( mid , freq , n ) * mean ( mid , freq , n ) ) / ( freqSum - 1 ) ) NEW_LINE return sd NEW_LINE DEDENT lower_limit = [ 50 , 61 , 71 , 86 , 96 ] NEW_LINE upper_limit = [ 60 , 70 , 85 , 95 , 100 ] NEW_LINE freq = [ 9 , 7 , 9 , 12 , 8 ] NEW_LINE n = len ( lower_limit ) NEW_LINE print ( groupedSD ( lower_limit , upper_limit , freq , n ) ) NEW_LINE |
Average of first n even natural numbers | Function to find average of sum of first n even numbers ; sum of first n even numbers ; calculating Average ; driver code | def avg_of_even_num ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum = sum + 2 * i NEW_LINE DEDENT return sum / n NEW_LINE DEDENT n = 9 NEW_LINE print ( avg_of_even_num ( n ) ) NEW_LINE |
Average of first n even natural numbers | Return the average of sum of first n even numbers ; Driven Program | def avg_of_even_num ( n ) : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT n = 8 NEW_LINE print ( avg_of_even_num ( n ) ) NEW_LINE |
Sum of square of first n odd numbers | Python3 code to find sum of square of first n odd numbers ; driver code | def squareSum ( n ) : NEW_LINE INDENT return int ( n * ( 4 * n * n - 1 ) / 3 ) NEW_LINE DEDENT ans = squareSum ( 8 ) NEW_LINE print ( ans ) NEW_LINE |
Check whether given three numbers are adjacent primes | Function checks whether given number is prime or not . ; Check if n is a multiple of 2 ; If not , then just check the odds ; Return next prime number ; Start with next number ; Breaks after finding next prime number ; Check given three numbers are adjacent primes are not ; Check given three numbers are primes are not ; Find next prime of a ; If next is not same as 'a ; If next next is not same as 'c ; Driver code for above functions | def isPrime ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 3 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 2 NEW_LINE DEDENT return True NEW_LINE DEDENT def nextPrime ( start ) : NEW_LINE INDENT nxt = start + 1 NEW_LINE while ( isPrime ( nxt ) == False ) : NEW_LINE INDENT nxt = nxt + 1 NEW_LINE DEDENT return nxt NEW_LINE DEDENT def areAdjacentPrimes ( a , b , c ) : NEW_LINE INDENT if ( isPrime ( a ) == False or isPrime ( b ) == False or isPrime ( c ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT nxt = nextPrime ( a ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( nxt != b ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( nextPrime ( b ) != c ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if ( areAdjacentPrimes ( 11 , 13 , 19 ) ) : NEW_LINE INDENT print ( " Yes " ) , NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Python3 Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function that find sum of series . ; Driver method ; Function call | import math NEW_LINE def sumOfSeries ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT sum = sum + i * i NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE |
Program to find sum of series 1 + 2 + 2 + 3 + 3 + 3 + . . . + n | Python3 Program to find sum of series 1 + 2 + 2 + 3 + . . . + n ; Function that find sum of series . ; Driver method | import math NEW_LINE def sumOfSeries ( n ) : NEW_LINE INDENT return ( ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( sumOfSeries ( n ) ) NEW_LINE |
Maximum binomial coefficient term value | Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Return maximum binomial coefficient term value . ; if n is even ; if n is odd ; Driver Code | def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for x in range ( k + 1 ) ] for y 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 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; NEW_LINE DEDENT DEDENT DEDENT return C [ n ] [ k ] ; NEW_LINE DEDENT def maxcoefficientvalue ( n ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT return binomialCoeff ( n , int ( n / 2 ) ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return binomialCoeff ( n , int ( ( n + 1 ) / 2 ) ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE print ( maxcoefficientvalue ( n ) ) ; NEW_LINE DEDENT |
Smallest n digit number divisible by given three numbers | Python3 code to find smallest n digit number which is divisible by x , y and z . ; LCM for x , y , z ; returns smallest n digit number divisible by x , y and z ; find the LCM ; find power of 10 for least number ; reminder after ; If smallest number itself divides lcm . ; add lcm - reminder number for next n digit number ; this condition check the n digit number is possible or not if it is possible it return the number else return 0 ; driver code ; if number is possible then it print the number | from fractions import gcd NEW_LINE import math NEW_LINE def LCM ( x , y , z ) : NEW_LINE INDENT ans = int ( ( x * y ) / ( gcd ( x , y ) ) ) NEW_LINE return int ( ( z * ans ) / ( gcd ( ans , z ) ) ) NEW_LINE DEDENT def findDivisible ( n , x , y , z ) : NEW_LINE INDENT lcm = LCM ( x , y , z ) NEW_LINE ndigitnumber = math . pow ( 10 , n - 1 ) NEW_LINE reminder = ndigitnumber % lcm NEW_LINE if reminder == 0 : NEW_LINE INDENT return ndigitnumber NEW_LINE DEDENT ndigitnumber += lcm - reminder NEW_LINE if ndigitnumber < math . pow ( 10 , n ) : NEW_LINE INDENT return int ( ndigitnumber ) NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT n = 4 NEW_LINE x = 2 NEW_LINE y = 3 NEW_LINE z = 5 NEW_LINE res = findDivisible ( n , x , y , z ) NEW_LINE if res != 0 : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE DEDENT |
Sum of squares of first n natural numbers | Return the sum of square of first n natural numbers ; Driven Program | def squaresum ( n ) : NEW_LINE INDENT return ( n * ( n + 1 ) / 2 ) * ( 2 * n + 1 ) / 3 NEW_LINE DEDENT n = 4 NEW_LINE print ( squaresum ( n ) ) ; NEW_LINE |
Program to calculate distance between two points | Python3 program to calculate distance between two points ; Function to calculate distance ; Calculating distance ; Drivers Code | import math NEW_LINE def distance ( x1 , y1 , x2 , y2 ) : NEW_LINE INDENT return math . sqrt ( math . pow ( x2 - x1 , 2 ) + math . pow ( y2 - y1 , 2 ) * 1.0 ) NEW_LINE DEDENT print ( " % .6f " % distance ( 3 , 4 , 4 , 3 ) ) NEW_LINE |
Check if a large number is divisibility by 15 | to find sum ; function to check if a large number is divisible by 15 ; length of string ; check divisibility by 5 ; Sum of digits ; if divisible by 3 ; Driver Code | def accumulate ( s ) : NEW_LINE INDENT acc = 0 ; NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT acc += ord ( s [ i ] ) - 48 ; NEW_LINE DEDENT return acc ; NEW_LINE DEDENT def isDivisible ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE if ( s [ n - 1 ] != '5' and s [ n - 1 ] != '0' ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT sum = accumulate ( s ) ; NEW_LINE return ( sum % 3 == 0 ) ; NEW_LINE DEDENT s = "15645746327462384723984023940239" ; NEW_LINE if isDivisible ( s ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT s = "15645746327462384723984023940235" ; NEW_LINE if isDivisible ( s ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Shortest path with exactly k edges in a directed and weighted graph | Define number of vertices in the graph and inifinite value ; A naive recursive function to count walks from u to v with k edges ; Base cases ; Initialize result ; Go to all adjacents of u and recur ; Driver Code ; Let us create the graph shown in above diagram | V = 4 NEW_LINE INF = 999999999999 NEW_LINE def shortestPath ( graph , u , v , k ) : NEW_LINE INDENT if k == 0 and u == v : NEW_LINE INDENT return 0 NEW_LINE DEDENT if k == 1 and graph [ u ] [ v ] != INF : NEW_LINE INDENT return graph [ u ] [ v ] NEW_LINE DEDENT if k <= 0 : NEW_LINE INDENT return INF NEW_LINE DEDENT res = INF NEW_LINE for i in range ( V ) : NEW_LINE INDENT if graph [ u ] [ i ] != INF and u != i and v != i : NEW_LINE INDENT rec_res = shortestPath ( graph , i , v , k - 1 ) NEW_LINE if rec_res != INF : NEW_LINE INDENT res = min ( res , graph [ u ] [ i ] + rec_res ) NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT INF = 999999999999 NEW_LINE graph = [ [ 0 , 10 , 3 , 2 ] , [ INF , 0 , INF , 7 ] , [ INF , INF , 0 , 6 ] , [ INF , INF , INF , 0 ] ] NEW_LINE u = 0 NEW_LINE v = 3 NEW_LINE k = 2 NEW_LINE print ( " Weight β of β the β shortest β path β is " , shortestPath ( graph , u , v , k ) ) NEW_LINE DEDENT |
Shortest path with exactly k edges in a directed and weighted graph | Define number of vertices in the graph and inifinite value ; A Dynamic programming based function to find the shortest path from u to v with exactly k edges . ; Table to be filled up using DP . The value sp [ i ] [ j ] [ e ] will store weight of the shortest path from i to j with exactly k edges ; Loop for number of edges from 0 to k ; for source ; for destination ; initialize value ; from base cases ; go to adjacent only when number of edges is more than 1 ; There should be an edge from i to a and a should not be same as either i or j ; Let us create the graph shown in above diagram | V = 4 NEW_LINE INF = 999999999999 NEW_LINE def shortestPath ( graph , u , v , k ) : NEW_LINE INDENT global V , INF NEW_LINE sp = [ [ None ] * V for i in range ( V ) ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT sp [ i ] [ j ] = [ None ] * ( k + 1 ) NEW_LINE DEDENT DEDENT for e in range ( k + 1 ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT sp [ i ] [ j ] [ e ] = INF NEW_LINE if ( e == 0 and i == j ) : NEW_LINE INDENT sp [ i ] [ j ] [ e ] = 0 NEW_LINE DEDENT if ( e == 1 and graph [ i ] [ j ] != INF ) : NEW_LINE INDENT sp [ i ] [ j ] [ e ] = graph [ i ] [ j ] NEW_LINE DEDENT if ( e > 1 ) : NEW_LINE INDENT for a in range ( V ) : NEW_LINE INDENT if ( graph [ i ] [ a ] != INF and i != a and j != a and sp [ a ] [ j ] [ e - 1 ] != INF ) : NEW_LINE INDENT sp [ i ] [ j ] [ e ] = min ( sp [ i ] [ j ] [ e ] , graph [ i ] [ a ] + sp [ a ] [ j ] [ e - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return sp [ u ] [ v ] [ k ] NEW_LINE DEDENT graph = [ [ 0 , 10 , 3 , 2 ] , [ INF , 0 , INF , 7 ] , [ INF , INF , 0 , 6 ] , [ INF , INF , INF , 0 ] ] NEW_LINE u = 0 NEW_LINE v = 3 NEW_LINE k = 2 NEW_LINE print ( " Weight β of β the β shortest β path β is " , shortestPath ( graph , u , v , k ) ) NEW_LINE |
Multistage Graph ( Shortest Path ) | Returns shortest distance from 0 to N - 1. ; dist [ i ] is going to store shortest distance from node i to node N - 1. ; Calculating shortest path for rest of the nodes ; Initialize distance from i to destination ( N - 1 ) ; Check all nodes of next stages to find shortest distance from i to N - 1. ; Reject if no edge exists ; We apply recursive equation to distance to target through j . and compare with minimum distance so far . ; Driver code ; Graph stored in the form of an adjacency Matrix | def shortestDist ( graph ) : NEW_LINE INDENT global INF NEW_LINE dist = [ 0 ] * N NEW_LINE dist [ N - 1 ] = 0 NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT dist [ i ] = INF NEW_LINE for j in range ( N ) : NEW_LINE INDENT if graph [ i ] [ j ] == INF : NEW_LINE INDENT continue NEW_LINE DEDENT dist [ i ] = min ( dist [ i ] , graph [ i ] [ j ] + dist [ j ] ) NEW_LINE DEDENT DEDENT return dist [ 0 ] NEW_LINE DEDENT N = 8 NEW_LINE INF = 999999999999 NEW_LINE graph = [ [ INF , 1 , 2 , 5 , INF , INF , INF , INF ] , [ INF , INF , INF , INF , 4 , 11 , INF , INF ] , [ INF , INF , INF , INF , 9 , 5 , 16 , INF ] , [ INF , INF , INF , INF , INF , INF , 2 , INF ] , [ INF , INF , INF , INF , INF , INF , INF , 18 ] , [ INF , INF , INF , INF , INF , INF , INF , 13 ] , [ INF , INF , INF , INF , INF , INF , INF , 2 ] ] NEW_LINE print ( shortestDist ( graph ) ) NEW_LINE |
Reverse Level Order Traversal | A binary tree node ; Function to print reverse level order traversal ; Print nodes at a given level ; Compute the height of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node ; Compute the height of each subtree ; Use the larger one ; Let us create trees shown in above diagram | 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 reverseLevelOrder ( root ) : NEW_LINE INDENT h = height ( root ) NEW_LINE for i in reversed ( range ( 1 , h + 1 ) ) : NEW_LINE INDENT printGivenLevel ( root , i ) NEW_LINE DEDENT DEDENT def printGivenLevel ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if level == 1 : NEW_LINE INDENT print root . data , NEW_LINE DEDENT elif level > 1 : NEW_LINE INDENT printGivenLevel ( root . left , level - 1 ) NEW_LINE printGivenLevel ( root . right , level - 1 ) NEW_LINE DEDENT DEDENT def height ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lheight = height ( node . left ) NEW_LINE rheight = height ( node . right ) NEW_LINE if lheight > rheight : NEW_LINE INDENT return lheight + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return rheight + 1 NEW_LINE DEDENT DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print " Level β Order β traversal β of β binary β tree β is " NEW_LINE reverseLevelOrder ( root ) NEW_LINE |
Minimize the number of weakly connected nodes | Set of nodes which are traversed in each launch of the DFS ; Function traversing the graph using DFS approach and updating the set of nodes ; Building a undirected graph ; Computes the minimum number of disconnected components when a bi - directed graph is converted to a undirected graph ; Declaring and initializing a visited array ; We check if each node is visited once or not ; We only launch DFS from a node iff it is unvisited . ; Clearing the set of nodes on every relaunch of DFS ; Relaunching DFS from an unvisited node . ; Iterating over the node set to count the number of nodes visited after making the graph directed and storing it in the variable count . If count / 2 == number of nodes - 1 , then increment count by 1. ; Driver code ; Building graph in the form of a adjacency list | node = set ( ) NEW_LINE Graph = [ [ ] for i in range ( 10001 ) ] NEW_LINE def dfs ( visit , src ) : NEW_LINE INDENT visit [ src ] = True NEW_LINE node . add ( src ) NEW_LINE llen = len ( Graph [ src ] ) NEW_LINE for i in range ( llen ) : NEW_LINE INDENT if ( not visit [ Graph [ src ] [ i ] ] ) : NEW_LINE INDENT dfs ( visit , Graph [ src ] [ i ] ) NEW_LINE DEDENT DEDENT DEDENT def buildGraph ( x , y , llen ) : NEW_LINE INDENT for i in range ( llen ) : NEW_LINE INDENT p = x [ i ] NEW_LINE q = y [ i ] NEW_LINE Graph [ p ] . append ( q ) NEW_LINE Graph [ q ] . append ( p ) NEW_LINE DEDENT DEDENT def compute ( n ) : NEW_LINE INDENT visit = [ False for i in range ( n + 5 ) ] NEW_LINE number_of_nodes = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( not visit [ i ] ) : NEW_LINE INDENT node . clear ( ) NEW_LINE dfs ( visit , i ) NEW_LINE count = 0 NEW_LINE for it in node : NEW_LINE INDENT count += len ( Graph [ ( it ) ] ) NEW_LINE DEDENT count //= 2 NEW_LINE if ( count == len ( node ) - 1 ) : NEW_LINE number_of_nodes += 1 NEW_LINE DEDENT DEDENT return number_of_nodes NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE m = 4 NEW_LINE x = [ 1 , 1 , 4 , 4 , 0 , 0 , 0 , 0 , 0 ] NEW_LINE y = [ 2 , 3 , 5 , 6 , 0 , 0 , 0 , 0 , 0 ] NEW_LINE buildGraph ( x , y , n ) NEW_LINE print ( str ( compute ( n ) ) + " β weakly β connected β nodes " ) NEW_LINE DEDENT |
Karp 's minimum mean (or average) weight cycle algorithm | a struct to represent edges ; vector to store edges @ SuppressWarnings ( " unchecked " ) ; calculates the shortest path ; initializing all distances as - 1 ; shortest distance From first vertex to in tself consisting of 0 edges ; filling up the dp table ; Returns minimum value of average weight of a cycle in graph . ; array to store the avg values ; Compute average values for all vertices using weights of shortest paths store in dp . ; Find minimum value in avg [ ] ; Driver Code | class edge : NEW_LINE INDENT def __init__ ( self , u , w ) : NEW_LINE INDENT self . From = u NEW_LINE self . weight = w NEW_LINE DEDENT DEDENT def addedge ( u , v , w ) : NEW_LINE INDENT edges [ v ] . append ( edge ( u , w ) ) NEW_LINE DEDENT V = 4 NEW_LINE edges = [ [ ] for i in range ( V ) ] NEW_LINE def shortestpath ( dp ) : NEW_LINE INDENT for i in range ( V + 1 ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT dp [ 0 ] [ 0 ] = 0 NEW_LINE for i in range ( 1 , V + 1 ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT for k in range ( len ( edges [ j ] ) ) : NEW_LINE INDENT if ( dp [ i - 1 ] [ edges [ j ] [ k ] . From ] != - 1 ) : NEW_LINE INDENT curr_wt = ( dp [ i - 1 ] [ edges [ j ] [ k ] . From ] + edges [ j ] [ k ] . weight ) NEW_LINE if ( dp [ i ] [ j ] == - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = curr_wt NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , curr_wt ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT def minAvgWeight ( ) : NEW_LINE INDENT dp = [ [ None ] * V for i in range ( V + 1 ) ] NEW_LINE shortestpath ( dp ) NEW_LINE avg = [ - 1 ] * V NEW_LINE for i in range ( V ) : NEW_LINE INDENT if ( dp [ V ] [ i ] != - 1 ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT if ( dp [ j ] [ i ] != - 1 ) : NEW_LINE INDENT avg [ i ] = max ( avg [ i ] , ( dp [ V ] [ i ] - dp [ j ] [ i ] ) / ( V - j ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT result = avg [ 0 ] NEW_LINE for i in range ( V ) : NEW_LINE INDENT if ( avg [ i ] != - 1 and avg [ i ] < result ) : NEW_LINE INDENT result = avg [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT addedge ( 0 , 1 , 1 ) NEW_LINE addedge ( 0 , 2 , 10 ) NEW_LINE addedge ( 1 , 2 , 3 ) NEW_LINE addedge ( 2 , 3 , 2 ) NEW_LINE addedge ( 3 , 1 , 0 ) NEW_LINE addedge ( 3 , 0 , 8 ) NEW_LINE print ( minAvgWeight ( ) ) NEW_LINE |
Frequency of maximum occurring subsequence in given string | Python3 program for the above approach ; Function to find the frequency ; freq stores frequency of each english lowercase character ; dp [ i ] [ j ] stores the count of subsequence with ' a ' + i and ' a ' + j character ; Increment the count of subsequence j and s [ i ] ; Update the frequency array ; For 1 length subsequence ; For 2 length subsequence ; Return the final result ; Given string str ; Function call | import numpy NEW_LINE def findCount ( s ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE dp = [ [ 0 ] * 26 ] * 26 NEW_LINE freq = numpy . zeros ( 26 ) NEW_LINE dp = numpy . zeros ( [ 26 , 26 ] ) NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT dp [ j ] [ ord ( s [ i ] ) - ord ( ' a ' ) ] += freq [ j ] NEW_LINE DEDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT ans = max ( freq [ i ] , ans ) NEW_LINE DEDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT for j in range ( 0 , 26 ) : NEW_LINE INDENT ans = max ( dp [ i ] [ j ] , ans ) NEW_LINE DEDENT DEDENT return int ( ans ) NEW_LINE DEDENT str = " acbab " NEW_LINE print ( findCount ( str ) ) NEW_LINE |
Create an array such that XOR of subarrays of length K is X | Function to construct the array ; Creating a list of size K , initialised with 0 ; Initialising the first element with the given XOR ; Driver code | def constructArray ( N , K , X ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT ans . append ( 0 ) NEW_LINE DEDENT ans [ 0 ] = X NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT print ( ans [ i % K ] , end = " β " ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE K = 2 NEW_LINE X = 4 NEW_LINE constructArray ( N , K , X ) NEW_LINE |
Two player game in which a player can remove all occurrences of a number | Python3 implementation for two player game in which a player can remove all occurrences of a number ; Function that print whether player1 can wins or loses ; Storing the number of occurrence of elements in unordered map ; Variable to check if the occurrence of repeated elements is >= 4 and multiple of 2 or not ; Count elements which occur more than once ; Driver code | from collections import defaultdict NEW_LINE def game ( v , n ) : NEW_LINE INDENT m = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( v [ i ] not in m ) : NEW_LINE INDENT m [ v [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ v [ i ] ] += 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE check = 0 NEW_LINE for i in m . values ( ) : NEW_LINE INDENT if ( i > 1 ) : NEW_LINE INDENT if ( i >= 4 and i % 2 == 0 ) : NEW_LINE INDENT check += 1 NEW_LINE DEDENT count += 1 NEW_LINE DEDENT DEDENT if ( check % 2 != 0 ) : NEW_LINE INDENT flag = False NEW_LINE DEDENT if ( check % 2 != 0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT elif ( n % 2 == 0 and count % 2 == 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 arr = [ 3 , 2 , 2 , 3 , 3 , 5 ] NEW_LINE size = len ( arr ) NEW_LINE game ( arr , size ) NEW_LINE DEDENT |
Count of elements which form a loop in an Array according to given constraints | Python3 program to number of elements which form a cycle in an array ; Function to count number of elements forming a cycle ; Array to store parent node of traversal . ; Array to determine whether current node is already counted in the cycle . ; Check if current node is already traversed or not . If node is not traversed yet then parent value will be - 1. ; Traverse the graph until an already visited node is not found . ; Check parent value to ensure a cycle is present . ; Count number of nodes in the cycle . ; Driver code | import math NEW_LINE mod = 1000000007 NEW_LINE def solve ( A , n ) : NEW_LINE INDENT cnt = 0 NEW_LINE parent = [ - 1 ] * n NEW_LINE vis = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i NEW_LINE if ( parent [ j ] == - 1 ) : NEW_LINE INDENT while ( parent [ j ] == - 1 ) : NEW_LINE INDENT parent [ j ] = i NEW_LINE j = math . gcd ( j , A [ j ] ) % n NEW_LINE DEDENT if ( parent [ j ] == i ) : NEW_LINE INDENT while ( vis [ j ] == 0 ) : NEW_LINE INDENT vis [ j ] = 1 NEW_LINE cnt += 1 NEW_LINE j = math . gcd ( j , A [ j ] ) % n NEW_LINE DEDENT DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT A = [ 1 , 1 , 6 , 2 ] NEW_LINE n = len ( A ) NEW_LINE print ( solve ( A , n ) ) NEW_LINE |
Find farthest node from each node in Tree | Add edge between U and V in tree ; Edge from U to V ; Edge from V to U ; DFS to find the first End Node of diameter ; Calculating level of nodes ; Go in opposite direction of parent ; Function to clear the levels of the nodes ; Set all value of lvl [ ] to 0 for next dfs ; Set maximum with 0 ; DFS will calculate second end of the diameter ; Calculating level of nodes ; Store the node with maximum depth from end1 ; Go in opposite direction of parent ; Function to find the distance of the farthest distant node ; Storing distance from end1 to node u ; Function to find the distance of nodes from second end of diameter ; Storing distance from end2 to node u ; Joining Edge between two nodes of the tree ; Find the one end of the diameter of tree ; Find the other end of the diameter of tree ; Find the distance to each node from end1 ; Find the distance to each node from end2 ; Comparing distance between the two ends of diameter ; Driver code ; Function Call | def AddEdge ( u , v ) : NEW_LINE INDENT global adj NEW_LINE adj [ u ] . append ( v ) NEW_LINE adj [ v ] . append ( u ) NEW_LINE DEDENT def findFirstEnd ( u , p ) : NEW_LINE INDENT global lvl , adj , end1 , maxi NEW_LINE lvl [ u ] = 1 + lvl [ p ] NEW_LINE if ( lvl [ u ] > maxi ) : NEW_LINE INDENT maxi = lvl [ u ] NEW_LINE end1 = u NEW_LINE DEDENT for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( adj [ u ] [ i ] != p ) : NEW_LINE INDENT findFirstEnd ( adj [ u ] [ i ] , u ) NEW_LINE DEDENT DEDENT DEDENT def clear ( n ) : NEW_LINE INDENT global lvl , dist1 , dist2 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT lvl [ i ] = 0 NEW_LINE DEDENT maxi = 0 NEW_LINE dist1 [ 0 ] = dist2 [ 0 ] = - 1 NEW_LINE DEDENT def findSecondEnd ( u , p ) : NEW_LINE INDENT global lvl , adj , maxi , end2 NEW_LINE lvl [ u ] = 1 + lvl [ p ] NEW_LINE if ( lvl [ u ] > maxi ) : NEW_LINE INDENT maxi = lvl [ u ] NEW_LINE end2 = u NEW_LINE DEDENT for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( adj [ u ] [ i ] != p ) : NEW_LINE INDENT findSecondEnd ( adj [ u ] [ i ] , u ) NEW_LINE DEDENT DEDENT DEDENT def findDistancefromFirst ( u , p ) : NEW_LINE INDENT global dist1 , adj NEW_LINE dist1 [ u ] = 1 + dist1 [ p ] NEW_LINE for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( adj [ u ] [ i ] != p ) : NEW_LINE INDENT findDistancefromFirst ( adj [ u ] [ i ] , u ) NEW_LINE DEDENT DEDENT DEDENT def findDistancefromSecond ( u , p ) : NEW_LINE INDENT global dist2 , adj NEW_LINE dist2 [ u ] = 1 + dist2 [ p ] NEW_LINE for i in range ( len ( adj [ u ] ) ) : NEW_LINE INDENT if ( adj [ u ] [ i ] != p ) : NEW_LINE INDENT findDistancefromSecond ( adj [ u ] [ i ] , u ) NEW_LINE DEDENT DEDENT DEDENT def findNodes ( ) : NEW_LINE INDENT global adj , lvl , dist1 , dist2 , end1 , end2 , maxi NEW_LINE n = 5 NEW_LINE AddEdge ( 1 , 2 ) NEW_LINE AddEdge ( 1 , 3 ) NEW_LINE AddEdge ( 3 , 4 ) NEW_LINE AddEdge ( 3 , 5 ) NEW_LINE findFirstEnd ( 1 , 0 ) NEW_LINE clear ( n ) NEW_LINE findSecondEnd ( end1 , 0 ) NEW_LINE findDistancefromFirst ( end1 , 0 ) NEW_LINE findDistancefromSecond ( end2 , 0 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT x = dist1 [ i ] NEW_LINE y = dist2 [ i ] NEW_LINE if ( x >= y ) : NEW_LINE INDENT print ( end1 , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( end2 , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT adj = [ [ ] for i in range ( 10000 ) ] NEW_LINE lvl = [ 0 for i in range ( 10000 ) ] NEW_LINE dist1 = [ - 1 for i in range ( 10000 ) ] NEW_LINE dist2 = [ - 1 for i in range ( 10000 ) ] NEW_LINE end1 , end2 , maxi = 0 , 0 , 0 NEW_LINE findNodes ( ) NEW_LINE DEDENT |
Sum and Product of all even digit sum Nodes of a Singly Linked List | Node of Linked List ; Function to insert a node at the beginning of the singly Linked List ; Insert the data ; Link old list to the new node ; Move head to pothe new node ; Function to find the digit sum for a number ; Return the sum ; Function to find the required sum and product ; Initialise the sum and product to 0 and 1 respectively ; Traverse the given linked list ; If current node has even digit sum then include it in resultant sum and product ; Find the sum and the product ; Print the final Sum and Product ; Driver Code ; Head of the linked list ; Create the linked list 15 . 16 . 8 . 6 . 13 ; Function call | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def digitSum ( num ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( num ) : NEW_LINE INDENT sum += ( num % 10 ) NEW_LINE num //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def sumAndProduct ( head_ref ) : NEW_LINE INDENT prod = 1 NEW_LINE sum = 0 NEW_LINE ptr = head_ref NEW_LINE while ( ptr != None ) : NEW_LINE INDENT if ( not ( digitSum ( ptr . data ) & 1 ) ) : NEW_LINE INDENT prod *= ptr . data NEW_LINE sum += ptr . data NEW_LINE DEDENT ptr = ptr . next NEW_LINE DEDENT print ( " Sum β = " , sum ) NEW_LINE print ( " Product β = " , prod ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 13 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 16 ) NEW_LINE head = push ( head , 15 ) NEW_LINE sumAndProduct ( head ) NEW_LINE DEDENT |
Shortest Palindromic Substring | Function return the shortest palindromic substring ; One by one consider every character as center point of even and length palindromes ; Find the longest odd length palindrome with center point as i ; Find the even length palindrome with center points as i - 1 and i . ; Smallest substring which is not empty ; Driver code | def ShortestPalindrome ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT l = i NEW_LINE r = i NEW_LINE ans1 = " " NEW_LINE ans2 = " " NEW_LINE while ( ( l >= 0 ) and ( r < n ) and ( s [ l ] == s [ r ] ) ) : NEW_LINE INDENT ans1 += s [ l ] NEW_LINE l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT l = i - 1 NEW_LINE r = i NEW_LINE while ( ( l >= 0 ) and ( r < n ) and ( s [ l ] == s [ r ] ) ) : NEW_LINE INDENT ans2 += s [ l ] NEW_LINE l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT v . append ( ans1 ) NEW_LINE v . append ( ans2 ) NEW_LINE DEDENT ans = v [ 0 ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ i ] != " " ) : NEW_LINE INDENT ans = min ( ans , v [ i ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE print ( ShortestPalindrome ( s ) ) NEW_LINE |
Find numbers which are multiples of first array and factors of second array | Python3 implementation of the approach ; Function to return the LCM of two numbers ; Function to print the required numbers ; To store the lcm of array a [ ] elements and the gcd of array b [ ] elements ; Finding LCM of first array ; Finding GCD of second array ; No such element exists ; All the multiples of lcmA which are less than or equal to gcdB and evenly divide gcdB will satisfy the conditions ; Driver code | from math import gcd NEW_LINE def lcm ( x , y ) : NEW_LINE INDENT temp = ( x * y ) // gcd ( x , y ) ; NEW_LINE return temp ; NEW_LINE DEDENT def findNumbers ( a , n , b , m ) : NEW_LINE INDENT lcmA = 1 ; __gcdB = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT lcmA = lcm ( lcmA , a [ i ] ) ; NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT __gcdB = gcd ( __gcdB , b [ i ] ) ; NEW_LINE DEDENT if ( __gcdB % lcmA != 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT num = lcmA ; NEW_LINE while ( num <= __gcdB ) : NEW_LINE INDENT if ( __gcdB % num == 0 ) : NEW_LINE INDENT print ( num , end = " β " ) ; NEW_LINE DEDENT num += lcmA ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 2 , 4 ] ; NEW_LINE b = [ 16 , 32 , 64 ] ; NEW_LINE n = len ( a ) ; NEW_LINE m = len ( b ) ; NEW_LINE findNumbers ( a , n , b , m ) ; NEW_LINE DEDENT |
Probability such that two subset contains same number of elements | Python3 implementation of the above approach ; Returns value of Binomial Coefficient C ( n , k ) ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of ; Iterative Function to calculate ( x ^ y ) in O ( log y ) ; Initialize result ; If y is odd , multiply x with result ; y must be even now y = y / 2 ; Change x to x ^ 2 ; Function to find probability ; Calculate total possible ways and favourable ways . ; Divide by gcd such that they become relatively coprime ; Driver code | import math NEW_LINE def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( 0 , k ) : NEW_LINE INDENT res = res * ( n - i ) NEW_LINE res = res // ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def power ( x , y ) : NEW_LINE INDENT res = 1 NEW_LINE while ( y > 0 ) : NEW_LINE INDENT if ( y & 1 ) : NEW_LINE INDENT res = res * x NEW_LINE DEDENT y = y // 2 NEW_LINE x = x * x NEW_LINE DEDENT return res NEW_LINE DEDENT def FindProbability ( n ) : NEW_LINE INDENT up = binomialCoeff ( 2 * n , n ) NEW_LINE down = power ( 2 , 2 * n ) NEW_LINE g = math . gcd ( up , down ) NEW_LINE up = up // g NEW_LINE down = down // g NEW_LINE print ( up , " / " , down ) NEW_LINE DEDENT N = 8 NEW_LINE FindProbability ( N ) NEW_LINE |
How to learn Pattern printing easily ? | Python3 implementation of the approach | N = 4 NEW_LINE print ( " Value β of β N : β " , N ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT min = i if i < j else j NEW_LINE print ( N - min + 1 , end = " β " ) NEW_LINE DEDENT for j in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT min = i if i < j else j NEW_LINE print ( N - min + 1 , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT for i in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT min = i if i < j else j NEW_LINE print ( N - min + 1 , end = " β " ) NEW_LINE DEDENT for j in range ( N - 1 , 0 , - 1 ) : NEW_LINE INDENT min = i if i < j else j NEW_LINE print ( N - min + 1 , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT |
Largest perfect square number in an Array | Python3 program to find the largest perfect square number among n numbers ; Function to check if a number is perfect square number or not ; takes the sqrt of the number ; checks if it is a perfect square number ; Function to find the largest perfect square number in the array ; stores the maximum of all perfect square numbers ; Traverse all elements in the array ; store the maximum if current element is a perfect square ; Driver code | from math import sqrt NEW_LINE def checkPerfectSquare ( n ) : NEW_LINE INDENT d = sqrt ( n ) NEW_LINE if d * d == n : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def largestPerfectSquareNumber ( a , n ) : NEW_LINE INDENT maxi = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( checkPerfectSquare ( a [ i ] ) ) : NEW_LINE INDENT maxi = max ( a [ i ] , maxi ) NEW_LINE DEDENT DEDENT return maxi NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 16 , 20 , 25 , 2 , 3 , 10 ] NEW_LINE n = len ( a ) NEW_LINE print ( largestPerfectSquareNumber ( a , n ) ) NEW_LINE DEDENT |
Maximum number of parallelograms that can be made using the given length of line segments | Function to find the maximum number of parallelograms can be made ; Finding the length of the frequency array ; Increasing the occurrence of each segment ; To store the count of parallelograms ; Counting parallelograms that can be made using 4 similar sides ; counting segments which have occurrence left >= 2 ; Adding parallelograms that can be made using 2 similar sides ; Driver code | def convert ( n , a ) : NEW_LINE INDENT z = max ( a ) + 1 NEW_LINE ff = [ 0 ] * z NEW_LINE for i in range ( n ) : NEW_LINE INDENT ff [ a [ i ] ] += 1 NEW_LINE DEDENT cc = 0 NEW_LINE for i in range ( z ) : NEW_LINE INDENT cc += ff [ i ] // 4 NEW_LINE ff [ i ] = ff [ i ] % 4 NEW_LINE DEDENT vv = 0 NEW_LINE for i in range ( z ) : NEW_LINE INDENT if ( ff [ i ] >= 2 ) : NEW_LINE INDENT vv += 1 NEW_LINE DEDENT DEDENT cc += vv // 2 NEW_LINE print ( cc ) NEW_LINE DEDENT n = 4 NEW_LINE a = [ 1 , 2 , 1 , 2 ] NEW_LINE convert ( n , a ) NEW_LINE |
Count pairs ( i , j ) such that ( i + j ) is divisible by A and B both | Python3 implementation of above approach ; Function to find the LCM ; Function to count the pairs ; Driver code | from math import gcd NEW_LINE def find_LCM ( x , y ) : NEW_LINE INDENT return ( x * y ) // gcd ( x , y ) NEW_LINE DEDENT def CountPairs ( n , m , A , B ) : NEW_LINE INDENT cnt = 0 NEW_LINE lcm = find_LCM ( A , B ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT cnt += ( m + ( i % lcm ) ) // lcm NEW_LINE DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , m , A , B = 60 , 90 , 5 , 10 NEW_LINE print ( CountPairs ( n , m , A , B ) ) NEW_LINE DEDENT |
Sorting without comparison of elements | Represents node of a doubly linked list ; Count of elements in given range ; Count frequencies of all elements ; Traverse through range . For every element , print it its count times . ; Driver Code | def sortArr ( arr , n , min_no , max_no ) : NEW_LINE INDENT m = max_no - min_no + 1 NEW_LINE c = [ 0 ] * m NEW_LINE for i in range ( n ) : NEW_LINE INDENT c [ arr [ i ] - min_no ] += 1 NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( ( c [ i ] ) ) : NEW_LINE INDENT print ( ( i + min_no ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 10 , 10 , 1 , 4 , 4 , 100 , 0 ] NEW_LINE min_no , max_no = 0 , 100 NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n , min_no , max_no ) NEW_LINE |
Find Binary permutations of given size not present in the Array | Python 3 program for the above approach ; Function to find a Binary String of same length other than the Strings present in the array ; Map all the strings present in the array ; Find all the substring that can be made ; If num already exists then increase counter ; If not found print ; If all the substrings are present then print - 1 ; Driver Code | from math import pow NEW_LINE def findMissingBinaryString ( nums , N ) : NEW_LINE INDENT s = set ( ) NEW_LINE counter = 0 NEW_LINE for x in nums : NEW_LINE INDENT s . add ( x ) NEW_LINE DEDENT total = int ( pow ( 2 , N ) ) NEW_LINE ans = " " NEW_LINE for i in range ( total ) : NEW_LINE INDENT num = " " NEW_LINE j = N - 1 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( i & ( 1 << j ) ) : NEW_LINE INDENT num += '1' NEW_LINE DEDENT else : NEW_LINE INDENT num += '0' NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT if ( num in s ) : NEW_LINE INDENT continue NEW_LINE counter += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( num , end = " , β " ) NEW_LINE DEDENT DEDENT if ( counter == total ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE arr = [ "101" , "111" , "001" , "011" , "100" , "110" ] NEW_LINE findMissingBinaryString ( arr , N ) NEW_LINE DEDENT |
Queries to find number of connected grid components of given sizes in a Matrix | Python 3 implementation for the above approach ; stores information about which cell are already visited in a particular BFS ; Stores the final result grid ; Stores the count of cells in the largest connected component ; Function checks if a cell is valid , i . e . it is inside the grid and equal to 1 ; Map to count the frequency of each connected component ; function to calculate the largest connected component ; Iterate over every cell ; Stores the indices of the matrix cells ; Mark the starting cell as visited and push it into the queue ; Iterate while the queue is not empty ; Go to the adjacent cells ; Drivers Code ; Given input array of 1 s and 0 s ; queries array ; sizeof queries array ; Count the frequency of each connected component ; Iterate over the given queries array and And answer the queries | n = 6 NEW_LINE m = 6 NEW_LINE dx = [ 0 , 1 , - 1 , 0 ] NEW_LINE dy = [ 1 , 0 , 0 , - 1 ] NEW_LINE visited = [ [ False for i in range ( m ) ] for j in range ( n ) ] NEW_LINE result = [ [ 0 for i in range ( m ) ] for j in range ( n ) ] NEW_LINE COUNT = 0 NEW_LINE def is_valid ( x , y , matrix ) : NEW_LINE INDENT if ( x < n and y < m and x >= 0 and y >= 0 ) : NEW_LINE INDENT if ( visited [ x ] [ y ] == False and matrix [ x ] [ y ] == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT mp = { } NEW_LINE def findComponentSize ( matrix ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( visited [ i ] [ j ] == False and matrix [ i ] [ j ] == 1 ) : NEW_LINE INDENT COUNT = 0 NEW_LINE q = [ ] NEW_LINE q . append ( [ i , j ] ) NEW_LINE visited [ i ] [ j ] = True NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q = q [ 1 : ] NEW_LINE x = p [ 0 ] NEW_LINE y = p [ 1 ] NEW_LINE COUNT += 1 NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT newX = x + dx [ i ] NEW_LINE newY = y + dy [ i ] NEW_LINE if ( is_valid ( newX , newY , matrix ) ) : NEW_LINE INDENT q . append ( [ newX , newY ] ) NEW_LINE visited [ newX ] [ newY ] = True NEW_LINE DEDENT DEDENT DEDENT if COUNT in mp : NEW_LINE INDENT mp [ COUNT ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ COUNT ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 1 , 1 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 1 , 1 , 1 ] , [ 0 , 0 , 0 , 1 , 1 , 1 ] , [ 0 , 0 , 1 , 0 , 0 , 0 ] , [ 1 , 0 , 0 , 0 , 0 , 0 ] ] NEW_LINE queries = [ 6 , 1 , 8 , 2 ] NEW_LINE N = len ( queries ) NEW_LINE findComponentSize ( matrix ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if queries [ i ] in mp : NEW_LINE print ( mp [ queries [ i ] ] , end = " β " ) NEW_LINE else : NEW_LINE print ( 0 , end = " β " ) NEW_LINE DEDENT DEDENT |
Minimum value of X such that sum of arr [ i ] | Function to check if there exists an X that satisfies the given conditions ; Find the required value of the given expression ; Function to find the minimum value of X using binary search . ; Boundaries of the Binary Search ; Find the middle value ; Check for the middle value ; Update the upper ; Update the lower ; Driver Code | def check ( a , b , k , n , x ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum = sum + pow ( max ( a [ i ] - x , 0 ) , b [ i ] ) NEW_LINE DEDENT if ( sum <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def findMin ( a , b , n , k ) : NEW_LINE INDENT l = 0 NEW_LINE u = max ( a ) NEW_LINE while ( l < u ) : NEW_LINE INDENT m = ( l + u ) // 2 NEW_LINE if ( check ( a , b , k , n , m ) ) : NEW_LINE INDENT u = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT DEDENT return l NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 4 , 3 , 5 ] NEW_LINE brr = [ 4 , 3 , 2 , 3 , 1 ] NEW_LINE K = 12 NEW_LINE N = len ( arr ) NEW_LINE print ( findMin ( arr , brr , N , K ) ) NEW_LINE DEDENT |
Count of indices pairs such that product of elements at these indices is equal to absolute difference of indices | Function to count the number of pairs ( i , j ) such that arr [ i ] * arr [ j ] is equal to abs ( i - j ) ; Stores the resultant number of pairs ; Iterate over the range [ 0 , N ) ; Now , iterate from the value arr [ i ] - ( i % arr [ i ] ) till N with an increment of arr [ i ] ; If the given criteria satisfy then increment the value of count ; Return the resultant count ; Driver Code | def getPairsCount ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT s = arr [ i ] - ( i % arr [ i ] ) NEW_LINE for j in range ( s , n ) : NEW_LINE INDENT if ( i < j and ( arr [ i ] * arr [ j ] ) == abs ( i - j ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( getPairsCount ( arr , N ) ) NEW_LINE |
Find frequency of each character with positions in given Array of Strings | Function to print every occurence of every characters in every string ; Iterate over the vector arr [ ] ; Traverse the string arr [ i ] ; Push the pair of { i + 1 , j + 1 } in mp [ arr [ i ] [ j ] ] ; Print the occurences of every character ; Driver Code ; Input ; Function call | def printOccurences ( arr , N ) : NEW_LINE INDENT mp = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( len ( arr [ i ] ) ) : NEW_LINE INDENT mp [ ord ( arr [ i ] [ j ] ) - ord ( ' a ' ) ] . append ( ( i + 1 , j + 1 ) ) NEW_LINE DEDENT DEDENT for i in range ( 26 ) : NEW_LINE INDENT if len ( mp [ i ] ) == 0 : NEW_LINE INDENT continue NEW_LINE DEDENT print ( " Occurences β of : " , chr ( i + ord ( ' a ' ) ) , " = " , end = " β " ) NEW_LINE for j in mp [ i ] : NEW_LINE INDENT print ( " [ " + str ( j [ 0 ] ) + " β " + str ( j [ 1 ] ) + " ] β " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " geeksforgeeks " , " gfg " ] NEW_LINE N = len ( arr ) NEW_LINE printOccurences ( arr , N ) NEW_LINE DEDENT |
Count of subarrays with X as the most frequent element , for each value of X from 1 to N | Function to calculate the number of subarrays where X ( 1 <= X <= N ) is the most frequent element ; array to store the final answers ; Array to store current frequencies ; Variable to store the current most frequent element ; Update frequency array ; Update answer ; Pranswer ; Driver code ; Input ; Function call | def mostFrequent ( arr , N ) : NEW_LINE INDENT ans = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = [ 0 ] * N NEW_LINE best = 0 NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT count [ arr [ j ] - 1 ] += 1 NEW_LINE if ( count [ arr [ j ] - 1 ] > count [ best - 1 ] or ( count [ arr [ j ] - 1 ] == count [ best - 1 ] and arr [ j ] < best ) ) : NEW_LINE INDENT best = arr [ j ] NEW_LINE DEDENT ans [ best - 1 ] += 1 NEW_LINE DEDENT DEDENT print ( * ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE mostFrequent ( arr , N ) NEW_LINE DEDENT |
Count array elements whose highest power of 2 less than or equal to that number is present in the given array | Python program for the above approach ; Function to count array elements whose highest power of 2 is less than or equal to that number is present in the given array ; Stores the resultant count of array elements ; Stores frequency of visited array elements ; Traverse the array ; Calculate log base 2 of the element arr [ i ] ; Highest power of 2 whose value is at most arr [ i ] ; Increment the count by 1 ; Return the resultant count ; Driver Code | from math import log2 NEW_LINE def countElement ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE m = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT lg = int ( log2 ( arr [ i ] ) ) NEW_LINE p = pow ( 2 , lg ) NEW_LINE if ( p in m ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 4 , 6 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countElement ( arr , N ) ) NEW_LINE DEDENT |
Maximum number of intersections possible for any of the N given segments | Python 3 program for the above approach ; Function to find the maximum number of intersections one segment has with all the other given segments ; Stores the resultant maximum count ; Stores the starting and the ending points ; Sort arrays points in the ascending order ; Traverse the array arr [ ] ; Find the count of segments on left of ith segment ; Find the count of segments on right of ith segment ; Find the total segments not intersecting with the current segment ; Store the count of segments that intersect with the ith segment ; Update the value of count ; Return the resultant count ; Driver Code | from bisect import bisect_left , bisect_right NEW_LINE def lower_bound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = low + ( high - low ) // 2 NEW_LINE if ( element > a [ middle ] ) : NEW_LINE INDENT low = middle + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = middle NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT def maximumIntersections ( arr , N ) : NEW_LINE INDENT count = 0 NEW_LINE L = [ 0 ] * N NEW_LINE R = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT L [ i ] = arr [ i ] [ 0 ] NEW_LINE R [ i ] = arr [ i ] [ 1 ] NEW_LINE DEDENT L . sort ( ) NEW_LINE R . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT l = arr [ i ] [ 0 ] NEW_LINE r = arr [ i ] [ 1 ] NEW_LINE x = lower_bound ( L , 0 , N , l ) NEW_LINE y = N - lower_bound ( R , 0 , N , r + 1 ) NEW_LINE cnt = x + y NEW_LINE cnt = N - cnt - 1 NEW_LINE count = max ( count , cnt ) NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 6 ] , [ 5 , 5 ] , [ 2 , 3 ] ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumIntersections ( arr , N ) ) NEW_LINE DEDENT |
Program to find the Nth Composite Number | Function to find the Nth Composite Numbers using Sieve of Eratosthenes ; Sieve of prime numbers ; ; Iterate over the range [ 2 , 1000005 ] ; If IsPrime [ p ] is true ; Iterate over the range [ p * p , 1000005 ] ; Stores the list of composite numbers ; Iterate over the range [ 4 , 1000005 ] ; If i is not prime ; Return Nth Composite Number ; Driver Code | def NthComposite ( N ) : NEW_LINE INDENT IsPrime = [ True ] * 1000005 NEW_LINE DEDENT / * Initialize the array to true * / NEW_LINE INDENT for p in range ( 2 , 1000005 ) : NEW_LINE INDENT if p * p > 1000005 : NEW_LINE INDENT break NEW_LINE DEDENT if ( IsPrime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 1000005 , p ) : NEW_LINE INDENT IsPrime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT Composites = [ ] NEW_LINE for p in range ( 4 , 1000005 ) : NEW_LINE INDENT if ( not IsPrime [ p ] ) : NEW_LINE INDENT Composites . append ( p ) NEW_LINE DEDENT DEDENT return Composites [ N - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE print ( NthComposite ( N ) ) NEW_LINE DEDENT |
Intersection point of two Linked Lists | Set 3 | Structure of a node of a Linked List ; ; Function to find the intersection point of the two Linked Lists ; Traverse the first linked list and multiply all values by - 1 ; Update a . data ; Update a ; Traverse the second Linked List and find the value of the first node having negative value ; Intersection point ; Update b ; Function to create linked lists ; Linked List L1 ; Linked List L2 ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT DEDENT / * Constructor * / def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . next = None NEW_LINE DEDENT def intersectingNode ( headA , headB ) : NEW_LINE INDENT a = headA NEW_LINE while ( a ) : NEW_LINE INDENT a . data *= - 1 NEW_LINE a = a . next NEW_LINE DEDENT b = headB NEW_LINE while ( b ) : NEW_LINE INDENT if ( b . data < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT b = b . next NEW_LINE DEDENT return b NEW_LINE DEDENT def formLinkList ( head1 , head2 ) : NEW_LINE INDENT head1 = Node ( 3 ) NEW_LINE head1 . next = Node ( 6 ) NEW_LINE head1 . next . next = Node ( 9 ) NEW_LINE head1 . next . next . next = Node ( 15 ) NEW_LINE head1 . next . next . next . next = Node ( 30 ) NEW_LINE head2 = Node ( 10 ) NEW_LINE head2 . next = head1 . next . next . next NEW_LINE return head1 , head2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 , head2 = formLinkList ( None , None ) NEW_LINE print ( abs ( intersectingNode ( head1 , head2 ) . data ) ) NEW_LINE DEDENT |
Modify array of strings by replacing characters repeating in the same or remaining strings | Function to remove duplicate characters across the strings ; Stores distinct characters ; Size of the array ; Stores the list of modified strings ; Traverse the array ; Stores the modified string ; Iterate over the characters of the modified string ; If character is already present ; Insert character into the Set ; Print the list of modified strings ; Print each string ; Driver Code ; Given array of strings ; Function Call to modify the given array of strings | def removeDuplicateCharacters ( arr ) : NEW_LINE INDENT cset = set ( [ ] ) NEW_LINE n = len ( arr ) NEW_LINE out = [ ] NEW_LINE for st in arr : NEW_LINE INDENT out_curr = " " NEW_LINE for ch in st : NEW_LINE INDENT if ( ch in cset ) : NEW_LINE INDENT continue NEW_LINE DEDENT out_curr += ch NEW_LINE cset . add ( ch ) NEW_LINE DEDENT if ( len ( out_curr ) ) : NEW_LINE INDENT out . append ( out_curr ) NEW_LINE DEDENT DEDENT for i in range ( len ( out ) ) : NEW_LINE INDENT print ( out [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " Geeks " , " For " , " Geeks " , " Post " ] NEW_LINE removeDuplicateCharacters ( arr ) NEW_LINE DEDENT |
Sum of array elements which are prime factors of a given number | Function to check if a number is prime or not ; Corner cases ; Check if n is a multiple of 2 or 3 ; Above condition allows to check only for every 6 th number , starting from 5 ; If n is a multiple of i and i + 2 ; Function to find the sum of array elements which are prime factors of K ; Stores the required sum ; Traverse the given array ; If current element is a prime factor of k , add it to the sum ; Print the result ; Given arr [ ] ; Store the size of the array | def isPrime ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = 5 NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT i = i + 6 NEW_LINE DEDENT return True NEW_LINE DEDENT def primeFactorSum ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( k % arr [ i ] == 0 and isPrime ( arr [ i ] ) ) : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 5 , 6 , 7 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE K = 35 NEW_LINE primeFactorSum ( arr , N , K ) NEW_LINE |
Minimum number of array elements from either ends required to be subtracted from X to reduce X to 0 | Python3 Program to implement the above approach ; Function to count the minimum number of operations required to reduce x to 0 ; If sum of the array is less than x ; Stores the count of operations ; Two pointers to traverse the array ; Reduce x by the sum of the entire array ; Iterate until l reaches the front of the array ; If sum of elements from the front exceeds x ; Shift towards left ; If sum exceeds 0 ; Reduce x by elements from the right ; If x is reduced to 0 ; Update the minimum count of operations required ; Driver Code | import math NEW_LINE def minOperations ( nums , x ) : NEW_LINE INDENT if sum ( nums ) < x : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = math . inf NEW_LINE l , r = len ( nums ) - 1 , len ( nums ) NEW_LINE x -= sum ( nums ) NEW_LINE while l >= 0 : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT x += nums [ l ] NEW_LINE l -= 1 NEW_LINE DEDENT if x > 0 : NEW_LINE INDENT r -= 1 NEW_LINE x -= nums [ r ] NEW_LINE DEDENT if x == 0 : NEW_LINE INDENT ans = min ( ans , ( l + 1 ) + ( len ( nums ) - r ) ) NEW_LINE DEDENT DEDENT return ans if ans < math . inf else - 1 NEW_LINE DEDENT nums = [ 1 , 1 , 4 , 2 , 3 ] NEW_LINE x = 5 NEW_LINE print ( minOperations ( nums , x ) ) NEW_LINE |
Number of subarrays having even product | Function to count subarrays with even product ; Total number of subarrays ; Counter variables ; Traverse the array ; If current element is odd ; Update count of subarrays with odd product up to index i ; Print count of subarrays with even product ; Driver code ; Input ; Length of an array ; Function call to count even product subarrays | def evenproduct ( arr , length ) : NEW_LINE INDENT total_subarray = length * ( length + 1 ) // 2 NEW_LINE total_odd = 0 NEW_LINE count_odd = 0 NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT count_odd = 0 NEW_LINE DEDENT else : NEW_LINE INDENT count_odd += 1 NEW_LINE total_odd += count_odd NEW_LINE DEDENT DEDENT print ( total_subarray - total_odd ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 5 , 4 , 9 ] NEW_LINE length = len ( arr ) NEW_LINE evenproduct ( arr , length ) NEW_LINE DEDENT |
Check if all rows of a Binary Matrix have all ones placed adjacently or not | Function to check if all 1 s are placed adjacently in an array or not ; Base Case ; Stores the sum of XOR of all pair of adjacent elements ; Calculate sum of XOR of all pair of adjacent elements ; Check for corner cases ; Return true ; Function to check if all the rows have all 1 s grouped together or not ; Traverse each row ; Check if all 1 s are placed together in the ith row or not ; Function to check if all 1 s in a row are grouped together in a matrix or not ; Print the result ; Given matrix ; Function Call | def checkGroup ( arr ) : NEW_LINE INDENT if len ( arr ) <= 2 : NEW_LINE INDENT return True NEW_LINE DEDENT corner = arr [ 0 ] + arr [ - 1 ] NEW_LINE xorSum = 0 NEW_LINE for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT xorSum += ( arr [ i ] ^ arr [ i + 1 ] ) NEW_LINE DEDENT if not corner : NEW_LINE INDENT if xorSum > 2 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT elif corner == 1 : NEW_LINE INDENT if xorSum > 1 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if xorSum > 0 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isInGroupUtil ( mat ) : NEW_LINE INDENT for i in mat : NEW_LINE INDENT if not checkGroup ( i ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isInGroup ( mat ) : NEW_LINE INDENT ans = isInGroupUtil ( mat ) NEW_LINE if ans : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT mat = [ [ 0 , 1 , 1 , 0 ] , [ 1 , 1 , 0 , 0 ] , [ 0 , 0 , 0 , 1 ] , [ 1 , 1 , 1 , 0 ] ] NEW_LINE isInGroup ( mat ) NEW_LINE |
Print all numbers up to N having product of digits equal to K | Function to find the product of digits of a number ; Stores the product of digits of a number ; Return the product ; Function to print all numbers upto N having product of digits equal to K ; Stores whether any number satisfying the given conditions exists or not ; Iterate over the range [ 1 , N ] ; If product of digits of arr [ i ] is equal to K or not ; Print that number ; If no numbers are found ; Driver Code ; Given value of N & K ; Function call to print all numbers from [ 1 , N ] with product of digits K | def productOfDigits ( N ) : NEW_LINE INDENT product = 1 ; NEW_LINE while ( N != 0 ) : NEW_LINE INDENT product = product * ( N % 10 ) ; NEW_LINE N = N // 10 ; NEW_LINE DEDENT return product ; NEW_LINE DEDENT def productOfDigitsK ( N , K ) : NEW_LINE INDENT flag = 0 ; NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( K == productOfDigits ( i ) ) : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE flag = 1 ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 500 ; K = 10 ; NEW_LINE productOfDigitsK ( N , K ) ; NEW_LINE DEDENT |
Minimize difference between maximum and minimum array elements by removing a K | Function to minimize difference between maximum and minimum array elements by removing a K - length subarray ; Size of array ; Stores the maximum and minimum in the suffix subarray [ i . . N - 1 ] ; Traverse the array ; Stores the maximum and minimum in the prefix subarray [ 0 . . i - 1 ] ; Store the minimum difference ; Traverse the array ; If the suffix doesn 't exceed the end of the array ; Store the maximum element in array after removing subarray of size K ; Stores the maximum element in array after removing subarray of size K ; Update minimum difference ; Updating the maxPrefix and minPrefix with current element ; Print the minimum difference ; Driver Code | def minimiseDifference ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE maxSuffix = [ 0 for i in range ( N + 1 ) ] NEW_LINE minSuffix = [ 0 for i in range ( N + 1 ) ] NEW_LINE maxSuffix [ N ] = - 1e9 NEW_LINE minSuffix [ N ] = 1e9 NEW_LINE maxSuffix [ N - 1 ] = arr [ N - 1 ] NEW_LINE minSuffix [ N - 1 ] = arr [ N - 1 ] NEW_LINE i = N - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT maxSuffix [ i ] = max ( maxSuffix [ i + 1 ] , arr [ i ] ) NEW_LINE minSuffix [ i ] = min ( minSuffix [ i + 1 ] , arr [ i ] ) NEW_LINE i -= 1 NEW_LINE DEDENT maxPrefix = arr [ 0 ] NEW_LINE minPrefix = arr [ 0 ] NEW_LINE minDiff = maxSuffix [ K ] - minSuffix [ K ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( i + K <= N ) : NEW_LINE INDENT maximum = max ( maxSuffix [ i + K ] , maxPrefix ) NEW_LINE minimum = min ( minSuffix [ i + K ] , minPrefix ) NEW_LINE minDiff = min ( minDiff , maximum - minimum ) NEW_LINE DEDENT maxPrefix = max ( maxPrefix , arr [ i ] ) NEW_LINE minPrefix = min ( minPrefix , arr [ i ] ) NEW_LINE DEDENT print ( minDiff ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 5 , 8 , 9 , 1 , 2 ] NEW_LINE K = 2 NEW_LINE minimiseDifference ( arr , K ) NEW_LINE DEDENT |
Minimize segments required to be removed such that at least one segment intersects with all remaining segments | Pyhton3 program for the above approach ; Function to find the minimum number of segments required to be deleted ; Stores the start and end points ; Traverse segments and fill the startPoints and endPoints ; Sort the startPoints ; Sort the startPoints ; Store the minimum number of deletions required and initialize with ( N - 1 ) ; Traverse the array segments [ ] ; Store the starting point ; Store the ending point ; Store the number of segments satisfying the first condition of non - intersection ; Store the number of segments satisfying the second condition of non - intersection ; Update answer ; Print the answer ; Driver Code ; Function Call | from bisect import bisect_left , bisect_right NEW_LINE def minSegments ( segments , n ) : NEW_LINE INDENT startPoints = [ 0 for i in range ( n ) ] NEW_LINE endPoints = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT startPoints [ i ] = segments [ i ] [ 0 ] NEW_LINE endPoints [ i ] = segments [ i ] [ 1 ] NEW_LINE DEDENT startPoints . sort ( reverse = False ) NEW_LINE endPoints . sort ( reverse = False ) NEW_LINE ans = n - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT f = segments [ i ] [ 0 ] NEW_LINE s = segments [ i ] [ 1 ] NEW_LINE leftDelete = bisect_left ( endPoints , f ) NEW_LINE rightDelete = max ( 0 , n - bisect_right ( startPoints , s ) ) NEW_LINE ans = min ( ans , leftDelete + rightDelete ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 ] , [ 5 , 6 ] , [ 6 , 7 ] , [ 7 , 10 ] , [ 8 , 9 ] ] NEW_LINE N = len ( arr ) NEW_LINE minSegments ( arr , N ) NEW_LINE DEDENT |
Longest substring where all the characters appear at least K times | Set 3 | Function to find the length of the longest substring ; Store the required answer ; Create a frequency map of the characters of the string ; Store the length of the string ; Traverse the string , s ; Increment the frequency of the current character by 1 ; Stores count of unique characters ; Find the number of unique characters in string ; Iterate in range [ 1 , unique ] ; Initialize frequency of all characters as 0 ; Stores the start and the end of the window ; Stores the current number of unique characters and characters occuring atleast K times ; New unique character ; New character which occurs atleast k times ; Expand window by incrementing end by 1 ; Check if this character is present atleast k times ; Check if this character is unique ; Shrink the window by incrementing start by 1 ; If there are curr_unique characters and each character is atleast k times ; Update the overall maximum length ; Print the answer ; | def longestSubstring ( s , k ) : NEW_LINE INDENT ans = 0 NEW_LINE freq = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT unique = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( freq [ i ] != 0 ) : NEW_LINE INDENT unique += 1 NEW_LINE DEDENT DEDENT for curr_unique in range ( 1 , unique + 1 ) : NEW_LINE INDENT Freq = [ 0 ] * 26 NEW_LINE start , end = 0 , 0 NEW_LINE cnt , count_k = 0 , 0 NEW_LINE while ( end < n ) : NEW_LINE INDENT if ( cnt <= curr_unique ) : NEW_LINE INDENT ind = ord ( s [ end ] ) - ord ( ' a ' ) NEW_LINE if ( Freq [ ind ] == 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT Freq [ ind ] += 1 NEW_LINE if ( Freq [ ind ] == k ) : NEW_LINE INDENT count_k += 1 NEW_LINE DEDENT end += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ind = ord ( s [ start ] ) - ord ( ' a ' ) NEW_LINE if ( Freq [ ind ] == k ) : NEW_LINE INDENT count_k -= 1 NEW_LINE DEDENT Freq [ ind ] -= 1 NEW_LINE if ( Freq [ ind ] == 0 ) : NEW_LINE INDENT cnt -= 1 NEW_LINE DEDENT start += 1 NEW_LINE DEDENT if ( ( cnt == curr_unique ) and ( count_k == curr_unique ) ) : NEW_LINE INDENT ans = max ( ans , end - start ) NEW_LINE DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT / * Driver Code * / NEW_LINE S = " aabbba " NEW_LINE K = 3 NEW_LINE longestSubstring ( S , K ) NEW_LINE |
Print matrix elements using DFS traversal | Direction vectors ; Function to check if current position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited or not ; Utility function to prmatrix elements using DFS Traversal ; Mark the current cell visited ; Print element at the cell ; Traverse all four adjacent cells of the current element ; Check if x and y is valid index or not ; Function to print matrix elementsdef ; Function call to prmatrix elements by DFS traversal ; Driver Code ; Given matrix ; Row of the matrix ; Column of the matrix | dRow = [ - 1 , 0 , 1 , 0 ] NEW_LINE dCol = [ 0 , 1 , 0 , - 1 ] NEW_LINE def isValid ( row , col , COL , ROW ) : NEW_LINE INDENT global vis NEW_LINE if ( row < 0 or col < 0 or col > COL - 1 or row > ROW - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( vis [ row ] [ col ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def DFSUtil ( row , col , grid , M , N ) : NEW_LINE INDENT global vis NEW_LINE vis [ row ] [ col ] = True NEW_LINE print ( grid [ row ] [ col ] , end = " β " ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT x = row + dRow [ i ] NEW_LINE y = col + dCol [ i ] NEW_LINE if ( isValid ( x , y , M , N ) ) : NEW_LINE INDENT DFSUtil ( x , y , grid , M , N ) NEW_LINE DEDENT DEDENT DEDENT def DFS ( row , col , grid , M , N ) : NEW_LINE INDENT global vis NEW_LINE DFSUtil ( 0 , 0 , grid , M , N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT grid = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE vis = [ [ False for i in range ( M ) ] for i in range ( N ) ] NEW_LINE DFS ( 0 , 0 , grid , M , N ) NEW_LINE DEDENT |
Print matrix elements using DFS traversal | Direction vectors ; Function to check if curruent position is valid or not ; Check if the cell is out of bounds ; Check if the cell is visited ; Function to print the matrix elements ; Stores if a position in the matrix been visited or not ; Initialize stack to implement DFS ; Push the first position of grid [ ] [ ] in the stack ; Mark the cell ( 0 , 0 ) visited ; Stores top element of stack ; Delete the top ( ) element of stack ; Print element at the cell ; Traverse in all four adjacent sides of current positions ; Check if x and y is valid position and then push the position of current cell in the stack ; Push the current cell ; Mark current cell visited ; Given matrix ; Row of the matrix ; Column of the matrix | dRow = [ - 1 , 0 , 1 , 0 ] NEW_LINE dCol = [ 0 , 1 , 0 , - 1 ] NEW_LINE vis = [ ] NEW_LINE def isValid ( row , col , COL , ROW ) : NEW_LINE INDENT global vis NEW_LINE if ( row < 0 or col < 0 or col > COL - 1 or row > ROW - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( vis [ row ] [ col ] == True ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def DFS_iterative ( grid , M , N ) : NEW_LINE INDENT global vis NEW_LINE vis = [ ] NEW_LINE for i in range ( M + 5 ) : NEW_LINE INDENT vis . append ( [ ] ) NEW_LINE for j in range ( N + 5 ) : NEW_LINE INDENT vis [ i ] . append ( False ) NEW_LINE DEDENT DEDENT st = [ ] NEW_LINE st . append ( [ 0 , 0 ] ) NEW_LINE vis [ 0 ] [ 0 ] = True NEW_LINE while ( len ( st ) > 0 ) : NEW_LINE INDENT p = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE row = p [ 0 ] NEW_LINE col = p [ 1 ] NEW_LINE print ( grid [ row ] [ col ] , " " , end = " " ) NEW_LINE for i in range ( 4 ) : NEW_LINE INDENT x = row + dRow [ i ] NEW_LINE y = col + dCol [ i ] NEW_LINE if ( isValid ( x , y , M , N ) ) : NEW_LINE INDENT st . append ( [ x , y ] ) NEW_LINE vis [ x ] [ y ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT grid = [ [ 1 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 ] ] NEW_LINE M = len ( grid ) NEW_LINE N = len ( grid [ 0 ] ) NEW_LINE DFS_iterative ( grid , M , N ) NEW_LINE |
Segregate 1 s and 0 s in separate halves of a Binary String | Function to count the minimum number of operations required to segregate all 1 s and 0 s in a binary string ; Stores the count of unequal pair of adjacent characters ; If an unequal pair of adjacent characters occurs ; For odd count ; For even count ; Given string ; Length of the string ; Prints the minimum count of operations required | def minOps ( s , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( s [ i ] != s [ i - 1 ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( ans % 2 == 1 ) : NEW_LINE INDENT print ( ( ans - 1 ) // 2 ) NEW_LINE return NEW_LINE DEDENT print ( ans // 2 ) NEW_LINE DEDENT str = "01011100" NEW_LINE N = len ( str ) NEW_LINE minOps ( str , N ) NEW_LINE |
Find index of the element differing in parity with all other array elements | Function to print the array element which differs in parity with the remaining array elements ; Multimaps to store even and odd numbers along with their indices ; Traverse the array ; If array element is even ; Otherwise ; If only one even element is present in the array ; If only one odd element is present in the array ; ; Given array ; Size of the array | def OddOneOut ( arr , N ) : NEW_LINE INDENT e , o = { } , { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT e [ arr [ i ] ] = i NEW_LINE DEDENT else : NEW_LINE INDENT o [ arr [ i ] ] = i NEW_LINE DEDENT DEDENT if ( len ( e ) == 1 ) : NEW_LINE INDENT print ( list ( e . values ( ) ) [ 0 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( list ( o . values ( ) ) [ 0 ] ) NEW_LINE DEDENT DEDENT / * Driver Code * / NEW_LINE arr = [ 2 , 4 , 7 , 8 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE OddOneOut ( arr , N ) NEW_LINE |
Count indices where the maximum in the prefix array is less than that in the suffix array | Function to print the count of indices in which the maximum in prefix arrays is less than that in the suffix array ; If size of array is 1 ; pre [ ] : Prefix array suf [ ] : Suffix array ; Stores the required count ; Find the maximum in prefix array ; Find the maximum in suffix array ; Traverse the array ; If maximum in prefix array is less than maximum in the suffix array ; Print the answer ; Driver Code ; Function Call | def count ( a , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT pre = [ 0 ] * ( n - 1 ) NEW_LINE suf = [ 0 ] * ( n - 1 ) NEW_LINE max = a [ 0 ] NEW_LINE ans = 0 NEW_LINE pre [ 0 ] = a [ 0 ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] > max ) : NEW_LINE INDENT max = a [ i ] NEW_LINE DEDENT pre [ i ] = max NEW_LINE DEDENT max = a [ n - 1 ] NEW_LINE suf [ n - 2 ] = a [ n - 1 ] NEW_LINE for i in range ( n - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( a [ i ] > max ) : NEW_LINE INDENT max = a [ i ] NEW_LINE DEDENT suf [ i - 1 ] = max NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( pre [ i ] < suf [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 8 , 1 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE count ( arr , N ) NEW_LINE |
Length of the longest subsequence such that XOR of adjacent elements is equal to K | Function to find maximum length of subsequence ; Stores maximum length of subsequence ; HashMap to store the longest length of subsequence ending at an integer , say X ; Stores the maximum length of subsequence ending at index i ; Base case ; Iterate over the range [ 1 , N - 1 ] ; If dpj is not NULL ; Update dp [ i ] ; Update ans ; Update the maximum length of subsequence ending at element is a [ i ] in HashMap ; Return the ans if ans >= 2. Otherwise , return 0 ; Driver Code ; Input ; Print the length of the longest subsequence | def xorSubsequence ( a , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE map = { } NEW_LINE dp = [ 0 ] * n NEW_LINE map [ a [ 0 ] ] = 1 NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] ^ k in map ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , map [ a [ i ] ^ k ] + 1 ) NEW_LINE DEDENT ans = max ( ans , dp [ i ] ) NEW_LINE if a [ i ] in map : NEW_LINE INDENT map [ a [ i ] ] = max ( map [ a [ i ] ] , dp [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT map [ a [ i ] ] = max ( 1 , dp [ i ] ) NEW_LINE DEDENT DEDENT if ans >= 2 : NEW_LINE return ans NEW_LINE return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 4 , 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE K = 1 NEW_LINE print ( xorSubsequence ( arr , N , K ) ) NEW_LINE DEDENT |
Sum of subtree depths for every node of a given Binary Tree | Binary tree node ; Constructor to set the data of the newly created tree node ; Function to allocate a new node with the given data and null in its left and right pointers ; DFS function to calculate the sum of depths of all subtrees depth sum ; Store total number of node in its subtree and total sum of depth in its subtree ; Check if left is not null ; Call recursively the DFS function for left child ; Increment the sum of depths by ptemp . first + p . temp . first ; Increment p . first by count of noded in left subtree ; Check if right is not null ; Call recursively the DFS function for right child ; Increment the sum of depths by ptemp . first + p . temp . first ; Increment p . first by count of nodes in right subtree ; Increment the result by total sum of depth in current subtree ; Return p ; Given Tree ; Print the result | class TreeNode : 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 ans = 0 NEW_LINE def newNode ( data ) : NEW_LINE INDENT Node = TreeNode ( data ) NEW_LINE return ( Node ) NEW_LINE DEDENT def sumofsubtree ( root ) : NEW_LINE INDENT global ans NEW_LINE p = [ 1 , 0 ] NEW_LINE if ( root . left != None ) : NEW_LINE INDENT ptemp = sumofsubtree ( root . left ) NEW_LINE p [ 1 ] += ptemp [ 0 ] + ptemp [ 1 ] NEW_LINE p [ 0 ] += ptemp [ 0 ] NEW_LINE DEDENT if ( root . right != None ) : NEW_LINE INDENT ptemp = sumofsubtree ( root . right ) NEW_LINE p [ 1 ] += ptemp [ 0 ] + ptemp [ 1 ] NEW_LINE p [ 0 ] += ptemp [ 0 ] NEW_LINE DEDENT ans += p [ 1 ] NEW_LINE return p NEW_LINE DEDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . left . left . left = newNode ( 8 ) NEW_LINE root . left . left . right = newNode ( 9 ) NEW_LINE sumofsubtree ( root ) NEW_LINE print ( ans ) NEW_LINE |
Minimum time required to fill given N slots | Function to return the minimum time to fill all the slots ; Stores visited slots ; Checks if a slot is visited or not ; Insert all filled slots ; Iterate until queue is not empty ; Iterate through all slots in the queue ; Front index ; If previous slot is present and not visited ; If next slot is present and not visited ; Increment the time at each level ; Print the answer ; Driver Code ; Function Call | def minTime ( arr , N , K ) : NEW_LINE INDENT q = [ ] NEW_LINE vis = [ False ] * ( N + 1 ) NEW_LINE time = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT q . append ( arr [ i ] ) NEW_LINE vis [ arr [ i ] ] = True NEW_LINE DEDENT while ( len ( q ) > 0 ) : NEW_LINE INDENT for i in range ( len ( q ) ) : NEW_LINE INDENT curr = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( curr - 1 >= 1 and vis [ curr - 1 ] == 0 ) : NEW_LINE INDENT vis [ curr - 1 ] = True NEW_LINE q . append ( curr - 1 ) NEW_LINE DEDENT if ( curr + 1 <= N and vis [ curr + 1 ] == 0 ) : NEW_LINE INDENT vis [ curr + 1 ] = True NEW_LINE q . append ( curr + 1 ) NEW_LINE DEDENT DEDENT time += 1 NEW_LINE DEDENT print ( time - 1 ) NEW_LINE DEDENT N = 6 NEW_LINE arr = [ 2 , 6 ] NEW_LINE K = len ( arr ) NEW_LINE minTime ( arr , N , K ) NEW_LINE |
Count of integers having difference with its reverse equal to D | Maximum digits in N ; Utility function to find count of N such that N + D = reverse ( N ) ; If d is a multiple of 9 , no such value N found ; Divide D by 9 check reverse of number and its sum ; B [ i ] : Stores power of ( 10 , i ) ; Calculate power ( 10 , i ) ; Update B [ i ] ; Stores count of N such that N + D = reverse ( N ) ; Iterate over the range [ 1 , MAXL ] ; Update ans ; Function to find count of possible values of N such that N + D = reverse ( N ) ; Base Case ; If D is not qual to 0 ; Stores count of possible values of N such that N + D = reverse ( N ) ; Update ans ; If l is even ; Update ans ; Stores count of possible values of N such that N + D = reverse ( N ) ; Iterae over the range [ - 9 , 9 ] ; Update ans ; Driver Code ; Function call | MAXL = 17 ; NEW_LINE N = 0 ; NEW_LINE v = 0 ; NEW_LINE def findN ( D ) : NEW_LINE INDENT global N ; NEW_LINE global v ; NEW_LINE if ( D % 9 != 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT D //= 9 ; NEW_LINE B = [ 0 ] * MAXL ; NEW_LINE B [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , MAXL ) : NEW_LINE INDENT B [ i ] = B [ i - 1 ] * 10 ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( 1 , MAXL + 1 ) : NEW_LINE INDENT N = ( i + 1 ) // 2 ; NEW_LINE v = [ 0 ] * N ; NEW_LINE for j in range ( N ) : NEW_LINE INDENT for k in range ( j , i - j ) : NEW_LINE INDENT v [ j ] += B [ k ] ; NEW_LINE DEDENT DEDENT temp = [ 0 ] * N ; NEW_LINE ans += count ( D , i , 0 , temp ) ; NEW_LINE return ans ; NEW_LINE DEDENT DEDENT def count ( D , l , t , x ) : NEW_LINE INDENT global N ; NEW_LINE global v ; NEW_LINE if ( t == N ) : NEW_LINE INDENT if ( D != 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT ans = 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT ans *= ( 9 if i == 0 else 10 ) - abs ( x [ i ] ) ; NEW_LINE DEDENT if ( l % 2 == 0 ) : NEW_LINE INDENT ans *= 10 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for m in range ( - 9 , 10 ) : NEW_LINE INDENT if ( - v [ t ] < D + v [ t ] * m and D + v [ t ] * m < v [ t ] ) : NEW_LINE INDENT x [ t ] = m ; NEW_LINE ans += count ( D + v [ t ] * m , l , t + 1 , x ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT D = 63 ; NEW_LINE print ( findN ( D ) ) ; NEW_LINE DEDENT |
Search for an element in a Mountain Array | Function to find the index of the peak element in the array ; Stores left most index in which the peak element can be found ; Stores right most index in which the peak element can be found ; Stores mid of left and right ; If element at mid is less than element at ( mid + 1 ) ; Update left ; Update right ; Function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; Stores mid of left and right ; If X found at mid ; If X is greater than mid ; Update left ; Update right ; Function to perform binary search in an a subarray if elements of the subarray are in an ascending order ; Stores mid of left and right ; If X found at mid ; Update right ; Update left ; Function to find the smallest index of X ; Stores index of peak element in array ; Stores index of X in the array ; If X greater than or equal to first element of array and less than the peak element ; Update res ; If element not found on left side of peak element ; Update res ; Print res ; Driver Code ; Given X ; Given array ; Function Call | def findPeak ( arr ) : NEW_LINE INDENT left = 0 NEW_LINE right = len ( arr ) - 1 NEW_LINE while ( left < right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE if ( arr [ mid ] < arr [ ( mid + 1 ) ] ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid NEW_LINE DEDENT DEDENT return left NEW_LINE DEDENT def BS ( X , left , right , arr ) : NEW_LINE INDENT while ( left <= right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE if ( arr [ mid ] == X ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( X > arr [ mid ] ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def reverseBS ( X , left , right , arr ) : NEW_LINE INDENT while ( left <= right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE if ( arr [ mid ] == X ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( X > arr [ mid ] ) : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def findInMA ( X , mountainArr ) : NEW_LINE INDENT peakIndex = findPeak ( mountainArr ) NEW_LINE res = - 1 NEW_LINE if ( X >= mountainArr [ 0 ] and X <= mountainArr [ peakIndex ] ) : NEW_LINE INDENT res = BS ( X , 0 , peakIndex , mountainArr ) NEW_LINE DEDENT if ( res == - 1 ) : NEW_LINE INDENT res = reverseBS ( X , peakIndex + 1 , mountainArr . size ( ) - 1 , mountainArr ) NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = 3 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 , 3 , 1 ] NEW_LINE findInMA ( X , arr ) NEW_LINE DEDENT |
Rearrange given array to obtain positive prefix sums at exactly X indices | Function to rearrange the array according to the given condition ; Using 2 nd operation making all values positive ; Sort the array ; Assign K = N - K ; Count number of zeros ; If number of zeros if greater ; Using 2 nd operation convert it into one negative ; Using 2 nd operation convert it into one negative ; Print array ; Driver Code ; Function Call | def rearrange ( a , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT a [ i ] = abs ( a [ i ] ) NEW_LINE DEDENT a = sorted ( a ) NEW_LINE x = n - x ; NEW_LINE z = a . count ( 0 ) NEW_LINE if ( x > n - z ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , n , 2 ) : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT a [ i ] = - a [ i ] NEW_LINE x -= 1 NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if x <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT if ( a [ i ] > 0 ) : NEW_LINE INDENT a [ i ] = - a [ i ] NEW_LINE x -= 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , - 2 , 4 , 5 , - 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE rearrange ( arr , N , K ) NEW_LINE DEDENT |
Maximize product of a strictly increasing or decreasing subarray | Function to find the maximum product of subarray in the array , arr [ ] ; Maximum positive product ending at the i - th index ; Minimum negative product ending at the current index ; Maximum product up to i - th index ; Check if an array element is positive or not ; Traverse the array ; If current element is positive ; Update max_ending_here ; Update min_ending_here ; Update flag ; If current element is 0 , reset the start index of subarray ; Update max_ending_here ; Update min_ending_here ; If current element is negative ; Stores max_ending_here ; Update max_ending_here ; Update min_ending_here ; Update max_so_far , if needed ; If no array elements is positive and max_so_far is 0 ; Function to find the maximum product of either increasing subarray or the decreasing subarray ; Stores start index of either increasing subarray or the decreasing subarray ; Initially assume maxProd to be 1 ; Traverse the array ; Store the longest either increasing subarray or the decreasing subarray whose start index is i ; Check for increasing subarray ; Insert elements of increasing subarray ; Check for decreasing subarray ; Insert elements of decreasing subarray ; Stores maximum subarray product of current increasing or decreasing subarray ; Update maxProd ; Update i ; Finally prmaxProd ; Driver Code | def maxSubarrayProduct ( arr , n ) : NEW_LINE INDENT max_ending_here = 1 NEW_LINE min_ending_here = 1 NEW_LINE max_so_far = 0 NEW_LINE flag = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT max_ending_here = max_ending_here * arr [ i ] NEW_LINE min_ending_here = min ( min_ending_here * arr [ i ] , 1 ) NEW_LINE flag = 1 NEW_LINE DEDENT elif ( arr [ i ] == 0 ) : NEW_LINE INDENT max_ending_here = 1 NEW_LINE min_ending_here = 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp = max_ending_here NEW_LINE max_ending_here = max ( min_ending_here * arr [ i ] , 1 ) NEW_LINE min_ending_here = temp * arr [ i ] NEW_LINE DEDENT if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT DEDENT if ( flag == 0 and max_so_far == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max_so_far NEW_LINE DEDENT def findMaxProduct ( a , n ) : NEW_LINE INDENT i = 0 NEW_LINE maxProd = - 10 ** 9 NEW_LINE while ( i < n ) : NEW_LINE INDENT v = [ ] NEW_LINE v . append ( a [ i ] ) NEW_LINE if i < n - 1 and a [ i ] < a [ i + 1 ] : NEW_LINE INDENT while ( i < n - 1 and a [ i ] < a [ i + 1 ] ) : NEW_LINE INDENT v . append ( a [ i + 1 ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT elif ( i < n - 1 and a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT while ( i < n - 1 and a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT v . append ( a [ i + 1 ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT prod = maxSubarrayProduct ( v , len ( v ) ) NEW_LINE maxProd = max ( maxProd , prod ) NEW_LINE i += 1 NEW_LINE DEDENT return maxProd NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 10 , 8 , 1 , 100 , 101 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaxProduct ( arr , N ) ) NEW_LINE DEDENT |
Number of connected components of a graph ( using Disjoint Set Union ) | Stores the parent of each vertex ; Function to find the topmost parent of vertex a ; If current vertex is the topmost vertex ; Otherwise , set topmost vertex of its parent as its topmost vertex ; Function to connect the component having vertex a with the component having vertex b ; Connect edges ; Function to find unique top most parents ; Traverse all vertices ; Insert all topmost vertices obtained ; Print count of connected components ; Function to print answer ; Setting parent to itself ; Traverse all edges ; Print answer ; Given N ; Given edges ; Function call | parent = [ 0 ] * ( 1000000 ) NEW_LINE def root ( a ) : NEW_LINE INDENT if ( a == parent [ a ] ) : NEW_LINE INDENT return a NEW_LINE DEDENT parent [ a ] = root ( parent [ a ] ) NEW_LINE return parent [ a ] NEW_LINE DEDENT def connect ( a , b ) : NEW_LINE INDENT a = root ( a ) NEW_LINE b = root ( b ) NEW_LINE if ( a != b ) : NEW_LINE INDENT parent [ b ] = a NEW_LINE DEDENT DEDENT def connectedComponents ( n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( root ( parent [ i ] ) ) NEW_LINE DEDENT print ( len ( s ) ) NEW_LINE DEDENT def printAnswer ( N , edges ) : NEW_LINE INDENT for i in range ( N + 1 ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE DEDENT for i in range ( len ( edges ) ) : NEW_LINE INDENT connect ( edges [ i ] [ 0 ] , edges [ i ] [ 1 ] ) NEW_LINE DEDENT connectedComponents ( N ) NEW_LINE DEDENT N = 6 NEW_LINE edges = [ [ 1 , 0 ] , [ 2 , 3 ] , [ 1 , 2 ] , [ 4 , 5 ] ] NEW_LINE printAnswer ( N , edges ) NEW_LINE |
Remove all zero | Function to remove the rows or columns from the matrix which contains all 0 s elements ; Stores count of rows ; col [ i ] : Stores count of 0 s in current column ; row [ i ] : Stores count of 0 s in current row ; Traverse the matrix ; Stores count of 0 s in current row ; Update col [ j ] ; Update count ; Update row [ i ] ; Traverse the matrix ; If all elements of current row is 0 ; If all elements of current column is 0 ; Driver Code ; Function Call | def removeZeroRowCol ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE col = [ 0 ] * ( n + 1 ) NEW_LINE row = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT col [ j ] += ( arr [ i ] [ j ] == 1 ) NEW_LINE count += ( arr [ i ] [ j ] == 1 ) NEW_LINE DEDENT row [ i ] = count NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( row [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT if ( col [ j ] != 0 ) : NEW_LINE INDENT print ( arr [ i ] [ j ] , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT arr = [ [ 1 , 1 , 0 , 1 ] , [ 0 , 0 , 0 , 0 ] , [ 1 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 1 ] ] NEW_LINE removeZeroRowCol ( arr ) NEW_LINE |
Find a pair of overlapping intervals from a given Set | Function to find a pair ( i , j ) such that i - th interval lies within the j - th interval ; Store interval and index of the interval in the form of { { l , r } , index } ; Traverse the array , arr [ ] [ ] ; Stores l - value of the interval ; Stores r - value of the interval ; Push current interval and index into tup ; Sort the vector based on l - value of the intervals ; Stores r - value of current interval ; Stores index of current interval ; Traverse the vector , tup [ ] ; Stores l - value of previous interval ; Stores l - value of current interval ; If Q and R are equal ; Print the index of interval ; Stores r - value of current interval ; If T is less than or equal to curr ; Update curr ; Update currPos ; If such intervals found ; Given l - value of segments ; Given r - value of segments ; Given size ; Function Call | def findOverlapSegement ( N , a , b ) : NEW_LINE INDENT tup = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT x = a [ i ] NEW_LINE y = b [ i ] NEW_LINE tup . append ( ( ( x , y ) , i ) ) NEW_LINE DEDENT tup . sort ( ) NEW_LINE curr = tup [ 0 ] [ 0 ] [ 1 ] NEW_LINE currPos = tup [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT Q = tup [ i - 1 ] [ 0 ] [ 0 ] NEW_LINE R = tup [ i ] [ 0 ] [ 0 ] NEW_LINE if Q == R : NEW_LINE INDENT if tup [ i - 1 ] [ 0 ] [ 1 ] < tup [ i ] [ 0 ] [ 1 ] : NEW_LINE INDENT print ( tup [ i - 1 ] [ 1 ] , tup [ i ] [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( tup [ i ] [ 1 ] , tup [ i - 1 ] [ 1 ] ) NEW_LINE DEDENT return NEW_LINE DEDENT T = tup [ i ] [ 0 ] [ 1 ] NEW_LINE if ( T <= curr ) : NEW_LINE INDENT print ( tup [ i ] [ 1 ] , currPos ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT curr = T NEW_LINE currPos = tup [ i ] [ 1 ] NEW_LINE DEDENT DEDENT print ( " - 1" , " - 1" , end = " " ) NEW_LINE DEDENT a = [ 1 , 2 , 3 , 2 , 2 ] NEW_LINE b = [ 5 , 10 , 10 , 2 , 15 ] NEW_LINE N = len ( a ) NEW_LINE findOverlapSegement ( N , a , b ) NEW_LINE |
Replace each node of a Binary Tree with the sum of all the nodes present in its diagonal | Structure of a tree node ; Function to replace each node with the sum of nodes at the same diagonal ; IF root is NULL ; Replace nodes ; Traverse the left subtree ; Traverse the right subtree ; Function to find the sum of all the nodes at each diagonal of the tree ; If root is not NULL ; If update sum of nodes at current diagonal ; Traverse the left subtree ; Traverse the right subtree ; Function to print the nodes of the tree using level order traversal ; Stores node at each level of the tree ; Stores count of nodes at current level ; Stores front element of the queue ; Insert left subtree ; Insert right subtree ; Update length ; Driver code ; Build tree ; Store sum of nodes at each diagonal of the tree ; Find sum of nodes at each diagonal of the tree ; Replace nodes with the sum of nodes at the same diagonal ; Print tree | class TreeNode : NEW_LINE INDENT def __init__ ( self , val = 0 , left = None , right = None ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def replaceDiag ( root , d , diagMap ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT root . val = diagMap [ d ] NEW_LINE replaceDiag ( root . left , d + 1 , diagMap ) NEW_LINE replaceDiag ( root . right , d , diagMap ) NEW_LINE DEDENT def getDiagSum ( root , d , diagMap ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return NEW_LINE DEDENT if d in diagMap : NEW_LINE INDENT diagMap [ d ] += root . val NEW_LINE DEDENT else : NEW_LINE INDENT diagMap [ d ] = root . val NEW_LINE DEDENT getDiagSum ( root . left , d + 1 , diagMap ) NEW_LINE getDiagSum ( root . right , d , diagMap ) NEW_LINE DEDENT def levelOrder ( root ) : NEW_LINE INDENT que = [ root ] NEW_LINE while True : NEW_LINE INDENT length = len ( que ) NEW_LINE if not length : NEW_LINE INDENT break NEW_LINE DEDENT while length : NEW_LINE INDENT temp = que . pop ( 0 ) NEW_LINE print ( temp . val , end = ' β ' ) NEW_LINE if temp . left : NEW_LINE INDENT que . append ( temp . left ) NEW_LINE DEDENT if temp . right : NEW_LINE INDENT que . append ( temp . right ) NEW_LINE DEDENT length -= 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 5 ) NEW_LINE root . left = TreeNode ( 6 ) NEW_LINE root . right = TreeNode ( 3 ) NEW_LINE root . left . left = TreeNode ( 4 ) NEW_LINE root . left . right = TreeNode ( 9 ) NEW_LINE root . right . right = TreeNode ( 2 ) NEW_LINE diagMap = { } NEW_LINE getDiagSum ( root , 0 , diagMap ) NEW_LINE replaceDiag ( root , 0 , diagMap ) NEW_LINE levelOrder ( root ) NEW_LINE DEDENT |
Count maximum concatenation of pairs from given array that are divisible by 3 | Function to count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Stores count pairs whose concatenation is divisible by 3 and each element can be present in at most one pair ; Check if an element present in any pair or not ; Generate all possible pairs ; If the element already present in a pair ; If the element already present in a pair ; If concatenation of elements is divisible by 3 ; Update ans ; Mark i is True ; Mark j is True ; Driver Code ; To display the result | def countDivBy3InArray ( arr ) : NEW_LINE INDENT ans = 0 NEW_LINE taken = [ False ] * len ( arr ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if taken [ i ] : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( i + 1 , len ( arr ) ) : NEW_LINE INDENT if taken [ j ] : NEW_LINE INDENT continue NEW_LINE DEDENT if ( not int ( str ( arr [ i ] ) + str ( arr [ j ] ) ) % 3 or not int ( str ( arr [ j ] ) + str ( arr [ i ] ) ) % 3 ) : NEW_LINE INDENT ans += 1 NEW_LINE taken [ i ] = True NEW_LINE taken [ j ] = True NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 5 , 3 , 2 , 8 , 7 ] NEW_LINE print ( countDivBy3InArray ( arr ) ) NEW_LINE |
Longest increasing sequence possible by the boundary elements of an Array | Function to find longest strictly increasing sequence using boundary elements ; Maintains rightmost element in the sequence ; Pointer to start of array ; Pointer to end of array ; Stores the required sequence ; Traverse the array ; If arr [ i ] > arr [ j ] ; If arr [ j ] is greater than rightmost element of the sequence ; Push arr [ j ] into the sequence ; Update rightmost element ; Push arr [ i ] into the sequence ; Update rightmost element ; If arr [ i ] < arr [ j ] ; If arr [ i ] > rightmost element ; Push arr [ i ] into the sequence ; Update rightmost element ; If arr [ j ] > rightmost element ; Push arr [ j ] into the sequence ; Update rightmost element ; If arr [ i ] is equal to arr [ j ] ; If i and j are at the same element ; If arr [ i ] > rightmostelement ; Push arr [ j ] into the sequence ; Update rightmost element ; Traverse array from left to right ; Stores the increasing sequence from the left end ; Traverse array from left to right ; Push arr [ k ] to max_left vector ; Traverse the array from right to left ; Stores the increasing sequence from the right end ; Traverse array from right to left ; Push arr [ k ] to max_right vector ; If size of max_left is greater than max_right ; Push max_left elements to the original sequence ; Otherwise ; Push max_right elements to the original sequence ; Print the sequence ; Driver Code ; Print the longest increasing sequence using boundary elements | def findMaxLengthSequence ( N , arr ) : NEW_LINE INDENT rightmost_element = - 1 NEW_LINE i = 0 NEW_LINE j = N - 1 NEW_LINE sequence = [ ] NEW_LINE while ( i <= j ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT if ( arr [ j ] > rightmost_element ) : NEW_LINE INDENT sequence . append ( arr [ j ] ) NEW_LINE rightmost_element = arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ i ] > rightmost_element ) : NEW_LINE INDENT sequence . append ( arr [ i ] ) NEW_LINE rightmost_element = arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( arr [ i ] < arr [ j ] ) : NEW_LINE INDENT if ( arr [ i ] > rightmost_element ) : NEW_LINE INDENT sequence . append ( arr [ i ] ) NEW_LINE rightmost_element = arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT elif ( arr [ j ] > rightmost_element ) : NEW_LINE INDENT sequence . append ( arr [ j ] ) NEW_LINE rightmost_element = arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT if ( arr [ i ] > rightmost_element ) : NEW_LINE INDENT sequence . append ( arr [ i ] ) NEW_LINE rightmost_element = arr [ i ] NEW_LINE i += 1 NEW_LINE DEDENT break NEW_LINE DEDENT else : NEW_LINE INDENT sequence . append ( arr [ i ] ) NEW_LINE k = i + 1 NEW_LINE max_left = [ ] NEW_LINE while ( k < j and arr [ k ] > arr [ k - 1 ] ) : NEW_LINE INDENT max_left . append ( arr [ k ] ) NEW_LINE k += 1 NEW_LINE DEDENT l = j - 1 NEW_LINE max_right = [ ] NEW_LINE while ( l > i and arr [ l ] > arr [ l + 1 ] ) : NEW_LINE INDENT max_right . append ( arr [ l ] ) NEW_LINE l -= 1 NEW_LINE DEDENT if ( len ( max_left ) > len ( max_right ) ) : NEW_LINE INDENT for element in max_left : NEW_LINE INDENT sequence . append ( element ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for element in max_right : NEW_LINE INDENT sequence . append ( element ) NEW_LINE DEDENT DEDENT break NEW_LINE DEDENT DEDENT DEDENT for element in sequence : NEW_LINE INDENT print ( element , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE arr = [ 1 , 3 , 2 , 1 ] NEW_LINE findMaxLengthSequence ( N , arr ) NEW_LINE DEDENT |
Maximum average of subtree values in a given Binary Tree | Structure of the Tree node ; Stores the result ; Function for finding maximum subtree average ; Checks if current node is not None and doesn 't have any children ; Stores sum of its subtree in index 0 and count number of nodes in index 1 ; Traverse all children of the current node ; Recursively calculate max average of subtrees among its children ; Increment sum by sum of its child 's subtree ; Increment number of nodes by its child 's node ; Increment sum by current node 's value ; Increment number of nodes by one ; Take maximum of ans and current node 's average ; Finally return pair of { sum , count } ; Driver Code ; Given tree ; Function call ; Print answer | class TreeNode : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . children = [ ] NEW_LINE DEDENT DEDENT ans = 0.0 NEW_LINE def MaxAverage ( root ) : NEW_LINE INDENT global ans NEW_LINE if ( root != None and len ( root . children ) == 0 ) : NEW_LINE INDENT ans = max ( ans , ( root . val ) ) NEW_LINE return [ root . val , 1 ] NEW_LINE DEDENT childResult = [ 0 for i in range ( 2 ) ] NEW_LINE for child in root . children : NEW_LINE INDENT childTotal = MaxAverage ( child ) NEW_LINE childResult [ 0 ] = childResult [ 0 ] + childTotal [ 0 ] NEW_LINE childResult [ 1 ] = childResult [ 1 ] + childTotal [ 1 ] NEW_LINE DEDENT sum = childResult [ 0 ] + root . val NEW_LINE count = childResult [ 1 ] + 1 NEW_LINE ans = max ( ans , sum / count ) NEW_LINE return [ sum , count ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = TreeNode ( 20 ) NEW_LINE left = TreeNode ( 12 ) NEW_LINE right = TreeNode ( 18 ) NEW_LINE root . children . append ( left ) NEW_LINE root . children . append ( right ) NEW_LINE left . children . append ( TreeNode ( 11 ) ) NEW_LINE left . children . append ( TreeNode ( 3 ) ) NEW_LINE right . children . append ( TreeNode ( 15 ) ) NEW_LINE right . children . append ( TreeNode ( 8 ) ) NEW_LINE MaxAverage ( root ) NEW_LINE print ( ans * 1.0 ) NEW_LINE DEDENT |
Check if a Binary String can be converted to another by reversing substrings consisting of even number of 1 s | Function to check if string A can be transformed to string B by reversing substrings of A having even number of 1 s ; Store the size of string A ; Store the size of string B ; Store the count of 1 s in A and B ; Stores cntA for string A and cntB for string B ; Traverse the string A ; If current character is 1 ; Increment 1 s count ; Otherwise , update odd1A or even1A depending whether count1A is odd or even ; Traverse the string B ; If current character is 1 ; Increment 1 s count ; Otherwise , update odd1B or even1B depending whether count1B is odd or even ; If the condition is satisfied ; If True , prYes ; Otherwise , prNo ; Driver Code ; Function Call | def canTransformStrings ( A , B ) : NEW_LINE INDENT n1 = len ( A ) ; NEW_LINE n2 = len ( B ) ; NEW_LINE count1A = 0 ; NEW_LINE count1B = 0 ; NEW_LINE odd1A = 0 ; odd1B = 0 ; NEW_LINE even1A = 0 ; even1B = 0 ; NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT if ( A [ i ] == '1' ) : NEW_LINE INDENT count1A += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( count1A & 1 ) == 1 ) : NEW_LINE INDENT odd1A += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT even1A += 1 ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( n2 ) : NEW_LINE INDENT if ( B [ i ] == '1' ) : NEW_LINE INDENT count1B += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( count1B & 1 ) == 1 ) : NEW_LINE INDENT odd1B += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT even1B += 1 ; NEW_LINE DEDENT DEDENT DEDENT if ( count1A == count1B and odd1A == odd1B and even1A == even1B ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = "10011" ; NEW_LINE B = "11100" ; NEW_LINE canTransformStrings ( A , B ) ; NEW_LINE DEDENT |
Smallest element present in every subarray of all possible lengths | Function to print the common elements for all subarray lengths ; Function to find and store the minimum element present in all subarrays of all lengths from 1 to n ; Skip lengths for which answer [ i ] is - 1 ; Initialize minimum as the first element where answer [ i ] is not - 1 ; Updating the answer array ; If answer [ i ] is - 1 , then minimum can be substituted in that place ; Find minimum answer ; Function to find the minimum number corresponding to every subarray of length K , for every K from 1 to N ; Stores the minimum common elements for all subarray lengths Initialize with - 1. ; Find for every element , the minimum length such that the number is present in every subsequence of that particular length or more ; To store first occurence and gaps between occurences ; To cover the distance between last occurence and the end of the array ; To find the distance between any two occurences ; Update and store the answer ; Print the required answer ; Function to find the smallest element common in all subarrays for every possible subarray lengths ; Initializing indices array ; Store the numbers present in the array ; Push the index in the indices [ A [ i ] ] and also store the numbers in set to get the numbers present in input array ; Function call to calculate length of subarray for which a number is present in every subarray of that length ; Given array ; Size of array ; Function Call | def printAnswer ( answer , N ) : NEW_LINE INDENT for i in range ( N + 1 ) : NEW_LINE INDENT print ( answer [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def updateAnswerArray ( answer , N ) : NEW_LINE INDENT i = 0 NEW_LINE while ( answer [ i ] == - 1 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT minimum = answer [ i ] NEW_LINE while ( i <= N ) : NEW_LINE INDENT if ( answer [ i ] == - 1 ) : NEW_LINE INDENT answer [ i ] = minimum NEW_LINE DEDENT else : NEW_LINE INDENT answer [ i ] = min ( minimum , answer [ i ] ) NEW_LINE DEDENT minimum = min ( minimum , answer [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def lengthOfSubarray ( indices , st , N ) : NEW_LINE INDENT answer = [ - 1 for i in range ( N + 1 ) ] NEW_LINE for itr in st : NEW_LINE INDENT start = - 1 NEW_LINE gap = - 1 NEW_LINE indices [ itr ] . append ( N ) NEW_LINE for i in range ( len ( indices [ itr ] ) ) : NEW_LINE INDENT gap = max ( gap , indices [ itr ] [ i ] - start ) NEW_LINE start = indices [ itr ] [ i ] NEW_LINE DEDENT if ( answer [ gap ] == - 1 ) : NEW_LINE INDENT answer [ gap ] = itr NEW_LINE DEDENT DEDENT updateAnswerArray ( answer , N ) NEW_LINE printAnswer ( answer , N ) NEW_LINE DEDENT def smallestPresentNumber ( arr , N ) : NEW_LINE INDENT indices = [ [ ] for i in range ( N + 1 ) ] NEW_LINE elements = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT indices [ arr [ i ] ] . append ( i ) NEW_LINE elements . append ( arr [ i ] ) NEW_LINE DEDENT elements = list ( set ( elements ) ) NEW_LINE lengthOfSubarray ( indices , elements , N ) NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 3 , 2 , 3 , 1 , 3 , 2 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE smallestPresentNumber ( arr , N ) NEW_LINE |
Minimize remaining array element by removing pairs and replacing them by their absolute difference | function to find the smallest element left in the array by the given operations ; Base Case ; If this subproblem has occurred previously ; Including i - th array element into the first subset ; If i - th array element is not selected ; Update dp [ i ] [ sum ] ; Utility function to find smallest element left in the array by the given operations ; Stores sum of the array elements ; Traverse the array ; Update total ; Stores overlapping subproblems ; Driver Code | def smallestLeft ( arr , total , sum , i , dp ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return abs ( total - 2 * sum ) NEW_LINE DEDENT if ( dp [ i ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ sum ] NEW_LINE DEDENT X = smallestLeft ( arr , total , sum + arr [ i - 1 ] , i - 1 , dp ) NEW_LINE Y = smallestLeft ( arr , total , sum , i - 1 , dp ) NEW_LINE dp [ i ] [ sum ] = min ( X , Y ) NEW_LINE return dp [ i ] [ sum ] NEW_LINE DEDENT def UtilSmallestElement ( arr , N ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT total += arr [ i ] NEW_LINE DEDENT dp = [ [ - 1 for y in range ( total ) ] for x in range ( N + 1 ) ] NEW_LINE print ( smallestLeft ( arr , total , 0 , N , dp ) ) NEW_LINE DEDENT arr = [ 2 , 7 , 4 , 1 , 8 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE UtilSmallestElement ( arr , N ) NEW_LINE |
Minimize remaining array element by removing pairs and replacing them by their absolute difference | Function to find minimize the remaining array element by removing pairs and replacing them by their absolute difference ; Stores sum of array elements ; Traverse the array ; Update totalSum ; Stores half of totalSum ; dp [ i ] : True if sum i can be obtained as a subset sum ; Base case ; Stores closest sum that can be obtained as a subset sum ; Traverse the array ; Iterate over all possible value of sum ; Update dp [ j ] ; If sum i can be obtained from array elements ; Update reach ; Driver Code | def SmallestElementLeft ( arr , N ) : NEW_LINE INDENT totalSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT totalSum += arr [ i ] NEW_LINE DEDENT req = totalSum // 2 NEW_LINE dp = [ False for i in range ( req + 1 ) ] NEW_LINE memset ( dp , false , sizeof ( dp ) ) ; NEW_LINE dp [ 0 ] = True NEW_LINE reach = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT j = req NEW_LINE while j >= arr [ i ] : NEW_LINE INDENT dp [ j ] = dp [ j ] or dp [ j - arr [ i ] ] NEW_LINE if ( dp [ j ] ) : NEW_LINE INDENT reach = max ( reach , j ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT DEDENT return totalSum - ( 2 * reach ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( SmallestElementLeft ( arr , N ) ) NEW_LINE DEDENT |
Replace even | Function to count the minimum number of substrings of str1 such that replacing even - indexed characters of those substrings converts the str1 to str2 ; Stores length of str1 ; Stores minimum count of operations to convert str1 to str2 ; Traverse both the given string ; If current character in both the strings are equal ; Stores current index of the string ; If current character in both the strings are not equal ; Replace str1 [ ptr ] by str2 [ ptr ] ; Update ptr ; Update cntOp ; Driver Code | def minOperationsReq ( str11 , str22 ) : NEW_LINE INDENT str1 = list ( str11 ) NEW_LINE str2 = list ( str22 ) NEW_LINE N = len ( str1 ) NEW_LINE cntOp = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str1 [ i ] == str2 [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT ptr = i NEW_LINE while ( ptr < N and str1 [ ptr ] != str2 [ ptr ] ) : NEW_LINE INDENT str1 [ ptr ] = str2 [ ptr ] NEW_LINE ptr += 2 NEW_LINE DEDENT cntOp += 1 NEW_LINE DEDENT return cntOp NEW_LINE DEDENT str1 = " abcdef " NEW_LINE str2 = " ffffff " NEW_LINE print ( minOperationsReq ( str1 , str2 ) ) NEW_LINE |
Check if GCD of all Composite Numbers in an array divisible by K is a Fibonacci Number or not | Python3 program for the above approach ; Function to check if a number is composite or not ; Corner cases ; Check if the number is divisible by 2 or 3 or not ; Check if n is a multiple of any other prime number ; Function to check if a number is a Perfect Square or not ; Function to check if a number is a Fibonacci number or not ; If 5 * n ^ 2 + 4 or 5 * n ^ 2 - 4 or both are perfect square ; Function to check if GCD of composite numbers from the array a [ ] which are divisible by k is a Fibonacci number or not ; Traverse the array ; If array element is composite and divisible by k ; Calculate GCD of all elements in compositeset ; If GCD is Fibonacci ; Driver Code | import math NEW_LINE def isComposite ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return False NEW_LINE DEDENT if n <= 3 : NEW_LINE INDENT return False NEW_LINE DEDENT if n % 2 == 0 or n % 3 == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT i = 5 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( ( n % i == 0 ) or ( n % ( i + 2 ) == 0 ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 6 NEW_LINE DEDENT return False NEW_LINE DEDENT def isPerfectSquare ( x ) : NEW_LINE INDENT s = int ( math . sqrt ( x ) ) NEW_LINE return ( s * s == x ) NEW_LINE DEDENT def isFibonacci ( n ) : NEW_LINE INDENT return ( isPerfectSquare ( 5 * n * n + 4 ) or isPerfectSquare ( 5 * n * n - 4 ) ) NEW_LINE DEDENT def ifgcdFibonacci ( a , n , k ) : NEW_LINE INDENT compositeset = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( isComposite ( a [ i ] ) and a [ i ] % k == 0 ) : NEW_LINE INDENT compositeset . append ( a [ i ] ) NEW_LINE DEDENT DEDENT gcd = compositeset [ 0 ] NEW_LINE for i in range ( 1 , len ( compositeset ) , 1 ) : NEW_LINE INDENT gcd = math . gcd ( gcd , compositeset [ i ] ) NEW_LINE if gcd == 1 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( isFibonacci ( gcd ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE return NEW_LINE DEDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 34 , 2 , 4 , 8 , 5 , 7 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE ifgcdFibonacci ( arr , n , k ) NEW_LINE DEDENT |
Longest subarray in which all elements are a factor of K | Function to find the length of the longest subarray in which all elements are a factor of K ; Stores length of the longest subarray in which all elements are a factor of K ; Stores length of the current subarray ; Traverse the array arr [ ] ; If A [ i ] is a factor of K ; Update Len ; Update MaxLen ; If A [ i ] is not a factor of K ; Reset Len ; Driver Code | def find_longest_subarray ( A , N , K ) : NEW_LINE INDENT MaxLen = 0 NEW_LINE Len = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( K % A [ i ] == 0 ) : NEW_LINE INDENT Len += 1 NEW_LINE MaxLen = max ( MaxLen , Len ) NEW_LINE DEDENT else : NEW_LINE INDENT Len = 0 NEW_LINE DEDENT DEDENT return MaxLen NEW_LINE DEDENT A = [ 2 , 8 , 3 , 10 , 6 , 7 , 4 , 9 ] NEW_LINE N = len ( A ) NEW_LINE K = 60 NEW_LINE print ( find_longest_subarray ( A , N , K ) ) NEW_LINE |
Length of smallest meeting that can be attended | Python3 program to implement the above approach ; Function to find the minimum time to attend exactly one meeting ; Stores minimum time to attend exactly one meeting ; Sort entrance [ ] array ; Sort exit [ ] time ; Traverse meeting [ ] [ ] ; Stores start time of current meeting ; Stores end time of current meeting ; Find just greater value of u in entrance [ ] ; Find just greater or equal value of u in entrance [ ] ; Stores enter time to attend the current meeting ; Stores exist time after attending the meeting ; Update start lies in range [ 0 , m - 1 ] and end lies in the range [ 0 , p - 1 ] ; Update ans ; Return answer ; Driver Code ; Stores interval of meeting ; Stores entrance timings ; Stores exit timings ; Stores total count of meetings ; Stores total entrance timings ; Stores total exit timings ; Minimum time | from bisect import bisect_left , bisect_right NEW_LINE import sys NEW_LINE def minTime ( meeting , n , entrance , m , exit , p ) : NEW_LINE INDENT ans = sys . maxsize NEW_LINE entrance = sorted ( entrance ) NEW_LINE exit = sorted ( exit ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT u = meeting [ i ] [ 0 ] NEW_LINE v = meeting [ i ] [ 1 ] NEW_LINE it1 = bisect_right ( entrance , u ) NEW_LINE it2 = bisect_left ( exit , v ) NEW_LINE start = it1 - 1 NEW_LINE end = it2 NEW_LINE if ( start >= 0 and start < m and end >= 0 and end < p ) : NEW_LINE INDENT ans = min ( ans , exit [ end ] - entrance [ start ] ) NEW_LINE DEDENT DEDENT if ans >= sys . maxsize : NEW_LINE INDENT ans = - 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT meeting = [ [ 15 , 19 ] , [ 5 , 10 ] , [ 7 , 25 ] ] NEW_LINE entrance = [ 4 , 13 , 25 , 2 ] NEW_LINE exit = [ 10 , 25 ] NEW_LINE n = len ( meeting ) NEW_LINE m = len ( entrance ) NEW_LINE p = len ( exit ) NEW_LINE print ( minTime ( meeting , n , entrance , m , exit , p ) ) NEW_LINE DEDENT |
Divide array into two arrays which does not contain any pair with sum K | Function to split the given array into two separate arrays satisfying given condition ; Stores resultant arrays ; Traverse the array ; If a [ i ] is smaller than or equal to k / 2 ; Print first array ; Print second array ; Driver Code ; Given K ; Given array ; Given size | def splitArray ( a , n , k ) : NEW_LINE INDENT first = [ ] NEW_LINE second = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] <= k // 2 ) : NEW_LINE INDENT first . append ( a [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT second . append ( a [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( first ) ) : NEW_LINE INDENT print ( first [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " , β end β = β " " ) NEW_LINE for i in range ( len ( second ) ) : NEW_LINE INDENT print ( second [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 5 NEW_LINE a = [ 0 , 1 , 3 , 2 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE n = len ( a ) NEW_LINE splitArray ( a , n , k ) NEW_LINE DEDENT |
Find all the queens attacking the king in a chessboard | Function to find the queen closest to king in an attacking position ; Function to find all the queens attacking the king in the chessboard ; Iterating over the coordinates of the queens ; If king is horizontally on the right of current queen ; If no attacker is present in that direction ; Or if the current queen is closest in that direction ; Set current queen as the attacker ; If king is horizontally on the left of current queen ; If no attacker is present in that direction ; Or if the current queen is closest in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the left by a queen diagonal above ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the left by a queen diagonally below ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the right by a queen diagonally above ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If the king is attacked by a queen from the right by a queen diagonally below ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If a king is vertically below the current queen ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; If a king is vertically above the current queen ; If no attacker is present in that direction ; Or the current queen is the closest attacker in that direction ; Set current queen as the attacker ; Return the coordinates ; Print all the coordinates of the queens attacking the king ; Driver Code | def dis ( ans , attacker ) : NEW_LINE INDENT return ( abs ( ans [ 0 ] - attacker [ 0 ] ) + abs ( ans [ 1 ] - attacker [ 1 ] ) ) NEW_LINE DEDENT def findQueens ( queens , king ) : NEW_LINE INDENT sol = [ ] NEW_LINE attackers = [ [ 0 for x in range ( 8 ) ] for y in range ( 8 ) ] NEW_LINE for i in range ( len ( queens ) ) : NEW_LINE INDENT if ( king [ 0 ] == queens [ i ] [ 0 ] and king [ 1 ] > queens [ i ] [ 1 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 3 ] ) == 0 ) or ( ( dis ( attackers [ 3 ] , king ) > dis ( queens [ i ] , king ) ) ) ) : NEW_LINE INDENT attackers [ 3 ] = queens [ i ] ; NEW_LINE DEDENT DEDENT if ( king [ 0 ] == queens [ i ] [ 0 ] and king [ 1 ] < queens [ i ] [ 1 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 4 ] ) == 0 ) or ( dis ( attackers [ 4 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 4 ] = queens [ i ] ; NEW_LINE DEDENT DEDENT if ( king [ 0 ] - queens [ i ] [ 0 ] == king [ 1 ] - queens [ i ] [ 1 ] and king [ 0 ] > queens [ i ] [ 0 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 0 ] ) == 0 ) or ( dis ( attackers [ 0 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 0 ] = queens [ i ] NEW_LINE DEDENT DEDENT if ( king [ 0 ] - queens [ i ] [ 0 ] == king [ 1 ] - queens [ i ] [ 1 ] and king [ 0 ] < queens [ i ] [ 0 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 7 ] ) == 0 ) or ( dis ( attackers [ 7 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 7 ] = queens [ i ] NEW_LINE DEDENT DEDENT if ( king [ 1 ] - queens [ i ] [ 1 ] == 0 and king [ 0 ] > queens [ i ] [ 0 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 1 ] ) == 0 ) or ( dis ( attackers [ 1 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 1 ] = queens [ i ] NEW_LINE DEDENT DEDENT if ( king [ 1 ] - queens [ i ] [ 1 ] == 0 and king [ 0 ] < queens [ i ] [ 0 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 6 ] ) == 0 ) or ( dis ( attackers [ 6 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 6 ] = queens [ i ] ; NEW_LINE DEDENT DEDENT if ( king [ 0 ] - queens [ i ] [ 0 ] == - ( king [ 1 ] - queens [ i ] [ 1 ] ) and king [ 0 ] > queens [ i ] [ 0 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 2 ] ) == 0 ) or ( dis ( attackers [ 2 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 2 ] = queens [ i ] NEW_LINE DEDENT DEDENT if ( king [ 0 ] - queens [ i ] [ 0 ] == - ( king [ 1 ] - queens [ i ] [ 1 ] ) and king [ 0 ] < queens [ i ] [ 0 ] ) : NEW_LINE INDENT if ( ( len ( attackers [ 5 ] ) == 0 ) or ( dis ( attackers [ 5 ] , king ) > dis ( queens [ i ] , king ) ) ) : NEW_LINE INDENT attackers [ 5 ] = queens [ i ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( 8 ) : NEW_LINE INDENT f = 1 NEW_LINE for x in attackers [ i ] : NEW_LINE if x != 0 : NEW_LINE INDENT f = 0 NEW_LINE break NEW_LINE DEDENT if f == 0 : NEW_LINE sol . append ( attackers [ i ] ) NEW_LINE DEDENT return sol NEW_LINE DEDENT def print_board ( ans ) : NEW_LINE INDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT for j in range ( 2 ) : NEW_LINE INDENT print ( ans [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT king = [ 2 , 3 ] NEW_LINE queens = [ [ 0 , 1 ] , [ 1 , 0 ] , [ 4 , 0 ] , [ 0 , 4 ] , [ 3 , 3 ] , [ 2 , 4 ] ] NEW_LINE ans = findQueens ( queens , king ) ; NEW_LINE print_board ( ans ) ; NEW_LINE DEDENT |
Count numbers in a given range whose count of prime factors is a Prime Number | Python3 program to implement the above approach ; Function to find the smallest prime factor of all the numbers in range [ 0 , MAX ] ; Stores smallest prime factor of all the numbers in the range [ 0 , MAX ] ; No smallest prime factor of 0 and 1 exists ; Traverse all the numbers in the range [ 1 , MAX ] ; Update spf [ i ] ; Update all the numbers whose smallest prime factor is 2 ; Traverse all the numbers in the range [ 1 , sqrt ( MAX ) ] ; Check if i is a prime number ; Update all the numbers whose smallest prime factor is i ; Check if j is a prime number ; Function to find count of prime factor of num ; Stores count of prime factor of num ; Calculate count of prime factor ; Update count ; Update num ; Function to precalculate the count of numbers in the range [ 0 , i ] whose count of prime factors is a prime number ; Stores the sum of all the numbers in the range [ 0 , i ] count of prime factor is a prime number ; Traverse all the numbers in the range [ 1 , MAX ] ; Stores count of prime factor of i ; If count of prime factor is a prime number ; Update sum [ i ] ; Update sum [ i ] ; Driver code ; Stores smallest prime factor of all the numbers in the range [ 0 , MAX ] ; Stores the sum of all the numbers in the range [ 0 , i ] count of prime factor is a prime number ; N = sizeof ( Q ) / sizeof ( Q [ 0 ] ) ; | MAX = 1001 NEW_LINE def sieve ( ) : NEW_LINE INDENT global MAX NEW_LINE spf = [ 0 ] * MAX NEW_LINE spf [ 0 ] = spf [ 1 ] = - 1 NEW_LINE for i in range ( 2 , MAX ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAX , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT for i in range ( 3 , MAX ) : NEW_LINE INDENT if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAX ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT return spf NEW_LINE DEDENT def countFactors ( spf , num ) : NEW_LINE INDENT count = 0 NEW_LINE while ( num > 1 ) : NEW_LINE INDENT count += 1 NEW_LINE num = num // spf [ num ] NEW_LINE DEDENT return count NEW_LINE DEDENT def precalculateSum ( spf ) : NEW_LINE INDENT sum = [ 0 ] * MAX NEW_LINE for i in range ( 1 , MAX ) : NEW_LINE INDENT prime_factor = countFactors ( spf , i ) NEW_LINE if ( spf [ prime_factor ] == prime_factor ) : NEW_LINE INDENT sum [ i ] = sum [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum [ i ] = sum [ i - 1 ] NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT spf = sieve ( ) NEW_LINE sum = precalculateSum ( spf ) NEW_LINE Q = [ [ 4 , 8 ] , [ 30 , 32 ] ] NEW_LINE sum [ Q [ 0 ] [ 1 ] ] += 1 NEW_LINE for i in range ( 0 , 2 ) : NEW_LINE INDENT print ( ( sum [ Q [ i ] [ 1 ] ] - sum [ Q [ i ] [ 0 ] ] ) , end = " β " ) NEW_LINE DEDENT DEDENT |
Maximum number of Perfect Numbers present in a subarray of size K | Function to check a number is Perfect Number or not ; Stores sum of divisors ; Find all divisors and add them ; If sum of divisors is equal to N ; Function to return maximum sum of a subarray of size K ; If k is greater than N ; 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 ; Return the answer ; Function to find all the perfect numbers in the array ; The given array is converted into binary array ; Driver Code | def isPerfect ( N ) : NEW_LINE INDENT sum = 1 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if i * i > N : NEW_LINE INDENT break NEW_LINE DEDENT if ( N % i == 0 ) : NEW_LINE INDENT if ( i == N // i ) : NEW_LINE INDENT sum += i NEW_LINE DEDENT else : NEW_LINE INDENT sum += i + N // i NEW_LINE DEDENT DEDENT DEDENT if ( sum == N and N != 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def maxSum ( arr , N , K ) : NEW_LINE INDENT if ( N < K ) : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE 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 max_PerfectNumbers ( arr , N , K ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if isPerfect ( arr [ i ] ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT DEDENT return maxSum ( arr , N , K ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 28 , 2 , 3 , 6 , 496 , 99 , 8128 , 24 ] NEW_LINE K = 4 NEW_LINE N = len ( arr ) NEW_LINE print ( max_PerfectNumbers ( arr , N , K ) ) NEW_LINE DEDENT |
Count greater elements on the left side of every array element | Function to print the count of greater elements on left of each array element ; Function to get the count of greater elements on left of each array element ; Store distinct array elements in sorted order ; Stores the count of greater elements on the left side ; Traverse the array ; Insert array elements into the set ; Find previous greater element ; Find the distance between the previous greater element of arr [ i ] and last element of the set ; Driver code | def display ( countLeftGreater , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT print ( countLeftGreater [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def countGreater ( arr , N ) : NEW_LINE INDENT St = set ( ) NEW_LINE countLeftGreater = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT St . add ( arr [ i ] ) NEW_LINE it = 0 NEW_LINE for st in St : NEW_LINE INDENT if ( arr [ i ] < st ) : NEW_LINE INDENT break NEW_LINE DEDENT it += 1 NEW_LINE DEDENT countLeftGreater [ i ] = abs ( it - len ( St ) ) NEW_LINE DEDENT display ( countLeftGreater , N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 1 , 2 , 3 , 0 , 11 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE countGreater ( arr , N ) NEW_LINE DEDENT |
Count characters to be shifted from the start or end of a string to obtain another string | Function to find the minimum cost to convert string A to string B ; Length of string ; Initialize maxlen as 0 ; Traverse the string A ; Stores the length of substrings of string A ; Traversing string B for each character of A ; Shift i pointer towards right and increment length , if A [ i ] equals B [ j ] ; If traverse till end ; Update maxlen ; Return minimum cost ; Driver Code ; Given two strings A and B ; Function call | def minCost ( A , B ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE i = 0 ; NEW_LINE maxlen = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT length = 0 ; NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( A [ i ] == B [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE length += 1 ; NEW_LINE if ( i == n ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT maxlen = max ( maxlen , length ) ; NEW_LINE DEDENT return n - maxlen ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = " edacb " ; NEW_LINE B = " abcde " ; NEW_LINE print ( minCost ( A , B ) ) ; NEW_LINE DEDENT |
Lexicographic rank of a string among all its substrings | Function to find lexicographic rank of among all its substring ; Length of string ; Traverse the given string and store the indices of each character ; Extract the index ; Store it in the vector ; Traverse the alphaIndex array lesser than the index of first character of given string ; If alphaIndex [ i ] size exceeds 0 ; Traverse over the indices ; Add count of substring equal to n - alphaIndex [ i ] [ j ] ; Store all substrings in a vector strr starting with the first character of the given string ; Insert the current character to substring ; Store the subformed ; Sort the substring in the lexicographical order ; Find the rank of given string ; Increase the rank until the given is same ; If substring is same as the given string ; Add 1 to rank of the given string ; Driver Code ; Given string ; Function call | def lexicographicRank ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE alphaIndex = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT x = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE alphaIndex [ x ] . append ( i ) NEW_LINE DEDENT rank = - 1 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ord ( ' a ' ) + i >= ord ( s [ 0 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT if len ( alphaIndex [ i ] ) > 0 : NEW_LINE INDENT for j in range ( len ( alphaIndex [ i ] ) ) : NEW_LINE INDENT rank = rank + ( n - alphaIndex [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT strr = [ ] NEW_LINE for i in range ( len ( alphaIndex [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] ) ) : NEW_LINE INDENT substring = [ ] NEW_LINE jj = alphaIndex [ ord ( s [ 0 ] ) - ord ( ' a ' ) ] [ i ] NEW_LINE for j in range ( jj , n ) : NEW_LINE INDENT substring . append ( s [ j ] ) NEW_LINE strr . append ( substring ) NEW_LINE DEDENT DEDENT strr = sorted ( strr ) NEW_LINE for i in range ( len ( strr ) ) : NEW_LINE INDENT if ( strr [ i ] != s ) : NEW_LINE INDENT rank += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return rank + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT strr = " enren " NEW_LINE print ( lexicographicRank ( strr ) ) NEW_LINE DEDENT |
Find H | Function to find the H - index ; Set the range for binary search ; Check if current citations is possible ; Check to the right of mid ; Update h - index ; Since current value is not possible , check to the left of mid ; Print the h - index ; citations | def hIndex ( citations , n ) : NEW_LINE INDENT hindex = 0 NEW_LINE low = 0 NEW_LINE high = n - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( citations [ mid ] >= ( mid + 1 ) ) : NEW_LINE INDENT low = mid + 1 NEW_LINE hindex = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT print ( hindex ) NEW_LINE return hindex NEW_LINE DEDENT n = 5 NEW_LINE citations = [ 5 , 3 , 3 , 2 , 2 ] NEW_LINE hIndex ( citations , n ) NEW_LINE |
Check if all strings of an array can be made same by interchanging characters | Function to check if all strings are equal after swap operations ; Stores the frequency of characters ; Stores the length of string ; Traverse the array ; Traverse each string ; Check if frequency of character is divisible by N ; Driver Code | def checkEqual ( arr , N ) : NEW_LINE INDENT hash = [ 0 ] * 256 NEW_LINE M = len ( arr [ 0 ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT hash [ ord ( arr [ i ] [ j ] ) ] += 1 NEW_LINE DEDENT DEDENT for i in range ( 256 ) : NEW_LINE INDENT if ( hash [ i ] % N != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ " fdd " , " fhh " ] NEW_LINE N = len ( arr ) NEW_LINE if ( checkEqual ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Maximize sum of remaining elements after every removal of the array half with greater sum | Function to find the maximum sum ; Base Case ; Create a key to map the values ; Check if mapped key is found in the dictionary ; Traverse the array ; Store left prefix sum ; Store right prefix sum ; Compare the left and right values ; Store the value in dp array ; Return the final answer ; Function to print maximum sum ; Stores prefix sum ; Store results of subproblems ; Traversing the array ; Add prefix sum of array ; Print the answer ; Driver Code ; Function Call | def maxweight ( s , e , pre , dp ) : NEW_LINE INDENT if s == e : NEW_LINE INDENT return 0 NEW_LINE DEDENT key = ( s , e ) NEW_LINE if key in dp : NEW_LINE INDENT return dp [ key ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( s , e ) : NEW_LINE INDENT left = pre [ i ] - pre [ s - 1 ] NEW_LINE right = pre [ e ] - pre [ i ] NEW_LINE if left < right : NEW_LINE INDENT ans = max ( ans , left + maxweight ( s , i , pre , dp ) ) NEW_LINE DEDENT if left == right : NEW_LINE INDENT ans = max ( ans , left + maxweight ( s , i , pre , dp ) , right + maxweight ( i + 1 , e , pre , dp ) ) NEW_LINE DEDENT if left > right : NEW_LINE ans = max ( ans , right + maxweight ( i + 1 , e , pre , dp ) ) NEW_LINE dp [ key ] = ans NEW_LINE DEDENT return dp [ key ] NEW_LINE DEDENT def maxSum ( arr ) : NEW_LINE INDENT pre = { - 1 : 0 , 0 : arr [ 0 ] } NEW_LINE dp = { } NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + arr [ i ] NEW_LINE DEDENT print ( maxweight ( 0 , len ( arr ) - 1 , pre , dp ) ) NEW_LINE DEDENT arr = [ 6 , 2 , 3 , 4 , 5 , 5 ] NEW_LINE maxSum ( arr ) NEW_LINE |
Find K smallest leaf nodes from a given Binary Tree | Binary tree node ; Function to create new node ; Utility function which calculates smallest three nodes of all leaf nodes ; Check if current root is a leaf node ; Traverse the left and right subtree ; Function to find the K smallest nodes of the Binary Tree ; Sorting the Leaf nodes array ; Loop to print the K smallest Leaf nodes of the array ; Driver Code ; Construct binary tree ; Function Call | 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 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 storeLeaf ( root : Node , arr : list ) -> None : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( not root . left and not root . right ) : NEW_LINE INDENT arr . append ( root . data ) NEW_LINE return NEW_LINE DEDENT storeLeaf ( root . left , arr ) NEW_LINE storeLeaf ( root . right , arr ) NEW_LINE DEDENT def KSmallest ( root : Node , k : int ) -> None : NEW_LINE INDENT arr = [ ] NEW_LINE storeLeaf ( root , arr ) NEW_LINE arr . sort ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( i < len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . left . left = Node ( 21 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . left . right . right = Node ( 8 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . right . right = Node ( 19 ) NEW_LINE KSmallest ( root , 3 ) NEW_LINE DEDENT |
Check if all the pairs of an array are coprime with each other | Python3 implementation of the above approach ; Function to check if all the pairs of the array are coprime with each other or not ; Check if GCD of the pair is not equal to 1 ; All pairs are non - coprime Return false ; ; Driver 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 allCoprime ( A , n ) : NEW_LINE INDENT all_coprime = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if gcd ( A [ i ] , A [ j ] ) != 1 : NEW_LINE INDENT all_coprime = False ; NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT return all_coprime NEW_LINE DEDENT / * Function return gcd of two number * / NEW_LINE if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 5 , 11 , 7 , 19 ] NEW_LINE arr_size = len ( A ) NEW_LINE if ( allCoprime ( A , arr_size ) ) : NEW_LINE INDENT print ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT DEDENT |
Smallest power of 2 consisting of N digits | Python3 program of the above approach ; Function to return smallest power of 2 with N digits ; Driver Code | from math import log2 , ceil NEW_LINE def smallestNum ( n ) : NEW_LINE INDENT power = log2 ( 10 ) NEW_LINE print ( power ) ; NEW_LINE return ceil ( ( n - 1 ) * power ) NEW_LINE DEDENT n = 4 NEW_LINE print ( smallestNum ( n ) ) NEW_LINE |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.