text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Check if two sorted arrays can be merged to form a sorted array with no adjacent pair from the same array | Function to check if it is possible to merge the two given arrays with given conditions ; Stores index of the array A [ ] ; Stores index of the array B [ ] ; Check if the previous element are from the array A [ ] or from the array B [ ] ; Check if it is possible to merge the two given sorted arrays with given conditions ; Traverse both the arrays ; If A [ i ] is less than B [ j ] and previous element are not from A [ ] ; Update prev ; Update i ; If B [ j ] is less than A [ i ] and previous element are not from B [ ] ; Update prev ; Update j ; If A [ i ] equal to B [ j ] ; If previous element are not from B [ ] ; Update prev ; Update j ; If previous element is not from A [ ] ; Update prev ; Update i ; If it is not possible to merge two sorted arrays with given conditions ; Update flag ; Driver Code
def checkIfPossibleMerge ( A , B , N ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE prev = - 1 NEW_LINE flag = 1 NEW_LINE while ( i < N and j < N ) : NEW_LINE INDENT if ( A [ i ] < B [ j ] and prev != 0 ) : NEW_LINE INDENT prev = 0 NEW_LINE i += 1 NEW_LINE DEDENT elif ( B [ j ] < A [ i ] and prev != 1 ) : NEW_LINE INDENT prev = 1 NEW_LINE j += 1 NEW_LINE DEDENT elif ( A [ i ] == B [ j ] ) : NEW_LINE INDENT if ( prev != 1 ) : NEW_LINE INDENT prev = 1 NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prev = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT return flag NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 5 , 8 ] NEW_LINE B = [ 2 , 4 , 6 ] NEW_LINE N = len ( A ) NEW_LINE if ( checkIfPossibleMerge ( A , B , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimize array sum by replacing greater and smaller elements of pairs by half and double of their values respectively atmost K times | Function to find the minimum sum of array elements by given operations ; Base case ; Return 0 ; Base case ; Perform K operations ; Stores smallest element in the array ; Stores index of the smallest array element ; Stores largest element in the array ; Stores index of the largest array element ; Traverse the array elements ; If current element exceeds largest_element ; Update the largest element ; Update index of the largest array element ; If current element is smaller than smallest_element ; Update the smallest element ; Update index of the smallest array element ; Stores the value of smallest element by given operations ; Stores the value of largest element by given operations ; If the value of a + b less than the sum of smallest and largest element of the array ; Update smallest element of the array ; Update largest element of the array ; Stores sum of elements of the array by given operations ; Traverse the array ; Update ans ; Driver Code
def minimum_possible_sum ( arr , n , k ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT smallest_element = arr [ 0 ] NEW_LINE smallest_pos = 0 NEW_LINE largest_element = arr [ 0 ] NEW_LINE largest_pos = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] >= largest_element ) : NEW_LINE INDENT largest_element = arr [ i ] NEW_LINE largest_pos = i NEW_LINE DEDENT if ( arr [ i ] < smallest_element ) : NEW_LINE INDENT smallest_element = arr [ i ] NEW_LINE smallest_pos = i NEW_LINE DEDENT DEDENT a = smallest_element * 2 NEW_LINE b = largest_element // 2 NEW_LINE if ( a + b < smallest_element + largest_element ) : NEW_LINE INDENT arr [ smallest_pos ] = a NEW_LINE arr [ largest_pos ] = b NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 50 , 1 , 100 , 100 , 1 ] NEW_LINE K = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( minimum_possible_sum ( arr , n , K ) ) NEW_LINE DEDENT
Rearrange array elements excluded by given ranges to maximize sum of subarrays starting from the first index | Function that finds the maximum sum all subarrays from the starting index after rearranging the array ; Stores elements after rearranging ; Keeps track of visited elements ; Traverse the queries ; Mark elements that are not allowed to rearranged ; Stores the indices ; Get indices and elements that are allowed to rearranged ; Store the current index and element ; Sort vector v in descending order ; Insert elements in array ; Stores the resultant sum ; Stores the prefix sums ; Traverse the given array ; Return the maximum sum ; Driver Code ; Given array ; Given size ; Queries ; Number of queries ; Function Call
def maxSum ( n , a , l , q ) : NEW_LINE INDENT v = [ ] NEW_LINE d = [ 0 ] * n NEW_LINE for i in range ( q ) : NEW_LINE INDENT for x in range ( l [ i ] [ 0 ] , l [ i ] [ 1 ] + 1 ) : NEW_LINE INDENT if ( d [ x ] == 0 ) : NEW_LINE INDENT d [ x ] = 1 NEW_LINE DEDENT DEDENT DEDENT st = set ( [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( d [ i ] == 0 ) : NEW_LINE INDENT v . append ( a [ i ] ) NEW_LINE st . add ( i ) NEW_LINE DEDENT DEDENT v . sort ( reverse = True ) NEW_LINE c = 0 NEW_LINE for it in st : NEW_LINE INDENT a [ it ] = v NEW_LINE c += 1 NEW_LINE DEDENT pref_sum = 0 NEW_LINE temp_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp_sum += a [ i ] NEW_LINE pref_sum += temp_sum NEW_LINE DEDENT return pref_sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 8 , 4 , - 2 , - 6 , 4 , 7 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE q = [ [ 0 , 0 ] , [ 4 , 5 ] ] NEW_LINE queries = len ( q ) NEW_LINE print ( maxSum ( N , arr , q , queries ) ) NEW_LINE DEDENT
Count pairs with Bitwise XOR greater than both the elements of the pair | Python3 program for the above approach ; Function to count pairs whose XOR is greater than the pair itself ; Stores the count of pairs ; Sort the array ; Traverse the array ; If current element is 0 , then ignore it ; Traverse all the bits of element A [ i ] ; If current bit is set then update the count ; Update bits [ ] at the most significant bit of A [ i ] ; Print the count ; Driver Code ; Function Call
import math NEW_LINE def countPairs ( A , N ) : NEW_LINE INDENT count = 0 NEW_LINE A . sort ( ) NEW_LINE bits = [ 0 ] * 32 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT for j in range ( 0 , 32 ) : NEW_LINE INDENT if ( ( ( 1 << j ) & A [ i ] ) == 0 ) : NEW_LINE INDENT count += bits [ j ] NEW_LINE DEDENT DEDENT bits [ ( int ) ( math . log ( A [ i ] , 2 ) ) ] += 1 NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 4 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE countPairs ( arr , N ) NEW_LINE DEDENT
Maximum occurred integers after M circular operations in given range | Function to find the maximum occurred integer after completing all circular operations ; Stores the highest visit count for any element ; Stors the number of times an element is visited ; Iterate over the array ; Iterate over the range circularly form start to end ; Count number of times an element is visited ; Increment frequency of N ; Update maxVisited ; Increment frequency of start ; Update maxVisited ; Increment the start ; Increment the count for the last visited element ; Print most visited elements ; Driver Code ; Function Call
def mostvisitedsector ( N , A ) : NEW_LINE INDENT maxVisited = 0 NEW_LINE mp = { } NEW_LINE for i in range ( 0 , len ( A ) - 1 ) : NEW_LINE INDENT start = A [ i ] % N NEW_LINE end = A [ i + 1 ] % N NEW_LINE while ( start != end ) : NEW_LINE INDENT if ( start == 0 ) : NEW_LINE INDENT if N in mp : NEW_LINE INDENT mp [ N ] = mp [ N ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ N ] = 1 NEW_LINE DEDENT if ( mp [ N ] > maxVisited ) : NEW_LINE INDENT maxVisited = mp [ N ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if start in mp : NEW_LINE INDENT mp [ start ] = mp [ start ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ start ] = 1 NEW_LINE DEDENT if ( mp [ start ] > maxVisited ) : NEW_LINE INDENT maxVisited = mp [ start ] NEW_LINE DEDENT DEDENT start = ( start + 1 ) % N NEW_LINE DEDENT DEDENT if A [ - 1 ] in mp : NEW_LINE INDENT mp [ A [ - 1 ] ] = mp [ A [ - 1 ] ] + 1 NEW_LINE DEDENT if ( mp [ A [ - 1 ] ] > maxVisited ) : NEW_LINE INDENT maxVisited = mp [ A [ - 1 ] ] NEW_LINE DEDENT for x in mp : NEW_LINE INDENT if ( mp [ x ] == maxVisited ) : NEW_LINE INDENT print ( x , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE arr = [ 1 , 2 , 1 , 2 ] NEW_LINE mostvisitedsector ( N , arr ) NEW_LINE DEDENT
Area of the largest rectangle formed by lines parallel to X and Y axis from given set of points | Function to return the area of the largest rectangle formed by lines parallel to X and Y axis from given set of points ; Initialize two arrays ; Store x and y coordinates ; Sort arrays ; Initialize max differences ; Find max adjacent differences ; Return answer ; Driver Code ; Given points ; Total points ; Function call
def maxRectangle ( sequence , size ) : NEW_LINE INDENT X_Cord = [ 0 ] * size NEW_LINE Y_Cord = [ 0 ] * size NEW_LINE for i in range ( size ) : NEW_LINE INDENT X_Cord [ i ] = sequence [ i ] [ 0 ] NEW_LINE Y_Cord [ i ] = sequence [ i ] [ 1 ] NEW_LINE DEDENT X_Cord . sort ( ) NEW_LINE Y_Cord . sort ( ) NEW_LINE X_Max = 0 NEW_LINE Y_Max = 0 NEW_LINE for i in range ( size - 1 ) : NEW_LINE INDENT X_Max = max ( X_Max , X_Cord [ i + 1 ] - X_Cord [ i ] ) NEW_LINE Y_Max = max ( Y_Max , Y_Cord [ i + 1 ] - Y_Cord [ i ] ) NEW_LINE DEDENT return X_Max * Y_Max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT point = [ [ - 2 , 0 ] , [ 2 , 0 ] , [ 4 , 0 ] , [ 4 , 2 ] ] NEW_LINE n = len ( point ) NEW_LINE print ( maxRectangle ( point , n ) ) NEW_LINE DEDENT
Rearrange two given arrays such that sum of same indexed elements lies within given range | Function to check if there exists any arrangements of the arrays such that sum of element lie in the range [ K / 2 , K ] ; Sort the array arr1 [ ] in increasing order ; Sort the array arr2 [ ] in decreasing order ; Traverse the array ; If condition is not satisfied break the loop ; Print the result ; Driver Code
def checkArrangement ( A1 , A2 , n , k ) : NEW_LINE INDENT A1 = sorted ( A1 ) NEW_LINE A2 = sorted ( A2 ) NEW_LINE A2 = A2 [ : : - 1 ] NEW_LINE flag = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( A1 [ i ] + A2 [ i ] > k ) or ( A1 [ i ] + A2 [ i ] < k // 2 ) ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 3 , 4 , 5 ] NEW_LINE arr2 = [ 2 , 0 , 1 , 1 ] NEW_LINE K = 6 NEW_LINE N = len ( arr1 ) NEW_LINE checkArrangement ( arr1 , arr2 , N , K ) NEW_LINE DEDENT
Rearrange two given arrays to maximize sum of same indexed elements | Function to find the maximum possible sum by rearranging the given array elements ; Sort the array A [ ] in ascending order ; Sort the array B [ ] in descending order ; Stores maximum possible sum by rearranging array elements ; Traverse both the arrays ; Update maxSum ; Driver Code
def MaxRearrngeSum ( A , B , N ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( reverse = True ) NEW_LINE maxSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT maxSum += abs ( A [ i ] - B [ i ] ) NEW_LINE DEDENT return maxSum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 2 , 4 , 5 ] NEW_LINE B = [ 5 , 5 , 5 , 6 , 6 ] NEW_LINE N = len ( A ) NEW_LINE print ( MaxRearrngeSum ( A , B , N ) ) NEW_LINE DEDENT
Area of the largest rectangle possible from given coordinates | Function to find the maximum possible area of a rectangle ; Initialize variables ; Sort array arr1 [ ] ; Sort array arr2 [ ] ; Traverse arr1 [ ] and arr2 [ ] ; If arr1 [ i ] is same as arr2 [ j ] ; If no starting point is found yet ; Update maximum end ; If arr [ i ] > arr2 [ j ] ; If no rectangle is found ; Return the area ; Driver Code ; Given point ; Given length ; Given points ; Given length ; Function Call
def largestArea ( arr1 , n , arr2 , m ) : NEW_LINE INDENT end = 0 NEW_LINE start = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE arr1 . sort ( reverse = False ) NEW_LINE arr2 . sort ( reverse = False ) NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( arr1 [ i ] == arr2 [ j ] ) : NEW_LINE INDENT if ( start == 0 ) : NEW_LINE INDENT start = arr1 [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT end = arr1 [ i ] NEW_LINE DEDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT elif ( arr1 [ i ] > arr2 [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT if ( end == 0 or start == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return ( end - start ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 2 , 4 ] NEW_LINE N = len ( arr1 ) NEW_LINE arr2 = [ 1 , 3 , 4 ] NEW_LINE M = len ( arr2 ) NEW_LINE print ( largestArea ( arr1 , N , arr2 , M ) ) NEW_LINE DEDENT
Count pairs from two arrays with difference exceeding K | Function to count pairs that satisfy the given conditions ; Stores index of the left pointer . ; Stores index of the right pointer ; Stores count of total pairs that satisfy the conditions ; Sort arr [ ] array ; Sort brr [ ] array ; Traverse both the array and count then pairs ; If the value of ( brr [ j ] - arr [ i ] ) exceeds K ; Update cntPairs ; Update ; Update j ; Driver Code
def count_pairs ( arr , brr , N , M , K ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE cntPairs = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE brr = sorted ( brr ) NEW_LINE while ( i < N and j < M ) : NEW_LINE INDENT if ( brr [ j ] - arr [ i ] > K ) : NEW_LINE INDENT cntPairs += ( M - j ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j += 1 NEW_LINE DEDENT DEDENT return cntPairs NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 9 , 1 , 8 ] NEW_LINE brr = [ 10 , 12 , 7 , 4 , 2 , 3 ] NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE M = len ( brr ) NEW_LINE print ( count_pairs ( arr , brr , N , M , K ) ) NEW_LINE DEDENT
Merge two sorted arrays in O ( 1 ) extra space using Heap | Function to perform min heapify on array brr [ ] ; Stores index of left child of i . ; Stores index of right child of i . ; Stores index of the smallest element in ( arr [ i ] , arr [ left ] , arr [ right ] ) ; Check if arr [ left ] less than arr [ smallest ] ; Update smallest ; Check if arr [ right ] less than arr [ smallest ] ; Update smallest ; If i is not the index of smallest element ; Swap arr [ i ] and arr [ smallest ] ; Perform heapify on smallest ; Function to merge two sorted arrays ; Traverse the array arr [ ] ; Check if current element is less than brr [ 0 ] ; Swap arr [ i ] and brr [ 0 ] ; Perform heapify on brr [ ] ; Sort array brr [ ] ; Function to print array elements ; Traverse array arr [ ] ; Driver code ; Function call to merge two array ; Print first array ; Print Second array .
def minHeapify ( brr , i , M ) : NEW_LINE INDENT left = 2 * i + 1 NEW_LINE right = 2 * i + 2 NEW_LINE smallest = i NEW_LINE if ( left < M and brr [ left ] < brr [ smallest ] ) : NEW_LINE INDENT smallest = left NEW_LINE DEDENT if ( right < M and brr [ right ] < brr [ smallest ] ) : NEW_LINE INDENT smallest = right NEW_LINE DEDENT if ( smallest != i ) : NEW_LINE INDENT brr [ i ] , brr [ smallest ] = brr [ smallest ] , brr [ i ] NEW_LINE minHeapify ( brr , smallest , M ) NEW_LINE DEDENT DEDENT def merge ( arr , brr , N , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] > brr [ 0 ] ) : NEW_LINE INDENT arr [ i ] , brr [ 0 ] = brr [ 0 ] , arr [ i ] NEW_LINE minHeapify ( brr , 0 , M ) NEW_LINE DEDENT DEDENT brr . sort ( ) NEW_LINE DEDENT def printArray ( 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 = [ 2 , 23 , 35 , 235 , 2335 ] NEW_LINE brr = [ 3 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( brr ) NEW_LINE merge ( arr , brr , N , M ) NEW_LINE printArray ( arr , N ) NEW_LINE printArray ( brr , M ) NEW_LINE DEDENT
Merge two sorted arrays in O ( 1 ) extra space using QuickSort partition | Function to perform the partition around the pivot element ; Stores index of each element of the array , arr [ ] ; Stores index of each element of the array , brr [ ] ; Traverse both the array ; If pivot is smaller than arr [ l ] ; If Pivot is greater than brr [ r ] ; If either arr [ l ] > Pivot or brr [ r ] < Pivot ; Function to merge the two sorted array ; Stores index of each element of the array arr [ ] ; Stores index of each element of the array brr [ ] ; Stores index of each element the final sorted array ; Stores the pivot element ; Traverse both the array ; If pivot element is not found or index < N ; If pivot element is not found or index < N ; Place the first N elements of the sorted array into arr [ ] and the last M elements of the sorted array into brr [ ] ; Sort both the arrays ; Print the first N elements in sorted order ; Print the last M elements in sorted order ; Driver Code
def partition ( arr , N , brr , M , Pivot ) : NEW_LINE INDENT l = N - 1 NEW_LINE r = 0 NEW_LINE while ( l >= 0 and r < M ) : NEW_LINE INDENT if ( arr [ l ] < Pivot ) : NEW_LINE INDENT l -= 1 NEW_LINE DEDENT elif ( brr [ r ] > Pivot ) : NEW_LINE INDENT r += 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ l ] , brr [ r ] = brr [ r ] , arr [ l ] NEW_LINE l -= 1 NEW_LINE r += 1 NEW_LINE DEDENT DEDENT DEDENT def Merge ( arr , N , brr , M ) : NEW_LINE INDENT l = 0 NEW_LINE r = 0 NEW_LINE index = - 1 NEW_LINE Pivot = 0 NEW_LINE while ( index < N and l < N and r < M ) : NEW_LINE INDENT if ( arr [ l ] < brr [ r ] ) : NEW_LINE INDENT Pivot = arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT Pivot = brr [ r ] NEW_LINE r += 1 NEW_LINE DEDENT index += 1 NEW_LINE DEDENT while ( index < N and l < N ) : NEW_LINE INDENT Pivot = arr [ l ] NEW_LINE l += 1 NEW_LINE index += 1 NEW_LINE DEDENT while ( index < N and r < M ) : NEW_LINE INDENT Pivot = brr [ r ] NEW_LINE r += 1 NEW_LINE index += 1 NEW_LINE DEDENT partition ( arr , N , brr , M , Pivot ) NEW_LINE arr = sorted ( arr ) NEW_LINE brr = sorted ( brr ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT print ( brr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 9 ] NEW_LINE brr = [ 2 , 4 , 7 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( brr ) NEW_LINE Merge ( arr , N , brr , M ) NEW_LINE DEDENT
Count array elements with rank not exceeding K | Function to find count of array elements with rank less than or equal to k ; Initialize rank and position ; Sort the given array ; Traverse array from right to left ; Update rank with position , if adjacent elements are unequal ; Return position - 1 , if rank greater than k ; Increase position ; Driver Code ; Given array ; Given K ; Function Call
def rankLessThanK ( arr , k , n ) : NEW_LINE INDENT rank = 1 ; NEW_LINE position = 1 ; NEW_LINE arr = sorted ( arr ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i == n - 1 or arr [ i ] != arr [ i + 1 ] ) : NEW_LINE INDENT rank = position ; NEW_LINE if ( rank > k ) : NEW_LINE INDENT return position - 1 ; NEW_LINE DEDENT DEDENT position += 1 ; NEW_LINE DEDENT return n ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 2 , 3 , 4 , 5 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 4 ; NEW_LINE print ( rankLessThanK ( arr , K , N ) ) ; NEW_LINE DEDENT
Remove Sub | Function to remove sub - directories from the given lists dir ; Store final result ; Sort the given directories ; Insert 1 st directory ; Iterating in directory ; Current directory ; Our previous valid directory ; Find length of previous directory ; If subdirectory is found ; Else store it in result valid directory ; Driver Code ; Given lists of directories dir [ ] ; Function Call
def eraseSubdirectory ( dir ) : NEW_LINE INDENT res = [ ] NEW_LINE dir . sort ( ) NEW_LINE res . append ( dir [ 0 ] ) NEW_LINE print ( " { " , dir [ 0 ] , end = " , ▁ " ) NEW_LINE for i in range ( 1 , len ( dir ) ) : NEW_LINE INDENT curr = dir [ i ] NEW_LINE prev = res [ len ( res ) - 1 ] NEW_LINE l = len ( prev ) NEW_LINE if ( len ( curr ) > l and curr [ l ] == ' / ' and prev == curr [ : l ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT res . append ( curr ) NEW_LINE print ( curr , end = " , ▁ " ) NEW_LINE DEDENT print ( " } " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT dir = [ " / a " , " / a / j " , " / c / d / e " , " / c / d " , " / b " ] NEW_LINE eraseSubdirectory ( dir ) NEW_LINE DEDENT
Maximize count of pairs ( i , j ) from two arrays having element from first array not exceeding that from second array | Function to return the maximum number of required pairs ; Max Heap to add values of arr2 [ ] ; Sort the array arr1 [ ] ; Push all arr2 [ ] into Max Heap ; Initialize the ans ; Traverse the arr1 [ ] in decreasing order ; Remove element until a required pair is found ; Return maximum number of pairs ; Driver Code ; Given arrays ; Function Call
def numberOfPairs ( arr1 , n , arr2 , m ) : NEW_LINE INDENT pq = [ ] NEW_LINE arr1 . sort ( reverse = False ) NEW_LINE for j in range ( m ) : NEW_LINE INDENT pq . append ( arr2 [ j ] ) NEW_LINE DEDENT ans = 2 NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT pq . sort ( reverse = False ) NEW_LINE if ( pq [ 0 ] >= 2 * arr1 [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE print ( pq [ 0 ] ) NEW_LINE pq . remove ( pq [ 0 ] ) NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 3 , 2 , 1 ] NEW_LINE arr2 = [ 3 , 4 , 2 , 1 ] NEW_LINE N = len ( arr1 ) NEW_LINE M = len ( arr2 ) NEW_LINE print ( numberOfPairs ( arr1 , N , arr2 , M ) ) NEW_LINE DEDENT
Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2 | Python3 program for above approach ; Function to find minimum cost ; Sort the array ; Maximum possible common ratios ; Iterate over all possible common ratios ; Calculate operations required for the current common ratio ; Calculate minimum cost ; Driver Code ; Given N ; Given arr [ ] ; Function calling
import sys NEW_LINE def minCost ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE raised = 1 / ( n - 1 ) NEW_LINE temp = pow ( arr [ n - 1 ] , raised ) NEW_LINE r = round ( temp ) + 1 NEW_LINE min_cost = sys . maxsize NEW_LINE common_ratio = 1 NEW_LINE for j in range ( 1 , r + 1 ) : NEW_LINE INDENT curr_cost = 0 NEW_LINE prod = 1 NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT curr_cost += abs ( arr [ i ] - prod ) NEW_LINE prod *= j NEW_LINE if ( curr_cost >= min_cost ) : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( i == n ) : NEW_LINE INDENT min_cost = min ( min_cost , curr_cost ) NEW_LINE common_ratio = j NEW_LINE DEDENT DEDENT print ( min_cost , common_ratio ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 6 NEW_LINE arr = [ 1 , 11 , 4 , 27 , 15 , 33 ] NEW_LINE minCost ( arr , N ) NEW_LINE DEDENT
Mth bit in Nth binary string from a sequence generated by the given operations | Python3 program for above approach ; Function to calculate N Fibonacci numbers ; Function to find the mth bit in the string Sn ; Base case ; Length of left half ; Length of the right half ; Recursive check in the left half ; Recursive check in the right half ; Driver Code
maxN = 10 NEW_LINE def calculateFib ( fib , n ) : NEW_LINE INDENT fib [ 0 ] = fib [ 1 ] = 1 NEW_LINE for x in range ( 2 , n ) : NEW_LINE INDENT fib [ x ] = ( fib [ x - 1 ] + fib [ x - 2 ] ) NEW_LINE DEDENT DEDENT def find_mth_bit ( n , m , fib ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return n NEW_LINE DEDENT len_left = fib [ n - 2 ] NEW_LINE len_right = fib [ n - 1 ] NEW_LINE if ( m <= len_left ) : NEW_LINE INDENT return find_mth_bit ( n - 2 , len_left + 1 - m , fib ) NEW_LINE DEDENT else : NEW_LINE INDENT return find_mth_bit ( n - 1 , len_right + 1 - ( m - len_left ) , fib ) NEW_LINE DEDENT DEDENT def find_mth_bitUtil ( n , m ) : NEW_LINE INDENT fib = [ 0 for i in range ( maxN ) ] NEW_LINE calculateFib ( fib , maxN ) NEW_LINE ans = find_mth_bit ( n , m , fib ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE m = 3 NEW_LINE find_mth_bitUtil ( n , m ) NEW_LINE DEDENT
Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix | Function to count the minimum number of adjacent swaps ; Stores the size of the given matrix ; Stores the count of zero at the end of each row ; Traverse the given matrix ; Count of 0 s at the end of the ith row ; Stores the count of swaps ; Traverse the cntZero array ; If count of zero in the i - th row < ( N - i - 1 ) ; Stores the index of the row where count of zero > ( N - i - 1 ) ; If no row found that satisfy the condition ; Swap the adjacent row ; Driver Code
def minAdjSwaps ( mat ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE cntZero = [ 0 ] * ( N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N - 1 , - 1 , - 1 ) : NEW_LINE INDENT if mat [ i ] [ j ] != 0 : NEW_LINE INDENT break NEW_LINE DEDENT cntZero [ i ] += 1 NEW_LINE DEDENT DEDENT cntSwaps = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( cntZero [ i ] < ( N - i - 1 ) ) : NEW_LINE INDENT First = i NEW_LINE while ( First < N and cntZero [ First ] < ( N - i - 1 ) ) : NEW_LINE INDENT First += 1 NEW_LINE DEDENT if ( First == N ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT while ( First > i ) : NEW_LINE INDENT cntZero [ First ] = cntZero [ First - 1 ] NEW_LINE cntZero [ First - 1 ] = cntZero [ First ] NEW_LINE First -= 1 NEW_LINE cntSwaps += 1 NEW_LINE DEDENT DEDENT DEDENT return cntSwaps NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 0 , 0 , 2 ] , [ 3 , 1 , 0 ] , [ 4 , 0 , 0 ] ] NEW_LINE print ( minAdjSwaps ( mat ) ) NEW_LINE DEDENT
Largest area in a grid unbounded by towers | Function to calculate the largest area unguarded by towers ; Sort the x - coordinates of the list ; Sort the y - coordinates of the list ; dx -- > maximum uncovered tiles in x coordinates ; dy -- > maximum uncovered tiles in y coordinates ; Calculate the maximum uncovered distances for both x and y coordinates ; Largest unguarded area is max ( dx ) - 1 * max ( dy ) - 1 ; Driver Code ; Length and width of the grid ; No of guard towers ; Array to store the x and y coordinates ; Function call
def maxArea ( point_x , point_y , n , length , width ) : NEW_LINE INDENT point_x . sort ( ) NEW_LINE point_y . sort ( ) NEW_LINE dx = point_x [ 0 ] NEW_LINE dy = point_y [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dx = max ( dx , point_x [ i ] - point_x [ i - 1 ] ) NEW_LINE dy = max ( dy , point_y [ i ] - point_y [ i - 1 ] ) NEW_LINE DEDENT dx = max ( dx , ( length + 1 ) - point_x [ n - 1 ] ) NEW_LINE dy = max ( dy , ( width + 1 ) - point_y [ n - 1 ] ) NEW_LINE print ( ( dx - 1 ) * ( dy - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT length = 15 NEW_LINE width = 8 NEW_LINE n = 3 NEW_LINE point_x = [ 3 , 11 , 8 ] NEW_LINE point_y = [ 8 , 2 , 6 ] NEW_LINE maxArea ( point_x , point_y , n , length , width ) NEW_LINE DEDENT
Split an Array to maximize subarrays having equal count of odd and even elements for a cost not exceeding K | Function to find the cost of splitting the arrays into subarray with cost less than K ; Store the possible splits ; Stores the cost of each split ; Stores the count of even numbers ; Stores the count of odd numbers ; Count of odd & even elements ; Check the required conditions for a valid split ; Sort the cost of splits ; Find the minimum split costs adding up to sum less than K ; Given array and K ; Function call
def make_cuts ( arr , n , K ) : NEW_LINE INDENT ans = 0 NEW_LINE poss = [ ] NEW_LINE ce = 0 NEW_LINE co = 0 NEW_LINE for x in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ x ] % 2 == 0 ) : NEW_LINE INDENT ce += 1 NEW_LINE DEDENT else : NEW_LINE INDENT co += 1 NEW_LINE DEDENT if ( ce == co and co > 0 and ce > 0 ) : NEW_LINE INDENT poss . append ( abs ( arr [ x ] - arr [ x + 1 ] ) ) NEW_LINE DEDENT DEDENT poss . sort ( ) NEW_LINE for x in poss : NEW_LINE INDENT if ( K >= x ) : NEW_LINE INDENT ans += 1 NEW_LINE K -= x NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT N = 6 NEW_LINE K = 4 NEW_LINE arr = [ 1 , 2 , 5 , 10 , 15 , 20 ] NEW_LINE print ( make_cuts ( arr , N , K ) ) NEW_LINE
Cost of rearranging the array such that no element exceeds the sum of its adjacent elements | Function to check if given elements can be arranged such that sum of its neighbours is strictly greater ; Initialize the total cost ; Storing the original index of elements in a hashmap ; Sort the given array ; Check if a given condition is satisfies or not ; First number ; Add the cost to overall cost ; Last number ; Add the cost to overall cost ; Add the cost to overall cost ; Printing the cost ; Given array ; Function call
def Arrange ( arr , n ) : NEW_LINE INDENT cost = 0 NEW_LINE index = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT index [ arr [ i ] ] = i NEW_LINE DEDENT arr . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] + arr [ - 1 ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT cost += abs ( index [ arr [ i ] ] - i ) NEW_LINE DEDENT DEDENT elif ( i == n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] + arr [ 0 ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT cost += abs ( index [ arr [ i ] ] - i ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] + arr [ i + 1 ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT cost += abs ( index [ arr [ i ] ] - i ) NEW_LINE DEDENT DEDENT DEDENT print ( cost ) NEW_LINE return NEW_LINE DEDENT arr = [ 2 , 4 , 5 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE Arrange ( arr , N ) NEW_LINE
XOR of all possible pairwise sum from two given Arrays | Function to calculate the sum of XOR of the sum of every pair ; Stores the XOR of sums of every pair ; Iterate to generate all possible pairs ; Update XOR ; Return the answer ; Driver Code
def XorSum ( A , B , N ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT ans = ans ^ ( A [ i ] + B [ j ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 4 , 6 , 0 , 0 , 3 , 3 ] NEW_LINE B = [ 0 , 5 , 6 , 5 , 0 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( XorSum ( A , B , N ) ) NEW_LINE DEDENT
Maximum non | Python3 program for the above approach ; Function to find maximum distinct character after removing K character ; Freq implemented as hash table to store frequency of each character ; Store frequency of each character ; Insert each frequency in v ; Sort the freq of character in non - decreasing order ; Traverse the vector ; Update v [ i ] and k ; If K is still not 0 ; Store the final answer ; Count this character if freq 1 ; Return count of distinct characters ; Driver Code ; Given string ; Given k ; Function Call
from collections import defaultdict NEW_LINE def maxDistinctChar ( s , n , k ) : NEW_LINE INDENT freq = defaultdict ( int ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ s [ i ] ] += 1 NEW_LINE DEDENT v = [ ] NEW_LINE for it in freq . values ( ) : NEW_LINE INDENT v . append ( it ) NEW_LINE DEDENT v . sort ( ) NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT mn = min ( v [ i ] - 1 , k ) NEW_LINE v [ i ] -= mn NEW_LINE k -= mn NEW_LINE DEDENT if ( k > 0 ) : NEW_LINE INDENT for i in range ( len ( v ) ) : NEW_LINE INDENT mn = min ( v [ i ] , k ) ; NEW_LINE v [ i ] -= mn NEW_LINE k -= mn NEW_LINE DEDENT DEDENT res = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( v [ i ] == 1 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE N = len ( S ) NEW_LINE K = 1 NEW_LINE print ( maxDistinctChar ( S , N , K ) ) NEW_LINE DEDENT
Split N as the sum of K numbers satisfying the given conditions | list to store prime numbers ; Function to generate prime numbers using SieveOfEratosthenes ; Boolean array to store primes ; If p is a prime ; Mark all its multiples as non - prime ; Print all prime numbers ; Function to generate n as the sum of k numbers where atleast K - 1 are distinct and are product of 2 primes ; Stores the product of every pair of prime number ; Sort the products ; If sum exceeds n ; Otherwise , print the k required numbers ; Driver Code
primes = [ ] NEW_LINE def SieveOfEratosthenes ( ) : NEW_LINE INDENT prime = [ True ] * 10005 NEW_LINE p = 2 NEW_LINE while p * p <= 1000 : NEW_LINE INDENT if ( prime [ p ] == True ) : NEW_LINE INDENT for i in range ( p * p , 1001 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT for p in range ( 2 , 1001 ) : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT primes . append ( p ) NEW_LINE DEDENT DEDENT DEDENT def generate ( n , k ) : NEW_LINE INDENT prod = [ ] NEW_LINE SieveOfEratosthenes ( ) NEW_LINE l = len ( primes ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( i + 1 , l ) : NEW_LINE INDENT if ( primes [ i ] * primes [ j ] > 0 ) : NEW_LINE INDENT prod . append ( primes [ i ] * primes [ j ] ) NEW_LINE DEDENT DEDENT DEDENT prod . sort ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT sum += prod [ i ] NEW_LINE DEDENT if ( sum > n ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( k - 1 ) : NEW_LINE INDENT print ( prod [ i ] , end = " , ▁ " ) NEW_LINE DEDENT print ( n - sum ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 52 NEW_LINE k = 5 NEW_LINE generate ( n , k ) NEW_LINE DEDENT
Maximum modified Array sum possible by choosing elements as per the given conditions | Function that finds the maximum sum of the array elements according to the given condition ; Sort the array ; Take the max value from the array ; Iterate from the end of the array ; Check for the number had come before or not ; Take the value which is not occured already ; Change max to new value ; Return the maximum sum ; Driver code ; Given array arr [ ] ; Function call
def findMaxValue ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = arr [ n - 1 ] NEW_LINE maxPossible = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( maxPossible > 0 ) : NEW_LINE INDENT if ( arr [ i ] >= maxPossible ) : NEW_LINE INDENT ans += ( maxPossible - 1 ) NEW_LINE maxPossible = maxPossible - 1 NEW_LINE DEDENT else : NEW_LINE INDENT maxPossible = arr [ i ] NEW_LINE ans += maxPossible NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 4 , 1 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxValue ( arr , n ) ) NEW_LINE DEDENT
Minimum cost to sort an Array such that swapping X and Y costs XY | Function returns the minimum cost to sort the given array ; Create array of pairs in which 1 st element is the array element and 2 nd element is index of first ; Initialize the total cost ; Sort the array with respect to array value ; Initialize the overall minimum which is the 1 st element ; To keep track of visited elements create a visited array & initialize all elements as not visited ; Iterate over every element of the array ; If the element is visited or in the sorted position , and check for next element ; Create a vector which stores all elements of a cycle ; It covers all the elements of a cycle ; If cycle is found then the swapping is required ; Initialize local minimum with 1 st element of the vector as it contains the smallest element in the beginning ; Stores the cost with using only local minimum value . ; Stores the cost of using both local minimum and overall minimum ; Update the result2 ; Store the minimum of the two result to total cost ; Return the minimum cost ; Given array arr [ ] ; Function call
def minCost ( arr , n ) : NEW_LINE INDENT sortedarr = [ ] NEW_LINE total_cost = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sortedarr . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT sortedarr . sort ( ) NEW_LINE overall_minimum = sortedarr [ 0 ] [ 0 ] NEW_LINE vis = [ False ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if vis [ i ] and sortedarr [ i ] [ 1 ] == i : NEW_LINE INDENT continue NEW_LINE DEDENT v = [ ] NEW_LINE j = i NEW_LINE size = 0 NEW_LINE while vis [ j ] == False : NEW_LINE INDENT vis [ j ] = True NEW_LINE v . append ( sortedarr [ j ] [ 0 ] ) NEW_LINE j = sortedarr [ j ] [ 1 ] NEW_LINE size += 1 NEW_LINE DEDENT if size != 0 : NEW_LINE INDENT local_minimum = v [ 0 ] NEW_LINE result1 = 0 NEW_LINE result2 = 0 NEW_LINE for k in range ( 1 , size ) : NEW_LINE INDENT result1 += local_minimum * v [ k ] NEW_LINE DEDENT for k in range ( size ) : NEW_LINE INDENT result2 += overall_minimum * v [ k ] NEW_LINE DEDENT result2 += ( overall_minimum * local_minimum ) NEW_LINE total_cost += min ( result1 , result2 ) NEW_LINE DEDENT DEDENT return total_cost NEW_LINE DEDENT A = [ 1 , 8 , 9 , 7 , 6 ] NEW_LINE ans = minCost ( A , len ( A ) ) NEW_LINE print ( ans ) NEW_LINE
Maximize the last Array element as per the given conditions | Function to find the maximum possible value that can be placed at the last index ; Sort the array elements in ascending order ; If the first element is is not equal to 1 ; Traverse the array to make difference between adjacent elements <= 1 ; Driver Code
def maximizeFinalElement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE if ( arr [ 0 ] != 1 ) : NEW_LINE INDENT arr [ 0 ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] > 1 ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] + 1 ; NEW_LINE DEDENT DEDENT return arr [ n - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 ; NEW_LINE arr = [ 3 , 1 , 3 , 4 ] ; NEW_LINE max = maximizeFinalElement ( arr , n ) ; NEW_LINE print ( max ) ; NEW_LINE DEDENT
Find the point on X | Function to find median of the array ; Sort the given array ; If number of elements are even ; Return the first median ; Otherwise ; Driver Code
def findLeastDist ( A , N ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE if ( N % 2 == 0 ) : NEW_LINE INDENT return A [ ( N - 1 ) // 2 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT return A [ N // 2 ] ; NEW_LINE DEDENT DEDENT A = [ 4 , 1 , 5 , 10 , 2 ] ; NEW_LINE N = len ( A ) ; NEW_LINE print ( " ( " , findLeastDist ( A , N ) , " , ▁ " , 0 , " ) " ) ; NEW_LINE
Maximum sum of any submatrix of a Matrix which is sorted row | Function that finds the maximum Sub - Matrix Sum ; Number of rows in the matrix ; Number of columns in the matrix ; dp [ ] [ ] matrix to store the results of each iteration ; Base Case - The largest element in the matrix ; To stores the final result ; Find the max sub matrix sum for the last row ; Check whether the current sub - array yields maximum sum ; Calculate the max sub matrix sum for the last column ; Check whether the current sub - array yields maximum sum ; Build the dp [ ] [ ] matrix from bottom to the top row ; Update sum at each cell in dp [ ] [ ] ; Update the maximum sum ; Return the maximum sum ; Driver Code ; Given matrix mat [ ] [ ] ; Function call
def maxSubMatSum ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE dp = [ [ 0 ] * m for _ in range ( n ) ] NEW_LINE dp [ n - 1 ] [ m - 1 ] = mat [ n - 1 ] [ m - 1 ] NEW_LINE res = dp [ n - 1 ] [ m - 1 ] NEW_LINE for i in range ( m - 2 , - 1 , - 1 ) : NEW_LINE INDENT dp [ n - 1 ] [ i ] = ( mat [ n - 1 ] [ i ] + dp [ n - 1 ] [ i + 1 ] ) NEW_LINE res = max ( res , dp [ n - 1 ] [ i ] ) NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT dp [ i ] [ m - 1 ] = ( mat [ i ] [ m - 1 ] + dp [ i + 1 ] [ m - 1 ] ) NEW_LINE res = max ( res , dp [ i ] [ m - 1 ] ) NEW_LINE DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( m - 2 , - 1 , - 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( mat [ i ] [ j ] + dp [ i ] [ j + 1 ] + dp [ i + 1 ] [ j ] - dp [ i + 1 ] [ j + 1 ] ) NEW_LINE res = max ( res , dp [ i ] [ j ] ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ - 6 , - 4 , - 1 ] , [ - 3 , 2 , 4 ] , [ 2 , 5 , 8 ] ] NEW_LINE print ( maxSubMatSum ( mat ) ) NEW_LINE DEDENT
Arrange the numbers in the Array as per given inequalities | Function to place the integers in between the inequality signs ; Sort the integers array and set the index of smallest and largest element ; Iterate over the inequalities ; Append the necessary integers per symbol ; Add the final integer ; Return the answer ; Driver Code ; Given List of Integers ; Given list of inequalities ; Function Call ; Print the output
def formAnInequality ( integers , inequalities ) : NEW_LINE INDENT integers . sort ( ) NEW_LINE lowerIndex = 0 NEW_LINE higherIndex = len ( integers ) - 1 NEW_LINE sb = " " NEW_LINE for ch in inequalities : NEW_LINE INDENT if ( ch == ' < ' ) : NEW_LINE INDENT sb += ( " ▁ " + chr ( integers [ lowerIndex ] ) + " ▁ " + ch ) NEW_LINE lowerIndex += 1 NEW_LINE DEDENT else : NEW_LINE INDENT sb += ( " ▁ " + chr ( integers [ higherIndex ] ) + " ▁ " + ch ) NEW_LINE higherIndex -= 1 NEW_LINE DEDENT DEDENT sb += ( " ▁ " + chr ( integers [ lowerIndex ] ) ) NEW_LINE return sb NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT integers = [ 2 , 5 , 1 , 0 ] NEW_LINE inequalities = [ ' < ' , ' > ' , ' < ' ] NEW_LINE output = formAnInequality ( integers , inequalities ) NEW_LINE print ( output ) NEW_LINE DEDENT
Check if two arrays can be made equal by reversing subarrays multiple times | Function to check if array B can be made equal to array A ; Sort both the arrays ; Check if both the arrays are equal or not ; Driver Code
def canMadeEqual ( A , B , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( A [ i ] != B [ i ] ) : NEW_LINE return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , 3 ] NEW_LINE B = [ 1 , 3 , 2 ] NEW_LINE n = len ( A ) NEW_LINE if ( canMadeEqual ( A , B , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
Minimize difference between maximum and minimum of Array by at most K replacements | Function to find minimum difference between the maximum and the minimum elements arr [ ] by at most K replacements ; Check if turns are more than or equal to n - 1 then simply return zero ; Sort the array ; Set difference as the maximum possible difference ; Iterate over the array to track the minimum difference in k turns ; Return the answer ; Driver code ; Given array arr [ ] ; Given K replacements ; Function Call
def maxMinDifference ( arr , n , k ) : NEW_LINE INDENT if ( k >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT arr . sort ( ) NEW_LINE ans = arr [ n - 1 ] - arr [ 0 ] NEW_LINE i = k NEW_LINE j = n - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT ans = min ( arr [ j ] - arr [ i ] , ans ) NEW_LINE i -= 1 NEW_LINE j -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 4 , 6 , 11 , 15 ] NEW_LINE N = len ( arr ) NEW_LINE K = 3 NEW_LINE print ( maxMinDifference ( arr , N , K ) ) NEW_LINE DEDENT
Check if a decreasing Array can be sorted using Triple cyclic shift | Python3 program for the above approach ; if array is 3 2 1 can ' t ▁ ▁ be ▁ sorted ▁ because ▁ 2 ▁ is ▁ in ▁ ▁ its ▁ correct ▁ position , ▁ 1 ▁ ▁ and ▁ 3 ▁ can ' t shift right because cyclic right shift takes place between 3 elements ; check if its possible to sort ; Number of swap is N / 2 always for this approach ; printing index of the cyclic right shift ; Driver code
def sortarray ( arr , N ) : NEW_LINE INDENT if ( N == 3 ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT elif ( N % 4 == 0 or N % 4 == 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE print ( N // 2 ) NEW_LINE k = 1 NEW_LINE for l in range ( N // 4 ) : NEW_LINE INDENT print ( k , k + 1 , N ) NEW_LINE print ( k + 1 , N , N - 1 ) NEW_LINE k = k + 2 NEW_LINE N = N - 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE arr = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE sortarray ( arr , N ) NEW_LINE DEDENT
Find least non | Python3 program to find the least non - overlapping number from a given set intervals ; Function to find the smallest non - overlapping number ; Create a visited array ; Find the first missing value ; Driver code
MAX = int ( 1e5 + 5 ) NEW_LINE def find_missing ( interval ) : NEW_LINE INDENT vis = [ 0 ] * ( MAX ) NEW_LINE for i in range ( len ( interval ) ) : NEW_LINE INDENT start = interval [ i ] [ 0 ] NEW_LINE end = interval [ i ] [ 1 ] NEW_LINE vis [ start ] += 1 NEW_LINE vis [ end + 1 ] -= 1 NEW_LINE DEDENT for i in range ( 1 , MAX ) : NEW_LINE INDENT vis [ i ] += vis [ i - 1 ] NEW_LINE if ( vis [ i ] == 0 ) : NEW_LINE INDENT print ( i ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT interval = [ [ 0 , 14 ] , [ 86 , 108 ] , [ 22 , 30 ] , [ 5 , 17 ] ] NEW_LINE find_missing ( interval ) NEW_LINE
Find least non | function to find the smallest non - overlapping number ; Sort the intervals based on their starting value ; Check if any missing value exist ; Finally print the missing value ; Driver code
def find_missing ( interval ) : NEW_LINE INDENT interval . sort ( ) NEW_LINE mx = 0 NEW_LINE for i in range ( len ( interval ) ) : NEW_LINE INDENT if ( interval [ i ] [ 0 ] > mx ) : NEW_LINE INDENT print ( mx ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT mx = max ( mx , interval [ i ] [ 1 ] + 1 ) NEW_LINE DEDENT DEDENT print ( mx ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT interval = [ [ 0 , 14 ] , [ 86 , 108 ] , [ 22 , 30 ] , [ 5 , 17 ] ] NEW_LINE find_missing ( interval ) ; NEW_LINE DEDENT
Maximum bitwise OR value of subsequence of length K | Function to convert bit array to decimal number ; Return the final result ; Function to find the maximum Bitwise OR value of subsequence of length K ; Initialize bit array of size 32 with all value as 0 ; Iterate for each index of bit [ ] array from 31 to 0 , and check if the ith value of bit array is 0 ; Check for maximum contributing element ; Update the bit array if max_contributing element is found ; Decrement the value of K ; Return the result ; Given array arr [ ] ; Length of subsequence ; Function call
def build_num ( bit ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , 32 ) : NEW_LINE INDENT if ( bit [ i ] ) : NEW_LINE INDENT ans += ( 1 << i ) NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT def maximumOR ( arr , n , k ) : NEW_LINE INDENT bit = [ 0 ] * 32 NEW_LINE for i in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT if ( bit [ i ] == 0 and k > 0 ) : NEW_LINE INDENT temp = build_num ( bit ) NEW_LINE temp1 = temp NEW_LINE val = - 1 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT if ( temp1 < ( temp arr [ j ] ) ) : NEW_LINE INDENT temp1 = temp | arr [ j ] NEW_LINE val = arr [ j ] NEW_LINE DEDENT DEDENT if ( val != - 1 ) : NEW_LINE INDENT k -= 1 NEW_LINE for j in range ( 0 , 32 ) : NEW_LINE INDENT if ( val & ( 1 << j ) ) : NEW_LINE INDENT bit [ j ] += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT return build_num ( bit ) NEW_LINE DEDENT arr = [ 5 , 9 , 7 , 19 ] NEW_LINE k = 3 ; NEW_LINE n = len ( arr ) NEW_LINE print ( maximumOR ( arr , n , k ) ) NEW_LINE
Lexicographically smallest string after M operations | Function to find the lexicographical smallest string after performing M operations ; Size of the given string ; Declare an array a ; For each i , a [ i ] contain number of operations to update s [ i ] to 'a ; Check if m >= ar [ i ] , then update s [ i ] to ' a ' decrement k by a [ i ] ; Form a cycle of 26 ; Return the answer ; Driver code
def smallest_string ( s , m ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE l = list ( s ) NEW_LINE a = [ 0 ] * n ; NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT distance = ord ( s [ i ] ) - ord ( ' a ' ) ; NEW_LINE if ( distance == 0 ) : NEW_LINE INDENT a [ i ] = 0 ; NEW_LINE DEDENT else : NEW_LINE INDENT a [ i ] = 26 - distance ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( m >= a [ i ] ) : NEW_LINE INDENT l [ i ] = ' a ' ; NEW_LINE m = m - a [ i ] ; NEW_LINE DEDENT DEDENT m = m % 26 ; NEW_LINE for i in range ( len ( l ) - 1 ) : NEW_LINE INDENT print ( l [ i ] , end = " " ) NEW_LINE DEDENT print ( chr ( ord ( l [ n - 1 ] ) + m ) ) NEW_LINE DEDENT str = " aazzx " ; NEW_LINE m = 6 ; NEW_LINE smallest_string ( str , m ) ; NEW_LINE
Maximize jobs that can be completed under given constraint | Function to find maxiumum number of jobs ; Min Heap ; Sort ranges by start day ; Stores the minimum and maximum day in the ranges ; Iterating from min_day to max_day ; Insert the end day of the jobs which can be completed on i - th day in a priority queue ; Pop all jobs whose end day is less than current day ; If queue is empty , no job can be completed on the i - th day ; Increment the count of jobs completed ; Pop the job with least end day ; Return the jobs on the last day ; Driver code
def find_maximum_jobs ( N , ranges ) : NEW_LINE INDENT queue = [ ] NEW_LINE ranges . sort ( ) NEW_LINE min_day = ranges [ 0 ] [ 0 ] NEW_LINE max_day = 0 NEW_LINE for i in range ( N ) : NEW_LINE max_day = max ( max_day , ranges [ i ] [ 1 ] ) NEW_LINE index , count_jobs = 0 , 0 NEW_LINE for i in range ( min_day , max_day + 1 ) : NEW_LINE while ( index < len ( ranges ) and ranges [ index ] [ 0 ] <= i ) : NEW_LINE INDENT queue . append ( ranges [ index ] [ 1 ] ) NEW_LINE index += 1 NEW_LINE DEDENT queue . sort ( ) NEW_LINE while ( len ( queue ) > 0 and queue [ 0 ] < i ) : NEW_LINE INDENT queue . pop ( 0 ) NEW_LINE DEDENT if ( len ( queue ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT count_jobs += 1 NEW_LINE queue . pop ( 0 ) NEW_LINE return count_jobs NEW_LINE DEDENT N = 5 NEW_LINE ranges = [ ] NEW_LINE ranges . append ( ( 1 , 5 ) ) NEW_LINE ranges . append ( ( 1 , 5 ) ) NEW_LINE ranges . append ( ( 1 , 5 ) ) NEW_LINE ranges . append ( ( 2 , 3 ) ) NEW_LINE ranges . append ( ( 2 , 3 ) ) NEW_LINE print ( find_maximum_jobs ( N , ranges ) ) NEW_LINE
Minimize number of boxes by putting small box inside bigger one | Function to minimize the count ; Initial number of box ; Sort array of box size in increasing order ; Check is current box size is smaller than next box size ; Decrement box count Increment current box count Increment next box count ; Check if both box have same size ; Print the result ; Driver code
def minBox ( arr , n ) : NEW_LINE INDENT box = n NEW_LINE arr . sort ( ) NEW_LINE curr_box , next_box = 0 , 1 NEW_LINE while ( curr_box < n and next_box < n ) : NEW_LINE INDENT if ( arr [ curr_box ] < arr [ next_box ] ) : NEW_LINE INDENT box = box - 1 NEW_LINE curr_box = curr_box + 1 NEW_LINE next_box = next_box + 1 NEW_LINE DEDENT elif ( arr [ curr_box ] == arr [ next_box ] ) : NEW_LINE INDENT next_box = next_box + 1 NEW_LINE DEDENT DEDENT print ( box ) NEW_LINE DEDENT size = [ 1 , 2 , 3 ] NEW_LINE n = len ( size ) NEW_LINE minBox ( size , n ) NEW_LINE
Sort a string lexicographically using triple cyclic shifts | Python3 program for sorting a string using cyclic shift of three indices ; Store the indices which haven 't attained its correct position ; Store the indices undergoing cyclic shifts ; If the element is not at it 's correct position ; Check if all 3 indices can be placed to respective correct indices in a single move ; If the i - th index is still not present in its correct position , store the index ; To check if swapping two indices places them in their correct position ; for i in range len ( indices ) : print ( indices [ i ] [ 0 ] , indices [ i ] [ 1 ] , indices [ i ] [ 2 ] ) ; Driver code
import math NEW_LINE def sortString ( arr , n , moves ) : NEW_LINE INDENT pos = [ ] NEW_LINE indices = [ ] NEW_LINE flag = False NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != i ) : NEW_LINE INDENT if ( arr [ arr [ arr [ i ] ] ] == i and arr [ arr [ i ] ] != i ) : NEW_LINE INDENT temp = arr [ arr [ i ] ] NEW_LINE indices . append ( [ i , arr [ i ] , arr [ arr [ i ] ] ] ) NEW_LINE sw = arr [ i ] NEW_LINE arr [ i ] = arr [ arr [ i ] ] NEW_LINE arr [ sw ] = sw NEW_LINE sw = arr [ i ] NEW_LINE arr [ i ] = arr [ temp ] NEW_LINE arr [ temp ] = sw NEW_LINE DEDENT DEDENT if ( arr [ i ] != i ) : NEW_LINE INDENT pos . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != i ) : NEW_LINE INDENT pos1 = i NEW_LINE pos2 = arr [ i ] NEW_LINE pos3 = arr [ arr [ i ] ] NEW_LINE if ( pos3 != pos1 ) : NEW_LINE INDENT indices . append ( [ pos1 , pos2 , pos3 ] ) NEW_LINE arr [ pos1 ] , arr [ pos2 ] = arr [ pos2 ] , arr [ pos1 ] NEW_LINE arr [ pos1 ] , arr [ pos3 ] = arr [ pos3 ] , arr [ pos1 ] NEW_LINE pos . remove ( pos2 ) NEW_LINE if pos3 in pos : NEW_LINE INDENT pos . remove ( pos3 ) NEW_LINE DEDENT if ( arr [ pos1 ] == pos1 ) : NEW_LINE INDENT pos . remove ( pos1 ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( pos3 == pos [ 0 ] ) : NEW_LINE INDENT it = 0 NEW_LINE if ( pos [ 0 ] != pos [ - 1 ] ) : NEW_LINE INDENT it = it + 1 NEW_LINE pos3 = pos [ it ] NEW_LINE if ( pos [ it ] != pos [ - 1 ] and pos3 == pos2 ) : NEW_LINE INDENT it = it + 1 NEW_LINE pos3 = pos [ it ] NEW_LINE DEDENT elif ( pos [ it ] == pos [ - 1 ] and pos3 == pos2 ) : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT flag = True NEW_LINE break NEW_LINE DEDENT DEDENT indices . append ( [ pos1 , pos2 , pos3 ] ) NEW_LINE arr [ pos1 ] , arr [ pos2 ] = arr [ pos2 ] , arr [ pos1 ] NEW_LINE arr [ pos1 ] , arr [ pos3 ] = arr [ pos3 ] , arr [ pos1 ] NEW_LINE pos . remove ( pos2 ) NEW_LINE DEDENT DEDENT if ( arr [ i ] != i ) : NEW_LINE INDENT i = i - 1 NEW_LINE DEDENT DEDENT if ( flag == True or len ( indices ) > moves ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( len ( indices ) ) NEW_LINE DEDENT DEDENT s = " adceb " NEW_LINE arr = [ ] NEW_LINE for i in s : NEW_LINE INDENT arr . append ( ord ( i ) - ord ( ' a ' ) ) NEW_LINE DEDENT sortString ( arr , len ( s ) , math . floor ( len ( s ) / 2 ) ) NEW_LINE
Count of minimum reductions required to get the required sum K | Python3 program to find the count of minimum reductions required to get the required sum K ; Function to return the count of minimum reductions ; If the sum is already less than K ; Sort in non - increasing order of difference ; Driver Code ; Function Call
from typing import Any , List NEW_LINE def countReductions ( v : List [ Any ] , K : int ) -> int : NEW_LINE INDENT sum = 0 NEW_LINE for i in v : NEW_LINE INDENT sum += i [ 0 ] NEW_LINE DEDENT if ( sum <= K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT v . sort ( key = lambda a : a [ 0 ] - a [ 1 ] ) NEW_LINE i = 0 NEW_LINE while ( sum > K and i < len ( v ) ) : NEW_LINE INDENT sum -= ( v [ i ] [ 0 ] - v [ i ] [ 1 ] ) NEW_LINE i += 1 NEW_LINE DEDENT if ( sum <= K ) : NEW_LINE INDENT return i NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE K = 25 NEW_LINE v = [ [ 0 , 0 ] for _ in range ( N ) ] NEW_LINE v [ 0 ] = [ 10 , 5 ] NEW_LINE v [ 1 ] = [ 20 , 9 ] NEW_LINE v [ 2 ] = [ 12 , 10 ] NEW_LINE v [ 3 ] = [ 4 , 2 ] NEW_LINE print ( countReductions ( v , K ) ) NEW_LINE DEDENT
Merge two unsorted linked lists to get a sorted list | Create structure for a node ; Function to print the linked list ; Store the head of the linked list into a temporary node * and iterate ; Function takes the head of the LinkedList and the data as argument and if no LinkedList exists , it creates one with the head pointing to first node . If it exists already , it appends given node at end of the last node ; Create a new node ; Insert data into the temporary node and point it 's next to NULL ; Check if head is null , create a linked list with temp as head and tail of the list ; Else insert the temporary node after the tail of the existing node and make the temporary node as the tail of the linked list ; Return the list ; Function to concatenate the two lists ; Iterate through the head1 to find the last node join the next of last node of head1 to the 1 st node of head2 ; return the concatenated lists as a single list - head1 ; Sort the linked list using bubble sort ; Compares two adjacent elements and swaps if the first element is greater than the other one . ; Driver Code ; Given Linked List 1 ; Given Linked List 2 ; Merge the two lists in a single list ; Sort the unsorted merged list ; Print the final sorted merged list
class node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def setData ( head ) : NEW_LINE INDENT tmp = head NEW_LINE while ( tmp != None ) : NEW_LINE INDENT print ( tmp . data , end = " ▁ - > ▁ " ) NEW_LINE tmp = tmp . next NEW_LINE DEDENT DEDENT def getData ( head , num ) : NEW_LINE INDENT temp = node ( - 1 ) NEW_LINE tail = head NEW_LINE temp . data = num NEW_LINE temp . next = None NEW_LINE if ( head == None ) : NEW_LINE INDENT head = temp NEW_LINE tail = temp NEW_LINE DEDENT else : NEW_LINE INDENT while ( tail != None ) : NEW_LINE INDENT if ( tail . next == None ) : NEW_LINE INDENT tail . next = temp NEW_LINE tail = tail . next NEW_LINE DEDENT tail = tail . next NEW_LINE DEDENT DEDENT return head NEW_LINE DEDENT def mergelists ( head1 , head2 ) : NEW_LINE INDENT tail = head1 NEW_LINE while ( tail != None ) : NEW_LINE INDENT if ( tail . next == None and head2 != None ) : NEW_LINE INDENT tail . next = head2 NEW_LINE break NEW_LINE DEDENT tail = tail . next NEW_LINE DEDENT return head1 NEW_LINE DEDENT def sortlist ( head1 ) : NEW_LINE INDENT curr = head1 NEW_LINE temp = head1 NEW_LINE while ( curr . next != None ) : NEW_LINE INDENT temp = curr . next NEW_LINE while ( temp != None ) : NEW_LINE INDENT if ( temp . data < curr . data ) : NEW_LINE INDENT t = temp . data NEW_LINE temp . data = curr . data NEW_LINE curr . data = t NEW_LINE DEDENT temp = temp . next NEW_LINE DEDENT curr = curr . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = node ( - 1 ) NEW_LINE head2 = node ( - 1 ) NEW_LINE head1 = None NEW_LINE head2 = None NEW_LINE head1 = getData ( head1 , 4 ) NEW_LINE head1 = getData ( head1 , 7 ) NEW_LINE head1 = getData ( head1 , 5 ) NEW_LINE head2 = getData ( head2 , 2 ) NEW_LINE head2 = getData ( head2 , 1 ) NEW_LINE head2 = getData ( head2 , 8 ) NEW_LINE head2 = getData ( head2 , 1 ) NEW_LINE head1 = mergelists ( head1 , head2 ) NEW_LINE sortlist ( head1 ) NEW_LINE setData ( head1 ) NEW_LINE DEDENT
Find K elements whose absolute difference with median of array is maximum | Function for calculating median ; Check for even case ; Function to find the K maximum absolute difference with the median of the array ; Sort the array ; Store median ; Find and store difference ; If diff [ i ] is greater print it . Else print diff [ j ] ; Driver code
def findMedian ( a , n ) : NEW_LINE INDENT if ( n % 2 != 0 ) : NEW_LINE INDENT return a [ int ( n / 2 ) ] NEW_LINE DEDENT return ( a [ int ( ( n - 1 ) / 2 ) ] + a [ int ( n / 2 ) ] ) / 2.0 NEW_LINE DEDENT def kStrongest ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE median = findMedian ( arr , n ) NEW_LINE diff = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT diff [ i ] = abs ( median - arr [ i ] ) NEW_LINE DEDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while ( k > 0 ) : NEW_LINE INDENT if ( diff [ i ] > diff [ j ] ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ j ] , end = " ▁ " ) NEW_LINE j -= 1 NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE k = 3 NEW_LINE n = len ( arr ) NEW_LINE kStrongest ( arr , n , k ) NEW_LINE
Sort an array by swapping elements of different type specified by another array | Function to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; Consider the array to be already sorted ; Checking if array is already sorted ; Check for a pair which is in decreasing order ; Count the frequency of each type of element ; type0 stores count of elements of type 0 ; type1 stores count of elements of type 1 ; Return true if array is already sorted ; Return false if all elements are of same type and array is unsorted ; Possible for all other cases ; Driver code
def sorting_possible ( a , b , n ) : NEW_LINE INDENT sorted = True NEW_LINE type1 = 0 NEW_LINE type0 = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] < a [ i - 1 ] ) : NEW_LINE INDENT sorted = False NEW_LINE break NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( b [ i ] == 0 ) : NEW_LINE INDENT type0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT type1 += 1 NEW_LINE DEDENT DEDENT if ( sorted != False ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( type1 == n or type0 == n ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT a = [ 15 , 1 , 2 , 17 , 6 ] NEW_LINE b = [ 1 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( a ) NEW_LINE res = sorting_possible ( a , b , n ) NEW_LINE if ( res != False ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Shortest path in a directed graph by DijkstraΓ’ €ℒ s algorithm | Python3 implementation to find the shortest path in a directed graph from source vertex to the destination vertex ; Class of the node ; Adjacency list that shows the vertexNumber of child vertex and the weight of the edge ; Function to add the child for the given node ; Function to find the distance of the node from the given source vertex to the destination vertex ; Stores distance of each vertex from source vertex ; bool array that shows whether the vertex ' i ' is visited or not ; Set of vertices that has a parent ( one or more ) marked as visited ; Mark current as visited ; Inserting into the visited vertex ; Condition to check the distance is correct and update it if it is minimum from the previous computed distance ; The new current ; Loop to update the distance of the vertices of the graph ; Function to print the path from the source vertex to the destination vertex ; Condition to check if there is no path between the vertices ; Driver Code ; Loop to create the nodes ; Creating directed weighted edges ; Loop to print the distance of every node from source vertex
class Pair : NEW_LINE INDENT def __init__ ( self , first , second ) : NEW_LINE INDENT self . first = first NEW_LINE self . second = second NEW_LINE DEDENT DEDENT infi = 1000000000 ; NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , vertexNumber ) : NEW_LINE INDENT self . vertexNumber = vertexNumber NEW_LINE self . children = [ ] NEW_LINE DEDENT def Add_child ( self , vNumber , length ) : NEW_LINE INDENT p = Pair ( vNumber , length ) ; NEW_LINE self . children . append ( p ) ; NEW_LINE DEDENT DEDENT def dijkstraDist ( g , s , path ) : NEW_LINE INDENT dist = [ infi for i in range ( len ( g ) ) ] NEW_LINE visited = [ False for i in range ( len ( g ) ) ] NEW_LINE for i in range ( len ( g ) ) : NEW_LINE INDENT path [ i ] = - 1 NEW_LINE DEDENT dist [ s ] = 0 ; NEW_LINE path [ s ] = - 1 ; NEW_LINE current = s ; NEW_LINE sett = set ( ) NEW_LINE while ( True ) : NEW_LINE INDENT visited [ current ] = True ; NEW_LINE for i in range ( len ( g [ current ] . children ) ) : NEW_LINE INDENT v = g [ current ] . children [ i ] . first ; NEW_LINE if ( visited [ v ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT sett . add ( v ) ; NEW_LINE alt = dist [ current ] + g [ current ] . children [ i ] . second ; NEW_LINE if ( alt < dist [ v ] ) : NEW_LINE INDENT dist [ v ] = alt ; NEW_LINE path [ v ] = current ; NEW_LINE DEDENT DEDENT if current in sett : NEW_LINE INDENT sett . remove ( current ) ; NEW_LINE DEDENT if ( len ( sett ) == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT minDist = infi ; NEW_LINE index = 0 ; NEW_LINE for a in sett : NEW_LINE INDENT if ( dist [ a ] < minDist ) : NEW_LINE INDENT minDist = dist [ a ] ; NEW_LINE index = a ; NEW_LINE DEDENT DEDENT current = index ; NEW_LINE DEDENT return dist ; NEW_LINE DEDENT def printPath ( path , i , s ) : NEW_LINE INDENT if ( i != s ) : NEW_LINE INDENT if ( path [ i ] == - 1 ) : NEW_LINE INDENT print ( " Path ▁ not ▁ found ! ! " ) ; NEW_LINE return ; NEW_LINE DEDENT printPath ( path , path [ i ] , s ) ; NEW_LINE print ( path [ i ] + " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT v = [ ] NEW_LINE n = 4 NEW_LINE s = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT a = Node ( i ) ; NEW_LINE v . append ( a ) ; NEW_LINE DEDENT v [ 0 ] . Add_child ( 1 , 1 ) ; NEW_LINE v [ 0 ] . Add_child ( 2 , 4 ) ; NEW_LINE v [ 1 ] . Add_child ( 2 , 2 ) ; NEW_LINE v [ 1 ] . Add_child ( 3 , 6 ) ; NEW_LINE v [ 2 ] . Add_child ( 3 , 3 ) ; NEW_LINE path = [ 0 for i in range ( len ( v ) ) ] ; NEW_LINE dist = dijkstraDist ( v , s , path ) ; NEW_LINE for i in range ( len ( dist ) ) : NEW_LINE INDENT if ( dist [ i ] == infi ) : NEW_LINE INDENT print ( " { 0 } ▁ and ▁ { 1 } ▁ are ▁ not ▁ " + " connected " . format ( i , s ) ) ; NEW_LINE continue ; NEW_LINE DEDENT print ( " Distance ▁ of ▁ { } th ▁ vertex ▁ from ▁ source ▁ vertex ▁ { } ▁ is : ▁ { } " . format ( i , s , dist [ i ] ) ) ; NEW_LINE DEDENT DEDENT
Sort permutation of N natural numbers using triple cyclic right swaps | Function to sort the permutation with the given operations ; Visited array to check the array element is at correct position or not ; Loop to iterate over the elements of the given array ; Condition to check if the elements is at its correct position ; Condition to check if the element is included in any previous cyclic rotations ; Loop to find the cyclic rotations in required ; Condition to check if the cyclic rotation is a valid rotation ; Loop to find the index of the cyclic rotation for the current index ; Condition to if the cyclic rotation is a valid rotation ; Loop to find athe valid operations required to sort the permutation ; Total operation required ; Driver Code ; Function Call
def sortPermutation ( arr , n ) : NEW_LINE INDENT ans = [ ] NEW_LINE p = [ ] NEW_LINE visited = [ 0 ] * 200005 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( arr [ i ] == i ) : NEW_LINE INDENT visited [ i ] = 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( visited [ i ] == False ) : NEW_LINE INDENT x = i NEW_LINE v = [ ] NEW_LINE while ( visited [ x ] == False ) : NEW_LINE INDENT visited [ x ] = 1 NEW_LINE v . append ( x ) NEW_LINE x = arr [ x ] NEW_LINE DEDENT if ( ( len ( v ) - 3 ) % 2 == 0 ) : NEW_LINE INDENT for i in range ( 1 , len ( v ) , 2 ) : NEW_LINE INDENT ans . append ( [ v [ 0 ] , v [ i ] , v [ i + 1 ] ] ) NEW_LINE DEDENT continue NEW_LINE DEDENT p . append ( v [ 0 ] ) NEW_LINE p . append ( v [ len ( v ) - 1 ] ) NEW_LINE for i in range ( 1 , len ( v ) - 1 , 2 ) : NEW_LINE INDENT ans . append ( [ v [ 0 ] , v [ i ] , v [ i + 1 ] ] ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( len ( p ) % 4 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , len ( p ) , 4 ) : NEW_LINE INDENT ans . append ( [ p [ i ] , p [ i + 1 ] , p [ i + 2 ] ] ) NEW_LINE ans . append ( p [ i [ + 2 ] , p [ i ] , p [ i + 3 ] ] ) NEW_LINE DEDENT print ( len ( ans ) ) NEW_LINE for i in ans : NEW_LINE INDENT print ( i [ 0 ] , i [ 1 ] , i [ 2 ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 3 , 2 , 4 , 1 ] NEW_LINE n = 4 NEW_LINE sortPermutation ( arr , n ) NEW_LINE DEDENT
Maximize array sum by X increments when each element is divided by 10 | Python3 program for the above problem ; Initialize variables ; Add the current contribution of the element to the answer ; If the value is already maximum then we can 't change it ; Moves required to move to the next multiple of 10 ; No of times we can add 10 to this value so that its value does not exceed 1000. ; Sort the array ; Adding the values to increase the numbers to the next multiple of 10 ; If the total moves are less than X then increase the answer ; If the moves exceed X then we cannot increase numbers ; If there still remain some moves ; Remaining moves ; Add minimim of increments and remaining / 10 to the answer ; Output the final answer ; Driver Code
def maximizeval10 ( a , n , k ) : NEW_LINE INDENT increments = 0 NEW_LINE ans = 0 NEW_LINE v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += ( a [ i ] // 10 ) NEW_LINE if ( a [ i ] == 1000 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( 10 - a [ i ] % 10 ) NEW_LINE increments += ( 100 - ( ( a [ i ] ) // 10 ) - 1 ) ; NEW_LINE DEDENT DEDENT v . sort ( ) NEW_LINE sum = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT sum += v [ i ] NEW_LINE if ( sum <= k ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( sum < k ) : NEW_LINE INDENT remaining = k - sum NEW_LINE ans += min ( increments , remaining // 10 ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE X = 6 NEW_LINE A = [ 4 , 8 , 8 , 8 ] NEW_LINE maximizeval10 ( A , N , X ) NEW_LINE DEDENT
Split array into two subarrays such that difference of their maximum is minimum | Python3 Program to split a given array such that the difference between their maximums is minimized . ; Sort the array ; Return the difference between two highest elements ; Driver Program
def findMinDif ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE return ( arr [ N - 1 ] - arr [ N - 2 ] ) NEW_LINE DEDENT arr = [ 7 , 9 , 5 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMinDif ( arr , N ) ) NEW_LINE
Count of available non | Function to find the pivot index ; Function to implement Quick Sort ; Pivot is pointing to pivot index before which every element is smaller and after pivot , every element is greater ; Sort the array before pivot element ; Sort the array after pivot element ; Function to count the available intervals from the given range of numbers ; If range starts after 0 then an interval is available from 0 to start [ 0 ] ; When a new interval starts ; Since index variable i is being incremented , the current active interval will also get incremented ; When the current interval ends ; Since index variable j is being decremented , the currect active interval will also get decremented ; When start and end both are same there is no change in currActive ; If the end of interval is before the range so interval is available at the end ; Driver code ; Sort the start array ; Sort the end array ; Calling the function
def partition ( arr , l , h ) : NEW_LINE INDENT pivot = arr [ l ] NEW_LINE i = l + 1 NEW_LINE j = h NEW_LINE while ( i <= j ) : NEW_LINE INDENT while ( i <= h and arr [ i ] < pivot ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT while ( j > l and arr [ j ] > pivot ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( i < j ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = temp NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT arr [ l ] = arr [ j ] NEW_LINE arr [ j ] = pivot NEW_LINE return j NEW_LINE DEDENT def sortArray ( arr , l , h ) : NEW_LINE INDENT if ( l >= h ) : NEW_LINE INDENT return NEW_LINE DEDENT pivot = partition ( arr , l , h ) NEW_LINE sortArray ( arr , l , pivot - 1 ) NEW_LINE sortArray ( arr , pivot + 1 , h ) NEW_LINE DEDENT def findMaxIntervals ( start , end , n , R ) : NEW_LINE INDENT ans = 0 NEW_LINE prev = 0 NEW_LINE currActive = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE if ( start [ 0 ] > 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT while ( i < n and j < n ) : NEW_LINE INDENT if ( start [ i ] < end [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE currActive += 1 NEW_LINE DEDENT elif ( start [ i ] > end [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE currActive -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT if ( currActive == 0 ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT if ( end [ n - 1 ] < R ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT R = 10 NEW_LINE N = 3 NEW_LINE start = [ 2 , 5 , 8 ] NEW_LINE end = [ 3 , 9 , 10 ] NEW_LINE sortArray ( start , 0 , N - 1 ) NEW_LINE sortArray ( end , 0 , N - 1 ) NEW_LINE print ( findMaxIntervals ( start , end , N , R ) ) NEW_LINE DEDENT
Maximum items that can be bought from the cost Array based on given conditions | Function to find the maximum number of items that can be bought from the given cost array ; Sort the given array ; Variables to store the prefix sum , answer and the counter variables ; Initializing the first element of the prefix array ; If we can buy at least one item ; Iterating through the first K items and finding the prefix sum ; Check the number of items that can be bought ; Finding the prefix sum for the remaining elements ; Check the number of iteams that can be bought ; Driver code
def number ( a , n , p , k ) : NEW_LINE INDENT a . sort ( ) NEW_LINE pre = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pre . append ( 0 ) NEW_LINE DEDENT ans = 0 NEW_LINE val = 0 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE pre [ 0 ] = a [ 0 ] NEW_LINE if pre [ 0 ] <= p : NEW_LINE INDENT ans = 1 NEW_LINE DEDENT for i in range ( 1 , k - 1 ) : NEW_LINE INDENT pre [ i ] = pre [ i - 1 ] + a [ i ] NEW_LINE if pre [ i ] <= p : NEW_LINE INDENT ans = i + 1 NEW_LINE DEDENT DEDENT pre [ k - 1 ] = a [ k - 1 ] NEW_LINE for i in range ( k - 1 , n ) : NEW_LINE INDENT if i >= k : NEW_LINE INDENT pre [ i ] += pre [ i - k ] + a [ i ] NEW_LINE DEDENT if pre [ i ] <= p : NEW_LINE INDENT ans = i + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 5 NEW_LINE arr = [ 2 , 4 , 3 , 5 , 7 ] NEW_LINE p = 11 NEW_LINE k = 2 NEW_LINE print ( number ( arr , n , p , k ) ) NEW_LINE
Find the Maximum possible Sum for the given conditions | Function to find the maximum possible sum for the given conditions ; Sorting the array ; Variable to store the answer ; Iterating through the array ; If the value is greater than 0 ; If the value becomes 0 then break the loop because all the weights after this index will be 0 ; print profit ; Driver code
def maxProfit ( arr ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE ans = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] - ( 1 * i ) ) > 0 : NEW_LINE INDENT ans += ( arr [ i ] - ( 1 * i ) ) NEW_LINE DEDENT if ( arr [ i ] - ( 1 * i ) ) == 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 6 , 6 , 6 ] NEW_LINE print ( maxProfit ( arr ) ) NEW_LINE DEDENT
Check if the array can be sorted only if the elements on given positions can be swapped | Function to check if the array can be sorted only if the elements on the given positions can be swapped ; Creating an array for marking the positions ; Iterating through the array and mark the positions ; Iterating through the given array ; If pos [ i ] is 1 , then incrementing till 1 is continuously present in pos ; Sorting the required segment ; Checking if the vector is sorted or not ; Print yes if it is sorted ; Driver code
def check_vector ( A , n , p ) : NEW_LINE INDENT pos = [ 0 for i in range ( len ( A ) ) ] NEW_LINE for i in range ( len ( p ) ) : NEW_LINE INDENT pos [ p [ i ] - 1 ] = 1 NEW_LINE DEDENT flag = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( pos [ i ] == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT j = i NEW_LINE while ( j < n and pos [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT p = A [ : i ] NEW_LINE q = A [ i : i + j + 1 ] NEW_LINE r = A [ i + j + 1 : len ( A ) ] NEW_LINE q . sort ( reverse = False ) NEW_LINE A = p + q + r NEW_LINE i = j NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( A [ i ] > A [ i + 1 ] ) : NEW_LINE INDENT flag = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 1 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3 , 2 , 1 ] NEW_LINE p = [ 1 , 2 ] NEW_LINE check_vector ( A , len ( A ) , p ) NEW_LINE DEDENT
Sort an array of strings based on the given order | Python3 program to sort an array of strings based on the given order ; For storing priority of each character ; Custom comparator function for sort ; Loop through the minimum size between two words ; Check if the characters at position i are different , then the word containing lower valued character is smaller ; When loop breaks without returning , it means the prefix of both words were same till the execution of the loop . Now , the word with the smaller size will occur before in sorted order ; Function to print the new sorted array of strings ; Mapping each character to its occurrence position ; Sorting with custom sort function ; Printing the sorted order of words ; Driver code
from functools import cmp_to_key NEW_LINE mp = { } NEW_LINE def comp ( a , b ) : NEW_LINE INDENT for i in range ( min ( len ( a ) , len ( b ) ) ) : NEW_LINE INDENT if ( mp [ a [ i ] ] != mp [ b [ i ] ] ) : NEW_LINE INDENT if mp [ a [ i ] ] < mp [ b [ i ] ] : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT DEDENT if ( len ( a ) < len ( b ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 NEW_LINE DEDENT DEDENT def printSorted ( words , order ) : NEW_LINE INDENT for i in range ( len ( order ) ) : NEW_LINE INDENT mp [ order [ i ] ] = i NEW_LINE DEDENT words = sorted ( words , key = cmp_to_key ( comp ) ) NEW_LINE for x in words : NEW_LINE INDENT print ( x , end = " ▁ " ) NEW_LINE DEDENT DEDENT words = [ " word " , " world " , " row " ] NEW_LINE order = " worldabcefghijkmnpqstuvxyz " NEW_LINE printSorted ( words , order ) NEW_LINE
Sort elements of an array in increasing order of absolute difference of adjacent elements | Function to sort the elements of the array by difference ; Sorting the array ; Array to store the elements of the array ; Iterating over the length of the array to include each middle element of array ; Appending the middle element of the array ; Driver Code
def sortDiff ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE out = [ ] NEW_LINE while n : NEW_LINE INDENT out . append ( arr . pop ( n // 2 ) ) NEW_LINE n = n - 1 NEW_LINE DEDENT print ( * out ) NEW_LINE return out NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 8 , 1 , 2 , 3 , 0 ] NEW_LINE n = 5 NEW_LINE sortDiff ( arr , n ) NEW_LINE DEDENT
Minimum cost of choosing the array element | Function that find the minimum cost of selecting array element ; Sorting the given array in increasing order ; To store the prefix sum of arr [ ] ; Update the pref [ ] to find the cost selecting array element by selecting at most M element ; Print the pref [ ] for the result ; Driver Code
def minimumCost ( arr , N , M ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE pref = [ ] NEW_LINE pref . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT pref . append ( arr [ i ] + pref [ i - 1 ] ) NEW_LINE DEDENT for i in range ( M , N ) : NEW_LINE INDENT pref [ i ] += pref [ i - M ] NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( pref [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT arr = [ 6 , 19 , 3 , 4 , 4 , 2 , 6 , 7 , 8 ] NEW_LINE M = 2 NEW_LINE N = len ( arr ) NEW_LINE minimumCost ( arr , N , M ) ; NEW_LINE
Sort an Array alphabetically when each number is converted into words | Variable to store the word form of units digit and up to twenty ; Variable to store the word form of tens digit ; Function to convert a two digit number to the word by using the above defined arrays ; If n is more than 19 , divide it ; If n is non - zero ; Function to print a given number in words ; Stores the word representation of the given number n ; Handles digits at ten millions and hundred millions places ; Handles digits at hundred thousands and one millions places ; Handles digits at thousands and tens thousands places ; Handles digit at hundreds places ; Call the above function to convert the number into words ; Function to sort the array according to the albhabetical order ; Vector to store the number in words with respective elements ; Inserting number in words with respective elements in vector pair ; Sort the vector , this will sort the pair according to the alphabetical order . ; Print the sorted vector content ; Driver code
one = [ " " , " one ▁ " , " two ▁ " , " three ▁ " , " four ▁ " , " five ▁ " , " six ▁ " , " seven ▁ " , " eight ▁ " , " nine ▁ " , " ten ▁ " , " eleven ▁ " , " twelve ▁ " , " thirteen ▁ " , " fourteen ▁ " , " fifteen ▁ " , " sixteen ▁ " , " seventeen ▁ " , " eighteen ▁ " , " nineteen ▁ " ] NEW_LINE ten = [ " " , " " , " twenty ▁ " , " thirty ▁ " , " forty ▁ " , " fifty ▁ " , " sixty ▁ " , " seventy ▁ " , " eighty ▁ " , " ninety ▁ " ] NEW_LINE def numToWords ( n , s ) : NEW_LINE INDENT st = " " NEW_LINE if ( n > 19 ) : NEW_LINE INDENT st += ten [ n // 10 ] + one [ n % 10 ] NEW_LINE DEDENT else : NEW_LINE INDENT st += one [ n ] NEW_LINE DEDENT if ( n ) : NEW_LINE INDENT st += s NEW_LINE DEDENT return st NEW_LINE DEDENT def convertToWords ( n ) : NEW_LINE INDENT out = " " NEW_LINE out += numToWords ( ( n // 10000000 ) , " crore ▁ " ) NEW_LINE out += numToWords ( ( ( n // 100000 ) % 100 ) , " lakh ▁ " ) NEW_LINE out += numToWords ( ( ( n // 1000 ) % 100 ) , " thousand ▁ " ) NEW_LINE out += numToWords ( ( ( n // 100 ) % 10 ) , " hundred ▁ " ) NEW_LINE if ( n > 100 and n % 100 ) : NEW_LINE INDENT out += " and ▁ " NEW_LINE DEDENT out += numToWords ( ( n % 100 ) , " " ) NEW_LINE return out NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( ( convertToWords ( arr [ i ] ) , arr [ i ] ) ) ; NEW_LINE DEDENT vp . sort ( ) NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT print ( vp [ i ] [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 10 , 102 , 31 , 15 ] NEW_LINE n = len ( arr ) NEW_LINE sortArr ( arr , n ) NEW_LINE DEDENT
Maximum Possible Rating of a Coding Contest | Python3 program to find the Maximum Possible Rating of a Coding Contest ; Function to sort all problems descending to upvotes ; Function to return maximum rating ; Declaring vector of pairs ; Each pair represents a problem with its points and upvotes ; Step ( 1 ) - Sort problems by their upvotes value in decreasing order ; Declaring min_heap or priority queue to track of the problem with minimum points . ; Step ( 2 ) - Loop for i = 0 to K - 1 and do accordingly ; Step ( 3 ) - Loop for i = K to N - 1 and do accordingly ; Driver code
import heapq NEW_LINE def Comparator ( p1 ) : NEW_LINE INDENT return p1 [ 1 ] NEW_LINE DEDENT def FindMaxRating ( N , Point , Upvote , K ) : NEW_LINE INDENT vec = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT vec . append ( [ Point [ i ] , Upvote [ i ] ] ) NEW_LINE DEDENT vec . sort ( reverse = True , key = Comparator ) NEW_LINE pq = [ ] NEW_LINE heapq . heapify ( pq ) NEW_LINE total_points , max_rating = 0 , 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT total_points = ( total_points + vec [ i ] [ 0 ] ) NEW_LINE max_rating = max ( max_rating , total_points * vec [ i ] [ 1 ] ) NEW_LINE heapq . heappush ( pq , vec [ i ] [ 0 ] ) NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT if pq [ 0 ] < vec [ i ] [ 0 ] : NEW_LINE INDENT total_points = ( total_points - pq [ 0 ] + vec [ i ] [ 0 ] ) NEW_LINE max_rating = max ( max_rating , total_points * vec [ i ] [ 1 ] ) NEW_LINE heapq . heappop ( pq ) NEW_LINE heapq . heappush ( pq , vec [ i ] [ 0 ] ) NEW_LINE DEDENT DEDENT return max_rating NEW_LINE DEDENT Point = [ 2 , 10 , 3 , 1 , 5 , 8 ] NEW_LINE Upvote = [ 5 , 4 , 3 , 9 , 7 , 2 ] NEW_LINE N = len ( Point ) NEW_LINE K = 2 NEW_LINE print ( " Maximum ▁ Rating ▁ of ▁ Coding ▁ Contest ▁ is : " , FindMaxRating ( N , Point , Upvote , K ) ) NEW_LINE
Find sum of all unique elements in the array for K queries | Function to find the sum of unique elements after Q Query ; Updating the array after processing each query ; Making it to 0 - indexing ; Iterating over the array to get the final array ; Variable to store the sum ; Hash to maintain perviously occured elements ; Loop to find the maximum sum ; Driver code
def uniqueSum ( A , R , N , M ) : NEW_LINE INDENT for i in range ( 0 , M ) : NEW_LINE INDENT l = R [ i ] [ 0 ] NEW_LINE r = R [ i ] [ 1 ] + 1 NEW_LINE l -= 1 NEW_LINE r -= 1 NEW_LINE A [ l ] += 1 NEW_LINE if ( r < N ) : NEW_LINE INDENT A [ r ] -= 1 NEW_LINE DEDENT DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] += A [ i - 1 ] NEW_LINE DEDENT ans = 0 NEW_LINE s = { chr } NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( A [ i ] not in s ) : NEW_LINE INDENT ans += A [ i ] NEW_LINE DEDENT s . add ( A [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT A = [ 0 , 0 , 0 , 0 , 0 , 0 ] NEW_LINE R = [ [ 1 , 3 ] , [ 4 , 6 ] , [ 3 , 4 ] , [ 3 , 3 ] ] NEW_LINE N = len ( A ) NEW_LINE M = len ( R ) NEW_LINE print ( uniqueSum ( A , R , N , M ) ) NEW_LINE
Find the Kth pair in ordered list of all possible sorted pairs of the Array | Function to find the k - th pair ; Sorting the array ; Iterating through the array ; Finding the number of same elements ; Checking if N * T is less than the remaining K . If it is , then arr [ i ] is the first element in the required pair ; Printing the K - th pair ; Driver code
def kthpair ( n , k , arr ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE k -= 1 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT t = 1 NEW_LINE while ( arr [ i ] == arr [ i + t ] ) : NEW_LINE INDENT t += 1 NEW_LINE DEDENT if ( t * n > k ) : NEW_LINE INDENT break NEW_LINE DEDENT k = k - t * n NEW_LINE i += t NEW_LINE DEDENT print ( arr [ i ] , " ▁ " , arr [ k // t ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 3 , 2 NEW_LINE arr = [ 3 , 1 , 5 ] NEW_LINE kthpair ( n , k , arr ) NEW_LINE DEDENT
Minimum characters to be replaced to make frequency of all characters same | Function to find the minimum operations to convert given string to another with equal frequencies of characters ; Frequency of characters ; Loop to find the Frequency of each character ; Sort in decreasing order based on frequency ; Maximum possible answer ; Loop to find the minimum operations required such that frequency of every character is equal ; Driver Code
def minOperations ( s ) : NEW_LINE INDENT freq = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' A ' ) ] += 1 NEW_LINE DEDENT freq . sort ( reverse = True ) NEW_LINE answer = n NEW_LINE for i in range ( 1 , 27 ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT x = n // i NEW_LINE y = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT y += min ( freq [ j ] , x ) NEW_LINE DEDENT answer = min ( answer , n - y ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " BBC " NEW_LINE print ( minOperations ( s ) ) NEW_LINE DEDENT
Check if it is possible to sort an array with conditional swapping of elements at distance K | Function for finding if it possible to obtain sorted array or not ; Iterate over all elements until K ; Store elements as multiples of K ; Sort the elements ; Put elements in their required position ; Check if the array becomes sorted or not ; Driver code
def fun ( arr , n , k ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( k ) : NEW_LINE INDENT for j in range ( i , n , k ) : NEW_LINE INDENT v . append ( arr [ j ] ) ; NEW_LINE DEDENT v . sort ( ) ; NEW_LINE x = 0 NEW_LINE for j in range ( i , n , k ) : NEW_LINE INDENT arr [ j ] = v [ x ] ; NEW_LINE x += 1 NEW_LINE DEDENT v = [ ] NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT arr = [ 4 , 2 , 3 , 7 , 6 ] NEW_LINE K = 2 ; NEW_LINE n = len ( arr ) NEW_LINE if ( fun ( arr , n , K ) ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " no " ) NEW_LINE DEDENT
Sort an Array based on the absolute difference of adjacent elements | Function that arrange the array such that all absolute difference between adjacent element are sorted ; To store the resultant array ; Sorting the given array in ascending order ; Variable to represent left and right ends of the given array ; Traversing the answer array in reverse order and arrange the array elements from arr [ ] in reverse order ; Inserting elements in zig - zag manner ; Displaying the resultant array ; Driver Code ; Function Call
def sortedAdjacentDifferences ( arr , n ) : NEW_LINE INDENT ans = [ 0 ] * n NEW_LINE arr = sorted ( arr ) NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT ans [ i ] = arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans [ i ] = arr [ r ] NEW_LINE r -= 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( ans [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , - 2 , 4 , 8 , 6 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE sortedAdjacentDifferences ( arr , n ) NEW_LINE DEDENT
Minimum steps to convert an Array into permutation of numbers from 1 to N | Function to find minimum number of steps to convert a given sequence into a permutation ; Sort the given array ; To store the required minimum number of operations ; Find the operations on each step ; Return the answer ; Driver code ; Function call
def get_permutation ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT result += abs ( arr [ i ] - ( i + 1 ) ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 2 , 3 , 4 , 1 , 6 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( get_permutation ( arr , n ) ) NEW_LINE DEDENT
Minimum increment or decrement required to sort the array | Top | Python3 program of the above approach ; Dp array to memoized the value recursive call ; Function to find the minimum increment or decrement needed to make the array sorted ; If only one element is present , then arr [ ] is sorted ; If dp [ N ] [ maxE ] is precalculated , then return the result ; Iterate from minE to maxE which placed at previous index ; Update the answer according to recurrence relation ; Memoized the value for dp [ N ] [ maxE ] ; Return the final result ; Driver Code ; Find the minimum and maximum element from the arr [ ] ; Function Call
import sys NEW_LINE dp = [ [ 0 for x in range ( 1000 ) ] for y in range ( 1000 ) ] NEW_LINE def minimumIncDec ( arr , N , maxE , minE ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ N ] [ maxE ] ) : NEW_LINE INDENT return dp [ N ] [ maxE ] NEW_LINE DEDENT ans = sys . maxsize NEW_LINE for k in range ( minE , maxE + 1 ) : NEW_LINE INDENT x = minimumIncDec ( arr , N - 1 , k , minE ) NEW_LINE ans = min ( ans , x + abs ( arr [ N - 1 ] - k ) ) NEW_LINE DEDENT dp [ N ] [ maxE ] = ans NEW_LINE return dp [ N ] [ maxE ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE minE = min ( arr ) NEW_LINE maxE = max ( arr ) NEW_LINE print ( minimumIncDec ( arr , N , maxE , minE ) ) NEW_LINE DEDENT
Sort the major diagonal of the matrix | Function to sort the major diagonal of the matrix ; Loop to find the ith minimum element from the major diagonal ; Loop to find the minimum element from the unsorted matrix ; Swap to put the minimum element at the beginning of the major diagonal of matrix ; Loop to print the matrix ; Driven Code ; Sort the major Diagonal
def sortDiagonal ( a , M , N ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT sm = a [ i ] [ i ] NEW_LINE pos = i NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( sm > a [ j ] [ j ] ) : NEW_LINE INDENT sm = a [ j ] [ j ] NEW_LINE pos = j NEW_LINE DEDENT DEDENT a [ i ] [ i ] , a [ pos ] [ pos ] = a [ pos ] [ pos ] , a [ i ] [ i ] NEW_LINE DEDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT a = [ [ 4 , 2 ] , [ 3 , 1 ] ] NEW_LINE sortDiagonal ( a , 2 , 2 ) NEW_LINE
Minimum cost to make an Array a permutation of first N natural numbers | Function to calculate minimum cost for making permutation of size N ; sorting the array in ascending order ; To store the required answer ; Traverse the whole array ; Return the required answer ; Driver code ; Function call
def make_permutation ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += abs ( i + 1 - arr [ i ] ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 8 , 1 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( make_permutation ( arr , n ) ) ; NEW_LINE DEDENT
Find maximum sum from top to bottom row with no adjacent diagonal elements | Function to find the maximum path sum from top to bottom row ; Create an auxiliary array of next row with the element and it 's position ; Sort the auxiliary array ; Find maximum from row above to be added to the current element ; Find the maximum element from the next row that can be added to current row element ; Find the maximum sum ; Driver Code ; Function to find maximum path
def maxSum ( V , n , m ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT aux = [ ] NEW_LINE for j in range ( m ) : NEW_LINE INDENT aux . append ( [ V [ i + 1 ] [ j ] , j ] ) NEW_LINE DEDENT aux = sorted ( aux ) NEW_LINE aux = aux [ : : - 1 ] NEW_LINE for j in range ( m ) : NEW_LINE INDENT for k in range ( m ) : NEW_LINE INDENT if ( aux [ k ] [ 1 ] - j == 0 or abs ( aux [ k ] [ 1 ] - j ) > 1 ) : NEW_LINE INDENT V [ i ] [ j ] += aux [ k ] [ 0 ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( m ) : NEW_LINE INDENT ans = max ( ans , V [ 0 ] [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT V = [ [ 1 , 2 , 3 , 4 ] , [ 8 , 7 , 6 , 5 ] , [ 10 , 11 , 12 , 13 ] ] NEW_LINE n = len ( V ) NEW_LINE m = len ( V [ 0 ] ) NEW_LINE print ( maxSum ( V , n , m ) ) NEW_LINE DEDENT
Count numbers whose maximum sum of distinct digit | Function to find the digit - sum of a number ; Loop to iterate the number digit - wise to find digit - sum ; variable to store last digit ; Function to find the count of number ; Vector to store the Sum of Digits ; Sum of digits for each element in vector ; Sorting the digitSum vector ; Removing the duplicate elements ; Count variable to store the Count ; Finding the Count of Numbers ; Driver Code ; Function Call
def SumofDigits ( digit ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( digit != 0 ) : NEW_LINE INDENT rem = digit % 10 NEW_LINE sum += rem NEW_LINE digit //= 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT def findCountofNumbers ( arr , n , M ) : NEW_LINE INDENT SumDigits = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = SumofDigits ( arr [ i ] ) NEW_LINE SumDigits . append ( s ) NEW_LINE DEDENT SumDigits . sort ( ) NEW_LINE ip = list ( set ( SumDigits ) ) NEW_LINE count = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( len ( SumDigits ) ) : NEW_LINE INDENT if ( sum > M ) : NEW_LINE INDENT break NEW_LINE DEDENT sum += SumDigits [ i ] NEW_LINE if ( sum <= M ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 45 , 16 , 17 , 219 , 32 , 22 ] NEW_LINE M = 10 NEW_LINE n = len ( arr ) NEW_LINE print ( findCountofNumbers ( arr , n , M ) ) NEW_LINE DEDENT
Minimum sum of product of elements of pairs of the given array | Function to find the minimum product ; Sort the array using STL sort ( ) function ; Initialise product to 1 ; Find product of sum of all pairs ; Return the product ; Driver code ; Function call to find product
def minimumProduct ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE product = 1 NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT product *= ( arr [ i ] + arr [ i + 1 ] ) NEW_LINE DEDENT return product NEW_LINE DEDENT arr = [ 1 , 6 , 3 , 1 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minimumProduct ( arr , n ) ) NEW_LINE
Minimum removals required to make ranges non | ; Sort by minimum starting point ; If the current starting point is less than the previous interval 's ending point (ie. there is an overlap) ; Increase rem ; Remove the interval with the higher ending point ; Driver Code
def minRemovels ( ranges ) : NEW_LINE INDENT size = len ( ranges ) NEW_LINE rem = 0 NEW_LINE ranges . sort ( ) NEW_LINE end = ranges [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT if ( ranges [ i ] [ 0 ] < end ) : NEW_LINE INDENT rem += 1 NEW_LINE end = min ( ranges [ i ] [ 1 ] , end ) NEW_LINE DEDENT else : NEW_LINE INDENT end = ranges [ i ] [ 1 ] NEW_LINE DEDENT DEDENT return rem NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Input = [ [ 19 , 25 ] , [ 10 , 20 ] , [ 16 , 20 ] ] NEW_LINE print ( minRemovels ( Input ) ) NEW_LINE DEDENT
Check if elements of array can be arranged in AP , GP or HP | Returns true if arr [ 0. . n - 1 ] can form AP ; Base Case ; Sort array ; After sorting , difference between consecutive elements must be same . ; Traverse the given array and check if the difference between ith element and ( i - 1 ) th element is same or not ; Returns true if arr [ 0. . n - 1 ] can form GP ; Base Case ; Sort array ; After sorting , common ratio between consecutive elements must be same . ; Traverse the given array and check if the common ratio between ith element and ( i - 1 ) th element is same or not ; Returns true if arr [ 0. . n - 1 ] can form HP ; Base Case ; Find reciprocal of arr [ ] ; After finding reciprocal , check if the reciprocal is in A . P . To check for A . P . ; Driver Code ; Function to check AP ; Function to check GP ; Function to check HP
def checkIsAP ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE d = arr [ 1 ] - arr [ 0 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] != d ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def checkIsGP ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT arr . sort ( ) NEW_LINE r = arr [ 1 ] / arr [ 0 ] NEW_LINE for i in range ( 2 , n ) : NEW_LINE INDENT if ( arr [ i ] / arr [ i - 1 ] != r ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def checkIsHP ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return True NEW_LINE DEDENT rec = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT rec . append ( ( 1 / arr [ i ] ) ) NEW_LINE DEDENT if ( checkIsAP ( rec , n ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT arr = [ 1.0 / 5.0 , 1.0 / 10.0 , 1.0 / 15.0 , 1.0 / 20.0 ] NEW_LINE n = len ( arr ) NEW_LINE flag = 0 NEW_LINE if ( checkIsAP ( arr , n ) ) : NEW_LINE INDENT print ( " Yes , ▁ An ▁ AP ▁ can ▁ be ▁ formed " , end = ' ' ) NEW_LINE flag = 1 NEW_LINE DEDENT if ( checkIsGP ( arr , n ) ) : NEW_LINE INDENT print ( " Yes , ▁ A ▁ GP ▁ can ▁ be ▁ formed " , end = ' ' ) NEW_LINE flag = 1 NEW_LINE DEDENT if ( checkIsHP ( arr , n ) ) : NEW_LINE INDENT print ( " Yes , ▁ A ▁ HP ▁ can ▁ be ▁ formed " , end = ' ' ) NEW_LINE flag = 1 NEW_LINE DEDENT elif ( flag == 0 ) : NEW_LINE INDENT print ( " No " , end = ' ' ) NEW_LINE DEDENT
Sort the Array by reversing the numbers in it | Function to return the reverse of n ; Function to sort the array according to the reverse of elements ; Vector to store the reverse with respective elements ; Inserting reverse with elements in the vector pair ; Sort the vector , this will sort the pair according to the reverse of elements ; Print the sorted vector content ; Driver code
def reversDigits ( num ) : NEW_LINE INDENT rev_num = 0 ; NEW_LINE while ( num > 0 ) : NEW_LINE INDENT rev_num = rev_num * 10 + num % 10 ; NEW_LINE num = num // 10 ; NEW_LINE DEDENT return rev_num ; NEW_LINE DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT vp = [ ] ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( ( reversDigits ( arr [ i ] ) , arr [ i ] ) ) ; NEW_LINE DEDENT vp . sort ( ) NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT print ( vp [ i ] [ 1 ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 10 , 102 , 31 , 15 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sortArr ( arr , n ) ; NEW_LINE DEDENT
Count number of pairs with positive sum in an array | Returns number of pairs in arr [ 0. . n - 1 ] with positive sum ; Sort the array in increasing order ; Intialise result ; Intialise first and second pointer ; Till the pointers doesn 't converge traverse array to count the pairs ; If sum of arr [ i ] && arr [ j ] > 0 , then the count of pairs with positive sum is the difference between the two pointers ; Increase the count ; Driver 's Code ; Function call to count the pairs with positive sum
def CountPairs ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 0 ; NEW_LINE l = 0 ; r = n - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( arr [ l ] + arr [ r ] > 0 ) : NEW_LINE INDENT count += ( r - l ) ; NEW_LINE r -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 7 , - 1 , 3 , 2 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( CountPairs ( arr , n ) ) ; NEW_LINE DEDENT
Sort the given Matrix | Memory Efficient Approach | Function to sort the matrix ; Number of elements in matrix ; Loop to sort the matrix using Bubble Sort ; Condition to check if the Adjacent elements ; Swap if previous value is greater ; Loop to print the matrix ; Driver Code ; Function call to sort ; Function call to print matrix
def sortMat ( data , row , col ) : NEW_LINE INDENT size = row * col NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT for j in range ( 0 , size - 1 ) : NEW_LINE INDENT if ( data [ j // col ] [ j % col ] > data [ ( j + 1 ) // col ] [ ( j + 1 ) % col ] ) : NEW_LINE INDENT temp = data [ j // col ] [ j % col ] NEW_LINE data [ j // col ] [ j % col ] = data [ ( j + 1 ) // col ] [ ( j + 1 ) % col ] NEW_LINE data [ ( j + 1 ) // col ] [ ( j + 1 ) % col ] = temp NEW_LINE DEDENT DEDENT DEDENT DEDENT def printMat ( mat , row , col ) : NEW_LINE INDENT for i in range ( row ) : NEW_LINE INDENT for j in range ( col ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 5 , 4 , 7 ] , [ 1 , 3 , 8 ] , [ 2 , 9 , 6 ] ] NEW_LINE row = len ( mat ) NEW_LINE col = len ( mat [ 0 ] ) NEW_LINE sortMat ( mat , row , col ) NEW_LINE printMat ( mat , row , col ) NEW_LINE DEDENT
Partition the array into two odd length groups with minimized absolute difference between their median | Function to find minimise the median between partition array ; Sort the given array arr [ ] ; Return the difference of two middle element of the arr [ ] ; Driver Code ; Size of arr [ ] ; Function that returns the minimum the absolute difference between median of partition array
def minimiseMedian ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE ans = abs ( arr [ n // 2 ] - arr [ ( n // 2 ) - 1 ] ) ; NEW_LINE return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 15 , 25 , 35 , 50 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minimiseMedian ( arr , n ) ) ; NEW_LINE DEDENT
Maximum number of overlapping Intervals | Function that prmaximum overlap among ranges ; variable to store the maximum count ; storing the x and y coordinates in data vector ; pushing the x coordinate ; pushing the y coordinate ; sorting of ranges ; Traverse the data vector to count number of overlaps ; if x occur it means a new range is added so we increase count ; if y occur it means a range is ended so we decrease count ; updating the value of ans after every traversal ; printing the maximum value ; Driver code
def overlap ( v ) : NEW_LINE INDENT ans = 0 NEW_LINE count = 0 NEW_LINE data = [ ] NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT data . append ( [ v [ i ] [ 0 ] , ' x ' ] ) NEW_LINE data . append ( [ v [ i ] [ 1 ] , ' y ' ] ) NEW_LINE DEDENT data = sorted ( data ) NEW_LINE for i in range ( len ( data ) ) : NEW_LINE INDENT if ( data [ i ] [ 1 ] == ' x ' ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( data [ i ] [ 1 ] == ' y ' ) : NEW_LINE INDENT count -= 1 NEW_LINE DEDENT ans = max ( ans , count ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT v = [ [ 1 , 2 ] , [ 2 , 4 ] , [ 3 , 6 ] ] NEW_LINE overlap ( v ) NEW_LINE
Making three numbers equal with the given operations | Function that returns true if a , b and c can be made equal with the given operations ; Sort the three numbers ; Find the sum of difference of the 3 rd and 2 nd element and the 3 rd and 1 st element ; Subtract the difference from k ; Check the required condition ; Driver code
def canBeEqual ( a , b , c , k ) : NEW_LINE INDENT arr = [ 0 ] * 3 ; NEW_LINE arr [ 0 ] = a ; NEW_LINE arr [ 1 ] = b ; NEW_LINE arr [ 2 ] = c ; NEW_LINE arr . sort ( ) NEW_LINE diff = 2 * arr [ 2 ] - arr [ 1 ] - arr [ 0 ] ; NEW_LINE k = k - diff ; NEW_LINE if ( k < 0 or k % 3 != 0 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a1 = 6 ; b1 = 3 ; c1 = 2 ; k1 = 7 ; NEW_LINE if ( canBeEqual ( a1 , b1 , c1 , k1 ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Arrange numbers to form a valid sequence | Function to organize the given numbers to form a valid sequence . ; Sorting the array ; Two pointer technique to organize the numbers ; Driver code
def orgazineInOrder ( vec , op , n ) : NEW_LINE INDENT result = [ 0 ] * n ; NEW_LINE vec . sort ( ) ; NEW_LINE i = 0 ; NEW_LINE j = n - 1 ; NEW_LINE k = 0 ; NEW_LINE while ( i <= j and k <= n - 2 ) : NEW_LINE INDENT if ( op [ k ] == ' < ' ) : NEW_LINE INDENT result [ k ] = vec [ i ] ; NEW_LINE i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT result [ k ] = vec [ j ] ; NEW_LINE j -= 1 ; NEW_LINE DEDENT k += 1 ; NEW_LINE DEDENT result [ n - 1 ] = vec [ i ] ; NEW_LINE return result ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT vec = [ 8 , 2 , 7 , 1 , 5 , 9 ] ; NEW_LINE op = [ ' > ' , ' > ' , ' < ' , ' > ' , ' < ' ] ; NEW_LINE result = orgazineInOrder ( vec , op , len ( vec ) ) ; NEW_LINE for i in range ( len ( result ) ) : NEW_LINE INDENT print ( result [ i ] , end = " ▁ " ) ; NEW_LINE DEDENT DEDENT
Find the distance between two person after reconstruction of queue | Function to find the correct order and then return the distance between the two persons ; Make pair of both height & infront and insert to vector ; Sort the vector in ascending order ; Find the correct place for every person ; Insert into position vector according to infront value ; Driver code
def getDistance ( arr , n , a , b ) : NEW_LINE INDENT vp = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT vp . append ( [ arr [ i ] [ 0 ] , arr [ i ] [ 1 ] ] ) NEW_LINE DEDENT vp = sorted ( vp ) NEW_LINE pos = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( len ( vp ) ) : NEW_LINE INDENT height = vp [ i ] [ 0 ] NEW_LINE k = vp [ i ] [ 1 ] NEW_LINE pos [ k ] = height NEW_LINE DEDENT first = - 1 NEW_LINE second = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( pos [ i ] == a ) : NEW_LINE INDENT first = i NEW_LINE DEDENT if ( pos [ i ] == b ) : NEW_LINE INDENT second = i NEW_LINE DEDENT DEDENT return abs ( first - second ) NEW_LINE DEDENT arr = [ [ 5 , 0 ] , [ 3 , 0 ] , [ 2 , 0 ] , [ 6 , 4 ] , [ 1 , 0 ] , [ 4 , 3 ] ] NEW_LINE n = len ( arr ) NEW_LINE a = 6 NEW_LINE b = 5 NEW_LINE print ( getDistance ( arr , n , a , b ) ) NEW_LINE
Minimize the sum of differences of consecutive elements after removing exactly K elements | function to find minimum sum ; variable to store final answer and initialising it with the values when 0 elements is removed from the left and K from the right . ; loop to simulate removal of elements ; removing i elements from the left and and K - i elements from the right and updating the answer correspondingly ; returning final answer ; Driver code ; input values ; calling the required function ;
def findSum ( arr , n , k ) : NEW_LINE INDENT ans = arr [ n - k - 1 ] - arr [ 0 ] ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT ans = min ( arr [ n - 1 - ( k - i ) ] - arr [ i ] , ans ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 100 , 120 , 140 ] ; NEW_LINE k = 2 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findSum ( arr , n , k ) ) ; NEW_LINE DEDENT
Minimum elements to be removed from the ends to make the array sorted | Function to return the minimum number of elements to be removed from the ends of the array to make it sorted ; To store the final answer ; Two pointer loop ; While the array is increasing increment j ; Updating the ans ; Updating the left pointer ; Returning the final answer ; Driver code
def findMin ( arr , n ) : NEW_LINE INDENT ans = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( j < n and arr [ j ] >= arr [ j - 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT ans = max ( ans , j - i ) NEW_LINE i = j - 1 NEW_LINE DEDENT return n - ans NEW_LINE DEDENT arr = [ 3 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMin ( arr , n ) ) NEW_LINE
Number of subsequences of maximum length K containing no repeated elements | Returns number of subsequences of maximum length k and contains no repeated element ; Sort the array a [ ] ; Store the frequencies of all the distinct element in the vector arr ; count is the the number of such subsequences ; Create a 2 - d array dp [ n + 1 ] [ m + 1 ] to store the intermediate result ; Initialize the first row to 1 ; Update the dp [ ] [ ] array based on the recurrence relation ; Return the number of subsequences ; Driver code
def countSubSeq ( a , n , k ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE arr = [ ] NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT count = 1 NEW_LINE x = a [ i ] NEW_LINE i += 1 NEW_LINE while ( i < n and a [ i ] == x ) : NEW_LINE INDENT count += 1 NEW_LINE i += 1 NEW_LINE DEDENT arr . append ( count ) NEW_LINE DEDENT m = len ( arr ) NEW_LINE n = min ( m , k ) NEW_LINE count = 1 NEW_LINE dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT j = m NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( j > m - i ) : NEW_LINE INDENT dp [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j + 1 ] + arr [ j ] * dp [ i - 1 ] [ j + 1 ] NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT count = count + dp [ i ] [ 0 ] NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 2 , 2 , 3 , 3 , 5 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE print ( countSubSeq ( a , n , k ) ) NEW_LINE DEDENT
Find the count of unvisited indices in an infinite array | Function to return the count of unvisited indices starting from the index 0 ; Largest index that cannot be visited ; Push the index to the queue ; To store the required count ; Current index that cannot be visited ; Increment the count for the current index ; ( curr - m ) and ( curr - n ) are also unreachable if they are valid indices ; Return the required count ; Driver code
def countUnvisited ( n , m ) : NEW_LINE INDENT i = 0 NEW_LINE X = ( m * n ) - m - n NEW_LINE queue = [ ] NEW_LINE queue . append ( X ) NEW_LINE count = 0 NEW_LINE while ( len ( queue ) > 0 ) : NEW_LINE INDENT curr = queue [ 0 ] NEW_LINE queue . remove ( queue [ 0 ] ) NEW_LINE count += 1 NEW_LINE if ( curr - m > 0 ) : NEW_LINE INDENT queue . append ( curr - m ) NEW_LINE DEDENT if ( curr - n > 0 ) : NEW_LINE INDENT queue . append ( curr - n ) NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE m = 5 NEW_LINE print ( countUnvisited ( n , m ) ) NEW_LINE DEDENT
Check whether the string S1 can be made equal to S2 with the given operation | Function to return the string formed by the odd indexed characters of s ; Function to return the string formed by the even indexed characters of s ; Function that returns true if s1 can be made equal to s2 with the given operation ; Get the string formed by the even indexed characters of s1 ; Get the string formed by the even indexed characters of s2 ; Get the string formed by the odd indexed characters of s1 ; Get the string formed by the odd indexed characters of s2 ; Sorting all the lists ; If the strings can be made equal ; Driver code
def partOdd ( s ) : NEW_LINE INDENT odd = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if i % 2 != 0 : NEW_LINE INDENT odd . append ( s [ i ] ) NEW_LINE DEDENT DEDENT return odd NEW_LINE DEDENT def partEven ( s ) : NEW_LINE INDENT even = [ ] NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT even . append ( s [ i ] ) NEW_LINE DEDENT DEDENT return even NEW_LINE DEDENT def canBeMadeEqual ( s1 , s2 ) : NEW_LINE INDENT even_s1 = partEven ( s1 ) NEW_LINE even_s2 = partEven ( s2 ) NEW_LINE odd_s1 = partOdd ( s1 ) NEW_LINE odd_s2 = partOdd ( s2 ) NEW_LINE even_s1 . sort ( ) NEW_LINE even_s2 . sort ( ) NEW_LINE odd_s1 . sort ( ) NEW_LINE odd_s2 . sort ( ) NEW_LINE if even_s1 == even_s2 and odd_s1 == odd_s2 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT s1 = " cdab " NEW_LINE s2 = " abcd " NEW_LINE if canBeMadeEqual ( s1 , s2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
Sort the given stack elements based on their modulo with K | Function to sort the stack using another stack based on the values of elements modulo k ; Pop out the first element ; While temporary stack is not empty ; The top of the stack modulo k is greater than ( temp & k ) or if they are equal then compare the values ; Pop from temporary stack and push it to the input stack ; Push temp in temporary of stack ; Push all the elements in the original stack to get the ascending order ; Print the sorted elements ; Driver code
def sortStack ( input1 , k ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while ( len ( input1 ) != 0 ) : NEW_LINE INDENT tmp = input1 [ - 1 ] NEW_LINE input1 . pop ( ) NEW_LINE while ( len ( tmpStack ) != 0 ) : NEW_LINE INDENT tmpStackMod = tmpStack [ - 1 ] % k NEW_LINE tmpMod = tmp % k NEW_LINE if ( ( tmpStackMod > tmpMod ) or ( tmpStackMod == tmpMod and tmpStack [ - 1 ] > tmp ) ) : NEW_LINE INDENT input1 . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT tmpStack . append ( tmp ) NEW_LINE DEDENT while ( len ( tmpStack ) != 0 ) : NEW_LINE INDENT input1 . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT while ( len ( input1 ) != 0 ) : NEW_LINE INDENT print ( input1 [ - 1 ] , end = " ▁ " ) NEW_LINE input1 . pop ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT input1 = [ ] NEW_LINE input1 . append ( 10 ) NEW_LINE input1 . append ( 3 ) NEW_LINE input1 . append ( 2 ) NEW_LINE input1 . append ( 6 ) NEW_LINE input1 . append ( 12 ) NEW_LINE k = 4 NEW_LINE sortStack ( input1 , k ) NEW_LINE DEDENT
Longest sub | Function to return the length of the largest subsequence with non - negative sum ; To store the current sum ; Sort the input array in non - increasing order ; Traverse through the array ; Add the current element to the sum ; Condition when c_sum falls below zero ; Complete array has a non - negative sum ; Driver code
def maxLen ( arr , n ) : NEW_LINE INDENT c_sum = 0 ; NEW_LINE arr . sort ( reverse = True ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT c_sum += arr [ i ] ; NEW_LINE if ( c_sum < 0 ) : NEW_LINE INDENT return i ; NEW_LINE DEDENT DEDENT return n ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 5 , - 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxLen ( arr , n ) ) ; NEW_LINE DEDENT
Find Partition Line such that sum of values on left and right is equal | Python3 implementation of the approach ; Function that returns true if the required line exists ; To handle negative values from x [ ] ; Update arr [ ] such that arr [ i ] contains the sum of all v [ j ] such that x [ j ] = i for all valid values of j ; Update arr [ i ] such that arr [ i ] contains the sum of the subarray arr [ 0. . . i ] from the original array ; If all the points add to 0 then the line can be drawn anywhere ; If the line is drawn touching the leftmost possible points ; If the line is drawn just before the current point ; If the line is drawn touching the current point ; If the line is drawn just after the current point ; If the line is drawn touching the rightmost possible points ; Driver code
MAX = 1000 ; NEW_LINE def lineExists ( x , y , v , n ) : NEW_LINE INDENT size = ( 2 * MAX ) + 1 ; NEW_LINE arr = [ 0 ] * size ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ x [ i ] + MAX ] += v [ i ] ; NEW_LINE DEDENT for i in range ( 1 , size ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] ; NEW_LINE DEDENT if ( arr [ size - 1 ] == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( arr [ size - 1 ] - arr [ 0 ] == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT for i in range ( 1 , size - 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] == arr [ size - 1 ] - arr [ i - 1 ] ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( arr [ i - 1 ] == arr [ size - 1 ] - arr [ i ] ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( arr [ i ] == arr [ size - 1 ] - arr [ i ] ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT if ( arr [ size - 2 ] == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return False ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = [ - 3 , 5 , 8 ] ; NEW_LINE y = [ 8 , 7 , 9 ] ; NEW_LINE v = [ 8 , 2 , 10 ] ; NEW_LINE n = len ( x ) ; NEW_LINE if ( lineExists ( x , y , v , n ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT
Maximum sum of minimums of pairs in an array | Function to return the maximum required sum of the pairs ; Sort the array ; To store the sum ; Start making pairs of every two consecutive elements as n is even ; Minimum element of the current pair ; Return the maximum possible sum ; Driver code
def maxSum ( a , n ) : NEW_LINE INDENT a . sort ( ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( 0 , n - 1 , 2 ) : NEW_LINE INDENT sum += a [ i ] ; NEW_LINE DEDENT return sum ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 1 , 4 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( maxSum ( arr , n ) ) ; NEW_LINE DEDENT
Sort elements by modulo with K | Utility function to prthe contents of an array ; Function to sort the array elements based on their modulo with K ; Create K empty vectors ; Update the vectors such that v [ i ] will contain all the elements that give remainder as i when divided by k ; Sorting all the vectors separately ; Replacing the elements in arr [ ] with the required modulo sorted elements ; Add all the elements of the current vector to the array ; Print the sorted 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 sortWithRemainder ( arr , n , k ) : NEW_LINE INDENT v = [ [ ] for i in range ( k ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT v [ arr [ i ] % k ] . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT v [ i ] . sort ( ) NEW_LINE DEDENT j = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT for it in v [ i ] : NEW_LINE INDENT arr [ j ] = it NEW_LINE j += 1 NEW_LINE DEDENT DEDENT printArr ( arr , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 10 , 7 , 2 , 6 , 12 , 3 , 33 , 46 ] NEW_LINE n = len ( arr ) NEW_LINE k = 4 NEW_LINE sortWithRemainder ( arr , n , k ) NEW_LINE DEDENT
Minimum increment operations to make K elements equal | Function to return the minimum number of increment operations required to make any k elements of the array equal ; Sort the array in increasing order ; Calculate the number of operations needed to make 1 st k elements equal to the kth element i . e . the 1 st window ; Answer will be the minimum of all possible k sized windows ; Find the operations needed to make k elements equal to ith element ; Slide the window to the right and subtract increments spent on leftmost element of the previous window ; Add increments needed to make the 1 st k - 1 elements of this window equal to the kth element of the current window ; Driver code
def minOperations ( ar , k ) : NEW_LINE INDENT ar = sorted ( ar ) NEW_LINE opsNeeded = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT opsNeeded += ar [ k - 1 ] - ar [ i ] NEW_LINE DEDENT ans = opsNeeded NEW_LINE for i in range ( k , len ( ar ) ) : NEW_LINE INDENT opsNeeded = opsNeeded - ( ar [ i - 1 ] - ar [ i - k ] ) NEW_LINE opsNeeded += ( k - 1 ) * ( ar [ i ] - ar [ i - 1 ] ) NEW_LINE ans = min ( ans , opsNeeded ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 1 , 9 , 100 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( minOperations ( arr , k ) ) NEW_LINE
Lexicographical ordering using Heap Sort | Used for index in heap ; Predefining the heap array ; Defining formation of the heap ; Iterative heapiFy ; Just swapping if the element is smaller than already stored element ; Swapping the current index with its child ; Moving upward in the heap ; Defining heap sort ; Taking output of the minimum element ; Set first element as a last one ; Decrement of the size of the string ; Initializing the left and right index ; Process of heap sort If root element is minimum than its both of the child then break ; Otherwise checking that the child which one is smaller , swap them with parent element ; Swapping ; Changing the left index and right index ; Utility function ; To heapiFy ; Calling heap sort function ; Driver Code
x = - 1 ; NEW_LINE heap = [ 0 ] * 1000 ; NEW_LINE def heapForm ( k ) : NEW_LINE INDENT global x ; NEW_LINE x += 1 ; NEW_LINE heap [ x ] = k ; NEW_LINE child = x ; NEW_LINE index = x // 2 ; NEW_LINE while ( index >= 0 ) : NEW_LINE INDENT if ( heap [ index ] > heap [ child ] ) : NEW_LINE INDENT tmp = heap [ index ] ; NEW_LINE heap [ index ] = heap [ child ] ; NEW_LINE heap [ child ] = tmp ; NEW_LINE child = index ; NEW_LINE index = index // 2 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT DEDENT def heapSort ( ) : NEW_LINE INDENT global x ; NEW_LINE while ( x >= 0 ) : NEW_LINE INDENT k = heap [ 0 ] ; NEW_LINE print ( k , end = " ▁ " ) ; NEW_LINE heap [ 0 ] = heap [ x ] ; NEW_LINE x = x - 1 ; NEW_LINE tmp = - 1 ; NEW_LINE index = 0 ; NEW_LINE length = x ; NEW_LINE left1 = 1 ; NEW_LINE right1 = left1 + 1 ; NEW_LINE while ( left1 <= length ) : NEW_LINE INDENT if ( heap [ index ] <= heap [ left1 ] and heap [ index ] <= heap [ right1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT else : NEW_LINE INDENT if ( heap [ left1 ] < heap [ right1 ] ) : NEW_LINE INDENT tmp = heap [ index ] ; NEW_LINE heap [ index ] = heap [ left1 ] ; NEW_LINE heap [ left1 ] = tmp ; NEW_LINE index = left1 ; NEW_LINE DEDENT else : NEW_LINE INDENT tmp = heap [ index ] ; NEW_LINE heap [ index ] = heap [ right1 ] ; NEW_LINE heap [ right1 ] = tmp ; NEW_LINE index = right1 ; NEW_LINE DEDENT DEDENT left1 = 2 * left1 ; NEW_LINE right1 = left1 + 1 ; NEW_LINE DEDENT DEDENT DEDENT def sort ( k , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT heapForm ( k [ i ] ) ; NEW_LINE DEDENT heapSort ( ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " banana " , " orange " , " apple " , " pineapple " , " berries " , " lichi " ] ; NEW_LINE n = len ( arr ) ; NEW_LINE sort ( arr , n ) ; NEW_LINE DEDENT
Find Kth element in an array containing odd elements first and then even elements | Function to return the kth element in the modified array ; First odd number ; Insert the odd number ; Next odd number ; First even number ; Insert the even number ; Next even number ; Return the kth element ; Driver code
def getNumber ( n , k ) : NEW_LINE INDENT arr = [ 0 ] * n ; NEW_LINE i = 0 ; NEW_LINE odd = 1 ; NEW_LINE while ( odd <= n ) : NEW_LINE INDENT arr [ i ] = odd ; NEW_LINE i += 1 ; NEW_LINE odd += 2 ; NEW_LINE DEDENT even = 2 ; NEW_LINE while ( even <= n ) : NEW_LINE INDENT arr [ i ] = even ; NEW_LINE i += 1 ; NEW_LINE even += 2 ; NEW_LINE DEDENT return arr [ k - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 ; NEW_LINE k = 5 ; NEW_LINE print ( getNumber ( n , k ) ) ; NEW_LINE DEDENT
Swap Alternate Boundary Pairs | Utility function to print the contents of an array ; Function to update the array ; Initialize the pointers ; While there are elements to swap ; Update the pointers ; 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 UpdateArr ( arr , n ) : NEW_LINE INDENT i = 0 ; NEW_LINE j = n - 1 ; NEW_LINE while ( i < j ) : NEW_LINE INDENT temp = arr [ i ] ; NEW_LINE arr [ i ] = arr [ j ] ; NEW_LINE arr [ j ] = temp ; NEW_LINE i += 2 ; NEW_LINE j -= 2 ; NEW_LINE DEDENT printArr ( arr , n ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE UpdateArr ( arr , n ) ; NEW_LINE DEDENT
Count permutation such that sequence is non decreasing | Python3 implementation of the approach ; To store the factorials ; Function to update fact [ ] array such that fact [ i ] = i ! ; 0 ! = 1 ; i ! = i * ( i - 1 ) ! ; Function to return the count of possible permutations ; To store the result ; Sort the array ; Initial size of the block ; Increase the size of block ; Update the result for the previous block ; Reset the size to 1 ; Update the result for the last block ; Driver code ; Pre - calculating factorials
N = 20 NEW_LINE fact = [ 0 ] * N ; NEW_LINE def pre ( ) : NEW_LINE INDENT fact [ 0 ] = 1 ; NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT fact [ i ] = i * fact [ i - 1 ] ; NEW_LINE DEDENT DEDENT def CountPermutation ( a , n ) : NEW_LINE INDENT ways = 1 ; NEW_LINE a . sort ( ) ; NEW_LINE size = 1 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( a [ i ] == a [ i - 1 ] ) : NEW_LINE INDENT size += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ways *= fact [ size ] ; NEW_LINE size = 1 ; NEW_LINE DEDENT DEDENT ways *= fact [ size ] ; NEW_LINE return ways ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 4 , 4 , 2 , 4 ] ; NEW_LINE n = len ( a ) ; NEW_LINE pre ( ) ; NEW_LINE print ( CountPermutation ( a , n ) ) ; NEW_LINE DEDENT
Smallest element greater than X not present in the array | Function to return the smallest element greater than x which is not present in a [ ] ; Sort the array ; Continue until low is less than or equals to high ; Find mid ; If element at mid is less than or equals to searching element ; If mid is equals to searching element ; Increment searching element ; Make high as N - 1 ; Make low as mid + 1 ; Make high as mid - 1 ; Return the next greater element ; Driver code
def Next_greater ( a , n , x ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE low , high , ans = 0 , n - 1 , x + 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( a [ mid ] <= ans ) : NEW_LINE INDENT if ( a [ mid ] == ans ) : NEW_LINE INDENT ans += 1 NEW_LINE high = n - 1 NEW_LINE DEDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT a = [ 1 , 5 , 10 , 4 , 7 ] NEW_LINE x = 4 NEW_LINE n = len ( a ) NEW_LINE print ( Next_greater ( a , n , x ) ) NEW_LINE
Alternate XOR operations on sorted array | Python 3 implementation of the approach ; Function to find the maximum and the minimum elements from the array after performing the given operation k times ; To store the current sequence of elements ; To store the next sequence of elements after xoring with current elements ; Store the frequency of elements of arr [ ] in arr1 [ ] ; Storing all precomputed XOR values so that we don 't have to do it again and again as XOR is a costly operation ; Perform the operations k times ; The value of count decide on how many elements we have to apply XOR operation ; If current element is present in the array to be modified ; Suppose i = m and arr1 [ i ] = num , it means ' m ' appears ' num ' times If the count is even we have to perform XOR operation on alternate ' m ' starting from the 0 th index because count is even and we have to perform XOR operations starting with initial ' m ' Hence there will be ceil ( num / 2 ) operations on ' m ' that will change ' m ' to xor_val [ m ] i . e . m ^ x ; Decrease the frequency of ' m ' from arr1 [ ] ; Increase the frequency of ' m ^ x ' in arr2 [ ] ; If the count is odd we have to perform XOR operation on alternate ' m ' starting from the 1 st index because count is odd and we have to leave the 0 th ' m ' Hence there will be ( num / 2 ) XOR operations on ' m ' that will change ' m ' to xor_val [ m ] i . e . m ^ x ; Updating the count by frequency of the current elements as we have processed that many elements ; Updating arr1 [ ] which will now store the next sequence of elements At this time , arr1 [ ] stores the remaining ' m ' on which XOR was not performed and arr2 [ ] stores the frequency of ' m ^ x ' i . e . those ' m ' on which operation was performed Updating arr1 [ ] with frequency of remaining ' m ' & frequency of ' m ^ x ' from arr2 [ ] With help of arr2 [ ] , we prevent sorting of the array again and again ; Resetting arr2 [ ] for next iteration ; Finding the maximum and the minimum element from the modified array after the operations ; Printing the max and the min element ; Driver code
MAX = 10000 NEW_LINE import sys NEW_LINE from math import ceil , floor NEW_LINE def xorOnSortedArray ( arr , n , k , x ) : NEW_LINE INDENT arr1 = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE arr2 = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE xor_val = [ 0 for i in range ( MAX + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr1 [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT xor_val [ i ] = i ^ x NEW_LINE DEDENT while ( k > 0 ) : NEW_LINE INDENT k -= 1 NEW_LINE count = 0 NEW_LINE for i in range ( MAX + 1 ) : NEW_LINE INDENT store = arr1 [ i ] NEW_LINE if ( arr1 [ i ] > 0 ) : NEW_LINE INDENT if ( count % 2 == 0 ) : NEW_LINE INDENT div = arr1 [ i ] // 2 + 1 NEW_LINE arr1 [ i ] = arr1 [ i ] - div NEW_LINE arr2 [ xor_val [ i ] ] += div NEW_LINE DEDENT elif ( count % 2 != 0 ) : NEW_LINE INDENT div = arr1 [ i ] // 2 NEW_LINE arr1 [ i ] = arr1 [ i ] - div NEW_LINE arr2 [ xor_val [ i ] ] += div NEW_LINE DEDENT DEDENT count = count + store NEW_LINE DEDENT for i in range ( MAX + 1 ) : NEW_LINE INDENT arr1 [ i ] = arr1 [ i ] + arr2 [ i ] NEW_LINE arr2 [ i ] = 0 NEW_LINE DEDENT DEDENT mn = sys . maxsize NEW_LINE mx = - sys . maxsize - 1 NEW_LINE for i in range ( MAX + 1 ) : NEW_LINE INDENT if ( arr1 [ i ] > 0 ) : NEW_LINE INDENT if ( mn > i ) : NEW_LINE INDENT mn = i NEW_LINE DEDENT if ( mx < i ) : NEW_LINE INDENT mx = i NEW_LINE DEDENT DEDENT DEDENT print ( mn , mx ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 605 , 986 ] NEW_LINE n = len ( arr ) NEW_LINE k = 548 NEW_LINE x = 569 NEW_LINE xorOnSortedArray ( arr , n , k , x ) NEW_LINE DEDENT
Arrange N elements in circular fashion such that all elements are strictly less than sum of adjacent elements | Function to print the arrangement that satisifes the given condition ; Sort the array initially ; Array that stores the arrangement ; Once the array is sorted Re - fill the array again in the mentioned way in the approach ; Iterate in the array and check if the arrangement made satisfies the given condition or not ; For the first element the adjacents will be a [ 1 ] and a [ n - 1 ] ; For the last element the adjacents will be a [ 0 ] and a [ n - 2 ] ; If we reach this position then the arrangement is possible ; Driver code
def printArrangement ( a , n ) : NEW_LINE INDENT a = sorted ( a ) NEW_LINE b = [ 0 for i in range ( n ) ] NEW_LINE low = 0 NEW_LINE high = n - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT b [ low ] = a [ i ] NEW_LINE low += 1 NEW_LINE DEDENT else : NEW_LINE INDENT b [ high ] = a [ i ] NEW_LINE high -= 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT if ( b [ n - 1 ] + b [ 1 ] <= b [ i ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT DEDENT elif ( i == ( n - 1 ) ) : NEW_LINE INDENT if ( b [ n - 2 ] + b [ 0 ] <= b [ i ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( b [ i - 1 ] + b [ i + 1 ] <= b [ i ] ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( b [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT a = [ 1 , 4 , 4 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE printArrangement ( a , n ) NEW_LINE
Greatest contiguous sub | Function that returns the sub - array ; Data - structure to store all the sub - arrays of size K ; Iterate to find all the sub - arrays ; Store the sub - array elements in the array ; Push the vector in the container ; Sort the vector of elements ; The last sub - array in the sorted order will be the answer ; Driver code ; Get the sub - array
def findSubarray ( a , k , n ) : NEW_LINE INDENT vec = [ ] NEW_LINE for i in range ( n - k + 1 ) : NEW_LINE INDENT temp = [ ] NEW_LINE for j in range ( i , i + k ) : NEW_LINE INDENT temp . append ( a [ j ] ) NEW_LINE DEDENT vec . append ( temp ) NEW_LINE DEDENT vec = sorted ( vec ) NEW_LINE return vec [ len ( vec ) - 1 ] NEW_LINE DEDENT a = [ 1 , 4 , 3 , 2 , 5 ] NEW_LINE k = 4 NEW_LINE n = len ( a ) NEW_LINE ans = findSubarray ( a , k , n ) NEW_LINE for it in ans : NEW_LINE INDENT print ( it , end = " ▁ " ) NEW_LINE DEDENT
Unbounded Fractional Knapsack | Python implementation of the approach ; Function to return the maximum required value ; maxratio will store the maximum value to weight ratio we can have for any item and maxindex will store the index of that element ; Find the maximum ratio ; The item with the maximum value to weight ratio will be put into the knapsack repeatedly until full ; Driver code
import sys NEW_LINE def knapSack ( W , wt , val , n ) : NEW_LINE INDENT maxratio = - sys . maxsize - 1 ; NEW_LINE maxindex = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( val [ i ] / wt [ i ] ) > maxratio ) : NEW_LINE INDENT maxratio = ( val [ i ] / wt [ i ] ) ; NEW_LINE maxindex = i ; NEW_LINE DEDENT DEDENT return ( W * maxratio ) ; NEW_LINE DEDENT val = [ 14 , 27 , 44 , 19 ] ; NEW_LINE wt = [ 6 , 7 , 9 , 8 ] ; NEW_LINE n = len ( val ) ; NEW_LINE W = 50 ; NEW_LINE print ( knapSack ( W , wt , val , n ) ) ; NEW_LINE
Sort an array without changing position of negative numbers | Function to sort the array such that negative values do not get affected ; Store all non - negative values ; Sort non - negative values ; If current element is non - negative then update it such that all the non - negative values are sorted ; Print the sorted array ; Driver code
def sortArray ( a , n ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] >= 0 ) : NEW_LINE INDENT ans . append ( a [ i ] ) NEW_LINE DEDENT DEDENT ans = sorted ( ans ) NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] >= 0 ) : NEW_LINE INDENT a [ i ] = ans [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 2 , - 6 , - 3 , 8 , 4 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE sortArray ( arr , n ) NEW_LINE