text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Construct XOR tree by Given leaf nodes of Perfect Binary Tree | Python3 implementation of the above approach ; Maximum size for xor tree ; Allocating space to xor tree ; A recursive function that constructs xor tree for vector array [ start ... . . end ] . x is index of current node in XOR tree ; If there is one elemen... | from math import ceil , log NEW_LINE maxsize = 100005 NEW_LINE xor_tree = [ 0 ] * maxsize NEW_LINE def construct_Xor_Tree_Util ( current , start , end , x ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT xor_tree [ x ] = current [ start ] NEW_LINE return NEW_LINE DEDENT left = x * 2 + 1 NEW_LINE right = x * 2 ... |
Maximize distance between any two consecutive 1 ' s β after β flipping β M β 0' s | Function to return the count ; Flipping zeros at distance " d " ; Function to implement binary search ; Check for valid distance i . e mid ; Driver code | def check ( arr , n , m , d ) : NEW_LINE INDENT i = 0 NEW_LINE while ( i < n and m > 0 ) : NEW_LINE INDENT m -= 1 NEW_LINE i += d NEW_LINE DEDENT if m == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def maximumDistance ( arr , n , m ) : NEW_LINE INDENT low = 1 NEW_LINE high = n - 1 NEW_L... |
Maximum XOR value of maximum and second maximum element among all possible subarrays | Function to return the maximum possible xor ; To store the final answer ; Borward traversal ; Backward traversal ; Driver Code | def maximumXor ( arr : list , n : int ) -> int : NEW_LINE INDENT sForward , sBackward = [ ] , [ ] NEW_LINE ans = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while len ( sForward ) > 0 and arr [ i ] < arr [ sForward [ - 1 ] ] : NEW_LINE INDENT ans = max ( ans , arr [ i ] ^ arr [ sForward [ - 1 ] ] ) NEW_LINE sFo... |
Minimum count of Full Binary Trees such that the count of leaves is N | Function to return the minimum count of trees required ; To store the count of set bits in n ; Driver code | def minTrees ( n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n ) : NEW_LINE INDENT n &= ( n - 1 ) ; NEW_LINE count += 1 ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 ; NEW_LINE print ( minTrees ( n ) ) ; NEW_LINE DEDENT |
Count number of steps to cover a distance if steps can be taken in powers of 2 | Function to count the minimum number of steps ; bin ( K ) . count ( "1" ) is a Python3 function to count the number of set bits in a number ; Driver Code | def getMinSteps ( K ) : NEW_LINE INDENT return bin ( K ) . count ( "1" ) NEW_LINE DEDENT n = 343 NEW_LINE print ( getMinSteps ( n ) ) NEW_LINE |
Game Theory in Balanced Ternary Numeral System | ( Moving 3 k steps at a time ) | Function that returns true if the game cannot be won ; Driver code ; Common length | def isDefeat ( s1 , s2 , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( ( s1 [ i ] == '0' and s2 [ i ] == '1' ) or ( s1 [ i ] == '1' and s2 [ i ] == '0' ) ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( ( s1 [ i ] == '0' and s2 [ i ] == ' Z ' ) or ( s1 [ i ] == ' Z ' and s2 [ i ] == '0' ) ) : NEW... |
Check if matrix A can be converted to B by changing parity of corner elements of any submatrix | Python 3 implementation of the above approach ; Boolean function that returns true or false ; Traverse for all elements ; If both are not equal ; Change the parity of all corner elements ; Check if A is equal to B ; Not equ... | N = 3 NEW_LINE M = 3 NEW_LINE def check ( a , b ) : NEW_LINE INDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT for j in range ( 1 , M , 1 ) : NEW_LINE INDENT if ( a [ i ] [ j ] != b [ i ] [ j ] ) : NEW_LINE INDENT a [ i ] [ j ] ^= 1 NEW_LINE a [ 0 ] [ 0 ] ^= 1 NEW_LINE a [ 0 ] [ j ] ^= 1 NEW_LINE a [ i ] [ 0 ] ^= 1... |
Position of the K | Function that returns the Kth set bit ; Traverse in the binary ; Check if the last bit is set or not ; Check if count is equal to k then return the index ; Increase the index as we move right ; Right shift the number by 1 ; Driver Code | def FindIndexKthBit ( n , k ) : NEW_LINE INDENT cnt , ind = 0 , 0 NEW_LINE while n > 0 : NEW_LINE INDENT if n & 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if cnt == k : NEW_LINE INDENT return ind NEW_LINE DEDENT ind += 1 NEW_LINE n = n >> 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : ... |
Check if the binary representation of a number has equal number of 0 s and 1 s in blocks | Function to check ; Converting integer to its equivalent binary number ; If adjacent character are same then increase counter ; Driver code | def hasEqualBlockFrequency ( N ) : NEW_LINE INDENT S = bin ( N ) . replace ( "0b " , " " ) NEW_LINE p = set ( ) NEW_LINE c = 1 NEW_LINE for i in range ( len ( S ) - 1 ) : NEW_LINE INDENT if ( S [ i ] == S [ i + 1 ] ) : NEW_LINE INDENT c += 1 NEW_LINE DEDENT else : NEW_LINE INDENT p . add ( c ) NEW_LINE c = 1 NEW_LINE D... |
Distance between two nodes of binary tree with node values from 1 to N | Python 3 program to find minimum distance between two nodes in binary tree ; Function to get minimum path distance ; find the 1 st dis - similar bit count bit length of n1 and n2 ; find bit difference and maxBit ; calculate result by formula ; Dri... | from math import log2 NEW_LINE def minDistance ( n1 , n2 ) : NEW_LINE INDENT bitCount1 = int ( log2 ( n1 ) ) + 1 NEW_LINE bitCount2 = int ( log2 ( n2 ) ) + 1 NEW_LINE bitDiff = abs ( bitCount1 - bitCount2 ) NEW_LINE maxBitCount = max ( bitCount1 , bitCount2 ) NEW_LINE if ( bitCount1 > bitCount2 ) : NEW_LINE INDENT n2 =... |
Remove one bit from a binary number to get maximum value | Function to find the maximum binary number ; Traverse the binary number ; Try finding a 0 and skip it ; Driver code ; Get the binary number ; Find the maximum binary number | def printMaxAfterRemoval ( s ) : NEW_LINE INDENT flag = False NEW_LINE n = len ( s ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if s [ i ] == '0' and flag == False : NEW_LINE INDENT flag = True NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ i ] , end = " " ) NEW_LINE DEDENT DEDENT DEDENT ... |
Find position of left most dis | Python3 program to Find the leftmost position of first dis - similar bit ; Function to find first dis - similar bit ; return zero for equal number ; find the 1 st dis - similar bit count bit length of n1 and n ; find bit difference and maxBit ; Driver code | from math import floor , log2 NEW_LINE def bitPos ( n1 , n2 ) : NEW_LINE INDENT if n1 == n2 : NEW_LINE INDENT return 0 NEW_LINE DEDENT bitCount1 = floor ( log2 ( n1 ) ) + 1 NEW_LINE bitCount2 = floor ( log2 ( n2 ) ) + 1 NEW_LINE bitDiff = abs ( bitCount1 - bitCount2 ) NEW_LINE maxBitCount = max ( bitCount1 , bitCount2 ... |
Number of pairs with Bitwise OR as Odd number | Function to count pairs with odd OR ; Count total even numbers in array ; Even pair count ; Total pairs ; Return Odd pair count ; Driver Code | def countOddPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] % 2 != 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT evenPairCount = count * ( count - 1 ) / 2 NEW_LINE totPairs = N * ( N - 1 ) / 2 NEW_LINE return ( int ) ( totPairs - evenPairCount ) NEW_... |
Replace every array element by Bitwise Xor of previous and next element | Python3 program to update every array element with sum of previous and next numbers in array ; Nothing to do when array size is 1 ; store current value of arr [ 0 ] and update it ; Update rest of the array elements ; Store current value of next i... | def ReplaceElements ( arr , n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return NEW_LINE DEDENT prev = arr [ 0 ] NEW_LINE arr [ 0 ] = arr [ 0 ] ^ arr [ 1 ] NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT curr = arr [ i ] NEW_LINE arr [ i ] = prev ^ arr [ i + 1 ] NEW_LINE prev = curr NEW_LINE DEDENT arr [ n... |
Find triplets in an array whose AND is maximum | Python3 program to find triplet with maximum bitwise AND . ; Flag Array initially set to true for all numbers ; 2D array for bit representation of all the numbers . Initially all bits are set to 0. ; Finding bit representation of every number and storing it in bits array... | def maxTriplet ( a , n ) : NEW_LINE INDENT f = [ True for i in range ( n ) ] NEW_LINE bits = [ [ 0 for i in range ( 33 ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT num = a [ i ] NEW_LINE j = 32 NEW_LINE while ( num ) : NEW_LINE INDENT if ( num & 1 ) : NEW_LINE INDENT bits [ i ] [ j ] = 1 N... |
Find bitwise OR of all possible sub | function to return OR of sub - arrays ; Driver Code ; print OR of all subarrays | def OR ( a , n ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT ans |= a [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 4 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( OR ( a , n ) ) NEW_LINE DEDENT |
Maximum set bit sum in array without considering adjacent elements | Function to count total number of set bits in an integer ; Maximum sum of set bits ; Calculate total number of set bits for every element of the array ; find total set bits for each number and store back into the array ; current max excluding i ; curr... | def bit ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT count += 1 NEW_LINE n = n & ( n - 1 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def maxSumOfBits ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = bit ( arr [ i ] ) NEW_LINE DEDENT incl = arr [ 0 ] NEW_LIN... |
Increment a number without using ++ or + | function that increment the value . ; Invert bits and apply negative sign ; Driver code | def increment ( i ) : NEW_LINE INDENT i = - ( ~ ord ( i ) ) ; NEW_LINE return chr ( i ) ; NEW_LINE DEDENT n = ' a ' ; NEW_LINE print ( increment ( n ) ) ; NEW_LINE |
Count pairs with Bitwise XOR as ODD number | Function to count number of odd pairs ; find all pairs ; return number of odd pair ; Driver Code ; calling function findOddPair and print number of odd pair | def findOddPair ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] % 2 == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count * ( N - count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 5 , 4 , 7 , 2 , 1 ] NEW_LINE n = len ... |
Bitwise OR ( or | ) of a range | Returns the Most Significant Bit Position ( MSB ) ; Returns the Bitwise OR of all integers between L and R ; Find the MSB position in L ; Find the MSB position in R ; Add this value until msb_p1 and msb_p2 are same ; ; Calculate msb_p1 and msb_p2 ; Find the max of msb_p1 and msb_p2 ; Se... | def MSBPosition ( N ) : NEW_LINE INDENT msb_p = - 1 NEW_LINE while ( N ) : NEW_LINE INDENT N = N >> 1 NEW_LINE msb_p += 1 NEW_LINE DEDENT return msb_p NEW_LINE DEDENT def findBitwiseOR ( L , R ) : NEW_LINE INDENT res = 0 NEW_LINE msb_p1 = MSBPosition ( L ) NEW_LINE msb_p2 = MSBPosition ( R ) NEW_LINE while ( msb_p1 == ... |
Maximize the bitwise OR of an array | Function to maximize the bitwise OR sum ; Compute x ^ k ; Find prefix bitwise OR ; Find suffix bitwise OR ; Find maximum OR value ; Drivers code | def maxOR ( arr , n , k , x ) : NEW_LINE INDENT preSum = [ 0 ] * ( n + 1 ) NEW_LINE suffSum = [ 0 ] * ( n + 1 ) NEW_LINE pow = 1 NEW_LINE for i in range ( 0 , k ) : NEW_LINE INDENT pow *= x NEW_LINE DEDENT preSum [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT preSum [ i + 1 ] = preSum [ i ] | arr [ i ] N... |
How to turn on a particular bit in a number ? | Returns a number that has all bits same as n except the k 'th bit which is made 1 ; k must be greater than 0 ; Do | of n with a number with all unset bits except the k 'th bit ; Driver program to test above function | def turnOnK ( n , k ) : NEW_LINE INDENT if ( k <= 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return ( n | ( 1 << ( k - 1 ) ) ) NEW_LINE DEDENT n = 4 NEW_LINE k = 2 NEW_LINE print ( turnOnK ( n , k ) ) NEW_LINE |
Minimum sum of two numbers formed from digits of an array | Returns sum of two numbers formed from all digits in a [ ] ; sorted the elements ; Driver code | def minSum ( a , n ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE num1 , num2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT num1 = num1 * 10 + a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT num2 = num2 * 10 + a [ i ] NEW_LINE DEDENT DEDENT return num2 + num1 NEW_LINE DEDENT arr ... |
Find value of k | Python 3 program to find k - th bit from right ; Driver Code ; Function Call | def printKthBit ( n , k ) : NEW_LINE INDENT print ( ( n & ( 1 << ( k - 1 ) ) ) >> ( k - 1 ) ) NEW_LINE DEDENT n = 13 NEW_LINE k = 2 NEW_LINE printKthBit ( n , k ) NEW_LINE |
Disjoint Set Union on trees | Set 1 | Python3 code to find maximum subtree such that all nodes are even in weight ; Structure for Edge ; ' id ' : stores parent of a node . ' sz ' : stores size of a DSU tree . ; Function to assign root ; Function to find Union ; Utility function for Union ; Edge between ' u ' and 'v ; 0... | N = 100010 NEW_LINE class Edge : NEW_LINE INDENT def __init__ ( self , u , v ) : NEW_LINE INDENT self . u = u NEW_LINE self . v = v NEW_LINE DEDENT DEDENT id = [ 0 for i in range ( N ) ] NEW_LINE sz = [ 0 for i in range ( N ) ] ; NEW_LINE def Root ( idx ) : NEW_LINE INDENT i = idx ; NEW_LINE while ( i != id [ i ] ) : N... |
Odd numbers in N | Function to get no of set bits in binary representation of positive integer n ; Count number of 1 's in binary representation of n. ; Number of odd numbers in n - th row is 2 raised to power the count . ; Driver Program | def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while n : NEW_LINE INDENT count += n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countOfOddPascal ( n ) : NEW_LINE INDENT c = countSetBits ( n ) NEW_LINE return pow ( 2 , c ) NEW_LINE DEDENT n = 20 NEW_LINE print ( countOfOddPascal ( ... |
Queries on XOR of XORs of all subarrays | Python 3 Program to answer queries on XOR of XORs of all subarray ; Output for each query ; If number of element is even . ; If number of element is odd . ; if l is even ; if l is odd ; Wrapper Function ; Evaluating prefixodd and prefixeven ; Driver Code | N = 100 NEW_LINE def ansQueries ( prefeven , prefodd , l , r ) : NEW_LINE INDENT if ( ( r - l + 1 ) % 2 == 0 ) : NEW_LINE INDENT print ( "0" ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( l % 2 == 0 ) : NEW_LINE INDENT print ( prefeven [ r ] ^ prefeven [ l - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( prefodd [... |
Variation in Nim Game | Function to return final grundy Number ( G ) of game ; if pile size is odd ; We XOR pile size + 1 ; if pile size is even ; We XOR pile size - 1 ; Game with 3 piles ; pile with different sizes ; Function to return result of game ; if ( res == 0 ) : if G is zero ; else : if G is non zero | def solve ( p , n ) : NEW_LINE INDENT G = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( p [ i ] % 2 != 0 ) : NEW_LINE INDENT G ^= ( p [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT G ^= ( p [ i ] - 1 ) NEW_LINE DEDENT DEDENT return G NEW_LINE DEDENT n = 3 NEW_LINE p = [ 32 , 49 , 58 ] NEW_LINE res = solve ... |
Maximum AND value of a pair in an array | Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Driver function | def checkBit ( pattern , arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( pattern & arr [ i ] ) == pattern ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def maxAND ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for bit in range ... |
Minimum flips to make all 1 s in left and 0 s in right | Set 1 ( Using Bitmask ) | Function to count minimum number of flips ; This is converting string s into integer of base 2 ( if s = '100' then num = 4 ) ; Initialize minXor with n that can be maximum number of flips ; Right shift 1 by ( n - 1 ) bits ; Calculate bit... | def findMiniFlip ( nums ) : NEW_LINE INDENT n = len ( nums ) NEW_LINE s = ' ' NEW_LINE for i in range ( n ) : NEW_LINE INDENT s += str ( nums [ i ] ) NEW_LINE DEDENT num = int ( s , 2 ) NEW_LINE minXor = n ; NEW_LINE mask = ( 1 << ( n - 1 ) ) NEW_LINE while ( n - 1 > 0 ) : NEW_LINE INDENT temp = ( num ^ mask ) NEW_LINE... |
Check if a number is power of 8 or not | Python3 program to check if a number is power of 8 ; function to check if power of 8 ; calculate log8 ( n ) ; check if i is an integer or not ; Driver Code | from math import log , trunc NEW_LINE def checkPowerof8 ( n ) : NEW_LINE INDENT i = log ( n , 8 ) NEW_LINE return ( i - trunc ( i ) < 0.000001 ) ; NEW_LINE DEDENT n = 65 NEW_LINE if checkPowerof8 ( n ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find the n | utility function which is used to convert binary string into integer ; convert binary string into integer ; function to find nth binary palindrome number ; stores the binary palindrome string ; base case ; add 2 nd binary palindrome string ; runs till the nth binary palindrome number ; remove curr binary p... | def convertStringToInt ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans = ans * 2 + ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getNthNumber ( n ) : NEW_LINE INDENT q = [ ] NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT n... |
Check if binary representation of a given number and its complement are anagram | An efficient Python3 program to check if binary representations of a number and it 's complement are anagram. ; Returns true if binary representations of a and b are anagram . ; _popcnt64 ( a ) gives number of 1 's present in binary repr... | ULL_SIZE = 64 NEW_LINE def bit_anagram_check ( a ) : NEW_LINE INDENT return ( bin ( a ) . count ( "1" ) == ( ULL_SIZE >> 1 ) ) NEW_LINE DEDENT a = 4294967295 NEW_LINE print ( int ( bit_anagram_check ( a ) ) ) NEW_LINE |
Sum of numbers with exactly 2 bits set | To calculate sum of numbers ; Find numbers whose 2 bits are set ; If number is greater then n we don 't include this in sum ; Return sum of numbers ; Driver Code | def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE i = 1 NEW_LINE while ( ( 1 << i ) < n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT num = ( 1 << i ) + ( 1 << j ) NEW_LINE if ( num <= n ) : NEW_LINE INDENT sum += num NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 10 NE... |
Position of rightmost different bit | Python3 implementation to find the position of rightmost different bit in two number . ; Function to find rightmost different bit in two numbers . ; Driver code | from math import floor , log10 NEW_LINE def posOfRightMostDiffBit ( m , n ) : NEW_LINE INDENT return floor ( log10 ( pow ( m ^ n , 2 ) ) ) + 2 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m , n = 52 , 4 NEW_LINE print ( " Position β = β " , posOfRightMostDiffBit ( m , n ) ) NEW_LINE DEDENT |
Set the K | function to set the kth bit ; kth bit of n is being set by this operation ; Driver code | def setKthBit ( n , k ) : NEW_LINE INDENT return ( ( 1 << k ) n ) NEW_LINE DEDENT n = 10 NEW_LINE k = 2 NEW_LINE print ( " Kth β bit β set β number β = β " , setKthBit ( n , k ) ) NEW_LINE |
Reverse an array without using subtract sign Γ’ β¬Λ | Function to reverse array ; Trick to assign - 1 to a variable ; Reverse array in simple manner ; Swap ith index value with ( n - i - 1 ) th index value ; Driver code ; print the reversed array | def reverseArray ( arr , n ) : NEW_LINE INDENT import sys NEW_LINE x = - sys . maxsize // sys . maxsize NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT arr [ i ] , arr [ n + ( x * i ) + x ] = arr [ n + ( x * i ) + x ] , arr [ i ] NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , ... |
Reverse an array without using subtract sign Γ’ β¬Λ | Function to reverse array ; Reverse array in simple manner ; Swap ith index value with ( n - i - 1 ) th index value Note : A - B = A + ~ B + 1 So n - i = n + ~ i + 1 then n - i - 1 = ( n + ~ i + 1 ) + ~ 1 + 1 ; Driver code ; print the reversed array | def reverseArray ( arr , n ) : NEW_LINE INDENT for i in range ( n // 2 ) : NEW_LINE INDENT arr [ i ] , arr [ ( n + ~ i + 1 ) + ~ 1 + 1 ] = arr [ ( n + ~ i + 1 ) + ~ 1 + 1 ] , arr [ i ] NEW_LINE DEDENT DEDENT arr = [ 5 , 3 , 7 , 2 , 1 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE reverseArray ( arr , n ) NEW_LINE for i in ran... |
Maximum XOR value of a pair from a range | Method to get maximum xor value in range [ L , R ] ; get xor of limits ; loop to get msb position of L ^ R ; construct result by adding 1 , msbPos times ; Driver code | def maxXORInRange ( L , R ) : NEW_LINE INDENT LXR = L ^ R NEW_LINE msbPos = 0 NEW_LINE while ( LXR ) : NEW_LINE INDENT msbPos += 1 NEW_LINE LXR >>= 1 NEW_LINE DEDENT maxXOR , two = 0 , 1 NEW_LINE while ( msbPos ) : NEW_LINE INDENT maxXOR += two NEW_LINE two <<= 1 NEW_LINE msbPos -= 1 NEW_LINE DEDENT return maxXOR NEW_L... |
Numbers whose bitwise OR and sum with N are equal | Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to N , whose bitwise OR and SUM with N are equal . ; count number of zero bit in N ; power of 2 to count ; Driver code | def CountZeroBit ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT if ( not ( n & 1 ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def CountORandSumEqual ( N ) : NEW_LINE INDENT count = CountZeroBit ( N ) NEW_LINE return ( 1 << count ) NEW_LI... |
Count smaller numbers whose XOR with n produces greater value | Python program to count numbers whose XOR with n produces a value more than n . ; Position of current bit in n ; Traverse bits from LSB to MSB ; Initialize result ; If current bit is 0 , then there are 2 ^ k numbers with current bit 1 and whose XOR with n ... | def countNumbers ( n ) : NEW_LINE INDENT k = 0 NEW_LINE count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT if ( ( n & 1 ) == 0 ) : NEW_LINE INDENT count += pow ( 2 , k ) NEW_LINE DEDENT k += 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT n = 11 NEW_LINE print ( countNumbers ( n ) ) NEW_LINE |
Count all pairs with given XOR | Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty set that stores the visiting element of array . ; If there exist an element in set s with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with arr [ i ] ... | def xorPairCount ( arr , n , x ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( x ^ arr [ i ] in s ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT s . add ( arr [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [... |
Multiples of 4 ( An Interesting Method ) | Returns true if n is a multiple of 4. ; Find XOR of all numbers from 1 to n ; If XOR is equal n , then return true ; Printing multiples of 4 using above method | def isMultipleOf4 ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT XOR = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT XOR = XOR ^ i NEW_LINE DEDENT return ( XOR == n ) NEW_LINE DEDENT for n in range ( 0 , 43 ) : NEW_LINE INDENT if ( isMultipleOf4 ( n ) ) : NEW_LINE INDEN... |
Check sum of Covered and Uncovered nodes of Binary Tree | To create a newNode of tree and return pointer ; Utility function to calculate sum of all node of tree ; Recursive function to calculate sum of left boundary elements ; If leaf node , then just return its key value ; If left is available then go left otherwise g... | class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def Sum ( t ) : NEW_LINE INDENT if ( t == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return t . key + Sum ( t . left ) + Sum ( t . right ) NEW_LINE DEDE... |
Check if a number is Bleak | An efficient Python 3 program to check Bleak Number ; Function to get no of set bits in binary representation of passed binary no . ; A function to return ceiling of log x in base 2. For example , it returns 3 for 8 and 4 for 9. ; Returns true if n is Bleak ; Check for all numbers ' x ' sma... | import math NEW_LINE def countSetBits ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x ) : NEW_LINE INDENT x = x & ( x - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def ceilLog2 ( x ) : NEW_LINE INDENT count = 0 NEW_LINE x = x - 1 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT x = x >> 1... |
Count strings with consecutive 1 's | Returns count of n length binary strings with consecutive 1 's ; Count binary strings without consecutive 1 's. See the approach discussed on be ( http:goo.gl/p8A3sW ) ; Subtract a [ n - 1 ] + b [ n - 1 ] from 2 ^ n ; Driver code | def countStrings ( n ) : NEW_LINE INDENT a = [ 0 ] * n NEW_LINE b = [ 0 ] * n NEW_LINE a [ 0 ] = b [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] + b [ i - 1 ] NEW_LINE b [ i ] = a [ i - 1 ] NEW_LINE DEDENT return ( 1 << n ) - a [ n - 1 ] - b [ n - 1 ] NEW_LINE DEDENT print ( countS... |
How to swap two bits in a given integer ? | Python code for swapping given bits of a number ; left - shift 1 p1 and p2 times and using XOR ; Driver Code | def swapBits ( n , p1 , p2 ) : NEW_LINE INDENT n ^= 1 << p1 NEW_LINE n ^= 1 << p2 NEW_LINE return n NEW_LINE DEDENT print ( " Result β = " , swapBits ( 28 , 0 , 3 ) ) NEW_LINE |
Maximum length sub | Function to return the maximum length of the required sub - array ; To store the maximum length for a valid subarray ; To store the count of contiguous similar elements for previous group and the current group ; If current element is equal to the previous element then it is a part of the same group... | def maxLength ( a , n ) : NEW_LINE INDENT maxLen = 0 ; NEW_LINE prev_cnt = 0 ; curr_cnt = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] == a [ i - 1 ] ) : NEW_LINE INDENT curr_cnt += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT prev_cnt = curr_cnt ; NEW_LINE curr_cnt = 1 ; NEW_LINE DEDENT maxLen = ... |
Traveling Salesman Problem using Branch And Bound | Python3 program to solve Traveling Salesman Problem using Branch and Bound . ; final_path [ ] stores the final solution i . e . the path of the salesman . ; visited [ ] keeps track of the already visited nodes in a particular path ; Stores the final minimum weight of ... | import math NEW_LINE maxsize = float ( ' inf ' ) NEW_LINE final_path = [ None ] * ( N + 1 ) NEW_LINE visited = [ False ] * N NEW_LINE final_res = maxsize NEW_LINE TSP ( adj ) NEW_LINE print ( " Minimum β cost β : " , final_res ) NEW_LINE print ( " Path β Taken β : β " , end = ' β ' ) NEW_LINE for i in range ( N + 1 ) :... |
Check if two nodes are cousins in a Binary Tree | A Binary Tree Node ; Recursive function to check if two Nodes are siblings ; Base Case ; Recursive function to find level of Node ' ptr ' in a binary tree ; Base Case ; Return level if Node is present in left subtree ; Else search in right subtree ; Returns 1 if a and b... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isSibling ( root , a , b ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( ( root . left == a and root ... |
Check if all leaves are at same level | A binary tree node ; Recursive function which check whether all leaves are at same level ; Base Case ; If a tree node is encountered ; When a leaf node is found first time ; Set first leaf found ; If this is not first leaf node , compare its level with first leaf 's level ; If th... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def checkUtil ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT if root . left is None and root . ... |
Number of siblings of a given Node in n | Python3 program to find number of siblings of a given node ; Represents a node of an n - ary tree ; Function to calculate number of siblings of a given node ; Creating a queue and pushing the root ; Dequeue an item from queue and check if it is equal to x If YES , then return n... | from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . child = [ ] NEW_LINE self . key = data NEW_LINE DEDENT DEDENT def numberOfSiblings ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = Queue ( ) NEW_LINE q... |
Check if all leaves are at same level | Python3 program to check if all leaf nodes are at same level of binary tree ; Tree Node returns a new tree Node ; return true if all leaf nodes are at same level , else false ; create a queue for level order traversal ; traverse until the queue is empty ; traverse for complete le... | INT_MAX = 2 ** 31 NEW_LINE INT_MIN = - 2 ** 31 NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def checkLevelLeafNode ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 1 NEW_LIN... |
Sorting a Queue without extra space | Python3 program to implement sorting a queue data structure ; Queue elements after sortedIndex are already sorted . This function returns index of minimum element from front to sortedIndex ; This is dequeue ( ) in C ++ STL ; we add the condition i <= sortedIndex because we don 't w... | from queue import Queue NEW_LINE def minIndex ( q , sortedIndex ) : NEW_LINE INDENT min_index = - 1 NEW_LINE min_val = 999999999999 NEW_LINE n = q . qsize ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( curr <= min_val and i <= sortedIndex ) : NEW_LINE INDEN... |
Check if removing an edge can divide a Binary Tree in two halves | Python3 program to check if there exist an edge whose removal creates two trees of same size utility function to create a new node ; To calculate size of tree with given root ; This function returns true if there is an edge whose removal can divide the ... | class newNode : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def count ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( count ( root . left ) + count ( root . right ) + 1 ) ... |
Sliding Window Maximum ( Maximum of all subarrays of size k ) | Python program to find the maximum for each and every contiguous subarray of size k ; A Deque ( Double ended queue ) based method for printing maximum element of all subarrays of size k ; Create a Double Ended Queue , Qi that will store indexes of array el... | from collections import deque NEW_LINE def printMax ( arr , n , k ) : NEW_LINE INDENT Qi = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT while Qi and arr [ i ] >= arr [ Qi [ - 1 ] ] : NEW_LINE INDENT Qi . pop ( ) NEW_LINE DEDENT Qi . append ( i ) ; NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT ... |
Sum of minimum and maximum elements of all subarrays of size k . | Python3 program to find Sum of all minimum and maximum elements Of Sub - array Size k . ; Returns Sum of min and max element of all subarrays of size k ; Initialize result ; The queue will store indexes of useful elements in every window In deque ' G ' ... | from collections import deque NEW_LINE def SumOfKsubArray ( arr , n , k ) : NEW_LINE INDENT Sum = 0 NEW_LINE S = deque ( ) NEW_LINE G = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT while ( len ( S ) > 0 and arr [ S [ - 1 ] ] >= arr [ i ] ) : NEW_LINE INDENT S . pop ( ) NEW_LINE DEDENT while ( len ( G ) > 0... |
Check if removing an edge can divide a Binary Tree in two halves | Python3 program to check if there exist an edge whose removal creates two trees of same size ; To calculate size of tree with given root ; This function returns size of tree rooted with given root . It also set " res " as true if there is an edge whose ... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def count ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( count ( node . left ) + count ( node . righ... |
Distance of nearest cell having 1 in a binary matrix | Prthe distance of nearest cell having 1 for each cell . ; Initialize the answer matrix with INT_MAX . ; For each cell ; Traversing the whole matrix to find the minimum distance . ; If cell contain 1 , check for minimum distance . ; Printing the answer . ; Driver Co... | def printDistance ( mat ) : NEW_LINE INDENT global N , M NEW_LINE ans = [ [ None ] * M for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT ans [ i ] [ j ] = 999999999999 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LIN... |
Distance of nearest cell having 1 in a binary matrix | Python3 program to find distance of nearest cell having 1 in a binary matrix . ; Making a class of graph with bfs function . ; Function to create graph with N * M nodes considering each cell as a node and each boundary as an edge . ; A number to be assigned to a ce... | from collections import deque NEW_LINE MAX = 500 NEW_LINE N = 3 NEW_LINE M = 4 NEW_LINE g = [ [ ] for i in range ( MAX ) ] NEW_LINE n , m = 0 , 0 NEW_LINE def createGraph ( ) : NEW_LINE INDENT global g , n , m NEW_LINE k = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE... |
First negative integer in every window of size k | Function to find the first negative integer in every window of size k ; Loop for each subarray ( window ) of size k ; Traverse through the current window ; If a negative integer is found , then it is the first negative integer for current window . Print it , set the fl... | def printFirstNegativeInteger ( arr , n , k ) : NEW_LINE INDENT for i in range ( 0 , ( n - k + 1 ) ) : NEW_LINE INDENT flag = False NEW_LINE for j in range ( 0 , k ) : NEW_LINE INDENT if ( arr [ i + j ] < 0 ) : NEW_LINE INDENT print ( arr [ i + j ] , end = " β " ) NEW_LINE flag = True NEW_LINE break NEW_LINE DEDENT DED... |
First negative integer in every window of size k | Python3 implementation to find the first negative integer in every window of size k import deque ( ) from collections ; function to find the first negative integer in every window of size k ; A Double Ended Queue , Di that will store indexes of useful array elements fo... | from collections import deque NEW_LINE def printFirstNegativeInteger ( arr , n , k ) : NEW_LINE INDENT Di = deque ( ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT Di . append ( i ) ; NEW_LINE DEDENT DEDENT for i in range ( k , n ) : NEW_LINE INDENT if ( not Di ) : NEW_LINE INDE... |
First negative integer in every window of size k | Python3 code for First negative integer in every window of size k ; skip out of window and positive elements ; check if a negative element is found , otherwise use 0 ; Driver code | def printFirstNegativeInteger ( arr , k ) : NEW_LINE INDENT firstNegativeIndex = 0 NEW_LINE for i in range ( k - 1 , len ( arr ) ) : NEW_LINE INDENT while firstNegativeIndex < i and ( firstNegativeIndex <= i - k or arr [ firstNegativeIndex ] > 0 ) : NEW_LINE INDENT firstNegativeIndex += 1 NEW_LINE DEDENT firstNegativeE... |
Check if all levels of two trees are anagrams or not | Returns true if trees with root1 and root2 are level by level anagram , else returns false . ; Base Cases ; start level order traversal of two trees using two queues . ; n1 ( queue size ) indicates number of Nodes at current level in first tree and n2 indicates num... | def areAnagrams ( root1 , root2 ) : NEW_LINE INDENT if ( root1 == None and root2 == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root1 == None or root2 == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT q1 = [ ] NEW_LINE q2 = [ ] NEW_LINE q1 . append ( root1 ) NEW_LINE q2 . append ( root2 ) NEW_LINE ... |
Check if given Preorder , Inorder and Postorder traversals are of same tree | Python3 program to check if all three given traversals are of the same tree ; A Binary Tree Node ; Function to find index of value in arr [ start ... end ] . The function assumes that value is present in in ; Recursive function to construct b... | preIndex = 0 NEW_LINE class node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def search ( arr , strt , end , value ) : NEW_LINE INDENT for i in range ( strt , end + 1 ) : NEW_LINE INDENT if ( arr [ i ] == v... |
Check if X can give change to every person in the Queue | Function to check if every person will get the change from X ; To count the 5 $ and 10 & notes ; Serve the customer in order ; Increase the number of 5 $ note by one ; decrease the number of note 5 $ and increase 10 $ note by one ; decrease 5 $ and 10 $ note by ... | def isChangeable ( notes , n ) : NEW_LINE INDENT fiveCount = 0 NEW_LINE tenCount = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( notes [ i ] == 5 ) : NEW_LINE INDENT fiveCount += 1 NEW_LINE DEDENT elif ( notes [ i ] == 10 ) : NEW_LINE INDENT if ( fiveCount > 0 ) : NEW_LINE INDENT fiveCount -= 1 NEW_LINE tenCou... |
Index Mapping ( or Trivial Hashing ) with negatives allowed | Python3 program to implement direct index mapping with negative values allowed . ; Since array is global , it is initialized as 0. ; Searching if X is Present in the given array or not . ; if X is negative take the absolute value of X . ; Driver code ; Since... | MAX = 1000 NEW_LINE has = [ [ 0 for i in range ( 2 ) ] for j in range ( MAX + 1 ) ] NEW_LINE def search ( X ) : NEW_LINE INDENT if X >= 0 : NEW_LINE INDENT return has [ X ] [ 0 ] == 1 NEW_LINE DEDENT X = abs ( X ) NEW_LINE return has [ X ] [ 1 ] == 1 NEW_LINE DEDENT def insert ( a , n ) : NEW_LINE INDENT for i in range... |
Given level order traversal of a Binary Tree , check if the Tree is a Min | Returns true if given level order traversal is Min Heap . ; First non leaf node is at index ( n / 2 - 1 ) . Check whether each parent is greater than child ; Left child will be at index 2 * i + 1 Right child will be at index 2 * i + 2 ; If pare... | def isMinHeap ( level , n ) : NEW_LINE INDENT for i in range ( int ( n / 2 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if level [ i ] > level [ 2 * i + 1 ] : NEW_LINE INDENT return False NEW_LINE DEDENT if 2 * i + 2 < n : NEW_LINE INDENT if level [ i ] > level [ 2 * i + 2 ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDE... |
Minimum delete operations to make all elements of array same | Function to get minimum number of elements to be deleted from array to make array elements equal ; Create an dictionary and store frequencies of all array elements in it using element as key and frequency as value ; Find maximum frequency among all frequenc... | def minDelete ( arr , n ) : NEW_LINE INDENT freq = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in freq : NEW_LINE INDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT freq [ arr [ i ] ] = 1 ; NEW_LINE DEDENT DEDENT max_freq = 0 ; NEW_LINE for i , j in freq . items ( ) : NEW_LINE IN... |
Minimum operation to make all elements equal in array | Python3 program to find the minimum number of operations required to make all elements of array equal ; Function for min operation ; Insert all elements in hash . ; find the max frequency ; return result ; Driver Code | from collections import defaultdict NEW_LINE def minOperation ( arr , n ) : NEW_LINE INDENT Hash = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Hash [ arr [ i ] ] += 1 NEW_LINE DEDENT max_count = 0 NEW_LINE for i in Hash : NEW_LINE INDENT if max_count < Hash [ i ] : NEW_LINE INDENT max... |
Maximum distance between two occurrences of same element in array | Function to find maximum distance between equal elements ; Used to store element to first index mapping ; Traverse elements and find maximum distance between same occurrences with the help of map . ; If this is first occurrence of element , insert its ... | def maxDistance ( arr , n ) : NEW_LINE INDENT mp = { } NEW_LINE maxDict = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] = i NEW_LINE DEDENT else : NEW_LINE INDENT maxDict = max ( maxDict , i - mp [ arr [ i ] ] ) NEW_LINE DEDENT DEDENT return maxDi... |
Check if a given array contains duplicate elements within k distance from each other | Python 3 program to Check if a given array contains duplicate elements within k distance from each other ; Creates an empty list ; Traverse the input array ; If already present n hash , then we found a duplicate within k distance ; A... | def checkDuplicatesWithinK ( arr , n , k ) : NEW_LINE INDENT myset = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in myset : NEW_LINE INDENT return True NEW_LINE DEDENT myset . append ( arr [ i ] ) NEW_LINE if ( i >= k ) : NEW_LINE INDENT myset . remove ( arr [ i - k ] ) NEW_LINE DEDENT DEDENT retur... |
Find duplicates in a given array when elements are not limited to a range | Function to find the Duplicates , if duplicate occurs 2 times or more than 2 times in array so , it will print duplicate value only once at output ; Initialize ifPresent as false ; ArrayList to store the output ; Checking if element is present ... | def findDuplicates ( arr , Len ) : NEW_LINE INDENT ifPresent = False NEW_LINE a1 = [ ] NEW_LINE for i in range ( Len - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , Len ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT if arr [ i ] in a1 : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT ... |
Check if leaf traversal of two Binary Trees is same ? | Binary Tree node ; checks if a given node is leaf or not . ; Returns true of leaf traversal of two trees is same , else false ; Create empty stacks . These stacks are going to be used for iterative traversals . ; Loop until either of two stacks is not empty ; If o... | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = self . right = None NEW_LINE DEDENT def isLeaf ( self ) : NEW_LINE INDENT return ( self . left == None and self . right == None ) NEW_LINE DEDENT DEDENT def isSame ( root1 , root2 ) : NEW_LINE INDENT s1 = [ ]... |
Most frequent element in an array | Python3 program to find the most frequent element in an array . ; Sort the array ; find the max frequency using linear traversal ; If last element is most frequent ; Driver Code | def mostFrequent ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE max_count = 1 ; res = arr [ 0 ] ; curr_count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT curr_count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( curr_count > max_count ) : NEW_LINE ... |
Most frequent element in an array | Python3 program to find the most frequent element in an array . ; Insert all elements in Hash . ; find the max frequency ; Driver Code | import math as mt NEW_LINE def mostFrequent ( arr , n ) : NEW_LINE INDENT Hash = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in Hash . keys ( ) : NEW_LINE INDENT Hash [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Hash [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT max_count = 0 NEW_LINE ... |
Smallest subarray with all occurrences of a most frequent element | Python3 implementation to find smallest subarray with all occurrences of a most frequent element ; To store left most occurrence of elements ; To store counts of elements ; To store maximum frequency ; To store length and starting index of smallest res... | def smallestSubsegment ( a , n ) : NEW_LINE INDENT left = dict ( ) NEW_LINE count = dict ( ) NEW_LINE mx = 0 NEW_LINE mn , strindex = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE if ( x not in count . keys ( ) ) : NEW_LINE INDENT left [ x ] = i NEW_LINE count [ x ] = 1 NEW_LINE DEDENT else... |
Given an array of pairs , find all symmetric pairs in it | Print all pairs that have a symmetric counterpart ; Creates an empty hashMap hM ; Traverse through the given array ; First and second elements of current pair ; If found and value in hash matches with first element of this pair , we found symmetry ; Else put se... | def findSymPairs ( arr , row ) : NEW_LINE INDENT hM = dict ( ) NEW_LINE for i in range ( row ) : NEW_LINE INDENT first = arr [ i ] [ 0 ] NEW_LINE sec = arr [ i ] [ 1 ] NEW_LINE if ( sec in hM . keys ( ) and hM [ sec ] == first ) : NEW_LINE INDENT print ( " ( " , sec , " , " , first , " ) " ) NEW_LINE DEDENT else : NEW_... |
Find any one of the multiple repeating elements in read only array | Python 3 program to find one of the repeating elements in a read only array ; Function to find one of the repeating elements ; Size of blocks except the last block is sq ; Number of blocks to incorporate 1 to n values blocks are numbered from 0 to ran... | from math import sqrt NEW_LINE def findRepeatingNumber ( arr , n ) : NEW_LINE INDENT sq = sqrt ( n ) NEW_LINE range__ = int ( ( n / sq ) + 1 ) NEW_LINE count = [ 0 for i in range ( range__ ) ] NEW_LINE for i in range ( 0 , n + 1 , 1 ) : NEW_LINE INDENT count [ int ( ( arr [ i ] - 1 ) / sq ) ] += 1 NEW_LINE DEDENT selec... |
Group multiple occurrence of array elements ordered by first occurrence | A simple method to group all occurrences of individual elements ; Initialize all elements as not visited ; Traverse all elements ; Check if this is first occurrence ; If yes , print it and all subsequent occurrences ; Driver Code | def groupElements ( arr , n ) : NEW_LINE INDENT visited = [ False ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT visited [ i ] = False NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE for j in range ( i + 1 ,... |
Group multiple occurrence of array elements ordered by first occurrence | A hashing based method to group all occurrences of individual elements ; Creates an empty hashmap ; Traverse the array elements , and store count for every element in HashMap ; Increment count of elements in HashMap ; Traverse array again ; Check... | def orderedGroup ( arr ) : NEW_LINE INDENT hM = { } NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT hM [ arr [ i ] ] = hM . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT count = hM . get ( arr [ i ] , None ) NEW_LINE if count != None : NEW_LINE INDENT for j... |
How to check if two given sets are disjoint ? | Returns true if set1 [ ] and set2 [ ] are disjoint , else false ; Take every element of set1 [ ] and search it in set2 ; If no element of set1 is present in set2 ; Driver program | def areDisjoint ( set1 , set2 , m , n ) : NEW_LINE INDENT for i in range ( 0 , m ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( set1 [ i ] == set2 [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT set1 = [ 12 , 34 , 11 , 9 , 3 ] NEW_LINE set2 = [ 7 , 2... |
How to check if two given sets are disjoint ? | Returns true if set1 [ ] and set2 [ ] are disjoint , else false ; Sort the given two sets ; Check for same elements using merge like process ; if set1 [ i ] == set2 [ j ] ; Driver Code | def areDisjoint ( set1 , set2 , m , n ) : NEW_LINE INDENT set1 . sort ( ) NEW_LINE set2 . sort ( ) NEW_LINE i = 0 ; j = 0 NEW_LINE while ( i < m and j < n ) : NEW_LINE INDENT if ( set1 [ i ] < set2 [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( set2 [ j ] < set1 [ i ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT... |
How to check if two given sets are disjoint ? | This function prints all distinct elements ; Creates an empty hashset ; Traverse the first set and store its elements in hash ; Traverse the second set and check if any element of it is already in hash or not . ; Driver method to test above method | def areDisjoint ( set1 , set2 , n1 , n2 ) : NEW_LINE INDENT myset = set ( [ ] ) NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT myset . add ( set1 [ i ] ) NEW_LINE DEDENT for i in range ( n2 ) : NEW_LINE INDENT if ( set2 [ i ] in myset ) : NEW_LINE return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ =... |
Non | Python3 program to find Non - overlapping sum ; Function for calculating Non - overlapping sum of two array ; Insert elements of both arrays ; calculate non - overlapped sum ; Driver code ; size of array ; Function call | from collections import defaultdict NEW_LINE def findSum ( A , B , n ) : NEW_LINE INDENT Hash = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Hash [ A [ i ] ] += 1 NEW_LINE Hash [ B [ i ] ] += 1 NEW_LINE DEDENT Sum = 0 NEW_LINE for x in Hash : NEW_LINE INDENT if Hash [ x ] == 1 : NEW_LI... |
Find elements which are present in first array and not in second | Function for finding elements which are there in a [ ] but not in b [ ] . ; Driver code | def findMissing ( a , b , n , m ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( a [ i ] == b [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == m - 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ ... |
Find elements which are present in first array and not in second | Function for finding elements which are there in a [ ] but not in b [ ] . ; Store all elements of second array in a hash table ; Print all elements of first array that are not present in hash table ; Driver code | def findMissing ( a , b , n , m ) : NEW_LINE INDENT s = dict ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT s [ b [ i ] ] = 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if a [ i ] not in s . keys ( ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT a = [ 1 , 2 , 6 , 3 , 4... |
Check if two arrays are equal or not | Returns true if arr1 [ 0. . n - 1 ] and arr2 [ 0. . m - 1 ] contain same elements . ; If lengths of array are not equal means array are not equal ; Sort both arrays ; Linearly compare elements ; If all elements were same . ; Driver Code | def areEqual ( arr1 , arr2 , n , m ) : NEW_LINE INDENT if ( n != m ) : NEW_LINE INDENT return False NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE ... |
Pair with given sum and maximum shortest distance from end | function to find maximum shortest distance ; stores the shortest distance of every element in original array . ; shortest distance from ends ; if duplicates are found , b [ x ] is replaced with minimum of the previous and current position 's shortest distanc... | def find_maximum ( a , n , k ) : NEW_LINE INDENT b = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = a [ i ] NEW_LINE d = min ( 1 + i , n - i ) NEW_LINE if x not in b . keys ( ) : NEW_LINE INDENT b [ x ] = d NEW_LINE DEDENT else : NEW_LINE INDENT b [ x ] = min ( d , b [ x ] ) NEW_LINE DEDENT DEDENT ans = 1... |
Pair with given product | Set 1 ( Find if any pair exists ) | Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x ; Consider all possible pairs and check for every pair . ; Driver code | def isProduct ( arr , n , x ) : NEW_LINE INDENT for i in arr : NEW_LINE INDENT for j in arr : NEW_LINE INDENT if i * j == x : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 10 , 20 , 9 , 40 ] NEW_LINE x = 400 NEW_LINE n = len ( arr ) NEW_LINE if ( isProduct ( arr , n , x ... |
Pair with given product | Set 1 ( Find if any pair exists ) | Returns true if there is a pair in arr [ 0. . n - 1 ] with product equal to x . ; Create an empty set and insert first element into it ; Traverse remaining elements ; 0 case must be handles explicitly as x % 0 is undefined behaviour in C ++ ; x / arr [ i ] e... | def isProduct ( arr , n , x ) : NEW_LINE INDENT if n < 2 : NEW_LINE INDENT return False NEW_LINE DEDENT s = set ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT continue NEW_LINE DEDENT DEDENT if x ... |
Check whether a given binary tree is perfect or not | Returns depth of leftmost leaf . ; This function tests if a binary treeis perfect or not . It basically checks for two things : 1 ) All leaves are at same level 2 ) All internal nodes have two children ; An empty tree is perfect ; If leaf node , then its depth must ... | def findADepth ( node ) : NEW_LINE INDENT d = 0 NEW_LINE while ( node != None ) : NEW_LINE INDENT d += 1 NEW_LINE node = node . left NEW_LINE DEDENT return d NEW_LINE DEDENT def isPerfectRec ( root , d , level = 0 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root . left == ... |
Find pair with greatest product in array | Function to find greatest number ; Driver code | def findGreatest ( arr , n ) : NEW_LINE INDENT result = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] * arr [ k ] == arr [ i ] ) : NEW_LINE INDENT result = max ( result , arr [ i ] ) NEW_LINE DEDENT DEDENT DED... |
Find pair with greatest product in array | Python3 program to find the largest product number ; Function to find greatest number ; Store occurrences of all elements in hash array ; Sort the array and traverse all elements from end . ; For every element , check if there is another element which divides it . ; Check if t... | from math import sqrt NEW_LINE def findGreatest ( arr , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in arr : NEW_LINE INDENT m [ i ] = m . get ( i , 0 ) + 1 NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < i and arr [ j ] <= sqrt ( arr [... |
Remove minimum number of elements such that no common element exist in both array | To find no elements to remove so no common element exist ; To store count of array element ; Count elements of a ; Count elements of b ; Traverse through all common element , and pick minimum occurrence from two arrays ; To return count... | def minRemove ( a , b , n , m ) : NEW_LINE INDENT countA = dict ( ) NEW_LINE countB = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT countA [ a [ i ] ] = countA . get ( a [ i ] , 0 ) + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT countB [ b [ i ] ] = countB . get ( b [ i ] , 0 ) + 1 NEW_LINE DEDEN... |
Count items common to both the lists but with different prices | function to count items common to both the lists but with different prices ; for each item of ' list1' check if it is in ' list2' but with a different price ; required count of items ; Driver program to test above | def countItems ( list1 , list2 ) : NEW_LINE INDENT count = 0 NEW_LINE for i in list1 : NEW_LINE INDENT for j in list2 : NEW_LINE INDENT if i [ 0 ] == j [ 0 ] and i [ 1 ] != j [ 1 ] : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT list1 = [ ( " apple " , 60 ) , ( " bread " , 20 ) ,... |
Minimum Index Sum for Common Elements of Two Lists | Function to print common strings with minimum index sum ; resultant list ; iterating over sum in ascending order ; iterating over one list and check index ( Corresponding to given sum ) in other list ; put common strings in resultant list ; if common string found the... | def find ( list1 , list2 ) : NEW_LINE INDENT res = [ ] NEW_LINE max_possible_sum = len ( list1 ) + len ( list2 ) - 2 NEW_LINE for sum in range ( max_possible_sum + 1 ) : NEW_LINE INDENT for i in range ( sum + 1 ) : NEW_LINE INDENT if ( i < len ( list1 ) and ( sum - i ) < len ( list2 ) and list1 [ i ] == list2 [ sum - i... |
Minimum Index Sum for Common Elements of Two Lists | Hashing based Python3 program to find common elements with minimum index sum ; Function to print common strings with minimum index sum ; Mapping strings to their indices ; Resultant list ; If current sum is smaller than minsum ; If index sum is same then put this str... | import sys NEW_LINE def find ( list1 , list2 ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( len ( list1 ) ) : NEW_LINE INDENT Map [ list1 [ i ] ] = i NEW_LINE DEDENT res = [ ] NEW_LINE minsum = sys . maxsize NEW_LINE for j in range ( len ( list2 ) ) : NEW_LINE INDENT if list2 [ j ] in Map : NEW_LINE INDENT Sum... |
Check whether a binary tree is a full binary tree or not | Constructor of the node class for creating the node ; Checks if the binary tree is full or not ; If empty tree ; If leaf node ; If both left and right subtress are not None and left and right subtress are full ; We reach here when none of the above if condiitio... | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isFullTree ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT if root . left is None and root . right is N... |
Change the array into a permutation of numbers from 1 to n | Python3 code to make a permutation of numbers from 1 to n using minimum changes . ; Store counts of all elements . ; Find next missing element to put in place of current element . ; Replace with next missing and insert the missing element in hash . ; Driver C... | def makePermutation ( a , n ) : NEW_LINE INDENT count = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if count . get ( a [ i ] ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ a [ i ] ] = 1 ; NEW_LINE DEDENT DEDENT next_missing = 1 NEW_LINE for i in range ( n ) : NEW_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.