text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Check if value exists in level | Python3 implementation of the approach ; Class containing left and right child of current node and key value ; Function to locate which level to check for the existence of key . ; If the key is less than the root , it will certainly not exist in the tree because tree is level - order so... | from sys import maxsize NEW_LINE from collections import deque NEW_LINE INT_MIN = - maxsize NEW_LINE 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 findLevel ( root : Node , data : int ) -... |
Convert given Matrix into sorted Spiral Matrix | Python3 program to Convert given Matrix into sorted Spiral Matrix ; Function to convert the array to Spiral ; For Array pointer ; k - starting row index m - ending row index l - starting column index n - ending column index ; Print the first row from the remaining rows ;... | MAX = 1000 NEW_LINE def ToSpiral ( m , n , Sorted , a ) : NEW_LINE INDENT index = 0 NEW_LINE k = 0 NEW_LINE l = 0 NEW_LINE while ( k < m and l < n ) : NEW_LINE INDENT for i in range ( l , n , 1 ) : NEW_LINE INDENT a [ k ] [ i ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE DEDENT k += 1 NEW_LINE for i in range ( k , ... |
Reversal algorithm for right rotation of an array | Function to reverse arr from index start to end ; Function to right rotate arr of size n by d ; function to pr an array ; Driver code | def reverseArray ( arr , start , end ) : NEW_LINE INDENT while ( start < end ) : NEW_LINE INDENT arr [ start ] , arr [ end ] = arr [ end ] , arr [ start ] NEW_LINE start = start + 1 NEW_LINE end = end - 1 NEW_LINE DEDENT DEDENT def rightRotate ( arr , d , n ) : NEW_LINE INDENT reverseArray ( arr , 0 , n - 1 ) ; NEW_LIN... |
Print the nodes at odd levels of a tree | Iterative Python3 program to prodd level nodes A Binary Tree Node Utility function to create a new tree Node ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue root and initialize level as odd ; no... | 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 ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE isOd... |
Find a rotation with maximum hamming distance | Return the maximum hamming distance of a rotation ; arr [ ] to brr [ ] two times so that we can traverse through all rotations . ; We know hamming distance with 0 rotation would be 0. ; We try other rotations one by one and compute Hamming distance of every rotation ; We ... | def maxHamming ( arr , n ) : NEW_LINE INDENT brr = [ 0 ] * ( 2 * n + 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT brr [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT brr [ n + i ] = arr [ i ] NEW_LINE DEDENT maxHam = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT currHam = 0 NEW_L... |
Print left rotation of array in O ( n ) time and O ( 1 ) space | Function to leftRotate array multiple times ; To get the starting point of rotated array ; Prints the rotated array from start position ; Driver code ; Function Call ; Function Call ; Function Call | def leftRotate ( arr , n , k ) : NEW_LINE INDENT mod = k % n NEW_LINE s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT print str ( arr [ ( mod + i ) % n ] ) , NEW_LINE DEDENT print NEW_LINE return NEW_LINE DEDENT arr = [ 1 , 3 , 5 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE leftRotate ( arr , n , ... |
Minimum Circles needed to be removed so that all remaining circles are non intersecting | Function to return the count of non intersecting circles ; Structure with start and end of diameter of circles ; Sorting with smallest finish time first ; count stores number of circles to be removed ; cur stores ending of first c... | def CountCircles ( c , r , n ) : NEW_LINE INDENT diameter = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT obj = [ ] NEW_LINE obj . append ( c [ i ] - r [ i ] ) NEW_LINE obj . append ( c [ i ] + r [ i ] ) NEW_LINE diameter . append ( obj ) NEW_LINE DEDENT diameter . sort ( ) NEW_LINE count = 0 NEW_LINE cur = diame... |
Print left rotation of array in O ( n ) time and O ( 1 ) space | Python3 implementation to print left rotation of any array K times ; Function For The k Times Left Rotation ; The collections module has deque class which provides the rotate ( ) , which is inbuilt function to allow rotation ; Print the rotated array from... | from collections import deque NEW_LINE def leftRotate ( arr , k , n ) : NEW_LINE INDENT arr = deque ( arr ) NEW_LINE arr . rotate ( - k ) NEW_LINE arr = list ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT... |
Find element at given index after a number of rotations | Function to compute the element at given index ; Range [ left ... right ] ; Rotation will not have any effect ; Returning new element ; Driver Code ; No . of rotations ; Ranges according to 0 - based indexing | def findElement ( arr , ranges , rotations , index ) : NEW_LINE INDENT for i in range ( rotations - 1 , - 1 , - 1 ) : NEW_LINE INDENT left = ranges [ i ] [ 0 ] NEW_LINE right = ranges [ i ] [ 1 ] NEW_LINE if ( left <= index and right >= index ) : NEW_LINE INDENT if ( index == left ) : NEW_LINE INDENT index = right NEW_... |
Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged | Function that returns the string s in sorted form such that the positions of alphabets and numeric digits remain unchanged ; String to character array ; Sort the array ; Count of alphabets and numbers ; Get the index from wh... | def sort ( s ) : NEW_LINE INDENT c , s = list ( s ) , list ( s ) NEW_LINE c . sort ( ) NEW_LINE al_c = 0 NEW_LINE nu_c = 0 NEW_LINE while ord ( c [ al_c ] ) < 97 : NEW_LINE INDENT al_c += 1 NEW_LINE DEDENT for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] < ' a ' : NEW_LINE INDENT s [ i ] = c [ nu_c ] NEW_LINE ... |
Split the array and add the first part to the end | Python program to split array and move first part to end . ; Rotate array by 1. ; main | def splitArr ( arr , n , k ) : NEW_LINE INDENT for i in range ( 0 , k ) : NEW_LINE INDENT x = arr [ 0 ] NEW_LINE for j in range ( 0 , n - 1 ) : NEW_LINE INDENT arr [ j ] = arr [ j + 1 ] NEW_LINE DEDENT arr [ n - 1 ] = x NEW_LINE DEDENT DEDENT arr = [ 12 , 10 , 5 , 6 , 52 , 36 ] NEW_LINE n = len ( arr ) NEW_LINE positio... |
Split the array and add the first part to the end | Function to spilt array and move first part to end ; make a temporary array with double the size and each index is initialized to 0 ; copy array element in to new array twice ; Driver code | def SplitAndAdd ( A , length , rotation ) : NEW_LINE INDENT tmp = [ 0 for i in range ( length * 2 ) ] NEW_LINE for i in range ( length ) : NEW_LINE INDENT tmp [ i ] = A [ i ] NEW_LINE tmp [ i + length ] = A [ i ] NEW_LINE DEDENT for i in range ( rotation , rotation + length , 1 ) : NEW_LINE INDENT A [ i - rotation ] = ... |
Rearrange an array such that arr [ i ] = i | Function to tranform the array ; Iterate over the array ; Check is any ar [ j ] exists such that ar [ j ] is equal to i ; Iterate over array ; If not present ; Print the output ; Driver Code ; Function Call | def fixArray ( ar , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( ar [ j ] == i ) : NEW_LINE INDENT ar [ j ] , ar [ i ] = ar [ i ] , ar [ j ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ar [ i ] != i ) : NEW_LINE INDENT ar [ i ] = ... |
Perform K of Q queries to maximize the sum of the array elements | Function to perform K queries out of Q to maximize the final sum ; Get the initial sum of the array ; Stores the contriution of every query ; Sort the contribution of queries in descending order ; Get the K most contributions ; Driver code | def getFinalSum ( a , n , queries , q , k ) : NEW_LINE INDENT answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT answer += a [ i ] NEW_LINE DEDENT contribution = [ ] NEW_LINE for i in range ( q ) : NEW_LINE INDENT contribution . append ( queries [ i ] [ 1 ] - queries [ i ] [ 0 ] + 1 ) NEW_LINE DEDENT contributi... |
Queries to return the absolute difference between L | Function to return the result for a particular query ; Get the difference between the indices of L - th and the R - th smallest element ; Return the answer ; Function that performs all the queries ; Store the array numbers and their indices ; Sort the array elements... | def answerQuery ( arr , l , r ) : NEW_LINE INDENT answer = abs ( arr [ l - 1 ] [ 1 ] - arr [ r - 1 ] [ 1 ] ) NEW_LINE return answer NEW_LINE DEDENT def solveQueries ( a , n , q , m ) : NEW_LINE INDENT arr = [ [ 0 for i in range ( n ) ] for j in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] [ 0... |
Print all full nodes in a Binary Tree | utility that allocates a newNode with the given key ; Traverses given tree in Inorder fashion and prints all nodes that have both children as non - empty . ; Driver Code | class newNode : 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 findFullNode ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT findFullNode ( root . left ) NEW_LINE if ( root . left != None... |
K | Python3 implementation of the above approach ; Set to store the unique substring ; String to create each substring ; adding to set ; converting set into a list ; sorting the strings int the list into lexicographical order ; printing kth substring ; Driver Code | def kThLexString ( st , k , n ) : NEW_LINE INDENT z = set ( ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT pp = " " NEW_LINE for j in range ( i , i + k ) : NEW_LINE INDENT if ( j >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT pp += s [ j ] NEW_LINE z . add ( pp ) NEW_LINE DEDENT DEDENT fin = list ( z ) NEW_LINE fin ... |
Rearrange array such that arr [ i ] >= arr [ j ] if i is even and arr [ i ] <= arr [ j ] if i is odd and j < i | Python3 code to rearrange the array as per the given condition ; function to rearrange the array ; total even positions ; total odd positions ; copy original array in an auxiliary array ; sort the auxiliary ... | import array as a NEW_LINE import numpy as np NEW_LINE def rearrangeArr ( arr , n ) : NEW_LINE INDENT evenPos = int ( n / 2 ) NEW_LINE oddPos = n - evenPos NEW_LINE tempArr = np . empty ( n , dtype = object ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT tempArr [ i ] = arr [ i ] NEW_LINE DEDENT tempArr . sort ( ... |
Sort only non | Python3 program to sort only non primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to pri... | from math import sqrt NEW_LINE prime = [ 0 ] * 100005 NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT for i in range ( len ( prime ) ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if prime [ p ] == True : NEW_L... |
Sum of all nodes in a binary tree | utility that allocates a new Node with the given key ; Function to find sum of all the element ; Driver Code | class newNode : 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 addBT ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ( root . key + addBT ( root . left ) +... |
Maximum sum of absolute difference of any permutation | ; sort the original array so that we can retrieve the large elements from the end of array elements ; In this loop first we will insert one smallest element not entered till that time in final sequence and then enter a highest element ( not entered till that time... | import numpy as np NEW_LINE class GFG : NEW_LINE INDENT def MaxSumDifference ( a , n ) : NEW_LINE INDENT np . sort ( a ) ; NEW_LINE j = 0 NEW_LINE finalSequence = [ 0 for x in range ( n ) ] NEW_LINE for i in range ( 0 , int ( n / 2 ) ) : NEW_LINE INDENT finalSequence [ j ] = a [ i ] NEW_LINE finalSequence [ j + 1 ] = a... |
Minimum swaps required to bring all elements less than or equal to k together | Utility function to find minimum swaps required to club all elements less than or equals to k together ; Find count of elements which are less than equals to k ; Find unwanted elements in current window of size 'count ; Initialize answer ... | def minSwap ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] <= k ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT DEDENT bad = 0 NEW_LINE for i in range ( 0 , count ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT bad = bad + 1 NEW_LINE DEDEN... |
Rearrange positive and negative numbers using inbuilt sort function | Python3 implementation of the above approach ; Rearrange the array with all negative integers on left and positive integers on right use recursion to split the array with first element as one half and the rest array as another and then merge it with ... | def printArray ( array , length ) : NEW_LINE INDENT print ( " [ " , end = " " ) NEW_LINE for i in range ( length ) : NEW_LINE INDENT print ( array [ i ] , end = " " ) if ( i < ( length - 1 ) ) : print ( " , " , end = " β " ) else : print ( " ] " ) NEW_LINE DEDENT DEDENT def reverse ( array , start , end ) : NEW_LINE IN... |
Maximum product of subsequence of size k | Required function ; sorting given input array ; variable to store final product of all element of sub - sequence of size k ; CASE I If max element is 0 and k is odd then max product will be 0 ; CASE II If all elements are negative and k is odd then max product will be product ... | def maxProductSubarrayOfSizeK ( A , n , k ) : NEW_LINE INDENT A . sort ( ) NEW_LINE product = 1 NEW_LINE if ( A [ n - 1 ] == 0 and ( k & 1 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( A [ n - 1 ] <= 0 and ( k & 1 ) ) : NEW_LINE INDENT for i in range ( n - 1 , n - k + 1 , - 1 ) : NEW_LINE INDENT product *= A [ i ... |
Reorder an array according to given indexes | Function to reorder elements of arr [ ] according to index [ ] ; arr [ i ] should be present at index [ i ] index ; Copy temp [ ] to arr [ ] ; Driver program | def reorder ( arr , index , n ) : NEW_LINE INDENT temp = [ 0 ] * n ; NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT temp [ index [ i ] ] = arr [ i ] NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE index [ i ] = i NEW_LINE DEDENT DEDENT arr = [ 50 , 40 , 70 , 60 , 90 ] NEW... |
Reorder an array according to given indexes | Function to reorder elements of arr [ ] according to index [ ] ; Fix all elements one by one ; While index [ i ] and arr [ i ] are not fixed ; Store values of the target ( or correct ) position before placing arr [ i ] there ; Place arr [ i ] at its target ( or correct ) po... | def reorder ( arr , index , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT while ( index [ i ] != i ) : NEW_LINE INDENT oldTargetI = index [ index [ i ] ] NEW_LINE oldTargetE = arr [ index [ i ] ] NEW_LINE arr [ index [ i ] ] = arr [ i ] NEW_LINE index [ index [ i ] ] = index [ i ] NEW_LINE index [ i ... |
Stooge Sort | Function to implement stooge sort ; If first element is smaller than last , swap them ; If there are more than 2 elements in the array ; Recursively sort first 2 / 3 elements ; Recursively sort last 2 / 3 elements ; Recursively sort first 2 / 3 elements again to confirm ; deriver ; Calling Stooge Sort fun... | def stoogesort ( arr , l , h ) : NEW_LINE INDENT if l >= h : NEW_LINE INDENT return NEW_LINE DEDENT if arr [ l ] > arr [ h ] : NEW_LINE INDENT t = arr [ l ] NEW_LINE arr [ l ] = arr [ h ] NEW_LINE arr [ h ] = t NEW_LINE DEDENT if h - l + 1 > 2 : NEW_LINE INDENT t = ( int ) ( ( h - l + 1 ) / 3 ) NEW_LINE stoogesort ( ar... |
Reorder an array according to given indexes | Python3 code to reorder an array according to given indices ; left child in 0 based indexing ; right child in 1 based indexing ; Find largest index from root , left and right child ; Swap arr whenever index is swapped ; Build heap ; Swap the largest element of index ( first... | def heapify ( arr , index , i ) : NEW_LINE INDENT largest = i NEW_LINE left = 2 * i + 1 NEW_LINE right = 2 * i + 2 NEW_LINE global heapSize NEW_LINE if ( left < heapSize and index [ left ] > index [ largest ] ) : NEW_LINE INDENT largest = left NEW_LINE DEDENT if ( right < heapSize and index [ right ] > index [ largest ... |
Sum of all the parent nodes having child node x | function to get a new node ; put in the data ; function to find the Sum of all the parent nodes having child node x ; if root == None ; if left or right child of root is ' x ' , then add the root ' s β data β to β ' Sum ' ; recursively find the required parent nodes in... | class getNode : 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 SumOfParentOfX ( root , Sum , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( ( root . left and root . left . data =... |
Sort even | Python3 Program to sort even - placed elements in increasing and odd - placed in decreasing order with constant space complexity ; first odd index ; last index ; if last index is odd ; decrement j to even index ; swapping till half of array ; Sort first half in increasing ; Sort second half in decreasing ; ... | def bitonicGenerator ( arr , n ) : NEW_LINE INDENT i = 1 NEW_LINE j = n - 1 NEW_LINE if ( j % 2 != 0 ) : NEW_LINE INDENT j = j - 1 NEW_LINE DEDENT while ( i < j ) : NEW_LINE INDENT arr [ j ] , arr [ i ] = arr [ i ] , arr [ j ] NEW_LINE i = i + 2 NEW_LINE j = j - 2 NEW_LINE DEDENT arr_f = [ ] NEW_LINE arr_s = [ ] NEW_LI... |
Gnome Sort | A function to sort the given list using Gnome sort ; Driver Code | def gnomeSort ( arr , n ) : NEW_LINE INDENT index = 0 NEW_LINE while index < n : NEW_LINE INDENT if index == 0 : NEW_LINE INDENT index = index + 1 NEW_LINE DEDENT if arr [ index ] >= arr [ index - 1 ] : NEW_LINE INDENT index = index + 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ index ] , arr [ index - 1 ] = arr [ in... |
Cocktail Sort | Sorts arrar a [ 0. . n - 1 ] using Cocktail sort ; reset the swapped flag on entering the loop , because it might be true from a previous iteration . ; loop from left to right same as the bubble sort ; if nothing moved , then array is sorted . ; otherwise , reset the swapped flag so that it can be used ... | def cocktailSort ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE swapped = True NEW_LINE start = 0 NEW_LINE end = n - 1 NEW_LINE while ( swapped == True ) : NEW_LINE INDENT swapped = False NEW_LINE for i in range ( start , end ) : NEW_LINE INDENT if ( a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT a [ i ] , a [ i + 1 ] = a [... |
Find the point where maximum intervals overlap | Program to find maximum guest at any time in a party ; Sort arrival and exit arrays ; guests_in indicates number of guests at a time ; Similar to merge in merge sort to process all events in sorted order ; If next event in sorted order is arrival , increment count of gue... | def findMaxGuests ( arrl , exit , n ) : NEW_LINE INDENT arrl . sort ( ) ; NEW_LINE exit . sort ( ) ; NEW_LINE guests_in = 1 ; NEW_LINE max_guests = 1 ; NEW_LINE time = arrl [ 0 ] ; NEW_LINE i = 1 ; NEW_LINE j = 0 ; NEW_LINE while ( i < n and j < n ) : NEW_LINE INDENT if ( arrl [ i ] <= exit [ j ] ) : NEW_LINE INDENT gu... |
Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple method to rearrange arr [ 0. . n - 1 ] ' β so β that β ' arr [ j ] ' β becomes β ' i ' β if β ' arr [ i ] ' β is β ' j ; Create an auxiliary array of same size ; Store result in temp [ ] ; Copy temp back to arr [ ] ; A... | def rearrangeNaive ( arr , n ) : NEW_LINE INDENT temp = [ 0 ] * n NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT temp [ arr [ i ] ] = i NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE DEDENT DEDENT def printArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NE... |
Rearrange an array such that ' arr [ j ] ' becomes ' i ' if ' arr [ i ] ' is ' j ' | Set 1 | A simple method to rearrange arr [ 0. . n - 1 ] ' β so β that β ' arr [ j ] ' β becomes β ' i ' β if β ' arr [ i ] ' β is β ' j ; Retrieving old value and storing with the new one ; Retrieving new value ; A utility function to ... | def rearrange ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT arr [ arr [ i ] % n ] += i * n NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] //= n NEW_LINE DEDENT DEDENT def prArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β "... |
Rearrange an array in maximum minimum form | Set 1 | Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; Auxiliary array to hold modified array ; Indexes of smallest and largest elements from remaining array . ; To indicate whether we need to ... | def rearrange ( arr , n ) : NEW_LINE INDENT temp = n * [ None ] NEW_LINE small , large = 0 , n - 1 NEW_LINE flag = True NEW_LINE for i in range ( n ) : NEW_LINE INDENT if flag is True : NEW_LINE INDENT temp [ i ] = arr [ large ] NEW_LINE large -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT temp [ i ] = arr [ small ] NEW_L... |
Minimum number of coins needed to remove all the elements of the array based on given rules | Function to calculate minimum number of coins needed ; Consider the first element separately , add 1 to the total if it 's of type 1 ; Iterate from the second element ; If the current element is of type 2 then any Player can r... | def minimumcoins ( arr , N ) : NEW_LINE INDENT coins = 0 NEW_LINE j = 0 NEW_LINE if ( arr [ 0 ] == 1 ) : NEW_LINE INDENT coins += 1 NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE INDENT if ( arr [ i ] == 2 ) : NEW_LINE INDENT continue NEW_LINE DEDENT j = i NEW_LINE while ( j < N and arr [ j ] == 1 ) : NEW_LINE IND... |
Rearrange an array in maximum minimum form | Set 2 ( O ( 1 ) extra space ) | Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; Initialize index of first minimum and first maximum element ; Store maximum element of array ; Traverse array elem... | def rearrange ( arr , n ) : NEW_LINE INDENT max_idx = n - 1 NEW_LINE min_idx = 0 NEW_LINE max_elem = arr [ n - 1 ] + 1 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT arr [ i ] += ( arr [ max_idx ] % max_elem ) * max_elem NEW_LINE max_idx -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT a... |
Rearrange an array in maximum minimum form | Set 2 ( O ( 1 ) extra space ) | Prints max at first position , min at second position second max at third position , second min at fourth position and so on . ; initialize index of first minimum and first maximum element ; traverse array elements ; at even index : we have to... | def rearrange ( arr , n ) : NEW_LINE INDENT max_ele = arr [ n - 1 ] NEW_LINE min_ele = arr [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT arr [ i ] = max_ele NEW_LINE max_ele -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = min_ele NEW_LINE min_ele += 1 NEW_LINE DEDENT DEDE... |
Find sum of all left leaves in a given Binary Tree | A Binary tree node ; A utility function to check if a given node is leaf or not ; This function return sum of all left leaves in a given binary tree ; Initialize result ; Update result if root is not None ; If left of root is None , then add key of left child ; Else ... | 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 isLeaf ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return False NEW_LINE DEDENT if node . left is None and node . right is None... |
Move all negative numbers to beginning and positive to end with constant extra space | A Python 3 program to put all negative numbers before positive numbers ; print an array ; Driver code | def rearrange ( arr , n ) : NEW_LINE INDENT j = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = temp NEW_LINE j = j + 1 NEW_LINE DEDENT DEDENT print ( arr ) NEW_LINE DEDENT arr = [ - 1 , 2 , - 3 , 4 , 5 , 6... |
Maximize the diamonds by choosing different colour diamonds from adjacent boxes | Function to return the maximized value ; Number of rows and columns ; Creating the Dp array ; Populating the first column ; Iterating over all the rows ; Getting the ( i - 1 ) th max value ; Adding it to the current cell ; Getting the max... | def maxSum ( arr ) : NEW_LINE INDENT m = len ( arr ) NEW_LINE n = len ( arr [ 0 ] ) - 1 NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( m ) ] NEW_LINE for i in range ( 1 , m , 1 ) : NEW_LINE INDENT dp [ i ] [ 1 ] = arr [ i ] [ 1 ] NEW_LINE DEDENT for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT for j ... |
Move all negative elements to end in order with extra space allowed | Moves all - ve element to end of array in same order . ; Create an empty array to store result ; Traversal array and store + ve element in temp array index of temp ; If array contains all positive or all negative . ; Store - ve element in temp array ... | def segregateElements ( arr , n ) : NEW_LINE INDENT temp = [ 0 for k in range ( n ) ] NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ) : NEW_LINE INDENT temp [ j ] = arr [ i ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT if ( j == n or j == 0 ) : NEW_LINE INDENT return NEW_LINE DEDENT for ... |
Rearrange array such that even index elements are smaller and odd index elements are greater | Rearrange ; Utility that prints out an array in a line ; Driver code | def rearrange ( arr , n ) : NEW_LINE INDENT for i in range ( n - 1 ) : NEW_LINE INDENT if ( i % 2 == 0 and arr [ i ] > arr [ i + 1 ] ) : NEW_LINE INDENT temp = arr [ i ] NEW_LINE arr [ i ] = arr [ i + 1 ] NEW_LINE arr [ i + 1 ] = temp NEW_LINE DEDENT if ( i % 2 != 0 and arr [ i ] < arr [ i + 1 ] ) : NEW_LINE INDENT tem... |
Minimum distance between duplicates in a String | This function is used to find minimum distance between same repeating characters ; Store minimum distance between same repeating characters ; For loop to consider each element of string ; Comparison of string characters and updating the minDis value ; As this value woul... | def shortestDistance ( S , N ) : NEW_LINE INDENT minDis = len ( S ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( i + 1 , N ) : NEW_LINE INDENT if ( S [ i ] == S [ j ] and ( j - i ) < minDis ) : NEW_LINE INDENT minDis = j - i NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if ( minDis == len ( S ) ) : N... |
Positive elements at even and negative at odd positions ( Relative order not maintained ) | Python 3 program to rearrange positive and negative numbers ; Move forward the positive pointer till negative number number not encountered ; Move forward the negative pointer till positive number number not encountered ; Swap a... | def rearrange ( a , size ) : NEW_LINE INDENT positive = 0 NEW_LINE negative = 1 NEW_LINE while ( True ) : NEW_LINE INDENT while ( positive < size and a [ positive ] >= 0 ) : NEW_LINE INDENT positive = positive + 2 NEW_LINE DEDENT while ( negative < size and a [ negative ] <= 0 ) : NEW_LINE INDENT negative = negative + ... |
Print all numbers that can be obtained by adding A or B to N exactly M times | Function to find all possible numbers that can be obtained by adding A or B to N exactly M times ; For maintaining increasing order ; Smallest number that can be achieved ; If A and B are equal , the only number that can be onbtained is N + ... | def possibleNumbers ( N , M , A , B ) : NEW_LINE INDENT if ( A > B ) : NEW_LINE INDENT temp = A NEW_LINE A = B NEW_LINE B = temp NEW_LINE DEDENT number = N + M * A NEW_LINE print ( number , end = " β " ) NEW_LINE if ( A != B ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT number = number - A + B NEW_LINE pri... |
Positive elements at even and negative at odd positions ( Relative order not maintained ) | Print array function ; Driver code ; before modification ; out of order positive element ; find out of order negative element in remaining array ; out of order negative element ; find out of order positive element in remaining a... | def printArray ( a , n ) : NEW_LINE INDENT for i in a : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 1 , - 3 , 5 , 6 , - 3 , 6 , 7 , - 4 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE printArray ( arr , n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= 0 ... |
Segregate even and odd numbers | Set 3 | Python3 implementation of the above approach ; Driver code ; Function call | def arrayEvenAndOdd ( arr , n ) : NEW_LINE INDENT ind = 0 ; NEW_LINE a = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 == 0 ) : NEW_LINE INDENT a [ ind ] = arr [ i ] NEW_LINE ind += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] % 2 != 0 ) ... |
Segregate even and odd numbers | Set 3 | Function to segregate even odd numbers ; Swapping even and odd numbers ; Printing segregated array ; Driver Code | def arrayEvenAndOdd ( arr , n ) : NEW_LINE INDENT i = - 1 NEW_LINE j = 0 NEW_LINE while ( j != n ) : NEW_LINE INDENT if ( arr [ j ] % 2 == 0 ) : NEW_LINE INDENT i = i + 1 NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT j = j + 1 NEW_LINE DEDENT for i in arr : NEW_LINE INDENT print ( str ( i ) + "... |
Find sum of all left leaves in a given Binary Tree | A binary tree node ; Pass in a sum variable as an accumulator ; Check whether this node is a leaf node and is left ; Pass 1 for left and 0 for right ; A wrapper over above recursive function ; Use the above recursive function to evaluate sum ; Let us construct the Bi... | 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 leftLeavesSumRec ( root , isLeft , summ ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if root . left is None and ... |
Symmetric Tree ( Mirror Image of itself ) | Node structure ; Returns True if trees with roots as root1 and root 2 are mirror ; If both trees are empty , then they are mirror images ; For two trees to be mirror images , the following three conditions must be true 1 - Their root node 's key must be same 2 - left subtree... | 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 isMirror ( root1 , root2 ) : NEW_LINE INDENT if root1 is None and root2 is None : NEW_LINE INDENT return True NEW_LINE DEDENT if ( root1 is not ... |
Check if a matrix can be converted to another by repeatedly adding any value to X consecutive elements in a row or column | Function to check whether Matrix A [ ] [ ] can be transformed to Matrix B [ ] [ ] or not ; Traverse the matrix to perform horizontal operations ; Calculate difference ; Update next X elements ; Tr... | def Check ( A , B , M , N , X ) : NEW_LINE INDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N - X + 1 ) : NEW_LINE INDENT if ( A [ i ] [ j ] != B [ i ] [ j ] ) : NEW_LINE INDENT diff = B [ i ] [ j ] - A [ i ] [ j ] NEW_LINE for k in range ( X ) : NEW_LINE INDENT A [ i ] [ j + k ] = A [ i ] [ j + k ] + dif... |
Make all array elements equal by reducing array elements to half minimum number of times | Function to find minimum number of operations ; Initialize map ; Traverse the array ; Divide current array element until it reduces to 1 ; Traverse the map ; Find the maximum element having frequency equal to N ; Stores the minim... | def minOperations ( arr , N ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT res = arr [ i ] NEW_LINE while ( res ) : NEW_LINE if res in mp : NEW_LINE INDENT mp [ res ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT mp [ res ] = 1 NEW_LINE DEDENT res //= 2 NEW_LINE DEDENT mx = 1 NEW_LINE for it... |
Find the player to reach at least N by multiplying with any value from given range | Function to find the winner ; Backtrack from N to 1 ; Driver Code | def Winner ( N ) : NEW_LINE INDENT player = True NEW_LINE while N > 1 : NEW_LINE INDENT X , Y = divmod ( N , ( 9 if player else 2 ) ) NEW_LINE N = X + 1 if Y else X NEW_LINE player = not player NEW_LINE DEDENT if player : NEW_LINE return ' B ' NEW_LINE else : NEW_LINE return ' A ' NEW_LINE DEDENT N = 10 NEW_LINE print ... |
Program to find largest element in an array | returns maximum in arr [ ] of size n ; driver code | def largest ( arr , n ) : NEW_LINE INDENT return max ( arr ) NEW_LINE DEDENT arr = [ 10 , 324 , 45 , 90 , 9808 ] NEW_LINE n = len ( arr ) NEW_LINE print ( largest ( arr , n ) ) NEW_LINE |
Find the largest three distinct elements in an array | Python3 code to find largest three elements in an array ; It uses Tuned Quicksort with ; avg . case Time complexity = O ( nLogn ) ; to handle duplicate values ; Driver code | def find3largest ( arr , n ) : NEW_LINE INDENT arr = sorted ( arr ) NEW_LINE check = 0 NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( count < 4 ) : NEW_LINE INDENT if ( check != arr [ n - i ] ) : NEW_LINE INDENT print ( arr [ n - i ] , end = " β " ) NEW_LINE check = arr [ n - i ] NEW_LI... |
Minimum characters required to be removed to make frequency of each character unique | Function to find the minimum count of characters required to be deleted to make frequencies of all characters unique ; Stores frequency of each distinct character of str ; Store frequency of each distinct character such that the larg... | def minCntCharDeletionsfrequency ( str , N ) : NEW_LINE INDENT mp = { } NEW_LINE pq = [ ] NEW_LINE cntChar = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT mp [ str [ i ] ] = mp . get ( str [ i ] , 0 ) + 1 NEW_LINE DEDENT for it in mp : NEW_LINE INDENT pq . append ( mp [ it ] ) NEW_LINE DEDENT pq = sorted ( pq ) NEW... |
Program for Mean and median of an unsorted array | Function for calculating mean ; Function for calculating median ; First we sort the array ; check for even case ; Driver code ; Function call | def findMean ( a , n ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT return float ( sum / n ) NEW_LINE DEDENT def findMedian ( a , n ) : NEW_LINE INDENT sorted ( a ) NEW_LINE if n % 2 != 0 : NEW_LINE INDENT return float ( a [ int ( n / 2 ) ] ) NEW_LINE DEDE... |
Find sum of all left leaves in a given Binary Tree | A binary tree node ; A constructor to create a new Node ; Return the sum of left leaf nodes ; Using a stack for Depth - First Traversal of the tree ; sum holds the sum of all the left leaves ; Check if currentNode 's left child is a leaf node ; if currentNode is a le... | 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 sumOfLeftLeaves ( root ) : NEW_LINE INDENT if ( root is None ) : NEW_LINE INDENT return NEW_LINE DEDENT stack = [ ] NEW_LINE stack . append ( ro... |
Find a pair with sum N having minimum absolute difference | Function to find the value of X and Y having minimum value of abs ( X - Y ) ; If N is an odd number ; If N is an even number ; Driver Code | def findXandYwithminABSX_Y ( N ) : NEW_LINE INDENT if ( N % 2 == 1 ) : NEW_LINE INDENT print ( ( N // 2 ) , ( N // 2 + 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( N // 2 - 1 ) , ( N // 2 + 1 ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 12 NEW_LINE findXandYwithminABSX_Y ( ... |
Maximum sum possible by assigning alternate positive and negative sign to elements in a subsequence | Function to find the maximum sum subsequence ; Base Case ; If current state is already calculated then use it ; If current element is positive ; Update ans and recursively call with update value of flag ; Else current ... | def findMax ( a , dp , i , flag ) : NEW_LINE INDENT if ( i == len ( a ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ flag ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ flag ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( flag == 0 ) : NEW_LINE INDENT ans = max ( findMax ( a , dp , i + 1 , 0 ) , a [ i ] + findM... |
Find the player to last modify a string such that even number of consonants and no vowels are left in the string | Function to find a winner of the game if both the player plays optimally ; Stores the count of vowels and consonants ; Traverse the string ; Check if character is vowel ; Increment vowels count ; Otherwise... | def findWinner ( s ) : NEW_LINE INDENT vowels_count = 0 NEW_LINE consonants_count = 0 NEW_LINE p = len ( s ) NEW_LINE for i in range ( 0 , p ) : NEW_LINE INDENT if ( s [ i ] == ' a ' or s [ i ] == ' e ' or s [ i ] == ' i ' or s [ i ] == ' o ' or s [ i ] == ' u ' ) : NEW_LINE INDENT vowels_count = vowels_count + 1 NEW_L... |
K maximum sums of overlapping contiguous sub | Function to compute prefix - sum of the input array ; Update maxi by k maximum values from maxi and cand ; Here cand and maxi arrays are in non - increasing order beforehand . Now , j is the index of the next cand element and i is the index of next maxi element . Traverse ... | def prefix_sum ( arr , n ) : NEW_LINE INDENT pre_sum = list ( ) NEW_LINE pre_sum . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pre_sum . append ( pre_sum [ i - 1 ] + arr [ i ] ) NEW_LINE DEDENT return pre_sum NEW_LINE DEDENT def maxMerge ( maxi , cand ) : NEW_LINE INDENT k = len ( maxi ) NE... |
k smallest elements in same order using O ( 1 ) extra space | Function to print smallest k numbers in arr [ 0. . n - 1 ] ; For each arr [ i ] find whether it is a part of n - smallest with insertion sort concept ; find largest from first k - elements ; if largest is greater than arr [ i ] shift all element one place le... | def printSmall ( arr , n , k ) : NEW_LINE INDENT for i in range ( k , n ) : NEW_LINE INDENT max_var = arr [ k - 1 ] NEW_LINE pos = k - 1 NEW_LINE for j in range ( k - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ j ] > max_var ) : NEW_LINE INDENT max_var = arr [ j ] NEW_LINE pos = j NEW_LINE DEDENT DEDENT if ( max_var >... |
Find k pairs with smallest sums in two arrays | Python3 program to prints first k pairs with least sum from two arrays . ; Function to find k pairs with least sum such that one elemennt of a pair is from arr1 [ ] and other element is from arr2 [ ] ; Stores current index in arr2 [ ] for every element of arr1 [ ] . Initi... | import sys NEW_LINE def kSmallestPair ( arr1 , n1 , arr2 , n2 , k ) : NEW_LINE INDENT if ( k > n1 * n2 ) : NEW_LINE INDENT print ( " k β pairs β don ' t β exist " ) NEW_LINE return NEW_LINE DEDENT index2 = [ 0 for i in range ( n1 ) ] NEW_LINE while ( k > 0 ) : NEW_LINE INDENT min_sum = sys . maxsize NEW_LINE min_index ... |
Maximize count of strings of length 3 that can be formed from N 1 s and M 0 s | Function that counts the number of strings of length 3 that can be made with given m 0 s and n 1 s ; Print the count of strings ; Driver Code ; Given count of 1 s and 0 s ; Function call | def number_of_strings ( N , M ) : NEW_LINE INDENT print ( min ( N , min ( M , ( N + M ) // 3 ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE M = 19 NEW_LINE number_of_strings ( N , M ) NEW_LINE DEDENT |
Maximize count of subsets having product of smallest element and size of the subset at least X | Function to return the maximum count of subsets possible which satisfy the above condition ; Sort the array in descending order ; Stores the count of subsets ; Stores the size of the current subset ; Check for the necessary... | def maxSubset ( arr , N , X ) : NEW_LINE INDENT arr . sort ( reverse = True ) NEW_LINE counter = 0 NEW_LINE sz = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sz += 1 NEW_LINE if ( arr [ i ] * sz >= X ) : NEW_LINE INDENT counter += 1 NEW_LINE sz = 0 NEW_LINE DEDENT DEDENT return counter NEW_LINE DEDENT arr = [ 7 , ... |
Maximize modulus by replacing adjacent pairs with their modulus for any permutation of given Array | Python3 program to implement the above approach ; Function to find the maximum value possible of the given expression from all permutations of the array ; Stores the minimum value from the array ; Return the answer ; Dr... | import sys NEW_LINE def maximumModuloValue ( A , n ) : NEW_LINE INDENT mn = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT mn = min ( A [ i ] , mn ) NEW_LINE DEDENT return mn NEW_LINE DEDENT A = [ 7 , 10 , 12 ] NEW_LINE n = len ( A ) NEW_LINE print ( maximumModuloValue ( A , n ) ) NEW_LINE |
Final Matrix after incrementing submatrices by K in range given by Q queries | Function to update the given query ; Update top cell ; Update bottom left cell ; Update bottom right cell ; Update top right cell ; Function that updates the matrix mat [ ] [ ] by adding elements of aux [ ] [ ] ; Compute the prefix sum of al... | def updateQuery ( from_x , from_y , to_x , to_y , k , aux ) : NEW_LINE INDENT aux [ from_x ] [ from_y ] += k NEW_LINE if ( to_x + 1 < 3 ) : NEW_LINE INDENT aux [ to_x + 1 ] [ from_y ] -= k NEW_LINE DEDENT if ( to_x + 1 < 3 and to_y + 1 < 4 ) : NEW_LINE INDENT aux [ to_x + 1 ] [ to_y + 1 ] += k NEW_LINE DEDENT if ( to_y... |
Find Second largest element in an array | Function to print the second largest elements ; There should be atleast two elements ; Sort the array ; Start from second last element as the largest element is at last ; If the element is not equal to largest element ; Driver code | def print2largest ( arr , arr_size ) : NEW_LINE INDENT if ( arr_size < 2 ) : NEW_LINE INDENT print ( " β Invalid β Input β " ) NEW_LINE return NEW_LINE DEDENT arr . sort NEW_LINE for i in range ( arr_size - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] != arr [ arr_size - 1 ] ) : NEW_LINE print ( " The β second β la... |
Find sum of all left leaves in a given Binary Tree | Python3 program to find sum of all left leaves ; A binary tree node ; Return the sum of left leaf nodes ; A queue of pairs to do bfs traversal and keep track if the node is a left or right child if boolean value is true then it is a left child . ; Do bfs traversal ; ... | from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumOfLeftLeaves ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q =... |
Count of nested polygons that can be drawn by joining vertices internally | Function that counts the nested polygons inside another polygons ; Stores the count ; Child polygons can only exists if parent polygon has sides > 5 ; Get next nested polygon ; Return the count ; Given side of polygon ; Function call | def countNestedPolygons ( sides ) : NEW_LINE INDENT count = 0 NEW_LINE while ( sides > 5 ) : NEW_LINE INDENT sides //= 2 NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT N = 12 NEW_LINE print ( countNestedPolygons ( N ) ) NEW_LINE |
Find Second largest element in an array | Function to print second largest elements ; There should be atleast two elements ; Find the largest element ; Find the second largest element ; Driver code | def print2largest ( arr , arr_size ) : NEW_LINE INDENT if ( arr_size < 2 ) : NEW_LINE INDENT print ( " β Invalid β Input β " ) ; NEW_LINE return ; NEW_LINE DEDENT largest = second = - 2454635434 ; NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT largest = max ( largest , arr [ i ] ) ; NEW_LINE DEDENT for i in... |
Find Second largest element in an array | Function to print the second largest elements ; There should be atleast two elements ; If current element is smaller than first then update both first and second ; If arr [ i ] is in between first and second then update second ; Driver program to test above function | def print2largest ( arr , arr_size ) : NEW_LINE INDENT if ( arr_size < 2 ) : NEW_LINE INDENT print ( " β Invalid β Input β " ) NEW_LINE return NEW_LINE DEDENT first = second = - 2147483648 NEW_LINE for i in range ( arr_size ) : NEW_LINE INDENT if ( arr [ i ] > first ) : NEW_LINE INDENT second = first NEW_LINE first = a... |
Queries to count characters having odd frequency in a range [ L , R ] | Function to print the number of characters having odd frequencies for each query ; A function to construct the arr [ ] and prefix [ ] ; Stores array length ; Stores the unique powers of 2 associated to each character ; Prefix array to store the XOR... | def queryResult ( prefix , Q ) : NEW_LINE INDENT l = Q [ 0 ] NEW_LINE r = Q [ 1 ] NEW_LINE if ( l == 0 ) : NEW_LINE INDENT xorval = prefix [ r ] NEW_LINE print ( bin ( xorval ) . count ( '1' ) ) NEW_LINE DEDENT else : NEW_LINE INDENT xorval = prefix [ r ] ^ prefix [ l - 1 ] NEW_LINE print ( bin ( xorval ) . count ( '1'... |
Count of Binary Strings possible as per given conditions | Function to generate maximum possible strings that can be generated ; Maximum possible strings ; Driver code | def countStrings ( A , B , K ) : NEW_LINE INDENT X = ( A + B ) // ( K + 1 ) NEW_LINE return ( min ( A , min ( B , X ) ) * ( K + 1 ) ) NEW_LINE DEDENT N , M , K = 101 , 231 , 15 NEW_LINE print ( countStrings ( N , M , K ) ) NEW_LINE |
Construct a Matrix N x N with first N ^ 2 natural numbers for an input N | Function to print the desired matrix ; Iterate ove all [ 0 , N ] ; If is even ; If row number is even print the row in forward order ; if row number is odd print the row in reversed order ; Given Matrix Size ; Function Call | def UniqueMatrix ( N ) : NEW_LINE INDENT element_value = 1 NEW_LINE i = 0 NEW_LINE while ( i < N ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT for f in range ( element_value , element_value + N , 1 ) : NEW_LINE INDENT print ( f , end = ' β ' ) NEW_LINE DEDENT element_value += N NEW_LINE DEDENT else : NEW_LINE... |
Maximum and minimum of an array using minimum number of comparisons | structure is used to return two values from minMax ( ) ; If there is only one element then return it as min and max both ; If there are more than one elements , then initialize min and max ; Driver Code | class pair : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . min = 0 NEW_LINE self . max = 0 NEW_LINE DEDENT DEDENT def getMinMax ( arr : list , n : int ) -> pair : NEW_LINE INDENT minmax = pair ( ) NEW_LINE if n == 1 : NEW_LINE INDENT minmax . max = arr [ 0 ] NEW_LINE minmax . min = arr [ 0 ] NEW_LINE r... |
Find sum of all nodes of the given perfect binary tree | function to find Sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; list of vector to store nodes of all of the levels ; store the nodes of last level i . e . , the leaf nodes ; store nodes of rest of the level by moving in bottom - up mann... | def SumNodes ( l ) : NEW_LINE INDENT leafNodeCount = pow ( 2 , l - 1 ) NEW_LINE vec = [ [ ] for i in range ( l ) ] NEW_LINE for i in range ( 1 , leafNodeCount + 1 ) : NEW_LINE INDENT vec [ l - 1 ] . append ( i ) NEW_LINE DEDENT for i in range ( l - 2 , - 1 , - 1 ) : NEW_LINE INDENT k = 0 NEW_LINE while ( k < len ( vec ... |
Maximum and minimum of an array using minimum number of comparisons | getMinMax ( ) ; If array has even number of elements then initialize the first two elements as minimum and maximum ; set the starting index for loop ; If array has odd number of elements then initialize the first element as minimum and maximum ; set ... | def getMinMax ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE if ( n % 2 == 0 ) : NEW_LINE INDENT mx = max ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE mn = min ( arr [ 0 ] , arr [ 1 ] ) NEW_LINE i = 2 NEW_LINE DEDENT else : NEW_LINE INDENT mx = mn = arr [ 0 ] NEW_LINE i = 1 NEW_LINE DEDENT while ( i < n - 1 ) : NEW_LINE INDE... |
MO 's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction) | Function that accepts array and list of queries and print sum of each query ; Traverse through each query ; Extract left and right indices ; Compute sum of current query range ; Print sum of current query range ; Driver script | def printQuerySum ( arr , Q ) : NEW_LINE INDENT for q in Q : NEW_LINE INDENT L , R = q NEW_LINE s = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT s += arr [ i ] NEW_LINE DEDENT print ( " Sum β of " , q , " is " , s ) NEW_LINE DEDENT DEDENT arr = [ 1 , 1 , 2 , 1 , 3 , 4 , 5 , 2 , 8 ] NEW_LINE Q = [ [ 0 , 4 ]... |
Count of unique palindromic strings of length X from given string | Function to count different palindromic string of length X from the given string S ; Base case ; Create the frequency array Intitalise frequency array with 0 ; Count the frequency in the string ; Store frequency of the char ; Check the frequency which ... | def findways ( s , x ) : NEW_LINE INDENT if ( x > len ( s ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT n = len ( s ) NEW_LINE freq = [ 0 ] * 26 NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT se = set ( ) NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if... |
Min operations to reduce N to 1 by multiplying by A or dividing by B | Function to check if it is possible to convert a number N to 1 by a minimum use of the two operations ; For the Case b % a != 0 ; Check if n equal to 1 ; Check if n is not divisible by b ; Initialize a variable c ; Loop until n is divisible by b ; C... | def FindIfPossible ( n , a , b ) : NEW_LINE INDENT if ( b % a ) != 0 : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( n % b ) != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return int ( n / b ) NEW_LINE DEDENT DEDENT c = b / a NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE... |
Sqrt ( or Square Root ) Decomposition Technique | Set 1 ( Introduction ) | Python 3 program to demonstrate working of Square Root Decomposition . ; original array ; decomposed array ; block size ; Time Complexity : O ( 1 ) ; Time Complexity : O ( sqrt ( n ) ) ; traversing first block in range ; traversing completely ov... | from math import sqrt NEW_LINE MAXN = 10000 NEW_LINE SQRSIZE = 100 NEW_LINE arr = [ 0 ] * ( MAXN ) NEW_LINE block = [ 0 ] * ( SQRSIZE ) NEW_LINE blk_sz = 0 NEW_LINE def update ( idx , val ) : NEW_LINE INDENT blockNumber = idx // blk_sz NEW_LINE block [ blockNumber ] += val - arr [ idx ] NEW_LINE arr [ idx ] = val NEW_L... |
Find two numbers with sum N such that neither of them contains digit K | Python3 implementation of the above approach ; Count leading zeros ; It removes i characters starting from index 0 ; Check each digit of the N ; If digit is K break it ; For odd numbers ; Add D1 to A and D2 to B ; If the digit is not K , no need t... | def removeLeadingZeros ( Str ) : NEW_LINE INDENT i = 0 NEW_LINE n = len ( Str ) NEW_LINE while ( Str [ i ] == '0' and i < n ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT Str = Str [ i : ] NEW_LINE return Str NEW_LINE DEDENT def findPairs ( Sum , K ) : NEW_LINE INDENT A = " " NEW_LINE B = " " NEW_LINE N = str ( Sum ) NEW_L... |
Range Minimum Query ( Square Root Decomposition and Sparse Table ) | Python3 program to do range minimum query in O ( 1 ) time with O ( n * n ) extra space and O ( n * n ) preprocessing time . ; lookup [ i ] [ j ] is going to store index of minimum value in arr [ i . . j ] ; Structure to represent a query range ; Fills... | MAX = 500 NEW_LINE lookup = [ [ 0 for j in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE class Query : NEW_LINE INDENT def __init__ ( self , L , R ) : NEW_LINE INDENT self . L = L NEW_LINE self . R = R NEW_LINE DEDENT DEDENT def preprocess ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT lookup ... |
Minimum salary hike for each employee such that no employee feels unfair | Python Program to find the minimum hike of each employee such that no adjacent employee feels unfair ; As hikes are positive integers , keeping minimum value ; Pass - 1 : compare with previous employee ; Pass - 2 : compare with Next employee ; D... | def findMinimumHike ( ratings , employees ) : NEW_LINE INDENT hikes = [ 1 for i in range ( employees ) ] NEW_LINE for i in range ( 1 , employees ) : NEW_LINE INDENT if ( ratings [ i - 1 ] < ratings [ i ] and hikes [ i - 1 ] >= hikes [ i ] ) : NEW_LINE INDENT hikes [ i ] = hikes [ i - 1 ] + 1 ; NEW_LINE DEDENT DEDENT fo... |
Range Minimum Query ( Square Root Decomposition and Sparse Table ) | Python3 program to do range minimum query in O ( 1 ) time with O ( n Log n ) extra space and O ( n Log n ) preprocessing time ; lookup [ i ] [ j ] is going to store index of minimum value in arr [ i . . j ] . Ideally lookup table size should not be fi... | from math import log2 NEW_LINE MAX = 500 NEW_LINE lookup = [ [ 0 for i in range ( 500 ) ] for j in range ( 500 ) ] NEW_LINE class Query : NEW_LINE INDENT def __init__ ( self , l , r ) : NEW_LINE INDENT self . L = l NEW_LINE self . R = r NEW_LINE DEDENT DEDENT def preprocess ( arr : list , n : int ) : NEW_LINE INDENT gl... |
Find sum of all nodes of the given perfect binary tree | function to find sum of all of the nodes of given perfect binary tree ; function to find sum of all of the nodes of given perfect binary tree ; no of leaf nodes ; sum of nodes at last level ; sum of all nodes ; Driver Code | import math NEW_LINE def sumNodes ( l ) : NEW_LINE INDENT leafNodeCount = math . pow ( 2 , l - 1 ) ; NEW_LINE sumLastLevel = 0 ; NEW_LINE sumLastLevel = ( ( leafNodeCount * ( leafNodeCount + 1 ) ) / 2 ) ; NEW_LINE sum = sumLastLevel * l ; NEW_LINE return int ( sum ) ; NEW_LINE DEDENT l = 3 ; NEW_LINE print ( sumNodes (... |
Longest subsequence with different adjacent characters | dp table ; A recursive function to find the update the dp table ; If we reach end of the String ; If subproblem has been computed ; Initialise variable to find the maximum length ; Choose the current character ; Omit the current character ; Return the store answe... | dp = [ [ - 1 for i in range ( 27 ) ] for j in range ( 100005 ) ] ; NEW_LINE def calculate ( pos , prev , s ) : NEW_LINE INDENT if ( pos == len ( s ) ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( dp [ pos ] [ prev ] != - 1 ) : NEW_LINE INDENT return dp [ pos ] [ prev ] ; NEW_LINE DEDENT val = 0 ; NEW_LINE if ( ord... |
Constant time range add operation on an array | Utility method to add value val , to range [ lo , hi ] ; Utility method to get actual array from operation array ; convert array into prefix sum array ; method to print final updated array ; Driver code ; Range add Queries | def add ( arr , N , lo , hi , val ) : NEW_LINE INDENT arr [ lo ] += val NEW_LINE if ( hi != N - 1 ) : NEW_LINE INDENT arr [ hi + 1 ] -= val NEW_LINE DEDENT DEDENT def updateArray ( arr , N ) : NEW_LINE INDENT for i in range ( 1 , N ) : NEW_LINE INDENT arr [ i ] += arr [ i - 1 ] NEW_LINE DEDENT DEDENT def printArr ( arr... |
Maximum profit by buying and selling a share at most K times | Greedy Approach | Function to return the maximum profit ; Find the farthest decreasing span of prices before prices rise ; Find the farthest increasing span of prices before prices fall again ; Check if the current buying price is greater than that of the p... | def maxProfit ( n , k , prices ) : NEW_LINE INDENT ans = 0 NEW_LINE buy = 0 NEW_LINE sell = 0 NEW_LINE transaction = [ ] NEW_LINE profits = [ ] NEW_LINE while ( sell < n ) : NEW_LINE INDENT buy = sell NEW_LINE while ( buy < n - 1 and prices [ buy ] >= prices [ buy + 1 ] ) : NEW_LINE INDENT buy += 1 NEW_LINE DEDENT sell... |
Find sum in range L to R in given sequence of integers | Function to find the sum within the given range ; generating array from given sequence ; calculate the desired sum ; return the sum ; initialise the range | def findSum ( L , R ) : NEW_LINE INDENT arr = [ ] NEW_LINE i = 0 NEW_LINE x = 2 NEW_LINE k = 0 NEW_LINE while ( i <= R ) : NEW_LINE INDENT arr . insert ( k , i + x ) NEW_LINE k += 1 NEW_LINE if ( i + 1 <= R ) : NEW_LINE INDENT arr . insert ( k , i + 1 + x ) NEW_LINE DEDENT k += 1 NEW_LINE x *= - 1 NEW_LINE i += 2 NEW_L... |
Queries for GCD of all numbers of an array except elements in a given range | Calculating GCD using euclid algorithm ; Filling the prefix and suffix array ; Filling the prefix array following relation prefix ( i ) = GCD ( prefix ( i - 1 ) , arr ( i ) ) ; Filling the suffix array following the relation suffix ( i ) = GC... | def GCD ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return GCD ( b , a % b ) NEW_LINE DEDENT def FillPrefixSuffix ( prefix , arr , suffix , n ) : NEW_LINE INDENT prefix [ 0 ] = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT prefix [ i ] = GCD ( prefix [ i - 1 ] , ... |
Count of pairs from arrays A and B such that element in A is greater than element in B at that index | Python3 program to find the maximum count of values that follow the given condition ; Function to find the maximum count of values that follow the given condition ; Initializing the max - heap for the array A [ ] ; Ad... | import heapq NEW_LINE def check ( A , B , N ) : NEW_LINE INDENT pq1 = [ ] NEW_LINE pq2 = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT heapq . heappush ( pq1 , - A [ i ] ) NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT heapq . heappush ( pq2 , - B [ i ] ) NEW_LINE DEDENT c = 0 NEW_LINE for i in range ( N ... |
Number of elements less than or equal to a given number in a given subarray | Set 2 ( Including Updates ) | Number of elements less than or equal to a given number in a given subarray and allowing update operations . ; updating the bit array of a valid block ; answering the query ; traversing the first block in range ;... | MAX = 10001 NEW_LINE def update ( idx , blk , val , bit ) : NEW_LINE INDENT while idx < MAX : NEW_LINE INDENT bit [ blk ] [ idx ] += val NEW_LINE idx += ( idx & - idx ) NEW_LINE DEDENT DEDENT def query ( l , r , k , arr , blk_sz , bit ) : NEW_LINE INDENT summ = 0 NEW_LINE while l < r and l % blk_sz != 0 and l != 0 : NE... |
Queries for counts of array elements with values in given range | function to count elements within given range ; initialize result ; check if element is in range ; driver function ; Answer queries | def countInRange ( arr , n , x , y ) : NEW_LINE INDENT count = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] >= x and arr [ i ] <= y ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 9 , 10 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE i = 1 NEW_LINE j... |
Path with smallest product of edges with weight >= 1 | Function to return the smallest product of edges ; If the source is equal to the destination ; Initialise the priority queue ; Visited array ; While the priority - queue is not empty ; Current node ; Current product of distance ; Popping the top - most element ; If... | def dijkstra ( s , d , gr ) : NEW_LINE INDENT if ( s == d ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT pq = [ ] ; NEW_LINE pq . append ( ( 1 , s ) ) ; NEW_LINE v = [ 0 ] * ( len ( gr ) + 1 ) ; NEW_LINE while ( len ( pq ) != 0 ) : NEW_LINE INDENT curr = pq [ 0 ] [ 1 ] ; NEW_LINE dist = pq [ 0 ] [ 0 ] ; NEW_LINE pq . p... |
Queries for counts of array elements with values in given range | function to find first index >= x ; function to find last index <= x ; function to count elements within given range ; initialize result ; driver function ; Preprocess array ; Answer queries | def lowerIndex ( arr , n , x ) : NEW_LINE INDENT l = 0 NEW_LINE h = n - 1 NEW_LINE while ( l <= h ) : NEW_LINE INDENT mid = int ( ( l + h ) / 2 ) NEW_LINE if ( arr [ mid ] >= x ) : NEW_LINE h = mid - 1 NEW_LINE else : NEW_LINE l = mid + 1 NEW_LINE DEDENT return l NEW_LINE DEDENT def upperIndex ( arr , n , x ) : NEW_LIN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.