text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Construct XOR tree by Given leaf nodes of Perfect Binary Tree | Python3 implementation of the above approach ; Maximum size for xor tree ; Allocating space to xor tree ; A recursive function that constructs xor tree for vector array [ start ... . . end ] . x is index of current node in XOR tree ; If there is one element in vector array , store it in current node of XOR tree ; cout << xor_tree [ x ] << " ▁ x " ; for left subtree ; for right subtree ; for getting the middle index from corner indexes . ; Build the left and the right subtrees by xor operation ; merge the left and right subtrees by XOR operation ; Function to construct XOR tree from the given vector array . This function calls construct_Xor_Tree_Util ( ) to fill the allocated memory of xor_tree vector array ; Driver Code ; leaf nodes of Perfect Binary Tree ; Build the xor tree ; Height of xor tree ; Maximum size of xor tree ; Root node is at index 0 considering 0 - based indexing in XOR Tree ; prevalue at root node
from math import ceil , log NEW_LINE maxsize = 100005 NEW_LINE xor_tree = [ 0 ] * maxsize NEW_LINE def construct_Xor_Tree_Util ( current , start , end , x ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT xor_tree [ x ] = current [ start ] NEW_LINE return NEW_LINE DEDENT left = x * 2 + 1 NEW_LINE right = x * 2 + 2 NEW_LINE mid = start + ( end - start ) // 2 NEW_LINE construct_Xor_Tree_Util ( current , start , mid , left ) NEW_LINE construct_Xor_Tree_Util ( current , mid + 1 , end , right ) NEW_LINE xor_tree [ x ] = ( xor_tree [ left ] ^ xor_tree [ right ] ) NEW_LINE DEDENT def construct_Xor_Tree ( arr , n ) : NEW_LINE INDENT construct_Xor_Tree_Util ( arr , 0 , n - 1 , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT leaf_nodes = [ 40 , 32 , 12 , 1 , 4 , 3 , 2 , 7 ] NEW_LINE n = len ( leaf_nodes ) NEW_LINE construct_Xor_Tree ( leaf_nodes , n ) NEW_LINE x = ( ceil ( log ( n , 2 ) ) ) NEW_LINE max_size = 2 * pow ( 2 , x ) - 1 NEW_LINE print ( " Nodes ▁ of ▁ the ▁ XOR ▁ Tree : " ) NEW_LINE for i in range ( max_size ) : NEW_LINE INDENT print ( xor_tree [ i ] , end = " ▁ " ) NEW_LINE DEDENT root = 0 NEW_LINE print ( " Root : " , xor_tree [ root ] ) NEW_LINE DEDENT
Maximize distance between any two consecutive 1 ' s ▁ after ▁ flipping ▁ M ▁ 0' s | Function to return the count ; Flipping zeros at distance " d " ; Function to implement binary search ; Check for valid distance i . e mid ; Driver code
def check ( arr , n , m , d ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < n and m > 0 ) : NEW_LINE INDENT m -= 1 NEW_LINE i += d NEW_LINE DEDENT if m == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def maximumDistance ( arr , n , m ) : NEW_LINE INDENT low = 1 NEW_LINE high = n - 1 NEW_LINE ans = 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE flag = check ( arr , n , m , mid ) NEW_LINE if ( flag ) : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE m = 3 NEW_LINE arr = [ 0 ] * n NEW_LINE print ( maximumDistance ( arr , n , m ) ) NEW_LINE
Maximum XOR value of maximum and second maximum element among all possible subarrays | Function to return the maximum possible xor ; To store the final answer ; Borward traversal ; Backward traversal ; Driver Code
def maximumXor ( arr : list , n : int ) -> int : NEW_LINE INDENT sForward , sBackward = [ ] , [ ] NEW_LINE ans = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while len ( sForward ) > 0 and arr [ i ] < arr [ sForward [ - 1 ] ] : NEW_LINE INDENT ans = max ( ans , arr [ i ] ^ arr [ sForward [ - 1 ] ] ) NEW_LINE sForward . pop ( ) NEW_LINE DEDENT sForward . append ( i ) NEW_LINE while len ( sBackward ) > 0 and arr [ n - i - 1 ] < arr [ sBackward [ - 1 ] ] : NEW_LINE INDENT ans = max ( ans , arr [ n - i - 1 ] ^ arr [ sBackward [ - 1 ] ] ) NEW_LINE sBackward . pop ( ) NEW_LINE DEDENT sBackward . append ( n - i - 1 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maximumXor ( arr , n ) ) NEW_LINE DEDENT
Minimum count of Full Binary Trees such that the count of leaves is N | Function to return the minimum count of trees required ; To store the count of set bits in n ; Driver code
def minTrees ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 ; NEW_LINE print ( minTrees ( n ) ) ; NEW_LINE DEDENT
Count number of steps to cover a distance if steps can be taken in powers of 2 | Function to count the minimum number of steps ; bin ( K ) . count ( "1" ) is a Python3 function to count the number of set bits in a number ; Driver Code
def getMinSteps ( K ) : NEW_LINE INDENT return bin ( K ) . count ( "1" ) NEW_LINE DEDENT n = 343 NEW_LINE print ( getMinSteps ( n ) ) NEW_LINE
Game Theory in Balanced Ternary Numeral System | ( Moving 3 k steps at a time ) | Function that returns true if the game cannot be won ; Driver code ; Common length
def isDefeat ( s1 , s2 , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( ( s1 [ i ] == '0' and s2 [ i ] == '1' ) or ( s1 [ i ] == '1' and s2 [ i ] == '0' ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( ( s1 [ i ] == '0' and s2 [ i ] == ' Z ' ) or ( s1 [ i ] == ' Z ' and s2 [ i ] == '0' ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s1 = "01001101ZZ " NEW_LINE s2 = "10Z1001000" NEW_LINE n = 10 NEW_LINE if ( isDefeat ( s1 , s2 , n ) ) : NEW_LINE INDENT print ( " Defeat " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Victory " ) NEW_LINE DEDENT
Check if matrix A can be converted to B by changing parity of corner elements of any submatrix | Python 3 implementation of the above approach ; Boolean function that returns true or false ; Traverse for all elements ; If both are not equal ; Change the parity of all corner elements ; Check if A is equal to B ; Not equal ; Driver Code ; First binary matrix ; Second binary matrix
N = 3 NEW_LINE M = 3 NEW_LINE def check ( a , b ) : NEW_LINE INDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT for j in range ( 1 , M , 1 ) : NEW_LINE INDENT if ( a [ i ] [ j ] != b [ i ] [ j ] ) : NEW_LINE INDENT a [ i ] [ j ] ^= 1 NEW_LINE a [ 0 ] [ 0 ] ^= 1 NEW_LINE a [ 0 ] [ j ] ^= 1 NEW_LINE a [ i ] [ 0 ] ^= 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( a [ i ] [ j ] != b [ i ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ [ 0 , 1 , 0 ] , [ 0 , 1 , 0 ] , [ 1 , 0 , 0 ] ] NEW_LINE b = [ [ 1 , 0 , 0 ] , [ 1 , 0 , 0 ] , [ 1 , 0 , 0 ] ] NEW_LINE if ( check ( a , b ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Position of the K | Function that returns the Kth set bit ; Traverse in the binary ; Check if the last bit is set or not ; Check if count is equal to k then return the index ; Increase the index as we move right ; Right shift the number by 1 ; Driver Code
def FindIndexKthBit ( n , k ) : NEW_LINE INDENT cnt , ind = 0 , 0 NEW_LINE while n > 0 : NEW_LINE INDENT if n & 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if cnt == k : NEW_LINE INDENT return ind NEW_LINE DEDENT ind += 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 15 , 3 NEW_LINE ans = FindIndexKthBit ( n , k ) NEW_LINE if ans != - 1 : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ k - th ▁ set ▁ bit " ) NEW_LINE DEDENT DEDENT
Check if the binary representation of a number has equal number of 0 s and 1 s in blocks | Function to check ; Converting integer to its equivalent binary number ; If adjacent character are same then increase counter ; Driver code
def hasEqualBlockFrequency ( N ) : NEW_LINE INDENT S = bin ( N ) . replace ( "0b " , " " ) NEW_LINE p = set ( ) NEW_LINE c = 1 NEW_LINE for i in range ( len ( S ) - 1 ) : NEW_LINE INDENT if ( S [ i ] == S [ i + 1 ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT else : NEW_LINE INDENT p . add ( c ) NEW_LINE c = 1 NEW_LINE DEDENT p . add ( c ) NEW_LINE DEDENT if ( len ( p ) == 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE hasEqualBlockFrequency ( N ) NEW_LINE
Distance between two nodes of binary tree with node values from 1 to N | Python 3 program to find minimum distance between two nodes in binary tree ; Function to get minimum path distance ; find the 1 st dis - similar bit count bit length of n1 and n2 ; find bit difference and maxBit ; calculate result by formula ; Driver Code
from math import log2 NEW_LINE def minDistance ( n1 , n2 ) : NEW_LINE INDENT bitCount1 = int ( log2 ( n1 ) ) + 1 NEW_LINE bitCount2 = int ( log2 ( n2 ) ) + 1 NEW_LINE bitDiff = abs ( bitCount1 - bitCount2 ) NEW_LINE maxBitCount = max ( bitCount1 , bitCount2 ) NEW_LINE if ( bitCount1 > bitCount2 ) : NEW_LINE INDENT n2 = int ( n2 * pow ( 2 , bitDiff ) ) NEW_LINE DEDENT else : NEW_LINE INDENT n1 = int ( n1 * pow ( 2 , bitDiff ) ) NEW_LINE DEDENT xorValue = n1 ^ n2 NEW_LINE if xorValue == 0 : NEW_LINE INDENT bitCountXorValue = 1 NEW_LINE DEDENT else : NEW_LINE INDENT bitCountXorValue = int ( log2 ( xorValue ) ) + 1 NEW_LINE DEDENT disSimilarBitPosition = ( maxBitCount - bitCountXorValue ) NEW_LINE result = ( bitCount1 + bitCount2 - 2 * disSimilarBitPosition ) NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n1 = 12 NEW_LINE n2 = 5 NEW_LINE print ( minDistance ( n1 , n2 ) ) NEW_LINE DEDENT
Remove one bit from a binary number to get maximum value | Function to find the maximum binary number ; Traverse the binary number ; Try finding a 0 and skip it ; Driver code ; Get the binary number ; Find the maximum binary number
def printMaxAfterRemoval ( s ) : NEW_LINE INDENT flag = False NEW_LINE n = len ( s ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if s [ i ] == '0' and flag == False : NEW_LINE INDENT flag = True NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "1001" NEW_LINE printMaxAfterRemoval ( s ) NEW_LINE DEDENT
Find position of left most dis | Python3 program to Find the leftmost position of first dis - similar bit ; Function to find first dis - similar bit ; return zero for equal number ; find the 1 st dis - similar bit count bit length of n1 and n ; find bit difference and maxBit ; Driver code
from math import floor , log2 NEW_LINE def bitPos ( n1 , n2 ) : NEW_LINE INDENT if n1 == n2 : NEW_LINE INDENT return 0 NEW_LINE DEDENT bitCount1 = floor ( log2 ( n1 ) ) + 1 NEW_LINE bitCount2 = floor ( log2 ( n2 ) ) + 1 NEW_LINE bitDiff = abs ( bitCount1 - bitCount2 ) NEW_LINE maxBitCount = max ( bitCount1 , bitCount2 ) NEW_LINE if ( bitCount1 > bitCount2 ) : NEW_LINE INDENT n2 *= pow ( 2 , bitDiff ) NEW_LINE DEDENT else : NEW_LINE INDENT n1 *= pow ( 2 , bitDiff ) NEW_LINE DEDENT xorValue = n1 ^ n2 NEW_LINE bitCountXorValue = floor ( log2 ( xorValue ) ) + 1 NEW_LINE disSimilarBitPosition = ( maxBitCount - bitCountXorValue + 1 ) NEW_LINE return disSimilarBitPosition NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n1 , n2 = 53 , 55 NEW_LINE print ( bitPos ( n1 , n2 ) ) NEW_LINE DEDENT
Number of pairs with Bitwise OR as Odd number | Function to count pairs with odd OR ; Count total even numbers in array ; Even pair count ; Total pairs ; Return Odd pair count ; Driver Code
def countOddPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] % 2 != 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT evenPairCount = count * ( count - 1 ) / 2 NEW_LINE totPairs = N * ( N - 1 ) / 2 NEW_LINE return ( int ) ( totPairs - evenPairCount ) NEW_LINE DEDENT A = [ 5 , 6 , 2 , 8 ] NEW_LINE N = len ( A ) NEW_LINE print ( countOddPair ( A , N ) ) NEW_LINE
Replace every array element by Bitwise Xor of previous and next element | Python3 program to update every array element with sum of previous and next numbers in array ; Nothing to do when array size is 1 ; store current value of arr [ 0 ] and update it ; Update rest of the array elements ; Store current value of next interaction ; Update current value using previous value ; Update previous value ; Update last array element separately ; Driver Code ; Print the modified array
def ReplaceElements ( arr , n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return NEW_LINE DEDENT prev = arr [ 0 ] NEW_LINE arr [ 0 ] = arr [ 0 ] ^ arr [ 1 ] NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT curr = arr [ i ] NEW_LINE arr [ i ] = prev ^ arr [ i + 1 ] NEW_LINE prev = curr NEW_LINE DEDENT arr [ n - 1 ] = prev ^ arr [ n - 1 ] NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE ReplaceElements ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Find triplets in an array whose AND is maximum | Python3 program to find triplet with maximum bitwise AND . ; Flag Array initially set to true for all numbers ; 2D array for bit representation of all the numbers . Initially all bits are set to 0. ; Finding bit representation of every number and storing it in bits array . ; Checking last bit of the number ; Dividing number by 2. ; maximum And number initially 0. ; Traversing the 2d binary representation . 0 th index represents 32 th bits while 32 th index represents 0 th bit . ; If cnt greater than 3 then ( 32 - i ) th bits of the number will be set . ; Setting flags of the numbers whose ith bit is not set . ; Counting the numbers whose flag are true . ; Driver Code
def maxTriplet ( a , n ) : NEW_LINE INDENT f = [ True for i in range ( n ) ] NEW_LINE bits = [ [ 0 for i in range ( 33 ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT num = a [ i ] NEW_LINE j = 32 NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT bits [ i ] [ j ] = 1 NEW_LINE DEDENT j -= 1 NEW_LINE num >>= 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( 33 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( bits [ j ] [ i ] and f [ j ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt >= 3 ) : NEW_LINE INDENT ans += pow ( 2 , 32 - i ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( bits [ j ] [ i ] == False ) : NEW_LINE INDENT f [ j ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( f [ i ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT NumberOfTriplets = ( cnt * ( cnt - 1 ) * ( cnt - 2 ) ) // 6 NEW_LINE print ( NumberOfTriplets , ans ) NEW_LINE DEDENT a = [ 4 , 11 , 10 , 15 , 26 ] NEW_LINE n = len ( a ) NEW_LINE maxTriplet ( a , n ) NEW_LINE
Find bitwise OR of all possible sub | function to return OR of sub - arrays ; Driver Code ; print OR of all subarrays
def OR ( a , n ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ans |= a [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 4 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( OR ( a , n ) ) NEW_LINE DEDENT
Maximum set bit sum in array without considering adjacent elements | Function to count total number of set bits in an integer ; Maximum sum of set bits ; Calculate total number of set bits for every element of the array ; find total set bits for each number and store back into the array ; current max excluding i ; current max including i ; return max of incl and excl ; Driver code
def bit ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += 1 NEW_LINE n = n & ( n - 1 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def maxSumOfBits ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = bit ( arr [ i ] ) NEW_LINE DEDENT incl = arr [ 0 ] NEW_LINE excl = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if incl > excl : NEW_LINE INDENT excl_new = incl NEW_LINE DEDENT else : NEW_LINE INDENT excl_new = excl NEW_LINE DEDENT incl = excl + arr [ i ] ; NEW_LINE excl = excl_new NEW_LINE DEDENT if incl > excl : NEW_LINE INDENT return incl NEW_LINE DEDENT else : NEW_LINE INDENT return excl NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 5 , 6 , 7 , 20 , 25 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSumOfBits ( arr , n ) ) NEW_LINE DEDENT
Increment a number without using ++ or + | function that increment the value . ; Invert bits and apply negative sign ; Driver code
def increment ( i ) : NEW_LINE INDENT i = - ( ~ ord ( i ) ) ; NEW_LINE return chr ( i ) ; NEW_LINE DEDENT n = ' a ' ; NEW_LINE print ( increment ( n ) ) ; NEW_LINE
Count pairs with Bitwise XOR as ODD number | Function to count number of odd pairs ; find all pairs ; return number of odd pair ; Driver Code ; calling function findOddPair and print number of odd pair
def findOddPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count * ( N - count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 5 , 4 , 7 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( findOddPair ( a , n ) ) NEW_LINE DEDENT
Bitwise OR ( or | ) of a range | Returns the Most Significant Bit Position ( MSB ) ; Returns the Bitwise OR of all integers between L and R ; Find the MSB position in L ; Find the MSB position in R ; Add this value until msb_p1 and msb_p2 are same ; ; Calculate msb_p1 and msb_p2 ; Find the max of msb_p1 and msb_p2 ; Set all the bits from msb_p1 upto 0 th bit in the result ; Driver Code
def MSBPosition ( N ) : NEW_LINE INDENT msb_p = - 1 NEW_LINE while ( N ) : NEW_LINE INDENT N = N >> 1 NEW_LINE msb_p += 1 NEW_LINE DEDENT return msb_p NEW_LINE DEDENT def findBitwiseOR ( L , R ) : NEW_LINE INDENT res = 0 NEW_LINE msb_p1 = MSBPosition ( L ) NEW_LINE msb_p2 = MSBPosition ( R ) NEW_LINE while ( msb_p1 == msb_p2 ) : NEW_LINE INDENT res_val = ( 1 << msb_p1 ) NEW_LINE res += res_val NEW_LINE L -= res_val NEW_LINE R -= res_val NEW_LINE msb_p1 = MSBPosition ( L ) NEW_LINE msb_p2 = MSBPosition ( R ) NEW_LINE DEDENT msb_p1 = max ( msb_p1 , msb_p2 ) NEW_LINE for i in range ( msb_p1 , - 1 , - 1 ) : NEW_LINE INDENT res_val = ( 1 << i ) NEW_LINE res += res_val NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L , R = 12 , 18 NEW_LINE print ( findBitwiseOR ( L , R ) ) NEW_LINE DEDENT
Maximize the bitwise OR of an array | Function to maximize the bitwise OR sum ; Compute x ^ k ; Find prefix bitwise OR ; Find suffix bitwise OR ; Find maximum OR value ; Drivers code
def maxOR ( arr , n , k , x ) : NEW_LINE INDENT preSum = [ 0 ] * ( n + 1 ) NEW_LINE suffSum = [ 0 ] * ( n + 1 ) NEW_LINE pow = 1 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT pow *= x NEW_LINE DEDENT preSum [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT preSum [ i + 1 ] = preSum [ i ] | arr [ i ] NEW_LINE DEDENT suffSum [ n ] = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT suffSum [ i ] = suffSum [ i + 1 ] | arr [ i ] NEW_LINE DEDENT res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT res = max ( res , preSum [ i ] | ( arr [ i ] * pow ) suffSum [ i + 1 ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 2 , 4 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE x = 3 NEW_LINE print ( maxOR ( arr , n , k , x ) ) NEW_LINE
How to turn on a particular bit in a number ? | Returns a number that has all bits same as n except the k 'th bit which is made 1 ; k must be greater than 0 ; Do | of n with a number with all unset bits except the k 'th bit ; Driver program to test above function
def turnOnK ( n , k ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return ( n | ( 1 << ( k - 1 ) ) ) NEW_LINE DEDENT n = 4 NEW_LINE k = 2 NEW_LINE print ( turnOnK ( n , k ) ) NEW_LINE
Minimum sum of two numbers formed from digits of an array | Returns sum of two numbers formed from all digits in a [ ] ; sorted the elements ; Driver code
def minSum ( a , n ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE num1 , num2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT num1 = num1 * 10 + a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT num2 = num2 * 10 + a [ i ] NEW_LINE DEDENT DEDENT return num2 + num1 NEW_LINE DEDENT arr = [ 5 , 3 , 0 , 7 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The ▁ required ▁ sum ▁ is " , minSum ( arr , n ) ) NEW_LINE
Find value of k | Python 3 program to find k - th bit from right ; Driver Code ; Function Call
def printKthBit ( n , k ) : NEW_LINE INDENT print ( ( n & ( 1 << ( k - 1 ) ) ) >> ( k - 1 ) ) NEW_LINE DEDENT n = 13 NEW_LINE k = 2 NEW_LINE printKthBit ( n , k ) NEW_LINE
Disjoint Set Union on trees | Set 1 | Python3 code to find maximum subtree such that all nodes are even in weight ; Structure for Edge ; ' id ' : stores parent of a node . ' sz ' : stores size of a DSU tree . ; Function to assign root ; Function to find Union ; Utility function for Union ; Edge between ' u ' and 'v ; 0 - indexed nodes ; If weights of both ' u ' and ' v ' are even then we make union of them . ; Function to find maximum size of DSU tree ; Driver code ; Weights of nodes ; Number of nodes in a tree ; Initializing every node as a tree with single node . ; Find maximum size of DSU tree .
N = 100010 NEW_LINE class Edge : NEW_LINE INDENT def __init__ ( self , u , v ) : NEW_LINE INDENT self . u = u NEW_LINE self . v = v NEW_LINE DEDENT DEDENT id = [ 0 for i in range ( N ) ] NEW_LINE sz = [ 0 for i in range ( N ) ] ; NEW_LINE def Root ( idx ) : NEW_LINE INDENT i = idx ; NEW_LINE while ( i != id [ i ] ) : NEW_LINE INDENT id [ i ] = id [ id [ i ] ] NEW_LINE i = id [ i ] ; NEW_LINE DEDENT return i ; NEW_LINE DEDENT def Union ( a , b ) : NEW_LINE INDENT i = Root ( a ) NEW_LINE j = Root ( b ) ; NEW_LINE if ( i != j ) : NEW_LINE INDENT if ( sz [ i ] >= sz [ j ] ) : NEW_LINE INDENT id [ j ] = i NEW_LINE sz [ i ] += sz [ j ] ; NEW_LINE sz [ j ] = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT id [ i ] = j NEW_LINE sz [ j ] += sz [ i ] ; NEW_LINE sz [ i ] = 0 ; NEW_LINE DEDENT DEDENT DEDENT def UnionUtil ( e , W , q ) : NEW_LINE INDENT for i in range ( q ) : NEW_LINE DEDENT ' NEW_LINE INDENT u = e [ i ] . u NEW_LINE v = e [ i ] . v NEW_LINE u -= 1 NEW_LINE v -= 1 NEW_LINE if ( W [ u ] % 2 == 0 and W [ v ] % 2 == 0 ) : NEW_LINE INDENT Union ( u , v ) ; NEW_LINE DEDENT DEDENT def findMax ( n , W ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( W [ i ] % 2 == 0 ) : NEW_LINE INDENT maxi = max ( maxi , sz [ i ] ) ; NEW_LINE DEDENT DEDENT return maxi ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT W = [ 1 , 2 , 6 , 4 , 2 , 0 , 3 ] NEW_LINE n = len ( W ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT id [ i ] = i NEW_LINE sz [ i ] = 1 ; NEW_LINE DEDENT e = [ Edge ( 1 , 2 ) , Edge ( 1 , 3 ) , Edge ( 2 , 4 ) , Edge ( 2 , 5 ) , Edge ( 4 , 6 ) , Edge ( 6 , 7 ) ] NEW_LINE q = len ( e ) NEW_LINE UnionUtil ( e , W , q ) ; NEW_LINE maxi = findMax ( n , W ) ; NEW_LINE print ( " Maximum ▁ size ▁ of ▁ the ▁ subtree ▁ with ▁ " , end = ' ' ) ; NEW_LINE print ( " even ▁ weighted ▁ nodes ▁ = " , maxi ) ; NEW_LINE DEDENT
Odd numbers in N | Function to get no of set bits in binary representation of positive integer n ; Count number of 1 's in binary representation of n. ; Number of odd numbers in n - th row is 2 raised to power the count . ; Driver Program
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while n : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countOfOddPascal ( n ) : NEW_LINE INDENT c = countSetBits ( n ) NEW_LINE return pow ( 2 , c ) NEW_LINE DEDENT n = 20 NEW_LINE print ( countOfOddPascal ( n ) ) NEW_LINE
Queries on XOR of XORs of all subarrays | Python 3 Program to answer queries on XOR of XORs of all subarray ; Output for each query ; If number of element is even . ; If number of element is odd . ; if l is even ; if l is odd ; Wrapper Function ; Evaluating prefixodd and prefixeven ; Driver Code
N = 100 NEW_LINE def ansQueries ( prefeven , prefodd , l , r ) : NEW_LINE INDENT if ( ( r - l + 1 ) % 2 == 0 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( l % 2 == 0 ) : NEW_LINE INDENT print ( prefeven [ r ] ^ prefeven [ l - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( prefodd [ r ] ^ prefodd [ l - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT def wrapper ( arr , n , l , r , q ) : NEW_LINE INDENT prefodd = [ 0 ] * N NEW_LINE prefeven = [ 0 ] * N NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( ( i ) % 2 == 0 ) : NEW_LINE INDENT prefeven [ i ] = arr [ i - 1 ] ^ prefeven [ i - 1 ] NEW_LINE prefodd [ i ] = prefodd [ i - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT prefeven [ i ] = prefeven [ i - 1 ] NEW_LINE prefodd [ i ] = prefodd [ i - 1 ] ^ arr [ i - 1 ] NEW_LINE DEDENT DEDENT i = 0 NEW_LINE while ( i != q ) : NEW_LINE INDENT ansQueries ( prefeven , prefodd , l [ i ] , r [ i ] ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE l = [ 1 , 1 , 2 ] NEW_LINE r = [ 2 , 3 , 4 ] NEW_LINE q = len ( l ) NEW_LINE wrapper ( arr , n , l , r , q ) NEW_LINE DEDENT
Variation in Nim Game | Function to return final grundy Number ( G ) of game ; if pile size is odd ; We XOR pile size + 1 ; if pile size is even ; We XOR pile size - 1 ; Game with 3 piles ; pile with different sizes ; Function to return result of game ; if ( res == 0 ) : if G is zero ; else : if G is non zero
def solve ( p , n ) : NEW_LINE INDENT G = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] % 2 != 0 ) : NEW_LINE INDENT G ^= ( p [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT G ^= ( p [ i ] - 1 ) NEW_LINE DEDENT DEDENT return G NEW_LINE DEDENT n = 3 NEW_LINE p = [ 32 , 49 , 58 ] NEW_LINE res = solve ( p , n ) NEW_LINE INDENT print ( " Player ▁ 2 ▁ wins " ) NEW_LINE print ( " Player ▁ 1 ▁ wins " ) NEW_LINE DEDENT
Maximum AND value of a pair in an array | Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Driver function
def checkBit ( pattern , arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( pattern & arr [ i ] ) == pattern ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def maxAND ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for bit in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT count = checkBit ( res | ( 1 << bit ) , arr , n ) NEW_LINE if ( count >= 2 ) : NEW_LINE INDENT res = res | ( 1 << bit ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 4 , 8 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ AND ▁ Value ▁ = ▁ " , maxAND ( arr , n ) ) NEW_LINE
Minimum flips to make all 1 s in left and 0 s in right | Set 1 ( Using Bitmask ) | Function to count minimum number of flips ; This is converting string s into integer of base 2 ( if s = '100' then num = 4 ) ; Initialize minXor with n that can be maximum number of flips ; Right shift 1 by ( n - 1 ) bits ; Calculate bitwise XOR of num and mask ; Math . min ( a , b ) returns minimum of a and b return minimum number of flips till that digit ; Function to count number of 1 s ; Driver code
def findMiniFlip ( nums ) : NEW_LINE INDENT n = len ( nums ) NEW_LINE s = ' ' NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += str ( nums [ i ] ) NEW_LINE DEDENT num = int ( s , 2 ) NEW_LINE minXor = n ; NEW_LINE mask = ( 1 << ( n - 1 ) ) NEW_LINE while ( n - 1 > 0 ) : NEW_LINE INDENT temp = ( num ^ mask ) NEW_LINE minXor = min ( minXor , countones ( temp ) ) NEW_LINE n -= 1 NEW_LINE mask = ( mask | ( 1 << n - 1 ) ) NEW_LINE DEDENT return minXor NEW_LINE DEDENT def countones ( n ) : NEW_LINE INDENT c = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE c += 1 NEW_LINE DEDENT return c NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT nums = [ 1 , 0 , 1 , 1 , 0 , 0 , 0 ] NEW_LINE n = findMiniFlip ( nums ) NEW_LINE print ( n ) NEW_LINE DEDENT
Check if a number is power of 8 or not | Python3 program to check if a number is power of 8 ; function to check if power of 8 ; calculate log8 ( n ) ; check if i is an integer or not ; Driver Code
from math import log , trunc NEW_LINE def checkPowerof8 ( n ) : NEW_LINE INDENT i = log ( n , 8 ) NEW_LINE return ( i - trunc ( i ) < 0.000001 ) ; NEW_LINE DEDENT n = 65 NEW_LINE if checkPowerof8 ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Find the n | utility function which is used to convert binary string into integer ; convert binary string into integer ; function to find nth binary palindrome number ; stores the binary palindrome string ; base case ; add 2 nd binary palindrome string ; runs till the nth binary palindrome number ; remove curr binary palindrome string from queue ; if n == 0 then we find the n 'th binary palindrome so we return our answer ; calculate length of curr binary palindrome string ; if length is even . so it is our first case we have two choices ; if length is odd . so it is our second case we have only one choice ; Driver code ; Function Call
def convertStringToInt ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans = ans * 2 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getNthNumber ( n ) : NEW_LINE INDENT q = [ ] NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT n = n - 1 NEW_LINE q . append ( "11" ) NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT curr = q . pop ( 0 ) NEW_LINE n -= 1 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return convertStringToInt ( curr ) NEW_LINE DEDENT lenn = len ( curr ) NEW_LINE if ( len ( curr ) % 2 == 0 ) : NEW_LINE INDENT q . append ( curr [ 0 : int ( lenn / 2 ) ] + "0" + curr [ int ( lenn / 2 ) : ] ) NEW_LINE q . append ( curr [ 0 : int ( lenn / 2 ) ] + "1" + curr [ int ( lenn / 2 ) : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT midChar = curr [ int ( lenn / 2 ) ] NEW_LINE q . append ( curr [ 0 : int ( lenn / 2 ) ] + midChar + curr [ int ( lenn / 2 ) : ] ) NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT n = 9 NEW_LINE print ( getNthNumber ( n ) ) NEW_LINE
Check if binary representation of a given number and its complement are anagram | An efficient Python3 program to check if binary representations of a number and it 's complement are anagram. ; Returns true if binary representations of a and b are anagram . ; _popcnt64 ( a ) gives number of 1 's present in binary representation of a. If number of 1s is half of total bits, return true. ; Driver Code
ULL_SIZE = 64 NEW_LINE def bit_anagram_check ( a ) : NEW_LINE INDENT return ( bin ( a ) . count ( "1" ) == ( ULL_SIZE >> 1 ) ) NEW_LINE DEDENT a = 4294967295 NEW_LINE print ( int ( bit_anagram_check ( a ) ) ) NEW_LINE
Sum of numbers with exactly 2 bits set | To calculate sum of numbers ; Find numbers whose 2 bits are set ; If number is greater then n we don 't include this in sum ; Return sum of numbers ; Driver Code
def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE i = 1 NEW_LINE while ( ( 1 << i ) < n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT num = ( 1 << i ) + ( 1 << j ) NEW_LINE if ( num <= n ) : NEW_LINE INDENT sum += num NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( findSum ( n ) ) NEW_LINE
Position of rightmost different bit | Python3 implementation to find the position of rightmost different bit in two number . ; Function to find rightmost different bit in two numbers . ; Driver code
from math import floor , log10 NEW_LINE def posOfRightMostDiffBit ( m , n ) : NEW_LINE INDENT return floor ( log10 ( pow ( m ^ n , 2 ) ) ) + 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m , n = 52 , 4 NEW_LINE print ( " Position ▁ = ▁ " , posOfRightMostDiffBit ( m , n ) ) NEW_LINE DEDENT
Set the K | function to set the kth bit ; kth bit of n is being set by this operation ; Driver code
def setKthBit ( n , k ) : NEW_LINE INDENT return ( ( 1 << k ) n ) NEW_LINE DEDENT n = 10 NEW_LINE k = 2 NEW_LINE print ( " Kth ▁ bit ▁ set ▁ number ▁ = ▁ " , setKthBit ( n , k ) ) NEW_LINE
Reverse an array without using subtract sign Γ’ β‚¬Λœ | Function to reverse array ; Trick to assign - 1 to a variable ; Reverse array in simple manner ; Swap ith index value with ( n - i - 1 ) th index value ; Driver code ; print the reversed array
def reverseArray ( arr , n ) : NEW_LINE INDENT import sys NEW_LINE x = - sys . maxsize // sys . maxsize NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT arr [ i ] , arr [ n + ( x * i ) + x ] = arr [ n + ( x * i ) + x ] , arr [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 7 , 2 , 1 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE reverseArray ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Reverse an array without using subtract sign Γ’ β‚¬Λœ | Function to reverse array ; Reverse array in simple manner ; Swap ith index value with ( n - i - 1 ) th index value Note : A - B = A + ~ B + 1 So n - i = n + ~ i + 1 then n - i - 1 = ( n + ~ i + 1 ) + ~ 1 + 1 ; Driver code ; print the reversed array
def reverseArray ( arr , n ) : NEW_LINE INDENT for i in range ( n // 2 ) : NEW_LINE INDENT arr [ i ] , arr [ ( n + ~ i + 1 ) + ~ 1 + 1 ] = arr [ ( n + ~ i + 1 ) + ~ 1 + 1 ] , arr [ i ] NEW_LINE DEDENT DEDENT arr = [ 5 , 3 , 7 , 2 , 1 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE reverseArray ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Maximum XOR value of a pair from a range | Method to get maximum xor value in range [ L , R ] ; get xor of limits ; loop to get msb position of L ^ R ; construct result by adding 1 , msbPos times ; Driver code
def maxXORInRange ( L , R ) : NEW_LINE INDENT LXR = L ^ R NEW_LINE msbPos = 0 NEW_LINE while ( LXR ) : NEW_LINE INDENT msbPos += 1 NEW_LINE LXR >>= 1 NEW_LINE DEDENT maxXOR , two = 0 , 1 NEW_LINE while ( msbPos ) : NEW_LINE INDENT maxXOR += two NEW_LINE two <<= 1 NEW_LINE msbPos -= 1 NEW_LINE DEDENT return maxXOR NEW_LINE DEDENT L , R = 8 , 20 NEW_LINE print ( maxXORInRange ( L , R ) ) NEW_LINE
Numbers whose bitwise OR and sum with N are equal | Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to N , whose bitwise OR and SUM with N are equal . ; count number of zero bit in N ; power of 2 to count ; Driver code
def CountZeroBit ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT if ( not ( n & 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def CountORandSumEqual ( N ) : NEW_LINE INDENT count = CountZeroBit ( N ) NEW_LINE return ( 1 << count ) NEW_LINE DEDENT N = 10 NEW_LINE print ( CountORandSumEqual ( N ) ) NEW_LINE
Count smaller numbers whose XOR with n produces greater value | Python program to count numbers whose XOR with n produces a value more than n . ; Position of current bit in n ; Traverse bits from LSB to MSB ; Initialize result ; If current bit is 0 , then there are 2 ^ k numbers with current bit 1 and whose XOR with n produces greater value ; Increase position for next bit ; Reduce n to find next bit ; Driver code
def countNumbers ( n ) : NEW_LINE INDENT k = 0 NEW_LINE count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( ( n & 1 ) == 0 ) : NEW_LINE INDENT count += pow ( 2 , k ) NEW_LINE DEDENT k += 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT n = 11 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE
Count all pairs with given XOR | Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty set that stores the visiting element of array . ; If there exist an element in set s with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with arr [ i ] is equal to x , then increment count . ; Make element visited ; return total count of pairs with XOR equal to x ; Driver Code
def xorPairCount ( arr , n , x ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( x ^ arr [ i ] in s ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT s . add ( arr [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 10 , 15 , 7 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE x = 5 NEW_LINE print ( " Count ▁ of ▁ pair ▁ with ▁ given ▁ XOR ▁ = ▁ " + str ( xorPairCount ( arr , n , x ) ) ) NEW_LINE DEDENT
Multiples of 4 ( An Interesting Method ) | Returns true if n is a multiple of 4. ; Find XOR of all numbers from 1 to n ; If XOR is equal n , then return true ; Printing multiples of 4 using above method
def isMultipleOf4 ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT XOR = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT XOR = XOR ^ i NEW_LINE DEDENT return ( XOR == n ) NEW_LINE DEDENT for n in range ( 0 , 43 ) : NEW_LINE INDENT if ( isMultipleOf4 ( n ) ) : NEW_LINE INDENT print ( n , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Check sum of Covered and Uncovered nodes of Binary Tree | To create a newNode of tree and return pointer ; Utility function to calculate sum of all node of tree ; Recursive function to calculate sum of left boundary elements ; If leaf node , then just return its key value ; If left is available then go left otherwise go right ; Recursive function to calculate sum of right boundary elements ; If leaf node , then just return its key value ; If right is available then go right otherwise go left ; Returns sum of uncovered elements ; Initializing with 0 in case we don 't have left or right boundary ; returning sum of root node , left boundary and right boundary ; Returns true if sum of covered and uncovered elements is same . ; Sum of uncovered elements ; Sum of all elements ; Check if sum of covered and uncovered is same ; Helper function to prinorder traversal of binary tree ; Driver Code ; Making above given diagram 's binary tree
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def Sum ( t ) : NEW_LINE INDENT if ( t == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return t . key + Sum ( t . left ) + Sum ( t . right ) NEW_LINE DEDENT def uncoveredSumLeft ( t ) : NEW_LINE INDENT if ( t . left == None and t . right == None ) : NEW_LINE INDENT return t . key NEW_LINE DEDENT if ( t . left != None ) : NEW_LINE INDENT return t . key + uncoveredSumLeft ( t . left ) NEW_LINE DEDENT else : NEW_LINE INDENT return t . key + uncoveredSumLeft ( t . right ) NEW_LINE DEDENT DEDENT def uncoveredSumRight ( t ) : NEW_LINE INDENT if ( t . left == None and t . right == None ) : NEW_LINE INDENT return t . key NEW_LINE DEDENT if ( t . right != None ) : NEW_LINE INDENT return t . key + uncoveredSumRight ( t . right ) NEW_LINE DEDENT else : NEW_LINE INDENT return t . key + uncoveredSumRight ( t . left ) NEW_LINE DEDENT DEDENT def uncoverSum ( t ) : NEW_LINE INDENT lb = 0 NEW_LINE rb = 0 NEW_LINE if ( t . left != None ) : NEW_LINE INDENT lb = uncoveredSumLeft ( t . left ) NEW_LINE DEDENT if ( t . right != None ) : NEW_LINE INDENT rb = uncoveredSumRight ( t . right ) NEW_LINE DEDENT return t . key + lb + rb NEW_LINE DEDENT def isSumSame ( root ) : NEW_LINE INDENT sumUC = uncoverSum ( root ) NEW_LINE sumT = Sum ( root ) NEW_LINE return ( sumUC == ( sumT - sumUC ) ) NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if ( root ) : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . key , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 8 ) NEW_LINE root . left = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 4 ) NEW_LINE root . left . right . right = newNode ( 7 ) NEW_LINE root . right = newNode ( 10 ) NEW_LINE root . right . right = newNode ( 14 ) NEW_LINE root . right . right . left = newNode ( 13 ) NEW_LINE if ( isSumSame ( root ) ) : NEW_LINE INDENT print ( " Sum ▁ of ▁ covered ▁ and ▁ uncovered ▁ is ▁ same " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Sum ▁ of ▁ covered ▁ and ▁ uncovered ▁ is ▁ not ▁ same " ) NEW_LINE DEDENT DEDENT
Check if a number is Bleak | An efficient Python 3 program to check Bleak Number ; Function to get no of set bits in binary representation of passed binary no . ; A function to return ceiling of log x in base 2. For example , it returns 3 for 8 and 4 for 9. ; Returns true if n is Bleak ; Check for all numbers ' x ' smaller than n . If x + countSetBits ( x ) becomes n , then n can 't be Bleak ; Driver code
import math NEW_LINE def countSetBits ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x ) : NEW_LINE INDENT x = x & ( x - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def ceilLog2 ( x ) : NEW_LINE INDENT count = 0 NEW_LINE x = x - 1 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT x = x >> 1 NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def isBleak ( n ) : NEW_LINE INDENT for x in range ( ( n - ceilLog2 ( n ) ) , n ) : NEW_LINE INDENT if ( x + countSetBits ( x ) == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if ( isBleak ( 3 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT if ( isBleak ( 4 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Count strings with consecutive 1 's | Returns count of n length binary strings with consecutive 1 's ; Count binary strings without consecutive 1 's. See the approach discussed on be ( http:goo.gl/p8A3sW ) ; Subtract a [ n - 1 ] + b [ n - 1 ] from 2 ^ n ; Driver code
def countStrings ( n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE b = [ 0 ] * n NEW_LINE a [ 0 ] = b [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] + b [ i - 1 ] NEW_LINE b [ i ] = a [ i - 1 ] NEW_LINE DEDENT return ( 1 << n ) - a [ n - 1 ] - b [ n - 1 ] NEW_LINE DEDENT print ( countStrings ( 5 ) ) NEW_LINE
How to swap two bits in a given integer ? | Python code for swapping given bits of a number ; left - shift 1 p1 and p2 times and using XOR ; Driver Code
def swapBits ( n , p1 , p2 ) : NEW_LINE INDENT n ^= 1 << p1 NEW_LINE n ^= 1 << p2 NEW_LINE return n NEW_LINE DEDENT print ( " Result ▁ = " , swapBits ( 28 , 0 , 3 ) ) NEW_LINE
Maximum length sub | Function to return the maximum length of the required sub - array ; To store the maximum length for a valid subarray ; To store the count of contiguous similar elements for previous group and the current group ; If current element is equal to the previous element then it is a part of the same group ; Else update the previous group and start counting elements for the new group ; Update the maximum possible length for a group ; Return the maximum length of the valid subarray ; Driver code
def maxLength ( a , n ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE prev_cnt = 0 ; curr_cnt = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] == a [ i - 1 ] ) : NEW_LINE INDENT curr_cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT prev_cnt = curr_cnt ; NEW_LINE curr_cnt = 1 ; NEW_LINE DEDENT maxLen = max ( maxLen , min ( prev_cnt , curr_cnt ) ) ; NEW_LINE DEDENT return ( 2 * maxLen ) ; NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 0 , 0 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxLength ( arr , n ) ) ; NEW_LINE
Traveling Salesman Problem using Branch And Bound | Python3 program to solve Traveling Salesman Problem using Branch and Bound . ; final_path [ ] stores the final solution i . e . the path of the salesman . ; visited [ ] keeps track of the already visited nodes in a particular path ; Stores the final minimum weight of shortest tour . ; Function to copy temporary solution to the final solution ; Function to find the minimum edge cost having an end at the vertex i ; function to find the second minimum edge cost having an end at the vertex i ; function that takes as arguments : curr_bound -> lower bound of the root node curr_weight -> stores the weight of the path so far level -> current level while moving in the search space tree curr_path [ ] -> where the solution is being stored which would later be copied to final_path [ ] ; base case is when we have reached level N which means we have covered all the nodes once ; check if there is an edge from last vertex in path back to the first vertex ; curr_res has the total weight of the solution we got ; Update final result and final path if current result is better . ; for any other level iterate for all vertices to build the search space tree recursively ; Consider next vertex if it is not same ( diagonal entry in adjacency matrix and not visited already ) ; different computation of curr_bound for level 2 from the other levels ; curr_bound + curr_weight is the actual lower bound for the node that we have arrived on . If current lower bound < final_res , we need to explore the node further ; call TSPRec for the next level ; Else we have to prune the node by resetting all changes to curr_weight and curr_bound ; Also reset the visited array ; This function sets up final_path ; Calculate initial lower bound for the root node using the formula 1 / 2 * ( sum of first min + second min ) for all edges . Also initialize the curr_path and visited array ; Compute initial bound ; Rounding off the lower bound to an integer ; We start at vertex 1 so the first vertex in curr_path [ ] is 0 ; Call to TSPRec for curr_weight equal to 0 and level 1 ; Adjacency matrix for the given graph
import math NEW_LINE maxsize = float ( ' inf ' ) NEW_LINE final_path = [ None ] * ( N + 1 ) NEW_LINE visited = [ False ] * N NEW_LINE final_res = maxsize NEW_LINE TSP ( adj ) NEW_LINE print ( " Minimum ▁ cost ▁ : " , final_res ) NEW_LINE print ( " Path ▁ Taken ▁ : ▁ " , end = ' ▁ ' ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT print ( final_path [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT def copyToFinal ( curr_path ) : NEW_LINE INDENT final_path [ : N + 1 ] = curr_path [ : ] NEW_LINE final_path [ N ] = curr_path [ 0 ] NEW_LINE DEDENT def firstMin ( adj , i ) : NEW_LINE INDENT min = maxsize NEW_LINE for k in range ( N ) : NEW_LINE INDENT if adj [ i ] [ k ] < min and i != k : NEW_LINE INDENT min = adj [ i ] [ k ] NEW_LINE DEDENT DEDENT return min NEW_LINE DEDENT def secondMin ( adj , i ) : NEW_LINE INDENT first , second = maxsize , maxsize NEW_LINE for j in range ( N ) : NEW_LINE INDENT if i == j : NEW_LINE INDENT continue NEW_LINE DEDENT if adj [ i ] [ j ] <= first : NEW_LINE INDENT second = first NEW_LINE first = adj [ i ] [ j ] NEW_LINE DEDENT elif ( adj [ i ] [ j ] <= second and adj [ i ] [ j ] != first ) : NEW_LINE INDENT second = adj [ i ] [ j ] NEW_LINE DEDENT DEDENT return second NEW_LINE DEDENT def TSPRec ( adj , curr_bound , curr_weight , level , curr_path , visited ) : NEW_LINE INDENT global final_res NEW_LINE if level == N : NEW_LINE INDENT if adj [ curr_path [ level - 1 ] ] [ curr_path [ 0 ] ] != 0 : NEW_LINE INDENT curr_res = curr_weight + adj [ curr_path [ level - 1 ] ] [ curr_path [ 0 ] ] NEW_LINE if curr_res < final_res : NEW_LINE INDENT copyToFinal ( curr_path ) NEW_LINE final_res = curr_res NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( adj [ curr_path [ level - 1 ] ] [ i ] != 0 and visited [ i ] == False ) : NEW_LINE INDENT temp = curr_bound NEW_LINE curr_weight += adj [ curr_path [ level - 1 ] ] [ i ] NEW_LINE if level == 1 : NEW_LINE INDENT curr_bound -= ( ( firstMin ( adj , curr_path [ level - 1 ] ) + firstMin ( adj , i ) ) / 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT curr_bound -= ( ( secondMin ( adj , curr_path [ level - 1 ] ) + firstMin ( adj , i ) ) / 2 ) NEW_LINE DEDENT if curr_bound + curr_weight < final_res : NEW_LINE INDENT curr_path [ level ] = i NEW_LINE visited [ i ] = True NEW_LINE TSPRec ( adj , curr_bound , curr_weight , level + 1 , curr_path , visited ) NEW_LINE DEDENT curr_weight -= adj [ curr_path [ level - 1 ] ] [ i ] NEW_LINE curr_bound = temp NEW_LINE visited = [ False ] * len ( visited ) NEW_LINE for j in range ( level ) : NEW_LINE INDENT if curr_path [ j ] != - 1 : NEW_LINE INDENT visited [ curr_path [ j ] ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def TSP ( adj ) : NEW_LINE INDENT curr_bound = 0 NEW_LINE curr_path = [ - 1 ] * ( N + 1 ) NEW_LINE visited = [ False ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr_bound += ( firstMin ( adj , i ) + secondMin ( adj , i ) ) NEW_LINE DEDENT curr_bound = math . ceil ( curr_bound / 2 ) NEW_LINE visited [ 0 ] = True NEW_LINE curr_path [ 0 ] = 0 NEW_LINE TSPRec ( adj , curr_bound , 0 , 1 , curr_path , visited ) NEW_LINE DEDENT adj = [ [ 0 , 10 , 15 , 20 ] , [ 10 , 0 , 35 , 25 ] , [ 15 , 35 , 0 , 30 ] , [ 20 , 25 , 30 , 0 ] ] NEW_LINE N = 4 NEW_LINE
Check if two nodes are cousins in a Binary Tree | A Binary Tree Node ; Recursive function to check if two Nodes are siblings ; Base Case ; Recursive function to find level of Node ' ptr ' in a binary tree ; Base Case ; Return level if Node is present in left subtree ; Else search in right subtree ; Returns 1 if a and b are cousins , otherwise 0 ; 1. The two nodes should be on the same level in the binary tree The two nodes should not be siblings ( means that they should not have the smae parent node ; 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 isSibling ( root , a , b ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( ( root . left == a and root . right == b ) or ( root . left == b and root . right == a ) or isSibling ( root . left , a , b ) or isSibling ( root . right , a , b ) ) NEW_LINE DEDENT def level ( root , ptr , lev ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root == ptr : NEW_LINE INDENT return lev NEW_LINE DEDENT l = level ( root . left , ptr , lev + 1 ) NEW_LINE if l != 0 : NEW_LINE INDENT return l NEW_LINE DEDENT return level ( root . right , ptr , lev + 1 ) NEW_LINE DEDENT def isCousin ( root , a , b ) : NEW_LINE INDENT if ( ( level ( root , a , 1 ) == level ( root , b , 1 ) ) and not ( isSibling ( root , a , b ) ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 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 root . left . right . right = Node ( 15 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . left . right = Node ( 8 ) NEW_LINE node1 = root . left . right NEW_LINE node2 = root . right . right NEW_LINE print " Yes " if isCousin ( root , node1 , node2 ) == 1 else " No " NEW_LINE
Check if all leaves are at same level | A binary tree node ; Recursive function which check whether all leaves are at same level ; Base Case ; If a tree node is encountered ; When a leaf node is found first time ; Set first leaf found ; If this is not first leaf node , compare its level with first leaf 's level ; If this is not first leaf node , compare its level with first leaf 's level ; The main function to check if all leafs are at same level . It mainly uses checkUtil ( ) ; Let us create the tree as shown in the example
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 checkUtil ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT if check . leafLevel == 0 : NEW_LINE INDENT check . leafLevel = level NEW_LINE return True NEW_LINE DEDENT return level == check . leafLevel NEW_LINE DEDENT return ( checkUtil ( root . left , level + 1 ) and checkUtil ( root . right , level + 1 ) ) NEW_LINE DEDENT def check ( root ) : NEW_LINE INDENT level = 0 NEW_LINE check . leafLevel = 0 NEW_LINE return ( checkUtil ( root , level ) ) NEW_LINE DEDENT root = Node ( 12 ) NEW_LINE root . left = Node ( 5 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . left . right = Node ( 9 ) NEW_LINE root . left . left . left = Node ( 1 ) NEW_LINE root . left . right . left = Node ( 2 ) NEW_LINE if ( check ( root ) ) : NEW_LINE INDENT print " Leaves ▁ are ▁ at ▁ same ▁ level " NEW_LINE DEDENT else : NEW_LINE INDENT print " Leaves ▁ are ▁ not ▁ at ▁ same ▁ level " NEW_LINE DEDENT
Number of siblings of a given Node in n | Python3 program to find number of siblings of a given node ; Represents a node of an n - ary tree ; Function to calculate number of siblings of a given node ; Creating a queue and pushing the root ; Dequeue an item from queue and check if it is equal to x If YES , then return number of children ; Enqueue all children of the dequeued item ; If the value of children is equal to x , then return the number of siblings ; Driver Code ; Creating a generic tree as shown in above figure ; Node whose number of siblings is to be calculated ; Function calling
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . child = [ ] NEW_LINE self . key = data NEW_LINE DEDENT DEDENT def numberOfSiblings ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT p = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE for i in range ( len ( p . child ) ) : NEW_LINE INDENT if ( p . child [ i ] . key == x ) : NEW_LINE INDENT return len ( p . child ) - 1 NEW_LINE DEDENT q . put ( p . child [ i ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 50 ) NEW_LINE ( root . child ) . append ( newNode ( 2 ) ) NEW_LINE ( root . child ) . append ( newNode ( 30 ) ) NEW_LINE ( root . child ) . append ( newNode ( 14 ) ) NEW_LINE ( root . child ) . append ( newNode ( 60 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 15 ) ) NEW_LINE ( root . child [ 0 ] . child ) . append ( newNode ( 25 ) ) NEW_LINE ( root . child [ 0 ] . child [ 1 ] . child ) . append ( newNode ( 70 ) ) NEW_LINE ( root . child [ 0 ] . child [ 1 ] . child ) . append ( newNode ( 100 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 6 ) ) NEW_LINE ( root . child [ 1 ] . child ) . append ( newNode ( 1 ) ) NEW_LINE ( root . child [ 2 ] . child ) . append ( newNode ( 7 ) ) NEW_LINE ( root . child [ 2 ] . child [ 0 ] . child ) . append ( newNode ( 17 ) ) NEW_LINE ( root . child [ 2 ] . child [ 0 ] . child ) . append ( newNode ( 99 ) ) NEW_LINE ( root . child [ 2 ] . child [ 0 ] . child ) . append ( newNode ( 27 ) ) NEW_LINE ( root . child [ 3 ] . child ) . append ( newNode ( 16 ) ) NEW_LINE x = 100 NEW_LINE print ( numberOfSiblings ( root , x ) ) NEW_LINE DEDENT
Check if all leaves are at same level | Python3 program to check if all leaf nodes are at same level of binary tree ; Tree Node returns a new tree Node ; return true if all leaf nodes are at same level , else false ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; check for left child ; if its leaf node ; if it 's first leaf node, then update result ; if it 's not first leaf node, then compare the level with level of previous leaf node ; check for right child ; if it 's leaf node ; if it 's first leaf node till now, then update the result ; if it is not the first leaf node , then compare the level with level of previous leaf node ; Driver Code ; construct a tree
INT_MAX = 2 ** 31 NEW_LINE INT_MIN = - 2 ** 31 NEW_LINE 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 checkLevelLeafNode ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE result = INT_MAX NEW_LINE level = 0 NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT size = len ( q ) NEW_LINE level += 1 NEW_LINE while ( size > 0 or len ( q ) ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( temp . left ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE if ( not temp . left . right and not temp . left . left ) : NEW_LINE INDENT if ( result == INT_MAX ) : NEW_LINE INDENT result = level NEW_LINE DEDENT elif ( result != level ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE if ( not temp . right . left and not temp . right . right ) : NEW_LINE INDENT if ( result == INT_MAX ) : NEW_LINE INDENT result = level NEW_LINE DEDENT elif ( result != level ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT size -= 1 NEW_LINE DEDENT DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE result = checkLevelLeafNode ( root ) NEW_LINE if ( result ) : NEW_LINE INDENT print ( " All ▁ leaf ▁ nodes ▁ are ▁ at ▁ same ▁ level " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Leaf ▁ nodes ▁ not ▁ at ▁ same ▁ level " ) NEW_LINE DEDENT DEDENT
Sorting a Queue without extra space | Python3 program to implement sorting a queue data structure ; Queue elements after sortedIndex are already sorted . This function returns index of minimum element from front to sortedIndex ; This is dequeue ( ) in C ++ STL ; we add the condition i <= sortedIndex because we don 't want to traverse on the sorted part of the queue, which is the right part. ; This is enqueue ( ) in C ++ STL ; Moves given minimum element to rear of queue ; SortQueue Function ; Driver code ; Sort queue ; Prsorted queue
from queue import Queue NEW_LINE def minIndex ( q , sortedIndex ) : NEW_LINE INDENT min_index = - 1 NEW_LINE min_val = 999999999999 NEW_LINE n = q . qsize ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( curr <= min_val and i <= sortedIndex ) : NEW_LINE INDENT min_index = i NEW_LINE min_val = curr NEW_LINE DEDENT q . put ( curr ) NEW_LINE DEDENT return min_index NEW_LINE DEDENT def insertMinToRear ( q , min_index ) : NEW_LINE INDENT min_val = None NEW_LINE n = q . qsize ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( i != min_index ) : NEW_LINE INDENT q . put ( curr ) NEW_LINE DEDENT else : NEW_LINE INDENT min_val = curr NEW_LINE DEDENT DEDENT q . put ( min_val ) NEW_LINE DEDENT def sortQueue ( q ) : NEW_LINE INDENT for i in range ( 1 , q . qsize ( ) + 1 ) : NEW_LINE INDENT min_index = minIndex ( q , q . qsize ( ) - i ) NEW_LINE insertMinToRear ( q , min_index ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT q = Queue ( ) NEW_LINE q . put ( 30 ) NEW_LINE q . put ( 11 ) NEW_LINE q . put ( 15 ) NEW_LINE q . put ( 4 ) NEW_LINE sortQueue ( q ) NEW_LINE while ( q . empty ( ) == False ) : NEW_LINE INDENT print ( q . queue [ 0 ] , end = " ▁ " ) NEW_LINE q . get ( ) NEW_LINE DEDENT DEDENT
Check if removing an edge can divide a Binary Tree in two halves | Python3 program to check if there exist an edge whose removal creates two trees of same size utility function to create a new node ; To calculate size of tree with given root ; This function returns true if there is an edge whose removal can divide the tree in two halves n is size of tree ; Base cases ; Check for root ; Check for rest of the nodes ; This function mainly uses checkRec ( ) ; Count total nodes in given tree ; Now recursively check all nodes ; Driver code
class newNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def count ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( count ( root . left ) + count ( root . right ) + 1 ) NEW_LINE DEDENT def checkRec ( root , n ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( count ( root ) == n - count ( root ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return ( checkRec ( root . left , n ) or checkRec ( root . right , n ) ) NEW_LINE DEDENT def check ( root ) : NEW_LINE INDENT n = count ( root ) NEW_LINE return checkRec ( root , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 5 ) NEW_LINE root . left = newNode ( 1 ) NEW_LINE root . right = newNode ( 6 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 4 ) NEW_LINE if check ( root ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Sliding Window Maximum ( Maximum of all subarrays of size k ) | Python program to find the maximum for each and every contiguous subarray of size k ; A Deque ( Double ended queue ) based method for printing maximum element of all subarrays of size k ; Create a Double Ended Queue , Qi that will store indexes of array elements . The queue will store indexes of useful elements in every window and it will maintain decreasing order of values from front to rear in Qi , i . e . , arr [ Qi . front [ ] ] to arr [ Qi . rear ( ) ] are sorted in decreasing order ; Process first k ( or first window ) elements of array ; For every element , the previous smaller elements are useless so remove them from Qi ; Remove from rear ; Add new element at rear of queue ; Process rest of the elements , i . e . from arr [ k ] to arr [ n - 1 ] ; The element at the front of the queue is the largest element of previous window , so print it ; Remove the elements which are out of this window ; remove from front of deque ; Remove all elements smaller than the currently being added element ( Remove useless elements ) ; Add current element at the rear of Qi ; Print the maximum element of last window ; Driver code
from collections import deque NEW_LINE def printMax ( arr , n , k ) : NEW_LINE INDENT Qi = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT while Qi and arr [ i ] >= arr [ Qi [ - 1 ] ] : NEW_LINE INDENT Qi . pop ( ) NEW_LINE DEDENT Qi . append ( i ) ; NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT print ( str ( arr [ Qi [ 0 ] ] ) + " ▁ " , end = " " ) NEW_LINE while Qi and Qi [ 0 ] <= i - k : NEW_LINE INDENT Qi . popleft ( ) NEW_LINE DEDENT while Qi and arr [ i ] >= arr [ Qi [ - 1 ] ] : NEW_LINE INDENT Qi . pop ( ) NEW_LINE DEDENT Qi . append ( i ) NEW_LINE DEDENT print ( str ( arr [ Qi [ 0 ] ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 1 , 78 , 90 , 57 , 89 , 56 ] NEW_LINE k = 3 NEW_LINE printMax ( arr , len ( arr ) , k ) NEW_LINE DEDENT
Sum of minimum and maximum elements of all subarrays of size k . | Python3 program to find Sum of all minimum and maximum elements Of Sub - array Size k . ; Returns Sum of min and max element of all subarrays of size k ; Initialize result ; The queue will store indexes of useful elements in every window In deque ' G ' we maintain decreasing order of values from front to rear In deque ' S ' we maintain increasing order of values from front to rear ; Process first window of size K ; Remove all previous greater elements that are useless . ; Remove from rear ; Remove all previous smaller that are elements are useless . ; Remove from rear ; Add current element at rear of both deque ; Process rest of the Array elements ; Element at the front of the deque ' G ' & ' S ' is the largest and smallest element of previous window respectively ; Remove all elements which are out of this window ; remove all previous greater element that are useless ; Remove from rear ; remove all previous smaller that are elements are useless ; Remove from rear ; Add current element at rear of both deque ; Sum of minimum and maximum element of last window ; Driver program to test above functions
from collections import deque NEW_LINE def SumOfKsubArray ( arr , n , k ) : NEW_LINE INDENT Sum = 0 NEW_LINE S = deque ( ) NEW_LINE G = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT while ( len ( S ) > 0 and arr [ S [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT S . pop ( ) NEW_LINE DEDENT while ( len ( G ) > 0 and arr [ G [ - 1 ] ] <= arr [ i ] ) : NEW_LINE INDENT G . pop ( ) NEW_LINE DEDENT G . append ( i ) NEW_LINE S . append ( i ) NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT Sum += arr [ S [ 0 ] ] + arr [ G [ 0 ] ] NEW_LINE while ( len ( S ) > 0 and S [ 0 ] <= i - k ) : NEW_LINE INDENT S . popleft ( ) NEW_LINE DEDENT while ( len ( G ) > 0 and G [ 0 ] <= i - k ) : NEW_LINE INDENT G . popleft ( ) NEW_LINE DEDENT while ( len ( S ) > 0 and arr [ S [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT S . pop ( ) NEW_LINE DEDENT while ( len ( G ) > 0 and arr [ G [ - 1 ] ] <= arr [ i ] ) : NEW_LINE INDENT G . pop ( ) NEW_LINE DEDENT G . append ( i ) NEW_LINE S . append ( i ) NEW_LINE DEDENT Sum += arr [ S [ 0 ] ] + arr [ G [ 0 ] ] NEW_LINE return Sum NEW_LINE DEDENT arr = [ 2 , 5 , - 1 , 7 , - 3 , - 1 , - 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( SumOfKsubArray ( arr , n , k ) ) NEW_LINE
Check if removing an edge can divide a Binary Tree in two halves | Python3 program to check if there exist an edge whose removal creates two trees of same size ; To calculate size of tree with given root ; This function returns size of tree rooted with given root . It also set " res " as true if there is an edge whose removal divides tree in two halves . n is size of tree ; Base case ; Compute sizes of left and right children ; If required property is true for current node set " res " as true ; Return size ; This function mainly uses checkRec ( ) ; Count total nodes in given tree ; Initialize result and recursively check all nodes bool res = false ; ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def count ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( count ( node . left ) + count ( node . right ) + 1 ) NEW_LINE DEDENT def checkRec ( root , n ) : NEW_LINE INDENT global res NEW_LINE if ( root == None ) : NEW_LINE return 0 NEW_LINE c = ( checkRec ( root . left , n ) + 1 + checkRec ( root . right , n ) ) NEW_LINE if ( c == n - c ) : NEW_LINE INDENT res = True NEW_LINE DEDENT return c NEW_LINE DEDENT def check ( root ) : NEW_LINE INDENT n = count ( root ) NEW_LINE checkRec ( root , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT res = False NEW_LINE root = Node ( 5 ) NEW_LINE root . left = Node ( 1 ) NEW_LINE root . right = Node ( 6 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . right . left = Node ( 7 ) NEW_LINE root . right . right = Node ( 4 ) NEW_LINE check ( root ) NEW_LINE if res : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT
Distance of nearest cell having 1 in a binary matrix | Prthe distance of nearest cell having 1 for each cell . ; Initialize the answer matrix with INT_MAX . ; For each cell ; Traversing the whole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driver Code
def printDistance ( mat ) : NEW_LINE INDENT global N , M NEW_LINE ans = [ [ None ] * M for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT ans [ i ] [ j ] = 999999999999 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT for k in range ( N ) : NEW_LINE INDENT for l in range ( M ) : NEW_LINE INDENT if ( mat [ k ] [ l ] == 1 ) : NEW_LINE INDENT ans [ i ] [ j ] = min ( ans [ i ] [ j ] , abs ( i - k ) + abs ( j - l ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( ans [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 3 NEW_LINE M = 4 NEW_LINE mat = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 0 , 1 , 1 ] , [ 0 , 1 , 1 , 0 ] ] NEW_LINE printDistance ( mat ) NEW_LINE
Distance of nearest cell having 1 in a binary matrix | Python3 program to find distance of nearest cell having 1 in a binary matrix . ; Making a class of graph with bfs function . ; Function to create graph with N * M nodes considering each cell as a node and each boundary as an edge . ; A number to be assigned to a cell ; If last row , then add edge on right side . ; If not bottom right cell . ; If last column , then add edge toward down . ; Else makes an edge in all four directions . ; BFS function to find minimum distance ; Printing the solution . ; Find minimum distance ; Creating a graph with nodes values assigned from 1 to N x M and matrix adjacent . ; To store minimum distance ; To mark each node as visited or not in BFS ; Initialising the value of distance and visit . ; Inserting nodes whose value in matrix is 1 in the queue . ; Calling for Bfs with given Queue . ; Printing the solution . ; Driver code
from collections import deque NEW_LINE MAX = 500 NEW_LINE N = 3 NEW_LINE M = 4 NEW_LINE g = [ [ ] for i in range ( MAX ) ] NEW_LINE n , m = 0 , 0 NEW_LINE def createGraph ( ) : NEW_LINE INDENT global g , n , m NEW_LINE k = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( i == n ) : NEW_LINE INDENT if ( j != m ) : NEW_LINE INDENT g [ k ] . append ( k + 1 ) NEW_LINE g [ k + 1 ] . append ( k ) NEW_LINE DEDENT DEDENT elif ( j == m ) : NEW_LINE INDENT g [ k ] . append ( k + m ) NEW_LINE g [ k + m ] . append ( k ) NEW_LINE DEDENT else : NEW_LINE INDENT g [ k ] . append ( k + 1 ) NEW_LINE g [ k + 1 ] . append ( k ) NEW_LINE g [ k ] . append ( k + m ) NEW_LINE g [ k + m ] . append ( k ) NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT DEDENT def bfs ( visit , dist , q ) : NEW_LINE INDENT global g NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT temp = q . popleft ( ) NEW_LINE for i in g [ temp ] : NEW_LINE INDENT if ( visit [ i ] != 1 ) : NEW_LINE INDENT dist [ i ] = min ( dist [ i ] , dist [ temp ] + 1 ) NEW_LINE q . append ( i ) NEW_LINE visit [ i ] = 1 NEW_LINE DEDENT DEDENT DEDENT return dist NEW_LINE DEDENT def prt ( dist ) : NEW_LINE INDENT c = 1 NEW_LINE for i in range ( 1 , n * m + 1 ) : NEW_LINE INDENT print ( dist [ i ] , end = " ▁ " ) NEW_LINE if ( c % m == 0 ) : NEW_LINE INDENT print ( ) NEW_LINE DEDENT c += 1 NEW_LINE DEDENT DEDENT def findMinDistance ( mat ) : NEW_LINE INDENT global g , n , m NEW_LINE n , m = N , M NEW_LINE createGraph ( ) NEW_LINE dist = [ 0 ] * MAX NEW_LINE visit = [ 0 ] * MAX NEW_LINE for i in range ( 1 , M * N + 1 ) : NEW_LINE INDENT dist [ i ] = 10 ** 9 NEW_LINE visit [ i ] = 0 NEW_LINE DEDENT k = 1 NEW_LINE q = deque ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == 1 ) : NEW_LINE INDENT dist [ k ] = 0 NEW_LINE visit [ k ] = 1 NEW_LINE q . append ( k ) NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT dist = bfs ( visit , dist , q ) NEW_LINE prt ( dist ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 0 , 0 , 1 ] , [ 0 , 0 , 1 , 1 ] , [ 0 , 1 , 1 , 0 ] ] NEW_LINE findMinDistance ( mat ) NEW_LINE DEDENT
First negative integer in every window of size k | Function to find the first negative integer in every window of size k ; Loop for each subarray ( window ) of size k ; Traverse through the current window ; If a negative integer is found , then it is the first negative integer for current window . Print it , set the flag and break ; If the current window does not contain a negative integer ; Driver Code
def printFirstNegativeInteger ( arr , n , k ) : NEW_LINE INDENT for i in range ( 0 , ( n - k + 1 ) ) : NEW_LINE INDENT flag = False NEW_LINE for j in range ( 0 , k ) : NEW_LINE INDENT if ( arr [ i + j ] < 0 ) : NEW_LINE INDENT print ( arr [ i + j ] , end = " ▁ " ) NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( not ( flag ) ) : NEW_LINE INDENT print ( "0" , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE printFirstNegativeInteger ( arr , n , k ) NEW_LINE
First negative integer in every window of size k | Python3 implementation to find the first negative integer in every window of size k import deque ( ) from collections ; function to find the first negative integer in every window of size k ; A Double Ended Queue , Di that will store indexes of useful array elements for the current window of size k . The useful elements are all negative integers . ; Process first k ( or first window ) elements of array ; Add current element at the rear of Di if it is a negative integer ; Process rest of the elements , i . e . , from arr [ k ] to arr [ n - 1 ] ; if the window does not have a negative integer ; if Di is not empty then the element at the front of the queue is the first negative integer of the previous window ; Remove the elements which are out of this window ; Remove from front of queue ; Add current element at the rear of Di if it is a negative integer ; Print the first negative integer of last window ; Driver Code
from collections import deque NEW_LINE def printFirstNegativeInteger ( arr , n , k ) : NEW_LINE INDENT Di = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT Di . append ( i ) ; NEW_LINE DEDENT DEDENT for i in range ( k , n ) : NEW_LINE INDENT if ( not Di ) : NEW_LINE INDENT print ( 0 , end = ' ▁ ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ Di [ 0 ] ] , end = ' ▁ ' ) ; NEW_LINE DEDENT while Di and Di [ 0 ] <= ( i - k ) : NEW_LINE INDENT Di . popleft ( ) NEW_LINE DEDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT Di . append ( i ) ; NEW_LINE DEDENT DEDENT if not Di : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ Di [ 0 ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE printFirstNegativeInteger ( arr , n , k ) ; NEW_LINE DEDENT
First negative integer in every window of size k | Python3 code for First negative integer in every window of size k ; skip out of window and positive elements ; check if a negative element is found , otherwise use 0 ; Driver code
def printFirstNegativeInteger ( arr , k ) : NEW_LINE INDENT firstNegativeIndex = 0 NEW_LINE for i in range ( k - 1 , len ( arr ) ) : NEW_LINE INDENT while firstNegativeIndex < i and ( firstNegativeIndex <= i - k or arr [ firstNegativeIndex ] > 0 ) : NEW_LINE INDENT firstNegativeIndex += 1 NEW_LINE DEDENT firstNegativeElement = arr [ firstNegativeIndex ] if arr [ firstNegativeIndex ] < 0 else 0 NEW_LINE print ( firstNegativeElement , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , - 1 , - 7 , 8 , - 15 , 30 , 16 , 28 ] NEW_LINE k = 3 NEW_LINE printFirstNegativeInteger ( arr , k ) NEW_LINE DEDENT
Check if all levels of two trees are anagrams or not | Returns true if trees with root1 and root2 are level by level anagram , else returns false . ; Base Cases ; start level order traversal of two trees using two queues . ; n1 ( queue size ) indicates number of Nodes at current level in first tree and n2 indicates number of nodes in current level of second tree . ; If n1 and n2 are different ; If level order traversal is over ; Dequeue all Nodes of current level and Enqueue all Nodes of next level ; Check if nodes of current levels are anagrams or not . ; Utility function to create a new tree Node ; Driver Code ; Constructing both the trees .
def areAnagrams ( root1 , root2 ) : NEW_LINE INDENT if ( root1 == None and root2 == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root1 == None or root2 == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT q1 = [ ] NEW_LINE q2 = [ ] NEW_LINE q1 . append ( root1 ) NEW_LINE q2 . append ( root2 ) NEW_LINE while ( 1 ) : NEW_LINE INDENT n1 = len ( q1 ) NEW_LINE n2 = len ( q2 ) NEW_LINE if ( n1 != n2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n1 == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT curr_level1 = [ ] NEW_LINE curr_level2 = [ ] NEW_LINE while ( n1 > 0 ) : NEW_LINE INDENT node1 = q1 [ 0 ] NEW_LINE q1 . pop ( 0 ) NEW_LINE if ( node1 . left != None ) : NEW_LINE INDENT q1 . append ( node1 . left ) NEW_LINE DEDENT if ( node1 . right != None ) : NEW_LINE INDENT q1 . append ( node1 . right ) NEW_LINE DEDENT n1 -= 1 NEW_LINE node2 = q2 [ 0 ] NEW_LINE q2 . pop ( 0 ) NEW_LINE if ( node2 . left != None ) : NEW_LINE INDENT q2 . append ( node2 . left ) NEW_LINE DEDENT if ( node2 . right != None ) : NEW_LINE INDENT q2 . append ( node2 . right ) NEW_LINE DEDENT curr_level1 . append ( node1 . data ) NEW_LINE curr_level2 . append ( node2 . data ) NEW_LINE DEDENT curr_level1 . sort ( ) NEW_LINE curr_level2 . sort ( ) NEW_LINE if ( curr_level1 != curr_level2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT 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 if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 1 ) NEW_LINE root1 . left = newNode ( 3 ) NEW_LINE root1 . right = newNode ( 2 ) NEW_LINE root1 . right . left = newNode ( 5 ) NEW_LINE root1 . right . right = newNode ( 4 ) NEW_LINE root2 = newNode ( 1 ) NEW_LINE root2 . left = newNode ( 2 ) NEW_LINE root2 . right = newNode ( 3 ) NEW_LINE root2 . left . left = newNode ( 4 ) NEW_LINE root2 . left . right = newNode ( 5 ) NEW_LINE if areAnagrams ( root1 , root2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if given Preorder , Inorder and Postorder traversals are of same tree | Python3 program to check if all three given traversals are of the same tree ; A Binary Tree Node ; Function to find index of value in arr [ start ... end ] . The function assumes that value is present in in ; Recursive function to construct binary tree of size lenn from Inorder traversal in and Preorder traversal pre [ ] . Initial values of inStrt and inEnd should be 0 and lenn - 1. The function doesn 't do any error checking for cases where inorder and preorder do not form a tree ; Pick current node from Preorder traversal using preIndex and increment preIndex ; If this node has no children then return ; Else find the index of this node in Inorder traversal ; Using index in Inorder traversal , construct left and right subtress ; function to compare Postorder traversal on constructed tree and given Postorder ; first recur on left child ; now recur on right child ; Compare if data at current index in both Postorder traversals are same ; Driver code ; build tree from given Inorder and Preorder traversals ; compare postorder traversal on constructed tree with given Postorder traversal ; If both postorder traversals are same
preIndex = 0 NEW_LINE class node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def search ( arr , strt , end , value ) : NEW_LINE INDENT for i in range ( strt , end + 1 ) : NEW_LINE INDENT if ( arr [ i ] == value ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT def buildTree ( inn , pre , inStrt , inEnd ) : NEW_LINE INDENT global preIndex NEW_LINE if ( inStrt > inEnd ) : NEW_LINE INDENT return None NEW_LINE DEDENT tNode = node ( pre [ preIndex ] ) NEW_LINE preIndex += 1 NEW_LINE if ( inStrt == inEnd ) : NEW_LINE INDENT return tNode NEW_LINE DEDENT inIndex = search ( inn , inStrt , inEnd , tNode . data ) NEW_LINE tNode . left = buildTree ( inn , pre , inStrt , inIndex - 1 ) NEW_LINE tNode . right = buildTree ( inn , pre , inIndex + 1 , inEnd ) NEW_LINE return tNode NEW_LINE DEDENT def checkPostorder ( node , postOrder , index ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return index NEW_LINE DEDENT index = checkPostorder ( node . left , postOrder , index ) NEW_LINE index = checkPostorder ( node . right , postOrder , index ) NEW_LINE if ( node . data == postOrder [ index ] ) : NEW_LINE INDENT index += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return index NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT inOrder = [ 4 , 2 , 5 , 1 , 3 ] NEW_LINE preOrder = [ 1 , 2 , 4 , 5 , 3 ] NEW_LINE postOrder = [ 4 , 5 , 2 , 3 , 1 ] NEW_LINE lenn = len ( inOrder ) NEW_LINE root = buildTree ( inOrder , preOrder , 0 , lenn - 1 ) NEW_LINE index = checkPostorder ( root , postOrder , 0 ) NEW_LINE if ( index == lenn ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if X can give change to every person in the Queue | Function to check if every person will get the change from X ; To count the 5 $ and 10 & notes ; Serve the customer in order ; Increase the number of 5 $ note by one ; decrease the number of note 5 $ and increase 10 $ note by one ; decrease 5 $ and 10 $ note by one ; decrease 5 $ note by three ; queue of customers with available notes . ; Calling function
def isChangeable ( notes , n ) : NEW_LINE INDENT fiveCount = 0 NEW_LINE tenCount = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( notes [ i ] == 5 ) : NEW_LINE INDENT fiveCount += 1 NEW_LINE DEDENT elif ( notes [ i ] == 10 ) : NEW_LINE INDENT if ( fiveCount > 0 ) : NEW_LINE INDENT fiveCount -= 1 NEW_LINE tenCount += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( fiveCount > 0 and tenCount > 0 ) : NEW_LINE INDENT fiveCount -= 1 NEW_LINE tenCount -= 1 NEW_LINE DEDENT elif ( fiveCount >= 3 ) : NEW_LINE INDENT fiveCount -= 3 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT return 1 NEW_LINE DEDENT a = [ 5 , 5 , 5 , 10 , 20 ] NEW_LINE n = len ( a ) NEW_LINE if ( isChangeable ( a , n ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT
Index Mapping ( or Trivial Hashing ) with negatives allowed | Python3 program to implement direct index mapping with negative values allowed . ; Since array is global , it is initialized as 0. ; Searching if X is Present in the given array or not . ; if X is negative take the absolute value of X . ; Driver code ; Since array is global , it is initialized as 0.
MAX = 1000 NEW_LINE has = [ [ 0 for i in range ( 2 ) ] for j in range ( MAX + 1 ) ] NEW_LINE def search ( X ) : NEW_LINE INDENT if X >= 0 : NEW_LINE INDENT return has [ X ] [ 0 ] == 1 NEW_LINE DEDENT X = abs ( X ) NEW_LINE return has [ X ] [ 1 ] == 1 NEW_LINE DEDENT def insert ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if a [ i ] >= 0 : NEW_LINE INDENT has [ a [ i ] ] [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT has [ abs ( a [ i ] ) ] [ 1 ] = 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ - 1 , 9 , - 5 , - 8 , - 5 , - 2 ] NEW_LINE n = len ( a ) NEW_LINE insert ( a , n ) NEW_LINE X = - 5 NEW_LINE if search ( X ) == True : NEW_LINE INDENT print ( " Present " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Present " ) NEW_LINE DEDENT DEDENT
Given level order traversal of a Binary Tree , check if the Tree is a Min | Returns true if given level order traversal is Min Heap . ; First non leaf node is at index ( n / 2 - 1 ) . Check whether each parent is greater than child ; Left child will be at index 2 * i + 1 Right child will be at index 2 * i + 2 ; If parent is greater than right child ; Driver code
def isMinHeap ( level , n ) : NEW_LINE INDENT for i in range ( int ( n / 2 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if level [ i ] > level [ 2 * i + 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT if 2 * i + 2 < n : NEW_LINE INDENT if level [ i ] > level [ 2 * i + 2 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT level = [ 10 , 15 , 14 , 25 , 30 ] NEW_LINE n = len ( level ) NEW_LINE if isMinHeap ( level , n ) : NEW_LINE INDENT print ( " True " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) NEW_LINE DEDENT DEDENT
Minimum delete operations to make all elements of array same | Function to get minimum number of elements to be deleted from array to make array elements equal ; Create an dictionary and store frequencies of all array elements in it using element as key and frequency as value ; Find maximum frequency among all frequencies . ; To minimize delete operations , we remove all elements but the most frequent element . ; Driver code
def minDelete ( arr , n ) : NEW_LINE INDENT freq = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in freq : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ i ] ] = 1 ; NEW_LINE DEDENT DEDENT max_freq = 0 ; NEW_LINE for i , j in freq . items ( ) : NEW_LINE INDENT max_freq = max ( max_freq , j ) ; NEW_LINE DEDENT return n - max_freq ; NEW_LINE DEDENT arr = [ 4 , 3 , 4 , 4 , 2 , 4 ] ; NEW_LINE n = len ( arr ) NEW_LINE print ( minDelete ( arr , n ) ) ; NEW_LINE
Minimum operation to make all elements equal in array | Python3 program to find the minimum number of operations required to make all elements of array equal ; Function for min operation ; Insert all elements in hash . ; find the max frequency ; return result ; Driver Code
from collections import defaultdict NEW_LINE def minOperation ( arr , n ) : NEW_LINE INDENT Hash = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Hash [ arr [ i ] ] += 1 NEW_LINE DEDENT max_count = 0 NEW_LINE for i in Hash : NEW_LINE INDENT if max_count < Hash [ i ] : NEW_LINE INDENT max_count = Hash [ i ] NEW_LINE DEDENT DEDENT return n - max_count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 2 , 1 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minOperation ( arr , n ) ) NEW_LINE DEDENT
Maximum distance between two occurrences of same element in array | Function to find maximum distance between equal elements ; Used to store element to first index mapping ; Traverse elements and find maximum distance between same occurrences with the help of map . ; If this is first occurrence of element , insert its index in map ; Else update max distance ; Driver Program
def maxDistance ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE maxDict = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] = i NEW_LINE DEDENT else : NEW_LINE INDENT maxDict = max ( maxDict , i - mp [ arr [ i ] ] ) NEW_LINE DEDENT DEDENT return maxDict NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print maxDistance ( arr , n ) NEW_LINE DEDENT
Check if a given array contains duplicate elements within k distance from each other | Python 3 program to Check if a given array contains duplicate elements within k distance from each other ; Creates an empty list ; Traverse the input array ; If already present n hash , then we found a duplicate within k distance ; Add this item to hashset ; Remove the k + 1 distant item ; Driver Code
def checkDuplicatesWithinK ( arr , n , k ) : NEW_LINE INDENT myset = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in myset : NEW_LINE INDENT return True NEW_LINE DEDENT myset . append ( arr [ i ] ) NEW_LINE if ( i >= k ) : NEW_LINE INDENT myset . remove ( arr [ i - k ] ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 3 , 4 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( checkDuplicatesWithinK ( arr , n , 3 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Find duplicates in a given array when elements are not limited to a range | Function to find the Duplicates , if duplicate occurs 2 times or more than 2 times in array so , it will print duplicate value only once at output ; Initialize ifPresent as false ; ArrayList to store the output ; Checking if element is present in the ArrayList or not if present then break ; If element is not present in the ArrayList then add it to ArrayList and make ifPresent at true ; If duplicates is present then print ArrayList ; Driver Code
def findDuplicates ( arr , Len ) : NEW_LINE INDENT ifPresent = False NEW_LINE a1 = [ ] NEW_LINE for i in range ( Len - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , Len ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT if arr [ i ] in a1 : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT a1 . append ( arr [ i ] ) NEW_LINE ifPresent = True NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( ifPresent ) : NEW_LINE INDENT print ( a1 , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ duplicates ▁ present ▁ in ▁ arrays " ) NEW_LINE DEDENT DEDENT arr = [ 12 , 11 , 40 , 12 , 5 , 6 , 5 , 12 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE findDuplicates ( arr , n ) NEW_LINE
Check if leaf traversal of two Binary Trees is same ? | Binary Tree node ; checks if a given node is leaf or not . ; Returns true of leaf traversal of two trees is same , else false ; Create empty stacks . These stacks are going to be used for iterative traversals . ; Loop until either of two stacks is not empty ; If one of the stacks is empty means other stack has extra leaves so return false ; append right and left children of temp1 . Note that right child is inserted before left ; same for tree2 ; If one is None and other is not , then return false ; If both are not None and data is not same return false ; If control reaches this point , all leaves are matched ; Driver Code ; Let us create trees in above example 1
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = self . right = None NEW_LINE DEDENT def isLeaf ( self ) : NEW_LINE INDENT return ( self . left == None and self . right == None ) NEW_LINE DEDENT DEDENT def isSame ( root1 , root2 ) : NEW_LINE INDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE s1 . append ( root1 ) NEW_LINE s2 . append ( root2 ) NEW_LINE while ( len ( s1 ) != 0 or len ( s2 ) != 0 ) : NEW_LINE INDENT if ( len ( s1 ) == 0 or len ( s2 ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT temp1 = s1 . pop ( - 1 ) NEW_LINE while ( temp1 != None and not temp1 . isLeaf ( ) ) : NEW_LINE INDENT if ( temp1 . right != None ) : NEW_LINE INDENT s1 . append ( temp1 . right ) NEW_LINE DEDENT if ( temp1 . left != None ) : NEW_LINE INDENT s1 . append ( temp1 . left ) NEW_LINE temp1 = s1 . pop ( - 1 ) NEW_LINE DEDENT DEDENT temp2 = s2 . pop ( - 1 ) NEW_LINE while ( temp2 != None and not temp2 . isLeaf ( ) ) : NEW_LINE INDENT if ( temp2 . right != None ) : NEW_LINE INDENT s2 . append ( temp2 . right ) NEW_LINE DEDENT if ( temp2 . left != None ) : NEW_LINE INDENT s2 . append ( temp2 . left ) NEW_LINE DEDENT temp2 = s2 . pop ( - 1 ) NEW_LINE DEDENT if ( temp1 == None and temp2 != None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( temp1 != None and temp2 == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( temp1 != None and temp2 != None ) : NEW_LINE INDENT if ( temp1 . data != temp2 . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = Node ( 1 ) NEW_LINE root1 . left = Node ( 2 ) NEW_LINE root1 . right = Node ( 3 ) NEW_LINE root1 . left . left = Node ( 4 ) NEW_LINE root1 . right . left = Node ( 6 ) NEW_LINE root1 . right . right = Node ( 7 ) NEW_LINE root2 = Node ( 0 ) NEW_LINE root2 . left = Node ( 1 ) NEW_LINE root2 . right = Node ( 5 ) NEW_LINE root2 . left . right = Node ( 4 ) NEW_LINE root2 . right . left = Node ( 6 ) NEW_LINE root2 . right . right = Node ( 7 ) NEW_LINE if ( isSame ( root1 , root2 ) ) : NEW_LINE INDENT print ( " Same " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ Same " ) NEW_LINE DEDENT DEDENT
Most frequent element in an array | Python3 program to find the most frequent element in an array . ; Sort the array ; find the max frequency using linear traversal ; If last element is most frequent ; Driver Code
def mostFrequent ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE max_count = 1 ; res = arr [ 0 ] ; curr_count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT curr_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( curr_count > max_count ) : NEW_LINE INDENT max_count = curr_count NEW_LINE res = arr [ i - 1 ] NEW_LINE DEDENT curr_count = 1 NEW_LINE DEDENT DEDENT if ( curr_count > max_count ) : NEW_LINE INDENT max_count = curr_count NEW_LINE res = arr [ n - 1 ] NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 1 , 5 , 2 , 1 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( mostFrequent ( arr , n ) ) NEW_LINE
Most frequent element in an array | Python3 program to find the most frequent element in an array . ; Insert all elements in Hash . ; find the max frequency ; Driver Code
import math as mt NEW_LINE def mostFrequent ( arr , n ) : NEW_LINE INDENT Hash = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in Hash . keys ( ) : NEW_LINE INDENT Hash [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Hash [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT max_count = 0 NEW_LINE res = - 1 NEW_LINE for i in Hash : NEW_LINE INDENT if ( max_count < Hash [ i ] ) : NEW_LINE INDENT res = i NEW_LINE max_count = Hash [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 1 , 5 , 2 , 1 , 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( mostFrequent ( arr , n ) ) NEW_LINE
Smallest subarray with all occurrences of a most frequent element | Python3 implementation to find smallest subarray with all occurrences of a most frequent element ; To store left most occurrence of elements ; To store counts of elements ; To store maximum frequency ; To store length and starting index of smallest result window ; First occurrence of an element , store the index ; increase the frequency of elements ; Find maximum repeated element and store its last occurrence and first occurrence ; length of subsegment ; select subsegment of smallest size ; Print the subsegment with all occurrences of a most frequent element ; Driver code
def smallestSubsegment ( a , n ) : NEW_LINE INDENT left = dict ( ) NEW_LINE count = dict ( ) NEW_LINE mx = 0 NEW_LINE mn , strindex = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x not in count . keys ( ) ) : NEW_LINE INDENT left [ x ] = i NEW_LINE count [ x ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ x ] += 1 NEW_LINE DEDENT if ( count [ x ] > mx ) : NEW_LINE INDENT mx = count [ x ] NEW_LINE mn = i - left [ x ] + 1 NEW_LINE strindex = left [ x ] NEW_LINE DEDENT elif ( count [ x ] == mx and i - left [ x ] + 1 < mn ) : NEW_LINE INDENT mn = i - left [ x ] + 1 NEW_LINE strindex = left [ x ] NEW_LINE DEDENT DEDENT for i in range ( strindex , strindex + mn ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT A = [ 1 , 2 , 2 , 2 , 1 ] NEW_LINE n = len ( A ) NEW_LINE smallestSubsegment ( A , n ) NEW_LINE
Given an array of pairs , find all symmetric pairs in it | Print all pairs that have a symmetric counterpart ; Creates an empty hashMap hM ; Traverse through the given array ; First and second elements of current pair ; If found and value in hash matches with first element of this pair , we found symmetry ; Else put sec element of this pair in hash ; Driver Code
def findSymPairs ( arr , row ) : NEW_LINE INDENT hM = dict ( ) NEW_LINE for i in range ( row ) : NEW_LINE INDENT first = arr [ i ] [ 0 ] NEW_LINE sec = arr [ i ] [ 1 ] NEW_LINE if ( sec in hM . keys ( ) and hM [ sec ] == first ) : NEW_LINE INDENT print ( " ( " , sec , " , " , first , " ) " ) NEW_LINE DEDENT else : NEW_LINE INDENT hM [ first ] = sec NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 0 for i in range ( 2 ) ] for i in range ( 5 ) ] NEW_LINE arr [ 0 ] [ 0 ] , arr [ 0 ] [ 1 ] = 11 , 20 NEW_LINE arr [ 1 ] [ 0 ] , arr [ 1 ] [ 1 ] = 30 , 40 NEW_LINE arr [ 2 ] [ 0 ] , arr [ 2 ] [ 1 ] = 5 , 10 NEW_LINE arr [ 3 ] [ 0 ] , arr [ 3 ] [ 1 ] = 40 , 30 NEW_LINE arr [ 4 ] [ 0 ] , arr [ 4 ] [ 1 ] = 10 , 5 NEW_LINE findSymPairs ( arr , 5 ) NEW_LINE DEDENT
Find any one of the multiple repeating elements in read only array | Python 3 program to find one of the repeating elements in a read only array ; Function to find one of the repeating elements ; Size of blocks except the last block is sq ; Number of blocks to incorporate 1 to n values blocks are numbered from 0 to range - 1 ( both included ) ; Count array maintains the count for all blocks ; Traversing the read only array and updating count ; arr [ i ] belongs to block number ( arr [ i ] - 1 ) / sq i is considered to start from 0 ; The selected_block is set to last block by default . Rest of the blocks are checked ; after finding block with size > sq method of hashing is used to find the element repeating in this block ; checks if the element belongs to the selected_block ; repeating element found ; return - 1 if no repeating element exists ; Driver Code ; read only array , not to be modified ; array of size 6 ( n + 1 ) having elements between 1 and 5
from math import sqrt NEW_LINE def findRepeatingNumber ( arr , n ) : NEW_LINE INDENT sq = sqrt ( n ) NEW_LINE range__ = int ( ( n / sq ) + 1 ) NEW_LINE count = [ 0 for i in range ( range__ ) ] NEW_LINE for i in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT count [ int ( ( arr [ i ] - 1 ) / sq ) ] += 1 NEW_LINE DEDENT selected_block = range__ - 1 NEW_LINE for i in range ( 0 , range__ - 1 , 1 ) : NEW_LINE INDENT if ( count [ i ] > sq ) : NEW_LINE INDENT selected_block = i NEW_LINE break NEW_LINE DEDENT DEDENT m = { i : 0 for i in range ( n ) } NEW_LINE for i in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT if ( ( ( selected_block * sq ) < arr [ i ] ) and ( arr [ i ] <= ( ( selected_block + 1 ) * sq ) ) ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE if ( m [ arr [ i ] ] > 1 ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 3 , 5 , 4 ] NEW_LINE n = 5 NEW_LINE print ( " One ▁ of ▁ the ▁ numbers ▁ repeated ▁ in ▁ the ▁ array ▁ is : " , findRepeatingNumber ( arr , n ) ) NEW_LINE DEDENT
Group multiple occurrence of array elements ordered by first occurrence | A simple method to group all occurrences of individual elements ; Initialize all elements as not visited ; Traverse all elements ; Check if this is first occurrence ; If yes , print it and all subsequent occurrences ; Driver Code
def groupElements ( arr , n ) : NEW_LINE INDENT visited = [ False ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE visited [ j ] = True NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT arr = [ 4 , 6 , 9 , 2 , 3 , 4 , 9 , 6 , 10 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE groupElements ( arr , n ) NEW_LINE
Group multiple occurrence of array elements ordered by first occurrence | A hashing based method to group all occurrences of individual elements ; Creates an empty hashmap ; Traverse the array elements , and store count for every element in HashMap ; Increment count of elements in HashMap ; Traverse array again ; Check if this is first occurrence ; If yes , then print the element ' count ' times ; And remove the element from HashMap . ; Driver Code
def orderedGroup ( arr ) : NEW_LINE INDENT hM = { } NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT hM [ arr [ i ] ] = hM . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT count = hM . get ( arr [ i ] , None ) NEW_LINE if count != None : NEW_LINE INDENT for j in range ( 0 , count ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT del hM [ arr [ i ] ] NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 3 , 10 , 10 , 4 , 1 , 3 ] NEW_LINE orderedGroup ( arr ) NEW_LINE DEDENT
How to check if two given sets are disjoint ? | Returns true if set1 [ ] and set2 [ ] are disjoint , else false ; Take every element of set1 [ ] and search it in set2 ; If no element of set1 is present in set2 ; Driver program
def areDisjoint ( set1 , set2 , m , n ) : NEW_LINE INDENT for i in range ( 0 , m ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( set1 [ i ] == set2 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT set1 = [ 12 , 34 , 11 , 9 , 3 ] NEW_LINE set2 = [ 7 , 2 , 1 , 5 ] NEW_LINE m = len ( set1 ) NEW_LINE n = len ( set2 ) NEW_LINE print ( " yes " ) if areDisjoint ( set1 , set2 , m , n ) else ( " ▁ No " ) NEW_LINE
How to check if two given sets are disjoint ? | Returns true if set1 [ ] and set2 [ ] are disjoint , else false ; Sort the given two sets ; Check for same elements using merge like process ; if set1 [ i ] == set2 [ j ] ; Driver Code
def areDisjoint ( set1 , set2 , m , n ) : NEW_LINE INDENT set1 . sort ( ) NEW_LINE set2 . sort ( ) NEW_LINE i = 0 ; j = 0 NEW_LINE while ( i < m and j < n ) : NEW_LINE INDENT if ( set1 [ i ] < set2 [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( set2 [ j ] < set1 [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT set1 = [ 12 , 34 , 11 , 9 , 3 ] NEW_LINE set2 = [ 7 , 2 , 1 , 5 ] NEW_LINE m = len ( set1 ) NEW_LINE n = len ( set2 ) NEW_LINE print ( " Yes " ) if areDisjoint ( set1 , set2 , m , n ) else print ( " No " ) NEW_LINE
How to check if two given sets are disjoint ? | This function prints all distinct elements ; Creates an empty hashset ; Traverse the first set and store its elements in hash ; Traverse the second set and check if any element of it is already in hash or not . ; Driver method to test above method
def areDisjoint ( set1 , set2 , n1 , n2 ) : NEW_LINE INDENT myset = set ( [ ] ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT myset . add ( set1 [ i ] ) NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT if ( set2 [ i ] in myset ) : NEW_LINE return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT set1 = [ 10 , 5 , 3 , 4 , 6 ] NEW_LINE set2 = [ 8 , 7 , 9 , 3 ] NEW_LINE n1 = len ( set1 ) NEW_LINE n2 = len ( set2 ) NEW_LINE if ( areDisjoint ( set1 , set2 , n1 , n2 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Non | Python3 program to find Non - overlapping sum ; Function for calculating Non - overlapping sum of two array ; Insert elements of both arrays ; calculate non - overlapped sum ; Driver code ; size of array ; Function call
from collections import defaultdict NEW_LINE def findSum ( A , B , n ) : NEW_LINE INDENT Hash = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Hash [ A [ i ] ] += 1 NEW_LINE Hash [ B [ i ] ] += 1 NEW_LINE DEDENT Sum = 0 NEW_LINE for x in Hash : NEW_LINE INDENT if Hash [ x ] == 1 : NEW_LINE INDENT Sum += x NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 5 , 4 , 9 , 2 , 3 ] NEW_LINE B = [ 2 , 8 , 7 , 6 , 3 ] NEW_LINE n = len ( A ) NEW_LINE print ( findSum ( A , B , n ) ) NEW_LINE DEDENT
Find elements which are present in first array and not in second | Function for finding elements which are there in a [ ] but not in b [ ] . ; Driver code
def findMissing ( a , b , n , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( a [ i ] == b [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == m - 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 6 , 3 , 4 , 5 ] NEW_LINE b = [ 2 , 4 , 3 , 1 , 0 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE findMissing ( a , b , n , m ) NEW_LINE DEDENT
Find elements which are present in first array and not in second | Function for finding elements which are there in a [ ] but not in b [ ] . ; Store all elements of second array in a hash table ; Print all elements of first array that are not present in hash table ; Driver code
def findMissing ( a , b , n , m ) : NEW_LINE INDENT s = dict ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT s [ b [ i ] ] = 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if a [ i ] not in s . keys ( ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT a = [ 1 , 2 , 6 , 3 , 4 , 5 ] NEW_LINE b = [ 2 , 4 , 3 , 1 , 0 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE findMissing ( a , b , n , m ) NEW_LINE
Check if two arrays are equal or not | Returns true if arr1 [ 0. . n - 1 ] and arr2 [ 0. . m - 1 ] contain same elements . ; If lengths of array are not equal means array are not equal ; Sort both arrays ; Linearly compare elements ; If all elements were same . ; Driver Code
def areEqual ( arr1 , arr2 , n , m ) : NEW_LINE INDENT if ( n != m ) : NEW_LINE INDENT return False NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr1 = [ 3 , 5 , 2 , 5 , 2 ] NEW_LINE arr2 = [ 2 , 3 , 5 , 5 , 2 ] NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE if ( areEqual ( arr1 , arr2 , n , m ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Pair with given sum and maximum shortest distance from end | function to find maximum shortest distance ; stores the shortest distance of every element in original array . ; shortest distance from ends ; if duplicates are found , b [ x ] is replaced with minimum of the previous and current position 's shortest distance ; similar elements ignore them cause we need distinct elements ; Driver code
def find_maximum ( a , n , k ) : NEW_LINE INDENT b = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE d = min ( 1 + i , n - i ) NEW_LINE if x not in b . keys ( ) : NEW_LINE INDENT b [ x ] = d NEW_LINE DEDENT else : NEW_LINE INDENT b [ x ] = min ( d , b [ x ] ) NEW_LINE DEDENT DEDENT ans = 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x != ( k - x ) and ( k - x ) in b . keys ( ) ) : NEW_LINE INDENT ans = min ( max ( b [ x ] , b [ k - x ] ) , ans ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 3 , 5 , 8 , 6 , 7 ] NEW_LINE K = 11 NEW_LINE n = len ( a ) NEW_LINE print ( find_maximum ( a , n , K ) ) NEW_LINE
Pair with given product | Set 1 ( Find if any pair exists ) | Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x ; Consider all possible pairs and check for every pair . ; Driver code
def isProduct ( arr , n , x ) : NEW_LINE INDENT for i in arr : NEW_LINE INDENT for j in arr : NEW_LINE INDENT if i * j == x : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 10 , 20 , 9 , 40 ] NEW_LINE x = 400 NEW_LINE n = len ( arr ) NEW_LINE if ( isProduct ( arr , n , x ) == True ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT x = 900 NEW_LINE if ( isProduct ( arr , n , x ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Pair with given product | Set 1 ( Find if any pair exists ) | Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Create an empty set and insert first element into it ; Traverse remaining elements ; 0 case must be handles explicitly as x % 0 is undefined behaviour in C ++ ; x / arr [ i ] exists in hash , then we found a pair ; Insert arr [ i ] ; Driver code
def isProduct ( arr , n , x ) : NEW_LINE INDENT if n < 2 : NEW_LINE INDENT return False NEW_LINE DEDENT s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT if x % arr [ i ] == 0 : NEW_LINE INDENT if x // arr [ i ] in s : NEW_LINE INDENT return True NEW_LINE DEDENT s . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 20 , 9 , 40 ] NEW_LINE x = 400 NEW_LINE n = len ( arr ) NEW_LINE if isProduct ( arr , n , x ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT x = 190 NEW_LINE if isProduct ( arr , n , x ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check whether a given binary tree is perfect or not | Returns depth of leftmost leaf . ; This function tests if a binary treeis perfect or not . It basically checks for two things : 1 ) All leaves are at same level 2 ) All internal nodes have two children ; An empty tree is perfect ; If leaf node , then its depth must be same as depth of all other leaves . ; If internal node and one child is empty ; Left and right subtrees must be perfect . ; Wrapper over isPerfectRec ( ) ; Helper class that allocates a new node with the given key and None left and right pointer . ; Driver Code
def findADepth ( node ) : NEW_LINE INDENT d = 0 NEW_LINE while ( node != None ) : NEW_LINE INDENT d += 1 NEW_LINE node = node . left NEW_LINE DEDENT return d NEW_LINE DEDENT def isPerfectRec ( root , d , level = 0 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT return ( d == level + 1 ) NEW_LINE DEDENT if ( root . left == None or root . right == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT return ( isPerfectRec ( root . left , d , level + 1 ) and isPerfectRec ( root . right , d , level + 1 ) ) NEW_LINE DEDENT def isPerfect ( root ) : NEW_LINE INDENT d = findADepth ( root ) NEW_LINE return isPerfectRec ( root , d ) NEW_LINE DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , k ) : NEW_LINE INDENT self . key = k NEW_LINE self . right = self . left = None NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = None NEW_LINE root = newNode ( 10 ) NEW_LINE root . left = newNode ( 20 ) NEW_LINE root . right = newNode ( 30 ) NEW_LINE root . left . left = newNode ( 40 ) NEW_LINE root . left . right = newNode ( 50 ) NEW_LINE root . right . left = newNode ( 60 ) NEW_LINE root . right . right = newNode ( 70 ) NEW_LINE if ( isPerfect ( root ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Find pair with greatest product in array | Function to find greatest number ; Driver code
def findGreatest ( arr , n ) : NEW_LINE INDENT result = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] * arr [ k ] == arr [ i ] ) : NEW_LINE INDENT result = max ( result , arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 30 , 10 , 9 , 3 , 35 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findGreatest ( arr , n ) ) NEW_LINE DEDENT
Find pair with greatest product in array | Python3 program to find the largest product number ; Function to find greatest number ; Store occurrences of all elements in hash array ; Sort the array and traverse all elements from end . ; For every element , check if there is another element which divides it . ; Check if the result value exists in array or not if yes the return arr [ i ] ; To handle the case like arr [ i ] = 4 and arr [ j ] = 2 ; Drivers code
from math import sqrt NEW_LINE def findGreatest ( arr , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in arr : NEW_LINE INDENT m [ i ] = m . get ( i , 0 ) + 1 NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < i and arr [ j ] <= sqrt ( arr [ i ] ) ) : NEW_LINE INDENT if ( arr [ i ] % arr [ j ] == 0 ) : NEW_LINE INDENT result = arr [ i ] // arr [ j ] NEW_LINE if ( result != arr [ j ] and ( result in m . keys ( ) ) and m [ result ] > 0 ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT elif ( result == arr [ j ] and ( result in m . keys ( ) ) and m [ result ] > 1 ) : NEW_LINE INDENT return arr [ i ] NEW_LINE DEDENT DEDENT j += 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 17 , 2 , 1 , 15 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findGreatest ( arr , n ) ) NEW_LINE
Remove minimum number of elements such that no common element exist in both array | To find no elements to remove so no common element exist ; To store count of array element ; Count elements of a ; Count elements of b ; Traverse through all common element , and pick minimum occurrence from two arrays ; To return count of minimum elements ; Driver Code
def minRemove ( a , b , n , m ) : NEW_LINE INDENT countA = dict ( ) NEW_LINE countB = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT countA [ a [ i ] ] = countA . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT countB [ b [ i ] ] = countB . get ( b [ i ] , 0 ) + 1 NEW_LINE DEDENT res = 0 NEW_LINE for x in countA : NEW_LINE INDENT if x in countB . keys ( ) : NEW_LINE INDENT res += min ( countA [ x ] , countB [ x ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT a = [ 1 , 2 , 3 , 4 ] NEW_LINE b = [ 2 , 3 , 4 , 5 , 8 ] NEW_LINE n = len ( a ) NEW_LINE m = len ( b ) NEW_LINE print ( minRemove ( a , b , n , m ) ) NEW_LINE
Count items common to both the lists but with different prices | function to count items common to both the lists but with different prices ; for each item of ' list1' check if it is in ' list2' but with a different price ; required count of items ; Driver program to test above
def countItems ( list1 , list2 ) : NEW_LINE INDENT count = 0 NEW_LINE for i in list1 : NEW_LINE INDENT for j in list2 : NEW_LINE INDENT if i [ 0 ] == j [ 0 ] and i [ 1 ] != j [ 1 ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT list1 = [ ( " apple " , 60 ) , ( " bread " , 20 ) , ( " wheat " , 50 ) , ( " oil " , 30 ) ] NEW_LINE list2 = [ ( " milk " , 20 ) , ( " bread " , 15 ) , ( " wheat " , 40 ) , ( " apple " , 60 ) ] NEW_LINE print ( " Count ▁ = ▁ " , countItems ( list1 , list2 ) ) NEW_LINE
Minimum Index Sum for Common Elements of Two Lists | Function to print common strings with minimum index sum ; resultant list ; iterating over sum in ascending order ; iterating over one list and check index ( Corresponding to given sum ) in other list ; put common strings in resultant list ; if common string found then break as we are considering index sums in increasing order . ; print the resultant list ; Creating list1 ; Creating list2
def find ( list1 , list2 ) : NEW_LINE INDENT res = [ ] NEW_LINE max_possible_sum = len ( list1 ) + len ( list2 ) - 2 NEW_LINE for sum in range ( max_possible_sum + 1 ) : NEW_LINE INDENT for i in range ( sum + 1 ) : NEW_LINE INDENT if ( i < len ( list1 ) and ( sum - i ) < len ( list2 ) and list1 [ i ] == list2 [ sum - i ] ) : NEW_LINE INDENT res . append ( list1 [ i ] ) NEW_LINE DEDENT DEDENT if ( len ( res ) > 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT for i in range ( len ( res ) ) : NEW_LINE INDENT print ( res [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT list1 = [ ] NEW_LINE list1 . append ( " GeeksforGeeks " ) NEW_LINE list1 . append ( " Udemy " ) NEW_LINE list1 . append ( " Coursera " ) NEW_LINE list1 . append ( " edX " ) NEW_LINE list2 = [ ] NEW_LINE list2 . append ( " Codecademy " ) NEW_LINE list2 . append ( " Khan ▁ Academy " ) NEW_LINE list2 . append ( " GeeksforGeeks " ) NEW_LINE find ( list1 , list2 ) NEW_LINE
Minimum Index Sum for Common Elements of Two Lists | Hashing based Python3 program to find common elements with minimum index sum ; Function to print common strings with minimum index sum ; Mapping strings to their indices ; Resultant list ; If current sum is smaller than minsum ; If index sum is same then put this string in resultant list as well ; Print result ; Creating list1 ; Creating list2
import sys NEW_LINE def find ( list1 , list2 ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( len ( list1 ) ) : NEW_LINE INDENT Map [ list1 [ i ] ] = i NEW_LINE DEDENT res = [ ] NEW_LINE minsum = sys . maxsize NEW_LINE for j in range ( len ( list2 ) ) : NEW_LINE INDENT if list2 [ j ] in Map : NEW_LINE INDENT Sum = j + Map [ list2 [ j ] ] NEW_LINE if ( Sum < minsum ) : NEW_LINE INDENT minsum = Sum NEW_LINE res . clear ( ) NEW_LINE res . append ( list2 [ j ] ) NEW_LINE DEDENT elif ( Sum == minsum ) : NEW_LINE INDENT res . append ( list2 [ j ] ) NEW_LINE DEDENT DEDENT DEDENT print ( * res , sep = " ▁ " ) NEW_LINE DEDENT list1 = [ ] NEW_LINE list1 . append ( " GeeksforGeeks " ) NEW_LINE list1 . append ( " Udemy " ) NEW_LINE list1 . append ( " Coursera " ) NEW_LINE list1 . append ( " edX " ) NEW_LINE list2 = [ ] NEW_LINE list2 . append ( " Codecademy " ) NEW_LINE list2 . append ( " Khan ▁ Academy " ) NEW_LINE list2 . append ( " GeeksforGeeks " ) NEW_LINE find ( list1 , list2 ) NEW_LINE
Check whether a binary tree is a full binary tree or not | Constructor of the node class for creating the node ; Checks if the binary tree is full or not ; If empty tree ; If leaf node ; If both left and right subtress are not None and left and right subtress are full ; We reach here when none of the above if condiitions work ; Driver Program
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isFullTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT return True NEW_LINE DEDENT if root . left is not None and root . right is not None : NEW_LINE INDENT return ( isFullTree ( root . left ) and isFullTree ( root . right ) ) NEW_LINE DEDENT return False NEW_LINE DEDENT root = Node ( 10 ) ; NEW_LINE root . left = Node ( 20 ) ; NEW_LINE root . right = Node ( 30 ) ; NEW_LINE root . left . right = Node ( 40 ) ; NEW_LINE root . left . left = Node ( 50 ) ; NEW_LINE root . right . left = Node ( 60 ) ; NEW_LINE root . right . right = Node ( 70 ) ; NEW_LINE root . left . left . left = Node ( 80 ) ; NEW_LINE root . left . left . right = Node ( 90 ) ; NEW_LINE root . left . right . left = Node ( 80 ) ; NEW_LINE root . left . right . right = Node ( 90 ) ; NEW_LINE root . right . left . left = Node ( 80 ) ; NEW_LINE root . right . left . right = Node ( 90 ) ; NEW_LINE root . right . right . left = Node ( 80 ) ; NEW_LINE root . right . right . right = Node ( 90 ) ; NEW_LINE if isFullTree ( root ) : NEW_LINE INDENT print " The ▁ Binary ▁ tree ▁ is ▁ full " NEW_LINE DEDENT else : NEW_LINE INDENT print " Binary ▁ tree ▁ is ▁ not ▁ full " NEW_LINE DEDENT
Change the array into a permutation of numbers from 1 to n | Python3 code to make a permutation of numbers from 1 to n using minimum changes . ; Store counts of all elements . ; Find next missing element to put in place of current element . ; Replace with next missing and insert the missing element in hash . ; Driver Code
def makePermutation ( a , n ) : NEW_LINE INDENT count = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if count . get ( a [ i ] ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ a [ i ] ] = 1 ; NEW_LINE DEDENT DEDENT next_missing = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if count [ a [ i ] ] != 1 or a [ i ] > n or a [ i ] < 1 : NEW_LINE INDENT count [ a [ i ] ] -= 1 NEW_LINE while count . get ( next_missing ) : NEW_LINE INDENT next_missing += 1 NEW_LINE DEDENT a [ i ] = next_missing NEW_LINE count [ next_missing ] = 1 NEW_LINE DEDENT DEDENT DEDENT A = [ 2 , 2 , 3 , 3 ] NEW_LINE n = len ( A ) NEW_LINE makePermutation ( A , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT