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 equal to zero ; Driver Code
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 DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT array = [ 1 , 2 , 4 ] NEW_LINE length = len ( array ) NEW_LINE N = 3 NEW_LINE isSubsetAndZero ( array , length , N ) 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 INDENT print ( " Even ▁ Parity " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd Parity " ) ; NEW_LINE DEDENT if ( findParity ( 13 ) == 0 ) : NEW_LINE INDENT print ( " Even ▁ Parity " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Odd ▁ Parity " ) ; NEW_LINE DEDENT
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 in the range l to r and nowhere else ; if both are equal , then all bits are set in the given range ; else all bits are not set ; function to check whether all the bits in the given range of two numbers are complement of each other ; Driver Code
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 ^ b NEW_LINE return allBitsSetInTheGivenRange ( xor_value , l , r ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 10 NEW_LINE b = 5 NEW_LINE l = 1 NEW_LINE r = 3 NEW_LINE if ( bitsAreComplement ( a , b , l , r ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 from left is set take ' + ' sign ; Right shift to check if jth bit is set or not ; re - initialize ; Iterate in the array elements ; If the jth from left is set ; right shift ; Driver code
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_LINE DEDENT num = num >> 1 NEW_LINE DEDENT if ( sum % m == 0 ) : NEW_LINE INDENT num = 1 << ( n - 1 ) NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( ( i & num ) > 0 ) : NEW_LINE INDENT print ( " + " , a [ j ] , end = " ▁ " , sep = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " - " , a [ j ] , end = " ▁ " , sep = " " ) NEW_LINE DEDENT num = num >> 1 NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT DEDENT DEDENT a = [ 3 , 5 , 6 , 8 ] NEW_LINE n = len ( a ) NEW_LINE m = 5 NEW_LINE printCombinations ( a , n , m ) NEW_LINE
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 ( n ) : NEW_LINE INDENT temp = __builtin_popcount ( n ) NEW_LINE count = 0 NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT if ( temp == __builtin_popcount ( i ) ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT n = 4 NEW_LINE print ( smallerNumsWithSameSetBits ( n ) ) NEW_LINE
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 the tree ; level of child is always 0 ; Recursive call ; Increase the level of every parent , which is level of child + 1 ; If the parent is at odd level , then do a bitwise OR ; If the parent is at even level , then do a bitwise XOR ; Function that updates the tree ; If it is a leaf and the leaf which is to be updated ; out of range ; not a leaf then recurse ; recursive call ; check if the parent is at odd or even level and perform OR or XOR according to that ; Function that assigns value to a [ index ] and calls update function to update the tree ; Driver Code ; builds the tree ; 1 st query ; 2 nd query
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 + 1 , a ) NEW_LINE constructTree ( mid + 1 , high , 2 * pos + 2 , a ) NEW_LINE level [ pos ] = level [ 2 * pos + 1 ] + 1 NEW_LINE if level [ pos ] & 1 : NEW_LINE INDENT tree [ pos ] = tree [ 2 * pos + 1 ] | tree [ 2 * pos + 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT tree [ pos ] = tree [ 2 * pos + 1 ] ^ tree [ 2 * pos + 2 ] NEW_LINE DEDENT DEDENT def update ( low , high , pos , index , a ) : NEW_LINE INDENT if low == high and low == index : NEW_LINE INDENT tree [ pos ] = a [ low ] NEW_LINE return NEW_LINE DEDENT if index < low or index > high : NEW_LINE INDENT return NEW_LINE DEDENT if low != high : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE update ( low , mid , 2 * pos + 1 , index , a ) NEW_LINE update ( mid + 1 , high , 2 * pos + 2 , index , a ) NEW_LINE if level [ pos ] & 1 : NEW_LINE INDENT tree [ pos ] = tree [ 2 * pos + 1 ] | tree [ 2 * pos + 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT tree [ pos ] = tree [ 2 * pos + 1 ] ^ tree [ 2 * pos + 2 ] NEW_LINE DEDENT DEDENT DEDENT def updateValue ( index , value , a , n ) : NEW_LINE INDENT a [ index ] = value NEW_LINE update ( 0 , n - 1 , 0 , index , a ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 4 , 5 , 6 ] NEW_LINE n = len ( a ) NEW_LINE constructTree ( 0 , n - 1 , 0 , a ) NEW_LINE index , value = 0 , 2 NEW_LINE updateValue ( index , value , a , n ) NEW_LINE print ( tree [ 0 ] ) NEW_LINE index , value = 3 , 5 NEW_LINE updateValue ( index , value , a , n ) NEW_LINE print ( tree [ 0 ] ) NEW_LINE DEDENT
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 ( evenbitsetnumber ( n ) ) NEW_LINE
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 NEW_LINE if ( n & 1 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE DEDENT return n NEW_LINE DEDENT def setallevenbits ( n ) : NEW_LINE INDENT return n | getevenbits ( n ) NEW_LINE DEDENT / * Driver code * / NEW_LINE n = 10 NEW_LINE print ( setallevenbits ( n ) ) NEW_LINE
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 ( oddbitsetnumber ( n ) ) NEW_LINE
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 set bits number ; set all odd bits here ; take OR with odd set bits number ; Driver Program
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 NEW_LINE n |= n >> 16 NEW_LINE if ( ( n & 1 ) == 0 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE DEDENT return n NEW_LINE DEDENT def setalloddbits ( n ) : NEW_LINE INDENT return n | getevenbits ( n ) NEW_LINE DEDENT n = 10 NEW_LINE print ( setalloddbits ( n ) ) NEW_LINE
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 ; generate next number having alternate bit pattern ; if true then break ; display ; Driven code
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 < curr_num ) : NEW_LINE INDENT break NEW_LINE DEDENT print ( curr_num ) NEW_LINE DEDENT DEDENT n = 50 NEW_LINE printNumHavingAltBitPatrn ( n ) NEW_LINE
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 same position in each element . ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; Driver code
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 = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT print ( " The ▁ unique ▁ pair ▁ is ▁ ( " , x , " , ▁ " , y , " ) " , sep = " " ) NEW_LINE DEDENT a = [ 6 , 1 , 3 , 5 , 1 , 3 , 7 , 6 ] NEW_LINE n = len ( a ) NEW_LINE findUniquePair ( a , n ) NEW_LINE
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 Code
' 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 rightOnesPattern = ( rightOnesPattern ) // rightOne NEW_LINE rightOnesPattern >>= 2 NEW_LINE next = nextHigherOneBit | rightOnesPattern NEW_LINE DEDENT return next NEW_LINE DEDENT def mthSmallestWithKSetBits ( m , k ) : NEW_LINE INDENT num = ( 1 << k ) - 1 NEW_LINE for i in range ( 1 , m ) : NEW_LINE INDENT num = nxtHighWithNumOfSetBits ( num ) NEW_LINE DEDENT return num NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 6 NEW_LINE k = 4 NEW_LINE print ( mthSmallestWithKSetBits ( m , k ) ) NEW_LINE DEDENT
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 compare bits ; Compare left and right bits and converge ; Start from 1 , traverse through all the integers ; If we reach n , break the loop ; Driver code ; Function Call
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 isBinPalindrome ( x ) : NEW_LINE INDENT l = leftmostSetBit ( x ) NEW_LINE r = 1 NEW_LINE while ( l > r ) : NEW_LINE INDENT if ( isKthBitSet ( x , l ) != isKthBitSet ( x , r ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT return 1 NEW_LINE DEDENT def findNthPalindrome ( n ) : NEW_LINE INDENT pal_count = 0 NEW_LINE i = 0 NEW_LINE for i in range ( 1 , INT_MAX + 1 ) : NEW_LINE INDENT if ( isBinPalindrome ( i ) ) : NEW_LINE INDENT pal_count += 1 NEW_LINE DEDENT if ( pal_count == n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 9 NEW_LINE print ( findNthPalindrome ( n ) ) NEW_LINE DEDENT
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 rightmost different bit ; Driver code
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 n = 4 NEW_LINE print ( " position ▁ = ▁ " , int ( posOfRightMostDiffBit ( m , n ) ) ) 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_LINE INDENT return - 1 NEW_LINE DEDENT return n + ( 1 << c0 ) + ( 1 << ( c1 - 1 ) ) - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE print ( getNext ( n ) ) NEW_LINE n = 8 NEW_LINE print ( getNext ( n ) ) NEW_LINE DEDENT
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_LINE DEDENT N = 5 NEW_LINE a = "10100" NEW_LINE b = "00010" NEW_LINE c = "10011" NEW_LINE print ( totalFlips ( a , b , c , N ) ) NEW_LINE
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 ▁ = ▁ " , a [ 0 ] , " , ▁ b ▁ = ▁ " , b [ 0 ] , " , ▁ c ▁ = ▁ " , c [ 0 ] ) NEW_LINE swapThree ( a , b , c ) NEW_LINE print ( " After ▁ swapping ▁ a ▁ = ▁ " , a [ 0 ] , " , ▁ b ▁ = ▁ " , b [ 0 ] , " , ▁ c ▁ = ▁ " , c [ 0 ] ) NEW_LINE
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 ) ; Now divide elements in two sets by comparing rightmost set bit of XOR with bit at same position in each element . ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; XOR of first set in arr [ ] and { 1 , 2 , ... n } ; XOR of second set in arr [ ] and { 1 , 2 , ... n } ; Driver program to test above function ; Range of numbers is 2 plus size of array
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 ( 0 , n - 2 ) : NEW_LINE INDENT if arr [ i ] & set_bit_no : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if i & set_bit_no : NEW_LINE INDENT x = x ^ i NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ i NEW_LINE DEDENT DEDENT print ( " Two Missing Numbers are % d % d " % ( x , y ) ) NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 6 ] NEW_LINE n = 2 + len ( arr ) NEW_LINE findTwoMissingNumbers ( arr , n ) NEW_LINE
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 ( Divisible ( arr , n ) ) NEW_LINE
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 Above Tree
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 return 0 NEW_LINE DEDENT return ( getElements ( root . left ) + getElements ( root . right ) + 1 ) NEW_LINE DEDENT def insertChildrenCount ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT root . children = getElements ( root ) - 1 NEW_LINE insertChildrenCount ( root . left ) NEW_LINE insertChildrenCount ( root . right ) NEW_LINE DEDENT def children ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return root . children + 1 NEW_LINE DEDENT def randomNodeUtil ( root , count ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if count == children ( root . left ) : NEW_LINE INDENT return root . data NEW_LINE DEDENT if count < children ( root . left ) : NEW_LINE INDENT return randomNodeUtil ( root . left , count ) NEW_LINE DEDENT return randomNodeUtil ( root . right , count - children ( root . left ) - 1 ) NEW_LINE DEDENT def randomNode ( root ) : NEW_LINE INDENT count = randint ( 0 , root . children ) NEW_LINE return randomNodeUtil ( root , count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT 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 . right = Node ( 50 ) NEW_LINE root . right . left = Node ( 60 ) NEW_LINE root . right . right = Node ( 70 ) NEW_LINE insertChildrenCount ( root ) NEW_LINE print ( " A ▁ Random ▁ Node ▁ From ▁ Tree ▁ : " , randomNode ( root ) ) NEW_LINE DEDENT
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 return 1 else it will return 0 ; Random Function to that returns 0 , 1 or 2 with equal probability 1 with 75 % ; returns 0 , 1 , 2 or 3 with 25 % probability ; Driver code to test above functions
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 _ _ ' : NEW_LINE INDENT for i in range ( 100 ) : NEW_LINE INDENT print ( rand3 ( ) , end = " " ) NEW_LINE DEDENT DEDENT
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 , x ) NEW_LINE root . right = deleteLeaves ( root . right , x ) NEW_LINE if ( root . data == x and root . left == None and root . right == None ) : NEW_LINE INDENT return None NEW_LINE DEDENT return root NEW_LINE DEDENT def inorder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT inorder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 3 ) NEW_LINE root . right = newNode ( 10 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 1 ) NEW_LINE root . right . right = newNode ( 3 ) NEW_LINE root . right . right . left = newNode ( 3 ) NEW_LINE root . right . right . right = newNode ( 3 ) NEW_LINE deleteLeaves ( root , 3 ) NEW_LINE print ( " Inorder ▁ traversal ▁ after ▁ deletion ▁ : ▁ " ) NEW_LINE inorder ( root ) NEW_LINE DEDENT
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 while ( len ( q ) > 0 ) : NEW_LINE INDENT node = q . pop ( 0 ) NEW_LINE if node . left is not None : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT node = None NEW_LINE DEDENT return node NEW_LINE DEDENT def deleteTree ( node_ref ) : NEW_LINE INDENT node_ref = _deleteTree ( node_ref ) NEW_LINE return node_ref NEW_LINE DEDENT root = Node ( 15 ) NEW_LINE root . left = Node ( 10 ) NEW_LINE root . right = Node ( 20 ) NEW_LINE root . left . left = Node ( 8 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . right . left = Node ( 16 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE root = deleteTree ( 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 and entering the nodes
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 NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT root = q . pop ( 0 ) NEW_LINE if ( root . left ) : NEW_LINE INDENT count += 1 NEW_LINE q . append ( root . left ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT count += 1 NEW_LINE q . append ( root . right ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( sizeoftree ( root ) ) NEW_LINE
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 ( node . left ) NEW_LINE rDepth = maxDepth ( node . right ) NEW_LINE if ( lDepth > rDepth ) : NEW_LINE INDENT return lDepth + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return rDepth + 1 NEW_LINE DEDENT DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( " Height ▁ of ▁ tree ▁ is ▁ % d " % ( maxDepth ( root ) ) ) NEW_LINE
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 array element does not lie in range specified , then it is not part of current subtree . ; Store current value , to be printed later , after printing left and right subtrees . Increment preIndex to find left and right subtrees , and pass this updated value to recursive calls . ; All elements with value between minval and val lie in left subtree . ; All elements with value between val and maxval lie in right subtree . ; Function to find postorder traversal . ; To store index of element to be traversed next in preorder array . This is passed by reference to utility function . ; Driver Code ; Calling function
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 val = pre [ preIndex [ 0 ] ] NEW_LINE preIndex [ 0 ] += 1 NEW_LINE findPostOrderUtil ( pre , n , minval , val , preIndex ) NEW_LINE findPostOrderUtil ( pre , n , val , maxval , preIndex ) NEW_LINE print ( val , end = " ▁ " ) NEW_LINE DEDENT def findPostOrder ( pre , n ) : NEW_LINE INDENT preIndex = [ 0 ] NEW_LINE findPostOrderUtil ( pre , n , INT_MIN , INT_MAX , preIndex ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT pre = [ 40 , 30 , 35 , 80 , 100 ] NEW_LINE n = len ( pre ) NEW_LINE findPostOrder ( pre , n ) 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 node ; Driver Code ; Let us create binary tree shown in above diagram
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 not root . right ) : NEW_LINE INDENT if ( isEven ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT left = heightOfTreeUtil ( root . left , not isEven ) NEW_LINE right = heightOfTreeUtil ( root . right , not isEven ) NEW_LINE if ( left == 0 and right == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 1 + max ( left , right ) ) NEW_LINE DEDENT def heightOfTree ( root ) : NEW_LINE INDENT return heightOfTreeUtil ( root , False ) 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 . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . left . right . left = newNode ( 6 ) NEW_LINE print ( " Height ▁ of ▁ tree ▁ is " , heightOfTree ( root ) ) NEW_LINE DEDENT
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 of parent plus 1 ; This function reutns height of binary tree represented by parent array ; Create an array to store depth of all nodes and initialize depth of every node as 0 Depth of root is 1 ; fill depth of all nodes ; The height of binary tree is maximum of all depths . Find the maximum in depth [ ] and assign it to ht ; int parent [ ] = { 1 , 5 , 5 , 2 , 2 , - 1 , 3 } ;
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 [ i ] = depth [ parent [ i ] ] + 1 NEW_LINE DEDENT def findHeight ( parent ) : NEW_LINE INDENT n = len ( parent ) NEW_LINE depth = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT fillDepth ( parent , i , depth ) NEW_LINE DEDENT ht = depth [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ht = max ( ht , depth [ i ] ) NEW_LINE DEDENT return ht NEW_LINE DEDENT parent = [ - 1 , 0 , 0 , 1 , 1 , 3 , 5 ] NEW_LINE print " Height ▁ is ▁ % d " % ( findHeight ( parent ) ) NEW_LINE
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 tree ; base condition when binary tree is empty ; If tree is not empty then height = 1 + max of left height and right heights ; Driver function to test the 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 isBalanced ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT lh = height ( root . left ) NEW_LINE rh = height ( root . right ) NEW_LINE if ( abs ( lh - rh ) <= 1 ) and isBalanced ( root . left ) is True and isBalanced ( root . right ) is True : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def height ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return max ( height ( root . left ) , height ( root . right ) ) + 1 NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . left . left . left = Node ( 8 ) NEW_LINE if isBalanced ( root ) : NEW_LINE INDENT print ( " Tree ▁ is ▁ balanced " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Tree ▁ is ▁ not ▁ balanced " ) NEW_LINE DEDENT
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 its right ' s ▁ left ▁ is ▁ pointing ▁ to ▁ the ▁ node ▁ itself ▁ ▁ then ▁ it ' s a leaf ; Compute the height of a tree -- the number of Nodes along the longest path from the root node down to the farthest leaf node . ; if node is None , return 0 ; if node is a leaf node , return 1 ; compute the depth of each subtree and take maximum ; Driver Code ; Given tree contains 3 leaf nodes ; create circular doubly linked list out of leaf nodes of the tree set next pointer of linked list ; set prev pointer of linked list ; calculate height of the tree
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_LINE DEDENT def maxDepth ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( isLeaf ( node ) ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 1 + max ( maxDepth ( node . left ) , maxDepth ( node . right ) ) 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 . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . left . left . left = newNode ( 6 ) NEW_LINE L1 = root . left . left . left NEW_LINE L2 = root . left . right NEW_LINE L3 = root . right NEW_LINE L1 . right = L2 NEW_LINE L2 . right = L3 NEW_LINE L3 . right = L1 NEW_LINE L3 . left = L2 NEW_LINE L2 . left = L1 NEW_LINE L1 . left = L3 NEW_LINE print ( " Height ▁ of ▁ tree ▁ is ▁ " , maxDepth ( root ) ) NEW_LINE DEDENT
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 to get the diameter of a binary tree ; Base Case when tree is empty ; Get the height of left and right sub - trees ; Get the diameter of left and right sub - trees ; Return max of the following tree : 1 ) Diameter of left subtree 2 ) Diameter of right subtree 3 ) Height of left subtree + height of right subtree + 1 ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT 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 ( node . right ) ) NEW_LINE DEDENT def diameter ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT lheight = height ( root . left ) NEW_LINE rheight = height ( root . right ) NEW_LINE ldiameter = diameter ( root . left ) NEW_LINE rdiameter = diameter ( root . right ) NEW_LINE return max ( lheight + rheight + 1 , max ( ldiameter , rdiameter ) ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( diameter ( root ) ) NEW_LINE
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 range ( 1 , i + 1 , 1 ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT print ( N + 1 , end = " ▁ " ) ; NEW_LINE for j in range ( i + 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( j , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( N + 1 , end = " ▁ " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE arr = [ 0 , 1 , 0 ] NEW_LINE findpath ( N , arr ) NEW_LINE DEDENT
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 as the first character ; If the current character is same as the last character ; If count of open brackets becomes less than 0 ; Print the new string ; If the current character is same as the first character ; If bracket sequence is not balanced ; Check for unbalanced bracket sequence ; Print the sequence ; Given Input ; Function Call
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 ] == str [ 0 ] ) : NEW_LINE INDENT cntForOpen += 1 NEW_LINE DEDENT elif str [ i ] == str [ n - 1 ] : NEW_LINE INDENT cntForOpen -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntForOpen += 1 NEW_LINE DEDENT if ( cntForOpen < 0 ) : NEW_LINE INDENT check = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( check and cntForOpen == 0 ) : NEW_LINE INDENT print ( " Yes , ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ n - 1 ] ) : NEW_LINE INDENT print ( ' ) ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ( ' , end = " " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT cntForClose += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntForClose -= 1 NEW_LINE DEDENT if ( cntForClose < 0 ) : NEW_LINE INDENT check = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( check and cntForClose == 0 ) : NEW_LINE INDENT print ( " Yes , ▁ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] == str [ 0 ] ) : NEW_LINE INDENT print ( ' ( ' , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' ) ' , end = " " ) NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT DEDENT print ( " NO " , end = " " ) NEW_LINE DEDENT DEDENT str = "123122" NEW_LINE balBracketSequence ( str ) NEW_LINE
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 -- > diameter of right subtree height of left subtree and right subtree is obtained from lh and rh and returned value of function is stored in ldiameter and rdiameter ; height of tree will be max of left subtree height and right subtree height plus1 ; function to calculate diameter of binary tree ; Constructed binary tree is 1 / \ 2 3 / \ 4 5 ; Function Call
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 = Height ( ) NEW_LINE rh = Height ( ) NEW_LINE if root is None : NEW_LINE INDENT height . h = 0 NEW_LINE return 0 NEW_LINE DEDENT ldiameter = diameterOpt ( root . left , lh ) NEW_LINE rdiameter = diameterOpt ( root . right , rh ) NEW_LINE height . h = max ( lh . h , rh . h ) + 1 NEW_LINE return max ( lh . h + rh . h + 1 , max ( ldiameter , rdiameter ) ) NEW_LINE DEDENT def diameter ( root ) : NEW_LINE INDENT height = Height ( ) NEW_LINE return diameterOpt ( root , height ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( diameter ( root ) ) NEW_LINE
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 . ; This will storethe final answer ; 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 height ( root , ans ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left_height = height ( root . left , ans ) NEW_LINE right_height = height ( root . right , ans ) NEW_LINE ans [ 0 ] = max ( ans [ 0 ] , 1 + left_height + right_height ) NEW_LINE return 1 + max ( left_height , right_height ) NEW_LINE DEDENT def diameter ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = [ - 999999999999 ] NEW_LINE height_of_tree = height ( root , ans ) NEW_LINE return ans [ 0 ] 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 . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( " Diameter ▁ is " , diameter ( root ) ) NEW_LINE DEDENT
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_LINE DEDENT for i in range ( N - 1 , pivotPoint - 1 , - 1 ) : NEW_LINE INDENT print ( pre [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( pre [ 0 ] ) NEW_LINE DEDENT
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 same as the previous character ; Increase count of substrings possible with current character ; Reset count of substrings possible with current character ; Update count of substrings ; Update previous character ; Driver Code
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 = ' geeksforgeeks ' NEW_LINE countSubstrings ( s ) NEW_LINE
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 ; Stores first element of the original array ; Push it into the original array ; Mark as visited ; Traversing the neighbors and check if the elements are visited or not ; Traverse adjacent elements ; If element is not visited ; Push it into res ; Mark as visited ; Update the next adjacent ; Print original array ; Driver Code ; Given pairs of adjacent elements
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 INDENT if ( len ( mp [ it ] ) == 1 ) : NEW_LINE INDENT start = it + 3 NEW_LINE break NEW_LINE DEDENT DEDENT adjacent = start NEW_LINE res . append ( start ) NEW_LINE visited [ start ] = True NEW_LINE while ( len ( res ) != len ( A ) + 1 ) : NEW_LINE INDENT for elements in mp [ adjacent ] : NEW_LINE INDENT if ( elements not in visited ) : NEW_LINE INDENT res . append ( elements ) NEW_LINE visited [ elements ] = True NEW_LINE adjacent = elements NEW_LINE DEDENT DEDENT DEDENT print ( * res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ [ 5 , 1 ] , [ 3 , 4 ] , [ 3 , 5 ] ] NEW_LINE find_original_array ( A ) NEW_LINE DEDENT
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 ) ; Driver Code
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 , h + 1 ) : NEW_LINE INDENT print ( i , " ▁ " , i + 1 ) NEW_LINE DEDENT if d > h : NEW_LINE INDENT print ( 1 , " ▁ " , h + 2 ) NEW_LINE for i in range ( h + 2 , d + 1 ) : NEW_LINE INDENT print ( i , " ▁ " , i + 1 ) NEW_LINE DEDENT DEDENT for i in range ( d + 1 , n ) : NEW_LINE INDENT k = 1 NEW_LINE if d == h : NEW_LINE INDENT k = 2 NEW_LINE DEDENT print ( k , " ▁ " , i + 1 ) NEW_LINE DEDENT DEDENT n = 5 NEW_LINE d = 3 NEW_LINE h = 2 NEW_LINE constructTree ( n , d , h ) NEW_LINE
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 all number starting from 1 ; Check if i occurred n - k + 1 times ; Print the smallest number ; Print - 1 , if no such number found ; Function to count frequency of each number in each subarray of length K ; Traverse all subarrays of length K ; Check and print the smallest number present in every subarray and print it ; Function to generate the value of K ; Function call ; Driver Code ; Given array ; Size of array ; Function call
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 DEDENT DEDENT DEDENT def checkAnswer ( mp , N , K ) : NEW_LINE INDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if i in mp : NEW_LINE INDENT if ( mp [ i ] == ( N - K + 1 ) ) : NEW_LINE INDENT print ( i , end = " ▁ " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT DEDENT print ( - 1 , end = " ▁ " ) ; NEW_LINE DEDENT def smallestPresentNumber ( arr , N , K ) : NEW_LINE INDENT mp = { } ; NEW_LINE for i in range ( N - K + 1 ) : NEW_LINE INDENT uniqueElements ( arr , i , K , mp ) ; NEW_LINE DEDENT checkAnswer ( mp , N , K ) ; NEW_LINE DEDENT def generateK ( arr , N ) : NEW_LINE INDENT for k in range ( 1 , N + 1 ) : NEW_LINE INDENT smallestPresentNumber ( arr , N , k ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 5 , 3 , 2 , 3 , 1 , 3 , 2 , 7 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE generateK ( arr , N ) ; NEW_LINE DEDENT
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 ; Since we go level by level , the last stored right leaf node is deepest one ; Driver Code ; create a binary tree
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 . append ( root ) NEW_LINE result = None NEW_LINE while ( 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 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 result = temp . right NEW_LINE DEDENT DEDENT DEDENT return result 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 root . right . left . right = newnode ( 7 ) NEW_LINE root . right . right . right = newnode ( 8 ) NEW_LINE root . right . left . right . left = newnode ( 9 ) NEW_LINE root . right . right . right . right = newnode ( 10 ) NEW_LINE result = getDeepestRightLeafNode ( root ) NEW_LINE if result : NEW_LINE INDENT print ( " Deepest ▁ Right ▁ Leaf ▁ Node ▁ : : " , result . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ result , ▁ right ▁ leaf ▁ not ▁ found " ) NEW_LINE DEDENT DEDENT
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 contains unequal characters in both the strings ; Checks for the first index from left in which characters in both the strings are unequal ; Store the current index ; Break out of the loop ; Checks for the first index from right in which characters in both the strings are unequal ; Store the current index ; Break out of the loop ; Reverse the subString X [ L , R ] ; If X and Y are equal ; Otherwise ; Driver Code ; Function Call
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 = i NEW_LINE break NEW_LINE DEDENT DEDENT X = list ( X ) NEW_LINE X = X [ : L ] + X [ R : L - 1 : - 1 ] + X [ R + 1 : ] NEW_LINE if ( X == list ( Y ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " adcbef " NEW_LINE Y = " abcdef " NEW_LINE checkString ( X , Y ) NEW_LINE DEDENT
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 C ; Base Case ; Let maximum length be 0 ; Perform Binary search ; Find mid value ; Check if the current mid satisfy the given condition ; If yes , then store length ; Otherwise ; Return maximum length stored ; Function to check if it is possible to have such a subarray of length K ; Check for first window of size K ; Calculate the total cost and check if less than equal to c ; If it satisfy the condition ; Find the sum of current subarray and calculate total cost ; Include the new element of current subarray ; Discard the element of last subarray ; Calculate total cost and check <= c ; If possible , then return true ; If it is not possible ; Function that builds segment Tree ; If there is only one element ; Find the value of mid ; Build left and right parts of segment tree recursively ; Update the value at current index ; Function to find maximum element in the given range ; If the query is out of bounds ; If the segment is completely inside the query range ; Calculate the mid ; Return maximum in left & right of the segment tree recursively ; Driver Code ; Initialize and Build the Segment Tree ; Function Call
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 mid = int ( low + int ( ( high - low ) / 2 ) ) NEW_LINE if ( possible ( a , b , n , c , mid ) != 0 ) : NEW_LINE INDENT max_length = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return max_length NEW_LINE DEDENT def possible ( a , b , n , c , k ) : NEW_LINE INDENT sum = int ( 0 ) NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT total_cost = int ( sum * k + getMax ( b , 0 , n - 1 , 0 , k - 1 , 0 ) ) NEW_LINE if ( total_cost <= c ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE sum -= a [ i - k ] NEW_LINE total_cost = int ( sum * k + getMax ( b , 0 , n - 1 , i - k + 1 , i , 0 ) ) NEW_LINE if ( total_cost <= c ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT return 0 NEW_LINE DEDENT def build ( b , index , s , e ) : NEW_LINE INDENT if ( s == e ) : NEW_LINE INDENT seg [ index ] = b [ s ] NEW_LINE return NEW_LINE DEDENT mid = int ( s + int ( ( e - s ) / 2 ) ) NEW_LINE build ( b , 2 * index + 1 , s , mid ) NEW_LINE build ( b , 2 * index + 2 , mid + 1 , e ) NEW_LINE seg [ index ] = max ( seg [ 2 * index + 1 ] , seg [ 2 * index + 2 ] ) NEW_LINE DEDENT def getMax ( b , ss , se , qs , qe , index ) : NEW_LINE INDENT if ( se < qs or ss > qe ) : NEW_LINE INDENT return int ( INT_MIN / 2 ) NEW_LINE DEDENT if ( ss >= qs and se <= qe ) : NEW_LINE INDENT return seg [ index ] NEW_LINE DEDENT mid = int ( int ( ss ) + int ( ( se - ss ) / 2 ) ) NEW_LINE return max ( getMax ( b , ss , mid , qs , qe , 2 * index + 1 ) , getMax ( b , mid + 1 , se , qs , qe , 2 * index + 2 ) ) NEW_LINE DEDENT A = [ 1 , 2 , 1 , 6 , 5 , 5 , 6 , 1 ] NEW_LINE B = [ 14 , 8 , 15 , 15 , 9 , 10 , 7 , 12 ] NEW_LINE C = int ( 40 ) NEW_LINE N = len ( A ) NEW_LINE build ( B , 0 , 0 , N - 1 ) NEW_LINE print ( ( maxLength ( A , B , N , C ) ) ) NEW_LINE
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 value ; Check if the current mid satisfy the given condition ; If yes , then store length ; Otherwise ; Return maximum length stored ; Function to check if it is possible to have such a subarray of length K ; Finds the maximum element in each window of size k ; Check for window of size K ; For all possible subarrays of length k ; Until deque is empty ; Calculate the total cost and check if less than equal to c ; Find sum of current subarray and the total cost ; Include the new element of current subarray ; Discard the element of last subarray ; Remove all the elements in the old window ; Calculate total cost and check <= c ; If current subarray length satisfies ; If it is not possible ; Driver Code
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_length = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return max_length NEW_LINE DEDENT def possible ( a , b , n , c , k ) : NEW_LINE INDENT dq = [ ] NEW_LINE Sum = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE while ( len ( dq ) > 0 and b [ i ] > b [ dq [ len ( dq ) - 1 ] ] ) : NEW_LINE INDENT dq . pop ( len ( dq ) - 1 ) NEW_LINE DEDENT dq . append ( i ) NEW_LINE DEDENT total_cost = Sum * k + b [ dq [ 0 ] ] NEW_LINE if ( total_cost <= c ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT Sum += a [ i ] NEW_LINE Sum -= a [ i - k ] NEW_LINE while ( len ( dq ) > 0 and dq [ 0 ] <= i - k ) : NEW_LINE INDENT dq . pop ( 0 ) NEW_LINE DEDENT while ( len ( dq ) > 0 and b [ i ] > b [ dq [ len ( dq ) - 1 ] ] ) : NEW_LINE INDENT dq . pop ( len ( dq ) - 1 ) NEW_LINE DEDENT dq . append ( i ) NEW_LINE total_cost = Sum * k + b [ dq [ 0 ] ] NEW_LINE if ( total_cost <= c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT A = [ 1 , 2 , 1 , 6 , 5 , 5 , 6 , 1 ] NEW_LINE B = [ 14 , 8 , 15 , 15 , 9 , 10 , 7 , 12 ] NEW_LINE N = len ( A ) NEW_LINE C = 40 NEW_LINE print ( maxLength ( A , B , N , C ) ) NEW_LINE
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 using a and N ; Print the value 2 ^ a + 2 ^ b ; Driver Code ; Function Call
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 a = mid NEW_LINE break NEW_LINE DEDENT else : NEW_LINE INDENT a = mid NEW_LINE right = mid - 1 NEW_LINE DEDENT DEDENT t = a - 1 NEW_LINE b = N - ( t * ( t + 1 ) ) // 2 - 1 NEW_LINE print ( ( 1 << a ) + ( 1 << b ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 15 NEW_LINE findNthNum ( N ) NEW_LINE DEDENT
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 subsequence ; Driver code
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 , - 4 , - 2 , 3 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE longestSubWithMaxSum ( arr , N ) NEW_LINE
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 character in s1 is not present in s ; Stores the indices of each character in s ; Traverse string s ; Store indices of characters ; Stores index of last appended character ; Traverse string s1 ; Find the index of next character that can be appended ; Check if the current character be included in the current subsequence ; Otherwise ; Start a new subsequence ; Update index of last character appended ; Driver Code ; If S2 cannot be obtained from subsequences of S1 ; Otherwise
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 ( m ) : NEW_LINE INDENT if ( frequency [ ord ( s1 [ i ] ) - ord ( ' a ' ) ] == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT indices = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT indices [ ord ( s [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT ans = 2 NEW_LINE last = len ( indices [ ord ( s1 [ 0 ] ) - ord ( ' a ' ) ] ) - 1 NEW_LINE for i in range ( 1 , m ) : NEW_LINE INDENT ch = ord ( s1 [ i ] ) - ord ( ' a ' ) NEW_LINE it = bisect_right ( indices [ ch ] , last ) NEW_LINE if ( it != len ( indices [ ch ] ) ) : NEW_LINE INDENT last = it NEW_LINE DEDENT else : NEW_LINE INDENT ans += 1 NEW_LINE last = len ( indices [ ch ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = " acebcd " NEW_LINE S2 = " acbcde " NEW_LINE ans = findMinimumOperations ( S1 , S2 ) NEW_LINE if ( ans == - 1 ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " YES " ) NEW_LINE print ( ans ) NEW_LINE DEDENT DEDENT
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 left subtree exists and left child is even ; swap root 's data with left child and fix left subtree ; if right subtree exists and right child is even ; swap root 's data with right child and fix right subtree ; Function to sink all odd nodes to the bottom of binary tree . It does a postorder traversal and calls sink ( ) if any odd node is found ; If None or is a leaf , do nothing ; Process left and right subtrees before this node ; If root is odd , sink it ; Helper function to do Level Order Traversal of Binary Tree level by level . This function is used here only for showing modified tree . ; Do Level order traversal ; Print one level at a time ; Line separator for levels ; Constructed binary tree is 1 / \ 5 8 / \ / \ 2 4 9 10
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 INDENT if ( root == None or isLeaf ( root ) ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left and not ( root . left . data & 1 ) ) : NEW_LINE INDENT root . data , root . left . data = root . left . data , root . data NEW_LINE sink ( root . left ) NEW_LINE DEDENT elif ( root . right and not ( root . right . data & 1 ) ) : NEW_LINE INDENT root . data , root . right . data = root . right . data , root . data NEW_LINE sink ( root . right ) NEW_LINE DEDENT DEDENT def sinkOddNodes ( root ) : NEW_LINE INDENT if ( root == None or isLeaf ( root ) ) : NEW_LINE INDENT return NEW_LINE DEDENT sinkOddNodes ( root . left ) NEW_LINE sinkOddNodes ( root . right ) NEW_LINE if ( root . data & 1 ) : NEW_LINE INDENT sink ( root ) NEW_LINE DEDENT DEDENT def printLevelOrder ( root ) : NEW_LINE INDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) ) : NEW_LINE INDENT nodeCount = len ( q ) NEW_LINE while ( nodeCount ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE print ( node . data , end = " ▁ " ) NEW_LINE q . pop ( 0 ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT root = newnode ( 1 ) NEW_LINE root . left = newnode ( 5 ) NEW_LINE root . right = newnode ( 8 ) NEW_LINE root . left . left = newnode ( 2 ) NEW_LINE root . left . right = newnode ( 4 ) NEW_LINE root . right . left = newnode ( 9 ) NEW_LINE root . right . right = newnode ( 10 ) NEW_LINE sinkOddNodes ( root ) NEW_LINE print ( " Level ▁ order ▁ traversal ▁ of ▁ modified ▁ tree " ) NEW_LINE printLevelOrder ( root ) NEW_LINE
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 if a number is moran number ; Calculate sum of digits ; Check if n is divisible by the sum of digits ; Calculate the quotient ; If the quotient is prime ; Function to print the first K Moran numbers from the array ; Sort the given array ; Initialise a set ; Traverse the array from the end ; If the current array element is a Moran number ; Insert into the set ; Driver Code
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 ( r % i == 0 ) : NEW_LINE INDENT s = False NEW_LINE break NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT def isMorannumber ( n ) : NEW_LINE INDENT dup = n NEW_LINE sums = digiSum ( dup ) NEW_LINE if ( n % sums == 0 ) : NEW_LINE INDENT c = n // sums NEW_LINE if isPrime ( c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def FirstKMorannumber ( a , n , k ) : NEW_LINE INDENT X = k NEW_LINE a . sort ( ) NEW_LINE s = set ( ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( isMorannumber ( a [ i ] ) ) : NEW_LINE INDENT s . add ( a [ i ] ) NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT if ( k > 0 ) : NEW_LINE INDENT print ( X , end = ' ▁ Moran ▁ numbers ▁ are ▁ not ▁ ' ' present ▁ in ▁ the ▁ array ' ) NEW_LINE return NEW_LINE DEDENT lists = sorted ( s ) NEW_LINE for i in lists : NEW_LINE INDENT print ( i , end = ' , ▁ ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 34 , 198 , 21 , 42 , 63 , 45 , 22 , 44 , 43 ] NEW_LINE K = 4 NEW_LINE N = len ( A ) NEW_LINE FirstKMorannumber ( A , N , K ) NEW_LINE DEDENT
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 array ; If pair does not exist ; Increment count of pairs ; Return the count of pairs ; Driver Code
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 INDENT k = key - arr [ j ] NEW_LINE if k not in m : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT ans += m . get ( k , 0 ) NEW_LINE DEDENT if ( k == arr [ j ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans // 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 8 , 2 , 10 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPair ( arr , n ) ) NEW_LINE DEDENT
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 return a NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE r = 2 NEW_LINE arr = [ 400 , 567 , 890 , 765 , 987 ] NEW_LINE ranges = [ [ 300 , 380 ] , [ 800 , 1000 ] ] NEW_LINE print ( * findRockSample ( ranges , n , r , arr ) ) 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 ; function to return the longest odd level depth if it exists otherwise 0 ; Base case return from here ; increment current level ; if curr_level is odd and its a leaf node ; A wrapper over deepestOddLevelDepth ( ) ; Driver Code ; 10 / \ 28 13 / \ 14 15 / \ 23 24 Let us create Binary Tree shown in above example
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 deepestOddLevelDepthUtil ( curr_node , curr_level ) : NEW_LINE INDENT if ( curr_node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT curr_level += 1 NEW_LINE if ( curr_level % 2 != 0 and isleaf ( curr_node ) ) : NEW_LINE INDENT return curr_level NEW_LINE DEDENT return max ( deepestOddLevelDepthUtil ( curr_node . left , curr_level ) , deepestOddLevelDepthUtil ( curr_node . right , curr_level ) ) NEW_LINE DEDENT def deepestOddLevelDepth ( curr_node ) : NEW_LINE INDENT return deepestOddLevelDepthUtil ( curr_node , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 28 ) NEW_LINE root . right = newNode ( 13 ) NEW_LINE root . right . left = newNode ( 14 ) NEW_LINE root . right . right = newNode ( 15 ) NEW_LINE root . right . right . left = newNode ( 23 ) NEW_LINE root . right . right . right = newNode ( 24 ) NEW_LINE print ( deepestOddLevelDepth ( root ) ) NEW_LINE DEDENT
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 ; Recursive Call ; Any number can come in between first and last except the zero ; Recursive Call ; Function to place digit of the number ; When N is 1 and K > 0 , then the single number will be the first and last digit it cannot have difference greater than 0 ; This loop place the digit at the starting ; Recursive Call ; Vector to store results ; Generate all the resultant number ; Print the result ; Driver Code ; Function Call
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 - K + 48 NEW_LINE findNumbers ( st + pt , prev - K , n , K ) NEW_LINE DEDENT if ( K != 0 and prev + K < 10 ) : NEW_LINE INDENT pt = " " NEW_LINE pt += prev + K + 48 NEW_LINE findNumbers ( st + pt , prev + K , n , K ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for j in range ( 1 , 10 , 1 ) : NEW_LINE INDENT pt = " " NEW_LINE pt += j + 48 NEW_LINE findNumbers ( st + pt , prev , n , K ) NEW_LINE DEDENT DEDENT DEDENT def numDifference ( N , K ) : NEW_LINE INDENT global result NEW_LINE st = " " NEW_LINE if ( N == 1 and K == 0 ) : NEW_LINE INDENT result . append ( 0 ) NEW_LINE DEDENT elif ( N == 1 and K > 0 ) : NEW_LINE INDENT return result NEW_LINE DEDENT for i in range ( 1 , 10 , 1 ) : NEW_LINE INDENT temp = " " NEW_LINE temp += str ( 48 + i ) NEW_LINE findNumbers ( st + temp , i , N , K ) NEW_LINE st = " " NEW_LINE DEDENT return result NEW_LINE DEDENT def numDifferenceUtil ( N , K ) : NEW_LINE INDENT res = [ ] NEW_LINE res = numDifference ( N , K ) NEW_LINE for i in range ( 1 , len ( res ) ) : NEW_LINE INDENT print ( res [ i ] + 40 , end = " ▁ " ) NEW_LINE break NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 2 NEW_LINE K = 9 NEW_LINE numDifferenceUtil ( N , K ) NEW_LINE DEDENT
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 bricks ; Function call
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 ( points ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cnt = 1 NEW_LINE curr = points [ 0 ] [ 1 ] NEW_LINE for j in range ( 1 , len ( points ) ) : NEW_LINE INDENT if ( curr < points [ j ] [ 0 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE curr = points [ j ] [ 1 ] NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT bricks = [ [ 5000 , 900000 ] , [ 1 , 100 ] , [ 150 , 499 ] ] NEW_LINE print ( findMinBulletShots ( bricks ) ) NEW_LINE DEDENT
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 mark ; Print the total count ; Driver Code ; Given array arr ; Function call
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_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 9 , 6 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE countMaximum ( arr , N ) ; NEW_LINE DEDENT
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 Code
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 [ i ] == ' A ' ) : NEW_LINE INDENT temp1 [ i ] = ' B ' NEW_LINE DEDENT else : NEW_LINE INDENT temp1 [ i ] = ' A ' NEW_LINE DEDENT DEDENT temp1 = temp1 [ : : - 1 ] NEW_LINE prev = " " . join ( temp1 ) NEW_LINE cur += prev NEW_LINE prev = cur NEW_LINE DEDENT return cur [ k - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE K = 3 NEW_LINE print ( findKthChar ( N , K ) ) NEW_LINE DEDENT
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 ; Stores the sum of window ; Iterate over array ; Current element ; Remove index of minimum elements from deque which are less than the current element ; Insert current index in deque ; Update current window sum ; Calculate required operation to make current window elements equal ; If cost is less than k ; Shift window start pointer towards right and update current window sum ; Return answer ; Driver Code ; Function call
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 . popleft ( ) NEW_LINE DEDENT dq . append ( i ) NEW_LINE s += x NEW_LINE cost = a [ dq [ 0 ] ] * ( answer + 1 ) - s NEW_LINE if ( cost <= k ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( dq [ 0 ] == start ) : NEW_LINE INDENT dq . popleft ( ) NEW_LINE DEDENT s -= a [ start ] NEW_LINE start += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 2 , 4 ] NEW_LINE k = 10 NEW_LINE print ( maxSubarray ( a , k ) ) NEW_LINE DEDENT
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 depth of deepest odd level leaf . This function mainly uses depthOfOddLeafUtil ( ) ; 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 depthOfOddLeafUtil ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . left is None and root . right is None and level & 1 : NEW_LINE INDENT return level NEW_LINE DEDENT return ( max ( depthOfOddLeafUtil ( root . left , level + 1 ) , depthOfOddLeafUtil ( root . right , level + 1 ) ) ) NEW_LINE DEDENT def depthOfOddLeaf ( root ) : NEW_LINE INDENT level = 1 NEW_LINE depth = 0 NEW_LINE return depthOfOddLeafUtil ( root , level ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . right . left = Node ( 5 ) NEW_LINE root . right . right = Node ( 6 ) NEW_LINE root . right . left . right = Node ( 7 ) NEW_LINE root . right . right . right = Node ( 8 ) NEW_LINE root . right . left . right . left = Node ( 9 ) NEW_LINE root . right . right . right . right = Node ( 10 ) NEW_LINE root . right . right . right . right . left = Node ( 11 ) NEW_LINE print " % d ▁ is ▁ the ▁ required ▁ depth " % ( depthOfOddLeaf ( root ) ) NEW_LINE
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 ; Given array arr [ ] ; Length of the array ; Given K ; Function call
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 = 3 NEW_LINE print ( canSplitArray ( arr , N , K ) ) NEW_LINE DEDENT
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 INDENT return 1 NEW_LINE DEDENT elif data [ 0 ] < target : NEW_LINE INDENT return min ( smallSumSubset ( data [ 1 : ] , \ target , maxVal ) , 1 + smallSumSubset ( data [ 1 : ] , \ target - data [ 0 ] , maxVal ) ) NEW_LINE DEDENT DEDENT data = [ 3 , 1 , 7 , 1 , 2 ] NEW_LINE target = 11 NEW_LINE val = smallSumSubset ( data , target , len ( data ) + 1 ) NEW_LINE if val > len ( data ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( val ) NEW_LINE DEDENT
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 ; Stores the count of ' p ' after removal of all " pr " substrings up to str [ i ] ; Stores the count of ' r ' after removal of all " pr " substrings up to str [ i ] ; Stack to maintain the order of characters after removal of substrings ; If substring " pr " is removed ; Increase cost by X ; If any substring " rp " left in the Stack ; If any substring " rp " left in the Stack ; Driver Code
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 def maxCost ( str , X , Y ) : NEW_LINE INDENT N = len ( str ) NEW_LINE if ( Y > X ) : NEW_LINE INDENT swapXandY ( str , X , Y ) NEW_LINE DEDENT res = 0 NEW_LINE countP = 0 NEW_LINE countR = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( str [ i ] == ' p ' ) : NEW_LINE INDENT countP += 1 NEW_LINE DEDENT elif ( str [ i ] == ' r ' ) : NEW_LINE INDENT if ( countP > 0 ) : NEW_LINE INDENT countP -= 1 NEW_LINE res += X NEW_LINE DEDENT else : NEW_LINE INDENT countR += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT res += min ( countP , countR ) * Y NEW_LINE countP = 0 NEW_LINE countR = 0 NEW_LINE DEDENT DEDENT res += min ( countP , countR ) * Y NEW_LINE return res NEW_LINE DEDENT str = " abppprrr " NEW_LINE X = 5 NEW_LINE Y = 4 NEW_LINE print ( maxCost ( str , X , Y ) ) NEW_LINE
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 call
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 ( " No " ) NEW_LINE DEDENT DEDENT arr = [ 9 , 9 , 9 , 9 , 9 , 9 , 9 ] NEW_LINE uniqueElement ( arr ) NEW_LINE
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 the answer by taking the pair which is maximum for every possible sum ; Return the max possible pair ; Function to return the count of pairs ; Size of the array ; Stores the frequencies ; Count the frequency ; Driver Code
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 += min ( freq [ firElement ] , freq [ sum - firElement ] ) NEW_LINE DEDENT DEDENT sum += 1 NEW_LINE if ( sum % 2 == 0 ) : NEW_LINE INDENT possiblePair += freq [ sum // 2 ] // 2 NEW_LINE DEDENT ans = max ( ans , possiblePair ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def countofPairs ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE freq = [ 0 ] * ( n + 1 ) NEW_LINE maxi = - 1 NEW_LINE mini = n + 1 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT maxi = max ( maxi , a [ i ] ) NEW_LINE mini = min ( mini , a [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT freq [ a [ i ] ] += 1 NEW_LINE DEDENT return maxCount ( freq , maxi , mini ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 4 , 3 , 3 , 5 , 6 ] NEW_LINE print ( countofPairs ( a ) ) NEW_LINE DEDENT
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 new subarray by squaring the current element ; Update maximum subarray sum ; Return answer ; Driver Code ; Function call
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 ] , dp [ i - 1 ] [ 0 ] + a [ i ] ) NEW_LINE dp [ i ] [ 1 ] = max ( dp [ i - 1 ] [ 1 ] + a [ i ] , a [ i ] * a [ i ] ) NEW_LINE dp [ i ] [ 1 ] = max ( dp [ i ] [ 1 ] , dp [ i - 1 ] [ 0 ] + a [ i ] * a [ i ] ) NEW_LINE max_sum = max ( max_sum , dp [ i ] [ 1 ] ) NEW_LINE max_sum = max ( max_sum , dp [ i ] [ 0 ] ) NEW_LINE DEDENT return max_sum NEW_LINE DEDENT n = 5 NEW_LINE a = [ 1 , - 5 , 8 , 12 , - 8 ] NEW_LINE print ( getMaxSum ( a , n ) ) NEW_LINE
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 index ; Find the exceeded value ; If exceeded value is zero ; Driver Code
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 = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < K ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT x = K - arr [ i ] NEW_LINE if ( x == 0 ) : NEW_LINE INDENT ln = min ( ln , i ) NEW_LINE DEDENT if ( x in mp . keys ( ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT ln = min ( ln , i - mp [ x ] ) NEW_LINE DEDENT DEDENT DEDENT return ln NEW_LINE DEDENT arr = [ 1 , 2 , 4 , 3 , 2 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE K = 7 NEW_LINE ln = subArraylen ( arr , n , K ) NEW_LINE if ( ln == sys . maxsize ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ln ) NEW_LINE DEDENT
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 ; check if the node is leaf node and level is odd if level is odd , then update result ; check for left child ; check for right child ; Driver Code ; construct a tree
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 . 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 ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( not temp . left and not temp . right and ( level % 2 != 0 ) ) : NEW_LINE INDENT result = level NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT size -= 1 NEW_LINE DEDENT DEDENT return result 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 . left = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE root . right . left . right = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE root . right . left . right . left = newNode ( 9 ) NEW_LINE root . right . right . right . right = newNode ( 10 ) NEW_LINE root . right . right . right . right . left = newNode ( 11 ) NEW_LINE result = maxOddLevelDepth ( root ) NEW_LINE if ( result == INT_MAX ) : NEW_LINE INDENT print ( " No ▁ leaf ▁ node ▁ at ▁ odd ▁ level " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( result , end = " " ) NEW_LINE print ( " ▁ is ▁ the ▁ required ▁ depth ▁ " ) NEW_LINE DEDENT DEDENT
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 all primes between n1 and n2 ; Generate all primes between n1 and n2 ; Stores all concatenations of each pair of primes ; Generate all concatenations of each pair of primes ; Stores the primes out of the numbers generated above ; Store the unique primes ; Find the minimum ; Find the minimum ; Find N ; Print the N - th term of the Fibonacci Series ; Driver Code
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 DEDENT DEDENT def fibonacciOfPrime ( n1 , n2 ) : NEW_LINE INDENT SieveOfEratosthenes ( ) NEW_LINE initial = [ ] NEW_LINE for i in range ( n1 , n2 ) : NEW_LINE INDENT if prime [ i ] : NEW_LINE INDENT initial . append ( i ) NEW_LINE DEDENT DEDENT now = [ ] NEW_LINE for a in initial : NEW_LINE INDENT for b in initial : NEW_LINE INDENT if a != b : NEW_LINE INDENT c = str ( a ) + str ( b ) NEW_LINE now . append ( int ( c ) ) NEW_LINE DEDENT DEDENT DEDENT current = [ ] NEW_LINE for x in now : NEW_LINE INDENT if prime [ x ] : NEW_LINE INDENT current . append ( x ) NEW_LINE DEDENT DEDENT current = set ( current ) NEW_LINE first = min ( current ) NEW_LINE second = max ( current ) NEW_LINE count = len ( current ) - 1 NEW_LINE curr = 1 NEW_LINE while curr < count : NEW_LINE INDENT c = first + second NEW_LINE first = second NEW_LINE second = c NEW_LINE curr += 1 NEW_LINE DEDENT print ( c ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = 2 NEW_LINE y = 40 NEW_LINE fibonacciOfPrime ( x , y ) NEW_LINE DEDENT
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 the element at the top of the stack is smaller than arr [ i ] ; Store the index of next greater element ; Pop the top element ; Insert the current index ; Stores the count ; Driver Code
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 ] ) : NEW_LINE INDENT next_greater [ s [ - 1 ] ] = i NEW_LINE s . pop ( - 1 ) NEW_LINE DEDENT s . append ( i ) NEW_LINE DEDENT count = 0 NEW_LINE maxi = - sys . maxsize - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( next_greater [ i ] - i > k and maxi < arr [ i ] ) : NEW_LINE INDENT maxi = max ( maxi , arr [ i ] ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 3 , 6 , 4 , 3 , 2 ] NEW_LINE K = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( countElements ( arr , n , K ) ) NEW_LINE DEDENT
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 of 1 's ; Else we initialise the count with 0 ; We get the maximum count by skipping the current and the next element . ; Driver code
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 range ( n ) ] NEW_LINE for i in range ( n - 3 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i + 2 ] == 1 ) : NEW_LINE INDENT suffix [ i ] = suffix [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT suffix [ i ] = 0 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans = max ( ans , prefix [ i + 1 ] + suffix [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT n = 6 NEW_LINE arr = [ 1 , 1 , 1 , 0 , 1 , 1 ] NEW_LINE maxLengthOf1s ( arr , n ) NEW_LINE
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 last operation was performed ; Stores minimum number of operations ; Iterate from pos to n ; Check if s [ i ] is 0 ; Check if last operation was performed because of 1 ; Set last to 0 ; Check if last operation was performed because of 0 ; Set last to 1 ; Return the answer ; Driver Code
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 in range ( pos + 1 , n ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT if ( last == 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE last = 0 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( last == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE last = 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "10111" NEW_LINE print ( minOperations ( s ) ) NEW_LINE DEDENT
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 value " res " and " maxLevel " Note that res and maxLen are passed by reference . ; Driver Code
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 NEW_LINE find ( root . left , level , maxLevel , res ) NEW_LINE if ( level > maxLevel [ 0 ] ) : NEW_LINE INDENT res [ 0 ] = root . data NEW_LINE maxLevel [ 0 ] = level NEW_LINE DEDENT find ( root . right , level , maxLevel , res ) NEW_LINE DEDENT DEDENT def deepestNode ( root ) : NEW_LINE INDENT res = [ - 1 ] NEW_LINE maxLevel = [ - 1 ] NEW_LINE find ( root , 0 , maxLevel , res ) NEW_LINE return res [ 0 ] 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 . left = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE root . right . left . right = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE root . right . left . right . left = newNode ( 9 ) NEW_LINE print ( deepestNode ( root ) ) NEW_LINE DEDENT
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 DEDENT return clumps NEW_LINE DEDENT arr = [ 13 , 15 , 66 , 66 , 66 , 37 , 37 , 8 , 8 , 11 , 11 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countClumps ( arr , N ) ) 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 frequencies of the characters ; to store the count of characters whose number of occurrences is odd . ; iterating over the map ; Driver code
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 ) ) : NEW_LINE INDENT freq [ s [ i ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for value in freq . values ( ) : NEW_LINE INDENT if ( value % 2 == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count > k ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " poor " NEW_LINE K = 3 NEW_LINE iskPalindromesPossible ( str1 , K ) NEW_LINE str = " geeksforgeeks " NEW_LINE K = 10 NEW_LINE iskPalindromesPossible ( str , K ) NEW_LINE DEDENT
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 ( root . right ) NEW_LINE return max ( leftHt , rightHt ) + 1 NEW_LINE DEDENT def deepestNode ( root , levels ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( levels == 1 ) : NEW_LINE INDENT print ( root . data ) NEW_LINE DEDENT elif ( levels > 1 ) : NEW_LINE INDENT deepestNode ( root . left , levels - 1 ) NEW_LINE deepestNode ( root . right , levels - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = new_Node ( 1 ) NEW_LINE root . left = new_Node ( 2 ) NEW_LINE root . right = new_Node ( 3 ) NEW_LINE root . left . left = new_Node ( 4 ) NEW_LINE root . right . left = new_Node ( 5 ) NEW_LINE root . right . right = new_Node ( 6 ) NEW_LINE root . right . left . right = new_Node ( 7 ) NEW_LINE root . right . right . right = new_Node ( 8 ) NEW_LINE root . right . left . right . left = new_Node ( 9 ) NEW_LINE levels = height ( root ) NEW_LINE deepestNode ( root , levels ) NEW_LINE DEDENT
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 rotated or not ; To check if the elements to the left of the pivot are in descending or not ; To check if the elements to the right of the pivot are in ascending or not ; If any of the above if or else is true Then the array is sorted rotated ; Else the array is not sorted rotated ; Driver code
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 if ( mid > low and arr [ mid ] < arr [ mid - 1 ] ) : NEW_LINE INDENT return mid - 1 ; NEW_LINE DEDENT if ( arr [ low ] > arr [ mid ] ) : NEW_LINE INDENT return findPivot ( arr , low , mid - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return findPivot ( arr , mid + 1 , high ) ; NEW_LINE DEDENT DEDENT def isRotated ( arr , n ) : NEW_LINE INDENT l = 0 ; NEW_LINE r = n - 1 ; NEW_LINE pivot = - 1 ; NEW_LINE if ( arr [ l ] > arr [ r ] ) : NEW_LINE INDENT pivot = findPivot ( arr , l , r ) ; NEW_LINE temp = pivot NEW_LINE if ( l < pivot ) : NEW_LINE INDENT while ( pivot > l ) : NEW_LINE INDENT if ( arr [ pivot ] < arr [ pivot - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT pivot -= 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT pivot = temp NEW_LINE pivot += 1 ; NEW_LINE while ( pivot < r ) : NEW_LINE INDENT if ( arr [ pivot ] > arr [ pivot + 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT pivot + + 1 ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT else : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 4 , 5 , 1 , 2 ] ; NEW_LINE if ( isRotated ( arr , 5 ) ) : NEW_LINE INDENT print ( " True " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " False " ) ; NEW_LINE DEDENT 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 DEDENT q = deque ( ) NEW_LINE q . append ( root ) NEW_LINE while len ( q ) != 0 : NEW_LINE INDENT node = q . popleft ( ) NEW_LINE if node . left is not None : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT DEDENT return node . data NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = new_Node ( 1 ) NEW_LINE root . left = new_Node ( 2 ) NEW_LINE root . right = new_Node ( 3 ) NEW_LINE root . left . left = new_Node ( 4 ) NEW_LINE root . right . left = new_Node ( 5 ) NEW_LINE root . right . right = new_Node ( 6 ) NEW_LINE root . right . left . right = new_Node ( 7 ) NEW_LINE root . right . right . right = new_Node ( 8 ) NEW_LINE root . right . left . right . left = new_Node ( 9 ) NEW_LINE levels = deepestNode ( root ) NEW_LINE print ( levels ) NEW_LINE DEDENT
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 the students ; Updates that are to be done ; Number of students
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_LINE for j in range ( 1 , n ) : NEW_LINE INDENT if ( x [ j ] [ 1 ] >= highest [ 1 ] ) : NEW_LINE INDENT highest = x [ j ] NEW_LINE DEDENT DEDENT print ( " Name : ▁ " , highest [ 0 ] , " , ▁ Jump : ▁ " , abs ( highest [ 2 ] - 1 ) , sep = " " ) NEW_LINE DEDENT names = [ " sam " , " ram " , " geek " ] NEW_LINE marks = [ 80 , 79 , 75 ] NEW_LINE updates = [ 0 , 5 , - 9 ] NEW_LINE n = len ( marks ) NEW_LINE nameRank ( names , marks , updates , n ) NEW_LINE
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 digits in L and R ; First digits of L and R ; If L has lesser number of digits than R ; If the number that starts with firstDigitL and has number of digits = countDigitsL is within the range include the number ; Exclude the number ; If the number that starts with firstDigitR and has number of digits = countDigitsR is within the range include the number ; Exclude the number ; If both L and R have equal number of digits ; Include the number greater than L upto the maximum number whose digit = coutDigitsL ; Exclude the numbers which are greater than R ; Return the count ; Driver code
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 += ( count * d ) NEW_LINE count //= 10 NEW_LINE DEDENT return num NEW_LINE DEDENT def findCount ( L , R ) : NEW_LINE INDENT count = 0 NEW_LINE countDigitsL = countDigits ( L ) NEW_LINE countDigitsR = countDigits ( R ) NEW_LINE firstDigitL = ( L // pow ( 10 , countDigitsL - 1 ) ) NEW_LINE firstDigitR = ( R // pow ( 10 , countDigitsR - 1 ) ) NEW_LINE if ( countDigitsL < countDigitsR ) : NEW_LINE INDENT count += ( 9 * ( countDigitsR - countDigitsL - 1 ) ) NEW_LINE if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) : NEW_LINE INDENT count += ( 9 - firstDigitL + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count += ( 9 - firstDigitL ) NEW_LINE DEDENT if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) : NEW_LINE INDENT count += firstDigitR NEW_LINE DEDENT else : NEW_LINE INDENT count += ( firstDigitR - 1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( getDistinct ( firstDigitL , countDigitsL ) >= L ) : NEW_LINE INDENT count += ( 9 - firstDigitL + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT count += ( 9 - firstDigitL ) NEW_LINE DEDENT if ( getDistinct ( firstDigitR , countDigitsR ) <= R ) : NEW_LINE INDENT count -= ( 9 - firstDigitR ) NEW_LINE DEDENT else : NEW_LINE INDENT count -= ( 9 - firstDigitR + 1 ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT L = 10 NEW_LINE R = 50 NEW_LINE print ( findCount ( L , R ) ) NEW_LINE
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 ; given difference
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 : NEW_LINE INDENT m = k - mat [ i ] [ j ] NEW_LINE if m in s : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT s . add ( mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT n , m = 4 , 4 NEW_LINE mat = [ [ 5 , 2 , 3 , 4 ] , [ 5 , 6 , 7 , 8 ] , [ 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 100 ] ] NEW_LINE k = 85 NEW_LINE if isPairWithDiff ( mat , k ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 are greater and stack is not empty ; push next to stack so that we can find next smaller for it ; After iterating over the loop , the remaining elements in stack do not have the next smaller element , so print - 1 for them ; Driver Code ;
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 INDENT mp [ s [ - 1 ] ] = arr [ i ] NEW_LINE s . pop ( ) NEW_LINE DEDENT s . append ( arr [ i ] ) NEW_LINE DEDENT while ( len ( s ) != 0 ) : NEW_LINE INDENT mp [ s [ - 1 ] ] = - 1 NEW_LINE s . pop ( ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , " - - - > " , mp [ arr [ i ] ] ) NEW_LINE DEDENT DEDENT arr = [ 11 , 13 , 21 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE printNSE ( arr , n ) NEW_LINE s NEW_LINE
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 empty ; Since we go level by level , the last stored right leaf node is deepest one ; Driver Code ; create a binary tree
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 . append ( root ) NEW_LINE result = None NEW_LINE while ( 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 . left and not temp . left . right ) : NEW_LINE INDENT result = temp . left NEW_LINE DEDENT DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( temp . right ) NEW_LINE DEDENT DEDENT return result 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 . Left = newnode ( 4 ) NEW_LINE root . right . left = newnode ( 5 ) NEW_LINE root . right . right = newnode ( 6 ) NEW_LINE root . right . left . right = newnode ( 7 ) NEW_LINE root . right . right . right = newnode ( 8 ) NEW_LINE root . right . left . right . left = newnode ( 9 ) NEW_LINE root . right . right . right . right = newnode ( 10 ) NEW_LINE result = getDeepestLeftLeafNode ( root ) NEW_LINE if result : NEW_LINE INDENT print ( " Deepest ▁ Left ▁ Leaf ▁ Node ▁ : : " , result . data ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No ▁ result , ▁ Left ▁ leaf ▁ not ▁ found " ) NEW_LINE DEDENT DEDENT
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 vector of trees . ; List to store all possible trees ; if start > end then subtree will be empty so returning NULL in the list ; Iterating through all values from start to end for constructing left and right subtree recursively ; Constructing left subtree ; Constructing right subtree ; Looping through all left and right subtrees and connecting to ith root below ; Making arr [ i ] as root ; Connecting left subtree ; Connecting right subtree ; Adding this tree to list ; Driver program to test above function
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 preorder ( root . right ) NEW_LINE DEDENT DEDENT def getTrees ( arr , start , end ) : NEW_LINE INDENT trees = [ ] NEW_LINE if start > end : NEW_LINE INDENT trees . append ( None ) NEW_LINE return trees NEW_LINE DEDENT for i in range ( start , end + 1 ) : NEW_LINE INDENT ltrees = getTrees ( arr , start , i - 1 ) NEW_LINE rtrees = getTrees ( arr , i + 1 , end ) NEW_LINE for j in ltrees : NEW_LINE INDENT for k in rtrees : NEW_LINE INDENT node = Node ( arr [ i ] ) NEW_LINE node . left = j NEW_LINE node . right = k NEW_LINE trees . append ( node ) NEW_LINE DEDENT DEDENT DEDENT return trees NEW_LINE DEDENT inp = [ 4 , 5 , 7 ] NEW_LINE n = len ( inp ) NEW_LINE trees = getTrees ( inp , 0 , n - 1 ) NEW_LINE print " Preorder ▁ traversals ▁ of ▁ different ▁ possible\ STRNEWLINE ▁ Binary ▁ Trees ▁ are ▁ " NEW_LINE for i in trees : NEW_LINE INDENT preorder ( i ) ; NEW_LINE print " " NEW_LINE DEDENT
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 in fashion like 0. . . x - 1 , 1. . . x , 2. . . x + 1 , ... . , n - x - 1. . . n - 1 ; It can be explained with the reasoning that if for some x number of elements we can update the values then the increment to the segment ( i to j having length -> x ) so that all will be equal is ( x * maxx [ j ] ) this is the total sum of segment and ( pre [ j ] - pre [ i ] ) is present sum So difference of them should be less than k if yes , then that segment length ( x ) can be possible return true ; sort the array in ascending order ; Initializing the prefix array and maximum array ; Calculating prefix sum of the array ; Calculating max value upto that position in the array ; Binary search applied for computation here ; printing result ; Driver code
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 MaxNumberOfElements ( a , n , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT pre [ i ] = 0 NEW_LINE maxx [ i ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + a [ i - 1 ] NEW_LINE maxx [ i ] = max ( maxx [ i - 1 ] , a [ i - 1 ] ) NEW_LINE DEDENT l = 1 NEW_LINE r = n NEW_LINE while ( l < r ) : NEW_LINE INDENT mid = ( l + r ) // 2 NEW_LINE if ( ElementsCalculationFunc ( pre , maxx , mid - 1 , k , n ) ) : NEW_LINE INDENT ans = mid NEW_LINE l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE MaxNumberOfElements ( arr , n , k ) NEW_LINE DEDENT
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 ; palindrome of length 2 ; Palindromes of length more then 2. This loop is similar to Matrix Chain Multiplication . We start with a gap of length 2 and fill P table in a way that gap between starting and ending indexes increases one by one by outer loop . ; Pick starting point for current gap ; Set ending point ; If current string is palindrome ; function which recursively counts if a str [ i . . j ] is a k - palindromic or not . ; terminating condition for a which is a k - palindrome . ; terminating condition for a which is not a k - palindrome . ; increases the counter for the if it is a k - palindrome . ; mid is middle pointer of the str [ i ... j ] . ; if length of which is ( j - i + 1 ) is odd than we have to subtract one from mid else if even then no change . ; if the is k - palindrome then we check if it is a ( k + 1 ) - palindrome or not by just sending any of one half of the to the Count_k_Palindrome def . ; Finding all palindromic substrings of given string ; counting k - palindromes for each and every sub of given string . . ; Output the number of K - palindromic substrings of a given string . ; Driver code
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 checkSubStrPal ( str , n ) : NEW_LINE INDENT global P , Kpal , 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 Kpal [ i ] = 0 ; NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT P [ i ] [ i ] = True ; NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( str [ i ] == str [ i + 1 ] ) : NEW_LINE INDENT P [ i ] [ i + 1 ] = True ; NEW_LINE DEDENT DEDENT for gap in range ( 2 , n ) : NEW_LINE INDENT for i in range ( 0 , n - gap ) : NEW_LINE INDENT j = gap + i ; NEW_LINE if ( str [ i ] == str [ j ] and P [ i + 1 ] [ j - 1 ] ) : NEW_LINE INDENT P [ i ] [ j ] = True ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def countKPalindromes ( i , j , k ) : NEW_LINE INDENT global Kpal , P ; NEW_LINE if ( i == j ) : NEW_LINE INDENT Kpal [ k ] = Kpal [ k ] + 1 ; NEW_LINE return ; NEW_LINE DEDENT if ( P [ i ] [ j ] == False ) : NEW_LINE INDENT return ; NEW_LINE DEDENT Kpal [ k ] = Kpal [ k ] + 1 ; NEW_LINE mid = int ( ( i + j ) / 2 ) ; NEW_LINE if ( ( j - i + 1 ) % 2 == 1 ) : NEW_LINE INDENT mid = mid - 1 ; NEW_LINE DEDENT countKPalindromes ( i , mid , k + 1 ) ; NEW_LINE DEDENT def printKPalindromes ( s ) : NEW_LINE INDENT global P , Kpal , MAX_STR_LEN ; NEW_LINE n = len ( s ) ; NEW_LINE checkSubStrPal ( s , n ) ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , n - i ) : NEW_LINE INDENT countKPalindromes ( j , j + i , 1 ) ; NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT print ( Kpal [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT s = " abacaba " ; NEW_LINE printKPalindromes ( s ) ; NEW_LINE
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 DEDENT return sorted ( result ) ; NEW_LINE DEDENT numbers = [ 123 , 1232 , 456 , 234 , 32145 ] NEW_LINE result = printNumbers ( numbers ) NEW_LINE print ' , ▁ ' . join ( num for num in result ) NEW_LINE