text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Count pairs from two arrays having sum equal to K | Function to return the count of pairs having sum equal to K ; Initialize pairs to 0 ; Create dictionary of elements of array A1 ; count total pairs ; Every element can be part of at most one pair ; return total pairs ; Driver Code ; function call to print required answer | def countPairs ( A1 , A2 , n1 , n2 , K ) : NEW_LINE INDENT res = 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT if A1 [ i ] not in m . keys ( ) : NEW_LINE INDENT m [ A1 [ i ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ A1 [ i ] ] = m [ A1 [ i ] ] + 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n2 ) : NEW_LINE INDENT temp = K - A2 [ i ] NEW_LINE if temp in m . keys ( ) : NEW_LINE INDENT res = res + 1 NEW_LINE m [ temp ] = m [ temp ] - 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT A1 = [ 1 , 1 , 3 , 4 , 5 , 6 , 6 ] NEW_LINE A2 = [ 1 , 4 , 4 , 5 , 7 ] NEW_LINE K = 10 NEW_LINE n1 = len ( A1 ) NEW_LINE n2 = len ( A2 ) NEW_LINE print ( countPairs ( A1 , A2 , n1 , n2 , K ) ) NEW_LINE |
Count pairs in an array such that frequency of one is at least value of other | Python3 program to find the number of ordered pairs ; Function to find count of Ordered pairs ; Initialize pairs to 0 ; Store frequencies ; Count total Ordered_pairs ; Driver Code | from collections import defaultdict NEW_LINE def countOrderedPairs ( A , n ) : NEW_LINE INDENT orderedPairs = 0 NEW_LINE m = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT m [ A [ i ] ] += 1 NEW_LINE DEDENT for X , Y in m . items ( ) : NEW_LINE INDENT for j in range ( 1 , Y + 1 ) : NEW_LINE INDENT if m [ j ] >= X : NEW_LINE INDENT orderedPairs += 1 NEW_LINE DEDENT DEDENT DEDENT return orderedPairs NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 1 , 2 , 2 , 3 ] NEW_LINE n = len ( A ) NEW_LINE print ( countOrderedPairs ( A , n ) ) NEW_LINE DEDENT |
Longest subarray with elements having equal modulo K | function to find longest sub - array whose elements gives same remainder when divided with K ; Iterate in the array ; check if array element greater then X or not ; Driver code | def LongestSubarray ( arr , n , k ) : NEW_LINE INDENT count = 1 NEW_LINE max_lenght = 1 NEW_LINE prev_mod = arr [ 0 ] % k NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_mod = arr [ i ] % k NEW_LINE if curr_mod == prev_mod : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT max_lenght = max ( max_lenght , count ) NEW_LINE count = 1 NEW_LINE prev_mod = curr_mod NEW_LINE DEDENT DEDENT return max ( max_lenght , count ) NEW_LINE DEDENT arr = [ 4 , 9 , 7 , 18 , 29 , 11 ] NEW_LINE n = len ( arr ) NEW_LINE k = 11 NEW_LINE print ( LongestSubarray ( arr , n , k ) ) NEW_LINE |
Search in a sorted 2D matrix ( Stored in row major order ) | Python 3 program to find whether a given element is present in the given 2 - D matrix ; Basic binary search to find an element in a 1 - D array ; if element found return true ; if middle less than K then skip the left part of the array else skip the right part ; if not found return false ; Function to search an element in a matrix based on Divide and conquer approach ; if the element lies in the range of this row then call 1 - D binary search on this row ; if the element is less then the starting element of that row then search in upper rows else search in the lower rows ; if not found ; Driver code | M = 3 NEW_LINE N = 4 NEW_LINE def binarySearch1D ( arr , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = N - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + int ( ( high - low ) / 2 ) NEW_LINE if ( arr [ mid ] == K ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( arr [ mid ] < K ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def searchMatrix ( matrix , K ) : NEW_LINE INDENT low = 0 NEW_LINE high = M - 1 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = low + int ( ( high - low ) / 2 ) NEW_LINE if ( K >= matrix [ mid ] [ 0 ] and K <= matrix [ mid ] [ N - 1 ] ) : NEW_LINE INDENT return binarySearch1D ( matrix [ mid ] , K ) NEW_LINE DEDENT if ( K < matrix [ mid ] [ 0 ] ) : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT matrix = [ [ 1 , 3 , 5 , 7 ] , [ 10 , 11 , 16 , 20 ] , [ 23 , 30 , 34 , 50 ] ] NEW_LINE K = 3 NEW_LINE if ( searchMatrix ( matrix , K ) ) : NEW_LINE INDENT print ( " Found " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β found " ) NEW_LINE DEDENT DEDENT |
Program to find Nth term divisible by a or b | Python 3 program to find nth term divisible by a or b ; Function to return gcd of a and b ; Function to calculate how many numbers from 1 to num are divisible by a or b ; calculate number of terms divisible by a and by b then , remove the terms which are divisible by both a and b ; Binary search to find the nth term divisible by a or b ; set low to 1 and high to max ( a , b ) * n , here we have taken high as 10 ^ 18 ; if the current term is less than n then we need to increase low to mid + 1 ; if current term is greater than equal to n then high = mid ; Driver code | import sys NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if a == 0 : NEW_LINE INDENT return b NEW_LINE DEDENT return gcd ( b % a , a ) NEW_LINE DEDENT def divTermCount ( a , b , lcm , num ) : NEW_LINE INDENT return num // a + num // b - num // lcm NEW_LINE DEDENT def findNthTerm ( a , b , n ) : NEW_LINE INDENT low = 1 ; high = sys . maxsize NEW_LINE lcm = ( a * b ) // gcd ( a , b ) NEW_LINE while low < high : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if divTermCount ( a , b , lcm , mid ) < n : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT a = 2 ; b = 5 ; n = 10 NEW_LINE print ( findNthTerm ( a , b , n ) ) NEW_LINE |
Replace all occurrences of pi with 3.14 in a given string | Function to replace all occurrences of pi in a given with 3.14 ; Iterate through second last element of the string ; If current and current + 1 alphabets form the word ' pi ' append 3.14 to output ; Append the current letter ; Return the output string ; Driver Code | def replacePi ( input ) : NEW_LINE INDENT output = " " ; NEW_LINE size = len ( input ) ; NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( i + 1 < size and input [ i ] == ' p ' and input [ i + 1 ] == ' i ' ) : NEW_LINE INDENT output += "3.14" ; NEW_LINE i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT output += input [ i ] ; NEW_LINE DEDENT DEDENT return output ; NEW_LINE DEDENT input = "2 β * β pi β + β 3 β * β pi β = β 5 β * β pi " ; NEW_LINE print ( replacePi ( input ) ) ; NEW_LINE |
Number of elements that can be seen from right side | Python3 program to find number of elements that can be seen from right side ; Driver code | def numberOfElements ( height , n ) : NEW_LINE INDENT max_so_far = 0 NEW_LINE coun = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if height [ i ] > max_so_far : NEW_LINE INDENT max_so_far = height [ i ] NEW_LINE coun = coun + 1 NEW_LINE DEDENT DEDENT return coun NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 6 NEW_LINE height = [ 4 , 8 , 2 , 0 , 0 , 5 ] NEW_LINE print ( numberOfElements ( height , n ) ) NEW_LINE DEDENT |
Check if a pair with given product exists in Linked list | Link list node ; Push a new node on the front of the list . ; Checks if pair with given product exists in the list or not ; Check if pair exits ; Driver Code ; Start with the empty list ; Use push ( ) to construct linked list ; function to print the result | class Node : NEW_LINE INDENT def __init__ ( self , data , next ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = next NEW_LINE DEDENT DEDENT class LinkedList : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . head = None NEW_LINE DEDENT def push ( self , new_data ) : NEW_LINE INDENT new_node = Node ( new_data , self . head ) NEW_LINE self . head = new_node NEW_LINE DEDENT def check_pair_product ( self , prod ) : NEW_LINE INDENT p = self . head NEW_LINE s = set ( ) NEW_LINE while p != None : NEW_LINE INDENT curr = p . data NEW_LINE if ( prod % curr == 0 and ( prod // curr ) in s ) : NEW_LINE INDENT print ( curr , prod // curr ) NEW_LINE return True ; NEW_LINE DEDENT s . add ( p . data ) ; NEW_LINE p = p . next ; NEW_LINE DEDENT return False NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT linkedlist = LinkedList ( ) NEW_LINE linkedlist . push ( 1 ) NEW_LINE linkedlist . push ( 2 ) NEW_LINE linkedlist . push ( 1 ) NEW_LINE linkedlist . push ( 12 ) NEW_LINE linkedlist . push ( 1 ) NEW_LINE linkedlist . push ( 18 ) NEW_LINE linkedlist . push ( 47 ) NEW_LINE linkedlist . push ( 16 ) NEW_LINE linkedlist . push ( 12 ) NEW_LINE linkedlist . push ( 14 ) NEW_LINE res = linkedlist . check_pair_product ( 24 ) NEW_LINE if res == False : NEW_LINE INDENT print ( " NO β PAIR β EXIST " ) NEW_LINE DEDENT DEDENT |
Largest element in the array that is repeated exactly k times | Function that finds the largest element which is repeated ' k ' times ; sort the array ; if the value of ' k ' is 1 and the largest appears only once in the array ; counter to count the repeated elements ; check if the element at index ' i ' is equal to the element at index ' i + 1' then increase the count ; else set the count to 1 to start counting the frequency of the new number ; if the count is equal to k and the previous element is not equal to this element ; if there is no such element ; Driver code ; find the largest element that is repeated K times | def solve ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE if ( k == 1 and arr [ n - 2 ] != arr [ n - 1 ] ) : NEW_LINE INDENT print ( arr [ n - 1 ] ) NEW_LINE return NEW_LINE DEDENT count = 1 NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count = 1 NEW_LINE DEDENT if ( count == k and ( i == 0 or ( arr [ i - 1 ] != arr [ i ] ) ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " No β such β element " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE solve ( arr , n , k ) NEW_LINE DEDENT |
Largest element in the array that is repeated exactly k times | Python implementation of above approach ; Function that finds the largest element that occurs exactly ' k ' times ; store the frequency of each element ; to store the maximum element ; if current element has frequency ' k ' and current maximum hasn 't been set ; set the current maximum ; if current element has frequency ' k ' and it is greater than the current maximum ; change the current maximum ; if there is no element with frequency 'k ; print the largest element with frequency 'k ; Driver code ; find the largest element that is repeated K times | import sys NEW_LINE def solve ( arr , n , k ) : NEW_LINE INDENT m = { } ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] in m . keys ( ) ) : NEW_LINE INDENT m [ arr [ i ] ] += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT m [ arr [ i ] ] = 1 ; NEW_LINE DEDENT i += 1 ; NEW_LINE DEDENT max = sys . maxsize ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( m [ arr [ i ] ] == k and max == sys . maxsize ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE DEDENT elif ( m [ arr [ i ] ] == k and max < arr [ i ] ) : NEW_LINE INDENT max = arr [ i ] ; NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( max == sys . maxsize ) : NEW_LINE INDENT print ( " No β such β element " ) ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT print ( max ) ; NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 2 , 3 , 3 , 4 , 5 , 5 , 6 , 6 , 6 ] NEW_LINE k = 4 ; NEW_LINE n = len ( arr ) NEW_LINE solve ( arr , n , k ) NEW_LINE |
Sum and Product of minimum and maximum element of an Array | Function to find minimum element ; Function to find maximum element ; Function to get Sum ; Function to get product ; Driver Code ; Sum of min and max element ; Product of min and max element | def getMin ( arr , n ) : NEW_LINE INDENT res = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = min ( res , arr [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def getMax ( arr , n ) : NEW_LINE INDENT res = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = max ( res , arr [ i ] ) NEW_LINE DEDENT return res NEW_LINE DEDENT def findSum ( arr , n ) : NEW_LINE INDENT min = getMin ( arr , n ) NEW_LINE max = getMax ( arr , n ) NEW_LINE return min + max NEW_LINE DEDENT def findProduct ( arr , n ) : NEW_LINE INDENT min = getMin ( arr , n ) NEW_LINE max = getMax ( arr , n ) NEW_LINE return min * max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 12 , 1234 , 45 , 67 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Sum β = β " , findSum ( arr , n ) ) NEW_LINE print ( " Product β = β " , findProduct ( arr , n ) ) NEW_LINE DEDENT |
Count the number of pop operations on stack to get each element of the array | Function to find the count ; Hashmap to store all the elements which are popped once . ; Check if the number is present in the hashmap Or in other words been popped out from the stack before . ; Keep popping the elements while top is not equal to num ; Pop the top ie . equal to num ; Print the number of elements popped . ; Driver code | def countEle ( s , a , N ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT num = a [ i ] NEW_LINE if num in mp : NEW_LINE INDENT print ( "0" , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT cnt = 0 NEW_LINE while s [ - 1 ] != num : NEW_LINE INDENT mp [ s . pop ( ) ] = True NEW_LINE cnt += 1 NEW_LINE DEDENT s . pop ( ) NEW_LINE cnt += 1 NEW_LINE print ( cnt , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 NEW_LINE s = [ ] NEW_LINE s . append ( 1 ) NEW_LINE s . append ( 2 ) NEW_LINE s . append ( 3 ) NEW_LINE s . append ( 4 ) NEW_LINE s . append ( 6 ) NEW_LINE a = [ 6 , 3 , 4 , 1 , 2 ] NEW_LINE countEle ( s , a , N ) NEW_LINE DEDENT |
Queries to check whether a given digit is present in the given Range | Python3 program to answer Queries to check whether a given digit is present in the given range ; Segment Tree with set at each node ; Funtiom to build the segment tree ; Left child node ; Right child node ; Merging child nodes to get parent node . Since set is used , it will remove redundant digits . ; Function to query a range ; Complete Overlapp condition return true if digit is present . else false . ; No Overlapp condition Return false ; If digit is found in any child return true , else False ; Driver Code ; Build the tree ; Query 1 ; Query 2 | N = 6 NEW_LINE Tree = [ 0 ] * ( 6 * N ) NEW_LINE for i in range ( 6 * N ) : NEW_LINE INDENT Tree [ i ] = set ( ) NEW_LINE DEDENT def buildTree ( arr : list , idx : int , s : int , e : int ) -> None : NEW_LINE INDENT global Tree NEW_LINE if s == e : NEW_LINE INDENT Tree [ idx ] . add ( arr [ s ] ) NEW_LINE return NEW_LINE DEDENT mid = ( s + e ) // 2 NEW_LINE buildTree ( arr , 2 * idx , s , mid ) NEW_LINE buildTree ( arr , 2 * idx + 1 , mid + 1 , e ) NEW_LINE for it in Tree [ 2 * idx ] : NEW_LINE INDENT Tree [ idx ] . add ( it ) NEW_LINE DEDENT for it in Tree [ 2 * idx + 1 ] : NEW_LINE INDENT Tree [ idx ] . add ( it ) NEW_LINE DEDENT DEDENT def query ( idx : int , s : int , e : int , qs : int , qe : int , x : int ) -> bool : NEW_LINE INDENT global Tree NEW_LINE if qs <= s and e <= qe : NEW_LINE INDENT if list ( Tree [ idx ] ) . count ( x ) != 0 : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if qe < s or e < qs : NEW_LINE INDENT return False NEW_LINE DEDENT mid = ( s + e ) // 2 NEW_LINE leftAns = query ( 2 * idx , s , mid , qs , qe , x ) NEW_LINE rightAns = query ( 2 * idx + 1 , mid + 1 , e , qs , qe , x ) NEW_LINE return ( leftAns or rightAns ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 3 , 9 , 8 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE buildTree ( arr , 1 , 0 , n - 1 ) NEW_LINE l = 0 NEW_LINE r = 3 NEW_LINE x = 2 NEW_LINE if query ( 1 , 0 , n - 1 , l , r , x ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT l = 2 NEW_LINE r = 5 NEW_LINE x = 3 NEW_LINE if query ( 1 , 0 , n - 1 , l , r , x ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Count characters with same neighbors | Function to count the characters with same adjacent characters ; if length is less than 3 then return length as there will be only two characters ; Traverse the string ; Increment the count if the previous and next character is same ; Return count ; Driver code | def countChar ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n <= 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT count = 2 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ i + 1 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " egeeksk " NEW_LINE print ( countChar ( str ) ) NEW_LINE DEDENT |
First strictly smaller element in a sorted array in Java | Python3 program to find first element that is strictly smaller than given target ; Minimum size of the array should be 1 ; If target lies beyond the max element , than the index of strictly smaller value than target should be ( end - 1 ) ; Move to the left side if target is smaller ; Move right side ; Driver code | def next ( arr , target ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = len ( arr ) - 1 ; NEW_LINE if ( end == 0 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT if ( target > arr [ end ] ) : NEW_LINE INDENT return end ; NEW_LINE DEDENT ans = - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE if ( arr [ mid ] >= target ) : NEW_LINE INDENT end = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = mid ; NEW_LINE start = mid + 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 5 , 8 , 12 ] ; NEW_LINE print ( next ( arr , 5 ) ) ; NEW_LINE DEDENT |
First strictly greater element in a sorted array in Java | Python program to find first element that is strictly greater than given target . ; Move to right side if target is greater . ; Move left side . ; Driver code | def next ( arr , target ) : NEW_LINE INDENT start = 0 ; NEW_LINE end = len ( arr ) - 1 ; NEW_LINE ans = - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 ; NEW_LINE if ( arr [ mid ] <= target ) : NEW_LINE INDENT start = mid + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT ans = mid ; NEW_LINE end = mid - 1 ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 5 , 8 , 12 ] ; NEW_LINE print ( next ( arr , 8 ) ) ; NEW_LINE DEDENT |
Reallocation of elements based on Locality of Reference | A function to perform sequential search . ; Linearly search the element ; If not found ; Shift elements before one position ; Driver Code | def search ( arr , n , x ) : NEW_LINE INDENT res = - 1 NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT if ( x == arr [ i ] ) : NEW_LINE INDENT res = i NEW_LINE DEDENT DEDENT if ( res == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT temp = arr [ res ] NEW_LINE i = res NEW_LINE while ( i > 0 ) : NEW_LINE INDENT arr [ i ] = arr [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT arr [ 0 ] = temp NEW_LINE return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 25 , 36 , 85 , 98 , 75 , 89 , 15 , 63 , 66 , 64 , 74 , 27 , 83 , 97 ] NEW_LINE q = [ 63 , 63 , 86 , 63 , 78 ] NEW_LINE n = len ( arr ) NEW_LINE m = len ( q ) NEW_LINE for i in range ( 0 , m , 1 ) : NEW_LINE INDENT if ( search ( arr , n , q [ i ] ) ) : NEW_LINE INDENT print ( " Yes " , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT |
Probability of a key K present in array | Function to find the probability ; find probability upto 2 decimal places ; Driver Code | def kPresentProbability ( a , n , k ) : NEW_LINE INDENT count = a . count ( k ) NEW_LINE return round ( count / n , 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 4 , 7 , 2 , 0 , 8 , 7 , 5 ] NEW_LINE K = 2 NEW_LINE N = len ( A ) NEW_LINE print ( kPresentProbability ( A , N , K ) ) NEW_LINE DEDENT |
Largest subarray having sum greater than k | Comparison function used to sort preSum vector . ; Function to find index in preSum vector upto which all prefix sum values are less than or equal to val . ; Starting and ending index of search space . ; To store required index value . ; If middle value is less than or equal to val then index can lie in mid + 1. . n else it lies in 0. . mid - 1. ; Function to find largest subarray having sum greater than or equal to k . ; Length of largest subarray . ; Vector to store pair of prefix sum and corresponding ending index value . ; To store the current value of prefix sum . ; To store minimum index value in range 0. . i of preSum vector . ; Insert values in preSum vector . ; Update minInd array . ; If sum is greater than k , then answer is i + 1. ; If sum is less than or equal to k , then find if there is a prefix array having sum that needs to be added to current sum to make its value greater than k . If yes , then compare length of updated subarray with maximum length found so far . ; Driver code . | def compare ( a , b ) : NEW_LINE INDENT if a [ 0 ] == b [ 0 ] : NEW_LINE INDENT return a [ 1 ] < b [ 1 ] NEW_LINE DEDENT return a [ 0 ] < b [ 0 ] NEW_LINE DEDENT def findInd ( preSum , n , val ) : NEW_LINE INDENT l , h = 0 , n - 1 NEW_LINE ans = - 1 NEW_LINE while l <= h : NEW_LINE INDENT mid = ( l + h ) // 2 NEW_LINE if preSum [ mid ] [ 0 ] <= val : NEW_LINE INDENT ans = mid NEW_LINE l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT h = mid - 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def largestSub ( arr , n , k ) : NEW_LINE INDENT maxlen = 0 NEW_LINE preSum = [ ] NEW_LINE Sum = 0 NEW_LINE minInd = [ None ] * ( n ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum = Sum + arr [ i ] NEW_LINE preSum . append ( [ Sum , i ] ) NEW_LINE DEDENT preSum . sort ( ) NEW_LINE minInd [ 0 ] = preSum [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT minInd [ i ] = min ( minInd [ i - 1 ] , preSum [ i ] [ 1 ] ) NEW_LINE DEDENT Sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT Sum = Sum + arr [ i ] NEW_LINE if Sum > k : NEW_LINE INDENT maxlen = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ind = findInd ( preSum , n , Sum - k - 1 ) NEW_LINE if ind != - 1 and minInd [ ind ] < i : NEW_LINE INDENT maxlen = max ( maxlen , i - minInd [ ind ] ) NEW_LINE DEDENT DEDENT DEDENT return maxlen NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 2 , 1 , 6 , - 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE print ( largestSub ( arr , n , k ) ) NEW_LINE DEDENT |
Find the slope of the given number | function to find slope of a number ; to store slope of the given number 'num ; loop from the 2 nd digit up to the 2 nd last digit of the given number 'num ; if the digit is a maxima ; if the digit is a minima ; required slope ; Driver Code | def slopeOfNum ( num , n ) : NEW_LINE ' NEW_LINE INDENT slope = 0 NEW_LINE DEDENT ' NEW_LINE INDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( num [ i ] > num [ i - 1 ] and num [ i ] > num [ i + 1 ] ) : NEW_LINE INDENT slope += 1 NEW_LINE DEDENT elif ( num [ i ] < num [ i - 1 ] and num [ i ] < num [ i + 1 ] ) : NEW_LINE INDENT slope += 1 NEW_LINE DEDENT DEDENT return slope NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT num = "1213321" NEW_LINE n = len ( num ) NEW_LINE print ( " Slope β = " , slopeOfNum ( num , n ) ) NEW_LINE DEDENT |
Sudo Placement | Beautiful Pairs | Python3 code for finding required pairs ; The function to check if beautiful pair exists ; Set for hashing ; Traversing the first array ; Traversing the second array to check for every j corresponding to single i ; x + y = z = > x = y - z ; If such x exists then we return true ; Hash to make use of it next time ; No pair exists ; Driver Code ; If pair exists then 1 else 0 2 nd argument as size of first array fourth argument as sizeof 2 nd array | from typing import List NEW_LINE def pairExists ( arr1 : List [ int ] , m : int , arr2 : List [ int ] , n : int ) -> bool : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( arr2 [ 2 ] - arr1 [ 2 ] ) not in s : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT s . add ( arr1 [ i ] ) NEW_LINE DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr1 = [ 1 , 5 , 10 , 8 ] NEW_LINE arr2 = [ 2 , 20 , 13 ] NEW_LINE if ( pairExists ( arr1 , 4 , arr2 , 3 ) ) : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT DEDENT |
Sudo Placement | Placement Tour | Python Program to find the optimal number of elements such that the cumulative value should be less than given number ; This function returns true if the value cumulative according to received integer K is less than budget B , otherwise returns false ; Initialize a temporary array which stores the cumulative value of the original array ; Sort the array to find the smallest K values ; Check if the value is less than budget ; This function prints the optimal number of elements and respective cumulative value which is less than the given number ; Initialize answer as zero as optimal value may not exists ; If the current Mid Value is an optimal value , then try to maximize it ; Call Again to set the corresponding cumulative value for the optimal ans ; Driver Code ; Budget | value = 0 NEW_LINE def canBeOptimalValue ( K : int , arr : list , N : int , B : int ) -> bool : NEW_LINE INDENT global value NEW_LINE tmp = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT tmp [ i ] = ( arr [ i ] + K * ( i + 1 ) ) NEW_LINE DEDENT tmp . sort ( ) NEW_LINE value = 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT value += tmp [ i ] NEW_LINE DEDENT return value <= B NEW_LINE DEDENT def findNoOfElementsandValue ( arr : list , N : int , B : int ) : NEW_LINE INDENT global value NEW_LINE ans = 0 NEW_LINE value = 0 NEW_LINE while start <= end : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if canBeOptimalValue ( mid , arr , N , B ) : NEW_LINE INDENT ans = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT canBeOptimalValue ( ans , arr , N , B ) NEW_LINE print ( ans , value ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 5 , 6 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE B = 90 NEW_LINE findNoOfElementsandValue ( arr , N , B ) NEW_LINE DEDENT |
Previous greater element | Python 3 program previous greater element A naive solution to print previous greater element for every element in an array . ; Previous greater for first element never exists , so we print - 1. ; Let us process remaining elements . ; Find first element on left side that is greater than arr [ i ] . ; If all elements on left are smaller . ; Driver code | def prevGreater ( arr , n ) : NEW_LINE INDENT print ( " - 1" , end = " , β " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if arr [ i ] < arr [ j ] : NEW_LINE INDENT print ( arr [ j ] , end = " , β " ) NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if j == 0 and flag == 0 : NEW_LINE INDENT print ( " - 1" , end = " , β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 4 , 2 , 20 , 40 , 12 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE prevGreater ( arr , n ) NEW_LINE DEDENT |
Previous greater element | Python3 program to print previous greater element An efficient solution to print previous greater element for every element in an array . ; Create a stack and push index of first element to it ; Previous greater for first element is always - 1. ; Traverse remaining elements ; Pop elements from stack while stack is not empty and top of stack is smaller than arr [ i ] . We always have elements in decreasing order in a stack . ; If stack becomes empty , then no element is greater on left side . Else top of stack is previous greater . ; Driver code | import math as mt NEW_LINE def prevGreater ( arr , n ) : NEW_LINE INDENT s = list ( ) ; NEW_LINE s . append ( arr [ 0 ] ) NEW_LINE print ( " - 1 , β " , end = " " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT while ( len ( s ) > 0 and s [ - 1 ] < arr [ i ] ) : NEW_LINE INDENT s . pop ( ) NEW_LINE DEDENT if len ( s ) == 0 : NEW_LINE INDENT print ( " - 1 , β " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( s [ - 1 ] , " , β " , end = " " ) NEW_LINE DEDENT s . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT arr = [ 10 , 4 , 2 , 20 , 40 , 12 , 30 ] NEW_LINE n = len ( arr ) NEW_LINE prevGreater ( arr , n ) NEW_LINE |
Duplicates in an array in O ( n ) time and by using O ( 1 ) extra space | Set | Function to find repeating elements ; Flag variable used to represent whether repeating element is found or not . ; Check if current element is repeating or not . If it is repeating then value will be greater than or equal to n . ; Check if it is first repetition or not . If it is first repetition then value at index arr [ i ] is less than 2 * n . Print arr [ i ] if it is first repetition . ; Add n to index arr [ i ] to mark presence of arr [ i ] or to mark repetition of arr [ i ] . ; If flag variable is not set then no repeating element is found . So print - 1. ; Driver Function | def printDuplicates ( arr , n ) : NEW_LINE INDENT fl = 0 ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ arr [ i ] % n ] >= n ) : NEW_LINE INDENT if ( arr [ arr [ i ] % n ] < 2 * n ) : NEW_LINE INDENT print ( arr [ i ] % n , end = " β " ) NEW_LINE fl = 1 ; NEW_LINE DEDENT DEDENT arr [ arr [ i ] % n ] += n ; NEW_LINE DEDENT if ( fl == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT arr = [ 1 , 6 , 3 , 1 , 3 , 6 , 6 ] ; NEW_LINE arr_size = len ( arr ) ; NEW_LINE printDuplicates ( arr , arr_size ) ; NEW_LINE |
Find the smallest positive number missing from an unsorted array | Set 2 | Function to find smallest positive missing number . ; to store next array element in current traversal ; if value is negative or greater than array size , then it cannot be marked in array . So move to next element . ; traverse the array until we reach at an element which is already marked or which could not be marked . ; find first array index which is not marked which is also the smallest positive missing number . ; if all indices are marked , then smallest missing positive number is array_size + 1. ; Driver code | def findMissingNo ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] <= 0 or arr [ i ] > n ) : NEW_LINE INDENT continue NEW_LINE DEDENT val = arr [ i ] NEW_LINE while ( arr [ val - 1 ] != val ) : NEW_LINE INDENT nextval = arr [ val - 1 ] NEW_LINE arr [ val - 1 ] = val NEW_LINE val = nextval NEW_LINE if ( val <= 0 or val > n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != i + 1 ) : NEW_LINE INDENT return i + 1 NEW_LINE DEDENT DEDENT return n + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 7 , 6 , 8 , - 1 , - 10 , 15 ] NEW_LINE arr_size = len ( arr ) NEW_LINE missing = findMissingNo ( arr , arr_size ) NEW_LINE print ( " The β smallest β positive " , " missing β number β is β " , missing ) NEW_LINE DEDENT |
Print all triplets with given sum | Prints all triplets in arr [ ] with given sum ; Driver code | def findTriplets ( arr , n , sum ) : NEW_LINE INDENT for i in range ( 0 , n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] + arr [ k ] == sum ) : NEW_LINE INDENT print ( arr [ i ] , " β " , arr [ j ] , " β " , arr [ k ] , sep = " " ) NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT arr = [ 0 , - 1 , 2 , - 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE findTriplets ( arr , n , - 2 ) NEW_LINE |
Print all triplets with given sum | Python3 program to find triplets in a given array whose Sum is equal to given sum . ; function to print triplets with given sum ; Find all pairs with Sum equals to " Sum - arr [ i ] " ; Driver code | import math as mt NEW_LINE def findTriplets ( arr , n , Sum ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT s = dict ( ) NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT x = Sum - ( arr [ i ] + arr [ j ] ) NEW_LINE if x in s . keys ( ) : NEW_LINE INDENT print ( x , arr [ i ] , arr [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT s [ arr [ j ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 0 , - 1 , 2 , - 3 , 1 ] NEW_LINE Sum = - 2 NEW_LINE n = len ( arr ) NEW_LINE findTriplets ( arr , n , Sum ) NEW_LINE |
Maximum product quadruple ( sub | Python3 program to find a maximum product of a quadruple in array of integers ; Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; will contain max product ; Driver Code | import sys NEW_LINE def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 ; NEW_LINE DEDENT max_product = - sys . maxsize ; NEW_LINE for i in range ( n - 3 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 2 ) : NEW_LINE INDENT for k in range ( j + 1 , n - 1 ) : NEW_LINE INDENT for l in range ( k + 1 , n ) : NEW_LINE INDENT max_product = max ( max_product , arr [ i ] * arr [ j ] * arr [ k ] * arr [ l ] ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return max_product ; NEW_LINE DEDENT arr = [ 10 , 3 , 5 , 6 , 20 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE max = maxProduct ( arr , n ) ; NEW_LINE if ( max == - 1 ) : NEW_LINE INDENT print ( " No β Quadruple β Exists " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum β product β is " , max ) ; NEW_LINE DEDENT |
Maximum product quadruple ( sub | Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Sort the array in ascending order ; Return the maximum of x , y and z ; Driver Code | def maxProduct ( arr , n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT arr . sort ( ) NEW_LINE x = ( arr [ n - 1 ] * arr [ n - 2 ] * arr [ n - 3 ] * arr [ n - 4 ] ) NEW_LINE y = arr [ 0 ] * arr [ 1 ] * arr [ 2 ] * arr [ 3 ] NEW_LINE z = ( arr [ 0 ] * arr [ 1 ] * arr [ n - 1 ] * arr [ n - 2 ] ) NEW_LINE return max ( x , max ( y , z ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 10 , - 3 , 5 , 6 , - 20 ] NEW_LINE n = len ( arr ) NEW_LINE max = maxProduct ( arr , n ) NEW_LINE if ( max == - 1 ) : NEW_LINE INDENT print ( " No β Quadruple β Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Maximum β product β is " , max ) NEW_LINE DEDENT DEDENT |
Minimum value of " max β + β min " in a subarray | Python 3 program to find sum of maximum and minimum in any subarray of an array of positive numbers . ; Driver code | def maxSum ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ans = arr [ 0 ] + arr [ 1 ] NEW_LINE for i in range ( 1 , n - 1 , 1 ) : NEW_LINE INDENT ans = min ( ans , ( arr [ i ] + arr [ i + 1 ] ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 12 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE DEDENT |
Stella Octangula Number | Returns value of n * ( 2 * n * n - 1 ) ; Finds if a value of f ( n ) is equal to x where n is in interval [ low . . high ] ; Returns true if x isStella octangula number . Else returns false . ; Find ' high ' for binary search by repeated doubling ; If condition is satisfied for a power of 2. ; Call binary search ; Driver code | def f ( n ) : NEW_LINE INDENT return n * ( 2 * n * n - 1 ) ; NEW_LINE DEDENT def binarySearch ( low , high , x ) : NEW_LINE INDENT while ( low <= high ) : NEW_LINE INDENT mid = int ( ( low + high ) // 2 ) ; NEW_LINE if ( f ( mid ) < x ) : NEW_LINE INDENT low = mid + 1 ; NEW_LINE DEDENT elif ( f ( mid ) > x ) : NEW_LINE INDENT high = mid - 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT return True ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT def isStellaOctangula ( x ) : NEW_LINE INDENT if ( x == 0 ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT i = 1 ; NEW_LINE while ( f ( i ) < x ) : NEW_LINE INDENT i = i * 2 ; NEW_LINE DEDENT if ( f ( i ) == x ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT return binarySearch ( i / 2 , i , x ) ; NEW_LINE DEDENT n = 51 ; NEW_LINE if ( isStellaOctangula ( n ) == True ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT |
Sort the given string using character search | Python 3 implementation to sort the given string without using any sorting technique ; A character array to store the no . of occurrences of each character between ' a ' to 'z ; to store the final sorted string ; To store each occurrence of character by relative indexing ; To traverse the character array and append it to new_str ; Driver program to test above | def sortString ( st , n ) : NEW_LINE ' NEW_LINE INDENT arr = [ 0 ] * 26 NEW_LINE new_str = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ ord ( st [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 26 ) : NEW_LINE INDENT while ( arr [ i ] > 0 ) : NEW_LINE INDENT new_str += chr ( i + ord ( ' a ' ) ) NEW_LINE arr [ i ] -= 1 NEW_LINE DEDENT DEDENT return new_str NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " geeksforgeeks " NEW_LINE n = len ( st ) NEW_LINE print ( sortString ( st , n ) ) NEW_LINE DEDENT |
Maximum occurring character in a linked list | Link list node ; Storing element 's frequencies in a hash table. ; Calculating the first maximum element ; Push a node to linked list . Note that this function changes the head ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = ' ' NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def maxChar ( head ) : NEW_LINE INDENT p = head NEW_LINE hash = [ 0 for i in range ( 256 ) ] NEW_LINE while ( p != None ) : NEW_LINE hash [ ord ( p . data ) ] += 1 NEW_LINE p = p . next NEW_LINE p = head NEW_LINE max = - 1 NEW_LINE res = ' ' NEW_LINE while ( p != None ) : NEW_LINE if ( max < hash [ ord ( p . data ) ] ) : NEW_LINE INDENT res = p . data NEW_LINE max = hash [ ord ( p . data ) ] NEW_LINE DEDENT p = p . next NEW_LINE return res NEW_LINE DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = ( head_ref ) NEW_LINE ( head_ref ) = new_node NEW_LINE return head_ref NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE str = " skeegforskeeg " NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT head = push ( head , str [ i ] ) NEW_LINE DEDENT print ( maxChar ( head ) ) NEW_LINE DEDENT |
Maximum sum of elements from each row in the matrix | Python Program to find row - wise maximum element sum considering elements in increasing order . ; Function to perform given task ; Getting the maximum element from last row ; Comparing it with the elements of above rows ; Maximum of current row . ; If we could not an element smaller than prev_max . ; Driver code | N = 3 NEW_LINE def getGreatestSum ( a ) : NEW_LINE INDENT prev_max = 0 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( prev_max < a [ N - 1 ] [ j ] ) : NEW_LINE INDENT prev_max = a [ N - 1 ] [ j ] NEW_LINE DEDENT DEDENT sum = prev_max NEW_LINE for i in range ( N - 2 , - 1 , - 1 ) : NEW_LINE INDENT curr_max = - 2147483648 NEW_LINE for j in range ( N ) : NEW_LINE INDENT if ( prev_max > a [ i ] [ j ] and a [ i ] [ j ] > curr_max ) : NEW_LINE INDENT curr_max = a [ i ] [ j ] NEW_LINE DEDENT DEDENT if ( curr_max == - 2147483648 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT prev_max = curr_max NEW_LINE sum = sum + prev_max NEW_LINE DEDENT return sum NEW_LINE DEDENT a = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE print ( getGreatestSum ( a ) ) NEW_LINE b = [ [ 4 , 5 , 6 ] , [ 4 , 5 , 6 ] , [ 4 , 5 , 6 ] ] NEW_LINE print ( getGreatestSum ( b ) ) NEW_LINE |
Find the number of times every day occurs in a month | Python program to count occurrence of days in a month ; function to find occurrences ; stores days in a week ; Initialize all counts as 4. ; find index of the first day ; number of days whose occurrence will be 5 ; mark the occurrence to be 5 of n - 28 days ; print the days ; driver program to test the above function | import math NEW_LINE def occurrenceDays ( n , firstday ) : NEW_LINE INDENT days = [ " Monday " , " Tuesday " , " Wednesday " , " Thursday " , " Friday " , " Saturday " , " Sunday " ] NEW_LINE count = [ 4 for i in range ( 0 , 7 ) ] NEW_LINE pos = - 1 NEW_LINE for i in range ( 0 , 7 ) : NEW_LINE INDENT if ( firstday == days [ i ] ) : NEW_LINE INDENT pos = i NEW_LINE break NEW_LINE DEDENT DEDENT inc = n - 28 NEW_LINE for i in range ( pos , pos + inc ) : NEW_LINE INDENT if ( i > 6 ) : NEW_LINE INDENT count [ i % 7 ] = 5 NEW_LINE DEDENT else : NEW_LINE INDENT count [ i ] = 5 NEW_LINE DEDENT DEDENT for i in range ( 0 , 7 ) : NEW_LINE INDENT print ( days [ i ] , " β " , count [ i ] ) NEW_LINE DEDENT DEDENT n = 31 NEW_LINE firstday = " Tuesday " NEW_LINE occurrenceDays ( n , firstday ) NEW_LINE |
Value of k | Python3 code to find k - th element after append and insert middle operations ; ans = n Middle element of the sequence ; length of the resulting sequence . ; Updating the middle element of next sequence ; Moving to the left side of the middle element . ; Moving to the right side of the middle element . ; Driver code | import math NEW_LINE def findElement ( n , k ) : NEW_LINE INDENT left = 1 NEW_LINE right = math . pow ( 2 , n ) - 1 NEW_LINE while 1 : NEW_LINE INDENT mid = int ( ( left + right ) / 2 ) NEW_LINE if k == mid : NEW_LINE INDENT print ( ans ) NEW_LINE break NEW_LINE DEDENT ans -= 1 NEW_LINE if k < mid : NEW_LINE INDENT right = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT DEDENT DEDENT n = 4 NEW_LINE k = 8 NEW_LINE findElement ( n , k ) NEW_LINE |
First common element in two linked lists | Python3 program to find first common element in two unsorted linked list ; Link list node ; A utility function to insert a node at the beginning of a linked list ; Returns the first repeating element in linked list ; Traverse through every node of first list ; If current node is present in second list ; If no common node ; Driver code | import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def firstCommon ( head1 , head2 ) : NEW_LINE INDENT while ( head1 != None ) : NEW_LINE INDENT p = head2 NEW_LINE while ( p != None ) : NEW_LINE INDENT if ( p . data == head1 . data ) : NEW_LINE INDENT return head1 . data NEW_LINE DEDENT p = p . next NEW_LINE DEDENT head1 = head1 . next NEW_LINE DEDENT return 0 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head1 = None NEW_LINE head1 = push ( head1 , 20 ) NEW_LINE head1 = push ( head1 , 5 ) NEW_LINE head1 = push ( head1 , 15 ) NEW_LINE head1 = push ( head1 , 10 ) NEW_LINE head2 = None NEW_LINE head2 = push ( head2 , 10 ) NEW_LINE head2 = push ( head2 , 2 ) NEW_LINE head2 = push ( head2 , 15 ) NEW_LINE head2 = push ( head2 , 8 ) NEW_LINE print ( firstCommon ( head1 , head2 ) ) NEW_LINE DEDENT |
Print pair with maximum AND value in an array | Utility function to check number of elements having set msb as of pattern ; Function for finding maximum and value pair ; iterate over total of 30 bits from msb to lsb ; find the count of element having set msb ; if count >= 2 set particular bit in result ; Find the elements ; print the pair of elements ; inc count value after printing element ; return the result value ; Driver function | def checkBit ( pattern , arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( pattern & arr [ i ] ) == pattern ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT def maxAND ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE for bit in range ( 31 , - 1 , - 1 ) : NEW_LINE INDENT count = checkBit ( res | ( 1 << bit ) , arr , n ) NEW_LINE if ( count >= 2 ) : NEW_LINE INDENT res |= ( 1 << bit ) NEW_LINE DEDENT DEDENT if ( res == 0 ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Pair β = β " , end = " " ) NEW_LINE count = 0 NEW_LINE i = 0 NEW_LINE while ( i < n and count < 2 ) : NEW_LINE INDENT if ( ( arr [ i ] & res ) == res ) : NEW_LINE INDENT count += 1 NEW_LINE print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 4 , 8 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum AND Value = " , maxAND ( arr , n ) ) NEW_LINE |
Probability of choosing a random pair with maximum sum in an array | Function to get max first and second ; If current element is smaller than first , then update both first and second ; If arr [ i ] is in between first and second then update second ; cnt1 += 1 frequency of first maximum ; cnt2 += 1 frequency of second maximum ; Returns probability of choosing a pair with maximum sum . ; Driver Code | def countMaxSumPairs ( a , n ) : NEW_LINE INDENT first = 0 NEW_LINE second = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = a [ i ] NEW_LINE DEDENT elif ( a [ i ] > second and a [ i ] != first ) : NEW_LINE INDENT second = a [ i ] NEW_LINE DEDENT DEDENT cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == first ) : NEW_LINE if ( a [ i ] == second ) : NEW_LINE DEDENT if ( cnt1 == 1 ) : NEW_LINE INDENT return cnt2 NEW_LINE DEDENT if ( cnt1 > 1 ) : NEW_LINE INDENT return cnt1 * ( cnt1 - 1 ) / 2 NEW_LINE DEDENT DEDENT def findMaxSumProbability ( a , n ) : NEW_LINE INDENT total = n * ( n - 1 ) / 2 NEW_LINE max_sum_pairs = countMaxSumPairs ( a , n ) NEW_LINE return max_sum_pairs / total NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 2 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMaxSumProbability ( a , n ) ) NEW_LINE DEDENT |
Find if given number is sum of first n natural numbers | Function to find no . of elements to be added from 1 to get n ; Start adding numbers from 1 ; If sum becomes equal to s return n ; Driver code | def findS ( s ) : NEW_LINE INDENT _sum = 0 NEW_LINE n = 1 NEW_LINE while ( _sum < s ) : NEW_LINE INDENT _sum += n NEW_LINE n += 1 NEW_LINE DEDENT n -= 1 NEW_LINE if _sum == s : NEW_LINE INDENT return n NEW_LINE DEDENT return - 1 NEW_LINE DEDENT s = 15 NEW_LINE n = findS ( s ) NEW_LINE if n == - 1 : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT |
Find if given number is sum of first n natural numbers | Python3 program of the above approach ; Function to check if the s is the sum of first N natural number ; Solution of Quadratic Equation ; Condition to check if the solution is a integer ; Driver Code ; Function Call | import math NEW_LINE def isvalid ( s ) : NEW_LINE INDENT k = ( - 1 + math . sqrt ( 1 + 8 * s ) ) / 2 NEW_LINE if ( math . ceil ( k ) == math . floor ( k ) ) : NEW_LINE INDENT return int ( k ) NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT s = 15 NEW_LINE print ( isvalid ( s ) ) NEW_LINE |
Save from Bishop in chessboard | python program to find total safe position to place your Bishop ; function to calc total safe position ; i , j denotes row and column of position of bishop ; calc distance in four direction ; calc total sum of distance + 1 for unsafe positions ; return total safe positions ; driver function | import math NEW_LINE def calcSafe ( pos ) : NEW_LINE INDENT j = pos % 10 NEW_LINE i = pos / 10 NEW_LINE dis_11 = min ( abs ( 1 - i ) , abs ( 1 - j ) ) NEW_LINE dis_18 = min ( abs ( 1 - i ) , abs ( 8 - j ) ) NEW_LINE dis_81 = min ( abs ( 8 - i ) , abs ( 1 - j ) ) NEW_LINE dis_88 = min ( abs ( 8 - i ) , abs ( 8 - j ) ) NEW_LINE sum = ( dis_11 + dis_18 + dis_81 + dis_88 + 1 ) NEW_LINE return ( 64 - sum ) NEW_LINE DEDENT pos = 34 NEW_LINE print ( " Safe β Positions β = β " , math . ceil ( calcSafe ( pos ) ) ) NEW_LINE |
Count number of elements between two given elements in array | Function to count number of elements occurs between the elements . ; Find num1 ; If num1 is not present or present at end ; Find num2 ; If num2 is not present ; return number of elements between the two elements . ; Driver Code | def getCount ( arr , n , num1 , num2 ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == num1 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( i >= n - 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for j in range ( n - 1 , i + 1 , - 1 ) : NEW_LINE INDENT if ( arr [ j ] == num2 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( j == i ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( j - i - 1 ) NEW_LINE DEDENT arr = [ 3 , 5 , 7 , 6 , 4 , 9 , 12 , 4 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE num1 = 5 NEW_LINE num2 = 4 NEW_LINE print ( getCount ( arr , n , num1 , num2 ) ) NEW_LINE |
Best meeting point in 2D binary array | Python program to find best meeting point in 2D array ; Find all members home 's position ; Sort positions so we can find most beneficial point ; middle position will always beneficial for all group members but it will be sorted which we have already done ; Now find total distance from best meeting point ( x , y ) using Manhattan Distance formula ; Driver Code | ROW = 3 NEW_LINE COL = 5 NEW_LINE def minTotalDistance ( grid : list ) -> int : NEW_LINE INDENT if ROW == 0 or COL == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT vertical = [ ] NEW_LINE horizontal = [ ] NEW_LINE for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 : NEW_LINE INDENT vertical . append ( i ) NEW_LINE horizontal . append ( j ) NEW_LINE DEDENT DEDENT DEDENT vertical . sort ( ) NEW_LINE horizontal . sort ( ) NEW_LINE size = len ( vertical ) // 2 NEW_LINE x = vertical [ size ] NEW_LINE y = horizontal [ size ] NEW_LINE distance = 0 NEW_LINE for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if grid [ i ] [ j ] == 1 : NEW_LINE INDENT distance += abs ( x - i ) + abs ( y - j ) NEW_LINE DEDENT DEDENT DEDENT return distance NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ [ 1 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 0 , 0 ] , [ 0 , 1 , 1 , 0 , 0 ] ] NEW_LINE print ( minTotalDistance ( grid ) ) NEW_LINE DEDENT |
Count numbers with difference between number and its digit sum greater than specific value | Utility method to get sum of digits of K ; loop until K is not zero ; method returns count of numbers smaller than N , satisfying difference condition ; binary search while loop ; if difference between number and its sum of digit is smaller than given difference then smallest number will be on left side ; if difference between number and its sum of digit greater than equal to given difference then smallest number will be on right side ; return the difference between ' smallest β number β β found ' and ' N ' as result ; Driver code to test above methods | def sumOfDigit ( K ) : NEW_LINE INDENT sod = 0 NEW_LINE while ( K ) : NEW_LINE INDENT sod = sod + K % 10 NEW_LINE K = K // 10 NEW_LINE DEDENT return sod NEW_LINE DEDENT def totalNumbersWithSpecificDifference ( N , diff ) : NEW_LINE INDENT low = 1 NEW_LINE high = N NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if ( mid - sumOfDigit ( mid ) < diff ) : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT return ( N - high ) NEW_LINE DEDENT N = 13 NEW_LINE diff = 2 NEW_LINE print ( totalNumbersWithSpecificDifference ( N , diff ) ) NEW_LINE |
Randomized Binary Search Algorithm | To generate random number between x and y ie . . [ x , y ] ; A iterative randomized binary search function . It returns location of x in given array arr [ l . . r ] if present , otherwise - 1 ; Here we have defined middle as random index between l and r ie . . [ l , r ] ; Check if x is present at mid ; If x greater , ignore left half ; If x is smaller , ignore right half ; if we reach here , then element was not present ; Driver code | from random import randint NEW_LINE def getRandom ( x , y ) : NEW_LINE INDENT return randint ( x , y ) NEW_LINE DEDENT def randomizedBinarySearch ( arr , l , r , x ) : NEW_LINE INDENT while ( l <= r ) : NEW_LINE INDENT m = getRandom ( l , r ) NEW_LINE if ( arr [ m ] == x ) : NEW_LINE INDENT return m NEW_LINE DEDENT if ( arr [ m ] < x ) : NEW_LINE INDENT l = m + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = m - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 10 NEW_LINE result = randomizedBinarySearch ( arr , 0 , n - 1 , x ) NEW_LINE if result == 1 : NEW_LINE INDENT print ( " Element β is β not β present β in β array " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β is β present β at β index " , result ) NEW_LINE DEDENT |
Number of buildings facing the sun | Returns count buildings that can see sunlight ; Initialuze result ( Note that first building always sees sunlight ) ; Start traversing element ; If curr_element is maximum or current element is equal , update maximum and increment count ; Driver code | def countBuildings ( arr , n ) : NEW_LINE INDENT count = 1 NEW_LINE curr_max = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > curr_max or arr [ i ] == curr_max ) : NEW_LINE INDENT count += 1 NEW_LINE curr_max = arr [ i ] NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 7 , 4 , 8 , 2 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countBuildings ( arr , n ) ) NEW_LINE |
Find index of an extra element present in one sorted array | Returns index of extra . element in arr1 [ ] n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; Driver code ; Solve is passed both arrays | def findExtra ( arr1 , arr2 , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr1 [ i ] != arr2 [ i ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return n NEW_LINE DEDENT arr1 = [ 2 , 4 , 6 , 8 , 10 , 12 , 13 ] NEW_LINE arr2 = [ 2 , 4 , 6 , 8 , 10 , 12 ] NEW_LINE n = len ( arr2 ) NEW_LINE print ( findExtra ( arr1 , arr2 , n ) ) NEW_LINE |
Find index of an extra element present in one sorted array | Returns index of extra element in arr1 [ ] . n is size of arr2 [ ] . Size of arr1 [ ] is n - 1. ; left and right are end points denoting the current range . ; If middle element is same of both arrays , it means that extra element is after mid so we update left to mid + 1 ; If middle element is different of the arrays , it means that the index we are searching for is either mid , or before mid . Hence we update right to mid - 1. ; when right is greater than left our search is complete . ; Driver code ; Solve is passed both arrays | def findExtra ( arr1 , arr2 , n ) : NEW_LINE INDENT left = 0 NEW_LINE right = n - 1 NEW_LINE while ( left <= right ) : NEW_LINE INDENT mid = ( int ) ( ( left + right ) / 2 ) NEW_LINE if ( arr2 [ mid ] == arr1 [ mid ] ) : NEW_LINE INDENT left = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT index = mid NEW_LINE right = mid - 1 NEW_LINE DEDENT DEDENT return index NEW_LINE DEDENT arr1 = [ 2 , 4 , 6 , 8 , 10 , 12 , 13 ] NEW_LINE arr2 = [ 2 , 4 , 6 , 8 , 10 , 12 ] NEW_LINE n = len ( arr2 ) NEW_LINE print ( findExtra ( arr1 , arr2 , n ) ) NEW_LINE |
Make all array elements equal with minimum cost | Utility method to compute cost , when all values of array are made equal to X ; Method to find minimum cost to make all elements equal ; Setting limits for ternary search by smallest and largest element ; loop until difference between low and high become less than 3 , because after that mid1 and mid2 will start repeating ; mid1 and mid2 are representative array equal values of search space ; if mid2 point gives more total cost , skip third part ; if mid1 point gives more total cost , skip first part ; computeCost gets optimum cost by sending average of low and high as X ; Driver code | def computeCost ( arr , N , X ) : NEW_LINE INDENT cost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cost += abs ( arr [ i ] - X ) NEW_LINE DEDENT return cost NEW_LINE DEDENT def minCostToMakeElementEqual ( arr , N ) : NEW_LINE INDENT low = high = arr [ 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( low > arr [ i ] ) : low = arr [ i ] NEW_LINE if ( high < arr [ i ] ) : high = arr [ i ] NEW_LINE DEDENT while ( ( high - low ) > 2 ) : NEW_LINE INDENT mid1 = low + ( high - low ) // 3 NEW_LINE mid2 = high - ( high - low ) // 3 NEW_LINE cost1 = computeCost ( arr , N , mid1 ) NEW_LINE cost2 = computeCost ( arr , N , mid2 ) NEW_LINE if ( cost1 < cost2 ) : NEW_LINE INDENT high = mid2 NEW_LINE DEDENT else : NEW_LINE INDENT low = mid1 NEW_LINE DEDENT DEDENT return computeCost ( arr , N , ( low + high ) // 2 ) NEW_LINE DEDENT arr = [ 1 , 100 , 101 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minCostToMakeElementEqual ( arr , N ) ) NEW_LINE |
Minimum number of jumps required to sort numbers placed on a number line | Function to find the minimum number of jumps required to sort the array ; Base Case ; Store the required result ; Stores the current position of elements and their respective maximum jump ; Used to check if a position is already taken by another element ; Stores the sorted array a [ ] ; Traverse the array w [ ] & update positions jumps array a [ ] ; Sort the array a [ ] ; Traverse the array a [ ] over the range [ 1 , N - 1 ] ; Store the index of current element and its just smaller element in array w [ ] ; Iterate until current element position is at most its just smaller element position ; Update the position of the current element ; Print the result ; Driver Code | def minJumps ( w , l , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT ans = 0 NEW_LINE pos = { } NEW_LINE jump = { } NEW_LINE filled = { } NEW_LINE a = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT pos [ w [ i ] ] = i NEW_LINE filled [ i ] = True NEW_LINE jump [ w [ i ] ] = l [ i ] NEW_LINE a [ i ] = w [ i ] NEW_LINE DEDENT a . sort ( ) NEW_LINE for curr in range ( 1 , n , 1 ) : NEW_LINE INDENT currElementPos = pos [ a [ curr ] ] NEW_LINE prevElementPos = pos [ a [ curr - 1 ] ] NEW_LINE if ( currElementPos > prevElementPos ) : NEW_LINE INDENT continue NEW_LINE DEDENT while ( currElementPos <= prevElementPos or ( currElementPos in filled and filled [ currElementPos ] ) ) : NEW_LINE INDENT currElementPos += jump [ a [ curr ] ] NEW_LINE ans += 1 NEW_LINE DEDENT pos [ a [ curr ] ] = currElementPos NEW_LINE filled [ currElementPos ] = True NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT W = [ 2 , 1 , 4 , 3 ] NEW_LINE L = [ 4 , 1 , 2 , 4 ] NEW_LINE N = len ( W ) NEW_LINE minJumps ( W , L , N ) NEW_LINE DEDENT |
Make an array strictly increasing by repeatedly subtracting and adding arr [ i | Function to check if an array can be made strictly increasing ; Traverse the given array arr [ ] ; Update the value of p , arr [ i ] , and arr [ i - 1 ] ; Traverse the given array ; Check if the array arr [ ] is strictly increasing or not ; Otherwise , array is increasing order , prYes ; Driver Code | def check ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i - 1 ] >= ( i - 1 ) ) : NEW_LINE INDENT p = arr [ i - 1 ] - ( i - 1 ) NEW_LINE arr [ i ] += p NEW_LINE arr [ i - 1 ] -= p NEW_LINE DEDENT DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] <= arr [ i - 1 ] ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 2 , 7 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE check ( arr , N ) NEW_LINE DEDENT |
Rearrange array to make decimal equivalents of reversed binary representations of array elements sorted | Function to reverse the bits of a number ; Stores the reversed number ; Divide rev by 2 ; If the value of N is odd ; Update the value of N ; Return the final value of rev ; Function for rearranging the array element according to the given rules ; Stores the new array elements ; Function for rearranging the array ; Stores the new array ; Function to sort the array by reversing the binary representation ; Creating a new array ; Sort the array with the key ; Get arr from newArr ; Print the sorted array ; Driver Code | def keyFunc ( n ) : NEW_LINE INDENT rev = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT rev = rev << 1 NEW_LINE if ( n & 1 == 1 ) : NEW_LINE INDENT rev = rev ^ 1 NEW_LINE DEDENT n = n >> 1 NEW_LINE DEDENT return rev NEW_LINE DEDENT def getNew ( arr ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in arr : NEW_LINE INDENT ans . append ( [ keyFunc ( i ) , i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def getArr ( arr ) : NEW_LINE INDENT ans = [ ] NEW_LINE for i in arr : NEW_LINE INDENT ans . append ( i [ 1 ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def sortArray ( arr ) : NEW_LINE INDENT newArr = getNew ( arr ) NEW_LINE newArr . sort ( ) NEW_LINE arr = getArr ( newArr ) NEW_LINE print ( arr ) NEW_LINE DEDENT arr = [ 43 , 52 , 61 , 41 ] NEW_LINE sortArray ( arr ) NEW_LINE |
Minimize maximum array element by splitting array elements into powers of two at most K times | Function to find the minimum value of the maximum element of the array by splitting at most K array element into perfect powers of 2 ; Sort the array element in the ascending order ; Reverse the array ; If count of 0 is equal to N ; Otherwise , if K is greater than or equal to N ; Otherwise ; Driver Code | def minimumSize ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE arr . reverse ( ) NEW_LINE zero = arr . count ( 0 ) NEW_LINE if zero == N : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT elif K >= N : NEW_LINE INDENT print ( 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ K ] ) NEW_LINE DEDENT DEDENT arr = [ 2 , 4 , 8 , 2 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE minimumSize ( arr , N , K ) NEW_LINE |
Check if removal of a subsequence of non | Function to check if it is possible to sort the array or not ; Stores the index if there are two consecutive 1 's in the array ; Traverse the given array ; Check adjacent same elements having values 1 s ; If there are no two consecutive 1 s , then always remove all the 1 s from array & make it sorted ; If two consecutive 0 ' s β are β β present β after β two β consecutive β β 1' s then array can 't be sorted ; Otherwise , print Yes ; Driver Code | def isPossibleToSort ( arr , N ) : NEW_LINE INDENT idx = - 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] == 1 and arr [ i - 1 ] == 1 ) : NEW_LINE INDENT idx = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( idx == - 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return NEW_LINE DEDENT for i in range ( idx + 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] == 0 and arr [ i - 1 ] == 0 ) : NEW_LINE INDENT print ( " NO " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " YES " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 1 , 0 , 1 , 1 , 0 ] NEW_LINE N = len ( arr ) NEW_LINE isPossibleToSort ( arr , N ) NEW_LINE DEDENT |
Maximize ropes of consecutive length possible by connecting given ropes | Function to find maximized count of ropes of consecutive length ; Stores the maximum count of ropes of consecutive length ; Sort the ropes by their length ; Traverse the array ; If size of the current rope is less than or equal to current maximum possible size + 1 , update the range to curSize + ropes [ i ] ; If a rope of size ( curSize + 1 ) cannot be obtained ; Driver Code ; Input ; Function Call | def maxConsecutiveRopes ( ropes , N ) : NEW_LINE INDENT curSize = 0 NEW_LINE ropes = sorted ( ropes ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( ropes [ i ] <= curSize + 1 ) : NEW_LINE INDENT curSize = curSize + ropes [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return curSize NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE ropes = [ 1 , 2 , 7 , 1 , 1 ] NEW_LINE print ( maxConsecutiveRopes ( ropes , N ) ) NEW_LINE DEDENT |
Maximum ranges that can be uniquely represented by any integer from the range | Function to find the maximum number of ranges where each range can be uniquely represented by an integer ; Sort the ranges in ascending order ; Stores the count of ranges ; Stores previously assigned range ; Traverse the vector arr [ ] ; Skip the similar ranges of size 1 ; Find the range of integer available to be assigned ; Check if an integer is available to be assigned ; Update the previously assigned range ; Update the count of range ; Return the maximum count of ranges ; Driver Code | def maxRanges ( arr , N ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE count = 1 NEW_LINE prev = arr [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT last = arr [ i - 1 ] NEW_LINE current = arr [ i ] NEW_LINE if ( last [ 0 ] == current [ 0 ] and last [ 1 ] == current [ 1 ] and current [ 1 ] == current [ 0 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT start = max ( prev [ 0 ] , current [ 0 ] - 1 ) NEW_LINE end = max ( prev [ 1 ] , current [ 1 ] ) NEW_LINE if ( end - start > 0 ) : NEW_LINE INDENT prev [ 0 ] = 1 + start NEW_LINE prev [ 1 ] = end NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 4 ] , [ 4 , 4 ] , [ 2 , 2 ] , [ 3 , 4 ] , [ 1 , 1 ] ] NEW_LINE N = len ( arr ) NEW_LINE print ( maxRanges ( arr , N ) ) NEW_LINE DEDENT |
Sort a string lexicographically by reversing a substring | Function to find the substring in S required to be reversed ; Stores the size of the string ; Stores the starting point of the substring ; Iterate over the string S while i < N ; Increment the value of i ; Stores the ending index of the substring ; If start <= 0 or i >= N ; If start >= 1 and i <= N ; Return the boolean value ; If start >= 1 ; Return the boolean value ; If i < N ; Return true if S [ start ] is less than or equal to S [ i ] ; Otherwise ; Function to check if it is possible to sort the string or not ; global start , end , i Stores the starting and the ending index of substring ; Stores whether it is possible to sort the substring ; Traverse the range [ 1 , N ] ; If S [ i ] is less than S [ i - 1 ] ; If flag stores true ; If adjust ( S , i , start , end ) return false ; Pr - 1 ; Unset the flag ; Otherwise ; Pr - 1 ; If start is equal to - 1 ; Update start and end ; Print the value of start and end ; Driver Code | def adjust ( S , i , start , end ) : NEW_LINE INDENT N = len ( S ) NEW_LINE start = i - 1 NEW_LINE while ( i < N and S [ i ] < S [ i - 1 ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT end = i - 1 NEW_LINE if ( start <= 0 and i >= N ) : NEW_LINE INDENT return True , start , i , end NEW_LINE DEDENT if ( start >= 1 and i <= N ) : NEW_LINE INDENT return ( S [ end ] >= S [ start - 1 ] and S [ start ] <= S [ i ] ) , start , i , end NEW_LINE DEDENT if ( start >= 1 ) : NEW_LINE INDENT return ( S [ end ] >= S [ start - 1 ] ) , start , i , end NEW_LINE DEDENT if ( i < N ) : NEW_LINE INDENT return ( S [ start ] <= S [ i ] ) , start , i , end NEW_LINE DEDENT return False , start , i , end NEW_LINE DEDENT def isPossible ( S , N ) : NEW_LINE INDENT start , end = - 1 , - 1 NEW_LINE flag = True NEW_LINE i = 1 NEW_LINE while i < N : NEW_LINE INDENT if ( S [ i ] < S [ i - 1 ] ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT f , start , i , end = adjust ( S , i , start , end ) NEW_LINE if ( f == False ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT flag = False NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT if ( start == - 1 ) : NEW_LINE INDENT start , end = 1 , 1 NEW_LINE DEDENT print ( start , end ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcyxuz " NEW_LINE N = len ( S ) NEW_LINE isPossible ( S , N ) NEW_LINE DEDENT |
Split array into K non | Function find maximum sum of minimum and maximum of K subsets ; Stores the result ; Sort the array arr [ ] in decreasing order ; Traverse the range [ 0 , K ] ; Sort the array S [ ] in ascending order ; Traverse the array S [ ] ; If S { i ] is 1 ; Stores the index of the minimum element of the i - th subset ; Traverse the array S [ ] ; Update the counter ; Return the resultant sum ; Driver Code | def maximumSum ( arr , S , N , K ) : NEW_LINE INDENT ans = 0 NEW_LINE arr = sorted ( arr ) [ : : - 1 ] NEW_LINE for i in range ( K ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT S = sorted ( S ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT if ( S [ i ] == 1 ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT S [ i ] -= 1 NEW_LINE DEDENT counter = K - 1 NEW_LINE for i in range ( K ) : NEW_LINE INDENT counter = counter + S [ i ] NEW_LINE if ( S [ i ] != 0 ) : NEW_LINE INDENT ans += arr [ counter ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 13 , 7 , 17 ] NEW_LINE S = [ 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = len ( S ) NEW_LINE print ( maximumSum ( arr , S , N , K ) ) NEW_LINE DEDENT |
Modify an array by sorting after reversal of bits of each array element | Function to convert binary number to equivalent decimal ; Set base value to 1 , i . e 2 ^ 0 ; Function to convert a decimal to equivalent binary representation ; Stores the binary representation ; Since ASCII value of '0' , '1' are 48 and 49 ; As the string is already reversed , no further reversal is required ; Function to convert the reversed binary representation to equivalent integer ; Stores reversed binary representation of given decimal ; Stores equivalent decimal value of the binary representation ; Return the resultant integer ; Utility function to print the sorted array ; Sort the array ; Traverse the array ; Print the array elements ; Utility function to reverse the binary representations of all array elements and sort the modified array ; Traverse the array ; Passing array elements to reversedBinaryDecimal function ; Pass the array to the sorted array ; Driver Code | def binaryToDecimal ( n ) : NEW_LINE INDENT num = n NEW_LINE dec_value = 0 NEW_LINE base = 1 NEW_LINE length = len ( num ) NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( num [ i ] == '1' ) : NEW_LINE INDENT dec_value += base NEW_LINE DEDENT base = base * 2 NEW_LINE DEDENT return dec_value NEW_LINE DEDENT def decimalToBinary ( n ) : NEW_LINE INDENT binstr = " " NEW_LINE while ( n > 0 ) : NEW_LINE INDENT binstr += chr ( n % 2 + 48 ) NEW_LINE n = n // 2 NEW_LINE DEDENT return binstr NEW_LINE DEDENT def reversedBinaryDecimal ( N ) : NEW_LINE INDENT decimal_to_binar = decimalToBinary ( N ) NEW_LINE binary_to_decimal = binaryToDecimal ( decimal_to_binar ) NEW_LINE return binary_to_decimal NEW_LINE DEDENT def printSortedArray ( arr , size ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def modifyArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT arr [ i ] = reversedBinaryDecimal ( arr [ i ] ) NEW_LINE DEDENT printSortedArray ( arr , size ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 98 , 43 , 66 , 83 ] NEW_LINE n = len ( arr ) NEW_LINE modifyArray ( arr , n ) NEW_LINE DEDENT |
Check if sequence of removed middle elements from an array is sorted or not | Function to check if sequence of removed middle elements from an array is sorted or not ; Points toa the ends of the array ; Iterate l + 1 < r ; If the element at index L and R is greater than ( L + 1 ) - th and ( R - 1 ) - th elements ; If true , then decrement R by 1 and increment L by 1 ; Otherwise , return false ; If an increasing sequence is formed , then return true ; Driver Code | def isSortedArray ( arr , n ) : NEW_LINE INDENT l = 0 NEW_LINE r = ( n - 1 ) NEW_LINE while ( ( l + 1 ) < r ) : NEW_LINE INDENT if ( arr [ l ] >= max ( arr [ l + 1 ] , arr [ r - 1 ] ) and arr [ r ] >= max ( arr [ r - 1 ] , arr [ l + 1 ] ) ) : NEW_LINE INDENT l += 1 NEW_LINE r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 3 , 1 , 2 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE if ( isSortedArray ( arr , N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Length of longest strictly increasing subset with each pair of adjacent elements satisfying the condition 2 * A [ i ] Γ’ β°Β₯ A [ i + 1 ] | Function to find the length of the longest subset satisfying given conditions ; Sort the array in ascending order ; Stores the starting index and maximum length of the required subset ; Pointer to traverse the array ; Iterate while i < n ; Stores end point of current subset ; Store the length of the current subset ; Continue adding elements to the current subset till the condition satisfies ; Increment length of the current subset ; Increment the pointer j ; If length of the current subset exceeds overall maximum length ; Update maxlen ; Update index ; Increment j ; Update i ; Store the starting index of the required subset in i ; Print the required subset ; Print the array element ; Decrement maxlen ; Increment i ; Driver Code ; Given array ; Store the size of the array | def maxLenSubset ( a , n ) : NEW_LINE INDENT a . sort ( reverse = False ) NEW_LINE index = 0 NEW_LINE maxlen = - 1 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i NEW_LINE len1 = 1 NEW_LINE while ( j < n - 1 ) : NEW_LINE INDENT if ( 2 * a [ j ] >= a [ j + 1 ] ) : NEW_LINE INDENT len1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( maxlen < len1 ) : NEW_LINE INDENT maxlen = len1 NEW_LINE index = i NEW_LINE DEDENT j += 1 NEW_LINE i = j NEW_LINE DEDENT i = index NEW_LINE while ( maxlen > 0 ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE maxlen -= 1 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 3 , 1 , 5 , 11 ] NEW_LINE n = len ( a ) NEW_LINE maxLenSubset ( a , n ) NEW_LINE DEDENT |
Maximize count of intersecting line segments | Python3 program for the above approach ; Function to find the maximum number of intersecting line segments possible ; Stores pairs of line segments { X [ i ] , Y [ i ] ) ; Push { X [ i ] , Y [ i ] } into p ; Sort p in ascending order of points on X number line ; Stores the points on Y number line in descending order ; Insert the first Y pofrom p ; Binary search to find the lower bound of p [ i ] [ 1 ] ; If lower_bound doesn 't exist ; Insert p [ i ] [ 1 ] into the set ; Erase the next lower _bound from the set ; Insert p [ i ] [ 1 ] into the set ; Return the size of the set as the final result ; Driver Code ; Given Input ; Function call to find the maximum number of intersecting line segments | from bisect import bisect_left NEW_LINE def solve ( N , X , Y ) : NEW_LINE INDENT p = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT p . append ( [ X [ i ] , Y [ i ] ] ) NEW_LINE DEDENT p = sorted ( p ) NEW_LINE s = { } NEW_LINE s [ p [ 0 ] [ 1 ] ] = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT arr = list ( s . keys ( ) ) NEW_LINE it = bisect_left ( arr , p [ i ] [ 1 ] ) NEW_LINE if ( it == len ( s ) ) : NEW_LINE INDENT s [ p [ i ] [ 1 ] ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT del s [ arr [ it ] ] NEW_LINE s [ p [ i ] [ 1 ] ] = 1 NEW_LINE DEDENT DEDENT return len ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 3 NEW_LINE X = [ 1 , 2 , 0 ] NEW_LINE Y = [ 2 , 0 , 1 ] NEW_LINE maxintersection = solve ( N , X , Y ) NEW_LINE print ( maxintersection ) NEW_LINE DEDENT |
Reduce an array to a single element by repeatedly removing larger element from a pair with absolute difference at most K | Function to check if an array can be reduced to single element by removing maximum element among any chosen pairs ; Sort the array in descending order ; Traverse the array ; If the absolute difference of 2 consecutive array elements is greater than K ; If the array can be reduced to a single element ; Driver Code ; Function Call to check if an array can be reduced to a single element | def canReduceArray ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i + 1 ] > K ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 1 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 1 NEW_LINE canReduceArray ( arr , N , K ) NEW_LINE DEDENT |
Lexicographically smallest string possible by merging two sorted strings | Function to find lexicographically smallest possible by merging two sorted strings ; Stores length of s1 ; Stores length of s2 ; Pointer to beginning of string1 i . e . , s1 ; Pointer to beginning of string2 i . e . , s2 ; Stores the final string ; Traverse the strings ; Append the smaller of the two current characters ; Append the remaining characters of any of the two strings ; Print the final string ; Driver Code ; Function Call | def mergeStrings ( s1 , s2 ) : NEW_LINE INDENT len1 = len ( s1 ) NEW_LINE len2 = len ( s2 ) NEW_LINE pntr1 = 0 NEW_LINE pntr2 = 0 NEW_LINE ans = " " NEW_LINE while ( pntr1 < len1 and pntr2 < len2 ) : NEW_LINE INDENT if ( s1 [ pntr1 ] < s2 [ pntr2 ] ) : NEW_LINE INDENT ans += s1 [ pntr1 ] NEW_LINE pntr1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += s2 [ pntr2 ] NEW_LINE pntr2 += 1 NEW_LINE DEDENT DEDENT if ( pntr1 < len1 ) : NEW_LINE INDENT ans += s1 [ pntr1 : pntr1 + len1 ] NEW_LINE DEDENT if ( pntr2 < len2 ) : NEW_LINE INDENT ans += s2 [ pntr2 : pntr2 + len2 ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = " abdcdtx " NEW_LINE S2 = " achilp " NEW_LINE mergeStrings ( S1 , S2 ) NEW_LINE DEDENT |
Sort a string without altering the position of vowels | Function to sort the string leaving the vowels unchanged ; Length of string S ; Traverse the string S ; Sort the string temp ; Pointer to traverse the sorted string of consonants ; Traverse the string S ; Driver Code | def sortStr ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE temp = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] != ' a ' and S [ i ] != ' e ' and S [ i ] != ' i ' and S [ i ] != ' o ' and S [ i ] != ' u ' ) : NEW_LINE INDENT temp += S [ i ] NEW_LINE DEDENT DEDENT if ( len ( temp ) ) : NEW_LINE INDENT p = list ( temp ) NEW_LINE p . sort ( ) NEW_LINE temp = ' ' . join ( p ) NEW_LINE DEDENT ptr = 0 NEW_LINE for i in range ( N ) : NEW_LINE S = list ( S ) NEW_LINE if ( S [ i ] != ' a ' and S [ i ] != ' e ' and S [ i ] != ' i ' and S [ i ] != ' o ' and S [ i ] != ' u ' ) : NEW_LINE INDENT S [ i ] = temp [ ptr ] NEW_LINE ptr += 1 NEW_LINE DEDENT print ( ' ' . join ( S ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE sortStr ( S ) NEW_LINE DEDENT |
Count pairs from an array whose quotient of division of larger number by the smaller number does not exceed K | Python3 program for the above approach ; Function to count the number having quotient of division of larger element by the smaller element in the pair not exceeding K ; Sort the array in ascending order ; Store the required result ; Traverse the array ; Store the upper bound for the current array element ; Update the number of pairs ; Prthe result ; Given array , arr [ ] ; Store the size of the array | from bisect import bisect_right NEW_LINE def countPairs ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT high = bisect_right ( arr , k * arr [ i ] ) NEW_LINE ans += high - i - 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 2 , 3 , 9 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE countPairs ( arr , n , k ) NEW_LINE |
Kth highest XOR of diagonal elements from a Matrix | Function to find K - th maximum XOR of any diagonal in the matrix ; Number or rows ; Number of columns ; Store XOR of diagonals ; Traverse each diagonal ; Starting column of diagonal ; Count total elements in the diagonal ; Store XOR of current diagonal ; Push XOR of current diagonal ; Sort XOR values of diagonals ; Print the K - th Maximum XOR ; Driver Code | def findXOR ( mat , K ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE digXOR = [ ] NEW_LINE for l in range ( 1 , N + M , 1 ) : NEW_LINE INDENT s_col = max ( 0 , l - N ) NEW_LINE count = min ( [ l , ( M - s_col ) , N ] ) NEW_LINE currXOR = 0 NEW_LINE for j in range ( count ) : NEW_LINE INDENT currXOR = ( currXOR ^ mat [ min ( N , l ) - j - 1 ] [ s_col + j ] ) NEW_LINE DEDENT digXOR . append ( currXOR ) NEW_LINE DEDENT digXOR . sort ( reverse = False ) NEW_LINE print ( digXOR [ N + M - 1 - K ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE K = 3 NEW_LINE findXOR ( mat , K ) NEW_LINE DEDENT |
Maximum sum of absolute differences between distinct pairs of a triplet from an array | Function to find the maximum sum of absolute differences between distinct pairs of triplet in array ; Stores the maximum sum ; Sort the array in ascending order ; Sum of differences between pairs of the triplet ; Print the sum ; Driver Code | def maximumSum ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE arr . sort ( ) NEW_LINE sum = ( arr [ N - 1 ] - arr [ 0 ] ) + ( arr [ N - 2 ] - arr [ 0 ] ) + ( arr [ N - 1 ] - arr [ N - 2 ] ) ; NEW_LINE print ( sum ) NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE maximumSum ( arr , N ) NEW_LINE |
Maximum and minimum sum of Bitwise XOR of pairs from an array | Python3 program for the above approach ; c [ int , [ a , b ] ] Function to find the required sum ; Keeps the track of the visited array elements ; Stores the result ; Keeps count of visited elements ; Traverse the vector , V ; If n elements are visited , break out of the loop ; Store the pair ( i , j ) and their Bitwise XOR ; If i and j both are unvisited ; Add xorResult to res and mark i and j as visited ; Increment count by 2 ; Return the result ; Function to find the maximum and minimum possible sum of Bitwise XOR of all the pairs from the array ; Stores the XOR of all pairs ( i , j ) ; Store the XOR of all pairs ( i , j ) ; Update Bitwise XOR ; Sort the vector ; Initialize variables to store maximum and minimum possible sums ; Find the minimum sum possible ; Reverse the vector , v ; Find the maximum sum possible ; Print the result ; Driver Code | v = [ ] NEW_LINE def findSum ( n ) : NEW_LINE INDENT global v NEW_LINE um = { } NEW_LINE res = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( len ( v ) ) : NEW_LINE INDENT if ( cnt == n ) : NEW_LINE INDENT break NEW_LINE DEDENT x = v [ i ] [ 1 ] [ 0 ] NEW_LINE y = v [ i ] [ 1 ] [ 1 ] NEW_LINE xorResult = v [ i ] [ 0 ] NEW_LINE if ( x in um and um [ x ] == False and y in um and um [ y ] == False ) : NEW_LINE INDENT res += xorResult NEW_LINE um [ x ] = True NEW_LINE um [ y ] = True NEW_LINE cnt += 2 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT def findMaxMinSum ( a , n ) : NEW_LINE INDENT global v NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT xorResult = a [ i ] ^ a [ j ] NEW_LINE v . append ( [ xorResult , [ a [ i ] , a [ j ] ] ] ) NEW_LINE DEDENT DEDENT v . sort ( reverse = False ) NEW_LINE maxi = 0 NEW_LINE mini = 0 NEW_LINE mini = findSum ( n ) NEW_LINE mini = 6 NEW_LINE v = v [ : : - 1 ] NEW_LINE maxi = findSum ( n ) NEW_LINE maxi = 10 NEW_LINE print ( mini , maxi ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE findMaxMinSum ( arr , N ) NEW_LINE DEDENT |
Lexicographically smallest permutation having maximum sum of differences between adjacent elements | Function to find the lexicographically smallest permutation of an array such that the sum of the difference between adjacent elements is maximum ; Stores the size of the array ; Sort the given array in increasing order ; Swap the first and last array elements ; Print the required permutation ; Driver Code | def maximumSumPermutation ( arr ) : NEW_LINE INDENT N = len ( arr ) ; NEW_LINE arr . sort ( ) ; NEW_LINE temp = arr [ 0 ] ; NEW_LINE arr [ 0 ] = arr [ N - 1 ] ; NEW_LINE arr [ N - 1 ] = temp ; NEW_LINE for i in arr : NEW_LINE INDENT print ( i , end = " β " ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] ; NEW_LINE maximumSumPermutation ( arr ) ; NEW_LINE DEDENT |
Maximize count of 1 s in an array by repeated division of array elements by 2 at most K times | Python3 program to implement the above approach ; Function to count the maximum number of array elements that can be reduced to 1 by repeatedly dividing array elements by 2 ; Sort the array in ascending order ; Store the count of array elements ; Traverse the array ; Store the number of operations required to reduce arr [ i ] to 1 ; Decrement k by opr ; If k becomes less than 0 , then break out of the loop ; Increment cnt by 1 ; Prthe answer ; Driver Code | import math NEW_LINE def findMaxNumbers ( arr , n , k ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT opr = math . ceil ( math . log2 ( arr [ i ] ) ) NEW_LINE k -= opr NEW_LINE if ( k < 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT cnt += 1 NEW_LINE DEDENT print ( cnt ) NEW_LINE DEDENT arr = [ 5 , 8 , 4 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE findMaxNumbers ( arr , N , K ) NEW_LINE |
Mean of given array after removal of K percent of smallest and largest array elements | Function to calculate the mean of a given array after removal of Kth percent of smallest and largest array elements ; Sort the array ; Find the K - th percent of the array size ; Traverse the array ; Skip the first K - th percent & last K - th percent array elements ; Mean of the rest of elements ; Print mean upto 5 decimal places ; Driver Code | def meanOfRemainingElements ( arr , N , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE kthPercent = ( N * K ) / 100 NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i >= kthPercent and i < ( N - kthPercent ) ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT mean = sum / ( N - 2 * kthPercent ) NEW_LINE print ( ' % .5f ' % mean ) NEW_LINE DEDENT arr = [ 6 , 2 , 7 , 5 , 1 , 2 , 0 , 3 , 10 , 2 , 5 , 0 , 5 , 5 , 0 , 8 , 7 , 6 , 8 , 0 ] NEW_LINE arr_size = len ( arr ) NEW_LINE K = 5 NEW_LINE meanOfRemainingElements ( arr , arr_size , K ) NEW_LINE |
Make the array elements equal by performing given operations minimum number of times | Function to calculate the minimum operations of given type required to make the array elements equal ; Stores the total count of operations ; Traverse the array ; Update difference between pairs of adjacent elements ; Store the maximum count of operations ; Rest of the elements ; Total Operation - Maximum Operation ; Driver Code ; Given array ; Size of the array | def minOperation ( a , N ) : NEW_LINE INDENT totOps = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT totOps += abs ( a [ i ] - a [ i + 1 ] ) NEW_LINE DEDENT maxOps = max ( abs ( a [ 0 ] - a [ 1 ] ) , abs ( a [ N - 1 ] - a [ N - 2 ] ) ) NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT maxOps = max ( maxOps , abs ( a [ i ] - a [ i - 1 ] ) + abs ( a [ i ] - a [ i + 1 ] ) - abs ( a [ i - 1 ] - a [ i + 1 ] ) ) NEW_LINE DEDENT print ( totOps - maxOps ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , - 1 , 0 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE minOperation ( arr , N ) NEW_LINE DEDENT |
Count swaps required to sort an array using Insertion Sort | Stores the sorted array elements ; Function to count the number of swaps required to merge two sorted subarray in a sorted form ; Stores the count of swaps ; Function to count the total number of swaps required to sort the array ; Stores the total count of swaps required ; Find the middle index splitting the two halves ; Count the number of swaps required to sort the left subarray ; Count the number of swaps required to sort the right subarray ; Count the number of swaps required to sort the two sorted subarrays ; Driver Code | temp = [ 0 ] * 100000 NEW_LINE def merge ( A , left , mid , right ) : NEW_LINE INDENT swaps = 0 NEW_LINE i , j , k = left , mid , left NEW_LINE while ( i < mid and j <= right ) : NEW_LINE INDENT if ( A [ i ] <= A [ j ] ) : NEW_LINE INDENT temp [ k ] = A [ i ] NEW_LINE k , i = k + 1 , i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ k ] = A [ j ] NEW_LINE k , j = k + 1 , j + 1 NEW_LINE swaps += mid - i NEW_LINE DEDENT DEDENT while ( i < mid ) : NEW_LINE INDENT temp [ k ] = A [ i ] NEW_LINE k , i = k + 1 , i + 1 NEW_LINE DEDENT while ( j <= right ) : NEW_LINE INDENT temp [ k ] = A [ j ] NEW_LINE k , j = k + 1 , j + 1 NEW_LINE DEDENT while ( left <= right ) : NEW_LINE INDENT A [ left ] = temp [ left ] NEW_LINE left += 1 NEW_LINE DEDENT return swaps NEW_LINE DEDENT def mergeInsertionSwap ( A , left , right ) : NEW_LINE INDENT swaps = 0 NEW_LINE if ( left < right ) : NEW_LINE INDENT mid = left + ( right - left ) // 2 NEW_LINE swaps += mergeInsertionSwap ( A , left , mid ) NEW_LINE swaps += mergeInsertionSwap ( A , mid + 1 , right ) NEW_LINE swaps += merge ( A , left , mid + 1 , right ) NEW_LINE DEDENT return swaps NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 1 , 3 , 1 , 2 ] NEW_LINE N = len ( A ) NEW_LINE print ( mergeInsertionSwap ( A , 0 , N - 1 ) ) NEW_LINE DEDENT |
Maximum removals possible from an array such that sum of its elements is greater than or equal to that of another array | Function to maximize the count of elements required to be removed from arr [ ] such that the sum of arr [ ] is greater than or equal to sum of the array brr [ ] ; Sort the array arr [ ] ; Stores index of smallest element of arr [ ] ; Stores sum of elements of the array arr [ ] ; Traverse the array arr [ ] ; Update sumArr ; Stores sum of elements of the array brr [ ] ; Traverse the array brr [ ] ; Update sumArr ; Stores count of removed elements ; Repeatedly remove the smallest element of arr [ ] ; Update sumArr ; Remove the smallest element ; If the sum of remaining elements in arr [ ] >= sum of brr [ ] ; Update cntRemElem ; Driver Code | def maxCntRemovedfromArray ( arr , N , brr , M ) : NEW_LINE INDENT arr . sort ( reverse = False ) NEW_LINE i = 0 NEW_LINE sumArr = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sumArr += arr [ i ] NEW_LINE DEDENT sumBrr = 0 NEW_LINE for i in range ( M ) : NEW_LINE INDENT sumBrr += brr [ i ] NEW_LINE DEDENT cntRemElem = 0 NEW_LINE while ( i < N and sumArr >= sumBrr ) : NEW_LINE INDENT sumArr -= arr [ i ] NEW_LINE i += 1 NEW_LINE if ( sumArr >= sumBrr ) : NEW_LINE INDENT cntRemElem += 1 NEW_LINE DEDENT DEDENT return cntRemElem NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 6 ] NEW_LINE brr = [ 7 ] NEW_LINE N = len ( arr ) NEW_LINE M = len ( brr ) NEW_LINE print ( maxCntRemovedfromArray ( arr , N , brr , M ) ) NEW_LINE DEDENT |
Find any two pairs ( a , b ) and ( c , d ) such that a d | Function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; If no such pair is found ; Driver Code | def findPair ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT a , b = arr [ i ] [ 0 ] , arr [ i ] [ 1 ] NEW_LINE for j in range ( i + 1 , N ) : NEW_LINE INDENT c , d = arr [ j ] [ 0 ] , arr [ j ] [ 1 ] NEW_LINE if ( a < c and b > d ) : NEW_LINE INDENT print ( " ( " , a , b , " ) , β ( " , c , d , " ) " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT print ( " NO β SUCH β PAIR β EXIST " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 3 , 7 ] , [ 21 , 23 ] , [ 4 , 13 ] , [ 1 , 2 ] , [ 7 , - 1 ] ] NEW_LINE findPair ( arr , 5 ) NEW_LINE DEDENT |
Find any two pairs ( a , b ) and ( c , d ) such that a d | Function to find two pairs ( a , b ) and ( c , d ) such that a < c and b > d ; Sort the array in increasing order of first element of pairs ; Traverse the array ; If no such pair found ; Driver Code | def findPair ( arr , N ) : NEW_LINE INDENT arr . sort ( key = lambda x : x [ 0 ] ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT b = arr [ i - 1 ] [ 1 ] NEW_LINE d = arr [ i ] [ 1 ] NEW_LINE if ( b > d ) : NEW_LINE INDENT print ( " ( " , arr [ i - 1 ] [ 0 ] , b , " ) , β ( " , arr [ i ] [ 0 ] , d , " ) " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " NO SUCH PAIR EXIST " ) ; NEW_LINE DEDENT arr = [ [ 3 , 7 ] , [ 21 , 23 ] , [ 4 , 13 ] , [ 1 , 2 ] , [ 7 , - 1 ] ] NEW_LINE findPair ( arr , 5 ) NEW_LINE |
Print indices in non | Function to print the order of array elements generating non - decreasing quotient after division by X ; Stores the quotient and the order ; Traverse the array ; Sort the vector ; Print the order ; Driver Code | def printOrder ( order , N , X ) : NEW_LINE INDENT vect = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( order [ i ] % X == 0 ) : NEW_LINE INDENT vect . append ( [ order [ i ] // X , i + 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT vect . append ( [ order [ i ] // X + 1 , i + 1 ] ) NEW_LINE DEDENT DEDENT vect = sorted ( vect ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( vect [ i ] [ 1 ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , X = 3 , 3 NEW_LINE order = [ 2 , 7 , 4 ] NEW_LINE printOrder ( order , N , X ) NEW_LINE DEDENT |
Shuffle 2 n integers as a1 | Function to reverse the array from the position ' start ' to position 'end ; Stores mid of start and end ; Traverse the array in the range [ start , end ] ; Stores arr [ start + i ] ; Update arr [ start + i ] ; Update arr [ end - i ] ; Utility function to shuffle the given array in the of form { a1 , b1 , a2 , b2 , ... . an , bn } ; Stores the length of the array ; If length of the array is 2 ; Stores mid of the { start , end } ; Divide array into two halves of even length ; Update mid ; Calculate the mid - points of both halves of the array ; Reverse the subarray made from mid1 to mid2 ; Reverse the subarray made from mid1 to mid ; Reverse the subarray made from mid to mid2 ; Recursively calls for both the halves of the array ; Function to shuffle the given array in the form of { a1 , b1 , a2 , b2 , ... . an , bn } ; Function Call ; Print the modified array ; Driver Code ; Given array ; Size of the array ; Shuffles the given array to the required permutation | ' NEW_LINE def reverse ( arr , start , end ) : NEW_LINE INDENT mid = ( end - start + 1 ) // 2 NEW_LINE for i in range ( mid ) : NEW_LINE INDENT temp = arr [ start + i ] NEW_LINE arr [ start + i ] = arr [ end - i ] NEW_LINE arr [ end - i ] = temp NEW_LINE DEDENT return arr NEW_LINE DEDENT def shuffleArrayUtil ( arr , start , end ) : NEW_LINE INDENT i = 0 NEW_LINE l = end - start + 1 NEW_LINE if ( l == 2 ) : NEW_LINE INDENT return NEW_LINE DEDENT mid = start + l // 2 NEW_LINE if ( l % 4 ) : NEW_LINE INDENT mid -= 1 NEW_LINE DEDENT mid1 = start + ( mid - start ) // 2 NEW_LINE mid2 = mid + ( end + 1 - mid ) // 2 NEW_LINE arr = reverse ( arr , mid1 , mid2 - 1 ) NEW_LINE arr = reverse ( arr , mid1 , mid - 1 ) NEW_LINE arr = reverse ( arr , mid , mid2 - 1 ) NEW_LINE shuffleArrayUtil ( arr , start , mid - 1 ) NEW_LINE shuffleArrayUtil ( arr , mid , end ) NEW_LINE DEDENT def shuffleArray ( arr , N , start , end ) : NEW_LINE INDENT shuffleArrayUtil ( arr , start , end ) NEW_LINE for i in arr : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 5 , 2 , 4 , 6 ] NEW_LINE N = len ( arr ) NEW_LINE shuffleArray ( arr , N , 0 , N - 1 ) NEW_LINE DEDENT |
Reduce sum of same | Function to check if elements of B can be rearranged such that A [ i ] + B [ i ] <= X ; Checks the given condition ; Sort A in ascending order ; Sort B in descending order ; Traverse the arrays A and B ; If A [ i ] + B [ i ] exceeds X ; Rearrangement not possible , set flag to false ; If flag is true ; Otherwise ; Driver Code ; Function Call | def rearrange ( A , B , N , X ) : NEW_LINE INDENT flag = True NEW_LINE A = sorted ( A ) NEW_LINE B = sorted ( B ) [ : : - 1 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( A [ i ] + B [ i ] > X ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : 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 = [ 1 , 2 , 3 ] NEW_LINE B = [ 1 , 1 , 2 ] NEW_LINE X = 4 NEW_LINE N = len ( A ) NEW_LINE rearrange ( A , B , N , X ) NEW_LINE DEDENT |
Minimum increments or decrements by D required to make all array elements equal | Function to find minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Sort the array ; Traverse the array ; If difference between two consecutive elements are not divisible by D ; Store minimum count of operations required to make all array elements equal by incrementing or decrementing array elements by d ; Stores middle element of the array ; Traverse the array ; Update count ; Driver Code ; Given N & D ; Given array arr [ ] ; Function Call | def numOperation ( arr , N , D ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( ( arr [ i + 1 ] - arr [ i ] ) % D != 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE return NEW_LINE DEDENT DEDENT count = 0 NEW_LINE mid = arr [ N // 2 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT count += abs ( mid - arr [ i ] ) // D NEW_LINE DEDENT print ( count ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE D = 2 NEW_LINE arr = [ 2 , 4 , 6 , 8 ] NEW_LINE numOperation ( arr , N , D ) NEW_LINE DEDENT |
Maximize sum of second minimums of each K length partitions of the array | Function to find the maximum sum of second smallest of each partition of size K ; Sort the array A in ascending order ; Store the maximum sum of second smallest of each partition of size K ; Select every ( K - 1 ) th element as second smallest element ; Update sum ; Print the maximum sum ; Driver Code ; Given size of partitions ; Given array A ; Size of the given array ; Function Call | def findSum ( A , N , K ) : NEW_LINE INDENT A . sort ( ) ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( N // K , N , K - 1 ) : NEW_LINE INDENT sum += A [ i ] ; NEW_LINE DEDENT print ( sum ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 4 ; NEW_LINE A = [ 2 , 3 , 1 , 4 , 7 , 5 , 6 , 1 ] ; NEW_LINE N = len ( A ) ; NEW_LINE findSum ( A , N , K ) ; NEW_LINE DEDENT |
Minimize remaining array element by removing pairs and replacing them with their average | Function to find the smallest element left in the array by removing pairs and inserting their average ; Stores array elements such that the largest element present at top of PQ ; Traverse the array ; Insert arr [ i ] into PQ ; Iterate over elements of PQ while count of elements in PQ greater than 1 ; Stores largest element of PQ ; Pop the largest element of PQ ; Stores largest element of PQ ; Pop the largest element of PQ ; Insert the ceil value of average of top1 and top2 ; Driver Code | def findSmallestNumLeft ( arr , N ) : NEW_LINE INDENT PQ = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT PQ . append ( arr [ i ] ) NEW_LINE DEDENT PQ = sorted ( PQ ) NEW_LINE while ( len ( PQ ) > 1 ) : NEW_LINE INDENT top1 = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE top2 = PQ [ - 1 ] NEW_LINE del PQ [ - 1 ] NEW_LINE PQ . append ( ( top1 + top2 + 1 ) // 2 ) NEW_LINE PQ = sorted ( PQ ) NEW_LINE DEDENT return PQ [ - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 30 , 16 , 40 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findSmallestNumLeft ( arr , N ) ) NEW_LINE DEDENT |
Find the array element from indices not divisible by K having largest composite product of digits | Python3 program to implement the above approach ; Function to check if a number is a composite number or not ; Corner cases ; Check if number is divisible by 2 or 3 ; Check if number is a multiple of any other prime number ; Function to calculate the product of digits of a number ; Stores the product of digits ; Extract digits of a number ; Calculate product of digits ; Function to check if the product of digits of a number is a composite number or not ; Stores product of digits ; If product of digits is equal to 1 ; If product of digits is not prime ; Function to find the number with largest composite product of digits from the indices not divisible by k from the given array ; Traverse the array ; If index is divisible by k ; Check if product of digits is a composite number or not ; Sort the products ; Driver Code | from math import ceil , sqrt NEW_LINE def isComposite ( n ) : NEW_LINE INDENT if ( n <= 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n <= 3 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n % 2 == 0 or n % 3 == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT for i in range ( 5 , ceil ( sqrt ( n ) ) , 6 ) : NEW_LINE INDENT if ( n % i == 0 or n % ( i + 2 ) == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def digitProduct ( number ) : NEW_LINE INDENT product = 1 NEW_LINE while ( number > 0 ) : NEW_LINE INDENT product *= ( number % 10 ) NEW_LINE number //= 10 NEW_LINE DEDENT return product NEW_LINE DEDENT def compositedigitProduct ( num ) : NEW_LINE INDENT res = digitProduct ( num ) NEW_LINE if ( res == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( isComposite ( res ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def largestCompositeDigitProduct ( a , n , k ) : NEW_LINE INDENT pq = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( ( i % k ) == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( compositedigitProduct ( a [ i ] ) ) : NEW_LINE INDENT b = digitProduct ( a [ i ] ) NEW_LINE pq . append ( [ b , a [ i ] ] ) NEW_LINE DEDENT DEDENT pq = sorted ( pq ) NEW_LINE return pq [ - 1 ] [ 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 233 , 144 , 89 , 71 , 13 , 21 , 11 , 34 , 55 , 23 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE ans = largestCompositeDigitProduct ( arr , n , k ) NEW_LINE print ( ans ) NEW_LINE DEDENT |
Split array into K | Function to find the minimum sum of 2 nd smallest elements of each subset ; Sort the array ; Stores minimum sum of second elements of each subset ; Traverse first K 2 nd smallest elements ; Update their sum ; Prthe sum ; Driver Code ; Given Array ; Given size of the array ; Given subset lengths | def findMinimum ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE ans = 0 NEW_LINE for i in range ( 1 , 2 * ( N // K ) , 2 ) : NEW_LINE INDENT ans += arr [ i ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 20 , 5 , 7 , 8 , 14 , 2 , 17 , 16 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE findMinimum ( arr , N , K ) NEW_LINE DEDENT |
Find two non | Function to check if two non - intersecting subarrays with equal sum exists or not ; Sort the given array ; Traverse the array ; Check for duplicate elements ; If no duplicate element is present in the array ; Driver code ; Given array ; Size of array | def findSubarrays ( arr , N ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE i = 0 ; NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT print ( " YES " ) ; NEW_LINE return ; NEW_LINE DEDENT DEDENT print ( " NO " ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 3 , 0 , 1 , 2 , 0 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE findSubarrays ( arr , N ) ; NEW_LINE DEDENT |
Selection Sort VS Bubble Sort | Function for bubble sort ; Iterate from 1 to n - 1 ; Iterate from 0 to n - i - 1 ; Driver Code | def Bubble_Sort ( arr , n ) : NEW_LINE INDENT flag = True NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT flag = False NEW_LINE for j in range ( n - i ) : NEW_LINE INDENT if ( arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ] NEW_LINE flag = True NEW_LINE DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT n = 5 NEW_LINE arr = [ 2 , 0 , 1 , 4 , 3 ] NEW_LINE Bubble_Sort ( arr , n ) NEW_LINE print ( " The β Sorted β Array β by β using β Bubble β Sort β is β : β " , end = ' ' ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Print all array elements appearing more than N / K times | Function to prall array elements whose frequency is greater than N / K ; Sort the array , arr [ ] ; Traverse the array ; Stores frequency of arr [ i ] ; Traverse array elements which is equal to arr [ i ] ; Update cnt ; Update i ; If frequency of arr [ i ] is greater than ( N / K ) ; Driver Code | def NDivKWithFreq ( arr , N , K ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE i = 0 NEW_LINE while i < N : NEW_LINE INDENT cnt = 1 NEW_LINE while ( ( i + 1 ) < N and arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT cnt += 1 NEW_LINE i += 1 NEW_LINE DEDENT if ( cnt > ( N // K ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 6 , 6 , 6 , 6 , 7 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE NDivKWithFreq ( arr , N , K ) NEW_LINE DEDENT |
Sort M elements of given circular array starting from index K | Function to print the circular array ; Print the array ; Function to sort m elements of diven circular array starting from index k ; Traverse M elements ; Iterate from index k to k + m - 1 ; Check if the next element in the circular array is less than the current element ; Swap current element with the next element ; Print the circular array ; Driver Code ; Function Call | def printCircularArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def sortCircularArray ( arr , n , k , m ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( k , k + m - 1 ) : NEW_LINE INDENT if ( arr [ j % n ] > arr [ ( j + 1 ) % n ] ) : NEW_LINE INDENT arr [ j % n ] , arr [ ( j + 1 ) % n ] = ( arr [ ( j + 1 ) % n ] , arr [ j % n ] ) NEW_LINE DEDENT DEDENT DEDENT printCircularArray ( arr , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 1 , 6 , 5 , 3 ] NEW_LINE K = 2 NEW_LINE M = 3 NEW_LINE N = len ( arr ) NEW_LINE sortCircularArray ( arr , N , K , M ) NEW_LINE DEDENT |
Minimize cost required to complete all processes | Function to find minimum cost required to complete all the process ; Sort the array on descending order of Y ; Stores length of array ; Stores minimum cost required to complete all the process ; Stores minimum cost to initiate any process ; Traverse the array ; If minCostInit is less than the cost to initiate the process ; Update minCost ; Update minCostInit ; Update minCostInit ; Return minCost ; Driver Code ; Function Call | def minimumCostReqToCompthePrcess ( arr ) : NEW_LINE INDENT arr . sort ( key = lambda x : x [ 0 ] - x [ 1 ] ) NEW_LINE n = len ( arr ) NEW_LINE minCost = 0 NEW_LINE minCostInit = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] [ 1 ] > minCostInit : NEW_LINE INDENT minCost += ( arr [ i ] [ 1 ] - minCostInit ) NEW_LINE minCostInit = arr [ i ] [ 1 ] NEW_LINE DEDENT minCostInit -= arr [ i ] [ 0 ] NEW_LINE DEDENT return minCost NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 ] , [ 2 , 4 ] , [ 4 , 8 ] ] NEW_LINE print ( minimumCostReqToCompthePrcess ( arr ) ) NEW_LINE DEDENT |
Split array into equal length subsets with maximum sum of Kth largest element of each subset | Function to find the maximum sum of Kth largest element of M equal length partition ; Stores sum of K_th largest element of equal length partitions ; If N is not divisible by M ; Stores length of each partition ; If K is greater than length of partition ; Sort array in descending porder ; Traverse the array ; Update maxSum ; Driver code | def maximumKthLargestsumPart ( arr , N , M , K ) : NEW_LINE INDENT maxSum = 0 NEW_LINE if ( N % M != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT sz = ( N / M ) NEW_LINE if ( K > sz ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT arr = sorted ( arr ) NEW_LINE for i in range ( 0 , N // 2 ) : NEW_LINE INDENT t = arr [ i ] NEW_LINE arr [ i ] = arr [ N - i - 1 ] NEW_LINE arr [ N - i - 1 ] = t NEW_LINE DEDENT for i in range ( 1 , M + 1 ) : NEW_LINE INDENT maxSum += arr [ i * K - 1 ] NEW_LINE DEDENT return maxSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE M = 2 NEW_LINE K = 1 NEW_LINE N = len ( arr ) NEW_LINE print ( maximumKthLargestsumPart ( arr , N , M , K ) ) NEW_LINE DEDENT |
Minimize difference between maximum and minimum array elements by exactly K removals | Function to minimize the difference of the maximum and minimum array elements by removing K elements ; Base Condition ; Sort the array ; Initialize left and right pointers ; Iterate for K times ; Removing right element to reduce the difference ; Removing the left element to reduce the difference ; Print the minimum difference ; Driver Code ; Function Call | def minimumRange ( arr , N , K ) : NEW_LINE INDENT if ( K >= N ) : NEW_LINE INDENT print ( 0 , end = ' ' ) ; NEW_LINE return ; NEW_LINE DEDENT arr . sort ( ) ; NEW_LINE left = 0 ; right = N - 1 ; NEW_LINE for i in range ( K ) : NEW_LINE INDENT if ( arr [ right - 1 ] - arr [ left ] < arr [ right ] - arr [ left + 1 ] ) : NEW_LINE INDENT right -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT left += 1 ; NEW_LINE DEDENT DEDENT print ( arr [ right ] - arr [ left ] , end = ' ' ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 10 , 12 , 14 , 21 , 54 , 61 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 4 ; NEW_LINE minimumRange ( arr , N , K ) ; NEW_LINE DEDENT |
Split array into K subsets to maximize sum of their second largest elements | Function to split array into K subsets having maximum sum of their second maximum elements ; Sort the array ; Stores the maximum possible sum of second maximums ; Add second maximum of current subset ; Proceed to the second maximum of next subset ; Print the maximum sum obtained ; Driver Code ; Given array arr [ ] ; Size of array ; Function Call | def splitArray ( arr , n , K ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE i = n - 1 NEW_LINE result = 0 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT result += arr [ i - 1 ] NEW_LINE i -= 2 NEW_LINE K -= 1 NEW_LINE DEDENT print ( result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 3 , 1 , 5 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE splitArray ( arr , N , K ) NEW_LINE DEDENT |
Count subsequences for every array element in which they are the maximum | Function to merge the subarrays arr [ l . . m ] and arr [ m + 1 , . . r ] based on indices [ ] ; If a [ indices [ l ] ] is less than a [ indices [ j ] ] , add indice [ l ] to temp ; Else add indices [ j ] ; Add remaining elements ; Add remainging elements ; Recursive function to divide the array into to parts ; Recursive call for elements before mid ; Recursive call for elements after mid ; Merge the two sorted arrays ; Function to find the number of subsequences for each element ; Sorting the indices according to array arr [ ] ; Array to store output numbers ; Initialize subseq ; B [ i ] is 2 ^ i ; Doubling the subsequences ; Print the final output , array B [ ] ; Driver Code ; Given array ; Given length ; Function call | def merge ( indices , a , l , mid , r ) : NEW_LINE INDENT temp_ind = [ 0 ] * ( r - l + 1 ) NEW_LINE j = mid + 1 NEW_LINE i = 0 NEW_LINE temp_l = l NEW_LINE while ( l <= mid and j <= r ) : NEW_LINE INDENT if ( a [ indices [ l ] ] < a [ indices [ j ] ] ) : NEW_LINE INDENT temp_ind [ i ] = indices [ l ] NEW_LINE i += 1 NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp_ind [ i ] = indices [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while ( l <= mid ) : NEW_LINE INDENT temp_ind [ i ] = indices [ l ] NEW_LINE i += 1 NEW_LINE l += 1 NEW_LINE DEDENT while ( j <= r ) : NEW_LINE INDENT temp_ind [ i ] = indices [ j ] NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE DEDENT for k in range ( i ) : NEW_LINE INDENT indices [ temp_l ] = temp_ind [ k ] NEW_LINE temp_l += 1 NEW_LINE DEDENT DEDENT def divide ( indices , a , l , r ) : NEW_LINE INDENT if ( l >= r ) : NEW_LINE INDENT return NEW_LINE DEDENT mid = l // 2 + r // 2 NEW_LINE divide ( indices , a , l , mid ) NEW_LINE divide ( indices , a , mid + 1 , r ) NEW_LINE merge ( indices , a , l , mid , r ) NEW_LINE DEDENT def noOfSubsequences ( arr , N ) : NEW_LINE INDENT indices = N * [ 0 ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT indices [ i ] = i NEW_LINE DEDENT divide ( indices , arr , 0 , N - 1 ) NEW_LINE B = [ 0 ] * N NEW_LINE subseq = 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT B [ indices [ i ] ] = subseq NEW_LINE subseq *= 2 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( B [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE noOfSubsequences ( arr , N ) NEW_LINE DEDENT |
Maximize cost to empty given array by repetitively removing K array elements | Function to find the maximum cost to remove all array elements ; Stores maximum cost to remove array elements ; Sort array in ascending order ; Traverse the array ; Update maxCost ; Driver Code | def maxCostToRemove ( arr , N , K ) : NEW_LINE INDENT maxCost = 0 NEW_LINE arr = sorted ( arr ) NEW_LINE for i in range ( 0 , N , K ) : NEW_LINE INDENT maxCost += arr [ i + 1 ] NEW_LINE DEDENT return maxCost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 4 , 1 , 5 , 1 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE print ( maxCostToRemove ( arr , N , K ) ) NEW_LINE DEDENT |
Print all numbers up to N in words in lexicographical order | Function to convert a number to words ; Stores the digits ; Base cases ; Stores strings of unit place ; Stores strings for corner cases ; Stores strings for ten 's place digits ; Stores strings for powers of 10 ; If given number contains a single digit ; Iterate over all the digits ; Represent first 2 digits in words ; Represent last 2 digits in words ; Explicitly handle corner cases [ 10 , 19 ] ; Explicitly handle corner case 20 ; For rest of the two digit numbers i . e . , 21 to 99 ; Function to print all the numbers up to n in lexicographical order ; Convert all numbers in words ; Sort all strings ; Print answer ; Driver Code | def convert_to_words ( n ) : NEW_LINE INDENT num = str ( n ) NEW_LINE length = len ( num ) NEW_LINE ans = " " NEW_LINE if ( length == 0 ) : NEW_LINE INDENT ans += " Empty β String " NEW_LINE return ans NEW_LINE DEDENT single_digits = [ " zero " , " one " , " two " , " three " , " four " , " five " , " six " , " seven " , " eight " , " nine " ] NEW_LINE two_digits = [ " " , " ten " , " eleven " , " twelve " , " thirteen " , " fourteen " , " fifteen " , " sixteen " , " seventeen " , " eighteen " , " nineteen " ] NEW_LINE tens_multiple = [ " " , " " , " twenty " , " thirty " , " forty " , " fifty " , " sixty " , " seventy " , " eighty " , " ninety " ] NEW_LINE tens_power = [ " hundred " , " thousand " ] NEW_LINE if ( length == 1 ) : NEW_LINE INDENT ans += single_digits [ ord ( num [ 0 ] ) - ord ( '0' ) ] NEW_LINE return ans NEW_LINE DEDENT x = 0 NEW_LINE while ( x < len ( num ) ) : NEW_LINE INDENT if ( length >= 3 ) : NEW_LINE INDENT if ( num [ x ] - '0' != 0 ) : NEW_LINE INDENT ans += single_digits [ ord ( num [ x ] ) - ord ( '0' ) ] NEW_LINE ans += " β " NEW_LINE ans += tens_power [ len - 3 ] NEW_LINE ans += " β " NEW_LINE DEDENT length -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( ord ( num [ x ] ) - ord ( '0' ) == 1 ) : NEW_LINE INDENT sum = ( ord ( num [ x ] ) - ord ( '0' ) + ord ( num [ x ] ) - ord ( '0' ) ) NEW_LINE ans += two_digits [ sum ] NEW_LINE return ans NEW_LINE DEDENT elif ( ord ( num [ x ] ) - ord ( '0' ) == 2 and ord ( num [ x + 1 ] ) - ord ( '0' ) == 0 ) : NEW_LINE INDENT ans += " twenty " NEW_LINE return ans NEW_LINE DEDENT else : NEW_LINE INDENT i = ( ord ( num [ x ] ) - ord ( '0' ) ) NEW_LINE if ( i > 0 ) : NEW_LINE INDENT ans += tens_multiple [ i ] NEW_LINE ans += " β " NEW_LINE DEDENT else : NEW_LINE ans += " " NEW_LINE x += 1 NEW_LINE if ( ord ( num [ x ] ) - ord ( '0' ) != 0 ) : NEW_LINE INDENT ans += single_digits [ ord ( num [ x ] ) - ord ( '0' ) ] NEW_LINE DEDENT DEDENT DEDENT x += 1 NEW_LINE DEDENT return " " NEW_LINE DEDENT def lexNumbers ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s . append ( convert_to_words ( i ) ) NEW_LINE DEDENT s . sort ( ) NEW_LINE ans = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans . append ( s [ i ] ) NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT print ( ans [ i ] , end = " , β " ) NEW_LINE DEDENT print ( ans [ n - 1 ] , end = " " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE lexNumbers ( n ) NEW_LINE DEDENT |
Minimize cost to convert all array elements to 0 | Python3 program for the above approach ; Function to calculate the minimum cost of converting all array elements to 0 s ; Stores subarrays of 0 s only ; Traverse the array ; If consecutive 0 s occur ; Increment if needed ; Push the current length of consecutive 0 s in a vector ; Update lengths as 0 ; Sorting vector ; Stores the number of subarrays consisting of 1 s ; Traverse the array ; If current element is 1 ; Otherwise ; Increment count of consecutive ones ; Stores the minimum cost ; Traverse the array ; First element ; Traverse the subarray sizes ; Update cost ; Cost of performing X and Y operations ; Find the minimum cost ; Print the minimum cost ; Driver Code ; Function Call | import sys NEW_LINE def minimumCost ( binary , n , a , b ) : NEW_LINE INDENT groupOfZeros = [ ] NEW_LINE length = 0 NEW_LINE i = 0 NEW_LINE increment_need = True NEW_LINE while ( i < n ) : NEW_LINE INDENT increment_need = True NEW_LINE while ( i < n and binary [ i ] == 0 ) : NEW_LINE INDENT length += 1 NEW_LINE i += 1 NEW_LINE increment_need = False NEW_LINE DEDENT if ( increment_need == True ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT if ( length != 0 ) : NEW_LINE INDENT groupOfZeros . append ( length ) NEW_LINE DEDENT length = 0 NEW_LINE DEDENT groupOfZeros . sort ( ) NEW_LINE i = 0 NEW_LINE found_ones = False NEW_LINE NumOfOnes = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT found_ones = False NEW_LINE while ( i < n and binary [ i ] == 1 ) : NEW_LINE INDENT i += 1 NEW_LINE found_ones = True NEW_LINE DEDENT if ( found_ones == False ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT NumOfOnes += 1 NEW_LINE DEDENT DEDENT ans = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr = 0 NEW_LINE totalOnes = NumOfOnes NEW_LINE if ( i == 0 ) : NEW_LINE INDENT curr = totalOnes * a NEW_LINE DEDENT else : NEW_LINE INDENT mark = i NEW_LINE num_of_changes = 0 NEW_LINE for x in groupOfZeros : NEW_LINE INDENT if ( mark >= x ) : NEW_LINE INDENT totalOnes -= 1 NEW_LINE mark -= x NEW_LINE num_of_changes += x NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT curr = ( ( num_of_changes * b ) + ( totalOnes * a ) ) NEW_LINE DEDENT ans = min ( ans , curr ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 1 , 0 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE X = 10 NEW_LINE Y = 4 NEW_LINE minimumCost ( arr , N , X , Y ) NEW_LINE DEDENT |
Reduce array to longest sorted array possible by removing either half of given array in each operation | Function to check if the subarray arr [ i . . j ] is a sorted subarray or not ; Traverse all elements of the subarray arr [ i ... j ] ; If the previous element of the subarray exceeds current element ; Return 0 ; Return 1 ; Recursively partition the array into two equal halves ; If atmost one element is left in the subarray arr [ i . . j ] ; Checks if subarray arr [ i . . j ] is a sorted subarray or not ; If the subarray arr [ i ... j ] is a sorted subarray ; Stores middle element of the subarray arr [ i . . j ] ; Recursively partition the current subarray arr [ i . . j ] into equal halves ; Driver Code | def isSortedparitions ( arr , i , j ) : NEW_LINE INDENT for k in range ( i + 1 , j + 1 ) : NEW_LINE INDENT if ( arr [ k ] < arr [ k - 1 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE DEDENT def partitionsArr ( arr , i , j ) : NEW_LINE INDENT if ( i >= j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT flag = int ( isSortedparitions ( arr , i , j ) ) NEW_LINE if ( flag != 0 ) : NEW_LINE INDENT return ( j - i + 1 ) NEW_LINE DEDENT mid = ( i + j ) // 2 NEW_LINE X = partitionsArr ( arr , i , mid ) ; NEW_LINE Y = partitionsArr ( arr , mid + 1 , j ) NEW_LINE return max ( X , Y ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 12 , 1 , 2 , 13 , 14 , 3 , 4 ] NEW_LINE N = len ( arr ) NEW_LINE print ( partitionsArr ( arr , 0 , N - 1 ) ) NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.