text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Find k | Structure to store the start and end point ; Function to find Kth smallest number in a vector of merged intervals ; Traverse merged [ ] to find Kth smallest element using Linear search . ; To combined both type of ranges , overlapping as well as non - overlapping . ; Sorting intervals according to start time ;...
class Interval : NEW_LINE INDENT def __init__ ( self , s , e ) : NEW_LINE INDENT self . s = s NEW_LINE self . e = e NEW_LINE DEDENT DEDENT def kthSmallestNum ( merged : list , k : int ) -> int : NEW_LINE INDENT n = len ( merged ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT if k <= abs ( merged [ j ] . e - merged [ ...
Grouping Countries | Python3 program to count no of distinct countries from a given group of people ; Answer is valid if adjacent sitting num people give same answer ; someone gives different answer ; check next person ; one valid country group has been found ; Driven code
def countCountries ( ans , N ) : NEW_LINE INDENT total_countries = 0 NEW_LINE i = 0 NEW_LINE invalid = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT curr_size = ans [ i ] NEW_LINE num = ans [ i ] NEW_LINE while ( num > 0 ) : NEW_LINE INDENT if ( ans [ i ] != curr_size ) : NEW_LINE INDENT print ( " Invalid ▁ Answer " ) N...
Deepest left leaf node in a binary tree | A binary tree node ; Constructor to create a new node ; A utility function to find deepest leaf node . lvl : level of current node . maxlvl : pointer to the deepest left leaf node found so far isLeft : A bool indicate that this node is left child of its parent resPtr : Pointer ...
class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def deepestLeftLeafUtil ( root , lvl , maxlvl , isLeft ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if ( isLeft is T...
Check if an array contains all elements of a given range | Function to check the array for elements in given range ; Range is the no . of elements that are to be checked ; Traversing the array ; If an element is in range ; Checking whether elements in range 0 - range are negative ; Element from range is missing from ar...
def check_elements ( arr , n , A , B ) : NEW_LINE INDENT rangeV = B - A NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( abs ( arr [ i ] ) >= A and abs ( arr [ i ] ) <= B ) : NEW_LINE INDENT z = abs ( arr [ i ] ) - A NEW_LINE if ( arr [ z ] > 0 ) : NEW_LINE INDENT arr [ z ] = arr [ z ] * - 1 NEW_LINE DEDENT DED...
Recursive Programs to find Minimum and Maximum elements of array | function to print Minimum element using recursion ; if size = 0 means whole array has been traversed ; Driver Code
def findMinRec ( A , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return A [ 0 ] NEW_LINE DEDENT return min ( A [ n - 1 ] , findMinRec ( A , n - 1 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 1 , 4 , 45 , 6 , - 50 , 10 , 2 ] NEW_LINE n = len ( A ) NEW_LINE print ( findMinRec ( A ...
Allocate minimum number of pages | Utility function to check if current minimum value is feasible or not . ; iterate over all books ; check if current number of pages are greater than curr_min that means we will get the result after mid no . of pages ; count how many students are required to distribute curr_min pages ;...
def isPossible ( arr , n , m , curr_min ) : NEW_LINE INDENT studentsRequired = 1 NEW_LINE curr_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > curr_min ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( curr_sum + arr [ i ] > curr_min ) : NEW_LINE INDENT studentsRequired += 1 NEW_LINE curr_s...
Find Minimum Depth of a Binary Tree | Tree node ; Function to calculate the minimum depth of the tree ; Corner Case . Should never be hit unless the code is called on root = NULL ; Base Case : Leaf node . This acoounts for height = 1 ; If left subtree is Null , recur for right subtree ; If right subtree is Null , recur...
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minDepth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if root . left is None and root . right is None ...
Remove an occurrence of most frequent array element exactly K times | Function to print the most frequent array element exactly K times ; Stores frequency array element ; Count frequency of array element ; Maximum array element ; Traverse the Map ; Find the element with maximum frequency ; If the frequency is maximum ,...
def maxFreqElements ( arr , N , K ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if arr [ i ] in mp : NEW_LINE INDENT mp [ arr [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT while ( K > 0 ) : NEW_LINE INDENT Max = 0 NEW_LINE for i in mp : NE...
Maximize difference between maximum and minimum array elements after K operations | Function to find the maximum difference between the maximum and minimum in the array after K operations ; Stores maximum difference between largest and smallest array element ; Sort the array in descending order ; Traverse the array arr...
def maxDiffLargSmallOper ( arr , N , K ) : NEW_LINE INDENT maxDiff = 0 ; NEW_LINE arr . sort ( reverse = True ) ; NEW_LINE for i in range ( min ( K + 1 , N ) ) : NEW_LINE INDENT maxDiff += arr [ i ] ; NEW_LINE DEDENT return maxDiff ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 7 , 7 , ...
Minimize cost to convert all characters of a binary string to 0 s | Function to get the minimum Cost to convert all characters of given string to 0 s ; Stores the range of indexes of characters that need to be flipped ; Stores the number of times current character is flipped ; Stores minimum cost to get the required st...
def minCost ( s , R , C , N ) : NEW_LINE INDENT ch = list ( s ) NEW_LINE pq = [ ] NEW_LINE flip = 0 NEW_LINE cost = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT while ( len ( pq ) > 0 and pq [ 0 ] < i ) : NEW_LINE INDENT pq . pop ( 0 ) ; NEW_LINE flip -= 1 NEW_LINE DEDENT cn = ord ( ch [ i ] ) - ord ( '0' ) NEW_LI...
Find Minimum Depth of a Binary Tree | A Binary Tree node ; Iterative method to find minimum depth of Binary Tree ; Corner Case ; Create an empty queue for level order traversal ; Enqueue root and initialize depth as 1 ; Do level order traversal ; Remove the front queue item ; Get details of the removed item ; If this i...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minDepth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( { ' node ' : roo...
Maximum Manhattan distance between a distinct pair from N coordinates | Function to calculate the maximum Manhattan distance ; List to store maximum and minimum of all the four forms ; Sorting both the vectors ; Driver code ; Given Co - ordinates ; Function call
def MaxDist ( A , N ) : NEW_LINE INDENT V = [ 0 for i in range ( N ) ] NEW_LINE V1 = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT V [ i ] = A [ i ] [ 0 ] + A [ i ] [ 1 ] NEW_LINE V1 [ i ] = A [ i ] [ 0 ] - A [ i ] [ 1 ] NEW_LINE DEDENT V . sort ( ) NEW_LINE V1 . sort ( ) NEW_LINE maximum =...
Maximum distance between two points in coordinate plane using Rotating Caliper 's Method | ; Function calculates distance between two points ; Function to find the maximum distance between any two points ; Iterate over all possible pairs ; Update maxm ; Return actual distance ; Driver Code ; Number of points ; Given p...
from math import sqrt NEW_LINE def dist ( p1 , p2 ) : NEW_LINE INDENT x0 = p1 [ 0 ] - p2 [ 0 ] NEW_LINE y0 = p1 [ 1 ] - p2 [ 1 ] NEW_LINE return x0 * x0 + y0 * y0 NEW_LINE DEDENT def maxDist ( p ) : NEW_LINE INDENT n = len ( p ) NEW_LINE maxm = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , ...
Reorder an array such that sum of left half is not equal to sum of right half | Function to print the required reordering of the array if possible ; Sort the array in increasing order ; If all elements are equal , then it is not possible ; Else print the sorted array arr [ ] ; Driver Code ; Given array ; Function Call
def printArr ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE if ( arr [ 0 ] == arr [ n - 1 ] ) : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Yes " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DED...
Maximize Array sum by swapping at most K elements with another array | Function to find the maximum sum ; If element of array a is smaller than that of array b , swap them . ; Find sum of resultant array ; Driver code
def maximumSum ( a , b , k , n ) : NEW_LINE INDENT a . sort ( ) NEW_LINE b . sort ( ) NEW_LINE i = 0 NEW_LINE j = n - 1 NEW_LINE while i < k : NEW_LINE INDENT if ( a [ i ] < b [ j ] ) : NEW_LINE INDENT a [ i ] , b [ j ] = b [ j ] , a [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE j -...
Maximize distinct elements by incrementing / decrementing an element or keeping it same | Function that Maximize the count of distinct element ; Sort thr list ; Keeping track of previous change ; Decrement is possible ; Remain as it is ; Increment is possible ; Driver Code
def max_dist_ele ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prev < ( arr [ i ] - 1 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE prev = arr [ i ] - 1 NEW_LINE DEDENT elif prev < ( arr [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr...
Find if array can be sorted by swaps limited to multiples of k | CheckSort function To check if array can be sorted ; sortarr is sorted array of arr ; if k = 1 then ( always possible to sort ) swapping can easily give sorted array ; comparing sortarray with array ; element at index j must be in j = i + l * k form where...
def CheckSort ( arr , k , n ) : NEW_LINE INDENT sortarr = sorted ( arr ) NEW_LINE if ( k == 1 ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i , n , k ) : NEW_LINE INDENT if ( sortarr [ i ] == arr [ j ] ) : NEW_L...
Replace node with depth in a binary tree | A tree node structure ; Helper function replaces the data with depth Note : Default value of level is 0 for root . ; Base Case ; Replace data with current depth ; A utility function to prinorder traversal of a Binary Tree ; Driver Code ; Constructing tree given in the above fi...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def replaceNode ( node , level = 0 ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT node . data = level NEW_LINE replaceNode...
Product of minimum edge weight between all pairs of a Tree | Python3 implementation of the approach ; Function to return ( x ^ y ) mod p ; Declaring size array globally ; Initializing DSU data structure ; Function to find the root of ith node in the disjoint set ; Weighted union using Path Compression ; size of set A i...
mod = 1000000007 NEW_LINE def power ( x : int , y : int , p : int ) -> int : NEW_LINE INDENT res = 1 NEW_LINE x %= p NEW_LINE while y > 0 : NEW_LINE INDENT if y & 1 : NEW_LINE INDENT res = ( res * x ) % p NEW_LINE DEDENT y = y // 2 NEW_LINE x = ( x * x ) % p NEW_LINE DEDENT return res NEW_LINE DEDENT size = [ 0 ] * 300...
Check whether an array can be made strictly decreasing by modifying at most one element | Function that returns true if the array can be made strictly decreasing with at most one change ; To store the number of modifications required to make the array strictly decreasing ; Check whether the last element needs to be mod...
def check ( arr , n ) : NEW_LINE INDENT modify = 0 NEW_LINE if ( arr [ n - 1 ] >= arr [ n - 2 ] ) : NEW_LINE INDENT arr [ n - 1 ] = arr [ n - 2 ] - 1 NEW_LINE modify += 1 NEW_LINE DEDENT if ( arr [ 0 ] <= arr [ 1 ] ) : NEW_LINE INDENT arr [ 0 ] = arr [ 1 ] + 1 NEW_LINE modify += 1 NEW_LINE DEDENT for i in range ( n - 2...
Maximal Disjoint Intervals | Function to find maximal disjoint set ; sort the list of intervals ; First interval will always be included in set ; End point of first interval ; Check if given interval overlap with previously included interval , if not then include this interval and update the end point of last added int...
def maxDisjointIntervals ( list_ ) : NEW_LINE INDENT list_ . sort ( key = lambda x : x [ 1 ] ) NEW_LINE print ( " [ " , list_ [ 0 ] [ 0 ] , " , ▁ " , list_ [ 0 ] [ 1 ] , " ] " ) NEW_LINE r1 = list_ [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , len ( list_ ) ) : NEW_LINE INDENT l1 = list_ [ i ] [ 0 ] NEW_LINE r2 = list_ [ i...
Print k different sorted permutations of a given array | Utility function to print the original indices of the elements of the array ; Function to print the required permutations ; To keep track of original indices ; Sort the array ; Count the number of swaps that can be made ; Cannot generate 3 permutations ; Print th...
def printIndices ( n , a ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] [ 1 ] , end = " ▁ " ) NEW_LINE DEDENT print ( " " , ▁ end = " " ) NEW_LINE DEDENT def printPermutations ( n , a , k ) : NEW_LINE INDENT arr = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE IN...
Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; Get width of each level and compare the width with maximum width so far ; Get width of a given level ; Compute the " height " of a tree -- the number of nodes along the longest path from the root node down to the ...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT maxWidth = 0 NEW_LINE h = height ( root ) NEW_LINE for i in range ( 1 , h + 1 ) : NEW_LINE INDENT widt...
Divide N segments into two non | Function to print the answer if it exists using the concept of merge overlapping segments ; Sort the indices based on their corresponding value in V ; Resultant array Initialise all the values in resultant array with '2' except the first index of ' indices ' which is initialised as '1' ...
def printAnswer ( v , n ) : NEW_LINE INDENT indices = list ( range ( n ) ) NEW_LINE indices . sort ( key = lambda i : v [ i ] ) NEW_LINE res = [ 2 ] * n NEW_LINE res [ indices [ 0 ] ] = 1 NEW_LINE maxR = v [ indices [ 0 ] ] [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if maxR >= v [ indices [ i ] ] [ 0 ] :...
Count distinct elements in an array | This function prints all distinct elements ; Creates an empty hashset ; Traverse the input array ; If not present , then put it in hashtable and increment result ; Driver code
def countDistinct ( arr , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE res = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] not in s ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE res += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT arr = [ 6 , 10 , 5 , 4 , 9 , 120 , 4 , 6 , 10 ] NEW_LINE n = ...
In | Python3 program for the above approach ; Calculating next gap ; Function for swapping ; Merging the subarrays using shell sorting Time Complexity : O ( nlog n ) Space Complexity : O ( 1 ) ; merge sort makes log n recursive calls and each time calls merge ( ) which takes nlog n steps Time Complexity : O ( n * log n...
import math NEW_LINE def nextGap ( gap ) : NEW_LINE INDENT if gap <= 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT return int ( math . ceil ( gap / 2 ) ) NEW_LINE DEDENT def swap ( nums , i , j ) : NEW_LINE INDENT temp = nums [ i ] NEW_LINE nums [ i ] = nums [ j ] NEW_LINE nums [ j ] = temp NEW_LINE DEDENT def inPlaceMe...
Rearrange an array to maximize i * arr [ i ] | Function to calculate the maximum points earned by making an optimal selection on the given array ; Sorting the array ; Variable to store the total points earned ; Driver Code
def findOptimalSolution ( a , N ) : NEW_LINE INDENT a . sort ( ) NEW_LINE points = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT points += a [ i ] * i NEW_LINE DEDENT return points NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 1 , 4 , 2 , 3 , 9 ] NEW_LINE N = len ( a ) NEW_LINE print (...
Minimum number of towers required such that every house is in the range of at least one tower | Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is...
def number_of_tower ( house , r , n ) : NEW_LINE INDENT house . sort ( ) NEW_LINE numOfTower = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT numOfTower += 1 NEW_LINE loc = house [ i ] + r NEW_LINE while ( i < n and house [ i ] <= loc ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE loc = house [...
Check if the characters of a given string are in alphabetical order | Function that checks whether the string is in alphabetical order or not ; length of the string ; create a character array of the length of the string ; sort the character array ; check if the character array is equal to the string or not ; Driver cod...
def isAlphabaticOrder ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE c = [ s [ i ] for i in range ( len ( s ) ) ] NEW_LINE c . sort ( reverse = False ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( c [ i ] != s [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ ...
Sort first k values in ascending order and remaining n | function to sort the array ; Sort first k elements in ascending order ; Sort remaining n - k elements in descending order ; Our arr contains 8 elements
def printOrder ( arr , n , k ) : NEW_LINE INDENT a = arr [ 0 : k ] ; NEW_LINE a . sort ( ) ; NEW_LINE b = arr [ k : n ] ; NEW_LINE b . sort ( ) ; NEW_LINE b . reverse ( ) ; NEW_LINE return a + b ; NEW_LINE DEDENT arr = [ 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , - 1 ] ; NEW_LINE k = 4 ; NEW_LINE n = len ( arr ) ; NEW_LINE arr = ...
Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; base case ; Initialize result ; Do Level order traversal keeping track of number of nodes at every level ; Get the size of queue when the level order traversal for one level finishes ; Update the maximum node coun...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT maxWidth = 0 NEW_LINE q = [ ] NEW_LINE q . ...
Merging and Sorting Two Unsorted Stacks | Sorts input stack and returns sorted stack . ; pop out the first element ; while temporary stack is not empty and top of stack is greater than temp ; pop from temporary stack and push it to the input stack ; push temp in temporary of stack ; Push contents of both stacks in resu...
def sortStack ( Input ) : NEW_LINE INDENT tmpStack = [ ] NEW_LINE while len ( Input ) != 0 : NEW_LINE INDENT tmp = Input [ - 1 ] NEW_LINE Input . pop ( ) NEW_LINE while len ( tmpStack ) != 0 and tmpStack [ - 1 ] > tmp : NEW_LINE INDENT Input . append ( tmpStack [ - 1 ] ) NEW_LINE tmpStack . pop ( ) NEW_LINE DEDENT tmpS...
Lexicographical concatenation of all substrings of a string | Python Program to create concatenation of all substrings in lexicographic order . ; Creating an array to store substrings ; finding all substrings of string ; Sort all substrings in lexicographic order ; Concatenating all substrings ; Driver code
def lexicographicSubConcat ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE sub_count = ( n * ( n + 1 ) ) // 2 ; NEW_LINE arr = [ 0 ] * sub_count ; NEW_LINE index = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , n - i + 1 ) : NEW_LINE INDENT arr [ index ] = s [ i : i + j ] ; NEW_LINE index += ...
Insertion Sort by Swapping Elements | Iterative python program to sort an array by swapping elements ; Utility function to print a Vector ; Function performs insertion sort on vector V ; Insert V [ i ] into list 0. . i - 1 ; Swap V [ j ] and V [ j - 1 ] ; Decrement j ; Driver Code
import math NEW_LINE def printVector ( V ) : NEW_LINE INDENT for i in V : NEW_LINE INDENT print ( i , end = " ▁ " ) NEW_LINE DEDENT print ( " ▁ " ) NEW_LINE DEDENT def insertionSort ( V ) : NEW_LINE INDENT N = len ( V ) NEW_LINE for i in range ( 1 , N ) : NEW_LINE j = i NEW_LINE while ( j > 0 and V [ j ] < V [ j - 1 ] ...
Program to sort string in descending order | Python program to sort a string in descending order using library function ; Driver code ; function call
def descOrder ( s ) : NEW_LINE INDENT s . sort ( reverse = True ) NEW_LINE str1 = ' ' . join ( s ) NEW_LINE print ( str1 ) NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT s = list ( ' geeksforgeeks ' ) NEW_LINE descOrder ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT
Sort string of characters | Python 3 program to sort a string of characters ; function to print string in sorted order ; Hash array to keep count of characters . Initially count of all charters is initialized to zero . ; Traverse string and increment count of characters ; ' a ' - ' a ' will be 0 , ' b ' - ' a ' will be...
MAX_CHAR = 26 NEW_LINE def sortString ( str ) : NEW_LINE INDENT charCount = [ 0 for i in range ( MAX_CHAR ) ] NEW_LINE for i in range ( 0 , len ( str ) , 1 ) : NEW_LINE INDENT charCount [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT for i in range ( 0 , MAX_CHAR , 1 ) : NEW_LINE INDENT for j in range ( 0 , ...
Smallest element in an array that is repeated exactly ' k ' times . | Python program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] ; Computing frequencies of all elements ; Finding the smallest element with frequency as k ; If frequency of any of the numb...
MAX = 1000 NEW_LINE def findDuplicate ( arr , n , k ) : NEW_LINE INDENT freq = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 1 and arr [ i ] > MAX ) : NEW_LINE INDENT print " Out ▁ of ▁ range " NEW_LINE return - 1 NEW_LINE DEDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT fo...
Find the Sub | Python3 program to find subarray with sum closest to 0 ; Returns subarray with sum closest to 0. ; To consider the case of subarray starting from beginning of the array ; Store prefix sum with index ; Sort on the basis of sum ; Find two consecutive elements with minimum difference ; Update minimum differ...
class prefix : NEW_LINE INDENT def __init__ ( self , sum , index ) : NEW_LINE INDENT self . sum = sum NEW_LINE self . index = index NEW_LINE DEDENT DEDENT def findSubArray ( arr , n ) : NEW_LINE INDENT start , end , min_diff = None , None , float ( ' inf ' ) NEW_LINE pre_sum = [ None ] * ( n + 1 ) NEW_LINE pre_sum [ 0 ...
TimSort | Python3 program to perform basic timSort ; Becomes 1 if any 1 bits are shifted off ; This function sorts array from left index to to right index which is of size atmost RUN ; Merge function merges the sorted runs ; original array is broken in two parts left and right array ; after comparing , we merge those t...
MIN_MERGE = 32 NEW_LINE def calcMinRun ( n ) : NEW_LINE INDENT r = 0 NEW_LINE while n >= MIN_MERGE : NEW_LINE INDENT r |= n & 1 NEW_LINE n >>= 1 NEW_LINE DEDENT return n + r NEW_LINE DEDENT def insertionSort ( arr , left , right ) : NEW_LINE INDENT for i in range ( left + 1 , right + 1 ) : NEW_LINE INDENT j = i NEW_LIN...
Program to print an array in Pendulum Arrangement | Prints pendulam arrangement of arr [ ] ; sorting the elements ; Auxiliary array to store output ; calculating the middle index ; storing the minimum element in the middle i is index for output array and j is for input array . ; adjustment for when no . of elements is ...
def pendulumArrangement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE op = [ 0 ] * n NEW_LINE mid = int ( ( n - 1 ) / 2 ) NEW_LINE j = 1 NEW_LINE i = 1 NEW_LINE op [ mid ] = arr [ 0 ] NEW_LINE for i in range ( 1 , mid + 1 ) : NEW_LINE INDENT op [ mid + i ] = arr [ j ] NEW_LINE j += 1 NEW_LINE op [ mid - i ] = a...
Maximum width of a binary tree | A binary tree node ; Function to get the maximum width of a binary tree ; Create an array that will store count of nodes at each level ; Fill the count array using preorder traversal ; Return the maximum value from count array ; A function that fills count array with count of nodes at e...
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getMaxWidth ( root ) : NEW_LINE INDENT h = height ( root ) NEW_LINE count = [ 0 ] * h NEW_LINE level = 0 NEW_LINE getMaxWidthRecur ( root , c...
Minimize the sum of product of two arrays with permutations allowed | Returns minimum sum of product of two arrays with permutations allowed ; Sort A and B so that minimum and maximum value can easily be fetched . ; Multiplying minimum value of A and maximum value of B ; Driven Program
def minValue ( A , B , n ) : NEW_LINE INDENT A . sort ( ) NEW_LINE B . sort ( ) NEW_LINE result = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT result += ( A [ i ] * B [ n - i - 1 ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT A = [ 3 , 1 , 1 ] NEW_LINE B = [ 6 , 5 , 4 ] NEW_LINE n = len ( A ) NEW_LINE print min...
Count of numbers in range [ L , R ] which can be represented as sum of two perfect powers | Function to find the number of numbers that can be expressed in the form of the sum of two perfect powers ; Stores all possible powers ; Push 1 and 0 in it ; Iterate over all the exponents ; Iterate over all possible numbers ; T...
def TotalPerfectPowerSum ( L , R ) : NEW_LINE INDENT pows = [ ] NEW_LINE pows . append ( 0 ) NEW_LINE pows . append ( 1 ) NEW_LINE for p in range ( 2 , 25 ) : NEW_LINE INDENT num = 2 NEW_LINE while ( ( int ) ( pow ( num , p ) + 0.5 ) <= R ) : NEW_LINE INDENT pows . append ( ( int ) ( pow ( num , p ) + 0.5 ) ) NEW_LINE ...
Minimize absolute difference between sum of subtrees formed after splitting Binary tree into two | Python3 implementation for the above approach ; Structure of Node ; Function to calculate minimum absolute difference of subtrees after splitting the tree into two parts ; Reference variable to store the answer ; Function...
import sys NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . val = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def minAbsDiff ( root ) : NEW_LINE INDENT minDiff = [ 0 ] * ( 1 ) NEW_LINE minDiff [ 0 ] = sys . maxsize NEW_LINE postOrder ( ro...
Vertical width of Binary tree | Set 1 | class to create a new tree node ; get vertical width ; traverse left ; if curr is decrease then get value in minimum ; if curr is increase then get value in maximum ; traverse right ; 1 is added to include root in the width ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def lengthUtil ( root , maximum , minimum , curr = 0 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT lengthUtil ( root . le...
Maximize Array sum after changing sign of any elements for exactly M times | Function to find the maximum sum with M flips ; Declare a priority queue i . e . min heap ; Declare the sum as zero ; Push all elements of the array in it ; Iterate for M times ; Get the top element ; Flip the sign of the top element ; Remove ...
def findMaximumSumWithMflips ( arr , N , M ) : NEW_LINE INDENT pq = [ ] NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT pq . append ( arr [ i ] ) NEW_LINE sum += arr [ i ] NEW_LINE pq . sort ( ) NEW_LINE DEDENT while ( M > 0 ) : NEW_LINE INDENT sum -= pq [ 0 ] NEW_LINE temp = - 1 * pq [ 0 ] NEW_LINE pq...
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | Function to find the minimum number of operations to make all the elements of the array equal ; Store the sum of the array arr [ ] ; Traverse through the array ; If it is not possible to make all array element e...
def miniOperToMakeAllEleEqual ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % n ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT valueAfterDivision = sum // n NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LIN...
Minimum operations to make product of adjacent element pair of prefix sum negative | Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the...
def minOperations ( a ) : NEW_LINE INDENT res = 100000000000 NEW_LINE N = len ( a ) NEW_LINE for r in range ( 0 , 2 ) : NEW_LINE INDENT sum = 0 NEW_LINE ans = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE if ( ( i + r ) % 2 ) : NEW_LINE INDENT if ( sum <= 0 ) : NEW_LINE INDENT ans += - s...
Minimize sum of product of same | Function to print the arrays ; Function to reverse the subarray ; Function to calculate the minimum product of same - indexed elements of two given arrays ; Calculate initial product ; Traverse all odd length subarrays ; Remove the previous product ; Add the current product ; Check if ...
def Print ( a , b ) : NEW_LINE INDENT minProd = 0 NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) ; NEW_LINE for i in range ( len ( b ) ) : NEW_LINE INDENT print ( b [ i ] , end = " ▁ " ) NEW_LINE minProd += a [ i ] * b [ i ] NEW_LINE DEDENT print ( ) NE...
Maximize cost of removing all occurrences of substrings " ab " and " ba " | Function to find the maximum cost of removing substrings " ab " and " ba " from S ; MaxStr is the substring char array with larger cost ; MinStr is the substring char array with smaller cost ; ; Denotes larger point ; Denotes smaller point ; St...
def MaxCollection ( S , P , Q ) : NEW_LINE INDENT maxstr = [ i for i in ( " ab " if P >= Q else " ba " ) ] NEW_LINE minstr = [ i for i in ( " ba " if P >= Q else " ab " ) ] NEW_LINE maxp = max ( P , Q ) NEW_LINE minp = min ( P , Q ) NEW_LINE cost = 0 NEW_LINE stack1 = [ ] NEW_LINE s = [ i for i in S ] NEW_LINE for ch i...
Vertical width of Binary tree | Set 2 | A binary tree node has data , pointer to left child and a pointer to right child ; Function to fill hd in set . ; Third parameter is horizontal distance ; Driver Code ; Creating the above tree
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def fillSet ( root , s , hd ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT fillSet ( root . left , s , hd - 1 ) NEW_LINE s . add ...
Maximum value of ( arr [ i ] * arr [ j ] ) + ( arr [ j ] | Function to find the value of the expression a * b + ( b - a ) ; Function to find the maximum value of the expression a * b + ( b - a ) possible for any pair ( a , b ) ; Sort the vector in ascending order ; Stores the maximum value ; Update ans by choosing the ...
def calc ( a , b ) : NEW_LINE INDENT return a * b + ( b - a ) NEW_LINE DEDENT def findMaximum ( arr , N ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE ans = - 10 ** 9 NEW_LINE ans = max ( ans , calc ( arr [ 0 ] , arr [ 1 ] ) ) NEW_LINE ans = max ( ans , calc ( arr [ N - 2 ] , arr [ N - 1 ] ) ) NEW_LINE return ans NE...
Minimize flips on K | ; Store previous flip events ; Remove an item which is out range of window . ; In a window , if A [ i ] is a even number with even times fliped , it need to be fliped again . On other hand , if A [ i ] is a odd number with odd times fliped , it need to be fliped again . ; Insert ; Driver code
def minKBitFlips ( A , K , N ) : NEW_LINE INDENT flip = [ ] NEW_LINE count = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( len ( flip ) > 0 and ( i - flip [ 0 ] >= K ) ) : NEW_LINE INDENT flip . pop ( 0 ) NEW_LINE DEDENT if ( A [ i ] % 2 == len ( flip ) % 2 ) : NEW_LINE INDENT if ( i + K - 1 >= N ) : NEW_LINE ...
Minimize flips on K | ; We 're flipping the subarray from A[i] to A[i+K-1] ; ' ' ▁ If ▁ we ▁ can ' t flip the entire subarray , its impossible ; Driver Code
def minKBitFlips ( A , K ) : NEW_LINE INDENT temp = [ 0 ] * len ( A ) NEW_LINE count = 0 NEW_LINE flip = 0 NEW_LINE for i in range ( len ( A ) ) : NEW_LINE INDENT flip ^= temp [ i ] NEW_LINE if ( A [ i ] == flip ) : NEW_LINE INDENT count += 1 NEW_LINE if ( i + K > len ( A ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDEN...
Generate an N | Function to calculate GCD of given array ; Function to calculate GCD of two integers ; Utility function to check for all the combinations ; If a sequence of size N is obtained ; If gcd of current combination is K ; If current element from first array is divisible by K ; Recursively proceed further ; If ...
def GCDArr ( a ) : NEW_LINE INDENT ans = a [ 0 ] NEW_LINE for i in a : NEW_LINE INDENT ans = GCD ( ans , i ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def GCD ( a , b ) : NEW_LINE INDENT if not b : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def findSubseqUtil ( a , b , ans , k , ...
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order | Function to find the K - th element in the required permutation ; Stores the required permutation ; Insert all the even numbers less than or equal to N ; Now , insert all odd numbers less than o...
def findKthElement ( N , K ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT for i in range ( 1 , N + 1 ) : NEW_LINE INDENT if ( i % 2 != 0 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT DEDENT print ( v ...
Minimum subsequences of a string A required to be appended to obtain the string B | Python3 program for the above approach ; Function to count the minimum subsequences of a A required to be appended to obtain the B ; Size of the string ; Maps characters to their respective indices ; Insert indices of characters into th...
from bisect import bisect_right NEW_LINE def countminOpsToConstructAString ( A , B ) : NEW_LINE INDENT N = len ( A ) NEW_LINE i = 0 NEW_LINE mp = [ [ ] for i in range ( 26 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ ord ( A [ i ] ) - ord ( ' a ' ) ] . append ( i ) NEW_LINE DEDENT previous = - 1 NEW_LINE an...
Maximize difference between odd and even indexed array elements by shift operations | Function to minimize array elements by shift operations ; For checking all the left shift operations ; Left shift ; Consider the minimum possible value ; Function to maximize array elements by shift operations ; For checking all the l...
def minimize ( n ) : NEW_LINE INDENT optEle = n NEW_LINE strEle = str ( n ) NEW_LINE for idx in range ( len ( strEle ) ) : NEW_LINE INDENT temp = int ( strEle [ idx : ] + strEle [ : idx ] ) NEW_LINE optEle = min ( optEle , temp ) NEW_LINE DEDENT return optEle NEW_LINE DEDENT def maximize ( n ) : NEW_LINE INDENT optEle ...
Find if given vertical level of binary tree is sorted or not | Python program to determine whether vertical level l of binary tree is sorted or not . ; Structure of a tree node . ; Helper function to determine if vertical level l of given binary tree is sorted or not . ; If root is null , then the answer is an empty su...
from collections import deque NEW_LINE from sys import maxsize NEW_LINE INT_MIN = - maxsize NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def isSorted ( root : Node , level : int ) -> b...
Minimize operations of removing 2 i | Function to find minimum count of steps required to remove all the array elements ; Stores minimum count of steps required to remove all the array elements ; Update N ; Traverse each bit of N ; If current bit is set ; Update cntStep ; Driver Code
def minimumStepReqArr ( arr , N ) : NEW_LINE INDENT cntStep = 0 NEW_LINE N += 1 NEW_LINE i = 31 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( N & ( 1 << i ) ) : NEW_LINE INDENT cntStep += 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT return cntStep NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [...
Minimize removal of alternating subsequences to empty given Binary String | Function to find the minimum number of operations required to empty the string ; Initialize variables ; Traverse the string ; If current character is 0 ; Update maximum consecutive 0 s and 1 s ; Print the minimum operation ; Driver code + ; inp...
def minOpsToEmptyString ( S , N ) : NEW_LINE INDENT one = 0 NEW_LINE zero = 0 NEW_LINE x0 = 0 NEW_LINE x1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '0' ) : NEW_LINE INDENT x0 += 1 NEW_LINE x1 = 0 NEW_LINE DEDENT else : NEW_LINE INDENT x1 += 1 NEW_LINE x0 = 0 NEW_LINE DEDENT zero = max ( x0 , z...
Swap upper and lower triangular halves of a given Matrix | Function to swap laterally inverted images of upper and lower triangular halves of a given matrix ; Store the matrix elements from upper & lower triangular halves ; Traverse the matrix mat [ ] [ ] ; Find the index ; If current element lies on the principal diag...
def ReverseSwap ( mat , n ) : NEW_LINE INDENT lowerEle = [ [ ] for i in range ( n ) ] NEW_LINE upperEle = [ [ ] for i in range ( n ) ] NEW_LINE index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT index = abs ( i - j ) NEW_LINE if ( i == j ) : NEW_LINE INDENT continue NEW_LIN...
Minimize sum of K positive integers with given LCM | Function to find the prime power of X ; Stores prime powers of X ; Iterate over the range [ 2 , sqrt ( X ) ] ; If X is divisible by i ; Stores prime power ; Calculate prime power of X ; Update X ; Update p ; Insert prime powers into primePow [ ] ; If X exceeds 1 ; Fu...
def primePower ( X ) : NEW_LINE INDENT primePow = [ ] NEW_LINE for i in range ( 2 , X + 1 ) : NEW_LINE INDENT if i * i > X + 1 : NEW_LINE INDENT break NEW_LINE DEDENT if ( X % i == 0 ) : NEW_LINE INDENT p = 1 NEW_LINE while ( X % i == 0 ) : NEW_LINE INDENT X //= i NEW_LINE p *= i NEW_LINE DEDENT primePow . append ( p )...
Minimum removal of subsequences of distinct consecutive characters required to empty a given string | Function to count minimum operations required to make the string an empty string ; Stores count of 1 s by removing consecutive distinct subsequence ; Stores count of 0 s by removing consecutive distinct subsequence ; T...
def findMinOperationsReqEmpStr ( str ) : NEW_LINE INDENT cntOne = 0 NEW_LINE cntZero = 0 NEW_LINE for element in str : NEW_LINE INDENT if element == '0' : NEW_LINE INDENT if cntOne > 0 : NEW_LINE INDENT cntOne = cntOne - 1 NEW_LINE DEDENT cntZero = cntZero + 1 NEW_LINE DEDENT else : NEW_LINE INDENT if cntZero > 0 : NEW...
Minimum number of flips required such that the last cell of matrix can be reached from any other cell | Function to calculate the minimum number of flips required ; Dimensions of mat [ ] [ ] ; Initialize answer ; Count all ' D ' s in the last row ; Count all ' R ' s in the last column ; Print answer ; Given matrix ; Fu...
def countChanges ( mat ) : NEW_LINE INDENT n = len ( mat ) NEW_LINE m = len ( mat [ 0 ] ) NEW_LINE ans = 0 NEW_LINE for j in range ( m - 1 ) : NEW_LINE INDENT if ( mat [ n - 1 ] [ j ] != ' R ' ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( mat [ i ] [ m - 1 ] != ' D ...
Check if a binary tree is sorted level | Python3 program to determine whether binary tree is level sorted or not . ; Function to create new tree node . ; Function to determine if given binary tree is level sorted or not . ; to store maximum value of previous level . ; to store minimum value of current level . ; to stor...
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def isSorted ( root ) : NEW_LINE INDENT prevMax = - 999999999999 NEW_LINE minval = None NEW_LINE maxval = None NEW_LINE levelS...
Smallest subsequence having GCD equal to GCD of given array | Python3 program to implement the above approach ; Function to print the smallest subsequence that satisfies the condition ; Stores gcd of the array . ; Traverse the given array ; Update gcdArr ; Traverse the given array . ; If current element equal to gcd of...
import math NEW_LINE def printSmallSub ( arr , N ) : NEW_LINE INDENT gcdArr = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT gcdArr = math . gcd ( gcdArr , arr [ i ] ) NEW_LINE DEDENT for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] == gcdArr ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LIN...
Count pairs in an array whose product is composite number | Python3 program to implement the above approach ; Function to get all the prime numbers in the range [ 1 , X ] ; Stores the boolean value to check if a number is prime or not ; Mark all non prime numbers as false ; If i is prime number ; Mark j as a composite ...
X = 1000000 NEW_LINE def getPrimeNum ( ) : NEW_LINE INDENT isPrime = [ True ] * ( X ) NEW_LINE isPrime [ 0 ] = False NEW_LINE isPrime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i <= X : NEW_LINE INDENT if ( isPrime [ i ] == True ) : NEW_LINE INDENT for j in range ( i * i , X , i ) : NEW_LINE INDENT isPrime [ j ] =...
Find the greater number closest to N having at most one non | Python3 program to implement the above approach ; Function to calculate X ^ n in log ( n ) ; Stores the value of X ^ n ; If N is odd ; Function to find the closest number > N having at most 1 non - zero digit ; Stores the count of digits in N ; Stores the po...
import math NEW_LINE def power ( X , n ) : NEW_LINE INDENT res = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT if ( n & 1 != 0 ) : NEW_LINE INDENT res = res * X NEW_LINE DEDENT X = X * X NEW_LINE n = n >> 1 NEW_LINE DEDENT return res NEW_LINE DEDENT def closestgtNum ( N ) : NEW_LINE INDENT n = int ( math . log10 ( N ) ...
Rearrange an array to make similar indexed elements different from that of another array | Function to find the arrangement of array B [ ] such that element at each index of A [ ] and B [ ] are not equal ; Length of array ; Print not possible , if arrays only have single equal element ; Reverse array B ; Traverse over ...
def RearrangeB ( A , B ) : NEW_LINE INDENT n = len ( A ) NEW_LINE if ( n == 1 and A [ 0 ] == B [ 0 ] ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT for i in range ( n // 2 ) : NEW_LINE INDENT t = B [ i ] NEW_LINE B [ i ] = B [ n - i - 1 ] NEW_LINE B [ n - i - 1 ] = t NEW_LINE DEDENT for i in range ( ...
Swap the elements between any two given quadrants of a Matrix | Python3 program for the above approach ; Function to iterate over the X quadrant and swap its element with Y quadrant ; Iterate over X quadrant ; Swap operations ; Function to swap the elements of the two given quadrants ; For Swapping 1 st and 2 nd Quadra...
N , M = 6 , 6 NEW_LINE def swap ( mat , startx_X , starty_X , startx_Y , starty_Y ) : NEW_LINE INDENT row , col = 0 , 0 NEW_LINE i = startx_X NEW_LINE while ( bool ( True ) ) : NEW_LINE INDENT col = 0 NEW_LINE j = startx_X NEW_LINE while ( bool ( True ) ) : NEW_LINE INDENT temp = mat [ i ] [ j ] NEW_LINE mat [ i ] [ j ...
Bottom View of a Binary Tree | Tree node class ; Constructor of tree node ; Method that prints the bottom view . ; Initialize a variable ' hd ' with 0 for the root element . ; TreeMap which stores key value pair sorted on key value ; Queue to store tree nodes in level order traversal ; Assign initialized horizontal dis...
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . hd = 1000000 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def bottomView ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT hd = 0 NEW_LINE...
Minimum increments by index value required to obtain at least two equal Array elements | Function to calculate the minimum number of steps required ; Stores minimum difference ; Driver Code
def incrementCount ( arr , N ) : NEW_LINE INDENT mini = arr [ 0 ] - arr [ 1 ] NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT mini = min ( mini , arr [ i - 1 ] - arr [ i ] ) NEW_LINE DEDENT print ( mini ) NEW_LINE DEDENT N = 3 NEW_LINE arr = [ 12 , 8 , 4 ] NEW_LINE incrementCount ( arr , N ) NEW_LINE
Minimum operations required to convert all characters of a String to a given Character | Function to find the minimum number of operations required ; Maximum number of characters that can be changed in one operation ; If length of the less than maximum number of characters that can be changed in an operation ; Set the ...
def countOperations ( n , k ) : NEW_LINE INDENT div = 2 * k + 1 NEW_LINE if ( n // 2 <= k ) : NEW_LINE INDENT print ( 1 ) NEW_LINE if ( n > k ) : NEW_LINE INDENT print ( k + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( n ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( n % div == 0 ) : NEW_LINE INDENT oprn = ...
Length of largest subsequence consisting of a pair of alternating digits | Function to find the length of the largest subsequence consisting of a pair of alternating digits ; Variable initialization ; Nested loops for iteration ; Check if i is not equal to j ; Initialize length as 0 ; Iterate from 0 till the size of th...
def largestSubsequence ( s ) : NEW_LINE INDENT maxi = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_LINE INDENT if ( i != j ) : NEW_LINE INDENT lenn = 0 NEW_LINE prev1 = chr ( j + ord ( '0' ) ) NEW_LINE for k in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ k ] == chr ( i + ord ( '0' )...
Bottom View of a Binary Tree | Tree node class ; Constructor of tree node ; printBottomViewUtil function ; Base case ; If current level is more than or equal to maximum level seen so far for the same horizontal distance or horizontal distance is seen for the first time , update the dictionary ; recur for left subtree b...
class Node : NEW_LINE INDENT def __init__ ( self , key = None , left = None , right = None ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = left NEW_LINE self . right = right NEW_LINE DEDENT DEDENT def printBottomViewUtil ( root , d , hd , level ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return N...
Find maximum GCD value from root to leaf in a Binary tree | Initialise to update the maximum gcd value from all the path ; Node structure ; Initialize constructor ; Function to find gcd of a and b ; Function to find the gcd of a path ; Function to find the maximum value of gcd from root to leaf in a Binary tree ; Check...
global maxm NEW_LINE maxm = 0 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . val = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a %...
Count of pairs with sum N from first N natural numbers | Funciton to calculate the value of count ; Stores the count of pairs ; Set the two pointers ; Check if the sum of pirs is equal to n ; Increase the count of pairs ; Move to the next pair ; Driver code
def numberOfPairs ( n ) : NEW_LINE INDENT count = 0 NEW_LINE i = 1 NEW_LINE j = n - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( i + j ) == n : NEW_LINE count += 1 NEW_LINE i += 1 NEW_LINE j -= 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 NEW_LINE print ( n...
Count of ways to generate a Matrix with product of each row and column as 1 or | Function to return the number of possible ways ; Check if product can be - 1 ; driver code
def Solve ( N , M ) : NEW_LINE INDENT temp = ( N - 1 ) * ( M - 1 ) NEW_LINE ans = pow ( 2 , temp ) NEW_LINE if ( ( N + M ) % 2 != 0 ) : NEW_LINE INDENT print ( ans ) NEW_LINE else : NEW_LINE print ( 2 * ans ) NEW_LINE if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N , M = 3 , 3 NEW_LINE Solve ( N , M ) NEW_LINE DEDE...
Maximum number of bridges in a path of a given graph | Python3 program to find the maximum number of bridges in any path of the given graph ; Stores the nodes and their connections ; Store the tree with Bridges as the edges ; Stores the visited nodes ; For finding bridges ; for Disjoint Set Union ; For storing actual b...
N = 100005 NEW_LINE v = [ ] NEW_LINE g = [ ] NEW_LINE vis = [ False ] * ( N ) NEW_LINE In = [ 0 ] * ( N ) NEW_LINE low = [ 0 ] * ( N ) NEW_LINE parent = [ 0 ] * ( N ) NEW_LINE rnk = [ 0 ] * ( N ) NEW_LINE bridges = [ ] NEW_LINE n , m = 6 , 6 NEW_LINE timer = 0 NEW_LINE diameter = 0 NEW_LINE def swap ( x , y ) : NEW_LIN...
Program to count leaf nodes in a binary tree | A Binary tree node ; Function to get the count of leaf nodes in binary tree ; create a tree ; get leaf count of the abve tree
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getLeafCount ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . left is None and node . right ...
Make a palindromic string from given string | Function to find winner of the game ; Array to Maintain frequency of the characters in S initialise freq array with 0 ; Maintain count of all distinct characters ; Finding frequency of each character ; Count unique duplicate characters ; Loop to count the unique duplicate c...
def palindromeWinner ( S ) : NEW_LINE INDENT freq = [ 0 for i in range ( 0 , 26 ) ] NEW_LINE count = 0 NEW_LINE for i in range ( 0 , len ( S ) ) : NEW_LINE INDENT if ( freq [ ord ( S [ i ] ) - 97 ] == 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT freq [ ord ( S [ i ] ) - 97 ] += 1 NEW_LINE DEDENT unique = 0 NEW_LINE...
Number of substrings with length divisible by the number of 1 's in it | Python3 program to count number of substring under given condition ; Function return count of such substring ; Selection of adequate x value ; Store where 1 's are located ; If there are no ones , then answer is 0 ; For ease of implementation ; Co...
import math NEW_LINE def countOfSubstrings ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE x = int ( math . sqrt ( n ) ) NEW_LINE ones = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT ones . append ( i ) NEW_LINE DEDENT DEDENT if ( len ( ones ) == 0 ) : NEW_LINE INDENT return...
Find the largest number smaller than integer N with maximum number of set bits | Function to return the largest number less than N ; Iterate through all the numbers ; Find the number of set bits for the current number ; Check if this number has the highest set bits ; Return the result ; Driver code
def largestNum ( n ) : NEW_LINE INDENT num = 0 ; NEW_LINE max_setBits = 0 ; NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT setBits = bin ( i ) . count ( '1' ) ; NEW_LINE if ( setBits >= max_setBits ) : NEW_LINE INDENT num = i ; NEW_LINE max_setBits = setBits ; NEW_LINE DEDENT DEDENT return num ; NEW_LINE DEDENT if...
Iterative program to count leaf nodes in a Binary Tree | Python3 program to count leaf nodes in a Binary Tree ; Helper function that allocates a new Node with the given data and None left and right pointers . ; Function to get the count of leaf Nodes in a binary tree ; If tree is empty ; Initialize empty queue . ; Do l...
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def getLeafCount ( node ) : NEW_LINE INDENT if ( not node ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = Queue ( ) NEW_LI...
Find the Kth smallest element in the sorted generated array | Function to return the Kth element in B [ ] ; Initialize the count Array ; Reduce N repeatedly to half its value ; Add count to start ; Subtract same count after end index ; Store each element of Array [ ] with their count ; Sort the elements wrt value ; If ...
def solve ( Array , N , K ) : NEW_LINE INDENT count_Arr = [ 0 ] * ( N + 2 ) ; NEW_LINE factor = 1 ; NEW_LINE size = N ; NEW_LINE while ( size ) : NEW_LINE INDENT start = 1 ; NEW_LINE end = size ; NEW_LINE count_Arr [ 1 ] += factor * N ; NEW_LINE count_Arr [ end + 1 ] -= factor * N ; NEW_LINE factor += 1 ; NEW_LINE size...
Maximum number that can be display on Seven Segment Display using N segments | Function to print maximum number that can be formed using N segments ; If n is odd ; use 3 three segment to print 7 ; remaining to print 1 ; If n is even ; print n / 2 1 s . ; Driver 's Code
def printMaxNumber ( n ) : NEW_LINE INDENT if ( n % 2 == 1 ) : NEW_LINE INDENT print ( "7" , end = " " ) ; NEW_LINE for i in range ( int ( ( n - 3 ) / 2 ) ) : NEW_LINE INDENT print ( "1" , end = " " ) ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( n / 2 ) : NEW_LINE INDENT print ( "1" , end = " " ) ; ...
Find the sum of digits of a number at even and odd places | Function to find the sum of the odd and even positioned digits in a number ; To store the respective sums ; Converting integer to string ; Traversing the string ; Driver code
def getSum ( n ) : NEW_LINE INDENT sumOdd = 0 NEW_LINE sumEven = 0 NEW_LINE num = str ( n ) NEW_LINE for i in range ( len ( num ) ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT sumOdd = sumOdd + int ( num [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT sumEven = sumEven + int ( num [ i ] ) NEW_LINE DEDENT DEDEN...
Iterative program to count leaf nodes in a Binary Tree | Node class ; Program to count leaves ; If the node itself is " None " return 0 , as there are no leaves ; It the node is a leaf then both right and left children will be " None " ; Now we count the leaves in the left and right subtrees and return the sum ; Driver...
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def countLeaves ( node ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . left == None and node . right == ...
Partition an array such into maximum increasing segments | Python 3 program to divide into maximum number of segments ; Returns the maximum number of sorted subarrays in a valid partition ; Find minimum value from right for every index ; Finding the shortest prefix such that all the elements in the prefix are less than...
import sys NEW_LINE def sorted_partitions ( arr , n ) : NEW_LINE INDENT right_min = [ 0 ] * ( n + 1 ) NEW_LINE right_min [ n ] = sys . maxsize NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT right_min [ i ] = min ( right_min [ i + 1 ] , arr [ i ] ) NEW_LINE DEDENT partitions = 0 NEW_LINE current_max = a...
Minimize Cost with Replacement with other allowed | Function returns the minimum cost of the array ; Driver Code
def getMinCost ( arr , n ) : NEW_LINE INDENT min_ele = min ( arr ) NEW_LINE return min_ele * ( n - 1 ) NEW_LINE DEDENT arr = [ 4 , 2 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( getMinCost ( arr , n ) ) NEW_LINE
Minimum swaps required to make a binary string alternating | function to count minimum swaps required to make binary String alternating ; stores total number of ones ; stores total number of zeroes ; checking impossible condition ; odd length string ; number of even positions ; stores number of zeroes and ones at even ...
def countMinSwaps ( s ) : NEW_LINE INDENT N = len ( s ) NEW_LINE one = 0 NEW_LINE zero = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT one += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zero += 1 NEW_LINE DEDENT DEDENT if ( one > zero + 1 or zero > one + 1 ) : NEW_LINE INDENT re...
Check if it is possible to return to the starting position after moving in the given directions | Main method ; n = 0 Count of North s = 0 Count of South e = 0 Count of East w = 0 Count of West
st = " NNNWEWESSS " NEW_LINE length = len ( st ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( st [ i ] == " N " ) : NEW_LINE INDENT n += 1 NEW_LINE DEDENT if ( st [ i ] == " S " ) : NEW_LINE INDENT s += 1 NEW_LINE DEDENT if ( st [ i ] == " W " ) : NEW_LINE INDENT w += 1 NEW_LINE DEDENT if ( st [ i ] == " E...
Minimum cost to make array size 1 by removing larger of pairs | function to calculate the minimum cost ; Minimum cost is n - 1 multiplied with minimum element . ; driver code
def cost ( a , n ) : NEW_LINE INDENT return ( ( n - 1 ) * min ( a ) ) NEW_LINE DEDENT a = [ 4 , 3 , 2 ] NEW_LINE n = len ( a ) NEW_LINE print ( cost ( a , n ) ) NEW_LINE
Count Non | class that allocates a new node with the given data and None left and right pointers . ; Computes the number of non - leaf nodes in a tree . ; Base cases . ; If root is Not None and its one of its child is also not None ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def countNonleaf ( root ) : NEW_LINE INDENT if ( root == None or ( root . left == None and root . right == None ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDE...
Minimum cost for acquiring all coins with k extra coins allowed with every coin | Python3 program to acquire all n coins ; function to calculate min cost ; sort the coins value ; calculate no . of coins needed ; calculate sum of all selected coins ; Driver code
import math NEW_LINE def minCost ( coin , n , k ) : NEW_LINE INDENT coin . sort ( ) NEW_LINE coins_needed = math . ceil ( 1.0 * n // ( k + 1 ) ) ; NEW_LINE ans = 0 NEW_LINE for i in range ( coins_needed - 1 + 1 ) : NEW_LINE INDENT ans += coin [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT coin = [ 8 , 5 , 3 , 10 , 2 ...
Program for First Fit algorithm in Memory Management | Function to allocate memory to blocks as per First fit algorithm ; Stores block id of the block allocated to a process ; pick each process and find suitable blocks according to its size ad assign to it ; allocate block j to p [ i ] process ; Reduce available memory...
def firstFit ( blockSize , m , processSize , n ) : NEW_LINE INDENT allocation = [ - 1 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if blockSize [ j ] >= processSize [ i ] : NEW_LINE INDENT allocation [ i ] = j NEW_LINE blockSize [ j ] -= processSize [ i ] NEW_LINE break N...
Greedy Algorithm to find Minimum number of Coins | Python3 program to find minimum number of denominations ; All denominations of Indian Currency ; Initialize Result ; Traverse through all denomination ; Find denominations ; Print result ; Driver Code
def findMin ( V ) : NEW_LINE INDENT deno = [ 1 , 2 , 5 , 10 , 20 , 50 , 100 , 500 , 1000 ] NEW_LINE n = len ( deno ) NEW_LINE ans = [ ] NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT while ( V >= deno [ i ] ) : NEW_LINE INDENT V -= deno [ i ] NEW_LINE ans . append ( deno [ i ] ) NEW_LINE DEDENT i -= 1 N...
Minimize count of array elements to be removed such that at least K elements are equal to their index values | Function to minimize the removals of array elements such that atleast K elements are equal to their indices ; Store the array as 1 - based indexing Copy of first array ; Make a dp - table of ( N * N ) size ; D...
def MinimumRemovals ( a , N , K ) : NEW_LINE INDENT b = [ 0 for i in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT b [ i + 1 ] = a [ i ] NEW_LINE DEDENT dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LIN...
Count of Arrays of size N having absolute difference between adjacent elements at most 1 | Function to find the count of possible arrays such that the absolute difference between any adjacent elements is atmost 1 ; Stores the dp states where dp [ i ] [ j ] represents count of arrays of length i + 1 having their last el...
def countArray ( arr , N , M ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( M + 2 ) ] for j in range ( N ) ] NEW_LINE if ( arr [ 0 ] == - 1 ) : NEW_LINE INDENT for j in range ( 1 , M + 1 , 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] = 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ 0 ] [ arr [ 0 ] ] = 1 NEW_LINE DEDENT ...