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... | 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 , prev... |
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 ... | 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 ) == Fal... |
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 tha... | 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 ] == ... |
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... | 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_L... |
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... | 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 ( ( m... |
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 ... | 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 INDEN... |
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 . appen... |
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 ... | 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 ( ro... |
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 th... | 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 . dat... |
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... |
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 ele... | 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 ] > ar... |
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 ... |
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 cou... |
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... | 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... |
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 ... | 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_LIN... |
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... |
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_L... |
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_s... | 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 prin... |
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 F... | 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 . so... |
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 tes... | 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 ] , " ,... |
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 t... | 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 ] , ' , β ' , ... |
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 progr... | 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 [... |
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 = l... |
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 [ ]... | 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 DED... |
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 co... | 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... |
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 al... | 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 ]... |
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 arra... | 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... |
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... | 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 N... |
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... |
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 . ; d... | 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 ] ,... |
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 binaryS... |
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 -... |
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 t... | 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 [ ... |
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 r... | 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... |
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 , ot... | 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 ) ... |
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 a... | 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 ... |
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 c... | 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 = getNe... |
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 duplicat... | 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 i... |
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 -... | 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 [ hi... |
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 em... | 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_L... |
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 o... | 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 ... |
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 ca... | 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 IN... |
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 ... | 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 [... |
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 an... | 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 ]... |
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... |
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_L... |
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 alway... | 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 ... |
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 ... | 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... |
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 ] m... | 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 INDEN... |
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 ... | 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 ... |
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 =... |
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 ] cont... | 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 ]... |
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 ev... | 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... |
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 ... | 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... |
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... |
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 colum... | 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 (... |
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 ,... |
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 ) , kna... |
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 IND... |
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 retu... | 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 ... |
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 ... | 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 eggFlo... |
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 an... | 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 ] =... |
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 value... | 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 ... |
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 ] ==... | 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 DE... |
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 ... |
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 (... |
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... | 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 )... |
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 ( m... | 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_LI... |
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 getN... |
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 ... | 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... |
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 [... | 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 ) ]... |
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 ] ; Initializ... | 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 DEDE... |
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 s... | 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 ... |
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 includin... | 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 ) : NE... |
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 ... | 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 ... |
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 ; ... | 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_LI... |
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 ... | 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 = ... |
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... | 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 ( 1... |
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... | 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 D... |
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 numb... | 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 ) :... |
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... |
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 m... | 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... |
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 ... |
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 ... | 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 N... |
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... | 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 ... |
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 ... | 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 ... |
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 ; ... | 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 i... |
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... |
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_LI... |
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 =... |
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... | 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 ] =... |
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 ) // ... |
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 respective... | 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 DEDE... |
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 th... | 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 +... |
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 pr... |
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... | 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 +... |
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... | 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 ... |
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 . .... | 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 ) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.