text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Maximize sum of product of neighbouring elements of the element removed from Array | Function to calculate maximum possible score using the given operations ; Iterate through all possible len1gths of the subarray ; Iterate through all the possible starting indices i having len1gth len1 ; Stores the rightmost index of t...
def maxMergingScore ( A , N ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( 101 ) ] for j in range ( 101 ) ] NEW_LINE for len1 in range ( 1 , N , 1 ) : NEW_LINE INDENT for i in range ( 0 , N - len1 , 1 ) : NEW_LINE INDENT j = i + len1 NEW_LINE dp [ i ] [ j ] = 0 NEW_LINE for k in range ( i + 1 , j , 1 ) : NEW_LINE INDE...
Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp Initializing dp with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp with ( ...
def LongestOddEvenSubarray ( A , N ) : NEW_LINE INDENT dp = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 0 and A [ i - 1 ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ i - 1 ] % 2 != 0 ) ) : NEW_LINE INDENT dp = dp + 1 NEW_LINE ans = max ( ans , dp ) NEW_LINE DEDENT else : NE...
Count of N | python program for the above approach ; Function to find number of ' N ' digit numbers such that the element is mean of sum of its adjacent digits ; If digit = n + 1 , a valid n - digit number has been formed ; If the state has already been computed ; If current position is 1 , then any digit from [ 1 - 9 ...
dp = [ [ [ - 1 for i in range ( 10 ) ] for col in range ( 20 ) ] for row in range ( 100 ) ] NEW_LINE def countOfNumbers ( digit , prev1 , prev2 , n ) : NEW_LINE INDENT if ( digit == n + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT val = dp [ digit ] [ prev1 ] [ prev2 ] NEW_LINE if ( val != - 1 ) : NEW_LINE INDENT ret...
Count half nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Iterative Method to count half nodes of binary tree ; Base Case ; Create an empty queue for level order traversal ; initialize count for half nodes ; Enqueue left child ; Enqueue right child ; Driver Program to test above function
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 def gethalfCount ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT queue = [ ] NEW_LINE queue . append ( root )...
Count N | Python3 program for the above approach ; Function to count N digit numbers whose digits are less than or equal to the absolute difference of previous two digits ; If all digits are traversed ; If the state has already been computed ; If the current digit is 1 , any digit from [ 1 - 9 ] can be placed . If N ==...
dp = [ [ [ - 1 for i in range ( 10 ) ] for j in range ( 10 ) ] for k in range ( 50 ) ] NEW_LINE def countOfNumbers ( digit , prev1 , prev2 , N ) : NEW_LINE INDENT if ( digit == N + 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ digit ] [ prev1 ] [ prev2 ] != - 1 ) : NEW_LINE INDENT return dp [ digit ] [ prev1...
Count number of unique ways to paint a N x 3 grid | Function to count the number of ways to paint N * 3 grid based on given conditions ; Count of ways to pain a row with same colored ends ; Count of ways to pain a row with different colored ends ; Traverse up to ( N - 1 ) th row ; For same colored ends ; For different ...
def waysToPaint ( n ) : NEW_LINE INDENT same = 6 NEW_LINE diff = 6 NEW_LINE for _ in range ( n - 1 ) : NEW_LINE INDENT sameTmp = 3 * same + 2 * diff NEW_LINE diffTmp = 2 * same + 2 * diff NEW_LINE same = sameTmp NEW_LINE diff = diffTmp NEW_LINE DEDENT print ( same + diff ) NEW_LINE DEDENT N = 2 NEW_LINE waysToPaint ( N...
Maximize sum by selecting X different | Function to find maximum sum of at most N with different index array elements such that at most X are from A [ ] , Y are from B [ ] and Z are from C [ ] ; Base Cases ; Selecting i - th element from A [ ] ; Selecting i - th element from B [ ] ; Selecting i - th element from C [ ] ...
def FindMaxS ( X , Y , Z , n ) : NEW_LINE INDENT global A , B , C NEW_LINE if ( X < 0 or Y < 0 or Z < 0 ) : NEW_LINE INDENT return - 10 ** 9 NEW_LINE DEDENT if ( n < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ch = A [ n ] + FindMaxS ( X - 1 , Y , Z , n - 1 ) NEW_LINE ca = B [ n ] + FindMaxS ( X , Y - 1 , Z , n - 1 ...
Rearrange array by interchanging positions of even and odd elements in the given array | Function to replace each even element by odd and vice - versa in a given array ; Traverse array ; If current element is even then swap it with odd ; Perform Swap ; Change the sign ; If current element is odd then swap it with even ...
def replace ( arr , n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ i ] >= 0 and arr [ j ] >= 0 and arr [ i ] % 2 == 0 and arr [ j ] % 2 != 0 ) : NEW_LINE INDENT tmp = arr [ i ] NEW_LINE arr [ i ] = arr [ j ] NEW_LINE arr [ j ] = tmp NEW_LINE arr [ ...
Count half nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Function to get the count of half Nodes in a binary tree ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree shown in above example
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def gethalfCount ( root ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE if ( root . left == None and root . ...
Minimize cost to reduce array to a single element by replacing K consecutive elements by their sum | Function to find the minimum cost to reduce given array to a single element by replacing consecutive K array elements ; Stores length of arr ; If ( N - 1 ) is not multiple of ( K - 1 ) ; Store prefix sum of the array ; ...
def minimumCostToMergeK ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE if ( N - 1 ) % ( K - 1 ) != 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT prefixSum = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT prefixSum [ i ] = ( prefixSum [ i - 1 ] + arr [ i - 1 ] ) NEW_LINE DEDENT dp = [...
Check if end of a sorted Array can be reached by repeated jumps of one more , one less or same number of indices as previous jump | Python3 program for the above approach ; Utility function to check if it is possible to move from index 1 to N - 1 ; Successfully reached end index ; memo [ i ] [ j ] is already calculated...
N = 8 NEW_LINE def check ( memo , i , j , A ) : NEW_LINE INDENT if ( i == N - 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( memo [ i ] [ j ] != - 1 ) : NEW_LINE INDENT return memo [ i ] [ j ] NEW_LINE DEDENT flag = 0 NEW_LINE for k in range ( i + 1 , N ) : NEW_LINE INDENT if ( A [ k ] - A [ i ] > j + 1 ) : NEW_LI...
Maximum subsequence sum such that no K elements are consecutive | Function to find the maximum sum of a subsequence consisting of no K consecutive array elements ; Stores states of dp ; Stores the prefix sum ; Update the prefix sum ; Base case for i < K ; For indices less than k take all the elements ; For i >= K case ...
def Max_Sum ( arr , K , N ) : NEW_LINE INDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE prefix = [ None ] * ( N + 1 ) NEW_LINE prefix [ 0 ] = 0 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT prefix [ i ] = prefix [ i - 1 ] + arr [ i - 1 ] NEW_LINE DEDENT dp [ 0 ] = 0 NEW_LINE for i in range ( 1 , K ) : NEW_LINE INDENT d...
Count possible splits of sum N into K integers such that the minimum is at least P | Function that finds the value of the Binomial Coefficient C ( n , k ) ; Stores the value of Binomial Coefficient in bottom up manner ; Base Case ; Find the value using previously stored values ; Return the value of C ( N , K ) ; Functi...
def binomialCoeff ( n , k ) : NEW_LINE INDENT C = [ [ 0 for x in range ( k + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , k ) + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ ...
Minimum pair merge operations required to make Array non | Function to find the minimum operations to make the array Non - increasing ; Size of the array ; Dp table initialization ; dp [ i ] : Stores minimum number of operations required to make subarray { A [ i ] , ... , A [ N ] } non - increasing ; Increment the valu...
def solve ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE dp = [ 0 ] * ( n + 1 ) NEW_LINE val = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = a [ i ] NEW_LINE j = i NEW_LINE while ( j + 1 < n and sum < val [ j + 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE sum += a [ j ] NEW_LINE DED...
Count full nodes in a Binary tree ( Iterative and Recursive ) | A node structure ; Iterative Method to count full nodes of binary tree ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize count ; initialize count for full nodes ; Enqueue left child ; Enqueue right child ; 2 / \ 7 ...
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 def getfullCount ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return 0 NEW_LINE DEDENT queue = [ ] NEW_LINE queue . append ( root )...
Count of Distinct Substrings occurring consecutively in a given String | Function to count the distinct substrings placed consecutively in the given string ; Length of the string ; If length of the string does not exceed 1 ; Initialize a DP - table ; Stores the distinct substring ; Iterate from end of the string ; Iter...
def distinctSimilarSubstrings ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE if ( n <= 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT dp = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE substrings = set ( ) NEW_LINE for j in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT for i in range ( j - 1 ...
Finding shortest path between any two nodes using Floyd Warshall Algorithm | Initializing the distance and Next array ; No edge between node i and j ; Function construct the shortest path between u and v ; If there 's no path between node u and v, simply return an empty array ; Storing the path in a vector ; Standard...
def initialise ( V ) : NEW_LINE INDENT global dis , Next NEW_LINE for i in range ( V ) : NEW_LINE INDENT for j in range ( V ) : NEW_LINE INDENT dis [ i ] [ j ] = graph [ i ] [ j ] NEW_LINE if ( graph [ i ] [ j ] == INF ) : NEW_LINE INDENT Next [ i ] [ j ] = - 1 NEW_LINE DEDENT else : NEW_LINE INDENT Next [ i ] [ j ] = ...
Count sequences of length K having each term divisible by its preceding term | Stores the factors of i - th element in v [ i ] ; Function to find all the factors of N ; Iterate upto sqrt ( N ) ; Function to return the count of sequences of length K having all terms divisible by its preceding term ; Calculate factors of...
vp = [ [ ] for i in range ( 2009 ) ] NEW_LINE def finding_factors ( n ) : NEW_LINE INDENT i = 1 NEW_LINE a = 0 NEW_LINE global vp NEW_LINE while ( i * i <= n ) : NEW_LINE INDENT if ( n % i == 0 ) : NEW_LINE INDENT if ( i * i == n ) : NEW_LINE INDENT vp [ n ] . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT vp [ n ...
Largest possible square submatrix with maximum AND value | Function to calculate and return the length of square submatrix with maximum AND value ; Extract dimensions ; Auxiliary array Initialize auxiliary array ; c : Stores the maximum value in the matrix p : Stores the number of elements in the submatrix having maxim...
def MAX_value ( arr ) : NEW_LINE INDENT row = len ( arr ) NEW_LINE col = len ( arr ) NEW_LINE dp = [ [ 0 for i in range ( col ) ] for j in range ( row ) ] NEW_LINE i , j = 0 , 0 NEW_LINE c , p = arr [ 0 ] [ 0 ] , 0 NEW_LINE d = row NEW_LINE for i in range ( d ) : NEW_LINE INDENT for j in range ( d ) : NEW_LINE INDENT i...
Smallest power of 2 consisting of N digits | Python3 program to implement the above approach ; Function to return smallest power of 2 with N digits ; Iterate through all powers of 2 ; Driver Code
from math import log10 , log NEW_LINE def smallestNum ( n ) : NEW_LINE INDENT res = 1 NEW_LINE i = 2 NEW_LINE while ( True ) : NEW_LINE INDENT length = int ( log10 ( i ) + 1 ) NEW_LINE if ( length == n ) : NEW_LINE INDENT return int ( log ( i ) // log ( 2 ) ) NEW_LINE DEDENT i *= 2 NEW_LINE DEDENT DEDENT n = 4 NEW_LINE...
Maximum weighted edge in path between two nodes in an N | Python3 implementation to find the maximum weighted edge in the simple path between two nodes in N - ary Tree ; Depths of Nodes ; Parent at every 2 ^ i level ; Maximum node at every 2 ^ i level ; Graph that stores destinations and its weight ; Function to traver...
import math NEW_LINE N = 100005 ; NEW_LINE level = [ 0 for i in range ( N ) ] NEW_LINE LG = 20 ; NEW_LINE dp = [ [ 0 for j in range ( N ) ] for i in range ( LG ) ] NEW_LINE mx = [ [ 0 for j in range ( N ) ] for i in range ( LG ) ] NEW_LINE v = [ [ ] for i in range ( N ) ] NEW_LINE n = 0 NEW_LINE def dfs_lca ( a , par ,...
Count full nodes in a Binary tree ( Iterative and Recursive ) | A binary tree Node has data , pointer to left child and a pointer to right child ; Function to get the count of full Nodes in a binary tree ; Driver code ; 2 / \ 7 5 \ \ 6 9 / \ / 1 11 4 Let us create Binary Tree as shown
class newNode ( ) : 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 getfullCount ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT res = 0 NEW_LINE if ( root . le...
Count Possible Decodings of a given Digit Sequence in O ( N ) time and Constant Auxiliary space | A Dynamic programming based function to count decodings in digit sequence ; For base condition "01123" should return 0 ; Using last two calculated values , calculate for ith index ; Change boolean to int ; Return the requi...
def countDecodingDP ( digits , n ) : NEW_LINE INDENT if ( digits [ 0 ] == '0' ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT count0 = 1 ; count1 = 1 ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dig1 = 0 ; dig3 = 0 ; NEW_LINE if ( digits [ i - 1 ] != '0' ) : NEW_LINE INDENT dig1 = 1 ; NEW_LINE DEDENT if ( d...
Maximum of all distances to the nearest 1 cell from any 0 cell in a Binary matrix | Function to find the maximum distance ; Set up top row and left column ; Pass one : top left to bottom right ; Check if there was no " One " Cell ; Set up top row and left column ; Past two : bottom right to top left ; Driver code
def maxDistance ( grid ) : NEW_LINE INDENT if ( len ( grid ) == 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT N = len ( grid ) NEW_LINE INF = 1000000 NEW_LINE if grid [ 0 ] [ 0 ] == 1 : NEW_LINE INDENT grid [ 0 ] [ 0 ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT grid [ 0 ] [ 0 ] = INF NEW_LINE DEDENT for i in range (...
Minimize total cost without repeating same task in two consecutive iterations | Function to return the minimum cost for N iterations ; Construct the dp table ; 1 st row of dp table will be equal to the 1 st of cost matrix ; Iterate through all the rows ; To iterate through the columns of current row ; Initialize val as...
def findCost ( cost_mat , N , M ) : NEW_LINE INDENT dp = [ [ 0 ] * M for _ in range ( M ) ] NEW_LINE dp [ 0 ] = cost_mat [ 0 ] NEW_LINE for row in range ( 1 , N ) : NEW_LINE INDENT for curr_col in range ( M ) : NEW_LINE INDENT val = 999999999 NEW_LINE for prev_col in range ( M ) : NEW_LINE INDENT if curr_col != prev_co...
Split the given string into Primes : Digit DP | Function to precompute all the primes upto 1000000 and store it in a set using Sieve of Eratosthenes ; Here str ( ) is used for converting int to string ; A function to find the minimum number of segments the given string can be divided such that every segment is a prime ...
def getPrimesFromSeive ( primes ) : NEW_LINE INDENT prime = [ True ] * ( 1000001 ) NEW_LINE prime [ 0 ] , prime [ 1 ] = False , False NEW_LINE i = 2 NEW_LINE while ( i * i <= 1000000 ) : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT for j in range ( i * i , 1000001 , i ) : NEW_LINE INDENT prime [ j ] = F...
Connect Nodes at same Level ( Level Order Traversal ) | connect nodes at same level using level order traversal ; Node class ; set nextRight of all nodes of a tree ; null marker to represent end of current level ; do level order of tree using None markers ; next element in queue represents next node at current level ; ...
import sys NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE self . nextRight = None NEW_LINE DEDENT def __str__ ( self ) : NEW_LINE INDENT return ' { } ' . format ( self . data ) NEW_LINE DEDENT DEDE...
Number of ways to convert a character X to a string Y | Python3 implementation of the approach ; Function to find the modular - inverse ; While power > 1 ; Updating s and a ; Updating power ; Return the final answer ; Function to return the count of ways ; To store the final answer ; To store pre - computed factorials ...
MOD = 1000000007 ; NEW_LINE def modInv ( a , p = MOD - 2 ) : NEW_LINE INDENT s = 1 ; NEW_LINE while ( p != 1 ) : NEW_LINE INDENT if ( p % 2 ) : NEW_LINE INDENT s = ( s * a ) % MOD ; NEW_LINE DEDENT a = ( a * a ) % MOD ; NEW_LINE p //= 2 ; NEW_LINE DEDENT return ( a * s ) % MOD ; NEW_LINE DEDENT def findCnt ( x , y ) : ...
Find the Largest divisor Subset in the Array | Function to find the required subsequence ; Sort the array ; Keep a count of the length of the subsequence and the previous element Set the initial values ; Maximum length of the subsequence and the last element ; Run a loop for every element ; Check for all the divisors ;...
def findSubSeq ( arr , n ) : NEW_LINE INDENT arr . sort ( ) ; NEW_LINE count = [ 1 ] * n ; NEW_LINE prev = [ - 1 ] * n ; NEW_LINE max = 0 ; NEW_LINE maxprev = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ i ] % arr [ j ] == 0 and count [ j ] + 1 ...
Minimum number of integers required such that each Segment contains at least one of them | Function to compute minimum number of points which cover all segments ; Sort the list of tuples by their second element . ; To store the solution ; Iterate over all the segments ; Get the start point of next segment ; Loop over a...
def minPoints ( points ) : NEW_LINE INDENT points . sort ( key = lambda x : x [ 1 ] ) NEW_LINE coordinates = [ ] NEW_LINE i = 0 NEW_LINE while i < n : NEW_LINE INDENT seg = points [ i ] [ 1 ] NEW_LINE coordinates . append ( seg ) NEW_LINE p = i + 1 NEW_LINE if p >= n : NEW_LINE INDENT break NEW_LINE DEDENT arrived = po...
Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Python3 implementation of the approach ; Function to find the minimum required sum using dynamic programming ; dp [ i ] [ j ] = minimum val of accommodation till j 'th index of the string using i+1 number of buckets. Final ans will be in dp[n-1][...
import sys NEW_LINE def solve ( Str , K ) : NEW_LINE INDENT n = len ( Str ) NEW_LINE dp = [ [ 0 for i in range ( n ) ] for j in range ( K ) ] NEW_LINE if ( n < K ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT elif ( n == K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT zeroes = 0 NEW_LINE ones = 0 NEW_LINE for i in range...
Queries for bitwise AND in the index range [ L , R ] of the given array | Python3 implementation of the approach ; Array to store bit - wise prefix count ; Function to find the prefix sum ; Loop for each bit ; Loop to find prefix count ; Function to answer query ; To store the answer ; Loop for each bit ; To store the ...
import numpy as np NEW_LINE MAX = 100000 NEW_LINE bitscount = 32 NEW_LINE prefix_count = np . zeros ( ( bitscount , MAX ) ) ; NEW_LINE def findPrefixCount ( arr , n ) : NEW_LINE INDENT for i in range ( 0 , bitscount ) : NEW_LINE INDENT prefix_count [ i ] [ 0 ] = ( ( arr [ 0 ] >> i ) & 1 ) ; NEW_LINE for j in range ( 1 ...
Longest path in a directed Acyclic graph | Dynamic Programming | Function to traverse the DAG and apply Dynamic Programming to find the longest path ; Mark as visited ; Traverse for all its children ; If not visited ; Store the max of the paths ; Function to add an edge ; Function that returns the longest path ; Dp arr...
def dfs ( node , adj , dp , vis ) : NEW_LINE INDENT vis [ node ] = True NEW_LINE for i in range ( 0 , len ( adj [ node ] ) ) : NEW_LINE INDENT if not vis [ adj [ node ] [ i ] ] : NEW_LINE INDENT dfs ( adj [ node ] [ i ] , adj , dp , vis ) NEW_LINE DEDENT dp [ node ] = max ( dp [ node ] , 1 + dp [ adj [ node ] [ i ] ] )...
Largest subset of rectangles such that no rectangle fit in any other rectangle | Recursive function to get the largest subset ; Base case when it exceeds ; If the state has been visited previously ; Initialize ; No elements in subset yet ; First state which includes current index ; Second state which does not include c...
def findLongest ( a , n , present , previous ) : NEW_LINE INDENT if present == n : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif previous != - 1 : NEW_LINE INDENT if dp [ present ] [ previous ] != - 1 : NEW_LINE INDENT return dp [ present ] [ previous ] NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE if previous == - 1 : NEW_L...
Maximum length subsequence such that adjacent elements in the subsequence have a common factor | Python3 implementation of the above approach ; to compute least prime divisor of i ; Function that returns the maximum length subsequence such that adjacent elements have a common factor . ; Initialize dp array with 1. ; p ...
import math as mt NEW_LINE N = 100005 NEW_LINE MAX = 1000002 NEW_LINE lpd = [ 0 for i in range ( MAX ) ] NEW_LINE def preCompute ( ) : NEW_LINE INDENT lpd [ 0 ] , lpd [ 1 ] = 1 , 1 NEW_LINE for i in range ( 2 , mt . ceil ( mt . sqrt ( MAX ) ) ) : NEW_LINE INDENT for j in range ( 2 * i , MAX , i ) : NEW_LINE INDENT if (...
Number of ways to partition a string into two balanced subsequences | For maximum length of input string ; Declaring the DP table ; Function to calculate the number of valid assignments ; Return 1 if both subsequences are balanced ; Increment the count if it is an opening bracket ; Decrement the count if it a closing b...
MAX = 10 NEW_LINE F = [ [ [ - 1 for i in range ( MAX ) ] for j in range ( MAX ) ] for k in range ( MAX ) ] NEW_LINE def noOfAssignments ( S , n , i , c_x , c_y ) : NEW_LINE INDENT if F [ i ] [ c_x ] [ c_y ] != - 1 : NEW_LINE INDENT return F [ i ] [ c_x ] [ c_y ] NEW_LINE DEDENT if i == n : NEW_LINE INDENT F [ i ] [ c_x...
Gould 's Sequence | Utility function to count odd numbers in ith row of Pascals 's triangle ; Initialize count as zero ; Return 2 ^ count ; Function to generate gould 's Sequence ; loop to generate gould 's Sequence up to n ; Driver code ; Get n ; Function call
def countOddNumber ( row_num ) : NEW_LINE INDENT count = 0 NEW_LINE while row_num != 0 : NEW_LINE INDENT count += row_num & 1 NEW_LINE row_num >>= 1 NEW_LINE DEDENT return ( 1 << count ) NEW_LINE DEDENT def gouldSequence ( n ) : NEW_LINE INDENT for row_num in range ( 0 , n ) : NEW_LINE INDENT print ( countOddNumber ( r...
Count numbers ( smaller than or equal to N ) with given digit sum | N can be max 10 ^ 18 and hence digitsum will be 162 maximum . ; If sum_so_far equals to given sum then return 1 else 0 ; Our constructed number should not become greater than N . ; If tight is true then it will also be true for ( i + 1 ) digit . ; Driv...
def solve ( i , tight , sum_so_far , Sum , number , length ) : NEW_LINE INDENT if i == length : NEW_LINE INDENT if sum_so_far == Sum : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT ans = dp [ i ] [ tight ] [ sum_so_far ] NEW_LINE if ans != - 1 : NEW_LINE INDENT return a...
Longest dividing subsequence | lds ( ) returns the length of the longest dividing subsequence in arr [ ] of size n ; Compute optimized lds values in bottom up manner ; Return maximum value in lds [ ] ; Driver Code
def lds ( arr , n ) : NEW_LINE INDENT lds = [ 0 for i in range ( n ) ] NEW_LINE lds [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT lds [ i ] = 1 NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( lds [ j ] != 0 and arr [ i ] % arr [ j ] == 0 ) : NEW_LINE INDENT lds [ i ] = max ( lds [ i ] , lds [ j ] + 1 )...
Memoization ( 1D , 2D and 3D ) | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] memoization applied in recursive solution ; base case ; if the same state has already been computed ; if equal , then we store the value of the function call ; store it in arr to avoid further repetitive work in future functi...
def lcs ( X , Y , Z , m , n , o ) : NEW_LINE INDENT global arr NEW_LINE if ( m == 0 or n == 0 or o == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( arr [ m - 1 ] [ n - 1 ] [ o - 1 ] != - 1 ) : NEW_LINE INDENT return arr [ m - 1 ] [ n - 1 ] [ o - 1 ] NEW_LINE DEDENT if ( X [ m - 1 ] == Y [ n - 1 ] and Y [ n - 1 ] ...
Find the probability of reaching all points after N moves from point N | Function to calculate the probabilities ; Array where row represent the pass and the column represents the points on the line ; Initially the person can reach left or right with one move ; Calculate probabilities for N - 1 moves ; When the person ...
def printProbabilities ( n , left ) : NEW_LINE INDENT right = 1 - left ; NEW_LINE arr = [ [ 0 for j in range ( 2 * n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE arr [ 1 ] [ n + 1 ] = right ; NEW_LINE arr [ 1 ] [ n - 1 ] = left ; NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , 2 * n + 1 ) : ...
Check if it is possible to reach a number by making jumps of two given length | Python3 implementation of the approach ; Function to perform BFS traversal to find minimum number of step needed to reach x from K ; Calculate GCD of d1 and d2 ; If position is not reachable return - 1 ; Queue for BFS ; Hash Table for marki...
from math import gcd as __gcd NEW_LINE from collections import deque as queue NEW_LINE def minStepsNeeded ( k , d1 , d2 , x ) : NEW_LINE INDENT gcd = __gcd ( d1 , d2 ) NEW_LINE if ( ( k - x ) % gcd != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT q = queue ( ) NEW_LINE visited = dict ( ) NEW_LINE q . appendleft ( [ ...
Tiling with Dominoes | Python 3 program to find no . of ways to fill a 3 xn board with 2 x1 dominoes . ; Driver Code
def countWays ( n ) : NEW_LINE INDENT A = [ 0 ] * ( n + 1 ) NEW_LINE B = [ 0 ] * ( n + 1 ) NEW_LINE A [ 0 ] = 1 NEW_LINE A [ 1 ] = 0 NEW_LINE B [ 0 ] = 0 NEW_LINE B [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT A [ i ] = A [ i - 2 ] + 2 * B [ i - 1 ] NEW_LINE B [ i ] = A [ i - 1 ] + B [ i - 2 ] NEW_...
Newman | Recursive function to find the n - th element of sequence ; Driver code
def sequence ( n ) : NEW_LINE INDENT if n == 1 or n == 2 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return sequence ( sequence ( n - 1 ) ) + sequence ( n - sequence ( n - 1 ) ) ; NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT n = 10 NEW_LINE print sequence ( n ) NEW_LINE DEDENT if __name__...
Connect nodes at same level | A binary tree node ; Sets the nextRight of root and calls connectRecur ( ) for other nodes ; Set the nextRight for root ; Set the next right for rest of the nodes ( other than root ) ; Set next right of all descendents of p . Assumption : p is a compete binary tree ; Base case ; Set the ne...
class newnode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = self . nextRight = None NEW_LINE DEDENT DEDENT def connect ( p ) : NEW_LINE INDENT p . nextRight = None NEW_LINE connectRecur ( p ) NEW_LINE DEDENT def connectRecur ( p ) : NEW_LINE IN...
Counting pairs when a person can form pair with at most one | Number of ways in which participant can take part . ; Base condition ; A participant can choose to consider ( 1 ) Remains single . Number of people reduce to ( x - 1 ) ( 2 ) Pairs with one of the ( x - 1 ) others . For every pairing , number of people reduce...
def numberOfWays ( x ) : NEW_LINE INDENT if x == 0 or x == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ( numberOfWays ( x - 1 ) + ( x - 1 ) * numberOfWays ( x - 2 ) ) NEW_LINE DEDENT DEDENT x = 3 NEW_LINE print ( numberOfWays ( x ) ) NEW_LINE
Counting pairs when a person can form pair with at most one | Python program to find Number of ways in which participant can take part . ; Driver code
def numberOfWays ( x ) : NEW_LINE INDENT dp = [ ] NEW_LINE dp . append ( 1 ) NEW_LINE dp . append ( 1 ) NEW_LINE for i in range ( 2 , x + 1 ) : NEW_LINE INDENT dp . append ( dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ) NEW_LINE DEDENT return ( dp [ x ] ) NEW_LINE DEDENT x = 3 NEW_LINE print ( numberOfWays ( x ) ) NEW_LINE
Longest Repeated Subsequence | Refer https : www . geeksforgeeks . org / longest - repeating - subsequence / for complete code . This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; Create and initialize DP table ; Fill dp table ( similar to LCS loops...
def findLongestRepeatingSubSeq ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE dp = [ [ 0 for k in range ( n + 1 ) ] for l in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ j - 1 ] and i != j ) : NEW_LINE INDENT dp ...
Number of ways to arrange N items under given constraints | Python3 program to find number of ways to arrange items under given constraint ; method returns number of ways with which items can be arranged ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored...
import numpy as np NEW_LINE def waysToArrange ( N , K , k ) : NEW_LINE INDENT C = np . zeros ( ( N + 1 , N + 1 ) ) NEW_LINE for i in range ( N + 1 ) : NEW_LINE INDENT for j in range ( i + 1 ) : NEW_LINE INDENT if ( j == 0 or j == i ) : NEW_LINE INDENT C [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT C [ i ] [ j...
Minimum cells required to reach destination with jumps equal to cell values | Python3 implementation to count minimum cells required to be covered to reach destination ; function to count minimum cells required to be covered to reach destination ; to store min cells required to be covered to reach a particular cell ; b...
SIZE = 100 NEW_LINE MAX = 10000000 NEW_LINE def minCells ( mat , m , n ) : NEW_LINE INDENT dp = [ [ MAX for i in range ( n ) ] for i in range ( m ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( m ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT if ( dp [ i ] [ j ] != MAX and ( j + mat [ i ] [ j ] ) ...
Find longest bitonic sequence such that increasing and decreasing parts are from two different arrays | Python3 to find largest bitonic sequence such that ; utility Binary search ; function to find LIS in reverse form ; leN = 1 it will always poto empty location ; new smallest value ; arr [ i ] wants to extend largest ...
res = [ ] NEW_LINE def GetCeilIndex ( arr , T , l , r , key ) : NEW_LINE INDENT while ( r - l > 1 ) : NEW_LINE INDENT m = l + ( r - l ) // 2 ; NEW_LINE if ( arr [ T [ m ] ] >= key ) : NEW_LINE INDENT r = m NEW_LINE DEDENT else : NEW_LINE INDENT l = m NEW_LINE DEDENT DEDENT return r NEW_LINE DEDENT def LIS ( arr , n ) :...
Maximize the binary matrix by filpping submatrix once | Python 3 program to find maximum number of ones after one flipping in Binary Matrix ; Return number of ones in square submatrix of size k x k starting from ( x , y ) ; Return maximum number of 1 s after flipping a submatrix ; Precomputing the number of 1 s ; Findi...
R = 3 NEW_LINE C = 3 NEW_LINE def cal ( ones , x , y , k ) : NEW_LINE INDENT return ( ones [ x + k - 1 ] [ y + k - 1 ] - ones [ x - 1 ] [ y + k - 1 ] - ones [ x + k - 1 ] [ y - 1 ] + ones [ x - 1 ] [ y - 1 ] ) NEW_LINE DEDENT def sol ( mat ) : NEW_LINE INDENT ans = 0 NEW_LINE ones = [ [ 0 for i in range ( C + 1 ) ] for...
Level with maximum number of nodes | Python3 implementation to find the level having Maximum number of Nodes Importing Queue ; Helper class that allocates a new node with the given data and None left and right pointers . ; function to find the level having Maximum number of Nodes ; Current level ; Maximum Nodes at same...
from queue import Queue NEW_LINE class newNode : 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 maxNodeLevel ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT ...
Minimum steps to minimize n as per given condition | A tabulation based solution in Python3 ; driver program
def getMinSteps ( n ) : NEW_LINE INDENT table = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT table [ i ] = n - i NEW_LINE DEDENT for i in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( not ( i % 2 ) ) : NEW_LINE INDENT table [ i // 2 ] = min ( table [ i ] + 1 , table [ i // 2 ] ) NEW_LINE DEDENT ...
How to solve a Dynamic Programming Problem ? | Returns the number of arrangements to form 'n ; Base case
' NEW_LINE def solve ( n ) : NEW_LINE INDENT if n < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( solve ( n - 1 ) + solve ( n - 3 ) + solve ( n - 5 ) ) NEW_LINE DEDENT
Maximum points collected by two persons allowed to meet once | Python program to find maximum points that can be collected by two persons in a matrix . ; To store points collected by Person P1 when he / she begins journy from start and from end . ; To store points collected by Person P2 when he / she begins journey fro...
M = 3 NEW_LINE N = 3 NEW_LINE def findMaxPoints ( A ) : NEW_LINE INDENT P1S = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE P1E = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE P2S = [ [ 0 for i in range ( N + 2 ) ] for j in range ( M + 2 ) ] NEW_LINE P2E = [ [ 0 for i in ra...
Longest subsequence such that difference between adjacents is one | Function to find the length of longest subsequence ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Start traversing the given array ; Compare with all the previous elements ; If the element is consecutive then consider th...
def longestSubseqWithDiffOne ( arr , n ) : NEW_LINE INDENT dp = [ 1 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ i ] == arr [ j ] + 1 ) or ( arr [ i ] == arr [ j ] - 1 ) ) : NEW_LINE INDENT dp [ i ] = max ( dp [ i ] , dp [ j ] + 1 ) NEW_LINE ...
Non | A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Returns count of ways to connect n points on a circle such that no two connecting lines cross each other and every point is connected ...
def catalanDP ( n ) : NEW_LINE INDENT catalan = [ 1 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT catalan [ i ] = 0 NEW_LINE for j in range ( i ) : NEW_LINE INDENT catalan [ i ] += ( catalan [ j ] * catalan [ i - j - 1 ] ) NEW_LINE DEDENT DEDENT return catalan [ n ] NEW_LINE DEDENT ...
Ways to arrange Balls such that adjacent balls are of different types | Python3 program to count number of ways to arrange three types of balls such that no two balls of same color are adjacent to each other ; table to store to store results of subproblems ; Returns count of arrangements where last placed ball is ' las...
MAX = 100 ; NEW_LINE dp = [ [ [ [ - 1 ] * 4 for i in range ( MAX ) ] for j in range ( MAX ) ] for k in range ( MAX ) ] ; NEW_LINE ' NEW_LINE def countWays ( p , q , r , last ) : NEW_LINE INDENT if ( p < 0 or q < 0 or r < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( p == 1 and q == 0 and r == 0 and last == 0 ) ...
Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Base cases ; countDer ( n ) = ( n - 1 ) [ countDer ( n - 1 ) + der ( n - 2 ) ] ; Driver Code
def countDer ( n ) : NEW_LINE INDENT if ( n == 1 ) : return 0 NEW_LINE if ( n == 2 ) : return 1 NEW_LINE return ( n - 1 ) * ( countDer ( n - 1 ) + countDer ( n - 2 ) ) NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count ▁ of ▁ Derangements ▁ is ▁ " , countDer ( n ) ) NEW_LINE
Count Derangements ( Permutation such that no element appears in its original position ) | Function to count derangements ; Create an array to store counts for subproblems ; Base cases ; Fill der [ 0. . n ] in bottom up manner using above recursive formula ; Return result for n ; Driver Code
def countDer ( n ) : NEW_LINE INDENT der = [ 0 for i in range ( n + 1 ) ] NEW_LINE der [ 1 ] = 0 NEW_LINE der [ 2 ] = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) NEW_LINE DEDENT return der [ n ] NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count ▁ of ▁...
Find number of solutions of a linear equation of n variables | Returns count of solutions for given rhs and coefficients coeff [ 0. . . n - 1 ] ; Create and initialize a table to store results of subproblems ; Fill table in bottom up manner ; Driver Code
def countSol ( coeff , n , rhs ) : NEW_LINE INDENT dp = [ 0 for i in range ( rhs + 1 ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( coeff [ i ] , rhs + 1 ) : NEW_LINE INDENT dp [ j ] += dp [ j - coeff [ i ] ] NEW_LINE DEDENT DEDENT return dp [ rhs ] NEW_LINE DEDENT coeff = [ ...
Largest value in each level of Binary Tree | Set | Python program to print largest value on each level of binary tree ; Helper function that allocates a new node with the given data and None left and right pointers . ; put in the data ; function to find largest values ; if tree is empty ; push root to the queue ' q ' ;...
INT_MIN = - 2147483648 NEW_LINE class newNode : 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 largestValueInEachLevel ( root ) : NEW_LINE INDENT if ( not root ) : NEW_LINE INDENT return NEW_LINE DEDEN...
Populate Inorder Successor for all nodes | Tree node ; Set next of p and all descendants of p by traversing them in reverse Inorder ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; First set the next pointer in right subtree ; Set the next as previously visited node in rever...
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 self . next = None NEW_LINE DEDENT DEDENT next = None NEW_LINE def populateNext ( p ) : NEW_LINE INDENT global next NEW_LINE if ( p != None ) : NEW_LINE INDENT...
Maximum Product Cutting | DP | The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver program to test above functions
def maxProd ( n ) : NEW_LINE INDENT if ( n == 2 or n == 3 ) : NEW_LINE INDENT return ( n - 1 ) NEW_LINE DEDENT res = 1 NEW_LINE while ( n > 4 ) : NEW_LINE INDENT n -= 3 ; NEW_LINE res *= 3 ; NEW_LINE DEDENT return ( n * res ) NEW_LINE DEDENT print ( " Maximum ▁ Product ▁ is ▁ " , maxProd ( 10 ) ) ; NEW_LINE
Dice Throw | DP | The main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The e...
def findWays ( m , n , x ) : NEW_LINE INDENT table = [ [ 0 ] * ( x + 1 ) for i in range ( n + 1 ) ] NEW_LINE for j in range ( 1 , min ( m + 1 , x + 1 ) ) : NEW_LINE INDENT table [ 1 ] [ j ] = 1 NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , x + 1 ) : NEW_LINE INDENT for k in range (...
Dice Throw | DP | * Count ways * * @ param f * @ param d * @ param s * @ return ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are nev...
def findWays ( f , d , s ) : NEW_LINE INDENT mem = [ [ 0 for i in range ( s + 1 ) ] for j in range ( d + 1 ) ] NEW_LINE mem [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , d + 1 ) : NEW_LINE INDENT for j in range ( 1 , s + 1 ) : NEW_LINE INDENT mem [ i ] [ j ] = mem [ i ] [ j - 1 ] + mem [ i - 1 ] [ j - 1 ] NEW_LINE if j...
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which su...
import sys NEW_LINE def findMinInsertions ( str , l , h ) : NEW_LINE INDENT if ( l > h ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( l == h ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( l == h - 1 ) : NEW_LINE INDENT return 0 if ( str [ l ] == str [ h ] ) else 1 NEW_LINE DEDENT if ( str [ l ] == str...
Longest Palindromic Subsequence | DP | A utility function to get max of two egers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and l...
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 ] =...
Smallest value in each level of Binary Tree | Python3 program to print smallest element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Inorder Traversal Search minimum element in each level and store it into vector array . ; height of tree for the size of vector array ; vector for store a...
INT_MAX = 1000006 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def heightoftree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT left = he...
Smallest value in each level of Binary Tree | Python3 program to prminimum element in each level of binary tree . Importing Queue ; Utility class to create a new tree node ; return height of tree p ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order ...
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def heightoftree ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = heightoft...
Count occurrences of a string that can be constructed from another given string | Python3 implementation of the above approach ; Function to find the count ; Initialize hash for both strings ; hash the frequency of letters of str1 ; hash the frequency of letters of str2 ; Find the count of str2 constructed from str1 ; ...
import sys NEW_LINE def findCount ( str1 , str2 ) : NEW_LINE INDENT len1 = len ( str1 ) NEW_LINE len2 = len ( str2 ) NEW_LINE ans = sys . maxsize NEW_LINE hash1 = [ 0 ] * 26 NEW_LINE hash2 = [ 0 ] * 26 NEW_LINE for i in range ( 0 , len1 ) : NEW_LINE INDENT hash1 [ ord ( str1 [ i ] ) - 97 ] = hash1 [ ord ( str1 [ i ] ) ...
Check if a string is the typed name of the given name | Check if the character is vowel or not ; Returns true if ' typed ' is a typed name given str ; Traverse through all characters of str ; If current characters do not match ; If not vowel , simply move ahead in both ; Count occurrences of current vowel in str ; Coun...
def isVowel ( c ) : NEW_LINE INDENT vowel = " aeiou " NEW_LINE for i in range ( len ( vowel ) ) : NEW_LINE INDENT if ( vowel [ i ] == c ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT def printRLE ( str , typed ) : NEW_LINE INDENT n = len ( str ) NEW_LINE m = len ( typed ) NEW_LINE j...
Get Level of a node in a Binary Tree | Python3 program to Get Level of a node in a Binary Tree Helper function that allocates a new node with the given data and None left and right pairs . ; Constructor to create a new node ; Helper function for getLevel ( ) . It returns level of the data if data is present in tree , o...
class newNode : 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 getLevelUtil ( node , data , level ) : NEW_LINE INDENT if ( node == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( node . data == ...
Program to replace a word with asterisks in a sentence | Function takes two parameter ; Break down sentence by ' ▁ ' spaces and store each individual word in a different list ; A new string to store the result ; Creating the censor which is an asterisks " * " text of the length of censor word ; count variable to access...
def censor ( text , word ) : NEW_LINE INDENT word_list = text . split ( ) NEW_LINE result = ' ' NEW_LINE stars = ' * ' * len ( word ) NEW_LINE count = 0 NEW_LINE index = 0 ; NEW_LINE for i in word_list : NEW_LINE INDENT if i == word : NEW_LINE INDENT word_list [ index ] = stars NEW_LINE DEDENT index += 1 NEW_LINE DEDEN...
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 ; Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the...
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 ) ...
Longest Substring containing '1' | Function to find length of longest substring containing '1 ; Count the number of contiguous 1 's ; Driver Code
' NEW_LINE def maxlength ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE ans = 0 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT count = 1 NEW_LINE j = i + 1 NEW_LINE while ( j <= n - 1 and s [ j ] == '1' ) : NEW_LINE INDENT count += 1 NEW_LINE j += 1 NEW_LINE DEDENT ans = max (...
Generate all possible strings formed by replacing letters with given respective symbols | Function to generate all possible string by replacing the characters with mapped symbols ; Base Case ; Function call with the P - th character not replaced ; Replace the P - th character ; Function call with the P - th character r...
def generateLetters ( S , P , M ) : NEW_LINE INDENT if ( P == len ( S ) ) : NEW_LINE INDENT print ( S ) ; NEW_LINE return NEW_LINE DEDENT generateLetters ( S , P + 1 , M ) ; NEW_LINE S = S . replace ( S [ P ] , M [ S [ P ] ] ) NEW_LINE generateLetters ( S , P + 1 , M ) ; NEW_LINE DEDENT S = " aBc " ; NEW_LINE M = { } ;...
Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same | Python3 program for the above approach ; Function to check if S contains any pair of adjacent characters that are same ; Traverse the String S ; If current pair of adjacent characters are the same ; Return true ...
import sys NEW_LINE ansSwaps = 0 NEW_LINE def check ( S ) : NEW_LINE INDENT for i in range ( 1 , len ( S ) ) : NEW_LINE INDENT if ( S [ i - 1 ] == S [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT def minimumSwaps ( S , swaps , idx ) : NEW_LINE INDENT global ansSwaps NEW_LINE i...
Get level of a node in binary tree | iterative approach | Python3 program to find closest value in Binary search Tree ; Helper function that allocates a new node with the given data and None left and right poers . ; utility function to return level of given node ; extra None is appended to keep track of all the nodes t...
_MIN = - 2147483648 NEW_LINE _MAX = 2147483648 NEW_LINE class getnode : 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 getlevel ( root , data ) : NEW_LINE INDENT q = [ ] NEW_LINE level = 1 NEW_LINE q ....
Lexicographically smallest Palindromic Path in a Binary Tree | Struct binary tree node ; Function to check if the is palindrome or not ; Function to find the lexicographically smallest palindromic path in the Binary Tree ; Base case ; Append current node 's data to the string ; Check if a node is leaf or not ; Check f...
class Node : NEW_LINE INDENT def __init__ ( self , d ) : NEW_LINE INDENT self . data = d NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def checkPalindrome ( s ) : NEW_LINE INDENT low , high = 0 , len ( s ) - 1 NEW_LINE while ( low < high ) : NEW_LINE INDENT if ( s [ low ] != s [ high ]...
Find mirror of a given node in Binary tree | Python3 program to find the mirror node in Binary tree ; A binary tree node has data , reference to left child and a reference to right child ; recursive function to find mirror ; If any of the node is none then node itself and decendent have no mirror , so return none , no ...
class Node : NEW_LINE INDENT def __init__ ( self , key , lchild = None , rchild = None ) : NEW_LINE INDENT self . key = key NEW_LINE self . lchild = None NEW_LINE self . rchild = None NEW_LINE DEDENT DEDENT def findMirrorRec ( target , left , right ) : NEW_LINE INDENT if left == None or right == None : NEW_LINE INDENT ...
Smallest substring with each letter occurring both in uppercase and lowercase | python 3 program for the above approach ; Function to check if the current string is balanced or not ; For every character , check if there exists uppercase as well as lowercase characters ; Function to find smallest length substring in the...
import sys NEW_LINE def balanced ( small , caps ) : NEW_LINE INDENT for i in range ( 26 ) : NEW_LINE INDENT if ( small [ i ] != 0 and ( caps [ i ] == 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( ( small [ i ] == 0 ) and ( caps [ i ] != 0 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT return 1 NEW_LINE...
Convert given string to another by minimum replacements of subsequences by its smallest character | Function to return the minimum number of operation ; Storing data ; Initialize both arrays ; Stores the index of character ; Filling str1array , convChar and hashmap convertMap . ; Not possible to convert ; Calculate res...
def transformString ( str1 , str2 ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE convChar = [ ] NEW_LINE str1array = [ ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT convChar . append ( [ ] ) NEW_LINE str1array . append ( [ ] ) NEW_LINE DEDENT convertMap = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT str1arra...
Find largest subtree having identical left and right subtrees | Helper class that allocates a new node with the given data and None left and right pointers . ; Sets maxSize to size of largest subtree with identical left and right . maxSize is set with size of the maximum sized subtree . It returns size of subtree roote...
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def largestSubtreeUtil ( root , Str , maxSize , maxNode ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT left = [ " " ] NE...
Smallest number containing all possible N length permutations using digits 0 to D | Initialize set to see if all the possible permutations are present in the min length string ; To keep min length string ; Generate the required string ; Iterate over all possible character ; Append to make a new string ; If the new stri...
visited = set ( ) NEW_LINE ans = [ ] NEW_LINE def dfs ( curr , D ) : NEW_LINE INDENT for c in range ( D ) : NEW_LINE INDENT c = str ( c ) NEW_LINE neighbour = curr + c NEW_LINE if neighbour not in visited : NEW_LINE INDENT visited . add ( neighbour ) NEW_LINE dfs ( neighbour [ 1 : ] , D ) NEW_LINE ans . append ( c ) NE...
Check if a string is a scrambled form of another string | Python3 program to check if a given string is a scrambled form of another string ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Check for the condition of anagram ; Check if ...
def isScramble ( S1 : str , S2 : str ) : NEW_LINE INDENT if len ( S1 ) != len ( S2 ) : NEW_LINE INDENT return False NEW_LINE DEDENT n = len ( S1 ) NEW_LINE if not n : NEW_LINE INDENT return True NEW_LINE DEDENT if S1 == S2 : NEW_LINE INDENT return True NEW_LINE DEDENT if sorted ( S1 ) != sorted ( S2 ) : NEW_LINE INDENT...
Smallest number possible by swapping adjacent even odd pairs | Function to return the smallest number possible ; Arrays to store odd and even digits in the order of their appearance in the given string ; Insert the odd and even digits ; pointer to odd digit ; pointer to even digit ; In case number of even and odd digit...
def findAns ( s ) : NEW_LINE INDENT odd = [ ] NEW_LINE even = [ ] NEW_LINE for c in s : NEW_LINE INDENT digit = int ( c ) NEW_LINE if ( digit & 1 ) : NEW_LINE INDENT odd . append ( digit ) NEW_LINE DEDENT else : NEW_LINE INDENT even . append ( digit ) NEW_LINE DEDENT DEDENT i = 0 NEW_LINE j = 0 NEW_LINE ans = " " NEW_L...
Program to Convert BCD number into Decimal number | Function to convert BCD to Decimal ; Iterating through the bits backwards ; Forming the equivalent digit ( 0 to 9 ) from the group of 4. ; Reinitialize all variables and compute the number ; Update the answer ; Reverse the number formed . ; Driver Code ; Function Call
def bcdToDecimal ( s ) : NEW_LINE INDENT length = len ( s ) ; NEW_LINE check = 0 ; NEW_LINE check0 = 0 ; NEW_LINE num = 0 ; NEW_LINE sum = 0 ; NEW_LINE mul = 1 ; NEW_LINE rev = 0 ; NEW_LINE for i in range ( length - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum += ( ord ( s [ i ] ) - ord ( '0' ) ) * mul ; NEW_LINE mul *= 2 ; N...
Find Count of Single Valued Subtrees | Utility function to create a new node ; This function increments count by number of single valued subtrees under root . It returns true if subtree under root is Singly , else false . ; Return False to indicate None ; Recursively count in left and right subtress also ; If any of th...
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 countSingleRec ( root , count ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return True NEW_LINE DEDENT left = countSingleRec ( root ...
Count minimum swap to make string palindrome | Function to Count minimum swap ; Counter to count minimum swap ; A loop which run in half string from starting ; Left pointer ; Right pointer ; A loop which run from right pointer to left pointer ; if both char same then break the loop if not same then we have to move righ...
def CountSwap ( s , n ) : NEW_LINE INDENT s = list ( s ) NEW_LINE count = 0 NEW_LINE ans = True NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT left = i NEW_LINE right = n - left - 1 NEW_LINE while left < right : NEW_LINE INDENT if s [ left ] == s [ right ] : NEW_LINE INDENT break NEW_LINE DEDENT else : NEW_LINE I...
Bitwise XOR of a Binary array | Function to return the bitwise XOR of all the binary strings ; Get max size and reverse each string Since we have to perform XOR operation on bits from right to left Reversing the string will make it easier to perform operation from left to right ; Add 0 s to the end of strings if needed...
import sys NEW_LINE def strBitwiseXOR ( arr , n ) : NEW_LINE INDENT result = " " NEW_LINE max_len = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT max_len = max ( max_len , len ( arr [ i ] ) ) NEW_LINE arr [ i ] = arr [ i ] [ : : - 1 ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT s = " " NEW_LINE for j i...
Count of sticks required to represent the given string | stick [ ] stores the count of matchsticks required to represent the alphabets ; number [ ] stores the count of matchsticks required to represent the numerals ; Function that return the count of sticks required to represent the given string ; For every char of the...
sticks = [ 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 ] ; NEW_LINE number = [ 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 ] ; NEW_LINE def countSticks ( string ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT ch = string [ i ...
Find the last remaining Character in the Binary String according to the given conditions | Python3 implementation of the above approach ; Converting string to array ; Delete counters for each to count the deletes ; Counters to keep track of characters left from each type ; Queue to simulate the process ; Initializing t...
from collections import deque ; NEW_LINE def remainingDigit ( S , N ) : NEW_LINE INDENT c = [ i for i in S ] NEW_LINE de = [ 0 , 0 ] NEW_LINE count = [ 0 , 0 ] NEW_LINE q = deque ( ) NEW_LINE for i in c : NEW_LINE INDENT x = 0 NEW_LINE if i == '1' : NEW_LINE INDENT x = 1 NEW_LINE DEDENT count [ x ] += 1 NEW_LINE q . ap...
Closest leaf to a given node in Binary Tree | Utility class to create a new node ; This function finds closest leaf to root . This distance is stored at * minDist . ; base case ; If this is a leaf node , then check if it is closer than the closest so far ; Recur for left and right subtrees ; This function finds if ther...
class newNode : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def findLeafDown ( root , lev , minDist ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left == None and root . ri...
Find the closest leaf in a Binary Tree | Python program to find closest leaf of a given key in binary tree ; A binary tree node ; A utility function to find distance of closest leaf of the tree rooted under given root ; Base Case ; Return minum of left and right plus one ; Returns destance of the closes leaf to a given...
INT_MAX = 2 ** 32 NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def closestDown ( root ) : NEW_LINE INDENT if root is None : NEW_LINE INDENT return INT_MAX NEW_LINE DEDENT if root . lef...
Find the time which is palindromic and comes after the given time | Function to return the required time ; To store the resultant time ; Hours are stored in h as integer ; Minutes are stored in m as integer ; Reverse of h ; Reverse of h as a string ; If MM < reverse of ( HH ) ; 0 is added if HH < 10 ; 0 is added if rev...
def getTime ( s , n ) : NEW_LINE INDENT res = " " NEW_LINE h = int ( s [ 0 : 2 ] ) ; NEW_LINE m = int ( s [ 3 : 5 ] ) ; NEW_LINE rev_h = ( h % 10 ) * 10 + ( ( h % 100 ) - ( h % 10 ) ) // 10 ; NEW_LINE rev_hs = str ( rev_h ) NEW_LINE temp = " " NEW_LINE if ( h == 23 and m >= 32 ) : NEW_LINE INDENT res = " - 1" ; NEW_LIN...
Count of sub | Function to return the count of valid sub - Strings ; Variable ans to store all the possible subStrings Initialize its value as total number of subStrings that can be formed from the given String ; Stores recent index of the characters ; If character is a update a 's index and the variable ans ; If char...
def CountSubString ( Str , n ) : NEW_LINE INDENT ans = ( n * ( n + 1 ) ) // 2 NEW_LINE a_index = 0 NEW_LINE b_index = 0 NEW_LINE c_index = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( Str [ i ] == ' a ' ) : NEW_LINE INDENT a_index = i + 1 NEW_LINE ans -= min ( b_index , c_index ) NEW_LINE DEDENT elif ( Str [ ...
Find the numbers of strings that can be formed after processing Q queries | Python3 program to implement above approach ; To store the size of string and number of queries ; To store parent and rank of ith place ; To store maximum interval ; Function for initialization ; Function to find parent ; Function to make union...
N = 2005 NEW_LINE mod = 10 ** 9 + 7 NEW_LINE n , q = 0 , 0 NEW_LINE par = [ 0 for i in range ( N ) ] NEW_LINE Rank = [ 0 for i in range ( N ) ] NEW_LINE m = dict ( ) NEW_LINE def initialize ( ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT Rank [ i ] , par [ i ] = 0 , i NEW_LINE DEDENT DEDENT def find ( ...
Iterative Search for a key ' x ' in Binary Tree | Iterative level order traversal based method to search in Binary Tree importing Queue ; Helper function that allocates a new node with the given data and None left and right pointers . ; An iterative process to search an element x in a given binary tree ; Base Case ; Cr...
from queue import Queue NEW_LINE class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = self . right = None NEW_LINE DEDENT DEDENT def iterativeSearch ( root , x ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT q = Q...