text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Queries for decimal values of subarrays of a binary array | implementation of finding number represented by binary subarray ; Fills pre [ ] ; returns the number represented by a binary subarray l to r ; if r is equal to n - 1 r + 1 does not exist ; Driver Code | from math import pow NEW_LINE def precompute ( arr , n , pre ) : NEW_LINE INDENT pre [ n - 1 ] = arr [ n - 1 ] * pow ( 2 , 0 ) NEW_LINE i = n - 2 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT pre [ i ] = ( pre [ i + 1 ] + arr [ i ] * ( 1 << ( n - 1 - i ) ) ) NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT def decimalOfSubarr ( arr , l , r , n , pre ) : NEW_LINE INDENT if ( r != n - 1 ) : NEW_LINE INDENT return ( ( pre [ l ] - pre [ r + 1 ] ) / ( 1 << ( n - 1 - r ) ) ) NEW_LINE DEDENT return pre [ l ] / ( 1 << ( n - 1 - r ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE pre = [ 0 for i in range ( n ) ] NEW_LINE precompute ( arr , n , pre ) NEW_LINE print ( int ( decimalOfSubarr ( arr , 2 , 4 , n , pre ) ) ) NEW_LINE print ( int ( decimalOfSubarr ( arr , 4 , 5 , n , pre ) ) ) NEW_LINE DEDENT |
Count elements which divide all numbers in range L | function to count element Time complexity O ( n ^ 2 ) worst case ; answer for query ; 0 based index ; iterate for all elements ; check if the element divides all numbers in range ; no of elements ; if all elements are divisible by a [ i ] ; answer for every query ; Driver Code | def answerQuery ( a , n , l , r ) : NEW_LINE INDENT count = 0 NEW_LINE l = l - 1 NEW_LINE for i in range ( l , r , 1 ) : NEW_LINE INDENT element = a [ i ] NEW_LINE divisors = 0 NEW_LINE for j in range ( l , r , 1 ) : NEW_LINE INDENT if ( a [ j ] % a [ i ] == 0 ) : NEW_LINE INDENT divisors += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( divisors == ( r - l ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 2 , 3 , 5 ] NEW_LINE n = len ( a ) NEW_LINE l = 1 NEW_LINE r = 4 NEW_LINE print ( answerQuery ( a , n , l , r ) ) NEW_LINE l = 2 NEW_LINE r = 4 NEW_LINE print ( answerQuery ( a , n , l , r ) ) NEW_LINE DEDENT |
Minimum number of Binary strings to represent a Number | Function to find the minimum number of binary strings to represent a number ; Storing digits in correct order ; Find the maximum digit in the array ; Traverse for all the binary strings ; If digit at jth position is greater than 0 then substitute 1 ; Driver code | def minBinary ( n ) : NEW_LINE INDENT digit = [ 0 for i in range ( 3 ) ] NEW_LINE len = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT digit [ len ] = n % 10 NEW_LINE len += 1 NEW_LINE n //= 10 NEW_LINE DEDENT digit = digit [ : : - 1 ] NEW_LINE ans = 0 NEW_LINE for i in range ( len ) : NEW_LINE INDENT ans = max ( ans , digit [ i ] ) NEW_LINE DEDENT print ( " Minimum β Number β of β binary β strings β needed : " , ans ) NEW_LINE for i in range ( 1 , ans + 1 , 1 ) : NEW_LINE INDENT num = 0 NEW_LINE for j in range ( 0 , len , 1 ) : NEW_LINE INDENT if ( digit [ j ] > 0 ) : NEW_LINE INDENT num = num * 10 + 1 NEW_LINE digit [ j ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT num *= 10 NEW_LINE DEDENT DEDENT print ( num , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 564 NEW_LINE minBinary ( n ) NEW_LINE DEDENT |
Number whose sum of XOR with given array range is maximum | Python3 program to find smallest integer X such that sum of its XOR with range is maximum . ; Function to make prefix array which counts 1 's of each bit up to that number ; Making a prefix array which sums number of 1 's up to that position ; If j - th bit of a number is set then add one to previously counted 1 's ; Function to find X ; Initially taking maximum value all bits 1 ; Iterating over each bit ; get 1 ' s β at β ith β bit β between β the β β range β L - R β by β subtracting β 1' s till Rth number - 1 's till L-1th number ; If 1 ' s β are β more β than β or β equal β β to β 0' s then unset the ith bit from answer ; Set ith bit to 0 by doing Xor with 1 ; Driver Code | import math NEW_LINE one = [ [ 0 for x in range ( 32 ) ] for y in range ( 100001 ) ] NEW_LINE MAX = 2147483647 NEW_LINE def make_prefix ( A , n ) : NEW_LINE INDENT global one , MAX NEW_LINE for j in range ( 0 , 32 ) : NEW_LINE INDENT one [ 0 ] [ j ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT a = A [ i - 1 ] NEW_LINE for j in range ( 0 , 32 ) : NEW_LINE INDENT x = int ( math . pow ( 2 , j ) ) NEW_LINE if ( a & x ) : NEW_LINE INDENT one [ i ] [ j ] = 1 + one [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT one [ i ] [ j ] = one [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT DEDENT def Solve ( L , R ) : NEW_LINE INDENT global one , MAX NEW_LINE l = L NEW_LINE r = R NEW_LINE tot_bits = r - l + 1 NEW_LINE X = MAX NEW_LINE for i in range ( 0 , 31 ) : NEW_LINE INDENT x = one [ r ] [ i ] - one [ l - 1 ] [ i ] NEW_LINE if ( x >= ( tot_bits - x ) ) : NEW_LINE INDENT ith_bit = pow ( 2 , i ) NEW_LINE X = X ^ ith_bit NEW_LINE DEDENT DEDENT return X NEW_LINE DEDENT n = 5 NEW_LINE q = 3 NEW_LINE A = [ 210 , 11 , 48 , 22 , 133 ] NEW_LINE L = [ 1 , 4 , 2 ] NEW_LINE R = [ 3 , 14 , 4 ] NEW_LINE make_prefix ( A , n ) NEW_LINE for j in range ( 0 , q ) : NEW_LINE INDENT print ( Solve ( L [ j ] , R [ j ] ) , end = " " ) NEW_LINE DEDENT |
Array range queries over range queries | Function to execute type 1 query ; incrementing the array by 1 for type 1 queries ; Function to execute type 2 query ; If the query is of type 1 function call to type 1 query ; If the query is of type 2 recursive call to type 2 query ; Input size of array amd number of queries ; Build query matrix ; Perform queries ; printing the result | def type1 ( arr , start , limit ) : NEW_LINE INDENT for i in range ( start , limit + 1 ) : NEW_LINE INDENT arr [ i ] += 1 NEW_LINE DEDENT DEDENT def type2 ( arr , query , start , limit ) : NEW_LINE INDENT for i in range ( start , limit + 1 ) : NEW_LINE INDENT if ( query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT type1 ( arr , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) NEW_LINE DEDENT elif ( query [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT type2 ( arr , query , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) NEW_LINE DEDENT DEDENT DEDENT n = 5 NEW_LINE m = 5 NEW_LINE arr = [ 0 for i in range ( n + 1 ) ] NEW_LINE temp = [ 1 , 1 , 2 , 1 , 4 , 5 , 2 , 1 , 2 , 2 , 1 , 3 , 2 , 3 , 4 ] NEW_LINE query = [ [ 0 for i in range ( 3 ) ] for j in range ( 6 ) ] NEW_LINE j = 0 NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT query [ i ] [ 0 ] = temp [ j ] NEW_LINE j += 1 NEW_LINE query [ i ] [ 1 ] = temp [ j ] NEW_LINE j += 1 NEW_LINE query [ i ] [ 2 ] = temp [ j ] NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT type1 ( arr , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) NEW_LINE DEDENT elif ( query [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT type2 ( arr , query , query [ i ] [ 1 ] , query [ i ] [ 2 ] ) NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Array range queries over range queries | Function to create the record array ; Driver Code ; Build query matrix ; If query is of type 2 then function call to record_sum ; If query is of type 1 then simply add 1 to the record array ; for type 1 queries adding the contains of record array to the main array record array ; printing the array | def record_sum ( record , l , r , n , adder ) : NEW_LINE INDENT for i in range ( l , r + 1 ) : NEW_LINE INDENT record [ i ] += adder NEW_LINE DEDENT DEDENT n = 5 NEW_LINE m = 5 NEW_LINE arr = [ 0 ] * n NEW_LINE query = [ [ 1 , 1 , 2 ] , [ 1 , 4 , 5 ] , [ 2 , 1 , 2 ] , [ 2 , 1 , 3 ] , [ 2 , 3 , 4 ] ] NEW_LINE record = [ 0 ] * m NEW_LINE for i in range ( m - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( query [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT record_sum ( record , query [ i ] [ 1 ] - 1 , query [ i ] [ 2 ] - 1 , m , record [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT record_sum ( record , i , i , m , 1 ) NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT if ( query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT record_sum ( arr , query [ i ] [ 1 ] - 1 , query [ i ] [ 2 ] - 1 , n , record [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' β ' ) NEW_LINE DEDENT |
Array range queries over range queries | Python3 program to perform range queries over range queries . ; For prefix sum array ; This function is used to apply square root decomposition in the record array ; Traversing first block in range ; Traversing completely overlapped blocks in range ; Traversing last block in range ; Function to print the resultant array ; Driver code ; If query is of type 2 then function call to record_func ; If query is of type 1 then simply add 1 to the record array ; Merging the value of the block in the record array ; If query is of type 1 then the array elements are over - written by the record array ; The prefix sum of the array ; Printing the resultant array | import math NEW_LINE max = 10000 NEW_LINE def update ( arr , l ) : NEW_LINE INDENT arr [ l ] += arr [ l - 1 ] NEW_LINE DEDENT def record_func ( block_size , block , record , l , r , value ) : NEW_LINE INDENT while ( l < r and l % block_size != 0 and l != 0 ) : NEW_LINE INDENT record [ l ] += value NEW_LINE l += 1 NEW_LINE DEDENT while ( l + block_size <= r + 1 ) : NEW_LINE INDENT block [ l // block_size ] += value NEW_LINE l += block_size NEW_LINE DEDENT while ( l <= r ) : NEW_LINE INDENT record [ l ] += value NEW_LINE l += 1 NEW_LINE DEDENT DEDENT def print_array ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 5 NEW_LINE arr = [ 0 ] * n NEW_LINE record = [ 0 ] * m NEW_LINE block_size = ( int ) ( math . sqrt ( m ) ) NEW_LINE block = [ 0 ] * max NEW_LINE command = [ [ 1 , 1 , 2 ] , [ 1 , 4 , 5 ] , [ 2 , 1 , 2 ] , [ 2 , 1 , 3 ] , [ 2 , 3 , 4 ] ] NEW_LINE for i in range ( m - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( command [ i ] [ 0 ] == 2 ) : NEW_LINE INDENT x = i // ( block_size ) NEW_LINE record_func ( block_size , block , record , command [ i ] [ 1 ] - 1 , command [ i ] [ 2 ] - 1 , ( block [ x ] + record [ i ] + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT record [ i ] += 1 NEW_LINE DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT check = ( i // block_size ) NEW_LINE record [ i ] += block [ check ] NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if ( command [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT arr [ command [ i ] [ 1 ] - 1 ] += record [ i ] NEW_LINE if ( ( command [ i ] [ 2 ] - 1 ) < n - 1 ) : NEW_LINE INDENT arr [ ( command [ i ] [ 2 ] ) ] -= record [ i ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT update ( arr , i ) NEW_LINE DEDENT print_array ( arr , n ) NEW_LINE DEDENT |
Array range queries for searching an element | Structure to represent a query range ; Find the root of the group containing the element at index x ; merge the two groups containing elements at indices x and y into one group ; make n subsets with every element as its root ; consecutive elements equal in value are merged into one single group ; Driver Code ; check if the current element in consideration is equal to x or not if it is equal , then x exists in the range ; Print if x exists or not | class Query : NEW_LINE INDENT def __init__ ( self , L , R , X ) : NEW_LINE INDENT self . L = L NEW_LINE self . R = R NEW_LINE self . X = X NEW_LINE DEDENT DEDENT maxn = 100 NEW_LINE root = [ 0 ] * maxn NEW_LINE def find ( x ) : NEW_LINE INDENT if x == root [ x ] : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT root [ x ] = find ( root [ x ] ) NEW_LINE return root [ x ] NEW_LINE DEDENT DEDENT def uni ( x , y ) : NEW_LINE INDENT p = find ( x ) NEW_LINE q = find ( y ) NEW_LINE if p != q : NEW_LINE INDENT root [ p ] = root [ q ] NEW_LINE DEDENT DEDENT def initialize ( a , n , q , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT root [ i ] = i NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if a [ i ] == a [ i - 1 ] : NEW_LINE INDENT uni ( i , i - 1 ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 1 , 5 , 4 , 5 ] NEW_LINE n = len ( a ) NEW_LINE q = [ Query ( 0 , 2 , 2 ) , Query ( 1 , 4 , 1 ) , Query ( 2 , 4 , 5 ) ] NEW_LINE m = len ( q ) NEW_LINE initialize ( a , n , q , m ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT flag = False NEW_LINE l = q [ i ] . L NEW_LINE r = q [ i ] . R NEW_LINE x = q [ i ] . X NEW_LINE p = r NEW_LINE while p >= l : NEW_LINE INDENT if a [ p ] == x : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT p = find ( p ) - 1 NEW_LINE DEDENT if flag : NEW_LINE INDENT print ( " % d β exists β between β [ % d , β % d ] " % ( x , l , r ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " % d β does β not β exists β between β [ % d , β % d ] " % ( x , l , r ) ) NEW_LINE DEDENT DEDENT DEDENT |
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; Iterate over 1 to a to find distinct pairs ; For each integer from 1 to a b / n integers exists such that pair / sum is divisible by n ; If ( i % n + b % n ) >= n one more pair is possible ; Return answer ; Driver code | def findCountOfPairs ( a , b , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , a + 1 ) : NEW_LINE INDENT ans += b // n NEW_LINE ans += 1 if ( i % n + b % n ) >= n else 0 NEW_LINE DEDENT return ans NEW_LINE DEDENT a = 5 ; b = 13 ; n = 3 NEW_LINE print ( findCountOfPairs ( a , b , n ) ) NEW_LINE |
Count of pairs from 1 to a and 1 to b whose sum is divisible by N | Function to find the distinct pairs from 1 - a & 1 - b such that their sum is divisible by n . ; if first element is bigger then swap ; count is store the number of pair . ; we use temp for breaking a loop . ; count when a is greater . ; Count when a is smaller but b is greater ; Count when a and b both are smaller ; For storing The pair in count . ; return the number of pairs . ; Driver code | def findCountOfPairs ( a , b , n ) : NEW_LINE INDENT if ( a > b ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT temp = 1 NEW_LINE count = 0 NEW_LINE i = n NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( a >= i ) : NEW_LINE INDENT temp = i - 1 NEW_LINE DEDENT elif ( b >= i ) : NEW_LINE INDENT temp = a NEW_LINE DEDENT elif ( i > b ) : NEW_LINE INDENT temp = a - ( i - b ) + 1 NEW_LINE DEDENT if ( temp > 0 ) : NEW_LINE INDENT count += temp NEW_LINE DEDENT i += n NEW_LINE DEDENT return count NEW_LINE DEDENT a = 5 NEW_LINE b = 13 NEW_LINE n = 3 NEW_LINE print ( findCountOfPairs ( a , b , n ) ) NEW_LINE |
Array range queries for elements with frequency same as value | Python 3 Program to answer Q queries to find number of times an element x appears x times in a Query subarray ; Returns the count of number x with frequency x in the subarray from start to end ; map for frequency of elements ; store frequency of each element in arr [ start end ] ; Count elements with same frequency as value ; Driver code ; 2D array of queries with 2 columns ; calculating number of queries | import math as mt NEW_LINE def solveQuery ( start , end , arr ) : NEW_LINE INDENT frequency = dict ( ) NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT if arr [ i ] in frequency . keys ( ) : NEW_LINE INDENT frequency [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT frequency [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for x in frequency : NEW_LINE INDENT if x == frequency [ x ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT A = [ 1 , 2 , 2 , 3 , 3 , 3 ] NEW_LINE n = len ( A ) NEW_LINE queries = [ [ 0 , 1 ] , [ 1 , 1 ] , [ 0 , 2 ] , [ 1 , 3 ] , [ 3 , 5 ] , [ 0 , 5 ] ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT start = queries [ i ] [ 0 ] NEW_LINE end = queries [ i ] [ 1 ] NEW_LINE print ( " Answer β for β Query β " , ( i + 1 ) , " β = β " , solveQuery ( start , end , A ) ) NEW_LINE DEDENT |
Buy minimum items without change and given coins | Python3 implementation of above approach ; See if we can buy less than 10 items Using 10 Rs coins and one r Rs coin ; We can always buy 10 items ; Driver Code | def minItems ( k , r ) : NEW_LINE INDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( ( i * k - r ) % 10 == 0 or ( i * k ) % 10 == 0 ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return 10 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k , r = 15 , 2 ; NEW_LINE print ( minItems ( k , r ) ) NEW_LINE DEDENT |
Number of indexes with equal elements in given range | function that answers every query in O ( r - l ) ; traverse from l to r and count the required indexes ; Driver Code ; 1 - st query ; 2 nd query | def answer_query ( a , n , l , r ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( l , r ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT a = [ 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 ] NEW_LINE n = len ( a ) NEW_LINE L = 1 NEW_LINE R = 8 NEW_LINE print ( answer_query ( a , n , L , R ) ) NEW_LINE L = 0 NEW_LINE R = 4 NEW_LINE print ( answer_query ( a , n , L , R ) ) NEW_LINE |
Diagonal Sum of a Binary Tree | Python3 program calculate the sum of diagonal nodes . ; A binary tree node structure ; To map the node with level - index ; Recursvise function to calculate sum of elements where level - index is same ; If there is no child then return ; Add the element in the group of node whose level - index is equal ; Left child call ; Right child call ; Function call ; For different values of level - index add te sum of those node to answer ; Driver code ; Build binary tree ; Function Call ; Print the daigonal sums | from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT grid = { } NEW_LINE def addConsideringGrid ( root , level , index ) : NEW_LINE INDENT global grid NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT grid [ level - index ] = ( grid . get ( level - index , 0 ) + root . data ) NEW_LINE addConsideringGrid ( root . left , level + 1 , index - 1 ) NEW_LINE addConsideringGrid ( root . right , level + 1 , index + 1 ) NEW_LINE DEDENT def diagonalSum ( root ) : NEW_LINE INDENT addConsideringGrid ( root , 0 , 0 ) NEW_LINE ans = [ ] NEW_LINE for x in grid : NEW_LINE INDENT ans . append ( grid [ x ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 9 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 5 ) NEW_LINE root . right . left . right = Node ( 7 ) NEW_LINE root . right . left . left = Node ( 12 ) NEW_LINE root . left . right . left = Node ( 11 ) NEW_LINE root . left . left . right = Node ( 10 ) NEW_LINE v = diagonalSum ( root ) NEW_LINE for i in v : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT |
Number of indexes with equal elements in given range | Python program to count the number of indexes in range L R such that Ai = Ai + 1 ; array to store count of index from 0 to i that obey condition ; precomputing prefixans [ ] array ; traverse to compute the prefixans [ ] array ; def that answers every query in O ( 1 ) ; Driver Code ; pre - computation ; 1 - st query ; 2 nd query | N = 1000 NEW_LINE prefixans = [ 0 ] * N ; NEW_LINE def countIndex ( a , n ) : NEW_LINE INDENT global N , prefixans NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] == a [ i + 1 ] ) : NEW_LINE INDENT prefixans [ i ] = 1 NEW_LINE DEDENT if ( i != 0 ) : NEW_LINE INDENT prefixans [ i ] = ( prefixans [ i ] + prefixans [ i - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def answer_query ( l , r ) : NEW_LINE INDENT global N , prefixans NEW_LINE if ( l == 0 ) : NEW_LINE INDENT return prefixans [ r - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return ( prefixans [ r - 1 ] - prefixans [ l - 1 ] ) NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 2 , 2 , 3 , 3 , 4 , 4 , 4 ] NEW_LINE n = len ( a ) NEW_LINE countIndex ( a , n ) NEW_LINE L = 1 NEW_LINE R = 8 NEW_LINE print ( answer_query ( L , R ) ) NEW_LINE L = 0 NEW_LINE R = 4 NEW_LINE print ( answer_query ( L , R ) ) NEW_LINE |
Count subarrays with Prime sum | Function to count subarrays with Prime sum ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Initialize result ; Traverse through the array ; return answer ; Driver Code | def primeSubarrays ( A , n ) : NEW_LINE INDENT max_val = 10 ** 7 NEW_LINE prime = [ True ] * ( max_val + 1 ) NEW_LINE prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( max_val ** ( 0.5 ) ) + 1 ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( 2 * p , max_val + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT val = A [ i ] NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT val += A [ j ] NEW_LINE if prime [ val ] == True : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( A ) NEW_LINE print ( primeSubarrays ( A , n ) ) NEW_LINE DEDENT |
Total numbers with no repeated digits in a range | Function to check if the given number has repeated digit or not ; Traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; Function to find total number in the given range which has no repeated digit ; Traversing through the range ; Add 1 to the answer if i has no repeated digit else 0 ; Driver 's Code ; Calling the calculate | def repeated_digit ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE while n != 0 : NEW_LINE INDENT d = n % 10 NEW_LINE if d in a : NEW_LINE INDENT return 0 NEW_LINE DEDENT a . append ( d ) NEW_LINE n = n // 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def calculate ( L , R ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT answer = answer + repeated_digit ( i ) NEW_LINE DEDENT return answer NEW_LINE DEDENT L = 1 NEW_LINE R = 100 NEW_LINE print ( calculate ( L , R ) ) NEW_LINE |
Minimum swaps required to make a binary string alternating | returns the minimum number of swaps of a binary string passed as the argument to make it alternating ; counts number of zeroes at odd and even positions ; counts number of ones at odd and even positions ; alternating string starts with 0 ; alternating string starts with 1 ; calculates the minimum number of swaps ; Driver code | def countMinSwaps ( st ) : NEW_LINE INDENT min_swaps = 0 NEW_LINE odd_0 , even_0 = 0 , 0 NEW_LINE odd_1 , even_1 = 0 , 0 NEW_LINE n = len ( st ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT if st [ i ] == "1" : NEW_LINE INDENT even_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT even_0 += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if st [ i ] == "1" : NEW_LINE INDENT odd_1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT odd_0 += 1 NEW_LINE DEDENT DEDENT DEDENT cnt_swaps_1 = min ( even_0 , odd_1 ) NEW_LINE cnt_swaps_2 = min ( even_1 , odd_0 ) NEW_LINE return min ( cnt_swaps_1 , cnt_swaps_2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "000111" NEW_LINE print ( countMinSwaps ( st ) ) NEW_LINE DEDENT |
Total numbers with no repeated digits in a range | Maximum ; Prefix Array ; Function to check if the given number has repeated digit or not ; Traversing through each digit ; if the digit is present more than once in the number ; return 0 if the number has repeated digit ; return 1 if the number has no repeated digit ; Function to pre calculate the Prefix array ; Traversing through the numbers from 2 to MAX ; Generating the Prefix array ; Calclute Function ; Answer ; Pre - calculating the Prefix array . ; Calling the calculate function to find the total number of number which has no repeated digit | MAX = 1000 NEW_LINE Prefix = [ 0 ] NEW_LINE def repeated_digit ( n ) : NEW_LINE INDENT a = [ ] NEW_LINE while n != 0 : NEW_LINE INDENT d = n % 10 NEW_LINE if d in a : NEW_LINE INDENT return 0 NEW_LINE DEDENT a . append ( d ) NEW_LINE n = n // 10 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def pre_calculation ( MAX ) : NEW_LINE INDENT global Prefix NEW_LINE Prefix . append ( repeated_digit ( 1 ) ) NEW_LINE for i in range ( 2 , MAX + 1 ) : NEW_LINE INDENT Prefix . append ( repeated_digit ( i ) + Prefix [ i - 1 ] ) NEW_LINE DEDENT DEDENT def calculate ( L , R ) : NEW_LINE INDENT return Prefix [ R ] - Prefix [ L - 1 ] NEW_LINE DEDENT pre_calculation ( MAX ) NEW_LINE L = 1 NEW_LINE R = 100 NEW_LINE print ( calculate ( L , R ) ) NEW_LINE |
Difference Array | Range update query in O ( 1 ) | Creates a diff array D [ ] for A [ ] and returns it after filling initial values . ; We use one extra space because update ( l , r , x ) updates D [ r + 1 ] ; Does range update ; Prints updated Array ; Note that A [ 0 ] or D [ 0 ] decides values of rest of the elements . ; Array to be updated ; Create and fill difference Array ; After below update ( l , r , x ) , the elements should become 20 , 15 , 20 , 40 ; After below updates , the array should become 30 , 35 , 70 , 60 | def initializeDiffArray ( A ) : NEW_LINE INDENT n = len ( A ) NEW_LINE D = [ 0 for i in range ( 0 , n + 1 ) ] NEW_LINE D [ 0 ] = A [ 0 ] ; D [ n ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT D [ i ] = A [ i ] - A [ i - 1 ] NEW_LINE DEDENT return D NEW_LINE DEDENT def update ( D , l , r , x ) : NEW_LINE INDENT D [ l ] += x NEW_LINE D [ r + 1 ] -= x NEW_LINE DEDENT def printArray ( A , D ) : NEW_LINE INDENT for i in range ( 0 , len ( A ) ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT A [ i ] = D [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT A [ i ] = D [ i ] + A [ i - 1 ] NEW_LINE DEDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT A = [ 10 , 5 , 20 , 40 ] NEW_LINE D = initializeDiffArray ( A ) NEW_LINE update ( D , 0 , 1 , 10 ) NEW_LINE printArray ( A , D ) NEW_LINE update ( D , 1 , 3 , 20 ) NEW_LINE update ( D , 2 , 2 , 30 ) NEW_LINE printArray ( A , D ) NEW_LINE |
Largest Sum Contiguous Subarray | Python program to find maximum contiguous subarray Function to find the maximum contiguous subarray ; Driver function to check the above function | from sys import maxint NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - maxint - 1 NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT if max_ending_here < 0 : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT a = [ - 13 , - 3 , - 25 , - 20 , - 3 , - 16 , - 23 , - 12 , - 5 , - 22 , - 15 , - 4 , - 7 ] NEW_LINE print " Maximum β contiguous β sum β is " , maxSubArraySum ( a , len ( a ) ) NEW_LINE |
Place N ^ 2 numbers in matrix such that every row has an equal sum | Python3 program to distribute n ^ 2 numbers to n people ; 2D array for storing the final result ; Using modulo to go to the firs column after the last column ; Making a 2D array containing numbers ; Driver Code | def solve ( arr , n ) : NEW_LINE INDENT ans = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT ans [ i ] [ j ] = arr [ j ] [ ( i + j ) % n ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def show ( arr , n ) : NEW_LINE INDENT res = solve ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( res [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def makeArray ( n ) : NEW_LINE INDENT arr = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE c = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT arr [ i ] [ j ] = c NEW_LINE c += 1 NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT n = 5 NEW_LINE arr = makeArray ( n ) NEW_LINE show ( arr , n ) NEW_LINE |
Largest Sum Contiguous Subarray | ; Do not compare for all elements . Compare only when max_ending_here > 0 | def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = a [ 0 ] NEW_LINE max_ending_here = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here = max_ending_here + a [ i ] NEW_LINE if max_ending_here < 0 : NEW_LINE INDENT max_ending_here = 0 NEW_LINE DEDENT elif ( max_so_far < max_ending_here ) : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE DEDENT DEDENT return max_so_far NEW_LINE DEDENT |
Minimum rooms for m events of n batches with given schedule | Returns minimum number of rooms required to perform classes of n groups in m slots with given schedule . ; Store count of classes happening in every slot . ; initialize all values to zero ; Number of rooms required is equal to maximum classes happening in a particular slot . ; Driver Code | def findMinRooms ( slots , n , m ) : NEW_LINE INDENT counts = [ 0 ] * m ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( slots [ i ] [ j ] == '1' ) : NEW_LINE INDENT counts [ j ] += 1 ; NEW_LINE DEDENT DEDENT DEDENT return max ( counts ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE m = 7 ; NEW_LINE slots = [ "0101011" , "0011001" , "0110111" ] ; NEW_LINE print ( findMinRooms ( slots , n , m ) ) ; NEW_LINE |
Largest Sum Contiguous Subarray | Python program to find maximum contiguous subarray ; Driver function to check the above function | def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = a [ 0 ] NEW_LINE curr_max = a [ 0 ] NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT curr_max = max ( a [ i ] , curr_max + a [ i ] ) NEW_LINE max_so_far = max ( max_so_far , curr_max ) NEW_LINE DEDENT return max_so_far NEW_LINE DEDENT a = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE print " Maximum β contiguous β sum β is " , maxSubArraySum ( a , len ( a ) ) NEW_LINE |
Largest Sum Contiguous Subarray | Function to find the maximum contiguous subarray and print its starting and end index ; Driver program to test maxSubArraySum | from sys import maxsize NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - maxsize - 1 NEW_LINE max_ending_here = 0 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE s = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here += a [ i ] NEW_LINE if max_so_far < max_ending_here : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE start = s NEW_LINE end = i NEW_LINE DEDENT if max_ending_here < 0 : NEW_LINE INDENT max_ending_here = 0 NEW_LINE s = i + 1 NEW_LINE DEDENT DEDENT print ( " Maximum β contiguous β sum β is β % d " % ( max_so_far ) ) NEW_LINE print ( " Starting β Index β % d " % ( start ) ) NEW_LINE print ( " Ending β Index β % d " % ( end ) ) NEW_LINE DEDENT a = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE maxSubArraySum ( a , len ( a ) ) NEW_LINE |
Minimum sum by choosing minimum of pairs from array | Returns minimum possible sum in array B [ ] ; driver code | def minSum ( A ) : NEW_LINE INDENT min_val = min ( A ) ; NEW_LINE return min_val * ( len ( A ) - 1 ) NEW_LINE DEDENT A = [ 7 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE print ( minSum ( A ) ) NEW_LINE |
Program for Next Fit algorithm in Memory Management | Function to allocate memory to blocks as per Next fit algorithm ; Initially no block is assigned to any process ; pick each process and find suitable blocks according to its size ad assign to it ; Do not start from beginning ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; mod m will help in traversing the blocks from starting block after we reach the end . ; Driver Code | def NextFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while j < m : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT allocation [ i ] = j NEW_LINE blockSize [ j ] -= processSize [ i ] NEW_LINE break NEW_LINE DEDENT j = ( j + 1 ) % m NEW_LINE DEDENT DEDENT print ( " Process β No . β Process β Size β Block β no . " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( i + 1 , " β " , processSize [ i ] , end = " β " ) NEW_LINE if allocation [ i ] != - 1 : NEW_LINE INDENT print ( allocation [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Allocated " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT blockSize = [ 5 , 10 , 20 ] NEW_LINE processSize = [ 10 , 20 , 5 ] NEW_LINE m = len ( blockSize ) NEW_LINE n = len ( processSize ) NEW_LINE NextFit ( blockSize , m , processSize , n ) NEW_LINE DEDENT |
Find if there is a pair in root to a leaf path with sum equals to root 's data | utility that allocates a new node with the given data and None left and right pointers . ; Function to prroot to leaf path which satisfies the condition ; Base condition ; Check if current node makes a pair with any of the existing elements in set . ; Insert current node in set ; If result returned by either left or right child is True , return True . ; Remove current node from hash table ; A wrapper over printPathUtil ( ) ; create an empty hash table ; Recursively check in left and right subtrees . ; Driver Code | class newnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printPathUtil ( node , s , root_data ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT rem = root_data - node . data NEW_LINE if rem in s : NEW_LINE INDENT return True NEW_LINE DEDENT s . add ( node . data ) NEW_LINE res = printPathUtil ( node . left , s , root_data ) or printPathUtil ( node . right , s , root_data ) NEW_LINE s . remove ( node . data ) NEW_LINE return res NEW_LINE DEDENT def isPathSum ( root ) : NEW_LINE INDENT s = set ( ) NEW_LINE return printPathUtil ( root . left , s , root . data ) or printPathUtil ( root . right , s , root . data ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newnode ( 8 ) NEW_LINE root . left = newnode ( 5 ) NEW_LINE root . right = newnode ( 4 ) NEW_LINE root . left . left = newnode ( 9 ) NEW_LINE root . left . right = newnode ( 7 ) NEW_LINE root . left . right . left = newnode ( 1 ) NEW_LINE root . left . right . right = newnode ( 12 ) NEW_LINE root . left . right . right . right = newnode ( 2 ) NEW_LINE root . right . right = newnode ( 11 ) NEW_LINE root . right . right . left = newnode ( 3 ) NEW_LINE print ( " Yes " ) if ( isPathSum ( root ) ) else print ( " No " ) NEW_LINE DEDENT |
Find the subarray with least average | Prints beginning and ending indexes of subarray of size k with minimum average ; k must be smaller than or equal to n ; Initialize beginning index of result ; Compute sum of first subarray of size k ; Initialize minimum sum as current sum ; Traverse from ( k + 1 ) ' th β β element β to β n ' th element ; Add current item and remove first item of previous subarray ; Update result if needed ; Driver Code ; Subarray size | def findMinAvgSubarray ( arr , n , k ) : NEW_LINE INDENT if ( n < k ) : return 0 NEW_LINE res_index = 0 NEW_LINE curr_sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE DEDENT min_sum = curr_sum NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT curr_sum += arr [ i ] - arr [ i - k ] NEW_LINE if ( curr_sum < min_sum ) : NEW_LINE INDENT min_sum = curr_sum NEW_LINE res_index = ( i - k + 1 ) NEW_LINE DEDENT DEDENT print ( " Subarray β between β [ " , res_index , " , β " , ( res_index + k - 1 ) , " ] β has β minimum β average " ) NEW_LINE DEDENT arr = [ 3 , 7 , 90 , 20 , 10 , 50 , 40 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE findMinAvgSubarray ( arr , n , k ) NEW_LINE |
Find the Largest number with given number of digits and sum of digits | Prints the smalles possible number with digit sum ' s ' and ' m ' number of digits . ; If sum of digits is 0 , then a number is possible only if number of digits is 1. ; Sum greater than the maximum possible sum . ; Create an array to store digits of result ; Fill from most significant digit to least significant digit . ; Fill 9 first to make the number largest ; If remaining sum becomes less than 9 , then fill the remaining sum ; Driver code | def findLargest ( m , s ) : NEW_LINE INDENT if ( s == 0 ) : NEW_LINE INDENT if ( m == 1 ) : NEW_LINE INDENT print ( " Largest β number β is β " , "0" , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β possible " , end = " " ) NEW_LINE DEDENT return NEW_LINE DEDENT if ( s > 9 * m ) : NEW_LINE INDENT print ( " Not β possible " , end = " " ) NEW_LINE return NEW_LINE DEDENT res = [ 0 ] * m NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if ( s >= 9 ) : NEW_LINE INDENT res [ i ] = 9 NEW_LINE s = s - 9 NEW_LINE DEDENT else : NEW_LINE INDENT res [ i ] = s NEW_LINE s = 0 NEW_LINE DEDENT DEDENT print ( " Largest β number β is β " , end = " " ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT print ( res [ i ] , end = " " ) NEW_LINE DEDENT DEDENT s = 9 NEW_LINE m = 2 NEW_LINE findLargest ( m , s ) NEW_LINE |
Minimum number of jumps to reach end | Returns minimum number of jumps to reach arr [ h ] from arr [ l ] ; Base case : when source and destination are same ; when nothing is reachable from the given source ; Traverse through all the points reachable from arr [ l ] . Recursively get the minimum number of jumps needed to reach arr [ h ] from these reachable points . ; Driver program to test above function | def minJumps ( arr , l , h ) : NEW_LINE INDENT if ( h == l ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ l ] == 0 ) : NEW_LINE INDENT return float ( ' inf ' ) NEW_LINE DEDENT min = float ( ' inf ' ) NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( i < l + arr [ l ] + 1 ) : NEW_LINE INDENT jumps = minJumps ( arr , i , h ) NEW_LINE if ( jumps != float ( ' inf ' ) and jumps + 1 < min ) : NEW_LINE INDENT min = jumps + 1 NEW_LINE DEDENT DEDENT DEDENT return min NEW_LINE DEDENT arr = [ 1 , 3 , 6 , 3 , 2 , 3 , 6 , 8 , 9 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( ' Minimum β number β of β jumps β to β reach ' , ' end β is ' , minJumps ( arr , 0 , n - 1 ) ) NEW_LINE |
Camel and Banana Puzzle | DP | Stores the overlapping state ; Recursive function to find the maximum number of bananas that can be transferred to A distance using memoization ; Base Case where count of bananas is less that the given distance ; Base Case where count of bananas is less that camel 's capacity ; Base Case where distance = 0 ; If the current state is already calculated ; Stores the maximum count of bananas ; Stores the number of trips to transfer B bananas using a camel of capacity C ; Loop to iterate over all the breakpoints in range [ 1 , A ] ; Recursive call over the remaining path ; Update the maxCount ; Memoize the current value ; Return answer ; Function to find the maximum number of bananas that can be transferred ; Function Call ; Driver Code | dp = [ [ - 1 for i in range ( 3001 ) ] for j in range ( 1001 ) ] NEW_LINE def recBananaCnt ( A , B , C ) : NEW_LINE INDENT if ( B <= A ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( B <= C ) : NEW_LINE INDENT return B - A NEW_LINE DEDENT if ( A == 0 ) : NEW_LINE INDENT return B NEW_LINE DEDENT if ( dp [ A ] [ B ] != - 1 ) : NEW_LINE INDENT return dp [ A ] [ B ] NEW_LINE DEDENT maxCount = - 2 ** 32 NEW_LINE tripCount = ( ( 2 * B ) // C ) - 1 if ( B % C == 0 ) else ( ( 2 * B ) // C ) + 1 NEW_LINE for i in range ( 1 , A + 1 ) : NEW_LINE INDENT curCount = recBananaCnt ( A - i , B - tripCount * i , C ) NEW_LINE if ( curCount > maxCount ) : NEW_LINE INDENT maxCount = curCount NEW_LINE dp [ A ] [ B ] = maxCount NEW_LINE DEDENT DEDENT return maxCount NEW_LINE DEDENT def maxBananaCnt ( A , B , C ) : NEW_LINE INDENT return recBananaCnt ( A , B , C ) NEW_LINE DEDENT A = 1000 NEW_LINE B = 3000 NEW_LINE C = 1000 NEW_LINE print ( maxBananaCnt ( A , B , C ) ) NEW_LINE |
Count of valid arrays of size P with elements in range [ 1 , N ] having duplicates at least M distance apart | Function to calculate the total number of arrays ; If the size of the array is P ; Check if all elements are used atlease once ; Check if this state is already calculated ; Initialize the result ; Use a number from the list of unused numbers ; There are ' unused ' number of favourable choices ; Use a number from already present number atlease M distance back ; There are ' used β - β M ' number of favourable choices ; Store the result ; Function to solve the problem ; Initialize DP table : dp [ i ] [ j ] [ j ] i : current position / index j : number of used elements k : number of unused elements ; Driver Code | def calculate ( position , used , unused , P , M , dp ) : NEW_LINE INDENT if ( position == P ) : NEW_LINE INDENT if unused == 0 : NEW_LINE return 1 NEW_LINE else : NEW_LINE return 0 NEW_LINE DEDENT if ( dp [ position ] [ used ] [ unused ] != - 1 ) : NEW_LINE INDENT return dp [ position ] [ used ] [ unused ] NEW_LINE DEDENT result = 0 NEW_LINE if ( unused > 0 ) : NEW_LINE INDENT result += calculate ( position + 1 , used + 1 , unused - 1 , P , M , dp ) * unused NEW_LINE DEDENT if ( used > M ) : NEW_LINE INDENT result += calculate ( position + 1 , used , unused , P , M , dp ) * ( used - M ) NEW_LINE DEDENT dp [ position ] [ used ] [ unused ] = result NEW_LINE return dp [ position ] [ used ] [ unused ] NEW_LINE DEDENT def solve ( N , P , M ) : NEW_LINE INDENT dp = [ [ [ - 1 for i in range ( 101 ) ] for i in range ( 101 ) ] for j in range ( 101 ) ] NEW_LINE return calculate ( 0 , 0 , N , P , M , dp ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE M = 0 NEW_LINE P = 3 NEW_LINE print ( solve ( N , P , M ) ) NEW_LINE DEDENT |
Minimum number of jumps to reach end | Returns Minimum number of jumps to reach end ; jumps [ 0 ] will hold the result ; Start from the second element , move from right to left and construct the jumps [ ] array where jumps [ i ] represents minimum number of jumps needed to reach arr [ m - 1 ] form arr [ i ] ; If arr [ i ] is 0 then arr [ n - 1 ] can 't be reached from here ; If we can directly reach to the end point from here then jumps [ i ] is 1 ; Otherwise , to find out the minimum number of jumps needed to reach arr [ n - 1 ] , check all the points reachable from here and jumps [ ] value for those points ; initialize min value ; following loop checks with all reachavle points and takes the minimum ; Handle overflow ; or INT_MAX ; Driver program to test above function | def minJumps ( arr , n ) : NEW_LINE INDENT jumps = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT jumps [ i ] = float ( ' inf ' ) NEW_LINE DEDENT elif ( arr [ i ] >= n - i - 1 ) : NEW_LINE INDENT jumps [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT min = float ( ' inf ' ) NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( j <= arr [ i ] + i ) : NEW_LINE INDENT if ( min > jumps [ j ] ) : NEW_LINE INDENT min = jumps [ j ] NEW_LINE DEDENT DEDENT DEDENT if ( min != float ( ' inf ' ) ) : NEW_LINE INDENT jumps [ i ] = min + 1 NEW_LINE DEDENT else : NEW_LINE INDENT jumps [ i ] = min NEW_LINE DEDENT DEDENT DEDENT return jumps [ 0 ] NEW_LINE DEDENT arr = [ 1 , 3 , 6 , 3 , 2 , 3 , 6 , 8 , 9 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( ' Minimum β number β of β jumps β to β reach ' , ' end β is ' , minJumps ( arr , n - 1 ) ) NEW_LINE |
Count N | Stores the dp states ; Check if a number is a prime or not ; Function to generate all prime numbers that are less than or equal to n ; Base cases . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of as non - prime ; Function to find the count of N - digit numbers such that the sum of digits is a prime number ; If end of array is reached ; If the sum is equal to a prime number ; Otherwise ; If the dp - states are already computed ; If index = 1 , any digit from [ 1 - 9 ] can be placed . If N = 1 , 0 also can be placed . ; Otherwise , any digit from [ 0 - 9 ] can be placed . ; Return the answer . ; Find all primes less than or equal to 1000 , which is sufficient for N upto 100 ; Given Input ; Function call | dp = [ [ - 1 ] * 100 ] * 1000 NEW_LINE prime = [ True ] * 1005 NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT prime [ 0 ] = prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while ( p * p <= n ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , n + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def countOfNumbers ( index , sum , N ) : NEW_LINE INDENT if ( index == N + 1 ) : NEW_LINE INDENT if ( prime [ sum ] == True ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT val = dp [ index ] [ sum ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT return val NEW_LINE DEDENT val = 0 NEW_LINE if ( index == 1 ) : NEW_LINE INDENT for digit in range ( ( ( 0 , 1 ) [ N == 1 ] ) + 1 , 10 , 1 ) : NEW_LINE INDENT val += countOfNumbers ( index + 1 , sum + digit , N ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for digit in range ( 0 , 10 , 1 ) : NEW_LINE INDENT val += countOfNumbers ( index + 1 , sum + digit , N ) NEW_LINE DEDENT DEDENT return val NEW_LINE DEDENT SieveOfEratosthenes ( 1000 ) NEW_LINE N = 6 NEW_LINE print ( countOfNumbers ( 1 , 0 , N ) ) NEW_LINE |
Maximum number of groups that can receive fresh donuts distributed in batches of size K | Stores the result of the same recursive calls ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Store the key and check if it is present in the hashmap ; If already calculated ; If left is 0 ; Traverse the array [ ] arr ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] by 1 ; Otherwise , traverse the given array [ ] arr ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] by 1 ; Memoize the result and return it ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array [ ] arr ; Hashmap to memoize the results ; Store the maximum number of groups ; Return the answer ; Driver Code | memo = { } NEW_LINE def dfs ( V , left , K ) : NEW_LINE INDENT q = 0 NEW_LINE v = [ str ( int ) for int in V ] NEW_LINE key = " , " . join ( v ) NEW_LINE key += str ( left ) NEW_LINE if key in memo : NEW_LINE INDENT return memo [ key ] NEW_LINE DEDENT elif left == 0 : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE INDENT if V [ i ] > 0 : NEW_LINE INDENT V [ i ] -= 1 NEW_LINE q = max ( q , 1 + dfs ( V , K - i , K ) ) NEW_LINE V [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 1 , K ) : NEW_LINE INDENT if V [ i ] > 0 : NEW_LINE INDENT V [ i ] -= 1 NEW_LINE if i <= left : NEW_LINE INDENT nleft = left - i NEW_LINE DEDENT else : NEW_LINE INDENT nleft = K + left - i NEW_LINE DEDENT q = max ( q , dfs ( V , nleft , K ) ) NEW_LINE V [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT if key in memo : NEW_LINE INDENT memo [ key ] = q NEW_LINE DEDENT else : NEW_LINE INDENT memo [ key ] = q NEW_LINE DEDENT return q NEW_LINE DEDENT def maxGroups ( K , arr ) : NEW_LINE INDENT V = [ 0 ] * ( K ) NEW_LINE for x in range ( len ( arr ) ) : NEW_LINE INDENT V [ arr [ x ] % K ] += 1 NEW_LINE DEDENT memo = { } NEW_LINE ans = V [ 0 ] + dfs ( V , 0 , K ) NEW_LINE return ans NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE K = 3 NEW_LINE print ( maxGroups ( K , arr ) ) NEW_LINE |
Smallest subarray with sum greater than a given value | Returns length of smallest subarray with sum greater than x . If there is no subarray with given sum , then returns n + 1 ; Initialize length of smallest subarray as n + 1 ; Pick every element as starting point ; Initialize sum starting with current start ; If first element itself is greater ; Try different ending points for curremt start ; add last element to current sum ; If sum becomes more than x and length of this subarray is smaller than current smallest length , update the smallest length ( or result ) ; Driver program to test above function | def smallestSubWithSum ( arr , n , x ) : NEW_LINE INDENT min_len = n + 1 NEW_LINE for start in range ( 0 , n ) : NEW_LINE INDENT curr_sum = arr [ start ] NEW_LINE if ( curr_sum > x ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for end in range ( start + 1 , n ) : NEW_LINE INDENT curr_sum += arr [ end ] NEW_LINE if curr_sum > x and ( end - start + 1 ) < min_len : NEW_LINE INDENT min_len = ( end - start + 1 ) NEW_LINE DEDENT DEDENT DEDENT return min_len ; NEW_LINE DEDENT arr1 = [ 1 , 4 , 45 , 6 , 10 , 19 ] NEW_LINE x = 51 NEW_LINE n1 = len ( arr1 ) NEW_LINE res1 = smallestSubWithSum ( arr1 , n1 , x ) ; NEW_LINE if res1 == n1 + 1 : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res1 ) NEW_LINE DEDENT arr2 = [ 1 , 10 , 5 , 2 , 7 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE x = 9 NEW_LINE res2 = smallestSubWithSum ( arr2 , n2 , x ) ; NEW_LINE if res2 == n2 + 1 : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res2 ) NEW_LINE DEDENT arr3 = [ 1 , 11 , 100 , 1 , 0 , 200 , 3 , 2 , 1 , 250 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE x = 280 NEW_LINE res3 = smallestSubWithSum ( arr3 , n3 , x ) NEW_LINE if res3 == n3 + 1 : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res3 ) NEW_LINE DEDENT |
Smallest subarray with sum greater than a given value | Returns length of smallest subarray with sum greater than x . If there is no subarray with given sum , then returns n + 1 ; Initialize current sum and minimum length ; Initialize starting and ending indexes ; Keep adding array elements while current sum is smaller than or equal to x ; If current sum becomes greater than x . ; Update minimum length if needed ; remove starting elements ; Driver program | def smallestSubWithSum ( arr , n , x ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE min_len = n + 1 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE while ( end < n ) : NEW_LINE INDENT while ( curr_sum <= x and end < n ) : NEW_LINE INDENT curr_sum += arr [ end ] NEW_LINE end += 1 NEW_LINE DEDENT while ( curr_sum > x and start < n ) : NEW_LINE INDENT if ( end - start < min_len ) : NEW_LINE INDENT min_len = end - start NEW_LINE DEDENT curr_sum -= arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT DEDENT return min_len NEW_LINE DEDENT arr1 = [ 1 , 4 , 45 , 6 , 10 , 19 ] NEW_LINE x = 51 NEW_LINE n1 = len ( arr1 ) NEW_LINE res1 = smallestSubWithSum ( arr1 , n1 , x ) NEW_LINE print ( " Not β possible " ) if ( res1 == n1 + 1 ) else print ( res1 ) NEW_LINE arr2 = [ 1 , 10 , 5 , 2 , 7 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE x = 9 NEW_LINE res2 = smallestSubWithSum ( arr2 , n2 , x ) NEW_LINE print ( " Not β possible " ) if ( res2 == n2 + 1 ) else print ( res2 ) NEW_LINE arr3 = [ 1 , 11 , 100 , 1 , 0 , 200 , 3 , 2 , 1 , 250 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE x = 280 NEW_LINE res3 = smallestSubWithSum ( arr3 , n3 , x ) NEW_LINE print ( " Not β possible " ) if ( res3 == n3 + 1 ) else print ( res3 ) NEW_LINE |
Sum of nodes on the longest path from root to leaf node | function to get a new node ; put in the data ; function to find the Sum of nodes on the longest path from root to leaf node ; if true , then we have traversed a root to leaf path ; update maximum Length and maximum Sum according to the given conditions ; recur for left subtree ; recur for right subtree ; utility function to find the Sum of nodes on the longest path from root to leaf node ; if tree is NULL , then Sum is 0 ; finding the maximum Sum ' maxSum ' for the maximum Length root to leaf path ; required maximum Sum ; Driver Code ; binary tree formation 4 ; / \ ; 2 5 ; / \ / \ ; 7 1 2 3 ; / ; 6 | class getNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def SumOfLongRootToLeafPath ( root , Sum , Len , maxLen , maxSum ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT if ( maxLen [ 0 ] < Len ) : NEW_LINE INDENT maxLen [ 0 ] = Len NEW_LINE maxSum [ 0 ] = Sum NEW_LINE DEDENT elif ( maxLen [ 0 ] == Len and maxSum [ 0 ] < Sum ) : NEW_LINE INDENT maxSum [ 0 ] = Sum NEW_LINE DEDENT return NEW_LINE DEDENT SumOfLongRootToLeafPath ( root . left , Sum + root . data , Len + 1 , maxLen , maxSum ) NEW_LINE SumOfLongRootToLeafPath ( root . right , Sum + root . data , Len + 1 , maxLen , maxSum ) NEW_LINE DEDENT def SumOfLongRootToLeafPathUtil ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxSum = [ - 999999999999 ] NEW_LINE maxLen = [ 0 ] NEW_LINE SumOfLongRootToLeafPath ( root , 0 , 0 , maxLen , maxSum ) NEW_LINE return maxSum [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 4 ) NEW_LINE root . left = getNode ( 2 ) NEW_LINE root . right = getNode ( 5 ) NEW_LINE root . left . left = getNode ( 7 ) NEW_LINE root . left . right = getNode ( 1 ) NEW_LINE root . right . left = getNode ( 2 ) NEW_LINE root . right . right = getNode ( 3 ) NEW_LINE root . left . right . left = getNode ( 6 ) NEW_LINE print ( " Sum β = β " , SumOfLongRootToLeafPathUtil ( root ) ) NEW_LINE DEDENT |
Count L | Function to find the number of arrays of length L such that each element divides the next element ; Stores the number of sequences of length i that ends with j ; Base Case ; Iterate over the range [ 0 , l ] ; Iterate for all multiples of j ; Incrementing dp [ i + 1 ] [ k ] by dp [ i ] [ j ] as the next element is multiple of j ; Stores the number of arrays ; Add all array of length L that ends with i ; Return the resultant count ; Driver Code | def numberOfArrays ( n , l ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( l + 1 ) ] NEW_LINE dp [ 0 ] [ 1 ] = 1 NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT for k in range ( j , n + 1 , j ) : NEW_LINE INDENT dp [ i + 1 ] [ k ] += dp [ i ] [ j ] NEW_LINE DEDENT DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT ans += dp [ l ] [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , L = 2 , 4 NEW_LINE print ( numberOfArrays ( N , L ) ) NEW_LINE DEDENT |
Count minimum steps to get the given desired array | Returns count of minimum operations to convert a zero array to target array with increment and doubling operations . This function computes count by doing reverse steps , i . e . , convert target to zero array . ; Initialize result ( Count of minimum moves ) ; Keep looping while all elements of target don 't become 0. ; To store count of zeroes in current target array ; To find first odd element ; If odd number found ; If 0 , then increment zero_count ; All numbers are 0 ; All numbers are even ; Divide the whole array by 2 and increment result ; Make all odd numbers even by subtracting one and increment result . ; Driver Code | def countMinOperations ( target , n ) : NEW_LINE INDENT result = 0 ; NEW_LINE while ( True ) : NEW_LINE INDENT zero_count = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( ( target [ i ] & 1 ) > 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT elif ( target [ i ] == 0 ) : NEW_LINE INDENT zero_count += 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT if ( zero_count == n ) : NEW_LINE INDENT return result ; NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT target [ j ] = target [ j ] // 2 ; NEW_LINE DEDENT result += 1 ; NEW_LINE DEDENT for j in range ( i , n ) : NEW_LINE INDENT if ( target [ j ] & 1 ) : NEW_LINE INDENT target [ j ] -= 1 ; NEW_LINE result += 1 ; NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 16 , 16 , 16 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( " Minimum β number β of β steps β required β to " , " get the given target array is " , countMinOperations ( arr , n ) ) ; NEW_LINE |
Maximize sum of odd | Function to find the maximum sum of array elements chosen by Player A according to the given criteria ; Store the key ; Corner Case ; Check if all the elements can be taken or not ; If the difference is less than or equal to the available chances then pick all numbers ; Find the sum of array elements over the range [ start , N ] ; If yes then return that value ; Traverse over the range [ 1 , 2 * M ] ; Sum of elements for Player A ; Even chance sum can be obtained by subtracting the odd chances sum - total and picking up the maximum from that ; Storing the value in dictionary ; Return the maximum sum of odd chances ; Driver Code ; Stores the precomputed values ; Function Call | def recursiveChoosing ( arr , start , M , dp ) : NEW_LINE INDENT key = ( start , M ) NEW_LINE if start >= N : NEW_LINE INDENT return 0 NEW_LINE DEDENT if N - start <= 2 * M : NEW_LINE INDENT return sum ( arr [ start : ] ) NEW_LINE DEDENT psa = 0 NEW_LINE total = sum ( arr [ start : ] ) NEW_LINE if key in dp : NEW_LINE INDENT return dp [ key ] NEW_LINE DEDENT for x in range ( 1 , 2 * M + 1 ) : NEW_LINE INDENT psb = recursiveChoosing ( arr , start + x , max ( x , M ) , dp ) NEW_LINE psa = max ( psa , total - psb ) NEW_LINE DEDENT dp [ key ] = psa NEW_LINE return dp [ key ] NEW_LINE DEDENT arr = [ 2 , 7 , 9 , 4 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE dp = { } NEW_LINE print ( recursiveChoosing ( arr , 0 , 1 , dp ) ) NEW_LINE |
Number of subsets with product less than k | Python3 to find the count subset having product less than k ; declare four vector for dividing array into two halves and storing product value of possible subsets for them ; ignore element greater than k and divide array into 2 halves ; ignore element if greater than k ; generate all subsets for 1 st half ( vect1 ) ; push only in case subset product is less than equal to k ; generate all subsets for 2 nd half ( vect2 ) ; push only in case subset product is less than equal to k ; sort subset2 ; for null subset decrement the value of count ; return count ; Driver Code | import bisect NEW_LINE def findSubset ( arr , n , k ) : NEW_LINE INDENT vect1 , vect2 , subset1 , subset2 = [ ] , [ ] , [ ] , [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] > k : NEW_LINE INDENT continue NEW_LINE DEDENT if i <= n // 2 : NEW_LINE INDENT vect1 . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT vect2 . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( 0 , ( 1 << len ( vect1 ) ) ) : NEW_LINE INDENT value = 1 NEW_LINE for j in range ( 0 , len ( vect1 ) ) : NEW_LINE INDENT if i & ( 1 << j ) : NEW_LINE INDENT value *= vect1 [ j ] NEW_LINE DEDENT DEDENT if value <= k : NEW_LINE INDENT subset1 . append ( value ) NEW_LINE DEDENT DEDENT for i in range ( 0 , ( 1 << len ( vect2 ) ) ) : NEW_LINE INDENT value = 1 NEW_LINE for j in range ( 0 , len ( vect2 ) ) : NEW_LINE INDENT if i & ( 1 << j ) : NEW_LINE INDENT value *= vect2 [ j ] NEW_LINE DEDENT DEDENT if value <= k : NEW_LINE INDENT subset2 . append ( value ) NEW_LINE DEDENT DEDENT subset2 . sort ( ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , len ( subset1 ) ) : NEW_LINE INDENT count += bisect . bisect ( subset2 , ( k // subset1 [ i ] ) ) NEW_LINE DEDENT count -= 1 NEW_LINE return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 2 , 3 , 6 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 25 NEW_LINE print ( findSubset ( arr , n , k ) ) NEW_LINE DEDENT |
Maximum Sum Subsequence made up of consecutive elements of different parity | Function to calculate the maximum sum subsequence with consecutive terms having different parity ; Base Case ; Store the parity of number at the ith position ; If the dp state has already been calculated , return it ; If the array is traversed and no element has been selected yet then select the current element ; If the parity of the current and previously selected element are different , then select the current element ; Skip the current element and move to the next element ; Return the result ; Function to calculate the maximum sum subsequence with consecutive terms having different parity ; Initialize the dp [ ] array with - 1 ; Initially the prev value is set to say 2 , as the first element can anyways be selected ; Driver Code | def maxSum ( arr , i , n , prev , is_selected , dp ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cur = abs ( arr [ i ] ) % 2 NEW_LINE if ( dp [ i ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ prev ] NEW_LINE DEDENT if ( i == n - 1 and is_selected == 0 ) : NEW_LINE INDENT dp [ i ] [ prev ] = arr [ i ] NEW_LINE return dp [ i ] [ prev ] NEW_LINE DEDENT if ( cur != prev ) : NEW_LINE INDENT dp [ i ] [ prev ] = arr [ i ] + maxSum ( arr , i + 1 , n , cur , 1 , dp ) NEW_LINE DEDENT dp [ i ] [ prev ] = max ( dp [ i ] [ prev ] , maxSum ( arr , i + 1 , n , prev , is_selected , dp ) ) NEW_LINE return dp [ i ] [ prev ] NEW_LINE DEDENT def maxSumUtil ( arr , n ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( 3 ) ] for j in range ( 100 ) ] NEW_LINE print ( maxSum ( arr , 0 , n , 2 , 0 , dp ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 6 , 8 , - 5 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE maxSumUtil ( arr , N ) NEW_LINE DEDENT |
Find minimum number of merge operations to make an array palindrome | Returns minimum number of count operations required to make arr [ ] palindrome ; Initialize result ; Start from two corners ; If corner elements are same , problem reduces arr [ i + 1. . j - 1 ] ; If left element is greater , then we merge right two elements ; need to merge from tail . ; Else we merge left two elements ; Driver program to test above | def findMinOps ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE i , j = 0 , n - 1 NEW_LINE while i <= j : NEW_LINE INDENT if arr [ i ] == arr [ j ] : NEW_LINE INDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif arr [ i ] > arr [ j ] : NEW_LINE INDENT j -= 1 NEW_LINE arr [ j ] += arr [ j + 1 ] NEW_LINE ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE arr [ i ] += arr [ i - 1 ] NEW_LINE ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 4 , 5 , 9 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Count β of β minimum β operations β is β " + str ( findMinOps ( arr , n ) ) ) NEW_LINE |
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array | Returns the smallest number that cannot be represented as sum of subset of elements from set represented by sorted array arr [ 0. . n - 1 ] ; Initialize result ; Traverse the array and increment ' res ' if arr [ i ] is smaller than or equal to ' res ' . ; Driver program to test above function | def findSmallest ( arr , n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] <= res : NEW_LINE INDENT res = res + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr1 = [ 1 , 3 , 4 , 5 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( findSmallest ( arr1 , n1 ) ) NEW_LINE arr2 = [ 1 , 2 , 6 , 10 , 11 , 15 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( findSmallest ( arr2 , n2 ) ) NEW_LINE arr3 = [ 1 , 1 , 1 , 1 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE print ( findSmallest ( arr3 , n3 ) ) NEW_LINE arr4 = [ 1 , 1 , 3 , 4 ] NEW_LINE n4 = len ( arr4 ) NEW_LINE print ( findSmallest ( arr4 , n4 ) ) NEW_LINE |
Count distinct possible Bitwise XOR values of subsets of an array | Stores the Bitwise XOR of every possible subset ; Function to generate all combinations of subsets and store their Bitwise XOR in set S ; If the end of the subset is reached ; Stores the Bitwise XOR of the current subset ; Iterate comb [ ] to find XOR ; Insert the Bitwise XOR of R elements ; Otherwise , iterate to generate all possible subsets ; Recursive call for next index ; Function to find the size of the set having Bitwise XOR of all the subsets of the given array ; Iterate ove the given array ; Generate all possible subsets ; Print the size of the set ; Driver Code ; Function Call | s = set ( [ ] ) NEW_LINE def countXOR ( arr , comb , start , end , index , r ) : NEW_LINE INDENT if ( index == r ) : NEW_LINE INDENT new_xor = 0 NEW_LINE for j in range ( r ) : NEW_LINE INDENT new_xor ^= comb [ j ] NEW_LINE DEDENT s . add ( new_xor ) NEW_LINE return NEW_LINE DEDENT i = start NEW_LINE while i <= end and ( end - i + 1 ) >= ( r - index ) : NEW_LINE INDENT comb [ index ] = arr [ i ] NEW_LINE countXOR ( arr , comb , i + 1 , end , index + 1 , r ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def maxSizeSet ( arr , N ) : NEW_LINE INDENT for r in range ( 2 , N + 1 ) : NEW_LINE INDENT comb = [ 0 ] * ( r + 1 ) NEW_LINE countXOR ( arr , comb , 0 , N - 1 , 0 , r ) NEW_LINE DEDENT print ( len ( s ) ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE maxSizeSet ( arr , N ) NEW_LINE |
Size of The Subarray With Maximum Sum | Python3 program to print largest contiguous array sum ; Function to find the maximum contiguous subarray and print its starting and end index ; Driver program to test maxSubArraySum | from sys import maxsize NEW_LINE def maxSubArraySum ( a , size ) : NEW_LINE INDENT max_so_far = - maxsize - 1 NEW_LINE max_ending_here = 0 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE s = 0 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT max_ending_here += a [ i ] NEW_LINE if max_so_far < max_ending_here : NEW_LINE INDENT max_so_far = max_ending_here NEW_LINE start = s NEW_LINE end = i NEW_LINE DEDENT if max_ending_here < 0 : NEW_LINE INDENT max_ending_here = 0 NEW_LINE s = i + 1 NEW_LINE DEDENT DEDENT return ( end - start + 1 ) NEW_LINE DEDENT a = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE print ( maxSubArraySum ( a , len ( a ) ) ) NEW_LINE |
Longest subarray of an array which is a subsequence in another array | Function to find the length of the longest subarray in arr1 which is a subsequence in arr2 ; Length of the array arr1 ; Length of the array arr2 ; Length of the required longest subarray ; Initialize DParray ; Traverse array arr1 ; Traverse array arr2 ; arr1 [ i - 1 ] contributes to the length of the subarray ; Otherwise ; Find the maximum value present in DP ; Return the result ; Driver Code ; Function call to find the length of the longest required subarray | def LongSubarrSeq ( arr1 , arr2 ) : NEW_LINE INDENT M = len ( arr1 ) ; NEW_LINE N = len ( arr2 ) ; NEW_LINE maxL = 0 ; NEW_LINE DP = [ [ 0 for i in range ( N + 1 ) ] for j in range ( M + 1 ) ] ; NEW_LINE for i in range ( 1 , M + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( arr1 [ i - 1 ] == arr2 [ j - 1 ] ) : NEW_LINE INDENT DP [ i ] [ j ] = 1 + DP [ i - 1 ] [ j - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i ] [ j ] = DP [ i ] [ j - 1 ] ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( M + 1 ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT maxL = max ( maxL , DP [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT return maxL ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 4 , 2 , 3 , 1 , 5 , 6 ] ; NEW_LINE arr2 = [ 3 , 1 , 4 , 6 , 5 , 2 ] ; NEW_LINE print ( LongSubarrSeq ( arr1 , arr2 ) ) ; NEW_LINE DEDENT |
Find minimum difference between any two elements | Returns minimum difference between any pair ; Initialize difference as infinite ; Find the min diff by comparing difference of all possible pairs in given array ; Return min diff ; Driver code | def findMinDiff ( arr , n ) : NEW_LINE INDENT diff = 10 ** 20 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if abs ( arr [ i ] - arr [ j ] ) < diff : NEW_LINE INDENT diff = abs ( arr [ i ] - arr [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return diff NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 19 , 18 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum β difference β is β " + str ( findMinDiff ( arr , n ) ) ) NEW_LINE |
Count possible N | DP array for memoization ; Utility function to count N digit numbers with digit i not appearing more than max_digit [ i ] consecutively ; If number with N digits is generated ; Create a reference variable ; Check if the current state is already computed before ; Initialize ans as zero ; Check if count of previous digit has reached zero or not ; Fill current position only with digits that are unequal to previous digit ; Else set the value of count for this new digit accordingly from max_digit [ ] ; Function to count N digit numbers with digit i not appearing more than max_digit [ i ] consecutive times ; Stores the final count ; Print the total count ; Driver Code ; Function Call | dp = [ [ [ - 1 for i in range ( 5005 ) ] for i in range ( 12 ) ] for i in range ( 12 ) ] NEW_LINE def findCountUtil ( N , maxDigit , position , previous , count ) : NEW_LINE INDENT global dp NEW_LINE if ( position == N ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = dp [ position ] [ previous ] [ count ] NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( count == 0 and previous != i ) : NEW_LINE INDENT ans = ( ans + ( findCountUtil ( N , maxDigit , position + 1 , i , maxDigit [ i ] - 1 ) ) % 1000000007 ) % 1000000007 NEW_LINE DEDENT elif ( count != 0 ) : NEW_LINE INDENT ans = ( ans + ( findCountUtil ( N , maxDigit , position + 1 , i , count - 1 if ( previous == i and position != 0 ) else maxDigit [ i ] - 1 ) ) % 1000000007 ) % 1000000007 NEW_LINE DEDENT DEDENT dp [ position ] [ previous ] [ count ] = ans NEW_LINE return ans NEW_LINE DEDENT def findCount ( N , maxDigit ) : NEW_LINE INDENT ans = findCountUtil ( N , maxDigit , 0 , 0 , 1 ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE maxDigit = [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] NEW_LINE findCount ( N , maxDigit ) NEW_LINE DEDENT |
Find minimum difference between any two elements | Returns minimum difference between any pair ; Sort array in non - decreasing order ; Initialize difference as infinite ; Find the min diff by comparing adjacent pairs in sorted array ; Return min diff ; Driver code | def findMinDiff ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE diff = 10 ** 20 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if arr [ i + 1 ] - arr [ i ] < diff : NEW_LINE INDENT diff = arr [ i + 1 ] - arr [ i ] NEW_LINE DEDENT DEDENT return diff NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 19 , 18 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum β difference β is β " + str ( findMinDiff ( arr , n ) ) ) NEW_LINE |
Space optimization using bit manipulations | Python3 program to mark numbers as multiple of 2 or 5 ; Driver code ; Iterate through a to b , If it is a multiple of 2 or 5 Mark index in array as 1 | import math NEW_LINE a = 2 NEW_LINE b = 10 NEW_LINE size = abs ( b - a ) + 1 NEW_LINE array = [ 0 ] * size NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 or i % 5 == 0 ) : NEW_LINE INDENT array [ i - a ] = 1 NEW_LINE DEDENT DEDENT print ( " MULTIPLES β of β 2 β and β 5 : " ) NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT if ( array [ i - a ] == 1 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT |
Remove all nodes which don 't lie in any path with sum>= k | A utility function to create a new Binary Tree node with given data ; print the tree in LVR ( Inorder traversal ) way . ; Main function which truncates the binary tree . ; Base Case ; Initialize left and right Sums as Sum from root to this node ( including this node ) ; Recursively prune left and right subtrees ; Get the maximum of left and right Sums ; If maximum is smaller than k , then this node must be deleted ; A wrapper over pruneUtil ( ) ; Driver Code ; k is 45 | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def Print ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT Print ( root . left ) NEW_LINE print ( root . data , end = " β " ) NEW_LINE Print ( root . right ) NEW_LINE DEDENT DEDENT def pruneUtil ( root , k , Sum ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT lSum = [ Sum [ 0 ] + ( root . data ) ] NEW_LINE rSum = [ lSum [ 0 ] ] NEW_LINE root . left = pruneUtil ( root . left , k , lSum ) NEW_LINE root . right = pruneUtil ( root . right , k , rSum ) NEW_LINE Sum [ 0 ] = max ( lSum [ 0 ] , rSum [ 0 ] ) NEW_LINE if ( Sum [ 0 ] < k [ 0 ] ) : NEW_LINE INDENT root = None NEW_LINE DEDENT return root NEW_LINE DEDENT def prune ( root , k ) : NEW_LINE INDENT Sum = [ 0 ] NEW_LINE return pruneUtil ( root , k , Sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = [ 45 ] NEW_LINE 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 root . left . right . left = newNode ( 12 ) NEW_LINE root . right . right . left = newNode ( 10 ) NEW_LINE root . right . right . left . right = newNode ( 11 ) NEW_LINE root . left . left . right . left = newNode ( 13 ) NEW_LINE root . left . left . right . right = newNode ( 14 ) NEW_LINE root . left . left . right . right . left = newNode ( 15 ) NEW_LINE print ( " Tree β before β truncation " ) NEW_LINE Print ( root ) NEW_LINE print ( ) NEW_LINE root = prune ( root , k ) NEW_LINE print ( " Tree β after β truncation " ) NEW_LINE Print ( root ) NEW_LINE DEDENT |
Tree Traversals ( Inorder , Preorder and Postorder ) | A class that represents an individual node in a Binary Tree ; A function to do postorder tree traversal ; First recur on left child ; the recur on right child ; now print the data of node ; A function to do inorder tree traversal ; First recur on left child ; then print the data of node ; now recur on right child ; A function to do preorder tree traversal ; First print the data of node ; Then recur on left child ; Finally recur on right child ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = key NEW_LINE DEDENT DEDENT def printPostorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT printPostorder ( root . left ) NEW_LINE printPostorder ( root . right ) NEW_LINE print ( root . val ) , NEW_LINE DEDENT DEDENT def printInorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT printInorder ( root . left ) NEW_LINE print ( root . val ) , NEW_LINE printInorder ( root . right ) NEW_LINE DEDENT DEDENT def printPreorder ( root ) : NEW_LINE INDENT if root : NEW_LINE INDENT print ( root . val ) , NEW_LINE printPreorder ( root . left ) NEW_LINE printPreorder ( root . right ) NEW_LINE 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 " Preorder β traversal β of β binary β tree β is " NEW_LINE printPreorder ( root ) NEW_LINE print " NEW_LINE Inorder traversal of binary tree is " NEW_LINE printInorder ( root ) NEW_LINE print " NEW_LINE Postorder traversal of binary tree is " NEW_LINE printPostorder ( root ) NEW_LINE |
Maximum subarray sum possible after removing at most K array elements | Python3 program to implement the above approach ; Function to find the maximum subarray sum greater than or equal to 0 by removing K array elements ; Base case ; If overlapping subproblems already occurred ; Include current element in the subarray ; If K elements already removed from the subarray ; Remove current element from the subarray ; Utility function to find the maximum subarray sum by removing at most K array elements ; Stores maximum subarray sum by removing at most K elements ; Calculate maximum element in dp [ ] [ ] ; Update res ; If all array elements are negative ; Update res ; Driver Code | M = 100 NEW_LINE def mxSubSum ( i , arr , j ) : NEW_LINE INDENT global dp NEW_LINE if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( 0 , arr [ i ] ) NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT X = max ( 0 , arr [ i ] + mxSubSum ( i - 1 , arr , j ) ) NEW_LINE if ( j == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = X NEW_LINE return X NEW_LINE DEDENT Y = mxSubSum ( i - 1 , arr , j - 1 ) NEW_LINE dp [ i ] [ j ] = max ( X , Y ) NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT def MaximumSubarraySum ( n , arr , k ) : NEW_LINE INDENT mxSubSum ( n - 1 , arr , k ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( k + 1 ) : NEW_LINE INDENT res = max ( res , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT if ( max ( arr ) < 0 ) : NEW_LINE INDENT res = max ( arr ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT dp = [ [ - 1 for i in range ( 100 ) ] for i in range ( 100 ) ] NEW_LINE arr = [ - 2 , 1 , 3 , - 2 , 4 , - 7 , 20 ] NEW_LINE K = 1 NEW_LINE N = len ( arr ) NEW_LINE print ( MaximumSubarraySum ( N , arr , K ) ) NEW_LINE DEDENT |
Minimum number of operations required to make all elements of at least one row of given Matrix prime | Python 3 program to implement the above approach ; Function to generate all prime numbers using Sieve of Eratosthenes ; Function to check if a number is prime or not ; prime [ i ] : Check if i is a prime number or not ; Iterate over the range [ 2 , sqrt ( n ) ] ; If p is a prime number ; Mark all multiples of i to false ; Update i ; Function to find minimum operations to make all elements of at least one row of the matrix as prime numbers ; dp [ i ] : Stores minimum operations to get i prime numbers in a row ; Traverse the array ; Stores count of prime numbers in a i - th row ; Iterate over the range [ ( 1 << m ) - 1 , 0 ] ; If a row exist which contains j prime numbers ; Update dp [ j bitmask ] ; Update dp [ bitmask ] ; Return minimum operations to get a row of the matrix with all prime numbers ; Function to count prime numbers in a row ; i - th bit of bitmask check if i - th column is a prime or not ; Traverse the array ; if a [ i ] is a prime number ; Update bitmask ; Driver Code ; Stores count of columns in the matrix ; Stores length ; Calculate all prime numbers in range [ 1 , max ] using sieve ; Function Call | from math import sqrt NEW_LINE prime = [ True for i in range ( 10001 ) ] NEW_LINE def sieve ( n ) : NEW_LINE INDENT global prime NEW_LINE for p in range ( 2 , int ( sqrt ( 10000 ) ) + 1 , 1 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 10001 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def MinWays ( a , n , m ) : NEW_LINE INDENT dp = [ n + 1 for i in range ( 1 << m ) ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT bitmask = BitMask ( a [ i ] ) NEW_LINE j = ( 1 << m ) - 1 NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( dp [ j ] != n + 1 ) : NEW_LINE INDENT dp [ j bitmask ] = min ( dp [ j bitmask ] , dp [ j ] + 1 ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT dp [ bitmask ] = 1 NEW_LINE DEDENT if ( dp [ ( 1 << m ) - 1 ] - 1 ) == ( n + 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( dp [ ( 1 << m ) - 1 ] - 1 ) NEW_LINE DEDENT DEDENT def BitMask ( a ) : NEW_LINE INDENT global prime NEW_LINE bitmask = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT if ( prime [ a [ i ] ] ) : NEW_LINE INDENT bitmask |= ( 1 << i ) NEW_LINE DEDENT DEDENT return bitmask NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 4 , 6 , 5 , 8 ] , [ 2 , 9 , 12 , 14 ] , [ 32 , 7 , 18 , 16 ] , [ 12 , 4 , 35 , 17 ] ] NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE n = len ( mat ) NEW_LINE max = 10000 NEW_LINE sieve ( max ) NEW_LINE print ( MinWays ( mat , n , m ) ) NEW_LINE DEDENT |
Minimize cost to empty given array where cost of removing an element is its absolute difference with Time instant | Python3 program for the above approach ; Function to find the minimum cost to delete all array elements ; Sort the input array ; Store the maximum time to delete the array in the worst case ; Store the result in cost [ ] [ ] table ; Base Case ; Store the minimum of all cost values of the previous index ; Iterate from range [ 1 , n ] using variable i ; Update prev ; Iterate from range [ 1 , m ] using variable j ; Update cost [ i ] [ j ] ; Update the prev ; Store the minimum cost to delete all elements ; Find the minimum of all values of cost [ n ] [ j ] ; Print minimum cost ; Driver Code ; Function Call | INF = 10000 NEW_LINE def minCost ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE m = 2 * n NEW_LINE cost = [ [ INF for i in range ( m + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE cost [ 0 ] [ 0 ] = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT prev = cost [ i - 1 ] [ 0 ] NEW_LINE for j in range ( 1 , m + 1 ) : NEW_LINE INDENT cost [ i ] [ j ] = min ( cost [ i ] [ j ] , prev + abs ( j - arr [ i - 1 ] ) ) NEW_LINE prev = min ( prev , cost [ i - 1 ] [ j ] ) NEW_LINE DEDENT DEDENT minCost = INF NEW_LINE for j in range ( 1 , m + 1 ) : NEW_LINE INDENT minCost = min ( minCost , cost [ n ] [ j ] ) NEW_LINE DEDENT print ( minCost ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 4 , 4 , 5 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE minCost ( arr , N ) NEW_LINE DEDENT |
Space optimization using bit manipulations | Python3 code to for marking multiples ; index >> 5 corresponds to dividing index by 32 index & 31 corresponds to modulo operation of index by 32 Function to check value of bit position whether it is zero or one ; Sets value of bit for corresponding index ; Driver code ; Size that will be used is actual_size / 32 ceil is used to initialize the array with positive number ; Array is dynamically initialized as we are calculating size at run time ; Iterate through every index from a to b and call setbit ( ) if it is a multiple of 2 or 5 | import math NEW_LINE def checkbit ( array , index ) : NEW_LINE INDENT return array [ index >> 5 ] & ( 1 << ( index & 31 ) ) NEW_LINE DEDENT def setbit ( array , index ) : NEW_LINE INDENT array [ index >> 5 ] |= ( 1 << ( index & 31 ) ) NEW_LINE DEDENT a = 2 NEW_LINE b = 10 NEW_LINE size = abs ( b - a ) NEW_LINE size = math . ceil ( size / 32 ) NEW_LINE array = [ 0 for i in range ( size ) ] NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 or i % 5 == 0 ) : NEW_LINE INDENT setbit ( array , i - a ) NEW_LINE DEDENT DEDENT print ( " MULTIPLES β of β 2 β and β 5 : " ) NEW_LINE for i in range ( a , b + 1 ) : NEW_LINE INDENT if ( checkbit ( array , i - a ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT |
Longest Span with same Sum in two Binary arrays | Returns length of the longest common subarray with same sum ; Initialize result ; One by one pick all possible starting points of subarrays ; Initialize sums of current subarrays ; Conider all points for starting with arr [ i ] ; Update sums ; If sums are same and current length is more than maxLen , update maxLen ; Driver program to test above function | def longestCommonSum ( arr1 , arr2 , n ) : NEW_LINE INDENT maxLen = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum1 = 0 NEW_LINE sum2 = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT sum1 += arr1 [ j ] NEW_LINE sum2 += arr2 [ j ] NEW_LINE if ( sum1 == sum2 ) : NEW_LINE INDENT len = j - i + 1 NEW_LINE if ( len > maxLen ) : NEW_LINE INDENT maxLen = len NEW_LINE DEDENT DEDENT DEDENT DEDENT return maxLen NEW_LINE DEDENT arr1 = [ 0 , 1 , 0 , 1 , 1 , 1 , 1 ] NEW_LINE arr2 = [ 1 , 1 , 1 , 1 , 1 , 0 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( " Length β of β the β longest β common β span β with β same β " " sum β is " , longestCommonSum ( arr1 , arr2 , n ) ) NEW_LINE |
Number of Longest Increasing Subsequences | Function to count the number of LIS in the array nums [ ] ; Base Case ; Initialize dp_l array with 1 s ; Initialize dp_c array with 1 s ; If current element is smaller ; Store the maximum element from dp_l ; Stores the count of LIS ; Traverse dp_l and dp_c simultaneously ; Update the count ; Return the count of LIS ; Given array arr [ ] ; Function Call | def findNumberOfLIS ( nums ) : NEW_LINE INDENT if not nums : NEW_LINE INDENT return 0 NEW_LINE DEDENT n = len ( nums ) NEW_LINE dp_l = [ 1 ] * n NEW_LINE dp_c = [ 1 ] * n NEW_LINE for i , num in enumerate ( nums ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if nums [ i ] <= nums [ j ] : NEW_LINE INDENT continue NEW_LINE DEDENT if dp_l [ j ] + 1 > dp_l [ i ] : NEW_LINE INDENT dp_l [ i ] = dp_l [ j ] + 1 NEW_LINE dp_c [ i ] = dp_c [ j ] NEW_LINE DEDENT elif dp_l [ j ] + 1 == dp_l [ i ] : NEW_LINE INDENT dp_c [ i ] += dp_c [ j ] NEW_LINE DEDENT DEDENT DEDENT max_length = max ( x for x in dp_l ) NEW_LINE count = 0 NEW_LINE for l , c in zip ( dp_l , dp_c ) : NEW_LINE INDENT if l == max_length : NEW_LINE INDENT count += c NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 4 , 7 ] NEW_LINE print ( findNumberOfLIS ( arr ) ) NEW_LINE |
Check if a Binary Tree contains node values in strictly increasing and decreasing order at even and odd levels | ''Tree node ; ''Function to return new tree node ; ''Function to check if the tree is even-odd tree ; '' Stores nodes of each level ; '' Store the current level of the binary tree ; '' Traverse until the queue is empty ; '' Stores the number of nodes present in the current level ; '' Insert left and right child of node into the queue ; '' If the level is even ; '' If the nodes in this level are in strictly increasing order or not ; '' If the level is odd ; '' If the nodes in this level are in strictly decreasing order or not ; '' Increment the level count ; ''Driver code ; '' Construct a Binary Tree ; '' Check if the binary tree is even-odd tree or not | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . val = data NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp NEW_LINE DEDENT def checkEvenOddLevel ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE level = 0 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT l = [ ] NEW_LINE size = len ( q ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) ; NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) ; NEW_LINE DEDENT if ( level % 2 == 0 ) : NEW_LINE INDENT for i in range ( len ( l ) - 1 ) : NEW_LINE INDENT if ( l [ i + 1 ] > l [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT return False NEW_LINE DEDENT DEDENT elif ( level % 2 == 1 ) : NEW_LINE INDENT for i in range ( len ( l ) - 1 ) : NEW_LINE INDENT if ( l [ i + 1 ] < l [ i ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT return False NEW_LINE DEDENT DEDENT level += 1 NEW_LINE DEDENT return True NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = None NEW_LINE root = newNode ( 2 ) NEW_LINE root . left = newNode ( 6 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 11 ) NEW_LINE root . left . left . left = newNode ( 10 ) NEW_LINE root . left . left . right = newNode ( 5 ) NEW_LINE root . left . right . right = newNode ( 1 ) NEW_LINE if ( checkEvenOddLevel ( root ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Longest Span with same Sum in two Binary arrays | Returns largest common subarray with equal number of 0 s and 1 s ; Find difference between the two ; Creates an empty hashMap hM ; Initialize sum of elements ; Initialize result ; Traverse through the given array ; Add current element to sum ; To handle sum = 0 at last index ; If this sum is seen before , then update max_len if required ; Else put this sum in hash table ; Driver code | def longestCommonSum ( arr1 , arr2 , n ) : NEW_LINE INDENT arr = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr1 [ i ] - arr2 [ i ] ; NEW_LINE DEDENT hm = { } NEW_LINE sum = 0 NEW_LINE max_len = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE if ( sum == 0 ) : NEW_LINE INDENT max_len = i + 1 NEW_LINE DEDENT if sum in hm : NEW_LINE INDENT max_len = max ( max_len , i - hm [ sum ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hm [ sum ] = i NEW_LINE DEDENT DEDENT return max_len NEW_LINE DEDENT arr1 = [ 0 , 1 , 0 , 1 , 1 , 1 , 1 ] NEW_LINE arr2 = [ 1 , 1 , 1 , 1 , 1 , 0 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( longestCommonSum ( arr1 , arr2 , n ) ) NEW_LINE |
Minimum length of Run Length Encoding possible by removing at most K characters from a given string | Python3 program to implement the above approach ; Function which solves the desired problem ; Base Case ; If the entire string has been traversed ; If precomputed subproblem occurred ; Minimum run length encoding by removing the current character ; Minimum run length encoding by retaining the current character ; If the current and the previous characters match ; Otherwise ; Function to return minimum run - length encoding for string s by removing atmost k characters ; Driver Code | maxN = 20 NEW_LINE dp = [ [ [ [ 0 for i in range ( maxN ) ] for j in range ( 27 ) ] for k in range ( 27 ) ] for l in range ( maxN ) ] NEW_LINE def solve ( s , n , idx , k , last , count ) : NEW_LINE INDENT if ( k < 0 ) : NEW_LINE INDENT return n + 1 NEW_LINE DEDENT if ( idx == n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = dp [ idx ] [ k ] [ ord ( last ) - ord ( ' a ' ) ] [ count ] NEW_LINE if ( ans != - 1 ) : NEW_LINE INDENT return ans NEW_LINE DEDENT ans = n + 1 NEW_LINE ans = min ( ans , solve ( s , n , idx + 1 , k - 1 , last , count ) ) NEW_LINE inc = 0 NEW_LINE if ( count == 1 or count == 9 or count == 99 ) : NEW_LINE INDENT inc = 1 NEW_LINE DEDENT if ( last == s [ idx ] ) : NEW_LINE INDENT ans = min ( ans , inc + solve ( s , n , idx + 1 , k , s [ idx ] , count + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( ans , 1 + solve ( s , n , idx + 1 , k , s [ idx ] , 1 ) ) NEW_LINE DEDENT dp [ idx ] [ k ] [ ord ( last ) - ord ( ' a ' ) ] [ count ] = ans NEW_LINE print ( ans ) NEW_LINE return dp [ idx ] [ k ] [ ord ( last ) - ord ( ' a ' ) ] [ count ] NEW_LINE DEDENT def MinRunLengthEncoding ( s , n , k ) : NEW_LINE INDENT for i in range ( maxN ) : NEW_LINE INDENT for j in range ( 27 ) : NEW_LINE INDENT for k in range ( 27 ) : NEW_LINE INDENT for l in range ( maxN ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] [ l ] = - 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return solve ( s , n , 0 , k , chr ( 123 ) , 0 ) - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abbbcdcdd " NEW_LINE N = 9 NEW_LINE K = 2 NEW_LINE print ( MinRunLengthEncoding ( S , N , K ) ) NEW_LINE DEDENT |
Count unique paths is a matrix whose product of elements contains odd number of divisors | Python3 program for the above approach ; Function to calculate and store all the paths product in vector ; Base Case ; If reaches the bottom right corner and product is a perfect square ; Find square root ; If square root is an integer ; Move towards down in the matrix ; Move towards right in the matrix ; Driver Code ; Given matrix mat ; Function call | import math NEW_LINE countPaths = 0 ; NEW_LINE def CountUniquePaths ( a , i , j , m , n , ans ) : NEW_LINE INDENT if ( i >= m or j >= n ) : NEW_LINE INDENT return ; NEW_LINE DEDENT global countPaths ; NEW_LINE if ( i == m - 1 and j == n - 1 ) : NEW_LINE INDENT sr = math . sqrt ( ans * a [ i ] [ j ] ) ; NEW_LINE if ( ( sr - math . floor ( sr ) ) == 0 ) : NEW_LINE INDENT countPaths += 1 ; NEW_LINE DEDENT DEDENT CountUniquePaths ( a , i + 1 , j , m , n , ans * a [ i ] [ j ] ) ; NEW_LINE CountUniquePaths ( a , i , j + 1 , m , n , ans * a [ i ] [ j ] ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 3 ; N = 2 ; NEW_LINE mat = [ [ 1 , 1 ] , [ 3 , 1 ] , [ 3 , 1 ] ] ; NEW_LINE CountUniquePaths ( mat , 0 , 0 , M , N , 1 ) ; NEW_LINE print ( countPaths ) ; NEW_LINE DEDENT |
Maximize sum by selecting M elements from the start or end of rows of a Matrix | Function to select m elements having maximum sum ; Base case ; If precomputed subproblem occurred ; Either skip the current row ; Iterate through all the possible segments of current row ; Check if it is possible to select elements from i to j ; Compuete the sum of i to j as calculated ; Store the computed answer and return ; Function to precompute the prefix sum for every row of the matrix ; Preprocessing to calculate sum from i to j ; Utility function to select m elements having maximum sum ; Preprocessing step ; Initialize dp array with - 1 ; Stores maximum sum of M elements ; Driver Code ; Given N ; Given M ; Given matrix ; Function call | def mElementsWithMaxSum ( matrix , M , block , dp ) : NEW_LINE INDENT if block == len ( matrix ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ block ] [ M ] != - 1 ) : NEW_LINE INDENT return dp [ block ] [ M ] NEW_LINE DEDENT ans = mElementsWithMaxSum ( matrix , M , block + 1 , dp ) NEW_LINE for i in range ( len ( matrix [ block ] ) ) : NEW_LINE INDENT for j in range ( i , len ( matrix [ block ] ) ) : NEW_LINE INDENT if ( j - i + 1 <= M ) : NEW_LINE INDENT x = 0 NEW_LINE if i - 1 >= 0 : NEW_LINE INDENT x = matrix [ block ] [ i - 1 ] NEW_LINE DEDENT ans = max ( ans , matrix [ block ] [ j ] - x + mElementsWithMaxSum ( matrix , M - j + i - 1 , block + 1 , dp ) ) NEW_LINE DEDENT DEDENT DEDENT dp [ block ] [ M ] = ans NEW_LINE return ans NEW_LINE DEDENT def preComputing ( matrix , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( len ( matrix [ i ] ) ) : NEW_LINE INDENT if j > 0 : NEW_LINE INDENT matrix [ i ] [ j ] = matrix [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT return matrix NEW_LINE DEDENT def mElementsWithMaxSumUtil ( matrix , M , N ) : NEW_LINE INDENT matrix = preComputing ( matrix , N ) NEW_LINE sum = 20 NEW_LINE dp = [ [ - 1 for i in range ( M + 5 ) ] for i in range ( N + 5 ) ] NEW_LINE sum += mElementsWithMaxSum ( matrix , M , 0 , dp ) NEW_LINE print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE M = 4 NEW_LINE matrix = [ [ 2 , 3 , 5 ] , [ - 1 , 7 ] , [ 8 , 10 ] ] NEW_LINE mElementsWithMaxSumUtil ( matrix , M , N ) NEW_LINE DEDENT |
Find the last remaining element after repeated removal of odd and even indexed elements alternately | Function to calculate the last remaining element from the sequence ; If dp [ n ] is already calculated ; Base Case : ; Recursive Call ; Return the value of dp [ n ] ; Given N ; Stores the ; Function Call | def lastRemaining ( n , dp ) : NEW_LINE INDENT if n in dp : NEW_LINE INDENT return dp [ n ] NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ n ] = 2 * ( 1 + n // 2 - lastRemaining ( n // 2 , dp ) ) NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT N = 5 NEW_LINE dp = { } NEW_LINE print ( lastRemaining ( N , dp ) ) NEW_LINE |
Maximum subsequence sum possible by multiplying each element by its index | Initialize dp array ; Function to find the maximum sum of the subsequence formed ; Base Case ; If already calculated state occurs ; Include the current element ; Exclude the current element ; Update the maximum ans ; Function to calculate maximum sum of the subsequence obtained ; Print the maximum sum possible ; Given array ; Size of the array ; Function call | dp = [ [ - 1 for x in range ( 1005 ) ] for y in range ( 1005 ) ] NEW_LINE def maximumSumUtil ( a , index , count , n ) : NEW_LINE INDENT if ( index > n or count > n + 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ count ] NEW_LINE DEDENT ans1 = ( maximumSumUtil ( a , index + 1 , count + 1 , n ) + a [ index ] * count ) NEW_LINE ans2 = maximumSumUtil ( a , index + 1 , count , n ) NEW_LINE dp [ index ] [ count ] = max ( ans1 , ans2 ) NEW_LINE return dp [ index ] [ count ] NEW_LINE DEDENT def maximumSum ( arr , N ) : NEW_LINE INDENT print ( maximumSumUtil ( arr , 0 , 1 , N - 1 ) ) NEW_LINE DEDENT arr = [ - 1 , 2 , - 10 , 4 , - 20 ] NEW_LINE N = len ( arr ) NEW_LINE maximumSum ( arr , N ) NEW_LINE |
Sort an array according to absolute difference with given value | Function to sort an array according absolute difference with x . ; Store values in a map with the difference with X as key ; Update the values of array ; Function to print the array ; Driver code | def rearrange ( arr , n , x ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = abs ( x - arr [ i ] ) NEW_LINE DEDENT m = { k : v for k , v in sorted ( m . items ( ) , key = lambda item : item [ 1 ] ) } NEW_LINE i = 0 NEW_LINE for it in m . keys ( ) : NEW_LINE INDENT arr [ i ] = it NEW_LINE i += 1 NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 3 , 9 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE x = 7 NEW_LINE rearrange ( arr , n , x ) NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT |
Minimum Steps to obtain N from 1 by the given operations | Python3 program to implement the above approach ; Base Case ; Recursive Call for n - 1 ; Check if n is divisible by 2 ; Check if n is divisible by 3 ; Returns a tuple ( a , b ) , where a : Minimum steps to obtain x from 1 b : Previous number ; Function that find the optimal solution ; Print the length ; Exit condition for loop = - 1 when n has reached 1 ; Return the sequence in reverse order ; Given N ; Function Call | def find_sequence ( n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 , - 1 NEW_LINE DEDENT ans = ( find_sequence ( n - 1 ) [ 0 ] + 1 , n - 1 ) NEW_LINE if n % 2 == 0 : NEW_LINE INDENT div_by_2 = find_sequence ( n // 2 ) NEW_LINE if div_by_2 [ 0 ] < ans [ 0 ] : NEW_LINE INDENT ans = ( div_by_2 [ 0 ] + 1 , n // 2 ) NEW_LINE DEDENT DEDENT if n % 3 == 0 : NEW_LINE INDENT div_by_3 = find_sequence ( n // 3 ) NEW_LINE if div_by_3 [ 0 ] < ans [ 0 ] : NEW_LINE INDENT ans = ( div_by_3 [ 0 ] + 1 , n // 3 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def find_solution ( n ) : NEW_LINE INDENT a , b = find_sequence ( n ) NEW_LINE print ( a ) NEW_LINE sequence = [ ] NEW_LINE sequence . append ( n ) NEW_LINE while b != - 1 : NEW_LINE INDENT sequence . append ( b ) NEW_LINE _ , b = find_sequence ( b ) NEW_LINE DEDENT return sequence [ : : - 1 ] NEW_LINE DEDENT n = 5 NEW_LINE print ( * find_solution ( n ) ) NEW_LINE |
Count of vessels completely filled after a given time | Function to find the number of completely filled vessels ; Store the vessels ; Assuming all water is present in the vessel at the first level ; Store the number of vessel that are completely full ; Traverse all the levels ; Number of vessel at each level is j ; Calculate the exceeded amount of water ; If current vessel has less than 1 unit of water then continue ; One more vessel is full ; If left bottom vessel present ; If right bottom vessel present ; Number of levels ; Number of seconds ; Function call | def FindNoOfFullVessels ( n , t ) : NEW_LINE INDENT Matrix = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE Matrix [ 0 ] [ 0 ] = t * 1.0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT exceededwater = Matrix [ i ] [ j ] - 1.0 NEW_LINE if ( exceededwater < 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT ans += 1 NEW_LINE if ( i + 1 < n ) : NEW_LINE INDENT Matrix [ i + 1 ] [ j ] += exceededwater / 2 NEW_LINE DEDENT if ( i + 1 < n and j + 1 < n ) : NEW_LINE INDENT Matrix [ i + 1 ] [ j + 1 ] += exceededwater / 2 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT N = 3 NEW_LINE T = 4 NEW_LINE print ( FindNoOfFullVessels ( N , T ) ) NEW_LINE |
Sort an array in wave form | Python function to sort the array arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] >= arr [ 5 ] ; sort the array ; Swap adjacent elements ; Driver program | def sortInWave ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( 0 , n - 1 , 2 ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE DEDENT DEDENT arr = [ 10 , 90 , 49 , 2 , 1 , 5 , 23 ] NEW_LINE sortInWave ( arr , len ( arr ) ) NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT |
Count of maximum occurring subsequence using only those characters whose indices are in GP | Function to count maximum occurring subsequence using only those characters whose indexes are in GP ; Initialize 1 - D array and 2 - D dp array to 0 ; Iterate till the length of the given string ; Update ans for 1 - length subsequence ; Update ans for 2 - length subsequence ; Return the answer ; Given string s ; Function call | def findMaxTimes ( S ) : NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE dp = [ [ 0 for x in range ( 26 ) ] for y in range ( 26 ) ] NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT now = ord ( S [ i ] ) - ord ( ' a ' ) NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT dp [ j ] [ now ] += arr [ j ] NEW_LINE DEDENT arr [ now ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT ans = max ( ans , arr [ i ] ) NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT for j in range ( 26 ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT S = " ddee " NEW_LINE print ( findMaxTimes ( S ) ) NEW_LINE |
Sort an array in wave form | Python function to sort the array arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] >= arr [ 5 ] ; Traverse all even elements ; If current even element is smaller than previous ; If current even element is smaller than next ; Driver program | def sortInWave ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n , 2 ) : NEW_LINE INDENT if ( i > 0 and arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT arr [ i ] , arr [ i - 1 ] = arr [ i - 1 ] , arr [ i ] NEW_LINE DEDENT if ( i < n - 1 and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ] NEW_LINE DEDENT DEDENT DEDENT arr = [ 10 , 90 , 49 , 2 , 1 , 5 , 23 ] NEW_LINE sortInWave ( arr , len ( arr ) ) NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT |
Remove all nodes which don 't lie in any path with sum>= k | binary tree node contains data field , left and right pointer ; inorder traversal ; Function to remove all nodes which do not lie in th sum path ; Base case ; Recur for left and right subtree ; if node is leaf and sum is found greater than data than remove node An important thing to remember is that a non - leaf node can become a leaf when its children are removed ; Driver program to test above function | 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 inorder ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE print ( root . data , " " , end = " " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT def prune ( root , sum ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = prune ( root . left , sum - root . data ) NEW_LINE root . right = prune ( root . right , sum - root . data ) NEW_LINE if root . left is None and root . right is None : NEW_LINE INDENT if sum > root . data : NEW_LINE INDENT return None NEW_LINE DEDENT DEDENT return root NEW_LINE 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 root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . left . left . left = Node ( 8 ) NEW_LINE root . left . left . right = Node ( 9 ) NEW_LINE root . left . right . left = Node ( 12 ) NEW_LINE root . right . right . left = Node ( 10 ) NEW_LINE root . right . right . left . right = Node ( 11 ) NEW_LINE root . left . left . right . left = Node ( 13 ) NEW_LINE root . left . left . right . right = Node ( 14 ) NEW_LINE root . left . left . right . right . left = Node ( 15 ) NEW_LINE print ( " Tree β before β truncation " ) NEW_LINE inorder ( root ) NEW_LINE prune ( root , 45 ) NEW_LINE print ( " Tree after truncation " ) NEW_LINE inorder ( root ) NEW_LINE |
Count all possible unique sum of series K , K + 1 , K + 2 , K + 3 , K + 4 , ... , K + N | Function to count the unique sum ; Set fsum [ 0 ] as ar [ 0 ] ; Set rsum [ 0 ] as ar [ n ] ; For each i update fsum [ i ] with ar [ i ] + fsum [ i - 1 ] ; For each i from n - 1 , update rsum [ i ] with ar [ i ] + fsum [ i + 1 ] ; K represent size of subset as explained above ; Using above relation ; Return the result ; Given a number N ; Function call | def count_unique_sum ( n ) : NEW_LINE INDENT ar = [ 0 ] * ( n + 1 ) NEW_LINE fsum = [ 0 ] * ( n + 1 ) NEW_LINE rsum = [ 0 ] * ( n + 1 ) NEW_LINE ans = 1 NEW_LINE for i in range ( 0 , n + 1 ) : NEW_LINE INDENT ar [ i ] = i NEW_LINE DEDENT fsum [ 0 ] = ar [ 0 ] NEW_LINE rsum [ n ] = ar [ n ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT fsum [ i ] = ar [ i ] + fsum [ i - 1 ] NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT rsum [ i ] = ar [ i ] + rsum [ i + 1 ] NEW_LINE DEDENT for k in range ( 2 , n + 1 ) : NEW_LINE INDENT ans += ( 1 + rsum [ n + 1 - k ] - fsum [ k - 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT N = 4 NEW_LINE print ( count_unique_sum ( N ) ) NEW_LINE |
Merge an array of size n into another array of size m + n | Python program to Merge an array of size n into another array of size m + n ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current index of N [ ] ; Current index of output mPlusN [ ] ; Take an element from mPlusN [ ] if a ) value of the picked element is smaller and we have not reached end of it b ) We have reached end of N [ ] ; Otherwise take element from N [ ] ; Utility that prints out an array on a line ; Initialize arrays ; Move the m elements at the end of mPlusN ; Merge N [ ] into mPlusN [ ] ; Print the resultant mPlusN | NA = - 1 NEW_LINE def moveToEnd ( mPlusN , size ) : NEW_LINE INDENT i = 0 NEW_LINE j = size - 1 NEW_LINE for i in range ( size - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( mPlusN [ i ] != NA ) : NEW_LINE INDENT mPlusN [ j ] = mPlusN [ i ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT DEDENT def merge ( mPlusN , N , m , n ) : NEW_LINE INDENT i = n NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE while ( k < ( m + n ) ) : NEW_LINE INDENT if ( ( j == n ) or ( i < ( m + n ) and mPlusN [ i ] <= N [ j ] ) ) : NEW_LINE INDENT mPlusN [ k ] = mPlusN [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mPlusN [ k ] = N [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , " β " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT mPlusN = [ 2 , 8 , NA , NA , NA , 13 , NA , 15 , 20 ] NEW_LINE N = [ 5 , 7 , 9 , 25 ] NEW_LINE n = len ( N ) NEW_LINE m = len ( mPlusN ) - n NEW_LINE moveToEnd ( mPlusN , m + n ) NEW_LINE merge ( mPlusN , N , m , n ) NEW_LINE printArray ( mPlusN , m + n ) NEW_LINE |
Count of N | Function to return the count of such numbers ; For 1 - digit numbers , the count is 10 irrespective of K ; dp [ j ] stores the number of such i - digit numbers ending with j ; Stores the results of length i ; Initialize count for 1 - digit numbers ; Compute values for count of digits greater than 1 ; Find the range of allowed numbers if last digit is j ; Perform Range update ; Prefix sum to find actual count of i - digit numbers ending with j ; Update dp [ ] ; Stores the final answer ; Return the final answer ; Driver code | def getCount ( n , K ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 10 NEW_LINE DEDENT dp = [ 0 ] * 11 NEW_LINE next = [ 0 ] * 11 NEW_LINE for i in range ( 1 , 9 + 1 ) : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 9 + 1 ) : NEW_LINE INDENT l = max ( 0 , j - k ) NEW_LINE r = min ( 9 , j + k ) NEW_LINE next [ l ] += dp [ j ] NEW_LINE next [ r + 1 ] -= dp [ j ] NEW_LINE DEDENT for j in range ( 1 , 9 + 1 ) : NEW_LINE INDENT next [ j ] += next [ j - 1 ] NEW_LINE DEDENT for j in range ( 10 ) : NEW_LINE INDENT dp [ j ] = next [ j ] NEW_LINE next [ j ] = 0 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( 9 + 1 ) : NEW_LINE INDENT count += dp [ i ] NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE k = 1 NEW_LINE print ( getCount ( n , k ) ) NEW_LINE DEDENT |
Sort 1 to N by swapping adjacent elements | Return true if array can be sorted otherwise false ; Check bool array B and sorts elements for continuous sequence of 1 ; Sort array A from i to j ; Check if array is sorted or not ; Driver program to test sortedAfterSwap ( ) | def sortedAfterSwap ( A , B , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( B [ i ] == 1 ) : NEW_LINE INDENT j = i NEW_LINE while ( B [ j ] == 1 ) : NEW_LINE INDENT j = j + 1 NEW_LINE DEDENT A = A [ 0 : i ] + sorted ( A [ i : j + 1 ] ) + A [ j + 1 : ] NEW_LINE i = j NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( A [ i ] != i + 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT A = [ 1 , 2 , 5 , 3 , 4 , 6 ] NEW_LINE B = [ 0 , 1 , 1 , 1 , 0 ] NEW_LINE n = len ( A ) NEW_LINE if ( sortedAfterSwap ( A , B , n ) ) : NEW_LINE INDENT print ( " A β can β be β sorted " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " A β can β not β be β sorted " ) NEW_LINE DEDENT |
Print negative weight cycle in a Directed Graph | Structure to represent a weighted edge in graph ; Structure to represent a directed and weighted graph ; V . Number of vertices , E . Number of edges ; Graph is represented as an array of edges . ; Creates a new graph with V vertices and E edges ; Function runs Bellman - Ford algorithm and prints negative cycle ( if present ) ; Relax all edges | V | - 1 times . ; Check for negative - weight cycles ; Store one of the vertex of the negative weight cycle ; To store the cycle vertex ; Reverse cycle [ ] ; Printing the negative cycle ; Driver Code ; Number of vertices in graph ; Number of edges in graph ; Given Graph ; Function Call | class Edge : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . src = 0 NEW_LINE self . dest = 0 NEW_LINE self . weight = 0 NEW_LINE DEDENT DEDENT class Graph : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . V = 0 NEW_LINE self . E = 0 NEW_LINE self . edge = [ ] NEW_LINE DEDENT DEDENT def createGraph ( V , E ) : NEW_LINE INDENT graph = Graph ( ) ; NEW_LINE graph . V = V ; NEW_LINE graph . E = E ; NEW_LINE graph . edge = [ Edge ( ) for i in range ( graph . E ) ] NEW_LINE return graph ; NEW_LINE DEDENT def NegCycleBellmanFord ( graph , src ) : NEW_LINE INDENT V = graph . V ; NEW_LINE E = graph . E ; NEW_LINE dist = [ 1000000 for i in range ( V ) ] NEW_LINE parent = [ - 1 for i in range ( V ) ] NEW_LINE dist [ src ] = 0 ; NEW_LINE for i in range ( 1 , V ) : NEW_LINE INDENT for j in range ( E ) : NEW_LINE INDENT u = graph . edge [ j ] . src ; NEW_LINE v = graph . edge [ j ] . dest ; NEW_LINE weight = graph . edge [ j ] . weight ; NEW_LINE if ( dist [ u ] != 1000000 and dist [ u ] + weight < dist [ v ] ) : NEW_LINE INDENT dist [ v ] = dist [ u ] + weight ; NEW_LINE parent [ v ] = u ; NEW_LINE DEDENT DEDENT DEDENT C = - 1 ; NEW_LINE for i in range ( E ) : NEW_LINE INDENT u = graph . edge [ i ] . src ; NEW_LINE v = graph . edge [ i ] . dest ; NEW_LINE weight = graph . edge [ i ] . weight ; NEW_LINE if ( dist [ u ] != 1000000 and dist [ u ] + weight < dist [ v ] ) : NEW_LINE INDENT C = v ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( C != - 1 ) : NEW_LINE INDENT for i in range ( V ) : NEW_LINE INDENT C = parent [ C ] ; NEW_LINE DEDENT cycle = [ ] NEW_LINE v = C NEW_LINE while ( True ) : NEW_LINE INDENT cycle . append ( v ) NEW_LINE if ( v == C and len ( cycle ) > 1 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT v = parent [ v ] NEW_LINE DEDENT cycle . reverse ( ) NEW_LINE for v in cycle : NEW_LINE INDENT print ( v , end = " β " ) ; NEW_LINE DEDENT print ( ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 5 ; NEW_LINE E = 5 ; NEW_LINE graph = createGraph ( V , E ) ; NEW_LINE graph . edge [ 0 ] . src = 0 ; NEW_LINE graph . edge [ 0 ] . dest = 1 ; NEW_LINE graph . edge [ 0 ] . weight = 1 ; NEW_LINE graph . edge [ 1 ] . src = 1 ; NEW_LINE graph . edge [ 1 ] . dest = 2 ; NEW_LINE graph . edge [ 1 ] . weight = 2 ; NEW_LINE graph . edge [ 2 ] . src = 2 ; NEW_LINE graph . edge [ 2 ] . dest = 3 ; NEW_LINE graph . edge [ 2 ] . weight = 3 ; NEW_LINE graph . edge [ 3 ] . src = 3 ; NEW_LINE graph . edge [ 3 ] . dest = 4 ; NEW_LINE graph . edge [ 3 ] . weight = - 3 ; NEW_LINE graph . edge [ 4 ] . src = 4 ; NEW_LINE graph . edge [ 4 ] . dest = 1 ; NEW_LINE graph . edge [ 4 ] . weight = - 3 ; NEW_LINE NegCycleBellmanFord ( graph , 0 ) ; NEW_LINE DEDENT |
Sort 1 to N by swapping adjacent elements | Return true if array can be sorted otherwise false ; Check if array is sorted or not ; Driver program | def sortedAfterSwap ( A , B , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if B [ i ] : NEW_LINE INDENT if A [ i ] != i + 1 : NEW_LINE INDENT A [ i ] , A [ i + 1 ] = A [ i + 1 ] , A [ i ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if A [ i ] != i + 1 : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 2 , 5 , 3 , 4 , 6 ] NEW_LINE B = [ 0 , 1 , 1 , 1 , 0 ] NEW_LINE n = len ( A ) NEW_LINE if ( sortedAfterSwap ( A , B , n ) ) : NEW_LINE INDENT print ( " A β can β be β sorted " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " A β can β not β be β sorted " ) NEW_LINE DEDENT DEDENT |
Sort an array containing two types of elements | Method for segregation 0 and 1 given input array ; Driver Code | def segregate0and1 ( arr , n ) : NEW_LINE INDENT type0 = 0 ; type1 = n - 1 NEW_LINE while ( type0 < type1 ) : NEW_LINE INDENT if ( arr [ type0 ] == 1 ) : NEW_LINE INDENT arr [ type0 ] , arr [ type1 ] = arr [ type1 ] , arr [ type0 ] NEW_LINE type1 -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT type0 += 1 NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE segregate0and1 ( arr , n ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Pentanacci Numbers | Recursive program to find the Nth Pentanacci number ; Function to print the Nth Pentanacci number ; Driver code | def printpentaRec ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 or \ n == 2 or n == 3 or n == 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( n == 5 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( printpentaRec ( n - 1 ) + printpentaRec ( n - 2 ) + printpentaRec ( n - 3 ) + printpentaRec ( n - 4 ) + printpentaRec ( n - 5 ) ) NEW_LINE DEDENT DEDENT def printPenta ( n ) : NEW_LINE INDENT print ( printpentaRec ( n ) ) NEW_LINE DEDENT n = 10 NEW_LINE printPenta ( n ) NEW_LINE |
Count Inversions in an array | Set 1 ( Using Merge Sort ) | Python3 program to count inversions in an array ; Driver Code | def getInvCount ( arr , n ) : NEW_LINE INDENT inv_count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] ) : NEW_LINE INDENT inv_count += 1 NEW_LINE DEDENT DEDENT DEDENT return inv_count NEW_LINE DEDENT arr = [ 1 , 20 , 6 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Number β of β inversions β are " , getInvCount ( arr , n ) ) NEW_LINE |
Find if there is a path between two vertices in an undirected graph | Python3 program to check if there is exist a path between two vertices of an undirected graph . ; A BFS based function to check whether d is reachable from s . ; Base case ; Mark all the vertices as not visited ; Create a queue for BFS ; Mark the current node as visited and enqueue it ; Dequeue a vertex from queue and prit ; Get all adjacent vertices of the dequeued vertex s If a adjacent has not been visited , then mark it visited and enqueue it ; If this adjacent node is the destination node , then return true ; Else , continue to do BFS ; If BFS is complete without visiting d ; Driver program to test methods of graph class ; Create a graph given in the above diagram | from collections import deque NEW_LINE def addEdge ( v , w ) : NEW_LINE INDENT global adj NEW_LINE adj [ v ] . append ( w ) NEW_LINE adj [ w ] . append ( v ) NEW_LINE DEDENT def isReachable ( s , d ) : NEW_LINE INDENT if ( s == d ) : NEW_LINE INDENT return True NEW_LINE DEDENT visited = [ False for i in range ( V ) ] NEW_LINE queue = deque ( ) NEW_LINE visited [ s ] = True NEW_LINE queue . append ( s ) NEW_LINE while ( len ( queue ) > 0 ) : NEW_LINE INDENT s = queue . popleft ( ) NEW_LINE for i in adj [ s ] : NEW_LINE INDENT if ( i == d ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( not visited [ i ] ) : NEW_LINE INDENT visited [ i ] = True NEW_LINE queue . append ( i ) NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = 4 NEW_LINE adj = [ [ ] for i in range ( V + 1 ) ] NEW_LINE addEdge ( 0 , 1 ) NEW_LINE addEdge ( 0 , 2 ) NEW_LINE addEdge ( 1 , 2 ) NEW_LINE addEdge ( 2 , 0 ) NEW_LINE addEdge ( 2 , 3 ) NEW_LINE addEdge ( 3 , 3 ) NEW_LINE u , v = 1 , 3 NEW_LINE if ( isReachable ( u , v ) ) : NEW_LINE INDENT print ( " There β is β a β path β from " , u , " to " , v ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " There β is β no β path β from " , u , " to " , v ) NEW_LINE DEDENT DEDENT |
Range queries for alternatively addition and subtraction on given Array | Function to find the result of alternatively adding and subtracting elements in the range [ L , R ] ; A boolean variable flag to alternatively add and subtract ; Iterate from [ L , R ] ; If flag is False , then add & toggle the flag ; If flag is True subtract and toggle the flag ; Return the final result ; Function to find the value for each query ; Iterate for each query ; Driver Code ; Given array ; Given Queries ; Function Call | def findResultUtil ( arr , L , R ) : NEW_LINE INDENT result = 0 NEW_LINE flag = False NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT if ( flag == False ) : NEW_LINE INDENT result = result + arr [ i ] NEW_LINE flag = True NEW_LINE DEDENT else : NEW_LINE INDENT result = result - arr [ i ] NEW_LINE flag = False NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def findResult ( arr , n , q , m ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT print ( findResultUtil ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 13 , 15 , 2 , 45 , 31 , 22 , 3 , 27 ] NEW_LINE n = len ( arr ) NEW_LINE q = [ [ 2 , 5 ] , [ 6 , 8 ] , [ 1 , 7 ] , [ 4 , 8 ] , [ 0 , 5 ] ] NEW_LINE m = len ( q ) NEW_LINE findResult ( arr , n , q , m ) NEW_LINE DEDENT |
Two elements whose sum is closest to zero | Python3 code to find Two elements whose sum is closest to zero ; Array should have at least two elements ; Initialization of values ; Driver program to test above function | def minAbsSumPair ( arr , arr_size ) : NEW_LINE INDENT inv_count = 0 NEW_LINE if arr_size < 2 : NEW_LINE INDENT print ( " Invalid β Input " ) NEW_LINE return NEW_LINE DEDENT min_l = 0 NEW_LINE min_r = 1 NEW_LINE min_sum = arr [ 0 ] + arr [ 1 ] NEW_LINE for l in range ( 0 , arr_size - 1 ) : NEW_LINE INDENT for r in range ( l + 1 , arr_size ) : NEW_LINE INDENT sum = arr [ l ] + arr [ r ] NEW_LINE if abs ( min_sum ) > abs ( sum ) : NEW_LINE INDENT min_sum = sum NEW_LINE min_l = l NEW_LINE min_r = r NEW_LINE DEDENT DEDENT DEDENT print ( " The β two β elements β whose β sum β is β minimum β are " , arr [ min_l ] , " and β " , arr [ min_r ] ) NEW_LINE DEDENT arr = [ 1 , 60 , - 10 , 70 , - 80 , 85 ] NEW_LINE minAbsSumPair ( arr , 6 ) ; NEW_LINE |
Maximize sum of topmost elements of S stacks by popping at most N elements | Python3 program to maximize the sum of top of the stack values of S stacks by popping at most N element ; Function for computing the maximum sum at the top of the stacks after popping at most N elements from S stack ; Constructing a dp matrix of dimensions ( S + 1 ) x ( N + 1 ) ; Loop over all i stacks ; Store the maximum of popping j elements up to the current stack by popping k elements from current stack and j - k elements from all previous stacks combined ; Store the maximum sum of popping N elements across all stacks ; dp [ S ] [ N ] has the maximum sum ; Driver code ; Number of stacks ; Length of each stack ; Maximum elements that can be popped | import sys NEW_LINE def maximumSum ( S , M , N , stacks ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( N + 1 ) ] for y in range ( S + 1 ) ] NEW_LINE for i in range ( S ) : NEW_LINE INDENT for j in range ( N + 1 ) : NEW_LINE INDENT for k in range ( min ( j , M ) + 1 ) : NEW_LINE INDENT dp [ i + 1 ] [ j ] = max ( dp [ i + 1 ] [ j ] , stacks [ i ] [ k ] + dp [ i ] [ j - k ] ) NEW_LINE DEDENT DEDENT DEDENT result = - sys . maxsize - 1 NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT result = max ( result , dp [ S ] [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = 2 NEW_LINE M = 4 NEW_LINE stacks = [ [ 2 , 6 , 4 , 5 ] , [ 1 , 6 , 15 , 10 ] ] NEW_LINE N = 3 NEW_LINE print ( maximumSum ( S , M , N , stacks ) ) NEW_LINE DEDENT |
Abstraction of Binary Search | ''Function to find X such that it is less than the target value and function is f(x) = x ^ 2 ; '' Initialise start and end ; '' Loop till start <= end ; '' Find the mid ; '' Check for the left half ; Store the result ; Reinitialize the start point ; '' Check for the right half ; '' Print maximum value of x such that x ^ 2 is less than the targetValue ; ''Driver Code ; '' Given targetValue; ; '' Function Call | def findX ( targetValue ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = targetValue ; NEW_LINE mid = 0 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = start + ( end - start ) // 2 ; NEW_LINE if ( mid * mid <= targetValue ) : NEW_LINE INDENT result = mid NEW_LINE start = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 ; NEW_LINE DEDENT DEDENT print ( result ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT targetValue = 81 ; NEW_LINE findX ( targetValue ) ; NEW_LINE DEDENT |
Two elements whose sum is closest to zero | Python3 implementation using STL ; Modified to sort by abolute values ; Absolute value shows how close it is to zero ; If found an even close value update min and store the index ; Driver code | import sys NEW_LINE def findMinSum ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( not abs ( arr [ i - 1 ] ) < abs ( arr [ i ] ) ) : NEW_LINE INDENT arr [ i - 1 ] , arr [ i ] = arr [ i ] , arr [ i - 1 ] NEW_LINE DEDENT DEDENT Min = sys . maxsize NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( abs ( arr [ i - 1 ] + arr [ i ] ) <= Min ) : NEW_LINE INDENT Min = abs ( arr [ i - 1 ] + arr [ i ] ) NEW_LINE x = i - 1 NEW_LINE y = i NEW_LINE DEDENT DEDENT print ( " The β two β elements β whose β sum β is β minimum β are " , arr [ x ] , " and " , arr [ y ] ) NEW_LINE DEDENT arr = [ 1 , 60 , - 10 , 70 , - 80 , 85 ] NEW_LINE n = len ( arr ) NEW_LINE findMinSum ( arr , n ) NEW_LINE |
Number of ways to paint K cells in 3 x N grid such that no P continuous columns are left unpainted | Python 3 implementation to find the number of ways to paint K cells of 3 x N grid such that No two adjacent cells are painted ; Visited array to keep track of which columns were painted ; Recursive Function to compute the number of ways to paint the K cells of the 3 x N grid ; Condition to check if total cells painted are K ; Check if any P continuous columns were left unpainted ; Condition to check if no P continuous columns were left unpainted ; return 0 if there are P continuous columns are left unpainted ; Condition to check if No further cells can be painted , so return 0 ; if already calculated the value return the val instead of calculating again ; Previous column was not painted ; Column is painted so , make vis [ col ] = true ; Condition to check if the number of cells to be painted is equal to or more than 2 , then we can paint first and third row ; Condition to check if number of previous continuous columns left unpainted is less than P ; Condition to check if first row was painted in previous column ; Condition to check if second row was painted in previous column ; Condition to check if the number of cells to be painted is equal to or more than 2 , then we can paint first and third row ; Condition to check if third row was painted in previous column ; Condition to check if first and third row were painted in previous column ; Memoize the data and return the Computed value ; Function to find the number of ways to paint 3 x N grid ; Set all values of dp to - 1 ; ; Set all values of Visited array to false ; Driver Code | mod = 1e9 + 7 NEW_LINE MAX = 301 NEW_LINE MAXP = 3 NEW_LINE MAXK = 600 NEW_LINE MAXPREV = 4 NEW_LINE dp = [ [ [ [ - 1 for x in range ( MAXPREV + 1 ) ] for y in range ( MAXK ) ] for z in range ( MAXP + 1 ) ] for k in range ( MAX ) ] NEW_LINE vis = [ False ] * MAX NEW_LINE def helper ( col , prevCol , painted , prev , N , P , K ) : NEW_LINE INDENT if ( painted >= K ) : NEW_LINE INDENT continuousCol = 0 NEW_LINE maxContinuousCol = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( vis [ i ] == False ) : NEW_LINE INDENT continuousCol += 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxContinuousCol = max ( maxContinuousCol , continuousCol ) NEW_LINE continuousCol = 0 NEW_LINE DEDENT DEDENT maxContinuousCol = max ( maxContinuousCol , continuousCol ) NEW_LINE if ( maxContinuousCol < P ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( col >= N ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ col ] [ prevCol ] [ painted ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ col ] [ prevCol ] [ painted ] [ prev ] NEW_LINE DEDENT res = 0 NEW_LINE if ( prev == 0 ) : NEW_LINE INDENT vis [ col ] = True NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 1 , N , P , K ) ) % mod ) NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ) NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ) NEW_LINE if ( painted + 2 <= K ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , 0 , painted + 2 , 4 , N , P , K ) ) % mod ) NEW_LINE DEDENT vis [ col ] = False NEW_LINE if ( prevCol + 1 < P ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ) NEW_LINE DEDENT DEDENT elif ( prev == 1 ) : NEW_LINE INDENT vis [ col ] = True NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ) NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ) NEW_LINE vis [ col ] = False NEW_LINE if ( prevCol + 1 < P ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ) NEW_LINE DEDENT DEDENT elif ( prev == 2 ) : NEW_LINE INDENT vis [ col ] = True NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 1 , N , P , K ) ) % mod ) NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ) NEW_LINE if ( painted + 2 <= K ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , 0 , painted + 2 , 4 , N , P , K ) ) % mod ) NEW_LINE DEDENT vis [ col ] = False NEW_LINE if ( prevCol + 1 < P ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ) NEW_LINE DEDENT DEDENT elif ( prev == 3 ) : NEW_LINE INDENT vis [ col ] = True NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 1 , N , P , K ) ) % mod ) NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ) NEW_LINE vis [ col ] = False NEW_LINE if ( prevCol + 1 < P ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT vis [ col ] = True NEW_LINE res += ( ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ) NEW_LINE vis [ col ] = False NEW_LINE if ( prevCol + 1 < P ) : NEW_LINE INDENT res += ( ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ) NEW_LINE DEDENT DEDENT dp [ col ] [ prevCol ] [ painted ] [ prev ] = res % mod NEW_LINE return dp [ col ] [ prevCol ] [ painted ] [ prev ] NEW_LINE DEDENT def solve ( n , p , k ) : NEW_LINE INDENT global dp NEW_LINE global vis NEW_LINE return helper ( 0 , 0 , 0 , 0 , n , p , k ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE K = 2 NEW_LINE P = 2 NEW_LINE print ( int ( solve ( N , P , K ) ) ) NEW_LINE DEDENT |
Convert undirected connected graph to strongly connected directed graph | To store the assigned Edges ; Flag variable to check Bridges ; Function to implement DFS Traversal ; Mark the current node as visited ; Update the order of node v ; Update the bridge_detect for node v ; Traverse the adjacency list of Node v ; Ignores if same edge is traversed ; Ignores the edge u -- > v as v -- > u is already processed ; Finds a back Edges , cycle present ; Update the bridge_detect [ v ] ; Else DFS traversal for current node in the adjacency list ; Update the bridge_detect [ v ] ; Store the current directed Edge ; Condition for Bridges ; Return flag ; Function to print the direction of edges to make graph SCCs ; Arrays to store the visited , bridge_detect and order of Nodes ; DFS Traversal from vertex 1 ; If flag is zero , then Bridge is present in the graph ; Else print the direction of Edges assigned ; Function to create graph ; Traverse the Edges ; Push the edges in an adjacency list ; Driver code ; N vertices and M Edges ; To create Adjacency List ; Create an undirected graph ; Function Call | ans = [ ] NEW_LINE flag = 1 ; NEW_LINE def dfs ( adj , order , bridge_detect , mark , v , l ) : NEW_LINE INDENT global flag NEW_LINE mark [ v ] = 1 ; NEW_LINE order [ v ] = order [ l ] + 1 ; NEW_LINE bridge_detect [ v ] = order [ v ] ; NEW_LINE for i in range ( len ( adj [ v ] ) ) : NEW_LINE INDENT u = adj [ v ] [ i ] ; NEW_LINE if ( u == l ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( order [ v ] < order [ u ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( mark [ u ] ) : NEW_LINE INDENT bridge_detect [ v ] = min ( order [ u ] , bridge_detect [ v ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT dfs ( adj , order , bridge_detect , mark , u , v ) ; NEW_LINE DEDENT bridge_detect [ v ] = min ( bridge_detect [ u ] , bridge_detect [ v ] ) ; NEW_LINE ans . append ( [ v , u ] ) ; NEW_LINE DEDENT if ( bridge_detect [ v ] == order [ v ] and l != 0 ) : NEW_LINE INDENT flag = 0 ; NEW_LINE DEDENT return flag ; NEW_LINE DEDENT def convert ( adj , n ) : NEW_LINE INDENT order = [ 0 for i in range ( n ) ] NEW_LINE bridge_detect = [ 0 for i in range ( n ) ] NEW_LINE mark = [ False for i in range ( n ) ] NEW_LINE flag = dfs ( adj , order , bridge_detect , mark , 1 , 0 ) ; NEW_LINE if ( flag == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT for it in ans : NEW_LINE INDENT print ( " { } β - > β { } " . format ( it [ 0 ] , it [ 1 ] ) ) NEW_LINE DEDENT DEDENT DEDENT def createGraph ( Edges , adj , M ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT u = Edges [ i ] [ 0 ] ; NEW_LINE v = Edges [ i ] [ 1 ] ; NEW_LINE adj [ u ] . append ( v ) ; NEW_LINE adj [ v ] . append ( u ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE M = 6 ; NEW_LINE Edges = [ [ 0 , 1 ] , [ 0 , 2 ] , [ 1 , 2 ] , [ 1 , 4 ] , [ 2 , 3 ] , [ 3 , 4 ] ] ; NEW_LINE adj = [ [ ] for i in range ( N ) ] NEW_LINE createGraph ( Edges , adj , M ) ; NEW_LINE convert ( adj , N ) ; NEW_LINE DEDENT |
Shortest Un | Bool function for checking an array elements are in increasing ; Bool function for checking an array elements are in decreasing ; increasing and decreasing are two functions . if function return True value then print 0 otherwise 3. ; Driver code | def increasing ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] >= a [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def decreasing ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( a [ i ] < a [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def shortestUnsorted ( a , n ) : NEW_LINE INDENT if ( increasing ( a , n ) == True or decreasing ( a , n ) == True ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 3 NEW_LINE DEDENT DEDENT ar = [ 7 , 9 , 10 , 8 , 11 ] NEW_LINE n = len ( ar ) NEW_LINE print ( shortestUnsorted ( ar , n ) ) NEW_LINE |
Find the maximum path sum between two leaves of a binary tree | Python program to find maximumpath sum between two leaves of a binary tree ; A binary tree node ; Utility function to find maximum sum between anytwo leaves . This function calculates two values : 1 ) Maximum path sum between two leaves which are stored in res2 ) The maximum root to leaf path sum which is returned If one side of root is empty , then it returns INT_MIN ; Base Case ; Find maximumsum in left and righ subtree . Also find maximum root to leaf sums in left and righ subtrees ans store them in ls and rs ; If both left and right children exist ; update result if needed ; Return maximum possible value for root being on one side ; If any of the two children is empty , return root sum for root being on one side ; The main function which returns sum of the maximum sum path betwee ntwo leaves . THis function mainly uses maxPathSumUtil ( ) ; Driver program to test above function | INT_MIN = - 2 ** 32 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def maxPathSumUtil ( root , res ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT ls = maxPathSumUtil ( root . left , res ) NEW_LINE rs = maxPathSumUtil ( root . right , res ) NEW_LINE if root . left is not None and root . right is not None : NEW_LINE INDENT res [ 0 ] = max ( res [ 0 ] , ls + rs + root . data ) NEW_LINE return max ( ls , rs ) + root . data NEW_LINE DEDENT if root . left is None : NEW_LINE INDENT return rs + root . data NEW_LINE DEDENT else : NEW_LINE INDENT return ls + root . data NEW_LINE DEDENT DEDENT def maxPathSum ( root ) : NEW_LINE INDENT res = [ INT_MIN ] NEW_LINE maxPathSumUtil ( root , res ) NEW_LINE return res [ 0 ] NEW_LINE DEDENT root = Node ( - 15 ) NEW_LINE root . left = Node ( 5 ) NEW_LINE root . right = Node ( 6 ) NEW_LINE root . left . left = Node ( - 8 ) NEW_LINE root . left . right = Node ( 1 ) NEW_LINE root . left . left . left = Node ( 2 ) NEW_LINE root . left . left . right = Node ( 6 ) NEW_LINE root . right . left = Node ( 3 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE root . right . right . right = Node ( 0 ) NEW_LINE root . right . right . right . left = Node ( 4 ) NEW_LINE root . right . right . right . right = Node ( - 1 ) NEW_LINE root . right . right . right . right . left = Node ( 10 ) NEW_LINE print " Max β pathSum β of β the β given β binary β tree β is " , maxPathSum ( root ) NEW_LINE |
Minimum number of swaps required to sort an array | Function returns the minimum number of swaps required to sort the array ; Create two arrays and use as pairs where first array is element and second array is position of first element ; Sort the array by array element values to get right position of every element as the elements of second array . ; To keep track of visited elements . Initialize all elements as not visited or false . ; Initialize result ; Traverse array elements ; alreadt swapped or alreadt present at correct position ; find number of nodes in this cycle and add it to ans ; move to next node ; update answer by adding current cycle ; return answer ; Driver Code | def minSwaps ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE arrpos = [ * enumerate ( arr ) ] NEW_LINE arrpos . sort ( key = lambda it : it [ 1 ] ) NEW_LINE vis = { k : False for k in range ( n ) } NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if vis [ i ] or arrpos [ i ] [ 0 ] == i : NEW_LINE INDENT continue NEW_LINE DEDENT cycle_size = 0 NEW_LINE j = i NEW_LINE while not vis [ j ] : NEW_LINE INDENT vis [ j ] = True NEW_LINE j = arrpos [ j ] [ 0 ] NEW_LINE cycle_size += 1 NEW_LINE DEDENT if cycle_size > 0 : NEW_LINE INDENT ans += ( cycle_size - 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 5 , 4 , 3 , 2 ] NEW_LINE print ( minSwaps ( arr ) ) NEW_LINE |
Minimum number of swaps required to sort an array | swap function ; indexOf function ; Return the minimum number of swaps required to sort the array ; This is checking whether the current element is at the right place or not ; Swap the current element with the right index so that arr [ 0 ] to arr [ i ] is sorted ; Driver code ; Output will be 5 | def swap ( arr , i , j ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = temp NEW_LINE DEDENT def indexOf ( arr , ele ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] == ele ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def minSwaps ( arr , N ) : NEW_LINE INDENT ans = 0 NEW_LINE temp = arr . copy ( ) NEW_LINE temp . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != temp [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE swap ( arr , i , indexOf ( arr , temp [ i ] ) ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 101 , 758 , 315 , 730 , 472 , 619 , 460 , 479 ] NEW_LINE n = len ( a ) NEW_LINE print ( minSwaps ( a , n ) ) NEW_LINE DEDENT |
Minimum number of swaps required to sort an array | Return the minimum number of swaps required to sort the array ; Dictionary which stores the indexes of the input array ; This is checking whether the current element is at the right place or not ; If not , swap this element with the index of the element which should come here ; Update the indexes in the hashmap accordingly ; Driver code ; Output will be 5 | def minSwap ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE temp = arr . copy ( ) NEW_LINE h = { } NEW_LINE temp . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT h [ arr [ i ] ] = i NEW_LINE DEDENT init = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != temp [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE init = arr [ i ] NEW_LINE arr [ i ] , arr [ h [ temp [ i ] ] ] = arr [ h [ temp [ i ] ] ] , arr [ i ] NEW_LINE h [ init ] = h [ temp [ i ] ] NEW_LINE h [ temp [ i ] ] = i NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 101 , 758 , 315 , 730 , 472 , 619 , 460 , 479 ] NEW_LINE n = len ( a ) NEW_LINE print ( minSwap ( a , n ) ) NEW_LINE |
Union and Intersection of two sorted arrays | Function prints union of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Print remaining elements of the larger array ; Driver program to test above function | def printUnion ( arr1 , arr2 , m , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE while i < m and j < n : NEW_LINE INDENT if arr1 [ i ] < arr2 [ j ] : NEW_LINE INDENT print ( arr1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT elif arr2 [ j ] < arr1 [ i ] : NEW_LINE INDENT print ( arr2 [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr2 [ j ] ) NEW_LINE j += 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT while i < m : NEW_LINE INDENT print ( arr1 [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT while j < n : NEW_LINE INDENT print ( arr2 [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT arr1 = [ 1 , 2 , 4 , 5 , 6 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 7 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE printUnion ( arr1 , arr2 , m , n ) NEW_LINE |
Union and Intersection of two sorted arrays | Python3 program to find union of two sorted arrays ( Handling Duplicates ) ; Taking max element present in either array ; Finding elements from 1 st array ( non duplicates only ) . Using another array for storing union elements of both arrays Assuming max element present in array is not more than 10 ^ 7 ; First element is always present in final answer ; Incrementing the First element ' s β count β β in β it ' s corresponding index in newtable ; Starting traversing the first array from 1 st index till last ; Checking whether current element is not equal to it 's previous element ; Finding only non common elements from 2 nd array ; By checking whether it 's already present in newtable or not ; Driver Code | def UnionArray ( arr1 , arr2 ) : NEW_LINE INDENT m = arr1 [ - 1 ] NEW_LINE n = arr2 [ - 1 ] NEW_LINE ans = 0 NEW_LINE if m > n : NEW_LINE INDENT ans = m NEW_LINE DEDENT else : NEW_LINE INDENT ans = n NEW_LINE DEDENT newtable = [ 0 ] * ( ans + 1 ) NEW_LINE print ( arr1 [ 0 ] , end = " β " ) NEW_LINE newtable [ arr1 [ 0 ] ] += 1 NEW_LINE for i in range ( 1 , len ( arr1 ) ) : NEW_LINE INDENT if arr1 [ i ] != arr1 [ i - 1 ] : NEW_LINE INDENT print ( arr1 [ i ] , end = " β " ) NEW_LINE newtable [ arr1 [ i ] ] += 1 NEW_LINE DEDENT DEDENT for j in range ( 0 , len ( arr2 ) ) : NEW_LINE INDENT if newtable [ arr2 [ j ] ] == 0 : NEW_LINE INDENT print ( arr2 [ j ] , end = " β " ) NEW_LINE newtable [ arr2 [ j ] ] += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 1 , 2 , 2 , 2 , 3 ] NEW_LINE arr2 = [ 2 , 3 , 4 , 5 ] NEW_LINE UnionArray ( arr1 , arr2 ) NEW_LINE DEDENT |