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 ...
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...
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 s...
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 = " ▁ " ) N...
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 no...
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 pri...
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 ; M...
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 ] ) : ...
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 = " ▁...
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 ...
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 ] ) ...
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 resu...
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 ] ;...
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...
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...
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...
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 ar...
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 [ ...
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 prefi...
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...
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 ; Drive...
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 ] ) N...
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 vector...
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 ] = ...
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 -...
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_L...
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 t...
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 ] ...
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...
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 su...
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 maximumF...
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 ,...
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 increasi...
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_LIN...
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...
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...
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 sortUglyNu...
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 mu...
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_LIN...
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...
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 [...
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 rem...
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 ...
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 re...
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 ...
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...
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 :...
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 ...
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 ...
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...
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" )...
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 t...
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 retur...
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 NE...
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 = [ ...
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 DED...
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 DED...
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 th...
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 DEDEN...
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...
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 I...
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 ;...
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 , ...
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 ord...
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_...
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 ...
' 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 ...
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...
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 = ...
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 cond...
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 ...
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 ,...
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 ; Dri...
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 . ...
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 descen...
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__ == "...
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_L...
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...
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 ; ...
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 ]...
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 ] , " , ...
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...
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 M...
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...
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 ...
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 ) ...
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...
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 ] = te...
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 ...
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...
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 ▁ ...
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...
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 ....
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 ( ...
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 ]...
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 ,...
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...
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 +...
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_L...
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 ...
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 ]...
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 ....
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 p...
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 ] NE...
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 ] ...
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 DEDEN...
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_...
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 e...
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 +...
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 nei...
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 IND...
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 ; Driv...
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 ( ...
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 . ...
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_co...
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...
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...
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 ...
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 ...
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 Pro...
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 r...
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 = l...
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 ( eve...
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 ( ) ; C...
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...
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 ) ...
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...
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_produ...
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 i...
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...
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 l...
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 , -...
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 ele...
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_LI...
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 ; Chec...
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 +...
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...
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 . a...
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 bre...
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__ == " ...
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 t...
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 IND...
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 ; Mu...
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 t...
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 NE...
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 ; Driv...
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 ) N...
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...
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 =...
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 _ _ " : N...
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 ] ...
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 ran...
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 theor...
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...
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 ...
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 =...