text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Find k | Structure to store the start and end point ; Function to find Kth smallest number in a vector of merged intervals ; Traverse merged [ ] to find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ; Merging all intervals into merged ; To check if starting point of next range is lying between the previous range and ending point of next range is greater than the Ending point of previous range then update ending point of previous range by ending point of next range . ; If starting point of next range is greater than the ending point of previous range then store next range in merged [ ] . ; Driver Code ; Merge all intervals into merged [ ] ; Processing all queries on merged intervals | class Interval : NEW_LINE INDENT def __init__ ( self , s , e ) : NEW_LINE INDENT self . s = s NEW_LINE self . e = e NEW_LINE DEDENT DEDENT def kthSmallestNum ( merged : list , k : int ) -> int : NEW_LINE INDENT n = len ( merged ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT if k <= abs ( merged [ j ] . e - merged [ j ] . s + 1 ) : NEW_LINE INDENT return merged [ j ] . s + k - 1 NEW_LINE DEDENT k = k - abs ( merged [ j ] . e - merged [ j ] . s + 1 ) NEW_LINE DEDENT if k : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT def mergeIntervals ( merged : list , arr : list , n : int ) : NEW_LINE INDENT arr . sort ( key = lambda a : a . s ) NEW_LINE merged . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prev = merged [ - 1 ] NEW_LINE curr = arr [ i ] NEW_LINE if curr . s >= prev . s and curr . s <= prev . e and curr . e > prev . e : NEW_LINE INDENT merged [ - 1 ] . e = curr . e NEW_LINE DEDENT else : NEW_LINE INDENT if curr . s > prev . e : NEW_LINE INDENT merged . append ( curr ) NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ Interval ( 2 , 6 ) , Interval ( 4 , 7 ) ] NEW_LINE n = len ( arr ) NEW_LINE query = [ 5 , 8 ] NEW_LINE q = len ( query ) NEW_LINE merged = [ ] NEW_LINE mergeIntervals ( merged , arr , n ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( kthSmallestNum ( merged , query [ i ] ) ) NEW_LINE DEDENT DEDENT |
Grouping Countries | Python3 program to count no of distinct countries from a given group of people ; Answer is valid if adjacent sitting num people give same answer ; someone gives different answer ; check next person ; one valid country group has been found ; Driven code | def countCountries ( ans , N ) : NEW_LINE INDENT total_countries = 0 NEW_LINE i = 0 NEW_LINE invalid = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT curr_size = ans [ i ] NEW_LINE num = ans [ i ] NEW_LINE while ( num > 0 ) : NEW_LINE INDENT if ( ans [ i ] != curr_size ) : NEW_LINE INDENT print ( " Invalid β Answer " ) NEW_LINE return ; NEW_LINE DEDENT else : NEW_LINE INDENT num = num - 1 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT total_countries = total_countries + 1 ; NEW_LINE DEDENT print ( " There β are β " , total_countries , " β distinct β companies β in β the β group . " ) NEW_LINE DEDENT ans = [ 1 , 1 , 2 , 2 , 4 , 4 , 4 , 4 ] ; NEW_LINE n = len ( ans ) ; NEW_LINE countCountries ( ans , n ) ; NEW_LINE |
Deepest left leaf node in a binary tree | A binary tree node ; Constructor to create a new node ; A utility function to find deepest leaf node . lvl : level of current node . maxlvl : pointer to the deepest left leaf node found so far isLeft : A bool indicate that this node is left child of its parent resPtr : Pointer to the result ; Base CAse ; Update result if this node is left leaf and its level is more than the max level of the current result ; Recur for left and right subtrees ; A wrapper for left and right subtree ; Driver program to test above function | class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def deepestLeftLeafUtil ( root , lvl , maxlvl , isLeft ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if ( isLeft is True ) : NEW_LINE INDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT if lvl > maxlvl [ 0 ] : NEW_LINE INDENT deepestLeftLeafUtil . resPtr = root NEW_LINE maxlvl [ 0 ] = lvl NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT deepestLeftLeafUtil ( root . left , lvl + 1 , maxlvl , True ) NEW_LINE deepestLeftLeafUtil ( root . right , lvl + 1 , maxlvl , False ) NEW_LINE DEDENT def deepestLeftLeaf ( root ) : NEW_LINE INDENT maxlvl = [ 0 ] NEW_LINE deepestLeftLeafUtil . resPtr = None NEW_LINE deepestLeftLeafUtil ( root , 0 , maxlvl , False ) NEW_LINE return deepestLeftLeafUtil . resPtr NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . right . left = Node ( 5 ) NEW_LINE root . right . right = Node ( 6 ) NEW_LINE root . right . left . right = Node ( 7 ) NEW_LINE root . right . right . right = Node ( 8 ) NEW_LINE root . right . left . right . left = Node ( 9 ) NEW_LINE root . right . right . right . right = Node ( 10 ) NEW_LINE result = deepestLeftLeaf ( root ) NEW_LINE if result is None : NEW_LINE INDENT print " There β is β not β left β leaf β in β the β given β tree " NEW_LINE DEDENT else : NEW_LINE INDENT print " The β deepst β left β child β is " , result . val NEW_LINE DEDENT |
Check if an array contains all elements of a given range | Function to check the array for elements in given range ; Range is the no . of elements that are to be checked ; Traversing the array ; If an element is in range ; Checking whether elements in range 0 - range are negative ; Element from range is missing from array ; All range elements are present ; Defining Array and size ; A is lower limit and B is the upper limit of range ; True denotes all elements were present ; False denotes any element was not present | def check_elements ( arr , n , A , B ) : NEW_LINE INDENT rangeV = B - A NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) >= A and abs ( arr [ i ] ) <= B ) : NEW_LINE INDENT z = abs ( arr [ i ] ) - A NEW_LINE if ( arr [ z ] > 0 ) : NEW_LINE INDENT arr [ z ] = arr [ z ] * - 1 NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( 0 , rangeV + 1 ) : NEW_LINE INDENT if i >= n : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT if ( count != ( rangeV + 1 ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT arr = [ 1 , 4 , 5 , 2 , 7 , 8 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE A = 2 NEW_LINE B = 5 NEW_LINE if ( check_elements ( arr , n , A , B ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Recursive Programs to find Minimum and Maximum elements of array | function to print Minimum element using recursion ; if size = 0 means whole array has been traversed ; Driver Code | def findMinRec ( A , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return A [ 0 ] NEW_LINE DEDENT return min ( A [ n - 1 ] , findMinRec ( A , n - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 4 , 45 , 6 , - 50 , 10 , 2 ] NEW_LINE n = len ( A ) NEW_LINE print ( findMinRec ( A , n ) ) NEW_LINE DEDENT |
Allocate minimum number of pages | Utility function to check if current minimum value is feasible or not . ; iterate over all books ; check if current number of pages are greater than curr_min that means we will get the result after mid no . of pages ; count how many students are required to distribute curr_min pages ; increment student count ; update curr_sum ; if students required becomes greater than given no . of students , return False ; else update curr_sum ; function to find minimum pages ; return - 1 if no . of books is less than no . of students ; Count total number of pages ; initialize start as 0 pages and end as total pages ; traverse until start <= end ; check if it is possible to distribute books by using mid as current minimum ; update result to current distribution as it 's the best we have found till now. ; as we are finding minimum and books are sorted so reduce end = mid - 1 that means ; if not possible means pages should be increased so update start = mid + 1 ; at - last return minimum no . of pages ; Number of pages in books ; m = 2 No . of students | def isPossible ( arr , n , m , curr_min ) : NEW_LINE INDENT studentsRequired = 1 NEW_LINE curr_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > curr_min ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( curr_sum + arr [ i ] > curr_min ) : NEW_LINE INDENT studentsRequired += 1 NEW_LINE curr_sum = arr [ i ] NEW_LINE if ( studentsRequired > m ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT curr_sum += arr [ i ] NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def findPages ( arr , n , m ) : NEW_LINE INDENT sum = 0 NEW_LINE if ( n < m ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT start , end = 0 , sum NEW_LINE result = 10 ** 9 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE if ( isPossible ( arr , n , m , mid ) ) : NEW_LINE INDENT result = mid NEW_LINE end = mid - 1 NEW_LINE DEDENT else : NEW_LINE INDENT start = mid + 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 12 , 34 , 67 , 90 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum β number β of β pages β = β " , findPages ( arr , n , m ) ) NEW_LINE |
Find Minimum Depth of a Binary Tree | Tree node ; Function to calculate the minimum depth of the tree ; Corner Case . Should never be hit unless the code is called on root = NULL ; Base Case : Leaf node . This acoounts for height = 1 ; If left subtree is Null , recur for right subtree ; If right subtree is Null , recur for left subtree ; Let us construct the Tree shown in the above figure | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minDepth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . left is None and root . right is None : NEW_LINE INDENT return 1 NEW_LINE DEDENT if root . left is None : NEW_LINE INDENT return minDepth ( root . right ) + 1 NEW_LINE DEDENT if root . right is None : NEW_LINE INDENT return minDepth ( root . left ) + 1 NEW_LINE DEDENT return min ( minDepth ( root . left ) , minDepth ( root . right ) ) + 1 NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print minDepth ( root ) NEW_LINE |
Remove an occurrence of most frequent array element exactly K times | Function to print the most frequent array element exactly K times ; Stores frequency array element ; Count frequency of array element ; Maximum array element ; Traverse the Map ; Find the element with maximum frequency ; If the frequency is maximum , store that number in element ; Print element as it contains the element having highest frequency ; Decrease the frequency of the maximum array element ; Reduce the number of operations ; Given array ; Size of the array ; Given K | def maxFreqElements ( arr , N , K ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT while ( K > 0 ) : NEW_LINE INDENT Max = 0 NEW_LINE for i in mp : NEW_LINE INDENT if ( mp [ i ] > Max ) : NEW_LINE INDENT Max = mp [ i ] NEW_LINE element = i NEW_LINE DEDENT DEDENT print ( element , end = " β " ) NEW_LINE if element in mp : NEW_LINE INDENT mp [ element ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ element ] = - 1 NEW_LINE DEDENT K -= 1 NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 2 , 1 , 4 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE maxFreqElements ( arr , N , K ) NEW_LINE |
Maximize difference between maximum and minimum array elements after K operations | Function to find the maximum difference between the maximum and minimum in the array after K operations ; Stores maximum difference between largest and smallest array element ; Sort the array in descending order ; Traverse the array arr [ ] ; Update maxDiff ; Driver Code | def maxDiffLargSmallOper ( arr , N , K ) : NEW_LINE INDENT maxDiff = 0 ; NEW_LINE arr . sort ( reverse = True ) ; NEW_LINE for i in range ( min ( K + 1 , N ) ) : NEW_LINE INDENT maxDiff += arr [ i ] ; NEW_LINE DEDENT return maxDiff ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 7 , 7 , 7 ] ; NEW_LINE N = len ( arr ) NEW_LINE K = 1 ; NEW_LINE print ( maxDiffLargSmallOper ( arr , N , K ) ) ; NEW_LINE DEDENT |
Minimize cost to convert all characters of a binary string to 0 s | Function to get the minimum Cost to convert all characters of given string to 0 s ; Stores the range of indexes of characters that need to be flipped ; Stores the number of times current character is flipped ; Stores minimum cost to get the required string ; Traverse the given string ; Remove all value from pq whose value is less than i ; Update flip ; Get the current number ; If current character is flipped odd times ; If current character contains non - zero value ; Update flip ; Update cost ; Append R [ i ] into pq ; Driver code ; Function call | def minCost ( s , R , C , N ) : NEW_LINE INDENT ch = list ( s ) NEW_LINE pq = [ ] NEW_LINE flip = 0 NEW_LINE cost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT while ( len ( pq ) > 0 and pq [ 0 ] < i ) : NEW_LINE INDENT pq . pop ( 0 ) ; NEW_LINE flip -= 1 NEW_LINE DEDENT cn = ord ( ch [ i ] ) - ord ( '0' ) NEW_LINE if ( flip % 2 == 1 ) : NEW_LINE INDENT cn = 1 - cn NEW_LINE DEDENT if ( cn == 1 ) : NEW_LINE INDENT flip += 1 NEW_LINE cost += C [ i ] NEW_LINE pq . append ( R [ i ] ) NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT N = 4 NEW_LINE s = "1010" NEW_LINE R = [ 1 , 2 , 2 , 3 ] NEW_LINE C = [ 3 , 1 , 2 , 3 ] NEW_LINE print ( minCost ( s , R , C , N ) ) NEW_LINE |
Find Minimum Depth of a Binary Tree | A Binary Tree node ; Iterative method to find minimum depth of Binary Tree ; Corner Case ; Create an empty queue for level order traversal ; Enqueue root and initialize depth as 1 ; Do level order traversal ; Remove the front queue item ; Get details of the removed item ; If this is the first leaf node seen so far then return its depth as answer ; If left subtree is not None , add it to queue ; if right subtree is not None , add it to queue ; Lets construct a binary tree shown in above diagram | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minDepth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( { ' node ' : root , ' depth ' : 1 } ) NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT queueItem = q . pop ( 0 ) NEW_LINE node = queueItem [ ' node ' ] NEW_LINE depth = queueItem [ ' depth ' ] NEW_LINE if node . left is None and node . right is None : NEW_LINE INDENT return depth NEW_LINE DEDENT if node . left is not None : NEW_LINE INDENT q . append ( { ' node ' : node . left , ' depth ' : depth + 1 } ) NEW_LINE DEDENT if node . right is not None : NEW_LINE INDENT q . append ( { ' node ' : node . right , ' depth ' : depth + 1 } ) NEW_LINE DEDENT DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print minDepth ( root ) NEW_LINE |
Maximum Manhattan distance between a distinct pair from N coordinates | Function to calculate the maximum Manhattan distance ; List to store maximum and minimum of all the four forms ; Sorting both the vectors ; Driver code ; Given Co - ordinates ; Function call | def MaxDist ( A , N ) : NEW_LINE INDENT V = [ 0 for i in range ( N ) ] NEW_LINE V1 = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT V [ i ] = A [ i ] [ 0 ] + A [ i ] [ 1 ] NEW_LINE V1 [ i ] = A [ i ] [ 0 ] - A [ i ] [ 1 ] NEW_LINE DEDENT V . sort ( ) NEW_LINE V1 . sort ( ) NEW_LINE maximum = max ( V [ - 1 ] - V [ 0 ] , V1 [ - 1 ] - V1 [ 0 ] ) NEW_LINE print ( maximum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE A = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] ] NEW_LINE MaxDist ( A , N ) NEW_LINE DEDENT |
Maximum distance between two points in coordinate plane using Rotating Caliper 's Method | ; Function calculates distance between two points ; Function to find the maximum distance between any two points ; Iterate over all possible pairs ; Update maxm ; Return actual distance ; Driver Code ; Number of points ; Given points ; Function Call | from math import sqrt NEW_LINE def dist ( p1 , p2 ) : NEW_LINE INDENT x0 = p1 [ 0 ] - p2 [ 0 ] NEW_LINE y0 = p1 [ 1 ] - p2 [ 1 ] NEW_LINE return x0 * x0 + y0 * y0 NEW_LINE DEDENT def maxDist ( p ) : NEW_LINE INDENT n = len ( p ) NEW_LINE maxm = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT maxm = max ( maxm , dist ( p [ i ] , p [ j ] ) ) NEW_LINE DEDENT DEDENT return sqrt ( maxm ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE p = [ ] NEW_LINE p . append ( [ 4 , 0 ] ) NEW_LINE p . append ( [ 0 , 2 ] ) NEW_LINE p . append ( [ - 1 , - 7 ] ) NEW_LINE p . append ( [ 1 , 10 ] ) NEW_LINE p . append ( [ 2 , - 3 ] ) NEW_LINE print ( maxDist ( p ) ) NEW_LINE DEDENT |
Reorder an array such that sum of left half is not equal to sum of right half | Function to print the required reordering of the array if possible ; Sort the array in increasing order ; If all elements are equal , then it is not possible ; Else print the sorted array arr [ ] ; Driver Code ; Given array ; Function Call | def printArr ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE if ( arr [ 0 ] == arr [ n - 1 ] ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 2 , 1 , 3 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE printArr ( arr , N ) NEW_LINE DEDENT |
Maximize Array sum by swapping at most K elements with another array | Function to find the maximum sum ; If element of array a is smaller than that of array b , swap them . ; Find sum of resultant array ; Driver code | def maximumSum ( a , b , k , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while i < k : NEW_LINE INDENT if ( a [ i ] < b [ j ] ) : NEW_LINE INDENT a [ i ] , b [ j ] = b [ j ] , a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT K = 1 NEW_LINE A = [ 2 , 3 , 4 ] NEW_LINE B = [ 6 , 8 , 5 ] NEW_LINE N = len ( A ) NEW_LINE maximumSum ( A , B , K , N ) NEW_LINE DEDENT |
Maximize distinct elements by incrementing / decrementing an element or keeping it same | Function that Maximize the count of distinct element ; Sort thr list ; Keeping track of previous change ; Decrement is possible ; Remain as it is ; Increment is possible ; Driver Code | def max_dist_ele ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prev < ( arr [ i ] - 1 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE prev = arr [ i ] - 1 NEW_LINE DEDENT elif prev < ( arr [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ i ] NEW_LINE DEDENT elif prev < ( arr [ i ] + 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ i ] + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 8 , 8 , 8 , 9 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( max_dist_ele ( arr , n ) ) NEW_LINE |
Find if array can be sorted by swaps limited to multiples of k | CheckSort function To check if array can be sorted ; sortarr is sorted array of arr ; if k = 1 then ( always possible to sort ) swapping can easily give sorted array ; comparing sortarray with array ; element at index j must be in j = i + l * k form where i = 0 , 1 , 2 , 3. . . where l = 0 , 1 , 2 , 3 , . . n - 1 ; if element is present then swapped ; if element of sorted array does not found in its sequence then flag remain zero that means arr can not be sort after swapping ; if flag is 0 Not possible else Possible ; Driver code ; size of step ; array initialized ; length of arr ; calling function | def CheckSort ( arr , k , n ) : NEW_LINE INDENT sortarr = sorted ( arr ) NEW_LINE if ( k == 1 ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i , n , k ) : NEW_LINE INDENT if ( sortarr [ i ] == arr [ j ] ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT if ( j + k >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " Not β possible β to β sort " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Possible β to β sort " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 3 NEW_LINE arr = [ 1 , 5 , 6 , 9 , 2 , 3 , 5 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE CheckSort ( arr , k , n ) NEW_LINE DEDENT |
Replace node with depth in a binary tree | A tree node structure ; Helper function replaces the data with depth Note : Default value of level is 0 for root . ; Base Case ; Replace data with current depth ; A utility function to prinorder traversal of a Binary Tree ; Driver Code ; Constructing tree given in the above figure | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def replaceNode ( node , level = 0 ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT node . data = level NEW_LINE replaceNode ( node . left , level + 1 ) NEW_LINE replaceNode ( node . right , level + 1 ) NEW_LINE DEDENT def printInorder ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( node . left ) NEW_LINE print ( node . data , end = " β " ) NEW_LINE printInorder ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 3 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 4 ) NEW_LINE print ( " Before β Replacing β Nodes " ) NEW_LINE printInorder ( root ) NEW_LINE replaceNode ( root ) NEW_LINE print ( ) NEW_LINE print ( " After β Replacing β Nodes " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT |
Product of minimum edge weight between all pairs of a Tree | Python3 implementation of the approach ; Function to return ( x ^ y ) mod p ; Declaring size array globally ; Initializing DSU data structure ; Function to find the root of ith node in the disjoint set ; Weighted union using Path Compression ; size of set A is small than size of set B ; size of set B is small than size of set A ; Function to add an edge in the tree ; Build the tree ; Function to return the required product ; Sorting the edges with respect to its weight ; Start iterating in decreasing order of weight ; Determine Current edge values ; Calculate root of each node and size of each set ; Using the formula ; Calculating final result ; Weighted union using Path Compression ; Driver Code | mod = 1000000007 NEW_LINE def power ( x : int , y : int , p : int ) -> int : NEW_LINE INDENT res = 1 NEW_LINE x %= p NEW_LINE while y > 0 : NEW_LINE INDENT if y & 1 : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y // 2 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT size = [ 0 ] * 300005 NEW_LINE freq = [ 0 ] * 300004 NEW_LINE edges = [ ] NEW_LINE def initialize ( arr : list , N : int ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT arr [ i ] = i NEW_LINE size [ i ] = 1 NEW_LINE DEDENT DEDENT def root ( arr : list , i : int ) -> int : NEW_LINE INDENT while arr [ i ] != i : NEW_LINE INDENT i = arr [ i ] NEW_LINE DEDENT return i NEW_LINE DEDENT def weighted_union ( arr : list , size : list , A : int , B : int ) : NEW_LINE INDENT root_A = root ( arr , A ) NEW_LINE root_B = root ( arr , B ) NEW_LINE if size [ root_A ] < size [ root_B ] : NEW_LINE INDENT arr [ root_A ] = arr [ root_B ] NEW_LINE size [ root_B ] += size [ root_A ] NEW_LINE DEDENT else : NEW_LINE INDENT arr [ root_B ] = arr [ root_A ] NEW_LINE size [ root_A ] += size [ root_B ] NEW_LINE DEDENT DEDENT def AddEdge ( a : int , b : int , w : int ) : NEW_LINE INDENT edges . append ( ( w , ( a , b ) ) ) NEW_LINE DEDENT def makeTree ( ) : NEW_LINE INDENT AddEdge ( 1 , 2 , 1 ) NEW_LINE AddEdge ( 1 , 3 , 3 ) NEW_LINE AddEdge ( 3 , 4 , 2 ) NEW_LINE DEDENT def minProduct ( ) -> int : NEW_LINE INDENT result = 1 NEW_LINE edges . sort ( key = lambda a : a [ 0 ] ) NEW_LINE for i in range ( len ( edges ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT curr_weight = edges [ i ] [ 0 ] NEW_LINE node1 = edges [ i ] [ 1 ] [ 0 ] NEW_LINE node2 = edges [ i ] [ 1 ] [ 1 ] NEW_LINE root1 = root ( freq , node1 ) NEW_LINE set1_size = size [ root1 ] NEW_LINE root2 = root ( freq , node2 ) NEW_LINE set2_size = size [ root2 ] NEW_LINE prod = set1_size * set2_size NEW_LINE product = power ( curr_weight , prod , mod ) NEW_LINE result = ( ( result % mod ) * ( product % mod ) ) % mod NEW_LINE weighted_union ( freq , size , node1 , node2 ) NEW_LINE DEDENT return result % mod NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE initialize ( freq , n ) NEW_LINE makeTree ( ) NEW_LINE print ( minProduct ( ) ) NEW_LINE DEDENT |
Check whether an array can be made strictly decreasing by modifying at most one element | Function that returns true if the array can be made strictly decreasing with at most one change ; To store the number of modifications required to make the array strictly decreasing ; Check whether the last element needs to be modify or not ; Check whether the first element needs to be modify or not ; Loop from 2 nd element to the 2 nd last element ; Check whether arr [ i ] needs to be modified ; Modifying arr [ i ] ; Check if arr [ i ] is equal to any of arr [ i - 1 ] or arr [ i + 1 ] ; If more than 1 modification is required ; Driver code | def check ( arr , n ) : NEW_LINE INDENT modify = 0 NEW_LINE if ( arr [ n - 1 ] >= arr [ n - 2 ] ) : NEW_LINE INDENT arr [ n - 1 ] = arr [ n - 2 ] - 1 NEW_LINE modify += 1 NEW_LINE DEDENT if ( arr [ 0 ] <= arr [ 1 ] ) : NEW_LINE INDENT arr [ 0 ] = arr [ 1 ] + 1 NEW_LINE modify += 1 NEW_LINE DEDENT for i in range ( n - 2 , 0 , - 1 ) : NEW_LINE INDENT if ( arr [ i - 1 ] <= arr [ i ] and arr [ i + 1 ] <= arr [ i ] ) or ( arr [ i - 1 ] >= arr [ i ] and arr [ i + 1 ] >= arr [ i ] ) : NEW_LINE INDENT arr [ i ] = ( arr [ i - 1 ] + arr [ i + 1 ] ) // 2 NEW_LINE modify += 1 NEW_LINE if ( arr [ i ] == arr [ i - 1 ] or arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT if ( modify > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 5 , 11 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE if ( check ( arr , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Maximal Disjoint Intervals | Function to find maximal disjoint set ; sort the list of intervals ; First interval will always be included in set ; End point of first interval ; Check if given interval overlap with previously included interval , if not then include this interval and update the end point of last added interval ; Driver code | def maxDisjointIntervals ( list_ ) : NEW_LINE INDENT list_ . sort ( key = lambda x : x [ 1 ] ) NEW_LINE print ( " [ " , list_ [ 0 ] [ 0 ] , " , β " , list_ [ 0 ] [ 1 ] , " ] " ) NEW_LINE r1 = list_ [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , len ( list_ ) ) : NEW_LINE INDENT l1 = list_ [ i ] [ 0 ] NEW_LINE r2 = list_ [ i ] [ 1 ] NEW_LINE if l1 > r1 : NEW_LINE INDENT print ( " [ " , l1 , " , β " , r2 , " ] " ) NEW_LINE r1 = r2 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE intervals = [ [ 1 , 4 ] , [ 2 , 3 ] , [ 4 , 6 ] , [ 8 , 9 ] ] NEW_LINE maxDisjointIntervals ( intervals ) NEW_LINE DEDENT |
Print k different sorted permutations of a given array | Utility function to print the original indices of the elements of the array ; Function to print the required permutations ; To keep track of original indices ; Sort the array ; Count the number of swaps that can be made ; Cannot generate 3 permutations ; Print the first permutation ; Find an index to swap and create second permutation ; Print the last permutation ; Driver code ; Function call | def printIndices ( n , a ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] [ 1 ] , end = " β " ) NEW_LINE DEDENT print ( " " , β end = " " ) NEW_LINE DEDENT def printPermutations ( n , a , k ) : NEW_LINE INDENT arr = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] [ 0 ] = a [ i ] NEW_LINE arr [ i ] [ 1 ] = i NEW_LINE DEDENT arr . sort ( reverse = False ) NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] [ 0 ] == arr [ i - 1 ] [ 0 ] ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count < k ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE return NEW_LINE DEDENT next_pos = 1 NEW_LINE for i in range ( k - 1 ) : NEW_LINE INDENT printIndices ( n , arr ) NEW_LINE for j in range ( next_pos , n ) : NEW_LINE INDENT if ( arr [ j ] [ 0 ] == arr [ j - 1 ] [ 0 ] ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ j - 1 ] NEW_LINE arr [ j - 1 ] = temp NEW_LINE next_pos = j + 1 NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT printIndices ( n , arr ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 3 , 3 , 1 ] NEW_LINE n = len ( a ) NEW_LINE k = 3 NEW_LINE printPermutations ( n , a , k ) NEW_LINE DEDENT |
Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; Get width of each level and compare the width with maximum width so far ; Get width of a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Constructed binary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 ; Function call | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT maxWidth = 0 NEW_LINE h = height ( root ) NEW_LINE for i in range ( 1 , h + 1 ) : NEW_LINE INDENT width = getWidth ( root , i ) NEW_LINE if ( width > maxWidth ) : NEW_LINE INDENT maxWidth = width NEW_LINE DEDENT DEDENT return maxWidth NEW_LINE DEDENT def getWidth ( root , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if level == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif level > 1 : NEW_LINE INDENT return ( getWidth ( root . left , level - 1 ) + getWidth ( root . right , level - 1 ) ) NEW_LINE DEDENT DEDENT def height ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lHeight = height ( node . left ) NEW_LINE rHeight = height ( node . right ) NEW_LINE return ( lHeight + 1 ) if ( lHeight > rHeight ) else ( rHeight + 1 ) NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . right . left = Node ( 6 ) NEW_LINE root . right . right . right = Node ( 7 ) NEW_LINE print " Maximum β width β is β % d " % ( getMaxWidth ( root ) ) NEW_LINE |
Divide N segments into two non | Function to print the answer if it exists using the concept of merge overlapping segments ; Sort the indices based on their corresponding value in V ; Resultant array Initialise all the values in resultant array with '2' except the first index of ' indices ' which is initialised as '1' Initialise maxR to store the maximum of all right values encountered so far ; If the i - th index has any any point in common with the ( i - 1 ) th index classify it as '1' in resultant array and update maxR if necessary else we have found the breakpoint and we can exit the loop ; Driver Code | def printAnswer ( v , n ) : NEW_LINE INDENT indices = list ( range ( n ) ) NEW_LINE indices . sort ( key = lambda i : v [ i ] ) NEW_LINE res = [ 2 ] * n NEW_LINE res [ indices [ 0 ] ] = 1 NEW_LINE maxR = v [ indices [ 0 ] ] [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if maxR >= v [ indices [ i ] ] [ 0 ] : NEW_LINE INDENT res [ indices [ i ] ] = res [ indices [ i - 1 ] ] NEW_LINE maxR = max ( maxR , v [ indices [ i ] ] [ 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT print ( " Not β possible " ) NEW_LINE return NEW_LINE DEDENT print ( " β " . join ( map ( str , res ) ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT v = [ [ 2 , 8 ] , [ 3 , 4 ] , [ 5 , 8 ] , [ 9 , 10 ] ] NEW_LINE n = len ( v ) NEW_LINE printAnswer ( v , n ) NEW_LINE DEDENT |
Count distinct elements in an array | This function prints all distinct elements ; Creates an empty hashset ; Traverse the input array ; If not present , then put it in hashtable and increment result ; Driver code | def countDistinct ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in s ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDistinct ( arr , n ) ) NEW_LINE |
In | Python3 program for the above approach ; Calculating next gap ; Function for swapping ; Merging the subarrays using shell sorting Time Complexity : O ( nlog n ) Space Complexity : O ( 1 ) ; merge sort makes log n recursive calls and each time calls merge ( ) which takes nlog n steps Time Complexity : O ( n * log n + 2 ( ( n / 2 ) * log ( n / 2 ) ) + 4 ( ( n / 4 ) * log ( n / 4 ) ) + ... . . + 1 ) Time Complexity : O ( logn * ( n * log n ) ) i . e . O ( n * ( logn ) ^ 2 ) Space Complexity : O ( 1 ) ; Calculating mid to slice the array in two halves ; Recursive calls to sort left and right subarrays ; UTILITY FUNCTIONS Function to pran array ; Driver Code | import math NEW_LINE def nextGap ( gap ) : NEW_LINE INDENT if gap <= 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return int ( math . ceil ( gap / 2 ) ) NEW_LINE DEDENT def swap ( nums , i , j ) : NEW_LINE INDENT temp = nums [ i ] NEW_LINE nums [ i ] = nums [ j ] NEW_LINE nums [ j ] = temp NEW_LINE DEDENT def inPlaceMerge ( nums , start , end ) : NEW_LINE INDENT gap = end - start + 1 NEW_LINE gap = nextGap ( gap ) NEW_LINE while gap > 0 : NEW_LINE INDENT i = start NEW_LINE while ( i + gap ) <= end : NEW_LINE INDENT j = i + gap NEW_LINE if nums [ i ] > nums [ j ] : NEW_LINE INDENT swap ( nums , i , j ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT gap = nextGap ( gap ) NEW_LINE DEDENT DEDENT def mergeSort ( nums , s , e ) : NEW_LINE INDENT if s == e : NEW_LINE INDENT return NEW_LINE DEDENT mid = ( s + e ) // 2 NEW_LINE mergeSort ( nums , s , mid ) NEW_LINE mergeSort ( nums , mid + 1 , e ) NEW_LINE inPlaceMerge ( nums , s , e ) NEW_LINE DEDENT def printArray ( A , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 11 , 13 , 5 , 6 , 7 ] NEW_LINE arr_size = len ( arr ) NEW_LINE mergeSort ( arr , 0 , arr_size - 1 ) NEW_LINE printArray ( arr , arr_size ) NEW_LINE DEDENT |
Rearrange an array to maximize i * arr [ i ] | Function to calculate the maximum points earned by making an optimal selection on the given array ; Sorting the array ; Variable to store the total points earned ; Driver Code | def findOptimalSolution ( a , N ) : NEW_LINE INDENT a . sort ( ) NEW_LINE points = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT points += a [ i ] * i NEW_LINE DEDENT return points NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 4 , 2 , 3 , 9 ] NEW_LINE N = len ( a ) NEW_LINE print ( findOptimalSolution ( a , N ) ) NEW_LINE DEDENT |
Minimum number of towers required such that every house is in the range of at least one tower | Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; Driver code ; given elements ; print number of towers | def number_of_tower ( house , r , n ) : NEW_LINE INDENT house . sort ( ) NEW_LINE numOfTower = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT numOfTower += 1 NEW_LINE loc = house [ i ] + r NEW_LINE while ( i < n and house [ i ] <= loc ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE loc = house [ i ] + r NEW_LINE while ( i < n and house [ i ] <= loc ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return numOfTower NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT house = [ 7 , 2 , 4 , 6 , 5 , 9 , 12 , 11 ] NEW_LINE r = 2 NEW_LINE n = len ( house ) NEW_LINE print ( number_of_tower ( house , r , n ) ) NEW_LINE DEDENT |
Check if the characters of a given string are in alphabetical order | Function that checks whether the string is in alphabetical order or not ; length of the string ; create a character array of the length of the string ; sort the character array ; check if the character array is equal to the string or not ; Driver code ; check whether the string is in alphabetical order or not | def isAlphabaticOrder ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE c = [ s [ i ] for i in range ( len ( s ) ) ] NEW_LINE c . sort ( reverse = False ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( c [ i ] != s [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " aabbbcc " NEW_LINE if ( isAlphabaticOrder ( s ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Sort first k values in ascending order and remaining n | function to sort the array ; Sort first k elements in ascending order ; Sort remaining n - k elements in descending order ; Our arr contains 8 elements | def printOrder ( arr , n , k ) : NEW_LINE INDENT a = arr [ 0 : k ] ; NEW_LINE a . sort ( ) ; NEW_LINE b = arr [ k : n ] ; NEW_LINE b . sort ( ) ; NEW_LINE b . reverse ( ) ; NEW_LINE return a + b ; NEW_LINE DEDENT arr = [ 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , - 1 ] ; NEW_LINE k = 4 ; NEW_LINE n = len ( arr ) ; NEW_LINE arr = printOrder ( arr , n , k ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT |
Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; base case ; Initialize result ; Do Level order traversal keeping track of number of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Update the maximum node count value ; Iterate for all the nodes in the queue currently ; Dequeue an node from queue ; ; Driver program to test above function ; Function call | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxWidth = 0 NEW_LINE q = [ ] NEW_LINE q . insert ( 0 , root ) NEW_LINE while ( q != [ ] ) : NEW_LINE INDENT count = len ( q ) NEW_LINE maxWidth = max ( count , maxWidth ) NEW_LINE while ( count is not 0 ) : NEW_LINE INDENT count = count - 1 NEW_LINE temp = q [ - 1 ] NEW_LINE q . pop ( ) NEW_LINE if temp . left is not None : NEW_LINE INDENT q . insert ( 0 , temp . left ) NEW_LINE DEDENT if temp . right is not None : NEW_LINE INDENT q . insert ( 0 , temp . right ) NEW_LINE DEDENT DEDENT DEDENT return maxWidth NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . right . left = Node ( 6 ) NEW_LINE root . right . right . right = Node ( 7 ) NEW_LINE print " Maximum β width β is β % d " % ( getMaxWidth ( root ) ) NEW_LINE |
Merging and Sorting Two Unsorted Stacks | Sorts input stack and returns sorted stack . ; pop out the first element ; while temporary stack is not empty and top of stack is greater than temp ; pop from temporary stack and push it to the input stack ; push temp in temporary of stack ; Push contents of both stacks in result ; Sort the result stack . ; main function ; This is the temporary stack | def sortStack ( Input ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while len ( Input ) != 0 : NEW_LINE INDENT tmp = Input [ - 1 ] NEW_LINE Input . pop ( ) NEW_LINE while len ( tmpStack ) != 0 and tmpStack [ - 1 ] > tmp : NEW_LINE INDENT Input . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT tmpStack . append ( tmp ) NEW_LINE DEDENT return tmpStack NEW_LINE DEDENT def sortedMerge ( s1 , s2 ) : NEW_LINE INDENT res = [ ] NEW_LINE while len ( s1 ) != 0 : NEW_LINE INDENT res . append ( s1 [ - 1 ] ) NEW_LINE s1 . pop ( ) NEW_LINE DEDENT while len ( s2 ) != 0 : NEW_LINE INDENT res . append ( s2 [ - 1 ] ) NEW_LINE s2 . pop ( ) NEW_LINE DEDENT return sortStack ( res ) NEW_LINE DEDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE s1 . append ( 34 ) NEW_LINE s1 . append ( 3 ) NEW_LINE s1 . append ( 31 ) NEW_LINE s2 . append ( 1 ) NEW_LINE s2 . append ( 12 ) NEW_LINE s2 . append ( 23 ) NEW_LINE tmpStack = [ ] NEW_LINE tmpStack = sortedMerge ( s1 , s2 ) NEW_LINE print ( " Sorted β and β merged β stack β : " ) NEW_LINE while len ( tmpStack ) != 0 : NEW_LINE INDENT print ( tmpStack [ - 1 ] , end = " β " ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT |
Lexicographical concatenation of all substrings of a string | Python Program to create concatenation of all substrings in lexicographic order . ; Creating an array to store substrings ; finding all substrings of string ; Sort all substrings in lexicographic order ; Concatenating all substrings ; Driver code | def lexicographicSubConcat ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE sub_count = ( n * ( n + 1 ) ) // 2 ; NEW_LINE arr = [ 0 ] * sub_count ; NEW_LINE index = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , n - i + 1 ) : NEW_LINE INDENT arr [ index ] = s [ i : i + j ] ; NEW_LINE index += 1 ; NEW_LINE DEDENT DEDENT arr . sort ( ) ; NEW_LINE res = " " ; NEW_LINE for i in range ( sub_count ) : NEW_LINE INDENT res += arr [ i ] ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT s = " abc " ; NEW_LINE print ( lexicographicSubConcat ( s ) ) ; NEW_LINE |
Insertion Sort by Swapping Elements | Iterative python program to sort an array by swapping elements ; Utility function to print a Vector ; Function performs insertion sort on vector V ; Insert V [ i ] into list 0. . i - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j ; Driver Code | import math NEW_LINE def printVector ( V ) : NEW_LINE INDENT for i in V : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT print ( " β " ) NEW_LINE DEDENT def insertionSort ( V ) : NEW_LINE INDENT N = len ( V ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE j = i NEW_LINE while ( j > 0 and V [ j ] < V [ j - 1 ] ) : NEW_LINE INDENT temp = V [ j ] ; NEW_LINE V [ j ] = V [ j - 1 ] ; NEW_LINE V [ j - 1 ] = temp ; NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT A = [ 9 , 8 , 7 , 5 , 2 , 1 , 2 , 3 ] NEW_LINE n = len ( A ) NEW_LINE print ( " Array " ) NEW_LINE printVector ( A ) NEW_LINE print ( " After β Sorting β : " ) NEW_LINE insertionSort ( A ) NEW_LINE printVector ( A ) NEW_LINE |
Program to sort string in descending order | Python program to sort a string in descending order using library function ; Driver code ; function call | def descOrder ( s ) : NEW_LINE INDENT s . sort ( reverse = True ) NEW_LINE str1 = ' ' . join ( s ) NEW_LINE print ( str1 ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT s = list ( ' geeksforgeeks ' ) NEW_LINE descOrder ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Sort string of characters | Python 3 program to sort a string of characters ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be 1 , so for location of character in count array we wil do str [ i ] - ' a ' . ; Traverse the hash array and print characters ; Driver Code | MAX_CHAR = 26 NEW_LINE def sortString ( str ) : NEW_LINE INDENT charCount = [ 0 for i in range ( MAX_CHAR ) ] NEW_LINE for i in range ( 0 , len ( str ) , 1 ) : NEW_LINE INDENT charCount [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 0 , MAX_CHAR , 1 ) : NEW_LINE INDENT for j in range ( 0 , charCount [ i ] , 1 ) : NEW_LINE INDENT print ( chr ( ord ( ' a ' ) + i ) , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " geeksforgeeks " NEW_LINE sortString ( s ) NEW_LINE DEDENT |
Smallest element in an array that is repeated exactly ' k ' times . | Python program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] ; Computing frequencies of all elements ; Finding the smallest element with frequency as k ; If frequency of any of the number is equal to k starting from 0 then return the number ; Driver code | MAX = 1000 NEW_LINE def findDuplicate ( arr , n , k ) : NEW_LINE INDENT freq = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 1 and arr [ i ] > MAX ) : NEW_LINE INDENT print " Out β of β range " NEW_LINE return - 1 NEW_LINE DEDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] == k ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 2 , 1 , 3 , 1 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print findDuplicate ( arr , n , k ) NEW_LINE |
Find the Sub | Python3 program to find subarray with sum closest to 0 ; Returns subarray with sum closest to 0. ; To consider the case of subarray starting from beginning of the array ; Store prefix sum with index ; Sort on the basis of sum ; Find two consecutive elements with minimum difference ; Update minimum difference and starting and ending indexes ; Return starting and ending indexes ; Driver code | class prefix : NEW_LINE INDENT def __init__ ( self , sum , index ) : NEW_LINE INDENT self . sum = sum NEW_LINE self . index = index NEW_LINE DEDENT DEDENT def findSubArray ( arr , n ) : NEW_LINE INDENT start , end , min_diff = None , None , float ( ' inf ' ) NEW_LINE pre_sum = [ None ] * ( n + 1 ) NEW_LINE pre_sum [ 0 ] = prefix ( 0 , - 1 ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT pre_sum [ i ] = prefix ( pre_sum [ i - 1 ] . sum + arr [ i - 1 ] , i - 1 ) NEW_LINE DEDENT pre_sum . sort ( key = lambda x : x . sum ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT diff = pre_sum [ i ] . sum - pre_sum [ i - 1 ] . sum NEW_LINE if min_diff > diff : NEW_LINE INDENT min_diff = diff NEW_LINE start = pre_sum [ i - 1 ] . index NEW_LINE end = pre_sum [ i ] . index NEW_LINE DEDENT DEDENT return ( start + 1 , end ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 3 , - 4 , - 1 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE point = findSubArray ( arr , n ) NEW_LINE print ( " Subarray β starting β from " , point [ 0 ] , " to " , point [ 1 ] ) NEW_LINE DEDENT |
TimSort | Python3 program to perform basic timSort ; Becomes 1 if any 1 bits are shifted off ; This function sorts array from left index to to right index which is of size atmost RUN ; Merge function merges the sorted runs ; original array is broken in two parts left and right array ; after comparing , we merge those two array in larger sub array ; Copy remaining elements of left , if any ; Copy remaining element of right , if any ; Iterative Timsort function to sort the array [ 0. . . n - 1 ] ( similar to merge sort ) ; Sort individual subarrays of size RUN ; Start merging from size RUN ( or 32 ) . It will merge to form size 64 , then 128 , 256 and so on ... . ; Pick starting point of left sub array . We are going to merge arr [ left . . left + size - 1 ] and arr [ left + size , left + 2 * size - 1 ] After every merge , we increase left by 2 * size ; Find ending point of left sub array mid + 1 is starting point of right sub array ; Merge sub array arr [ left ... . . mid ] & arr [ mid + 1. ... right ] ; Driver program to test above function ; Function Call | MIN_MERGE = 32 NEW_LINE def calcMinRun ( n ) : NEW_LINE INDENT r = 0 NEW_LINE while n >= MIN_MERGE : NEW_LINE INDENT r |= n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return n + r NEW_LINE DEDENT def insertionSort ( arr , left , right ) : NEW_LINE INDENT for i in range ( left + 1 , right + 1 ) : NEW_LINE INDENT j = i NEW_LINE while j > left and arr [ j ] < arr [ j - 1 ] : NEW_LINE INDENT arr [ j ] , arr [ j - 1 ] = arr [ j - 1 ] , arr [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT DEDENT def merge ( arr , l , m , r ) : NEW_LINE INDENT len1 , len2 = m - l + 1 , r - m NEW_LINE left , right = [ ] , [ ] NEW_LINE for i in range ( 0 , len1 ) : NEW_LINE INDENT left . append ( arr [ l + i ] ) NEW_LINE DEDENT for i in range ( 0 , len2 ) : NEW_LINE INDENT right . append ( arr [ m + 1 + i ] ) NEW_LINE DEDENT i , j , k = 0 , 0 , l NEW_LINE while i < len1 and j < len2 : NEW_LINE INDENT if left [ i ] <= right [ j ] : NEW_LINE INDENT arr [ k ] = left [ i ] NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ k ] = right [ j ] NEW_LINE j += 1 NEW_LINE DEDENT k += 1 NEW_LINE DEDENT while i < len1 : NEW_LINE INDENT arr [ k ] = left [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT while j < len2 : NEW_LINE INDENT arr [ k ] = right [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT def timSort ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE minRun = calcMinRun ( n ) NEW_LINE for start in range ( 0 , n , minRun ) : NEW_LINE INDENT end = min ( start + minRun - 1 , n - 1 ) NEW_LINE insertionSort ( arr , start , end ) NEW_LINE DEDENT size = minRun NEW_LINE while size < n : NEW_LINE INDENT for left in range ( 0 , n , 2 * size ) : NEW_LINE INDENT mid = min ( n - 1 , left + size - 1 ) NEW_LINE right = min ( ( left + 2 * size - 1 ) , ( n - 1 ) ) NEW_LINE if mid < right : NEW_LINE INDENT merge ( arr , left , mid , right ) NEW_LINE DEDENT DEDENT size = 2 * size NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ - 2 , 7 , 15 , - 14 , 0 , 15 , 0 , 7 , - 7 , - 4 , - 13 , 5 , 8 , - 14 , 12 ] NEW_LINE print ( " Given β Array β is " ) NEW_LINE print ( arr ) NEW_LINE timSort ( arr ) NEW_LINE print ( " After β Sorting β Array β is " ) NEW_LINE print ( arr ) NEW_LINE DEDENT |
Program to print an array in Pendulum Arrangement | Prints pendulam arrangement of arr [ ] ; sorting the elements ; Auxiliary array to store output ; calculating the middle index ; storing the minimum element in the middle i is index for output array and j is for input array . ; adjustment for when no . of elements is even ; Printing the pendulum arrangement ; input Array ; calling pendulum function | def pendulumArrangement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE op = [ 0 ] * n NEW_LINE mid = int ( ( n - 1 ) / 2 ) NEW_LINE j = 1 NEW_LINE i = 1 NEW_LINE op [ mid ] = arr [ 0 ] NEW_LINE for i in range ( 1 , mid + 1 ) : NEW_LINE INDENT op [ mid + i ] = arr [ j ] NEW_LINE j += 1 NEW_LINE op [ mid - i ] = arr [ j ] NEW_LINE j += 1 NEW_LINE DEDENT if ( int ( n % 2 ) == 0 ) : NEW_LINE INDENT op [ mid + i ] = arr [ j ] NEW_LINE DEDENT print ( " Pendulum β arrangement : " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( op [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 14 , 6 , 19 , 21 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE pendulumArrangement ( arr , n ) NEW_LINE |
Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; Create an array that will store count of nodes at each level ; Fill the count array using preorder traversal ; Return the maximum value from count array ; A function that fills count array with count of nodes at every level of given binary tree ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node . ; compute the height of each subtree ; use the larger one ; Return the maximum value from count array ; Constructed bunary tree is : 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT h = height ( root ) NEW_LINE count = [ 0 ] * h NEW_LINE level = 0 NEW_LINE getMaxWidthRecur ( root , count , level ) NEW_LINE return getMax ( count , h ) NEW_LINE DEDENT def getMaxWidthRecur ( root , count , level ) : NEW_LINE INDENT if root is not None : NEW_LINE INDENT count [ level ] += 1 NEW_LINE getMaxWidthRecur ( root . left , count , level + 1 ) NEW_LINE getMaxWidthRecur ( root . right , count , level + 1 ) NEW_LINE DEDENT DEDENT def height ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lHeight = height ( node . left ) NEW_LINE rHeight = height ( node . right ) NEW_LINE return ( lHeight + 1 ) if ( lHeight > rHeight ) else ( rHeight + 1 ) NEW_LINE DEDENT DEDENT def getMax ( count , n ) : NEW_LINE INDENT max = count [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( count [ i ] > max ) : NEW_LINE INDENT max = count [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . right = Node ( 8 ) NEW_LINE root . right . right . left = Node ( 6 ) NEW_LINE root . right . right . right = Node ( 7 ) NEW_LINE print " Maximum β width β is β % d " % ( getMaxWidth ( root ) ) NEW_LINE |
Minimize the sum of product of two arrays with permutations allowed | Returns minimum sum of product of two arrays with permutations allowed ; Sort A and B so that minimum and maximum value can easily be fetched . ; Multiplying minimum value of A and maximum value of B ; Driven Program | def minValue ( A , B , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT result += ( A [ i ] * B [ n - i - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT A = [ 3 , 1 , 1 ] NEW_LINE B = [ 6 , 5 , 4 ] NEW_LINE n = len ( A ) NEW_LINE print minValue ( A , B , n ) NEW_LINE |
Count of numbers in range [ L , R ] which can be represented as sum of two perfect powers | Function to find the number of numbers that can be expressed in the form of the sum of two perfect powers ; Stores all possible powers ; Push 1 and 0 in it ; Iterate over all the exponents ; Iterate over all possible numbers ; This loop will run for a maximum of sqrt ( R ) times ; Push this power in the array pows [ ] ; Increase the number ; Stores if i can be expressed as the sum of perfect power or not ; int ok [ R + 1 ] ; memset ( ok , 0 , sizeof ( ok ) ) ; Iterate over all possible pairs of the array pows [ ] ; The number is valid ; Find the prefix sum of the array ok [ ] ; Return the count of required number ; Driver Code | def TotalPerfectPowerSum ( L , R ) : NEW_LINE INDENT pows = [ ] NEW_LINE pows . append ( 0 ) NEW_LINE pows . append ( 1 ) NEW_LINE for p in range ( 2 , 25 ) : NEW_LINE INDENT num = 2 NEW_LINE while ( ( int ) ( pow ( num , p ) + 0.5 ) <= R ) : NEW_LINE INDENT pows . append ( ( int ) ( pow ( num , p ) + 0.5 ) ) NEW_LINE num = num + 1 NEW_LINE DEDENT DEDENT ok = [ 0 for _ in range ( R + 1 ) ] NEW_LINE for i in range ( 0 , int ( len ( pows ) ) ) : NEW_LINE INDENT for j in range ( 0 , len ( pows ) ) : NEW_LINE INDENT if ( pows [ i ] + pows [ j ] <= R and pows [ i ] + pows [ j ] >= L ) : NEW_LINE INDENT ok [ pows [ i ] + pows [ j ] ] = 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( 0 , R + 1 ) : NEW_LINE INDENT ok [ i ] += ok [ i - 1 ] NEW_LINE DEDENT return ok [ R ] - ok [ L - 1 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT L = 5 NEW_LINE R = 8 NEW_LINE print ( TotalPerfectPowerSum ( L , R ) ) NEW_LINE DEDENT |
Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two | Python3 implementation for the above approach ; Structure of Node ; Function to calculate minimum absolute difference of subtrees after splitting the tree into two parts ; Reference variable to store the answer ; Function to store sum of values of current node , left subtree and right subtree in place of current node 's value ; Function to perform every possible split and calculate absolute difference of subtrees ; Absolute difference in subtrees if left edge is broken ; Absolute difference in subtrees if right edge is broken ; Update minDiff if a difference lesser than it is found ; Construct the tree ; Print the output | import sys NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minAbsDiff ( root ) : NEW_LINE INDENT minDiff = [ 0 ] * ( 1 ) NEW_LINE minDiff [ 0 ] = sys . maxsize NEW_LINE postOrder ( root ) NEW_LINE preOrder ( root , minDiff ) NEW_LINE return minDiff [ 0 ] NEW_LINE DEDENT def postOrder ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT root . val += postOrder ( root . left ) + postOrder ( root . right ) NEW_LINE return root . val NEW_LINE DEDENT def preOrder ( root , minDiff ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT leftDiff = abs ( root . left . val - ( root . val - root . left . val ) ) NEW_LINE rightDiff = abs ( root . right . val - ( root . val - root . right . val ) ) NEW_LINE minDiff [ 0 ] = min ( minDiff [ 0 ] , min ( leftDiff , rightDiff ) ) NEW_LINE return NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE print ( minAbsDiff ( root ) ) NEW_LINE |
Vertical width of Binary tree | Set 1 | class to create a new tree node ; get vertical width ; traverse left ; if curr is decrease then get value in minimum ; if curr is increase then get value in maximum ; traverse right ; 1 is added to include root in the width ; Driver Code | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def lengthUtil ( root , maximum , minimum , curr = 0 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT lengthUtil ( root . left , maximum , minimum , curr - 1 ) NEW_LINE if ( minimum [ 0 ] > curr ) : NEW_LINE INDENT minimum [ 0 ] = curr NEW_LINE DEDENT if ( maximum [ 0 ] < curr ) : NEW_LINE INDENT maximum [ 0 ] = curr NEW_LINE DEDENT lengthUtil ( root . right , maximum , minimum , curr + 1 ) NEW_LINE DEDENT def getLength ( root ) : NEW_LINE INDENT maximum = [ 0 ] NEW_LINE minimum = [ 0 ] NEW_LINE lengthUtil ( root , maximum , minimum , 0 ) NEW_LINE return ( abs ( minimum [ 0 ] ) + maximum [ 0 ] ) + 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 7 ) NEW_LINE root . left = newNode ( 6 ) NEW_LINE root . right = newNode ( 5 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 2 ) NEW_LINE root . right . right = newNode ( 1 ) NEW_LINE print ( getLength ( root ) ) NEW_LINE DEDENT |
Maximize Array sum after changing sign of any elements for exactly M times | Function to find the maximum sum with M flips ; Declare a priority queue i . e . min heap ; Declare the sum as zero ; Push all elements of the array in it ; Iterate for M times ; Get the top element ; Flip the sign of the top element ; Remove the top element ; Update the sum ; Push the temp into the queue ; Driver program ; Given input | def findMaximumSumWithMflips ( arr , N , M ) : NEW_LINE INDENT pq = [ ] NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( arr [ i ] ) NEW_LINE sum += arr [ i ] NEW_LINE pq . sort ( ) NEW_LINE DEDENT while ( M > 0 ) : NEW_LINE INDENT sum -= pq [ 0 ] NEW_LINE temp = - 1 * pq [ 0 ] NEW_LINE pq = pq [ 1 : ] NEW_LINE sum += temp NEW_LINE pq . append ( temp ) NEW_LINE pq . sort ( ) NEW_LINE M -= 1 NEW_LINE DEDENT print ( sum ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 3 , 7 , - 1 , - 5 , - 3 ] NEW_LINE N = len ( arr ) NEW_LINE M = 4 NEW_LINE findMaximumSumWithMflips ( arr , N , M ) NEW_LINE DEDENT |
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | Function to find the minimum number of operations to make all the elements of the array equal ; Store the sum of the array arr [ ] ; Traverse through the array ; If it is not possible to make all array element equal ; Store the minimum number of operations needed ; Traverse through the array ; Finally , print the minimum number operation to make array elements equal ; Driver Code ; Given Input ; Function Call | def miniOperToMakeAllEleEqual ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % n ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT valueAfterDivision = sum // n NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( abs ( valueAfterDivision - arr [ i ] ) % k != 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT count += abs ( valueAfterDivision - arr [ i ] ) // k NEW_LINE DEDENT print ( count // 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE k = 3 NEW_LINE arr = [ 5 , 8 , 11 ] NEW_LINE miniOperToMakeAllEleEqual ( arr , n , k ) NEW_LINE DEDENT |
Minimum operations to make product of adjacent element pair of prefix sum negative | Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the value of sum ; Check if i + r is odd ; Check if prefix sum is not positive ; Update the value of ans and sum ; Check if prefix sum is not negative ; Update the value of ans and sum ; Update the value of res ; Print the value of res ; Driver code | def minOperations ( a ) : NEW_LINE INDENT res = 100000000000 NEW_LINE N = len ( a ) NEW_LINE for r in range ( 0 , 2 ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( ( i + r ) % 2 ) : NEW_LINE INDENT if ( sum <= 0 ) : NEW_LINE INDENT ans += - sum + 1 NEW_LINE sum = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( sum >= 0 ) : NEW_LINE INDENT ans += sum + 1 ; NEW_LINE sum = - 1 ; NEW_LINE DEDENT DEDENT DEDENT res = min ( res , ans ) NEW_LINE DEDENT print ( res ) NEW_LINE DEDENT a = [ 1 , - 3 , 1 , 0 ] NEW_LINE minOperations ( a ) ; NEW_LINE |
Minimize sum of product of same | Function to print the arrays ; Function to reverse the subarray ; Function to calculate the minimum product of same - indexed elements of two given arrays ; Calculate initial product ; Traverse all odd length subarrays ; Remove the previous product ; Add the current product ; Check if current product is minimum or not ; Traverse all even length subarrays ; Remove the previous product ; Add to the current product ; Check if current product is minimum or not ; Update the pointers ; Reverse the subarray ; Print the subarray ; Driver Code | def Print ( a , b ) : NEW_LINE INDENT minProd = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT print ( a [ i ] , end = " β " ) NEW_LINE DEDENT print ( ) ; NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT print ( b [ i ] , end = " β " ) NEW_LINE minProd += a [ i ] * b [ i ] NEW_LINE DEDENT print ( ) NEW_LINE print ( minProd ) NEW_LINE DEDENT def reverse ( left , right , arr ) : NEW_LINE INDENT while ( left < right ) : NEW_LINE INDENT temp = arr [ left ] NEW_LINE arr [ left ] = arr [ right ] NEW_LINE arr [ right ] = temp NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT DEDENT def minimumProdArray ( a , b , l ) : NEW_LINE INDENT total = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT total += a [ i ] * b [ i ] NEW_LINE DEDENT Min = 2147483647 NEW_LINE first = 0 ; NEW_LINE second = 0 ; NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT left = i - 1 ; NEW_LINE right = i + 1 ; NEW_LINE total1 = total ; NEW_LINE while ( left >= 0 and right < len ( a ) ) : NEW_LINE INDENT total1 -= a [ left ] * b [ left ] + a [ right ] * b [ right ] ; NEW_LINE total1 += a [ left ] * b [ right ] + a [ right ] * b [ left ] ; NEW_LINE if ( Min >= total1 ) : NEW_LINE INDENT Min = total1 NEW_LINE first = left NEW_LINE second = right NEW_LINE DEDENT left -= 1 NEW_LINE right += 1 NEW_LINE DEDENT DEDENT for i in range ( len ( a ) ) : NEW_LINE INDENT left = i NEW_LINE right = i + 1 NEW_LINE total1 = total NEW_LINE while ( left >= 0 and right < len ( a ) ) : NEW_LINE INDENT total1 -= a [ left ] * b [ left ] + a [ right ] * b [ right ] NEW_LINE total1 += a [ left ] * b [ right ] + a [ right ] * b [ left ] NEW_LINE if ( Min >= total1 ) : NEW_LINE INDENT Min = total1 NEW_LINE first = left NEW_LINE second = right NEW_LINE DEDENT left -= 1 NEW_LINE right += 1 NEW_LINE DEDENT DEDENT if ( Min < total ) : NEW_LINE INDENT reverse ( first , second , a ) NEW_LINE Print ( a , b ) NEW_LINE DEDENT else : NEW_LINE INDENT Print ( a , b ) NEW_LINE DEDENT DEDENT n = 4 ; NEW_LINE a = [ 2 , 3 , 1 , 5 ] NEW_LINE b = [ 8 , 2 , 4 , 3 ] NEW_LINE minimumProdArray ( a , b , n ) NEW_LINE |
Maximize cost of removing all occurrences of substrings " ab " and " ba " | Function to find the maximum cost of removing substrings " ab " and " ba " from S ; MaxStr is the substring char array with larger cost ; MinStr is the substring char array with smaller cost ; ; Denotes larger point ; Denotes smaller point ; Stores cost scored ; Stack to keep track of characters ; Traverse the string ; If the substring is maxstr ; Pop from the stack ; Add maxp to cost ; Push the character to the stack ; Remaining string after removing maxstr ; Find remaining string ; Reversing the string retrieved from the stack ; Removing all occurences of minstr ; If the substring is minstr ; Pop from the stack ; Add minp to the cost ; Otherwise ; Return the maximum cost ; Driver Code ; Input String ; Costs | def MaxCollection ( S , P , Q ) : NEW_LINE INDENT maxstr = [ i for i in ( " ab " if P >= Q else " ba " ) ] NEW_LINE minstr = [ i for i in ( " ba " if P >= Q else " ab " ) ] NEW_LINE maxp = max ( P , Q ) NEW_LINE minp = min ( P , Q ) NEW_LINE cost = 0 NEW_LINE stack1 = [ ] NEW_LINE s = [ i for i in S ] NEW_LINE for ch in s : NEW_LINE INDENT if ( len ( stack1 ) > 0 and ( stack1 [ - 1 ] == maxstr [ 0 ] and ch == maxstr [ 1 ] ) ) : NEW_LINE INDENT del stack1 [ - 1 ] NEW_LINE cost += maxp NEW_LINE DEDENT else : NEW_LINE INDENT stack1 . append ( ch ) NEW_LINE DEDENT DEDENT sb = " " NEW_LINE while ( len ( stack1 ) > 0 ) : NEW_LINE INDENT sb += stack1 [ - 1 ] NEW_LINE del stack1 [ - 1 ] NEW_LINE DEDENT sb = sb [ : : - 1 ] NEW_LINE remstr = sb NEW_LINE for ch in remstr : NEW_LINE INDENT if ( len ( stack1 ) > 0 and ( stack1 [ - 1 ] == minstr [ 0 ] and ch == minstr [ 1 ] ) ) : NEW_LINE INDENT del stack1 [ - 1 ] NEW_LINE cost += minp NEW_LINE DEDENT else : NEW_LINE INDENT stack1 . append ( ch ) NEW_LINE DEDENT DEDENT return cost NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " cbbaabbaab " NEW_LINE P = 6 ; NEW_LINE Q = 4 ; NEW_LINE print ( MaxCollection ( S , P , Q ) ) ; NEW_LINE DEDENT |
Vertical width of Binary tree | Set 2 | A binary tree node has data , pointer to left child and a pointer to right child ; Function to fill hd in set . ; Third parameter is horizontal distance ; Driver Code ; Creating the above tree | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def fillSet ( root , s , hd ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT fillSet ( root . left , s , hd - 1 ) NEW_LINE s . add ( hd ) NEW_LINE fillSet ( root . right , s , hd + 1 ) NEW_LINE DEDENT def verticalWidth ( root ) : NEW_LINE INDENT s = set ( ) NEW_LINE fillSet ( root , s , 0 ) NEW_LINE return len ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . left . right = Node ( 8 ) NEW_LINE root . right . right . right = Node ( 9 ) NEW_LINE print ( verticalWidth ( root ) ) NEW_LINE DEDENT |
Maximum value of ( arr [ i ] * arr [ j ] ) + ( arr [ j ] | Function to find the value of the expression a * b + ( b - a ) ; Function to find the maximum value of the expression a * b + ( b - a ) possible for any pair ( a , b ) ; Sort the vector in ascending order ; Stores the maximum value ; Update ans by choosing the pair of the minimum and 2 nd minimum ; Update ans by choosing the pair of maximum and 2 nd maximum ; Return the value of ans ; Driver Code ; Given inputs | def calc ( a , b ) : NEW_LINE INDENT return a * b + ( b - a ) NEW_LINE DEDENT def findMaximum ( arr , N ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE ans = - 10 ** 9 NEW_LINE ans = max ( ans , calc ( arr [ 0 ] , arr [ 1 ] ) ) NEW_LINE ans = max ( ans , calc ( arr [ N - 2 ] , arr [ N - 1 ] ) ) NEW_LINE return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , - 47 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaximum ( arr , N ) ) NEW_LINE arr = [ 0 , - 47 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMaximum ( arr , N ) ) NEW_LINE DEDENT |
Minimize flips on K | ; Store previous flip events ; Remove an item which is out range of window . ; In a window , if A [ i ] is a even number with even times fliped , it need to be fliped again . On other hand , if A [ i ] is a odd number with odd times fliped , it need to be fliped again . ; Insert ; Driver code | def minKBitFlips ( A , K , N ) : NEW_LINE INDENT flip = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( len ( flip ) > 0 and ( i - flip [ 0 ] >= K ) ) : NEW_LINE INDENT flip . pop ( 0 ) NEW_LINE DEDENT if ( A [ i ] % 2 == len ( flip ) % 2 ) : NEW_LINE INDENT if ( i + K - 1 >= N ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT flip . append ( i ) NEW_LINE count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT A = [ 0 , 1 , 0 ] NEW_LINE N = len ( A ) NEW_LINE K = 1 NEW_LINE ans = minKBitFlips ( A , K , 3 ) NEW_LINE print ( ans ) NEW_LINE |
Minimize flips on K | ; We 're flipping the subarray from A[i] to A[i+K-1] ; ' ' β If β we β can ' t flip the entire subarray , its impossible ; Driver Code | def minKBitFlips ( A , K ) : NEW_LINE INDENT temp = [ 0 ] * len ( A ) NEW_LINE count = 0 NEW_LINE flip = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT flip ^= temp [ i ] NEW_LINE if ( A [ i ] == flip ) : NEW_LINE INDENT count += 1 NEW_LINE if ( i + K > len ( A ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT flip ^= 1 NEW_LINE if ( i + K < len ( A ) ) : NEW_LINE INDENT temp [ i + K ] ^= 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT A = [ 0 , 1 , 0 ] NEW_LINE K = 1 NEW_LINE ans = minKBitFlips ( A , K ) NEW_LINE print ( ans ) NEW_LINE |
Generate an N | Function to calculate GCD of given array ; Function to calculate GCD of two integers ; Utility function to check for all the combinations ; If a sequence of size N is obtained ; If gcd of current combination is K ; If current element from first array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; If current element from second array is divisible by K ; Recursively proceed further ; If current combination satisfies given condition ; Remove the element from the combination ; Function to check for all possible combinations ; Stores the subsequence ; If GCD of any sequence is not equal to K ; Given arrays ; Given value of K ; Function call to generate a subsequence whose GCD is K | def GCDArr ( a ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in a : NEW_LINE INDENT ans = GCD ( ans , i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def GCD ( a , b ) : NEW_LINE INDENT if not b : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def findSubseqUtil ( a , b , ans , k , i ) : NEW_LINE INDENT if len ( ans ) == len ( a ) : NEW_LINE INDENT if GCDArr ( ans ) == k : NEW_LINE INDENT print ( ans ) NEW_LINE return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if not a [ i ] % K : NEW_LINE INDENT ans . append ( a [ i ] ) NEW_LINE temp = findSubseqUtil ( a , b , ans , k , i + 1 ) NEW_LINE if temp == True : NEW_LINE INDENT return True NEW_LINE DEDENT ans . pop ( ) NEW_LINE DEDENT if not b [ i ] % k : NEW_LINE INDENT ans . append ( b [ i ] ) NEW_LINE temp = findSubseqUtil ( a , b , ans , k , i + 1 ) NEW_LINE if temp == True : NEW_LINE INDENT return True NEW_LINE DEDENT ans . pop ( ) NEW_LINE DEDENT return False NEW_LINE DEDENT def findSubseq ( A , B , K , i ) : NEW_LINE INDENT ans = [ ] NEW_LINE findSubseqUtil ( A , B , ans , K , i ) NEW_LINE if not ans : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT A = [ 5 , 3 , 6 , 2 , 9 ] NEW_LINE B = [ 21 , 7 , 14 , 12 , 28 ] NEW_LINE K = 3 NEW_LINE ans = findSubseq ( A , B , K , 0 ) NEW_LINE |
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order | Function to find the K - th element in the required permutation ; Stores the required permutation ; Insert all the even numbers less than or equal to N ; Now , insert all odd numbers less than or equal to N ; Print the Kth element ; Driver Code ; functions call | def findKthElement ( N , K ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT print ( v [ K - 1 ] ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 10 NEW_LINE K = 3 NEW_LINE findKthElement ( N , K ) NEW_LINE DEDENT |
Minimum subsequences of a string A required to be appended to obtain the string B | Python3 program for the above approach ; Function to count the minimum subsequences of a A required to be appended to obtain the B ; Size of the string ; Maps characters to their respective indices ; Insert indices of characters into the sets ; Stores the position of the last visited index in the A . Initially set it to - 1. ; Stores the required count ; Iterate over the characters of B ; If the character in B is not present in A , return - 1 ; Fetch the next index from B [ i ] 's set ; If the iterator points to the end of that set ; If it doesn 't poto the end, update previous ; Prthe answer ; Driver Code | from bisect import bisect_right NEW_LINE def countminOpsToConstructAString ( A , B ) : NEW_LINE INDENT N = len ( A ) NEW_LINE i = 0 NEW_LINE mp = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ ord ( A [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT previous = - 1 NEW_LINE ans , i = 1 , 0 NEW_LINE while i < len ( B ) : NEW_LINE INDENT ch = B [ i ] NEW_LINE if ( len ( mp [ ord ( ch ) - ord ( ' a ' ) ] ) == 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT it = bisect_right ( mp [ ord ( ch ) - ord ( ' a ' ) ] , previous ) NEW_LINE if ( it == len ( mp [ ord ( ch ) - ord ( ' a ' ) ] ) ) : NEW_LINE INDENT previous = - 1 NEW_LINE ans += 1 NEW_LINE continue NEW_LINE DEDENT previous = mp [ ord ( ch ) - ord ( ' a ' ) ] [ it ] NEW_LINE i += 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A , B = " abc " , " abac " NEW_LINE countminOpsToConstructAString ( A , B ) NEW_LINE DEDENT |
Maximize difference between odd and even indexed array elements by shift operations | Function to minimize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the minimum possible value ; Function to maximize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the maximum possible value ; Function to maximize the absolute difference between even and odd indexed array elements ; To calculate the difference of odd indexed elements and even indexed elements ; To calculate the difference between odd and even indexed array elements ; Print the maximum value ; Driver Code | def minimize ( n ) : NEW_LINE INDENT optEle = n NEW_LINE strEle = str ( n ) NEW_LINE for idx in range ( len ( strEle ) ) : NEW_LINE INDENT temp = int ( strEle [ idx : ] + strEle [ : idx ] ) NEW_LINE optEle = min ( optEle , temp ) NEW_LINE DEDENT return optEle NEW_LINE DEDENT def maximize ( n ) : NEW_LINE INDENT optEle = n NEW_LINE strEle = str ( n ) NEW_LINE for idx in range ( len ( strEle ) ) : NEW_LINE INDENT temp = int ( strEle [ idx : ] + strEle [ : idx ] ) NEW_LINE optEle = max ( optEle , temp ) NEW_LINE DEDENT return optEle NEW_LINE DEDENT def minimumDifference ( arr ) : NEW_LINE INDENT caseOne = 0 NEW_LINE minVal = 0 NEW_LINE maxVal = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE minVal += minimize ( arr [ i ] ) NEW_LINE else : NEW_LINE maxVal += maximize ( arr [ i ] ) NEW_LINE DEDENT caseOne = abs ( maxVal - minVal ) NEW_LINE caseTwo = 0 NEW_LINE minVal = 0 NEW_LINE maxVal = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if i % 2 : NEW_LINE maxVal += maximize ( arr [ i ] ) NEW_LINE else : NEW_LINE minVal += minimize ( arr [ i ] ) NEW_LINE DEDENT caseTwo = abs ( maxVal - minVal ) NEW_LINE print ( max ( caseOne , caseTwo ) ) NEW_LINE DEDENT arr = [ 332 , 421 , 215 , 584 , 232 ] NEW_LINE minimumDifference ( arr ) NEW_LINE |
Find if given vertical level of binary tree is sorted or not | Python program to determine whether vertical level l of binary tree is sorted or not . ; Structure of a tree node . ; Helper function to determine if vertical level l of given binary tree is sorted or not . ; If root is null , then the answer is an empty subset and an empty subset is always considered to be sorted . ; Variable to store previous value in vertical level l . ; Variable to store current level while traversing tree vertically . ; Variable to store current node while traversing tree vertically . ; Declare queue to do vertical order traversal . A pair is used as element of queue . The first element in pair represents the node and the second element represents vertical level of that node . ; Insert root in queue . Vertical level of root is 0. ; Do vertical order traversal until all the nodes are not visited . ; Check if level of node extracted from queue is required level or not . If it is the required level then check if previous value in that level is less than or equal to value of node . ; If left child is not NULL then push it in queue with level reduced by 1. ; If right child is not NULL then push it in queue with level increased by 1. ; If the level asked is not present in the given binary tree , that means that level will contain an empty subset . Therefore answer will be true . ; Driver Code ; 1 / \ 2 5 / \ 7 4 / 6 | from collections import deque NEW_LINE from sys import maxsize NEW_LINE INT_MIN = - maxsize NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isSorted ( root : Node , level : int ) -> bool : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT prevVal = INT_MIN NEW_LINE currLevel = 0 NEW_LINE currNode = Node ( 0 ) NEW_LINE q = deque ( ) NEW_LINE q . append ( ( root , 0 ) ) NEW_LINE while q : NEW_LINE INDENT currNode = q [ 0 ] [ 0 ] NEW_LINE currLevel = q [ 0 ] [ 1 ] NEW_LINE q . popleft ( ) NEW_LINE if currLevel == level : NEW_LINE INDENT if prevVal <= currNode . key : NEW_LINE INDENT prevVal = currNode . key NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT if currNode . left : NEW_LINE INDENT q . append ( ( currNode . left , currLevel - 1 ) ) NEW_LINE DEDENT if currNode . right : NEW_LINE INDENT q . append ( ( currNode . right , currLevel + 1 ) ) NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 5 ) NEW_LINE root . left . left = Node ( 7 ) NEW_LINE root . left . right = Node ( 4 ) NEW_LINE root . left . right . left = Node ( 6 ) NEW_LINE level = - 1 NEW_LINE if isSorted ( root , level ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Minimize operations of removing 2 i | Function to find minimum count of steps required to remove all the array elements ; Stores minimum count of steps required to remove all the array elements ; Update N ; Traverse each bit of N ; If current bit is set ; Update cntStep ; Driver Code | def minimumStepReqArr ( arr , N ) : NEW_LINE INDENT cntStep = 0 NEW_LINE N += 1 NEW_LINE i = 31 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( N & ( 1 << i ) ) : NEW_LINE INDENT cntStep += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return cntStep NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minimumStepReqArr ( arr , N ) ) NEW_LINE DEDENT |
Minimize removal of alternating subsequences to empty given Binary String | Function to find the minimum number of operations required to empty the string ; Initialize variables ; Traverse the string ; If current character is 0 ; Update maximum consecutive 0 s and 1 s ; Print the minimum operation ; Driver code + ; input string ; length of string ; Function Call | def minOpsToEmptyString ( S , N ) : NEW_LINE INDENT one = 0 NEW_LINE zero = 0 NEW_LINE x0 = 0 NEW_LINE x1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT x0 += 1 NEW_LINE x1 = 0 NEW_LINE DEDENT else : NEW_LINE INDENT x1 += 1 NEW_LINE x0 = 0 NEW_LINE DEDENT zero = max ( x0 , zero ) NEW_LINE one = max ( x1 , one ) NEW_LINE DEDENT print ( max ( one , zero ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "0100100111" NEW_LINE N = len ( S ) NEW_LINE minOpsToEmptyString ( S , N ) NEW_LINE DEDENT |
Swap upper and lower triangular halves of a given Matrix | Function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; Store the matrix elements from upper & lower triangular halves ; Traverse the matrix mat [ ] [ ] ; Find the index ; If current element lies on the principal diagonal ; If current element lies below the principal diagonal ; If current element lies above the principal diagonal ; Traverse again to swap values ; Find the index ; Principal diagonal ; Below main diagonal ; Above main diagonal ; Traverse the matrix and pr ; Driver Code ; Given Matrix mat [ ] [ ] ; Swap the upper and lower triangular halves | def ReverseSwap ( mat , n ) : NEW_LINE INDENT lowerEle = [ [ ] for i in range ( n ) ] NEW_LINE upperEle = [ [ ] for i in range ( n ) ] NEW_LINE index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT index = abs ( i - j ) NEW_LINE if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( j < i ) : NEW_LINE INDENT lowerEle [ index ] . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT else : NEW_LINE INDENT upperEle [ index ] . append ( mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT index = abs ( i - j ) NEW_LINE if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT elif ( j < i ) : NEW_LINE INDENT mat [ i ] [ j ] = upperEle [ index ] [ - 1 ] NEW_LINE del upperEle [ index ] [ - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT mat [ i ] [ j ] = lowerEle [ index ] [ - 1 ] NEW_LINE del lowerEle [ index ] [ - 1 ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 2 ] , [ 4 , 5 ] ] NEW_LINE N = len ( mat ) NEW_LINE ReverseSwap ( mat , N ) NEW_LINE DEDENT |
Minimize sum of K positive integers with given LCM | Function to find the prime power of X ; Stores prime powers of X ; Iterate over the range [ 2 , sqrt ( X ) ] ; If X is divisible by i ; Stores prime power ; Calculate prime power of X ; Update X ; Update p ; Insert prime powers into primePow [ ] ; If X exceeds 1 ; Function to calculate the sum of array elements ; Stores sum of array elements ; Traverse the array ; Update sum ; Function to partition array into K groups such that sum of elements of the K groups is minimum ; If count of prime powers is equal to pos ; Stores minimum sum of of each partition of arr [ ] into K groups ; Traverse the array arr [ ] ; Include primePow [ pos ] into i - th groups ; Update res ; Remove factors [ pos ] from i - th groups ; Utility function to calculate minimum sum of K positive integers whose LCM is X ; Stores all prime powers of X ; Stores count of prime powers ; Stores minimum sum of K positive integers whose LCM is X ; If n is less than or equal to k ; Traverse primePow [ ] array ; Update sum ; Update sum ; arr [ i ] : Stores element in i - th group by partitioning the primePow [ ] array ; Update sum ; Driver Code | def primePower ( X ) : NEW_LINE INDENT primePow = [ ] NEW_LINE for i in range ( 2 , X + 1 ) : NEW_LINE INDENT if i * i > X + 1 : NEW_LINE INDENT break NEW_LINE DEDENT if ( X % i == 0 ) : NEW_LINE INDENT p = 1 NEW_LINE while ( X % i == 0 ) : NEW_LINE INDENT X //= i NEW_LINE p *= i NEW_LINE DEDENT primePow . append ( p ) NEW_LINE DEDENT DEDENT if ( X > 1 ) : NEW_LINE INDENT primePow . append ( X ) NEW_LINE DEDENT return primePow NEW_LINE DEDENT def getSum ( ar ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in ar : NEW_LINE INDENT sum += i NEW_LINE DEDENT return sum NEW_LINE DEDENT def getMinSum ( pos , arr , primePow ) : NEW_LINE INDENT if ( pos == len ( primePow ) ) : NEW_LINE INDENT return getSum ( arr ) NEW_LINE DEDENT res = 10 ** 9 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT arr [ i ] *= primePow [ pos ] NEW_LINE res = min ( res , getMinSum ( pos + 1 , arr , primePow ) ) NEW_LINE arr [ i ] //= primePow [ pos ] NEW_LINE DEDENT return res NEW_LINE DEDENT def minimumSumWithGivenLCM ( k , x ) : NEW_LINE INDENT primePow = primePower ( x ) NEW_LINE n = len ( primePow ) NEW_LINE sum = 0 NEW_LINE if ( n <= k ) : NEW_LINE INDENT for i in primePow : NEW_LINE INDENT sum += i NEW_LINE DEDENT sum += k - n NEW_LINE DEDENT else : NEW_LINE INDENT arr = [ 1 ] * ( k ) NEW_LINE sum = getMinSum ( 0 , arr , primePow ) NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 3 NEW_LINE x = 210 NEW_LINE print ( minimumSumWithGivenLCM ( k , x ) ) NEW_LINE DEDENT |
Minimum removal of subsequences of distinct consecutive characters required to empty a given string | Function to count minimum operations required to make the string an empty string ; Stores count of 1 s by removing consecutive distinct subsequence ; Stores count of 0 s by removing consecutive distinct subsequence ; Traverse the string ; If current character is 0 ; Update cntOne ; Update cntZero ; If current character is 1 ; Update cntZero ; Update cntOne ; Driver code | def findMinOperationsReqEmpStr ( str ) : NEW_LINE INDENT cntOne = 0 NEW_LINE cntZero = 0 NEW_LINE for element in str : NEW_LINE INDENT if element == '0' : NEW_LINE INDENT if cntOne > 0 : NEW_LINE INDENT cntOne = cntOne - 1 NEW_LINE DEDENT cntZero = cntZero + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if cntZero > 0 : NEW_LINE INDENT cntZero = cntZero - 1 NEW_LINE DEDENT cntOne = cntOne + 1 NEW_LINE DEDENT DEDENT return cntOne + cntZero NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = "0100100111" NEW_LINE print ( findMinOperationsReqEmpStr ( str ) ) NEW_LINE DEDENT |
Minimum number of flips required such that the last cell of matrix can be reached from any other cell | Function to calculate the minimum number of flips required ; Dimensions of mat [ ] [ ] ; Initialize answer ; Count all ' D ' s in the last row ; Count all ' R ' s in the last column ; Print answer ; Given matrix ; Function call ; Print answer | def countChanges ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE ans = 0 NEW_LINE for j in range ( m - 1 ) : NEW_LINE INDENT if ( mat [ n - 1 ] [ j ] != ' R ' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ m - 1 ] != ' D ' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ [ ' R ' , ' R ' , ' R ' , ' D ' ] , [ ' D ' , ' D ' , ' D ' , ' R ' ] , [ ' R ' , ' D ' , ' R ' , ' F ' ] ] NEW_LINE cnt = countChanges ( arr ) NEW_LINE print ( cnt ) NEW_LINE |
Check if a binary tree is sorted level | Python3 program to determine whether binary tree is level sorted or not . ; Function to create new tree node . ; Function to determine if given binary tree is level sorted or not . ; to store maximum value of previous level . ; to store minimum value of current level . ; to store maximum value of current level . ; to store number of nodes in current level . ; queue to perform level order traversal . ; find number of nodes in current level . ; traverse current level and find minimum and maximum value of this level . ; if minimum value of this level is not greater than maximum value of previous level then given tree is not level sorted . ; maximum value of this level is previous maximum value for next level . ; Driver Code ; 1 / 4 \ 6 / \ 8 9 / \ 12 10 | from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def isSorted ( root ) : NEW_LINE INDENT prevMax = - 999999999999 NEW_LINE minval = None NEW_LINE maxval = None NEW_LINE levelSize = None NEW_LINE q = Queue ( ) NEW_LINE q . put ( root ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT levelSize = q . qsize ( ) NEW_LINE minval = 999999999999 NEW_LINE maxval = - 999999999999 NEW_LINE while ( levelSize > 0 ) : NEW_LINE INDENT root = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE levelSize -= 1 NEW_LINE minval = min ( minval , root . key ) NEW_LINE maxval = max ( maxval , root . key ) NEW_LINE if ( root . left ) : NEW_LINE INDENT q . put ( root . left ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT q . put ( root . right ) NEW_LINE DEDENT DEDENT if ( minval <= prevMax ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT prevMax = maxval NEW_LINE DEDENT return 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 6 ) NEW_LINE root . left . right . left = newNode ( 8 ) NEW_LINE root . left . right . right = newNode ( 9 ) NEW_LINE root . left . right . left . left = newNode ( 12 ) NEW_LINE root . left . right . right . right = newNode ( 10 ) NEW_LINE if ( isSorted ( root ) ) : NEW_LINE INDENT print ( " Sorted " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β sorted " ) NEW_LINE DEDENT DEDENT |
Smallest subsequence having GCD equal to GCD of given array | Python3 program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of array . ; Generate all possible pairs . ; If gcd of current pair equal to gcdArr ; Print current pair of the array ; Driver Code | import math NEW_LINE def printSmallSub ( arr , N ) : NEW_LINE INDENT gcdArr = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT gcdArr = math . gcd ( gcdArr , arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] == gcdArr ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE return NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( math . gcd ( arr [ i ] , arr [ j ] ) == gcdArr ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE print ( arr [ j ] , end = " β " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 6 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE printSmallSub ( arr , N ) NEW_LINE DEDENT |
Count pairs in an array whose product is composite number | Python3 program to implement the above approach ; Function to get all the prime numbers in the range [ 1 , X ] ; Stores the boolean value to check if a number is prime or not ; Mark all non prime numbers as false ; If i is prime number ; Mark j as a composite number ; Function to get the count of pairs whose product is a composite number ; Stores the boolean value to check if a number is prime or not ; Stores the count of 1 s ; Stores the count of prime numbers ; Traverse the given array . ; Stores count of pairs whose product is not a composite number ; Stores the count of pairs whose product is composite number ; Driver Code | X = 1000000 NEW_LINE def getPrimeNum ( ) : NEW_LINE INDENT isPrime = [ True ] * ( X ) NEW_LINE isPrime [ 0 ] = False NEW_LINE isPrime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i <= X : NEW_LINE INDENT if ( isPrime [ i ] == True ) : NEW_LINE INDENT for j in range ( i * i , X , i ) : NEW_LINE INDENT isPrime [ j ] = False NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return isPrime NEW_LINE DEDENT def cntPairs ( arr , N ) : NEW_LINE INDENT isPrime = getPrimeNum ( ) NEW_LINE cntOne = 0 NEW_LINE cntPrime = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 1 ) : NEW_LINE INDENT cntOne += 1 NEW_LINE DEDENT elif ( isPrime [ i ] ) : NEW_LINE INDENT cntPrime += 1 NEW_LINE DEDENT DEDENT cntNonComp = 0 NEW_LINE cntNonComp = ( cntPrime * cntOne + cntOne * ( cntOne - 1 ) // 2 ) NEW_LINE res = 0 NEW_LINE res = ( N * ( N - 1 ) // 2 - cntNonComp ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE print ( cntPairs ( arr , N ) ) NEW_LINE DEDENT |
Find the greater number closest to N having at most one non | Python3 program to implement the above approach ; Function to calculate X ^ n in log ( n ) ; Stores the value of X ^ n ; If N is odd ; Function to find the closest number > N having at most 1 non - zero digit ; Stores the count of digits in N ; Stores the power of 10 ^ ( n - 1 ) ; Stores the last ( n - 1 ) digits ; Store the answer ; Driver Code ; Function call | import math NEW_LINE def power ( X , n ) : NEW_LINE INDENT res = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( n & 1 != 0 ) : NEW_LINE INDENT res = res * X NEW_LINE DEDENT X = X * X NEW_LINE n = n >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def closestgtNum ( N ) : NEW_LINE INDENT n = int ( math . log10 ( N ) + 1 ) NEW_LINE P = power ( 10 , n - 1 ) NEW_LINE Y = N % P NEW_LINE res = N + ( P - Y ) NEW_LINE return res NEW_LINE DEDENT N = 120 NEW_LINE print ( closestgtNum ( N ) ) NEW_LINE |
Rearrange an array to make similar indexed elements different from that of another array | Function to find the arrangement of array B [ ] such that element at each index of A [ ] and B [ ] are not equal ; Length of array ; Print not possible , if arrays only have single equal element ; Reverse array B ; Traverse over arrays to check if there is any index where A [ i ] and B [ i ] are equal ; Swap B [ i ] with B [ i - 1 ] ; Break the loop ; Print required arrangement of array B ; Given arrays A [ ] and B [ ] ; Function call | def RearrangeB ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE if ( n == 1 and A [ 0 ] == B [ 0 ] ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT for i in range ( n // 2 ) : NEW_LINE INDENT t = B [ i ] NEW_LINE B [ i ] = B [ n - i - 1 ] NEW_LINE B [ n - i - 1 ] = t NEW_LINE DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( B [ i ] == A [ i ] ) : NEW_LINE INDENT B [ i ] , B [ i - 1 ] = B [ i - 1 ] , B [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT for k in B : NEW_LINE INDENT print ( k , end = " β " ) NEW_LINE DEDENT DEDENT A = [ 2 , 4 , 5 , 8 ] NEW_LINE B = [ 2 , 4 , 5 , 8 ] NEW_LINE RearrangeB ( A , B ) NEW_LINE |
Swap the elements between any two given quadrants of a Matrix | Python3 program for the above approach ; Function to iterate over the X quadrant and swap its element with Y quadrant ; Iterate over X quadrant ; Swap operations ; Function to swap the elements of the two given quadrants ; For Swapping 1 st and 2 nd Quadrant ; For Swapping 1 st and 3 rd Quadrant ; For Swapping 1 st and 4 th Quadrant ; For Swapping 2 nd and 3 rd Quadrant ; For Swapping 2 nd and 4 th Quadrant ; For Swapping 3 rd and 4 th Quadrant ; Print the resultant matrix ; Function to print the matrix ; Iterate over the rows ; Iterate over the cols ; Given matrix ; Given quadrants ; Function Call | N , M = 6 , 6 NEW_LINE def swap ( mat , startx_X , starty_X , startx_Y , starty_Y ) : NEW_LINE INDENT row , col = 0 , 0 NEW_LINE i = startx_X NEW_LINE while ( bool ( True ) ) : NEW_LINE INDENT col = 0 NEW_LINE j = startx_X NEW_LINE while ( bool ( True ) ) : NEW_LINE INDENT temp = mat [ i ] [ j ] NEW_LINE mat [ i ] [ j ] = mat [ startx_Y + row ] [ starty_Y + col ] NEW_LINE mat [ startx_Y + row ] [ starty_Y + col ] = temp NEW_LINE col += 1 NEW_LINE if col >= M // 2 : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT row += 1 NEW_LINE if row >= N // 2 : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT def swapQuadOfMatrix ( mat , X , Y ) : NEW_LINE INDENT if ( X == 1 and Y == 2 ) : NEW_LINE INDENT swap ( mat , 0 , 0 , 0 , M // 2 ) NEW_LINE DEDENT elif ( X == 1 and Y == 3 ) : NEW_LINE INDENT swap ( mat , 0 , 0 , N // 2 , 0 ) NEW_LINE DEDENT elif ( X == 1 and Y == 4 ) : NEW_LINE INDENT swap ( mat , 0 , 0 , N // 2 , M // 2 ) NEW_LINE DEDENT elif ( X == 2 and Y == 3 ) : NEW_LINE INDENT swap ( mat , 0 , M // 2 , N // 2 , 0 ) NEW_LINE DEDENT elif ( X == 2 and Y == 4 ) : NEW_LINE INDENT swap ( mat , 0 , M // 2 , N // 2 , M // 2 ) NEW_LINE DEDENT elif ( X == 3 and Y == 4 ) : NEW_LINE INDENT swap ( mat , N // 2 , 0 , N // 2 , M // 2 ) NEW_LINE DEDENT printMat ( mat ) NEW_LINE DEDENT def printMat ( mat ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT mat = [ [ 1 , 2 , 3 , 4 , 5 , 6 ] , [ 7 , 8 , 9 , 10 , 11 , 12 ] , [ 13 , 14 , 15 , 16 , 17 , 18 ] , [ 19 , 20 , 21 , 22 , 23 , 24 ] , [ 25 , 26 , 27 , 28 , 29 , 30 ] , [ 31 , 32 , 33 , 34 , 35 , 36 ] ] NEW_LINE X , Y = 1 , 4 NEW_LINE swapQuadOfMatrix ( mat , X , Y ) NEW_LINE |
Bottom View of a Binary Tree | Tree node class ; Constructor of tree node ; Method that prints the bottom view . ; Initialize a variable ' hd ' with 0 for the root element . ; TreeMap which stores key value pair sorted on key value ; Queue to store tree nodes in level order traversal ; Assign initialized horizontal distance value to root node and add it to the queue . ; In STL , append ( ) is used enqueue an item ; Loop until the queue is empty ( standard level order loop ) ; In STL , pop ( ) is used dequeue an item ; Extract the horizontal distance value from the dequeued tree node . ; Put the dequeued tree node to TreeMap having key as horizontal distance . Every time we find a node having same horizontal distance we need to replace the data in the map . ; If the dequeued node has a left child , add it to the queue with a horizontal distance hd - 1. ; If the dequeued node has a right child , add it to the queue with a horizontal distance hd + 1. ; Traverse the map elements using the iterator . ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . hd = 1000000 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def bottomView ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT hd = 0 NEW_LINE m = dict ( ) NEW_LINE q = [ ] NEW_LINE root . hd = hd NEW_LINE q . append ( root ) NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT temp = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE hd = temp . hd NEW_LINE m [ hd ] = temp . data NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT temp . left . hd = hd - 1 NEW_LINE q . append ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT temp . right . hd = hd + 1 NEW_LINE q . append ( temp . right ) NEW_LINE DEDENT DEDENT for i in sorted ( m . keys ( ) ) : NEW_LINE INDENT print ( m [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE print ( " Bottom β view β of β the β given β binary β tree β : " ) NEW_LINE bottomView ( root ) NEW_LINE DEDENT |
Minimum increments by index value required to obtain at least two equal Array elements | Function to calculate the minimum number of steps required ; Stores minimum difference ; Driver Code | def incrementCount ( arr , N ) : NEW_LINE INDENT mini = arr [ 0 ] - arr [ 1 ] NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT mini = min ( mini , arr [ i - 1 ] - arr [ i ] ) NEW_LINE DEDENT print ( mini ) NEW_LINE DEDENT N = 3 NEW_LINE arr = [ 12 , 8 , 4 ] NEW_LINE incrementCount ( arr , N ) NEW_LINE |
Minimum operations required to convert all characters of a String to a given Character | Function to find the minimum number of operations required ; Maximum number of characters that can be changed in one operation ; If length of the less than maximum number of characters that can be changed in an operation ; Set the last index as the index for the operation ; Otherwise ; If size of the is equal to the maximum number of characters in an operation ; Find the number of operations required ; Find the starting position ; Print i - th index ; Shift to next index ; Otherwise ; Find the number of operations required ; If n % div exceeds k ; Print i - th index ; Shift to next index ; Driver Code | def countOperations ( n , k ) : NEW_LINE INDENT div = 2 * k + 1 NEW_LINE if ( n // 2 <= k ) : NEW_LINE INDENT print ( 1 ) NEW_LINE if ( n > k ) : NEW_LINE INDENT print ( k + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( n % div == 0 ) : NEW_LINE INDENT oprn = n // div NEW_LINE print ( oprn ) NEW_LINE pos = k + 1 NEW_LINE print ( pos , end = " β " ) NEW_LINE for i in range ( 1 , oprn + 1 ) : NEW_LINE INDENT print ( pos , end = " β " ) NEW_LINE pos += div NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT oprn = n // div + 1 NEW_LINE print ( oprn ) NEW_LINE pos = n % div NEW_LINE if ( n % div > k ) : NEW_LINE INDENT pos -= k NEW_LINE DEDENT for i in range ( 1 , oprn + 1 ) : NEW_LINE INDENT print ( pos , end = " β " ) NEW_LINE pos += div NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " edfreqwsazxet " NEW_LINE ch = ' $ ' NEW_LINE n = len ( str ) NEW_LINE k = 4 NEW_LINE countOperations ( n , k ) NEW_LINE DEDENT |
Length of largest subsequence consisting of a pair of alternating digits | Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of the string ; Increment length ; Increment length ; Update maxi ; Check if maxi is not equal to 1 the print otherwise pr0 ; Driver Code ; Given string ; Function call | def largestSubsequence ( s ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT lenn = 0 NEW_LINE prev1 = chr ( j + ord ( '0' ) ) NEW_LINE for k in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ k ] == chr ( i + ord ( '0' ) ) and prev1 == chr ( j + ord ( '0' ) ) ) : NEW_LINE INDENT prev1 = s [ k ] NEW_LINE lenn += 1 NEW_LINE DEDENT elif ( s [ k ] == chr ( j + ord ( '0' ) ) and prev1 == chr ( i + ord ( '0' ) ) ) : NEW_LINE INDENT prev1 = s [ k ] NEW_LINE lenn += 1 NEW_LINE DEDENT DEDENT maxi = max ( lenn , maxi ) NEW_LINE DEDENT DEDENT DEDENT if ( maxi != 1 ) : NEW_LINE INDENT print ( maxi ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( 0 ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "1542745249842" NEW_LINE largestSubsequence ( s ) NEW_LINE DEDENT |
Bottom View of a Binary Tree | Tree node class ; Constructor of tree node ; printBottomViewUtil function ; Base case ; If current level is more than or equal to maximum level seen so far for the same horizontal distance or horizontal distance is seen for the first time , update the dictionary ; recur for left subtree by decreasing horizontal distance and increasing level by 1 ; recur for right subtree by increasing horizontal distance and increasing level by 1 ; printBottomView function ; Create a dictionary where key -> relative horizontal distance of the node from root node and value -> pair containing node 's value and its level ; Traverse the dictionary in sorted order of their keys and print the bottom view ; Driver Code | class Node : NEW_LINE INDENT def __init__ ( self , key = None , left = None , right = None ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def printBottomViewUtil ( root , d , hd , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if hd in d : NEW_LINE INDENT if level >= d [ hd ] [ 1 ] : NEW_LINE INDENT d [ hd ] = [ root . data , level ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT d [ hd ] = [ root . data , level ] NEW_LINE DEDENT printBottomViewUtil ( root . left , d , hd - 1 , level + 1 ) NEW_LINE printBottomViewUtil ( root . right , d , hd + 1 , level + 1 ) NEW_LINE DEDENT def printBottomView ( root ) : NEW_LINE INDENT d = dict ( ) NEW_LINE printBottomViewUtil ( root , d , 0 , 0 ) NEW_LINE for i in sorted ( d . keys ( ) ) : NEW_LINE INDENT print ( d [ i ] [ 0 ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 22 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 3 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 25 ) NEW_LINE root . left . right . left = Node ( 10 ) NEW_LINE root . left . right . right = Node ( 14 ) NEW_LINE print ( " Bottom β view β of β the β given β binary β tree β : " ) NEW_LINE printBottomView ( root ) NEW_LINE DEDENT |
Find maximum GCD value from root to leaf in a Binary tree | Initialise to update the maximum gcd value from all the path ; Node structure ; Initialize constructor ; Function to find gcd of a and b ; Function to find the gcd of a path ; Function to find the maximum value of gcd from root to leaf in a Binary tree ; Check if root is not null ; Find the maximum gcd of path value and store in global maxm variable ; Traverse left of binary tree ; Traverse right of the binary tree ; Driver Code ; Given Tree ; Function call ; Print the maximum AND value | global maxm NEW_LINE maxm = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def find_gcd ( arr ) : NEW_LINE INDENT if ( len ( arr ) == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT g = arr [ 0 ] NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT g = gcd ( g , arr [ i ] ) NEW_LINE DEDENT return g NEW_LINE DEDENT def maxm_gcd ( root , ans ) : NEW_LINE INDENT global maxm NEW_LINE if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT ans . append ( root . val ) NEW_LINE maxm = max ( find_gcd ( ans ) , maxm ) NEW_LINE return NEW_LINE DEDENT ans . append ( root . val ) NEW_LINE maxm_gcd ( root . left , ans ) NEW_LINE maxm_gcd ( root . right , ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 15 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 7 ) NEW_LINE root . left . left = Node ( 15 ) NEW_LINE root . left . right = Node ( 1 ) NEW_LINE root . right . left = Node ( 31 ) NEW_LINE root . right . right = Node ( 9 ) NEW_LINE maxm_gcd ( root , [ ] ) NEW_LINE print ( maxm ) NEW_LINE DEDENT |
Count of pairs with sum N from first N natural numbers | Funciton to calculate the value of count ; Stores the count of pairs ; Set the two pointers ; Check if the sum of pirs is equal to n ; Increase the count of pairs ; Move to the next pair ; Driver code | def numberOfPairs ( n ) : NEW_LINE INDENT count = 0 NEW_LINE i = 1 NEW_LINE j = n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( i + j ) == n : NEW_LINE count += 1 NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 NEW_LINE print ( numberOfPairs ( n ) ) NEW_LINE DEDENT |
Count of ways to generate a Matrix with product of each row and column as 1 or | Function to return the number of possible ways ; Check if product can be - 1 ; driver code | def Solve ( N , M ) : NEW_LINE INDENT temp = ( N - 1 ) * ( M - 1 ) NEW_LINE ans = pow ( 2 , temp ) NEW_LINE if ( ( N + M ) % 2 != 0 ) : NEW_LINE INDENT print ( ans ) NEW_LINE else : NEW_LINE print ( 2 * ans ) NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 3 , 3 NEW_LINE Solve ( N , M ) NEW_LINE DEDENT DEDENT DEDENT |
Maximum number of bridges in a path of a given graph | Python3 program to find the maximum number of bridges in any path of the given graph ; Stores the nodes and their connections ; Store the tree with Bridges as the edges ; Stores the visited nodes ; For finding bridges ; for Disjoint Set Union ; For storing actual bridges ; Stores the number of nodes and edges ; For finding bridges ; Function to find root of the component in which A lies ; Doing path compression ; Function to do union between a and b ; If both are already in the same component ; If both have same rank , then increase anyone 's rank ; Function to find bridges ; Initialize in time and low value ; Update the low value of the parent ; Perform DFS on its child updating low if the child has connection with any ancestor ; Bridge found ; Otherwise ; Find union between parent and child as they are in same component ; Function to find diameter of the tree for storing max two depth child ; Finding max two depth from its children ; Update diameter with the sum of max two depths ; Return the maximum depth ; Function to find maximum bridges bwtween any two nodes ; DFS to find bridges ; If no bridges are found ; Iterate over all bridges ; Find the endpoints ; Generate the tree with bridges as the edges ; Update the head ; Return the diameter ; Graph = > 1 -- -- 2 -- -- 3 -- -- 4 | | 5 -- -- 6 | N = 100005 NEW_LINE v = [ ] NEW_LINE g = [ ] NEW_LINE vis = [ False ] * ( N ) NEW_LINE In = [ 0 ] * ( N ) NEW_LINE low = [ 0 ] * ( N ) NEW_LINE parent = [ 0 ] * ( N ) NEW_LINE rnk = [ 0 ] * ( N ) NEW_LINE bridges = [ ] NEW_LINE n , m = 6 , 6 NEW_LINE timer = 0 NEW_LINE diameter = 0 NEW_LINE def swap ( x , y ) : NEW_LINE INDENT temp = x NEW_LINE x = y NEW_LINE y = temp NEW_LINE DEDENT def find_set ( a ) : NEW_LINE INDENT global N , v , g , vis , In , low , parent , rnk , bridges , n , m , timer , diameter NEW_LINE if parent [ a ] == a : NEW_LINE INDENT return a NEW_LINE DEDENT parent [ a ] = find_set ( parent [ a ] ) NEW_LINE return parent [ a ] NEW_LINE DEDENT def union_set ( a , b ) : NEW_LINE INDENT global N , v , g , vis , In , low , parent , rnk , bridges , n , m , timer , diameter NEW_LINE x , y = find_set ( a ) , find_set ( b ) NEW_LINE if x == y : NEW_LINE INDENT return NEW_LINE DEDENT if rnk [ x ] == rnk [ y ] : NEW_LINE INDENT rnk [ x ] += 1 NEW_LINE DEDENT if rnk [ y ] > rnk [ x ] : NEW_LINE INDENT swap ( x , y ) NEW_LINE DEDENT parent [ y ] = x NEW_LINE DEDENT def dfsBridges ( a , par ) : NEW_LINE INDENT global N , v , g , vis , In , low , parent , rnk , bridges , n , m , timer , diameter NEW_LINE vis [ a ] = True NEW_LINE timer += 1 NEW_LINE In [ a ] , low [ a ] = timer , timer NEW_LINE for i in range ( len ( v [ a ] ) ) : NEW_LINE INDENT if v [ a ] [ i ] == par : NEW_LINE continue NEW_LINE if vis [ v [ a ] [ i ] ] : NEW_LINE low [ a ] = min ( low [ a ] , In [ v [ a ] [ i ] ] ) NEW_LINE else : NEW_LINE dfsBridges ( v [ a ] [ i ] , a ) NEW_LINE low [ a ] = min ( low [ a ] , low [ v [ a ] [ i ] ] ) NEW_LINE if In [ a ] < low [ v [ a ] [ i ] ] : NEW_LINE INDENT bridges . append ( [ v [ a ] [ i ] , a ] ) NEW_LINE DEDENT else : NEW_LINE INDENT union_set ( v [ a ] [ i ] , a ) NEW_LINE DEDENT DEDENT DEDENT def dfsDiameter ( a , par ) : NEW_LINE INDENT global N , v , g , vis , In , low , parent , rnk , bridges , n , m , timer , diameter NEW_LINE x , y = 0 , 0 NEW_LINE for i in range ( len ( g [ a ] ) ) : NEW_LINE INDENT if g [ a ] [ i ] == par : NEW_LINE continue NEW_LINE mx = dfsDiameter ( g [ a ] [ i ] , a ) NEW_LINE if mx > x : NEW_LINE y = x NEW_LINE x = mx NEW_LINE elif mx > y : NEW_LINE y = mx NEW_LINE DEDENT diameter = max ( diameter , x + y ) NEW_LINE return x + 1 NEW_LINE DEDENT def findMaxBridges ( ) : NEW_LINE INDENT global N , v , g , vis , In , low , parent , rnk , bridges , n , m , timer , diameter NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE rnk [ i ] = 1 NEW_LINE DEDENT dfsBridges ( 1 , 0 ) ; NEW_LINE if len ( bridges ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT head = - 1 NEW_LINE for i in range ( len ( bridges ) ) : NEW_LINE INDENT a = find_set ( bridges [ i ] [ 0 ] ) NEW_LINE b = find_set ( bridges [ i ] [ 1 ] ) NEW_LINE g [ a ] . append ( b ) NEW_LINE g [ b ] . append ( a ) NEW_LINE head = a NEW_LINE DEDENT diameter = 0 NEW_LINE dfsDiameter ( head , 0 ) NEW_LINE return diameter NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT v . append ( [ ] ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT g . append ( [ ] ) NEW_LINE DEDENT v [ 1 ] . append ( 2 ) NEW_LINE v [ 2 ] . append ( 1 ) NEW_LINE v [ 2 ] . append ( 3 ) NEW_LINE v [ 3 ] . append ( 2 ) NEW_LINE v [ 2 ] . append ( 5 ) NEW_LINE v [ 5 ] . append ( 2 ) NEW_LINE v [ 5 ] . append ( 6 ) NEW_LINE v [ 6 ] . append ( 5 ) NEW_LINE v [ 6 ] . append ( 3 ) NEW_LINE v [ 3 ] . append ( 6 ) NEW_LINE v [ 3 ] . append ( 4 ) NEW_LINE v [ 4 ] . append ( 4 ) NEW_LINE ans = findMaxBridges ( ) NEW_LINE print ( ans ) NEW_LINE |
Program to count leaf nodes in a binary tree | A Binary tree node ; Function to get the count of leaf nodes in binary tree ; create a tree ; get leaf count of the abve tree | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getLeafCount ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . left is None and node . right is None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return getLeafCount ( node . left ) + getLeafCount ( node . right ) NEW_LINE DEDENT DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print " Leaf β count β of β the β tree β is β % d " % ( getLeafCount ( root ) ) NEW_LINE |
Make a palindromic string from given string | Function to find winner of the game ; Array to Maintain frequency of the characters in S initialise freq array with 0 ; Maintain count of all distinct characters ; Finding frequency of each character ; Count unique duplicate characters ; Loop to count the unique duplicate characters ; Condition for Player - 1 to be winner ; Else Player - 2 is always winner ; Driven Code ; Function call | def palindromeWinner ( S ) : NEW_LINE INDENT freq = [ 0 for i in range ( 0 , 26 ) ] NEW_LINE count = 0 NEW_LINE for i in range ( 0 , len ( S ) ) : NEW_LINE INDENT if ( freq [ ord ( S [ i ] ) - 97 ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT freq [ ord ( S [ i ] ) - 97 ] += 1 NEW_LINE DEDENT unique = 0 NEW_LINE duplicate = 0 NEW_LINE for i in range ( 0 , 26 ) : NEW_LINE INDENT if ( freq [ i ] == 1 ) : NEW_LINE INDENT unique += 1 NEW_LINE DEDENT elif ( freq [ i ] >= 2 ) : NEW_LINE INDENT duplicate += 1 NEW_LINE DEDENT DEDENT if ( unique == 1 and ( unique + duplicate ) == count ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 2 NEW_LINE DEDENT S = " abcbc " ; NEW_LINE print ( " Player - " , palindromeWinner ( S ) ) NEW_LINE |
Number of substrings with length divisible by the number of 1 's in it | Python3 program to count number of substring under given condition ; Function return count of such substring ; Selection of adequate x value ; Store where 1 's are located ; If there are no ones , then answer is 0 ; For ease of implementation ; Count storage ; Iterate on all k values less than fixed x ; Keeps a count of 1 's occured during string traversal ; Iterate on string and modify the totCount ; If this character is 1 ; Add to the final sum / count ; Increase totCount at exterior position ; Reduce totCount at index + k * n ; Slightly modified prefix sum storage ; Number of 1 's till i-1 ; Traversing over string considering each position and finding bounds and count using the inequalities ; Calculating bounds for l and r ; If valid then add to answer ; Driver code | import math NEW_LINE def countOfSubstrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE x = int ( math . sqrt ( n ) ) NEW_LINE ones = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT ones . append ( i ) NEW_LINE DEDENT DEDENT if ( len ( ones ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ones . append ( n ) NEW_LINE totCount = [ 0 ] * ( n * x + n ) NEW_LINE sum = 0 NEW_LINE for k in range ( x + 1 ) : NEW_LINE INDENT now = 0 NEW_LINE totCount [ k * n ] += 1 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( s [ j - 1 ] == '1' ) : NEW_LINE INDENT now += 1 NEW_LINE DEDENT index = j - k * now NEW_LINE sum += totCount [ index + k * n ] NEW_LINE totCount [ index + k * n ] += 1 NEW_LINE DEDENT now = 0 NEW_LINE totCount [ k * n ] -= 1 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( s [ j - 1 ] == '1' ) : NEW_LINE INDENT now += 1 NEW_LINE DEDENT index = j - k * now NEW_LINE totCount [ index + k * n ] -= 1 NEW_LINE DEDENT DEDENT prefix_sum = [ - 1 ] * n NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT prefix_sum [ i ] = cnt NEW_LINE if ( s [ i ] == '1' ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT for k in range ( n ) : NEW_LINE INDENT j = 1 NEW_LINE while ( j <= ( n // x ) and prefix_sum [ k ] + j <= cnt ) : NEW_LINE INDENT l = ( ones [ prefix_sum [ k ] + j - 1 ] - k + 1 ) NEW_LINE r = ones [ prefix_sum [ k ] + j ] - k NEW_LINE l = max ( l , j * ( x + 1 ) ) NEW_LINE if ( l <= r ) : NEW_LINE INDENT sum += r // j - ( l - 1 ) // j NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "1111100000" NEW_LINE print ( countOfSubstrings ( S ) ) NEW_LINE DEDENT |
Find the largest number smaller than integer N with maximum number of set bits | Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code | def largestNum ( n ) : NEW_LINE INDENT num = 0 ; NEW_LINE max_setBits = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT setBits = bin ( i ) . count ( '1' ) ; NEW_LINE if ( setBits >= max_setBits ) : NEW_LINE INDENT num = i ; NEW_LINE max_setBits = setBits ; NEW_LINE DEDENT DEDENT return num ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 345 ; NEW_LINE print ( largestNum ( N ) ) ; NEW_LINE DEDENT |
Iterative program to count leaf nodes in a Binary Tree | Python3 program to count leaf nodes in a Binary Tree ; Helper function that allocates a new Node with the given data and None left and right pointers . ; Function to get the count of leaf Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do level order traversal starting from root Initialize count of leaves ; Driver Code ; 1 / \ 2 3 / \ 4 5 Let us create Binary Tree shown in above example ; get leaf count of the above created tree | from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def getLeafCount ( node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = Queue ( ) NEW_LINE count = 0 NEW_LINE q . put ( node ) NEW_LINE while ( not q . empty ( ) ) : NEW_LINE INDENT temp = q . queue [ 0 ] NEW_LINE q . get ( ) NEW_LINE if ( temp . left != None ) : NEW_LINE INDENT q . put ( temp . left ) NEW_LINE DEDENT if ( temp . right != None ) : NEW_LINE INDENT q . put ( temp . right ) NEW_LINE DEDENT if ( temp . left == None and temp . right == None ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( getLeafCount ( root ) ) NEW_LINE DEDENT |
Find the Kth smallest element in the sorted generated array | Function to return the Kth element in B [ ] ; Initialize the count Array ; Reduce N repeatedly to half its value ; Add count to start ; Subtract same count after end index ; Store each element of Array [ ] with their count ; Sort the elements wrt value ; If Kth element is in range of element [ i ] return element [ i ] ; If K is out of bound ; Driver code | def solve ( Array , N , K ) : NEW_LINE INDENT count_Arr = [ 0 ] * ( N + 2 ) ; NEW_LINE factor = 1 ; NEW_LINE size = N ; NEW_LINE while ( size ) : NEW_LINE INDENT start = 1 ; NEW_LINE end = size ; NEW_LINE count_Arr [ 1 ] += factor * N ; NEW_LINE count_Arr [ end + 1 ] -= factor * N ; NEW_LINE factor += 1 ; NEW_LINE size //= 2 ; NEW_LINE DEDENT for i in range ( 2 , N + 1 ) : NEW_LINE INDENT count_Arr [ i ] += count_Arr [ i - 1 ] ; NEW_LINE DEDENT element = [ ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT element . append ( ( Array [ i ] , count_Arr [ i + 1 ] ) ) ; NEW_LINE DEDENT element . sort ( ) ; NEW_LINE start = 1 ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT end = start + element [ i ] [ 1 ] - 1 ; NEW_LINE if ( K >= start and K <= end ) : NEW_LINE INDENT return element [ i ] [ 0 ] ; NEW_LINE DEDENT start += element [ i ] [ 1 ] ; NEW_LINE DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 2 , 4 , 5 , 1 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 13 ; NEW_LINE print ( solve ( arr , N , K ) ) ; NEW_LINE DEDENT |
Maximum number that can be display on Seven Segment Display using N segments | Function to print maximum number that can be formed using N segments ; If n is odd ; use 3 three segment to print 7 ; remaining to print 1 ; If n is even ; print n / 2 1 s . ; Driver 's Code | def printMaxNumber ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT print ( "7" , end = " " ) ; NEW_LINE for i in range ( int ( ( n - 3 ) / 2 ) ) : NEW_LINE INDENT print ( "1" , end = " " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( n / 2 ) : NEW_LINE INDENT print ( "1" , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT n = 5 ; NEW_LINE printMaxNumber ( n ) ; NEW_LINE |
Find the sum of digits of a number at even and odd places | Function to find the sum of the odd and even positioned digits in a number ; To store the respective sums ; Converting integer to string ; Traversing the string ; Driver code | def getSum ( n ) : NEW_LINE INDENT sumOdd = 0 NEW_LINE sumEven = 0 NEW_LINE num = str ( n ) NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT sumOdd = sumOdd + int ( num [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT sumEven = sumEven + int ( num [ i ] ) NEW_LINE DEDENT DEDENT print ( " Sum β odd β = β " , sumOdd ) NEW_LINE print ( " Sum β even β = β " , sumEven ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 457892 NEW_LINE getSum ( n ) NEW_LINE DEDENT |
Iterative program to count leaf nodes in a Binary Tree | Node class ; Program to count leaves ; If the node itself is " None " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " None " ; Now we count the leaves in the left and right subtrees and return the sum ; Driver Code ; get leaf count of the above created tree | class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def countLeaves ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . left == None and node . right == None ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return countLeaves ( node . left ) + countLeaves ( node . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE print ( countLeaves ( root ) ) NEW_LINE DEDENT |
Partition an array such into maximum increasing segments | Python 3 program to divide into maximum number of segments ; Returns the maximum number of sorted subarrays in a valid partition ; Find minimum value from right for every index ; Finding the shortest prefix such that all the elements in the prefix are less than or equal to the elements in the rest of the array . ; if current max is less than the right prefix min , we increase number of partitions . ; Driver code ; Find minimum value from right for every index | import sys NEW_LINE def sorted_partitions ( arr , n ) : NEW_LINE INDENT right_min = [ 0 ] * ( n + 1 ) NEW_LINE right_min [ n ] = sys . maxsize NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT right_min [ i ] = min ( right_min [ i + 1 ] , arr [ i ] ) NEW_LINE DEDENT partitions = 0 NEW_LINE current_max = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT current_max = max ( current_max , arr [ i ] ) NEW_LINE if ( current_max <= right_min [ i + 1 ] ) : NEW_LINE INDENT partitions += 1 NEW_LINE DEDENT DEDENT return partitions NEW_LINE DEDENT arr = [ 3 , 1 , 2 , 4 , 100 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE ans = sorted_partitions ( arr , n ) NEW_LINE print ( ans ) NEW_LINE |
Minimize Cost with Replacement with other allowed | Function returns the minimum cost of the array ; Driver Code | def getMinCost ( arr , n ) : NEW_LINE INDENT min_ele = min ( arr ) NEW_LINE return min_ele * ( n - 1 ) NEW_LINE DEDENT arr = [ 4 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getMinCost ( arr , n ) ) NEW_LINE |
Minimum swaps required to make a binary string alternating | function to count minimum swaps required to make binary String alternating ; stores total number of ones ; stores total number of zeroes ; checking impossible condition ; odd length string ; number of even positions ; stores number of zeroes and ones at even positions ; even length string ; stores number of ones at odd and even position respectively ; Driver code | def countMinSwaps ( s ) : NEW_LINE INDENT N = len ( s ) NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT DEDENT if ( one > zero + 1 or zero > one + 1 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( N % 2 ) : NEW_LINE INDENT num = ( N + 1 ) / 2 NEW_LINE one_even = 0 NEW_LINE zero_even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT one_even += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero_even += 1 NEW_LINE DEDENT DEDENT DEDENT if ( one > zero ) : NEW_LINE INDENT return num - one_even NEW_LINE DEDENT else : NEW_LINE INDENT return num - zero_even NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT one_odd = 0 NEW_LINE one_even = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT if ( i % 2 ) : NEW_LINE INDENT one_odd += 1 NEW_LINE DEDENT else : NEW_LINE INDENT one_even += 1 NEW_LINE DEDENT DEDENT DEDENT return min ( N // 2 - one_odd , N // 2 - one_even ) NEW_LINE DEDENT DEDENT s = "111000" NEW_LINE print ( countMinSwaps ( s ) ) NEW_LINE |
Check if it is possible to return to the starting position after moving in the given directions | Main method ; n = 0 Count of North s = 0 Count of South e = 0 Count of East w = 0 Count of West | st = " NNNWEWESSS " NEW_LINE length = len ( st ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( st [ i ] == " N " ) : NEW_LINE INDENT n += 1 NEW_LINE DEDENT if ( st [ i ] == " S " ) : NEW_LINE INDENT s += 1 NEW_LINE DEDENT if ( st [ i ] == " W " ) : NEW_LINE INDENT w += 1 NEW_LINE DEDENT if ( st [ i ] == " E " ) : NEW_LINE INDENT e += 1 NEW_LINE DEDENT DEDENT if ( n == s and w == e ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Minimum cost to make array size 1 by removing larger of pairs | function to calculate the minimum cost ; Minimum cost is n - 1 multiplied with minimum element . ; driver code | def cost ( a , n ) : NEW_LINE INDENT return ( ( n - 1 ) * min ( a ) ) NEW_LINE DEDENT a = [ 4 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( cost ( a , n ) ) NEW_LINE |
Count Non | class that allocates a new node with the given data and None left and right pointers . ; Computes the number of non - leaf nodes in a tree . ; Base cases . ; If root is Not None and its one of its child is also not None ; Driver Code | class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def countNonleaf ( root ) : NEW_LINE INDENT if ( root == None or ( root . left == None and root . right == None ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( 1 + countNonleaf ( root . left ) + countNonleaf ( root . right ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE print ( countNonleaf ( root ) ) NEW_LINE DEDENT |
Minimum cost for acquiring all coins with k extra coins allowed with every coin | Python3 program to acquire all n coins ; function to calculate min cost ; sort the coins value ; calculate no . of coins needed ; calculate sum of all selected coins ; Driver code | import math NEW_LINE def minCost ( coin , n , k ) : NEW_LINE INDENT coin . sort ( ) NEW_LINE coins_needed = math . ceil ( 1.0 * n // ( k + 1 ) ) ; NEW_LINE ans = 0 NEW_LINE for i in range ( coins_needed - 1 + 1 ) : NEW_LINE INDENT ans += coin [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT coin = [ 8 , 5 , 3 , 10 , 2 , 1 , 15 , 25 ] NEW_LINE n = len ( coin ) NEW_LINE k = 3 NEW_LINE print ( minCost ( coin , n , k ) ) NEW_LINE |
Program for First Fit algorithm in Memory Management | Function to allocate memory to blocks as per First fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; Reduce available memory in this block . ; Driver code | def firstFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT allocation [ i ] = j NEW_LINE blockSize [ j ] -= processSize [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT print ( " β Process β No . β Process β Size β Block β no . " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " β " , i + 1 , " β " , processSize [ i ] , " β " , end = " β " ) NEW_LINE if allocation [ i ] != - 1 : NEW_LINE INDENT print ( allocation [ i ] + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Not β Allocated " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT blockSize = [ 100 , 500 , 200 , 300 , 600 ] NEW_LINE processSize = [ 212 , 417 , 112 , 426 ] NEW_LINE m = len ( blockSize ) NEW_LINE n = len ( processSize ) NEW_LINE firstFit ( blockSize , m , processSize , n ) NEW_LINE DEDENT |
Greedy Algorithm to find Minimum number of Coins | Python3 program to find minimum number of denominations ; All denominations of Indian Currency ; Initialize Result ; Traverse through all denomination ; Find denominations ; Print result ; Driver Code | def findMin ( V ) : NEW_LINE INDENT deno = [ 1 , 2 , 5 , 10 , 20 , 50 , 100 , 500 , 1000 ] NEW_LINE n = len ( deno ) NEW_LINE ans = [ ] NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT while ( V >= deno [ i ] ) : NEW_LINE INDENT V -= deno [ i ] NEW_LINE ans . append ( deno [ i ] ) NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT for i in range ( len ( ans ) ) : NEW_LINE INDENT print ( ans [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 93 NEW_LINE print ( " Following β is β minimal β number " , " of β change β for " , n , " : β " , end = " " ) NEW_LINE findMin ( n ) NEW_LINE DEDENT |
Minimize count of array elements to be removed such that at least K elements are equal to their index values | Function to minimize the removals of array elements such that atleast K elements are equal to their indices ; Store the array as 1 - based indexing Copy of first array ; Make a dp - table of ( N * N ) size ; Delete the current element ; Take the current element ; Check for the minimum removals ; Driver Code | def MinimumRemovals ( a , N , K ) : NEW_LINE INDENT b = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT b [ i + 1 ] = a [ i ] NEW_LINE DEDENT dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT dp [ i + 1 ] [ j ] = max ( dp [ i + 1 ] [ j ] , dp [ i ] [ j ] ) NEW_LINE dp [ i + 1 ] [ j + 1 ] = max ( dp [ i + 1 ] [ j + 1 ] , dp [ i ] [ j ] + ( 1 if ( b [ i + 1 ] == j + 1 ) else 0 ) ) NEW_LINE DEDENT DEDENT j = N NEW_LINE while ( j >= 0 ) : NEW_LINE INDENT if ( dp [ N ] [ j ] >= K ) : NEW_LINE INDENT return ( N - j ) NEW_LINE DEDENT j -= 1 NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 5 , 1 , 3 , 2 , 3 ] NEW_LINE K = 2 NEW_LINE N = len ( arr ) NEW_LINE print ( MinimumRemovals ( arr , N , K ) ) NEW_LINE DEDENT |
Count of Arrays of size N having absolute difference between adjacent elements at most 1 | Function to find the count of possible arrays such that the absolute difference between any adjacent elements is atmost 1 ; Stores the dp states where dp [ i ] [ j ] represents count of arrays of length i + 1 having their last element as j ; Case where 1 st array element is missing ; All integers in range [ 1 , M ] are reachable ; Only reachable integer is arr [ 0 ] ; Iterate through all values of i ; If arr [ i ] is not missing ; Only valid value of j is arr [ i ] ; If arr [ i ] is missing ; Iterate through all possible values of j in range [ 1 , M ] ; Stores the count of valid arrays ; Calculate the total count of valid arrays ; Return answer ; Driver Code ; Function Call | def countArray ( arr , N , M ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( M + 2 ) ] for j in range ( N ) ] NEW_LINE if ( arr [ 0 ] == - 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ 0 ] [ arr [ 0 ] ] = 1 NEW_LINE DEDENT for i in range ( 1 , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] != - 1 ) : NEW_LINE INDENT j = arr [ i ] NEW_LINE dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ] NEW_LINE DEDENT if ( arr [ i ] == - 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT dp [ i ] [ j ] += dp [ i - 1 ] [ j - 1 ] + dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j + 1 ] NEW_LINE DEDENT DEDENT DEDENT arrCount = 0 NEW_LINE for j in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT arrCount += dp [ N - 1 ] [ j ] NEW_LINE DEDENT return arrCount NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , - 1 , 2 , 1 , - 1 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE M = 10 NEW_LINE print ( countArray ( arr , N , M ) ) NEW_LINE DEDENT |
Subsets and Splits