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 sorted ; If the key is equal to the root then simply return 0 ( zero 'th level) ; If the key is found in any leftmost element then simply return true No need for any extra searching ; If key lies between the root data and the left child 's data OR if key is greater than root data and there is no level underneath it, return the current level ; Function to traverse a binary encoded path and return the value encountered after traversal . ; Go left ; Incomplete path ; Go right ; Incomplete path ; Return the data at the node ; Function to generate gray code of corresponding binary number of integer i ; Create new arraylist to store the gray code ; Reverse the encoding till here ; Leftmost digits are filled with 0 ; Function to search the key in a particular level of the tree . ; Find the middle index ; Encode path from root to this index in the form of 0 s and 1 s where 0 means LEFT and 1 means RIGHT ; Traverse the path in the tree and check if the key is found ; If path is incomplete ; Check the left part of the level ; Check the right part of the level ; Check the left part of the level ; Key not found in that level ; Function that returns true if the key is found in the tree ; Find the level where the key may lie ; If level is - 1 then return false ; If level is - 2 i . e . key was found in any leftmost element then simply return true ; Apply binary search on the elements of that level ; Driver code ; Consider the following level order sorted tree 5 / \ 8 10 / \ / \ 13 23 25 30 / \ / 32 40 50 ; Keys to be searched
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 ) -> int : NEW_LINE INDENT if ( data < root . data ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT if ( data == root . data ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT cur_level = 0 NEW_LINE while True : NEW_LINE INDENT cur_level += 1 NEW_LINE root = root . left NEW_LINE if ( root . data == data ) : NEW_LINE INDENT return - 2 NEW_LINE DEDENT if ( root . data < data and ( root . left == None or root . left . data > data ) ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return cur_level NEW_LINE DEDENT def traversePath ( root : Node , path : list ) -> int : NEW_LINE INDENT for i in range ( len ( path ) ) : NEW_LINE INDENT direction = path [ i ] NEW_LINE if ( direction == 0 ) : NEW_LINE INDENT if ( root . left == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT root = root . left NEW_LINE DEDENT else : NEW_LINE INDENT if ( root . right == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT root = root . right NEW_LINE DEDENT DEDENT return root . data NEW_LINE DEDENT def generateGray ( n : int , x : int ) -> list : NEW_LINE INDENT gray = [ ] NEW_LINE i = 0 NEW_LINE while ( x > 0 ) : NEW_LINE INDENT gray . append ( x % 2 ) NEW_LINE x = x / 2 NEW_LINE i += 1 NEW_LINE DEDENT gray . reverse ( ) NEW_LINE for j in range ( n - i ) : NEW_LINE INDENT gray . insert ( 0 , gray [ 0 ] ) NEW_LINE DEDENT return gray NEW_LINE DEDENT def binarySearch ( root : Node , start : int , end : int , data : int , level : int ) -> bool : NEW_LINE INDENT if ( end >= start ) : NEW_LINE INDENT mid = ( start + end ) / 2 NEW_LINE encoding = generateGray ( level , mid ) NEW_LINE element_found = traversePath ( root , encoding ) NEW_LINE if ( element_found == - 1 ) : NEW_LINE INDENT return binarySearch ( root , start , mid - 1 , data , level ) NEW_LINE DEDENT if ( element_found == data ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( element_found < data ) : NEW_LINE INDENT return binarySearch ( root , mid + 1 , end , data , level ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( root , start , mid - 1 , data , level ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findKey ( root : Node , data : int ) -> bool : NEW_LINE INDENT level = findLevel ( root , data ) NEW_LINE if ( level == - 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( level == - 2 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return binarySearch ( root , 0 , int ( pow ( 2 , level ) - 1 ) , data , level ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = Node ( 5 ) NEW_LINE root . left = Node ( 8 ) NEW_LINE root . right = Node ( 10 ) NEW_LINE root . left . left = Node ( 13 ) NEW_LINE root . left . right = Node ( 23 ) NEW_LINE root . right . left = Node ( 25 ) NEW_LINE root . right . right = Node ( 30 ) NEW_LINE root . left . left . left = Node ( 32 ) NEW_LINE root . left . left . right = Node ( 40 ) NEW_LINE root . left . right . left = Node ( 50 ) NEW_LINE arr = [ 5 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( findKey ( root , arr [ i ] ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT DEDENT
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 ; Print the last column from the remaining columns ; Print the last row from the remaining rows ; Print the first column from the remaining columns ; Function to convert 2D array to 1D array ; Store value 2D Matrix To 1D array ; Function to print the Matrix ; Print Spiral Matrix ; Function to sort the array ; Sort array Using InBuilt Function ; Function to Convert given Matrix into sorted Spiral Matrix ; Driver code
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 , m , 1 ) : NEW_LINE INDENT a [ i ] [ n - 1 ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE DEDENT n -= 1 NEW_LINE if ( k < m ) : NEW_LINE INDENT i = n - 1 NEW_LINE while ( i >= l ) : NEW_LINE INDENT a [ m - 1 ] [ i ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE i -= 1 NEW_LINE DEDENT m -= 1 NEW_LINE DEDENT if ( l < n ) : NEW_LINE INDENT i = m - 1 NEW_LINE while ( i >= k ) : NEW_LINE INDENT a [ i ] [ l ] = Sorted [ index ] NEW_LINE index += 1 NEW_LINE i -= 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT DEDENT DEDENT def convert2Dto1D ( y , m , n ) : NEW_LINE INDENT index = 0 NEW_LINE x = [ 0 for i in range ( m * n ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT x [ index ] = y [ i ] [ j ] NEW_LINE index += 1 NEW_LINE DEDENT DEDENT return x NEW_LINE DEDENT def PrintMatrix ( a , m , n ) : NEW_LINE INDENT for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( a [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ' ' , end = " " ) NEW_LINE DEDENT DEDENT def SortArray ( x ) : NEW_LINE INDENT x . sort ( reverse = False ) NEW_LINE return x NEW_LINE DEDENT def convertMatrixToSortedSpiral ( y , m , n ) : NEW_LINE INDENT a = [ [ 0 for i in range ( MAX ) ] for j in range ( MAX ) ] NEW_LINE x = [ 0 for i in range ( 15 ) ] NEW_LINE x = convert2Dto1D ( y , m , n ) NEW_LINE x = SortArray ( x ) NEW_LINE ToSpiral ( m , n , x , a ) NEW_LINE PrintMatrix ( a , m , n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 4 NEW_LINE n = 3 NEW_LINE y = [ [ 2 , 5 , 12 ] , [ 22 , 45 , 55 ] , [ 1 , 6 , 8 ] , [ 13 , 56 , 10 ] ] NEW_LINE convertMatrixToSortedSpiral ( y , m , n ) NEW_LINE DEDENT
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_LINE reverseArray ( arr , 0 , d - 1 ) ; NEW_LINE reverseArray ( arr , d , n - 1 ) ; NEW_LINE DEDENT def prArray ( arr , size ) : NEW_LINE INDENT for i in range ( 0 , size ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE rightRotate ( arr , k , n ) NEW_LINE prArray ( arr , n ) NEW_LINE
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 ; nodeCount ( queue size ) indicates number of nodes at current level . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver Code
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def printOddNodes ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT q = [ ] NEW_LINE q . append ( root ) NEW_LINE isOdd = True NEW_LINE while ( 1 ) : NEW_LINE INDENT nodeCount = len ( q ) NEW_LINE if ( nodeCount == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT while ( nodeCount > 0 ) : NEW_LINE INDENT node = q [ 0 ] NEW_LINE if ( isOdd ) : NEW_LINE INDENT print ( node . data , end = " ▁ " ) NEW_LINE DEDENT q . pop ( 0 ) NEW_LINE if ( node . left != None ) : NEW_LINE INDENT q . append ( node . left ) NEW_LINE DEDENT if ( node . right != None ) : NEW_LINE INDENT q . append ( node . right ) NEW_LINE DEDENT nodeCount -= 1 NEW_LINE DEDENT isOdd = not isOdd NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE printOddNodes ( root ) NEW_LINE DEDENT
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 can never get more than n . ; driver program
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_LINE k = 0 NEW_LINE for j in range ( i , i + n ) : NEW_LINE INDENT if brr [ j ] != arr [ k ] : NEW_LINE INDENT currHam += 1 NEW_LINE k = k + 1 NEW_LINE DEDENT DEDENT if currHam == n : NEW_LINE INDENT return n NEW_LINE DEDENT maxHam = max ( maxHam , currHam ) NEW_LINE DEDENT return maxHam NEW_LINE DEDENT arr = [ 2 , 4 , 6 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( maxHamming ( arr , n ) ) NEW_LINE
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 , k ) NEW_LINE k = 3 NEW_LINE leftRotate ( arr , n , k ) NEW_LINE k = 4 NEW_LINE leftRotate ( arr , n , k ) NEW_LINE
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 circle ; Non intersecting circles ; Intersecting circles ; Centers of circles ; Radius of circles ; Number of circles
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 = diameter [ 0 ] [ 1 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( diameter [ i ] [ 0 ] > cur ) : NEW_LINE INDENT cur = diameter [ i ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count ) NEW_LINE DEDENT c = [ 1 , 2 , 3 , 4 ] NEW_LINE r = [ 1 , 1 , 1 , 1 ] NEW_LINE n = len ( c ) NEW_LINE CountCircles ( c , r , n ) NEW_LINE
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 start position ; Driver Code ; Function Call
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 arr = [ 1 , 3 , 5 , 7 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE k = 2 NEW_LINE leftRotate ( arr , k , n ) NEW_LINE DEDENT
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_LINE DEDENT else : NEW_LINE INDENT index = index - 1 NEW_LINE DEDENT DEDENT DEDENT return arr [ index ] NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE rotations = 2 NEW_LINE ranges = [ [ 0 , 2 ] , [ 0 , 3 ] ] NEW_LINE index = 1 NEW_LINE print ( findElement ( arr , ranges , rotations , index ) ) NEW_LINE
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 where the alphabets start ; Now replace the string with sorted string ; If the position was occupied by an alphabet then replace it with alphabet ; Else replace it with a number ; Return the sorted string ; Driver Code
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 nu_c += 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ i ] = c [ al_c ] NEW_LINE al_c += 1 NEW_LINE DEDENT DEDENT return ' ' . join ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " d4c3b2a1" NEW_LINE print ( sort ( s ) ) NEW_LINE DEDENT
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 position = 2 NEW_LINE splitArr ( arr , n , position ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT
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 ] = tmp [ i ] ; NEW_LINE DEDENT DEDENT arr = [ 12 , 10 , 5 , 6 , 52 , 36 ] NEW_LINE n = len ( arr ) NEW_LINE position = 2 NEW_LINE SplitAndAdd ( arr , n , position ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE
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 ] = - 1 NEW_LINE DEDENT DEDENT print ( " Array ▁ after ▁ Rearranging " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( ar [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT ar = [ - 1 , - 1 , 6 , 1 , 9 , 3 , 2 , - 1 , 4 , - 1 ] NEW_LINE n = len ( ar ) NEW_LINE fixArray ( ar , n ) ; NEW_LINE
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 contribution . sort ( reverse = True ) NEW_LINE i = 0 NEW_LINE while ( i < k ) : NEW_LINE INDENT answer += contribution [ i ] NEW_LINE i += 1 NEW_LINE DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 1 , 2 , 2 , 2 , 3 ] NEW_LINE n = len ( a ) NEW_LINE queries = [ [ 0 , 4 ] , [ 1 , 2 ] , [ 2 , 5 ] , [ 2 , 3 ] , [ 2 , 4 ] ] NEW_LINE q = len ( queries ) ; NEW_LINE k = 3 NEW_LINE print ( getFinalSum ( a , n , queries , q , k ) ) NEW_LINE DEDENT
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 ; Answer all the queries ; Driver code
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 ] = a [ i ] NEW_LINE arr [ i ] [ 1 ] = i NEW_LINE DEDENT arr . sort ( reverse = False ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT print ( answerQuery ( arr , q [ i ] [ 0 ] , q [ i ] [ 1 ] ) ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 5 , 4 , 2 , 8 , 6 , 7 ] NEW_LINE n = len ( a ) NEW_LINE q = [ [ 2 , 5 ] , [ 1 , 3 ] , [ 1 , 5 ] , [ 3 , 6 ] ] NEW_LINE m = len ( q ) NEW_LINE solveQueries ( a , n , q , m ) NEW_LINE DEDENT
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 and root . right != None ) : NEW_LINE INDENT print ( root . data , end = " ▁ " ) NEW_LINE DEDENT findFullNode ( root . right ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . right . left = newNode ( 5 ) NEW_LINE root . right . right = newNode ( 6 ) NEW_LINE root . right . left . right = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE root . right . left . right . left = newNode ( 9 ) NEW_LINE findFullNode ( root ) NEW_LINE DEDENT
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 . sort ( ) NEW_LINE print ( fin [ k - 1 ] ) NEW_LINE DEDENT s = " geeksforgeeks " NEW_LINE k = 5 NEW_LINE n = len ( s ) NEW_LINE kThLexString ( s , k , n ) NEW_LINE
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 array ; fill up odd position in original array ; fill up even positions in original array ; display array ; Driver code
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 ( ) NEW_LINE j = oddPos - 1 NEW_LINE for i in range ( 0 , n , 2 ) : NEW_LINE INDENT arr [ i ] = tempArr [ j ] NEW_LINE j = j - 1 NEW_LINE DEDENT j = oddPos NEW_LINE for i in range ( 1 , n , 2 ) : NEW_LINE INDENT arr [ i ] = tempArr [ j ] NEW_LINE j = j + 1 NEW_LINE DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT arr = a . array ( ' i ' , [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ] ) NEW_LINE rearrangeArr ( arr , 7 ) NEW_LINE
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 print the array such that only non primes are sorted ; list v will store all non prime numbers ; If not prime , insert into list ; sorting list of non primes ; print the required array ; Driver code
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_LINE INDENT for i in range ( p * 2 , n , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def sortedArray ( arr , n ) : NEW_LINE INDENT SieveOfEratosthenes ( 100005 ) NEW_LINE v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prime [ arr [ i ] ] == 0 : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( ) NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prime [ arr [ i ] ] == True : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( v [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE arr = [ 100 , 11 , 500 , 2 , 17 , 1 ] NEW_LINE sortedArray ( arr , n ) NEW_LINE DEDENT
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 ) + addBT ( root . right ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 1 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 3 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 5 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 7 ) NEW_LINE root . right . left . right = newNode ( 8 ) NEW_LINE sum = addBT ( root ) NEW_LINE print ( " Sum ▁ of ▁ all ▁ the ▁ nodes ▁ is : " , sum ) NEW_LINE DEDENT
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 ) in final sequence so that we have large difference value . This process is repeated till all array has completely entered in sequence . Here , we have loop till n / 2 because we are inserting two elements at a time in loop . ; If there are odd elements , push the middle element at the end . ; variable to store the maximum sum of absolute difference ; In this loop absolute difference of elements for the final sequence is calculated . ; absolute difference of last element and 1 st element ; return the value ; Driver Code
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 [ n - i - 1 ] NEW_LINE j = j + 2 NEW_LINE DEDENT if ( n % 2 != 0 ) : NEW_LINE finalSequence [ n - 1 ] = a [ n // 2 + 1 ] NEW_LINE MaximumSum = 0 NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT MaximumSum = ( MaximumSum + abs ( finalSequence [ i ] - finalSequence [ i + 1 ] ) ) NEW_LINE DEDENT MaximumSum = ( MaximumSum + abs ( finalSequence [ n - 1 ] - finalSequence [ 0 ] ) ) ; NEW_LINE print ( MaximumSum ) NEW_LINE DEDENT DEDENT a = [ 1 , 2 , 4 , 8 ] NEW_LINE n = len ( a ) NEW_LINE GFG . MaxSumDifference ( a , n ) ; NEW_LINE
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 with ' bad ' value of current window ; Decrement count of previous window ; Increment count of current window ; Update ans if count of ' bad ' is less in current window ; Driver code
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 DEDENT DEDENT ans = bad NEW_LINE j = count NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( j == n ) : NEW_LINE INDENT break NEW_LINE DEDENT if ( arr [ i ] > k ) : NEW_LINE INDENT bad = bad - 1 NEW_LINE DEDENT if ( arr [ j ] > k ) : NEW_LINE INDENT bad = bad + 1 NEW_LINE DEDENT ans = min ( ans , bad ) NEW_LINE j = j + 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT arr = [ 2 , 1 , 5 , 6 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( minSwap ( arr , n , k ) ) NEW_LINE arr1 = [ 2 , 7 , 9 , 5 , 8 , 7 , 4 ] NEW_LINE n = len ( arr1 ) NEW_LINE k = 5 NEW_LINE print ( minSwap ( arr1 , n , k ) ) NEW_LINE
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 head of the array in each step ; exit condition ; rearrange the array except the first element in each recursive call ; If the first element of the array is positive , then right - rotate the array by one place first and then reverse the merged array . ; Driver code
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 INDENT while ( start < end ) : NEW_LINE INDENT temp = array [ start ] NEW_LINE array [ start ] = array [ end ] NEW_LINE array [ end ] = temp NEW_LINE start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT DEDENT def rearrange ( array , start , end ) : NEW_LINE INDENT if ( start == end ) : NEW_LINE INDENT return NEW_LINE DEDENT rearrange ( array , ( start + 1 ) , end ) NEW_LINE if ( array [ start ] >= 0 ) : NEW_LINE INDENT reverse ( array , ( start + 1 ) , end ) NEW_LINE reverse ( array , start , end ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT array = [ - 12 , - 11 , - 13 , - 5 , - 6 , 7 , 5 , 3 , 6 ] NEW_LINE length = len ( array ) NEW_LINE countNegative = 0 NEW_LINE for i in range ( length ) : NEW_LINE INDENT if ( array [ i ] < 0 ) : NEW_LINE INDENT countNegative += 1 NEW_LINE DEDENT DEDENT print ( " array : ▁ " , end = " " ) NEW_LINE printArray ( array , length ) NEW_LINE rearrange ( array , 0 , ( length - 1 ) ) NEW_LINE reverse ( array , countNegative , ( length - 1 ) ) NEW_LINE print ( " rearranged ▁ array : ▁ " , end = " " ) NEW_LINE printArray ( array , length ) NEW_LINE DEDENT
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 of rightmost - subarray of size k ; else i is current left pointer index ; j is current right pointer index ; CASE III if k is odd and rightmost element in sorted array is positive then it must come in subsequence Multiplying A [ j ] with product and correspondingly changing j ; CASE IV Now k is even . So , Now we deal with pairs Each time a pair is multiplied to product ie . . two elements are added to subsequence each time . Effectively k becomes half Hence , k >>= 1 means k /= 2 ; Now finding k corresponding pairs to get maximum possible value of product ; product from left pointers ; product from right pointers ; Taking the max product from two choices . Correspondingly changing the pointer 's position ; Finally return product ; Driver Code
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 ] NEW_LINE DEDENT return product NEW_LINE DEDENT i = 0 NEW_LINE j = n - 1 NEW_LINE if ( k & 1 ) : NEW_LINE INDENT product *= A [ j ] NEW_LINE j -= 1 NEW_LINE k -= 1 NEW_LINE DEDENT k >>= 1 NEW_LINE for itr in range ( k ) : NEW_LINE INDENT left_product = A [ i ] * A [ i + 1 ] NEW_LINE right_product = A [ j ] * A [ j - 1 ] NEW_LINE if ( left_product > right_product ) : NEW_LINE INDENT product *= left_product NEW_LINE i += 2 NEW_LINE DEDENT else : NEW_LINE INDENT product *= right_product NEW_LINE j -= 2 NEW_LINE DEDENT DEDENT return product NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 1 , 2 , - 1 , - 3 , - 6 , 4 ] NEW_LINE n = len ( A ) NEW_LINE k = 4 NEW_LINE print ( maxProductSubarrayOfSizeK ( A , n , k ) ) NEW_LINE DEDENT
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_LINE index = [ 3 , 0 , 4 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE reorder ( arr , index , n ) NEW_LINE print ( " Reordered ▁ array ▁ is : " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " Modified Index array is : " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( index [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 ) position . Also copy corrected index for new position ; Copy old target values to arr [ i ] and index [ i ] ; Driver program
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 ] = oldTargetI NEW_LINE arr [ i ] = oldTargetE NEW_LINE DEDENT DEDENT DEDENT arr = [ 50 , 40 , 70 , 60 , 90 ] NEW_LINE index = [ 3 , 0 , 4 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE reorder ( arr , index , n ) NEW_LINE print ( " Reordered ▁ array ▁ is : " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( " Modified Index array is : " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( index [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 function to sort the array ; Display the sorted array
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 ( arr , l , ( h - t ) ) NEW_LINE stoogesort ( arr , l + t , ( h ) ) NEW_LINE stoogesort ( arr , l , ( h - t ) ) NEW_LINE DEDENT DEDENT arr = [ 2 , 4 , 5 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE stoogesort ( arr , 0 , n - 1 ) NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' ▁ ' ) NEW_LINE DEDENT DEDENT
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 element ) with the last element ; Swap arr whenever index is swapped ; Driver Code
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 ] ) : NEW_LINE INDENT largest = right NEW_LINE DEDENT if ( largest != i ) : NEW_LINE INDENT arr [ largest ] , arr [ i ] = arr [ i ] , arr [ largest ] NEW_LINE index [ largest ] , index [ i ] = index [ i ] , index [ largest ] NEW_LINE heapify ( arr , index , largest ) NEW_LINE DEDENT DEDENT def heapSort ( arr , index , n ) : NEW_LINE INDENT global heapSize NEW_LINE for i in range ( int ( ( n - 1 ) / 2 ) , - 1 , - 1 ) : NEW_LINE INDENT heapify ( arr , index , i ) NEW_LINE DEDENT for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT index [ 0 ] , index [ i ] = index [ i ] , index [ 0 ] NEW_LINE arr [ 0 ] , arr [ i ] = arr [ i ] , arr [ 0 ] NEW_LINE heapSize -= 1 NEW_LINE heapify ( arr , index , 0 ) NEW_LINE DEDENT DEDENT arr = [ 50 , 40 , 70 , 60 , 90 ] NEW_LINE index = [ 3 , 0 , 4 , 1 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE global heapSize NEW_LINE heapSize = n NEW_LINE heapSort ( arr , index , n ) NEW_LINE print ( " Reordered ▁ array ▁ is : ▁ " ) NEW_LINE print ( * arr , sep = ' ▁ ' ) NEW_LINE print ( " Modified ▁ Index ▁ array ▁ is : ▁ " ) NEW_LINE print ( * index , sep = ' ▁ ' ) NEW_LINE
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 the left and right subtree ; utility function to find the Sum of all the parent nodes having child node x ; required Sum of parent nodes ; Driver Code ; binary tree formation 4 ; / \ ; 2 5 ; / \ / \ ; 7 2 2 3
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 == x ) or ( root . right and root . right . data == x ) ) : NEW_LINE INDENT Sum [ 0 ] += root . data NEW_LINE DEDENT SumOfParentOfX ( root . left , Sum , x ) NEW_LINE SumOfParentOfX ( root . right , Sum , x ) NEW_LINE DEDENT def SumOfParentOfXUtil ( root , x ) : NEW_LINE INDENT Sum = [ 0 ] NEW_LINE SumOfParentOfX ( root , Sum , x ) NEW_LINE return Sum [ 0 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = getNode ( 4 ) NEW_LINE root . left = getNode ( 2 ) NEW_LINE root . right = getNode ( 5 ) NEW_LINE root . left . left = getNode ( 7 ) NEW_LINE root . left . right = getNode ( 2 ) NEW_LINE root . right . left = getNode ( 2 ) NEW_LINE root . right . right = getNode ( 3 ) NEW_LINE x = 2 NEW_LINE print ( " Sum ▁ = ▁ " , SumOfParentOfXUtil ( root , x ) ) NEW_LINE DEDENT
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 ; Driver Program
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_LINE for i in range ( int ( ( n + 1 ) / 2 ) ) : NEW_LINE INDENT arr_f . append ( arr [ i ] ) NEW_LINE DEDENT i = int ( ( n + 1 ) / 2 ) NEW_LINE while ( i < n ) : NEW_LINE INDENT arr_s . append ( arr [ i ] ) NEW_LINE i = i + 1 NEW_LINE DEDENT arr_f . sort ( ) NEW_LINE arr_s . sort ( reverse = True ) NEW_LINE for i in arr_s : NEW_LINE INDENT arr_f . append ( i ) NEW_LINE DEDENT return arr_f NEW_LINE DEDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE arr = bitonicGenerator ( arr , n ) NEW_LINE print ( arr ) NEW_LINE
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 [ index - 1 ] , arr [ index ] NEW_LINE index = index - 1 NEW_LINE DEDENT DEDENT return arr NEW_LINE DEDENT arr = [ 34 , 2 , 10 , - 9 ] NEW_LINE n = len ( arr ) NEW_LINE arr = gnomeSort ( arr , n ) NEW_LINE print " Sorted ▁ sequence ▁ after ▁ applying ▁ Gnome ▁ Sort ▁ : " , NEW_LINE for i in arr : NEW_LINE INDENT print i , NEW_LINE DEDENT
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 in the next stage ; move the end point back by one , because item at the end is in its rightful spot ; from right to left , doing the same comparison as in the previous stage ; increase the starting point , because the last stage would have moved the next smallest number to its rightful spot . ; Driver code
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 [ i + 1 ] , a [ i ] NEW_LINE swapped = True NEW_LINE DEDENT DEDENT if ( swapped == False ) : NEW_LINE INDENT break NEW_LINE DEDENT swapped = False NEW_LINE end = end - 1 NEW_LINE for i in range ( end - 1 , start - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] > a [ i + 1 ] ) : NEW_LINE INDENT a [ i ] , a [ i + 1 ] = a [ i + 1 ] , a [ i ] NEW_LINE swapped = True NEW_LINE DEDENT DEDENT start = start + 1 NEW_LINE DEDENT DEDENT a = [ 5 , 1 , 4 , 2 , 8 , 0 , 2 ] NEW_LINE cocktailSort ( a ) NEW_LINE print ( " Sorted ▁ array ▁ is : " ) NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT print ( " % ▁ d " % a [ i ] ) NEW_LINE DEDENT
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 guests ; Update max_guests if needed ; increment index of arrival array ; If event is exit , decrement count ; of guests . ; Driver Code
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 guests_in = guests_in + 1 ; NEW_LINE if ( guests_in > max_guests ) : NEW_LINE INDENT max_guests = guests_in ; NEW_LINE time = arrl [ i ] ; NEW_LINE DEDENT i = i + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT guests_in = guests_in - 1 ; NEW_LINE j = j + 1 ; NEW_LINE DEDENT DEDENT print ( " Maximum ▁ Number ▁ of ▁ Guests ▁ = " , max_guests , " at ▁ time " , time ) NEW_LINE DEDENT arrl = [ 1 , 2 , 10 , 5 , 5 ] ; NEW_LINE exit = [ 4 , 5 , 12 , 9 , 12 ] ; NEW_LINE n = len ( arrl ) ; NEW_LINE findMaxGuests ( arrl , exit , n ) ; NEW_LINE
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 utility function to print contents of arr [ 0. . n - 1 ] ; Driver program
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 ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 3 , 0 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given ▁ array ▁ is " , end = " ▁ " ) NEW_LINE printArray ( arr , n ) NEW_LINE rearrangeNaive ( arr , n ) NEW_LINE print ( " Modified array is " , ▁ end ▁ = ▁ " " ) NEW_LINE printArray ( arr , n ) NEW_LINE
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 pr contents of arr [ 0. . n - 1 ] ; Driver code
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 = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 2 , 0 , 1 , 4 , 5 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given ▁ array ▁ is ▁ : ▁ " ) NEW_LINE prArray ( arr , n ) NEW_LINE rearrange ( arr , n ) NEW_LINE print ( " Modified ▁ array ▁ is ▁ : " ) NEW_LINE prArray ( arr , n ) NEW_LINE
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 copy rmaining largest or remaining smallest at next position ; Store result in temp [ ] ; Copy temp [ ] to arr [ ] ; Driver code
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_LINE small += 1 NEW_LINE DEDENT flag = bool ( 1 - flag ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = temp [ i ] NEW_LINE DEDENT return arr NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Original ▁ Array " ) NEW_LINE print ( arr ) NEW_LINE print ( " Modified ▁ Array " ) NEW_LINE print ( rearrange ( arr , n ) ) NEW_LINE
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 remove the element ; Second pointer to reach end of type 1 elements ; Increment j until arr [ j ] is equal to 1 and j is not out of bounds ; Number of type 1 elements in a continious chunk ; From next iteration i pointer will start from index of j ; Return the minimum count of coins ; Driver Code
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 INDENT j += 1 NEW_LINE DEDENT x = ( j - i ) NEW_LINE coins += x // 3 NEW_LINE i = j - 1 NEW_LINE DEDENT return coins NEW_LINE DEDENT N = 8 NEW_LINE arr = [ 1 , 2 , 1 , 1 , 2 , 1 , 1 , 1 ] NEW_LINE print ( minimumcoins ( arr , N ) ) NEW_LINE
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 elements ; At even index : we have to put maximum element ; At odd index : we have to put minimum element ; array elements back to it 's original form ; Driver Code
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 arr [ i ] += ( arr [ min_idx ] % max_elem ) * max_elem NEW_LINE min_idx += 1 NEW_LINE DEDENT DEDENT for i in range ( 0 , n ) : NEW_LINE INDENT arr [ i ] = arr [ i ] / max_elem NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Original ▁ Array " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT rearrange ( arr , n ) NEW_LINE print ( " Modified Array " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( int ( arr [ i ] ) , end = " ▁ " ) NEW_LINE DEDENT
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 put maximum element ; at odd index : we have to put minimum element ; Driver code
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 DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Origianl ▁ Array " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT rearrange ( arr , n ) NEW_LINE print ( " Modified Array " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 recur for left child of root ; Recur for right child of root and update res ; return result ; Driver program to test above function
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 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def leftLeavesSum ( root ) : NEW_LINE INDENT res = 0 NEW_LINE if root is not None : NEW_LINE INDENT if isLeaf ( root . left ) : NEW_LINE INDENT res += root . left . key NEW_LINE DEDENT else : NEW_LINE INDENT res += leftLeavesSum ( root . left ) NEW_LINE DEDENT res += leftLeavesSum ( root . right ) NEW_LINE DEDENT return res NEW_LINE DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 9 ) NEW_LINE root . right = Node ( 49 ) NEW_LINE root . right . left = Node ( 23 ) NEW_LINE root . right . right = Node ( 52 ) NEW_LINE root . right . right . left = Node ( 50 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . right = Node ( 12 ) NEW_LINE print " Sum ▁ of ▁ left ▁ leaves ▁ is " , leftLeavesSum ( root ) NEW_LINE
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 , - 7 , 8 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE rearrange ( arr , n ) NEW_LINE
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 sum from the last column ; Driver code ; Columns are indexed 1 - based
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 in range ( 1 , m , 1 ) : NEW_LINE INDENT mx = 0 NEW_LINE for k in range ( 1 , m , 1 ) : NEW_LINE INDENT if ( k != j ) : NEW_LINE INDENT if ( dp [ k ] [ i - 1 ] > mx ) : NEW_LINE INDENT mx = dp [ k ] [ i - 1 ] NEW_LINE DEDENT DEDENT DEDENT if ( mx and arr [ j ] [ i ] ) : NEW_LINE INDENT dp [ j ] [ i ] = arr [ j ] [ i ] + mx NEW_LINE DEDENT DEDENT DEDENT ans = - 1 NEW_LINE for i in range ( 1 , m , 1 ) : NEW_LINE INDENT if ( dp [ i ] [ n ] ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] [ n ] ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 10 , 2 , 20 , 0 ] , [ 0 , 0 , 0 , 5 , 0 ] , [ 0 , 0 , 0 , 0 , 6 ] , [ 0 , 4 , 0 , 11 , 5 ] , [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 0 ] ] NEW_LINE print ( maxSum ( arr ) ) NEW_LINE DEDENT
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 ; Copy contents of temp [ ] to arr [ ] ; Driver program
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 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 for k in range ( n ) : NEW_LINE INDENT arr [ k ] = temp [ k ] NEW_LINE DEDENT DEDENT arr = [ 1 , - 1 , - 3 , - 2 , 7 , 5 , 11 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE segregateElements ( arr , n ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT
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 temp = arr [ i ] NEW_LINE arr [ i ] = arr [ i + 1 ] NEW_LINE arr [ i + 1 ] = temp NEW_LINE DEDENT DEDENT DEDENT def printArray ( arr , size ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , " ▁ " , end = " " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 6 , 4 , 2 , 1 , 8 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Before ▁ rearranging : ▁ " ) NEW_LINE printArray ( arr , n ) NEW_LINE rearrange ( arr , n ) NEW_LINE print ( " After ▁ rearranging : " ) NEW_LINE printArray ( arr , n ) ; NEW_LINE
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 would be least therefore break ; If minDis value is not updated that means no repeating characters ; Minimum distance is minDis - 1 ; Given Input ; Function Call
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 ) ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return minDis - 1 NEW_LINE DEDENT DEDENT S = " geeksforgeeks " NEW_LINE N = 13 NEW_LINE print ( shortestDistance ( S , N ) ) NEW_LINE
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 array elements to fix their position . ; Break from the while loop when any index exceeds the size of the array ; Driver code
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 + 2 NEW_LINE DEDENT if ( positive < size and negative < size ) : NEW_LINE INDENT temp = a [ positive ] NEW_LINE a [ positive ] = a [ negative ] NEW_LINE a [ negative ] = temp NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , - 3 , 5 , 6 , - 3 , 6 , 7 , - 4 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE rearrange ( arr , n ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT
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 + M * A ; For finding other numbers , subtract A from number 1 time and add B to number 1 time ; Driver Code ; Given Input ; Function Call
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 print ( number , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE M = 3 NEW_LINE A = 4 NEW_LINE B = 6 NEW_LINE possibleNumbers ( N , M , A , B ) NEW_LINE DEDENT
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 array ; after modification
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 and i % 2 == 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] < 0 and j % 2 == 0 ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT elif ( arr [ i ] < 0 and i % 2 == 0 ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] >= 0 and j % 2 == 1 ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT DEDENT printArray ( arr , n ) ; NEW_LINE
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 ) : NEW_LINE INDENT a [ ind ] = arr [ i ] NEW_LINE ind += 1 NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT print ( a [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT arr = [ 1 , 3 , 2 , 4 , 7 , 6 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE arrayEvenAndOdd ( arr , n ) NEW_LINE
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 ) + " ▁ " , end = ' ' ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 3 , 2 , 4 , 7 , 6 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE arrayEvenAndOdd ( arr , n ) NEW_LINE DEDENT
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 Binary Tree shown in the above figure
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 root . right is None and isLeft == True : NEW_LINE INDENT summ [ 0 ] += root . key NEW_LINE DEDENT leftLeavesSumRec ( root . left , 1 , summ ) NEW_LINE leftLeavesSumRec ( root . right , 0 , summ ) NEW_LINE DEDENT def leftLeavesSum ( root ) : NEW_LINE INDENT summ = [ 0 ] NEW_LINE leftLeavesSumRec ( root , 0 , summ ) NEW_LINE return summ [ 0 ] NEW_LINE DEDENT root = Node ( 20 ) ; NEW_LINE root . left = Node ( 9 ) ; NEW_LINE root . right = Node ( 49 ) ; NEW_LINE root . right . left = Node ( 23 ) ; NEW_LINE root . right . right = Node ( 52 ) ; NEW_LINE root . right . right . left = Node ( 50 ) ; NEW_LINE root . left . left = Node ( 5 ) ; NEW_LINE root . left . right = Node ( 12 ) ; NEW_LINE root . left . right . right = Node ( 12 ) ; NEW_LINE print " Sum ▁ of ▁ left ▁ leaves ▁ is " , leftLeavesSum ( root ) NEW_LINE
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 of left tree and right subtree of the right tree have to be mirror images 3 - right subtree of left tree and left subtree of right tree have to be mirror images ; If none of the above conditions is true then root1 and root2 are not mirror images ; returns true if the tree is symmetric i . e mirror image of itself ; Check if tree is mirror of itself ; Let 's construct the tree show in the above figure
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 None and root2 is not None ) : NEW_LINE INDENT if root1 . key == root2 . key : NEW_LINE INDENT return ( isMirror ( root1 . left , root2 . right ) and isMirror ( root1 . right , root2 . left ) ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def isSymmetric ( root ) : NEW_LINE INDENT return isMirror ( root , root ) NEW_LINE DEDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . right = Node ( 2 ) NEW_LINE root . left . left = Node ( 3 ) NEW_LINE root . left . right = Node ( 4 ) NEW_LINE root . right . left = Node ( 4 ) NEW_LINE root . right . right = Node ( 3 ) NEW_LINE print " Symmetric " if isSymmetric ( root ) == True else " Not ▁ symmetric " NEW_LINE
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 ; Traverse the matrix to perform vertical operations ; Calculate difference ; Update next K elements ; A [ i ] [ j ] is not equal to B [ i ] [ j ] ; Conversion is not possible ; Conversion is possible ; Driver Code ; Input
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 ] + diff NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( M - X + 1 ) : NEW_LINE INDENT for j in range ( N ) : 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 + k ] [ j ] = A [ i + k ] [ j ] + diff NEW_LINE DEDENT DEDENT DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( A [ i ] [ j ] != B [ i ] [ j ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT return 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M , N , X = 2 , 2 , 2 NEW_LINE A = [ [ 0 , 0 ] , [ 0 , 0 ] ] NEW_LINE B = [ [ 1 , 2 ] , [ 0 , 1 ] ] NEW_LINE if ( Check ( A , B , M , N , X ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 minimum number of operations required ; Count operations required to convert current element to mx ; Print the answer ; Given array ; Size of the array
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 in mp : NEW_LINE INDENT if ( mp [ it ] == N ) : NEW_LINE mx = it NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT res = arr [ i ] NEW_LINE while ( res != mx ) : NEW_LINE ans += 1 NEW_LINE res //= 2 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT arr = [ 3 , 1 , 1 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE minOperations ( arr , N ) NEW_LINE
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 ( Winner ( N ) ) NEW_LINE
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_LINE count += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT arr = [ 12 , 45 , 1 , - 1 , 45 , 54 , 23 , 5 , 0 , - 10 ] NEW_LINE n = len ( arr ) NEW_LINE find3largest ( arr , n ) NEW_LINE
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 largest frequency is present at the top ; Stores minimum count of characters required to be deleted to make frequency of each character unique ; Traverse the string ; Update frequency of str [ i ] ; Traverse the map ; Insert current frequency into pq ; Traverse the priority_queue ; Stores topmost element of pq ; Pop the topmost element ; If pq is empty ; Return cntChar ; If frequent and topmost element of pq are equal ; If frequency of the topmost element is greater than 1 ; Insert the decremented value of frequent ; Update cntChar ; Driver Code ; Stores length of str
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_LINE while ( len ( pq ) > 0 ) : NEW_LINE INDENT frequent = pq [ - 1 ] NEW_LINE del pq [ - 1 ] NEW_LINE if ( len ( pq ) == 0 ) : NEW_LINE INDENT return cntChar NEW_LINE DEDENT if ( frequent == pq [ - 1 ] ) : NEW_LINE INDENT if ( frequent > 1 ) : NEW_LINE INDENT pq . append ( frequent - 1 ) NEW_LINE DEDENT cntChar += 1 NEW_LINE DEDENT pq = sorted ( pq ) NEW_LINE DEDENT return cntChar NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " abbbcccd " NEW_LINE N = len ( str ) NEW_LINE print ( minCntCharDeletionsfrequency ( str , N ) ) NEW_LINE DEDENT
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 DEDENT return float ( ( a [ int ( ( n - 1 ) / 2 ) ] + a [ int ( n / 2 ) ] ) / 2.0 ) NEW_LINE DEDENT a = [ 1 , 3 , 4 , 2 , 7 , 5 , 8 , 6 ] NEW_LINE n = len ( a ) NEW_LINE print ( " Mean ▁ = " , findMean ( a , n ) ) NEW_LINE print ( " Median ▁ = " , findMedian ( a , n ) ) NEW_LINE
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 leaf , add its data to the sum ; Driver Code
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 ( root ) NEW_LINE sum = 0 NEW_LINE while len ( stack ) > 0 : NEW_LINE INDENT currentNode = stack . pop ( ) NEW_LINE if currentNode . left is not None : NEW_LINE INDENT stack . append ( currentNode . left ) NEW_LINE if currentNode . left . left is None and currentNode . left . right is None : NEW_LINE INDENT sum = sum + currentNode . left . data NEW_LINE DEDENT DEDENT if currentNode . right is not None : NEW_LINE INDENT stack . append ( currentNode . right ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT root = Tree ( 20 ) ; NEW_LINE root . left = Tree ( 9 ) ; NEW_LINE root . right = Tree ( 49 ) ; NEW_LINE root . right . left = Tree ( 23 ) ; NEW_LINE root . right . right = Tree ( 52 ) ; NEW_LINE root . right . right . left = Tree ( 50 ) ; NEW_LINE root . left . left = Tree ( 5 ) ; NEW_LINE root . left . right = Tree ( 12 ) ; NEW_LINE root . left . right . right = Tree ( 12 ) ; NEW_LINE print ( ' Sum ▁ of ▁ left ▁ leaves ▁ is ▁ { } ' . format ( sumOfLeftLeaves ( root ) ) ) NEW_LINE
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 ( N ) NEW_LINE DEDENT
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 element is negative ; Update ans and recursively call with update value of flag ; Return maximum sum subsequence ; Function that finds the maximum sum of element of the subsequence with alternate + ve and - ve signs ; Create auxiliary array dp [ ] [ ] ; Function call ; Driver Code ; Given array arr [ ] ; Function call
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 ] + findMax ( a , dp , i + 1 , 1 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( findMax ( a , dp , i + 1 , 1 ) , - 1 * a [ i ] + findMax ( a , dp , i + 1 , 0 ) ) NEW_LINE DEDENT dp [ i ] [ flag ] = ans NEW_LINE return ans NEW_LINE DEDENT def findMaxSumUtil ( arr , N ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( 2 ) ] for i in range ( N ) ] NEW_LINE print ( findMax ( arr , dp , 0 , 0 ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE findMaxSumUtil ( arr , N ) NEW_LINE DEDENT
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 increment the consonants count ; Check if Player B wins ; Check if Player A wins ; Check if Player A wins ; If game ends in a Draw ; Given String s ; Function Call
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_LINE DEDENT else : NEW_LINE INDENT consonants_count = consonants_count + 1 NEW_LINE DEDENT DEDENT if ( vowels_count == 0 ) : NEW_LINE INDENT if ( consonants_count % 2 == 0 ) : NEW_LINE INDENT print ( " Player ▁ B " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Player ▁ A " ) NEW_LINE DEDENT DEDENT elif ( vowels_count == 1 and consonants_count % 2 != 0 ) : NEW_LINE INDENT print ( " Player ▁ A " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " D " ) NEW_LINE DEDENT DEDENT s = " abcd " NEW_LINE findWinner ( s ) NEW_LINE
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 through maxi array . If cand [ j ] > maxi [ i ] insert cand [ j ] at the ith position in the maxi array and remove the minimum element of the maxi array i . e . the last element and increase j by 1 i . e . take the next element from cand . ; Insert prefix_sum [ i ] to mini array if needed ; Traverse the mini array from left to right . If prefix_sum [ i ] is less than any element then insert prefix_sum [ i ] at that position and delete maximum element of the mini array i . e . the rightmost element from the array . ; Function to compute k maximum overlapping sub - array sums ; Compute the prefix sum of the input array . ; Set all the elements of mini as + infinite except 0 th . Set the 0 th element as 0. ; Set all the elements of maxi as - infinite . ; Initialize cand array . ; For each element of the prefix_sum array do : compute the cand array . take k maximum values from maxi and cand using maxmerge function . insert prefix_sum [ i ] to mini array if needed using insertMini function . ; Elements of maxi array is the k maximum overlapping sub - array sums . Print out the elements of maxi array . ; Test case 1 ; Test case 2
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 ) NEW_LINE j = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( cand [ j ] > maxi [ i ] ) : NEW_LINE INDENT maxi . insert ( i , cand [ j ] ) NEW_LINE del maxi [ - 1 ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT def insertMini ( mini , pre_sum ) : NEW_LINE INDENT k = len ( mini ) NEW_LINE for i in range ( k ) : NEW_LINE INDENT if ( pre_sum < mini [ i ] ) : NEW_LINE INDENT mini . insert ( i , pre_sum ) NEW_LINE del mini [ - 1 ] NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT def kMaxOvSubArray ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE pre_sum = prefix_sum ( arr , n ) NEW_LINE mini = [ float ( ' inf ' ) for i in range ( k ) ] NEW_LINE mini [ 0 ] = 0 NEW_LINE maxi = [ - float ( ' inf ' ) for i in range ( k ) ] NEW_LINE cand = [ 0 for i in range ( k ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( k ) : NEW_LINE INDENT cand [ j ] = pre_sum [ i ] - mini [ j ] NEW_LINE DEDENT maxMerge ( maxi , cand ) NEW_LINE insertMini ( mini , pre_sum [ i ] ) NEW_LINE DEDENT for ele in maxi : NEW_LINE INDENT print ( ele , end = ' ▁ ' ) NEW_LINE DEDENT print ( ' ' ) NEW_LINE DEDENT arr1 = [ 4 , - 8 , 9 , - 4 , 1 , - 8 , - 1 , 6 ] NEW_LINE k1 = 4 NEW_LINE kMaxOvSubArray ( arr1 , k1 ) NEW_LINE arr2 = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE k2 = 3 NEW_LINE kMaxOvSubArray ( arr2 , k2 ) NEW_LINE
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 left ; make arr [ k - 1 ] = arr [ i ] ; print result ; Driver program
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 > arr [ i ] ) : NEW_LINE INDENT j = pos NEW_LINE while ( j < k - 1 ) : NEW_LINE INDENT arr [ j ] = arr [ j + 1 ] NEW_LINE j += 1 NEW_LINE DEDENT arr [ k - 1 ] = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 0 , k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE printSmall ( arr , n , k ) NEW_LINE
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 [ ] . Initially all values are considered 0. Here current index is the index before which all elements are considered as part of output . ; Initialize current pair sum as infinite ; To pick next pair , traverse for all elements of arr1 [ ] , for every element , find corresponding current element in arr2 [ ] and pick minimum of all formed pairs . ; Check if current element of arr1 [ ] plus element of array2 to be used gives minimum sum ; Update index that gives minimum ; update minimum sum ; Driver code
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 = 0 NEW_LINE for i1 in range ( 0 , n1 , 1 ) : NEW_LINE INDENT if ( index2 [ i1 ] < n2 and arr1 [ i1 ] + arr2 [ index2 [ i1 ] ] < min_sum ) : NEW_LINE INDENT min_index = i1 NEW_LINE min_sum = arr1 [ i1 ] + arr2 [ index2 [ i1 ] ] NEW_LINE DEDENT DEDENT print ( " ( " , arr1 [ min_index ] , " , " , arr2 [ index2 [ min_index ] ] , " ) " , end = " ▁ " ) NEW_LINE index2 [ min_index ] += 1 NEW_LINE k -= 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr1 = [ 1 , 3 , 11 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE arr2 = [ 2 , 4 , 8 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE k = 4 NEW_LINE kSmallestPair ( arr1 , n1 , arr2 , n2 , k ) NEW_LINE DEDENT
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 conditions ; Driver Code
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 , 11 , 2 , 9 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE X = 10 NEW_LINE print ( maxSubset ( arr , N , X ) ) NEW_LINE
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 ; Driver Code
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 all columns ; Compute the prefix sum of all rows ; Get the final matrix by adding mat and aux matrix at each cell ; Function that prints matrix mat [ ] ; Traverse each row ; Traverse each columns ; Function that performs each query in the given matrix and print the updated matrix after each operation performed ; Initialize all elements to 0 ; Update auxiliary matrix by traversing each query ; Update Query ; Compute the final answer ; Print the updated matrix ; Driver Code ; Given 4 atrix ; Given Queries ; Function Call
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 + 1 < 4 ) : NEW_LINE INDENT aux [ from_x ] [ to_y + 1 ] -= k NEW_LINE DEDENT return aux NEW_LINE DEDENT def updatematrix ( mat , aux ) : NEW_LINE INDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 1 , 4 ) : NEW_LINE INDENT aux [ i ] [ j ] += aux [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 4 ) : NEW_LINE INDENT for j in range ( 1 , 3 ) : NEW_LINE INDENT aux [ j ] [ i ] += aux [ j - 1 ] [ i ] NEW_LINE DEDENT DEDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 4 ) : NEW_LINE INDENT mat [ i ] [ j ] += aux [ i ] [ j ] NEW_LINE DEDENT DEDENT return mat NEW_LINE DEDENT def printmatrix ( mat ) : NEW_LINE INDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 4 ) : NEW_LINE INDENT print ( mat [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT def matrixQuery ( mat , Q , q ) : NEW_LINE INDENT aux = [ [ 0 for i in range ( 4 ) ] for i in range ( 3 ) ] NEW_LINE for i in range ( Q ) : NEW_LINE INDENT updateQuery ( q [ i ] [ 0 ] , q [ i ] [ 1 ] , q [ i ] [ 2 ] , q [ i ] [ 3 ] , q [ i ] [ 4 ] , aux ) NEW_LINE DEDENT updatematrix ( mat , aux ) NEW_LINE printmatrix ( mat ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT mat = [ [ 1 , 0 , 1 , 2 ] , [ 0 , 2 , 4 , 1 ] , [ 1 , 2 , 1 , 0 ] ] NEW_LINE Q = 1 NEW_LINE q = [ [ 0 , 0 , 1 , 1 , 2 ] ] NEW_LINE matrixQuery ( mat , Q , q ) NEW_LINE DEDENT
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 ▁ largest ▁ element ▁ is " , arr [ i ] ) NEW_LINE return NEW_LINE DEDENT print ( " There ▁ is ▁ no ▁ second ▁ largest ▁ element " ) NEW_LINE DEDENT arr = [ 12 , 35 , 1 , 10 , 34 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print2largest ( arr , n ) NEW_LINE
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 ; If temp is a leaf node and left child of its parent ; If it is not leaf then push its children nodes into queue ; Boolean value is true here because it is left child of its parent ; Boolean value is false here because it is right child of its parent ; Driver Code
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 = deque ( ) NEW_LINE q . append ( [ root , 0 ] ) NEW_LINE sum = 0 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT temp = q [ 0 ] [ 0 ] NEW_LINE is_left_child = q [ 0 ] [ 1 ] NEW_LINE q . popleft ( ) NEW_LINE if ( not temp . left and not temp . right and is_left_child ) : NEW_LINE INDENT sum = sum + temp . key NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT q . append ( [ temp . left , 1 ] ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( [ temp . right , 0 ] ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 9 ) NEW_LINE root . right = Node ( 49 ) NEW_LINE root . right . left = Node ( 23 ) NEW_LINE root . right . right = Node ( 52 ) NEW_LINE root . right . right . left = Node ( 50 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . right = Node ( 12 ) NEW_LINE print ( " Sum ▁ of ▁ left ▁ leaves ▁ is " , sumOfLeftLeaves ( root ) ) NEW_LINE DEDENT
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 range ( 0 , arr_size ) : NEW_LINE INDENT if ( arr [ i ] != largest ) : NEW_LINE INDENT second = max ( second , arr [ i ] ) ; NEW_LINE DEDENT DEDENT if ( second == - 2454635434 ) : NEW_LINE INDENT print ( " There ▁ is ▁ no ▁ second ▁ " + " largest ▁ element " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ second ▁ largest ▁ " + " element is " , second ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 12 , 35 , 1 , 10 , 34 , 1 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print2largest ( arr , n ) ; NEW_LINE DEDENT
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 = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] > second and arr [ i ] != first ) : NEW_LINE INDENT second = arr [ i ] NEW_LINE DEDENT DEDENT if ( second == - 2147483648 ) : NEW_LINE INDENT print ( " There ▁ is ▁ no ▁ second ▁ largest ▁ element " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " The ▁ second ▁ largest ▁ element ▁ is " , second ) NEW_LINE DEDENT DEDENT arr = [ 12 , 35 , 1 , 10 , 34 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print2largest ( arr , n ) NEW_LINE
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 values from array elements ; Driver Code
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' ) ) NEW_LINE DEDENT DEDENT def calculateCount ( S , Q , m ) : NEW_LINE INDENT n = len ( S ) NEW_LINE arr = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = ( 1 << ( ord ( S [ i ] ) - ord ( ' a ' ) ) ) NEW_LINE DEDENT prefix = [ 0 ] * n NEW_LINE x = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT x ^= arr [ i ] NEW_LINE prefix [ i ] = x NEW_LINE DEDENT for i in range ( m ) : NEW_LINE INDENT queryResult ( prefix , Q [ i ] ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " geeksforgeeks " NEW_LINE Q = [ [ 2 , 4 ] , [ 0 , 3 ] , [ 0 , 12 ] ] NEW_LINE calculateCount ( S , Q , 3 ) NEW_LINE DEDENT
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 INDENT for k in range ( element_value + N - 1 , element_value - 1 , - 1 ) : NEW_LINE INDENT print ( k , end = ' ▁ ' ) NEW_LINE DEDENT element_value += N NEW_LINE DEDENT print ( ) NEW_LINE i = i + 1 NEW_LINE DEDENT DEDENT N = 4 NEW_LINE UniqueMatrix ( N ) 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 return minmax NEW_LINE DEDENT if arr [ 0 ] > arr [ 1 ] : NEW_LINE INDENT minmax . max = arr [ 0 ] NEW_LINE minmax . min = arr [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT minmax . max = arr [ 1 ] NEW_LINE minmax . min = arr [ 0 ] NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT if arr [ i ] > minmax . max : NEW_LINE INDENT minmax . max = arr [ i ] NEW_LINE DEDENT elif arr [ i ] < minmax . min : NEW_LINE INDENT minmax . min = arr [ i ] NEW_LINE DEDENT DEDENT return minmax NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1000 , 11 , 445 , 1 , 330 , 3000 ] NEW_LINE arr_size = 6 NEW_LINE minmax = getMinMax ( arr , arr_size ) NEW_LINE print ( " Minimum ▁ element ▁ is " , minmax . min ) NEW_LINE print ( " Maximum ▁ element ▁ is " , minmax . max ) NEW_LINE DEDENT
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 manner ; loop to calculate values of parent nodes from the children nodes of lower level ; store the value of parent node as Sum of children nodes ; traverse the list of vector and calculate the Sum ; Driver Code
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 [ i + 1 ] ) - 1 ) : NEW_LINE INDENT vec [ i ] . append ( vec [ i + 1 ] [ k ] + vec [ i + 1 ] [ k + 1 ] ) NEW_LINE k += 2 NEW_LINE DEDENT DEDENT Sum = 0 NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( len ( vec [ i ] ) ) : NEW_LINE INDENT Sum += vec [ i ] [ j ] NEW_LINE DEDENT DEDENT return Sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT l = 3 NEW_LINE print ( SumNodes ( l ) ) NEW_LINE DEDENT
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 the starting index for loop ; In the while loop , pick elements in pair and compare the pair with max and min so far ; Increment the index by 2 as two elements are processed in loop ; Driver Code
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 INDENT if arr [ i ] < arr [ i + 1 ] : NEW_LINE INDENT mx = max ( mx , arr [ i + 1 ] ) NEW_LINE mn = min ( mn , arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT mx = max ( mx , arr [ i ] ) NEW_LINE mn = min ( mn , arr [ i + 1 ] ) NEW_LINE DEDENT i += 2 NEW_LINE DEDENT return ( mx , mn ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1000 , 11 , 445 , 1 , 330 , 3000 ] NEW_LINE mx , mn = getMinMax ( arr ) NEW_LINE print ( " Minimum ▁ element ▁ is " , mn ) NEW_LINE print ( " Maximum ▁ element ▁ is " , mx ) NEW_LINE DEDENT
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 ] , [ 1 , 3 ] , [ 2 , 4 ] ] NEW_LINE printQuerySum ( arr , Q ) NEW_LINE
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 is greater than zero ; No . of different char we can put at the position of the i and x - i ; Iterator pointing to the last element of the set ; Decrease the value of the char we put on the position i and n - i ; Different no of char we can put at the position x / 2 ; Return total no of different string ; Driver code
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 ( freq [ i ] > 0 ) : NEW_LINE INDENT se . add ( freq [ i ] ) NEW_LINE DEDENT DEDENT ans = 1 NEW_LINE for i in range ( x // 2 ) : NEW_LINE INDENT count = 0 NEW_LINE for u in se : NEW_LINE INDENT if ( u >= 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT ans *= count NEW_LINE DEDENT p = list ( se ) NEW_LINE val = p [ - 1 ] NEW_LINE p . pop ( - 1 ) NEW_LINE se = set ( p ) NEW_LINE if ( val > 2 ) : NEW_LINE INDENT se . add ( val - 2 ) NEW_LINE DEDENT DEDENT if ( x % 2 != 0 ) : NEW_LINE INDENT count = 0 NEW_LINE for u in se : NEW_LINE INDENT if ( u > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT ans = ans * count NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " aaa " NEW_LINE x = 2 NEW_LINE print ( findways ( s , x ) ) NEW_LINE DEDENT
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 ; Count number of divisions ; Loop until n is divisible by c ; Count number of operations ; Check if n is reduced to 1 ; Count steps ; Return the total number of steps ; Given n , a and b ; Function Call
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 while ( n % b == 0 ) : NEW_LINE INDENT n /= b NEW_LINE x += 1 NEW_LINE DEDENT while ( n % c == 0 ) : NEW_LINE INDENT n /= c NEW_LINE y += 1 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT total_steps = x + 2 * y NEW_LINE return total_steps NEW_LINE DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT n = 48 NEW_LINE a = 3 NEW_LINE b = 12 NEW_LINE print ( FindIfPossible ( n , a , b ) ) 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 overlapped blocks in range ; traversing last block in range ; Fills values in input [ ] ; initiating block pointer ; calculating size of block ; building the decomposed array ; entering next block incementing block pointer ; We have used separate array for input because the purpose of this code is to explain SQRT decomposition in competitive programming where we have multiple inputs .
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_LINE DEDENT def query ( l , r ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( l < r and l % blk_sz != 0 and l != 0 ) : NEW_LINE INDENT sum += arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT while ( l + blk_sz <= r ) : NEW_LINE INDENT sum += block [ l // blk_sz ] NEW_LINE l += blk_sz NEW_LINE DEDENT while ( l <= r ) : NEW_LINE INDENT sum += arr [ l ] NEW_LINE l += 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT def preprocess ( input , n ) : NEW_LINE INDENT blk_idx = - 1 NEW_LINE global blk_sz NEW_LINE blk_sz = int ( sqrt ( n ) ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = input [ i ] ; NEW_LINE if ( i % blk_sz == 0 ) : NEW_LINE INDENT blk_idx += 1 ; NEW_LINE DEDENT block [ blk_idx ] += arr [ i ] NEW_LINE DEDENT DEDENT input = [ 1 , 5 , 2 , 4 , 6 , 1 , 3 , 5 , 7 , 10 ] NEW_LINE n = len ( input ) NEW_LINE preprocess ( input , n ) NEW_LINE print ( " query ( 3,8 ) ▁ : ▁ " , query ( 3 , 8 ) ) NEW_LINE print ( " query ( 1,6 ) ▁ : ▁ " , query ( 1 , 6 ) ) NEW_LINE update ( 8 , 0 ) NEW_LINE print ( " query ( 8,8 ) ▁ : ▁ " , query ( 8 , 8 ) ) NEW_LINE
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 to break String D in A and 0 in B ; Remove leading zeros ; Print the answer ; Driver code
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_LINE n = len ( N ) NEW_LINE for i in range ( n ) : NEW_LINE D = int ( N [ i ] ) - int ( '0' ) NEW_LINE if ( D == K ) : NEW_LINE INDENT D1 = D // 2 ; NEW_LINE D2 = ( D // 2 ) + ( D % 2 ) NEW_LINE A = A + ( str ) ( D1 + int ( '0' ) ) NEW_LINE B = B + ( str ) ( D2 + int ( '0' ) ) NEW_LINE DEDENT else : NEW_LINE INDENT A = A + ( str ) ( D + int ( '0' ) ) NEW_LINE B = B + '0' NEW_LINE DEDENT A = removeLeadingZeros ( A ) NEW_LINE B = removeLeadingZeros ( B ) NEW_LINE print ( A + " , ▁ " + B ) NEW_LINE DEDENT N = 33673 NEW_LINE K = 3 NEW_LINE findPairs ( N , K ) NEW_LINE
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 lookup array lookup [ n ] [ n ] for all possible values of query ranges ; Initialize lookup [ ] [ ] for the intervals with length 1 ; Fill rest of the entries in bottom up manner ; To find minimum of [ 0 , 4 ] , we compare minimum of arr [ lookup [ 0 ] [ 3 ] ] with arr [ 4 ] . ; Prints minimum of given m query ranges in arr [ 0. . n - 1 ] ; Fill lookup table for all possible input queries ; One by one compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Driver code
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 [ i ] [ i ] = i ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ lookup [ i ] [ j - 1 ] ] < arr [ j ] ) : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT lookup [ i ] [ j ] = j ; NEW_LINE DEDENT DEDENT DEDENT DEDENT def RMQ ( arr , n , q , m ) : NEW_LINE INDENT preprocess ( arr , n ) ; NEW_LINE for i in range ( m ) : NEW_LINE INDENT L = q [ i ] . L NEW_LINE R = q [ i ] . R ; NEW_LINE print ( " Minimum ▁ of ▁ [ " + str ( L ) + " , ▁ " + str ( R ) + " ] ▁ is ▁ " + str ( arr [ lookup [ L ] [ R ] ] ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 7 , 2 , 3 , 0 , 5 , 10 , 3 , 12 , 18 ] NEW_LINE n = len ( a ) NEW_LINE q = [ Query ( 0 , 4 ) , Query ( 4 , 7 ) , Query ( 7 , 8 ) ] NEW_LINE m = len ( q ) NEW_LINE RMQ ( a , n , q , m ) ; NEW_LINE DEDENT
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 ; Driver Code ; Function Call ; result -> [ 2 , 1 , 3 , 2 , 1 , 2 ] ; Function Call ; result -> [ 1 , 2 , 3 , 1 ] ; Function Call ; result -> [ 1 , 2 ]
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 for i in range ( employees - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( ratings [ i ] > ratings [ i + 1 ] and hikes [ i + 1 ] >= hikes [ i ] ) : NEW_LINE INDENT hikes [ i ] = hikes [ i + 1 ] + 1 ; NEW_LINE DEDENT DEDENT return hikes NEW_LINE DEDENT data = [ 5 , 3 , 4 , 2 , 1 , 6 ] NEW_LINE result = findMinimumHike ( data , len ( data ) ) NEW_LINE print ( result ) NEW_LINE data = [ 1 , 3 , 5 , 4 ] NEW_LINE result = findMinimumHike ( data , len ( data ) ) NEW_LINE print ( result ) NEW_LINE data = [ 1 , 4 ] NEW_LINE result = findMinimumHike ( data , len ( data ) ) NEW_LINE print ( result ) NEW_LINE
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 fixed and should be determined using n Log n . It is kept constant to keep code simple . ; Structure to represent a query range ; Fills lookup array lookup [ ] [ ] in bottom up manner . ; Initialize M for the intervals with length 1 ; Compute values from smaller to bigger intervals ; Compute minimum value for all intervals with size 2 ^ j ; For arr [ 2 ] [ 10 ] , we compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] ; Returns minimum of arr [ L . . R ] ; For [ 2 , 10 ] , j = 3 ; For [ 2 , 10 ] , we compare arr [ lookup [ 0 ] [ 3 ] ] and arr [ lookup [ 3 ] [ 3 ] ] , ; Prints minimum of given m query ranges in arr [ 0. . n - 1 ] ; Fills table lookup [ n ] [ Log n ] ; One by one compute sum of all queries ; Left and right boundaries of current range ; Print sum of current query range ; Driver Code
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 global lookup NEW_LINE for i in range ( n ) : NEW_LINE INDENT lookup [ i ] [ 0 ] = i NEW_LINE DEDENT j = 1 NEW_LINE while ( 1 << j ) <= n : NEW_LINE INDENT i = 0 NEW_LINE while i + ( 1 << j ) - 1 < n : NEW_LINE INDENT if ( arr [ lookup [ i ] [ j - 1 ] ] < arr [ lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] ] ) : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i + ( 1 << ( j - 1 ) ) ] [ j - 1 ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT DEDENT def query ( arr : list , L : int , R : int ) -> int : NEW_LINE INDENT global lookup NEW_LINE j = int ( log2 ( R - L + 1 ) ) NEW_LINE if ( arr [ lookup [ L ] [ j ] ] <= arr [ lookup [ R - ( 1 << j ) + 1 ] [ j ] ] ) : NEW_LINE INDENT return arr [ lookup [ L ] [ j ] ] NEW_LINE DEDENT else : NEW_LINE INDENT return arr [ lookup [ R - ( 1 << j ) + 1 ] [ j ] ] NEW_LINE DEDENT DEDENT def RMQ ( arr : list , n : int , q : list , m : int ) : NEW_LINE INDENT preprocess ( arr , n ) NEW_LINE for i in range ( m ) : NEW_LINE INDENT L = q [ i ] . L NEW_LINE R = q [ i ] . R NEW_LINE print ( " Minimum ▁ of ▁ [ % d , ▁ % d ] ▁ is ▁ % d " % ( L , R , query ( arr , L , R ) ) ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT a = [ 7 , 2 , 3 , 0 , 5 , 10 , 3 , 12 , 18 ] NEW_LINE n = len ( a ) NEW_LINE q = [ Query ( 0 , 4 ) , Query ( 4 , 7 ) , Query ( 7 , 8 ) ] NEW_LINE m = len ( q ) NEW_LINE RMQ ( a , n , q , m ) NEW_LINE DEDENT
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 ( l ) ) ; NEW_LINE
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 answer to the current subproblem ; Function to find the longest Subsequence with different adjacent character ; Length of the String s ; Return the final ans after every recursive call ; Driver Code ; Function call
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 ( s [ pos ] ) - ord ( ' a ' ) + 1 != prev ) : NEW_LINE INDENT val = max ( val , 1 + calculate ( pos + 1 , ord ( s [ pos ] ) - ord ( ' a ' ) + 1 , s ) ) ; NEW_LINE DEDENT val = max ( val , calculate ( pos + 1 , prev , s ) ) ; NEW_LINE dp [ pos ] [ prev ] = val ; NEW_LINE return dp [ pos ] [ prev ] ; NEW_LINE DEDENT def longestSubsequence ( s ) : NEW_LINE INDENT n = len ( s ) ; NEW_LINE return calculate ( 0 , 0 , s ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " ababa " ; NEW_LINE print ( longestSubsequence ( str ) ) ; NEW_LINE DEDENT
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 , N ) : NEW_LINE INDENT updateArray ( arr , N ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT N = 6 NEW_LINE arr = [ 0 for i in range ( N ) ] NEW_LINE add ( arr , N , 0 , 2 , 100 ) NEW_LINE add ( arr , N , 1 , 5 , 100 ) NEW_LINE add ( arr , N , 2 , 3 , 100 ) NEW_LINE printArr ( arr , N ) NEW_LINE
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 previous transaction ; Store the profit ; Remove the previous transaction ; Check if the current selling price is less than that of the previous transactions ; Store the new profit ; Remove the previous transaction ; Add the new transactions ; Finally store the profits of all the transactions ; Add the highest K profits ; Return the maximum profit ; Driver code
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 = buy + 1 NEW_LINE while ( sell < n and prices [ sell ] >= prices [ sell - 1 ] ) : NEW_LINE INDENT sell += 1 NEW_LINE DEDENT while ( len ( transaction ) != 0 and prices [ buy ] < prices [ transaction [ len ( transaction ) - 1 ] [ 0 ] ] ) : NEW_LINE INDENT p = transaction [ len ( transaction ) - 1 ] NEW_LINE profits . append ( prices [ p [ 1 ] - 1 ] - prices [ p [ 0 ] ] ) NEW_LINE transaction . remove ( transaction [ len ( transaction ) - 1 ] ) NEW_LINE DEDENT profits . sort ( reverse = True ) NEW_LINE while ( len ( transaction ) != 0 and prices [ sell - 1 ] > prices [ transaction [ len ( transaction ) - 1 ] [ 1 ] - 1 ] ) : NEW_LINE INDENT p = transaction [ len ( transaction ) - 1 ] NEW_LINE profits . append ( prices [ p [ 1 ] - 1 ] - prices [ buy ] ) NEW_LINE buy = p [ 0 ] NEW_LINE transaction . remove ( transaction [ len ( transaction ) - 1 ] ) NEW_LINE DEDENT transaction . append ( [ buy , sell ] ) NEW_LINE DEDENT profits . sort ( reverse = True ) NEW_LINE while ( len ( transaction ) != 0 ) : NEW_LINE INDENT profits . append ( prices [ transaction [ len ( transaction ) - 1 ] [ 1 ] - 1 ] - prices [ transaction [ len ( transaction ) - 1 ] [ 0 ] ] ) NEW_LINE transaction . remove ( transaction [ len ( transaction ) - 1 ] ) NEW_LINE DEDENT profits . sort ( reverse = True ) NEW_LINE while ( k != 0 and len ( profits ) != 0 ) : NEW_LINE INDENT ans += profits [ 0 ] NEW_LINE profits . remove ( profits [ 0 ] ) NEW_LINE k -= 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 3 NEW_LINE prices = [ 1 , 12 , 10 , 7 , 10 , 13 , 11 , 10 , 7 , 6 , 9 ] NEW_LINE n = len ( prices ) NEW_LINE print ( " Maximum ▁ profit ▁ is " , maxProfit ( n , k , prices ) ) NEW_LINE DEDENT
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_LINE DEDENT sum = 0 NEW_LINE for i in range ( L , R + 1 ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT return sum NEW_LINE DEDENT L = 0 NEW_LINE R = 5 NEW_LINE print ( findSum ( L , R ) ) NEW_LINE
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 ) = GCD ( suffix ( i + 1 ) , arr ( i ) ) ; To calculate gcd of the numbers outside range ; If l = 0 , we need to tell GCD of numbers from r + 1 to n ; If r = n - 1 we need to return the gcd of numbers from 1 to l ; Driver code
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 ] , arr [ i ] ) NEW_LINE DEDENT suffix [ n - 1 ] = arr [ n - 1 ] NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT suffix [ i ] = GCD ( suffix [ i + 1 ] , arr [ i ] ) NEW_LINE DEDENT DEDENT def GCDoutsideRange ( l , r , prefix , suffix , n ) : NEW_LINE INDENT if ( l == 0 ) : NEW_LINE INDENT return suffix [ r + 1 ] NEW_LINE DEDENT if ( r == n - 1 ) : NEW_LINE INDENT return prefix [ l - 1 ] NEW_LINE DEDENT return GCD ( prefix [ l - 1 ] , suffix [ r + 1 ] ) NEW_LINE DEDENT arr = [ 2 , 6 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE prefix = [ ] NEW_LINE suffix = [ ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT prefix . append ( 0 ) NEW_LINE suffix . append ( 0 ) NEW_LINE DEDENT FillPrefixSuffix ( prefix , arr , suffix , n ) NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE print ( GCDoutsideRange ( l , r , prefix , suffix , n ) ) NEW_LINE l = 1 NEW_LINE r = 1 NEW_LINE print ( GCDoutsideRange ( l , r , prefix , suffix , n ) ) NEW_LINE l = 1 NEW_LINE r = 2 NEW_LINE print ( GCDoutsideRange ( l , r , prefix , suffix , n ) ) NEW_LINE
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 [ ] ; Adding the values of A [ ] into max heap ; Adding the values of B [ ] into max heap ; Counter variable ; Loop to iterate through the heap ; Comparing the values at the top . If the value of heap A [ ] is greater , then counter is incremented ; Driver code
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 ) : NEW_LINE INDENT if - pq1 [ 0 ] > - pq2 [ 0 ] : NEW_LINE INDENT c += 1 NEW_LINE heapq . heappop ( pq1 ) NEW_LINE heapq . heappop ( pq2 ) NEW_LINE DEDENT else : NEW_LINE INDENT if len ( pq2 ) == 0 : NEW_LINE INDENT break NEW_LINE DEDENT heapq . heappop ( pq2 ) NEW_LINE DEDENT DEDENT return ( c ) NEW_LINE DEDENT A = [ 10 , 3 , 7 , 5 , 8 ] NEW_LINE B = [ 8 , 6 , 2 , 5 , 9 ] NEW_LINE N = len ( A ) NEW_LINE print ( check ( A , B , N ) ) NEW_LINE
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 ; Traversing completely overlapped blocks in range for such blocks bit array of that block is queried ; Traversing the last block ; Preprocessing the array ; updating the bit array at the original and new value of array ; Driver Code ; size of block size will be equal to square root of n ; initialising bit array of each block as elements of array cannot exceed 10 ^ 4 so size of bit array is accordingly
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 : NEW_LINE INDENT if arr [ l ] <= k : NEW_LINE INDENT summ += 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT while l + blk_sz <= r : NEW_LINE INDENT idx = k NEW_LINE while idx > 0 : NEW_LINE INDENT summ += bit [ l // blk_sz ] [ idx ] NEW_LINE idx -= ( idx & - idx ) NEW_LINE DEDENT l += blk_sz NEW_LINE DEDENT while l <= r : NEW_LINE INDENT if arr [ l ] <= k : NEW_LINE INDENT summ += 1 NEW_LINE DEDENT l += 1 NEW_LINE DEDENT return summ NEW_LINE DEDENT def preprocess ( arr , blk_sz , n , bit ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT update ( arr [ i ] , i // blk_sz , 1 , bit ) NEW_LINE DEDENT DEDENT def preprocessUpdate ( i , v , blk_sz , arr , bit ) : NEW_LINE INDENT update ( arr [ i ] , i // blk_sz , - 1 , bit ) NEW_LINE update ( v , i // blk_sz , 1 , bit ) NEW_LINE arr [ i ] = v NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE from math import sqrt NEW_LINE blk_sz = int ( sqrt ( n ) ) NEW_LINE bit = [ [ 0 for i in range ( MAX ) ] for j in range ( blk_sz + 1 ) ] NEW_LINE preprocess ( arr , blk_sz , n , bit ) NEW_LINE print ( query ( 1 , 3 , 1 , arr , blk_sz , bit ) ) NEW_LINE preprocessUpdate ( 3 , 10 , blk_sz , arr , bit ) NEW_LINE print ( query ( 3 , 3 , 4 , arr , blk_sz , bit ) ) NEW_LINE preprocessUpdate ( 2 , 1 , blk_sz , arr , bit ) NEW_LINE preprocessUpdate ( 0 , 2 , blk_sz , arr , bit ) NEW_LINE print ( query ( 0 , 4 , 5 , arr , blk_sz , bit ) ) NEW_LINE DEDENT
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 = 4 NEW_LINE print ( countInRange ( arr , n , i , j ) ) NEW_LINE i = 9 NEW_LINE j = 12 NEW_LINE print ( countInRange ( arr , n , i , j ) ) NEW_LINE
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 already visited continue ; Marking the node as visited ; If it is a destination node ; Traversing the current node ; If no path exists ; Driver code ; Graph as adjacency matrix ; Input edges ; print ( gr ) ; Source and destination ; Dijkstra
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 . pop ( ) ; NEW_LINE if ( v [ curr ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT v [ curr ] = 1 ; NEW_LINE if ( curr == d ) : NEW_LINE INDENT return dist ; NEW_LINE DEDENT for it in gr [ curr ] : NEW_LINE INDENT if it not in pq : NEW_LINE INDENT pq . insert ( 0 , ( dist * it [ 1 ] , it [ 0 ] ) ) ; NEW_LINE DEDENT DEDENT DEDENT return - 1 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 ; NEW_LINE gr = { } ; NEW_LINE gr [ 1 ] = [ ( 3 , 9 ) ] ; NEW_LINE gr [ 2 ] = [ ( 3 , 1 ) ] ; NEW_LINE gr [ 1 ] . append ( ( 2 , 5 ) ) ; NEW_LINE gr [ 3 ] = [ ] ; NEW_LINE s = 1 ; d = 3 ; NEW_LINE print ( dijkstra ( s , d , gr ) ) ; NEW_LINE DEDENT
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_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 l = mid + 1 NEW_LINE else : NEW_LINE h = mid - 1 NEW_LINE DEDENT return h NEW_LINE DEDENT def countInRange ( arr , n , x , y ) : NEW_LINE INDENT count = 0 ; NEW_LINE count = upperIndex ( arr , n , y ) - lowerIndex ( arr , n , x ) + 1 ; NEW_LINE return count NEW_LINE DEDENT arr = [ 1 , 3 , 4 , 9 , 10 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE arr . sort ( ) NEW_LINE i = 1 NEW_LINE j = 4 NEW_LINE print ( countInRange ( arr , n , i , j ) ) NEW_LINE i = 9 NEW_LINE j = 12 NEW_LINE print ( countInRange ( arr , n , i , j ) ) NEW_LINE