text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Unique element in an array where all elements occur k times except one | Python 3 program to find unique element where every element appears k times except one ; Create a count array to store count of numbers that have a particular bit set . count [ i ] stores count of array elements with i - th bit set . ; AND ( bitwi...
import sys NEW_LINE def findUnique ( a , n , k ) : NEW_LINE INDENT INT_SIZE = 8 * sys . getsizeof ( int ) NEW_LINE count = [ 0 ] * INT_SIZE NEW_LINE for i in range ( INT_SIZE ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ( a [ j ] & ( 1 << i ) ) != 0 ) : NEW_LINE INDENT count [ i ] += 1 NEW_LINE DEDEN...
Check whether the number has only first and last bits set | function to check whether ' n ' is a power of 2 or not ; function to check whether number has only first and last bits set ; Driver program to test above
def powerOfTwo ( n ) : NEW_LINE INDENT return ( not ( n & n - 1 ) ) NEW_LINE DEDENT def onlyFirstAndLastAreSet ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return powerOfTwo ( n - 1 ) NEW_LINE DEDENT n = 9 NEW_LINE if ( onlyFirstAndLastAreSet ( n ) ) : NEW_LINE INDENT print ( ' Ye...
Check if a number has bits in alternate pattern | Set | function to check if all the bits are set or not in the binary representation of 'n ; if true , then all bits are set ; else all bits are not set ; function to check if a number has bits in alternate pattern ; to check if all bits are set in 'num ; Driver code
' NEW_LINE def allBitsAreSet ( n ) : NEW_LINE INDENT if ( ( ( n + 1 ) & n ) == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT def bitsAreInAltOrder ( n ) : NEW_LINE INDENT num = n ^ ( n >> 1 ) ; NEW_LINE DEDENT ' NEW_LINE INDENT return allBitsAreSet ( num ) ; NEW_LINE DEDENT n = 10 ;...
Minimum flips required to maximize a number with k set bits | Python3 for finding min flip for maximizing given n ; function for finding set bit ; return count of set bit ; function for finding min flip ; number of bits in n ; Find the largest number of same size with k set bits ; Count bit differences to find required...
import math NEW_LINE def setBit ( xorValue ) : NEW_LINE INDENT count = 0 NEW_LINE while ( xorValue ) : NEW_LINE INDENT if ( xorValue % 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT xorValue = int ( xorValue / 2 ) NEW_LINE DEDENT return count NEW_LINE DEDENT def minFlip ( n , k ) : NEW_LINE INDENT size = int ( math ....
Set all the bits in given range of a number | Function to toggle bits in the given range ; calculating a number ' range ' having set bits in the range from l to r and all other bits as 0 ( or unset ) . ; Driver code
def setallbitgivenrange ( n , l , r ) : NEW_LINE INDENT range = ( ( ( 1 << ( l - 1 ) ) - 1 ) ^ ( ( 1 << ( r ) ) - 1 ) ) NEW_LINE return ( n range ) NEW_LINE DEDENT n , l , r = 17 , 2 , 3 NEW_LINE print ( setallbitgivenrange ( n , l , r ) ) NEW_LINE
Count total bits in a number | Python3 program to find total bit in given number ; log function in base 2 take only integer part ; Driver Code
import math NEW_LINE def countBits ( number ) : NEW_LINE INDENT return int ( ( math . log ( number ) / math . log ( 2 ) ) + 1 ) ; NEW_LINE DEDENT num = 65 ; NEW_LINE print ( countBits ( num ) ) ; NEW_LINE
Check whether all the bits are unset in the given range or not | function to check whether all the bits are unset 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 ...
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 ( new_num == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 17 NEW_LINE l =...
Toggle all bits after most significant bit | Returns a number which has all set bits starting from MSB of n ; This makes sure two bits ( From MSB and including MSB ) are set ; This makes sure 4 bits ( From MSB and including MSB ) are set ; Driver code
def setAllBitsAfterMSB ( 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 NEW_LINE DEDENT def toggle ( n ) : NEW_LINE INDENT n = n ^ setAllBitsAfterMSB ( n ) NEW_LINE return n NEW_LINE DEDENT n = 10 NEW_LINE n = toggle ( n ) NEW_LIN...
Check if a number has two adjacent set bits | Python 3 program to check if there are two adjacent set bits . ; Driver Code
def adjacentSet ( n ) : NEW_LINE INDENT return ( n & ( n >> 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE if ( adjacentSet ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Position of rightmost common bit in two numbers | Python3 implementation to find the position of rightmost same bit ; Function to find the position of rightmost set bit in 'n ; Function to find the position of rightmost same bit in the binary representations of ' m ' and 'n ; position of rightmost same bit ; Driver Cod...
import math NEW_LINE ' NEW_LINE def getRightMostSetBit ( n ) : NEW_LINE INDENT return int ( math . log2 ( n & - n ) ) + 1 NEW_LINE DEDENT ' NEW_LINE def posOfRightMostSameBit ( m , n ) : NEW_LINE INDENT return getRightMostSetBit ( ~ ( m ^ n ) ) NEW_LINE DEDENT m , n = 16 , 7 NEW_LINE print ( " Position ▁ = ▁ " , posOfR...
Position of rightmost common bit in two numbers | Function to find the position of rightmost same bit in the binary representations of ' m ' and 'n ; Initialize loop counter ; Check whether the value ' m ' is odd ; Check whether the value ' n ' is odd ; Below ' if ' checks for both values to be odd or even ; Right shif...
' NEW_LINE def posOfRightMostSameBit ( m , n ) : NEW_LINE INDENT loopCounter = 1 NEW_LINE while ( m > 0 or n > 0 ) : NEW_LINE INDENT a = m % 2 == 1 NEW_LINE b = n % 2 == 1 NEW_LINE if ( not ( a ^ b ) ) : NEW_LINE INDENT return loopCounter NEW_LINE DEDENT m = m >> 1 NEW_LINE n = n >> 1 NEW_LINE loopCounter += 1 NEW_LINE...
Check whether all the bits are set in the given range | 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 no...
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 " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT n , l , r = 22 , 2 , 3 NEW_LINE print ( allBitsSetInTheGivenRange (...
1 to n bit numbers with no consecutive 1 s in binary representation | Python3 program to print all numbers upto n bits with no consecutive set bits . ; Let us first compute 2 raised to power n . ; loop 1 to n to check all the numbers ; A number i doesn ' t ▁ contain ▁ ▁ consecutive ▁ set ▁ bits ▁ if ▁ ▁ bitwise ▁ and ▁...
def printNonConsecutive ( n ) : NEW_LINE INDENT p = ( 1 << n ) NEW_LINE for i in range ( 1 , p ) : NEW_LINE INDENT if ( ( i & ( i << 1 ) ) == 0 ) : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT n = 3 NEW_LINE printNonConsecutive ( n ) NEW_LINE
Find the n | Efficient Python3 program to find n - th palindrome ; Construct the nth binary palindrome with the given group number , aux_number and operation type ; No need to insert any bit in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , ...
INT_SIZE = 32 NEW_LINE def constructNthNumber ( group_no , aux_num , op ) : NEW_LINE INDENT a = [ 0 ] * INT_SIZE NEW_LINE num , i = 0 , 0 NEW_LINE if op == 2 : NEW_LINE INDENT len_f = 2 * group_no NEW_LINE a [ len_f - 1 ] = a [ 0 ] = 1 NEW_LINE while aux_num : NEW_LINE INDENT a [ group_no + i ] = a [ group_no - 1 - i ]...
Shuffle a pack of cards and answer the query | Function to find card at given index ; Answer will be reversal of N bits from MSB ; Calculating the reverse binary representation ; Printing the result ; No . of Shuffle Steps ; Key position
def shuffle ( N , key ) : NEW_LINE INDENT NO_OF_BITS = N NEW_LINE reverse_num = 0 NEW_LINE for i in range ( NO_OF_BITS ) : NEW_LINE INDENT temp = ( key & ( 1 << i ) ) NEW_LINE if ( temp ) : NEW_LINE INDENT reverse_num |= ( 1 << ( ( NO_OF_BITS - 1 ) - i ) ) NEW_LINE DEDENT DEDENT print ( reverse_num ) NEW_LINE DEDENT N ...
Sum of numbers with exactly 2 bits set | To count number of set bits ; To calculate sum of numbers ; To count sum of number whose 2 bit are set ; Driver code
def countSetBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count = count + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def findSum ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( countSetBits ( i ) == 2 ) : NEW_LIN...
Toggle the last m bits | function to toggle the last m bits ; calculating a number ' num ' having ' m ' bits and all are set . ; toggle the last m bits and return the number ; Driver code
def toggleLastMBits ( n , m ) : NEW_LINE INDENT num = ( 1 << m ) - 1 NEW_LINE return ( n ^ num ) NEW_LINE DEDENT n = 107 NEW_LINE m = 4 NEW_LINE print ( toggleLastMBits ( n , m ) ) NEW_LINE
Set the rightmost unset bit | Python3 implementation to set the rightmost unset bit ; function to find the position of rightmost set bit ; if n = 0 , return 1 ; if all bits of ' n ' are set ; position of rightmost unset bit in ' n ' passing ~ n as argument ; set the bit at position 'pos ; Driver code
import math NEW_LINE def getPosOfRightmostSetBit ( n ) : NEW_LINE INDENT return int ( math . log2 ( n & - n ) + 1 ) NEW_LINE DEDENT def setRightmostUnsetBit ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( ( n & ( n + 1 ) ) == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT pos = get...
Previous smaller integer having one less number of set bits | Python3 implementation to find the previous smaller integer with one less number of set bits ; Function to find the position of rightmost set bit . ; Function to find the previous smaller integer ; position of rightmost set bit of n ; turn off or unset the b...
import math NEW_LINE def getFirstSetBitPos ( n ) : NEW_LINE INDENT return ( int ) ( math . log ( n & - n ) / math . log ( 2 ) ) + 1 NEW_LINE DEDENT def previousSmallerInteger ( n ) : NEW_LINE INDENT pos = getFirstSetBitPos ( n ) NEW_LINE DEDENT ' NEW_LINE INDENT return ( n & ~ ( 1 << ( pos - 1 ) ) ) NEW_LINE DEDENT n =...
Check if all bits of a number are set | function to check if all the bits are set or not in the binary representation of 'n ; all bits are not set ; loop till n becomes '0 ; if the last bit is not set ; right shift ' n ' by 1 ; all bits are set ; Driver program to test above
' NEW_LINE def areAllBitsSet ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT while ( n > 0 ) : NEW_LINE INDENT if ( ( n & 1 ) == 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT return " Yes " NEW_LINE DEDENT n = 7 NEW_LINE pri...
Check if all bits of a number are set | function to check if all the bits are set or not in the binary representation of 'n ; all bits are not set ; if true , then all bits are set ; else all bits are not set ; Driver program to test above
' NEW_LINE def areAllBitsSet ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return " No " NEW_LINE DEDENT if ( ( ( n + 1 ) & n ) == 0 ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT n = 7 NEW_LINE print ( areAllBitsSet ( n ) ) NEW_LINE
Next greater integer having one more number of set bits | Python3 implementation to find the next greater integer with one more number of set bits ; Function to find the position of rightmost set bit . Returns - 1 if there are no set bits ; Function to find the next greater integer ; position of rightmost unset bit of ...
import math NEW_LINE def getFirstSetBitPos ( n ) : NEW_LINE INDENT return ( ( int ) ( math . log ( n & - n ) / math . log ( 2 ) ) + 1 ) - 1 NEW_LINE DEDENT def nextGreaterWithOneMoreSetBit ( n ) : NEW_LINE INDENT pos = getFirstSetBitPos ( ~ n ) NEW_LINE if ( pos > - 1 ) : NEW_LINE INDENT return ( 1 << pos ) | n NEW_LIN...
Toggle all the bits of a number except k | Returns a number with all bit toggled in n except k - th bit ; 1 ) Toggle k - th bit by doing n ^ ( 1 << k ) 2 ) Toggle all bits of the modified number ; Driver code
def toggleAllExceptK ( n , k ) : NEW_LINE INDENT temp = bin ( n ^ ( 1 << k ) ) [ 2 : ] NEW_LINE ans = " " NEW_LINE for i in temp : NEW_LINE INDENT if i == '1' : NEW_LINE INDENT ans += '0' NEW_LINE DEDENT else : NEW_LINE INDENT ans += '1' NEW_LINE DEDENT DEDENT return int ( ans , 2 ) NEW_LINE DEDENT if __name__ == ' _ _...
Count numbers whose sum with x is equal to XOR with x | Function to find total 0 bit in a number ; Function to find Count of non - negative numbers less than or equal to x , whose bitwise XOR and SUM with x are equal . ; count number of zero bit in x ; power of 2 to count ; Driver code ; Function call
def CountZeroBit ( x ) : NEW_LINE INDENT count = 0 NEW_LINE while ( x ) : NEW_LINE INDENT if ( ( x & 1 ) == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT x >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def CountXORandSumEqual ( x ) : NEW_LINE INDENT count = CountZeroBit ( x ) NEW_LINE return ( 1 << count ) NEW_...
Find missing number in another array which is shuffled copy | Returns the missing number Size of arr2 [ ] is n - 1 ; missing number 'mnum ; 1 st array is of size 'n ; 2 nd array is of size 'n - 1 ; Required missing number ; Driver Code
def missingNumber ( arr1 , arr2 , n ) : NEW_LINE ' NEW_LINE INDENT mnum = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT mnum = mnum ^ arr1 [ i ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT mnum = mnum ^ arr2 [ i ] NEW_LINE DEDENT return mnum NEW_LINE ...
Find Duplicates of array using bit array | A class to represent array of bits using array of integers ; Constructor ; Divide by 32. To store n bits , we need n / 32 + 1 integers ( Assuming int is stored using 32 bits ) ; Get value of a bit at given position ; Divide by 32 to find position of integer . ; Now find bit nu...
class BitArray : NEW_LINE INDENT def __init__ ( self , n ) : NEW_LINE INDENT self . arr = [ 0 ] * ( ( n >> 5 ) + 1 ) NEW_LINE DEDENT def get ( self , pos ) : NEW_LINE INDENT self . index = pos >> 5 NEW_LINE self . bitNo = pos & 0x1F NEW_LINE return ( self . arr [ self . index ] & ( 1 << self . bitNo ) ) != 0 NEW_LINE D...
Count smaller values whose XOR with x is greater than x | Python3 program to find count of values whose XOR with x is greater than x and values are smaller than x ; Initialize result ; Traversing through all bits of x ; If current last bit of x is set then increment count by n . Here n is a power of 2 corresponding to ...
def countValues ( x ) : NEW_LINE INDENT count = 0 ; NEW_LINE n = 1 ; NEW_LINE while ( x > 0 ) : NEW_LINE INDENT if ( x % 2 == 0 ) : NEW_LINE INDENT count += n ; NEW_LINE DEDENT n *= 2 ; NEW_LINE x /= 2 ; NEW_LINE x = int ( x ) ; NEW_LINE DEDENT return count ; NEW_LINE DEDENT x = 10 ; NEW_LINE print ( countValues ( x ) ...
Construct an array from XOR of all elements of array except element at same index | function to construct new array ; calculate xor of array ; update array ; Driver code ; print result
def constructXOR ( A , n ) : NEW_LINE INDENT XOR = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT XOR ^= A [ i ] NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT A [ i ] = XOR ^ A [ i ] NEW_LINE DEDENT DEDENT A = [ 2 , 4 , 1 , 3 , 5 ] NEW_LINE n = len ( A ) NEW_LINE constructXOR ( A , n ) NEW_LINE for ...
Count all pairs of an array which differ in K bits | Utility function to count total ones in a number ; Function to count pairs of K different bits ; initialize final answer ; Check for K differ bit ; Driver code
def bitCount ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n ) : NEW_LINE INDENT if ( n & 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT n >>= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def countPairsWithKDiff ( arr , n , k ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n - 1 , 1 ) : NEW_LINE INDE...
Count all pairs of an array which differ in K bits | Function to calculate K bit different pairs in array ; Get the maximum value among all array elemensts ; Set the count array to 0 , count [ ] stores the total frequency of array elements ; Initialize result ; For 0 bit answer will be total count of same number ; if c...
def kBitDifferencePairs ( arr , n , k ) : NEW_LINE INDENT MAX = max ( arr ) NEW_LINE count = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT ans = 0 NEW_LINE if ( k == 0 ) : NEW_LINE INDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT ans += ( co...
Ways to represent a number as a sum of 1 ' s ▁ and ▁ 2' s | Function to multiply matrix . ; Power function in log n ; function that returns ( n + 1 ) th Fibonacci number Or number of ways to represent n as sum of 1 ' s ▁ 2' s ; Driver Code
def multiply ( F , M ) : NEW_LINE INDENT x = F [ 0 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 0 ] NEW_LINE y = F [ 0 ] [ 0 ] * M [ 0 ] [ 1 ] + F [ 0 ] [ 1 ] * M [ 1 ] [ 1 ] NEW_LINE z = F [ 1 ] [ 0 ] * M [ 0 ] [ 0 ] + F [ 1 ] [ 1 ] * M [ 1 ] [ 0 ] NEW_LINE w = F [ 1 ] [ 0 ] * M [ 0 ] [ 1 ] + F [ 1 ] [ 1 ] * M ...
Multiplication of two numbers with shift operator | Function for multiplication ; check for set bit and left shift n , count times ; increment of place value ( count ) ; Driver code
def multiply ( n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE count = 0 NEW_LINE while ( m ) : NEW_LINE INDENT if ( m % 2 == 1 ) : NEW_LINE INDENT ans += n << count NEW_LINE DEDENT count += 1 NEW_LINE m = int ( m / 2 ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 20 NEW_L...
Compare two integers without using any Comparison operator | Function return true if A ^ B > 0 else false ; Driver Code
def EqualNumber ( A , B ) : NEW_LINE INDENT return ( A ^ B ) NEW_LINE DEDENT A = 5 ; B = 6 NEW_LINE print ( int ( not ( EqualNumber ( A , B ) ) ) ) NEW_LINE
Check if bits of a number has count of consecutive set bits in increasing order | Returns true if n has increasing count of continuous - 1 else false ; store the bit - pattern of n into bit bitset - bp ; set prev_count = 0 and curr_count = 0. ; increment current count of continuous - 1 ; traverse all continuous - 0 ; c...
def findContinuous1 ( n ) : NEW_LINE INDENT bp = list ( bin ( n ) ) NEW_LINE bits = len ( bp ) NEW_LINE prev_count = 0 NEW_LINE curr_count = 0 NEW_LINE i = 0 NEW_LINE while ( i < bits ) : NEW_LINE INDENT if ( bp [ i ] == '1' ) : NEW_LINE INDENT curr_count += 1 NEW_LINE i += 1 NEW_LINE DEDENT elif ( bp [ i - 1 ] == '0' ...
Check if bits of a number has count of consecutive set bits in increasing order | Python3 program to check if counts of consecutive 1 s are increasing order . ; Returns true if n has counts of consecutive 1 's are increasing order. ; Initialize previous count ; We traverse bits from right to left and check if counts ar...
import sys NEW_LINE def areSetBitsIncreasing ( n ) : NEW_LINE INDENT prev_count = sys . maxsize NEW_LINE while ( n > 0 ) : NEW_LINE INDENT while ( n > 0 and n % 2 == 0 ) : NEW_LINE INDENT n = int ( n / 2 ) NEW_LINE DEDENT curr_count = 1 NEW_LINE while ( n > 0 and n % 2 == 1 ) : NEW_LINE INDENT n = n / 2 NEW_LINE curr_c...
Check if a number has bits in alternate pattern | Set 1 | Returns true if n has alternate bit pattern else false ; Store last bit ; Traverse through remaining bits ; If current bit is same as previous ; Driver code
def findPattern ( n ) : NEW_LINE INDENT prev = n % 2 NEW_LINE n = n // 2 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT curr = n % 2 NEW_LINE if ( curr == prev ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev = curr NEW_LINE n = n // 2 NEW_LINE DEDENT return True NEW_LINE DEDENT n = 10 NEW_LINE print ( " Yes " ) if ( ...
XOR counts of 0 s and 1 s in binary representation | Returns XOR of counts 0 s and 1 s in binary representation of n . ; calculating count of zeros and ones ; Driver Code
def countXOR ( n ) : NEW_LINE INDENT count0 , count1 = 0 , 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( n % 2 == 0 ) : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT n //= 2 NEW_LINE DEDENT return ( count0 ^ count1 ) NEW_LINE DEDENT n = 31 NEW_LINE print ( countXOR ...
Count all pairs with given XOR | Returns count of pairs in arr [ 0. . n - 1 ] with XOR value equals to x . ; create empty map that stores counts of individual elements of array . ; If there exist an element in map m with XOR equals to x ^ arr [ i ] , that means there exist an element such that the XOR of element with a...
def xorPairCount ( arr , n , x ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_xor = x ^ arr [ i ] NEW_LINE if ( curr_xor in m . keys ( ) ) : NEW_LINE INDENT result += m [ curr_xor ] NEW_LINE DEDENT if arr [ i ] in m . keys ( ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 NEW_LINE DEDENT...
Bitwise and ( or & ) of a range | Find position of MSB in n . For example if n = 17 , then position of MSB is 4. If n = 7 , value of MSB is 3 ; Function to find Bit - wise & of all numbers from x to y . ; res = 0 Initialize result ; Find positions of MSB in x and y ; If positions are not same , return ; Add 2 ^ msb_p1 ...
def msbPos ( n ) : NEW_LINE INDENT msb_p = - 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE msb_p += 1 NEW_LINE DEDENT return msb_p NEW_LINE DEDENT def andOperator ( x , y ) : NEW_LINE INDENT while ( x > 0 and y > 0 ) : NEW_LINE INDENT msb_p1 = msbPos ( x ) NEW_LINE msb_p2 = msbPos ( y ) NEW_LINE if (...
Multiply a number with 10 without using multiplication operator | Function to find multiplication of n with 10 without using multiplication operator ; Driver program to run the case
def multiplyTen ( n ) : NEW_LINE INDENT return ( n << 1 ) + ( n << 3 ) NEW_LINE DEDENT n = 50 NEW_LINE print ( multiplyTen ( n ) ) NEW_LINE
Equal Sum and XOR | function to count number of values less than equal to n that satisfy the given condition ; Traverse all numbers from 0 to n and increment result only when given condition is satisfied . ; Driver Code
def countValues ( n ) : NEW_LINE INDENT countV = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT if ( ( n + i ) == ( n ^ i ) ) : NEW_LINE INDENT countV += 1 ; NEW_LINE DEDENT DEDENT return countV ; NEW_LINE DEDENT n = 12 ; NEW_LINE print ( countValues ( n ) ) ; NEW_LINE
Equal Sum and XOR | function to count number of values less than equal to n that satisfy the given condition ; unset_bits keeps track of count of un - set bits in binary representation of n ; Return 2 ^ unset_bits ; Driver code
def countValues ( n ) : NEW_LINE INDENT unset_bits = 0 NEW_LINE while ( n ) : NEW_LINE INDENT if n & 1 == 0 : NEW_LINE INDENT unset_bits += 1 NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT return 1 << unset_bits NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 12 NEW_LINE print ( countValues ( n ) ) NE...
Find profession in a special family | Returns ' e ' if profession of node at given level and position is engineer . Else doctor . The function assumes that given position and level have valid values . ; Base case ; Recursively find parent 's profession. If parent is a Doctor, this node will be a Doctor if it is at od...
def findProffesion ( level , pos ) : NEW_LINE INDENT if ( level == 1 ) : NEW_LINE INDENT return ' e ' NEW_LINE DEDENT if ( findProffesion ( level - 1 , ( pos + 1 ) // 2 ) == ' d ' ) : NEW_LINE INDENT if ( pos % 2 ) : NEW_LINE INDENT return ' d ' NEW_LINE DEDENT else : NEW_LINE INDENT return ' e ' NEW_LINE DEDENT DEDENT...
Print first n numbers with exactly two set bits | Prints first n numbers with two set bits ; Initialize higher of two sets bits ; Keep reducing n for every number with two set bits . ; Consider all lower set bits for current higher set bit ; Print current number ; If we have found n numbers ; Consider next lower bit fo...
def printTwoSetBitNums ( n ) : NEW_LINE INDENT x = 1 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT y = 0 NEW_LINE while ( y < x ) : NEW_LINE INDENT print ( ( 1 << x ) + ( 1 << y ) , end = " ▁ " ) NEW_LINE n -= 1 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT y += 1 NEW_LINE DEDENT x += 1 NEW_LINE DEDENT D...
Find even occurring elements in an array of limited range | Function to find the even occurring elements in given array ; do for each element of array ; left - shift 1 by value of current element ; Toggle the bit every time element gets repeated ; Traverse array again and use _xor to find even occurring elements ; left...
def printRepeatingEven ( arr , n ) : NEW_LINE INDENT axor = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT pos = 1 << arr [ i ] ; NEW_LINE axor ^= pos ; NEW_LINE DEDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT pos = 1 << arr [ i ] ; NEW_LINE if ( not ( pos & axor ) ) : NEW_LINE INDENT print ( arr [ i ] ,...
Cyclic Redundancy Check and Modulo | Returns XOR of ' a ' and ' b ' ( both of same length ) ; initialize result ; Traverse all bits , if bits are same , then XOR is 0 , else 1 ; Performs Modulo - 2 division ; Number of bits to be XORed at a time . ; Slicing the divident to appropriate length for particular step ; repla...
def xor ( a , b ) : NEW_LINE INDENT result = [ ] NEW_LINE for i in range ( 1 , len ( b ) ) : NEW_LINE INDENT if a [ i ] == b [ i ] : NEW_LINE INDENT result . append ( '0' ) NEW_LINE DEDENT else : NEW_LINE INDENT result . append ( '1' ) NEW_LINE DEDENT DEDENT return ' ' . join ( result ) NEW_LINE DEDENT def mod2div ( di...
Check if a number is Bleak | Function to get no of set bits in binary representation of passed binary no . ; Returns true if n is Bleak ; Check for all numbers ' x ' smaller than n . If x + countSetBits ( x ) becomes n , then n can 't be Bleak. ; Driver code
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 isBleak ( n ) : NEW_LINE INDENT for x in range ( 1 , n ) : NEW_LINE INDENT if ( x + countSetBits ( x ) == n ) : NEW_LINE INDENT return F...
Given a set , find XOR of the XOR 's of all subsets. | Returns XOR of all XOR 's of given subset ; XOR is 1 only when n is 1 , else 0 ; Driver code
def findXOR ( Set , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return Set [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT Set = [ 1 , 2 , 3 ] NEW_LINE n = len ( Set ) NEW_LINE print ( " XOR ▁ of ▁ XOR ' s ▁ of ▁ all ▁ subsets ▁ is ▁ " , findXOR ( Set , n ) ) ; NEW_LINE
Find XOR of two number without using XOR operator | Returns XOR of x and y ; Assuming 32 - bit Integer ; Find current bits in x and y ; If both are 1 then 0 else xor is same as OR ; Update result ; Driver Code
def myXOR ( x , y ) : NEW_LINE INDENT for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT b1 = x & ( 1 << i ) NEW_LINE b2 = y & ( 1 << i ) NEW_LINE b1 = min ( b1 , 1 ) NEW_LINE b2 = min ( b2 , 1 ) NEW_LINE xoredBit = 0 NEW_LINE if ( b1 & b2 ) : NEW_LINE INDENT xoredBit = 0 NEW_LINE DEDENT else : NEW_LINE INDENT xoredBi...
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
How to swap two bits in a given integer ? | This function swaps bit at positions p1 and p2 in an integer n ; Move p1 'th to rightmost side ; Move p2 'th to rightmost side ; XOR the two bits ; Put the xor bit back to their original positions ; XOR ' x ' with the original number so that the two sets are swapped ; Driver ...
def swapBits ( n , p1 , p2 ) : NEW_LINE INDENT bit1 = ( n >> p1 ) & 1 NEW_LINE bit2 = ( n >> p2 ) & 1 NEW_LINE x = ( bit1 ^ bit2 ) NEW_LINE x = ( x << p1 ) | ( x << p2 ) NEW_LINE result = n ^ x NEW_LINE return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT res = swapBits ( 28 , 0 , 3 ) NEW_LIN...
Write a function that returns 2 for input 1 and returns 1 for 2 |
def invert ( x ) : NEW_LINE INDENT if ( x == 1 ) : NEW_LINE INDENT return 2 NEW_LINE else : NEW_LINE return 1 NEW_LINE DEDENT DEDENT
Write a function that returns 2 for input 1 and returns 1 for 2 |
def invertSub ( x ) : NEW_LINE INDENT return ( 3 - x ) NEW_LINE DEDENT
Maximum length sub | Function to return the maximum length of the required sub - array ; For the first consecutive pair of elements ; While a consecutive pair can be selected ; If current pair forms a valid sub - array ; 2 is the length of the current sub - array ; To extend the sub - array both ways ; While elements a...
def maxLength ( arr , n ) : NEW_LINE INDENT maxLen = 0 NEW_LINE i = 0 NEW_LINE j = i + 1 NEW_LINE while ( j < n ) : NEW_LINE INDENT if ( arr [ i ] != arr [ j ] ) : NEW_LINE INDENT maxLen = max ( maxLen , 2 ) NEW_LINE l = i - 1 NEW_LINE r = j + 1 NEW_LINE while ( l >= 0 and r < n and arr [ l ] == arr [ i ] and arr [ r ]...
FreivaldΓ’ €ℒ s Algorithm to check if a matrix is product of two | Python3 code to implement FreivaldaTMs Algorithm ; Function to check if ABx = Cx ; Generate a random vector ; Now comput B * r for evaluating expression A * ( B * r ) - ( C * r ) ; Now comput C * r for evaluating expression A * ( B * r ) - ( C * r ) ; No...
import random NEW_LINE N = 2 NEW_LINE def freivald ( a , b , c ) : NEW_LINE INDENT r = [ 0 ] * N NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT r [ i ] = ( int ) ( random . randrange ( 509090009 ) % 2 ) NEW_LINE DEDENT br = [ 0 ] * N NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NE...
Expectation or expected value of an array | Function to calculate expectation ; variable prb is for probability of each element which is same for each element ; calculating expectation overall ; returning expectation as sum ; Driver program ; Function for calculating expectation ; Display expectation of given array
def calc_Expectation ( a , n ) : NEW_LINE INDENT prb = 1 / n NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += ( a [ i ] * prb ) NEW_LINE DEDENT return float ( sum ) NEW_LINE DEDENT n = 6 ; NEW_LINE a = [ 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 ] NEW_LINE expect = calc_Expectation ( a , n ) NEW_LINE...
Program to generate CAPTCHA and verify user | Python program to automatically generate CAPTCHA and verify user ; Returns true if given two strings are same ; Generates a CAPTCHA of given length ; Characters to be included ; Generate n characters from above set and add these characters to captcha . ; Generate a random C...
import random NEW_LINE def checkCaptcha ( captcha , user_captcha ) : NEW_LINE INDENT if captcha == user_captcha : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def generateCaptcha ( n ) : NEW_LINE INDENT chrs = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" NEW_LINE captcha...
Sum of N | Function to calculate the sum recursively ; Base cases ; If n is odd ; If n is even ; Function to print the value of Sum ; Driver Program ; first element ; common difference ; Number of elements ; Mod value
def SumGPUtil ( r , n , m ) : NEW_LINE INDENT if n == 0 : return 1 NEW_LINE if n == 1 : return ( 1 + r ) % m NEW_LINE if n % 2 == 1 : NEW_LINE INDENT ans = ( 1 + r ) * SumGPUtil ( r * r % m , ( n - 1 ) // 2 , m ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = 1 + r * ( 1 + r ) * SumGPUtil ( r * r % m , n // 2 - 1 , m ) N...
Length of longest subarray in which elements greater than K are more than elements not greater than K | Function to find the Length of a longest subarray in which elements greater than K are more than elements not greater than K ; Create a new array in which we store 1 if a [ i ] > k otherwise we store - 1. ; Taking pr...
def LongestSubarray ( a , n , k ) : NEW_LINE INDENT pre = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > k ) : NEW_LINE INDENT pre [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT pre [ i ] = - 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT pre [ i ] = pre...
Choose points from two ranges such that no point lies in both the ranges | Function to find the required points ; Driver code
def findPoints ( l1 , r1 , l2 , r2 ) : NEW_LINE INDENT x = min ( l1 , l2 ) if ( l1 != l2 ) else - 1 NEW_LINE y = max ( r1 , r2 ) if ( r1 != r2 ) else - 1 NEW_LINE print ( x , y ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT l1 = 5 NEW_LINE r1 = 10 NEW_LINE l2 = 1 NEW_LINE r2 = 7 NEW_LINE findPoints...
Tail Recursion | A NON - tail - recursive function . The function is not tail recursive because the value returned by fact ( n - 1 ) is used in fact ( n ) and call to fact ( n - 1 ) is not the last thing done by fact ( n ) ; Driver program to test above function
def fact ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return n * fact ( n - 1 ) NEW_LINE DEDENT print ( fact ( 5 ) ) NEW_LINE
Minimum number of working days required to achieve each of the given scores | Function to find the minimum number of days required to work to at least arr [ i ] points for every array element ; Traverse the array P [ ] ; Find the prefix sum ; Traverse the array arr [ ] ; Find the minimum index of the array having value...
def minDays ( P , arr ) : NEW_LINE INDENT for i in range ( 1 , len ( P ) ) : NEW_LINE INDENT P [ i ] += P [ i ] + P [ i - 1 ] NEW_LINE DEDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT index = binarySeach ( P , arr [ i ] ) NEW_LINE if ( index != - 1 ) : NEW_LINE INDENT print ( index + 1 , end = " ▁ " ) NEW_LINE D...
Maximize profit that can be earned by selling an item among N buyers | Python3 program for the above approach ; Function to find the maximum profit earned by selling an item among N buyers ; Stores the maximum profit ; Stores the price of the item ; Sort the array ; Traverse the array ; Count of buyers with budget >= a...
import sys NEW_LINE def maximumProfit ( arr , N ) : NEW_LINE INDENT ans = - sys . maxsize - 1 NEW_LINE price = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT count = ( N - i ) NEW_LINE if ( ans < count * arr [ i ] ) : NEW_LINE INDENT price = arr [ i ] NEW_LINE ans = count * arr [ i ] NEW_LINE...
Maximum length palindromic substring for every index such that it starts and ends at that index | Function to return true if S [ i ... j ] is a palindrome ; Iterate until i < j ; If unequal character encountered ; Otherwise ; Function to find for every index , longest palindromic substrings starting or ending at that i...
def isPalindrome ( S , i , j ) : NEW_LINE INDENT while ( i < j ) : NEW_LINE INDENT if ( S [ i ] != S [ j ] ) : NEW_LINE return False NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def printLongestPalindrome ( S , N ) : NEW_LINE INDENT palLength = [ 0 for i in range ( N ) ] NEW_LINE for i in...
Sum of array elements which are multiples of a given number | Function to find the sum of array elements which are multiples of N ; Stores the sum ; Traverse the array ; Print total sum ; Driver Code ; Given arr [ ] ; Function call
def mulsum ( arr , n , N ) : NEW_LINE INDENT sums = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] % N == 0 : NEW_LINE INDENT sums = sums + arr [ i ] NEW_LINE DEDENT DEDENT print ( sums ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 5 , 6 ] NEW_LINE n = len (...
Farthest index that can be reached from the Kth index of given array by given operations | Function to find the farthest index that can be reached ; Declare a priority queue ; Iterate the array ; If current element is greater than the next element ; Otherwise , store their difference ; Push diff into pq ; If size of pq...
def farthestHill ( arr , X , Y , N , K ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( K , N - 1 , 1 ) : NEW_LINE INDENT if ( arr [ i ] >= arr [ i + 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT diff = arr [ i + 1 ] - arr [ i ] NEW_LINE pq . append ( diff ) NEW_LINE if ( len ( pq ) > Y ) : NEW_LINE INDENT X -...
Lexicographically largest string possible consisting of at most K consecutive similar characters | Function to return nearest lower character ; Traverse charset from start - 1 ; If no character can be appended ; Function to find largest string ; Stores the frequency of characters ; Traverse the string ; Append larger c...
def nextAvailableChar ( charset , start ) : NEW_LINE INDENT for i in range ( start - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( charset [ i ] > 0 ) : NEW_LINE INDENT charset [ i ] -= 1 NEW_LINE return chr ( i + ord ( ' a ' ) ) NEW_LINE DEDENT DEDENT return ' \0' NEW_LINE DEDENT def newString ( originalLabel , limit ) : NEW...
Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace odd elements with even elements and vice versa ; Length of the array ; Traverse the given array ; If arr [ i ] is visited ; Find the next odd element ; Find next even element ; Mark them visited ; Swap them ; Pr...
def swapEvenOdd ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE o = - 1 NEW_LINE e = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT r = - 1 NEW_LINE if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT o += 1 NEW_LINE while ( arr [ o ] % 2 == 0 or arr [ o ]...
Check if a palindromic string can be obtained by concatenating substrings split from same indices of two given strings | Python3 program to implement the above approach ; iterate through the length if we could find a [ i ] = = b [ j ] we could increment I and decrement j ; else we could just break the loop as its not a...
def check ( a , b , n ) : NEW_LINE INDENT i , j = 0 , n - 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( a [ i ] != b [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE xa = a [ i : j + 1 ] NEW_LINE xb = b [ i : j + 1 ] NEW_LINE if ( xa == xa [ : : - 1 ] or xb == xb [ : : - 1 ] ) : NEW_L...
Maximize length of subarray having equal elements by adding at most K | Function to find the maximum number of indices having equal elements after adding at most k numbers ; Sort the array in ascending order ; Make prefix sum array ; Initialize variables ; Update mid ; Check if any subarray can be obtained of length mi...
def maxEqualIdx ( arr , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE prefixSum = [ 0 ] * ( len ( arr ) + 1 ) NEW_LINE prefixSum [ 1 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( prefixSum ) - 1 , 1 ) : NEW_LINE INDENT prefixSum [ i + 1 ] = prefixSum [ i ] + arr [ i ] NEW_LINE DEDENT max = len ( arr ) NEW_LINE min ...
Sum of product of all pairs of a Binary Array | Function to print the sum of product of all pairs of the given array ; Stores count of one in the given array ; Stores the size of the given array ; If current element is 1 ; Increase count ; Return the sum of product of all pairs ; Driver Code
def productSum ( arr ) : NEW_LINE INDENT cntOne = 0 NEW_LINE N = len ( arr ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cntOne += 1 NEW_LINE DEDENT DEDENT return cntOne * ( cntOne - 1 ) // 2 NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 , 1 ] NEW_LINE print ( productSum ( arr ) ) NE...
Minimum value of X that can be added to N to minimize sum of the digits to Γƒ Β’ Γ’ €°€ K | ''Python program for the above approach ; ''Function to find the minimum number needed to be added so that the sum of the digits does not exceed K ; ; ; '' Add the digits of num2 ; ''If the sum of the digits of N is less than or...
import math ; NEW_LINE def minDigits ( N , K ) : NEW_LINE ' ▁ Find ▁ the ▁ number ▁ of ▁ digits ' ' ' NEW_LINE digits_num = int ( math . floor ( math . log ( N ) + 1 ) ) ; NEW_LINE INDENT temp_sum = 0 ; NEW_LINE temp = digits_num ; NEW_LINE result = 0 ; NEW_LINE X = 0 ; var = 0 ; NEW_LINE sum1 = 0 ; NEW_LINE num2 = N ;...
Count of Ways to obtain given Sum from the given Array elements | Python3 program to implement the above approach ; Function to call dfs to calculate the number of ways ; Iterate till the length of array ; Initialize the memorization table ; Function to perform the DFS to calculate the number of ways ; Base case : Reac...
import sys NEW_LINE def findWays ( nums , S ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT sum += nums [ i ] NEW_LINE DEDENT memo = [ [ - sys . maxsize - 1 for i in range ( 2 * sum + 1 ) ] for j in range ( len ( nums ) + 1 ) ] NEW_LINE return dfs ( memo , nums , S , 0 , 0 , sum )...
Longest subarray with sum not divisible by X | Function to print the longest subarray with sum of elements not divisible by X ; Pref [ ] stores the prefix sum Suff [ ] stores the suffix sum ; If array element is divisibile by x ; Increase count ; If all the array elements are divisible by x ; No subarray possible ; Rev...
def max_length ( N , x , v ) : NEW_LINE INDENT preff , suff = [ ] , [ ] NEW_LINE ct = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT a = v [ i ] NEW_LINE if a % x == 0 : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT DEDENT if ct == N : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT v . reverse ( ) NEW_LINE ...
Number of times Maximum and minimum value updated during traversal of array | Function to find the count the number of times maximum and minimum value updated ; Update the maximum and minimum values during traversal ; Driver code
def maximumUpdates ( arr ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE max = arr [ 0 ] NEW_LINE minCount , maxCount = 1 , 1 NEW_LINE for arr in arr : NEW_LINE INDENT if arr > max : NEW_LINE INDENT maxCount += 1 NEW_LINE max = arr NEW_LINE DEDENT if arr < min : NEW_LINE INDENT minCount += 1 ; NEW_LINE min = arr NEW_LINE ...
Find the farthest smaller number in the right side | Function to find the farthest smaller number in the right side ; To store minimum element in the range i to n ; If current element in the suffix_min is less than a [ i ] then move right ; Print the required answer ; Driver code
def farthest_min ( a , n ) : NEW_LINE INDENT suffix_min = [ 0 for i in range ( n ) ] NEW_LINE suffix_min [ n - 1 ] = a [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix_min [ i ] = min ( suffix_min [ i + 1 ] , a [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT low = i + 1 NE...
Print numbers in descending order along with their frequencies | Function to print the elements in descending along with their frequencies ; Sorts the element in decreasing order ; traverse the array elements ; Prints the number and count ; Prints the last step ; Driver Code
def printElements ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) NEW_LINE cnt = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( a [ i ] != a [ i + 1 ] ) : NEW_LINE INDENT print ( a [ i ] , " ▁ occurs ▁ " , cnt , " times " ) NEW_LINE cnt = 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += 1 NEW_LINE DE...
Find element position in given monotonic sequence | Python 3 implementation of the approach ; Function to return the value of f ( n ) for given values of a , b , c , n ; if c is 0 , then value of n can be in order of 10 ^ 15. if c != 0 , then n ^ 3 value has to be in order of 10 ^ 18 so maximum value of n can be 10 ^ 6...
from math import log2 , floor NEW_LINE SMALL_N = 1000000 NEW_LINE LARGE_N = 1000000000000000 NEW_LINE def func ( a , b , c , n ) : NEW_LINE INDENT res = a * n NEW_LINE logVlaue = floor ( log2 ( n ) ) NEW_LINE res += b * n * logVlaue NEW_LINE res += c * ( n * n * n ) NEW_LINE return res NEW_LINE DEDENT def getPositionIn...
Check if array can be sorted with one swap | A linear Python 3 program to check if array becomes sorted after one swap ; Create a sorted copy of original array ; Check if 0 or 1 swap required to get the sorted array ; Driver Code
def checkSorted ( n , arr ) : NEW_LINE INDENT b = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT b . append ( arr [ i ] ) NEW_LINE DEDENT b . sort ( ) NEW_LINE ct = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] != b [ i ] : NEW_LINE INDENT ct += 1 NEW_LINE DEDENT DEDENT if ct == 0 or ct == 2 : NEW...
Check whether ( i , j ) exists such that arr [ i ] != arr [ j ] and arr [ arr [ i ] ] is equal to arr [ arr [ j ] ] | Function that will tell whether such Indices present or Not . ; Checking 1 st condition i . e whether Arr [ i ] equal to Arr [ j ] or not ; Checking 2 nd condition i . e whether Arr [ Arr [ i ] ] equal ...
def checkIndices ( Arr , N ) : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( Arr [ i ] != Arr [ j ] ) : NEW_LINE INDENT if ( Arr [ Arr [ i ] - 1 ] == Arr [ Arr [ j ] - 1 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False N...
Find two non | Function to find two non - overlapping with same Sum in an array ; first create an empty Map key -> which is Sum of a pair of elements in the array value -> vector storing index of every pair having that Sum ; consider every pair ( arr [ i ] , arr [ j ] ) and where ( j > i ) ; calculate Sum of current pa...
def findPairs ( arr , size ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( 0 , size - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , size ) : NEW_LINE INDENT Sum = arr [ i ] + arr [ j ] NEW_LINE if Sum in Map : NEW_LINE INDENT for pair in Map [ Sum ] : NEW_LINE INDENT m , n = pair NEW_LINE if ( ( m != i and m !...
Print all pairs with given sum | Returns number of pairs in arr [ 0. . n - 1 ] with sum equal to 'sum ; Consider all possible pairs and check their sums ; Driver Code
' NEW_LINE def printPairs ( arr , n , sum ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] == sum ) : NEW_LINE INDENT print ( " ( " , arr [ i ] , " , ▁ " , arr [ j ] , " ) " , sep = " " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [...
Ways to choose three points with distance between the most distant points <= L | ; def countTripletsLessThanL ( n , L , arr ) : ; arr = sorted ( arr ) ; ways = 0 ; for i in range ( n ) : ; indexGreater = upper_bound ( arr , 0 , n , arr [ i ] + L ) ; ; numberOfElements = indexGreater - ( i + 1 ) ; ; if ( numberOfElemen...
Returns the number of triplets with the NEW_LINE distance between farthest points <= L NEW_LINE INDENT sort the array NEW_LINE INDENT find index of element greater than arr [ i ] + L NEW_LINE find Number of elements between the ith NEW_LINE index and indexGreater since the Numbers NEW_LINE are sorted and the elements a...
Making elements distinct in a sorted array by minimum increments | To find minimum sum of unique elements . ; While current element is same as previous or has become smaller than previous . ; Driver code
def minSum ( arr , n ) : NEW_LINE INDENT sm = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] == arr [ i - 1 ] : NEW_LINE INDENT j = i NEW_LINE while j < n and arr [ j ] <= arr [ j - 1 ] : NEW_LINE INDENT arr [ j ] = arr [ j ] + 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT sm = sm + arr [ i ] NEW...
Making elements distinct in a sorted array by minimum increments | To find minimum sum of unique elements ; If violation happens , make current value as 1 plus previous value and add to sum . ; No violation . ; Drivers code
def minSum ( arr , n ) : NEW_LINE INDENT sum = arr [ 0 ] ; prev = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] <= prev : NEW_LINE INDENT prev = prev + 1 NEW_LINE sum = sum + prev NEW_LINE DEDENT else : NEW_LINE INDENT sum = sum + arr [ i ] NEW_LINE prev = arr [ i ] NEW_LINE DEDENT DEDENT r...
Randomized Binary Search Algorithm | Python3 program to implement recursive randomized algorithm . To generate random number between x and y ie . . [ x , y ] ; A recursive randomized binary search function . It returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; Here we have defined middle...
import random NEW_LINE def getRandom ( x , y ) : NEW_LINE INDENT tmp = ( x + random . randint ( 0 , 100000 ) % ( y - x + 1 ) ) NEW_LINE return tmp NEW_LINE DEDENT def randomizedBinarySearch ( arr , l , r , x ) : NEW_LINE INDENT if r >= l : NEW_LINE INDENT mid = getRandom ( l , r ) NEW_LINE if arr [ mid ] == x : NEW_LIN...
Program to remove vowels from a String | Python program to remove vowels from a string Function to remove vowels ; Driver program
def rem_vowel ( string ) : NEW_LINE INDENT vowels = [ ' a ' , ' e ' , ' i ' , ' o ' , ' u ' ] NEW_LINE result = [ letter for letter in string if letter . lower ( ) not in vowels ] NEW_LINE result = ' ' . join ( result ) NEW_LINE print ( result ) NEW_LINE DEDENT string = " GeeksforGeeks ▁ - ▁ A ▁ Computer ▁ Science ▁ Po...
Make all array elements equal with minimum cost | This function assumes that a [ ] is sorted . If a [ ] is not sorted , we need to sort it first . ; If there are odd elements , we choose middle element ; If there are even elements , then we choose the average of middle two . ; After deciding the final value , find the ...
def minCostToMakeElementEqual ( a ) : NEW_LINE INDENT l = len ( a ) NEW_LINE if ( l % 2 == 1 ) : NEW_LINE INDENT y = a [ l // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT y = ( a [ l // 2 ] + a [ ( l - 2 ) // 2 ] ) // 2 NEW_LINE DEDENT s = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT s += abs ( a [ i ] - y ) NEW_LIN...
Check if an array can be sorted by rearranging odd and even | Function to check if array can be sorted or not ; Function to check if given array can be sorted or not ; Traverse the array ; Traverse remaining elements at indices separated by 2 ; If current element is the minimum ; If any smaller minimum exists ; Swap wi...
def isSorted ( arr ) : NEW_LINE INDENT for i in range ( len ( arr ) - 1 ) : NEW_LINE INDENT if arr [ i ] > arr [ i + 1 ] : NEW_LINE return False NEW_LINE DEDENT return True NEW_LINE DEDENT def sortPoss ( arr ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT idx = - 1 NEW_LINE minVar = arr [ i ] NEW_L...
Print all array elements appearing more than N / K times | Function to + find the upper_bound of an array element ; Stores minimum index in which K lies ; Stores maximum index in which K lies ; Calculate the upper bound of K ; Stores mid element of l and r ; If arr [ mid ] is less than or equal to K ; Right subarray ; ...
def upperBound ( arr , N , K ) : NEW_LINE INDENT l = 0 ; NEW_LINE r = N ; NEW_LINE while ( l < r ) : NEW_LINE INDENT mid = ( l + r ) // 2 ; NEW_LINE if ( arr [ mid ] <= K ) : NEW_LINE INDENT l = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT r = mid ; NEW_LINE DEDENT DEDENT return l ; NEW_LINE DEDENT def NDivKWithFre...
Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1 | Function to find maximum possible sum after changing the array elements as per the given constraints ; Stores the frequency of elements in given array ; Update frequency ; stores the previously selected int...
def maxSum ( a , n ) : NEW_LINE INDENT count = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT count [ min ( a [ i ] , n ) ] += 1 NEW_LINE DEDENT size = 0 NEW_LINE ans = 0 NEW_LINE for k in range ( 1 , n + 1 ) : NEW_LINE INDENT while ( count [ k ] > 0 and size < k ) : NEW_LINE INDENT size += 1 NEW...
Find sum of product of every number and its frequency in given range | Function to solve queries ; Calculating answer for every query ; The end points of the ith query ; Map for storing frequency ; Incrementing the frequency ; Iterating over map to find answer ; Adding the contribution of ith number ; Print answer ; Dr...
def answerQueries ( arr , n , queries ) : NEW_LINE INDENT for i in range ( len ( queries ) ) : NEW_LINE INDENT ans = 0 NEW_LINE l = queries [ i ] [ 0 ] - 1 NEW_LINE r = queries [ i ] [ 1 ] - 1 NEW_LINE freq = dict ( ) NEW_LINE for j in range ( l , r + 1 ) : NEW_LINE INDENT freq [ arr [ j ] ] = freq . get ( arr [ j ] , ...
Longest subsequence with first and last element greater than all other elements | Python implementation of the above approach ; Function to update the value in Fenwick tree ; Function to return the query result ; Function to return the length of subsequence ; Store the value in struct Array ; If less than 2 elements ar...
from typing import List NEW_LINE class Query : NEW_LINE INDENT def __init__ ( self ) -> None : NEW_LINE INDENT self . l = 0 NEW_LINE self . r = 0 NEW_LINE self . x = 0 NEW_LINE self . index = 0 NEW_LINE DEDENT DEDENT class Arrays : NEW_LINE INDENT def __init__ ( self ) -> None : NEW_LINE INDENT self . val = 0 NEW_LINE ...
Pandigital Product | Calculate the multiplicand , multiplier , and product eligible for pandigital ; To check the string formed from multiplicand multiplier and product is pandigital ; Driver code
def PandigitalProduct_1_9 ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( ( n % i == 0 ) and bool ( isPandigital ( str ( n ) + str ( i ) + str ( n // i ) ) ) ) : NEW_LINE INDENT return bool ( True ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return bool ( False ) NEW_LINE DEDENT def isPandigi...
Median and Mode using Counting Sort | Function that sort input array a [ ] and calculate mode and median using counting sort ; The output array b [ ] will have sorted array ; Variable to store max of input array which will to have size of count array ; Auxiliary ( count ) array to store count . Initialize count array a...
def printModeMedian ( a , n ) : NEW_LINE INDENT b = [ 0 ] * n NEW_LINE Max = max ( a ) NEW_LINE t = Max + 1 NEW_LINE count = [ 0 ] * t NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ a [ i ] ] += 1 NEW_LINE DEDENT mode = 0 NEW_LINE k = count [ 0 ] NEW_LINE for i in range ( 1 , t ) : NEW_LINE INDENT if ( count [...
Check if both halves of the string have at least one different character | Python implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Counts frequency of characters in each half Compares the two counter array and returns true if these ...
MAX = 26 NEW_LINE def function ( st ) : NEW_LINE INDENT global MAX NEW_LINE l = len ( st ) NEW_LINE counter1 , counter2 = [ 0 ] * MAX , [ 0 ] * MAX NEW_LINE for i in range ( l // 2 ) : NEW_LINE INDENT counter1 [ ord ( st [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l // 2 , l ) : NEW_LINE INDENT coun...
Check if both halves of the string have at least one different character | Python3 implementation to check if both halves of the string have at least one different character ; Function which break string into two halves Increments frequency of characters for first half Decrements frequency of characters for second half...
MAX = 26 NEW_LINE def function ( st ) : NEW_LINE INDENT global MAX NEW_LINE l = len ( st ) NEW_LINE counter = [ 0 ] * MAX NEW_LINE for i in range ( l // 2 ) : NEW_LINE INDENT counter [ ord ( st [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( l // 2 , l ) : NEW_LINE INDENT counter [ ord ( st [ i ] ) - or...
Minimum difference between max and min of all K | Returns min difference between max and min of any K - size subset ; sort the array so that close elements come together . ; initialize result by a big integer number ; loop over first ( N - K ) elements of the array only ; get difference between max and min of current K...
def minDifferenceAmongMaxMin ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE res = 2147483647 NEW_LINE for i in range ( ( N - K ) + 1 ) : NEW_LINE INDENT curSeqDiff = arr [ i + K - 1 ] - arr [ i ] NEW_LINE res = min ( res , curSeqDiff ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 10 , 20 , 30 , 100 , 1...
Position of an element after stable sort | Python program to get index of array element in sorted array Method returns the position of arr [ idx ] after performing stable - sort on array ; Count of elements smaller than current element plus the equal element occurring before given index ; If element is smaller then inc...
def getIndexInSortedArray ( arr , n , idx ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ idx ] ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT if ( arr [ i ] == arr [ idx ] and i < idx ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result ; NEW_LINE ...
Find permutation of numbers upto N with a specific sum in a specific range | Function to check if sum is possible with remaining numbers ; Stores the minimum sum possible with x numbers ; Stores the maximum sum possible with x numbers ; If S lies in the range [ minSum , maxSum ] ; Function to find the resultant permuta...
def possible ( x , S , N ) : NEW_LINE INDENT minSum = ( x * ( x + 1 ) ) // 2 NEW_LINE maxSum = ( x * ( ( 2 * N ) - x + 1 ) ) // 2 NEW_LINE if ( S < minSum or S > maxSum ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def findPermutation ( N , L , R , S ) : NEW_LINE INDENT x = R - L + 1 NEW_...