text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Highest power of two that divides a given number | Python3 program to find highest power of 2 that divides n . ; Driver code
def highestPowerOf2 ( n ) : NEW_LINE INDENT return ( n & ( ~ ( n - 1 ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 48 NEW_LINE print ( highestPowerOf2 ( n ) ) NEW_LINE DEDENT
Check whether bitwise AND of a number with any subset of an array is zero or not | Function to check whether bitwise AND of a number with any subset of an array is zero or not ; variable to store the AND of all the elements ; find the AND of all the elements of the array ; if the AND of all the array elements and N is ...
def isSubsetAndZero ( array , length , N ) : NEW_LINE INDENT arrAnd = array [ 0 ] NEW_LINE for i in range ( 1 , length ) : NEW_LINE INDENT arrAnd = arrAnd & array [ i ] NEW_LINE DEDENT if ( ( arrAnd & N ) == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT ...
Finding the Parity of a number Efficiently | Function to find the parity ; Rightmost bit of y holds the parity value if ( y & 1 ) is 1 then parity is odd else even ; Driver code
def findParity ( x ) : NEW_LINE INDENT y = x ^ ( x >> 1 ) ; NEW_LINE y = y ^ ( y >> 2 ) ; NEW_LINE y = y ^ ( y >> 4 ) ; NEW_LINE y = y ^ ( y >> 8 ) ; NEW_LINE y = y ^ ( y >> 16 ) ; NEW_LINE if ( y & 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if ( findParity ( 9 ) == 0 ) : NEW_LINE INDEN...
Check if bits in range L to R of two numbers are complement of each other or not | function to check whether all the bits are set in the given range or not ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; new number which will only have one or more set bits...
def allBitsSetInTheGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE new_num = n & num NEW_LINE if ( num == new_num ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def bitsAreComplement ( a , b , l , r ) : NEW_LINE INDENT xor_value = a...
Sum of the series 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... . . + 2 ^ n | function to calculate sum of series ; initialize sum to 0 ; loop to calculate sum of series ; calculate 2 ^ i ; Driver code
def calculateSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum = sum + ( 1 << i ) NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( " Sum ▁ of ▁ series ▁ " , calculateSum ( n ) ) NEW_LINE
Print all the combinations of N elements by changing sign such that their sum is divisible by M | Function to print all the combinations ; Iterate for all combinations ; Initially 100 in binary if n is 3 as 1 << ( 3 - 1 ) = 100 in binary ; Iterate in the array and assign signs to the array elements ; If the j - th bit ...
def printCombinations ( a , n , m ) : NEW_LINE INDENT for i in range ( 0 , ( 1 << n ) ) : NEW_LINE INDENT sum = 0 NEW_LINE num = 1 << ( n - 1 ) NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( i & num ) > 0 ) : NEW_LINE INDENT sum += a [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT sum += ( - 1 * a [ j ] ) NEW_...
Same Number Of Set Bits As N | ; function ; __builtin_popcount function that count set bits in n ; Iterate from n - 1 to 1 ; check if the number of set bits equals to temp increment count ; Driver Code
/ * returns number of set bits in a number * / NEW_LINE def __builtin_popcount ( n ) : NEW_LINE INDENT t = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT d = n % 2 NEW_LINE n = int ( n / 2 ) NEW_LINE if ( d == 1 ) : NEW_LINE INDENT t = t + 1 NEW_LINE DEDENT DEDENT return t NEW_LINE DEDENT def smallerNumsWithSameSetBits (...
Multiply any Number with 4 using Bitwise Operator | function the return multiply a number with 4 using bitwise operator ; returning a number with multiply with 4 using2 bit shifring right ; derive function
def multiplyWith4 ( n ) : NEW_LINE INDENT return ( n << 2 ) NEW_LINE DEDENT n = 4 NEW_LINE print ( multiplyWith4 ( n ) ) NEW_LINE
Leftover element after performing alternate Bitwise OR and Bitwise XOR operations on adjacent pairs | Python3 program to print the Leftover element after performing alternate Bitwise OR and Bitwise XOR operations to the pairs . ; array to store the tree ; array to store the level of every parent ; function to construct...
N = 1000 NEW_LINE tree = [ None ] * N NEW_LINE level = [ None ] * N NEW_LINE def constructTree ( low , high , pos , a ) : NEW_LINE INDENT if low == high : NEW_LINE INDENT level [ pos ] , tree [ pos ] = 0 , a [ high ] NEW_LINE return NEW_LINE DEDENT mid = ( low + high ) // 2 NEW_LINE constructTree ( low , mid , 2 * pos ...
Set all even bits of a number | Sets even bits of n and returns modified number . ; Generate 101010. . .10 number and store in res . ; if bit is even then generate number and or with res ; return OR number ; Driver code
def evenbitsetnumber ( n ) : NEW_LINE INDENT count = 0 NEW_LINE res = 0 NEW_LINE temp = n NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT if ( count % 2 == 1 ) : NEW_LINE INDENT res |= ( 1 << count ) NEW_LINE DEDENT count += 1 NEW_LINE temp >>= 1 NEW_LINE DEDENT return ( n res ) NEW_LINE DEDENT n = 10 NEW_LINE print ( ev...
Set all even bits of a number | return msb set number ; set all bits ; return msb increment n by 1 and shift by 1 ; return even seted number ; get msb here ; generate even bits like 101010. . ; if bits is odd then shift by 1 ; return even set bits number ; set all even bits here ; take or with even set bits number ;
def getmsb ( n ) : NEW_LINE INDENT n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE return ( n + 1 ) >> 1 NEW_LINE DEDENT def getevenbits ( n ) : NEW_LINE INDENT n = getmsb ( n ) NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16...
Set all odd bits of a number | set all odd bit ; res for store 010101. . number ; generate number form of 010101. . ... till temp size ; if bit is odd , then generate number and or with res ; Driver code
def oddbitsetnumber ( n ) : NEW_LINE INDENT count = 0 NEW_LINE res = 0 NEW_LINE temp = n NEW_LINE while temp > 0 : NEW_LINE INDENT if count % 2 == 0 : NEW_LINE INDENT res |= ( 1 << count ) NEW_LINE DEDENT count += 1 NEW_LINE temp >>= 1 NEW_LINE DEDENT return ( n res ) NEW_LINE DEDENT n = 10 NEW_LINE print ( oddbitsetnu...
Set all odd bits of a number | Efficient python3 program to set all odd bits number ; return MSB set number ; set all bits including MSB . ; return MSB ; Returns a number of same size ( MSB at same position ) as n and all odd bits set . ; generate odd bits like 010101. . ; if bits is even then shift by 1 ; return odd s...
import math NEW_LINE def getmsb ( n ) : NEW_LINE INDENT n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE return ( n + 1 ) >> 1 NEW_LINE DEDENT def getevenbits ( n ) : NEW_LINE INDENT n = getmsb ( n ) NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 ...
Print numbers in the range 1 to n having bits in alternate pattern | function to print numbers in the range 1 to nhaving bits in alternate pattern ; first number having bits in alternate pattern ; display ; loop until n < curr_num ; generate next number having alternate bit pattern ; if true then break ; display ; gene...
def printNumHavingAltBitPatrn ( n ) : NEW_LINE INDENT curr_num = 1 NEW_LINE print ( curr_num ) NEW_LINE while ( 1 ) : NEW_LINE INDENT curr_num = curr_num << 1 ; NEW_LINE if ( n < curr_num ) : NEW_LINE INDENT break ; NEW_LINE DEDENT print ( curr_num ) NEW_LINE curr_num = ( ( curr_num ) << 1 ) ^ 1 ; NEW_LINE if ( n < cur...
Smallest perfect power of 2 greater than n ( without using arithmetic operators ) | Function to find smallest perfect power of 2 greater than n ; To store perfect power of 2 ; bitwise left shift by 1 ; bitwise right shift by 1 ; Required perfect power of 2 ; Driver program to test above
def perfectPowerOf2 ( n ) : NEW_LINE INDENT per_pow = 1 NEW_LINE while n > 0 : NEW_LINE INDENT per_pow = per_pow << 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return per_pow NEW_LINE DEDENT n = 128 NEW_LINE print ( " Perfect ▁ power ▁ of ▁ 2 ▁ greater ▁ than " , n , " : " , perfectPowerOf2 ( n ) ) NEW_LINE
Find Unique pair in an array with pairs of numbers | Python 3 program to find a unique pair in an array of pairs . ; XOR each element and get XOR of two unique elements ( ans ) ; Get a set bit of XOR ( We get the rightmost set bit ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at sam...
def findUniquePair ( arr , n ) : NEW_LINE INDENT XOR = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT XOR = XOR ^ arr [ i ] NEW_LINE DEDENT set_bit_no = XOR & ~ ( XOR - 1 ) NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] & set_bit_no ) : NEW_LINE INDENT x ...
M | function to find the next higher number with same number of set bits as in 'x ; the approach is same as discussed in ; function to find the mth smallest number having k number of set bits ; smallest number having ' k ' number of set bits ; finding the mth smallest number having k set bits ; required number ; Driver...
' NEW_LINE def nxtHighWithNumOfSetBits ( x ) : NEW_LINE INDENT rightOne = 0 NEW_LINE nextHigherOneBit = 0 NEW_LINE rightOnesPattern = 0 NEW_LINE next = 0 NEW_LINE if ( x ) : NEW_LINE INDENT rightOne = x & ( - x ) NEW_LINE nextHigherOneBit = x + rightOne NEW_LINE rightOnesPattern = x ^ nextHigherOneBit NEW_LINE rightOne...
Count unset bits of a number | An optimized Python program to count unset bits in an integer . ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Count set bits in toggled number ; Driver code
import math NEW_LINE def countUnsetBits ( n ) : NEW_LINE INDENT x = n NEW_LINE n |= n >> 1 NEW_LINE n |= n >> 2 NEW_LINE n |= n >> 4 NEW_LINE n |= n >> 8 NEW_LINE n |= n >> 16 NEW_LINE t = math . log ( x ^ n , 2 ) NEW_LINE return math . floor ( t ) NEW_LINE DEDENT n = 17 NEW_LINE print ( countUnsetBits ( n ) ) NEW_LINE
Count total bits in a number | Function to get no of bits in binary representation of positive integer ; Driver program
def countBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT i = 65 NEW_LINE print ( countBits ( i ) ) NEW_LINE
Toggle all bits after most significant bit | Function to toggle bits starting from MSB ; temporary variable to use XOR with one of a n ; Run loop until the only set bit in temp crosses MST of n . ; Toggle bit of n corresponding to current set bit in temp . ; Move set bit to next higher position . ; Driver code
def toggle ( n ) : NEW_LINE INDENT temp = 1 NEW_LINE while ( temp <= n ) : NEW_LINE INDENT n = n ^ temp NEW_LINE temp = temp << 1 NEW_LINE DEDENT return n NEW_LINE DEDENT n = 10 NEW_LINE n = toggle ( n ) NEW_LINE print ( n ) NEW_LINE
Find the n | Python 3 program to find n - th number whose binary representation is palindrome . ; Finds if the kth bit is set in the binary representation ; Returns the position of leftmost set bit in the binary representation ; Finds whether the integer in binary representation is palindrome or not ; One by one compar...
INT_MAX = 2147483647 NEW_LINE def isKthBitSet ( x , k ) : NEW_LINE INDENT return 1 if ( x & ( 1 << ( k - 1 ) ) ) else 0 NEW_LINE DEDENT def leftmostSetBit ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x ) : NEW_LINE INDENT count += 1 NEW_LINE x = x >> 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def isBinPalindr...
Print ' K ' th least significant bit of a number | Function returns 1 if set , 0 if not ; Driver code ; Function call
def LSB ( num , K ) : NEW_LINE INDENT return bool ( num & ( 1 << ( K - 1 ) ) ) NEW_LINE DEDENT num , k = 10 , 4 NEW_LINE res = LSB ( num , k ) NEW_LINE if res : NEW_LINE INDENT print 1 NEW_LINE DEDENT else : NEW_LINE INDENT print 0 NEW_LINE DEDENT
Check if two numbers are equal without using comparison operators | Finds if a and b are same ; Driver code
def areSame ( a , b ) : NEW_LINE INDENT if ( not ( a - b ) ) : NEW_LINE INDENT print " Same " NEW_LINE DEDENT else : NEW_LINE INDENT print " Not ▁ Same " NEW_LINE DEDENT DEDENT areSame ( 10 , 20 ) NEW_LINE
Toggle bits in the given range | function to toggle bits in the given range ; calculating a number ' num ' having ' r ' number of bits and bits in the range l to r are the only set bits ; toggle bits in the range l to r in ' n ' Besides this , we can calculate num as : num = ( 1 << r ) - l . ; Driver code
def toggleBitsFromLToR ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE return ( n ^ num ) NEW_LINE DEDENT n = 50 NEW_LINE l = 2 NEW_LINE r = 5 NEW_LINE print ( toggleBitsFromLToR ( n , l , r ) ) NEW_LINE
Position of rightmost different bit | Python implementation to find the position of rightmost different bit ; Function to find the position of rightmost set bit in 'n ; to handle edge case when n = 0. ; Function to find the position of rightmost different bit in the binary representations of ' m ' and 'n ; position of ...
import math NEW_LINE ' NEW_LINE def getRightMostSetBit ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return math . log2 ( n & - n ) + 1 NEW_LINE DEDENT ' NEW_LINE def posOfRightMostDiffBit ( m , n ) : NEW_LINE INDENT return getRightMostSetBit ( m ^ n ) NEW_LINE DEDENT m = 52 NEW_LINE ...
Closest ( or Next ) smaller and greater numbers with same number of set bits | Main Function to find next smallest number bigger than n ; Compute c0 and c1 ; If there is no bigger number with the same no . of 1 's ; Driver Code ; input 1 ; input 2
def getNext ( n ) : NEW_LINE INDENT c = n NEW_LINE c0 = 0 NEW_LINE c1 = 0 NEW_LINE while ( ( ( c & 1 ) == 0 ) and ( c != 0 ) ) : NEW_LINE INDENT c0 = c0 + 1 NEW_LINE c >>= 1 NEW_LINE DEDENT while ( ( c & 1 ) == 1 ) : NEW_LINE INDENT c1 = c1 + 1 NEW_LINE c >>= 1 NEW_LINE DEDENT if ( c0 + c1 == 31 or c0 + c1 == 0 ) : NEW...
Count minimum bits to flip such that XOR of A and B equal to C | Python code to find minimum bits to be flip ; If both A [ i ] and B [ i ] are equal ; if A [ i ] and B [ i ] are unequal ; N represent total count of Bits
def totalFlips ( A , B , C , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if A [ i ] == B [ i ] and C [ i ] == '1' : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT elif A [ i ] != B [ i ] and C [ i ] == '0' : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW...
Swap three variables without using temporary variable | Assign c ' s ▁ value ▁ to ▁ a , ▁ a ' s value to b and b 's value to c. ; Store XOR of all in a ; After this , b has value of a [ 0 ] ; After this , c has value of b ; After this , a [ 0 ] has value of c ; Driver code ; Calling Function
def swapThree ( a , b , c ) : NEW_LINE INDENT a [ 0 ] = a [ 0 ] ^ b [ 0 ] ^ c [ 0 ] NEW_LINE b [ 0 ] = a [ 0 ] ^ b [ 0 ] ^ c [ 0 ] NEW_LINE c [ 0 ] = a [ 0 ] ^ b [ 0 ] ^ c [ 0 ] NEW_LINE a [ 0 ] = a [ 0 ] ^ b [ 0 ] ^ c [ 0 ] NEW_LINE DEDENT a , b , c = [ 10 ] , [ 20 ] , [ 30 ] NEW_LINE print ( " Before ▁ swapping ▁ a ▁...
Find Two Missing Numbers | Set 2 ( XOR based solution ) | Function to find two missing numbers in range [ 1 , n ] . This function assumes that size of array is n - 2 and all array elements are distinct ; Get the XOR of all elements in arr [ ] and { 1 , 2 . . n } ; Get a set bit of XOR ( We get the rightmost set bit ) ;...
def findTwoMissingNumbers ( arr , n ) : NEW_LINE INDENT XOR = arr [ 0 ] NEW_LINE for i in range ( 1 , n - 2 ) : NEW_LINE INDENT XOR ^= arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT XOR ^= i NEW_LINE DEDENT set_bit_no = XOR & ~ ( XOR - 1 ) NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ...
Find XOR of two number without using XOR operator | Returns XOR of x and y ; Driver Code
def myXOR ( x , y ) : NEW_LINE INDENT return ( x & ( ~ y ) ) | ( ( ~ x ) & y ) NEW_LINE DEDENT x = 3 NEW_LINE y = 5 NEW_LINE print ( " XOR ▁ is " , myXOR ( x , y ) ) NEW_LINE
Convert a given temperature to another system based on given boiling and freezing points | Function to return temperature in the second thermometer ; Calculate the temperature ; Driver Code
def temp_convert ( F1 , B1 , F2 , B2 , T ) : NEW_LINE INDENT t2 = F2 + ( ( float ) ( B2 - F2 ) / ( B1 - F1 ) * ( T - F1 ) ) NEW_LINE return t2 NEW_LINE DEDENT F1 = 0 NEW_LINE B1 = 100 NEW_LINE F2 = 32 NEW_LINE B2 = 212 NEW_LINE T = 37 NEW_LINE print ( temp_convert ( F1 , B1 , F2 , B2 , T ) ) NEW_LINE
Maximum possible elements which are divisible by 2 | Function to find maximum possible elements which divisible by 2 ; To store count of even numbers ; All even numbers and half of odd numbers ; Driver code ; Function call
def Divisible ( arr , n ) : NEW_LINE INDENT count_even = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT count_even += 1 NEW_LINE DEDENT DEDENT return count_even + ( n - count_even ) // 2 NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( ...
Select a Random Node from a tree with equal probability | Python3 program to Select a Random Node from a tree ; This is used to fill children counts . ; Inserts Children count for each node ; Returns number of children for root ; Helper Function to return a random node ; Returns Random node ; Driver Code ; Creating Abo...
from random import randint NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . children = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getElements ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT ret...
Implement rand3 ( ) using rand2 ( ) | Python3 Program to print 0 , 1 or 2 with equal Probability ; Random Function to that returns 0 or 1 with equal probability ; randint ( 0 , 100 ) function will generate odd or even number [ 1 , 100 ] with equal probability . If rand ( ) generates odd number , the function will retur...
import random NEW_LINE def rand2 ( ) : NEW_LINE INDENT tmp = random . randint ( 1 , 100 ) NEW_LINE return tmp % 2 NEW_LINE DEDENT def rand3 ( ) : NEW_LINE INDENT r = 2 * rand2 ( ) + rand2 ( ) NEW_LINE if r < 3 : NEW_LINE INDENT return r NEW_LINE DEDENT return rand3 ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : ...
Delete leaf nodes with value as x | A utility class to allocate a new node ; deleteleaves ( ) ; inorder ( ) ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def deleteLeaves ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT root . left = deleteLeaves ( root . left ,...
Non | A binary tree node ; Non - recursive function to delete an entrie binary tree ; Base Case ; Create a empty queue for level order traversal ; Do level order traversal starting from root ; Deletes a tree and sets the root as None ; Create a binary tree ; delete entire binary tree
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 _deleteTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE...
Iterative program to Calculate Size of a tree | Node Structure ; Return size of tree ; if tree is empty it will return 0 ; Using level order Traversal . ; when the queue is empty : the pop ( ) method returns null . ; Increment count ; Enqueue left child ; Increment count ; Enqueue right child ; creating a binary tree a...
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 sizeoftree ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE count = 1...
Write a Program to Find the Maximum Depth or Height of a Tree | A binary tree node ; Compute the " maxDepth " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node ; Compute the depth of each subtree ; Use the larger one ; 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 maxDepth ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT lDepth = maxDepth ( n...
Find postorder traversal of BST from preorder traversal | Python3 program for finding postorder traversal of BST from preorder traversal ; Function to find postorder traversal from preorder traversal . ; If entire preorder array is traversed then return as no more element is left to be added to post order array . ; If ...
INT_MIN = - 2 ** 31 NEW_LINE INT_MAX = 2 ** 31 NEW_LINE def findPostOrderUtil ( pre , n , minval , maxval , preIndex ) : NEW_LINE INDENT if ( preIndex [ 0 ] == n ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( pre [ preIndex [ 0 ] ] < minval or pre [ preIndex [ 0 ] ] > maxval ) : NEW_LINE INDENT return NEW_LINE DEDENT ...
Height of binary tree considering even level leaves only | A binary tree node has data , pointer to left child and a pointer to right child ; Base Case ; left stores the result of left subtree , and right stores the result of right subtree ; If both left and right returns 0 , it means there is no valid path till leaf n...
class newNode : 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 heightOfTreeUtil ( root , isEven ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( not root . left and n...
Find Height of Binary Tree represented by Parent array | This functio fills depth of i 'th element in parent[] The depth is filled in depth[i] ; If depth [ i ] is already filled ; If node at index i is root ; If depth of parent is not evaluated before , then evaluate depth of parent first ; Depth of this node is depth ...
def fillDepth ( parent , i , depth ) : NEW_LINE INDENT if depth [ i ] != 0 : NEW_LINE INDENT return NEW_LINE DEDENT if parent [ i ] == - 1 : NEW_LINE INDENT depth [ i ] = 1 NEW_LINE return NEW_LINE DEDENT if depth [ parent [ i ] ] == 0 : NEW_LINE INDENT fillDepth ( parent , parent [ i ] , depth ) NEW_LINE DEDENT depth ...
How to determine if a binary tree is height | A binary tree Node ; function to check if tree is height - balanced or not ; Base condition ; for left and right subtree height allowed values for ( lh - rh ) are 1 , - 1 , 0 ; if we reach here means tree is not height - balanced tree ; function to find height of binary tre...
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 isBalanced ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT lh = height ( root . left ) NEW_LINE rh =...
Find height of a special binary tree whose leaf nodes are connected | Helper function that allocates a new node with the given data and None left and right poers . ; Construct to create a new node ; function to check if given node is a leaf node or node ; If given node ' s ▁ left ' s right is pointing to given node and...
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isLeaf ( node ) : NEW_LINE INDENT return node . left and node . left . right == node and node . right and node . right . left == node NEW_LI...
Diameter of a Binary Tree | A binary tree node ; The function Compute the " height " of a tree . Height is the number of nodes along the longest path from the root node down to the farthest leaf node . ; Base Case : Tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Function t...
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 height ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 + max ( height ( node . left ) , height...
Find if possible to visit every nodes in given Graph exactly once based on given conditions | Function to find print path ; If a [ 0 ] is 1 ; Printing path ; Seeking for a [ i ] = 0 and a [ i + 1 ] = 1 ; Printing path ; If a [ N - 1 ] = 0 ; Driver Code ; Given Input ; Function Call
def findpath ( N , a ) : NEW_LINE INDENT if ( a [ 0 ] ) : NEW_LINE INDENT print ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT if ( a [ i ] == 0 and a [ i + 1 ] ) : NEW_LINE INDENT for j in...
Modify a numeric string to a balanced parentheses by replacements | Function to check if the given string can be converted to a balanced bracket sequence or not ; Check if the first and last characters are equal ; Initialize two variables to store the count of open and closed brackets ; If the current character is same...
def balBracketSequence ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( str [ 0 ] == str [ n - 1 ] ) : NEW_LINE INDENT print ( " No " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT cntForOpen = 0 NEW_LINE cntForClose = 0 NEW_LINE check = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == s...
Diameter of a Binary Tree | A binary tree Node ; utility class to pass height object ; Optimised recursive function to find diameter of binary tree ; to store height of left and right subtree ; base condition - when binary tree is empty ; diameter is also 0 ; ldiameter -- > diameter of left subtree rdiamter -- > diamet...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT class Height : NEW_LINE INDENT def __init ( self ) : NEW_LINE INDENT self . h = 0 NEW_LINE DEDENT DEDENT def diameterOpt ( root , height ) : NEW_LINE INDENT lh...
Diameter of a Binary Tree in O ( n ) [ A new method ] | Tree node structure used in the program ; Function to find height of a tree ; update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; Computes the diameter of binary tree with given root . ;...
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 height ( root , ans ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left_height = height ( root . left , ans ) NEW_LI...
Find postorder traversal of BST from preorder traversal | Run loop from 1 to length of pre ; Prfrom pivot length - 1 to zero ; Prfrom end to pivot length ; Driver Code
def getPostOrderBST ( pre , N ) : NEW_LINE INDENT pivotPoint = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( pre [ 0 ] <= pre [ i ] ) : NEW_LINE INDENT pivotPoint = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( pivotPoint - 1 , 0 , - 1 ) : NEW_LINE INDENT print ( pre [ i ] , end = " ▁ " ) NEW_LI...
Count substrings made up of a single distinct character | Function to count the number of substrings made up of a single distinct character ; Stores the required count ; Stores the count of substrings possible by using current character ; Stores the previous character ; Traverse the string ; If current character is sam...
def countSubstrings ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE subs = 1 NEW_LINE pre = ' ' NEW_LINE for i in s : NEW_LINE INDENT if pre == i : NEW_LINE INDENT subs += 1 NEW_LINE DEDENT else : NEW_LINE INDENT subs = 1 NEW_LINE DEDENT ans += subs NEW_LINE pre = i NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT s = ' geeksfor...
Generate an array from given pairs of adjacent elements | Utility function to find original array ; Map to store all neighbors for each element ; Vector to store original elements ; Stotrs which array elements are visited ; A djacency list to store neighbors of each array element ; Find the first corner element ; Store...
def find_original_array ( A ) : NEW_LINE INDENT mp = [ [ ] for i in range ( 6 ) ] NEW_LINE res = [ ] NEW_LINE visited = { } NEW_LINE for it in A : NEW_LINE INDENT mp [ it [ 0 ] ] . append ( it [ 1 ] ) NEW_LINE mp [ it [ 1 ] ] . append ( it [ 0 ] ) NEW_LINE DEDENT start = 0 NEW_LINE for it in range ( 6 ) : NEW_LINE INDE...
Possible edges of a tree for given diameter , height and vertices | Function to construct the tree ; Special case when d == 2 , only one edge ; Tree is not possible ; Satisfy the height condition by add edges up to h ; Add d - h edges from 1 to satisfy diameter condition ; Remaining edges at vertex 1 or 2 ( d == h ) ; ...
def constructTree ( n , d , h ) : NEW_LINE INDENT if d == 1 : NEW_LINE INDENT if n == 2 and h == 1 : NEW_LINE INDENT print ( "1 ▁ 2" ) NEW_LINE return 0 NEW_LINE DEDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT if d > 2 * h : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return 0 NEW_LINE DEDENT for i in range ( 1...
Smallest element present in every subarray of all possible lengths | Function to add count of numbers in the map for a subarray of length k ; Set to store unique elements ; Add elements to the set ; Adding count in map ; Function to check if there is any number which repeats itself in every subarray of length K ; Check...
def uniqueElements ( arr , start , K , mp ) : NEW_LINE INDENT st = set ( ) ; NEW_LINE for i in range ( K ) : NEW_LINE INDENT st . add ( arr [ start + i ] ) ; NEW_LINE DEDENT for itr in st : NEW_LINE INDENT if itr in mp : NEW_LINE INDENT mp [ itr ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT mp [ itr ] = 1 ; NEW_LINE ...
Deepest right leaf node in a binary tree | Iterative approach | Helper function that allocates a new node with the given data and None left and right poers . ; Constructor to create a new node ; utility function to return level of given node ; create a queue for level order traversal ; traverse until the queue is empty...
class newnode : 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 getDeepestRightLeafNode ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return None NEW_LINE DEDENT q = [ ] NEW_LINE q . appe...
Check if two strings can be made equal by reversing a substring of one of the strings | Function to check if the strings can be made equal or not by reversing a substring of X ; Store the first index from the left which contains unequal characters in both the strings ; Store the first element from the right which conta...
def checkString ( X , Y ) : NEW_LINE INDENT L = - 1 NEW_LINE R = - 1 NEW_LINE for i in range ( len ( X ) ) : NEW_LINE INDENT if ( X [ i ] != Y [ i ] ) : NEW_LINE INDENT L = i NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( len ( X ) - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( X [ i ] != Y [ i ] ) : NEW_LINE INDENT R ...
Maximum length of same indexed subarrays from two given arrays satisfying the given condition | Python3 program for the above approach ; Stores the segment tree node values ; Function to find maximum length of subarray such that sum of maximum element in subarray in brr [ ] and sum of subarray in arr [ ] * K is at most...
import math NEW_LINE seg = [ 0 for x in range ( 10000 ) ] NEW_LINE INT_MIN = int ( - 10000000 ) NEW_LINE def maxLength ( a , b , n , c ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT max_length = int ( 0 ) NEW_LINE low = 0 NEW_LINE high = n NEW_LINE while ( low <= high ) : NEW_LINE INDENT m...
Maximum length of same indexed subarrays from two given arrays satisfying the given condition | Function to find maximum length of subarray such that sum of maximum element in subarray in brr [ ] and sum of subarray in [ ] arr * K is at most C ; Base Case ; Let maximum length be 0 ; Perform Binary search ; Find mid val...
def maxLength ( a , b , n , c ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT max_length = 0 NEW_LINE low = 0 NEW_LINE high = n NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = int ( low + ( high - low ) / 2 ) NEW_LINE if ( possible ( a , b , n , c , mid ) ) : NEW_LINE INDENT max_leng...
Program to find the Nth natural number with exactly two bits set | Set 2 | Function to find the Nth number with exactly two bits set ; Initialize variables ; Initialize the range in which the value of ' a ' is present ; Perform Binary Search ; Find the mid value ; Update the range using the mid value t ; Find b value u...
def findNthNum ( N ) : NEW_LINE INDENT last_num = 0 NEW_LINE left = 1 NEW_LINE right = N NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE t = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( t < N ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT elif ( t == N ) : NEW_LINE INDENT ...
Longest subsequence having maximum sum | Function to find the longest subsequence from the given array with maximum sum ; Stores the largest element of the array ; If Max is less than 0 ; Print the largest element of the array ; Traverse the array ; If arr [ i ] is greater than or equal to 0 ; Print elements of the sub...
def longestSubWithMaxSum ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE if ( Max < 0 ) : NEW_LINE INDENT print ( Max ) NEW_LINE return NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , ...
Check if string S2 can be obtained by appending subsequences of string S1 | Python3 Program to implement the above approach ; Function for finding minimum number of operations ; Stores the length of strings ; Stores frequency of characters in string s ; Update frequencies of character in s ; Traverse string s1 ; If any...
from bisect import bisect , bisect_left , bisect_right NEW_LINE def findMinimumOperations ( s , s1 ) : NEW_LINE INDENT n = len ( s ) NEW_LINE m = len ( s1 ) NEW_LINE frequency = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT frequency [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range (...
Sink Odd nodes in Binary Tree | Helper function to allocates a new node ; Helper function to check if node is leaf node ; A recursive method to sink a tree with odd root This method assumes that the subtrees are already sinked . This method is similar to Heapify of Heap - Sort ; If None or is a leaf , do nothing ; if l...
class newnode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isLeaf ( root ) : NEW_LINE INDENT return ( root . left == None and root . right == None ) NEW_LINE DEDENT def sink ( root ) : NEW_LINE INDEN...
Print first K distinct Moran numbers from a given array | ; Function to calculate the sum of digits of a number ; Stores the sum of digits ; Add the digit to sum ; Remove digit ; Returns the sum of digits ; Function to check if a number is prime or not ; If r has any divisor ; Set r as non - prime ; Function to check ...
import math NEW_LINE def digiSum ( a ) : NEW_LINE INDENT sums = 0 NEW_LINE while ( a != 0 ) : NEW_LINE INDENT sums += a % 10 NEW_LINE a = a // 10 NEW_LINE DEDENT return sums NEW_LINE DEDENT def isPrime ( r ) : NEW_LINE INDENT s = True NEW_LINE for i in range ( 2 , int ( math . sqrt ( r ) ) + 1 ) : NEW_LINE INDENT if ( ...
Number of pairs whose sum is a power of 2 | Set 2 | Python3 program to implement the above approach ; Function to count all pairs whose sum is a power of two ; Stores the frequency of each element of the array ; Update frequency of array elements ; Stores count of required pairs ; Current power of 2 ; Traverse the arra...
from math import pow NEW_LINE def countPair ( arr , n ) : NEW_LINE INDENT m = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ arr [ i ] ] = m . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 31 ) : NEW_LINE INDENT key = int ( pow ( 2 , i ) ) NEW_LINE for j in range ( n ) : NEW_LINE ...
Counting Rock Samples | TCS Codevita 2020 | Function to find the rock samples in the ranges ; Iterate over the ranges ; Driver Code ; Function Call
def findRockSample ( ranges , n , r , arr ) : NEW_LINE INDENT a = [ ] NEW_LINE for i in range ( r ) : NEW_LINE INDENT c = 0 NEW_LINE l , h = ranges [ i ] [ 0 ] , ranges [ i ] [ 1 ] NEW_LINE for val in arr : NEW_LINE INDENT if l <= val <= h : NEW_LINE INDENT c += 1 NEW_LINE DEDENT DEDENT a . append ( c ) NEW_LINE DEDENT...
Depth of the deepest odd level node in Binary Tree | Python3 program to find depth of the deepest odd level node Helper function that allocates a new node with the given data and None left and right poers . ; Constructor to create a new node ; Utility function which returns whether the current node is a leaf or not ; f...
class newNode : 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 isleaf ( curr_node ) : NEW_LINE INDENT return ( curr_node . left == None and curr_node . right == None ) NEW_LINE DEDENT def deepestOddLev...
N digit numbers having difference between the first and last digits as K | Function to store and check the difference of digits ; Base Case ; Last digit of the number to check the difference from the first digit ; Condition to avoid repeated values ; Update the string pt ; Recursive Call ; Update the string pt ; Recurs...
result = [ ] NEW_LINE def findNumbers ( st , prev , n , K ) : NEW_LINE INDENT global result NEW_LINE if ( len ( st ) == n ) : NEW_LINE INDENT result . append ( int ( st ) ) NEW_LINE return NEW_LINE DEDENT if ( len ( st ) == n - 1 ) : NEW_LINE INDENT if ( prev - K >= 0 ) : NEW_LINE INDENT pt = " " NEW_LINE pt += prev - ...
Minimum Number of Bullets required to penetrate all bricks | Function to find the minimum number of bullets required to penetrate all bricks ; Sort the points in ascending order ; Check if there are no points ; Iterate through all the points ; Increase the count ; Return the count ; Driver Code ; Given coordinates of b...
def findMinBulletShots ( points ) : NEW_LINE INDENT for i in range ( len ( points ) ) : NEW_LINE INDENT points [ i ] = points [ i ] [ : : - 1 ] NEW_LINE DEDENT points = sorted ( points ) NEW_LINE for i in range ( len ( points ) ) : NEW_LINE INDENT points [ i ] = points [ i ] [ : : - 1 ] NEW_LINE DEDENT if ( len ( point...
Count array elements that can be maximized by adding any permutation of first N natural numbers | Function to get the count of values that can have the maximum value ; Sort array in decreasing order ; Stores the answer ; mark stores the maximum value till each index i ; Check if arr [ i ] can be maximum ; Update the ma...
def countMaximum ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) ; NEW_LINE count = 0 ; NEW_LINE mark = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( a [ i ] + n >= mark ) ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT mark = max ( mark , a [ i ] + i + 1 ) ; NEW_LINE DEDENT print ( count ) ; NEW_...
Kth character from the Nth string obtained by the given operations | Function to return Kth character from recursive string ; If N is 1 then return A ; Iterate a loop and generate the recursive string ; Update current string ; Change A to B and B to A ; Reverse the previous string ; Return the kth character ; Driver Co...
def findKthChar ( n , k ) : NEW_LINE INDENT prev = " A " NEW_LINE cur = " " NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return ' A ' NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT cur = prev + " B " NEW_LINE temp1 = [ y for y in prev ] NEW_LINE for i in range ( len ( prev ) ) : NEW_LINE INDENT if ( temp1 [...
Maximize length of subarray of equal elements by performing at most K increment operations | Python3 program for above approach ; Function to find the maximum length of subarray of equal elements after performing at most K increments ; Length of array ; Stores the size of required subarray ; Starting po of a window ; S...
from collections import deque NEW_LINE def maxSubarray ( a , k ) : NEW_LINE INDENT n = len ( a ) NEW_LINE answer = 0 NEW_LINE start = 0 NEW_LINE s = 0 NEW_LINE dq = deque ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE while ( len ( dq ) > 0 and a [ dq [ - 1 ] ] <= x ) : NEW_LINE INDENT dq . po...
Find depth of the deepest odd level leaf node | A Binary tree node ; A recursive function to find depth of the deepest odd level leaf node ; Base Case ; If this node is leaf and its level is odd , return its level ; If not leaf , return the maximum value from left and right subtrees ; Main function which calculates the...
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 depthOfOddLeafUtil ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . left is None and r...
Check if an array can be split into subarrays with GCD exceeding K | Function to check if it is possible to split an array into subarrays having GCD at least K ; Iterate over the array arr [ ] ; If the current element is less than or equal to k ; If no array element is found to be less than or equal to k ; Driver Code ...
def canSplitArray ( arr , n , k ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] <= k ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT return " Yes " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 6 , 1 , 8 , 16 ] NEW_LINE N = len ( arr ) NEW_LINE K = ...
Smallest subarray from a given Array with sum greater than or equal to K | Set 2 | Function to find the smallest subarray sum greater than or equal to target ; Base Case ; If sum of the array is less than target ; If target is equal to the sum of the array ; Required condition ; Driver Code
def smallSumSubset ( data , target , maxVal ) : NEW_LINE INDENT if target <= 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif sum ( data ) < target : NEW_LINE INDENT return maxVal NEW_LINE DEDENT elif sum ( data ) == target : NEW_LINE INDENT return len ( data ) NEW_LINE DEDENT elif data [ 0 ] >= target : NEW_LINE INDE...
Maximize cost obtained by removal of substrings " pr " or " rp " from a given String | Function to maintain the case , X >= Y ; To maintain X >= Y ; Replace ' p ' to 'r ; Replace ' r ' to ' p ' . ; Function to return the maximum cost ; Stores the length of the string ; To maintain X >= Y . ; Stores the maximum cost ; S...
def swapXandY ( str , X , Y ) : NEW_LINE INDENT N = len ( str ) NEW_LINE X , Y = Y , X NEW_LINE for i in range ( N ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( str [ i ] == ' p ' ) : NEW_LINE INDENT str [ i ] = ' r ' NEW_LINE DEDENT elif ( str [ i ] == ' r ' ) : NEW_LINE INDENT str [ i ] = ' p ' NEW_LINE DEDENT DEDENT de...
Check if an array contains only one distinct element | Function to find if the array contains only one distinct element ; Assume first element to be the unique element ; Traversing the array ; If current element is not equal to X then break the loop and print No ; Compare and print the result ; Driver Code ; Function c...
def uniqueElement ( arr ) : NEW_LINE INDENT x = arr [ 0 ] NEW_LINE flag = 1 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] != x ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print (...
Maximum Count of pairs having equal Sum based on the given conditions | Function to find the maximum count of pairs having equal sum ; Size of the array ; Iterate through evey sum of pairs possible from the given array ; Count of pairs with given sum ; Check for a possible pair ; Update count of possible pair ; Update ...
def maxCount ( freq , maxi , mini ) : NEW_LINE INDENT n = len ( freq ) - 1 NEW_LINE ans = 0 NEW_LINE sum = 2 * mini NEW_LINE while sum <= 2 * maxi : NEW_LINE INDENT possiblePair = 0 NEW_LINE for firElement in range ( 1 , ( sum + 1 ) // 2 ) : NEW_LINE INDENT if ( sum - firElement <= maxi ) : NEW_LINE INDENT possiblePair...
Maximum Subarray Sum possible by replacing an Array element by its Square | Function to find the maximum subarray sum possible ; Stores sum without squaring ; Stores sum squaring ; Stores the maximum subarray sum ; Either extend the subarray or start a new subarray ; Either extend previous squared subarray or start a n...
def getMaxSum ( a , n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( 2 ) ] for y in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = a [ 0 ] NEW_LINE dp [ 0 ] [ 1 ] = a [ 0 ] * a [ 0 ] NEW_LINE max_sum = max ( dp [ 0 ] [ 0 ] , dp [ 0 ] [ 1 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = max ( a [ i ] ,...
Smallest Subarray with Sum K from an Array | Python3 program to implement the above approach ; Function to find the length of the smallest subarray with sum K ; Stores the frequency of prefix sums in the array ; Initialize ln ; If sum of array till i - th index is less than K ; No possible subarray exists till i - th i...
from collections import defaultdict NEW_LINE import sys NEW_LINE def subArraylen ( arr , n , K ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE mp [ arr [ 0 ] ] = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] + arr [ i - 1 ] NEW_LINE mp [ arr [ i ] ] = i NEW_LINE DEDENT ln = sy...
Find depth of the deepest odd level leaf node | Python3 program to find depth of the deepest odd level leaf node of binary tree ; tree node returns a new tree Node ; return max odd number depth of leaf node ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete level ; ch...
INT_MAX = 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 maxOddLevelDepth ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = [ ] NEW_LINE q . a...
Nth Term of a Fibonacci Series of Primes formed by concatenating pairs of Primes in a given range | Stores at each index if it 's a prime or not ; Sieve of Eratosthenes to generate all possible primes ; If p is a prime ; Set all multiples of p as non - prime ; Function to generate the required Fibonacci Series ; Stores...
prime = [ True for i in range ( 100001 ) ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT p = 2 NEW_LINE while ( p * p <= 100000 ) : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 100001 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DED...
Count of Array elements greater than all elements on its left and next K elements on its right | Python3 program to implement the above approach ; Function to print the count of Array elements greater than all elements on its left and next K elements on its right ; Iterate over the array ; If the stack is not empty and...
import sys NEW_LINE def countElements ( arr , n , k ) : NEW_LINE INDENT s = [ ] NEW_LINE next_greater = [ n ] * ( n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( i ) NEW_LINE continue NEW_LINE DEDENT while ( len ( s ) != 0 and arr [ s [ - 1 ] ] < arr [ i ] ) ...
Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Python program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences ...
def maxLengthOf1s ( arr , n ) : NEW_LINE INDENT prefix = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i - 2 ] == 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT prefix [ i ] = 0 NEW_LINE DEDENT DEDENT suffix = [ 0 for i in ran...
Minimum number of operations required to obtain a given Binary String | Function to find the minimum number of operations required to obtain the string s ; Iterate the string s ; If first occurrence of 1 is found ; Mark the index ; Base case : If no 1 occurred ; No operations required ; Stores the character for which l...
def minOperations ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE pos = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( pos == - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT last = 1 NEW_LINE ans = 1 NEW_LINE for i i...
Find the Deepest Node in a Binary Tree | A Binary Tree Node Utility function to create a new tree node ; maxLevel : keeps track of maximum level seen so far . res : Value of deepest node so far . level : Level of root ; Update level and resue ; Returns value of deepest node ; Initialze result and max level ; Updates va...
class newNode : 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 self . visited = False NEW_LINE DEDENT DEDENT def find ( root , level , maxLevel , res ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT level += 1 ...
Count the number of clumps in the given Array | Function to count the number of clumps in the given array arr [ ] ; Initialise count of clumps as 0 ; Traverse the arr [ ] ; Whenever a sequence of same value is encountered ; Return the count of clumps ; Driver Code ; length of the given array arr [ ] ; Function Call
def countClumps ( arr , N ) : NEW_LINE INDENT clumps = 0 NEW_LINE i = 0 NEW_LINE while ( i < N - 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE while ( i + 1 < N and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT flag = 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( flag ) : NEW_LINE INDENT clumps += 1 NEW_LINE DEDENT i += 1 NEW_LINE...
Find if string is K | Find if string is K - Palindrome or not using all characters exactly once Python 3 program to find if string is K - Palindrome or not using all characters exactly once ; when size of string is less than k ; when size of string is equal to k ; when size of string is greater than k to store the freq...
def iskPalindromesPossible ( s , k ) : NEW_LINE INDENT if ( len ( s ) < k ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE return NEW_LINE DEDENT if ( len ( s ) == k ) : NEW_LINE INDENT print ( " Possible " ) NEW_LINE return NEW_LINE DEDENT freq = dict . fromkeys ( s , 0 ) NEW_LINE for i in range ( len ( s ) )...
Find the Deepest Node in a Binary Tree | A tree node with constructor ; Utility function to find height of a tree , rooted at ' root ' . ; levels : current Level Utility function to print all nodes at a given level . ; Driver Code ; Calculating height of tree ; Printing the deepest node
class new_Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def height ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT leftHt = height ( root . left ) NEW_LINE rightHt = height ( ...
Check if an array is sorted and rotated using Binary Search | Function to return the index of the pivot ; Base cases ; Check if element at ( mid - 1 ) is pivot Consider the cases like { 4 , 5 , 1 , 2 , 3 } ; Decide whether we need to go to the left half or the right half ; Function to check if a given array is sorted r...
def findPivot ( arr , low , high ) : NEW_LINE INDENT if ( high < low ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( high == low ) : NEW_LINE INDENT return low ; NEW_LINE DEDENT mid = ( low + high ) // 2 ; NEW_LINE if ( mid < high and arr [ mid + 1 ] < arr [ mid ] ) : NEW_LINE INDENT return mid ; NEW_LINE DEDENT ...
Find the Deepest Node in a Binary Tree | A Python3 program to find value of the deepest node in a given binary tree by method 3 ; A tree node with constructor ; constructor ; Funtion to return the deepest node ; Creating a Queue ; Iterates untill queue become empty ; Driver Code
from collections import deque NEW_LINE class new_Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def deepestNode ( root ) : NEW_LINE INDENT node = None NEW_LINE if root == None : NEW_LINE INDENT return 0 NEW_LINE DE...
Find a distinct pair ( x , y ) in given range such that x divides y | Function to return the possible pair ; ans1 , ans2 store value of x and y respectively ; Driver Code
def findpair ( l , r ) : NEW_LINE INDENT ans1 = l NEW_LINE ans2 = 2 * l NEW_LINE print ( ans1 , " , ▁ " , ans2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l , r = 1 , 10 NEW_LINE findpair ( l , r ) NEW_LINE DEDENT
Jump in rank of a student after updating marks | Function to print the name of student who stood first after updation in rank ; Array of students ; Store the name of the student ; Update the marks of the student ; Store the current rank of the student ; Print the name and jump in rank ; Names of the students ; Marks of...
def nameRank ( names , marks , updates , n ) : NEW_LINE INDENT x = [ [ 0 for j in range ( 3 ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x [ i ] [ 0 ] = names [ i ] NEW_LINE x [ i ] [ 1 ] = marks [ i ] + updates [ i ] NEW_LINE x [ i ] [ 2 ] = i + 1 NEW_LINE DEDENT highest = x [ 0 ] NEW_LIN...
Integers from the range that are composed of a single distinct digit | Function to return the count of digits of a number ; Function to return a number that contains only digit ' d ' repeated exactly count times ; Function to return the count of integers that are composed of a single distinct digit only ; Count of digi...
def countDigits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE n //= 10 NEW_LINE DEDENT return count NEW_LINE DEDENT def getDistinct ( d , count ) : NEW_LINE INDENT num = 0 NEW_LINE count = pow ( 10 , count - 1 ) NEW_LINE while ( count > 0 ) : NEW_LINE INDENT num += ( c...
Check if a pair with given absolute difference exists in a Matrix | Python 3 program to check for pairs with given difference exits in the matrix or not ; Function to check if a pair with given difference exist in the matrix ; Store elements in a hash ; Loop to iterate over the elements of the matrix ; Input matrix ; g...
N = 4 NEW_LINE M = 4 NEW_LINE def isPairWithDiff ( mat , k ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if mat [ i ] [ j ] > k : NEW_LINE INDENT m = mat [ i ] [ j ] - k NEW_LINE if m in s : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT else ...
Next Smaller Element | prints element and NSE pair for all elements of arr [ ] of size n ; push the first element to stack ; iterate for rest of the elements ; if stack is not empty , then pop an element from stack . If the popped element is greater than next , then a ) print the pair b ) keep popping while elements ar...
def printNSE ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE mp = { } NEW_LINE s . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( len ( s ) == 0 ) : NEW_LINE INDENT s . append ( arr [ i ] ) NEW_LINE continue NEW_LINE DEDENT while ( len ( s ) != 0 and s [ - 1 ] > arr [ i ] ) : NEW_LINE INDE...
Deepest left leaf node in a binary tree | iterative approach | Helper function that allocates a new node with the given data and None left and right poers . ; Constructor to create a new node ; utility function to return deepest left leaf node ; create a queue for level order traversal ; traverse until the queue is emp...
class newnode : 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 getDeepestLeftLeafNode ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return None NEW_LINE DEDENT q = [ ] NEW_LINE q . appen...
Find all possible binary trees with given Inorder Traversal | Node Structure ; Utility to create a new node ; A utility function to do preorder traversal of BST ; Function for constructing all possible trees with given inorder traversal stored in an array from arr [ start ] to arr [ end ] . This function returns a vect...
class Node : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . key = item NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def preorder ( root ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT print root . key , NEW_LINE preorder ( root . left ) NEW_LINE preord...
Check if a string is suffix of another | Python3 program to find if a string is suffix of another ; Test case - sensitive implementation of endsWith function
if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 = " geeks " ; NEW_LINE s2 = " geeksforgeeks " ; NEW_LINE result = s2 . endswith ( s1 ) ; NEW_LINE if ( result ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Maximum elements that can be made equal with k updates | Function to calculate the maximum number of equal elements possible with atmost K increment of values . Here we have done sliding window to determine that whether there are x number of elements present which on increment will become equal . The loop here will run...
def ElementsCalculationFunc ( pre , maxx , x , k , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = x NEW_LINE while j <= n : NEW_LINE INDENT if ( x * maxx [ j ] - ( pre [ j ] - pre [ i ] ) <= k ) : NEW_LINE INDENT return True NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT return False NEW_LINE DEDENT def MaxNumberOfEl...
Count palindromic characteristics of a String | Python program which counts different palindromic characteristics of a string . ; function which checks whether a substr [ i . . j ] of a given is a palindrome or not . ; P [ i , j ] = True if substr [ i . . j ] is palindrome , else False ; palindrome of single length ; p...
MAX_STR_LEN = 1000 ; NEW_LINE P = [ [ 0 for x in range ( MAX_STR_LEN ) ] for y in range ( MAX_STR_LEN ) ] ; NEW_LINE for i in range ( 0 , MAX_STR_LEN ) : NEW_LINE INDENT for j in range ( 0 , MAX_STR_LEN ) : NEW_LINE INDENT P [ i ] [ j ] = False ; NEW_LINE DEDENT DEDENT Kpal = [ 0 ] * MAX_STR_LEN ; NEW_LINE def checkSub...
Print number in ascending order which contains 1 , 2 and 3 in their digits . | convert all numbers to strings ; check if each number in the list has 1 , 2 and 3 ; sort all the numbers ; Driver Code
def printNumbers ( numbers ) : NEW_LINE INDENT numbers = map ( str , numbers ) NEW_LINE result = [ ] NEW_LINE for num in numbers : NEW_LINE INDENT if ( '1' in num and '2' in num and '3' in num ) : NEW_LINE INDENT result . append ( num ) NEW_LINE DEDENT DEDENT if not result : NEW_LINE INDENT result = [ ' - 1' ] NEW_LINE...