text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Minimum Decrements on Subarrays required to reduce all Array elements to zero | Function to count the minimum number of subarrays that are required to be decremented by 1 ; Base case ; Initializing ans to first element ; For A [ i ] > A [ i - 1 ] , operation ( A [ i ] - A [ i - 1 ] ) is required ; Return the count ; Driver Code | def min_operations ( A ) : NEW_LINE INDENT if len ( A ) == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = A [ 0 ] NEW_LINE for i in range ( 1 , len ( A ) ) : NEW_LINE INDENT if A [ i ] > A [ i - 1 ] : NEW_LINE INDENT ans += A [ i ] - A [ i - 1 ] NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 1 , 2 , 3 , 2 , 1 ] NEW_LINE print ( min_operations ( A ) ) NEW_LINE |
Difference between highest and least frequencies in an array | Python code to find the difference between highest and least frequencies ; Put all elements in a hash map ; Find counts of maximum and minimum frequent elements ; Driver code | from collections import defaultdict NEW_LINE def findDiff ( arr , n ) : NEW_LINE INDENT mp = defaultdict ( lambda : 0 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT max_count = 0 ; min_count = n NEW_LINE for key , values in mp . items ( ) : NEW_LINE INDENT max_count = max ( max_count , values ) NEW_LINE min_count = min ( min_count , values ) NEW_LINE DEDENT return max_count - min_count NEW_LINE DEDENT arr = [ 7 , 8 , 4 , 5 , 4 , 1 , 1 , 7 , 7 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findDiff ( arr , n ) ) NEW_LINE |
Iterative function to check if two trees are identical | Iterative Python3 program to check if two trees are identical ; Utility function to create a new tree node ; Iterative method to find height of Binary Tree ; Return true if both trees are empty ; Return false if one is empty and other is not ; Create an empty queues for simultaneous traversals ; Enqueue Roots of trees in respective queues ; Get front nodes and compare them ; Remove front nodes from queues ; Enqueue left children of both nodes ; If one left child is empty and other is not ; Right child code ( Similar to left child code ) ; Driver Code | 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 areIdentical ( root1 , root2 ) : NEW_LINE INDENT if ( root1 and root2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root1 or root2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT q1 = Queue ( ) NEW_LINE q2 = Queue ( ) NEW_LINE q1 . put ( root1 ) NEW_LINE q2 . put ( root2 ) NEW_LINE while ( not q1 . empty ( ) and not q2 . empty ( ) ) : NEW_LINE INDENT n1 = q1 . queue [ 0 ] NEW_LINE n2 = q2 . queue [ 0 ] NEW_LINE if ( n1 . data != n2 . data ) : NEW_LINE INDENT return False NEW_LINE DEDENT q1 . get ( ) NEW_LINE q2 . get ( ) NEW_LINE if ( n1 . left and n2 . left ) : NEW_LINE INDENT q1 . put ( n1 . left ) NEW_LINE q2 . put ( n2 . left ) NEW_LINE DEDENT elif ( n1 . left or n2 . left ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( n1 . right and n2 . right ) : NEW_LINE INDENT q1 . put ( n1 . right ) NEW_LINE q2 . put ( n2 . right ) NEW_LINE DEDENT elif ( n1 . right or n2 . right ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root1 = newNode ( 1 ) NEW_LINE root1 . left = newNode ( 2 ) NEW_LINE root1 . right = newNode ( 3 ) NEW_LINE root1 . left . left = newNode ( 4 ) NEW_LINE root1 . left . right = newNode ( 5 ) NEW_LINE root2 = newNode ( 1 ) NEW_LINE root2 . left = newNode ( 2 ) NEW_LINE root2 . right = newNode ( 3 ) NEW_LINE root2 . left . left = newNode ( 4 ) NEW_LINE root2 . left . right = newNode ( 5 ) NEW_LINE if areIdentical ( root1 , root2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
Queries to check if vertices X and Y are in the same Connected Component of an Undirected Graph | Maximum number of nodes or vertices that can be present in the graph ; Store the parent of each vertex ; Stores the size of each set ; Function to initialize the parent of each vertices ; Function to find the representative of the set which contain element v ; Path compression technique to optimize the time complexity ; Function to merge two different set into a single set by finding the representative of each set and merge the smallest set with the larger one ; Finding the set representative of each element ; Check if they have different set repersentative ; Compare the set sizes ; Assign parent of smaller set to the larger one ; Add the size of smaller set to the larger one ; Function to check the vertices are on the same set or not ; Check if they have same set representative or not ; Driver code ; Connected vertices and taking them into single set ; Number of queries ; Function call | MAX_NODES = 100005 NEW_LINE parent = [ 0 for i in range ( MAX_NODES ) ] ; NEW_LINE size_set = [ 0 for i in range ( MAX_NODES ) ] ; NEW_LINE def make_set ( v ) : NEW_LINE INDENT parent [ v ] = v ; NEW_LINE size_set [ v ] = 1 ; NEW_LINE DEDENT def find_set ( v ) : NEW_LINE INDENT if ( v == parent [ v ] ) : NEW_LINE INDENT return v ; NEW_LINE DEDENT parent [ v ] = find_set ( parent [ v ] ) ; NEW_LINE return parent [ v ] NEW_LINE DEDENT def union_set ( a , b ) : NEW_LINE INDENT a = find_set ( a ) ; NEW_LINE b = find_set ( b ) ; NEW_LINE if ( a != b ) : NEW_LINE INDENT if ( size_set [ a ] < size_set [ b ] ) : NEW_LINE INDENT swap ( a , b ) ; NEW_LINE DEDENT parent [ b ] = a ; NEW_LINE size_set [ a ] += size_set [ b ] ; NEW_LINE DEDENT DEDENT def check ( a , b ) : NEW_LINE INDENT a = find_set ( a ) ; NEW_LINE b = find_set ( b ) ; NEW_LINE if a == b : NEW_LINE INDENT return ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT return ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 5 NEW_LINE m = 3 ; NEW_LINE make_set ( 1 ) ; NEW_LINE make_set ( 2 ) ; NEW_LINE make_set ( 3 ) ; NEW_LINE make_set ( 4 ) ; NEW_LINE make_set ( 5 ) ; NEW_LINE union_set ( 1 , 3 ) ; NEW_LINE union_set ( 3 , 4 ) ; NEW_LINE union_set ( 3 , 5 ) ; NEW_LINE q = 3 ; NEW_LINE print ( check ( 1 , 5 ) ) NEW_LINE print ( check ( 3 , 2 ) ) NEW_LINE print ( check ( 5 , 2 ) ) NEW_LINE DEDENT |
Count of N | Function to calculate the total count of N - digit numbers such that the sum of digits at even positions and odd positions are divisible by A and B respectively ; For single digit numbers ; Largest possible number ; Count of possible odd digits ; Count of possible even digits ; Calculate total count of sequences of length even_count with sum divisible by A where first digit can be zero ; Calculate total count of sequences of length odd_count with sum divisible by B where cannot be zero ; Return their product as answer ; Driver Code | def count ( N , A , B ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 9 // B + 1 NEW_LINE DEDENT max_sum = 9 * N NEW_LINE odd_count = N // 2 + N % 2 NEW_LINE even_count = N - odd_count NEW_LINE dp = [ [ 0 for x in range ( max_sum + 1 ) ] for y in range ( even_count ) ] NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT dp [ 0 ] [ i % A ] += 1 NEW_LINE DEDENT for i in range ( 1 , even_count ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT for k in range ( max_sum + 1 ) : NEW_LINE INDENT if ( dp [ i - 1 ] [ k ] > 0 ) : NEW_LINE INDENT dp [ i ] [ ( j + k ) % A ] += dp [ i - 1 ] [ k ] NEW_LINE DEDENT DEDENT DEDENT DEDENT dp1 = [ [ 0 for x in range ( max_sum ) ] for y in range ( odd_count ) ] NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT dp1 [ 0 ] [ i % B ] += 1 NEW_LINE DEDENT for i in range ( 1 , odd_count ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT for k in range ( max_sum + 1 ) : NEW_LINE INDENT if ( dp1 [ i - 1 ] [ k ] > 0 ) : NEW_LINE INDENT dp1 [ i ] [ ( j + k ) % B ] += dp1 [ i - 1 ] [ k ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return dp [ even_count - 1 ] [ 0 ] * dp1 [ odd_count - 1 ] [ 0 ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 2 NEW_LINE A = 2 NEW_LINE B = 5 NEW_LINE print ( count ( N , A , B ) ) NEW_LINE DEDENT |
Maximum possible difference of two subsets of an array | Python3 find maximum difference of subset sum ; function for maximum subset diff ; if frequency of any element is two make both equal to zero ; Driver Code | import math NEW_LINE def maxDiff ( arr , n ) : NEW_LINE INDENT SubsetSum_1 = 0 NEW_LINE SubsetSum_2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT isSingleOccurance = True NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT isSingleOccurance = False NEW_LINE arr [ i ] = arr [ j ] = 0 NEW_LINE break NEW_LINE DEDENT DEDENT if ( isSingleOccurance == True ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT SubsetSum_1 += arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT SubsetSum_2 += arr [ i ] NEW_LINE DEDENT DEDENT DEDENT return abs ( SubsetSum_1 - SubsetSum_2 ) NEW_LINE DEDENT arr = [ 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β Difference β = β { } " . format ( maxDiff ( arr , n ) ) ) NEW_LINE |
Count of all possible Paths in a Tree such that Node X does not appear before Node Y | Maximum number of nodes ; Vector to store the tree ; Function to perform DFS Traversal ; Mark the node as visited ; Initialize the subtree size of each node as 1 ; If the node is same as A ; Mark check_subtree [ node ] as true ; Otherwise ; Iterate over the adjacent nodes ; If the adjacent node is not visited ; Update the size of the subtree of current node ; Check if the subtree of current node contains node A ; Return size of subtree of node ; Function to add edges to the tree ; Function to calculate the number of possible paths ; Stores the size of subtree of each node ; Stores which nodes are visited ; Stores if the subtree of a node contains node A ; DFS Call ; Stores the difference between total number of nodes and subtree size of an immediate child of Y lies between the path from A to B ; Iterate over the adjacent nodes B ; If the node is in the path from A to B ; Calculate the difference ; Return the final answer ; Driver Code ; Insert Edges | NN = int ( 3e5 ) NEW_LINE G = [ ] NEW_LINE for i in range ( NN + 1 ) : NEW_LINE INDENT G . append ( [ ] ) NEW_LINE DEDENT def dfs ( node , A , subtree_size , visited , check_subtree ) : NEW_LINE INDENT visited [ node ] = True NEW_LINE subtree_size [ node ] = 1 NEW_LINE if ( node == A ) : NEW_LINE INDENT check_subtree [ node ] = True NEW_LINE DEDENT else : NEW_LINE INDENT check_subtree [ node ] = False NEW_LINE DEDENT for v in G [ node ] : NEW_LINE INDENT if ( not visited [ v ] ) : NEW_LINE INDENT subtree_size [ node ] += dfs ( v , A , subtree_size , visited , check_subtree ) NEW_LINE check_subtree [ node ] = ( check_subtree [ node ] check_subtree [ v ] ) NEW_LINE DEDENT DEDENT return subtree_size [ node ] NEW_LINE DEDENT def addedge ( node1 , node2 ) : NEW_LINE INDENT G [ node1 ] += [ node2 ] NEW_LINE G [ node2 ] += [ node1 ] NEW_LINE DEDENT def numberOfPairs ( N , B , A ) : NEW_LINE INDENT subtree_size = [ 0 ] * ( N + 1 ) NEW_LINE visited = [ 0 ] * ( N + 1 ) NEW_LINE check_subtree = [ 0 ] * ( N + 1 ) NEW_LINE dfs ( B , A , subtree_size , visited , check_subtree ) NEW_LINE difference = 0 NEW_LINE for v in G [ B ] : NEW_LINE INDENT if ( check_subtree [ v ] ) : NEW_LINE INDENT difference = N - subtree_size [ v ] NEW_LINE break NEW_LINE DEDENT DEDENT return ( ( N * ( N - 1 ) ) - difference * ( subtree_size [ A ] ) ) NEW_LINE DEDENT N = 9 NEW_LINE X = 5 NEW_LINE Y = 3 NEW_LINE addedge ( 0 , 2 ) NEW_LINE addedge ( 1 , 2 ) NEW_LINE addedge ( 2 , 3 ) NEW_LINE addedge ( 3 , 4 ) NEW_LINE addedge ( 4 , 6 ) NEW_LINE addedge ( 4 , 5 ) NEW_LINE addedge ( 5 , 7 ) NEW_LINE addedge ( 5 , 8 ) NEW_LINE print ( numberOfPairs ( N , Y , X ) ) NEW_LINE |
Largest possible value of M not exceeding N having equal Bitwise OR and XOR between them | Python3 program to implement the above approach ; Function to find required number M ; Initialising m ; Finding the index of the most significant bit of N ; Calculating required number ; Driver Code | from math import log2 NEW_LINE def equalXORandOR ( n ) : NEW_LINE INDENT m = 0 NEW_LINE MSB = int ( log2 ( n ) ) NEW_LINE for i in range ( MSB + 1 ) : NEW_LINE INDENT if ( not ( n & ( 1 << i ) ) ) : NEW_LINE INDENT m += ( 1 << i ) NEW_LINE DEDENT DEDENT return m NEW_LINE DEDENT n = 14 NEW_LINE print ( equalXORandOR ( n ) ) NEW_LINE |
Maximum possible difference of two subsets of an array | function for maximum subset diff ; sort the array ; calculate the result ; check for last element ; return result ; Driver Code | def maxDiff ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) != abs ( arr [ i + 1 ] ) ) : NEW_LINE INDENT result += abs ( arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT pass NEW_LINE DEDENT DEDENT if ( arr [ n - 2 ] != arr [ n - 1 ] ) : NEW_LINE INDENT result += abs ( arr [ n - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β Difference β = β " , maxDiff ( arr , n ) ) NEW_LINE DEDENT |
Count of Palindromic Strings possible by swapping of a pair of Characters | Function to return the count of possible palindromic strings ; Stores the frequencies of each character ; Stores the length of the string ; Increase the number of swaps , the current character make with its previous occurrences ; Increase frequency ; Driver Code | def findNewString ( s ) : NEW_LINE INDENT ans = 0 NEW_LINE freq = [ 0 ] * 26 NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] NEW_LINE freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT s = " aaabaaa " NEW_LINE print ( findNewString ( s ) ) NEW_LINE |
Maximum possible difference of two subsets of an array | function for maximum subset diff ; construct hash for positive elements ; calculate subset sum for positive elements ; construct hash for negative elements ; calculate subset sum for negative elements ; Driver Code | def maxDiff ( arr , n ) : NEW_LINE INDENT hashPositive = dict ( ) NEW_LINE hashNegative = dict ( ) NEW_LINE SubsetSum_1 , SubsetSum_2 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 ) : NEW_LINE INDENT hashPositive [ arr [ i ] ] = hashPositive . get ( arr [ i ] , 0 ) + 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > 0 and arr [ i ] in hashPositive . keys ( ) and hashPositive [ arr [ i ] ] == 1 ) : NEW_LINE INDENT SubsetSum_1 += arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT hashNegative [ abs ( arr [ i ] ) ] = hashNegative . get ( abs ( arr [ i ] ) , 0 ) + 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 and abs ( arr [ i ] ) in hashNegative . keys ( ) and hashNegative [ abs ( arr [ i ] ) ] == 1 ) : NEW_LINE INDENT SubsetSum_2 += arr [ i ] NEW_LINE DEDENT DEDENT return abs ( SubsetSum_1 - SubsetSum_2 ) NEW_LINE DEDENT arr = [ 4 , 2 , - 3 , 3 , - 2 , - 2 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β Difference β = " , maxDiff ( arr , n ) ) NEW_LINE |
Change the given string according to the given conditions | Function to proofread the spells ; Loop to iterate over the characters of the string ; Push the current character c in the stack ; Check for Rule 1 ; Check for Rule 2 ; To store the resultant string ; Loop to iterate over the characters of stack ; Return the resultant string ; Given string str ; Function Call | def proofreadSpell ( str ) : NEW_LINE INDENT result = [ ] NEW_LINE for c in str : NEW_LINE INDENT result . append ( c ) NEW_LINE n = len ( result ) NEW_LINE if ( n >= 3 ) : NEW_LINE INDENT if ( result [ n - 1 ] == result [ n - 2 ] and result [ n - 1 ] == result [ n - 3 ] ) : NEW_LINE INDENT result . pop ( ) NEW_LINE DEDENT DEDENT n = len ( result ) NEW_LINE if ( n >= 4 ) : NEW_LINE INDENT if ( result [ n - 1 ] == result [ n - 2 ] and result [ n - 3 ] == result [ n - 4 ] ) : NEW_LINE INDENT result . pop ( ) NEW_LINE DEDENT DEDENT DEDENT resultStr = " " NEW_LINE for c in result : NEW_LINE INDENT resultStr += c NEW_LINE DEDENT return resultStr NEW_LINE DEDENT str = " hello " NEW_LINE print ( proofreadSpell ( str ) ) NEW_LINE |
Smallest subarray with k distinct numbers | Prints the minimum range that contains exactly k distinct numbers . ; Consider every element as starting point . ; Find the smallest window starting with arr [ i ] and containing exactly k distinct elements . ; There are less than k distinct elements now , so no need to continue . ; If there was no window with k distinct elements ( k is greater than total distinct elements ) ; Driver code | def minRange ( arr , n , k ) : NEW_LINE INDENT l = 0 NEW_LINE r = n NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = [ ] NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT s . append ( arr [ j ] ) NEW_LINE if ( len ( s ) == k ) : NEW_LINE INDENT if ( ( j - i ) < ( r - l ) ) : NEW_LINE INDENT r = j NEW_LINE l = i NEW_LINE DEDENT break NEW_LINE DEDENT DEDENT if ( j == n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( l == 0 and r == n ) : NEW_LINE INDENT print ( " Invalid β k " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( l , r ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE minRange ( arr , n , k ) NEW_LINE DEDENT |
Smallest subarray with k distinct numbers | Python3 program to find the minimum range that contains exactly k distinct numbers . ; Prints the minimum range that contains exactly k distinct numbers . ; Initially left and right side is - 1 and - 1 , number of distinct elements are zero and range is n . ; Initialize right side ; increment right side . ; if number of distinct elements less than k . ; if distinct elements are equal to k and length is less than previous length . ; if number of distinct elements less than k , then break . ; if distinct elements equals to k then try to increment left side . ; increment left side . ; it is same as explained in above loop . ; Driver code for above function . | from collections import defaultdict NEW_LINE def minRange ( arr , n , k ) : NEW_LINE INDENT l , r = 0 , n NEW_LINE i = 0 NEW_LINE j = - 1 NEW_LINE hm = defaultdict ( lambda : 0 ) NEW_LINE while i < n : NEW_LINE INDENT while j < n : NEW_LINE INDENT j += 1 NEW_LINE if len ( hm ) < k and j < n : NEW_LINE INDENT hm [ arr [ j ] ] += 1 NEW_LINE DEDENT if len ( hm ) == k and ( ( r - l ) >= ( j - i ) ) : NEW_LINE INDENT l , r = i , j NEW_LINE break NEW_LINE DEDENT DEDENT if len ( hm ) < k : NEW_LINE INDENT break NEW_LINE DEDENT while len ( hm ) == k : NEW_LINE INDENT if hm [ arr [ i ] ] == 1 : NEW_LINE INDENT del ( hm [ arr [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hm [ arr [ i ] ] -= 1 NEW_LINE DEDENT i += 1 NEW_LINE if len ( hm ) == k and ( r - l ) >= ( j - i ) : NEW_LINE INDENT l , r = i , j NEW_LINE DEDENT DEDENT if hm [ arr [ i ] ] == 1 : NEW_LINE INDENT del ( hm [ arr [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT hm [ arr [ i ] ] -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if l == 0 and r == n : NEW_LINE INDENT print ( " Invalid β k " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( l , r ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 1 , 2 , 2 , 3 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE minRange ( arr , n , k ) NEW_LINE DEDENT |
Sum of f ( a [ i ] , a [ j ] ) over all pairs in an array of n integers | Function to calculate the sum ; map to keep a count of occurrences ; Traverse in the list from start to end number of times a [ i ] can be in a pair and to get the difference we subtract pre_sum . ; if the ( a [ i ] - 1 ) is present then subtract that value as f ( a [ i ] , a [ i ] - 1 ) = 0 ; if the ( a [ i ] + 1 ) is present then add that value as f ( a [ i ] , a [ i ] - 1 ) = 0 here we add as a [ i ] - ( a [ i ] - 1 ) < 0 which would have been added as negative sum , so we add to remove this pair from the sum value ; keeping a counter for every element ; Driver Code | def sum ( a , n ) : NEW_LINE INDENT cnt = dict ( ) NEW_LINE ans = 0 NEW_LINE pre_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += ( i * a [ i ] ) - pre_sum NEW_LINE pre_sum += a [ i ] NEW_LINE if ( a [ i ] - 1 ) in cnt : NEW_LINE INDENT ans -= cnt [ a [ i ] - 1 ] NEW_LINE DEDENT if ( a [ i ] + 1 ) in cnt : NEW_LINE INDENT ans += cnt [ a [ i ] + 1 ] NEW_LINE DEDENT if a [ i ] not in cnt : NEW_LINE INDENT cnt [ a [ i ] ] = 0 NEW_LINE DEDENT cnt [ a [ i ] ] += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 2 , 3 , 1 , 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( sum ( a , n ) ) NEW_LINE DEDENT |
Minimum distance between the maximum and minimum element of a given Array | Python3 Program to implement the above approach ; Function to find the minimum distance between the minimum and the maximum element ; Stores the minimum and maximum array element ; Stores the most recently traversed indices of the minimum and the maximum element ; Stores the minimum distance between the minimum and the maximium ; Find the maximum and the minimum element from the given array ; Find the minimum distance ; Check if current element is equal to minimum ; Check if current element is equal to maximum ; If both the minimum and the maximum element has occurred at least once ; Driver Code | import sys NEW_LINE def minDistance ( a , n ) : NEW_LINE INDENT maximum = - 1 NEW_LINE minimum = sys . maxsize NEW_LINE min_index = - 1 NEW_LINE max_index = - 1 NEW_LINE min_dist = n + 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] > maximum ) : NEW_LINE INDENT maximum = a [ i ] NEW_LINE DEDENT if ( a [ i ] < minimum ) : NEW_LINE INDENT minimum = a [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == minimum ) : NEW_LINE INDENT min_index = i NEW_LINE DEDENT if ( a [ i ] == maximum ) : NEW_LINE INDENT max_index = i NEW_LINE DEDENT if ( min_index != - 1 and max_index != - 1 ) : NEW_LINE INDENT min_dist = ( min ( min_dist , abs ( min_index - max_index ) ) ) NEW_LINE DEDENT DEDENT return min_dist NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 3 , 2 , 1 , 2 , 1 , 4 , 5 , 8 , 6 , 7 , 8 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( minDistance ( a , n ) ) NEW_LINE DEDENT |
Kth diagonal from the top left of a given matrix | Function returns required diagonal ; Initialize values to prupper diagonals ; Initialize values to print lower diagonals ; Traverse the diagonals ; Print its contents ; Driver code | def printDiagonal ( K , N , M ) : NEW_LINE INDENT startrow , startcol = 0 , 0 NEW_LINE if K - 1 < N : NEW_LINE INDENT startrow = K - 1 NEW_LINE startcol = 0 NEW_LINE DEDENT else : NEW_LINE INDENT startrow = N - 1 NEW_LINE startcol = K - N NEW_LINE DEDENT while startrow >= 0 and startcol < N : NEW_LINE INDENT print ( M [ startrow ] [ startcol ] , end = " β " ) NEW_LINE startrow -= 1 NEW_LINE startcol += 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , K = 3 , 4 NEW_LINE M = [ [ 4 , 7 , 8 ] , [ 9 , 2 , 3 ] , [ 0 , 4 , 1 ] ] NEW_LINE printDiagonal ( K , N , M ) NEW_LINE DEDENT |
Longest substring that starts with X and ends with Y | Function returns length of longest substring starting with X and ending with Y ; Length of string ; Find the length of the string starting with X from the beginning ; Find the length of the string ending with Y from the end ; Longest substring ; Print the length ; Driver Code ; Given string str ; Starting and Ending characters ; Function Call | def longestSubstring ( str , X , Y ) : NEW_LINE INDENT N = len ( str ) NEW_LINE start = 0 NEW_LINE end = N - 1 NEW_LINE xPos = 0 NEW_LINE yPos = 0 NEW_LINE while ( True ) : NEW_LINE INDENT if ( str [ start ] == X ) : NEW_LINE INDENT xPos = start NEW_LINE break NEW_LINE DEDENT start += 1 NEW_LINE DEDENT while ( True ) : NEW_LINE INDENT if ( str [ end ] == Y ) : NEW_LINE INDENT yPos = end NEW_LINE break NEW_LINE DEDENT end -= 1 NEW_LINE DEDENT length = ( yPos - xPos ) + 1 NEW_LINE print ( length ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " HASFJGHOGAKZZFEGA " NEW_LINE X = ' A ' NEW_LINE Y = ' Z ' NEW_LINE longestSubstring ( str , X , Y ) NEW_LINE DEDENT |
Find parent of given node in a Binary Tree with given postorder traversal | Python implementation to find the parent of the given node ; Function to find the parent of the given node ; Check whether the given node is a root node . if it is then return - 1 because root node has no parent ; Loop till we found the given node ; Find the middle node of the tree because at every level tree parent is divided into two halves ; if the node is found return the parent always the child nodes of every node is node / 2 or ( node - 1 ) ; if the node to be found is greater than the mid search for left subtree else search in right subtree ; Driver code | import math NEW_LINE def findParent ( height , node ) : NEW_LINE INDENT start = 1 NEW_LINE end = pow ( 2 , height ) - 1 NEW_LINE if ( end == node ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT while ( node >= 1 ) : NEW_LINE INDENT end = end - 1 NEW_LINE mid = start + ( end - start ) // 2 NEW_LINE if ( mid == node or end == node ) : NEW_LINE INDENT return ( end + 1 ) NEW_LINE DEDENT elif ( node < mid ) : NEW_LINE INDENT end = mid NEW_LINE DEDENT else : NEW_LINE INDENT start = mid NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT height = 4 NEW_LINE node = 6 NEW_LINE k = findParent ( height , node ) NEW_LINE print ( k ) NEW_LINE DEDENT |
Replace every element with the smallest of the others | Python3 code for the above approach . ; There should be atleast two elements ; If current element is smaller than firstSmallest then update both firstSmallest and secondSmallest ; If arr [ i ] is in between firstSmallest and secondSmallest then update secondSmallest ; Replace every element by smallest of all other elements ; Print the modified array . ; Driver code | def ReplaceElements ( arr , n ) : NEW_LINE INDENT if ( n < 2 ) : NEW_LINE INDENT print ( " Invalid β Input " ) NEW_LINE return NEW_LINE DEDENT firstSmallest = 10 ** 18 NEW_LINE secondSmallest = 10 ** 18 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < firstSmallest ) : NEW_LINE INDENT secondSmallest = firstSmallest NEW_LINE firstSmallest = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < secondSmallest and arr [ i ] != firstSmallest ) : NEW_LINE INDENT secondSmallest = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] != firstSmallest ) : NEW_LINE INDENT arr [ i ] = firstSmallest NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = secondSmallest NEW_LINE DEDENT DEDENT for i in arr : NEW_LINE INDENT print ( i , end = " , β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 1 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE ReplaceElements ( arr , n ) NEW_LINE DEDENT |
Count subarrays with equal number of 1 ' s β and β 0' s | function to count subarrays with equal number of 1 ' s β and β 0' s ; ' um ' implemented as hash table to store frequency of values obtained through cumulative sum ; Traverse original array and compute cumulative sum and increase count by 1 for this sum in ' um ' . Adds ' - 1' when arr [ i ] == 0 ; traverse the hash table um ; If there are more than one prefix subarrays with a particular sum ; add the subarrays starting from 1 st element and have equal number of 1 ' s β and β 0' s ; required count of subarrays ; Driver code to test above | def countSubarrWithEqualZeroAndOne ( arr , n ) : NEW_LINE INDENT um = dict ( ) NEW_LINE curr_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curr_sum += ( - 1 if ( arr [ i ] == 0 ) else arr [ i ] ) NEW_LINE if um . get ( curr_sum ) : NEW_LINE INDENT um [ curr_sum ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT um [ curr_sum ] = 1 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for itr in um : NEW_LINE INDENT if um [ itr ] > 1 : NEW_LINE INDENT count += ( ( um [ itr ] * int ( um [ itr ] - 1 ) ) / 2 ) NEW_LINE DEDENT DEDENT if um . get ( 0 ) : NEW_LINE INDENT count += um [ 0 ] NEW_LINE DEDENT return int ( count ) NEW_LINE DEDENT arr = [ 1 , 0 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Count β = " , countSubarrWithEqualZeroAndOne ( arr , n ) ) NEW_LINE |
Longest subarray having count of 1 s one more than count of 0 s | function to find the length of longest subarray having count of 1 ' s β one β more β than β count β of β 0' s ; unordered_map ' um ' implemented as hash table ; traverse the given array ; consider '0' as '-1 ; when subarray starts form index '0 ; make an entry for ' sum ' if it is not present in 'um ; check if ' sum - 1' is present in ' um ' or not ; update maxLength ; required maximum length ; Driver code | def lenOfLongSubarr ( arr , n ) : NEW_LINE INDENT um = { i : 0 for i in range ( 10 ) } NEW_LINE sum = 0 NEW_LINE maxLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT sum += - 1 NEW_LINE DEDENT else : NEW_LINE INDENT sum += 1 NEW_LINE DEDENT if ( sum == 1 ) : NEW_LINE INDENT maxLen = i + 1 NEW_LINE DEDENT elif ( sum not in um ) : NEW_LINE INDENT um [ sum ] = i NEW_LINE DEDENT if ( ( sum - 1 ) in um ) : NEW_LINE INDENT if ( maxLen < ( i - um [ sum - 1 ] ) ) : NEW_LINE INDENT maxLen = i - um [ sum - 1 ] NEW_LINE DEDENT DEDENT DEDENT return maxLen NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 1 , 1 , 0 , 0 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Length β = " , lenOfLongSubarr ( arr , n ) ) NEW_LINE DEDENT |
Print all triplets in sorted array that form AP | Function to print all triplets in given sorted array that forms AP ; Use hash to find if there is a previous element with difference equal to arr [ j ] - arr [ i ] ; Driver code | def printAllAPTriplets ( arr , n ) : NEW_LINE INDENT s = [ ] ; NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT diff = arr [ j ] - arr [ i ] ; NEW_LINE if ( ( arr [ i ] - diff ) in arr ) : NEW_LINE INDENT print ( " { } β { } β { } " . format ( ( arr [ i ] - diff ) , arr [ i ] , arr [ j ] ) , end = " " ) ; NEW_LINE DEDENT DEDENT DEDENT s . append ( arr [ i ] ) ; NEW_LINE DEDENT arr = [ 2 , 6 , 9 , 12 , 17 , 22 , 31 , 32 , 35 , 42 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE printAllAPTriplets ( arr , n ) ; NEW_LINE |
Print all triplets in sorted array that form AP | Function to print all triplets in given sorted array that forms AP ; Search other two elements of AP with arr [ i ] as middle . ; if a triplet is found ; Since elements are distinct , arr [ k ] and arr [ j ] cannot form any more triplets with arr [ i ] ; If middle element is more move to higher side , else move lower side . ; Driver code | def printAllAPTriplets ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT j = i - 1 NEW_LINE k = i + 1 NEW_LINE while ( j >= 0 and k < n ) : NEW_LINE INDENT if ( arr [ j ] + arr [ k ] == 2 * arr [ i ] ) : NEW_LINE INDENT print ( arr [ j ] , " " , arr [ i ] , " " , arr [ k ] ) NEW_LINE k += 1 NEW_LINE j -= 1 NEW_LINE DEDENT elif ( arr [ j ] + arr [ k ] < 2 * arr [ i ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 2 , 6 , 9 , 12 , 17 , 22 , 31 , 32 , 35 , 42 ] NEW_LINE n = len ( arr ) NEW_LINE printAllAPTriplets ( arr , n ) NEW_LINE |
Check if there is a root to leaf path with given sequence | Class of Node ; Util function ; If root is NULL or reached end of the array ; If current node is leaf ; If current node is equal to arr [ index ] this means that till this level path has been matched and remaining path can be either in left subtree or right subtree . ; Function to check given sequence of root to leaf path exist in tree or not . index represents current element in sequence of rooth to leaf path ; Driver Code ; arr [ ] : sequence of root to leaf path | 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 existPathUtil ( root , arr , n , index ) : NEW_LINE INDENT if not root or index == n : NEW_LINE INDENT return False NEW_LINE DEDENT if not root . left and not root . right : NEW_LINE INDENT if root . val == arr [ index ] and index == n - 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT return ( ( index < n ) and ( root . val == arr [ index ] ) and ( existPathUtil ( root . left , arr , n , index + 1 ) or existPathUtil ( root . right , arr , n , index + 1 ) ) ) NEW_LINE DEDENT def existPath ( root , arr , n , index ) : NEW_LINE INDENT if not root : NEW_LINE INDENT return ( n == 0 ) NEW_LINE DEDENT return existPathUtil ( root , arr , n , 0 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 8 , 6 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE root = Node ( 5 ) NEW_LINE root . left = Node ( 3 ) NEW_LINE root . right = Node ( 8 ) NEW_LINE root . left . left = Node ( 2 ) NEW_LINE root . left . right = Node ( 4 ) NEW_LINE root . left . left . left = Node ( 1 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . left . right = Node ( 7 ) NEW_LINE if existPath ( root , arr , n , 0 ) : NEW_LINE INDENT print ( " Path β Exists " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Path β does β not β Exist " ) NEW_LINE DEDENT DEDENT |
All unique triplets that sum up to a given value | Function to all find unique triplets without using extra space ; Sort the input array ; For handling the cases when no such triplets exits . ; Iterate over the array from start to n - 2. ; Index of the first element in remaining range . ; Index of the last element ; Setting our new target ; Checking if current element is same as previous ; Checking if current element is same as previous ; If we found the triplets then print it and set the flag ; If target is greater then increment the start index ; If target is smaller than decrement the end index ; If no such triplets found ; Driver code ; Function call | def findTriplets ( a , n , sum ) : NEW_LINE INDENT a . sort ( ) NEW_LINE flag = False NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT if ( i == 0 or a [ i ] > a [ i - 1 ] ) : NEW_LINE INDENT start = i + 1 NEW_LINE end = n - 1 NEW_LINE target = sum - a [ i ] NEW_LINE while ( start < end ) : NEW_LINE INDENT if ( start > i + 1 and a [ start ] == a [ start - 1 ] ) : NEW_LINE INDENT start += 1 NEW_LINE continue NEW_LINE DEDENT if ( end < n - 1 and a [ end ] == a [ end + 1 ] ) : NEW_LINE INDENT end -= 1 NEW_LINE continue NEW_LINE DEDENT if ( target == a [ start ] + a [ end ] ) : NEW_LINE INDENT print ( " [ " , a [ i ] , " , " , a [ start ] , " , " , a [ end ] , " ] " , end = " β " ) NEW_LINE flag = True NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT elif ( target > ( a [ start ] + a [ end ] ) ) : NEW_LINE INDENT start += 1 NEW_LINE DEDENT else : NEW_LINE INDENT end -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if ( flag == False ) : NEW_LINE INDENT print ( " No β Such β Triplets β Exist " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 12 , 3 , 6 , 1 , 6 , 9 ] NEW_LINE n = len ( a ) NEW_LINE sum = 24 NEW_LINE findTriplets ( a , n , sum ) NEW_LINE DEDENT |
Find the position of the given row in a 2 | Python implementation of the approach ; Function to find a row in the given matrix using linear search ; Assume that the current row matched with the given array ; If any element of the current row doesn 't match with the corresponding element of the given array ; Set matched to false and break ; ; If matched then return the row number ; No row matched with the given array ; Driver code | m , n = 6 , 4 ; NEW_LINE def linearCheck ( ar , arr ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT matched = True ; NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( ar [ i ] [ j ] != arr [ j ] ) : NEW_LINE INDENT matched = False ; NEW_LINE break ; NEW_LINE DEDENT DEDENT if ( matched ) : NEW_LINE INDENT return i + 1 ; NEW_LINE DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT mat = [ [ 0 , 0 , 1 , 0 ] , [ 10 , 9 , 22 , 23 ] , [ 40 , 40 , 40 , 40 ] , [ 43 , 44 , 55 , 68 ] , [ 81 , 73 , 100 , 132 ] , [ 100 , 75 , 125 , 133 ] ] ; NEW_LINE row = [ 10 , 9 , 22 , 23 ] ; NEW_LINE print ( linearCheck ( mat , row ) ) ; NEW_LINE DEDENT |
Count number of triplets with product equal to given number | Method to count such triplets ; Consider all triplets and count if their product is equal to m ; Driver code | def countTriplets ( arr , n , m ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , n - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] * arr [ j ] * arr [ k ] == m ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 4 , 6 , 2 , 3 , 8 ] NEW_LINE m = 24 NEW_LINE print ( countTriplets ( arr , len ( arr ) , m ) ) NEW_LINE DEDENT |
Count number of triplets with product equal to given number | Function to find the triplet ; Consider all pairs and check for a third number so their product is equal to product ; Check if current pair divides product or not If yes , then search for ( product / li [ i ] * li [ j ] ) ; Check if the third number is present in the map and it is not equal to any other two elements and also check if this triplet is not counted already using their indexes ; Driver code | def countTriplets ( li , product ) : NEW_LINE INDENT flag = 0 NEW_LINE count = 0 NEW_LINE for i in range ( len ( li ) ) : NEW_LINE INDENT if li [ i ] != 0 and product % li [ i ] == 0 : NEW_LINE INDENT for j in range ( i + 1 , len ( li ) ) : NEW_LINE INDENT if li [ j ] != 0 and product % ( li [ j ] * li [ i ] ) == 0 : NEW_LINE INDENT if product // ( li [ j ] * li [ i ] ) in li : NEW_LINE INDENT n = li . index ( product // ( li [ j ] * li [ i ] ) ) NEW_LINE if n > i and n > j : NEW_LINE INDENT flag = 1 NEW_LINE count += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT print ( count ) NEW_LINE DEDENT li = [ 1 , 4 , 6 , 2 , 3 , 8 ] NEW_LINE product = 24 NEW_LINE countTriplets ( li , product ) NEW_LINE |
Count of index pairs with equal elements in an array | Return the number of pairs with equal values . ; for each index i and j ; finding the index with same value but different index . ; Driven Code | def countPairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] == arr [ j ] ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE |
Queries to answer the number of ones and zero to the left of given index | Function to pre - calculate the left [ ] array ; Iterate in the binary array ; Initialize the number of 1 and 0 ; Increase the count ; Driver code ; Queries ; Solve queries | def preCalculate ( binary , n , left ) : NEW_LINE INDENT count1 , count0 = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT left [ i ] [ 0 ] = count1 NEW_LINE left [ i ] [ 1 ] = count0 NEW_LINE if ( binary [ i ] ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT DEDENT DEDENT binary = [ 1 , 1 , 1 , 0 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( binary ) NEW_LINE left = [ [ 0 for i in range ( 2 ) ] for i in range ( n ) ] NEW_LINE preCalculate ( binary , n , left ) NEW_LINE queries = [ 0 , 1 , 2 , 4 ] NEW_LINE q = len ( queries ) NEW_LINE for i in range ( q ) : NEW_LINE INDENT print ( left [ queries [ i ] ] [ 0 ] , " ones " , left [ queries [ i ] ] [ 1 ] , " zeros " ) NEW_LINE DEDENT |
Count of index pairs with equal elements in an array | Python3 program to count of index pairs with equal elements in an array . ; Return the number of pairs with equal values . ; Finding frequency of each number . ; Calculating pairs of each value . ; Driver Code | import math as mt NEW_LINE def countPairs ( arr , n ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for it in mp : NEW_LINE INDENT count = mp [ it ] NEW_LINE ans += ( count * ( count - 1 ) ) // 2 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countPairs ( arr , n ) ) NEW_LINE |
Partition the array into three equal sum segments | This function returns true if the array can be divided into three equal sum segments ; Prefix Sum Array ; Suffix Sum Array ; Stores the total sum of the array ; We can also take pre [ pos2 - 1 ] - pre [ pos1 ] == total_sum / 3 here . ; Driver Code | def equiSumUtil ( arr , pos1 , pos2 ) : NEW_LINE INDENT n = len ( arr ) ; NEW_LINE pre = [ 0 ] * n ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE pre [ i ] = sum ; NEW_LINE DEDENT suf = [ 0 ] * n ; NEW_LINE sum = 0 ; NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += arr [ i ] ; NEW_LINE suf [ i ] = sum ; NEW_LINE DEDENT total_sum = sum ; NEW_LINE i = 0 ; NEW_LINE j = n - 1 ; NEW_LINE while ( i < j - 1 ) : NEW_LINE INDENT if ( pre [ i ] == total_sum // 3 ) : NEW_LINE INDENT pos1 = i ; NEW_LINE DEDENT if ( suf [ j ] == total_sum // 3 ) : NEW_LINE INDENT pos2 = j ; NEW_LINE DEDENT if ( pos1 != - 1 and pos2 != - 1 ) : NEW_LINE INDENT if ( suf [ pos1 + 1 ] - suf [ pos2 ] == total_sum // 3 ) : NEW_LINE INDENT return [ True , pos1 , pos2 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT return [ False , pos1 , pos2 ] ; NEW_LINE DEDENT DEDENT if ( pre [ i ] < suf [ j ] ) : NEW_LINE INDENT i += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 ; NEW_LINE DEDENT DEDENT return [ False , pos1 , pos2 ] ; NEW_LINE DEDENT def equiSum ( arr ) : NEW_LINE INDENT pos1 = - 1 ; NEW_LINE pos2 = - 1 ; NEW_LINE ans = equiSumUtil ( arr , pos1 , pos2 ) ; NEW_LINE pos1 = ans [ 1 ] ; NEW_LINE pos2 = ans [ 2 ] ; NEW_LINE if ( ans [ 0 ] ) : NEW_LINE INDENT print ( " First β Segment β : β " , end = " " ) ; NEW_LINE for i in range ( pos1 + 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE print ( " Second β Segment β : β " , end = " " ) ; NEW_LINE for i in range ( pos1 + 1 , pos2 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE print ( " Third β Segment β : β " , end = " " ) ; NEW_LINE for i in range ( pos2 , len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT print ( " " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT println ( " Array β cannot β be β divided β into " , " three β equal β sum β segments " ) ; NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 6 , 2 , 7 , 1 , 2 , 8 ] ; NEW_LINE equiSum ( arr ) ; NEW_LINE |
Print cousins of a given node in Binary Tree | A utility function to create a new Binary Tree Node ; It returns level of the node if it is present in tree , otherwise returns 0. ; base cases ; If node is present in left subtree ; If node is not present in left subtree ; Prnodes at a given level such that sibling of node is not printed if it exists ; Base cases ; If current node is parent of a node with given level ; Recur for left and right subtrees ; This function prints cousins of a given node ; Get level of given node ; Prnodes of given level . ; Driver Code | class newNode : NEW_LINE INDENT def __init__ ( self , item ) : NEW_LINE INDENT self . data = item NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def getLevel ( root , node , level ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( root == node ) : NEW_LINE INDENT return level NEW_LINE DEDENT downlevel = getLevel ( root . left , node , level + 1 ) NEW_LINE if ( downlevel != 0 ) : NEW_LINE INDENT return downlevel NEW_LINE DEDENT return getLevel ( root . right , node , level + 1 ) NEW_LINE DEDENT def printGivenLevel ( root , node , level ) : NEW_LINE INDENT if ( root == None or level < 2 ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( level == 2 ) : NEW_LINE INDENT if ( root . left == node or root . right == node ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left ) : NEW_LINE INDENT print ( root . left . data , end = " β " ) NEW_LINE DEDENT if ( root . right ) : NEW_LINE INDENT print ( root . right . data , end = " β " ) NEW_LINE DEDENT DEDENT elif ( level > 2 ) : NEW_LINE INDENT printGivenLevel ( root . left , node , level - 1 ) NEW_LINE printGivenLevel ( root . right , node , level - 1 ) NEW_LINE DEDENT DEDENT def printCousins ( root , node ) : NEW_LINE INDENT level = getLevel ( root , node , 1 ) NEW_LINE printGivenLevel ( root , node , level ) 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 root . left . right . right = newNode ( 15 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . left . right = newNode ( 8 ) NEW_LINE printCousins ( root , root . left . right ) NEW_LINE DEDENT |
Leftmost and rightmost indices of the maximum and the minimum element of an array | Function to return the index of the rightmost minimum element from the array ; First element is the minimum in a sorted array ; While the elements are equal to the minimum update rightMin ; Final check whether there are any elements which are equal to the minimum ; Function to return the index of the leftmost maximum element from the array ; Last element is the maximum in a sorted array ; While the elements are equal to the maximum update leftMax ; Final check whether there are any elements which are equal to the maximum ; Driver code ; First element is the leftmost minimum in a sorted array ; Last element is the rightmost maximum in a sorted array | def getRightMin ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE rightMin = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] == min ) : NEW_LINE INDENT rightMin = i NEW_LINE DEDENT i *= 2 NEW_LINE DEDENT i = rightMin + 1 NEW_LINE while ( i < n and arr [ i ] == min ) : NEW_LINE INDENT rightMin = i NEW_LINE i += 1 NEW_LINE DEDENT return rightMin NEW_LINE DEDENT def getLeftMax ( arr , n ) : NEW_LINE INDENT max = arr [ n - 1 ] NEW_LINE leftMax = n - 1 NEW_LINE i = n - 2 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] == max ) : NEW_LINE INDENT leftMax = i NEW_LINE DEDENT i = int ( i / 2 ) NEW_LINE DEDENT i = leftMax - 1 NEW_LINE while ( i >= 0 and arr [ i ] == max ) : NEW_LINE INDENT leftMax = i NEW_LINE i -= 1 NEW_LINE DEDENT return leftMax NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 0 , 0 , 1 , 2 , 5 , 5 , 6 , 8 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum β left β : " , 0 ) NEW_LINE print ( " Minimum β right β : " , getRightMin ( arr , n ) ) NEW_LINE print ( " Maximum β left β : " , getLeftMax ( arr , n ) ) NEW_LINE print ( " Maximum β right β : " , ( n - 1 ) ) NEW_LINE DEDENT |
Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Sort the array ; Check if elements are consecutive or not . If not , update count ; Drivers code | def countNum ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ i + 1 ] and arr [ i ] != arr [ i + 1 ] - 1 ) : NEW_LINE INDENT count += arr [ i + 1 ] - arr [ i ] - 1 ; NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 3 , 5 , 8 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countNum ( arr , n ) ) NEW_LINE |
Find the k smallest numbers after deleting given elements | Python3 program to find the k maximum number from the array after n deletions ; Find k maximum element from arr [ 0. . m - 1 ] after deleting elements from del [ 0. . n - 1 ] ; Hash Map of the numbers to be deleted ; Increment the count of del [ i ] ; Search if the element is present ; Decrement its frequency ; If the frequency becomes 0 , erase it from the map ; Else push it ; Driver code | import math as mt NEW_LINE def findElementsAfterDel ( arr , m , dell , n , k ) : NEW_LINE INDENT mp = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if dell [ i ] in mp . keys ( ) : NEW_LINE INDENT mp [ dell [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ dell [ i ] ] = 1 NEW_LINE DEDENT DEDENT heap = list ( ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT if ( arr [ i ] in mp . keys ( ) ) : NEW_LINE INDENT mp [ arr [ i ] ] -= 1 NEW_LINE if ( mp [ arr [ i ] ] == 0 ) : NEW_LINE INDENT mp . pop ( arr [ i ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT heap . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT heap . sort ( ) NEW_LINE return heap [ : k ] NEW_LINE DEDENT array = [ 5 , 12 , 33 , 4 , 56 , 12 , 20 ] NEW_LINE m = len ( array ) NEW_LINE dell = [ 12 , 56 , 5 ] NEW_LINE n = len ( dell ) NEW_LINE k = 3 NEW_LINE print ( * findElementsAfterDel ( array , m , dell , n , k ) ) NEW_LINE |
Elements to be added so that all elements of a range are present in array | Function to count numbers to be added ; Make a hash of elements and store minimum and maximum element ; Traverse all elements from minimum to maximum and count if it is not in the hash ; Driver code | def countNum ( arr , n ) : NEW_LINE INDENT s = dict ( ) NEW_LINE count , maxm , minm = 0 , - 10 ** 9 , 10 ** 9 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s [ arr [ i ] ] = 1 NEW_LINE if ( arr [ i ] < minm ) : NEW_LINE INDENT minm = arr [ i ] NEW_LINE DEDENT if ( arr [ i ] > maxm ) : NEW_LINE INDENT maxm = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( minm , maxm + 1 ) : NEW_LINE INDENT if i not in s . keys ( ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 3 , 5 , 8 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countNum ( arr , n ) ) NEW_LINE |
Find minimum speed to finish all Jobs | Function to check if the person can do all jobs in H hours with speed K ; Function to return the minimum speed of person to complete all jobs ; If H < N it is not possible to complete all jobs as person can not move from one element to another during current hour ; Max element of array ; Use binary search to find smallest K ; Driver Code ; Print required maxLenwer | def isPossible ( A , n , H , K ) : NEW_LINE INDENT time = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT time += ( A [ i ] - 1 ) // K + 1 NEW_LINE DEDENT return time <= H NEW_LINE DEDENT def minJobSpeed ( A , n , H ) : NEW_LINE INDENT if H < n : NEW_LINE INDENT return - 1 NEW_LINE DEDENT Max = max ( A ) NEW_LINE lo , hi = 1 , Max NEW_LINE while lo < hi : NEW_LINE INDENT mi = lo + ( hi - lo ) // 2 NEW_LINE if not isPossible ( A , n , H , mi ) : NEW_LINE INDENT lo = mi + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hi = mi NEW_LINE DEDENT DEDENT return lo NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 3 , 6 , 7 , 11 ] NEW_LINE H = 8 NEW_LINE n = len ( A ) NEW_LINE print ( minJobSpeed ( A , n , H ) ) NEW_LINE DEDENT |
Number of anomalies in an array | Python3 program to implement the above approach ; Sort the array so that we can apply binary search . ; One by one check every element if it is anomaly or not using binary search . ; If arr [ i ] is not largest element and element just greater than it is within k , then return False . ; If there are more than one occurrences of arr [ i ] , return False . ; If arr [ i ] is not smallest element and just smaller element is not k distance away ; Driver code | def countAnomalies ( a , n , k ) : NEW_LINE INDENT a = sorted ( a ) ; NEW_LINE res = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT u = upper_bound ( a , 0 , n , a [ i ] ) ; NEW_LINE if ( u < n and a [ u ] - a [ i ] <= k ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT s = lower_bound ( a , 0 , n , a [ i ] ) ; NEW_LINE if ( u - s > 1 ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( s > 0 and a [ s - 1 ] - a [ i ] <= k ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT res += 1 ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT def lower_bound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = int ( low + int ( high - low ) / 2 ) ; NEW_LINE if ( element > a [ middle ] ) : NEW_LINE INDENT low = middle + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT high = middle ; NEW_LINE DEDENT DEDENT return low ; NEW_LINE DEDENT def upper_bound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = int ( low + ( high - low ) / 2 ) ; NEW_LINE if ( a [ middle ] > element ) : NEW_LINE INDENT high = middle ; NEW_LINE DEDENT else : NEW_LINE INDENT low = middle + 1 ; NEW_LINE DEDENT DEDENT return low ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 7 , 1 , 8 ] NEW_LINE k = 5 ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( countAnomalies ( arr , n , k ) ) ; NEW_LINE DEDENT |
Subarrays with distinct elements | Returns sum of lengths of all subarrays with distinct elements . ; For maintaining distinct elements . ; Initialize ending point and result ; Fix starting point ; Calculating and adding all possible length subarrays in arr [ i . . j ] ; Remove arr [ i ] as we pick new stating point from next ; Driven Code | def sumoflength ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE j = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT while ( j < n and ( arr [ j ] not in s ) ) : NEW_LINE INDENT s . append ( arr [ j ] ) NEW_LINE j += 1 NEW_LINE DEDENT ans += ( ( j - i ) * ( j - i + 1 ) ) // 2 NEW_LINE s . remove ( arr [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( sumoflength ( arr , n ) ) NEW_LINE DEDENT |
Count subarrays having total distinct elements same as original array | Function to calculate distinct sub - array ; Count distinct elements in whole array ; Reset the container by removing all elements ; Use sliding window concept to find count of subarrays having k distinct elements . ; If window size equals to array distinct element size , then update answer ; Decrease the frequency of previous element for next sliding window ; If frequency is zero then decrease the window size ; Driver code | def countDistictSubarray ( arr , n ) : NEW_LINE INDENT vis = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT vis [ arr [ i ] ] = 1 NEW_LINE DEDENT k = len ( vis ) NEW_LINE vid = dict ( ) NEW_LINE ans = 0 NEW_LINE right = 0 NEW_LINE window = 0 NEW_LINE for left in range ( n ) : NEW_LINE INDENT while ( right < n and window < k ) : NEW_LINE INDENT if arr [ right ] in vid . keys ( ) : NEW_LINE INDENT vid [ arr [ right ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT vid [ arr [ right ] ] = 1 NEW_LINE DEDENT if ( vid [ arr [ right ] ] == 1 ) : NEW_LINE INDENT window += 1 NEW_LINE DEDENT right += 1 NEW_LINE DEDENT if ( window == k ) : NEW_LINE INDENT ans += ( n - right + 1 ) NEW_LINE DEDENT vid [ arr [ left ] ] -= 1 NEW_LINE if ( vid [ arr [ left ] ] == 0 ) : NEW_LINE INDENT window -= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 3 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countDistictSubarray ( arr , n ) ) NEW_LINE |
Count subarrays with same even and odd elements | function that returns the count of subarrays that contain equal number of odd as well as even numbers ; initialize difference and answer with 0 ; initialize these auxiliary arrays with 0 ; since the difference is initially 0 , we have to initialize hash_positive [ 0 ] with 1 ; for loop to iterate through whole array ( zero - based indexing is used ) ; incrementing or decrementing difference based on arr [ i ] being even or odd , check if arr [ i ] is odd ; adding hash value of ' difference ' to our answer as all the previous occurrences of the same difference value will make even - odd subarray ending at index ' i ' . After that , we will increment hash array for that ' difference ' value for its occurrence at index ' i ' . if difference is negative then use hash_negative ; else use hash_positive ; return total number of even - odd subarrays ; Driver code ; Printing total number of even - odd subarrays | def countSubarrays ( arr , n ) : NEW_LINE INDENT difference = 0 NEW_LINE ans = 0 NEW_LINE hash_positive = [ 0 ] * ( n + 1 ) NEW_LINE hash_negative = [ 0 ] * ( n + 1 ) NEW_LINE hash_positive [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] & 1 == 1 ) : NEW_LINE INDENT difference = difference + 1 NEW_LINE DEDENT else : NEW_LINE INDENT difference = difference - 1 NEW_LINE DEDENT if ( difference < 0 ) : NEW_LINE INDENT ans += hash_negative [ - difference ] NEW_LINE hash_negative [ - difference ] = hash_negative [ - difference ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += hash_positive [ difference ] NEW_LINE hash_positive [ difference ] = hash_positive [ difference ] + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 3 , 4 , 6 , 8 , 1 , 10 , 5 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Total β Number β of β Even - Odd β subarrays β are β " + str ( countSubarrays ( arr , n ) ) ) NEW_LINE |
Evaluation of Expression Tree | Class to represent the nodes of syntax tree ; This function receives a node of the syntax tree and recursively evaluate it ; empty tree ; leaf node ; evaluate left tree ; evaluate right tree ; check which operation to apply ; Driver function to test above problem | class node : NEW_LINE INDENT def __init__ ( self , value ) : NEW_LINE INDENT self . left = None NEW_LINE self . data = value NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def evaluateExpressionTree ( 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 int ( root . data ) NEW_LINE DEDENT left_sum = evaluateExpressionTree ( root . left ) NEW_LINE right_sum = evaluateExpressionTree ( root . right ) NEW_LINE if root . data == ' + ' : NEW_LINE INDENT return left_sum + right_sum NEW_LINE DEDENT elif root . data == ' - ' : NEW_LINE INDENT return left_sum - right_sum NEW_LINE DEDENT elif root . data == ' * ' : NEW_LINE INDENT return left_sum * right_sum NEW_LINE DEDENT else : NEW_LINE INDENT return left_sum / right_sum NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = node ( ' + ' ) NEW_LINE root . left = node ( ' * ' ) NEW_LINE root . left . left = node ( '5' ) NEW_LINE root . left . right = node ( '4' ) NEW_LINE root . right = node ( ' - ' ) NEW_LINE root . right . left = node ( '100' ) NEW_LINE root . right . right = node ( '20' ) NEW_LINE print evaluateExpressionTree ( root ) NEW_LINE root = None NEW_LINE root = node ( ' + ' ) NEW_LINE root . left = node ( ' * ' ) NEW_LINE root . left . left = node ( '5' ) NEW_LINE root . left . right = node ( '4' ) NEW_LINE root . right = node ( ' - ' ) NEW_LINE root . right . left = node ( '100' ) NEW_LINE root . right . right = node ( ' / ' ) NEW_LINE root . right . right . left = node ( '20' ) NEW_LINE root . right . right . right = node ( '2' ) NEW_LINE print evaluateExpressionTree ( root ) NEW_LINE DEDENT |
Minimum number of distinct elements after removing m items | Function to find distintc id 's ; Store the occurrence of ids ; Store into the list value as key and vice - versa ; Start removing elements from the beginning ; Remove if current value is less than or equal to mi ; Return the remaining size ; Driver code | def distinctIds ( arr , n , mi ) : NEW_LINE INDENT m = { } NEW_LINE v = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in m : NEW_LINE m [ arr [ i ] ] += 1 NEW_LINE else : NEW_LINE m [ arr [ i ] ] = 1 NEW_LINE DEDENT for i in m : NEW_LINE INDENT v . append ( [ m [ i ] , i ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE size = len ( v ) NEW_LINE for i in range ( size ) : NEW_LINE INDENT if ( v [ i ] [ 0 ] <= mi ) : NEW_LINE mi -= v [ i ] [ 0 ] NEW_LINE count += 1 NEW_LINE else : NEW_LINE return size - count NEW_LINE DEDENT return size - count NEW_LINE DEDENT arr = [ 2 , 3 , 1 , 2 , 3 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE m = 3 NEW_LINE print ( distinctIds ( arr , n , m ) ) NEW_LINE |
Number of Larger Elements on right side in a string | Python3 program to find counts of right greater characters for every character . ; Driver code | def printGreaterCount ( str ) : NEW_LINE INDENT len__ = len ( str ) NEW_LINE right = [ 0 for i in range ( len__ ) ] NEW_LINE for i in range ( len__ ) : NEW_LINE INDENT for j in range ( i + 1 , len__ , 1 ) : NEW_LINE INDENT if ( str [ i ] < str [ j ] ) : NEW_LINE INDENT right [ i ] += 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( len__ ) : NEW_LINE INDENT print ( right [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " abcd " NEW_LINE printGreaterCount ( str ) NEW_LINE DEDENT |
Maximum consecutive numbers present in an array | Python3 program to find largest consecutive numbers present in arr . ; We insert all the array elements into unordered set . ; check each possible sequence from the start then update optimal length ; if current element is the starting element of a sequence ; Then check for next elements in the sequence ; increment the value of array element and repeat search in the set ; Update optimal length if this length is more . To get the length as it is incremented one by one ; Driver code | def findLongestConseqSubseq ( arr , n ) : NEW_LINE INDENT S = set ( ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT S . add ( arr [ i ] ) ; NEW_LINE DEDENT ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if S . __contains__ ( arr [ i ] ) : NEW_LINE INDENT j = arr [ i ] ; NEW_LINE while ( S . __contains__ ( j ) ) : NEW_LINE INDENT j += 1 ; NEW_LINE DEDENT ans = max ( ans , j - arr [ i ] ) ; NEW_LINE DEDENT DEDENT return ans ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 94 , 93 , 1000 , 5 , 92 , 78 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( findLongestConseqSubseq ( arr , n ) ) ; NEW_LINE DEDENT |
N / 3 repeated number in an array with O ( 1 ) space | Python 3 program to find if any element appears more than n / 3. ; take the integers as the maximum value of integer hoping the integer would not be present in the array ; if this element is previously seen , increment count1 . ; if this element is previously seen , increment count2 . ; if current element is different from both the previously seen variables , decrement both the counts . ; Again traverse the array and find the actual counts . ; Driver code | import sys NEW_LINE def appearsNBy3 ( arr , n ) : NEW_LINE INDENT count1 = 0 NEW_LINE count2 = 0 NEW_LINE first = sys . maxsize NEW_LINE second = sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( first == arr [ i ] ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT elif ( second == arr [ i ] ) : NEW_LINE INDENT count2 += 1 NEW_LINE DEDENT elif ( count1 == 0 ) : NEW_LINE INDENT count1 += 1 NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( count2 == 0 ) : NEW_LINE INDENT count2 += 1 NEW_LINE second = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT count1 -= 1 NEW_LINE count2 -= 1 NEW_LINE DEDENT DEDENT count1 = 0 NEW_LINE count2 = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] == first ) : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT elif ( arr [ i ] == second ) : NEW_LINE INDENT count2 += 1 NEW_LINE DEDENT DEDENT if ( count1 > n / 3 ) : NEW_LINE INDENT return first NEW_LINE DEDENT if ( count2 > n / 3 ) : NEW_LINE INDENT return second NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( appearsNBy3 ( arr , n ) ) NEW_LINE |
Count pairs in array whose sum is divisible by 4 | Python3 code to count pairs whose sum is divisible by '4 ; Function to count pairs whose sum is divisible by '4 ; Create a frequency array to count occurrences of all remainders when divided by 4 ; Count occurrences of all remainders ; If both pairs are divisible by '4 ; If both pairs are 2 modulo 4 ; If one of them is equal to 1 modulo 4 and the other is equal to 3 modulo 4 ; Driver code | ' NEW_LINE ' NEW_LINE def count4Divisibiles ( arr , n ) : NEW_LINE INDENT freq = [ 0 , 0 , 0 , 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] % 4 ] += 1 NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT ans = freq [ 0 ] * ( freq [ 0 ] - 1 ) / 2 NEW_LINE ans += freq [ 2 ] * ( freq [ 2 ] - 1 ) / 2 NEW_LINE ans += freq [ 1 ] * freq [ 3 ] NEW_LINE return int ( ans ) NEW_LINE DEDENT arr = [ 2 , 2 , 1 , 7 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( count4Divisibiles ( arr , n ) ) NEW_LINE |
Find Sum of all unique sub | function for finding grandSum ; calculate cumulative sum of array cArray [ 0 ] will store sum of zero elements ; store all subarray sum in vector ; sort the vector ; mark all duplicate sub - array sum to zero ; calculate total sum ; return totalSum ; Drivers code | def findSubarraySum ( arr , n ) : NEW_LINE INDENT cArray = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 0 , n , 1 ) : NEW_LINE INDENT cArray [ i + 1 ] = cArray [ i ] + arr [ i ] NEW_LINE DEDENT subArrSum = [ ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 , 1 ) : NEW_LINE INDENT subArrSum . append ( cArray [ j ] - cArray [ i - 1 ] ) NEW_LINE DEDENT DEDENT subArrSum . sort ( reverse = False ) NEW_LINE totalSum = 0 NEW_LINE for i in range ( 0 , len ( subArrSum ) - 1 , 1 ) : NEW_LINE INDENT if ( subArrSum [ i ] == subArrSum [ i + 1 ] ) : NEW_LINE INDENT j = i + 1 NEW_LINE while ( subArrSum [ j ] == subArrSum [ i ] and j < len ( subArrSum ) ) : NEW_LINE INDENT subArrSum [ j ] = 0 NEW_LINE j += 1 NEW_LINE DEDENT subArrSum [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( 0 , len ( subArrSum ) , 1 ) : NEW_LINE INDENT totalSum += subArrSum [ i ] NEW_LINE DEDENT return totalSum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 3 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSubarraySum ( arr , n ) ) NEW_LINE DEDENT |
Smallest number whose set bits are maximum in a given range | Python code to find number whose set bits are maximum among ' l ' and 'r ; Returns smallest number whose set bits are maximum in given range . ; Initialize the maximum count and final answer as ' num ' ; Traverse for every bit of ' i ' number ; If count is greater than previous calculated max_count , update it ; driver code | ' NEW_LINE def countMaxSetBits ( left , right ) : NEW_LINE INDENT max_count = - 1 NEW_LINE for i in range ( left , right + 1 ) : NEW_LINE INDENT temp = i NEW_LINE cnt = 0 NEW_LINE while temp : NEW_LINE INDENT if temp & 1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT temp = temp >> 1 NEW_LINE DEDENT if cnt > max_count : NEW_LINE INDENT max_count = cnt NEW_LINE num = i NEW_LINE DEDENT DEDENT return num NEW_LINE DEDENT l = 1 NEW_LINE r = 5 NEW_LINE print ( countMaxSetBits ( l , r ) ) NEW_LINE l = 1 NEW_LINE r = 10 NEW_LINE print ( countMaxSetBits ( l , r ) ) NEW_LINE |
Find Sum of all unique sub | function for finding grandSum ; Go through all subarrays , compute sums and count occurrences of sums . ; Print all those Sums that appear once . ; Driver code | def findSubarraySum ( arr , n ) : NEW_LINE INDENT res = 0 NEW_LINE m = dict ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT Sum = 0 NEW_LINE for j in range ( i , n ) : NEW_LINE INDENT Sum += arr [ j ] NEW_LINE m [ Sum ] = m . get ( Sum , 0 ) + 1 NEW_LINE DEDENT DEDENT for x in m : NEW_LINE INDENT if m [ x ] == 1 : NEW_LINE INDENT res += x NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 3 , 2 , 3 , 1 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findSubarraySum ( arr , n ) ) NEW_LINE |
Recaman 's sequence | Prints first n terms of Recaman sequence ; Create an array to store terms ; First term of the sequence is always 0 ; Fill remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code | def recaman ( n ) : NEW_LINE INDENT arr = [ 0 ] * n NEW_LINE arr [ 0 ] = 0 NEW_LINE print ( arr [ 0 ] , end = " , β " ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr = arr [ i - 1 ] - i NEW_LINE for j in range ( 0 , i ) : NEW_LINE INDENT if ( ( arr [ j ] == curr ) or curr < 0 ) : NEW_LINE INDENT curr = arr [ i - 1 ] + i NEW_LINE break NEW_LINE DEDENT DEDENT arr [ i ] = curr NEW_LINE print ( arr [ i ] , end = " , β " ) NEW_LINE DEDENT DEDENT n = 17 NEW_LINE recaman ( n ) NEW_LINE |
Print the longest leaf to leaf path in a Binary tree | Tree node structure used in the program ; Function to find height of a tree ; Update the answer , because diameter of a tree is nothing but maximum value of ( left_height + right_height + 1 ) for each node ; Save the root , this will help us finding the left and the right part of the diameter ; Save the height of left & right subtree as well . ; Prints the root to leaf path ; Print left part of the path in reverse order ; This function finds out all the root to leaf paths ; Append this node to the path array ; If it 's a leaf, so print the path that led to here ; Print only one path which is equal to the height of the tree . print ( pathlen , " - - - " , maxm ) ; Otherwise try both subtrees ; Computes the diameter of a binary tree with given root . ; lh will store height of left subtree rh will store height of right subtree ; f is a flag whose value helps in printing left & right part of the diameter only once ; Print the left part of the diameter ; Print the right part of the diameter ; Driver code ; Enter the binary tree ... 1 / \ 2 3 / \ 4 5 \ / \ 8 6 7 / 9 | 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 height ( root ) : NEW_LINE INDENT global ans , k , lh , rh , f NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left_height = height ( root . left ) NEW_LINE right_height = height ( root . right ) NEW_LINE if ( ans < 1 + left_height + right_height ) : NEW_LINE INDENT ans = 1 + left_height + right_height NEW_LINE k = root NEW_LINE lh = left_height NEW_LINE rh = right_height NEW_LINE DEDENT return 1 + max ( left_height , right_height ) NEW_LINE DEDENT def printArray ( ints , lenn , f ) : NEW_LINE INDENT if ( f == 0 ) : NEW_LINE INDENT for i in range ( lenn - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( ints [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT elif ( f == 1 ) : NEW_LINE INDENT for i in range ( lenn ) : NEW_LINE INDENT print ( ints [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT def printPathsRecur ( node , path , maxm , pathlen ) : NEW_LINE INDENT global f NEW_LINE if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT path [ pathlen ] = node . data NEW_LINE pathlen += 1 NEW_LINE if ( node . left == None and node . right == None ) : NEW_LINE INDENT if ( pathlen == maxm and ( f == 0 or f == 1 ) ) : NEW_LINE INDENT printArray ( path , pathlen , f ) NEW_LINE f = 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT printPathsRecur ( node . left , path , maxm , pathlen ) NEW_LINE printPathsRecur ( node . right , path , maxm , pathlen ) NEW_LINE DEDENT DEDENT def diameter ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT global ans , lh , rh NEW_LINE global f , k , pathLen NEW_LINE height_of_tree = height ( root ) NEW_LINE lPath = [ 0 for i in range ( 100 ) ] NEW_LINE printPathsRecur ( k . left , lPath , lh , 0 ) ; NEW_LINE print ( k . data , end = " β " ) NEW_LINE rPath = [ 0 for i in range ( 100 ) ] NEW_LINE f = 1 NEW_LINE printPathsRecur ( k . right , rPath , rh , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k , lh , rh , f , ans , pathLen = None , 0 , 0 , 0 , 0 - 10 ** 19 , 0 NEW_LINE 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 . left . right . left = Node ( 6 ) NEW_LINE root . left . right . right = Node ( 7 ) NEW_LINE root . left . left . right = Node ( 8 ) NEW_LINE root . left . left . right . left = Node ( 9 ) NEW_LINE diameter ( root ) NEW_LINE DEDENT |
Recaman 's sequence | Prints first n terms of Recaman sequence ; Print first term and store it in a hash ; Print remaining terms using recursive formula . ; If arr [ i - 1 ] - i is negative or already exists . ; Driver code | def recaman ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT print ( 0 , " , " , end = ' ' ) NEW_LINE s = set ( [ ] ) NEW_LINE s . add ( 0 ) NEW_LINE prev = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr = prev - i NEW_LINE if ( curr < 0 or curr in s ) : NEW_LINE INDENT curr = prev + i NEW_LINE DEDENT s . add ( curr ) NEW_LINE print ( curr , " , " , end = ' ' ) NEW_LINE prev = curr NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 17 NEW_LINE recaman ( n ) NEW_LINE DEDENT |
Largest subset whose all elements are Fibonacci numbers | Prints largest subset of an array whose all elements are fibonacci numbers ; Find maximum element in arr [ ] ; Generate all Fibonacci numbers till max and store them in hash . ; Npw iterate through all numbers and quickly check for Fibonacci using hash . ; Driver code | def findFibSubset ( arr , n ) : NEW_LINE INDENT m = max ( arr ) NEW_LINE a = 0 NEW_LINE b = 1 NEW_LINE hash = [ ] NEW_LINE hash . append ( a ) NEW_LINE hash . append ( b ) NEW_LINE while ( b < m ) : NEW_LINE INDENT c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE hash . append ( b ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in hash : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 2 , 8 , 5 , 20 , 1 , 40 , 13 , 23 ] NEW_LINE n = len ( arr ) NEW_LINE findFibSubset ( arr , n ) NEW_LINE DEDENT |
Pairs of Amicable Numbers | Efficient Python3 program to count Amicable pairs in an array . ; Calculating the sum of proper divisors ; 1 is a proper divisor ; To handle perfect squares ; check if pair is ambicle ; This function prints count of amicable pairs present in the input array ; Map to store the numbers ; Iterate through each number , and find the sum of proper divisors and check if it 's also present in the array ; It 's sum of proper divisors ; As the pairs are counted twice , thus divide by 2 ; Driver Code | import math NEW_LINE def sumOfDiv ( x ) : NEW_LINE INDENT sum = 1 ; NEW_LINE for i in range ( 2 , int ( math . sqrt ( x ) ) ) : NEW_LINE INDENT if x % i == 0 : NEW_LINE INDENT sum += i NEW_LINE if i != x / i : NEW_LINE INDENT sum += x / i NEW_LINE DEDENT DEDENT DEDENT return int ( sum ) ; NEW_LINE DEDENT def isAmbicle ( a , b ) : NEW_LINE INDENT return ( sumOfDiv ( a ) == b and sumOfDiv ( b ) == a ) NEW_LINE DEDENT def countPairs ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if sumOfDiv ( arr [ i ] ) in s : NEW_LINE INDENT sum = sumOfDiv ( arr [ i ] ) NEW_LINE if isAmbicle ( arr [ i ] , sum ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return int ( count / 2 ) ; NEW_LINE DEDENT arr1 = [ 220 , 284 , 1184 , 1210 , 2 , 5 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( countPairs ( arr1 , n1 ) ) NEW_LINE arr2 = [ 2620 , 2924 , 5020 , 5564 , 6232 , 6368 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( countPairs ( arr2 , n2 ) ) NEW_LINE |
Minimum number of characters required to be removed such that every character occurs same number of times | Python3 program for the above approach ; Function to find minimum number of character removals required to make frequency of all distinct characters the same ; Stores the frequency of each character ; Traverse the string ; Stores the frequency of each charachter in sorted order ; Traverse the Map ; Insert the frequency in multiset ; Stores the count of elements required to be removed ; Stores the size of multiset ; Traverse the multiset ; Update the ans ; Increment i by 1 ; Return ; Driver Code ; Input | import sys NEW_LINE def minimumDeletion ( s , n ) : NEW_LINE INDENT countMap = { } NEW_LINE for i in s : NEW_LINE INDENT countMap [ i ] = countMap . get ( i , 0 ) + 1 NEW_LINE DEDENT countMultiset = [ ] NEW_LINE for it in countMap : NEW_LINE INDENT countMultiset . append ( countMap [ it ] ) NEW_LINE DEDENT ans = sys . maxsize + 1 NEW_LINE i = 0 NEW_LINE m = len ( countMultiset ) NEW_LINE for j in sorted ( countMultiset ) : NEW_LINE INDENT ans = min ( ans , n - ( m - i ) * j ) NEW_LINE i += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE N = len ( S ) NEW_LINE print ( minimumDeletion ( S , N ) ) NEW_LINE DEDENT |
Calculate cost of visiting all array elements in increasing order | Function to calculate total cost of visiting array elements in increasing order ; Stores the pair of element and their positions ; Traverse the array arr [ ] ; Push the pair { arr [ i ] , i } in v ; Sort the vector in ascending order . ; Stores the total cost ; Stores the index of last element visited ; Traverse the vector v ; Increment ans ; Assign ; Return ans ; Driver Code | def calculateDistance ( arr , N ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT v . append ( [ arr [ i ] , i ] ) NEW_LINE DEDENT v . sort ( ) NEW_LINE ans = 0 NEW_LINE last = 0 NEW_LINE for j in v : NEW_LINE INDENT ans += abs ( j [ 1 ] - last ) NEW_LINE last = j [ 1 ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 3 , 2 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( calculateDistance ( arr , N ) ) NEW_LINE DEDENT |
Modify array by sorting nearest perfect squares of array elements having their digits sorted in decreasing order | Python 3 program of the above approach ; Function to sort array in ascending order after replacing array elements by nearest perfect square of decreasing order of digits ; Traverse the array of strings ; Convert the current array element to a string ; Sort each string in descending order ; Convert the string to equivalent integer ; Calculate square root of current array element ; Calculate perfect square ; Find the nearest perfect square ; Sort the array in ascending order ; Print the array ; Driver Code | import math NEW_LINE def sortArr ( arr , N ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT s = str ( arr [ i ] ) NEW_LINE list1 = list ( s ) NEW_LINE list1 . sort ( reverse = True ) NEW_LINE s = ' ' . join ( list1 ) NEW_LINE arr [ i ] = int ( s ) NEW_LINE sr = int ( math . sqrt ( arr [ i ] ) ) NEW_LINE a = sr * sr NEW_LINE b = ( sr + 1 ) * ( sr + 1 ) NEW_LINE if ( ( arr [ i ] - a ) < ( b - arr [ i ] ) ) : NEW_LINE INDENT arr [ i ] = a NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = b NEW_LINE DEDENT DEDENT arr . sort ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 29 , 43 , 28 , 12 ] NEW_LINE N = len ( arr ) NEW_LINE sortArr ( arr , N ) NEW_LINE DEDENT |
Minimize cost required to make all array elements greater than or equal to zero | Python3 program for the above approach ; Function to find the minimum cost to make all array of elements greater than or equal to 0 ; sort the array in ascending order ; stores the count to make current array element >= 0 ; stores the cost to make all array elements >= 0 ; Traverse the array and insert all the elements which are <= 0 ; if current array element is negative ; cost to make all array elements >= 0 ; update curr if ans is minimum ; return minimum cost ; Given array ; size of the array ; Given value of x ; Function call to find minimum cost to make all array elements >= 0 | import sys NEW_LINE def mincost ( arr , N , X ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE cost = 0 NEW_LINE min_cost = sys . maxsize NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cost = abs ( arr [ i ] ) * x + ( sum - abs ( arr [ i ] ) * i ) NEW_LINE sum += abs ( arr [ i ] ) NEW_LINE min_cost = min ( min_cost , cost ) NEW_LINE DEDENT DEDENT return min_cost NEW_LINE DEDENT arr = [ - 1 , - 3 , - 2 , 4 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE x = 2 NEW_LINE print ( mincost ( arr , N , x ) ) NEW_LINE |
Count arrays having at least K elements exceeding XOR of all given array elements by X given operations | Stores the final answer ; Utility function to count arrays having at least K elements exceeding XOR of all given array elements ; If no operations are left ; Stores the count of possible arrays ; Count array elements are greater than XOR ; Stores first element ; Delete first element ; Recursive call ; Insert first element into vector ; Stores the last element ; Remove last element from vector ; Recursive call ; Push last element into vector ; Increment first element ; Recursive call ; Decrement first element ; Increment last element ; Recursive call ; Decrement last element ; Function to find the count of arrays having atleast K elements greater than XOR of array ; Stores the XOR value of original array ; Traverse the vector ; Print the answer ; Given vector ; Given value of X & K | ans = 0 NEW_LINE def countArraysUtil ( arr , X , K , xorVal ) : NEW_LINE INDENT global ans NEW_LINE if ( X == 0 ) : NEW_LINE INDENT cnt = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > xorVal ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT DEDENT if ( cnt >= K ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT return NEW_LINE DEDENT temp = arr [ 0 ] NEW_LINE arr . pop ( 0 ) NEW_LINE countArraysUtil ( arr , X - 1 , K , xorVal ) NEW_LINE arr . insert ( 0 , temp ) NEW_LINE temp = arr [ - 1 ] NEW_LINE arr . pop ( ) NEW_LINE countArraysUtil ( arr , X - 1 , K , xorVal ) NEW_LINE arr . append ( temp ) NEW_LINE arr [ 0 ] += 1 NEW_LINE countArraysUtil ( arr , X - 1 , K , xorVal ) NEW_LINE arr [ 0 ] -= 1 NEW_LINE arr [ len ( arr ) - 1 ] += 1 NEW_LINE countArraysUtil ( arr , X - 1 , K , xorVal ) NEW_LINE arr [ len ( arr ) - 1 ] -= 1 NEW_LINE DEDENT def countArrays ( arr , X , K ) : NEW_LINE INDENT xorVal = 0 NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT xorVal = xorVal ^ arr [ i ] NEW_LINE DEDENT countArraysUtil ( arr , X , K , xorVal ) NEW_LINE print ( ans ) NEW_LINE DEDENT arr = [ 10 , 2 , 10 , 5 ] NEW_LINE X = 3 NEW_LINE K = 3 NEW_LINE countArrays ( arr , X , K ) NEW_LINE |
Difference between maximum and minimum of a set of anagrams from an array | Python3 program for the above approach ; Utility function to find the hash value for each element of the given array ; Initialize an array with first 10 prime numbers ; Iterate over digits of N ; Update Hash Value ; Update N ; Function to find the set of anagrams in the array and print the difference between the maximum and minimum of these numbers ; Map to store the hash value and the array elements having that hash value ; Find the hash value for each arr [ i ] by calling hash function ; Iterate over the map ; If size of vector at m [ i ] greater than 1 then it must contain the anagrams ; Find the minimum and maximum element of this anagrams vector ; Display the difference ; If the end of Map is reached , then no anagrams are present ; Given array ; Size of the array | import math NEW_LINE from collections import defaultdict NEW_LINE def hashFunction ( N ) : NEW_LINE INDENT prime = [ 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 ] NEW_LINE value = 1 NEW_LINE while ( N != 0 ) : NEW_LINE INDENT r = N % 10 NEW_LINE value = value * prime [ r ] NEW_LINE N = N // 10 NEW_LINE DEDENT return value NEW_LINE DEDENT def findDiff ( arr , n ) : NEW_LINE INDENT m = defaultdict ( lambda : [ ] ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT h = hashFunction ( arr [ i ] ) NEW_LINE m [ h ] . append ( arr [ i ] ) NEW_LINE DEDENT i = 0 NEW_LINE while ( i != len ( m ) ) : NEW_LINE INDENT if ( len ( m [ i ] ) > 1 ) : NEW_LINE INDENT minn = min ( m [ i ] ) NEW_LINE maxx = max ( m [ i ] ) NEW_LINE print ( maxx - minn ) NEW_LINE break NEW_LINE DEDENT elif ( i == ( len ( m ) - 1 ) ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT arr = [ 121 , 312 , 234 , 211 , 112 , 102 ] NEW_LINE N = len ( arr ) NEW_LINE findDiff ( arr , N ) NEW_LINE |
Maximum number of apples that can be eaten by a person | Function to find the maximum number of apples a person can eat such that the person eat at most one apple in a day . ; Store count of apples and number of days those apples are edible ; Stores indices of the array ; Stores count of days ; Stores maximum count of edible apples ; Traverse both the arrays ; If top element of the apple is not already expired ; Insert count of apples and their expiration date ; Remove outdated apples ; Insert all the apples produces by tree on current day ; Stores top element of pq ; Remove top element of pq ; If count of apples in curr is greater than 0 ; Insert count of apples and their expiration date ; Update total_apples ; Update index ; Driver Code | def cntMaxApples ( apples , days ) : NEW_LINE INDENT pq = [ ] NEW_LINE i = 0 NEW_LINE n = len ( apples ) NEW_LINE total_apples = 0 NEW_LINE while ( i < n or len ( pq ) > 0 ) : NEW_LINE if ( i < n and apples [ i ] != 0 ) : NEW_LINE INDENT pq . append ( [ i + days [ i ] - 1 , apples [ i ] ] ) NEW_LINE pq . sort ( ) NEW_LINE DEDENT while ( len ( pq ) > 0 and pq [ 0 ] [ 0 ] < i ) : NEW_LINE INDENT pq . pop ( 0 ) NEW_LINE DEDENT if ( len ( pq ) > 0 ) : NEW_LINE INDENT curr = pq [ 0 ] NEW_LINE pq . pop ( 0 ) NEW_LINE if ( len ( curr ) > 1 ) : NEW_LINE pq . append ( [ curr [ 0 ] , curr [ 1 ] - 1 ] ) NEW_LINE pq . sort ( ) NEW_LINE total_apples += 1 NEW_LINE DEDENT i += 1 NEW_LINE return total_apples NEW_LINE DEDENT apples = [ 1 , 2 , 3 , 5 , 2 ] NEW_LINE days = [ 3 , 2 , 1 , 4 , 2 ] NEW_LINE print ( cntMaxApples ( apples , days ) ) NEW_LINE |
Maximum area rectangle by picking four sides from array | function for finding max area ; sort array in non - increasing order ; Initialize two sides of rectangle ; traverse through array ; if any element occurs twice store that as dimension ; return the product of dimensions ; Driver code | def findArea ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE dimension = [ 0 , 0 ] NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while ( i < n - 1 and j < 2 ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + 1 ] ) : NEW_LINE INDENT dimension [ j ] = arr [ i ] NEW_LINE j += 1 NEW_LINE i += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return ( dimension [ 0 ] * dimension [ 1 ] ) NEW_LINE DEDENT arr = [ 4 , 2 , 1 , 4 , 6 , 6 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findArea ( arr , n ) ) NEW_LINE |
Maximum of sum of length of rectangles and squares formed by given sticks | Python3 implementation of the above approach ; Function to find the maximum of sum of lengths of rectangles and squares formed using given set of sticks ; Stores the count of frequencies of all the array elements ; Stores frequencies which are at least 2 ; Convert all frequencies to nearest smaller even values . ; Sum of elements up to index of multiples of 4 ; Print the sum ; Driver Code | from collections import Counter NEW_LINE def findSumLength ( arr , n ) : NEW_LINE INDENT freq = dict ( Counter ( arr ) ) NEW_LINE freq_2 = { } NEW_LINE for i in freq : NEW_LINE INDENT if freq [ i ] >= 2 : NEW_LINE INDENT freq_2 [ i ] = freq [ i ] NEW_LINE DEDENT DEDENT arr1 = [ ] NEW_LINE for i in freq_2 : NEW_LINE arr1 . extend ( [ i ] * ( freq_2 [ i ] // 2 ) * 2 ) NEW_LINE arr1 . sort ( reverse = True ) NEW_LINE summ = 0 NEW_LINE for i in range ( ( len ( arr1 ) // 4 ) * 4 ) : NEW_LINE INDENT summ += arr1 [ i ] NEW_LINE DEDENT print ( summ ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 3 , 2 , 3 , 6 , 4 , 4 , 4 , 5 , 5 , 5 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE findSumLength ( arr , n ) ; NEW_LINE DEDENT |
Maximum area rectangle by picking four sides from array | function for finding max area ; traverse through array ; If this is first occurrence of arr [ i ] , simply insert and continue ; If this is second ( or more ) occurrence , update first and second maximum values . ; return the product of dimensions ; Driver Code | def findArea ( arr , n ) : NEW_LINE INDENT s = [ ] NEW_LINE first = 0 NEW_LINE second = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] not in s : NEW_LINE INDENT s . append ( arr [ i ] ) NEW_LINE continue NEW_LINE DEDENT if ( arr [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > second ) : NEW_LINE INDENT second = arr [ i ] NEW_LINE DEDENT DEDENT return ( first * second ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 2 , 1 , 4 , 6 , 6 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findArea ( arr , n ) ) NEW_LINE DEDENT |
Print root to leaf paths without using recursion | Helper function that allocates a new node with the given data and None left and right pointers . ; Function to print root to leaf path for a leaf using parent nodes stored in map ; start from leaf node and keep on appending nodes into stack till root node is reached ; Start popping nodes from stack and print them ; An iterative function to do preorder traversal of binary tree and print root to leaf path without using recursion ; Corner Case ; Create an empty stack and append root to it ; Create a map to store parent pointers of binary tree nodes ; parent of root is None ; Pop all items one by one . Do following for every popped item a ) append its right child and set its parent pointer b ) append its left child and set its parent pointer Note that right child is appended first so that left is processed first ; Pop the top item from stack ; If leaf node encountered , print Top To Bottom path ; append right & left children of the popped node to stack . Also set their parent pointer in the map ; Driver Code ; Constructed binary tree is 10 / \ 8 2 / \ / 3 5 2 | 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 printTopToBottomPath ( curr , parent ) : NEW_LINE INDENT stk = [ ] NEW_LINE while ( curr ) : NEW_LINE INDENT stk . append ( curr ) NEW_LINE curr = parent [ curr ] NEW_LINE DEDENT while len ( stk ) != 0 : NEW_LINE INDENT curr = stk [ - 1 ] NEW_LINE stk . pop ( - 1 ) NEW_LINE print ( curr . data , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def printRootToLeaf ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT nodeStack = [ ] NEW_LINE nodeStack . append ( root ) NEW_LINE parent = { } NEW_LINE parent [ root ] = None NEW_LINE while len ( nodeStack ) != 0 : NEW_LINE INDENT current = nodeStack [ - 1 ] NEW_LINE nodeStack . pop ( - 1 ) NEW_LINE if ( not ( current . left ) and not ( current . right ) ) : NEW_LINE INDENT printTopToBottomPath ( current , parent ) NEW_LINE DEDENT if ( current . right ) : NEW_LINE INDENT parent [ current . right ] = current NEW_LINE nodeStack . append ( current . right ) NEW_LINE DEDENT if ( current . left ) : NEW_LINE INDENT parent [ current . left ] = current NEW_LINE nodeStack . append ( current . left ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 10 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . right = newNode ( 2 ) NEW_LINE root . left . left = newNode ( 3 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 2 ) NEW_LINE printRootToLeaf ( root ) NEW_LINE DEDENT |
Game of replacing array elements | Function return which player win the game ; Create hash that will stores all distinct element ; Traverse an array element ; Driver code | def playGame ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE DEDENT return 1 if len ( s ) % 2 == 0 else 2 NEW_LINE DEDENT arr = [ 1 , 1 , 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Player " , playGame ( arr , n ) , " Wins " ) NEW_LINE |
Length of longest strict bitonic subsequence | function to find length of longest strict bitonic subsequence ; hash table to map the array element with the length of the longest subsequence of which it is a part of and is the last / first element of that subsequence ; arrays to store the length of increasing and decreasing subsequences which end at them or start from them ; to store the length of longest strict bitonic subsequence ; traverse the array elements from left to right ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in 'inc ; update arr [ i ] subsequence length in ' inc ' and in len_inc [ ] ; traverse the array elements from right to left ; initialize current length for element arr [ i ] as 0 ; if ' arr [ i ] -1' is in 'dcr ; update arr [ i ] subsequence length in ' dcr ' and in len_dcr [ ] ; calculating the length of all the strict bitonic subsequence ; required longest length strict bitonic subsequence ; Driver Code | def longLenStrictBitonicSub ( arr , n ) : NEW_LINE INDENT inc , dcr = dict ( ) , dict ( ) NEW_LINE len_inc , len_dcr = [ 0 ] * n , [ 0 ] * n NEW_LINE longLen = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT len = 0 NEW_LINE if inc . get ( arr [ i ] - 1 ) in inc . values ( ) : NEW_LINE INDENT len = inc . get ( arr [ i ] - 1 ) NEW_LINE DEDENT inc [ arr [ i ] ] = len_inc [ i ] = len + 1 NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT len = 0 NEW_LINE if dcr . get ( arr [ i ] - 1 ) in dcr . values ( ) : NEW_LINE INDENT len = dcr . get ( arr [ i ] - 1 ) NEW_LINE DEDENT dcr [ arr [ i ] ] = len_dcr [ i ] = len + 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if longLen < ( len_inc [ i ] + len_dcr [ i ] - 1 ) : NEW_LINE INDENT longLen = len_inc [ i ] + len_dcr [ i ] - 1 NEW_LINE DEDENT DEDENT return longLen NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 2 , 3 , 4 , 5 , 3 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Longest β length β strict β bitonic β subsequence β = " , longLenStrictBitonicSub ( arr , n ) ) NEW_LINE DEDENT |
Selection Sort VS Bubble Sort | ; Driver Code | def Selection_Sort ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT min_index = i NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] < arr [ min_index ] ) : NEW_LINE INDENT min_index = j NEW_LINE DEDENT DEDENT arr [ i ] , arr [ min_index ] = arr [ min_index ] , arr [ i ] NEW_LINE DEDENT DEDENT n = 5 NEW_LINE arr = [ 2 , 0 , 1 , 4 , 3 ] NEW_LINE Selection_Sort ( arr , n ) NEW_LINE print ( " The β Sorted β Array β by β using β " \ " Selection β Sort β is β : β " , end = ' ' ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Last seen array element ( last appearance is earliest ) | Python3 program to find last seen element in an array . ; Returns last seen element in arr [ ] ; Store last occurrence index of every element ; Find an element in hash with minimum index value ; Driver code | import sys ; NEW_LINE def lastSeenElement ( a , n ) : NEW_LINE INDENT hash = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ a [ i ] ] = i NEW_LINE DEDENT res_ind = sys . maxsize NEW_LINE res = 0 NEW_LINE for x , y in hash . items ( ) : NEW_LINE INDENT if y < res_ind : NEW_LINE INDENT res_ind = y NEW_LINE res = x NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 2 , 1 , 2 , 2 , 4 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( lastSeenElement ( a , n ) ) NEW_LINE DEDENT |
Selection Sort VS Bubble Sort | ; Driver Code | def Bubble_Sort ( arr , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , n - i ) : NEW_LINE INDENT if ( arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ] NEW_LINE DEDENT DEDENT DEDENT return arr NEW_LINE DEDENT n = 5 NEW_LINE arr = [ 2 , 0 , 1 , 4 , 3 ] NEW_LINE arr = Bubble_Sort ( arr , n ) NEW_LINE print ( " The β Sorted β Array β by β using β Bubble β Sort β is β : β " , end = ' ' ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT |
Minimum cost required to connect all houses in a city | Python3 program for the above approach ; Utility function to find set of an element v using path compression technique ; If v is the parent ; Otherwise , recursively find its parent ; Function to perform union of the sets a and b ; Find parent of a and b ; If parent are different ; Swap Operation ; Update parent of b as a ; Otherwise , return 0 ; Function to create a Minimum Cost Spanning tree for given houses ; Stores adjacency list of graph ; Traverse each coordinate ; Find the Manhattan distance ; Add the edges ; Sort all the edges ; Initialize parent [ ] and size [ ] ; Stores the minimum cost ; Finding the minimum cost ; Perform the unioun operation ; Print the minimum cost ; Driver Code ; Given houses ; Function Call | parent = [ 0 ] * 100 NEW_LINE size = [ 0 ] * 100 NEW_LINE def find_set ( v ) : NEW_LINE INDENT if ( v == parent [ v ] ) : NEW_LINE INDENT return v NEW_LINE DEDENT parent [ v ] = find_set ( parent [ v ] ) NEW_LINE return parent [ v ] NEW_LINE DEDENT def union_sets ( a , b ) : NEW_LINE INDENT a = find_set ( a ) NEW_LINE b = find_set ( b ) NEW_LINE if ( a != b ) : NEW_LINE INDENT if ( size [ a ] < size [ b ] ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT parent [ b ] = a NEW_LINE size [ a ] += size [ b ] NEW_LINE return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def MST ( houses , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT p = abs ( houses [ i ] [ 0 ] - houses [ j ] [ 0 ] ) NEW_LINE p += abs ( houses [ i ] [ 1 ] - houses [ j ] [ 1 ] ) NEW_LINE v . append ( [ p , i , j ] ) NEW_LINE DEDENT DEDENT v = sorted ( v ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT parent [ i ] = i NEW_LINE size [ i ] = 1 NEW_LINE DEDENT ans = 0 NEW_LINE for x in v : NEW_LINE INDENT if ( union_sets ( x [ 1 ] , x [ 2 ] ) ) : NEW_LINE INDENT ans += x [ 0 ] NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT houses = [ [ 0 , 0 ] , [ 2 , 2 ] , [ 3 , 10 ] , [ 5 , 2 ] , [ 7 , 0 ] ] NEW_LINE N = len ( houses ) NEW_LINE MST ( houses , N ) NEW_LINE DEDENT |
Lexicographically smallest subsequence possible by removing a character from given string | Function to find the lexicographically smallest subsequence of length N - 1 ; Store index of character to be deleted ; Traverse the String ; If ith character > ( i + 1 ) th character then store it ; If any character found in non alphabetical order then remove it ; Otherwise remove last character ; Print the resultant subsequence ; Driver Code ; Given String S ; Function Call | def firstSubsequence ( s ) : NEW_LINE INDENT isMax = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] > s [ i + 1 ] ) : NEW_LINE INDENT isMax = i NEW_LINE break NEW_LINE DEDENT DEDENT if ( isMax >= 0 ) : NEW_LINE INDENT s = s [ 0 : isMax ] + s [ isMax + 1 : len ( s ) ] NEW_LINE DEDENT s . rerase ( isMax , 1 ) ; NEW_LINE else : NEW_LINE INDENT s . erase ( s . length ( ) - 1 , 1 ) ; NEW_LINE s = s [ 0 : s . length ( ) - 1 ] NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE firstSubsequence ( S ) NEW_LINE DEDENT |
Maximize product of array by replacing array elements with its sum or product with element from another array | Function to find the largest product of array A [ ] ; Base Case ; Store all the elements of the array A [ ] ; Sort the Array B [ ] ; Traverse the array B [ ] ; Pop minimum element ; Check which operation is producing maximum element ; Insert resultant element into the priority queue ; Evaluate the product of the elements of A [ ] ; Return the maximum product ; Given arrays ; Function Call | def largeProduct ( A , B , N ) : NEW_LINE INDENT if ( N == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT pq = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( A [ i ] ) NEW_LINE DEDENT B . sort ( ) NEW_LINE pq . sort ( reverse = True ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT minn = pq . pop ( ) NEW_LINE maximized_element = max ( minn * B [ i ] , minn + B [ i ] ) NEW_LINE pq . append ( maximized_element ) NEW_LINE pq . sort ( reverse = True ) NEW_LINE DEDENT max_product = 1 NEW_LINE while ( len ( pq ) > 0 ) : NEW_LINE INDENT max_product *= pq . pop ( ) ; NEW_LINE DEDENT return max_product NEW_LINE DEDENT A = [ 1 , 1 , 10 ] NEW_LINE B = [ 1 , 1 , 1 ] NEW_LINE N = 3 NEW_LINE print ( largeProduct ( A , B , N ) ) NEW_LINE |
Print all root to leaf paths with there relative positions | Python3 program to print the longest leaf to leaf path ; Tree node structure used in the program ; Prints given root to leafAllpaths with underscores ; Find the minimum horizontal distance value in current root to leafAllpaths ; Find minimum horizontal distance ; Print the root to leafAllpaths with " _ " that indicate the related position ; Current tree node ; Print underscore ; Print current key ; A utility function prall path from root to leaf working of this function is similar to function of " Print _ vertical _ order " : Prpaths of binary tree in vertical order https : www . geeksforgeeks . org / print - binary - tree - vertical - order - set - 2 / ; Base case ; Leaf node ; Add leaf node and then prpath ; Store current path information ; Call left sub_tree ; Call left sub_tree ; Base case ; Driver code | MAX_PATH_SIZE = 1000 NEW_LINE 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 printPath ( size ) : NEW_LINE INDENT minimum_Hd = 10 ** 19 NEW_LINE p = [ ] NEW_LINE global Allpaths NEW_LINE for it in range ( size ) : NEW_LINE INDENT p = Allpaths [ it ] NEW_LINE minimum_Hd = min ( minimum_Hd , p [ 0 ] ) NEW_LINE DEDENT for it in range ( size ) : NEW_LINE INDENT p = Allpaths [ it ] NEW_LINE noOfUnderScores = abs ( p [ 0 ] - minimum_Hd ) NEW_LINE for i in range ( noOfUnderScores ) : NEW_LINE INDENT print ( end = " _ β " ) NEW_LINE DEDENT print ( p [ 1 ] ) NEW_LINE DEDENT print ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " ) NEW_LINE DEDENT def printAllPathsUtil ( root , HD , order ) : NEW_LINE INDENT global Allpaths NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . right == None ) : NEW_LINE INDENT Allpaths [ order ] = [ HD , root . data ] NEW_LINE printPath ( order + 1 ) NEW_LINE return NEW_LINE DEDENT Allpaths [ order ] = [ HD , root . data ] NEW_LINE printAllPathsUtil ( root . left , HD - 1 , order + 1 ) NEW_LINE printAllPathsUtil ( root . right , HD + 1 , order + 1 ) NEW_LINE DEDENT def printAllPaths ( root ) : NEW_LINE INDENT global Allpaths NEW_LINE if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printAllPathsUtil ( root , 0 , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT Allpaths = [ [ 0 , 0 ] for i in range ( MAX_PATH_SIZE ) ] NEW_LINE root = Node ( ' A ' ) NEW_LINE root . left = Node ( ' B ' ) NEW_LINE root . right = Node ( ' C ' ) NEW_LINE root . left . left = Node ( ' D ' ) NEW_LINE root . left . right = Node ( ' E ' ) NEW_LINE root . right . left = Node ( ' F ' ) NEW_LINE root . right . right = Node ( ' G ' ) NEW_LINE printAllPaths ( root ) NEW_LINE DEDENT |
Minimum steps required to rearrange given array to a power sequence of 2 | Function to calculate the minimum steps required to convert given array into a power sequence of 2 ; Sort the array in ascending order ; Calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; Return the answer ; Driver Code | def minsteps ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += abs ( arr [ i ] - pow ( 2 , i ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 8 , 2 , 10 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( minsteps ( arr , n ) ) NEW_LINE |
Block swap algorithm for array rotation | Wrapper over the recursive function leftRotateRec ( ) It left rotates arr by d . ; * Return If number of elements to be rotated is zero or equal to array size ; * If number of elements to be rotated is exactly half of array size ; If A is shorter ; If B is shorter ; function to pran array ; * This function swaps d elements starting at * index fi with d elements starting at index si ; Driver Code | def leftRotate ( arr , d , n ) : NEW_LINE INDENT leftRotateRec ( arr , 0 , d , n ) ; NEW_LINE DEDENT def leftRotateRec ( arr , i , d , n ) : NEW_LINE INDENT if ( d == 0 or d == n ) : NEW_LINE INDENT return ; NEW_LINE DEDENT if ( n - d == d ) : NEW_LINE INDENT swap ( arr , i , n - d + i , d ) ; NEW_LINE return ; NEW_LINE DEDENT if ( d < n - d ) : NEW_LINE INDENT swap ( arr , i , n - d + i , d ) ; NEW_LINE leftRotateRec ( arr , i , d , n - d ) ; NEW_LINE DEDENT else : NEW_LINE INDENT swap ( arr , i , d , n - d ) ; NEW_LINE leftRotateRec ( arr , n - d + i , 2 * d - n , d ) ; NEW_LINE DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT def swap ( arr , fi , si , d ) : NEW_LINE INDENT for i in range ( d ) : NEW_LINE INDENT temp = arr [ fi + i ] ; NEW_LINE arr [ fi + i ] = arr [ si + i ] ; NEW_LINE arr [ si + i ] = temp ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ; NEW_LINE leftRotate ( arr , 2 , 7 ) ; NEW_LINE printArray ( arr , 7 ) ; NEW_LINE DEDENT |
Cost required to empty a given array by repeated removal of maximum obtained by given operations | Function to find the total cost of removing all array elements ; Sort the array in descending order ; Stores the total cost ; Contribution of i - th greatest element to the cost ; Remove the element ; If negative ; Add to the final cost ; Return the cost ; Given array arr [ ] ; Function call | def findCost ( a , n ) : NEW_LINE INDENT a . sort ( reverse = True ) NEW_LINE count = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT p = a [ j ] - j NEW_LINE a [ j ] = 0 NEW_LINE if ( p < 0 ) : NEW_LINE INDENT p = 0 NEW_LINE continue NEW_LINE DEDENT count += p NEW_LINE DEDENT return count NEW_LINE DEDENT arr = [ 1 , 6 , 7 , 4 , 2 , 5 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findCost ( arr , N ) ) NEW_LINE |
Block swap algorithm for array rotation | Python3 code for above implementation ; A is shorter ; B is shorter ; Finally , block swap A and B | def leftRotate ( arr , d , n ) : NEW_LINE INDENT if ( d == 0 or d == n ) : NEW_LINE INDENT return ; NEW_LINE DEDENT i = d NEW_LINE j = n - d NEW_LINE while ( i != j ) : NEW_LINE INDENT if ( i < j ) : NEW_LINE INDENT swap ( arr , d - i , d + j - i , i ) NEW_LINE j -= i NEW_LINE DEDENT else : NEW_LINE INDENT swap ( arr , d - i , d , j ) NEW_LINE i -= j NEW_LINE DEDENT DEDENT swap ( arr , d - i , d , i ) NEW_LINE DEDENT |
Count of index pairs with equal elements in an array | Set 2 | Function that count the pairs having same elements in the array arr [ ] ; Hash map to keep track of occurences of elements ; Traverse the array arr [ ] ; Check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; Return the result ; Given array arr [ ] ; Function call | def countPairs ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE count = { } NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] in count : NEW_LINE INDENT ans += count [ arr [ i ] ] NEW_LINE DEDENT if arr [ i ] in count : NEW_LINE INDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 2 , 1 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countPairs ( arr , N ) ) NEW_LINE |
Maximize shortest path between given vertices by adding a single edge | Function that performs BFS Traversal ; Fill initially each distance as INF fill ( dist , dist + N , INF ) ; Perform BFS ; Traverse the current edges ; Update the distance ; Insert in queue ; Function that maximizes the shortest path between source and destination vertex by adding a single edge between given selected nodes ; To update the shortest distance between node 1 to other vertices ; To update the shortest distance between node N to other vertices ; Store the values x [ i ] - y [ i ] ; Sort all the vectors of pairs ; Traverse data [ ] ; Maximize x [ a ] - y [ b ] ; Prminimum cost ; Driver Code ; Given nodes and edges ; Sort the selected nodes ; Given edges ; Function Call | def bfs ( x , s ) : NEW_LINE INDENT global edges , dist NEW_LINE q = [ 0 for i in range ( 200000 ) ] NEW_LINE qh , qt = 0 , 0 NEW_LINE q [ qh ] = s NEW_LINE qh += 1 NEW_LINE dist [ x ] [ s ] = 0 NEW_LINE while ( qt < qh ) : NEW_LINE INDENT xx = q [ qt ] NEW_LINE qt += 1 NEW_LINE for y in edges [ xx ] : NEW_LINE INDENT if ( dist [ x ] [ y ] == 10 ** 18 ) : NEW_LINE INDENT dist [ x ] [ y ] = dist [ x ] [ xx ] + 1 NEW_LINE q [ qh ] = y NEW_LINE qh += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT def shortestPathCost ( selected , K ) : NEW_LINE INDENT global dist , edges NEW_LINE data = [ ] NEW_LINE bfs ( 0 , 0 ) NEW_LINE bfs ( 1 , N - 1 ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT data . append ( [ dist [ 0 ] [ selected [ i ] ] - dist [ 1 ] [ selected [ i ] ] , selected [ i ] ] ) NEW_LINE DEDENT data = sorted ( data ) NEW_LINE best = 0 NEW_LINE MAX = - 10 ** 18 NEW_LINE for it in data : NEW_LINE INDENT a = it [ 1 ] NEW_LINE best = max ( best , MAX + dist [ 1 ] [ a ] ) NEW_LINE MAX = max ( MAX , dist [ 0 ] [ a ] ) NEW_LINE DEDENT print ( min ( dist [ 0 ] [ N - 1 ] , best + 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT edges = [ [ ] for i in range ( 5 ) ] NEW_LINE dist = [ [ 10 ** 18 for i in range ( 1000005 ) ] for i in range ( 2 ) ] NEW_LINE N , M = 5 , 4 NEW_LINE K = 2 NEW_LINE selected = [ 1 , 3 ] NEW_LINE selected = sorted ( selected ) NEW_LINE edges [ 0 ] . append ( 1 ) NEW_LINE edges [ 1 ] . append ( 0 ) NEW_LINE edges [ 1 ] . append ( 2 ) NEW_LINE edges [ 2 ] . append ( 1 ) NEW_LINE edges [ 2 ] . append ( 3 ) NEW_LINE edges [ 3 ] . append ( 2 ) NEW_LINE edges [ 3 ] . append ( 4 ) NEW_LINE edges [ 4 ] . append ( 3 ) NEW_LINE shortestPathCost ( selected , K ) NEW_LINE DEDENT |
Program to cyclically rotate an array by one | i and j pointing to first and last element respectively ; Driver function | def rotate ( arr , n ) : NEW_LINE INDENT i = 0 NEW_LINE j = n - 1 NEW_LINE while i != j : NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE i = i + 1 NEW_LINE pass NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given β array β is " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' β ' ) NEW_LINE DEDENT rotate ( arr , n ) NEW_LINE print ( " Rotated array is " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' β ' ) NEW_LINE DEDENT |
Minimum cost to empty Array where cost of removing an element is 2 ^ ( removed_count ) * arr [ i ] | Function to find the minimum cost of removing elements from the array ; Sorting in Increasing order ; Loop to find the minimum cost of removing elements ; Driver Code ; Function call | def removeElements ( arr , n ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += arr [ i ] * pow ( 2 , i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 4 NEW_LINE arr = [ 3 , 1 , 2 , 3 ] NEW_LINE print ( removeElements ( arr , n ) ) NEW_LINE DEDENT |
Sorting boundary elements of a matrix | Python program for the above approach ; Appending border elements ; Sorting the list ; Printing first row with first N elements from A ; Printing N - 2 rows ; Print elements from last ; Print middle elements from original matrix ; Print elements from front ; Printing last row ; Dimensions of a Matrix ; Given Matrix ; Function Call | def printMatrix ( grid , m , n ) : NEW_LINE INDENT A = [ ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if j == n - 1 or ( i == m - 1 ) or j == 0 or i == 0 : NEW_LINE INDENT A . append ( grid [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT A . sort ( ) NEW_LINE print ( * A [ : n ] ) NEW_LINE for i in range ( m - 2 ) : NEW_LINE INDENT print ( A [ len ( A ) - i - 1 ] , end = " β " ) NEW_LINE for j in range ( 1 , n - 1 ) : NEW_LINE INDENT print ( grid [ i + 1 ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( A [ n + i ] ) NEW_LINE DEDENT print ( * reversed ( A [ n + m - 2 : n + m - 2 + n ] ) ) NEW_LINE DEDENT m , n = 4 , 5 NEW_LINE grid = [ [ 1 , 2 , 3 , 4 , 0 ] , [ 1 , 1 , 1 , 1 , 2 ] , [ 1 , 2 , 2 , 2 , 4 ] , [ 1 , 9 , 3 , 1 , 7 ] ] NEW_LINE printMatrix ( grid , m , n ) NEW_LINE |
Lexicographically largest string possible in one swap | Function to return the lexicographically largest string possible by swapping at most one character ; Initialize with - 1 for every character ; Keep updating the last occurrence of each character ; If a previously unvisited character occurs ; Stores the sorted string ; Character to replace ; Find the last occurrence of this character ; Swap this with the last occurrence ; Driver code | def findLargest ( s ) : NEW_LINE INDENT Len = len ( s ) NEW_LINE loccur = [ - 1 for i in range ( 26 ) ] NEW_LINE for i in range ( Len - 1 , - 1 , - 1 ) : NEW_LINE INDENT chI = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( loccur [ chI ] == - 1 ) : NEW_LINE INDENT loccur [ chI ] = i NEW_LINE DEDENT DEDENT sorted_s = sorted ( s , reverse = True ) NEW_LINE for i in range ( Len ) : NEW_LINE INDENT if ( s [ i ] != sorted_s [ i ] ) : NEW_LINE INDENT chI = ( ord ( sorted_s [ i ] ) - ord ( ' a ' ) ) NEW_LINE last_occ = loccur [ chI ] NEW_LINE temp = list ( s ) NEW_LINE temp [ i ] , temp [ last_occ ] = ( temp [ last_occ ] , temp [ i ] ) NEW_LINE s = " " . join ( temp ) NEW_LINE break NEW_LINE DEDENT DEDENT return s NEW_LINE DEDENT s = " yrstvw " NEW_LINE print ( findLargest ( s ) ) NEW_LINE |
Given a sorted and rotated array , find if there is a pair with a given sum | This function returns True if arr [ 0. . n - 1 ] has a pair with sum equals to x . ; Find the pivot element ; l is now index of smallest element ; r is now index of largest element ; Keep moving either l or r till they meet ; If we find a pair with sum x , we return True ; If current pair sum is less , move to the higher sum ; Move to the lower sum side ; Driver program to test above function | def pairInSortedRotated ( arr , n , x ) : NEW_LINE INDENT for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT l = ( i + 1 ) % n NEW_LINE r = i NEW_LINE while ( l != r ) : NEW_LINE INDENT if ( arr [ l ] + arr [ r ] == x ) : NEW_LINE INDENT return True ; NEW_LINE DEDENT if ( arr [ l ] + arr [ r ] < x ) : NEW_LINE INDENT l = ( l + 1 ) % n ; NEW_LINE DEDENT else : NEW_LINE INDENT r = ( n + r - 1 ) % n ; NEW_LINE DEDENT DEDENT return False ; NEW_LINE DEDENT arr = [ 11 , 15 , 6 , 8 , 9 , 10 ] NEW_LINE sum = 16 NEW_LINE n = len ( arr ) NEW_LINE if ( pairInSortedRotated ( arr , n , sum ) ) : NEW_LINE INDENT print ( " Array β has β two β elements β with β sum β 16" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Array β doesn ' t β have β two β elements β with β sum β 16 β " ) NEW_LINE DEDENT |
Given a sorted and rotated array , find if there is a pair with a given sum | This function returns count of number of pairs with sum equals to x . ; Find the pivot element . Pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; Variable to store count of number of pairs . ; Find sum of pair formed by arr [ l ] and arr [ r ] and update l , r and cnt accordingly . ; If we find a pair with sum x , then increment cnt , move l and r to next element . ; This condition is required to be checked , otherwise l and r will cross each other and loop will never terminate . ; If current pair sum is less , move to the higher sum side . ; If current pair sum is greater , move to the lower sum side . ; Driver Code | def pairsInSortedRotated ( arr , n , x ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if arr [ i ] > arr [ i + 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT l = ( i + 1 ) % n NEW_LINE r = i NEW_LINE cnt = 0 NEW_LINE while ( l != r ) : NEW_LINE INDENT if arr [ l ] + arr [ r ] == x : NEW_LINE INDENT cnt += 1 NEW_LINE if l == ( r - 1 + n ) % n : NEW_LINE INDENT return cnt NEW_LINE DEDENT l = ( l + 1 ) % n NEW_LINE r = ( r - 1 + n ) % n NEW_LINE DEDENT elif arr [ l ] + arr [ r ] < x : NEW_LINE INDENT l = ( l + 1 ) % n NEW_LINE DEDENT else : NEW_LINE INDENT r = ( n + r - 1 ) % n NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT arr = [ 11 , 15 , 6 , 7 , 9 , 10 ] NEW_LINE s = 16 NEW_LINE print ( pairsInSortedRotated ( arr , 6 , s ) ) NEW_LINE |
Find maximum value of Sum ( i * arr [ i ] ) with only rotations on given array allowed | returns max possible value of Sum ( i * arr [ i ] ) ; stores sum of arr [ i ] ; stores sum of i * arr [ i ] ; initialize result ; try all rotations one by one and find the maximum rotation sum ; return result ; test maxsum ( arr ) function | def maxSum ( arr ) : NEW_LINE INDENT arrSum = 0 NEW_LINE currVal = 0 NEW_LINE n = len ( arr ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT arrSum = arrSum + arr [ i ] NEW_LINE currVal = currVal + ( i * arr [ i ] ) NEW_LINE DEDENT maxVal = currVal NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT currVal = currVal + arrSum - n * arr [ n - j ] NEW_LINE if currVal > maxVal : NEW_LINE INDENT maxVal = currVal NEW_LINE DEDENT DEDENT return maxVal NEW_LINE DEDENT arr = [ 10 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE print " Max β sum β is : β " , maxSum ( arr ) NEW_LINE |
Print the nodes at odd levels of a tree | Recursive Python3 program to print odd level nodes Utility method to create a node ; If empty tree ; If current node is of odd level ; Recur for children with isOdd switched . ; 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 printOddNodes ( root , isOdd = True ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( isOdd ) : NEW_LINE INDENT print ( root . data , end = " β " ) NEW_LINE DEDENT printOddNodes ( root . left , not isOdd ) NEW_LINE printOddNodes ( root . right , not isOdd ) 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 printOddNodes ( root ) NEW_LINE DEDENT |
Maximum sum of i * arr [ i ] among all rotations of a given array | A Naive Python3 program to find maximum sum rotation ; Returns maximum value of i * arr [ i ] ; Initialize result ; Consider rotation beginning with i for all possible values of i . ; Initialize sum of current rotation ; Compute sum of all values . We don 't acutally rotation the array, but compute sum by finding ndexes when arr[i] is first element ; Update result if required ; Driver code | import sys NEW_LINE def maxSum ( arr , n ) : NEW_LINE INDENT res = - sys . maxsize NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE for j in range ( 0 , n ) : NEW_LINE INDENT index = int ( ( i + j ) % n ) NEW_LINE curr_sum += j * arr [ index ] NEW_LINE DEDENT res = max ( res , curr_sum ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 8 , 3 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE |
Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient Python3 program to compute maximum sum of i * arr [ i ] ; Compute sum of all array elements ; Compute sum of i * arr [ i ] for initial configuration . ; Initialize result ; Compute values for other iterations ; Compute next value using previous value in O ( 1 ) time ; Update current value ; Update result if required ; Driver code | def maxSum ( arr , n ) : NEW_LINE INDENT cum_sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT cum_sum += arr [ i ] NEW_LINE DEDENT curr_val = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT curr_val += i * arr [ i ] NEW_LINE DEDENT res = curr_val NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT next_val = ( curr_val - ( cum_sum - arr [ i - 1 ] ) + arr [ i - 1 ] * ( n - 1 ) ) NEW_LINE curr_val = next_val NEW_LINE res = max ( res , next_val ) NEW_LINE DEDENT return res NEW_LINE DEDENT arr = [ 8 , 3 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxSum ( arr , n ) ) NEW_LINE |
Find the Rotation Count in Rotated Sorted array | Returns count of rotations for an array which is first sorted in ascending order , then rotated ; We basically find index of minimum element ; Driver code | def countRotations ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( min > arr [ i ] ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE min_index = i NEW_LINE DEDENT DEDENT return min_index ; NEW_LINE DEDENT arr = [ 15 , 18 , 2 , 3 , 6 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countRotations ( arr , n ) ) NEW_LINE |
Find the Rotation Count in Rotated Sorted array | Returns count of rotations for an array which is first sorted in ascending order , then rotated ; This condition is needed to handle the case when array is not rotated at all ; If there is only one element left ; Find mid ; Check if element ( mid + 1 ) is minimum element . Consider the cases like { 3 , 4 , 5 , 1 , 2 } ; Check if mid itself is minimum element ; Decide whether we need to go to left half or right half ; Driver code | def countRotations ( arr , low , high ) : NEW_LINE INDENT if ( high < low ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( high == low ) : NEW_LINE INDENT return low NEW_LINE DEDENT mid = low + ( high - low ) / 2 ; NEW_LINE mid = int ( mid ) NEW_LINE if ( mid < high and arr [ mid + 1 ] < arr [ mid ] ) : NEW_LINE INDENT return ( mid + 1 ) NEW_LINE DEDENT if ( mid > low and arr [ mid ] < arr [ mid - 1 ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( arr [ high ] > arr [ mid ] ) : NEW_LINE INDENT return countRotations ( arr , low , mid - 1 ) ; NEW_LINE DEDENT return countRotations ( arr , mid + 1 , high ) NEW_LINE DEDENT arr = [ 15 , 18 , 2 , 3 , 6 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countRotations ( arr , 0 , n - 1 ) ) NEW_LINE |
Quickly find multiple left rotations of an array | Set 1 | Fills temp with two copies of arr ; Store arr elements at i and i + n ; Function to left rotate an array k times ; Starting position of array after k rotations in temp will be k % n ; Print array after k rotations ; Driver program | def preprocess ( arr , n ) : NEW_LINE INDENT temp = [ None ] * ( 2 * n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp [ i ] = temp [ i + n ] = arr [ i ] NEW_LINE DEDENT return temp NEW_LINE DEDENT def leftRotate ( arr , n , k , temp ) : NEW_LINE INDENT start = k % n NEW_LINE for i in range ( start , start + n ) : NEW_LINE INDENT print ( temp [ i ] , end = " β " ) NEW_LINE DEDENT print ( " " ) NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE temp = preprocess ( arr , n ) NEW_LINE k = 2 NEW_LINE leftRotate ( arr , n , k , temp ) NEW_LINE k = 3 NEW_LINE leftRotate ( arr , n , k , temp ) NEW_LINE k = 4 NEW_LINE leftRotate ( arr , n , k , temp ) NEW_LINE |
Arrange the array such that upon performing given operations an increasing order is obtained | Function to arrange array in such a way that after performing given operation We get increasing sorted array ; Size of given array ; Sort the given array ; Start erasing last element and place it at ith index ; While we reach at starting ; Store last element ; Shift all elements by 1 position in right ; insert last element at ith position ; print desired Array ; Given Array | def Desired_Array ( v ) : NEW_LINE INDENT n = len ( v ) NEW_LINE v . sort ( ) NEW_LINE i = n - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT p = v [ n - 1 ] NEW_LINE for j in range ( n - 1 , i - 1 , - 1 ) : NEW_LINE INDENT v [ j ] = v [ j - 1 ] NEW_LINE DEDENT v [ i ] = p NEW_LINE i -= 1 NEW_LINE DEDENT for x in v : NEW_LINE INDENT print ( x , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT v = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE Desired_Array ( v ) NEW_LINE v1 = [ 1 , 12 , 2 , 10 , 4 , 16 , 6 ] NEW_LINE Desired_Array ( v1 ) NEW_LINE |
Quickly find multiple left rotations of an array | Set 1 | Function to left rotate an array k times ; Print array after k rotations ; Driver Code | def leftRotate ( arr , n , k ) : NEW_LINE INDENT for i in range ( k , k + n ) : NEW_LINE INDENT print ( str ( arr [ i % n ] ) , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 5 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 ; NEW_LINE leftRotate ( arr , n , k ) NEW_LINE print ( ) NEW_LINE k = 3 ; NEW_LINE leftRotate ( arr , n , k ) NEW_LINE print ( ) NEW_LINE k = 4 NEW_LINE leftRotate ( arr , n , k ) NEW_LINE print ( ) NEW_LINE |
How to sort an array in a single loop ? | Function for Sorting the array using a single loop ; Finding the length of array 'arr ; Sorting using a single loop ; Checking the condition for two simultaneous elements of the array ; Swapping the elements . ; updating the value of j = - 1 so after getting updated for j ++ in the loop it becomes 0 and the loop begins from the start . ; Driver Code ; Declaring an integer array of size 11. ; Printing the original Array . ; Sorting the array using a single loop ; Printing the sorted array . | def sortArrays ( arr ) : NEW_LINE ' NEW_LINE INDENT length = len ( arr ) NEW_LINE j = 0 NEW_LINE while j < length - 1 : NEW_LINE INDENT if ( arr [ j ] > arr [ j + 1 ] ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ j + 1 ] NEW_LINE arr [ j + 1 ] = temp NEW_LINE j = - 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT return arr NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 99 , 9 , 8 , 7 , 6 , 0 , 5 , 4 , 3 ] NEW_LINE print ( " Original β array : β " , arr ) NEW_LINE arr = sortArrays ( arr ) NEW_LINE print ( " Sorted β array : β " , arr ) NEW_LINE DEDENT |
How to sort an array in a single loop ? | Function for Sorting the array using a single loop ; Sorting using a single loop ; Type Conversion of char to int . ; Comparing the ascii code . ; Swapping of the characters ; Declaring a String ; declaring character array ; copying the contents of the string to char array ; Printing the original Array . ; Sorting the array using a single loop ; Printing the sorted array . | def sortArrays ( arr , length ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < length - 1 ) : NEW_LINE INDENT d1 = arr [ j ] NEW_LINE d2 = arr [ j + 1 ] NEW_LINE if ( d1 > d2 ) : NEW_LINE INDENT temp = arr [ j ] NEW_LINE arr [ j ] = arr [ j + 1 ] NEW_LINE arr [ j + 1 ] = temp NEW_LINE j = - 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT return arr NEW_LINE DEDENT geeks = " GEEKSFORGEEKS " NEW_LINE n = len ( geeks ) NEW_LINE arr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = geeks [ i ] NEW_LINE DEDENT print ( " Original β array : β [ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " " ) if ( i + 1 != n ) : print ( " , β " , end = " " ) print ( " ] " ) NEW_LINE DEDENT ansarr = sortArrays ( arr , n ) NEW_LINE print ( " Sorted β array : β [ " , end = " " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ansarr [ i ] , end = " " ) if ( i + 1 != n ) : print ( " , β " , end = " " ) print ( " ] " ) NEW_LINE DEDENT |