text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find a triplet in an array whose sum is closest to a given number | Python3 implementation of the approach ; Function to return the sum of a triplet which is closest to x ; Sort the array ; To store the closest sum ; Fix the smallest number among the three integers ; Two pointers initially pointing at the last and the element next to the fixed element ; While there could be more pairs to check ; Calculate the sum of the current triplet ; If the sum is more closer than the current closest sum ; If sum is greater then x then decrement the second pointer to get a smaller sum ; Else increment the first pointer to get a larger sum ; Return the closest sum found ; Driver code
import sys NEW_LINE def solution ( arr , x ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE closestSum = sys . maxsize ; NEW_LINE for i in range ( len ( arr ) - 2 ) : NEW_LINE INDENT ptr1 = i + 1 ; ptr2 = len ( arr ) - 1 ; NEW_LINE while ( ptr1 < ptr2 ) : NEW_LINE INDENT sum = arr [ i ] + arr [ ptr1 ] + arr [ ptr2 ] ; NEW_LINE if ( abs ( x - sum ) < abs ( x - closestSum ) ) : NEW_LINE INDENT closestSum = sum ; NEW_LINE DEDENT if ( sum > x ) : NEW_LINE INDENT ptr2 -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ptr1 += 1 ; NEW_LINE DEDENT DEDENT DEDENT return closestSum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 1 , 2 , 1 , - 4 ] ; NEW_LINE x = 1 ; NEW_LINE print ( solution ( arr , x ) ) ; NEW_LINE DEDENT
Merge two BSTs with constant extra space | Node of the binary tree ; A utility function to print Inorder traversal of a Binary Tree ; The function to print data of two BSTs in sorted order ; Base cases ; If the first tree is exhausted simply print the inorder traversal of the second tree ; If second tree is exhausted simply print the inoreder traversal of the first tree ; A temporary pointer currently pointing to root of first tree ; previous pointer to store the parent of temporary pointer ; Traverse through the first tree until you reach the leftmost element , which is the first element of the tree in the inorder traversal . This is the least element of the tree ; Another temporary pointer currently pointing to root of second tree ; Previous pointer to store the parent of second temporary pointer ; Traverse through the second tree until you reach the leftmost element , which is the first element of the tree in inorder traversal . This is the least element of the tree . ; Compare the least current least elements of both the tree ; If first tree 's element is smaller print it ; If the node has no parent , that means this node is the root ; Simply make the right child of the root as new root ; If node has a parent ; As this node is the leftmost node , it is certain that it will not have a let child so we simply assign this node ' s ▁ right ▁ pointer , ▁ which ▁ can ▁ be ▁ ▁ either ▁ null ▁ or ▁ not , ▁ to ▁ its ▁ parent ' s left pointer . This statement is just doing the task of deleting the node ; recursively call the merge function with updated tree ; If the node has no parent , that means this node is the root ; Simply make the right child of root as new root ; If node has a parent ; Recursively call the merge function with updated tree ; Driver Code ; Print sorted nodes of both trees
class node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inorder ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT inorder ( root . left ) NEW_LINE print ( root . data , end = " ▁ " ) NEW_LINE inorder ( root . right ) NEW_LINE DEDENT DEDENT def merge ( root1 , root2 ) : NEW_LINE INDENT if ( not root1 and not root2 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( not root1 ) : NEW_LINE INDENT inorder ( root2 ) NEW_LINE return NEW_LINE DEDENT if ( not root2 ) : NEW_LINE INDENT inorder ( root1 ) NEW_LINE return NEW_LINE DEDENT temp1 = root1 NEW_LINE prev1 = None NEW_LINE while ( temp1 . left ) : NEW_LINE INDENT prev1 = temp1 NEW_LINE temp1 = temp1 . left NEW_LINE DEDENT temp2 = root2 NEW_LINE prev2 = None NEW_LINE while ( temp2 . left ) : NEW_LINE INDENT prev2 = temp2 NEW_LINE temp2 = temp2 . left NEW_LINE DEDENT if ( temp1 . data <= temp2 . data ) : NEW_LINE INDENT print ( temp1 . data , end = " ▁ " ) NEW_LINE if ( prev1 == None ) : NEW_LINE INDENT merge ( root1 . right , root2 ) NEW_LINE DEDENT else : NEW_LINE INDENT prev1 . left = temp1 . right NEW_LINE merge ( root1 , root2 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( temp2 . data , end = " ▁ " ) NEW_LINE if ( prev2 == None ) : NEW_LINE INDENT merge ( root1 , root2 . right ) NEW_LINE DEDENT else : NEW_LINE INDENT prev2 . left = temp2 . right NEW_LINE merge ( root1 , root2 ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = None NEW_LINE root2 = None NEW_LINE root1 = node ( 3 ) NEW_LINE root1 . left = node ( 1 ) NEW_LINE root1 . right = node ( 5 ) NEW_LINE root2 = node ( 4 ) NEW_LINE root2 . left = node ( 2 ) NEW_LINE root2 . right = node ( 6 ) NEW_LINE merge ( root1 , root2 ) NEW_LINE DEDENT
Print elements of an array according to the order defined by another array | set 2 | Function to print an array according to the order defined by another array ; Declaring map and iterator ; Store the frequency of each number of a1 [ ] int the map ; Traverse through a2 [ ] ; Check whether number is present in map or not ; Print that number that many times of its frequency ; Print those numbers that are not present in a2 [ ] ; Driver code
def print_in_order ( a1 , a2 , n , m ) : NEW_LINE INDENT mp = dict . fromkeys ( a1 , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ a1 [ i ] ] += 1 ; NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT if a2 [ i ] in mp . keys ( ) : NEW_LINE INDENT for j in range ( mp [ a2 [ i ] ] ) : NEW_LINE INDENT print ( a2 [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT del ( mp [ a2 [ i ] ] ) ; NEW_LINE DEDENT DEDENT for key , value in mp . items ( ) : NEW_LINE INDENT for j in range ( value ) : NEW_LINE INDENT print ( key , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT print ( ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a1 = [ 2 , 1 , 2 , 5 , 7 , 1 , 9 , 3 , 6 , 8 , 8 ] ; NEW_LINE a2 = [ 2 , 1 , 8 , 3 ] ; NEW_LINE n = len ( a1 ) ; NEW_LINE m = len ( a2 ) ; NEW_LINE print_in_order ( a1 , a2 , n , m ) ; NEW_LINE DEDENT
Check whether we can sort two arrays by swapping A [ i ] and B [ i ] | Function to check whether both the array can be sorted in ( strictly increasing ) ascending order ; Traverse through the array and find out the min and max variable at each position make one array of min variables and another of maximum variable ; Maximum and minimum variable ; Assign min value to B [ i ] and max value to A [ i ] ; Now check whether the array is sorted or not ; Driver code
def IsSorted ( A , B , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT x = max ( A [ i ] , B [ i ] ) ; NEW_LINE y = min ( A [ i ] , B [ i ] ) ; NEW_LINE A [ i ] = x ; NEW_LINE B [ i ] = y ; NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( A [ i ] <= A [ i - 1 ] or B [ i ] <= B [ i - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 4 , 3 , 5 , 7 ] ; NEW_LINE B = [ 2 , 2 , 5 , 8 , 9 ] ; NEW_LINE n = len ( A ) ; NEW_LINE if ( IsSorted ( A , B , n ) ) : NEW_LINE INDENT print ( True ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( False ) NEW_LINE DEDENT DEDENT
Find the largest possible k | Function to find the largest possible k - multiple set ; Sort the given array ; To store k - multiple set ; Traverse through the whole array ; Check if x / k is already present or not ; Print the k - multiple set ; Driver code ; Function call
def K_multiple ( a , n , k ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE s = set ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( a [ i ] % k == 0 and a [ i ] // k not in s ) or a [ i ] % k != 0 ) : NEW_LINE INDENT s . add ( a [ i ] ) ; NEW_LINE DEDENT DEDENT for i in s : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 3 , 4 , 5 , 6 , 10 ] ; NEW_LINE k = 2 ; NEW_LINE n = len ( a ) ; NEW_LINE K_multiple ( a , n , k ) ; NEW_LINE DEDENT
Maximum water that can be stored between two buildings | Return the maximum water that can be stored ; To store the maximum water so far ; Both the pointers are pointing at the first and the last buildings respectively ; While the water can be stored between the currently chosen buildings ; Update maximum water so far and increment i ; Update maximum water so far and decrement j ; Any of the pointers can be updated ( or both ) ; Driver code
def maxWater ( height , n ) : NEW_LINE INDENT maximum = 0 ; NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( height [ i ] < height [ j ] ) : NEW_LINE INDENT maximum = max ( maximum , ( j - i - 1 ) * height [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT elif ( height [ j ] < height [ i ] ) : NEW_LINE INDENT maximum = max ( maximum , ( j - i - 1 ) * height [ j ] ) ; NEW_LINE j -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT maximum = max ( maximum , ( j - i - 1 ) * height [ i ] ) ; NEW_LINE i += 1 ; NEW_LINE j -= 1 ; NEW_LINE DEDENT DEDENT return maximum ; NEW_LINE DEDENT height = [ 2 , 1 , 3 , 4 , 6 , 5 ] NEW_LINE n = len ( height ) NEW_LINE print ( maxWater ( height , n ) ) ; NEW_LINE
Count the maximum number of elements that can be selected from the array | Function to return the maximum count of selection possible from the given array following the given process ; Initialize result ; Sorting the array ; Initialize the select variable ; Loop through array ; If selection is possible ; Increment result ; Increment selection variable ; Driver Code
def maxSelectionCount ( a , n ) : NEW_LINE INDENT res = 0 ; NEW_LINE a . sort ( ) ; NEW_LINE select = 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] >= select ) : NEW_LINE DEDENT DEDENT res += 1 ; NEW_LINE select += 1 ; NEW_LINE INDENT return res ; NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 3 , 5 , 1 , 4 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( maxSelectionCount ( arr , N ) ) ; NEW_LINE
Print combinations of distinct numbers which add up to give sum N | arr [ ] to store all the distinct elements index - next location in array num - given number reducedNum - reduced number ; Set to store all the distinct elements ; Base condition ; Iterate over all the elements and store it into the set ; Calculate the sum of all the elements of the set ; Compare whether the sum is equal to n or not , if it is equal to n print the numbers ; Find previous number stored in the array ; Store all the numbers recursively into the arr [ ] ; Function to find all the distinct combinations of n ; Driver code
def findCombinationsUtil ( arr , index , n , red_num ) : NEW_LINE INDENT s = set ( ) NEW_LINE sum = 0 NEW_LINE if ( red_num < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( red_num == 0 ) : NEW_LINE INDENT for i in range ( index ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT for itr in s : NEW_LINE INDENT sum = sum + ( itr ) NEW_LINE DEDENT if ( sum == n ) : NEW_LINE INDENT for i in s : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE return NEW_LINE DEDENT DEDENT if ( index == 0 ) : NEW_LINE INDENT prev = 1 NEW_LINE DEDENT else : NEW_LINE INDENT prev = arr [ index - 1 ] NEW_LINE DEDENT for k in range ( prev , n + 1 , 1 ) : NEW_LINE INDENT arr [ index ] = k NEW_LINE findCombinationsUtil ( arr , index + 1 , n , red_num - k ) NEW_LINE DEDENT DEDENT def findCombinations ( n ) : NEW_LINE INDENT a = [ 0 for i in range ( n + 1 ) ] NEW_LINE findCombinationsUtil ( a , 0 , n , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 7 NEW_LINE findCombinations ( n ) NEW_LINE DEDENT
Check whether an array can be made strictly increasing by modifying atmost one element | Function that returns true if arr [ ] can be made strictly increasing after modifying at most one element ; To store the number of modifications required to make the array strictly increasing ; Check whether the first element needs to be modify or not ; Loop from 2 nd element to the 2 nd last element ; Check whether arr [ i ] needs to be modified ; Modifying arr [ i ] ; Check if arr [ i ] is equal to any of arr [ i - 1 ] or arr [ i + 1 ] ; Check whether the last element needs to be modify or not ; If more than 1 modification is required ; Driver code
def check ( arr , n ) : NEW_LINE INDENT modify = 0 NEW_LINE if ( arr [ 0 ] > arr [ 1 ] ) : NEW_LINE INDENT arr [ 0 ] = arr [ 1 ] // 2 NEW_LINE modify += 1 NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( ( arr [ i - 1 ] < arr [ i ] and arr [ i + 1 ] < arr [ i ] ) or ( arr [ i - 1 ] > arr [ i ] and arr [ i + 1 ] > arr [ i ] ) ) : NEW_LINE INDENT arr [ i ] = ( arr [ i - 1 ] + arr [ i + 1 ] ) // 2 NEW_LINE if ( arr [ i ] == arr [ i - 1 ] or arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT modify += 1 NEW_LINE DEDENT DEDENT if ( arr [ n - 1 ] < arr [ n - 2 ] ) : NEW_LINE INDENT modify += 1 NEW_LINE DEDENT if ( modify > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 8 , 6 , 9 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE if ( check ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Check if the given matrix is increasing row and column wise | Python3 implementation of the approach ; Function that returns true if the matrix is strictly increasing ; Check if the matrix is strictly increasing ; Out of bound condition ; Out of bound condition ; Driver code
N , M = 2 , 2 NEW_LINE def isMatrixInc ( a ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( i - 1 >= 0 ) : NEW_LINE INDENT if ( a [ i ] [ j ] <= a [ i - 1 ] [ j ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT if ( j - 1 >= 0 ) : NEW_LINE INDENT if ( a [ i ] [ j ] <= a [ i ] [ j - 1 ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ [ 2 , 10 ] , [ 11 , 20 ] ] ; NEW_LINE if ( isMatrixInc ( a ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Maximize the size of array by deleting exactly k sub | Python implementation of above approach ; Sieve of Eratosthenes ; Function to return the size of the maximized array ; Insert the indices of composite numbers ; Compute the number of prime between two consecutive composite ; Sort the diff vector ; Compute the prefix sum of diff vector ; Impossible case ; Delete sub - arrays of length 1 ; Find the number of primes to be deleted when deleting the sub - arrays ; Driver code
N = 10000005 NEW_LINE prime = [ False ] * N NEW_LINE def seive ( ) : NEW_LINE INDENT for i in range ( 2 , N ) : NEW_LINE INDENT if not prime [ i ] : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT prime [ j ] = True NEW_LINE DEDENT DEDENT DEDENT prime [ 1 ] = True NEW_LINE DEDENT def maxSizeArr ( arr , n , k ) : NEW_LINE INDENT v , diff = [ ] , [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prime [ arr [ i ] ] : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , len ( v ) ) : NEW_LINE INDENT diff . append ( v [ i ] - v [ i - 1 ] - 1 ) NEW_LINE DEDENT diff . sort ( ) NEW_LINE for i in range ( 1 , len ( diff ) ) : NEW_LINE INDENT diff [ i ] += diff [ i - 1 ] NEW_LINE DEDENT if k > n or ( k == 0 and len ( v ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT elif len ( v ) <= k : NEW_LINE INDENT return ( n - k ) NEW_LINE DEDENT elif len ( v ) > k : NEW_LINE INDENT tt = len ( v ) - k NEW_LINE s = 0 NEW_LINE s += diff [ tt - 1 ] NEW_LINE res = n - ( len ( v ) + s ) NEW_LINE return res NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT seive ( ) NEW_LINE arr = [ 2 , 4 , 2 , 2 , 4 , 2 , 4 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( maxSizeArr ( arr , n , k ) ) NEW_LINE DEDENT
Sort an array according to count of set bits | Set 2 | function to sort the array according to the number of set bits in elements ; Counting no of setBits in arr [ i ] ; The count is subtracted from 32 because the result needs to be in descending order ; Printing the numbers in descending order of set bit count ; Driver code
def sortArr ( arr , n ) : NEW_LINE INDENT mp = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT count = 0 NEW_LINE k = arr [ i ] NEW_LINE while ( k ) : NEW_LINE INDENT k = k & k - 1 NEW_LINE count += 1 NEW_LINE DEDENT mp . append ( ( 32 - count , arr [ i ] ) ) NEW_LINE DEDENT mp . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for it in mp : NEW_LINE INDENT print ( it [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 2 , 3 , 9 , 4 , 6 , 7 , 15 , 32 ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE DEDENT
Smallest multiple of N formed using the given set of digits | Function to return the required number ; Initialize both vectors with their initial values ; Sort the vector of digits ; Initialize the queue ; If modulus value is not present in the queue ; Compute digits modulus given number and update the queue and vectors ; While queue is not empty ; Remove the first element of the queue ; Compute new modulus values by using old queue values and each digit of the set ; If value is not present in the queue ; If required condition can 't be satisfied ; Initialize new vector ; Constructing the solution by backtracking ; Reverse the vector ; Return the required number ; Driver code
def findSmallestNumber ( arr , n ) : NEW_LINE INDENT dp = [ float ( ' inf ' ) ] * n NEW_LINE result = [ ( - 1 , 0 ) ] * n NEW_LINE arr . sort ( ) NEW_LINE q = [ ] NEW_LINE for i in arr : NEW_LINE INDENT if i != 0 : NEW_LINE INDENT if dp [ i % n ] > 10 ** 9 : NEW_LINE INDENT q . append ( i % n ) NEW_LINE dp [ i % n ] = 1 NEW_LINE result [ i % n ] = - 1 , i NEW_LINE DEDENT DEDENT DEDENT while len ( q ) > 0 : NEW_LINE INDENT u = q . pop ( 0 ) NEW_LINE for i in arr : NEW_LINE INDENT v = ( u * 10 + i ) % n NEW_LINE if dp [ u ] + 1 < dp [ v ] : NEW_LINE INDENT dp [ v ] = dp [ u ] + 1 NEW_LINE q . append ( v ) NEW_LINE result [ v ] = u , i NEW_LINE DEDENT DEDENT DEDENT if dp [ 0 ] > 10 ** 9 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans = [ ] NEW_LINE u = 0 NEW_LINE while u != - 1 : NEW_LINE INDENT ans . append ( result [ u ] [ 1 ] ) NEW_LINE u = result [ u ] [ 0 ] NEW_LINE DEDENT ans = ans [ : : - 1 ] NEW_LINE for i in ans : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 2 , 3 ] NEW_LINE n = 12 NEW_LINE print ( findSmallestNumber ( arr , n ) ) NEW_LINE DEDENT
Count number of subsets whose median is also present in the same subset | Python 3 implementation of the approach ; Function to return the factorial of a number ; Function to return the value of nCr ; Function to return ' a ' raised to the power n with complexity O ( log ( n ) ) ; Function to return the number of sub - sets whose median is also present in the set ; Number of odd length sub - sets ; Sort the array ; Checking each element for leftmost middle element while they are equal ; Calculate the number of elements in right of rightmost middle element ; Calculate the number of elements in left of leftmost middle element ; Add selected even length subsets to the answer ; Driver code
mod = 1000000007 NEW_LINE def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return int ( fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ) NEW_LINE DEDENT def powmod ( a , n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT pt = powmod ( a , int ( n / 2 ) ) NEW_LINE pt = ( pt * pt ) % mod NEW_LINE if ( n % 2 ) : NEW_LINE INDENT return ( pt * a ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT return pt NEW_LINE DEDENT DEDENT def CountSubset ( arr , n ) : NEW_LINE INDENT ans = powmod ( 2 , n - 1 ) NEW_LINE arr . sort ( reverse = False ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j < n and arr [ j ] == arr [ i ] ) : NEW_LINE INDENT r = n - 1 - j NEW_LINE l = i NEW_LINE ans = ( ans + nCr ( l + r , l ) ) % mod NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( CountSubset ( arr , n ) ) NEW_LINE DEDENT
Count number of subsets whose median is also present in the same subset | Python3 implementation of the approach ; Function to store pascal triangle in 2 - d array ; Function to return a raised to the power n with complexity O ( log ( n ) ) ; Function to return the number of sub - sets whose median is also present in the set ; Number of odd length sub - sets ; Sort the array ; Checking each element for leftmost middle element while they are equal ; Calculate the number of elements in right of rightmost middle element ; Calculate the number of elements in left of leftmost middle element ; Add selected even length subsets to the answer ; Driver code
mod = 1000000007 NEW_LINE arr = [ [ None for i in range ( 1001 ) ] for j in range ( 1001 ) ] NEW_LINE def Preprocess ( ) : NEW_LINE INDENT arr [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , 1001 ) : NEW_LINE INDENT arr [ i ] [ 0 ] = 1 NEW_LINE for j in range ( 1 , i ) : NEW_LINE INDENT arr [ i ] [ j ] = ( arr [ i - 1 ] [ j - 1 ] + arr [ i - 1 ] [ j ] ) % mod NEW_LINE DEDENT arr [ i ] [ i ] = 1 NEW_LINE DEDENT DEDENT def powmod ( a , n ) : NEW_LINE INDENT if not n : NEW_LINE INDENT return 1 NEW_LINE DEDENT pt = powmod ( a , n // 2 ) NEW_LINE pt = ( pt * pt ) % mod NEW_LINE if n % 2 : NEW_LINE INDENT return ( pt * a ) % mod NEW_LINE DEDENT else : NEW_LINE INDENT return pt NEW_LINE DEDENT DEDENT def CountSubset ( val , n ) : NEW_LINE INDENT ans = powmod ( 2 , n - 1 ) NEW_LINE val . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while j < n and val [ j ] == val [ i ] : NEW_LINE INDENT r = n - 1 - j NEW_LINE l = i NEW_LINE ans = ( ans + arr [ l + r ] [ l ] ) % mod NEW_LINE j += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT Preprocess ( ) NEW_LINE val = [ 2 , 3 , 2 ] NEW_LINE n = len ( val ) NEW_LINE print ( CountSubset ( val , n ) ) NEW_LINE DEDENT
Reorder the position of the words in alphabetical order | Function to print the ordering of words ; Creating list of words and assigning them index numbers ; Sort the list of words lexicographically ; Print the ordering ; Driver Code
def reArrange ( words , n ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ words [ i ] ] = i + 1 NEW_LINE DEDENT words . sort ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( mp [ words [ i ] ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT words = [ " live " , " place " , " travel " , " word " , " sky " ] NEW_LINE n = len ( words ) NEW_LINE reArrange ( words , n ) ; NEW_LINE
Sum of elements in 1 st array such that number of elements less than or equal to them in 2 nd array is maximum | Python 3 implementation of the approach ; Function to return the required sum ; Creating hash array initially filled with zero ; Calculate the frequency of elements of arr2 [ ] ; Running sum of hash array such that hash [ i ] will give count of elements less than or equal to i in arr2 [ ] ; To store the maximum value of the number of elements in arr2 [ ] which are smaller than or equal to some element of arr1 [ ] ; Calculate the sum of elements from arr1 [ ] corresponding to maximum frequency ; Return the required sum ; Driver code
MAX = 100000 NEW_LINE def findSumofEle ( arr1 , m , arr2 , n ) : NEW_LINE INDENT hash = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ arr2 [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 1 , MAX , 1 ) : NEW_LINE INDENT hash [ i ] = hash [ i ] + hash [ i - 1 ] NEW_LINE DEDENT maximumFreq = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT maximumFreq = max ( maximumFreq , hash [ arr1 [ i ] ] ) NEW_LINE DEDENT sumOfElements = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( maximumFreq == hash [ arr1 [ i ] ] ) : NEW_LINE INDENT sumOfElements += arr1 [ i ] NEW_LINE DEDENT DEDENT return sumOfElements NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 2 , 5 , 6 , 8 ] NEW_LINE arr2 = [ 4 , 10 ] NEW_LINE m = len ( arr1 ) NEW_LINE n = len ( arr2 ) NEW_LINE print ( findSumofEle ( arr1 , m , arr2 , n ) ) NEW_LINE DEDENT
Print 2 | Function to print the coordinates along with their frequency in ascending order ; map to store the pairs and their frequencies ; Store the coordinates along with their frequencies ; Driver code
def Print ( x , y , n ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT m [ ( x [ i ] , y [ i ] ) ] = m . get ( ( x [ i ] , y [ i ] ) , 0 ) + 1 NEW_LINE DEDENT e = sorted ( m ) NEW_LINE for i in e : NEW_LINE INDENT print ( i [ 0 ] , i [ 1 ] , m [ i ] ) NEW_LINE DEDENT DEDENT x = [ 1 , 2 , 1 , 1 , 1 ] NEW_LINE y = [ 1 , 1 , 3 , 1 , 3 ] NEW_LINE n = len ( x ) NEW_LINE Print ( x , y , n ) NEW_LINE
Split the array elements into strictly increasing and decreasing sequence | Function to print both the arrays ; Store both arrays ; Used for hashing ; Iterate for every element ; Increase the count ; If first occurrence ; If second occurrence ; If occurs more than 2 times ; Sort in increasing order ; Print the increasing array ; Sort in reverse order ; Print the decreasing array ; Driver code
def PrintBothArrays ( a , n ) : NEW_LINE INDENT v1 , v2 = [ ] , [ ] ; NEW_LINE mpp = dict . fromkeys ( a , 0 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT mpp [ a [ i ] ] += 1 ; NEW_LINE if ( mpp [ a [ i ] ] == 1 ) : NEW_LINE INDENT v1 . append ( a [ i ] ) ; NEW_LINE DEDENT elif ( mpp [ a [ i ] ] == 2 ) : NEW_LINE INDENT v2 . append ( a [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not ▁ possible " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT v1 . sort ( ) ; NEW_LINE print ( " Strictly ▁ increasing ▁ array ▁ is : " ) ; NEW_LINE for it in v1 : NEW_LINE INDENT print ( it , end = " ▁ " ) ; NEW_LINE DEDENT v2 . sort ( reverse = True ) ; NEW_LINE print ( " Strictly decreasing array is : " ) ; NEW_LINE for it in v2 : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 7 , 2 , 7 , 3 , 3 , 1 , 4 ] ; NEW_LINE n = len ( a ) ; NEW_LINE PrintBothArrays ( a , n ) ; NEW_LINE DEDENT
Iterative selection sort for linked list | ; Traverse the List ; Traverse the unsorted sublist ; Swap Data
def selectionSort ( head ) : NEW_LINE INDENT temp = head NEW_LINE while ( temp ) : NEW_LINE INDENT minn = temp NEW_LINE r = temp . next NEW_LINE while ( r ) : NEW_LINE INDENT if ( minn . data > r . data ) : NEW_LINE INDENT minn = r NEW_LINE DEDENT r = r . next NEW_LINE DEDENT x = temp . data NEW_LINE temp . data = minn . data NEW_LINE minn . data = x NEW_LINE temp = temp . next NEW_LINE DEDENT DEDENT
Sort ugly numbers in an array at their relative positions | Function that returns true if n is an ugly number ; While divisible by 2 , keep dividing ; While divisible by 3 , keep dividing ; While divisible by 5 , keep dividing ; n must be 1 if it was ugly ; Function to sort ugly numbers in their relative positions ; To store the ugly numbers from the array ; If current element is an ugly number ; Add it to the ArrayList and set arr [ i ] to - 1 ; Sort the ugly numbers ; Position of an ugly number ; Driver code
def isUgly ( n ) : NEW_LINE INDENT while n % 2 == 0 : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT while n % 3 == 0 : NEW_LINE INDENT n = n // 3 NEW_LINE DEDENT while n % 5 == 0 : NEW_LINE INDENT n = n // 5 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def sortUglyNumbers ( arr , n ) : NEW_LINE INDENT list = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if isUgly ( arr [ i ] ) : NEW_LINE INDENT list . append ( arr [ i ] ) NEW_LINE arr [ i ] = - 1 NEW_LINE DEDENT DEDENT list . sort ( ) NEW_LINE j = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] == - 1 : NEW_LINE INDENT print ( list [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 7 , 12 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE sortUglyNumbers ( arr , n ) NEW_LINE DEDENT
Sort elements of the array that occurs in between multiples of K | Utility function to print the contents of an array ; Function to sort elements in between multiples of k ; To store the index of previous multiple of k ; If it is not the first multiple of k ; Sort the elements in between the previous and the current multiple of k ; Update previous to be current ; Print the updated array ; Driver code
def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def sortArr ( arr , n , k ) : NEW_LINE INDENT prev = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % k == 0 ) : NEW_LINE INDENT if ( prev != - 1 ) : NEW_LINE INDENT temp = arr [ prev + 1 : i ] ; NEW_LINE temp . sort ( ) ; NEW_LINE arr = arr [ : prev + 1 ] + temp + arr [ i : ] ; NEW_LINE DEDENT prev = i ; NEW_LINE DEDENT DEDENT printArr ( arr , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 1 , 13 , 3 , 7 , 8 , 21 , 13 , 12 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE sortArr ( arr , n , k ) ; NEW_LINE DEDENT
Find A and B from list of divisors | Function to print A and B all of whose divisors are present in the given array ; Sort the array ; A is the largest element from the array ; Iterate from the second largest element ; If current element is not a divisor of A then it must be B ; If current element occurs more than once ; Print A and B ; Driver code
def printNumbers ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE A , B = arr [ n - 1 ] , - 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if A % arr [ i ] != 0 : NEW_LINE INDENT B = arr [ i ] NEW_LINE break NEW_LINE DEDENT if i - 1 >= 0 and arr [ i ] == arr [ i - 1 ] : NEW_LINE INDENT B = arr [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT print ( " A ▁ = " , A , " , ▁ B ▁ = " , B ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 8 , 16 , 1 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE printNumbers ( arr , n ) NEW_LINE DEDENT
Find the modified array after performing k operations of given type | Utility function to print the contents of an array ; Function to remove the minimum value of the array from every element of the array ; Get the minimum value from the array ; Remove the minimum value from every element of the array ; Function to remove every element of the array from the maximum value of the array ; Get the maximum value from the array ; Remove every element of the array from the maximum value of the array ; Function to print the modified array after k operations ; If k is odd then remove the minimum element of the array from every element of the array ; Else remove every element of the array from the maximum value from the array ; Print the modified array ; Driver code
def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT def removeMin ( arr , n ) : NEW_LINE INDENT minVal = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT minVal = min ( minVal , arr [ i ] ) ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] - minVal ; NEW_LINE DEDENT DEDENT def removeFromMax ( arr , n ) : NEW_LINE INDENT maxVal = arr [ 0 ] ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT maxVal = max ( maxVal , arr [ i ] ) ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = maxVal - arr [ i ] ; NEW_LINE DEDENT DEDENT def modifyArray ( arr , n , k ) : NEW_LINE INDENT if ( k % 2 == 0 ) : NEW_LINE INDENT removeMin ( arr , n ) ; NEW_LINE DEDENT else : NEW_LINE INDENT removeFromMax ( arr , n ) ; NEW_LINE DEDENT printArray ( arr , n ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 8 , 12 , 16 ] ; NEW_LINE n = len ( arr ) NEW_LINE k = 2 ; NEW_LINE modifyArray ( arr , n , k ) ; NEW_LINE DEDENT
Maximum product from array such that frequency sum of all repeating elements in product is less than or equal to 2 * k | Function to return the maximum product value ; To store the product ; Sort the array ; Efficiently finding product including every element once ; Storing values in hash map ; Including the greater repeating values so that product can be maximized ; Driver code
def maxProd ( arr , n , k ) : NEW_LINE INDENT product = 1 ; NEW_LINE s = dict . fromkeys ( arr , 0 ) ; NEW_LINE arr . sort ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ arr [ i ] ] == 0 ) : NEW_LINE INDENT product = product * arr [ i ] ; NEW_LINE DEDENT s [ arr [ i ] ] = s [ arr [ i ] ] + 1 ; NEW_LINE DEDENT j = n - 1 ; NEW_LINE while ( j >= 0 and k > 0 ) : NEW_LINE INDENT if ( ( k > ( s [ arr [ j ] ] - 1 ) ) and ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) : NEW_LINE INDENT product *= pow ( arr [ j ] , s [ arr [ j ] ] - 1 ) ; NEW_LINE k = k - s [ arr [ j ] ] + 1 ; NEW_LINE s [ arr [ j ] ] = 0 ; NEW_LINE DEDENT if ( k <= ( s [ arr [ j ] ] - 1 ) and ( ( s [ arr [ j ] ] - 1 ) > 0 ) ) : NEW_LINE INDENT product *= pow ( arr [ j ] , k ) ; NEW_LINE break ; NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT return product ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 6 , 7 , 8 , 2 , 5 , 6 , 8 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 2 ; NEW_LINE print ( maxProd ( arr , n , k ) ) ; NEW_LINE DEDENT
Merge K sorted arrays of different sizes | ( Divide and Conquer Approach ) | Function to merge two arrays ; array to store the result after merging l and r ; variables to store the current pointers for l and r ; loop to merge l and r using two pointer ; Function to merge all the arrays ; 2D - array to store the results of a step temporarily ; Loop to make pairs of arrays and merge them ; To clear the data of previous steps ; Returning the required output array ; Driver Code ; Input arrays ; Merged sorted array
def mergeTwoArrays ( l , r ) : NEW_LINE INDENT ret = [ ] NEW_LINE l_in , r_in = 0 , 0 NEW_LINE while l_in + r_in < len ( l ) + len ( r ) : NEW_LINE INDENT if ( l_in != len ( l ) and ( r_in == len ( r ) or l [ l_in ] < r [ r_in ] ) ) : NEW_LINE INDENT ret . append ( l [ l_in ] ) NEW_LINE l_in += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ret . append ( r [ r_in ] ) NEW_LINE r_in += 1 NEW_LINE DEDENT DEDENT return ret NEW_LINE DEDENT def mergeArrays ( arr ) : NEW_LINE INDENT arr_s = [ ] NEW_LINE while len ( arr ) != 1 : NEW_LINE INDENT arr_s [ : ] = [ ] NEW_LINE for i in range ( 0 , len ( arr ) , 2 ) : NEW_LINE INDENT if i == len ( arr ) - 1 : NEW_LINE INDENT arr_s . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT arr_s . append ( mergeTwoArrays ( arr [ i ] , arr [ i + 1 ] ) ) NEW_LINE DEDENT DEDENT arr = arr_s [ : ] NEW_LINE DEDENT return arr [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 3 , 13 ] , [ 8 , 10 , 11 ] , [ 9 , 15 ] ] NEW_LINE output = mergeArrays ( arr ) NEW_LINE for i in range ( 0 , len ( output ) ) : NEW_LINE INDENT print ( output [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Minimize the sum of the squares of the sum of elements of each group the array is divided into | Function to return the minimized sum ; Sort the array to pair the elements ; Variable to hold the answer ; Pair smallest with largest , second smallest with second largest , and so on ; Driver code
def findAnswer ( n , arr ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE sum = 0 NEW_LINE for i in range ( int ( n / 2 ) ) : NEW_LINE INDENT sum += ( ( arr [ i ] + arr [ n - i - 1 ] ) * ( arr [ i ] + arr [ n - i - 1 ] ) ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 53 , 28 , 143 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findAnswer ( n , arr ) ) NEW_LINE DEDENT
Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ) | Python3 program to merge K sorted arrays ; Function to perform merge operation ; to store the starting point of left and right array ; to store the size of left and right array ; array to temporarily store left and right array ; storing data in left array ; storing data in right array ; to store the current index of temporary left and right array ; to store the current index for output array ; two pointer merge for two sorted arrays ; Code to drive merge - sort and create recursion tree ; base step to initialize the output array before performing merge operation ; to sort left half ; to sort right half ; merge the left and right half ; Driver code ; input 2D - array ; Number of arrays ; Output array ; Print merged array
n = 4 ; NEW_LINE def merge ( l , r , output ) : NEW_LINE INDENT l_in = l * n ; NEW_LINE r_in = ( ( l + r ) // 2 + 1 ) * n ; NEW_LINE l_c = ( ( l + r ) // 2 - l + 1 ) * n ; NEW_LINE r_c = ( r - ( l + r ) // 2 ) * n ; NEW_LINE l_arr = [ 0 ] * l_c ; r_arr = [ 0 ] * r_c ; NEW_LINE for i in range ( l_c ) : NEW_LINE INDENT l_arr [ i ] = output [ l_in + i ] ; NEW_LINE DEDENT for i in range ( r_c ) : NEW_LINE INDENT r_arr [ i ] = output [ r_in + i ] ; NEW_LINE DEDENT l_curr = 0 ; r_curr = 0 ; NEW_LINE in1 = l_in ; NEW_LINE while ( l_curr + r_curr < l_c + r_c ) : NEW_LINE INDENT if ( r_curr == r_c or ( l_curr != l_c and l_arr [ l_curr ] < r_arr [ r_curr ] ) ) : NEW_LINE INDENT output [ in1 ] = l_arr [ l_curr ] ; NEW_LINE l_curr += 1 ; in1 += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT output [ in1 ] = r_arr [ r_curr ] ; NEW_LINE r_curr += 1 ; in1 += 1 ; NEW_LINE DEDENT DEDENT DEDENT def divide ( l , r , output , arr ) : NEW_LINE INDENT if ( l == r ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT output [ l * n + i ] = arr [ l ] [ i ] ; NEW_LINE DEDENT return ; NEW_LINE DEDENT divide ( l , ( l + r ) // 2 , output , arr ) ; NEW_LINE divide ( ( l + r ) // 2 + 1 , r , output , arr ) ; NEW_LINE merge ( l , r , output ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 5 , 7 , 15 , 18 ] , [ 1 , 8 , 9 , 17 ] , [ 1 , 4 , 7 , 7 ] ] ; NEW_LINE k = len ( arr ) ; NEW_LINE output = [ 0 ] * ( n * k ) ; NEW_LINE divide ( 0 , k - 1 , output , arr ) ; NEW_LINE for i in range ( n * k ) : NEW_LINE INDENT print ( output [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT
Make palindromic string non | Function to print the non - palindromic string if it exists , otherwise prints - 1 ; If all characters are not same , set flag to 1 ; Update frequency of the current character ; If all characters are same ; Print characters in sorted manner ; Driver Code
def findNonPalinString ( s ) : NEW_LINE INDENT freq = [ 0 ] * ( 26 ) NEW_LINE flag = 0 NEW_LINE for i in range ( 0 , len ( s ) ) : NEW_LINE INDENT if s [ i ] != s [ 0 ] : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT if not flag : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , 26 ) : NEW_LINE INDENT for j in range ( 0 , freq [ i ] ) : NEW_LINE INDENT print ( chr ( ord ( ' a ' ) + i ) , end = " " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abba " NEW_LINE findNonPalinString ( s ) NEW_LINE DEDENT
Minimum operations of given type to make all elements of a matrix equal | Function to return the minimum number of operations required ; Create another array to store the elements of matrix ; If not possible ; Sort the array to get median ; To count the minimum operations ; If there are even elements , then there are two medians . We consider the best of two as answer . ; Return minimum operations required ; Driver code
def minOperations ( n , m , k , matrix ) : NEW_LINE INDENT arr = [ 0 ] * ( n * m ) NEW_LINE mod = matrix [ 0 ] [ 0 ] % k NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT arr [ i * m + j ] = matrix [ i ] [ j ] NEW_LINE if matrix [ i ] [ j ] % k != mod : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT DEDENT arr . sort ( ) NEW_LINE median = arr [ ( n * m ) // 2 ] NEW_LINE minOperations = 0 NEW_LINE for i in range ( 0 , n * m ) : NEW_LINE INDENT minOperations += abs ( arr [ i ] - median ) // k NEW_LINE DEDENT if ( n * m ) % 2 == 0 : NEW_LINE INDENT median2 = arr [ ( ( n * m ) // 2 ) - 1 ] NEW_LINE minOperations2 = 0 NEW_LINE for i in range ( 0 , n * m ) : NEW_LINE INDENT minOperations2 += abs ( arr [ i ] - median2 ) // k NEW_LINE DEDENT minOperations = min ( minOperations , minOperations2 ) NEW_LINE DEDENT return minOperations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT matrix = [ [ 2 , 4 , 6 ] , [ 8 , 10 , 12 ] , [ 14 , 16 , 18 ] , [ 20 , 22 , 24 ] ] NEW_LINE n = len ( matrix ) NEW_LINE m = len ( matrix [ 0 ] ) NEW_LINE k = 2 NEW_LINE print ( minOperations ( n , m , k , matrix ) ) NEW_LINE DEDENT
Count distinct elements in an array | Python3 program to count distinct elements in a given array ; Pick all elements one by one ; If not printed earlier , then print it ; Driver Code
def countDistinct ( arr , n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT j = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i == j + 1 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 12 , 10 , 9 , 45 , 2 , 10 , 10 , 45 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDistinct ( arr , n ) ) NEW_LINE
Count distinct elements in an array | Python3 program to count all distinct elements in a given array ; First sort the array so that all occurrences become consecutive ; Traverse the sorted array ; Move the index ahead while there are duplicates ; Driver Code
def countDistinct ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE res = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT while ( i < n - 1 and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT res += 1 ; NEW_LINE i += 1 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT arr = [ 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countDistinct ( arr , n ) ) ; NEW_LINE
Choose n elements such that their mean is maximum | Utility function to print the contents of an array ; Function to print the array with maximum mean ; Sort the original array ; Construct new array ; Print the resultant array ; Driver code
def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def printMaxMean ( arr , n ) : NEW_LINE INDENT newArr = [ 0 ] * n NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT newArr [ i ] = arr [ i + n ] NEW_LINE DEDENT printArray ( newArr , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 8 , 3 , 1 , 3 , 7 , 0 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE printMaxMean ( arr , n // 2 ) NEW_LINE DEDENT
Average of remaining elements after removing K largest and K smallest elements from array | Function to find average ; base case if 2 * k >= n means all element get removed ; first sort all elements ; sum of req number ; find average ; Driver code
def average ( arr , n , k ) : NEW_LINE INDENT total = 0 NEW_LINE if ( 2 * k >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr . sort ( ) NEW_LINE start , end = k , n - k - 1 NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT total += arr [ i ] NEW_LINE DEDENT return ( total / ( n - 2 * k ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE print ( average ( arr , n , k ) ) NEW_LINE DEDENT
Minimum sum after subtracting multiples of k from the elements of the array | function to calculate minimum sum after transformation ; no element can be reduced further ; if all the elements of the array are identical ; check if a [ i ] can be reduced to a [ 0 ] ; one of the elements cannot be reduced to be equal to the other elements ; if k = 1 then all elements can be reduced to 1 ; Driver code
def min_sum ( n , k , a ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE if ( a [ 0 ] < 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT if ( a [ 0 ] == a [ n - 1 ] ) : NEW_LINE INDENT return ( n * a [ 0 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT f = 0 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT p = a [ i ] - a [ 0 ] NEW_LINE if ( p % k == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( f ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( k == 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT else : NEW_LINE INDENT return ( n * ( a [ 0 ] % k ) ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 ] NEW_LINE K = 1 NEW_LINE N = len ( arr ) NEW_LINE print ( min_sum ( N , K , arr ) ) NEW_LINE DEDENT
In | Merges two subarrays of arr . First subarray is arr [ l . . m ] Second subarray is arr [ m + 1. . r ] Inplace Implementation ; If the direct merge is already sorted ; Two pointers to maintain start of both arrays to merge ; If element 1 is in right place ; Shift all the elements between element 1 element 2 , right by 1. ; Update all the pointers ; * l is for left index and r is right index of the sub - array of arr to be sorted ; Same as ( l + r ) / 2 , but avoids overflow for large l and r ; Sort first and second halves ; Function to pran array ; Driver program to test above functions
def merge ( arr , start , mid , end ) : NEW_LINE INDENT start2 = mid + 1 NEW_LINE if ( arr [ mid ] <= arr [ start2 ] ) : NEW_LINE INDENT return NEW_LINE DEDENT while ( start <= mid and start2 <= end ) : NEW_LINE INDENT if ( arr [ start ] <= arr [ start2 ] ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT value = arr [ start2 ] NEW_LINE index = start2 NEW_LINE while ( index != start ) : NEW_LINE INDENT arr [ index ] = arr [ index - 1 ] NEW_LINE index -= 1 NEW_LINE DEDENT arr [ start ] = value NEW_LINE start += 1 NEW_LINE mid += 1 NEW_LINE start2 += 1 NEW_LINE DEDENT DEDENT DEDENT def mergeSort ( arr , l , r ) : NEW_LINE INDENT if ( l < r ) : NEW_LINE INDENT m = l + ( r - l ) // 2 NEW_LINE mergeSort ( arr , l , m ) NEW_LINE mergeSort ( arr , m + 1 , r ) NEW_LINE merge ( arr , l , m , r ) NEW_LINE DEDENT DEDENT def printArray ( A , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 11 , 13 , 5 , 6 , 7 ] NEW_LINE arr_size = len ( arr ) NEW_LINE mergeSort ( arr , 0 , arr_size - 1 ) NEW_LINE printArray ( arr , arr_size ) NEW_LINE DEDENT
Minimum Increment / decrement to make array elements equal | Function to return minimum operations need to be make each element of array equal ; Initialize cost to 0 ; Sort the array ; Middle element ; Find Cost ; If n , is even . Take minimum of the Cost obtained by considering both middle elements ; FInd cost again ; Take minimum of two cost ; Return total cost ; Driver code
def minCost ( A , n ) : NEW_LINE INDENT cost = 0 NEW_LINE A . sort ( ) ; NEW_LINE K = A [ int ( n / 2 ) ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cost = cost + abs ( A [ i ] - K ) NEW_LINE DEDENT if n % 2 == 0 : NEW_LINE INDENT tempCost = 0 NEW_LINE K = A [ int ( n / 2 ) - 1 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tempCost = tempCost + abs ( A [ i ] - K ) NEW_LINE DEDENT cost = min ( cost , tempCost ) NEW_LINE DEDENT return cost NEW_LINE DEDENT A = [ 1 , 6 , 7 , 10 ] NEW_LINE n = len ( A ) NEW_LINE print ( minCost ( A , n ) ) NEW_LINE
Print array elements in alternatively increasing and decreasing order | Function to print array elements in alternative increasing and decreasing order ; First sort the array in increasing order ; start with 2 elements in increasing order ; till all the elements are not printed ; printing the elements in increasing order ; else : printing the elements in decreasing order ; increasing the number of elements to printed in next iteration ; Driver Code
def printArray ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE flag = 0 NEW_LINE k = 2 NEW_LINE while ( l <= r ) : NEW_LINE INDENT if ( flag == 0 ) : NEW_LINE INDENT i = l NEW_LINE while i < l + k and i <= r : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT flag = 1 NEW_LINE l = i NEW_LINE i = r NEW_LINE while i > r - k and i >= l : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE i -= 1 NEW_LINE DEDENT flag = 0 NEW_LINE r = i NEW_LINE DEDENT k += 1 NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE printArray ( arr , n ) NEW_LINE DEDENT
Count triplets in a sorted doubly linked list whose product is equal to a given value x | Python3 implementation to count triplets in a sorted doubly linked list whose product is equal to a given value 'x ; Structure of node of doubly linked list ; Function to count pairs whose product equal to given 'value ; The loop terminates when either of two pointers become None , or they cross each other ( second . next == first ) , or they become same ( first == second ) ; Pair found ; Increment count ; Move first in forward direction ; Move second in backward direction ; If product is greater than ' value ' move second in backward direction ; Else move first in forward direction ; Required count of pairs ; Function to count triplets in a sorted doubly linked list whose product is equal to a given value 'x ; If list is empty ; Get pointer to the last node of the doubly linked list ; Traversing the doubly linked list ; For each current node ; Count pairs with product ( x / current . data ) in the range first to last and add it to the ' count ' of triplets ; Required count of triplets ; A utility function to insert a new node at the beginning of doubly linked list ; Allocate node ; Put in the data ; Driver code ; Start with an empty doubly linked list ; Insert values in sorted order
' NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE self . prev = None NEW_LINE DEDENT DEDENT ' NEW_LINE def countPairs ( first , second , value ) : NEW_LINE INDENT count = 0 NEW_LINE while ( first != None and second != None and first != second and second . next != first ) : NEW_LINE INDENT if ( ( first . data * second . data ) == value ) : NEW_LINE INDENT count += 1 NEW_LINE first = first . next NEW_LINE second = second . prev NEW_LINE DEDENT elif ( ( first . data * second . data ) > value ) : NEW_LINE INDENT second = second . prev NEW_LINE DEDENT else : NEW_LINE INDENT first = first . next NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT ' NEW_LINE def countTriplets ( head , x ) : NEW_LINE INDENT if ( head == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT count = 0 NEW_LINE last = head NEW_LINE while ( last . next != None ) : NEW_LINE INDENT last = last . next NEW_LINE DEDENT current = head NEW_LINE while current != None : NEW_LINE INDENT first = current . next NEW_LINE count += countPairs ( first , last , x // current . data ) NEW_LINE current = current . next NEW_LINE DEDENT return count NEW_LINE DEDENT def insert ( head , data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE temp . data = data NEW_LINE temp . next = temp . prev = None NEW_LINE if ( ( head ) == None ) : NEW_LINE INDENT ( head ) = temp NEW_LINE DEDENT else : NEW_LINE INDENT temp . next = head NEW_LINE ( head ) . prev = temp NEW_LINE ( head ) = temp NEW_LINE DEDENT return head NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = insert ( head , 9 ) NEW_LINE head = insert ( head , 8 ) NEW_LINE head = insert ( head , 6 ) NEW_LINE head = insert ( head , 5 ) NEW_LINE head = insert ( head , 4 ) NEW_LINE head = insert ( head , 2 ) NEW_LINE head = insert ( head , 1 ) NEW_LINE x = 8 NEW_LINE print ( " Count ▁ = ▁ " + str ( countTriplets ( head , x ) ) ) NEW_LINE DEDENT
Check if the characters of a given string are in alphabetical order | Function that checks whether the string is in alphabetical order or not ; if element at index ' i ' is less than the element at index ' i - 1' then the string is not sorted ; Driver code ; check whether the string is in alphabetical order or not
def isAlphabaticOrder ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] < s [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " aabbbcc " NEW_LINE if ( isAlphabaticOrder ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Product of non | Function to find the product of all non - repeated elements in an array ; sort all elements of array ; Driver code
def findProduct ( arr , n ) : NEW_LINE INDENT sorted ( arr ) NEW_LINE prod = 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] != arr [ i ] ) : NEW_LINE INDENT prod = prod * arr [ i ] NEW_LINE DEDENT DEDENT return prod ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 , 1 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findProduct ( arr , n ) ) NEW_LINE DEDENT
Check if it is possible to rearrange rectangles in a non | Python3 implementation of above approach ; Function to check if it possible to form rectangles with heights as non - ascending ; set maximum ; replace the maximum with previous maximum ; replace the minimum with previous minimum ; print NO if the above two conditions fail at least once ; initialize the number of rectangles ; initialize n rectangles with length and breadth
import sys ; NEW_LINE def rotateRec ( n , L , B ) : NEW_LINE INDENT m = sys . maxsize ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( max ( L [ i ] , B [ i ] ) <= m ) : NEW_LINE INDENT m = max ( L [ i ] , B [ i ] ) ; NEW_LINE DEDENT elif ( min ( L [ i ] , B [ i ] ) <= m ) : NEW_LINE INDENT m = min ( L [ i ] , B [ i ] ) ; NEW_LINE DEDENT else : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT DEDENT return 1 ; NEW_LINE DEDENT n = 3 ; NEW_LINE L = [ 5 , 5 , 6 ] ; NEW_LINE B = [ 6 , 7 , 8 ] ; NEW_LINE if ( rotateRec ( n , L , B ) == 1 ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) ; NEW_LINE DEDENT
Find a point such that sum of the Manhattan distances is minimized | Function to print the required points which minimizes the sum of Manhattan distances ; Sorting points in all dimension ; Output the required k points ; Driver code ; function call to print required points
def minDistance ( n , k , point ) : NEW_LINE INDENT for i in range ( k ) : NEW_LINE INDENT point [ i ] . sort ( ) NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT print ( point [ i ] [ ( ( n + 1 ) // 2 ) - 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT n = 4 NEW_LINE k = 4 NEW_LINE point = [ [ 1 , 5 , 2 , 4 ] , [ 6 , 2 , 0 , 6 ] , [ 9 , 5 , 1 , 3 ] , [ 6 , 7 , 5 , 9 ] ] NEW_LINE minDistance ( n , k , point ) NEW_LINE
Sort first k values in ascending order and remaining n | Function to sort the array ; Store the k elements in an array ; Store the remaining n - k elements in an array ; sorting the array from 0 to k - 1 places ; sorting the array from k to n places ; storing the values in the final array arr ; printing the array ; Driver code
def printOrder ( arr , n , k ) : NEW_LINE INDENT len1 = k NEW_LINE len2 = n - k NEW_LINE arr1 = [ 0 ] * k NEW_LINE arr2 = [ 0 ] * ( n - k ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT arr1 [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( k , n ) : NEW_LINE INDENT arr2 [ i - k ] = arr [ i ] NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i < k ) : NEW_LINE INDENT arr [ i ] = arr1 [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = arr2 [ len2 - 1 ] NEW_LINE len2 -= 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , - 1 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE printOrder ( arr , n , k ) NEW_LINE DEDENT
Find the largest number that can be formed with the given digits | Function to generate largest possible number with given digits ; Declare a hash array of size 10 and initialize all the elements to zero ; store the number of occurrences of the digits in the given array into the hash table ; Traverse the hash in descending order to print the required number ; Print the number of times a digits occurs ; Driver code
def findMaxNum ( arr , n ) : NEW_LINE INDENT hash = [ 0 ] * 10 NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 9 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( hash [ i ] ) : NEW_LINE INDENT print ( i , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE findMaxNum ( arr , n ) NEW_LINE DEDENT
Sort a nearly sorted array using STL | Given an array of size n , where every element is k away from its target position , sorts the array in O ( n Log n ) time . ; Sort the array using inbuilt function ; An utility function to print array elements ; Driver code
def sortK ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT k = 3 NEW_LINE arr = [ 2 , 6 , 3 , 12 , 56 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE sortK ( arr , n , k ) NEW_LINE print ( " Following ▁ is ▁ sorted ▁ array " ) NEW_LINE printArray ( arr , n ) NEW_LINE
Equally divide into two sets such that one set has maximum distinct elements | Python 3 program to equally divide n elements into two sets such that second set has maximum distinct elements . ; Driver code
def distribution ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return min ( count , n / 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 1 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( int ( distribution ( arr , n ) ) ) NEW_LINE DEDENT
Print all the pairs that contains the positive and negative values of an element | Function to print pairs of positive and negative values present in the array ; Store all the positive elements in the unordered_set ; Start traversing the array ; Check if the positive value of current element exists in the set or not ; Print that pair ; Driver code
def printPairs ( arr , n ) : NEW_LINE INDENT pairs = set ( ) NEW_LINE pair_exists = False NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] > 0 : NEW_LINE INDENT pairs . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] < 0 : NEW_LINE INDENT if ( - arr [ i ] ) in pairs : NEW_LINE INDENT print ( " { } , ▁ { } " . format ( arr [ i ] , - arr [ i ] ) ) NEW_LINE pair_exists = True NEW_LINE DEDENT DEDENT DEDENT if pair_exists == False : NEW_LINE INDENT print ( " No ▁ such ▁ pair ▁ exists " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 8 , 9 , - 4 , 1 , - 1 , - 8 , - 9 ] NEW_LINE n = len ( arr ) NEW_LINE printPairs ( arr , n ) NEW_LINE DEDENT
Sort 3 numbers | Python3 program to sort an array of size 3
a = [ 10 , 12 , 5 ] NEW_LINE a . sort ( ) NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT print ( a [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT
Print triplets with sum less than k | A Simple python 3 program to count triplets with sum smaller than a given value ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver Code
def printTriplets ( arr , n , sum ) : NEW_LINE INDENT for i in range ( 0 , n - 2 , 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 , 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n , 1 ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] + arr [ k ] < sum ) : NEW_LINE INDENT print ( arr [ i ] , " , " , arr [ j ] , " , " , arr [ k ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 1 , 3 , 4 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE sum = 12 NEW_LINE printTriplets ( arr , n , sum ) NEW_LINE DEDENT
Count number of triplets in an array having sum in the range [ a , b ] | Function to count triplets ; Initialize result ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; Driver code
def countTriplets ( arr , n , a , b ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( ( arr [ i ] + arr [ j ] + arr [ k ] >= a ) and ( arr [ i ] + arr [ j ] + arr [ k ] <= b ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE a = 8 ; b = 16 NEW_LINE print ( countTriplets ( arr , n , a , b ) ) NEW_LINE DEDENT
Count number of triplets in an array having sum in the range [ a , b ] | Function to find count of triplets having sum less than or equal to val . ; sort the input array . ; Initialize result ; to store sum ; Fix the first element ; Initialize other two elements as corner elements of subarray arr [ j + 1. . k ] ; Use Meet in the Middle concept . ; If sum of current triplet is greater , then to reduce it decrease k . ; If sum is less than or equal to given value , then add possible triplets ( k - j ) to result . ; Function to return count of triplets having sum in range [ a , b ] . ; to store count of triplets . ; Find count of triplets having sum less than or equal to b and subtract count of triplets having sum less than or equal to a - 1. ; Driver code
def countTripletsLessThan ( arr , n , val ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE j = 0 ; k = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT j = i + 1 NEW_LINE k = n - 1 NEW_LINE while j != k : NEW_LINE INDENT sum = arr [ i ] + arr [ j ] + arr [ k ] NEW_LINE if sum > val : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( k - j ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT def countTriplets ( arr , n , a , b ) : NEW_LINE INDENT res = 0 NEW_LINE res = ( countTripletsLessThan ( arr , n , b ) - countTripletsLessThan ( arr , n , a - 1 ) ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 7 , 5 , 3 , 8 , 4 , 1 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE a = 8 ; b = 16 NEW_LINE print ( countTriplets ( arr , n , a , b ) ) NEW_LINE DEDENT
Sum of Areas of Rectangles possible for an array | Function to find area of rectangles ; sorting the array in descending order ; store the final sum of all the rectangles area possible ; temporary variable to store the length of rectangle ; Selecting the length of rectangle so that difference between any two number is 1 only . Here length is selected so flag is set ; flag is set means we have got length of rectangle ; length is set to a [ i + 1 ] so that if a [ i + 1 ] is less than a [ i ] by 1 then also we have the correct chice for length ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Selecting the width of rectangle so that difference between any two number is 1 only . Here width is selected so now flag is again unset for next rectangle ; area is calculated for rectangle ; flag is set false for another rectangle which we can get from elements in array ; incrementing the counter one time more as we have considered a [ i + 1 ] element also so . ; Driver code
def MaxTotalRectangleArea ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) NEW_LINE sum = 0 NEW_LINE flag = False NEW_LINE len = 0 NEW_LINE i = 0 NEW_LINE while ( i < n - 1 ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT if ( ( a [ i ] == a [ i + 1 ] or a [ i ] - a [ i + 1 ] == 1 ) and flag == False ) : NEW_LINE INDENT flag = True NEW_LINE len = a [ i + 1 ] NEW_LINE i = i + 1 NEW_LINE DEDENT elif ( ( a [ i ] == a [ i + 1 ] or a [ i ] - a [ i + 1 ] == 1 ) and flag == True ) : NEW_LINE INDENT sum = sum + a [ i + 1 ] * len NEW_LINE flag = False NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT a = [ 10 , 10 , 10 , 10 , 11 , 10 , 11 , 10 , 9 , 9 , 8 , 8 ] NEW_LINE n = len ( a ) NEW_LINE print ( MaxTotalRectangleArea ( a , n ) ) NEW_LINE
Insertion sort to sort even and odd positioned elements in different orders | Function to calculate the given problem . ; checking for odd positioned . ; Inserting even positioned elements in ascending order . ; sorting the even positioned . ; Inserting odd positioned elements in descending order . ; A utility function to print an array of size n ; Driver program
def evenOddInsertionSort ( arr , n ) : NEW_LINE INDENT for i in range ( 2 , n ) : NEW_LINE INDENT j = i - 2 NEW_LINE temp = arr [ i ] NEW_LINE if ( ( i + 1 ) & 1 == 1 ) : NEW_LINE INDENT while ( temp >= arr [ j ] and j >= 0 ) : NEW_LINE INDENT arr [ j + 2 ] = arr [ j ] NEW_LINE j -= 2 NEW_LINE DEDENT arr [ j + 2 ] = temp NEW_LINE DEDENT else : NEW_LINE INDENT while ( temp <= arr [ j ] and j >= 0 ) : NEW_LINE INDENT arr [ j + 2 ] = arr [ j ] NEW_LINE j -= 2 NEW_LINE DEDENT arr [ j + 2 ] = temp NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 12 , 11 , 13 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE evenOddInsertionSort ( arr , n ) NEW_LINE printArray ( arr , n ) NEW_LINE
Stable sort for descending order | Bubble sort implementation to sort elements in descending order . ; Sorts a [ ] in descending order using bubble sort . ; Driver code
def print1 ( a , n ) : NEW_LINE INDENT for i in range ( 0 , n + 1 ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT def sort ( a , n ) : NEW_LINE INDENT for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT for j in range ( n , n - i , - 1 ) : NEW_LINE INDENT if ( a [ j ] > a [ j - 1 ] ) : NEW_LINE INDENT a [ j ] , a [ j - 1 ] = a [ j - 1 ] , a [ j ] NEW_LINE DEDENT DEDENT DEDENT print1 ( a , n ) NEW_LINE DEDENT n = 7 NEW_LINE a = [ 2 , 4 , 3 , 2 , 4 , 5 , 3 ] NEW_LINE sort ( a , n - 1 ) NEW_LINE
Subtraction in the Array | Function to perform the given operation on arr [ ] ; Skip elements which are 0 ; Pick smallest non - zero element ; If all the elements of arr [ ] are 0 ; Driver code
def operations ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE i = 0 ; sum = 0 ; NEW_LINE while ( k > 0 ) : NEW_LINE INDENT while ( i < n and arr [ i ] - sum == 0 ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT if ( i < n and arr [ i ] - sum > 0 ) : NEW_LINE INDENT print ( arr [ i ] - sum , end = " ▁ " ) ; NEW_LINE sum = arr [ i ] ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) ; NEW_LINE DEDENT k -= 1 ; NEW_LINE DEDENT DEDENT k = 5 ; NEW_LINE arr = [ 3 , 6 , 4 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE operations ( arr , n , k ) ; NEW_LINE
Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Python C ++ program to sort an array of 0 s 1 s and 2 s . ; Variables to maintain the count of 0 ' s , ▁ ▁ 1' s and 2 's in the array ; Putting the 0 's in the array in starting. ; Putting the 1 ' s ▁ in ▁ the ▁ array ▁ after ▁ the ▁ 0' s . ; Putting the 2 ' s ▁ in ▁ the ▁ array ▁ after ▁ the ▁ 1' s ; Prints the array ; Driver code
import math NEW_LINE def sort012 ( arr , n ) : NEW_LINE INDENT count0 = 0 NEW_LINE count1 = 0 NEW_LINE count2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT count0 = count0 + 1 NEW_LINE DEDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT count1 = count1 + 1 NEW_LINE DEDENT if ( arr [ i ] == 2 ) : NEW_LINE INDENT count2 = count2 + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , count0 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT for i in range ( count0 , ( count0 + count1 ) ) : NEW_LINE INDENT arr [ i ] = 1 NEW_LINE DEDENT for i in range ( ( count0 + count1 ) , n ) : NEW_LINE INDENT arr [ i ] = 2 NEW_LINE DEDENT return NEW_LINE DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE sort012 ( arr , n ) NEW_LINE printArray ( arr , n ) NEW_LINE
Alternate Lower Upper String Sort | Python3 program for unusul string sorting ; Function for alternate sorting of string ; Count occurrences of individual lower case and upper case characters ; Traverse through count arrays and one by one pick characters . Below loop takes O ( n ) time considering the MAX is constant . ; Driver code
MAX = 26 NEW_LINE def alternateSort ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lCount = [ 0 for i in range ( MAX ) ] NEW_LINE uCount = [ 0 for i in range ( MAX ) ] NEW_LINE s = list ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] . isupper ( ) ) : NEW_LINE INDENT uCount [ ord ( s [ i ] ) - ord ( ' A ' ) ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT lCount [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT DEDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE while ( k < n ) : NEW_LINE INDENT while ( i < MAX and uCount [ i ] == 0 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( i < MAX ) : NEW_LINE INDENT s [ k ] = chr ( ord ( ' A ' ) + i ) NEW_LINE k += 1 NEW_LINE uCount [ i ] -= 1 NEW_LINE DEDENT while ( j < MAX and lCount [ j ] == 0 ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT if ( j < MAX ) : NEW_LINE INDENT s [ k ] = chr ( ord ( ' a ' ) + j ) NEW_LINE k += 1 NEW_LINE lCount [ j ] -= 1 NEW_LINE DEDENT DEDENT print ( " " . join ( s ) ) NEW_LINE DEDENT str = " bAwutndekWEdkd " NEW_LINE alternateSort ( str ) NEW_LINE
Sum of Manhattan distances between all pairs of points | Return the sum of distance between all the pair of points . ; for each point , finding distance to rest of the point ; Driven Code
def distancesum ( x , y , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT sum += ( abs ( x [ i ] - x [ j ] ) + abs ( y [ i ] - y [ j ] ) ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT x = [ - 1 , 1 , 3 , 2 ] NEW_LINE y = [ 5 , 6 , 5 , 3 ] NEW_LINE n = len ( x ) NEW_LINE print ( distancesum ( x , y , n ) ) NEW_LINE
Sum of Manhattan distances between all pairs of points | Return the sum of distance of one axis . ; sorting the array . ; for each point , finding the distance . ; Driven Code
def distancesum ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE res = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT res += ( arr [ i ] * i - sum ) NEW_LINE sum += arr [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT def totaldistancesum ( x , y , n ) : NEW_LINE INDENT return distancesum ( x , n ) + distancesum ( y , n ) NEW_LINE DEDENT x = [ - 1 , 1 , 3 , 2 ] NEW_LINE y = [ 5 , 6 , 5 , 3 ] NEW_LINE n = len ( x ) NEW_LINE print ( totaldistancesum ( x , y , n ) ) NEW_LINE
Sort an array with swapping only with a special element is allowed | n is total number of elements . index is index of 999 or space . k is number of elements yet to be sorted . ; Print the sorted array when loop reaches the base case ; Else if k > 0 and space is at 0 th index swap each number with space and store index at second last index ; If space is neither start of array nor last element of array and element before it greater than / the element next to space ; First swap space and element next to space in case of { 3 , 999 , 2 } make it { 3 , 2 , 999 } ; Than swap space and greater element convert { 3 , 2 , 999 } to { 999 , 2 , 3 } ; Wrapper over sortRec . ; Find index of space ( or 999 ) ; Invalid input ; Driver Code
def sortRec ( arr , index , k , n ) : NEW_LINE INDENT if ( k == 0 ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( 999 , end = " " ) NEW_LINE DEDENT elif ( k > 0 and index == 0 ) : NEW_LINE INDENT index = n - 2 NEW_LINE for i in range ( 1 , index + 1 ) : NEW_LINE INDENT arr [ i - 1 ] = arr [ i ] NEW_LINE DEDENT arr [ index ] = 999 NEW_LINE DEDENT if ( index - 1 >= 0 and index + 1 < n and arr [ index - 1 ] > arr [ index + 1 ] ) : NEW_LINE INDENT arr [ index ] , arr [ index + 1 ] = arr [ index + 1 ] , arr [ index ] NEW_LINE arr [ index - 1 ] , arr [ index + 1 ] = arr [ index + 1 ] , arr [ index - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT if ( index - 1 < 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT arr [ index ] , arr [ index - 1 ] = arr [ index - 1 ] , arr [ index ] NEW_LINE DEDENT sortRec ( arr , index - 1 , k - 1 , n ) NEW_LINE DEDENT def sort ( arr , n ) : NEW_LINE INDENT index = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == 999 ) : NEW_LINE INDENT index = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( index == - 1 ) : NEW_LINE INDENT return NEW_LINE DEDENT sortRec ( arr , index , n , n ) NEW_LINE DEDENT arr = [ 3 , 2 , 999 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE sort ( arr , n ) NEW_LINE
Find array with k number of merge sort calls | Python program to find an array that can be sorted with k merge sort calls . ; We make two recursive calls , so reduce k by 2. ; Create an array with values in [ 1 , n ] ; calling unsort function ; Driver code
def unsort ( l , r , a , k ) : NEW_LINE INDENT if ( k < 1 or l + 1 == r ) : NEW_LINE INDENT return NEW_LINE DEDENT k -= 2 NEW_LINE mid = ( l + r ) // 2 NEW_LINE temp = a [ mid - 1 ] NEW_LINE a [ mid - 1 ] = a [ mid ] NEW_LINE a [ mid ] = temp NEW_LINE unsort ( l , mid , a , k ) NEW_LINE unsort ( mid , r , a , k ) NEW_LINE DEDENT def arrayWithKCalls ( n , k ) : NEW_LINE INDENT if ( k % 2 == 0 ) : NEW_LINE INDENT print ( " NO ▁ SOLUTION " ) NEW_LINE return NEW_LINE DEDENT a = [ 0 for i in range ( n + 2 ) ] NEW_LINE a [ 0 ] = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT a [ i ] = i + 1 NEW_LINE DEDENT k -= 1 NEW_LINE unsort ( 0 , n , a , k ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , " ▁ " , end = " " ) NEW_LINE DEDENT DEDENT n = 10 NEW_LINE k = 17 NEW_LINE arrayWithKCalls ( n , k ) NEW_LINE
Program to sort string in descending order | Python program to sort a string of characters in descending order ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we wil do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver program to test above function
MAX_CHAR = 26 ; NEW_LINE def sortString ( str ) : NEW_LINE INDENT charCount = [ 0 ] * MAX_CHAR ; NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT charCount [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 ; NEW_LINE DEDENT for i in range ( MAX_CHAR - 1 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( charCount [ i ] ) : NEW_LINE INDENT print ( chr ( 97 + i ) , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT s = " alkasingh " ; NEW_LINE sortString ( s ) ; NEW_LINE
Median after K additional integers | Find median of array after adding k elements ; sorting the array in increasing order . ; printing the median of array . Since n + K is always odd and K < n , so median of array always lies in the range of n . ; driver function
def printMedian ( arr , n , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE print ( arr [ int ( ( n + K ) / 2 ) ] ) NEW_LINE DEDENT arr = [ 5 , 3 , 2 , 8 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE printMedian ( arr , n , k ) NEW_LINE
Dual pivot Quicksort | Python3 program to implement dual pivot QuickSort ; lp means left pivot and rp means right pivot ; p is the left pivot , and q is the right pivot . ; If elements are less than the left pivot ; If elements are greater than or equal to the right pivot ; Bring pivots to their appropriate positions . ; Returning the indices of the pivots ; Driver code
def dualPivotQuickSort ( arr , low , high ) : NEW_LINE INDENT if low < high : NEW_LINE INDENT lp , rp = partition ( arr , low , high ) NEW_LINE dualPivotQuickSort ( arr , low , lp - 1 ) NEW_LINE dualPivotQuickSort ( arr , lp + 1 , rp - 1 ) NEW_LINE dualPivotQuickSort ( arr , rp + 1 , high ) NEW_LINE DEDENT DEDENT def partition ( arr , low , high ) : NEW_LINE INDENT if arr [ low ] > arr [ high ] : NEW_LINE INDENT arr [ low ] , arr [ high ] = arr [ high ] , arr [ low ] NEW_LINE DEDENT j = k = low + 1 NEW_LINE g , p , q = high - 1 , arr [ low ] , arr [ high ] NEW_LINE while k <= g : NEW_LINE INDENT if arr [ k ] < p : NEW_LINE INDENT arr [ k ] , arr [ j ] = arr [ j ] , arr [ k ] NEW_LINE j += 1 NEW_LINE DEDENT elif arr [ k ] >= q : NEW_LINE INDENT while arr [ g ] > q and k < g : NEW_LINE INDENT g -= 1 NEW_LINE DEDENT arr [ k ] , arr [ g ] = arr [ g ] , arr [ k ] NEW_LINE g -= 1 NEW_LINE if arr [ k ] < p : NEW_LINE INDENT arr [ k ] , arr [ j ] = arr [ j ] , arr [ k ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT k += 1 NEW_LINE DEDENT j -= 1 NEW_LINE g += 1 NEW_LINE arr [ low ] , arr [ j ] = arr [ j ] , arr [ low ] NEW_LINE arr [ high ] , arr [ g ] = arr [ g ] , arr [ high ] NEW_LINE return j , g NEW_LINE DEDENT arr = [ 24 , 8 , 42 , 75 , 29 , 77 , 38 , 57 ] NEW_LINE dualPivotQuickSort ( arr , 0 , 7 ) NEW_LINE print ( ' Sorted ▁ array : ▁ ' , end = ' ' ) NEW_LINE for i in arr : NEW_LINE INDENT print ( i , end = ' ▁ ' ) NEW_LINE DEDENT print ( ) NEW_LINE
A sorting algorithm that slightly improves on selection sort | Python3 program to implement min max selection sort . ; shifting the min . ; Shifting the max . The equal condition happens if we shifted the max to arr [ min_i ] in the previous swap . ; Driver code
def minMaxSelectionSort ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE max = arr [ i ] NEW_LINE min_i = i NEW_LINE max_i = i NEW_LINE for k in range ( i , j + 1 , 1 ) : NEW_LINE INDENT if ( arr [ k ] > max ) : NEW_LINE INDENT max = arr [ k ] NEW_LINE max_i = k NEW_LINE DEDENT elif ( arr [ k ] < min ) : NEW_LINE INDENT min = arr [ k ] NEW_LINE min_i = k NEW_LINE DEDENT DEDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ min_i ] NEW_LINE arr [ min_i ] = temp NEW_LINE if ( arr [ min_i ] == max ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ min_i ] NEW_LINE arr [ min_i ] = temp NEW_LINE DEDENT else : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ max_i ] NEW_LINE arr [ max_i ] = temp NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT print ( " Sorted ▁ array : " , end = " ▁ " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 23 , 78 , 45 , 8 , 32 , 56 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE minMaxSelectionSort ( arr , n ) NEW_LINE DEDENT
Sort an array according to absolute difference with a given value " using ▁ constant ▁ extra ▁ space " | Python 3 program to sort an array based on absolute difference with a given value x . ; Below lines are similar to insertion sort ; Insert arr [ i ] at correct place ; Function to print the array ; Driver Code
def arrange ( arr , n , x ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT diff = abs ( arr [ i ] - x ) NEW_LINE j = i - 1 NEW_LINE if ( abs ( arr [ j ] - x ) > diff ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE while ( abs ( arr [ j ] - x ) > diff and j >= 0 ) : NEW_LINE INDENT arr [ j + 1 ] = arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT arr [ j + 1 ] = temp NEW_LINE DEDENT DEDENT DEDENT def print_1 ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 3 , 9 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE x = 7 NEW_LINE arrange ( arr , n , x ) NEW_LINE print_1 ( arr , n ) NEW_LINE DEDENT
Check if a grid can become row | v [ ] is vector of strings . len is length of strings in every row . ; Driver code ; l = 5 Length of strings
def check ( v , l ) : NEW_LINE INDENT n = len ( v ) NEW_LINE for i in v : NEW_LINE INDENT i = ' ' . join ( sorted ( i ) ) NEW_LINE DEDENT for i in range ( l - 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( v [ i ] [ j ] > v [ i + 1 ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT v = [ " ebcda " , " ihgfj " , " klmno " , " pqrst " , " yvwxu " ] NEW_LINE if check ( v , l ) : NEW_LINE INDENT print " Yes " NEW_LINE DEDENT else : NEW_LINE INDENT print " No " NEW_LINE DEDENT
Sort first half in ascending and second half in descending order | 1 | function to print half of the array in ascending order and the other half in descending order ; sorting the array ; printing first half in ascending order ; printing second half in descending order ; Driver code
def printOrder ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT for j in range ( n - 1 , n // 2 - 1 , - 1 ) : NEW_LINE INDENT print ( arr [ j ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 6 , 2 , 1 , 3 , 8 , - 1 ] NEW_LINE n = len ( arr ) NEW_LINE printOrder ( arr , n ) NEW_LINE DEDENT
Find the Sub | Python 3 program to find subarray with sum closest to 0 ; Function to find the subarray ; Pick a starting point ; Consider current starting point as a subarray and update minimum sum and subarray indexes ; Try all subarrays starting with i ; update minimum sum and subarray indexes ; Return starting and ending indexes ; Driver Code
import sys NEW_LINE def findSubArray ( arr , n ) : NEW_LINE INDENT min_sum = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sum = arr [ i ] NEW_LINE if ( min_sum > abs ( curr_sum ) ) : NEW_LINE INDENT min_sum = abs ( curr_sum ) NEW_LINE start = i NEW_LINE end = i NEW_LINE DEDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT curr_sum = curr_sum + arr [ j ] NEW_LINE if ( min_sum > abs ( curr_sum ) ) : NEW_LINE INDENT min_sum = abs ( curr_sum ) NEW_LINE start = i NEW_LINE end = j NEW_LINE DEDENT DEDENT DEDENT p = [ start , end ] NEW_LINE return p NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 5 , 4 , - 6 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE point = findSubArray ( arr , n ) NEW_LINE print ( " Subarray ▁ starting ▁ from ▁ " , end = " " ) NEW_LINE print ( point [ 0 ] , " to " , point [ 1 ] ) NEW_LINE DEDENT
Find shortest unique prefix for every word in a given list | Set 2 ( Using Sorting ) | Python3 program to prshortest unique prefixes for every word . ; Create an array to store the results ; Sort the array of strings ; Compare the first with its only right neighbor ; Store the unique prefix of a [ 1 ] from its left neighbor ; Compute common prefix of a [ i ] unique from its right neighbor ; Compare the new prefix with previous prefix ; Store the prefix of a [ i + 1 ] unique from its left neighbour ; Compute the unique prefix for the last in sorted array ; Driver Code
def uniquePrefix ( a ) : NEW_LINE INDENT size = len ( a ) NEW_LINE res = [ 0 ] * ( size ) NEW_LINE a = sorted ( a ) NEW_LINE j = 0 NEW_LINE while ( j < min ( len ( a [ 0 ] ) - 1 , len ( a [ 1 ] ) - 1 ) ) : NEW_LINE INDENT if ( a [ 0 ] [ j ] == a [ 1 ] [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT ind = 0 NEW_LINE res [ ind ] = a [ 0 ] [ 0 : j + 1 ] NEW_LINE ind += 1 NEW_LINE temp_prefix = a [ 1 ] [ 0 : j + 1 ] NEW_LINE for i in range ( 1 , size - 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < min ( len ( a [ i ] ) - 1 , len ( a [ i + 1 ] ) - 1 ) ) : NEW_LINE INDENT if ( a [ i ] [ j ] == a [ i + 1 ] [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT new_prefix = a [ i ] [ 0 : j + 1 ] NEW_LINE if ( len ( temp_prefix ) > len ( new_prefix ) ) : NEW_LINE INDENT res [ ind ] = temp_prefix NEW_LINE ind += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res [ ind ] = new_prefix NEW_LINE ind += 1 NEW_LINE DEDENT temp_prefix = a [ i + 1 ] [ 0 : j + 1 ] NEW_LINE DEDENT j = 0 NEW_LINE sec_last = a [ size - 2 ] NEW_LINE last = a [ size - 1 ] NEW_LINE while ( j < min ( len ( sec_last ) - 1 , len ( last ) - 1 ) ) : NEW_LINE INDENT if ( sec_last [ j ] == last [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT res [ ind ] = last [ 0 : j + 1 ] NEW_LINE return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = [ " zebra " , " dog " , " duck " , " dove " ] NEW_LINE output = uniquePrefix ( input ) NEW_LINE print ( " The ▁ shortest ▁ unique ▁ prefixes ▁ " + " in ▁ sorted ▁ order ▁ are ▁ : ▁ " ) NEW_LINE for i in output : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Find the minimum and maximum amount to buy all N candies | Function to find the minimum amount to buy all candies ; Buy current candy ; And take k candies for free from the last ; Function to find the maximum amount to buy all candies ; Buy candy with maximum amount ; And get k candies for free from the starting ; Driver code ; Function call
def findMinimum ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE i = 0 NEW_LINE while ( n ) : NEW_LINE INDENT res += arr [ i ] NEW_LINE n = n - k NEW_LINE i += 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def findMaximum ( arr , n , k ) : NEW_LINE INDENT res = 0 NEW_LINE index = 0 NEW_LINE i = n - 1 NEW_LINE while ( i >= index ) : NEW_LINE INDENT res += arr [ i ] NEW_LINE index += k NEW_LINE i -= 1 NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 3 , 2 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE arr . sort ( ) NEW_LINE print ( findMinimum ( arr , n , k ) , " ▁ " , findMaximum ( arr , n , k ) ) NEW_LINE
Find maximum height pyramid from the given array of objects | Returns maximum number of pyramidcal levels n boxes of given widths . ; Sort objects in increasing order of widths ; Total width of previous level and total number of objects in previous level ; Number of object in current level . ; Width of current level . ; Picking the object . So increase current width and number of object . ; If current width and number of object are greater than previous . ; Update previous width , number of object on previous level . ; Reset width of current level , number of object on current level . ; Increment number of level . ; Driver Code
def maxLevel ( boxes , n ) : NEW_LINE INDENT boxes . sort ( ) NEW_LINE prev_width = boxes [ 0 ] NEW_LINE prev_count = 1 NEW_LINE curr_count = 0 NEW_LINE curr_width = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_width += boxes [ i ] NEW_LINE curr_count += 1 NEW_LINE if ( curr_width > prev_width and curr_count > prev_count ) : NEW_LINE INDENT prev_width = curr_width NEW_LINE prev_count = curr_count NEW_LINE curr_count = 0 NEW_LINE curr_width = 0 NEW_LINE ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT boxes = [ 10 , 20 , 30 , 50 , 60 , 70 ] NEW_LINE n = len ( boxes ) NEW_LINE print ( maxLevel ( boxes , n ) ) NEW_LINE DEDENT
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed | This funt merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; Copy the remaining elements of left subarray ( if there are any ) to temp ; Copy the remaining elements of right subarray ( if there are any ) to temp ; Copy back the merged elements to original array ; An auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; Merge the two parts ; This function sorts the input array and returns the number of inversions in the array ; method returns minimum number of swaps to reach permuted array 'arr ; loop over all elements to check Invalid permutation condition ; if an element is at distance more than 2 from its actual position then it is not possible to reach permuted array just by swapping with 2 positions left elements so returning - 1 ; If permuted array is not Invalid , then number of Inversion in array will be our final answer ; Driver code to test above methods ; change below example
def merge ( arr , temp , left , mid , right ) : NEW_LINE INDENT inv_count = 0 NEW_LINE DEDENT i = left NEW_LINE j = mid NEW_LINE k = left NEW_LINE INDENT while ( i <= mid - 1 ) and ( j <= right ) : NEW_LINE INDENT if arr [ i ] <= arr [ j ] : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE k , i = k + 1 , i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k , j = k + 1 , j + 1 NEW_LINE inv_count = inv_count + ( mid - i ) NEW_LINE DEDENT DEDENT while i <= mid - 1 : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE k , i = k + 1 , i + 1 NEW_LINE DEDENT while j <= right : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k , j = k + 1 , j + 1 NEW_LINE DEDENT for i in range ( left , right + 1 ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE DEDENT return inv_count NEW_LINE DEDENT def _mergeSort ( arr , temp , left , right ) : NEW_LINE INDENT inv_count = 0 NEW_LINE if right > left : NEW_LINE INDENT mid = ( right + left ) // 2 NEW_LINE inv_count = _mergeSort ( arr , temp , left , mid ) NEW_LINE inv_count += _mergeSort ( arr , temp , mid + 1 , right ) NEW_LINE inv_count += merge ( arr , temp , left , mid + 1 , right ) NEW_LINE DEDENT return inv_count NEW_LINE DEDENT def mergeSort ( arr , array_size ) : NEW_LINE INDENT temp = [ None ] * array_size NEW_LINE return _mergeSort ( arr , temp , 0 , array_size - 1 ) NEW_LINE DEDENT ' NEW_LINE def minSwapToReachArr ( arr , N ) : NEW_LINE INDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] - 1 ) - i > 2 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT numOfInversion = mergeSort ( arr , N ) NEW_LINE return numOfInversion NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE res = minSwapToReachArr ( arr , N ) NEW_LINE if res == - 1 : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( res ) NEW_LINE DEDENT DEDENT
Sort all even numbers in ascending order and then sort all odd numbers in descending order | To do two way sort . First sort even numbers in ascending order , then odd numbers in descending order . ; Make all odd numbers negative ; Check for odd ; Sort all numbers ; Retaining original array ; Driver code
def twoWaySort ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE DEDENT DEDENT arr . sort ( ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] & 1 ) : NEW_LINE INDENT arr [ i ] *= - 1 NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 3 , 2 , 7 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE twoWaySort ( arr , n ) ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
Possible to form a triangle from array values | Method prints possible triangle when array values are taken as sides ; If number of elements are less than 3 , then no triangle is possible ; first sort the array ; loop for all 3 consecutive triplets ; If triplet satisfies triangle condition , break ; Driver Code
def isPossibleTriangle ( arr , N ) : NEW_LINE INDENT if N < 3 : NEW_LINE INDENT return False NEW_LINE DEDENT arr . sort ( ) NEW_LINE for i in range ( N - 2 ) : NEW_LINE INDENT if arr [ i ] + arr [ i + 1 ] > arr [ i + 2 ] : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 4 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print ( " Yes " if isPossibleTriangle ( arr , N ) else " No " ) NEW_LINE
K | Python program to find the K - th smallest element after removing some integers from natural number . ; Return the K - th smallest element . ; Making an array , and mark all number as unmarked . ; Marking the number present in the given array . ; If j is unmarked , reduce k by 1. ; If k is 0 return j . ; Driven Program
MAX = 1000000 NEW_LINE def ksmallest ( arr , n , k ) : NEW_LINE INDENT b = [ 0 ] * MAX ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT b [ arr [ i ] ] = 1 ; NEW_LINE DEDENT for j in range ( 1 , MAX ) : NEW_LINE INDENT if ( b [ j ] != 1 ) : NEW_LINE INDENT k -= 1 ; NEW_LINE DEDENT if ( k is not 1 ) : NEW_LINE INDENT return j ; NEW_LINE DEDENT DEDENT DEDENT k = 1 ; NEW_LINE arr = [ 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( ksmallest ( arr , n , k ) ) ; NEW_LINE
Sort an array when two halves are sorted | Python program to Merge two sorted halves of array Into Single Sorted Array ; Sort the given array using sort STL ; Driver Code ; Print sorted Array
def mergeTwoHalf ( A , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 3 , 8 , - 1 , 7 , 10 ] NEW_LINE n = len ( A ) NEW_LINE mergeTwoHalf ( A , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT
Choose k array elements such that difference of maximum and minimum is minimized | Return minimum difference of maximum and minimum of k elements of arr [ 0. . n - 1 ] . ; Sorting the array . ; Find minimum value among all K size subarray . ; Driver code
def minDiff ( arr , n , k ) : NEW_LINE INDENT result = + 2147483647 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT result = int ( min ( result , arr [ i + k - 1 ] - arr [ i ] ) ) NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 10 , 100 , 300 , 200 , 1000 , 20 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( minDiff ( arr , n , k ) ) NEW_LINE
Sort even | Python3 program to separately sort even - placed and odd placed numbers and place them together in sorted array . ; create evenArr [ ] and oddArr [ ] ; Put elements in oddArr [ ] and evenArr [ ] as per their position ; sort evenArr [ ] in ascending order sort oddArr [ ] in descending order ; Driver Code
def bitonicGenerator ( arr , n ) : NEW_LINE INDENT evenArr = [ ] NEW_LINE oddArr = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( i % 2 ) == 0 ) : NEW_LINE INDENT evenArr . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT oddArr . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT evenArr = sorted ( evenArr ) NEW_LINE oddArr = sorted ( oddArr ) NEW_LINE oddArr = oddArr [ : : - 1 ] NEW_LINE i = 0 NEW_LINE for j in range ( len ( evenArr ) ) : NEW_LINE INDENT arr [ i ] = evenArr [ j ] NEW_LINE i += 1 NEW_LINE DEDENT for j in range ( len ( oddArr ) ) : NEW_LINE INDENT arr [ i ] = oddArr [ j ] NEW_LINE i += 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE bitonicGenerator ( arr , n ) NEW_LINE for i in arr : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT
Number of swaps to sort when only adjacent swapping allowed | This function merges two sorted arrays and returns inversion count in the arrays . ; i is index for left subarray ; j is index for right subarray ; k is index for resultant merged subarray ; this is tricky -- see above explanation / diagram for merge ( ) ; Copy the remaining elements of left subarray ( if there are any ) to temp ; Copy the remaining elements of right subarray ( if there are any ) to temp ; Copy back the merged elements to original array ; An auxiliary recursive function that sorts the input array and returns the number of inversions in the array . ; Divide the array into two parts and call _mergeSortAndCountInv ( ) for each of the parts ; Inversion count will be sum of inversions in left - part , right - part and number of inversions in merging ; Merge the two parts ; This function sorts the input array and returns the number of inversions in the array ; Driver progra to test above functions
def merge ( arr , temp , left , mid , right ) : NEW_LINE INDENT inv_count = 0 NEW_LINE DEDENT i = left NEW_LINE j = mid NEW_LINE k = left NEW_LINE INDENT while ( ( i <= mid - 1 ) and ( j <= right ) ) : NEW_LINE INDENT if ( arr [ i ] <= arr [ j ] ) : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE inv_count = inv_count + ( mid - i ) NEW_LINE DEDENT DEDENT while ( i <= mid - 1 ) : NEW_LINE INDENT temp [ k ] = arr [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT while ( j <= right ) : NEW_LINE INDENT temp [ k ] = arr [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT for i in range ( left , right + 1 , 1 ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE DEDENT return inv_count NEW_LINE DEDENT def _mergeSort ( arr , temp , left , right ) : NEW_LINE INDENT inv_count = 0 NEW_LINE if ( right > left ) : NEW_LINE INDENT mid = int ( ( right + left ) / 2 ) NEW_LINE inv_count = _mergeSort ( arr , temp , left , mid ) NEW_LINE inv_count += _mergeSort ( arr , temp , mid + 1 , right ) NEW_LINE inv_count += merge ( arr , temp , left , mid + 1 , right ) NEW_LINE DEDENT return inv_count NEW_LINE DEDENT def countSwaps ( arr , n ) : NEW_LINE INDENT temp = [ 0 for i in range ( n ) ] NEW_LINE return _mergeSort ( arr , temp , 0 , n - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 20 , 6 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Number ▁ of ▁ swaps ▁ is " , countSwaps ( arr , n ) ) NEW_LINE DEDENT
Check whether a given number is even or odd | Returns true if n is even , else odd ; Driver code
def isEven ( n ) : NEW_LINE INDENT return ( n % 2 == 0 ) NEW_LINE DEDENT n = 101 NEW_LINE print ( " Even " if isEven ( n ) else " Odd " ) NEW_LINE
Find Surpasser Count of each element in array | Function to find surpasser count of each element in array ; stores surpasser count for element arr [ i ] ; Function to print an array ; Driver program to test above functions
def findSurpasser ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] > arr [ i ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = " ▁ " ) NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , 7 , 5 , 3 , 0 , 8 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given ▁ array ▁ is " ) NEW_LINE printArray ( arr , n ) NEW_LINE print ( " Surpasser Count of array is " ) ; NEW_LINE findSurpasser ( arr , n ) NEW_LINE
Minimum sum of two numbers formed from digits of an array | Function to find and return minimum sum of two numbers formed from digits of the array . ; sort the array ; let two numbers be a and b ; Fill a and b with every alternate digit of input array ; return the sum ; Driver code
def solve ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE a = 0 ; b = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT a = a * 10 + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT b = b * 10 + arr [ i ] NEW_LINE DEDENT DEDENT return a + b NEW_LINE DEDENT arr = [ 6 , 8 , 4 , 5 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Sum ▁ is ▁ " , solve ( arr , n ) ) NEW_LINE
Maximum product of a triplet ( subsequence of size 3 ) in array | Python3 program to find a maximum product of a triplet in array of integers ; Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; will contain max product ; Driver Program
import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT max_product = - ( sys . maxsize - 1 ) NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT max_product = max ( max_product , arr [ i ] * arr [ j ] * arr [ k ] ) NEW_LINE DEDENT DEDENT DEDENT return max_product NEW_LINE DEDENT arr = [ 10 , 3 , 5 , 6 , 20 ] NEW_LINE n = len ( arr ) NEW_LINE max = maxProduct ( arr , n ) NEW_LINE if max == - 1 : NEW_LINE INDENT print ( " No ▁ Tripplet ▁ Exits " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum ▁ product ▁ is " , max ) NEW_LINE DEDENT
Maximum product of a triplet ( subsequence of size 3 ) in array | A Python3 program to find a maximum product of a triplet in array of integers ; Function to find a maximum product of a triplet in array of integers of size n ; If size is less than 3 , no triplet exists ; Construct four auxiliary vectors of size n and initialize them by - 1 ; Will contain max product ; To store maximum element on left of array ; To store minimum element on left of array ; leftMax [ i ] will contain max element on left of arr [ i ] excluding arr [ i ] . leftMin [ i ] will contain min element on left of arr [ i ] excluding arr [ i ] . ; Reset max_sum to store maximum element on right of array ; Reset min_sum to store minimum element on right of array ; rightMax [ i ] will contain max element on right of arr [ i ] excluding arr [ i ] . rightMin [ i ] will contain min element on right of arr [ i ] excluding arr [ i ] . ; For all array indexes i except first and last , compute maximum of arr [ i ] * x * y where x can be leftMax [ i ] or leftMin [ i ] and y can be rightMax [ i ] or rightMin [ i ] . ; Driver code
import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT leftMin = [ - 1 for i in range ( n ) ] NEW_LINE rightMin = [ - 1 for i in range ( n ) ] NEW_LINE leftMax = [ - 1 for i in range ( n ) ] NEW_LINE rightMax = [ - 1 for i in range ( n ) ] NEW_LINE max_product = - sys . maxsize - 1 NEW_LINE max_sum = arr [ 0 ] NEW_LINE min_sum = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT leftMax [ i ] = max_sum NEW_LINE if ( arr [ i ] > max_sum ) : NEW_LINE INDENT max_sum = arr [ i ] NEW_LINE DEDENT leftMin [ i ] = min_sum NEW_LINE if ( arr [ i ] < min_sum ) : NEW_LINE INDENT min_sum = arr [ i ] NEW_LINE DEDENT DEDENT max_sum = arr [ n - 1 ] NEW_LINE min_sum = arr [ n - 1 ] NEW_LINE for j in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT rightMax [ j ] = max_sum NEW_LINE if ( arr [ j ] > max_sum ) : NEW_LINE INDENT max_sum = arr [ j ] NEW_LINE DEDENT rightMin [ j ] = min_sum NEW_LINE if ( arr [ j ] < min_sum ) : NEW_LINE INDENT min_sum = arr [ j ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT max1 = max ( arr [ i ] * leftMax [ i ] * rightMax [ i ] , arr [ i ] * leftMin [ i ] * rightMin [ i ] ) NEW_LINE max2 = max ( arr [ i ] * leftMax [ i ] * rightMin [ i ] , arr [ i ] * leftMin [ i ] * rightMax [ i ] ) NEW_LINE max_product = max ( max_product , max ( max1 , max2 ) ) NEW_LINE DEDENT return max_product NEW_LINE DEDENT arr = [ 1 , 4 , 3 , - 6 , - 7 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE Max = maxProduct ( arr , n ) NEW_LINE if ( Max == - 1 ) : NEW_LINE INDENT print ( " No ▁ Triplet ▁ Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum ▁ product ▁ is " , Max ) NEW_LINE DEDENT
Maximum product of a triplet ( subsequence of size 3 ) in array | Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Sort the array in ascending order ; Return the maximum of product of last three elements and product of first two elements and last element ; Driver Code
def maxProduct ( arr , n ) : NEW_LINE INDENT if n < 3 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT arr . sort ( ) NEW_LINE return max ( arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] , arr [ n - 1 ] * arr [ n - 2 ] * arr [ n - 3 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 10 , - 3 , 5 , 6 , - 20 ] NEW_LINE n = len ( arr ) NEW_LINE _max = maxProduct ( arr , n ) NEW_LINE if _max == - 1 : NEW_LINE INDENT print ( " No ▁ Triplet ▁ Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum ▁ product ▁ is " , _max ) NEW_LINE DEDENT DEDENT
Maximum product of a triplet ( subsequence of size 3 ) in array | A O ( n ) Python3 program to find maximum product pair in an array . ; Function to find a maximum product of a triplet in array of integers of size n ; If size is less than 3 , no triplet exists ; Initialize Maximum , second maximum and third maximum element ; Initialize Minimum and second minimum element ; Update Maximum , second maximum and third maximum element ; Update second maximum and third maximum element ; Update third maximum element ; Update Minimum and second minimum element ; Update second minimum element ; Driver Code
import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT maxA = - sys . maxsize - 1 NEW_LINE maxB = - sys . maxsize - 1 NEW_LINE maxC = - sys . maxsize - 1 NEW_LINE minA = sys . maxsize NEW_LINE minB = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > maxA ) : NEW_LINE INDENT maxC = maxB NEW_LINE maxB = maxA NEW_LINE maxA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxB ) : NEW_LINE INDENT maxC = maxB NEW_LINE maxB = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > maxC ) : NEW_LINE INDENT maxC = arr [ i ] NEW_LINE DEDENT if ( arr [ i ] < minA ) : NEW_LINE INDENT minB = minA NEW_LINE minA = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < minB ) : NEW_LINE INDENT minB = arr [ i ] NEW_LINE DEDENT DEDENT return max ( minA * minB * maxA , maxA * maxB * maxC ) NEW_LINE DEDENT arr = [ 1 , - 4 , 3 , - 6 , 7 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE Max = maxProduct ( arr , n ) NEW_LINE if ( Max == - 1 ) : NEW_LINE INDENT print ( " No ▁ Triplet ▁ Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum ▁ product ▁ is " , Max ) NEW_LINE DEDENT
Minimum operations to convert Binary Matrix A to B by flipping submatrix of size K | Function to count the operations required to convert matrix A to B ; Store the sizes of matrix ; Stores count of flips required ; Traverse the iven matrix ; Check if the matrix values are not equal ; Increment the count of moves ; Check if the current square sized exists or not ; Flip all the bits in this square sized submatrix ; Count of operations required ; Driver Code
def minMoves ( a , b , K ) : NEW_LINE INDENT n = len ( a ) NEW_LINE m = len ( a [ 0 ] ) NEW_LINE cntOperations = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT if ( a [ i ] [ j ] != b [ i ] [ j ] ) : NEW_LINE INDENT cntOperations += 1 NEW_LINE if ( i + K - 1 >= n or j + K - 1 >= m ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for p in range ( 0 , K ) : NEW_LINE INDENT for q in range ( 0 , K ) : NEW_LINE INDENT if ( a [ i + p ] [ j + q ] == '0' ) : NEW_LINE INDENT a [ i + p ] [ j + q ] = '1' NEW_LINE DEDENT else : NEW_LINE INDENT a [ i + p ] [ j + q ] = '0' NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT return cntOperations NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ '1' , '0' , '0' ] , [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] ] NEW_LINE B = [ [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] , [ '0' , '0' , '0' ] ] NEW_LINE K = 3 NEW_LINE print ( minMoves ( A , B , K ) ) NEW_LINE DEDENT
Lexicographically largest permutation by sequentially inserting Array elements at ends | Function to find the lexicographically largest permutation by sequentially inserting the array elements ; Stores the current state of the new array ; Stores ythe current maximum element of array arr [ ] ; Iterate the array elements ; If the current element is smaller than the current maximum , then insert ; If the current element is at least the current maximum ; Update the value of the current maximum ; Print resultant permutation ; Driver Code
from typing import Deque NEW_LINE def largestPermutation ( arr , N ) : NEW_LINE INDENT p = Deque ( ) NEW_LINE mx = arr [ 0 ] NEW_LINE p . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] < mx ) : NEW_LINE INDENT p . append ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT p . appendleft ( arr [ i ] ) NEW_LINE mx = arr [ i ] NEW_LINE DEDENT DEDENT for i in p : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 1 , 2 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE largestPermutation ( arr , N ) NEW_LINE DEDENT
Largest value of K that a set of all possible subset | Function to find maximum count of consecutive integers from 0 in set S of all possible subset - sum ; Stores the maximum possible integer ; Sort the given array in non - decrasing order ; Iterate the given array ; If arr [ i ] <= X + 1 , then update X otherwise break the loop ; Return Answer ; Driver Code
def maxConsecutiveCnt ( arr ) : NEW_LINE INDENT X = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] <= ( X + 1 ) ) : NEW_LINE INDENT X = X + arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return X + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 4 ] NEW_LINE print ( maxConsecutiveCnt ( arr ) ) NEW_LINE DEDENT
Maximum length of subarray with same sum at corresponding indices from two Arrays | Function to find maximum length of subarray of array A and B having equal sum ; Stores the maximum size of valid subarray ; Stores the prefix sum of the difference of the given arrays ; Traverse the given array ; Add the difference of the corresponding array element ; If current difference is not present ; If current difference is present , update the value of maxSize ; Return the maximum length ; Driver Code
def maxLength ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE maxSize = 0 NEW_LINE pre = { } NEW_LINE diff = 0 NEW_LINE pre [ 0 ] = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT diff += ( A [ i ] - B [ i ] ) NEW_LINE if ( not ( diff in pre ) ) : NEW_LINE INDENT pre = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxSize = max ( maxSize , i - pre + 1 ) NEW_LINE DEDENT DEDENT return maxSize NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 , 4 ] NEW_LINE B = [ 4 , 3 , 2 , 1 ] NEW_LINE print ( maxLength ( A , B ) ) NEW_LINE DEDENT
Minimize product of first 2 ^ KΓ’ β‚¬β€œ 1 Natural Numbers by swapping bits for any pair any number of times | Function to find the minimum positive product after swapping bits at the similar position for any two numbers ; Stores the resultant number ; range / 2 numbers will be 1 and range / 2 numbers will be range - 1 ; Multiply with the final number ; Return the answer ; Driver Code
def minimumPossibleProduct ( K ) : NEW_LINE INDENT res = 1 NEW_LINE r = ( 1 << K ) - 1 NEW_LINE for i in range ( 0 , K ) : NEW_LINE INDENT res *= ( r - 1 ) NEW_LINE DEDENT res *= r NEW_LINE return res NEW_LINE DEDENT K = 3 NEW_LINE print ( minimumPossibleProduct ( K ) ) NEW_LINE
Maximum size of subset of given array such that a triangle can be formed by any three integers as the sides of the triangle | Function to find the maximum size of the subset of the given array such that a triangle can be formed from any three integers of the subset as sides ; Sort arr [ ] in increasing order ; Stores the maximum size of a valid subset of the given array ; Stores the starting index of the current window ; Stores the last index of the current window ; Iterate over the array arr [ ] ; Increment j till the value of arr [ i ] + arr [ i + 1 ] > arr [ j ] holds true ; Update the value of maxSize ; Return Answer ; Driver Code
def maximizeSubset ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE maxSize = 0 NEW_LINE i = 0 NEW_LINE j = i + 2 NEW_LINE while ( i < N - 2 ) : NEW_LINE INDENT while ( j < N and arr [ i ] + arr [ i + 1 ] > arr [ j ] ) : NEW_LINE INDENT j = j + 1 NEW_LINE DEDENT maxSize = max ( maxSize , j - i ) NEW_LINE i += 1 NEW_LINE j = max ( j , i + 2 ) NEW_LINE DEDENT return maxSize NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 7 , 4 , 1 , 6 , 9 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximizeSubset ( arr , N ) ) NEW_LINE DEDENT
Maximum possible value of array elements that can be made based on given capacity conditions | Function to find the maximum element after shifting operations in arr [ ] ; Stores the sum of array element ; Stores the maximum element in cap [ ] ; Iterate to find maximum element ; Return the resultant maximum value ; Driver Code
def maxShiftArrayValue ( arr , cap , N ) : NEW_LINE INDENT sumVals = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sumVals += arr [ i ] NEW_LINE DEDENT maxCapacity = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxCapacity = max ( cap [ i ] , maxCapacity ) NEW_LINE DEDENT return min ( maxCapacity , sumVals ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 ] NEW_LINE cap = [ 5 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxShiftArrayValue ( arr , cap , N ) ) NEW_LINE DEDENT
Minimize cost to connect the graph by connecting any pairs of vertices having cost at least 0 | Python 3 program for the above approach ; Function to perform the find operation to find the parent of a disjoint set ; FUnction to perform union operation of disjoint set union ; Update the minimum value such than it should be greater than 0 ; Update the minimum value such than it should be greater than 0 ; Function to minimize the cost to make the graph connected as per the given condition ; Stores the parent elements of sets ; Stores the rank of the sets ; Stores the minValue of the sets ; Update parent [ i ] to i ; Update minValue [ i ] to cost [ i - 1 ] ; Add i . first and i . second elements to the same set ; Stores the parent elements of the different components ; Insert parent of i to s ; Stores the minimum value from s ; Flag to mark if any minimum value is negative ; If minVal [ i ] is negative ; Mark flag as true ; Update the minimum value ; Stores minimum cost to add the edges ; If the given graph is connected or components minimum values not having any negative edge ; Update the minCost ; Print the value of minCost ; Print - 1 ; Driver Code
import sys NEW_LINE def Find ( parent , a ) : NEW_LINE INDENT if parent [ parent [ a ] ] != parent [ a ] : NEW_LINE INDENT parent [ a ] = Find ( parent , parent [ a ] ) NEW_LINE DEDENT return parent [ a ] NEW_LINE DEDENT def Union ( parent , rank , minVal , a , b ) : NEW_LINE INDENT a = Find ( parent , a ) NEW_LINE b = Find ( parent , b ) NEW_LINE if ( rank [ a ] == rank [ b ] ) : NEW_LINE INDENT rank [ a ] += 1 NEW_LINE DEDENT if ( rank [ a ] > rank [ b ] ) : NEW_LINE INDENT parent [ b ] = a NEW_LINE if ( minVal [ a ] >= 0 and minVal [ b ] >= 0 ) : NEW_LINE INDENT minVal [ a ] = min ( minVal [ a ] , minVal [ b ] ) NEW_LINE DEDENT elif ( minVal [ a ] >= 0 and minVal [ b ] < 0 ) : NEW_LINE INDENT minVal [ a ] = minVal [ a ] NEW_LINE DEDENT elif ( minVal [ a ] < 0 and minVal [ b ] >= 0 ) : NEW_LINE INDENT minVal [ a ] = minVal [ b ] NEW_LINE DEDENT else : NEW_LINE INDENT minVal [ a ] = max ( minVal [ a ] , minVal [ b ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT parent [ a ] = b NEW_LINE if ( minVal [ a ] >= 0 and minVal [ b ] >= 0 ) : NEW_LINE INDENT minVal [ b ] = min ( minVal [ a ] , minVal [ b ] ) NEW_LINE DEDENT elif ( minVal [ a ] >= 0 and minVal [ b ] < 0 ) : NEW_LINE INDENT minVal [ b ] = minVal [ a ] NEW_LINE DEDENT elif ( minVal [ a ] < 0 and minVal [ b ] >= 0 ) : NEW_LINE INDENT minVal [ b ] = minVal [ b ] NEW_LINE DEDENT else : NEW_LINE INDENT minVal [ b ] = max ( minVal [ a ] , minVal [ b ] ) NEW_LINE DEDENT DEDENT DEDENT def findMinCost ( G , cost , N , M ) : NEW_LINE INDENT parent = [ 0 for i in range ( N + 1 ) ] NEW_LINE rank = [ 0 for i in range ( N + 1 ) ] NEW_LINE minVal = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE minVal [ i ] = cost [ i - 1 ] NEW_LINE DEDENT for i in G : NEW_LINE INDENT Union ( parent , rank , minVal , i [ 0 ] , i [ 1 ] ) NEW_LINE DEDENT s = set ( ) NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT s . add ( Find ( parent , i ) ) NEW_LINE DEDENT min1 = [ 0 , sys . maxsize ] NEW_LINE flag = False NEW_LINE for i in s : NEW_LINE INDENT if ( minVal [ i ] < 0 ) : NEW_LINE INDENT flag = True NEW_LINE DEDENT if ( min1 [ 1 ] > minVal [ i ] ) : NEW_LINE INDENT min1 = [ i , minVal [ i ] ] NEW_LINE DEDENT DEDENT minCost = 0 NEW_LINE if ( flag == False or ( flag and len ( s ) == 1 ) ) : NEW_LINE INDENT for i in s : NEW_LINE INDENT if ( i != min1 [ 0 ] ) : NEW_LINE INDENT minCost += ( minVal [ i ] + min1 [ 1 ] ) NEW_LINE DEDENT DEDENT print ( minCost ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE G = [ [ 3 , 1 ] , [ 2 , 3 ] , [ 2 , 1 ] , [ 4 , 5 ] , [ 5 , 6 ] , [ 6 , 4 ] ] NEW_LINE cost = [ 2 , 1 , 5 , 3 , 2 , 9 ] NEW_LINE M = len ( G ) NEW_LINE findMinCost ( G , cost , N , M ) NEW_LINE DEDENT
Minimum size of Array possible with given sum and product values | Function to find the minimum size of array with sum S and product P ; Base Case ; Iterate through all values of S and check the mentioned condition ; Otherwise , print " - 1" ; Driver Code
def minimumSizeArray ( S , P ) : NEW_LINE INDENT if ( S == P ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT for i in range ( 2 , S + 1 ) : NEW_LINE INDENT d = i NEW_LINE if ( ( S / d ) >= pow ( P , 1.0 / d ) ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = 5 NEW_LINE P = 6 NEW_LINE print ( minimumSizeArray ( S , P ) ) NEW_LINE DEDENT
Smallest possible integer to be added to N | Function to find the smallest positive integer X such that X is added to every element of A except one element to give array B ; Stores the unique elements of array A ; Insert A [ i ] into the set s ; Sort array A [ ] ; Sort array B [ ] ; Assume X value as B [ 0 ] - A [ 1 ] ; Check if X value assumed is negative or 0 ; Update the X value to B [ 0 ] - A [ 0 ] ; If assumed value is wrong ; Update X value ; Driver Code
def findVal ( A , B , N ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT s . add ( A [ i ] ) NEW_LINE DEDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE X = B [ 0 ] - A [ 1 ] NEW_LINE if ( X <= 0 ) : NEW_LINE INDENT X = B [ 0 ] - A [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( N - 1 ) : NEW_LINE INDENT if ( B [ i ] - X not in s ) : NEW_LINE INDENT X = B [ 0 ] - A [ 0 ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( X ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 4 , 3 , 8 ] NEW_LINE B = [ 15 , 8 , 11 ] NEW_LINE N = len ( A ) NEW_LINE findVal ( A , B , N ) NEW_LINE DEDENT
Count of integral points that lie at a distance D from origin | python 3 program for the above approach ; Function to find the total valid integer coordinates at a distance D from origin ; Stores the count of valid points ; Iterate over possibel x coordinates ; Find the respective y coordinate with the pythagoras theorem ; Adding 4 to compensate the coordinates present on x and y axes . ; Return the answer ; Driver Code
from math import sqrt NEW_LINE def countPoints ( D ) : NEW_LINE INDENT count = 0 NEW_LINE for x in range ( 1 , int ( sqrt ( D * D ) ) , 1 ) : NEW_LINE INDENT y = int ( sqrt ( ( D * D - x * x ) ) ) NEW_LINE if ( x * x + y * y == D * D ) : NEW_LINE INDENT count += 4 NEW_LINE DEDENT DEDENT count += 4 NEW_LINE return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT D = 5 NEW_LINE print ( countPoints ( D ) ) NEW_LINE DEDENT
Sum of the shortest distance between all 0 s to 1 in given binary string | Function to find the total sum of the shortest distance between every 0 to 1 in a given binary string ; Stores the prefix distance and suffix distance from 0 to 1 ; Stores the current distance from 1 to 0 ; Marks the 1 ; If current character is 1 ; Mark haveOne to true ; Assign the cnt to 0 ; Assign prefixDistance [ i ] as 0 ; If haveOne is true ; Update the cnt ; Update prefixDistance [ i ] ; Assign prefixDistance [ i ] as INT_MAX ; Assign haveOne as false ; If current character is 1 ; Mark haveOne to true ; Assign the cnt to 0 ; Assign the suffixDistance [ i ] as 0 ; If haveOne is true ; Update the cnt ; Update suffixDistance [ i ] as cnt ; Assign suffixDistance [ i ] as INT_MAX ; Stores the total sum of distances between 0 to nearest 1 ; If current character is 0 ; Update the value of sum ; Print the value of the sum ; Driver Code
INT_MAX = 2147483647 NEW_LINE def findTotalDistance ( S , N ) : NEW_LINE INDENT prefixDistance = [ 0 for _ in range ( N ) ] NEW_LINE suffixDistance = [ 0 for _ in range ( N ) ] NEW_LINE cnt = 0 NEW_LINE haveOne = False NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT haveOne = True NEW_LINE cnt = 0 NEW_LINE prefixDistance [ i ] = 0 NEW_LINE DEDENT elif ( haveOne ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE prefixDistance [ i ] = cnt NEW_LINE DEDENT else : NEW_LINE INDENT prefixDistance [ i ] = INT_MAX NEW_LINE DEDENT DEDENT haveOne = False NEW_LINE for i in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT haveOne = True NEW_LINE cnt = 0 NEW_LINE suffixDistance [ i ] = 0 NEW_LINE DEDENT elif ( haveOne ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE suffixDistance [ i ] = cnt NEW_LINE DEDENT else : NEW_LINE INDENT suffixDistance [ i ] = INT_MAX NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT sum += min ( prefixDistance [ i ] , suffixDistance [ i ] ) NEW_LINE DEDENT DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "100100" NEW_LINE N = len ( S ) NEW_LINE findTotalDistance ( S , N ) NEW_LINE DEDENT