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 ( bitwise ) each element of the array with each set digit ( one at a time ) to get the count of set bits at each position ; Now consider all bits whose count is not multiple of k to form the required number . ; Driver Code
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 DEDENT DEDENT DEDENT res = 0 NEW_LINE for i in range ( INT_SIZE ) : NEW_LINE INDENT res += ( count [ i ] % k ) * ( 1 << i ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 6 , 2 , 5 , 2 , 2 , 6 , 6 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE print ( findUnique ( a , n , k ) ) ; NEW_LINE DEDENT
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 ( ' Yes ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' No ' ) NEW_LINE DEDENT
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 ; NEW_LINE if ( bitsAreInAltOrder ( n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT
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 flipping . ; Driver Code
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 . log ( n ) / math . log ( 2 ) + 1 ) NEW_LINE max = pow ( 2 , k ) - 1 NEW_LINE max = max << ( size - k ) NEW_LINE xorValue = ( n ^ max ) NEW_LINE return ( setBit ( xorValue ) ) NEW_LINE DEDENT n = 27 NEW_LINE k = 3 NEW_LINE print ( " Min ▁ Flips ▁ = ▁ " , minFlip ( n , k ) ) NEW_LINE
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 to r and nowhere else ; if new num is 0 , then all bits are unset in the given range ; else all bits are not unset ; Driver Code
def allBitsSetInTheGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE new_num = n & num NEW_LINE if ( 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 = 2 NEW_LINE r = 4 NEW_LINE print ( allBitsSetInTheGivenRange ( n , l , r ) ) NEW_LINE DEDENT
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_LINE print ( n ) NEW_LINE
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 Code
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 ▁ = ▁ " , posOfRightMostSameBit ( m , n ) ) NEW_LINE
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 shift value of m ; Right shift value of n ; When no common set is found ; Driver code
' 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 DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m , n = 16 , 7 NEW_LINE print ( " Position ▁ = ▁ " , posOfRightMostSameBit ( m , n ) ) NEW_LINE DEDENT
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 nowhere else ; if both are equal , then all bits are set in the given range ; else all bits are not set ; Driver code
def allBitsSetInTheGivenRange ( n , l , r ) : NEW_LINE INDENT num = ( ( 1 << r ) - 1 ) ^ ( ( 1 << ( l - 1 ) ) - 1 ) NEW_LINE new_num = n & num NEW_LINE if ( num == new_num ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT return " No " NEW_LINE DEDENT n , l , r = 22 , 2 , 3 NEW_LINE print ( allBitsSetInTheGivenRange ( n , l , r ) ) NEW_LINE
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 ▁ of ▁ i ▁ and ▁ left ▁ ▁ shifted ▁ i ▁ do ' t contain a common set bit . ; Driver code
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 , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Insert bit 0 in the middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Length of the final binary representation ; Fill first and last bit as 1 ; Start filling the a [ ] from middle , with the aux_num binary representation ; Get the auxiliary number 's ith bit and fill around middle ; Convert the number to decimal from binary ; Will return the nth binary palindrome number ; Add number of elements in all the groups , until the group of the nth number is found ; Total number of elements until this group ; Element 's offset position in the group ; Finding which bit to be placed in the middle and finding the number , which we will fill from the middle in both directions ; We need to fill this auxiliary number in binary form the middle in both directions ; op = 0 Need to Insert 0 at middle ; op = 1 Need to Insert 1 at middle ; Driver code ; Function Call
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 ] = aux_num & 1 NEW_LINE aux_num = aux_num >> 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT elif op == 0 : NEW_LINE INDENT len_f = 2 * group_no + 1 NEW_LINE a [ len_f - 1 ] = a [ 0 ] = 1 NEW_LINE a [ group_no ] = 0 NEW_LINE while aux_num : NEW_LINE INDENT a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 NEW_LINE aux_num = aux_num >> 1 NEW_LINE i += 1 NEW_LINE DEDENT len_f = 2 * group_no + 1 NEW_LINE a [ len_f - 1 ] = a [ 0 ] = 1 NEW_LINE a [ group_no ] = 1 NEW_LINE while aux_num : NEW_LINE INDENT a [ group_no + 1 + i ] = a [ group_no - 1 - i ] = aux_num & 1 NEW_LINE aux_num = aux_num >> 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , len_f ) : NEW_LINE INDENT num += ( 1 << i ) * a [ i ] NEW_LINE DEDENT return num NEW_LINE DEDENT def getNthNumber ( n ) : NEW_LINE INDENT group_no = 0 NEW_LINE count_upto_group , count_temp = 0 , 1 NEW_LINE while count_temp < n : NEW_LINE INDENT group_no += 1 NEW_LINE count_upto_group = count_temp NEW_LINE count_temp += 3 * ( 1 << ( group_no - 1 ) ) NEW_LINE DEDENT group_offset = n - count_upto_group - 1 NEW_LINE if ( group_offset + 1 ) <= ( 1 << ( group_no - 1 ) ) : NEW_LINE INDENT aux_num = group_offset NEW_LINE DEDENT else : NEW_LINE INDENT if ( ( ( group_offset + 1 ) - ( 1 << ( group_no - 1 ) ) ) % 2 ) : NEW_LINE else : NEW_LINE aux_num = ( ( ( group_offset ) - ( 1 << ( group_no - 1 ) ) ) // 2 ) NEW_LINE DEDENT return constructNthNumber ( group_no , aux_num , op ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 9 NEW_LINE print ( getNthNumber ( n ) ) NEW_LINE DEDENT
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 = 3 NEW_LINE key = 3 NEW_LINE shuffle ( N , key ) NEW_LINE
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_LINE INDENT sum = sum + i NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT n = 10 NEW_LINE print ( findSum ( n ) ) NEW_LINE
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 = getPosOfRightmostSetBit ( ~ n ) NEW_LINE DEDENT ' NEW_LINE INDENT return ( ( 1 << ( pos - 1 ) ) n ) NEW_LINE DEDENT n = 21 NEW_LINE print ( setRightmostUnsetBit ( n ) ) NEW_LINE
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 bit at position 'pos ; Driver code
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 = 25 NEW_LINE print ( " Previous ▁ small ▁ Integer ▁ = ▁ " , previousSmallerInteger ( n ) ) NEW_LINE
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 print ( areAllBitsSet ( n ) ) NEW_LINE
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 n by passing ~ n as argument ; if n consists of unset bits , then set the rightmost unset bit ; n does not consists of unset bits ; Driver code
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_LINE DEDENT return ( ( n << 1 ) + 1 ) NEW_LINE DEDENT n = 10 NEW_LINE print ( " Next ▁ greater ▁ integer ▁ = ▁ " , nextGreaterWithOneMoreSetBit ( n ) ) NEW_LINE
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__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4294967295 NEW_LINE k = 0 NEW_LINE print ( toggleAllExceptK ( n , k ) ) NEW_LINE DEDENT
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_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 10 NEW_LINE print ( CountXORandSumEqual ( x ) ) NEW_LINE DEDENT
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 DEDENT arr1 = [ 4 , 8 , 1 , 3 , 7 ] NEW_LINE arr2 = [ 7 , 4 , 3 , 1 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( " Missing ▁ number ▁ = ▁ " , missingNumber ( arr1 , arr2 , n ) ) 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 number in arr [ index ] ; Find value of given bit number in arr [ index ] ; Sets a bit at given position ; Find index of bit position ; Set bit number in arr [ index ] ; Main function to print all Duplicates ; create a bit with 32000 bits ; Traverse array elements ; Index in bit array ; If num is already present in bit array ; Else insert num ; Driver Code
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 DEDENT def set ( self , pos ) : NEW_LINE INDENT self . index = pos >> 5 NEW_LINE self . bitNo = pos & 0x1F NEW_LINE self . arr [ self . index ] |= ( 1 << self . bitNo ) NEW_LINE DEDENT DEDENT def checkDuplicates ( arr ) : NEW_LINE INDENT ba = BitArray ( 320000 ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT num = arr [ i ] NEW_LINE if ba . get ( num ) : NEW_LINE INDENT print ( num , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT ba . set ( num ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 1 , 10 , 12 , 10 ] NEW_LINE checkDuplicates ( arr ) NEW_LINE DEDENT
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 position of bit ; Simultaneously calculate the 2 ^ n ; Replace x with x / 2 ; ; Driver code
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 ) ) ; NEW_LINE
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 i in range ( 0 , n ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT xoredNum = arr [ i ] ^ arr [ j ] NEW_LINE if ( k == bitCount ( xoredNum ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 2 NEW_LINE arr = [ 2 , 4 , 1 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Total ▁ pairs ▁ for ▁ k ▁ = " , k , " are " , countPairsWithKDiff ( arr , n , k ) ) NEW_LINE DEDENT
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 count [ i ] is 0 , skip the next loop as it will not contribute the answer ; Update answer if k differ bit found ; Driver code
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 += ( count [ i ] * ( count [ i ] - 1 ) ) // 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT if ( count [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( i + 1 , MAX + 1 ) : NEW_LINE INDENT if ( bin ( i ^ j ) . count ( '1' ) == k ) : NEW_LINE INDENT ans += count [ i ] * count [ j ] NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT k = 2 NEW_LINE arr = [ 2 , 4 , 1 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Total ▁ pairs ▁ for ▁ k ▁ = " , k , " are " , kBitDifferencePairs ( arr , n , k ) ) NEW_LINE k = 3 NEW_LINE print ( " Total ▁ pairs ▁ for ▁ k ▁ = " , k , " are " , kBitDifferencePairs ( arr , n , k ) ) NEW_LINE
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 [ 1 ] [ 1 ] NEW_LINE F [ 0 ] [ 0 ] = x NEW_LINE F [ 0 ] [ 1 ] = y NEW_LINE F [ 1 ] [ 0 ] = z NEW_LINE F [ 1 ] [ 1 ] = w NEW_LINE DEDENT def power ( F , n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return NEW_LINE DEDENT M = [ [ 1 , 1 ] , [ 1 , 0 ] ] NEW_LINE power ( F , n // 2 ) NEW_LINE multiply ( F , F ) NEW_LINE if ( n % 2 != 0 ) : NEW_LINE INDENT multiply ( F , M ) NEW_LINE DEDENT DEDENT def countWays ( n ) : NEW_LINE INDENT F = [ [ 1 , 1 ] , [ 1 , 0 ] ] NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT power ( F , n ) NEW_LINE return F [ 0 ] [ 0 ] NEW_LINE DEDENT n = 5 NEW_LINE print ( countWays ( n ) ) NEW_LINE
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_LINE m = 13 NEW_LINE print ( multiply ( n , m ) ) NEW_LINE DEDENT
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 ; check prev_count and curr_count on encounter of first zero after continuous - 1 s ; check for last sequence of continuous - 1 ; Driver code
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' ) : NEW_LINE INDENT i += 1 NEW_LINE curr_count = 0 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( curr_count < prev_count ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT i += 1 NEW_LINE prev_count = curr_count NEW_LINE curr_count = 0 NEW_LINE DEDENT DEDENT if ( prev_count > curr_count and ( curr_count != 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 1 NEW_LINE DEDENT n = 179 NEW_LINE if ( findContinuous1 ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 are decreasing order . ; Ignore 0 s until we reach a set bit . ; Count current set bits ; Compare current with previous and update previous . ; Driver code
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_count += 1 NEW_LINE DEDENT if ( curr_count >= prev_count ) : NEW_LINE INDENT return False NEW_LINE DEDENT prev_count = curr_count NEW_LINE DEDENT return True NEW_LINE DEDENT n = 10 NEW_LINE if ( areSetBitsIncreasing ( n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ( findPattern ( n ) ) else print ( " No " ) NEW_LINE
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 ( 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 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 arr [ i ] is equal to x , then increment count . ; Increment count of current element ; return total count of pairs with XOR equal to x ; Driver Code
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 else : NEW_LINE INDENT m [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 2 , 5 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE x = 0 NEW_LINE print ( " Count ▁ of ▁ pairs ▁ with ▁ given ▁ XOR ▁ = ▁ " , xorPairCount ( arr , n , x ) ) NEW_LINE
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 to result ; subtract 2 ^ msb_p1 from x and y . ; Driver code
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 ( msb_p1 != msb_p2 ) : NEW_LINE INDENT break NEW_LINE DEDENT msb_val = ( 1 << msb_p1 ) NEW_LINE res = res + msb_val NEW_LINE x = x - msb_val NEW_LINE y = y - msb_val NEW_LINE DEDENT return res NEW_LINE DEDENT x , y = 10 , 15 NEW_LINE print ( andOperator ( x , y ) ) NEW_LINE
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 ) ) NEW_LINE DEDENT
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 odd position and an engineer if at even position ; If parent is an engineer , then current node will be an engineer if at add position and doctor if even position . ; Driver code
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 if ( pos % 2 ) : NEW_LINE INDENT return ' e ' NEW_LINE DEDENT else : NEW_LINE INDENT return ' d ' NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT level = 3 NEW_LINE pos = 4 NEW_LINE if ( findProffesion ( level , pos ) == ' e ' ) : NEW_LINE INDENT print ( " Engineer " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Doctor " ) 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 for current higher bit . ; Increment higher set bit ; Driver code
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 DEDENT printTwoSetBitNums ( 4 ) NEW_LINE
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 - shift 1 by value of current element ; Each 0 in _xor represents an even occurrence ; print the even occurring numbers ; set bit as 1 to avoid printing duplicates ; Driver code
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 ] , end = " ▁ " ) ; NEW_LINE axor ^= pos ; NEW_LINE DEDENT DEDENT DEDENT arr = [ 9 , 12 , 23 , 10 , 12 , 12 , 15 , 23 , 14 , 12 , 15 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE printRepeatingEven ( arr , n ) ; NEW_LINE
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 ; replace the divident by the result of XOR and pull 1 bit down ; else : If leftmost bit is '0' If the leftmost bit of the dividend ( or the part used in each step ) is 0 , the step cannot use the regular divisor ; we need to use an all - 0 s divisor . ; increment pick to move further ; For the last n bits , we have to carry it out normally as increased value of pick will cause Index Out of Bounds . ; Function used at the sender side to encode data by appending remainder of modular division at the end of data . ; Appends n - 1 zeroes at end of data ; Append remainder in the original data ; Driver code
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 ( divident , divisor ) : NEW_LINE INDENT pick = len ( divisor ) NEW_LINE tmp = divident [ 0 : pick ] NEW_LINE while pick < len ( divident ) : NEW_LINE INDENT if tmp [ 0 ] == '1' : NEW_LINE INDENT tmp = xor ( divisor , tmp ) + divident [ pick ] NEW_LINE tmp = xor ( '0' * pick , tmp ) + divident [ pick ] NEW_LINE DEDENT pick += 1 NEW_LINE DEDENT if tmp [ 0 ] == '1' : NEW_LINE INDENT tmp = xor ( divisor , tmp ) NEW_LINE DEDENT else : NEW_LINE INDENT tmp = xor ( '0' * pick , tmp ) NEW_LINE DEDENT checkword = tmp NEW_LINE return checkword NEW_LINE DEDENT def encodeData ( data , key ) : NEW_LINE INDENT l_key = len ( key ) NEW_LINE appended_data = data + '0' * ( l_key - 1 ) NEW_LINE remainder = mod2div ( appended_data , key ) NEW_LINE codeword = data + remainder NEW_LINE print ( " Remainder ▁ : ▁ " , remainder ) NEW_LINE print ( " Encoded ▁ Data ▁ ( Data ▁ + ▁ Remainder ) ▁ : ▁ " , codeword ) NEW_LINE DEDENT data = "100100" NEW_LINE key = "1101" NEW_LINE encodeData ( data , key ) NEW_LINE
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 False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if ( isBleak ( 3 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT if ( isBleak ( 4 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 xoredBit = ( b1 b2 ) NEW_LINE DEDENT res <<= 1 ; NEW_LINE res |= xoredBit NEW_LINE DEDENT return res NEW_LINE DEDENT x = 3 NEW_LINE y = 5 NEW_LINE print ( " XOR ▁ is " , myXOR ( x , y ) ) NEW_LINE
Find XOR of two number without using XOR operator | Returns XOR of x and y ; Driver Code
def myXOR ( x , y ) : NEW_LINE INDENT return ( ( x y ) & ( ~ x ~ y ) ) NEW_LINE DEDENT x = 3 NEW_LINE y = 5 NEW_LINE print ( " XOR ▁ is " , myXOR ( x , y ) ) NEW_LINE
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 program to test above function
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_LINE print ( " Result ▁ = ▁ " , res ) NEW_LINE DEDENT
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 at indices l and r are part of a valid sub - array ; Update the maximum length so far ; Select the next consecutive pair ; Return the maximum length ; Driver code
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 ] == arr [ j ] ) : NEW_LINE INDENT l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT maxLen = max ( maxLen , 2 * ( r - j ) ) NEW_LINE DEDENT i += 1 NEW_LINE j = i + 1 NEW_LINE DEDENT return maxLen NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 0 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxLength ( arr , n ) ) NEW_LINE
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 ) ; Now comput A * ( B * r ) for evaluating expression A * ( B * r ) - ( C * r ) ; Finally check if value of expression A * ( B * r ) - ( C * r ) is 0 or not ; Runs k iterations Freivald . The value of k determines accuracy . Higher value means higher accuracy . ; Driver code
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 ) : NEW_LINE INDENT br [ i ] = br [ i ] + b [ i ] [ j ] * r [ j ] NEW_LINE DEDENT DEDENT cr = [ 0 ] * N NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT cr [ i ] = cr [ i ] + c [ i ] [ j ] * r [ j ] NEW_LINE DEDENT DEDENT axbr = [ 0 ] * N NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( 0 , N ) : NEW_LINE INDENT axbr [ i ] = axbr [ i ] + a [ i ] [ j ] * br [ j ] NEW_LINE DEDENT DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( axbr [ i ] - cr [ i ] != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def isProduct ( a , b , c , k ) : NEW_LINE INDENT for i in range ( 0 , k ) : NEW_LINE INDENT if ( freivald ( a , b , c ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT a = [ [ 1 , 1 ] , [ 1 , 1 ] ] NEW_LINE b = [ [ 1 , 1 ] , [ 1 , 1 ] ] NEW_LINE c = [ [ 2 , 2 ] , [ 2 , 2 ] ] NEW_LINE k = 2 NEW_LINE if ( isProduct ( a , b , c , k ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 print ( " Expectation ▁ of ▁ array ▁ E ( X ) ▁ is ▁ : ▁ " , expect ) 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 CAPTCHA ; Ask user to enter a CAPTCHA ; Notify user about matching status
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 = " " NEW_LINE while ( n ) : NEW_LINE INDENT captcha += chrs [ random . randint ( 1 , 1000 ) % 62 ] NEW_LINE n -= 1 NEW_LINE DEDENT return captcha NEW_LINE DEDENT captcha = generateCaptcha ( 9 ) NEW_LINE print ( captcha ) NEW_LINE print ( " Enter ▁ above ▁ CAPTCHA : " ) NEW_LINE usr_captcha = input ( ) NEW_LINE if ( checkCaptcha ( captcha , usr_captcha ) ) : NEW_LINE INDENT print ( " CAPTCHA ▁ Matched " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " CAPTCHA ▁ Not ▁ Matched " ) NEW_LINE DEDENT
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 ) NEW_LINE DEDENT return ans % m NEW_LINE DEDENT def SumGP ( a , r , N , M ) : NEW_LINE INDENT answer = a * SumGPUtil ( r , N , M ) NEW_LINE answer = answer % M NEW_LINE print ( answer ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE a = 1 NEW_LINE r = 4 NEW_LINE N = 10000 NEW_LINE M = 100000 NEW_LINE INDENT SumGP ( a , r , N , M ) NEW_LINE DEDENT
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 prefix sum over it ; Len will store maximum Length of subarray ; This indicate there is at least one subarray of Length mid that has sum > 0 ; Check every subarray of Length mid if it has sum > 0 or not if sum > 0 then it will satisfy our required condition ; x will store the sum of subarray of Length mid ; Satisfy our given condition ; Check for higher Length as we get Length mid ; Check for lower Length as we did not get Length mid ; Driver code
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 [ i - 1 ] + pre [ i ] NEW_LINE DEDENT Len = 0 NEW_LINE lo = 1 NEW_LINE hi = n NEW_LINE while ( lo <= hi ) : NEW_LINE INDENT mid = ( lo + hi ) // 2 NEW_LINE ok = False NEW_LINE for i in range ( mid - 1 , n ) : NEW_LINE INDENT x = pre [ i ] NEW_LINE if ( i - mid >= 0 ) : NEW_LINE INDENT x -= pre [ i - mid ] NEW_LINE DEDENT if ( x > 0 ) : NEW_LINE INDENT ok = True NEW_LINE break NEW_LINE DEDENT DEDENT if ( ok == True ) : NEW_LINE INDENT Len = mid NEW_LINE lo = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mid - 1 NEW_LINE DEDENT DEDENT return Len NEW_LINE DEDENT a = [ 2 , 3 , 4 , 5 , 3 , 7 ] NEW_LINE k = 3 NEW_LINE n = len ( a ) NEW_LINE print ( LongestSubarray ( a , n , k ) ) NEW_LINE
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 ( l1 , r1 , l2 , r2 ) NEW_LINE DEDENT
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 at least arr [ i ] ; If the index is not - 1 ; Otherwise ; Function to find the lower bound of N using binary search ; Stores the lower bound ; Stores the upper bound ; Stores the minimum index having value is at least N ; Iterater while i <= j ; Stores the mid index of the range [ i , j ] ; If P [ mid ] is at least N ; Update the value of mid to index ; Update the value of j ; Update the value of i ; Return the resultant index ; Driver Code
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 DEDENT else : NEW_LINE INDENT print ( - 1 , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT def binarySeach ( P , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = len ( P ) - 1 NEW_LINE index = - 1 NEW_LINE while ( i <= j ) : NEW_LINE INDENT mid = i + ( j - i ) // 2 NEW_LINE if ( P [ mid ] >= N ) : NEW_LINE INDENT index = mid NEW_LINE j = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = mid + 1 NEW_LINE DEDENT DEDENT return index NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 400 , 200 , 700 , 900 , 1400 ] NEW_LINE P = [ 100 , 300 , 400 , 500 , 600 ] NEW_LINE minDays ( P , arr ) NEW_LINE DEDENT
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 >= arr [ i ] ; Update the maximum profit ; Return the maximum possible price ; Driver code
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 DEDENT DEDENT return price NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 22 , 87 , 9 , 50 , 56 , 43 ] NEW_LINE print ( maximumProfit ( arr , 6 ) ) NEW_LINE DEDENT
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 index ; Stores the maximum palindromic substring length for each index ; Traverse the string ; Stores the maximum length of palindromic substring ; Consider that palindromic substring ends at index i ; If current character is a valid starting index ; If S [ i , j ] is palindrome , ; Update the length of the longest palindrome ; Consider that palindromic substring starts at index i ; If current character is a valid ending index ; If str [ i , j ] is palindrome ; Update the length of the longest palindrome ; Update length of the longest palindromic substring for index i ; Print the length of the longest palindromic substring ; Driver Code
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 range ( N ) : NEW_LINE INDENT maxlength = 1 NEW_LINE for j in range ( i ) : NEW_LINE if ( S [ j ] == S [ i ] ) : NEW_LINE INDENT if ( isPalindrome ( S , j , i ) ) : NEW_LINE maxlength = i - j + 1 NEW_LINE break NEW_LINE DEDENT j = N - 1 NEW_LINE while ( j > i ) : NEW_LINE if ( S [ j ] == S [ i ] ) : NEW_LINE INDENT if ( isPalindrome ( S , i , j ) ) : NEW_LINE maxlength = max ( j - i + 1 , maxlength ) NEW_LINE break NEW_LINE DEDENT j -= 1 NEW_LINE palLength [ i ] = maxlength NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( palLength [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " bababa " NEW_LINE N = len ( S ) NEW_LINE printLongestPalindrome ( S , N ) NEW_LINE DEDENT
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 ( arr ) NEW_LINE N = 3 NEW_LINE mulsum ( arr , n , N ) NEW_LINE DEDENT
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 exceeds Y ; Decrease X by the top element of pq ; Remove top of pq ; If X is exhausted ; Current index is the farthest possible ; Print N - 1 as farthest index ; Driver Code ; Function Call
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 -= pq [ - 1 ] NEW_LINE pq [ - 1 ] NEW_LINE DEDENT if ( X < 0 ) : NEW_LINE INDENT print ( i ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( N - 1 ) NEW_LINE DEDENT arr = [ 4 , 2 , 7 , 6 , 9 , 14 , 12 ] NEW_LINE X = 5 NEW_LINE Y = 1 NEW_LINE K = 0 NEW_LINE N = len ( arr ) NEW_LINE farthestHill ( arr , X , Y , N , K ) NEW_LINE
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 character ; Decrease count in charset ; Increase count ; Check if count reached to charLimit ; Find nearest lower char ; If no character can be appended ; Append nearest lower character ; Reset count for next calculation ; Return new largest string ; Driver code ; Given string s
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_LINE INDENT n = len ( originalLabel ) NEW_LINE charset = [ 0 ] * ( 26 ) NEW_LINE newStrings = " " NEW_LINE for i in originalLabel : NEW_LINE INDENT charset [ ord ( i ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 25 , - 1 , - 1 ) : NEW_LINE INDENT count = 0 NEW_LINE while ( charset [ i ] > 0 ) : NEW_LINE INDENT newStrings += chr ( i + ord ( ' a ' ) ) NEW_LINE charset [ i ] -= 1 NEW_LINE count += 1 NEW_LINE if ( charset [ i ] > 0 and count == limit ) : NEW_LINE INDENT next = nextAvailableChar ( charset , i ) NEW_LINE if ( next == ' \0' ) : NEW_LINE INDENT return newStrings NEW_LINE DEDENT newStrings += next NEW_LINE count = 0 NEW_LINE DEDENT DEDENT DEDENT return newStrings NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " ccbbb " NEW_LINE K = 2 NEW_LINE print ( newString ( S , K ) ) NEW_LINE DEDENT
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 ; Print the final array ; Driver Code ; Given array arr ; Function Call
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 ] < 0 ) : NEW_LINE INDENT o += 1 NEW_LINE DEDENT r = o NEW_LINE DEDENT else : NEW_LINE INDENT e += 1 NEW_LINE while ( arr [ e ] % 2 == 1 or arr [ e ] < 0 ) : NEW_LINE INDENT e += 1 NEW_LINE DEDENT r = e NEW_LINE DEDENT arr [ i ] *= - 1 NEW_LINE arr [ r ] *= - 1 NEW_LINE tmp = arr [ i ] NEW_LINE arr [ i ] = arr [ r ] NEW_LINE arr [ r ] = tmp NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ( - 1 * arr [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 ] NEW_LINE swapEvenOdd ( arr ) NEW_LINE DEDENT
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 palindrome type sequence ; we could concatenate the a ' s ▁ left ▁ part ▁ ▁ + b ' s right part in a variable a and a ' s ▁ ▁ right ▁ part + b ' s left in the variable b ; we would check for the palindrome condition if yes we print True else False
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_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT a = " xbdef " NEW_LINE b = " cabex " NEW_LINE if check ( a , b , len ( a ) ) == True or check ( b , a , len ( a ) ) == True : NEW_LINE INDENT print ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( False ) NEW_LINE DEDENT
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 mid having equal elements ; Decrease max to mid ; Function to check if a subarray of length len consisting of equal elements can be obtained or not ; Sliding window ; Last element of the sliding window will be having the max size in the current window ; The current number of element in all indices of the current sliding window ; If the current number of the window , added to k exceeds totalNumbers ; Driver Code ; Function call
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 = 1 NEW_LINE ans = 1 NEW_LINE while ( min <= max ) : NEW_LINE INDENT mid = ( max + min ) // 2 NEW_LINE if ( check ( prefixSum , mid , k , arr ) ) : NEW_LINE INDENT ans = mid NEW_LINE min = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT max = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def check ( pSum , lenn , k , a ) : NEW_LINE INDENT i = 0 NEW_LINE j = lenn NEW_LINE while ( j <= len ( a ) ) : NEW_LINE INDENT maxSize = a [ j - 1 ] NEW_LINE totalNumbers = maxSize * lenn NEW_LINE currNumbers = pSum [ j ] - pSum [ i ] NEW_LINE if ( currNumbers + k >= totalNumbers ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT arr = [ 1 , 1 , 1 ] NEW_LINE k = 7 NEW_LINE print ( maxEqualIdx ( arr , k ) ) NEW_LINE
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 ) ) NEW_LINE
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 equal to K ; '' No number needs to be added ; '' Otherwise ; '' Calculate the sum of digits from least significant digit ; '' If sum exceeds K ; '' Increase previous digit by 1 ; '' Add zeros to the end ; '' Calculate difference between the result and N ; '' Return the result ; ''Driver Code
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 ; NEW_LINE DEDENT ' Calculate ▁ sum ▁ of ▁ the ▁ digits ' ' ' NEW_LINE INDENT while ( num2 != 0 ) : NEW_LINE sum1 += num2 % 10 ; NEW_LINE num2 /= 10 ; NEW_LINE DEDENT if ( sum1 <= K ) : NEW_LINE INDENT X = 0 ; NEW_LINE else : NEW_LINE DEDENT while ( temp > 0 ) : NEW_LINE var = int ( N // ( pow ( 10 , temp - 1 ) ) ) ; NEW_LINE INDENT temp_sum += var % 10 ; NEW_LINE if ( temp_sum >= K ) : NEW_LINE var = var // 10 ; NEW_LINE var += 1 ; NEW_LINE result = var * int ( pow ( 10 , temp ) ) ; NEW_LINE break ; NEW_LINE temp -= 1 ; NEW_LINE X = result - N ; NEW_LINE return X ; NEW_LINE DEDENT return - 1 ; NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 11 ; NEW_LINE K = 1 ; NEW_LINE DEDENT print ( minDigits ( N , K ) ) ; NEW_LINE
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 : Reached the end of array ; If current sum is obtained ; Otherwise ; If previously calculated subproblem occurred ; Check if the required sum can be obtained by adding current element or by subtracting the current index element ; Store the count of ways ; Driver Code
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 ) NEW_LINE DEDENT def dfs ( memo , nums , S , curr_sum , index , sum ) : NEW_LINE INDENT if ( index == len ( nums ) ) : NEW_LINE INDENT if ( S == curr_sum ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT if ( memo [ index ] [ curr_sum + sum ] != - sys . maxsize - 1 ) : NEW_LINE INDENT return memo [ index ] [ curr_sum + sum ] NEW_LINE DEDENT ans = ( dfs ( memo , nums , index + 1 , curr_sum + nums [ index ] , S , sum ) + dfs ( memo , nums , index + 1 , curr_sum - nums [ index ] , S , sum ) ) NEW_LINE memo [ index ] [ curr_sum + sum ] = ans NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = 3 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE answer = findWays ( arr , S ) NEW_LINE print ( answer ) NEW_LINE DEDENT
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 ; Reverse v to calculate the suffix sum ; Calculate the suffix sum ; Reverse to original form ; Reverse the suffix sum array ; Calculate the prefix sum ; Stores the starting index of required subarray ; Stores the ending index of required subarray ; If suffix sum till i - th index is not divisible by x ; Update the answer ; If prefix sum till i - th index is not divisible by x ; Update the answer ; Print the longest subarray ; Driver code
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 suff . append ( v [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT suff . append ( v [ i ] + suff [ i - 1 ] ) NEW_LINE DEDENT v . reverse ( ) NEW_LINE suff . reverse ( ) NEW_LINE preff . append ( v [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT preff . append ( v [ i ] + preff [ i - 1 ] ) NEW_LINE DEDENT ans = 0 NEW_LINE lp = 0 NEW_LINE rp = N - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if suff [ i ] % x != 0 and ans < N - 1 : NEW_LINE INDENT lp = i NEW_LINE rp = N - 1 NEW_LINE ans = max ( ans , N - i ) NEW_LINE DEDENT if preff [ i ] % x != 0 and ans < i + 1 : NEW_LINE INDENT lp = 0 NEW_LINE rp = i NEW_LINE ans = max ( ans , i + 1 ) NEW_LINE DEDENT DEDENT for i in range ( lp , rp + 1 ) : NEW_LINE INDENT print ( v [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT x = 3 NEW_LINE v = [ 1 , 3 , 2 , 6 ] NEW_LINE N = len ( v ) NEW_LINE max_length ( N , x , v ) 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 DEDENT DEDENT print ( " Number ▁ of ▁ times ▁ maximum ▁ " , end = " " ) NEW_LINE print ( " value ▁ updated ▁ = ▁ " , maxCount ) NEW_LINE print ( " Number ▁ of ▁ times ▁ minimum ▁ " , end = " " ) NEW_LINE print ( " value ▁ updated ▁ = ▁ " , minCount ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 20 , 22 ] NEW_LINE maximumUpdates ( arr ) NEW_LINE DEDENT
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 NEW_LINE high = n - 1 NEW_LINE ans = - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( suffix_min [ mid ] < a [ i ] ) : NEW_LINE INDENT ans = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT print ( ans , end = " ▁ " ) NEW_LINE DEDENT DEDENT a = [ 3 , 1 , 5 , 2 , 4 ] NEW_LINE n = len ( a ) NEW_LINE farthest_min ( a , n ) NEW_LINE
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 DEDENT DEDENT print ( a [ n - 1 ] , " occurs " , cnt , " times " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 1 , 1 , 2 , 3 , 4 , 9 , 9 , 10 ] NEW_LINE n = len ( a ) NEW_LINE printElements ( a , n ) NEW_LINE DEDENT
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. ; for efficient searching , use binary search . ; Driver code
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 getPositionInSeries ( a , b , c , k ) : NEW_LINE INDENT start = 1 NEW_LINE end = SMALL_N NEW_LINE if ( c == 0 ) : NEW_LINE INDENT end = LARGE_N NEW_LINE DEDENT ans = 0 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE val = func ( a , b , c , mid ) NEW_LINE if ( val == k ) : NEW_LINE INDENT ans = mid NEW_LINE break NEW_LINE DEDENT elif ( val > k ) : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = 2 NEW_LINE b = 1 NEW_LINE c = 1 NEW_LINE k = 12168587437017 NEW_LINE print ( getPositionInSeries ( a , b , c , k ) ) NEW_LINE DEDENT
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_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 3 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE if checkSorted ( n , arr ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 to Arr [ Arr [ j ] ] or not . ; Driver Code ; Calling function .
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 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Arr = [ 3 , 2 , 1 , 1 , 4 ] NEW_LINE N = len ( Arr ) NEW_LINE if checkIndices ( Arr , N ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 pair ; if Sum is already present in the Map ; check every pair having equal Sum ; if pairs don 't overlap, print them and return ; Insert current pair into the Map ; If no such pair found ; Driver Code
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 != j ) and ( n != i and n != j ) ) : NEW_LINE INDENT print ( " Pair ▁ First ▁ ( { } , ▁ { } ) " . format ( arr [ i ] , arr [ j ] ) ) NEW_LINE print ( " Pair ▁ Second ▁ ( { } , ▁ { } ) " . format ( arr [ m ] , arr [ n ] ) ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT if Sum not in Map : NEW_LINE INDENT Map [ Sum ] = [ ] NEW_LINE DEDENT Map [ Sum ] . append ( ( i , j ) ) NEW_LINE DEDENT DEDENT print ( " No ▁ such ▁ non - overlapping ▁ pairs ▁ present " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 4 , 7 , 8 , 4 ] NEW_LINE size = len ( arr ) NEW_LINE findPairs ( arr , size ) NEW_LINE DEDENT
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 = [ 1 , 5 , 7 , - 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 6 NEW_LINE printPairs ( arr , n , sum ) NEW_LINE
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 ( numberOfElements >= 2 ) : ways += ( numberOfElements * ( numberOfElements - 1 ) / 2 ) ; return ways ; def upper_bound ( a , low , high , element ) : while ( low < high ) : middle = int ( low + ( high - low ) / 2 ) ; if ( a [ middle ] > element ) : high = middle ; else : low = middle + 1 ; return low ; ; if __name__ == ' _ _ main _ _ ' : set of n points on the X axis
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 are distinct NEW_LINE from the points btw these indices represent NEW_LINE points within range ( a [ i ] + 1 and a [ i ] + L ) NEW_LINE both inclusive NEW_LINE if there are at least two elements in between NEW_LINE i and indexGreater find the Number of ways NEW_LINE to select two points out of these NEW_LINE DEDENT DEDENT Driver Code NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE L = 4 ; NEW_LINE ans = countTripletsLessThanL ( n , L , arr ) ; NEW_LINE print ( " Total ▁ Number ▁ of ▁ ways ▁ = ▁ " , ans ) ; NEW_LINE DEDENT
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_LINE DEDENT return sm NEW_LINE DEDENT arr = [ 2 , 2 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minSum ( arr , n ) ) NEW_LINE
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 return sum NEW_LINE DEDENT arr = [ 2 , 2 , 3 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minSum ( arr , n ) ) NEW_LINE
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 as random index between l and r ie . . [ l , r ] ; If the element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver code
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_LINE INDENT return mid NEW_LINE DEDENT if arr [ mid ] > x : NEW_LINE INDENT return randomizedBinarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return randomizedBinarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 10 NEW_LINE result = randomizedBinarySearch ( arr , 0 , n - 1 , x ) NEW_LINE if result == - 1 : NEW_LINE INDENT print ( ' Element ▁ is ▁ not ▁ present ▁ in ▁ array ' ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ' Element ▁ is ▁ present ▁ at ▁ index ▁ ' , result ) NEW_LINE DEDENT DEDENT
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 ▁ Portal ▁ for ▁ Geeks " NEW_LINE rem_vowel ( string ) NEW_LINE string = " Loving ▁ Python ▁ LOL " NEW_LINE rem_vowel ( string ) NEW_LINE
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 result . ; Driver code
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_LINE DEDENT return s NEW_LINE DEDENT a = [ 1 , 100 , 101 ] NEW_LINE print ( minCostToMakeElementEqual ( a ) ) NEW_LINE
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 with current element ; If array is sorted ; Otherwise ; Given array
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_LINE for j in range ( i , len ( arr ) , 2 ) : NEW_LINE if arr [ j ] < minVar : NEW_LINE INDENT minVar = arr [ j ] NEW_LINE idx = j NEW_LINE DEDENT if idx != - 1 : NEW_LINE arr [ i ] , arr [ idx ] = arr [ idx ] , arr [ i ] NEW_LINE DEDENT if isSorted ( arr ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT arr = [ 3 , 5 , 1 , 2 , 6 ] NEW_LINE print ( sortPoss ( arr ) ) NEW_LINE
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 ; Left subarray ; Function to prall array elements whose frequency is greater than N / K ; Sort the array arr ; Stores index of an array element ; Traverse the array ; Stores upper bound of arr [ i ] ; If frequency of arr [ i ] is greater than N / 4 ; Update i ; Driver Code ; Given array arr ; Size of array ; Function Call
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 NDivKWithFreq ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE i = 0 ; NEW_LINE while ( i < N ) : NEW_LINE INDENT X = upperBound ( arr , N , arr [ i ] ) ; NEW_LINE if ( ( X - i ) > N // 4 ) : NEW_LINE INDENT print ( arr [ i ] , end = " " ) ; NEW_LINE DEDENT i = X ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 4 ; NEW_LINE NDivKWithFreq ( arr , N , K ) ; NEW_LINE DEDENT
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 integer ; Stores the maximum possible sum ; Traverse over array count [ ] ; Run loop for each k ; Update ans ; Return maximum possible sum ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call
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_LINE ans += size NEW_LINE count [ k ] -= 1 NEW_LINE DEDENT ans += k * count [ k ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE DEDENT
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 ; Driver code
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 ] , 0 ) + 1 NEW_LINE DEDENT for i in freq : NEW_LINE INDENT ans += ( i * freq [ i ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE queries = [ [ 1 , 2 ] , [ 1 , 3 ] ] NEW_LINE answerQueries ( arr , n , queries ) NEW_LINE DEDENT
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 are present return that element . ; Set the left and right pointers to extreme ; Calculate left and right pointer index . ; Store the queries from [ L + 1 , R - 1 ] . ; Sort array and queries for fenwick updates ; For each query calculate maxx for the answer and store it in ans array . ; if queries [ i ] . index < q : ; Mx will be mx + 2 as while calculating mx , we excluded element at index left and right ; Driver Code
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 self . index = 0 NEW_LINE DEDENT DEDENT def update ( Fenwick : List [ int ] , index : int , val : int , n : int ) -> None : NEW_LINE INDENT while ( index <= n ) : NEW_LINE INDENT Fenwick [ index ] += val NEW_LINE index += index & ( - index ) NEW_LINE DEDENT DEDENT def query ( Fenwick : List [ int ] , index : int , n : int ) -> int : NEW_LINE INDENT summ = 0 NEW_LINE while ( index > 0 ) : NEW_LINE INDENT summ = summ + Fenwick [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return summ NEW_LINE DEDENT def maxLength ( n : int , v : List [ int ] ) -> int : NEW_LINE INDENT where = [ 0 for _ in range ( n + 2 ) ] NEW_LINE arr = [ Arrays ( ) for _ in range ( n ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT v [ i - 1 ] = v [ i - 1 ] - 1 NEW_LINE x = v [ i - 1 ] NEW_LINE where [ x ] = i - 1 NEW_LINE arr [ i - 1 ] . val = x NEW_LINE arr [ i - 1 ] . index = i - 1 NEW_LINE DEDENT if ( n <= 2 ) : NEW_LINE INDENT print ( n ) NEW_LINE return 0 NEW_LINE DEDENT left = n NEW_LINE right = 0 NEW_LINE mx = 0 NEW_LINE queries = [ Query ( ) for _ in range ( 4 * n ) ] NEW_LINE j = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT left = min ( left , where [ i ] ) NEW_LINE right = max ( right , where [ i ] ) NEW_LINE diff = right - left NEW_LINE if ( diff == 0 or diff == 1 ) : NEW_LINE INDENT continue NEW_LINE DEDENT val1 = v [ left ] NEW_LINE val2 = v [ right ] NEW_LINE minn = min ( val1 , val2 ) NEW_LINE queries [ j ] . l = left + 1 NEW_LINE queries [ j ] . r = right - 1 NEW_LINE queries [ j ] . x = minn NEW_LINE queries [ j ] . index = j NEW_LINE j += 1 NEW_LINE DEDENT Fenwick = [ 0 for _ in range ( n + 1 ) ] NEW_LINE q = j - 1 NEW_LINE arr [ : n + 1 ] . sort ( key = lambda x : x . val ) NEW_LINE queries [ : q + 1 ] . sort ( key = lambda val : val . x ) NEW_LINE curr = 0 NEW_LINE ans = [ 0 for _ in range ( q + 1 ) ] NEW_LINE for i in range ( q + 1 ) : NEW_LINE INDENT while ( arr [ curr ] . val <= queries [ i ] . x and curr < n ) : NEW_LINE INDENT update ( Fenwick , arr [ curr ] . index + 1 , 1 , n ) NEW_LINE curr += 1 NEW_LINE DEDENT ans [ queries [ i ] . index ] = query ( Fenwick , queries [ i ] . r + 1 , n ) - query ( Fenwick , queries [ i ] . l , n ) NEW_LINE DEDENT for i in range ( q + 1 ) : NEW_LINE INDENT mx = max ( mx , ans [ i ] ) NEW_LINE DEDENT mx = mx + 2 NEW_LINE return mx NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE v = [ 4 , 2 , 6 , 5 , 3 , 1 ] NEW_LINE print ( maxLength ( n , v ) ) NEW_LINE DEDENT
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 isPandigital ( Str ) : NEW_LINE INDENT if ( len ( Str ) != 9 ) : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT ch = " " . join ( sorted ( Str ) ) NEW_LINE if ( ch == "123456789" ) : NEW_LINE INDENT return bool ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT return bool ( False ) NEW_LINE DEDENT DEDENT n = 6952 NEW_LINE if ( bool ( PandigitalProduct_1_9 ( n ) ) ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) NEW_LINE DEDENT
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 as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each element of input array ; Mode is the index with maximum count ; Update count [ ] array with sum ; Sorted output array b [ ] to calculate median ; Median according to odd and even array size respectively . ; Output the result ; Driver Code
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 [ i ] > k ) : NEW_LINE INDENT k = count [ i ] NEW_LINE mode = i NEW_LINE DEDENT DEDENT for i in range ( 1 , t ) : NEW_LINE INDENT count [ i ] = count [ i ] + count [ i - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT b [ count [ a [ i ] ] - 1 ] = a [ i ] NEW_LINE count [ a [ i ] ] -= 1 NEW_LINE DEDENT median = 0.0 NEW_LINE if ( n % 2 != 0 ) : NEW_LINE INDENT median = b [ n // 2 ] NEW_LINE DEDENT else : NEW_LINE INDENT median = ( ( b [ ( n - 1 ) // 2 ] + b [ n // 2 ] ) / 2.0 ) NEW_LINE DEDENT print ( " median ▁ = " , median ) NEW_LINE print ( " mode ▁ = " , mode ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 1 , 2 , 7 , 1 , 2 , 5 , 3 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE printModeMedian ( arr , n ) NEW_LINE DEDENT
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 counter arrays differ ; Declaration and initialization of counter array ; Driver function
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 counter2 [ ord ( st [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( counter2 [ i ] != counter1 [ i ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT st = " abcasdsabcae " NEW_LINE if function ( st ) : print ( " Yes , ▁ both ▁ halves ▁ differ ▁ " , " by ▁ at ▁ least ▁ one ▁ character " ) NEW_LINE else : print ( " No , ▁ both ▁ halves ▁ do ▁ not ▁ differ ▁ at ▁ all " ) NEW_LINE
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 true if any index has non - zero value ; Declaration and initialization of counter array ; Driver function
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 ] ) - ord ( ' a ' ) ] -= 1 NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( counter [ i ] != 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT st = " abcasdsabcae " NEW_LINE if function ( st ) : NEW_LINE INDENT print ( " Yes , ▁ both ▁ halves ▁ differ ▁ by ▁ at ▁ " , " least ▁ one ▁ character " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No , ▁ both ▁ halves ▁ do ▁ not ▁ differ ▁ at ▁ all " ) NEW_LINE DEDENT
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 - sized segment ; Driver Code
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 , 101 , 102 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( minDifferenceAmongMaxMin ( arr , N , K ) ) NEW_LINE
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 increase the smaller count ; If element is equal then increase count only if it occurs before ; Driver code to test above methods
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 DEDENT arr = [ 3 , 4 , 3 , 5 , 2 , 3 , 4 , 3 , 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE idxOfEle = 5 NEW_LINE print getIndexInSortedArray ( arr , n , idxOfEle ) 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 permutation ; Stores the count of numbers in the given segment ; If the sum is not possible with numbers in the segment ; Output - 1 ; Stores the numbers present within the given segment ; Iterate over the numbers from 1 to N ; If ( S - i ) is a positive non - zero sum and if it is possible to obtain ( S - i ) remaining numbers ; Update sum S ; Update required numbers in the segement ; Push i in vector v ; If sum has been obtained ; Break from the loop ; If sum is not obtained ; Output - 1 ; Stores the numbers which are not present in given segment ; Loop to check the numbers not present in the segment ; Pointer to check if i is present in vector v or not ; If i is not present in v ; Push i in vector v1 ; Point to the first elements of v1 and v respectively ; Print the required permutation ; Driver Code
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_LINE if ( not possible ( x , S , N ) ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( N , 0 , - 1 ) : NEW_LINE INDENT if ( ( S - i ) >= 0 and possible ( x - 1 , S - i , i - 1 ) ) : NEW_LINE INDENT S = S - i NEW_LINE x -= 1 NEW_LINE v . append ( i ) NEW_LINE DEDENT if ( S == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( S != 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT v1 = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT it = i in v NEW_LINE if ( not it ) : NEW_LINE INDENT v1 . append ( i ) NEW_LINE DEDENT DEDENT j = 0 NEW_LINE f = 0 NEW_LINE for i in range ( 1 , L ) : NEW_LINE INDENT print ( v1 [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( L , R + 1 ) : NEW_LINE INDENT print ( v [ f ] , end = " ▁ " ) NEW_LINE f += 1 NEW_LINE DEDENT for i in range ( R + 1 , N + 1 ) : NEW_LINE INDENT print ( v1 [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 6 NEW_LINE L = 3 NEW_LINE R = 5 NEW_LINE S = 8 NEW_LINE findPermutation ( N , L , R , S ) NEW_LINE DEDENT