text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Flood fill Algorithm | Dimentions of paint screen ; A recursive function to replace previous color ' prevC ' at ' ( x , β y ) ' and all surrounding pixels of ( x , y ) with new color ' newC ' and ; Base cases ; Replace the color at ( x , y ) ; Recur for north , east , south and west ; It mainly finds the previous color on ( x , y ) and calls floodFillUtil ( ) ; Driver Code | M = 8 NEW_LINE N = 8 NEW_LINE def floodFillUtil ( screen , x , y , prevC , newC ) : NEW_LINE INDENT if ( x < 0 or x >= M or y < 0 or y >= N or screen [ x ] [ y ] != prevC or screen [ x ] [ y ] == newC ) : NEW_LINE INDENT return NEW_LINE DEDENT screen [ x ] [ y ] = newC NEW_LINE floodFillUtil ( screen , x + 1 , y , prevC , newC ) NEW_LINE floodFillUtil ( screen , x - 1 , y , prevC , newC ) NEW_LINE floodFillUtil ( screen , x , y + 1 , prevC , newC ) NEW_LINE floodFillUtil ( screen , x , y - 1 , prevC , newC ) NEW_LINE DEDENT def floodFill ( screen , x , y , newC ) : NEW_LINE INDENT prevC = screen [ x ] [ y ] NEW_LINE floodFillUtil ( screen , x , y , prevC , newC ) NEW_LINE DEDENT screen = [ [ 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 ] , [ 1 , 0 , 0 , 1 , 1 , 0 , 1 , 1 ] , [ 1 , 2 , 2 , 2 , 2 , 0 , 1 , 0 ] , [ 1 , 1 , 1 , 2 , 2 , 0 , 1 , 0 ] , [ 1 , 1 , 1 , 2 , 2 , 2 , 2 , 0 ] , [ 1 , 1 , 1 , 1 , 1 , 2 , 1 , 1 ] , [ 1 , 1 , 1 , 1 , 1 , 2 , 2 , 1 ] ] NEW_LINE x = 4 NEW_LINE y = 4 NEW_LINE newC = 3 NEW_LINE floodFill ( screen , x , y , newC ) NEW_LINE print ( " Updated β screen β after β call β to β floodFill : " ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT print ( screen [ i ] [ j ] , end = ' β ' ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT |
Collect maximum points in a grid using two traversals | A Memoization based program to find maximum collection using two traversals of a grid ; checks whether a given input is valid or not ; Driver function to collect max value ; if P1 or P2 is at an invalid cell ; if both traversals reach their destinations ; If both traversals are at last row but not at their destination ; If subproblem is already solved ; Initialize answer for this subproblem ; this variable is used to store gain of current cell ( s ) ; Recur for all possible cases , then store and return the one with max value ; This is mainly a wrapper over recursive function getMaxUtil ( ) . This function creates a table for memoization and calls getMaxUtil ( ) ; Create a memoization table and initialize all entries as - 1 ; Calculation maximum value using memoization based function getMaxUtil ( ) ; Driver program to test above functions | R = 5 NEW_LINE C = 4 NEW_LINE intmin = - 10000000 NEW_LINE intmax = 10000000 NEW_LINE def isValid ( x , y1 , y2 ) : NEW_LINE INDENT return ( ( x >= 0 and x < R and y1 >= 0 and y1 < C and y2 >= 0 and y2 < C ) ) NEW_LINE DEDENT def getMaxUtil ( arr , mem , x , y1 , y2 ) : NEW_LINE INDENT if isValid ( x , y1 , y2 ) == False : NEW_LINE INDENT return intmin NEW_LINE DEDENT if x == R - 1 and y1 == 0 and y2 == C - 1 : NEW_LINE INDENT if y1 == y2 : NEW_LINE INDENT return arr [ x ] [ y1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return arr [ x ] [ y1 ] + arr [ x ] [ y2 ] NEW_LINE DEDENT DEDENT if x == R - 1 : NEW_LINE INDENT return intmin NEW_LINE DEDENT if mem [ x ] [ y1 ] [ y2 ] != - 1 : NEW_LINE INDENT return mem [ x ] [ y1 ] [ y2 ] NEW_LINE DEDENT ans = intmin NEW_LINE temp = 0 NEW_LINE if y1 == y2 : NEW_LINE INDENT temp = arr [ x ] [ y1 ] NEW_LINE DEDENT else : NEW_LINE INDENT temp = arr [ x ] [ y1 ] + arr [ x ] [ y2 ] NEW_LINE DEDENT ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 - 1 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 + 1 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 , y2 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 - 1 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 - 1 , y2 + 1 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 - 1 ) ) NEW_LINE ans = max ( ans , temp + getMaxUtil ( arr , mem , x + 1 , y1 + 1 , y2 + 1 ) ) NEW_LINE mem [ x ] [ y1 ] [ y2 ] = ans NEW_LINE return ans NEW_LINE DEDENT def geMaxCollection ( arr ) : NEW_LINE INDENT mem = [ [ [ - 1 for i in range ( C ) ] for i in range ( C ) ] for i in range ( R ) ] NEW_LINE return getMaxUtil ( arr , mem , 0 , 0 , C - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 3 , 6 , 8 , 2 ] , [ 5 , 2 , 4 , 3 ] , [ 1 , 1 , 20 , 10 ] , [ 1 , 1 , 20 , 10 ] , [ 1 , 1 , 20 , 10 ] , ] NEW_LINE print ( ' Maximum β collection β is β ' , geMaxCollection ( arr ) ) NEW_LINE DEDENT |
Collect maximum coins before hitting a dead end | A Naive Recursive Python 3 program to find maximum number of coins that can be collected before hitting a dead end ; to check whether current cell is out of the grid or not ; dir = 0 for left , dir = 1 for facing right . This function returns number of maximum coins that can be collected starting from ( i , j ) . ; If this is a invalid cell or if cell is a blocking cell ; Check if this cell contains the coin ' C ' or if its empty ' E ' . ; Get the maximum of two cases when you are facing right in this cell ; Direction is right ; Direction is left Get the maximum of two cases when you are facing left in this cell ; Driver program to test above function ; As per the question initial cell is ( 0 , 0 ) and direction is right | R = 5 NEW_LINE C = 5 NEW_LINE def isValid ( i , j ) : NEW_LINE INDENT return ( i >= 0 and i < R and j >= 0 and j < C ) NEW_LINE DEDENT def maxCoinsRec ( arr , i , j , dir ) : NEW_LINE INDENT if ( isValid ( i , j ) == False or arr [ i ] [ j ] == ' # ' ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ i ] [ j ] == ' C ' ) : NEW_LINE INDENT result = 1 NEW_LINE DEDENT else : NEW_LINE INDENT result = 0 NEW_LINE DEDENT if ( dir == 1 ) : NEW_LINE INDENT return ( result + max ( maxCoinsRec ( arr , i + 1 , j , 0 ) , maxCoinsRec ( arr , i , j + 1 , 1 ) ) ) NEW_LINE DEDENT return ( result + max ( maxCoinsRec ( arr , i + 1 , j , 1 ) , maxCoinsRec ( arr , i , j - 1 , 0 ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ ' E ' , ' C ' , ' C ' , ' C ' , ' C ' ] , [ ' C ' , ' # ' , ' C ' , ' # ' , ' E ' ] , [ ' # ' , ' C ' , ' C ' , ' # ' , ' C ' ] , [ ' C ' , ' E ' , ' E ' , ' C ' , ' E ' ] , [ ' C ' , ' E ' , ' # ' , ' C ' , ' E ' ] ] NEW_LINE print ( " Maximum β number β of β collected β coins β is β " , maxCoinsRec ( arr , 0 , 0 , 1 ) ) NEW_LINE DEDENT |
Find length of the longest consecutive path from a given starting character | Python3 program to find the longest consecutive path ; tool matrices to recur for adjacent cells . ; dp [ i ] [ j ] Stores length of longest consecutive path starting at arr [ i ] [ j ] . ; check whether mat [ i ] [ j ] is a valid cell or not . ; Check whether current character is adjacent to previous character ( character processed in parent call ) or not . ; i , j are the indices of the current cell and prev is the character processed in the parent call . . also mat [ i ] [ j ] is our current character . ; If this cell is not valid or current character is not adjacent to previous one ( e . g . d is not adjacent to b ) or if this cell is already included in the path than return 0. ; If this subproblem is already solved , return the answer ; Initialize answer ; recur for paths with different adjacent cells and store the length of longest path . ; save the answer and return ; Returns length of the longest path with all characters consecutive to each other . This function first initializes dp array that is used to store results of subproblems , then it calls recursive DFS based function getLenUtil ( ) to find max length path ; check for each possible starting point ; recur for all eight adjacent cells ; Driver program | R = 3 NEW_LINE C = 3 NEW_LINE x = [ 0 , 1 , 1 , - 1 , 1 , 0 , - 1 , - 1 ] NEW_LINE y = [ 1 , 0 , 1 , 1 , - 1 , - 1 , 0 , - 1 ] NEW_LINE dp = [ [ 0 for i in range ( C ) ] for i in range ( R ) ] NEW_LINE def isvalid ( i , j ) : NEW_LINE INDENT if ( i < 0 or j < 0 or i >= R or j >= C ) : NEW_LINE INDENT return False NEW_LINE DEDENT return True NEW_LINE DEDENT def isadjacent ( prev , curr ) : NEW_LINE INDENT if ( ord ( curr ) - ord ( prev ) ) == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def getLenUtil ( mat , i , j , prev ) : NEW_LINE INDENT if ( isvalid ( i , j ) == False or isadjacent ( prev , mat [ i ] [ j ] ) == False ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT ans = 0 NEW_LINE for k in range ( 8 ) : NEW_LINE INDENT ans = max ( ans , 1 + getLenUtil ( mat , i + x [ k ] , j + y [ k ] , mat [ i ] [ j ] ) ) NEW_LINE DEDENT dp [ i ] [ j ] = ans NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT def getLen ( mat , s ) : NEW_LINE INDENT for i in range ( R ) : NEW_LINE INDENT for j in range ( C ) : NEW_LINE INDENT dp [ i ] [ j ] = - 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( R ) : NEW_LINE INDENT for j in range ( C ) : NEW_LINE INDENT if ( mat [ i ] [ j ] == s ) : NEW_LINE INDENT for k in range ( 8 ) : NEW_LINE INDENT ans = max ( ans , 1 + getLenUtil ( mat , i + x [ k ] , j + y [ k ] , s ) ) ; NEW_LINE DEDENT DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT mat = [ [ ' a ' , ' c ' , ' d ' ] , [ ' h ' , ' b ' , ' a ' ] , [ ' i ' , ' g ' , ' f ' ] ] NEW_LINE print ( getLen ( mat , ' a ' ) ) NEW_LINE print ( getLen ( mat , ' e ' ) ) NEW_LINE print ( getLen ( mat , ' b ' ) ) NEW_LINE print ( getLen ( mat , ' f ' ) ) NEW_LINE |
Find the longest path in a matrix with given constraints | Python3 program to find the longest path in a matrix with given constraints ; Returns length of the longest path beginning with mat [ i ] [ j ] . This function mainly uses lookup table dp [ n ] [ n ] ; Base case ; If this subproblem is already solved ; To store the path lengths in all the four directions ; Since all numbers are unique and in range from 1 to n * n , there is atmost one possible direction from any cell ; If none of the adjacent fours is one greater we will take 1 otherwise we will pick maximum from all the four directions ; Returns length of the longest path beginning with any cell ; Initialize result ; Create a lookup table and fill all entries in it as - 1 ; Compute longest path beginning from all cells ; Update result if needed ; Driver program | n = 3 NEW_LINE def findLongestFromACell ( i , j , mat , dp ) : NEW_LINE INDENT if ( i < 0 or i >= n or j < 0 or j >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT x , y , z , w = - 1 , - 1 , - 1 , - 1 NEW_LINE if ( j < n - 1 and ( ( mat [ i ] [ j ] + 1 ) == mat [ i ] [ j + 1 ] ) ) : NEW_LINE INDENT x = 1 + findLongestFromACell ( i , j + 1 , mat , dp ) NEW_LINE DEDENT if ( j > 0 and ( mat [ i ] [ j ] + 1 == mat [ i ] [ j - 1 ] ) ) : NEW_LINE INDENT y = 1 + findLongestFromACell ( i , j - 1 , mat , dp ) NEW_LINE DEDENT if ( i > 0 and ( mat [ i ] [ j ] + 1 == mat [ i - 1 ] [ j ] ) ) : NEW_LINE INDENT z = 1 + findLongestFromACell ( i - 1 , j , mat , dp ) NEW_LINE DEDENT if ( i < n - 1 and ( mat [ i ] [ j ] + 1 == mat [ i + 1 ] [ j ] ) ) : NEW_LINE INDENT w = 1 + findLongestFromACell ( i + 1 , j , mat , dp ) NEW_LINE DEDENT dp [ i ] [ j ] = max ( x , max ( y , max ( z , max ( w , 1 ) ) ) ) NEW_LINE return dp [ i ] [ j ] NEW_LINE DEDENT def finLongestOverAll ( mat ) : NEW_LINE INDENT result = 1 NEW_LINE dp = [ [ - 1 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( dp [ i ] [ j ] == - 1 ) : NEW_LINE INDENT findLongestFromACell ( i , j , mat , dp ) NEW_LINE DEDENT result = max ( result , dp [ i ] [ j ] ) ; NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT mat = [ [ 1 , 2 , 9 ] , [ 5 , 3 , 8 ] , [ 4 , 6 , 7 ] ] NEW_LINE print ( " Length β of β the β longest β path β is β " , finLongestOverAll ( mat ) ) NEW_LINE |
Minimum Initial Points to Reach Destination | Python3 program to find minimum initial points to reach destination ; dp [ i ] [ j ] represents the minimum initial points player should have so that when starts with cell ( i , j ) successfully reaches the destination cell ( m - 1 , n - 1 ) ; Base case ; Fill last row and last column as base to fill entire table ; fill the table in bottom - up fashion ; Driver code | import math as mt NEW_LINE R = 3 NEW_LINE C = 3 NEW_LINE def minInitialPoints ( points ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( C + 1 ) ] for y in range ( R + 1 ) ] NEW_LINE m , n = R , C NEW_LINE if points [ m - 1 ] [ n - 1 ] > 0 : NEW_LINE INDENT dp [ m - 1 ] [ n - 1 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ m - 1 ] [ n - 1 ] = abs ( points [ m - 1 ] [ n - 1 ] ) + 1 NEW_LINE DEDENT for i in range ( m - 2 , - 1 , - 1 ) : NEW_LINE INDENT dp [ i ] [ n - 1 ] = max ( dp [ i + 1 ] [ n - 1 ] - points [ i ] [ n - 1 ] , 1 ) NEW_LINE DEDENT for i in range ( 2 , - 1 , - 1 ) : NEW_LINE INDENT dp [ m - 1 ] [ i ] = max ( dp [ m - 1 ] [ i + 1 ] - points [ m - 1 ] [ i ] , 1 ) NEW_LINE DEDENT for i in range ( m - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT min_points_on_exit = min ( dp [ i + 1 ] [ j ] , dp [ i ] [ j + 1 ] ) NEW_LINE dp [ i ] [ j ] = max ( min_points_on_exit - points [ i ] [ j ] , 1 ) NEW_LINE DEDENT DEDENT return dp [ 0 ] [ 0 ] NEW_LINE DEDENT points = [ [ - 2 , - 3 , 3 ] , [ - 5 , - 10 , 1 ] , [ 10 , 30 , - 5 ] ] NEW_LINE print ( " Minimum β Initial β Points β Required : " , minInitialPoints ( points ) ) NEW_LINE |
Queue using Stacks | Python3 program to implement Queue using two stacks with costly enQueue ( ) ; Move all elements from s1 to s2 ; Push item into self . s1 ; Push everything back to s1 ; Dequeue an item from the queue ; if first stack is empty ; Return top of self . s1 ; Driver code | class Queue : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . s1 = [ ] NEW_LINE self . s2 = [ ] NEW_LINE DEDENT def enQueue ( self , x ) : NEW_LINE INDENT while len ( self . s1 ) != 0 : NEW_LINE INDENT self . s2 . append ( self . s1 [ - 1 ] ) NEW_LINE self . s1 . pop ( ) NEW_LINE DEDENT self . s1 . append ( x ) NEW_LINE while len ( self . s2 ) != 0 : NEW_LINE INDENT self . s1 . append ( self . s2 [ - 1 ] ) NEW_LINE self . s2 . pop ( ) NEW_LINE DEDENT DEDENT def deQueue ( self ) : NEW_LINE INDENT if len ( self . s1 ) == 0 : NEW_LINE INDENT print ( " Q β is β Empty " ) NEW_LINE DEDENT x = self . s1 [ - 1 ] NEW_LINE self . s1 . pop ( ) NEW_LINE return x NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT q = Queue ( ) NEW_LINE q . enQueue ( 1 ) NEW_LINE q . enQueue ( 2 ) NEW_LINE q . enQueue ( 3 ) NEW_LINE print ( q . deQueue ( ) ) NEW_LINE print ( q . deQueue ( ) ) NEW_LINE print ( q . deQueue ( ) ) NEW_LINE DEDENT |
Convert left | Python3 program to convert left - right to down - right representation of binary tree Helper function that allocates a new node with the given data and None left and right poers . ; Construct to create a new node ; An Iterative level order traversal based function to convert left - right to down - right representation . ; Base Case ; Recursively convert left an right subtrees ; If left child is None , make right child as left as it is the first child . ; If left child is NOT None , then make right child as right of left child ; Set root 's right as None ; A utility function to traverse a tree stored in down - right form . ; Driver Code ; 1 / \ 2 3 / \ 4 5 / / \ 6 7 8 | 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 convert ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT convert ( root . left ) NEW_LINE convert ( root . right ) NEW_LINE if ( root . left == None ) : NEW_LINE INDENT root . left = root . right NEW_LINE DEDENT else : NEW_LINE INDENT root . left . right = root . right NEW_LINE DEDENT root . right = None NEW_LINE DEDENT def downRightTraversal ( root ) : NEW_LINE INDENT if ( root != None ) : NEW_LINE INDENT print ( root . key , end = " β " ) NEW_LINE downRightTraversal ( root . right ) NEW_LINE downRightTraversal ( root . left ) 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 . right . left = newNode ( 4 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE root . right . left . left = newNode ( 6 ) NEW_LINE root . right . right . left = newNode ( 7 ) NEW_LINE root . right . right . right = newNode ( 8 ) NEW_LINE convert ( root ) NEW_LINE print ( " Traversal β of β the β tree β converted " , " to β down - right β form " ) NEW_LINE downRightTraversal ( root ) NEW_LINE DEDENT |
Convert a given tree to its Sum Tree | Node defintion ; Convert a given tree to a tree where every node contains sum of values of nodes in left and right subtrees in the original tree ; Base case ; Store the old value ; Recursively call for left and right subtrees and store the sum as new value of this node ; Return the sum of values of nodes in left and right subtrees and old_value of this node ; A utility function to print inorder traversal of a Binary Tree ; Utility function to create a new Binary Tree node ; Driver Code ; Constructing tree given in the above figure ; Print inorder traversal of the converted tree to test result of toSumTree ( ) | class node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . left = None NEW_LINE self . right = None NEW_LINE self . data = data NEW_LINE DEDENT DEDENT def toSumTree ( Node ) : NEW_LINE INDENT if ( Node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT old_val = Node . data NEW_LINE Node . data = toSumTree ( Node . left ) + toSumTree ( Node . right ) NEW_LINE return Node . data + old_val NEW_LINE DEDENT def printInorder ( Node ) : NEW_LINE INDENT if ( Node == None ) : NEW_LINE INDENT return NEW_LINE DEDENT printInorder ( Node . left ) NEW_LINE print ( Node . data , end = " β " ) NEW_LINE printInorder ( Node . right ) NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( 0 ) NEW_LINE temp . data = data NEW_LINE temp . left = None NEW_LINE temp . right = None NEW_LINE return temp NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT root = None NEW_LINE x = 0 NEW_LINE root = newNode ( 10 ) NEW_LINE root . left = newNode ( - 2 ) NEW_LINE root . right = newNode ( 6 ) NEW_LINE root . left . left = newNode ( 8 ) NEW_LINE root . left . right = newNode ( - 4 ) NEW_LINE root . right . left = newNode ( 7 ) NEW_LINE root . right . right = newNode ( 5 ) NEW_LINE toSumTree ( root ) NEW_LINE print ( " Inorder β Traversal β of β the β resultant β tree β is : β " ) NEW_LINE printInorder ( root ) NEW_LINE DEDENT |
Find a peak element | Find the peak element in the array ; first or last element is peak element ; check for every other element ; check if the neighbors are smaller ; Driver code . | def findPeak ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE return 0 NEW_LINE if ( arr [ 0 ] >= arr [ 1 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ n - 1 ] >= arr [ n - 2 ] ) : NEW_LINE INDENT return n - 1 NEW_LINE DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( arr [ i ] >= arr [ i - 1 ] and arr [ i ] >= arr [ i + 1 ] ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 3 , 20 , 4 , 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Index β of β a β peak β point β is " , findPeak ( arr , n ) ) NEW_LINE |
Find a peak element | A binary search based function that returns index of a peak element ; Find index of middle element ( low + high ) / 2 ; Compare middle element with its neighbours ( if neighbours exist ) ; If middle element is not peak and its left neighbour is greater than it , then left half must have a peak element ; If middle element is not peak and its right neighbour is greater than it , then right half must have a peak element ; A wrapper over recursive function findPeakUtil ( ) ; Driver code | def findPeakUtil ( arr , low , high , n ) : NEW_LINE INDENT mid = low + ( high - low ) / 2 NEW_LINE mid = int ( mid ) NEW_LINE if ( ( mid == 0 or arr [ mid - 1 ] <= arr [ mid ] ) and ( mid == n - 1 or arr [ mid + 1 ] <= arr [ mid ] ) ) : NEW_LINE INDENT return mid NEW_LINE DEDENT elif ( mid > 0 and arr [ mid - 1 ] > arr [ mid ] ) : NEW_LINE INDENT return findPeakUtil ( arr , low , ( mid - 1 ) , n ) NEW_LINE DEDENT else : NEW_LINE INDENT return findPeakUtil ( arr , ( mid + 1 ) , high , n ) NEW_LINE DEDENT DEDENT def findPeak ( arr , n ) : NEW_LINE INDENT return findPeakUtil ( arr , 0 , n - 1 , n ) NEW_LINE DEDENT arr = [ 1 , 3 , 20 , 4 , 1 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Index β of β a β peak β point β is " , findPeak ( arr , n ) ) NEW_LINE |
Find the two repeating elements in a given array | Print Repeating function ; Driver code | def printRepeating ( arr , size ) : NEW_LINE INDENT print ( " Repeating β elements β are β " , end = ' ' ) NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT for j in range ( i + 1 , size ) : NEW_LINE INDENT if arr [ i ] == arr [ j ] : NEW_LINE INDENT print ( arr [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT DEDENT DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printRepeating ( arr , arr_size ) NEW_LINE |
Find the two repeating elements in a given array | Function ; Driver code | def printRepeating ( arr , size ) : NEW_LINE INDENT count = [ 0 ] * size NEW_LINE print ( " β Repeating β elements β are β " , end = " " ) NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT if ( count [ arr [ i ] ] == 1 ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT else : NEW_LINE INDENT count [ arr [ i ] ] = count [ arr [ i ] ] + 1 NEW_LINE DEDENT DEDENT DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printRepeating ( arr , arr_size ) NEW_LINE |
Find the two repeating elements in a given array | Python3 code for Find the two repeating elements in a given array ; printRepeating function ; S is for sum of elements in arr [ ] ; P is for product of elements in arr [ ] ; Calculate Sum and Product of all elements in arr [ ] ; S is x + y now ; P is x * y now ; D is x - y now ; factorial of n ; Driver code | import math NEW_LINE def printRepeating ( arr , size ) : NEW_LINE INDENT S = 0 ; NEW_LINE P = 1 ; NEW_LINE n = size - 2 NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT S = S + arr [ i ] NEW_LINE P = P * arr [ i ] NEW_LINE DEDENT S = S - n * ( n + 1 ) // 2 NEW_LINE P = P // fact ( n ) NEW_LINE D = math . sqrt ( S * S - 4 * P ) NEW_LINE x = ( D + S ) // 2 NEW_LINE y = ( S - D ) // 2 NEW_LINE print ( " The β two β Repeating β elements β are β " , ( int ) ( x ) , " β & β " , ( int ) ( y ) ) NEW_LINE DEDENT def fact ( n ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( n * fact ( n - 1 ) ) NEW_LINE DEDENT DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printRepeating ( arr , arr_size ) NEW_LINE |
Find the two repeating elements in a given array | Python3 code to Find the two repeating elements in a given array ; Will hold xor of all elements ; Will have only single set bit of xor ; Get the xor of all elements in arr [ ] and 1 , 2 . . n ; Get the rightmost set bit in set_bit_no ; Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element . ; XOR of first set in arr [ ] ; XOR of second set in arr [ ] ; XOR of first set in arr [ ] and 1 , 2 , ... n ; XOR of second set in arr [ ] and 1 , 2 , ... n ; Driver code | def printRepeating ( arr , size ) : NEW_LINE INDENT xor = arr [ 0 ] NEW_LINE n = size - 2 NEW_LINE x = 0 NEW_LINE y = 0 NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT xor ^= arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT xor ^= i NEW_LINE DEDENT set_bit_no = xor & ~ ( xor - 1 ) NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT if ( arr [ i ] & set_bit_no ) : NEW_LINE INDENT x = x ^ arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i & set_bit_no ) : NEW_LINE INDENT x = x ^ i NEW_LINE DEDENT else : NEW_LINE INDENT y = y ^ i NEW_LINE DEDENT DEDENT print ( " The β two β repeating " , " elements β are " , y , x ) NEW_LINE DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printRepeating ( arr , arr_size ) NEW_LINE |
Find the two repeating elements in a given array | Function to print repeating ; Driver code | def printRepeating ( arr , size ) : NEW_LINE INDENT print ( " β The β repeating β elements β are " , end = " β " ) NEW_LINE for i in range ( 0 , size ) : NEW_LINE INDENT if ( arr [ abs ( arr [ i ] ) ] > 0 ) : NEW_LINE INDENT arr [ abs ( arr [ i ] ) ] = ( - 1 ) * arr [ abs ( arr [ i ] ) ] NEW_LINE DEDENT else : NEW_LINE INDENT print ( abs ( arr [ i ] ) , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 4 , 2 , 4 , 5 , 2 , 3 , 1 ] NEW_LINE arr_size = len ( arr ) NEW_LINE printRepeating ( arr , arr_size ) NEW_LINE |
Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | Returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . Also , prints the result ; Pick a starting point ; try all subarrays starting with 'i ; Driver program | def subArraySum ( arr , n , sum_ ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT curr_sum = arr [ i ] NEW_LINE j = i + 1 NEW_LINE while j <= n : NEW_LINE INDENT if curr_sum == sum_ : NEW_LINE INDENT print ( " Sum β found β between " ) NEW_LINE print ( " indexes β % β d β and β % β d " % ( i , j - 1 ) ) NEW_LINE return 1 NEW_LINE DEDENT if curr_sum > sum_ or j == n : NEW_LINE INDENT break NEW_LINE DEDENT curr_sum = curr_sum + arr [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT print ( " No β subarray β found " ) NEW_LINE return 0 NEW_LINE DEDENT arr = [ 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 ] NEW_LINE n = len ( arr ) NEW_LINE sum_ = 23 NEW_LINE subArraySum ( arr , n , sum_ ) NEW_LINE |
Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | Returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . Also , prints the result . ; Initialize curr_sum as value of first element and starting point as 0 ; Add elements one by one to curr_sum and if the curr_sum exceeds the sum , then remove starting element ; If curr_sum exceeds the sum , then remove the starting elements ; If curr_sum becomes equal to sum , then return true ; Add this element to curr_sum ; If we reach here , then no subarray ; Driver program | def subArraySum ( arr , n , sum_ ) : NEW_LINE INDENT curr_sum = arr [ 0 ] NEW_LINE start = 0 NEW_LINE i = 1 NEW_LINE while i <= n : NEW_LINE INDENT while curr_sum > sum_ and start < i - 1 : NEW_LINE INDENT curr_sum = curr_sum - arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT if curr_sum == sum_ : NEW_LINE INDENT print ( " Sum β found β between β indexes " ) NEW_LINE print ( " % β d β and β % β d " % ( start , i - 1 ) ) NEW_LINE return 1 NEW_LINE DEDENT if i < n : NEW_LINE INDENT curr_sum = curr_sum + arr [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT print ( " No β subarray β found " ) NEW_LINE return 0 NEW_LINE DEDENT arr = [ 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 ] NEW_LINE n = len ( arr ) NEW_LINE sum_ = 23 NEW_LINE subArraySum ( arr , n , sum_ ) NEW_LINE |
Smallest Difference Triplet from Three arrays | Function to find maximum number ; Function to find minimum number ; Finds and prints the smallest Difference Triplet ; sorting all the three arrays ; To store resultant three numbers ; pointers to arr1 , arr2 , arr3 respectively ; Loop until one array reaches to its end Find the smallest difference . ; maximum number ; Find minimum and increment its index . ; Comparing new difference with the previous one and updating accordingly ; Print result ; Driver code | def maximum ( a , b , c ) : NEW_LINE INDENT return max ( max ( a , b ) , c ) NEW_LINE DEDENT def minimum ( a , b , c ) : NEW_LINE INDENT return min ( min ( a , b ) , c ) NEW_LINE DEDENT def smallestDifferenceTriplet ( arr1 , arr2 , arr3 , n ) : NEW_LINE INDENT arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE arr3 . sort ( ) NEW_LINE res_min = 0 ; res_max = 0 ; res_mid = 0 NEW_LINE i = 0 ; j = 0 ; k = 0 NEW_LINE diff = 2147483647 NEW_LINE while ( i < n and j < n and k < n ) : NEW_LINE INDENT sum = arr1 [ i ] + arr2 [ j ] + arr3 [ k ] NEW_LINE max = maximum ( arr1 [ i ] , arr2 [ j ] , arr3 [ k ] ) NEW_LINE min = minimum ( arr1 [ i ] , arr2 [ j ] , arr3 [ k ] ) NEW_LINE if ( min == arr1 [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif ( min == arr2 [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT k += 1 NEW_LINE DEDENT if ( diff > ( max - min ) ) : NEW_LINE INDENT diff = max - min NEW_LINE res_max = max NEW_LINE res_mid = sum - ( max + min ) NEW_LINE res_min = min NEW_LINE DEDENT DEDENT print ( res_max , " , " , res_mid , " , " , res_min ) NEW_LINE DEDENT arr1 = [ 5 , 2 , 8 ] NEW_LINE arr2 = [ 10 , 7 , 12 ] NEW_LINE arr3 = [ 9 , 14 , 6 ] NEW_LINE n = len ( arr1 ) NEW_LINE smallestDifferenceTriplet ( arr1 , arr2 , arr3 , n ) NEW_LINE |
Find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Fix the second element as A [ j ] ; Now look for the third number ; If we reach here , then no triplet was found ; Driver program to test above function | def find3Numbers ( A , arr_size , sum ) : NEW_LINE INDENT for i in range ( 0 , arr_size - 2 ) : NEW_LINE INDENT for j in range ( i + 1 , arr_size - 1 ) : NEW_LINE INDENT for k in range ( j + 1 , arr_size ) : NEW_LINE INDENT if A [ i ] + A [ j ] + A [ k ] == sum : NEW_LINE INDENT print ( " Triplet β is " , A [ i ] , " , β " , A [ j ] , " , β " , A [ k ] ) NEW_LINE return True NEW_LINE DEDENT DEDENT DEDENT DEDENT return False NEW_LINE DEDENT A = [ 1 , 4 , 45 , 6 , 10 , 8 ] NEW_LINE sum = 22 NEW_LINE arr_size = len ( A ) NEW_LINE find3Numbers ( A , arr_size , sum ) NEW_LINE |
Find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Sort the elements ; Now fix the first element one by one and find the other two elements ; To find the other two elements , start two index variables from two corners of the array and move them toward each other index of the first element in the remaining elements ; index of the last element ; A [ i ] + A [ l ] + A [ r ] > sum ; If we reach here , then no triplet was found ; Driver program to test above function | def find3Numbers ( A , arr_size , sum ) : NEW_LINE INDENT A . sort ( ) NEW_LINE for i in range ( 0 , arr_size - 2 ) : NEW_LINE INDENT l = i + 1 NEW_LINE r = arr_size - 1 NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( A [ i ] + A [ l ] + A [ r ] == sum ) : NEW_LINE INDENT print ( " Triplet β is " , A [ i ] , ' , β ' , A [ l ] , ' , β ' , A [ r ] ) ; NEW_LINE return True NEW_LINE DEDENT elif ( A [ i ] + A [ l ] + A [ r ] < sum ) : NEW_LINE INDENT l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT A = [ 1 , 4 , 45 , 6 , 10 , 8 ] NEW_LINE sum = 22 NEW_LINE arr_size = len ( A ) NEW_LINE find3Numbers ( A , arr_size , sum ) NEW_LINE |
Find a triplet that sum to a given value | returns true if there is triplet with sum equal to ' sum ' present in A [ ] . Also , prints the triplet ; Fix the first element as A [ i ] ; Find pair in subarray A [ i + 1. . n - 1 ] with sum equal to sum - A [ i ] ; If we reach here , then no triplet was found ; Driver program to test above function | def find3Numbers ( A , arr_size , sum ) : NEW_LINE INDENT for i in range ( 0 , arr_size - 1 ) : NEW_LINE INDENT s = set ( ) NEW_LINE curr_sum = sum - A [ i ] NEW_LINE for j in range ( i + 1 , arr_size ) : NEW_LINE INDENT if ( curr_sum - A [ j ] ) in s : NEW_LINE INDENT print ( " Triplet β is " , A [ i ] , " , β " , A [ j ] , " , β " , curr_sum - A [ j ] ) NEW_LINE return True NEW_LINE DEDENT s . add ( A [ j ] ) NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT A = [ 1 , 4 , 45 , 6 , 10 , 8 ] NEW_LINE sum = 22 NEW_LINE arr_size = len ( A ) NEW_LINE find3Numbers ( A , arr_size , sum ) NEW_LINE |
Subarray / Substring vs Subsequence and Programs to Generate them | Prints all subarrays in arr [ 0. . n - 1 ] ; Pick starting point ; Pick ending point ; Print subarray between current starting and ending points ; Driver program | def subArray ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT for k in range ( i , j + 1 ) : NEW_LINE INDENT print ( arr [ k ] , end = " β " ) NEW_LINE DEDENT print ( " " , end = " " ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " All β Non - empty β Subarrays " ) NEW_LINE subArray ( arr , n ) ; NEW_LINE |
Subarray / Substring vs Subsequence and Programs to Generate them | Python3 code to generate all possible subsequences . Time Complexity O ( n * 2 ^ n ) ; Number of subsequences is ( 2 * * n - 1 ) ; Run from counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter is set If set then print jth element from arr [ ] ; Driver program | import math NEW_LINE def printSubsequences ( arr , n ) : NEW_LINE INDENT opsize = math . pow ( 2 , n ) NEW_LINE for counter in range ( 1 , ( int ) ( opsize ) ) : NEW_LINE INDENT for j in range ( 0 , n ) : NEW_LINE INDENT if ( counter & ( 1 << j ) ) : NEW_LINE INDENT print ( arr [ j ] , end = " β " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT arr = [ 1 , 2 , 3 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " All β Non - empty β Subsequences " ) NEW_LINE printSubsequences ( arr , n ) NEW_LINE |
A Product Array Puzzle | Function to print product array for a given array arr [ ] of size n ; Base case ; Allocate memory for the product array ; In this loop , temp variable contains product of elements on left side excluding arr [ i ] ; Initialize temp to 1 for product on right side ; In this loop , temp variable contains product of elements on right side excluding arr [ i ] ; Print the constructed prod array ; Driver Code | def productArray ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT i , temp = 1 , 1 NEW_LINE prod = [ 1 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT prod [ i ] = temp NEW_LINE temp *= arr [ i ] NEW_LINE DEDENT temp = 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT prod [ i ] *= temp NEW_LINE temp *= arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( prod [ i ] , end = " β " ) NEW_LINE DEDENT return NEW_LINE DEDENT arr = [ 10 , 3 , 5 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The β product β array β is : β n " ) NEW_LINE productArray ( arr , n ) NEW_LINE |
Check if array elements are consecutive | Added Method 3 | The function checks if the array elements are consecutive . If elements are consecutive , then returns true , else returns false ; 1 ) Get the Minimum element in array ; 2 ) Get the Maximum element in array ; 3 ) Max - Min + 1 is equal to n , then only check all elements ; Create a temp array to hold visited flag of all elements . Note that , calloc is used here so that all values are initialized as false ; If we see an element again , then return false ; If visited first time , then mark the element as visited ; If all elements occur once , then return true ; if ( Max - Min + 1 != n ) ; Driver Code | def areConsecutive ( arr , n ) : NEW_LINE INDENT if ( n < 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT Min = min ( arr ) NEW_LINE Max = max ( arr ) NEW_LINE if ( Max - Min + 1 == n ) : NEW_LINE INDENT visited = [ False for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( visited [ arr [ i ] - Min ] != False ) : NEW_LINE INDENT return False NEW_LINE DEDENT visited [ arr [ i ] - Min ] = True NEW_LINE DEDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT arr = [ 5 , 4 , 2 , 3 , 1 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( areConsecutive ( arr , n ) == True ) : NEW_LINE INDENT print ( " Array β elements β are β consecutive β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Array β elements β are β not β consecutive β " ) NEW_LINE DEDENT |
Check if array elements are consecutive | Added Method 3 | Helper functions to get minimum and maximum in an array The function checks if the array elements are consecutive . If elements are consecutive , then returns true , else returns false ; 1 ) Get the minimum element in array ; 2 ) Get the maximum element in array ; 3 ) max - min + 1 is equal to n then only check all elements ; if the value at index j is negative then there is repetition ; If we do not see a negative value then all elements are distinct ; if ( max - min + 1 != n ) ; UTILITY FUNCTIONS ; Driver Code | def areConsecutive ( arr , n ) : NEW_LINE INDENT if ( n < 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT min = getMin ( arr , n ) NEW_LINE max = getMax ( arr , n ) NEW_LINE if ( max - min + 1 == n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT j = - arr [ i ] - min NEW_LINE DEDENT else : NEW_LINE INDENT j = arr [ i ] - min NEW_LINE DEDENT if ( arr [ j ] > 0 ) : NEW_LINE INDENT arr [ j ] = - arr [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def getMin ( arr , n ) : NEW_LINE INDENT min = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < min ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE DEDENT DEDENT return min NEW_LINE DEDENT def getMax ( arr , n ) : NEW_LINE INDENT max = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > max ) : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 4 , 5 , 3 , 2 , 6 ] NEW_LINE n = len ( arr ) NEW_LINE if ( areConsecutive ( arr , n ) == True ) : NEW_LINE INDENT print ( " β Array β elements β are β consecutive β " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β Array β elements β are β not β consecutive β " ) NEW_LINE DEDENT DEDENT |
Find relative complement of two sorted arrays | Python program to find all those elements of arr1 [ ] that are not present in arr2 [ ] ; If current element in arr2 [ ] is greater , then arr1 [ i ] can 't be present in arr2[j..m-1] ; Skipping smaller elements of arr2 [ ] ; Equal elements found ( skipping in both arrays ) ; Printing remaining elements of arr1 [ ] ; Driver code | def relativeComplement ( arr1 , arr2 , n , m ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( arr1 [ i ] < arr2 [ j ] ) : NEW_LINE INDENT print ( arr1 [ i ] , " β " , end = " " ) NEW_LINE i += 1 NEW_LINE DEDENT elif ( arr1 [ i ] > arr2 [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT elif ( arr1 [ i ] == arr2 [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE j += 1 NEW_LINE DEDENT DEDENT while ( i < n ) : NEW_LINE INDENT print ( arr1 [ i ] , " β " , end = " " ) NEW_LINE DEDENT DEDENT arr1 = [ 3 , 6 , 10 , 12 , 15 ] NEW_LINE arr2 = [ 1 , 3 , 5 , 10 , 16 ] NEW_LINE n = len ( arr1 ) NEW_LINE m = len ( arr2 ) NEW_LINE relativeComplement ( arr1 , arr2 , n , m ) NEW_LINE |
Minimum increment by k operations to make all elements equal | function for calculating min operations ; max elements of array ; iterate for all elements ; check if element can make equal to max or not if not then return - 1 ; else update res fo required operations ; return result ; driver program | def minOps ( arr , n , k ) : NEW_LINE INDENT max1 = max ( arr ) NEW_LINE res = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if ( ( max1 - arr [ i ] ) % k != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT res += ( max1 - arr [ i ] ) / k NEW_LINE DEDENT DEDENT return int ( res ) NEW_LINE DEDENT arr = [ 21 , 33 , 9 , 45 , 63 ] NEW_LINE n = len ( arr ) NEW_LINE k = 6 NEW_LINE print ( minOps ( arr , n , k ) ) NEW_LINE |
Minimize ( max ( A [ i ] , B [ j ] , C [ k ] ) | python code for above approach . ; assigning the length - 1 value to each of three variables ; calculating min difference from last index of lists ; checking condition ; calculating max term from list ; Moving to smaller value in the array with maximum out of three . ; driver code | def solve ( A , B , C ) : NEW_LINE INDENT i = len ( A ) - 1 NEW_LINE j = len ( B ) - 1 NEW_LINE k = len ( C ) - 1 NEW_LINE min_diff = abs ( max ( A [ i ] , B [ j ] , C [ k ] ) - min ( A [ i ] , B [ j ] , C [ k ] ) ) NEW_LINE while i != - 1 and j != - 1 and k != - 1 : NEW_LINE INDENT current_diff = abs ( max ( A [ i ] , B [ j ] , C [ k ] ) - min ( A [ i ] , B [ j ] , C [ k ] ) ) NEW_LINE if current_diff < min_diff : NEW_LINE INDENT min_diff = current_diff NEW_LINE DEDENT max_term = max ( A [ i ] , B [ j ] , C [ k ] ) NEW_LINE if A [ i ] == max_term : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT elif B [ j ] == max_term : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT DEDENT return min_diff NEW_LINE DEDENT A = [ 5 , 8 , 10 , 15 ] NEW_LINE B = [ 6 , 9 , 15 , 78 , 89 ] NEW_LINE C = [ 2 , 3 , 6 , 6 , 8 , 8 , 10 ] NEW_LINE print ( solve ( A , B , C ) ) NEW_LINE |
Analysis of Algorithms | Set 2 ( Worst , Average and Best Cases ) | Linearly search x in arr [ ] . If x is present then return the index , otherwise return - 1 ; Driver Code | def search ( arr , x ) : NEW_LINE INDENT for index , value in enumerate ( arr ) : NEW_LINE INDENT if value == x : NEW_LINE INDENT return index NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 1 , 10 , 30 , 15 ] NEW_LINE x = 30 NEW_LINE print ( x , " is β present β at β index " , search ( arr , x ) ) NEW_LINE |
Binary Search | Returns index of x in arr if present , else - 1 ; If element is present at the middle itself ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; Element is not present in the array ; Driver Code | def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if r >= l : NEW_LINE INDENT mid = l + ( r - l ) // 2 NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] > x : NEW_LINE INDENT return binarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT else : NEW_LINE INDENT return binarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE x = 10 NEW_LINE result = binarySearch ( arr , 0 , len ( arr ) - 1 , x ) NEW_LINE if result != - 1 : NEW_LINE INDENT print ( " Element β is β present β at β index β % β d " % result ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β is β not β present β in β array " ) NEW_LINE DEDENT |
Binary Search | It returns location of x in given array arr if present , else returns - 1 ; Check if x is present at mid ; If x is greater , ignore left half ; If x is smaller , ignore right half ; If we reach here , then the element was not present ; Driver Code | def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT while l <= r : NEW_LINE INDENT mid = l + ( r - l ) // 2 ; NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] < x : NEW_LINE INDENT l = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT r = mid - 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE x = 10 NEW_LINE result = binarySearch ( arr , 0 , len ( arr ) - 1 , x ) NEW_LINE if result != - 1 : NEW_LINE INDENT print ( " Element β is β present β at β index β % β d " % result ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β is β not β present β in β array " ) NEW_LINE DEDENT |
Jump Search | Python3 code to implement Jump Search ; Finding block size to be jumped ; Finding the block where element is present ( if it is present ) ; Doing a linear search for x in block beginning with prev . ; If we reached next block or end of array , element is not present . ; If element is found ; Driver code to test function ; Find the index of ' x ' using Jump Search ; Print the index where ' x ' is located | import math NEW_LINE def jumpSearch ( arr , x , n ) : NEW_LINE INDENT step = math . sqrt ( n ) NEW_LINE prev = 0 NEW_LINE while arr [ int ( min ( step , n ) - 1 ) ] < x : NEW_LINE INDENT prev = step NEW_LINE step += math . sqrt ( n ) NEW_LINE if prev >= n : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT while arr [ int ( prev ) ] < x : NEW_LINE INDENT prev += 1 NEW_LINE if prev == min ( step , n ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT DEDENT if arr [ int ( prev ) ] == x : NEW_LINE INDENT return prev NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 55 , 89 , 144 , 233 , 377 , 610 ] NEW_LINE x = 55 NEW_LINE n = len ( arr ) NEW_LINE index = jumpSearch ( arr , x , n ) NEW_LINE print ( " Number " , x , " is β at β index " , " % .0f " % index ) NEW_LINE |
Interpolation Search | If x is present in arr [ 0. . n - 1 ] , then returns index of it , else returns - 1. ; Since array is sorted , an element present in array must be in range defined by corner ; Probing the position with keeping uniform distribution in mind . ; Condition of target found ; If x is larger , x is in right subarray ; If x is smaller , x is in left subarray ; Array of items in which search will be conducted ; Element to be searched ; If element was found | def interpolationSearch ( arr , lo , hi , x ) : NEW_LINE INDENT if ( lo <= hi and x >= arr [ lo ] and x <= arr [ hi ] ) : NEW_LINE INDENT pos = lo + ( ( hi - lo ) // ( arr [ hi ] - arr [ lo ] ) * ( x - arr [ lo ] ) ) NEW_LINE if arr [ pos ] == x : NEW_LINE INDENT return pos NEW_LINE DEDENT if arr [ pos ] < x : NEW_LINE INDENT return interpolationSearch ( arr , pos + 1 , hi , x ) NEW_LINE DEDENT if arr [ pos ] > x : NEW_LINE INDENT return interpolationSearch ( arr , lo , pos - 1 , x ) NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 10 , 12 , 13 , 16 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 33 , 35 , 42 , 47 ] NEW_LINE n = len ( arr ) NEW_LINE x = 18 NEW_LINE index = interpolationSearch ( arr , 0 , n - 1 , x ) NEW_LINE if index != - 1 : NEW_LINE INDENT print ( " Element β found β at β index " , index ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β not β found " ) NEW_LINE DEDENT |
Exponential Search | Returns the position of first occurrence of x in array ; IF x is present at first location itself ; Find range for binary search j by repeated doubling ; Call binary search for the found range ; A recurssive binary search function returns location of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at the middle itself ; If the element is smaller than mid , then it can only be present in the left subarray ; Else he element can only be present in the right ; We reach here if the element is not present ; Driver Code | def exponentialSearch ( arr , n , x ) : NEW_LINE INDENT if arr [ 0 ] == x : NEW_LINE INDENT return 0 NEW_LINE DEDENT i = 1 NEW_LINE while i < n and arr [ i ] <= x : NEW_LINE INDENT i = i * 2 NEW_LINE DEDENT return binarySearch ( arr , i / 2 , min ( i , n - 1 ) , x ) NEW_LINE DEDENT def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if r >= l : NEW_LINE INDENT mid = l + ( r - l ) / 2 NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT if arr [ mid ] > x : NEW_LINE INDENT return binarySearch ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binarySearch ( arr , mid + 1 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 3 , 4 , 10 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 10 NEW_LINE result = exponentialSearch ( arr , n , x ) NEW_LINE if result == - 1 : NEW_LINE INDENT print " Element β not β found β in β thye β array " NEW_LINE DEDENT else : NEW_LINE INDENT print " Element β is β present β at β index β % d " % ( result ) NEW_LINE DEDENT |
Radix Sort | A function to do counting sort of arr [ ] according to the digit represented by exp . ; The output array elements that will have sorted arr ; initialize count array as 0 ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output array ; Build the output array ; Copying the output array to arr [ ] , so that arr now contains sorted numbers ; Method to do Radix Sort ; Find the maximum number to know number of digits ; Do counting sort for every digit . Note that instead of passing digit number , exp is passed . exp is 10 ^ i where i is current digit number ; Driver code ; Function Call | def countingSort ( arr , exp1 ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE output = [ 0 ] * ( n ) NEW_LINE count = [ 0 ] * ( 10 ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT index = ( arr [ i ] / exp1 ) NEW_LINE count [ int ( index % 10 ) ] += 1 NEW_LINE DEDENT for i in range ( 1 , 10 ) : NEW_LINE INDENT count [ i ] += count [ i - 1 ] NEW_LINE DEDENT i = n - 1 NEW_LINE while i >= 0 : NEW_LINE INDENT index = ( arr [ i ] / exp1 ) NEW_LINE output [ count [ int ( index % 10 ) ] - 1 ] = arr [ i ] NEW_LINE count [ int ( index % 10 ) ] -= 1 NEW_LINE i -= 1 NEW_LINE DEDENT i = 0 NEW_LINE for i in range ( 0 , len ( arr ) ) : NEW_LINE INDENT arr [ i ] = output [ i ] NEW_LINE DEDENT DEDENT def radixSort ( arr ) : NEW_LINE INDENT max1 = max ( arr ) NEW_LINE exp = 1 NEW_LINE while max1 / exp > 0 : NEW_LINE INDENT countingSort ( arr , exp ) NEW_LINE exp *= 10 NEW_LINE DEDENT DEDENT arr = [ 170 , 45 , 75 , 90 , 802 , 24 , 2 , 66 ] NEW_LINE radixSort ( arr ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] ) NEW_LINE DEDENT |
Comb Sort | To find next gap from current ; Shrink gap by Shrink factor ; Function to sort arr [ ] using Comb Sort ; Initialize gap ; Initialize swapped as true to make sure that loop runs ; Keep running while gap is more than 1 and last iteration caused a swap ; Find next gap ; Initialize swapped as false so that we can check if swap happened or not ; Compare all elements with current gap ; ; ; Driver code to test above | def getNextGap ( gap ) : NEW_LINE INDENT gap = ( gap * 10 ) / 13 NEW_LINE if gap < 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return gap NEW_LINE DEDENT def combSort ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE gap = n NEW_LINE swapped = True NEW_LINE while gap != 1 or swapped == 1 : NEW_LINE INDENT gap = getNextGap ( gap ) NEW_LINE swapped = False NEW_LINE for i in range ( 0 , n - gap ) : NEW_LINE INDENT if arr [ i ] > arr [ i + gap ] : NEW_LINE DEDENT DEDENT DEDENT / * Swap arr [ i ] and arr [ i + gap ] * / NEW_LINE INDENT arr [ i ] , arr [ i + gap ] = arr [ i + gap ] , arr [ i ] NEW_LINE DEDENT / * Set swapped * / NEW_LINE INDENT swapped = True NEW_LINE DEDENT arr = [ 8 , 4 , 1 , 3 , - 44 , 23 , - 6 , 28 , 0 ] NEW_LINE combSort ( arr ) NEW_LINE print ( " Sorted β array : " ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT print ( arr [ i ] ) , NEW_LINE DEDENT |
Cycle Sort | Function sort the array using Cycle sort ; count number of memory writes ; Loop through the array to find cycles to rotate . ; initialize item as starting point ; Find where to put the item . ; If the item is already there , this is not a cycle . ; Otherwise , put the item there or right after any duplicates . ; put the item to it 's right position ; Rotate the rest of the cycle . ; Find where to put the item . ; Put the item there or right after any duplicates . ; put the item to it 's right position ; driver code | def cycleSort ( array ) : NEW_LINE INDENT writes = 0 NEW_LINE for cycleStart in range ( 0 , len ( array ) - 1 ) : NEW_LINE INDENT item = array [ cycleStart ] NEW_LINE pos = cycleStart NEW_LINE for i in range ( cycleStart + 1 , len ( array ) ) : NEW_LINE if array [ i ] < item : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT if pos == cycleStart : NEW_LINE continue NEW_LINE while item == array [ pos ] : NEW_LINE pos += 1 NEW_LINE array [ pos ] , item = item , array [ pos ] NEW_LINE writes += 1 NEW_LINE while pos != cycleStart : NEW_LINE pos = cycleStart NEW_LINE for i in range ( cycleStart + 1 , len ( array ) ) : NEW_LINE INDENT if array [ i ] < item : NEW_LINE pos += 1 NEW_LINE DEDENT while item == array [ pos ] : NEW_LINE INDENT pos += 1 NEW_LINE DEDENT array [ pos ] , item = item , array [ pos ] NEW_LINE writes += 1 NEW_LINE DEDENT return writes NEW_LINE DEDENT arr = [ 1 , 8 , 3 , 9 , 10 , 10 , 2 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE cycleSort ( arr ) NEW_LINE print ( " After β sort β : β " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( arr [ i ] , end = ' β ' ) NEW_LINE DEDENT |
Iterative Quick Sort | Function takes last element as pivot , places the pivot element at its correct position in sorted array , and places all smaller ( smaller than pivot ) to left of pivot and all greater elements to right of pivot ; The main function that implements QuickSort arr [ ] -- > Array to be sorted , low -- > Starting index , high -- > Ending index Function to do Quick sort ; pi is partitioning index , arr [ p ] is now at right place ; Driver Code | def partition ( arr , low , high ) : NEW_LINE INDENT i = ( low - 1 ) NEW_LINE pivot = arr [ high ] NEW_LINE for j in range ( low , high ) : NEW_LINE INDENT if arr [ j ] <= pivot : NEW_LINE INDENT i += 1 NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT arr [ i + 1 ] , arr [ high ] = arr [ high ] , arr [ i + 1 ] NEW_LINE return ( i + 1 ) NEW_LINE DEDENT def quickSort ( arr , low , high ) : NEW_LINE INDENT if low < high : NEW_LINE INDENT pi = partition ( arr , low , high ) NEW_LINE quickSort ( arr , low , pi - 1 ) NEW_LINE quickSort ( arr , pi + 1 , high ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 2 , 6 , 9 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE quickSort ( arr , 0 , n - 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT |
Iterative Quick Sort | This function is same in both iterative and recursive ; Function to do Quick sort arr [ ] -- > Array to be sorted , l -- > Starting index , h -- > Ending index ; Create an auxiliary stack ; initialize top of stack ; push initial values of l and h to stack ; Keep popping from stack while is not empty ; Pop h and l ; Set pivot element at its correct position in sorted array ; If there are elements on left side of pivot , then push left side to stack ; If there are elements on right side of pivot , then push right side to stack ; Driver code to test above ; Function calling | def partition ( arr , l , h ) : NEW_LINE INDENT i = ( l - 1 ) NEW_LINE x = arr [ h ] NEW_LINE for j in range ( l , h ) : NEW_LINE INDENT if arr [ j ] <= x : NEW_LINE INDENT i = i + 1 NEW_LINE arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE DEDENT DEDENT arr [ i + 1 ] , arr [ h ] = arr [ h ] , arr [ i + 1 ] NEW_LINE return ( i + 1 ) NEW_LINE DEDENT def quickSortIterative ( arr , l , h ) : NEW_LINE INDENT size = h - l + 1 NEW_LINE stack = [ 0 ] * ( size ) NEW_LINE top = - 1 NEW_LINE top = top + 1 NEW_LINE stack [ top ] = l NEW_LINE top = top + 1 NEW_LINE stack [ top ] = h NEW_LINE while top >= 0 : NEW_LINE INDENT h = stack [ top ] NEW_LINE top = top - 1 NEW_LINE l = stack [ top ] NEW_LINE top = top - 1 NEW_LINE p = partition ( arr , l , h ) NEW_LINE if p - 1 > l : NEW_LINE INDENT top = top + 1 NEW_LINE stack [ top ] = l NEW_LINE top = top + 1 NEW_LINE stack [ top ] = p - 1 NEW_LINE DEDENT if p + 1 < h : NEW_LINE INDENT top = top + 1 NEW_LINE stack [ top ] = p + 1 NEW_LINE top = top + 1 NEW_LINE stack [ top ] = h NEW_LINE DEDENT DEDENT DEDENT arr = [ 4 , 3 , 5 , 2 , 1 , 3 , 2 , 3 ] NEW_LINE n = len ( arr ) NEW_LINE quickSortIterative ( arr , 0 , n - 1 ) NEW_LINE print ( " Sorted β array β is : " ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT print ( " % β d " % arr [ i ] ) , NEW_LINE DEDENT |
Sort n numbers in range from 0 to n ^ 2 | A function to do counting sort of arr [ ] according to the digit represented by exp . ; output array ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; The main function to that sorts arr [ ] of size n using Radix Sort ; Do counting sort for first digit in base n . Note that instead of passing digit number , exp ( n ^ 0 = 1 ) is passed . ; Do counting sort for second digit in base n . Note that instead of passing digit number , exp ( n ^ 1 = n ) is passed . ; Driver Code ; Since array size is 7 , elements should be from 0 to 48 | def countSort ( arr , n , exp ) : NEW_LINE INDENT output = [ 0 ] * n NEW_LINE count = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT count [ i ] = 0 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT count [ ( arr [ i ] // exp ) % n ] += 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT count [ i ] += count [ i - 1 ] NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT output [ count [ ( arr [ i ] // exp ) % n ] - 1 ] = arr [ i ] NEW_LINE count [ ( arr [ i ] // exp ) % n ] -= 1 NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT arr [ i ] = output [ i ] NEW_LINE DEDENT DEDENT def sort ( arr , n ) : NEW_LINE INDENT countSort ( arr , n , 1 ) NEW_LINE countSort ( arr , n , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 40 , 12 , 45 , 32 , 33 , 1 , 22 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Given β array β is " ) NEW_LINE print ( * arr ) NEW_LINE sort ( arr , n ) NEW_LINE print ( " Sorted β array β is " ) NEW_LINE print ( * arr ) NEW_LINE DEDENT |
Search in an almost sorted array | A recursive binary search based function . It returns index of x in given array arr [ l . . r ] is present , otherwise - 1 ; If the element is present at one of the middle 3 positions ; If element is smaller than mid , then it can only be present in left subarray ; Else the element can only be present in right subarray ; We reach here when element is not present in array ; Driver Code | def binarySearch ( arr , l , r , x ) : NEW_LINE INDENT if ( r >= l ) : NEW_LINE INDENT mid = int ( l + ( r - l ) / 2 ) NEW_LINE if ( arr [ mid ] == x ) : return mid NEW_LINE if ( mid > l and arr [ mid - 1 ] == x ) : NEW_LINE INDENT return ( mid - 1 ) NEW_LINE DEDENT if ( mid < r and arr [ mid + 1 ] == x ) : NEW_LINE INDENT return ( mid + 1 ) NEW_LINE DEDENT if ( arr [ mid ] > x ) : NEW_LINE INDENT return binarySearch ( arr , l , mid - 2 , x ) NEW_LINE DEDENT return binarySearch ( arr , mid + 2 , r , x ) NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ 3 , 2 , 10 , 4 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 4 NEW_LINE result = binarySearch ( arr , 0 , n - 1 , x ) NEW_LINE if ( result == - 1 ) : NEW_LINE INDENT print ( " Element β is β not β present β in β array " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Element β is β present β at β index " , result ) NEW_LINE DEDENT |
Find the closest pair from two sorted arrays | Python3 program to find the pair from two sorted arays such that the sum of pair is closest to a given number x ; ar1 [ 0. . m - 1 ] and ar2 [ 0. . n - 1 ] are two given sorted arrays and x is given number . This function prints the pair from both arrays such that the sum of the pair is closest to x . ; Initialize the diff between pair sum and x . ; Start from left side of ar1 [ ] and right side of ar2 [ ] ; If this pair is closer to x than the previously found closest , then update res_l , res_r and diff ; If sum of this pair is more than x , move to smaller side ; move to the greater side ; Print the result ; Driver program to test above functions | import sys NEW_LINE def printClosest ( ar1 , ar2 , m , n , x ) : NEW_LINE INDENT diff = sys . maxsize NEW_LINE l = 0 NEW_LINE r = n - 1 NEW_LINE while ( l < m and r >= 0 ) : NEW_LINE INDENT if abs ( ar1 [ l ] + ar2 [ r ] - x ) < diff : NEW_LINE INDENT res_l = l NEW_LINE res_r = r NEW_LINE diff = abs ( ar1 [ l ] + ar2 [ r ] - x ) NEW_LINE DEDENT if ar1 [ l ] + ar2 [ r ] > x : NEW_LINE INDENT r = r - 1 NEW_LINE DEDENT else : NEW_LINE INDENT l = l + 1 NEW_LINE DEDENT DEDENT print ( " The β closest β pair β is β [ " , ar1 [ res_l ] , " , " , ar2 [ res_r ] , " ] " ) NEW_LINE DEDENT ar1 = [ 1 , 4 , 5 , 7 ] NEW_LINE ar2 = [ 10 , 20 , 30 , 40 ] NEW_LINE m = len ( ar1 ) NEW_LINE n = len ( ar2 ) NEW_LINE x = 38 NEW_LINE printClosest ( ar1 , ar2 , m , n , x ) NEW_LINE |
Given a sorted array and a number x , find the pair in array whose sum is closest to x | Python3 program to find the pair with sum closest to a given no . A sufficiently large value greater than any element in the input array ; Prints the pair with sum closest to x ; To store indexes of result pair ; Initialize left and right indexes and difference between pair sum and x ; While there are elements between l and r ; Check if this pair is closer than the closest pair so far ; If this pair has more sum , move to smaller values . ; Move to larger values ; Driver code to test above | MAX_VAL = 1000000000 NEW_LINE def printClosest ( arr , n , x ) : NEW_LINE INDENT res_l , res_r = 0 , 0 NEW_LINE l , r , diff = 0 , n - 1 , MAX_VAL NEW_LINE while r > l : NEW_LINE INDENT if abs ( arr [ l ] + arr [ r ] - x ) < diff : NEW_LINE INDENT res_l = l NEW_LINE res_r = r NEW_LINE diff = abs ( arr [ l ] + arr [ r ] - x ) NEW_LINE DEDENT if arr [ l ] + arr [ r ] > x : NEW_LINE INDENT r -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT l += 1 NEW_LINE DEDENT DEDENT print ( ' The β closest β pair β is β { } β and β { } ' . format ( arr [ res_l ] , arr [ res_r ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 22 , 28 , 29 , 30 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE x = 54 NEW_LINE printClosest ( arr , n , x ) NEW_LINE DEDENT |
Count 1 's in a sorted binary array | Returns counts of 1 's in arr[low..high]. The array is assumed to be sorted in non-increasing order ; get the middle index ; check if the element at middle index is last 1 ; If element is not last 1 , recur for right side ; else recur for left side ; Driver Code | def countOnes ( arr , low , high ) : NEW_LINE INDENT if high >= low : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if ( ( mid == high or arr [ mid + 1 ] == 0 ) and ( arr [ mid ] == 1 ) ) : NEW_LINE INDENT return mid + 1 NEW_LINE DEDENT if arr [ mid ] == 1 : NEW_LINE INDENT return countOnes ( arr , ( mid + 1 ) , high ) NEW_LINE DEDENT return countOnes ( arr , low , mid - 1 ) NEW_LINE DEDENT return 0 NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 1 , 0 , 0 , 0 ] NEW_LINE print ( " Count β of β 1 ' s β in β given β array β is " , countOnes ( arr , 0 , len ( arr ) - 1 ) ) NEW_LINE |
Minimum adjacent swaps to move maximum and minimum to corners | Function that returns the minimum swaps ; Index of leftmost largest element ; Index of rightmost smallest element ; Driver code | def minSwaps ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE maxx , minn , l , r = - 1 , arr [ 0 ] , 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] > maxx : NEW_LINE INDENT maxx = arr [ i ] NEW_LINE l = i NEW_LINE DEDENT if arr [ i ] <= minn : NEW_LINE INDENT minn = arr [ i ] NEW_LINE r = i NEW_LINE DEDENT DEDENT if r < l : NEW_LINE INDENT print ( l + ( n - r - 2 ) ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( l + ( n - r - 1 ) ) NEW_LINE DEDENT DEDENT arr = [ 5 , 6 , 1 , 3 ] NEW_LINE minSwaps ( arr ) NEW_LINE |
Activity Selection Problem | Greedy Algo | Prints a maximum set of activities that can be done by a single person , one at a time n -- > Total number of activities s [ ] -- > An array that contains start time of all activities f [ ] -- > An array that contains finish time of all activities ; The first activity is always selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; Driver program to test above function | def printMaxActivities ( s , f ) : NEW_LINE INDENT n = len ( f ) NEW_LINE print " The β following β activities β are β selected " NEW_LINE i = 0 NEW_LINE print i , NEW_LINE for j in xrange ( n ) : NEW_LINE INDENT if s [ j ] >= f [ i ] : NEW_LINE INDENT print j , NEW_LINE i = j NEW_LINE DEDENT DEDENT DEDENT s = [ 1 , 3 , 0 , 5 , 8 , 5 ] NEW_LINE f = [ 2 , 4 , 6 , 7 , 9 , 9 ] NEW_LINE printMaxActivities ( s , f ) NEW_LINE |
Activity Selection Problem | Greedy Algo | Returns count of the maximum set of activities that can be done by a single person , one at a time . ; Sort jobs according to finish time ; The first activity always gets selected ; Consider rest of the activities ; If this activity has start time greater than or equal to the finish time of previously selected activity , then select it ; Driver code | def MaxActivities ( arr , n ) : NEW_LINE INDENT selected = [ ] NEW_LINE Activity . sort ( key = lambda x : x [ 1 ] ) NEW_LINE i = 0 NEW_LINE selected . append ( arr [ i ] ) NEW_LINE for j in range ( 1 , n ) : NEW_LINE if arr [ j ] [ 0 ] >= arr [ i ] [ 1 ] : NEW_LINE INDENT selected . append ( arr [ j ] ) NEW_LINE i = j NEW_LINE DEDENT return selected NEW_LINE DEDENT Activity = [ [ 5 , 9 ] , [ 1 , 2 ] , [ 3 , 4 ] , [ 0 , 6 ] , [ 5 , 7 ] , [ 8 , 9 ] ] NEW_LINE n = len ( Activity ) NEW_LINE selected = MaxActivities ( Activity , n ) NEW_LINE print ( " Following β activities β are β selected β : " ) NEW_LINE print ( selected ) NEW_LINE |
Longest Increasing Subsequence | DP | global variable to store the maximum ; To make use of recursive calls , this function must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose 2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base Case ; maxEndingHere is the length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] . . arr [ n - 2 ] IF arr [ n - 1 ] is maller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare maxEndingHere with overall maximum . And update the overall maximum if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; maximum variable holds the result ; The function _lis ( ) stores its result in maximum ; returns max ; Driver program to test the above function | global maximum NEW_LINE def _lis ( arr , n ) : NEW_LINE INDENT global maximum NEW_LINE if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT maxEndingHere = 1 NEW_LINE for i in xrange ( 1 , n ) : NEW_LINE INDENT res = _lis ( arr , i ) NEW_LINE if arr [ i - 1 ] < arr [ n - 1 ] and res + 1 > maxEndingHere : NEW_LINE INDENT maxEndingHere = res + 1 NEW_LINE DEDENT DEDENT maximum = max ( maximum , maxEndingHere ) NEW_LINE return maxEndingHere NEW_LINE DEDENT def lis ( arr ) : NEW_LINE INDENT global maximum NEW_LINE n = len ( arr ) NEW_LINE maximum = 1 NEW_LINE _lis ( arr , n ) NEW_LINE return maximum NEW_LINE DEDENT arr = [ 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 ] NEW_LINE n = len ( arr ) NEW_LINE print " Length β of β lis β is β " , lis ( arr ) NEW_LINE |
Longest Increasing Subsequence | DP | lis returns length of the longest increasing subsequence in arr of size n ; Declare the list ( array ) for LIS and initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Initialize maximum to 0 to get the maximum of all LIS ; Pick maximum of all LIS values ; Driver program to test above function | def lis ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE lis = [ 1 ] * n NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if arr [ i ] > arr [ j ] and lis [ i ] < lis [ j ] + 1 : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT maximum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT maximum = max ( maximum , lis [ i ] ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT arr = [ 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 ] NEW_LINE print " Length β of β lis β is " , lis ( arr ) NEW_LINE |
Longest Common Subsequence | DP | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Driver program to test the above function | def lcs ( X , Y , m , n ) : NEW_LINE INDENT if m == 0 or n == 0 : NEW_LINE return 0 ; NEW_LINE elif X [ m - 1 ] == Y [ n - 1 ] : NEW_LINE return 1 + lcs ( X , Y , m - 1 , n - 1 ) ; NEW_LINE else : NEW_LINE return max ( lcs ( X , Y , m , n - 1 ) , lcs ( X , Y , m - 1 , n ) ) ; NEW_LINE DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE print " Length β of β LCS β is β " , lcs ( X , Y , len ( X ) , len ( Y ) ) NEW_LINE |
Longest Common Subsequence | DP | Dynamic Programming implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion Note : L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains the length of LCS of X [ 0. . n - 1 ] & Y [ 0. . m - 1 ] ; end of function lcs Driver program to test the above function | def lcs ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ None ] * ( n + 1 ) for i in xrange ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if i == 0 or j == 0 : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif X [ i - 1 ] == Y [ j - 1 ] : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE print " Length β of β LCS β is β " , lcs ( X , Y ) NEW_LINE |
Edit Distance | DP | A Space efficient Dynamic Programming based Python3 program to find minimum number operations to convert str1 to str2 ; Create a DP array to memoize result of previous computations ; Base condition when second String is empty then we remove all characters ; Start filling the DP This loop run for every character in second String ; This loop compares the char from second String with first String characters ; If first String is empty then we have to perform add character operation to get second String ; If character from both String is same then we do not perform any operation . here i % 2 is for bound the row number . ; If character from both String is not same then we take the minimum from three specified operation ; After complete fill the DP array if the len2 is even then we end up in the 0 th row else we end up in the 1 th row so we take len2 % 2 to get row ; Driver code | def EditDistDP ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE DP = [ [ 0 for i in range ( len1 + 1 ) ] for j in range ( 2 ) ] ; NEW_LINE for i in range ( 0 , len1 + 1 ) : NEW_LINE INDENT DP [ 0 ] [ i ] = i NEW_LINE DEDENT for i in range ( 1 , len2 + 1 ) : NEW_LINE INDENT for j in range ( 0 , len1 + 1 ) : NEW_LINE INDENT if ( j == 0 ) : NEW_LINE INDENT DP [ i % 2 ] [ j ] = i NEW_LINE DEDENT elif ( str1 [ j - 1 ] == str2 [ i - 1 ] ) : NEW_LINE INDENT DP [ i % 2 ] [ j ] = DP [ ( i - 1 ) % 2 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i % 2 ] [ j ] = ( 1 + min ( DP [ ( i - 1 ) % 2 ] [ j ] , min ( DP [ i % 2 ] [ j - 1 ] , DP [ ( i - 1 ) % 2 ] [ j - 1 ] ) ) ) NEW_LINE DEDENT DEDENT DEDENT print ( DP [ len2 % 2 ] [ len1 ] , " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " food " NEW_LINE str2 = " money " NEW_LINE EditDistDP ( str1 , str2 ) NEW_LINE DEDENT |
Edit Distance | DP | ; If any string is empty , return the remaining characters of other string ; To check if the recursive tree for given n & m has already been executed ; If characters are equal , execute recursive function for n - 1 , m - 1 ; If characters are nt equal , we need to find the minimum cost out of all 3 operations . ; temp variables ; Driver code | def minDis ( s1 , s2 , n , m , dp ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return m NEW_LINE DEDENT if ( m == 0 ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( dp [ n ] [ m ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ m ] ; NEW_LINE DEDENT if ( s1 [ n - 1 ] == s2 [ m - 1 ] ) : NEW_LINE INDENT if ( dp [ n - 1 ] [ m - 1 ] == - 1 ) : NEW_LINE INDENT dp [ n ] [ m ] = minDis ( s1 , s2 , n - 1 , m - 1 , dp ) NEW_LINE return dp [ n ] [ m ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ n ] [ m ] = dp [ n - 1 ] [ m - 1 ] NEW_LINE return dp [ n ] [ m ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( dp [ n - 1 ] [ m ] != - 1 ) : NEW_LINE m1 = dp [ n - 1 ] [ m ] NEW_LINE else : NEW_LINE m1 = minDis ( s1 , s2 , n - 1 , m , dp ) NEW_LINE if ( dp [ n ] [ m - 1 ] != - 1 ) : NEW_LINE m2 = dp [ n ] [ m - 1 ] NEW_LINE else : NEW_LINE m2 = minDis ( s1 , s2 , n , m - 1 , dp ) NEW_LINE if ( dp [ n - 1 ] [ m - 1 ] != - 1 ) : NEW_LINE m3 = dp [ n - 1 ] [ m - 1 ] NEW_LINE else : NEW_LINE m3 = minDis ( s1 , s2 , n - 1 , m - 1 , dp ) NEW_LINE dp [ n ] [ m ] = 1 + min ( m1 , min ( m2 , m3 ) ) NEW_LINE return dp [ n ] [ m ] NEW_LINE DEDENT DEDENT str1 = " voldemort " NEW_LINE str2 = " dumbledore " NEW_LINE n = len ( str1 ) NEW_LINE m = len ( str2 ) NEW_LINE dp = [ [ - 1 for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE print ( minDis ( str1 , str2 , n , m , dp ) ) NEW_LINE |
Min Cost Path | DP | A Naive recursive implementation of MCP ( Minimum Cost Path ) problem ; A utility function that returns minimum of 3 integers ; Returns cost of minimum cost path from ( 0 , 0 ) to ( m , n ) in mat [ R ] [ C ] ; Driver program to test above functions | R = 3 NEW_LINE C = 3 NEW_LINE import sys NEW_LINE def min ( x , y , z ) : NEW_LINE INDENT if ( x < y ) : NEW_LINE INDENT return x if ( x < z ) else z NEW_LINE DEDENT else : NEW_LINE INDENT return y if ( y < z ) else z NEW_LINE DEDENT DEDENT def minCost ( cost , m , n ) : NEW_LINE INDENT if ( n < 0 or m < 0 ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT elif ( m == 0 and n == 0 ) : NEW_LINE INDENT return cost [ m ] [ n ] NEW_LINE DEDENT else : NEW_LINE INDENT return cost [ m ] [ n ] + min ( minCost ( cost , m - 1 , n - 1 ) , minCost ( cost , m - 1 , n ) , minCost ( cost , m , n - 1 ) ) NEW_LINE DEDENT DEDENT cost = [ [ 1 , 2 , 3 ] , [ 4 , 8 , 2 ] , [ 1 , 5 , 3 ] ] NEW_LINE print ( minCost ( cost , 2 , 2 ) ) NEW_LINE |
Min Cost Path | DP | Dynamic Programming Python implementation of Min Cost Path problem ; Instead of following line , we can use int tc [ m + 1 ] [ n + 1 ] or dynamically allocate memoery to save space . The following line is used to keep te program simple and make it working on all compilers . ; Initialize first column of total cost ( tc ) array ; Initialize first row of tc array ; Construct rest of the tc array ; Driver program to test above functions | R = 3 NEW_LINE C = 3 NEW_LINE def minCost ( cost , m , n ) : NEW_LINE INDENT tc = [ [ 0 for x in range ( C ) ] for x in range ( R ) ] NEW_LINE tc [ 0 ] [ 0 ] = cost [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , m + 1 ) : NEW_LINE INDENT tc [ i ] [ 0 ] = tc [ i - 1 ] [ 0 ] + cost [ i ] [ 0 ] NEW_LINE DEDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT tc [ 0 ] [ j ] = tc [ 0 ] [ j - 1 ] + cost [ 0 ] [ j ] NEW_LINE DEDENT for i in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT tc [ i ] [ j ] = min ( tc [ i - 1 ] [ j - 1 ] , tc [ i - 1 ] [ j ] , tc [ i ] [ j - 1 ] ) + cost [ i ] [ j ] NEW_LINE DEDENT DEDENT return tc [ m ] [ n ] NEW_LINE DEDENT cost = [ [ 1 , 2 , 3 ] , [ 4 , 8 , 2 ] , [ 1 , 5 , 3 ] ] NEW_LINE print ( minCost ( cost , 2 , 2 ) ) NEW_LINE |
Min Cost Path | DP | Python3 program for the above approach ; For 1 st column ; For 1 st row ; For rest of the 2d matrix ; Returning the value in last cell ; Driver code | def minCost ( cost , row , col ) : NEW_LINE INDENT for i in range ( 1 , row ) : NEW_LINE INDENT cost [ i ] [ 0 ] += cost [ i - 1 ] [ 0 ] NEW_LINE DEDENT for j in range ( 1 , col ) : NEW_LINE INDENT cost [ 0 ] [ j ] += cost [ 0 ] [ j - 1 ] NEW_LINE DEDENT for i in range ( 1 , row ) : NEW_LINE INDENT for j in range ( 1 , col ) : NEW_LINE INDENT cost [ i ] [ j ] += ( min ( cost [ i - 1 ] [ j - 1 ] , min ( cost [ i - 1 ] [ j ] , cost [ i ] [ j - 1 ] ) ) ) NEW_LINE DEDENT DEDENT return cost [ row - 1 ] [ col - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT row = 3 NEW_LINE col = 3 NEW_LINE cost = [ [ 1 , 2 , 3 ] , [ 4 , 8 , 2 ] , [ 1 , 5 , 3 ] ] NEW_LINE print ( minCost ( cost , row , col ) ) ; NEW_LINE DEDENT |
0 | Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack of capacity W , then this item cannot be included in the optimal solution ; return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver Code | def knapSack ( W , wt , val , n ) : NEW_LINE INDENT if n == 0 or W == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( wt [ n - 1 ] > W ) : NEW_LINE INDENT return knapSack ( W , wt , val , n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) NEW_LINE DEDENT DEDENT val = [ 60 , 100 , 120 ] NEW_LINE wt = [ 10 , 20 , 30 ] NEW_LINE W = 50 NEW_LINE n = len ( val ) NEW_LINE print knapSack ( W , wt , val , n ) NEW_LINE |
0 | Returns the maximum value that can be put in a knapsack of capacity W ; Build table K [ ] [ ] in bottom up manner ; Driver code | def knapSack ( W , wt , val , n ) : NEW_LINE INDENT K = [ [ 0 for x in range ( W + 1 ) ] for x in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for w in range ( W + 1 ) : NEW_LINE INDENT if i == 0 or w == 0 : NEW_LINE INDENT K [ i ] [ w ] = 0 NEW_LINE DEDENT elif wt [ i - 1 ] <= w : NEW_LINE INDENT K [ i ] [ w ] = max ( val [ i - 1 ] + K [ i - 1 ] [ w - wt [ i - 1 ] ] , K [ i - 1 ] [ w ] ) NEW_LINE DEDENT else : NEW_LINE INDENT K [ i ] [ w ] = K [ i - 1 ] [ w ] NEW_LINE DEDENT DEDENT DEDENT return K [ n ] [ W ] NEW_LINE DEDENT val = [ 60 , 100 , 120 ] NEW_LINE wt = [ 10 , 20 , 30 ] NEW_LINE W = 50 NEW_LINE n = len ( val ) NEW_LINE print ( knapSack ( W , wt , val , n ) ) NEW_LINE |
Egg Dropping Puzzle | DP | ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; If there are no floors , then no trials needed . OR if there is one floor , one trial needed . ; We need k trials for one egg and k floors ; Consider all droppings from 1 st floor to kth floor and return the minimum of these values plus 1. ; Driver Code | import sys NEW_LINE def eggDrop ( n , k ) : NEW_LINE INDENT if ( k == 1 or k == 0 ) : NEW_LINE INDENT return k NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return k NEW_LINE DEDENT min = sys . maxsize NEW_LINE for x in range ( 1 , k + 1 ) : NEW_LINE INDENT res = max ( eggDrop ( n - 1 , x - 1 ) , eggDrop ( n , k - x ) ) NEW_LINE if ( res < min ) : NEW_LINE INDENT min = res NEW_LINE DEDENT DEDENT return min + 1 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 NEW_LINE k = 10 NEW_LINE print ( " Minimum β number β of β trials β in β worst β case β with " , n , " eggs β and " , k , " floors β is " , eggDrop ( n , k ) ) NEW_LINE DEDENT |
Egg Dropping Puzzle | DP | A Dynamic Programming based Python Program for the Egg Dropping Puzzle ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; A 2D table where entry eggFloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; We need one trial for one floor and0 trials for 0 floors ; We always need j trials for one egg and j floors . ; Fill rest of the entries in table using optimal substructure property ; eggFloor [ n ] [ k ] holds the result ; Driver program to test to pront printDups | INT_MAX = 32767 NEW_LINE def eggDrop ( n , k ) : NEW_LINE INDENT eggFloor = [ [ 0 for x in range ( k + 1 ) ] for x in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT eggFloor [ i ] [ 1 ] = 1 NEW_LINE eggFloor [ i ] [ 0 ] = 0 NEW_LINE DEDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT eggFloor [ 1 ] [ j ] = j NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 2 , k + 1 ) : NEW_LINE INDENT eggFloor [ i ] [ j ] = INT_MAX NEW_LINE for x in range ( 1 , j + 1 ) : NEW_LINE INDENT res = 1 + max ( eggFloor [ i - 1 ] [ x - 1 ] , eggFloor [ i ] [ j - x ] ) NEW_LINE if res < eggFloor [ i ] [ j ] : NEW_LINE INDENT eggFloor [ i ] [ j ] = res NEW_LINE DEDENT DEDENT DEDENT DEDENT return eggFloor [ n ] [ k ] NEW_LINE DEDENT n = 2 NEW_LINE k = 36 NEW_LINE print ( " Minimum β number β of β trials β in β worst β case β with " + str ( n ) + " eggs β and β " + str ( k ) + " β floors β is β " + str ( eggDrop ( n , k ) ) ) NEW_LINE |
Longest Palindromic Subsequence | DP | A utility function to get max of two integers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and last characters do not match ; Driver Code | def max ( x , y ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT return x NEW_LINE DEDENT return y NEW_LINE DEDENT def lps ( seq , i , j ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( seq [ i ] == seq [ j ] and i + 1 == j ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT if ( seq [ i ] == seq [ j ] ) : NEW_LINE INDENT return lps ( seq , i + 1 , j - 1 ) + 2 NEW_LINE DEDENT return max ( lps ( seq , i , j - 1 ) , lps ( seq , i + 1 , j ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT seq = " GEEKSFORGEEKS " NEW_LINE n = len ( seq ) NEW_LINE print ( " The β length β of β the β LPS β is " , lps ( seq , 0 , n - 1 ) ) NEW_LINE DEDENT |
Longest Palindromic Subsequence | DP | Returns the length of the longest palindromic subsequence in seq ; Create a table to store results of subproblems ; Strings of length 1 are palindrome of length 1 ; Build the table . Note that the lower diagonal values of table are useless and not filled in the process . The values are filled in a manner similar to Matrix Chain Multiplication DP solution ( See https : www . geeksforgeeks . org / dynamic - programming - set - 8 - matrix - chain - multiplication / cl is length of substring ; Driver program to test above functions | def lps ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE L = [ [ 0 for x in range ( n ) ] for x in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT L [ i ] [ i ] = 1 NEW_LINE DEDENT for cl in range ( 2 , n + 1 ) : NEW_LINE INDENT for i in range ( n - cl + 1 ) : NEW_LINE INDENT j = i + cl - 1 NEW_LINE if str [ i ] == str [ j ] and cl == 2 : NEW_LINE INDENT L [ i ] [ j ] = 2 NEW_LINE DEDENT elif str [ i ] == str [ j ] : NEW_LINE INDENT L [ i ] [ j ] = L [ i + 1 ] [ j - 1 ] + 2 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i ] [ j - 1 ] , L [ i + 1 ] [ j ] ) ; NEW_LINE DEDENT DEDENT DEDENT return L [ 0 ] [ n - 1 ] NEW_LINE DEDENT seq = " GEEKS β FOR β GEEKS " NEW_LINE n = len ( seq ) NEW_LINE print ( " The β length β of β the β LPS β is β " + str ( lps ( seq ) ) ) NEW_LINE |
Longest Bitonic Subsequence | DP | lbs ( ) returns the length of the Longest Bitonic Subsequence in arr [ ] of size n . The function mainly creates two temporary arrays lis [ ] and lds [ ] and returns the maximum lis [ i ] + lds [ i ] - 1. lis [ i ] == > Longest Increasing subsequence ending with arr [ i ] lds [ i ] == > Longest decreasing subsequence starting with arr [ i ] ; allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right ; allocate memory for LDS and initialize LDS values for all indexes ; Compute LDS values from right to left ; Return the maximum value of ( lis [ i ] + lds [ i ] - 1 ) ; Driver program to test the above function | def lbs ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE lis = [ 1 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if ( ( arr [ i ] > arr [ j ] ) and ( lis [ i ] < lis [ j ] + 1 ) ) : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT lds = [ 1 for i in range ( n + 1 ) ] NEW_LINE for i in reversed ( range ( n - 1 ) ) : NEW_LINE INDENT for j in reversed ( range ( i - 1 , n ) ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and lds [ i ] < lds [ j ] + 1 ) : NEW_LINE INDENT lds [ i ] = lds [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT maximum = lis [ 0 ] + lds [ 0 ] - 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT maximum = max ( ( lis [ i ] + lds [ i ] - 1 ) , maximum ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT arr = [ 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 ] NEW_LINE print " Length β of β LBS β is " , lbs ( arr ) NEW_LINE |
Palindrome Partitioning | DP | Python code for implementation of Naive Recursive approach ; Driver code | def isPalindrome ( x ) : NEW_LINE INDENT return x == x [ : : - 1 ] NEW_LINE DEDENT def minPalPartion ( string , i , j ) : NEW_LINE INDENT if i >= j or isPalindrome ( string [ i : j + 1 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = float ( ' inf ' ) NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT count = ( 1 + minPalPartion ( string , i , k ) + minPalPartion ( string , k + 1 , j ) ) NEW_LINE ans = min ( ans , count ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT string = " ababbbabbababa " NEW_LINE print ( " Min β cuts β needed β for β Palindrome β Partitioning β is β " , minPalPartion ( string , 0 , len ( string ) - 1 ) , ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Palindrome Partitioning | DP | minCut function ; Driver code | def minCut ( a ) : NEW_LINE INDENT cut = [ 0 for i in range ( len ( a ) ) ] NEW_LINE palindrome = [ [ False for i in range ( len ( a ) ) ] for j in range ( len ( a ) ) ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT minCut = i ; NEW_LINE for j in range ( i + 1 ) : NEW_LINE INDENT if ( a [ i ] == a [ j ] and ( i - j < 2 or palindrome [ j + 1 ] [ i - 1 ] ) ) : NEW_LINE INDENT palindrome [ j ] [ i ] = True ; NEW_LINE minCut = min ( minCut , 0 if j == 0 else ( cut [ j - 1 ] + 1 ) ) ; NEW_LINE DEDENT DEDENT cut [ i ] = minCut ; NEW_LINE DEDENT return cut [ len ( a ) - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( minCut ( " aab " ) ) NEW_LINE print ( minCut ( " aabababaxx " ) ) NEW_LINE DEDENT |
Palindrome Partitioning | DP | Using memoizatoin to solve the partition problem . Function to check if input string is pallindrome or not ; Using two pointer technique to check pallindrome ; Function to find keys for the Hashmap ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Key for the Input String ; If the no of partitions for string " ij " is already calculated then return the calculated value using the Hashmap ; Every String of length 1 is a pallindrome ; Make a cut at every possible location starting from i to j ; If left cut is found already ; If right cut is found already ; Recursively calculating for left and right strings ; Taking minimum of all k possible cuts ; Return the min cut value for complete string . ; Driver code | def ispallindrome ( input , start , end ) : NEW_LINE INDENT while ( start < end ) : NEW_LINE INDENT if ( input [ start ] != input [ end ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT return True ; NEW_LINE DEDENT def convert ( a , b ) : NEW_LINE INDENT return str ( a ) + str ( b ) ; NEW_LINE DEDENT def minpalparti_memo ( input , i , j , memo ) : NEW_LINE INDENT if ( i > j ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT ij = convert ( i , j ) ; NEW_LINE if ( ij in memo ) : NEW_LINE INDENT return memo [ ij ] ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT memo [ ij ] = 0 ; NEW_LINE return 0 ; NEW_LINE DEDENT if ( ispallindrome ( input , i , j ) ) : NEW_LINE INDENT memo [ ij ] = 0 ; NEW_LINE return 0 ; NEW_LINE DEDENT minimum = 1000000000 NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT left_min = 1000000000 NEW_LINE right_min = 1000000000 NEW_LINE left = convert ( i , k ) ; NEW_LINE right = convert ( k + 1 , j ) ; NEW_LINE if ( left in memo ) : NEW_LINE INDENT left_min = memo [ left ] ; NEW_LINE DEDENT if ( right in memo ) : NEW_LINE INDENT right_min = memo [ right ] ; NEW_LINE DEDENT if ( left_min == 1000000000 ) : NEW_LINE INDENT left_min = minpalparti_memo ( input , i , k , memo ) ; NEW_LINE DEDENT if ( right_min == 1000000000 ) : NEW_LINE INDENT right_min = minpalparti_memo ( input , k + 1 , j , memo ) ; NEW_LINE DEDENT minimum = min ( minimum , left_min + 1 + right_min ) ; NEW_LINE DEDENT memo [ ij ] = minimum ; NEW_LINE return memo [ ij ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = " ababbbabbababa " ; NEW_LINE memo = dict ( ) NEW_LINE print ( minpalparti_memo ( input , 0 , len ( input ) - 1 , memo ) ) NEW_LINE DEDENT |
Word Wrap Problem | DP | A Dynamic programming solution for Word Wrap Problem ; A utility function to print the solution ; l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa β bb β cc β ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; For simplicity , 1 extra space is used in all below arrays extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . The value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; Calculate line cost corresponding to the above calculated extra spaces . The value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; Driver Code | INF = 2147483647 NEW_LINE def printSolution ( p , n ) : NEW_LINE INDENT k = 0 NEW_LINE if p [ n ] == 1 : NEW_LINE INDENT k = 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = printSolution ( p , p [ n ] - 1 ) + 1 NEW_LINE DEDENT print ( ' Line β number β ' , k , ' : β From β word β no . β ' , p [ n ] , ' to β ' , n ) NEW_LINE return k NEW_LINE DEDENT def solveWordWrap ( l , n , M ) : NEW_LINE INDENT extras = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE lc = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE c = [ 0 for i in range ( n + 1 ) ] NEW_LINE p = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT extras [ i ] [ i ] = M - l [ i - 1 ] NEW_LINE for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT extras [ i ] [ j ] = ( extras [ i ] [ j - 1 ] - l [ j - 1 ] - 1 ) NEW_LINE DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT if extras [ i ] [ j ] < 0 : NEW_LINE INDENT lc [ i ] [ j ] = INF ; NEW_LINE DEDENT elif j == n and extras [ i ] [ j ] >= 0 : NEW_LINE INDENT lc [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT lc [ i ] [ j ] = ( extras [ i ] [ j ] * extras [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT c [ 0 ] = 0 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT c [ j ] = INF NEW_LINE for i in range ( 1 , j + 1 ) : NEW_LINE INDENT if ( c [ i - 1 ] != INF and lc [ i ] [ j ] != INF and ( ( c [ i - 1 ] + lc [ i ] [ j ] ) < c [ j ] ) ) : NEW_LINE INDENT c [ j ] = c [ i - 1 ] + lc [ i ] [ j ] NEW_LINE p [ j ] = i NEW_LINE DEDENT DEDENT DEDENT printSolution ( p , n ) NEW_LINE DEDENT l = [ 3 , 2 , 2 , 5 ] NEW_LINE n = len ( l ) NEW_LINE M = 6 NEW_LINE solveWordWrap ( l , n , M ) NEW_LINE |
Ugly Numbers | This function divides a by greatest divisible power of b ; Function to check if a number is ugly or not ; Function to get the nth ugly number ; ugly number count ; Check for all integers untill ugly count becomes n ; Driver code | def maxDivide ( a , b ) : NEW_LINE INDENT while a % b == 0 : NEW_LINE INDENT a = a / b NEW_LINE DEDENT return a NEW_LINE DEDENT def isUgly ( no ) : NEW_LINE INDENT no = maxDivide ( no , 2 ) NEW_LINE no = maxDivide ( no , 3 ) NEW_LINE no = maxDivide ( no , 5 ) NEW_LINE return 1 if no == 1 else 0 NEW_LINE DEDENT def getNthUglyNo ( n ) : NEW_LINE INDENT i = 1 NEW_LINE count = 1 NEW_LINE while n > count : NEW_LINE INDENT i += 1 NEW_LINE if isUgly ( i ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return i NEW_LINE DEDENT no = getNthUglyNo ( 150 ) NEW_LINE print ( "150th β ugly β no . β is β " , no ) NEW_LINE |
Longest Palindromic Substring | Set 1 | Function to pra subString str [ low . . high ] ; This function prints the longest palindrome subString It also returns the length of the longest palindrome ; Get length of input String ; All subStrings of length 1 are palindromes ; Nested loop to mark start and end index ; Check palindrome ; Palindrome ; Return length of LPS ; Driver Code | def printSubStr ( str , low , high ) : NEW_LINE INDENT for i in range ( low , high + 1 ) : NEW_LINE INDENT print ( str [ i ] , end = " " ) NEW_LINE DEDENT DEDENT def longestPalSubstr ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE maxLength = 1 NEW_LINE start = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i , n ) : NEW_LINE INDENT flag = 1 NEW_LINE for k in range ( 0 , ( ( j - i ) // 2 ) + 1 ) : NEW_LINE INDENT if ( str [ i + k ] != str [ j - k ] ) : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT DEDENT if ( flag != 0 and ( j - i + 1 ) > maxLength ) : NEW_LINE INDENT start = i NEW_LINE maxLength = j - i + 1 NEW_LINE DEDENT DEDENT DEDENT print ( " Longest β palindrome β subString β is : β " , end = " " ) NEW_LINE printSubStr ( str , start , start + maxLength - 1 ) NEW_LINE return maxLength NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " forgeeksskeegfor " NEW_LINE print ( " Length is : " , longestPalSubstr ( str ) ) NEW_LINE DEDENT |
Longest Palindromic Substring | Set 1 | Python program ; A utility function to print a substring str [ low . . high ] ; This function prints the longest palindrome substring of st [ ] . It also returns the length of the longest palindrome ; get length of input string ; table [ i ] [ j ] will be false if substring str [ i . . j ] is not palindrome . Else table [ i ] [ j ] will be true ; All substrings of length 1 are palindromes ; check for sub - string of length 2. ; Check for lengths greater than 2. k is length of substring ; Fix the starting index ; Get the ending index of substring from starting index i and length k ; checking for sub - string from ith index to jth index iff st [ i + 1 ] to st [ ( j - 1 ) ] is a palindrome ; return length of LPS ; Driver program to test above functions | import sys NEW_LINE def printSubStr ( st , low , high ) : NEW_LINE INDENT sys . stdout . write ( st [ low : high + 1 ] ) NEW_LINE sys . stdout . flush ( ) NEW_LINE return ' ' NEW_LINE DEDENT def longestPalSubstr ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE table = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE maxLength = 1 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT table [ i ] [ i ] = True NEW_LINE i = i + 1 NEW_LINE DEDENT start = 0 NEW_LINE i = 0 NEW_LINE while i < n - 1 : NEW_LINE INDENT if ( st [ i ] == st [ i + 1 ] ) : NEW_LINE INDENT table [ i ] [ i + 1 ] = True NEW_LINE start = i NEW_LINE maxLength = 2 NEW_LINE DEDENT i = i + 1 NEW_LINE DEDENT k = 3 NEW_LINE while k <= n : NEW_LINE INDENT i = 0 NEW_LINE while i < ( n - k + 1 ) : NEW_LINE INDENT j = i + k - 1 NEW_LINE if ( table [ i + 1 ] [ j - 1 ] and st [ i ] == st [ j ] ) : NEW_LINE INDENT table [ i ] [ j ] = True NEW_LINE if ( k > maxLength ) : NEW_LINE INDENT start = i NEW_LINE maxLength = k NEW_LINE DEDENT DEDENT i = i + 1 NEW_LINE DEDENT k = k + 1 NEW_LINE DEDENT print " Longest β palindrome β substring β is : β " , printSubStr ( st , start , start + maxLength - 1 ) NEW_LINE return maxLength NEW_LINE DEDENT st = " forgeeksskeegfor " NEW_LINE l = longestPalSubstr ( st ) NEW_LINE print " Length β is : " , l NEW_LINE |
Optimal Binary Search Tree | DP | A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A recursive function to calculate cost of optimal binary search tree ; Base cases no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; Driver Code | def Sum ( freq , i , j ) : NEW_LINE INDENT s = 0 NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT s += freq [ k ] NEW_LINE DEDENT return s NEW_LINE DEDENT def optCost ( freq , i , j ) : NEW_LINE INDENT if j < i : NEW_LINE INDENT return 0 NEW_LINE DEDENT if j == i : NEW_LINE INDENT return freq [ i ] NEW_LINE DEDENT fsum = Sum ( freq , i , j ) NEW_LINE Min = 999999999999 NEW_LINE for r in range ( i , j + 1 ) : NEW_LINE INDENT cost = ( optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ) NEW_LINE if cost < Min : NEW_LINE INDENT Min = cost NEW_LINE DEDENT DEDENT return Min + fsum NEW_LINE DEDENT def optimalSearchTree ( keys , freq , n ) : NEW_LINE INDENT return optCost ( freq , 0 , n - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT keys = [ 10 , 12 , 20 ] NEW_LINE freq = [ 34 , 8 , 50 ] NEW_LINE n = len ( keys ) NEW_LINE print ( " Cost β of β Optimal β BST β is " , optimalSearchTree ( keys , freq , n ) ) NEW_LINE DEDENT |
Optimal Binary Search Tree | DP | Dynamic Programming code for Optimal Binary Search Tree Problem ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; A Dynamic Programming based function that calculates minimum cost of a Binary Search Tree . ; Create an auxiliary 2D matrix to store results of subproblems ; For a single key , cost is equal to frequency of the key ; Now we need to consider chains of length 2 , 3 , ... . L is chain length . ; i is row number in cost ; Get column number j from row number i and chain length L ; Try making all keys in interval keys [ i . . j ] as root ; c = cost when keys [ r ] becomes root of this subtree ; Driver Code | INT_MAX = 2147483647 NEW_LINE def sum ( freq , i , j ) : NEW_LINE INDENT s = 0 NEW_LINE for k in range ( i , j + 1 ) : NEW_LINE INDENT s += freq [ k ] NEW_LINE DEDENT return s NEW_LINE DEDENT def optimalSearchTree ( keys , freq , n ) : NEW_LINE INDENT cost = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT cost [ i ] [ i ] = freq [ i ] NEW_LINE DEDENT for L in range ( 2 , n + 1 ) : NEW_LINE INDENT for i in range ( n - L + 2 ) : NEW_LINE INDENT j = i + L - 1 NEW_LINE if i >= n or j >= n : NEW_LINE INDENT break NEW_LINE DEDENT cost [ i ] [ j ] = INT_MAX NEW_LINE for r in range ( i , j + 1 ) : NEW_LINE INDENT c = 0 NEW_LINE if ( r > i ) : NEW_LINE INDENT c += cost [ i ] [ r - 1 ] NEW_LINE DEDENT if ( r < j ) : NEW_LINE INDENT c += cost [ r + 1 ] [ j ] NEW_LINE DEDENT c += sum ( freq , i , j ) NEW_LINE if ( c < cost [ i ] [ j ] ) : NEW_LINE INDENT cost [ i ] [ j ] = c NEW_LINE DEDENT DEDENT DEDENT DEDENT return cost [ 0 ] [ n - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT keys = [ 10 , 12 , 20 ] NEW_LINE freq = [ 34 , 8 , 50 ] NEW_LINE n = len ( keys ) NEW_LINE print ( " Cost β of β Optimal β BST β is " , optimalSearchTree ( keys , freq , n ) ) NEW_LINE DEDENT |
Largest Independent Set Problem | DP | A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree ; Calculate size excluding the current node ; Calculate size including the current node ; Return the maximum of two sizes ; A utility function to create a node ; Let us construct the tree given in the above diagram | def max ( x , y ) : NEW_LINE INDENT if ( x > y ) : NEW_LINE INDENT return x NEW_LINE DEDENT else : NEW_LINE INDENT return y NEW_LINE DEDENT DEDENT class node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def LISS ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT size_excl = LISS ( root . left ) + LISS ( root . right ) NEW_LINE size_incl = 1 NEW_LINE if ( root . left != None ) : NEW_LINE INDENT size_incl += LISS ( root . left . left ) + LISS ( root . left . right ) NEW_LINE DEDENT if ( root . right != None ) : NEW_LINE INDENT size_incl += LISS ( root . right . left ) + LISS ( root . right . right ) NEW_LINE DEDENT return max ( size_incl , size_excl ) NEW_LINE DEDENT def newNode ( data ) : NEW_LINE INDENT temp = node ( ) NEW_LINE temp . data = data NEW_LINE temp . left = temp . right = None NEW_LINE return temp NEW_LINE DEDENT root = newNode ( 20 ) NEW_LINE root . left = newNode ( 8 ) NEW_LINE root . left . left = newNode ( 4 ) NEW_LINE root . left . right = newNode ( 12 ) NEW_LINE root . left . right . left = newNode ( 10 ) NEW_LINE root . left . right . right = newNode ( 14 ) NEW_LINE root . right = newNode ( 22 ) NEW_LINE root . right . right = newNode ( 25 ) NEW_LINE print ( " Size β of β the β Largest " , " β Independent β Set β is β " , LISS ( root ) ) NEW_LINE |
Boolean Parenthesization Problem | DP | Returns count of all possible parenthesizations that lead to result true for a boolean expression with symbols like true and false and operators like & , | and ^ filled between symbols ; Fill diaginal entries first All diagonal entries in T [ i ] [ i ] are 1 if symbol [ i ] is T ( true ) . Similarly , all F [ i ] [ i ] entries are 1 if symbol [ i ] is F ( False ) ; Now fill T [ i ] [ i + 1 ] , T [ i ] [ i + 2 ] , T [ i ] [ i + 3 ] ... in order And F [ i ] [ i + 1 ] , F [ i ] [ i + 2 ] , F [ i ] [ i + 3 ] ... in order ; Find place of parenthesization using current value of gap ; Store Total [ i ] [ k ] and Total [ k + 1 ] [ j ] ; Follow the recursive formulas according to the current operator ; Driver Code ; There are 4 ways ( ( T T ) & ( F ^ T ) ) , ( T | ( T & ( F ^ T ) ) ) , ( ( ( T T ) & F ) ^ T ) and ( T | ( ( T & F ) ^ T ) ) | def countParenth ( symb , oper , n ) : NEW_LINE INDENT F = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE T = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if symb [ i ] == ' F ' : NEW_LINE INDENT F [ i ] [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT F [ i ] [ i ] = 0 NEW_LINE DEDENT if symb [ i ] == ' T ' : NEW_LINE INDENT T [ i ] [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT T [ i ] [ i ] = 0 NEW_LINE DEDENT DEDENT for gap in range ( 1 , n ) : NEW_LINE INDENT i = 0 NEW_LINE for j in range ( gap , n ) : NEW_LINE INDENT T [ i ] [ j ] = F [ i ] [ j ] = 0 NEW_LINE for g in range ( gap ) : NEW_LINE INDENT k = i + g NEW_LINE tik = T [ i ] [ k ] + F [ i ] [ k ] NEW_LINE tkj = T [ k + 1 ] [ j ] + F [ k + 1 ] [ j ] NEW_LINE if oper [ k ] == ' & ' : NEW_LINE INDENT T [ i ] [ j ] += T [ i ] [ k ] * T [ k + 1 ] [ j ] NEW_LINE F [ i ] [ j ] += ( tik * tkj - T [ i ] [ k ] * T [ k + 1 ] [ j ] ) NEW_LINE DEDENT if oper [ k ] == ' | ' : NEW_LINE INDENT F [ i ] [ j ] += F [ i ] [ k ] * F [ k + 1 ] [ j ] NEW_LINE T [ i ] [ j ] += ( tik * tkj - F [ i ] [ k ] * F [ k + 1 ] [ j ] ) NEW_LINE DEDENT if oper [ k ] == ' ^ ' : NEW_LINE INDENT T [ i ] [ j ] += ( F [ i ] [ k ] * T [ k + 1 ] [ j ] + T [ i ] [ k ] * F [ k + 1 ] [ j ] ) NEW_LINE F [ i ] [ j ] += ( T [ i ] [ k ] * T [ k + 1 ] [ j ] + F [ i ] [ k ] * F [ k + 1 ] [ j ] ) NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT return T [ 0 ] [ n - 1 ] NEW_LINE DEDENT symbols = " TTFT " NEW_LINE operators = " | & ^ " NEW_LINE n = len ( symbols ) NEW_LINE print ( countParenth ( symbols , operators , n ) ) NEW_LINE |
Boolean Parenthesization Problem | DP | CountWays function ; Base Condition ; Count number of True in left Partition ; Count number of False in left Partition ; Count number of True in right Partition ; Count number of False in right Partition ; Evaluate AND operation ; Evaluate OR operation ; Evaluate XOR operation ; Driver code ; We obtain the string T | T & F ^ T ; There are 4 ways ( ( T T ) & ( F ^ T ) ) , ( T | ( T & ( F ^ T ) ) ) , ( ( ( T T ) & F ) ^ T ) and ( T | ( ( T & F ) ^ T ) ) | def countWays ( N , S ) : NEW_LINE INDENT dp = [ [ [ - 1 for k in range ( 2 ) ] for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE return parenthesis_count ( S , 0 , N - 1 , 1 , dp ) NEW_LINE DEDENT def parenthesis_count ( Str , i , j , isTrue , dp ) : NEW_LINE INDENT if ( i > j ) : NEW_LINE return 0 NEW_LINE if ( i == j ) : NEW_LINE if ( isTrue == 1 ) : NEW_LINE INDENT return 1 if Str [ i ] == ' T ' else 0 NEW_LINE DEDENT else : NEW_LINE INDENT return 1 if Str [ i ] == ' F ' else 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] [ isTrue ] != - 1 ) : NEW_LINE return dp [ i ] [ j ] [ isTrue ] NEW_LINE temp_ans = 0 NEW_LINE for k in range ( i + 1 , j , 2 ) : NEW_LINE if ( dp [ i ] [ k - 1 ] [ 1 ] != - 1 ) : NEW_LINE INDENT leftTrue = dp [ i ] [ k - 1 ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT leftTrue = parenthesis_count ( Str , i , k - 1 , 1 , dp ) NEW_LINE DEDENT if ( dp [ i ] [ k - 1 ] [ 0 ] != - 1 ) : NEW_LINE INDENT leftFalse = dp [ i ] [ k - 1 ] [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT leftFalse = parenthesis_count ( Str , i , k - 1 , 0 , dp ) NEW_LINE DEDENT if ( dp [ k + 1 ] [ j ] [ 1 ] != - 1 ) : NEW_LINE INDENT rightTrue = dp [ k + 1 ] [ j ] [ 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT rightTrue = parenthesis_count ( Str , k + 1 , j , 1 , dp ) NEW_LINE DEDENT if ( dp [ k + 1 ] [ j ] [ 0 ] != - 1 ) : NEW_LINE INDENT rightFalse = dp [ k + 1 ] [ j ] [ 0 ] NEW_LINE DEDENT else : NEW_LINE INDENT rightFalse = parenthesis_count ( Str , k + 1 , j , 0 , dp ) NEW_LINE DEDENT if ( Str [ k ] == ' & ' ) : NEW_LINE INDENT if ( isTrue == 1 ) : NEW_LINE temp_ans = temp_ans + leftTrue * rightTrue NEW_LINE else : NEW_LINE temp_ans = temp_ans + leftTrue * rightFalse + leftFalse * rightTrue + leftFalse * rightFalse NEW_LINE DEDENT elif ( Str [ k ] == ' β ' ) : NEW_LINE INDENT if ( isTrue == 1 ) : NEW_LINE temp_ans = temp_ans + leftTrue * rightTrue + leftTrue * rightFalse + leftFalse * rightTrue NEW_LINE else : NEW_LINE temp_ans = temp_ans + leftFalse * rightFalse NEW_LINE DEDENT elif ( Str [ k ] == ' ^ ' ) : NEW_LINE INDENT if ( isTrue == 1 ) : NEW_LINE temp_ans = temp_ans + leftTrue * rightFalse + leftFalse * rightTrue NEW_LINE else : NEW_LINE temp_ans = temp_ans + leftTrue * rightTrue + leftFalse * rightFalse NEW_LINE DEDENT dp [ i ] [ j ] [ isTrue ] = temp_ans NEW_LINE return temp_ans NEW_LINE DEDENT symbols = " TTFT " NEW_LINE operators = " | & ^ " NEW_LINE S = " " NEW_LINE j = 0 NEW_LINE for i in range ( len ( symbols ) ) : NEW_LINE INDENT S = S + symbols [ i ] NEW_LINE if ( j < len ( operators ) ) : NEW_LINE INDENT S = S + operators [ j ] NEW_LINE j += 1 NEW_LINE DEDENT DEDENT N = len ( S ) NEW_LINE print ( countWays ( N , S ) ) NEW_LINE |
Mobile Numeric Keypad Problem | Return count of all possible numbers of length n in a given numeric keyboard ; left , up , right , down move from current location ; taking n + 1 for simplicity - count [ i ] [ j ] will store number count starting with digit i and length j count [ 10 ] [ n + 1 ] ; count numbers starting with digit i and of lengths 0 and 1 ; Bottom up - Get number count of length 2 , 3 , 4 , ... , n ; Loop on keypad row ; Loop on keypad column ; Process for 0 to 9 digits ; Here we are counting the numbers starting with digit keypad [ i ] [ j ] and of length k keypad [ i ] [ j ] will become 1 st digit , and we need to look for ( k - 1 ) more digits ; move left , up , right , down from current location and if new location is valid , then get number count of length ( k - 1 ) from that new digit and add in count we found so far ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver code | def getCount ( keypad , n ) : NEW_LINE INDENT if ( keypad == None or n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 10 NEW_LINE DEDENT row = [ 0 , 0 , - 1 , 0 , 1 ] NEW_LINE col = [ 0 , - 1 , 0 , 1 , 0 ] NEW_LINE count = [ [ 0 ] * ( n + 1 ) ] * 10 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE move = 0 NEW_LINE ro = 0 NEW_LINE co = 0 NEW_LINE num = 0 NEW_LINE nextNum = 0 NEW_LINE totalCount = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT count [ i ] [ 0 ] = 0 NEW_LINE count [ i ] [ 1 ] = 1 NEW_LINE DEDENT for k in range ( 2 , n + 1 ) : NEW_LINE INDENT for i in range ( 4 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT if ( keypad [ i ] [ j ] != ' * ' and keypad [ i ] [ j ] != ' # ' ) : NEW_LINE INDENT num = ord ( keypad [ i ] [ j ] ) - 48 NEW_LINE count [ num ] [ k ] = 0 NEW_LINE for move in range ( 5 ) : NEW_LINE INDENT ro = i + row [ move ] NEW_LINE co = j + col [ move ] NEW_LINE if ( ro >= 0 and ro <= 3 and co >= 0 and co <= 2 and keypad [ ro ] [ co ] != ' * ' and keypad [ ro ] [ co ] != ' # ' ) : NEW_LINE INDENT nextNum = ord ( keypad [ ro ] [ co ] ) - 48 NEW_LINE count [ num ] [ k ] += count [ nextNum ] [ k - 1 ] NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT DEDENT totalCount = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT totalCount += count [ i ] [ n ] NEW_LINE DEDENT return totalCount NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT keypad = [ [ '1' , '2' , '3' ] , [ '4' , '5' , '6' ] , [ '7' , '8' , '9' ] , [ ' * ' , '0' , ' # ' ] ] NEW_LINE print ( " Count β for β numbers β of β length " , 1 , " : " , getCount ( keypad , 1 ) ) NEW_LINE print ( " Count β for β numbers β of β length " , 2 , " : " , getCount ( keypad , 2 ) ) NEW_LINE print ( " Count β for β numbers β of β length " , 3 , " : " , getCount ( keypad , 3 ) ) NEW_LINE print ( " Count β for β numbers β of β length " , 4 , " : " , getCount ( keypad , 4 ) ) NEW_LINE print ( " Count β for β numbers β of β length " , 5 , " : " , getCount ( keypad , 5 ) ) NEW_LINE DEDENT |
Mobile Numeric Keypad Problem | Return count of all possible numbers of length n in a given numeric keyboard ; odd [ i ] , even [ i ] arrays represent count of numbers starting with digit i for any length j ; for j = 1 ; Bottom Up calculation from j = 2 to n ; Here we are explicitly writing lines for each number 0 to 9. But it can always be written as DFS on 4 X3 grid using row , column array valid moves ; Get count of all possible numbers of length " n " starting with digit 0 , 1 , 2 , ... , 9 ; Driver program to test above function | def getCount ( keypad , n ) : NEW_LINE INDENT if ( not keypad or n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 10 NEW_LINE DEDENT odd = [ 0 ] * 10 NEW_LINE even = [ 0 ] * 10 NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE useOdd = 0 NEW_LINE totalCount = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT odd [ i ] = 1 NEW_LINE DEDENT for j in range ( 2 , n + 1 ) : NEW_LINE INDENT useOdd = 1 - useOdd NEW_LINE if ( useOdd == 1 ) : NEW_LINE INDENT even [ 0 ] = odd [ 0 ] + odd [ 8 ] NEW_LINE even [ 1 ] = odd [ 1 ] + odd [ 2 ] + odd [ 4 ] NEW_LINE even [ 2 ] = odd [ 2 ] + odd [ 1 ] + odd [ 3 ] + odd [ 5 ] NEW_LINE even [ 3 ] = odd [ 3 ] + odd [ 2 ] + odd [ 6 ] NEW_LINE even [ 4 ] = odd [ 4 ] + odd [ 1 ] + odd [ 5 ] + odd [ 7 ] NEW_LINE even [ 5 ] = odd [ 5 ] + odd [ 2 ] + odd [ 4 ] + odd [ 8 ] + odd [ 6 ] NEW_LINE even [ 6 ] = odd [ 6 ] + odd [ 3 ] + odd [ 5 ] + odd [ 9 ] NEW_LINE even [ 7 ] = odd [ 7 ] + odd [ 4 ] + odd [ 8 ] NEW_LINE even [ 8 ] = odd [ 8 ] + odd [ 0 ] + odd [ 5 ] + odd [ 7 ] + odd [ 9 ] NEW_LINE even [ 9 ] = odd [ 9 ] + odd [ 6 ] + odd [ 8 ] NEW_LINE DEDENT else : NEW_LINE INDENT odd [ 0 ] = even [ 0 ] + even [ 8 ] NEW_LINE odd [ 1 ] = even [ 1 ] + even [ 2 ] + even [ 4 ] NEW_LINE odd [ 2 ] = even [ 2 ] + even [ 1 ] + even [ 3 ] + even [ 5 ] NEW_LINE odd [ 3 ] = even [ 3 ] + even [ 2 ] + even [ 6 ] NEW_LINE odd [ 4 ] = even [ 4 ] + even [ 1 ] + even [ 5 ] + even [ 7 ] NEW_LINE odd [ 5 ] = even [ 5 ] + even [ 2 ] + even [ 4 ] + even [ 8 ] + even [ 6 ] NEW_LINE odd [ 6 ] = even [ 6 ] + even [ 3 ] + even [ 5 ] + even [ 9 ] NEW_LINE odd [ 7 ] = even [ 7 ] + even [ 4 ] + even [ 8 ] NEW_LINE odd [ 8 ] = even [ 8 ] + even [ 0 ] + even [ 5 ] + even [ 7 ] + even [ 9 ] NEW_LINE odd [ 9 ] = even [ 9 ] + even [ 6 ] + even [ 8 ] NEW_LINE DEDENT DEDENT totalCount = 0 NEW_LINE if ( useOdd == 1 ) : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT totalCount += even [ i ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( 10 ) : NEW_LINE INDENT totalCount += odd [ i ] NEW_LINE DEDENT DEDENT return totalCount NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT keypad = [ [ '1' , '2' , '3' ] , [ '4' , '5' , '6' ] , [ '7' , '8' , '9' ] , [ ' * ' , '0' , ' # ' ] ] NEW_LINE print ( " Count β for β numbers β of β length β " , 1 , " : β " , getCount ( keypad , 1 ) ) NEW_LINE print ( " Count β for β numbers β of β length β " , 2 , " : β " , getCount ( keypad , 2 ) ) NEW_LINE print ( " Count β for β numbers β of β length β " , 3 , " : β " , getCount ( keypad , 3 ) ) NEW_LINE print ( " Count β for β numbers β of β length β " , 4 , " : β " , getCount ( keypad , 4 ) ) NEW_LINE print ( " Count β for β numbers β of β length β " , 5 , " : β " , getCount ( keypad , 5 ) ) NEW_LINE DEDENT |
Count of n digit numbers whose sum of digits equals to given sum | Recursive function to count ' n ' digit numbers with sum of digits as ' sum ' This function considers leading 0 's also as digits, that is why not directly called ; Base case ; Initialize answer ; Traverse through every digit and count numbers beginning with it using recursion ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize final answer ; Traverse through every digit from 1 to 9 and count numbers beginning with it ; Driver program | def countRec ( n , sum ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return ( sum == 0 ) NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 0 , 10 ) : NEW_LINE INDENT if ( sum - i >= 0 ) : NEW_LINE INDENT ans = ans + countRec ( n - 1 , sum - i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def finalCount ( n , sum ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( sum - i >= 0 ) : NEW_LINE INDENT ans = ans + countRec ( n - 1 , sum - i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n = 2 NEW_LINE sum = 5 NEW_LINE print ( finalCount ( n , sum ) ) NEW_LINE |
Count of n digit numbers whose sum of digits equals to given sum | A lookup table used for memoization ; Memoization based implementation of recursive function ; Base case ; If this subproblem is already evaluated , return the evaluated value ; Initialize answer ; Traverse through every digit and recursively count numbers beginning with it ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining n . ; Initialize final answer ; Traverse through every digit from 1 to 9 and count numbers beginning with it ; Driver Code | lookup = [ [ - 1 for i in range ( 501 ) ] for i in range ( 101 ) ] NEW_LINE def countRec ( n , Sum ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return Sum == 0 NEW_LINE DEDENT if ( lookup [ n ] [ Sum ] != - 1 ) : NEW_LINE INDENT return lookup [ n ] [ Sum ] NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT if ( Sum - i >= 0 ) : NEW_LINE INDENT ans += countRec ( n - 1 , Sum - i ) NEW_LINE DEDENT DEDENT lookup [ n ] [ Sum ] = ans NEW_LINE return lookup [ n ] [ Sum ] NEW_LINE DEDENT def finalCount ( n , Sum ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT if ( Sum - i >= 0 ) : NEW_LINE INDENT ans += countRec ( n - 1 , Sum - i ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT n , Sum = 3 , 5 NEW_LINE print ( finalCount ( n , Sum ) ) NEW_LINE |
Count of n digit numbers whose sum of digits equals to given sum | Python3 program to Count of n digit numbers whose sum of digits equals to given sum ; in case n = 2 start is 10 and end is ( 100 - 1 ) = 99 ; Driver Code | import math NEW_LINE def findCount ( n , sum ) : NEW_LINE INDENT start = math . pow ( 10 , n - 1 ) ; NEW_LINE end = math . pow ( 10 , n ) - 1 ; NEW_LINE count = 0 ; NEW_LINE i = start ; NEW_LINE while ( i <= end ) : NEW_LINE INDENT cur = 0 ; NEW_LINE temp = i ; NEW_LINE while ( temp != 0 ) : NEW_LINE INDENT cur += temp % 10 ; NEW_LINE temp = temp // 10 ; NEW_LINE DEDENT if ( cur == sum ) : NEW_LINE INDENT count = count + 1 ; NEW_LINE i += 9 ; NEW_LINE DEDENT else : NEW_LINE INDENT i = i + 1 ; NEW_LINE DEDENT DEDENT print ( count ) ; NEW_LINE DEDENT n = 3 ; NEW_LINE sum = 5 ; NEW_LINE findCount ( n , sum ) ; NEW_LINE |
Total number of non | Python3 program to count non - decreasing number with n digits ; dp [ i ] [ j ] contains total count of non decreasing numbers ending with digit i and of length j ; Fill table for non decreasing numbers of length 1. Base cases 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ; Fill the table in bottom - up manner ; Compute total numbers of non decreasing numbers of length 'len ; sum of all numbers of length of len - 1 in which last digit x is <= 'digit ; There total nondecreasing numbers of length n won 't be dp[0][n] + dp[1][n] ..+ dp[9][n] ; Driver Code | def countNonDecreasing ( n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n + 1 ) ] for i in range ( 10 ) ] NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT dp [ i ] [ 1 ] = 1 NEW_LINE DEDENT for digit in range ( 10 ) : NEW_LINE INDENT for len in range ( 2 , n + 1 ) : NEW_LINE INDENT for x in range ( digit + 1 ) : NEW_LINE INDENT dp [ digit ] [ len ] += dp [ x ] [ len - 1 ] NEW_LINE DEDENT DEDENT DEDENT count = 0 NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT count += dp [ i ] [ n ] NEW_LINE DEDENT return count NEW_LINE DEDENT n = 3 NEW_LINE print ( countNonDecreasing ( n ) ) NEW_LINE |
Total number of non | python program to count non - decreasing numner with n digits ; Compute value of N * ( N + 1 ) / 2 * ( N + 2 ) / 3 * ... . * ( N + n - 1 ) / n ; Driver program | def countNonDecreasing ( n ) : NEW_LINE INDENT N = 10 NEW_LINE count = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT count = int ( count * ( N + i - 1 ) ) NEW_LINE count = int ( count / i ) NEW_LINE DEDENT return count NEW_LINE DEDENT n = 3 ; NEW_LINE print ( countNonDecreasing ( n ) ) NEW_LINE |
Minimum number of squares whose sum equals to given number n | Returns count of minimum squares that sum to n ; base cases ; getMinSquares rest of the table using recursive formula Maximum squares required is n ( 1 * 1 + 1 * 1 + . . ) ; Go through all smaller numbers to recursively find minimum ; Driver code | def getMinSquares ( n ) : NEW_LINE INDENT if n <= 3 : NEW_LINE INDENT return n ; NEW_LINE DEDENT res = n NEW_LINE for x in range ( 1 , n + 1 ) : NEW_LINE INDENT temp = x * x ; NEW_LINE if temp > n : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT res = min ( res , 1 + getMinSquares ( n - temp ) ) NEW_LINE DEDENT DEDENT return res ; NEW_LINE DEDENT print ( getMinSquares ( 6 ) ) NEW_LINE |
Minimum number of squares whose sum equals to given number n | A dynamic programming based Python program to find minimum number of squares whose sum is equal to a given number ; Returns count of minimum squares that sum to n ; getMinSquares table for base case entries ; getMinSquares rest of the table using recursive formula ; max value is i as i can always be represented as 1 * 1 + 1 * 1 + ... ; Go through all smaller numbers to recursively find minimum ; Store result ; Driver code | from math import ceil , sqrt NEW_LINE def getMinSquares ( n ) : NEW_LINE INDENT dp = [ 0 , 1 , 2 , 3 ] NEW_LINE for i in range ( 4 , n + 1 ) : NEW_LINE INDENT dp . append ( i ) NEW_LINE for x in range ( 1 , int ( ceil ( sqrt ( i ) ) ) + 1 ) : NEW_LINE INDENT temp = x * x ; NEW_LINE if temp > i : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( dp [ i ] , 1 + dp [ i - temp ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT print ( getMinSquares ( 6 ) ) NEW_LINE |
Minimum number of squares whose sum equals to given number n | Python3 program for the above approach ; Function to count minimum squares that sum to n ; Creating visited vector of size n + 1 ; Queue of pair to store node and number of steps ; Initially ans variable is initialized with inf ; Push starting node with 0 0 indicate current number of step to reach n ; Mark starting node visited ; If node reaches its destination 0 update it with answer ; Loop for all possible path from 1 to i * i <= current node ( p . first ) ; If we are standing at some node then next node it can jump to will be current node - ( some square less than or equal n ) ; Check if it is valid and not visited yet ; Mark visited ; Push it it Queue ; Return ans to calling function ; Driver code | import sys NEW_LINE def numSquares ( n ) : NEW_LINE INDENT visited = [ 0 ] * ( n + 1 ) NEW_LINE q = [ ] NEW_LINE ans = sys . maxsize NEW_LINE q . append ( [ n , 0 ] ) NEW_LINE visited [ n ] = 1 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . pop ( 0 ) NEW_LINE if ( p [ 0 ] == 0 ) : NEW_LINE INDENT ans = min ( ans , p [ 1 ] ) NEW_LINE DEDENT i = 1 NEW_LINE while i * i <= p [ 0 ] : NEW_LINE INDENT path = p [ 0 ] - i * i NEW_LINE if path >= 0 and ( visited [ path ] == 0 or path == 0 ) : NEW_LINE INDENT visited [ path ] = 1 NEW_LINE q . append ( [ path , p [ 1 ] + 1 ] ) NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT print ( numSquares ( 12 ) ) NEW_LINE |
Find minimum number of coins that make a given value | A Naive recursive python program to find minimum of coins to make a given change V ; m is size of coins array ( number of different coins ) ; base case ; Initialize result ; Try every coin that has smaller value than V ; Check for INT_MAX to avoid overflow and see if result can minimized ; Driver program to test above function | import sys NEW_LINE def minCoins ( coins , m , V ) : NEW_LINE INDENT if ( V == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = sys . maxsize NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT if ( coins [ i ] <= V ) : NEW_LINE INDENT sub_res = minCoins ( coins , m , V - coins [ i ] ) NEW_LINE if ( sub_res != sys . maxsize and sub_res + 1 < res ) : NEW_LINE INDENT res = sub_res + 1 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT coins = [ 9 , 6 , 5 , 1 ] NEW_LINE m = len ( coins ) NEW_LINE V = 11 NEW_LINE print ( " Minimum β coins β required β is " , minCoins ( coins , m , V ) ) NEW_LINE |
Find minimum number of coins that make a given value | A Dynamic Programming based Python3 program to find minimum of coins to make a given change V ; m is size of coins array ( number ofdifferent coins ) ; table [ i ] will be storing the minimum number of coins required for i value . So table [ V ] will have result ; Base case ( If given value V is 0 ) ; Initialize all table values as Infinite ; Compute minimum coins required for all values from 1 to V ; Go through all coins smaller than i ; Driver Code | import sys NEW_LINE def minCoins ( coins , m , V ) : NEW_LINE INDENT table = [ 0 for i in range ( V + 1 ) ] NEW_LINE table [ 0 ] = 0 NEW_LINE for i in range ( 1 , V + 1 ) : NEW_LINE INDENT table [ i ] = sys . maxsize NEW_LINE DEDENT for i in range ( 1 , V + 1 ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( coins [ j ] <= i ) : NEW_LINE INDENT sub_res = table [ i - coins [ j ] ] NEW_LINE if ( sub_res != sys . maxsize and sub_res + 1 < table [ i ] ) : NEW_LINE INDENT table [ i ] = sub_res + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT if table [ V ] == sys . maxsize : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return table [ V ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT coins = [ 9 , 6 , 5 , 1 ] NEW_LINE m = len ( coins ) NEW_LINE V = 11 NEW_LINE print ( " Minimum β coins β required β is β " , minCoins ( coins , m , V ) ) NEW_LINE DEDENT |
Shortest Common Supersequence | A Naive recursive python program to find length of the shortest supersequence ; Driver Code | def superSeq ( X , Y , m , n ) : NEW_LINE INDENT if ( not m ) : NEW_LINE INDENT return n NEW_LINE DEDENT if ( not n ) : NEW_LINE INDENT return m NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] ) : NEW_LINE INDENT return 1 + superSeq ( X , Y , m - 1 , n - 1 ) NEW_LINE DEDENT return 1 + min ( superSeq ( X , Y , m - 1 , n ) , superSeq ( X , Y , m , n - 1 ) ) NEW_LINE DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE print ( " Length β of β the β shortest β supersequence β is β % d " % superSeq ( X , Y , len ( X ) , len ( Y ) ) ) NEW_LINE |
Shortest Common Supersequence | Returns length of the shortest supersequence of X and Y ; Fill table in bottom up manner ; Below steps follow above recurrence ; Driver Code | def superSeq ( X , Y , m , n ) : NEW_LINE INDENT dp = [ [ 0 ] * ( n + 2 ) for i in range ( m + 2 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( not i ) : NEW_LINE INDENT dp [ i ] [ j ] = j NEW_LINE DEDENT elif ( not j ) : NEW_LINE INDENT dp [ i ] [ j ] = i NEW_LINE DEDENT elif ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE print ( " Length β of β the β shortest β supersequence β is β % d " % superSeq ( X , Y , len ( X ) , len ( Y ) ) ) NEW_LINE |
Compute sum of digits in all numbers from 1 to n | Returns sum of all digits in numbers from 1 to n ; initialize result ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program | def sumOfDigitsFrom1ToN ( n ) : NEW_LINE INDENT result = 0 NEW_LINE for x in range ( 1 , n + 1 ) : NEW_LINE INDENT result = result + sumOfDigits ( x ) NEW_LINE DEDENT return result NEW_LINE DEDENT def sumOfDigits ( x ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( x != 0 ) : NEW_LINE INDENT sum = sum + x % 10 NEW_LINE x = x // 10 NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 328 NEW_LINE print ( " Sum β of β digits β in β numbers β from β 1 β to " , n , " is " , sumOfDigitsFrom1ToN ( n ) ) NEW_LINE |
Compute sum of digits in all numbers from 1 to n | PYTHON 3 program to compute sum of digits in numbers from 1 to n ; Function to computer sum of digits in numbers from 1 to n . Comments use example of 328 to explain the code ; base case : if n < 10 return sum of first n natural numbers ; d = number of digits minus one in n . For 328 , d is 2 ; computing sum of digits from 1 to 10 ^ d - 1 , d = 1 a [ 0 ] = 0 ; d = 2 a [ 1 ] = sum of digit from 1 to 9 = 45 d = 3 a [ 2 ] = sum of digit from 1 to 99 = a [ 1 ] * 10 + 45 * 10 ^ 1 = 900 d = 4 a [ 3 ] = sum of digit from 1 to 999 = a [ 2 ] * 10 + 45 * 10 ^ 2 = 13500 ; computing 10 ^ d ; Most significant digit ( msd ) of n , For 328 , msd is 3 which can be obtained using 328 / 100 ; EXPLANATION FOR FIRST and SECOND TERMS IN BELOW LINE OF CODE First two terms compute sum of digits from 1 to 299 ( sum of digits in range 1 - 99 stored in a [ d ] ) + ( sum of digits in range 100 - 199 , can be calculated as 1 * 100 + a [ d ] . ( sum of digits in range 200 - 299 , can be calculated as 2 * 100 + a [ d ] The above sum can be written as 3 * a [ d ] + ( 1 + 2 ) * 100 EXPLANATION FOR THIRD AND FOURTH TERMS IN BELOW LINE OF CODE The last two terms compute sum of digits in number from 300 to 328. The third term adds 3 * 29 to sum as digit 3 occurs in all numbers from 300 to 328. The fourth term recursively calls for 28 ; Driver Program | import math NEW_LINE def sumOfDigitsFrom1ToN ( n ) : NEW_LINE INDENT if ( n < 10 ) : NEW_LINE INDENT return ( n * ( n + 1 ) / 2 ) NEW_LINE DEDENT d = ( int ) ( math . log10 ( n ) ) NEW_LINE a = [ 0 ] * ( d + 1 ) NEW_LINE a [ 0 ] = 0 NEW_LINE a [ 1 ] = 45 NEW_LINE for i in range ( 2 , d + 1 ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] * 10 + 45 * ( int ) ( math . ceil ( math . pow ( 10 , i - 1 ) ) ) NEW_LINE DEDENT p = ( int ) ( math . ceil ( math . pow ( 10 , d ) ) ) NEW_LINE msd = n // p NEW_LINE return ( int ) ( msd * a [ d ] + ( msd * ( msd - 1 ) // 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToN ( n % p ) ) NEW_LINE DEDENT n = 328 NEW_LINE print ( " Sum β of β digits β in β numbers β from β 1 β to " , n , " is " , sumOfDigitsFrom1ToN ( n ) ) NEW_LINE |
Compute sum of digits in all numbers from 1 to n | Python program to compute sum of digits in numbers from 1 to n ; Function to computer sum of digits in numbers from 1 to n ; Driver code | import math NEW_LINE def sumOfDigitsFrom1ToNUtil ( n , a ) : NEW_LINE INDENT if ( n < 10 ) : NEW_LINE INDENT return ( n * ( n + 1 ) ) // 2 NEW_LINE DEDENT d = int ( math . log ( n , 10 ) ) NEW_LINE p = int ( math . ceil ( pow ( 10 , d ) ) ) NEW_LINE msd = n // p NEW_LINE return ( msd * a [ d ] + ( msd * ( msd - 1 ) // 2 ) * p + msd * ( 1 + n % p ) + sumOfDigitsFrom1ToNUtil ( n % p , a ) ) NEW_LINE DEDENT def sumOfDigitsFrom1ToN ( n ) : NEW_LINE INDENT d = int ( math . log ( n , 10 ) ) NEW_LINE a = [ 0 ] * ( d + 1 ) NEW_LINE a [ 0 ] = 0 NEW_LINE a [ 1 ] = 45 NEW_LINE for i in range ( 2 , d + 1 ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] * 10 + 45 * int ( math . ceil ( pow ( 10 , i - 1 ) ) ) NEW_LINE DEDENT return sumOfDigitsFrom1ToNUtil ( n , a ) NEW_LINE DEDENT n = 328 NEW_LINE print ( " Sum β of β digits β in β numbers β from β 1 β to " , n , " is " , sumOfDigitsFrom1ToN ( n ) ) NEW_LINE |
Count possible ways to construct buildings | Returns count of possible ways for N sections ; Base case ; 2 for one side and 4 for two sides ; countB is count of ways with a building at the end countS is count of ways with a space at the end prev_countB and prev_countS are previous values of countB and countS respectively . Initialize countB and countS for one side ; Use the above recursive formula for calculating countB and countS using previous values ; Result for one side is sum of ways ending with building and ending with space ; Result for 2 sides is square of result for one side ; Driver program | def countWays ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 4 NEW_LINE DEDENT countB = 1 NEW_LINE countS = 1 NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT prev_countB = countB NEW_LINE prev_countS = countS NEW_LINE countS = prev_countB + prev_countS NEW_LINE countB = prev_countS NEW_LINE DEDENT result = countS + countB NEW_LINE return ( result * result ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE print ( " Count β of β ways β for β " , N , " β sections β is β " , countWays ( N ) ) NEW_LINE DEDENT |
Count number of ways to reach a given score in a game | Returns number of ways to reach score n . ; table [ i ] will store count of solutions for value i . Initialize all table values as 0. ; Base case ( If given value is 0 ) ; One by one consider given 3 moves and update the table [ ] values after the index greater than or equal to the value of the picked move . ; Driver Program | def count ( n ) : NEW_LINE INDENT table = [ 0 for i in range ( n + 1 ) ] NEW_LINE table [ 0 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT table [ i ] += table [ i - 3 ] NEW_LINE DEDENT for i in range ( 5 , n + 1 ) : NEW_LINE INDENT table [ i ] += table [ i - 5 ] NEW_LINE DEDENT for i in range ( 10 , n + 1 ) : NEW_LINE INDENT table [ i ] += table [ i - 10 ] NEW_LINE DEDENT return table [ n ] NEW_LINE DEDENT n = 20 NEW_LINE print ( ' Count β for ' , n , ' is ' , count ( n ) ) NEW_LINE n = 13 NEW_LINE print ( ' Count β for ' , n , ' is ' , count ( n ) ) NEW_LINE |
Naive algorithm for Pattern Searching | Python3 program for Naive Pattern Searching algorithm ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver Code | def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE for i in range ( N - M + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while ( j < M ) : NEW_LINE INDENT if ( txt [ i + j ] != pat [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == M ) : NEW_LINE INDENT print ( " Pattern β found β at β index β " , i ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT txt = " AABAACAADAABAAABAA " NEW_LINE pat = " AABA " NEW_LINE search ( pat , txt ) NEW_LINE DEDENT |
Rabin | d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern ; hash value for txt ; The value of h would be " pow ( d , β M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern if the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative values of t , converting it to positive ; Driver Code ; A prime number ; Function Call | d = 256 NEW_LINE def search ( pat , txt , q ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE p = 0 NEW_LINE t = 0 NEW_LINE h = 1 NEW_LINE for i in xrange ( M - 1 ) : NEW_LINE INDENT h = ( h * d ) % q NEW_LINE DEDENT for i in xrange ( M ) : NEW_LINE INDENT p = ( d * p + ord ( pat [ i ] ) ) % q NEW_LINE t = ( d * t + ord ( txt [ i ] ) ) % q NEW_LINE DEDENT for i in xrange ( N - M + 1 ) : NEW_LINE INDENT if p == t : NEW_LINE INDENT for j in xrange ( M ) : NEW_LINE INDENT if txt [ i + j ] != pat [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT else : j += 1 NEW_LINE DEDENT if j == M : NEW_LINE INDENT print " Pattern β found β at β index β " + str ( i ) NEW_LINE DEDENT DEDENT if i < N - M : NEW_LINE INDENT t = ( d * ( t - ord ( txt [ i ] ) * h ) + ord ( txt [ i + M ] ) ) % q NEW_LINE if t < 0 : NEW_LINE INDENT t = t + q NEW_LINE DEDENT DEDENT DEDENT DEDENT txt = " GEEKS β FOR β GEEKS " NEW_LINE pat = " GEEK " NEW_LINE q = 101 NEW_LINE search ( pat , txt , q ) NEW_LINE |
Optimized Naive Algorithm for Pattern Searching | Python program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver program to test the above function | def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE i = 0 NEW_LINE while i <= N - M : NEW_LINE INDENT for j in xrange ( M ) : NEW_LINE INDENT if txt [ i + j ] != pat [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == M : NEW_LINE INDENT print " Pattern β found β at β index β " + str ( i ) NEW_LINE i = i + M NEW_LINE DEDENT elif j == 0 : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = i + j NEW_LINE DEDENT DEDENT DEDENT txt = " ABCEABCDABCEABCD " NEW_LINE pat = " ABCD " NEW_LINE search ( pat , txt ) NEW_LINE |
Finite Automata algorithm for Pattern Searching | Python program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; ns stores the result which is next state ns finally contains the longest prefix which is also suffix in " pat [ 0 . . state - 1 ] c " Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function | NO_OF_CHARS = 256 NEW_LINE def getNextState ( pat , M , state , x ) : NEW_LINE INDENT if state < M and x == ord ( pat [ state ] ) : NEW_LINE INDENT return state + 1 NEW_LINE DEDENT i = 0 NEW_LINE for ns in range ( state , 0 , - 1 ) : NEW_LINE INDENT if ord ( pat [ ns - 1 ] ) == x : NEW_LINE INDENT while ( i < ns - 1 ) : NEW_LINE INDENT if pat [ i ] != pat [ state - ns + 1 + i ] : NEW_LINE INDENT break NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if i == ns - 1 : NEW_LINE INDENT return ns NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT def computeTF ( pat , M ) : NEW_LINE INDENT global NO_OF_CHARS NEW_LINE TF = [ [ 0 for i in range ( NO_OF_CHARS ) ] \ for _ in range ( M + 1 ) ] NEW_LINE for state in range ( M + 1 ) : NEW_LINE INDENT for x in range ( NO_OF_CHARS ) : NEW_LINE INDENT z = getNextState ( pat , M , state , x ) NEW_LINE TF [ state ] [ x ] = z NEW_LINE DEDENT DEDENT return TF NEW_LINE DEDENT def search ( pat , txt ) : NEW_LINE INDENT global NO_OF_CHARS NEW_LINE M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE TF = computeTF ( pat , M ) NEW_LINE state = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT state = TF [ state ] [ ord ( txt [ i ] ) ] NEW_LINE if state == M : NEW_LINE INDENT print ( " Pattern β found β at β index : β { } " . format ( i - M + 1 ) ) NEW_LINE DEDENT DEDENT DEDENT def main ( ) : NEW_LINE INDENT txt = " AABAACAADAABAAABAA " NEW_LINE pat = " AABA " NEW_LINE search ( pat , txt ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Subsets and Splits