text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Union and Intersection of two sorted arrays | Function prints Intersection of arr1 [ ] and arr2 [ ] m is the number of elements in arr1 [ ] n is the number of elements in arr2 [ ] ; Driver program to test above function ; Function calling | def printIntersection ( arr1 , arr2 , m , n ) : NEW_LINE INDENT i , j = 0 , 0 NEW_LINE while i < m and j < n : NEW_LINE INDENT if arr1 [ i ] < arr2 [ j ] : NEW_LINE INDENT i += 1 NEW_LINE DEDENT elif arr2 [ j ] < arr1 [ i ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr2 [ j ] ) NEW_LINE j ... |
Count numbers less than N containing digits from the given set : Digit DP | Python3 implementation to find the count of numbers possible less than N , such that every digit is from the given set of digits ; Function to convert integer into the string ; Recursive function to find the count of numbers possible less than ... | import numpy as np ; NEW_LINE dp = np . ones ( ( 15 , 2 ) ) * - 1 ; NEW_LINE def convertToString ( num ) : NEW_LINE INDENT return str ( num ) ; NEW_LINE DEDENT def calculate ( pos , tight , D , sz , num ) : NEW_LINE INDENT if ( pos == len ( num ) ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( dp [ pos ] [ tight ] ... |
Maximum sum of elements divisible by K from the given array | Python3 implementation ; Function to return the maximum sum divisible by k from elements of v ; check if sum of elements excluding the current one is divisible by k ; check if sum of elements including the current one is divisible by k ; Store the maximum ; ... | dp = [ [ - 1 for i in range ( 1001 ) ] for j in range ( 1001 ) ] NEW_LINE def find_max ( i , sum , v , k ) : NEW_LINE INDENT if ( i == len ( v ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ sum ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ sum ] NEW_LINE DEDENT ans = 0 NEW_LINE if ( ( sum + find_max ( ... |
Find Union and Intersection of two unsorted arrays | Prints union of arr1 [ 0. . m - 1 ] and arr2 [ 0. . n - 1 ] ; Before finding union , make sure arr1 [ 0. . m - 1 ] is smaller ; Now arr1 [ ] is smaller Sort the first array and print its elements ( these two steps can be swapped as order in output is not important ) ... | def printUnion ( arr1 , arr2 , m , n ) : NEW_LINE INDENT if ( m > n ) : NEW_LINE INDENT tempp = arr1 NEW_LINE arr1 = arr2 NEW_LINE arr2 = tempp NEW_LINE temp = m NEW_LINE m = n NEW_LINE n = temp NEW_LINE DEDENT arr1 . sort ( ) NEW_LINE for i in range ( 0 , m ) : NEW_LINE INDENT print ( arr1 [ i ] , end = " β " ) NEW_LI... |
Find the maximum sum leaf to root path in a Binary Tree | A tree node structure ; A utility function that prints all nodes on the path from root to target_leaf ; base case ; return True if this node is the target_leaf or target leaf is present in one of its descendants ; This function Sets the target_leaf_ref to refer ... | class node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def printPath ( root , target_leaf ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( root == target_leaf or print... |
Find Union and Intersection of two unsorted arrays | Function to find intersection ; when both are equal ; Driver Code ; sort ; function call | def intersection ( a , b , n , m ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE while ( i < n and j < m ) : NEW_LINE INDENT if ( a [ i ] > b [ j ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( b [ j ] > a [ i ] ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( a [ i ]... |
Count of 1 's in any path in a Binary Tree | A binary tree node ; A utility function to allocate a new node ; This function updates overall count of 1 in ' res ' And returns count 1 s going through root . ; Base Case ; l and r store count of 1 s going through left and right child of root respectively ; maxCount represe... | class Node : NEW_LINE INDENT def __init__ ( self ) : NEW_LINE INDENT self . data = 0 NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT newNode = Node ( ) NEW_LINE newNode . data = data NEW_LINE newNode . left = newNode . right = None NEW_LINE return (... |
Find Union and Intersection of two unsorted arrays | Prints union of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Prints intersection of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Driver Program ; Function call | def printUnion ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT hs = set ( ) NEW_LINE for i in range ( 0 , n1 ) : NEW_LINE INDENT hs . add ( arr1 [ i ] ) NEW_LINE DEDENT for i in range ( 0 , n2 ) : NEW_LINE INDENT hs . add ( arr2 [ i ] ) NEW_LINE DEDENT print ( " Union : " ) NEW_LINE for i in hs : NEW_LINE INDENT print ( i ... |
Find Union and Intersection of two unsorted arrays | Prints intersection of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; Iterate first array ; Iterate second array ; Prints union of arr1 [ 0. . n1 - 1 ] and arr2 [ 0. . n2 - 1 ] ; placeZeroes function ; Function to itreate array ; placeValue function ; Hashing collis... | def findPosition ( a , b ) : NEW_LINE INDENT v = len ( a ) + len ( b ) ; NEW_LINE ans = [ 0 ] * v ; NEW_LINE zero1 = zero2 = 0 ; NEW_LINE print ( " Intersection β : " , end = " β " ) ; NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT zero1 = iterateArray ( a , v , ans , i ) ; NEW_LINE DEDENT for j in range ( len... |
Minimum number of coins that can generate all the values in the given range | Function to return the count of minimum coins required ; To store the required sequence ; Creating list of the sum of all previous bit values including that bit value ; Driver code | def findCount ( N ) : NEW_LINE INDENT list = [ ] NEW_LINE sum = 0 NEW_LINE for i in range ( 0 , 20 ) : NEW_LINE INDENT sum += 2 ** i NEW_LINE list . append ( sum ) NEW_LINE DEDENT for value in list : NEW_LINE INDENT if ( value >= N ) : NEW_LINE INDENT return ( list . index ( value ) + 1 ) NEW_LINE DEDENT DEDENT DEDENT ... |
Sort an array of 0 s , 1 s and 2 s | Function to sort array ; Function to print array ; Driver Program | def sort012 ( a , arr_size ) : NEW_LINE INDENT lo = 0 NEW_LINE hi = arr_size - 1 NEW_LINE mid = 0 NEW_LINE while mid <= hi : NEW_LINE INDENT if a [ mid ] == 0 : NEW_LINE INDENT a [ lo ] , a [ mid ] = a [ mid ] , a [ lo ] NEW_LINE lo = lo + 1 NEW_LINE mid = mid + 1 NEW_LINE DEDENT elif a [ mid ] == 1 : NEW_LINE INDENT m... |
Calculate the number of set bits for every number from 0 to N | Function to find the count of set bits in all the integers from 0 to n ; dp [ i ] will store the count of set bits in i Initialise the dp array ; Count of set bits in 0 is 0 ; For every number starting from 1 ; If current number is even ; Count of set bits... | def findSetBits ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) ; NEW_LINE print ( dp [ 0 ] , end = " β " ) ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i % 2 == 0 ) : NEW_LINE INDENT dp [ i ] = dp [ i // 2 ] ; NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i // 2 ] + 1 ; NEW_LINE DEDENT print ... |
Sort an array of 0 s , 1 s and 2 s | Utility function to print contents of an array ; Function to sort the array of 0 s , 1 s and 2 s ; Count the number of 0 s , 1 s and 2 s in the array ; Update the array ; Store all the 0 s in the beginning ; Then all the 1 s ; Finally all the 2 s ; Prthe sorted array ; Driver code | def printArr ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT def sortArr ( arr , n ) : NEW_LINE INDENT cnt0 = 0 NEW_LINE cnt1 = 0 NEW_LINE cnt2 = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if arr [ i ] == 0 : NEW_LINE INDENT cnt0 += 1 ... |
Find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted | Python3 program to find the Minimum length Unsorted Subarray , sorting which makes the complete array sorted ; step 1 ( a ) of above algo ; step 1 ( b ) of above algo ; step 2 ( a ) of above algo ; step 2 ( b ) of above algo ; s... | def printUnsorted ( arr , n ) : NEW_LINE INDENT e = n - 1 NEW_LINE for s in range ( 0 , n - 1 ) : NEW_LINE INDENT if arr [ s ] > arr [ s + 1 ] : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if s == n - 1 : NEW_LINE INDENT print ( " The β complete β array β is β sorted " ) NEW_LINE exit ( ) NEW_LINE DEDENT e = n - 1 NEW... |
Count the number of possible triangles | Function to count all possible triangles with arr [ ] elements ; Count of triangles ; The three loops select three different values from array ; The innermost loop checks for the triangle property ; Sum of two sides is greater than the third ; Driver code | def findNumberOfTriangles ( arr , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT for k in range ( j + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] + arr [ j ] > arr [ k ] and arr [ i ] + arr [ k ] > arr [ j ] and arr [ k ] + arr [ j ] > arr [ i... |
Count the number of possible triangles | Function to count all possible triangles with arr [ ] elements ; Sort array and initialize count as 0 ; Initialize count of triangles ; Fix the first element . We need to run till n - 3 as the other two elements are selected from arr [ i + 1. . . n - 1 ] ; Initialize index of th... | def findnumberofTriangles ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE arr . sort ( ) NEW_LINE count = 0 NEW_LINE for i in range ( 0 , n - 2 ) : NEW_LINE INDENT k = i + 2 NEW_LINE for j in range ( i + 1 , n ) : NEW_LINE INDENT while ( k < n and arr [ i ] + arr [ j ] > arr [ k ] ) : NEW_LINE INDENT k += 1 NEW_LINE... |
Count the number of possible triangles | CountTriangles function ; If it is possible with a [ l ] , a [ r ] and a [ i ] then it is also possible with a [ l + 1 ] . . a [ r - 1 ] , a [ r ] and a [ i ] ; checking for more possible solutions ; if not possible check for higher values of arr [ l ] ; Driver Code | def CountTriangles ( A ) : NEW_LINE INDENT n = len ( A ) ; NEW_LINE A . sort ( ) ; NEW_LINE count = 0 ; NEW_LINE for i in range ( n - 1 , 0 , - 1 ) : NEW_LINE INDENT l = 0 ; NEW_LINE r = i - 1 ; NEW_LINE while ( l < r ) : NEW_LINE INDENT if ( A [ l ] + A [ r ] > A [ i ] ) : NEW_LINE INDENT count += r - l ; NEW_LINE r -... |
Maximum sum of nodes in Binary tree such that no two are adjacent | A binary tree node structure ; Utility function to create a new Binary Tree node ; method returns maximum sum possible from subtrees rooted at grandChildrens of node ; call for children of left child only if it is not NULL ; call for children of right ... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def newNode ( data ) : NEW_LINE INDENT temp = Node ( data ) NEW_LINE return temp ; NEW_LINE DEDENT def sumOfGrandChildren ( node , mp ) : NEW_LIN... |
Flip minimum signs of array elements to get minimum sum of positive elements possible | Function to return the minimum number of elements whose sign must be flipped to get the positive sum of array elements as close to 0 as possible ; boolean variable used for toggling between maps ; Calculate the sum of all elements o... | def solve ( A , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 2000 ) ] for i in range ( 2000 ) ] NEW_LINE flag = 1 NEW_LINE sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += A [ i ] NEW_LINE DEDENT for i in range ( - sum , sum + 1 ) : NEW_LINE INDENT dp [ 0 ] [ i ] = 10 ** 9 NEW_LINE DEDENT dp [ 0 ] [ ... |
Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | | def countPairsBruteForce ( X , Y , m , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( pow ( X [ i ] , Y [ j ] ) > pow ( Y [ j ] , X [ i ] ) ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT |
Maximum items that can be filled in K Knapsacks of given Capacity | 2 - d array to store states of DP ; 2 - d array to store if a state has been solved ; Vector to store power of variable ' C ' . ; function to compute the states ; Base case ; Checking if a state has been solved ; Setting a state as solved ; Recurrence ... | x = 100 NEW_LINE dp = [ [ 0 for i in range ( x ) ] for i in range ( x ) ] NEW_LINE v = [ [ 0 for i in range ( x ) ] for i in range ( x ) ] NEW_LINE exp_c = [ ] NEW_LINE def FindMax ( i , r , w , n , c , k ) : NEW_LINE INDENT if ( i >= n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( v [ i ] [ r ] ) : NEW_LINE INDENT... |
Find number of pairs ( x , y ) in an array such that x ^ y > y ^ x | Python3 program to find the number of pairs ( x , y ) in an array such that x ^ y > y ^ x ; Function to return count of pairs with x as one element of the pair . It mainly looks for all values in Y where x ^ Y [ i ] > Y [ i ] ^ x ; If x is 0 , then th... | import bisect NEW_LINE def count ( x , Y , n , NoOfY ) : NEW_LINE INDENT if x == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if x == 1 : NEW_LINE INDENT return NoOfY [ 0 ] NEW_LINE DEDENT idx = bisect . bisect_right ( Y , x ) NEW_LINE ans = n - idx NEW_LINE ans += NoOfY [ 0 ] + NoOfY [ 1 ] NEW_LINE if x == 2 : NEW_LIN... |
Count all distinct pairs with difference equal to k | A simple program to count pairs with difference k ; Pick all elements one by one ; See if there is a pair of this picked element ; Driver program | def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if arr [ i ] - arr [ j ] == k or arr [ j ] - arr [ i ] == k : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT arr =... |
Count all distinct pairs with difference equal to k | Standard binary search function ; Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; Pick a first element point ; Driver Code | def binarySearch ( arr , low , high , x ) : NEW_LINE INDENT if ( high >= low ) : NEW_LINE INDENT mid = low + ( high - low ) // 2 NEW_LINE if x == arr [ mid ] : NEW_LINE INDENT return ( mid ) NEW_LINE DEDENT elif ( x > arr [ mid ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high , x ) NEW_LINE DEDENT e... |
Count all distinct pairs with difference equal to k | Returns count of pairs with difference k in arr [ ] of size n . ; Sort array elements ; arr [ r ] - arr [ l ] < sum ; Driver code | def countPairsWithDiffK ( arr , n , k ) : NEW_LINE INDENT count = 0 NEW_LINE arr . sort ( ) NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE while r < n : NEW_LINE INDENT if arr [ r ] - arr [ l ] == k : NEW_LINE INDENT count += 1 NEW_LINE l += 1 NEW_LINE r += 1 NEW_LINE DEDENT elif arr [ r ] - arr [ l ] > k : NEW_LINE INDENT l +... |
Count of sub | Python3 implementation of the approach ; Function to return the total number of required sub - sets ; Variable to store total elements which on dividing by 3 give remainder 0 , 1 and 2 respectively ; Create a dp table ; Process for n states and store the sum ( mod 3 ) for 0 , 1 and 2 ; Use of MOD for lar... | import math NEW_LINE def totalSubSets ( n , l , r ) : NEW_LINE INDENT MOD = 1000000007 ; NEW_LINE zero = ( math . floor ( r / 3 ) - math . ceil ( l / 3 ) + 1 ) ; NEW_LINE one = ( math . floor ( ( r - 1 ) / 3 ) - math . ceil ( ( l - 1 ) / 3 ) + 1 ) ; NEW_LINE two = ( math . floor ( ( r - 2 ) / 3 ) - math . ceil ( ( l - ... |
Check if a word exists in a grid or not | Python3 program to check if the word exists in the grid or not ; Function to check if a word exists in a grid starting from the first match in the grid level : index till which pattern is matched x , y : current position in 2D array ; Pattern matched ; Out of Boundary ; If grid... | r = 4 NEW_LINE c = 4 NEW_LINE def findmatch ( mat , pat , x , y , nrow , ncol , level ) : NEW_LINE INDENT l = len ( pat ) NEW_LINE if ( level == l ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( x < 0 or y < 0 or x >= nrow or y >= ncol ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( mat [ x ] [ y ] == pat [ ... |
Construct an array from its pair | Fills element in arr [ ] from its pair sum array pair [ ] . n is size of arr [ ] ; Driver code | def constructArr ( arr , pair , n ) : NEW_LINE INDENT arr [ 0 ] = ( pair [ 0 ] + pair [ 1 ] - pair [ n - 1 ] ) // 2 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT arr [ i ] = pair [ i - 1 ] - arr [ 0 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT pair = [ 15 , 13 , 11 , 10 , 12 , 10 , 9... |
Merge two sorted arrays with O ( 1 ) extra space | Merge ar1 [ ] and ar2 [ ] with O ( 1 ) extra space ; Iterate through all elements of ar2 [ ] starting from the last element ; Find the smallest element greater than ar2 [ i ] . Move all elements one position ahead till the smallest greater element is not found ; If the... | def merge ( ar1 , ar2 , m , n ) : NEW_LINE INDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT last = ar1 [ m - 1 ] NEW_LINE j = m - 2 NEW_LINE while ( j >= 0 and ar1 [ j ] > ar2 [ i ] ) : NEW_LINE INDENT ar1 [ j + 1 ] = ar1 [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT if ( j != m - 2 or last > ar2 [ i ] ) : NEW_LIN... |
Gould 's Sequence | Function to generate gould 's Sequence ; loop to generate each row of pascal 's Triangle up to nth row ; Loop to generate each element of ith row ; if c is odd increment count ; print count of odd elements ; Get n ; Function call | def gouldSequence ( n ) : NEW_LINE INDENT for row_num in range ( 1 , n ) : NEW_LINE INDENT count = 1 NEW_LINE c = 1 NEW_LINE for i in range ( 1 , row_num ) : NEW_LINE INDENT c = c * ( row_num - i ) / i NEW_LINE if ( c % 2 == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT print ( count , end = " β " ) NEW_LINE ... |
Product of maximum in first array and minimum in second | Function to calculate the product ; Sort the arrays to find the maximum and minimum elements in given arrays ; Return product of maximum and minimum . ; Driver Program | def minmaxProduct ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT arr1 . sort ( ) NEW_LINE arr2 . sort ( ) NEW_LINE return arr1 [ n1 - 1 ] * arr2 [ 0 ] NEW_LINE DEDENT arr1 = [ 10 , 2 , 3 , 6 , 4 , 1 ] NEW_LINE arr2 = [ 5 , 1 , 4 , 2 , 6 , 9 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( minmaxPro... |
Minimum odd cost path in a matrix | Python3 program to find Minimum odd cost path in a matrix ; Function to find the minimum cost ; leftmost element ; rightmost element ; Any element except leftmost and rightmost element of a row is reachable from direct upper or left upper or right upper row 's block ; Counting the mi... | M = 100 NEW_LINE N = 100 NEW_LINE def find_min_odd_cost ( given , m , n ) : NEW_LINE INDENT floor = [ [ 0 for i in range ( M ) ] for i in range ( N ) ] NEW_LINE min_odd_cost = 0 NEW_LINE i , j , temp = 0 , 0 , 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT floor [ 0 ] [ j ] = given [ 0 ] [ j ] NEW_LINE DEDENT for i ... |
Product of maximum in first array and minimum in second | Function to calculate the product ; Initialize max of first array ; initialize min of second array ; To find the maximum element in first array ; To find the minimum element in second array ; Process remaining elements ; Driver code | def minMaxProduct ( arr1 , arr2 , n1 , n2 ) : NEW_LINE INDENT max = arr1 [ 0 ] NEW_LINE min = arr2 [ 0 ] NEW_LINE i = 1 NEW_LINE while ( i < n1 and i < n2 ) : NEW_LINE INDENT if ( arr1 [ i ] > max ) : NEW_LINE INDENT max = arr1 [ i ] NEW_LINE DEDENT if ( arr2 [ i ] < min ) : NEW_LINE INDENT min = arr2 [ i ] NEW_LINE DE... |
Search , insert and delete in an unsorted array | Function to implement search operation ; Driver Code ; Using a last element as search element | def findElement ( arr , n , key ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] == key ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 12 , 34 , 10 , 6 , 40 ] NEW_LINE n = len ( arr ) NEW_LINE key = 40 NEW_LINE index = findElement ( arr , n , key ) NEW_LI... |
Search , insert and delete in a sorted array | function to implement binary search ; low + ( high - low ) / 2 ; Driver program to check above functions Let us search 3 in below array | def binarySearch ( arr , low , high , key ) : NEW_LINE INDENT mid = ( low + high ) / 2 NEW_LINE if ( key == arr [ int ( mid ) ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( key > arr [ int ( mid ) ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high , key ) NEW_LINE DEDENT if ( key < arr [ int ( ... |
Search , insert and delete in a sorted array | Inserts a key in arr [ ] of given capacity . n is current size of arr [ ] . This function returns n + 1 if insertion is successful , else n . ; Cannot insert more elements if n is already more than or equal to capcity ; Driver Code ; Inserting key | def insertSorted ( arr , n , key , capacity ) : NEW_LINE INDENT if ( n >= capacity ) : NEW_LINE INDENT return n NEW_LINE DEDENT i = n - 1 NEW_LINE while i >= 0 and arr [ i ] > key : NEW_LINE INDENT arr [ i + 1 ] = arr [ i ] NEW_LINE i -= 1 NEW_LINE DEDENT arr [ i + 1 ] = key NEW_LINE return ( n + 1 ) NEW_LINE DEDENT ar... |
Search , insert and delete in a sorted array | To search a ley to be deleted ; Function to delete an element ; Find position of element to be deleted ; Deleting element ; Driver code | def binarySearch ( arr , low , high , key ) : NEW_LINE INDENT if ( high < low ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( low + high ) // 2 NEW_LINE if ( key == arr [ mid ] ) : NEW_LINE INDENT return mid NEW_LINE DEDENT if ( key > arr [ mid ] ) : NEW_LINE INDENT return binarySearch ( arr , ( mid + 1 ) , high... |
Queries on number of Binary sub | Python 3 Program to answer queries on number of submatrix of given size ; Solve each query on matrix ; For each of the cell . ; finding submatrix size of oth row and column . ; intermediate cells . ; Find frequency of each distinct size for 0 s and 1 s . ; Find the Cumulative Sum . ; O... | MAX = 100 NEW_LINE N = 5 NEW_LINE M = 4 NEW_LINE def solveQuery ( n , m , mat , q , a , binary ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( m ) ] for y in range ( n ) ] NEW_LINE max = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT dp... |
Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space | Function that matches input txt with given wildcard pattern ; empty pattern can only match with empty sting Base case ; step 1 initialize markers : ; For step - ( 2 , 5 ) ; For step - ( 3 ) ; For step - ( 4 ) ; For step - ( 5 ) ; For ste... | def stringmatch ( txt , pat , n , m ) : NEW_LINE INDENT if ( m == 0 ) : NEW_LINE INDENT return ( n == 0 ) NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE index_txt = - 1 NEW_LINE index_pat = - 1 NEW_LINE while ( i < n - 2 ) : NEW_LINE INDENT if ( j < m and txt [ i ] == pat [ j ] ) : NEW_LINE INDENT i += 1 NEW_LINE j += 1... |
Find n | function to find nth stern ' diatomic series ; Initializing the DP array ; SET the Base case ; Traversing the array from 2 nd Element to nth Element ; Case 1 : for even n ; Case 2 : for odd n ; Driver program | def findSDSFunc ( n ) : NEW_LINE INDENT DP = [ 0 ] * ( n + 1 ) NEW_LINE DP [ 0 ] = 0 NEW_LINE DP [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT if ( int ( i % 2 ) == 0 ) : NEW_LINE INDENT DP [ i ] = DP [ int ( i / 2 ) ] NEW_LINE DEDENT else : NEW_LINE INDENT DP [ i ] = ( DP [ int ( ( i - 1 ) / 2 ) ] ... |
Check if any valid sequence is divisible by M | Python3 Program to Check if any valid sequence is divisible by M ; Calculate modulo for this call ; Base case ; check if sum is divisible by M ; check if the current state is already computed ; 1. Try placing '+ ; 2. Try placing '- ; calculate value of res for recursive c... | MAX = 100 NEW_LINE def isPossible ( n , index , modulo , M , arr , dp ) : NEW_LINE INDENT modulo = ( ( modulo % M ) + M ) % M NEW_LINE if ( index == n ) : NEW_LINE INDENT if ( modulo == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ index ] [ modulo ] != - 1 ) : NEW_LINE INDENT return... |
Find common elements in three sorted arrays | This function prints common elements in ar1 ; Initialize starting indexes for ar1 [ ] , ar2 [ ] and ar3 [ ] ; Iterate through three arrays while all arrays have elements ; If x = y and y = z , print any of them and move ahead in all arrays ; x < y ; y < z ; We reach here wh... | def findCommon ( ar1 , ar2 , ar3 , n1 , n2 , n3 ) : NEW_LINE INDENT i , j , k = 0 , 0 , 0 NEW_LINE while ( i < n1 and j < n2 and k < n3 ) : NEW_LINE INDENT if ( ar1 [ i ] == ar2 [ j ] and ar2 [ j ] == ar3 [ k ] ) : NEW_LINE INDENT print ar1 [ i ] , NEW_LINE i += 1 NEW_LINE j += 1 NEW_LINE k += 1 NEW_LINE DEDENT elif ar... |
Dynamic Programming on Trees | Set | Python3 code to find the maximum path sum ; Function for dfs traversal and to store the maximum value in dp [ ] for every node till the leaves ; Initially dp [ u ] is always a [ u ] ; Stores the maximum value from nodes ; Traverse the tree ; If child is parent , then we continue wit... | dp = [ 0 ] * 100 NEW_LINE def dfs ( a , v , u , parent ) : NEW_LINE INDENT dp [ u ] = a [ u - 1 ] NEW_LINE maximum = 0 NEW_LINE for child in v [ u ] : NEW_LINE INDENT if child == parent : NEW_LINE INDENT continue NEW_LINE DEDENT dfs ( a , v , child , u ) NEW_LINE maximum = max ( maximum , dp [ child ] ) NEW_LINE DEDENT... |
Jacobsthal and Jacobsthal | Return nth Jacobsthal number . ; base case ; Return nth Jacobsthal - Lucas number . ; base case ; Driven Program | def Jacobsthal ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + 2 * dp [ i - 2 ] NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT def Jacobsthal_Lucas ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 )... |
Find position of an element in a sorted array of infinite numbers | Binary search algorithm implementation ; function takes an infinite size array and a key to be searched and returns its position if found else - 1. We don 't know size of a[] and we can assume size to be infinite in this function. NOTE THAT THIS FUNCTI... | def binary_search ( 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 binary_search ( arr , l , mid - 1 , x ) NEW_LINE DEDENT return binary_search ( arr , mid + 1 ,... |
Count of possible hexagonal walks | Python 3 implementation of counting number of possible hexagonal walks ; We initialize our origin with 1 ; For each N = 1 to 14 , we traverse in all possible direction . Using this 3D array we calculate the number of ways at each step and the total ways for a given step shall be foun... | depth = 16 NEW_LINE ways = [ [ [ 0 for i in range ( 17 ) ] for i in range ( 17 ) ] for i in range ( 17 ) ] NEW_LINE def preprocess ( list , steps ) : NEW_LINE INDENT ways [ 0 ] [ 8 ] [ 8 ] = 1 NEW_LINE for N in range ( 1 , 16 , 1 ) : NEW_LINE INDENT for i in range ( 1 , depth , 1 ) : NEW_LINE INDENT for j in range ( 1 ... |
Check if possible to cross the matrix with given power | Python3 program to find if it is possible to cross the matrix with given power ; For each value of dp [ i ] [ j ] [ k ] ; For first cell and for each value of k ; For first cell of each row ; For first cell of each column ; For rest of the cell ; Down movement . ... | N = 105 NEW_LINE R = 3 NEW_LINE C = 4 NEW_LINE def maximumValue ( n , m , p , grid ) : NEW_LINE INDENT dp = [ [ [ False for i in range ( N ) ] for j in range ( N ) ] for k in range ( N ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT k = grid [ i ] [ j ] NEW_LINE while ( k <= p... |
Number of n digit stepping numbers | function that calculates the answer ; dp [ i ] [ j ] stores count of i digit stepping numbers ending with digit j . ; if n is 1 then answer will be 10. ; Initialize values for count of digits equal to 1. ; Compute values for count of digits more than 1. ; If ending digit is 0 ; If e... | def answer ( n ) : NEW_LINE INDENT dp = [ [ 0 for x in range ( 10 ) ] for y in range ( n + 1 ) ] ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return 10 ; NEW_LINE DEDENT for j in range ( 10 ) : NEW_LINE INDENT dp [ 1 ] [ j ] = 1 ; NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 10 ) : NEW_... |
Print Longest Palindromic Subsequence | Returns LCS X and Y ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Following code is used to print LCS ; Create a string length index + 1 and fill it with \ 0 ; Start f... | def lcs_ ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ 0 ] * ( n + 1 ) ] * ( m + 1 ) NEW_LINE for i in range ( n + 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 [ ... |
Count all subsequences having product less than K | Function to count numbers of such subsequences having product less than k . ; number of subsequence using j - 1 terms ; if arr [ j - 1 ] > i it will surely make product greater thus it won 't contribute then ; number of subsequence using 1 to j - 1 terms and j - th te... | def productSubSeqCount ( arr , k ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE dp = [ [ 0 for i in range ( n + 1 ) ] for j in range ( k + 1 ) ] NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i ] [ j - 1 ] NEW_LINE if arr [ j - 1 ] <= i and arr... |
Find the element that appears once in an array where every other element appears twice | function to find the once appearing element in array ; Do XOR of all elements and return ; Driver code | def findSingle ( ar , n ) : NEW_LINE INDENT res = ar [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT res = res ^ ar [ i ] NEW_LINE DEDENT return res NEW_LINE DEDENT ar = [ 2 , 3 , 5 , 4 , 5 , 3 , 4 ] NEW_LINE print " Element β occurring β once β is " , findSingle ( ar , len ( ar ) ) NEW_LINE |
Count all triplets whose sum is equal to a perfect cube | Python 3 program to calculate all triplets whose sum is perfect cube . ; Function to calculate all occurrence of a number in a given range ; if i == 0 assign 1 to present state ; else add + 1 to current state with previous state ; Function to calculate triplets ... | dp = [ [ 0 for i in range ( 15001 ) ] for j in range ( 1001 ) ] NEW_LINE def computeDpArray ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( 1 , 15001 , 1 ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( j == arr [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT d... |
Find the element that appears once in an array where every other element appears twice | function which find number ; applying the formula . ; driver code | def singleNumber ( nums ) : NEW_LINE INDENT return 2 * sum ( set ( nums ) ) - sum ( nums ) NEW_LINE DEDENT a = [ 2 , 3 , 5 , 4 , 5 , 3 , 4 ] NEW_LINE print ( int ( singleNumber ( a ) ) ) NEW_LINE a = [ 15 , 18 , 16 , 18 , 16 , 15 , 89 ] NEW_LINE print ( int ( singleNumber ( a ) ) ) NEW_LINE |
Maximum Subarray Sum Excluding Certain Elements | Function to check the element present in array B ; Utility function for findMaxSubarraySum ( ) with the following parameters A = > Array A , B = > Array B , n = > Number of elements in Array A , m = > Number of elements in Array B ; set max_so_far to INT_MIN ; if the el... | INT_MIN = - 2147483648 NEW_LINE def isPresent ( B , m , x ) : NEW_LINE INDENT for i in range ( 0 , m ) : NEW_LINE INDENT if B [ i ] == x : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def findMaxSubarraySumUtil ( A , B , n , m ) : NEW_LINE INDENT max_so_far = INT_MIN NEW_LINE curr_max... |
Number of n | Python3 program for counting n digit numbers with non decreasing digits ; Returns count of non - decreasing numbers with n digits . ; a [ i ] [ j ] = count of all possible number with i digits having leading digit as j ; Initialization of all 0 - digit number ; Initialization of all i - digit non - decrea... | import numpy as np NEW_LINE def nonDecNums ( n ) : NEW_LINE INDENT a = np . zeros ( ( n + 1 , 10 ) ) NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT a [ 0 ] [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT a [ i ] [ 9 ] = 1 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in... |
Count Balanced Binary Trees of Height h | Python3 program to count number of balanced binary trees of height h . ; base cases ; Driver program | def countBT ( h ) : NEW_LINE INDENT MOD = 1000000007 NEW_LINE dp = [ 0 for i in range ( h + 1 ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , h + 1 ) : NEW_LINE INDENT dp [ i ] = ( dp [ i - 1 ] * ( ( 2 * dp [ i - 2 ] ) % MOD + dp [ i - 1 ] ) % MOD ) % MOD NEW_LINE DEDENT return dp [ h ] NE... |
Maximum Subarray Sum Excluding Certain Elements | Python3 program implementation of the above idea ; Function to calculate the max sum of contigous subarray of B whose elements are not present in A ; Mark all the elements present in B ; Initialize max_so_far with INT_MIN ; Traverse the array A ; If current max is great... | import sys NEW_LINE def findMaxSubarraySum ( A , B ) : NEW_LINE INDENT m = dict ( ) NEW_LINE for i in range ( len ( B ) ) : NEW_LINE INDENT if B [ i ] not in m : NEW_LINE INDENT m [ B [ i ] ] = 0 NEW_LINE DEDENT m [ B [ i ] ] = 1 NEW_LINE DEDENT max_so_far = - sys . maxsize - 1 NEW_LINE currmax = 0 NEW_LINE for i in ra... |
Print all k | utility function to print contents of a vector from index i to it 's end ; Binary Tree Node ; This function prints all paths that have sum k ; empty node ; add current node to the path ; check if there 's any k sum path in the left sub-tree. ; check if there 's any k sum path in the right sub-tree. ... | def printVector ( v , i ) : NEW_LINE INDENT for j in range ( i , len ( v ) ) : NEW_LINE INDENT print ( v [ j ] , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = Non... |
Equilibrium index of an array | function to find the equilibrium index ; Check for indexes one by one until an equilibrium index is found ; get left sum ; get right sum ; if leftsum and rightsum are same , then we are done ; return - 1 if no equilibrium index is found ; driver code | def equilibrium ( arr ) : NEW_LINE INDENT leftsum = 0 NEW_LINE rightsum = 0 NEW_LINE n = len ( arr ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT leftsum = 0 NEW_LINE rightsum = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT leftsum += arr [ j ] NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT right... |
Find number of endless points | Python3 program to find count of endless points ; Returns count of endless points ; Fills column matrix . For every column , start from every last row and fill every entry as blockage after a 0 is found . ; flag which will be zero once we get a '0' and it will be 1 otherwise ; encountere... | import numpy as np NEW_LINE def countEndless ( input_mat , n ) : NEW_LINE INDENT row = np . zeros ( ( n , n ) ) NEW_LINE col = np . zeros ( ( n , n ) ) NEW_LINE for j in range ( n ) : NEW_LINE INDENT isEndless = 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( input_mat [ i ] [ j ] == 0 ) : NEW_LI... |
Equilibrium index of an array | function to find the equilibrium index ; finding the sum of whole array ; total_sum is now right sum for index i ; If no equilibrium index found , then return - 1 ; Driver code | def equilibrium ( arr ) : NEW_LINE INDENT total_sum = sum ( arr ) NEW_LINE leftsum = 0 NEW_LINE for i , num in enumerate ( arr ) : NEW_LINE INDENT total_sum -= num NEW_LINE if leftsum == total_sum : NEW_LINE INDENT return i NEW_LINE DEDENT leftsum += num NEW_LINE DEDENT return - 1 NEW_LINE DEDENT arr = [ - 7 , 1 , 5 , ... |
Sum of all substrings of a string representing a number | Set 1 | Returns sum of all substring of num ; allocate memory equal to length of string ; initialize first value with first digit ; loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; Driver code | def sumOfSubstrings ( num ) : NEW_LINE INDENT n = len ( num ) NEW_LINE sumofdigit = [ ] NEW_LINE sumofdigit . append ( int ( num [ 0 ] ) ) NEW_LINE res = sumofdigit [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT numi = int ( num [ i ] ) NEW_LINE sumofdigit . append ( ( i + 1 ) * numi + 10 * sumofdigit [ i - ... |
Sum of all substrings of a string representing a number | Set 1 | Returns sum of all substring of num ; storing prev value ; substrings sum upto current index loop over all digits of string ; update each sumofdigit from previous value ; add current value to the result ; prev = current update previous ; Driver code to t... | def sumOfSubstrings ( num ) : NEW_LINE INDENT n = len ( num ) NEW_LINE prev = int ( num [ 0 ] ) NEW_LINE res = prev NEW_LINE current = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT numi = int ( num [ i ] ) NEW_LINE current = ( i + 1 ) * numi + 10 * prev NEW_LINE res += current NEW_LINE DEDENT return res NEW_LIN... |
Equilibrium index of an array | Python program to find the equilibrium index of an array Function to find the equilibrium index ; Iterate from 0 to len ( arr ) ; If i is not 0 ; Iterate from 0 to len ( arr ) ; If no equilibrium index found , then return - 1 ; Driver code | def equilibrium ( arr ) : NEW_LINE INDENT left_sum = [ ] NEW_LINE right_sum = [ ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( i ) : NEW_LINE INDENT left_sum . append ( left_sum [ i - 1 ] + arr [ i ] ) NEW_LINE right_sum . append ( right_sum [ i - 1 ] + arr [ len ( arr ) - 1 - i ] ) NEW_LINE DEDENT el... |
Leaders in an array | Python Function to print leaders in array ; If loop didn 't break ; Driver function | def printLeaders ( arr , size ) : NEW_LINE INDENT 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 break NEW_LINE DEDENT DEDENT if j == size - 1 : NEW_LINE INDENT print arr [ i ] , NEW_LINE DEDENT DEDENT DEDENT arr = [ 16 , 17 , ... |
Leaders in an array | Python function to print leaders in array ; Rightmost element is always leader ; Driver function | def printLeaders ( arr , size ) : NEW_LINE INDENT max_from_right = arr [ size - 1 ] NEW_LINE print max_from_right , NEW_LINE for i in range ( size - 2 , - 1 , - 1 ) : NEW_LINE INDENT if max_from_right < arr [ i ] : NEW_LINE INDENT print arr [ i ] , NEW_LINE max_from_right = arr [ i ] NEW_LINE DEDENT DEDENT DEDENT arr =... |
Unbounded Knapsack ( Repetition of items allowed ) | Returns the maximum value with knapsack of W capacity ; dp [ i ] is going to store maximum value with knapsack capacity i . ; Fill dp [ ] using above recursive formula ; Driver program | def unboundedKnapsack ( W , n , val , wt ) : NEW_LINE INDENT dp = [ 0 for i in range ( W + 1 ) ] NEW_LINE ans = 0 NEW_LINE for i in range ( W + 1 ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( wt [ j ] <= i ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ i - wt [ j ] ] + val [ j ] ) NEW_LINE DEDEN... |
Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to first element , then return the first element ; Otherwise , linearly search for ceil value ; if x lies between arr [ i ] and arr [ i + 1 ] including arr [ i + 1 ] , then return arr [ i + 1 ] ; If... | def ceilSearch ( arr , low , high , x ) : NEW_LINE INDENT if x <= arr [ low ] : NEW_LINE INDENT return low NEW_LINE DEDENT i = low NEW_LINE for i in range ( high ) : NEW_LINE INDENT if arr [ i ] == x : NEW_LINE INDENT return i NEW_LINE DEDENT if arr [ i ] < x and arr [ i + 1 ] >= x : NEW_LINE INDENT return i + 1 NEW_LI... |
Maximum sum subarray removing at most one element | Method returns maximum sum of all subarray where removing one element is also allowed ; Maximum sum subarrays in forward and backward directions ; Initialize current max and max so far . ; calculating maximum sum subarrays in forward direction ; storing current maximu... | def maxSumSubarrayRemovingOneEle ( arr , n ) : NEW_LINE INDENT fw = [ 0 for k in range ( n ) ] NEW_LINE bw = [ 0 for k in range ( n ) ] NEW_LINE cur_max , max_so_far = arr [ 0 ] , arr [ 0 ] NEW_LINE fw [ 0 ] = cur_max NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT cur_max = max ( arr [ i ] , cur_max + arr [ i ] ) ... |
Ceiling in a sorted array | Function to get index of ceiling of x in arr [ low . . high ] ; If x is smaller than or equal to the first element , then return the first element ; If x is greater than the last element , then return - 1 ; get the index of middle element of arr [ low . . high ] low + ( high - low ) / 2 ; If... | def ceilSearch ( arr , low , high , x ) : NEW_LINE INDENT if x <= arr [ low ] : NEW_LINE INDENT return low NEW_LINE DEDENT if x > arr [ high ] : NEW_LINE INDENT return - 1 NEW_LINE DEDENT mid = ( low + high ) / 2 ; NEW_LINE if arr [ mid ] == x : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] < x : NEW_LINE... |
Sum of heights of all individual nodes in a binary tree | Compute the " maxHeight " of a particular Node ; compute the height of each subtree ; use the larger one ; Helper class that allocates a new Node with the given data and None left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder... | def getHeight ( Node ) : NEW_LINE INDENT if ( Node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT lHeight = getHeight ( Node . left ) NEW_LINE rHeight = getHeight ( Node . right ) NEW_LINE if ( lHeight > rHeight ) : NEW_LINE INDENT return ( lHeight + 1 ) NEW_LINE DEDENT else : NEW_LINE INDE... |
Path with maximum average value | Maximum number of rows and / or columns ; method returns maximum average of all path of cost matrix ; Initialize first column of total cost ( dp ) array ; Initialize first row of dp array ; Construct rest of the dp array ; divide maximum sum by constant path length : ( 2 N - 1 ) for ge... | M = 100 NEW_LINE def maxAverageOfPath ( cost , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N + 1 ) ] for j in range ( N + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = cost [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + cost [ i ] [ 0 ] NEW_LINE DEDENT for j in range ( 1 ,... |
Maximum weight path ending at any element of last row in a matrix | Python3 program to find the path having the maximum weight in matrix ; Function which return the maximum weight path sum ; creat 2D matrix to store the sum of the path ; Initialize first column of total weight array ( dp [ i to N ] [ 0 ] ) ; Calculate ... | MAX = 1000 NEW_LINE def maxCost ( mat , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE dp [ 0 ] [ 0 ] = mat [ 0 ] [ 0 ] NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = mat [ i ] [ 0 ] + dp [ i - 1 ] [ 0 ] NEW_LINE DEDENT for i in range ( 1 , N ) : NEW_LINE I... |
Number of permutation with K inversions | Limit on N and K ; 2D array memo for stopping solving same problem again ; method recursively calculates permutation with K inversion ; Base cases ; If already solved then return result directly ; Calling recursively all subproblem of permutation size N - 1 ; Call recursively o... | M = 100 NEW_LINE memo = [ [ 0 for i in range ( M ) ] for j in range ( M ) ] NEW_LINE def numberOfPermWithKInversion ( N , K ) : NEW_LINE INDENT if ( N == 0 ) : return 0 NEW_LINE if ( K == 0 ) : return 1 NEW_LINE if ( memo [ N ] [ K ] != 0 ) : NEW_LINE INDENT return memo [ N ] [ K ] NEW_LINE DEDENT sum = 0 NEW_LINE for ... |
Check if an array has a majority element | Returns true if there is a majority element in a [ ] ; Insert all elements in a hash table ; Check if frequency of any element is n / 2 or more . ; Driver code | def isMajority ( a ) : NEW_LINE INDENT mp = { } NEW_LINE for i in a : NEW_LINE INDENT if i in mp : mp [ i ] += 1 NEW_LINE else : mp [ i ] = 1 NEW_LINE DEDENT for x in mp : NEW_LINE INDENT if mp [ x ] >= len ( a ) // 2 : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT a = [ 2 , 3 , 9 , 2 ... |
Two Pointers Technique | Naive solution to find if there is a pair in A [ 0. . N - 1 ] with given sum . ; as equal i and j means same element ; pair exists ; as the array is sorted ; No pair found with given sum ; Driver code ; Function call | def isPairSum ( A , N , X ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( i == j ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( A [ i ] + A [ j ] == X ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( A [ i ] + A [ j ] > X ) : NEW_LINE INDENT break NEW_LINE D... |
Remove minimum elements from either side such that 2 * min becomes more than max | A utility function to find minimum in arr [ l . . h ] ; A utility function to find maximum in arr [ l . . h ] ; Returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; If the... | def mini ( arr , l , h ) : NEW_LINE INDENT mn = arr [ l ] NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( mn > arr [ i ] ) : NEW_LINE INDENT mn = arr [ i ] NEW_LINE DEDENT DEDENT return mn NEW_LINE DEDENT def max ( arr , l , h ) : NEW_LINE INDENT mx = arr [ l ] NEW_LINE for i in range ( l + 1 , h + 1 )... |
Two Pointers Technique | Two pointer technique based solution to find if there is a pair in A [ 0. . N - 1 ] with a given sum . ; represents first pointer ; represents second pointer ; If we find a pair ; If sum of elements at current pointers is less , we move towards higher values by doing i += 1 ; If sum of elements... | def isPairSum ( A , N , X ) : NEW_LINE INDENT i = 0 NEW_LINE j = N - 1 NEW_LINE while ( i < j ) : NEW_LINE INDENT if ( A [ i ] + A [ j ] == X ) : NEW_LINE INDENT return True NEW_LINE DEDENT elif ( A [ i ] + A [ j ] < X ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT DEDENT retur... |
Sum of heights of all individual nodes in a binary tree | A binary tree Node has data , pointer to left child and a pointer to right child ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code | class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . data = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE def getTotalHeightUtil ( root ) : NEW_LINE INDENT global sum NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDE... |
Inorder Tree Traversal without Recursion | A binary tree node ; Iterative function for inorder tree traversal ; traverse the tree ; Reach the left most Node of the current Node ; Place pointer to a tree node on the stack before traversing the node 's left subtree ; BackTrack from the empty subtree and visit the Node at... | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def inOrder ( root ) : NEW_LINE INDENT current = root NEW_LINE stack = [ ] NEW_LINE done = 0 NEW_LINE while True : NEW_LINE INDENT if current is ... |
Count all possible paths from top left to bottom right of a mXn matrix | Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 2D table to store results of subproblems one - liner logic to take input for rows and columns mat = [ [ i... | def numberOfPaths ( m , n ) : NEW_LINE INDENT count = [ [ 0 for x in range ( n ) ] for y in range ( m ) ] NEW_LINE for i in range ( m ) : NEW_LINE INDENT count [ i ] [ 0 ] = 1 ; NEW_LINE DEDENT for j in range ( n ) : NEW_LINE INDENT count [ 0 ] [ j ] = 1 ; NEW_LINE DEDENT for i in range ( 1 , m ) : NEW_LINE INDENT for ... |
Split array into two equal length subsets such that all repetitions of a number lies in a single subset | Python3 program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store freque... | from collections import defaultdict NEW_LINE def findSubsets ( arr ) : NEW_LINE INDENT M = defaultdict ( int ) NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 NEW_LINE DEDENT subsets = [ 0 ] * len ( M ) NEW_LINE i = 0 NEW_LINE for j in M : NEW_LINE INDENT subsets [ i ] = M [ j ] NEW_LINE ... |
Maximum Product Cutting | DP | The main function that returns maximum product obtainable from a rope of length n ; Base cases ; Make a cut at different places and take the maximum of all ; Return the maximum of all values ; Driver program to test above functions | def maxProd ( n ) : NEW_LINE INDENT if ( n == 0 or n == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT max_val = 0 NEW_LINE for i in range ( 1 , n - 1 ) : NEW_LINE INDENT max_val = max ( max_val , max ( i * ( n - i ) , maxProd ( n - i ) * i ) ) NEW_LINE DEDENT return max_val ; NEW_LINE DEDENT print ( " Maximum β Produc... |
Assembly Line Scheduling | DP | Python program to find minimum possible time by the car chassis to complete ; time taken to leave ; first station in line 1 time taken to leave ; Fill tables T1 [ ] and T2 [ ] using above given recursive relations ; consider exit times and return minimum ; Driver code | def carAssembly ( a , t , e , x ) : NEW_LINE INDENT NUM_STATION = len ( a [ 0 ] ) NEW_LINE T1 = [ 0 for i in range ( NUM_STATION ) ] NEW_LINE T2 = [ 0 for i in range ( NUM_STATION ) ] NEW_LINE DEDENT T1 [ 0 ] = e [ 0 ] + a [ 0 ] [ 0 ] NEW_LINE T2 [ 0 ] = e [ 1 ] + a [ 1 ] [ 0 ] NEW_LINE INDENT for i in range ( 1 , NUM_... |
Longest Common Substring | DP | Returns length of longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains the length of longest common suffix of X [ 0. . . i - 1 ] and Y [ 0. . . j - 1 ] . The fi... | def LCSubStr ( X , Y , m , n ) : NEW_LINE INDENT LCSuff = [ [ 0 for k in range ( n + 1 ) ] for l in range ( m + 1 ) ] NEW_LINE result = 0 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 LCSuff [ i ] [ j ] = 0 NEW_LINE DEDENT elif (... |
Minimum insertions to form a palindrome | DP | A utility function to find minimum of two integers ; A DP function to find minimum number of insertions ; Create a table of size n * n . table [ i ] [ j ] will store minimum number of insertions needed to convert str1 [ i . . j ] to a palindrome . ; Fill the table ; Return... | def Min ( a , b ) : NEW_LINE INDENT return min ( a , b ) NEW_LINE DEDENT def findMinInsertionsDP ( str1 , n ) : NEW_LINE INDENT table = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE l , h , gap = 0 , 0 , 0 NEW_LINE for gap in range ( 1 , n ) : NEW_LINE INDENT l = 0 NEW_LINE for h in range ( gap , n ) : N... |
Maximum Subarray Sum using Divide and Conquer algorithm | Find the maximum possible sum in arr [ ] auch that arr [ m ] is part of it ; Include elements on left of mid . ; Include elements on right of mid ; Return sum of elements on left and right of mid returning only left_sum + right_sum will fail for [ - 2 , 1 ] ; Re... | def maxCrossingSum ( arr , l , m , h ) : NEW_LINE INDENT sm = 0 NEW_LINE left_sum = - 10000 NEW_LINE for i in range ( m , l - 1 , - 1 ) : NEW_LINE INDENT sm = sm + arr [ i ] NEW_LINE if ( sm > left_sum ) : NEW_LINE INDENT left_sum = sm NEW_LINE DEDENT DEDENT sm = 0 NEW_LINE right_sum = - 1000 NEW_LINE for i in range ( ... |
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... |
Program to find amount of water in a given glass | Returns the amount of water in jth glass of ith row ; A row number i has maximum i columns . So input column number must be less than i ; There will be i * ( i + 1 ) / 2 glasses till ith row ( including ith row ) and Initialize all glasses as empty ; Put all water in f... | def findWater ( i , j , X ) : NEW_LINE INDENT if ( j > i ) : NEW_LINE INDENT print ( " Incorrect β Input " ) ; NEW_LINE return ; NEW_LINE DEDENT glass = [ 0 ] * int ( i * ( i + 1 ) / 2 ) ; NEW_LINE index = 0 ; NEW_LINE glass [ index ] = X ; NEW_LINE for row in range ( 1 , i ) : NEW_LINE INDENT for col in range ( 1 , ro... |
Maximum Length Chain of Pairs | DP | Python program for above approach ; This function assumes that arr [ ] is sorted in increasing order according the first ( or smaller ) values in pairs . ; Initialize MCL ( max chain length ) values for all indices ; Compute optimized chain length values in bottom up manner ; Pick m... | class Pair ( object ) : NEW_LINE INDENT def __init__ ( self , a , b ) : NEW_LINE INDENT self . a = a NEW_LINE self . b = b NEW_LINE DEDENT DEDENT def maxChainLength ( arr , n ) : NEW_LINE INDENT max = 0 NEW_LINE mcl = [ 1 for i in range ( n ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ... |
Palindrome Partitioning | DP | Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum number of cuts needed for palindrome partitioning of substring str [ i ... | def minPalPartion ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE C = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE P = [ [ False for i in range ( n ) ] for i in range ( n ) ] NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE L = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT P [ i ] [ i ] = True ; NEW_LINE C... |
Count subtrees that sum up to a given value x only using single recursive function | class to get a new node ; put in the data ; function to count subtress that Sum up to a given value x ; if tree is empty ; Sum of nodes in the left subtree ; Sum of nodes in the right subtree ; Sum of nodes in the subtree rooted with '... | class getNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def countSubtreesWithSumX ( root , count , x ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ls = countSubtreesWithSumX ( roo... |
Minimum replacements required to make given Matrix palindromic | Function to count minimum changes to make the matrix palindromic ; Rows in the matrix ; Columns in the matrix ; Traverse the given matrix ; Store the frequency of the four cells ; Iterate over the map ; Min changes to do to make all ; Four elements equal ... | def minchanges ( mat ) : NEW_LINE INDENT N = len ( mat ) NEW_LINE M = len ( mat [ 0 ] ) NEW_LINE ans = 0 NEW_LINE mp = { } NEW_LINE for i in range ( N // 2 ) : NEW_LINE INDENT for j in range ( M // 2 ) : NEW_LINE INDENT mp [ mat [ i ] [ M - 1 - j ] ] = mp . get ( mat [ i ] [ M - 1 - j ] , 0 ) + 1 NEW_LINE mp [ mat [ i ... |
Check if a number starts with another number or not | Function to check if B is a prefix of A or not ; Convert numbers into strings ; Check if s2 is a prefix of s1 or not using startswith ( ) function ; If result is true print Yes ; Driver code ; Given numbers ; Function call | def checkprefix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) NEW_LINE s2 = str ( B ) NEW_LINE result = s1 . startswith ( s2 ) NEW_LINE if result : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 12345 NE... |
Check three or more consecutive identical characters or numbers | Python3 program to check three or more consecutiveidentical characters or numbers using regular expression ; Function to check three or more consecutiveidentical characters or numbers using regular expression ; Regex to check three or more consecutive id... | import re NEW_LINE def isValidGUID ( str ) : NEW_LINE INDENT regex = " \\b ( [ a - zA - Z0-9 ] ) \\1\\1 + \\b " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDE... |
How to validate MAC address using Regular Expression | Python3 program to validate MAC address using using regular expression ; Function to validate MAC address . ; Regex to check valid MAC address ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test ... | import re NEW_LINE def isValidMACAddress ( str ) : NEW_LINE INDENT regex = ( " ^ ( [0-9A - Fa - f ] {2 } [ : - ] ) " + " { 5 } ( [0-9A - Fa - f ] {2 } ) | " + " ( [0-9a - fA - F ] {4 } \\ . " + " [ 0-9a - fA - F ] {4 } \\ . " + " [ 0-9a - fA - F ] {4 } ) $ " ) NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == No... |
How to validate GUID ( Globally Unique Identifier ) using Regular Expression | Python3 program to validate GUID ( Globally Unique Identifier ) using regular expression ; Function to validate GUID ( Globally Unique Identifier ) ; Regex to check valid GUID ( Globally Unique Identifier ) ; Compile the ReGex ; If the strin... | import re NEW_LINE def isValidGUID ( str ) : NEW_LINE INDENT regex = " ^ [ { ] ? [ 0-9a - fA - F ] {8 } " + " - ( [ 0-9a - fA - F ] {4 } - ) " + " { 3 } [ 0-9a - fA - F ] {12 } [ } ] ? $ " NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p... |
How to validate Indian driving license number using Regular Expression | Python program to validate Indian driving license number using regular expression ; Function to validate Indian driving license number . ; Regex to check valid Indian driving license number ; Compile the ReGex ; If the string is empty return false... | import re NEW_LINE def isValidLicenseNo ( str ) : NEW_LINE INDENT regex = ( " ^ ( ( [ A - Z ] {2 } [ 0-9 ] { 2 } ) " + " ( β ) | ( [ A - Z ] {2 } - [0-9 ] " + " { 2 } ) ) ( (19 β 20 ) [ 0-9 ] " + " [ 0-9 ] ) [0-9 ] { 7 } $ " ) NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return Fals... |
Count subtrees that sum up to a given value x only using single recursive function | Structure of a node of binary tree ; Function to get a new node ; Allocate space ; Utility function to count subtress that sum up to a given value x ; Driver code ; binary tree creation 5 / \ - 10 3 / \ / \ 9 8 - 4 7 | class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def getNode ( data ) : NEW_LINE INDENT newNode = Node ( data ) NEW_LINE return newNode NEW_LINE DEDENT count = 0 NEW_LINE ptr = None NEW_LINE def... |
How to validate Indian Passport number using Regular Expression | Python3 program to validate passport number of India using regular expression ; Function to validate the pin code of India . ; Regex to check valid pin code of India . ; Compile the ReGex ; If the string is empty return false ; Pattern class contains mat... | import re NEW_LINE def isValidPassportNo ( string ) : NEW_LINE INDENT regex = " ^ [ A - PR - WYa - pr - wy ] [1-9 ] \\d " + p = re . compile ( regex ) NEW_LINE if ( string == ' ' ) : NEW_LINE INDENT return False NEW_LINE DEDENT m = re . match ( p , string ) NEW_LINE if m is None : NEW_LINE INDENT return False NEW_LINE ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.