text
stringlengths
17
3.65k
code
stringlengths
70
5.84k
Length of Longest Balanced Subsequence | Python3 program to find length of the longest balanced subsequence ; Considering all balanced substrings of length 2 ; Considering all other substrings ; Driver Code
def maxLength ( s , n ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s [ i ] == ' ( ' and s [ i + 1 ] == ' ) ' ) : NEW_LINE INDENT dp [ i ] [ i + 1 ] = 2 NEW_LINE DEDENT DEDENT for l in range ( 2 , n ) : NEW_LINE INDENT i = - 1 NEW_L...
Maximum sum bitonic subarray | Function to find the maximum sum bitonic subarray . ; to store the maximum sum bitonic subarray ; Find the longest increasing subarray starting at i . ; Now we know that a [ i . . j ] is an increasing subarray . Remove non - positive elements from the left side as much as possible . ; Fin...
def maxSumBitonicSubArr ( arr , n ) : NEW_LINE INDENT max_sum = - 10 ** 9 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT j = i NEW_LINE while ( j + 1 < n and arr [ j ] < arr [ j + 1 ] ) : NEW_LINE INDENT j += 1 NEW_LINE DEDENT while ( i < j and arr [ i ] <= 0 ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT k = j ...
Smallest sum contiguous subarray | Python program to find the smallest sum contiguous subarray ; function to find the smallest sum contiguous subarray ; to store the minimum value that is ending up to the current index ; to store the minimum value encountered so far ; traverse the array elements ; if min_ending_here > ...
import sys NEW_LINE def smallestSumSubarr ( arr , n ) : NEW_LINE INDENT min_ending_here = sys . maxsize NEW_LINE min_so_far = sys . maxsize NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( min_ending_here > 0 ) : NEW_LINE INDENT min_ending_here = arr [ i ] NEW_LINE DEDENT else : NEW_LINE INDENT min_ending_here += a...
n | Python3 code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; If the Number is less than 6 return the number as it is . ; Call the function again and again the get the desired result . And convert the number to base 6. ; Decrease the Number by 1 and Call ans function to convert N to base 6 ; Driver code
def ans ( n ) : NEW_LINE INDENT if ( n < 6 ) : NEW_LINE INDENT return n NEW_LINE DEDENT return n % 6 + 10 * ( ans ( n // 6 ) ) - 1 NEW_LINE DEDENT def getSpecialNumber ( N ) : NEW_LINE INDENT return ans ( N ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 17 NEW_LINE answer = getSpecialNumber ( N...
Paper Cut into Minimum Number of Squares | Set 2 | Python3 program to find minimum number of squares to cut a paper using Dynamic Programming ; Returns min number of squares needed ; Initializing max values to vertical_min and horizontal_min ; N = 11 & M = 13 is a special case ; If the given rectangle is already a squa...
MAX = 300 NEW_LINE dp = [ [ 0 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def minimumSquare ( m , n ) : NEW_LINE INDENT vertical_min = 10000000000 NEW_LINE horizontal_min = 10000000000 NEW_LINE if n == 13 and m == 11 : NEW_LINE INDENT return 6 NEW_LINE DEDENT if m == 13 and n == 11 : NEW_LINE INDENT retu...
Number of n | Returns factorial of n ; returns nCr ; Driver code
def fact ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT res = res * i NEW_LINE DEDENT return res NEW_LINE DEDENT def nCr ( n , r ) : NEW_LINE INDENT return fact ( n ) // ( ( fact ( r ) * fact ( n - r ) ) ) NEW_LINE DEDENT n = 2 NEW_LINE print ( " Number ▁ of ▁ Non - Decreasing ▁...
Painting Fence Algorithm | Returns count of ways to color k posts using k colors ; There are k ways to color first post ; There are 0 ways for single post to violate ( same color_ and k ways to not violate ( different color ) ; Fill for 2 posts onwards ; Current same is same as previous diff ; We always have k - 1 choi...
def countWays ( n , k ) : NEW_LINE INDENT total = k NEW_LINE mod = 1000000007 NEW_LINE same , diff = 0 , k NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT same = diff NEW_LINE diff = total * ( k - 1 ) NEW_LINE diff = diff % mod NEW_LINE total = ( same + diff ) % mod NEW_LINE DEDENT return total NEW_LINE DEDENT ...
Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | Returns sum of all substring of num ; Initialize result ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying th...
def sumOfSubstrings ( num ) : NEW_LINE INDENT sum = 0 NEW_LINE INDENT mf = 1 NEW_LINE for i in range ( len ( num ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = sum + ( int ( num [ i ] ) ) * ( i + 1 ) * mf NEW_LINE mf = mf * 10 + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE...
Largest sum subarray with at | Returns maximum sum of a subarray with at - least k elements . ; maxSum [ i ] is going to store maximum sum till index i such that a [ i ] is part of the sum . ; We use Kadane 's algorithm to fill maxSum[] Below code is taken from method3 of https:www.geeksforgeeks.org/largest-sum-conti...
def maxSumWithK ( a , n , k ) : NEW_LINE INDENT maxSum = [ 0 for i in range ( n ) ] NEW_LINE maxSum [ 0 ] = a [ 0 ] NEW_LINE curr_max = a [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT curr_max = max ( a [ i ] , curr_max + a [ i ] ) NEW_LINE maxSum [ i ] = curr_max NEW_LINE DEDENT sum = 0 NEW_LINE for i in r...
Sequences of given length where every element is more than or equal to twice of previous | Recursive function to find the number of special sequences ; A special sequence cannot exist if length n is more than the maximum value m . ; If n is 0 , found an empty special sequence ; There can be two possibilities : ( 1 ) Re...
def getTotalNumberOfSequences ( m , n ) : NEW_LINE INDENT if m < n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if n == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT res = ( getTotalNumberOfSequences ( m - 1 , n ) + getTotalNumberOfSequences ( m // 2 , n - 1 ) ) NEW_LINE return res NEW_LINE DEDENT if __name__ == ' _ _ mai...
Sequences of given length where every element is more than or equal to twice of previous | DP based function to find the number of special sequence ; define T and build in bottom manner to store number of special sequences of length n and maximum value m ; Base case : If length of sequence is 0 or maximum value is 0 , ...
def getTotalNumberOfSequences ( m , n ) : NEW_LINE INDENT T = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if i == 0 or j == 0 : NEW_LINE INDENT T [ i ] [ j ] = 0 NEW_LINE DEDENT elif i < j : NEW_LINE INDENT T ...
Minimum number of deletions and insertions to transform one string into another | Returns length of length common subsequence for str1 [ 0. . m - 1 ] , str2 [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of str1 [ 0. . i - 1 ] and str2 ...
def lcs ( str1 , str2 , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif ( str1 [ i - 1 ] == str2 [ j -...
Minimum number of deletions to make a sorted sequence | lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; Initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Pick resultimum of all LIS values ; Function to calculate minimum number of deletions...
def lis ( arr , n ) : NEW_LINE INDENT result = 0 NEW_LINE lis = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT lis [ i ] = 1 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and lis [ i ] < lis [ j ] + 1 ) : NEW_LINE...
Clustering / Partitioning an array such that sum of square differences is minimum | Python3 program to find minimum cost k partitions of array . ; Returns minimum cost of partitioning a [ ] in k clusters . ; Create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal parti...
inf = 1000000000 ; NEW_LINE def minCost ( a , n , k ) : NEW_LINE INDENT dp = [ [ inf for i in range ( k + 1 ) ] for j in range ( n + 1 ) ] ; NEW_LINE dp [ 0 ] [ 0 ] = 0 ; NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT for m in range ( i - 1 , - 1 , - 1 ) : NEW_LIN...
Minimum number of deletions to make a string palindrome | Returns the length of the longest palindromic subsequence in 'str ; Create a table to store results of subproblems ; Strings of length 1 are palindrome of length 1 ; Build the table . Note that the lower diagonal values of table are useless and not filled in the...
' NEW_LINE def lps ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE L = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT L [ i ] [ i ] = 1 NEW_LINE DEDENT for cl in range ( 2 , n + 1 ) : NEW_LINE INDENT for i in range ( n - cl + 1 ) : NEW_LINE INDENT j = i + cl - 1 N...
Temple Offerings | Returns minimum offerings required ; Go through all templs one by one ; Go to left while height keeps increasing ; Go to right while height keeps increasing ; This temple should offer maximum of two values to follow the rule . ; Driver Code
def offeringNumber ( n , templeHeight ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT left = 0 NEW_LINE right = 0 NEW_LINE for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( templeHeight [ j ] < templeHeight [ j + 1 ] ) : NEW_LINE INDENT left += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LIN...
Subset with sum divisible by m | Returns true if there is a subset of arr [ ] with sum divisible by m ; This array will keep track of all the possible sum ( after modulo m ) which can be made using subsets of arr [ ] initialising boolean array with all false ; we 'll loop through all the elements of arr[] ; anytime we ...
def modularSum ( arr , n , m ) : NEW_LINE INDENT if ( n > m ) : NEW_LINE INDENT return True NEW_LINE DEDENT DP = [ False for i in range ( m ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( DP [ 0 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT temp = [ False for i in range ( m ) ] NEW_LINE for j in range ( m ...
Maximum sum of a path in a Right Number Triangle | tri [ ] [ ] is a 2D array that stores the triangle , n is number of lines or rows . ; Adding the element of row 1 to both the elements of row 2 to reduce a step from the loop ; Traverse remaining rows ; Loop to traverse columns ; tri [ i ] would store the possible comb...
def maxSum ( tri , n ) : NEW_LINE INDENT if n > 1 : NEW_LINE INDENT tri [ 1 ] [ 1 ] = tri [ 1 ] [ 1 ] + tri [ 0 ] [ 0 ] NEW_LINE tri [ 1 ] [ 0 ] = tri [ 1 ] [ 0 ] + tri [ 0 ] [ 0 ] NEW_LINE DEDENT for i in range ( 2 , n ) : NEW_LINE INDENT tri [ i ] [ 0 ] = tri [ i ] [ 0 ] + tri [ i - 1 ] [ 0 ] NEW_LINE tri [ i ] [ i ]...
Modify array to maximize sum of adjacent differences | Returns maximum - difference - sum with array modifications allowed . ; Initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + ab...
def maximumDifferenceSum ( arr , N ) : NEW_LINE INDENT dp = [ [ 0 , 0 ] for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i ] [ 1 ] = 0 NEW_LINE DEDENT for i in range ( N - 1 ) : NEW_LINE INDENT dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 0 ] , dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] )...
Count of strings that can be formed using a , b and c under given constraints | n is total number of characters . bCount and cCount are counts of ' b ' and ' c ' respectively . ; Base cases ; if we had saw this combination previously ; Three cases , we choose , a or b or c In all three cases n decreases by 1. ; A wrapp...
def countStrUtil ( dp , n , bCount = 1 , cCount = 2 ) : NEW_LINE INDENT if ( bCount < 0 or cCount < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( bCount == 0 and cCount == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ n ] [ bCount ] [ cCount ] !=...
Probability of Knight to remain in the chessboard | size of the chessboard ; Direction vector for the Knight ; returns true if the knight is inside the chessboard ; Bottom up approach for finding the probability to go out of chessboard . ; dp array ; For 0 number of steps , each position will have probability 1 ; for e...
N = 8 NEW_LINE dx = [ 1 , 2 , 2 , 1 , - 1 , - 2 , - 2 , - 1 ] NEW_LINE dy = [ 2 , 1 , - 1 , - 2 , - 2 , - 1 , 1 , 2 ] NEW_LINE def inside ( x , y ) : NEW_LINE INDENT return ( x >= 0 and x < N and y >= 0 and y < N ) NEW_LINE DEDENT def findProb ( start_x , start_y , steps ) : NEW_LINE INDENT dp1 = [ [ [ 0 for i in range...
Count of subarrays whose maximum element is greater than k | Return number of subarrays whose maximum element is less than or equal to K . ; To store count of subarrays with all elements less than or equal to k . ; Traversing the array . ; If element is greater than k , ignore . ; Counting the subarray length whose eac...
def countSubarray ( arr , n , k ) : NEW_LINE INDENT s = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( arr [ i ] > k ) : NEW_LINE INDENT i = i + 1 NEW_LINE continue NEW_LINE DEDENT count = 0 NEW_LINE while ( i < n and arr [ i ] <= k ) : NEW_LINE INDENT i = i + 1 NEW_LINE count = count + 1 NEW_LINE DED...
Sum of average of all subsets | Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; Method returns sum of average of all subsets ; Find sum of elements ; looping once for all subset of same size ;...
def nCr ( n , k ) : NEW_LINE INDENT C = [ [ 0 for i in range ( k + 1 ) ] for j 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 [ i ] [ j ] ...
Maximum subsequence sum such that no three are consecutive | Python3 program to find the maximum sum such that no three are consecutive using recursion . ; Returns maximum subsequence sum such that no three elements are consecutive ; 3 Base cases ( process first three elements ) ; Process rest of the elements We have t...
arr = [ 100 , 1000 , 100 , 1000 , 1 ] NEW_LINE sum = [ - 1 ] * 10000 NEW_LINE def maxSumWO3Consec ( n ) : NEW_LINE INDENT if ( sum [ n ] != - 1 ) : NEW_LINE INDENT return sum [ n ] NEW_LINE DEDENT if ( n == 0 ) : NEW_LINE INDENT sum [ n ] = 0 NEW_LINE return sum [ n ] NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT sum...
Maximum sum of pairs with specific difference | Method to return maximum sum we can get by finding less than K difference pairs ; Sort elements to ensure every i and i - 1 is closest possible pair ; To get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; ...
def maxSumPairWithDifferenceLessThanK ( arr , N , k ) : NEW_LINE INDENT maxSum = 0 NEW_LINE arr . sort ( ) NEW_LINE i = N - 1 NEW_LINE while ( i > 0 ) : NEW_LINE INDENT if ( arr [ i ] - arr [ i - 1 ] < k ) : NEW_LINE INDENT maxSum += arr [ i ] NEW_LINE maxSum += arr [ i - 1 ] NEW_LINE i -= 1 NEW_LINE DEDENT i -= 1 NEW_...
Count digit groupings of a number with given constraints | Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as pre...
def countGroups ( position , previous_sum , length , num ) : NEW_LINE INDENT if ( position == length ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT res = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( position , length ) : NEW_LINE INDENT sum = sum + int ( num [ i ] ) NEW_LINE if ( sum >= previous_sum ) : NEW_LINE INDENT r...
Count digit groupings of a number with given constraints | Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated f...
MAX = 40 NEW_LINE dp = [ [ - 1 for i in range ( 9 * MAX + 1 ) ] for i in range ( MAX ) ] NEW_LINE def countGroups ( position , previous_sum , length , num ) : NEW_LINE INDENT if ( position == length ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( dp [ position ] [ previous_sum ] != - 1 ) : NEW_LINE INDENT return dp [...
A Space Optimized DP solution for 0 | val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag dp [ W + 1 ] to store final result ; initially profit with 0 to W KnapSack capacity is 0 ; iterate through all items ; traverse dp array from right to left...
def KnapSack ( val , wt , n , W ) : NEW_LINE INDENT dp = [ 0 ] * ( W + 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( W , wt [ i ] , - 1 ) : NEW_LINE INDENT dp [ j ] = max ( dp [ j ] , val [ i ] + dp [ j - wt [ i ] ] ) ; NEW_LINE DEDENT DEDENT return dp [ W ] ; NEW_LINE DEDENT val = [ 7 , 8 , 4 ...
Find number of times a string occurs as a subsequence in given string | Iterative DP function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Create a table to store results of sub - problems ; If first string is empty ; If second string is empty ; Fill l...
def count ( a , b ) : NEW_LINE INDENT m = len ( a ) NEW_LINE n = len ( b ) NEW_LINE lookup = [ [ 0 ] * ( n + 1 ) for i in range ( m + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT lookup [ 0 ] [ i ] = 0 NEW_LINE DEDENT for i in range ( m + 1 ) : NEW_LINE INDENT lookup [ i ] [ 0 ] = 1 NEW_LINE DEDENT for i i...
Longest Geometric Progression | Returns length of the longest GP subset of sett [ ] ; Base cases ; let us sort the sett first ; An entry L [ i ] [ j ] in this table stores LLGP with sett [ i ] and sett [ j ] as first two elements of GP and j > i . ; Initialize result ( A single element is always a GP ) ; Initialize val...
def lenOfLongestGP ( sett , n ) : NEW_LINE INDENT if n < 2 : NEW_LINE INDENT return n NEW_LINE DEDENT if n == 2 : NEW_LINE INDENT return 2 if ( sett [ 1 ] % sett [ 0 ] == 0 ) else 1 NEW_LINE DEDENT sett . sort ( ) NEW_LINE L = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE llgp = 1 NEW_LINE for i in range...
Print Maximum Length Chain of Pairs | Dynamic Programming solution to construct Maximum Length Chain of Pairs ; comparator function for sort function ; Function to construct Maximum Length Chain of Pairs ; Sort by start time ; L [ i ] stores maximum length of chain of arr [ 0. . i ] that ends with arr [ i ] . ; L [ 0 ]...
class Pair : NEW_LINE INDENT def __init__ ( self , a , b ) : NEW_LINE INDENT self . a = a NEW_LINE self . b = b NEW_LINE DEDENT def __lt__ ( self , other ) : NEW_LINE INDENT return self . a < other . a NEW_LINE DEDENT DEDENT def maxChainLength ( arr ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE L = [ [ ] for x in range (...
Printing Longest Bitonic Subsequence | Utility function to print Longest Bitonic Subsequence ; Function to construct and print Longest Bitonic Subsequence ; LIS [ i ] stores the length of the longest increasing subsequence ending with arr [ i ] ; initialize LIS [ 0 ] to arr [ 0 ] ; Compute LIS values from left to right...
def _print ( arr : list , size : int ) : NEW_LINE INDENT for i in range ( size ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def printLBS ( arr : list , n : int ) : NEW_LINE INDENT LIS = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT LIS [ i ] = [ ] NEW_LINE DEDENT LIS [ 0 ] . ...
Find if string is K | Find if given string is K - Palindrome or not ; Create a table to store results of subproblems ; Fill dp [ ] [ ] in bottom up manner ; If first string is empty , only option is to remove all characters of second string ; If second string is empty , only option is to remove all characters of first ...
def isKPalDP ( str1 , str2 , m , n ) : NEW_LINE INDENT dp = [ [ 0 ] * ( n + 1 ) for _ in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if not i : NEW_LINE elif not j : NEW_LINE elif ( str1 [ i - 1 ] == str2 [ j - 1 ] ) : NEW_LINE INDENT dp [ i ] [ j ] =...
A Space Optimized Solution of LCS | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Binary index , used to index current row and previous row . ; Compute current binary index ; Last filled entry contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Driver Code
def lcs ( X , Y ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE L = [ [ 0 for i in range ( n + 1 ) ] for j in range ( 2 ) ] NEW_LINE bi = bool NEW_LINE for i in range ( m ) : NEW_LINE INDENT bi = i & 1 NEW_LINE for j in range ( n + 1 ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT L [ bi...
Count number of subsets having a particular XOR value | Python 3 arr dynamic programming solution to finding the number of subsets having xor of their elements as k ; Returns count of subsets of arr [ ] with XOR value equals to k . ; Find maximum element in arr [ ] ; Maximum possible XOR value ; Initializing all the va...
import math NEW_LINE def subsetXOR ( arr , n , k ) : NEW_LINE INDENT max_ele = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if arr [ i ] > max_ele : NEW_LINE INDENT max_ele = arr [ i ] NEW_LINE DEDENT DEDENT m = ( 1 << ( int ) ( math . log2 ( max_ele ) + 1 ) ) - 1 NEW_LINE if ( k > m ) : NEW_LINE retur...
Partition a set into two subsets such that the difference of subset sums is minimum | A Recursive Python3 program to solve minimum sum partition problem . ; Returns the minimum value of the difference of the two sets . ; Calculate sum of all elements ; Create an 2d list to store results of subproblems ; Initialize firs...
import sys NEW_LINE def findMin ( a , n ) : NEW_LINE INDENT su = 0 NEW_LINE su = sum ( a ) NEW_LINE dp = [ [ 0 for i in range ( su + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = True NEW_LINE DEDENT for j in range ( 1 , su + 1 ) : NEW_LINE INDENT dp [ 0 ] [ j ] =...
Count number of paths with at | Python3 program to count number of paths with maximum k turns allowed ; table to store results of subproblems ; Returns count of paths to reach ( i , j ) from ( 0 , 0 ) using at - most k turns . d is current direction , d = 0 indicates along row , d = 1 indicates along column . ; If inva...
MAX = 100 NEW_LINE dp = [ [ [ [ - 1 for col in range ( 2 ) ] for col in range ( MAX ) ] for row in range ( MAX ) ] for row in range ( MAX ) ] NEW_LINE def countPathsUtil ( i , j , k , d ) : NEW_LINE INDENT if ( i < 0 or j < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( i == 0 and j == 0 ) : NEW_LINE INDENT return...
Find minimum possible size of array with given rules for removing elements | Python3 program to find size of minimum possible array after removing elements according to given rules ; dp [ i ] [ j ] denotes the minimum number of elements left in the subarray arr [ i . . j ] . ; If already evaluated ; If size of array is...
MAX = 1000 NEW_LINE dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE def minSizeRec ( arr , low , high , k ) : NEW_LINE INDENT if dp [ low ] [ high ] != - 1 : NEW_LINE INDENT return dp [ low ] [ high ] NEW_LINE DEDENT if ( high - low + 1 ) < 3 : NEW_LINE INDENT return ( high - low + 1 ) NEW_LINE ...
Find number of solutions of a linear equation of n variables | Recursive function that returns count of solutions for given rhs value and coefficients coeff [ stat ... end ] ; Base case ; Initialize count of solutions ; One by one subtract all smaller or equal coefficients and recur ; Driver Code
def countSol ( coeff , start , end , rhs ) : NEW_LINE INDENT if ( rhs == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( start , end + 1 ) : NEW_LINE INDENT if ( coeff [ i ] <= rhs ) : NEW_LINE INDENT result += countSol ( coeff , i , end , rhs - coeff [ i ] ) NEW_LINE DEDENT DEDENT r...
Maximum weight transformation of a given string | Returns weight of the maximum weight transformation ; Base Case ; If this subproblem is already solved ; Don 't make pair, so weight gained is 1 ; If we can make pair ; If elements are dissimilar ; if elements are similar so for making a pair we toggle any of them . Si...
def getMaxRec ( string , i , n , lookup ) : NEW_LINE INDENT if i >= n : NEW_LINE INDENT return 0 NEW_LINE DEDENT if lookup [ i ] != - 1 : NEW_LINE INDENT return lookup [ i ] NEW_LINE DEDENT ans = 1 + getMaxRec ( string , i + 1 , n , lookup ) NEW_LINE if i + 1 < n : NEW_LINE INDENT if string [ i ] != string [ i + 1 ] : ...
Minimum steps to reach a destination | python program to count number of steps to reach a point ; source -> source vertex step -> value of last step taken dest -> destination vertex ; base cases ; if we go on positive side ; if we go on negative side ; minimum of both cases ; Driver Code
import sys NEW_LINE def steps ( source , step , dest ) : NEW_LINE INDENT if ( abs ( source ) > ( dest ) ) : NEW_LINE INDENT return sys . maxsize NEW_LINE DEDENT if ( source == dest ) : NEW_LINE INDENT return step NEW_LINE DEDENT pos = steps ( source + step + 1 , step + 1 , dest ) NEW_LINE neg = steps ( source - step - ...
Longest Common Substring | DP | Function to find the length of the longest LCS ; Create DP table ; Driver Code ; Function call
def LCSubStr ( s , t , n , m ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( m + 1 ) ] for j in range ( 2 ) ] NEW_LINE res = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( s [ i - 1 ] == t [ j - 1 ] ) : NEW_LINE INDENT dp [ i % 2 ] [ j ] = dp [ ( i - 1 ) % ...
Longest Common Substring | DP | Returns length of function for longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Driver code
def lcs ( i , j , count ) : NEW_LINE INDENT if ( i == 0 or j == 0 ) : NEW_LINE INDENT return count NEW_LINE DEDENT if ( X [ i - 1 ] == Y [ j - 1 ] ) : NEW_LINE INDENT count = lcs ( i - 1 , j - 1 , count + 1 ) NEW_LINE DEDENT count = max ( count , max ( lcs ( i , j - 1 , 0 ) , lcs ( i - 1 , j , 0 ) ) ) NEW_LINE return c...
Make Array elements equal by replacing adjacent elements with their XOR | Function to check if it is possible to make all the array elements equal using the given operation ; Stores the XOR of all elements of array A [ ] ; Case 1 , check if the XOR of the array A [ ] is 0 ; Maintains the XOR till the current element ; ...
def possibleEqualArray ( A , N ) : NEW_LINE INDENT tot_XOR = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT tot_XOR ^= A [ i ] NEW_LINE DEDENT if ( tot_XOR == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return NEW_LINE DEDENT cur_XOR = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_XOR ^...
Count of palindromes that can be obtained by concatenating equal length prefix and substrings | Function to calculate the number of palindromes ; Calculation of Z - array ; Calculation of sigma ( Z [ i ] + 1 ) ; return the count ; Given String
def countPalindrome ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE Z = [ 0 ] * N NEW_LINE l = 0 NEW_LINE r = 0 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if i <= r : NEW_LINE INDENT Z [ i ] = min ( r - i + 1 , Z [ i - 1 ] ) NEW_LINE DEDENT while ( ( i + Z [ i ] ) < N and ( S [ Z [ i ] ] == S [ i + Z [ i ] ] ) ...
Extract substrings between any pair of delimiters | Function to print strings present between any pair of delimeters ; Stores the indices ; If opening delimeter is encountered ; If closing delimeter is encountered ; Extract the position of opening delimeter ; Length of substring ; Extract the substring ; Driver Code
def printSubsInDelimeters ( string ) : NEW_LINE INDENT dels = [ ] ; NEW_LINE for i in range ( len ( string ) ) : NEW_LINE INDENT if ( string [ i ] == ' [ ' ) : NEW_LINE INDENT dels . append ( i ) ; NEW_LINE DEDENT elif ( string [ i ] == ' ] ' and len ( dels ) != 0 ) : NEW_LINE INDENT pos = dels [ - 1 ] ; NEW_LINE dels ...
Print matrix elements from top | Function to traverse the matrix diagonally upwards ; Store the number of rows ; Initialize queue ; Push the index of first element i . e . , ( 0 , 0 ) ; Get the front element ; Pop the element at the front ; Insert the element below if the current element is in first column ; Insert the...
def printDiagonalTraversal ( nums ) : NEW_LINE INDENT m = len ( nums ) NEW_LINE q = [ ] NEW_LINE q . append ( [ 0 , 0 ] ) NEW_LINE while ( len ( q ) != 0 ) : NEW_LINE INDENT p = q [ 0 ] NEW_LINE q . pop ( 0 ) ; NEW_LINE print ( nums [ p [ 0 ] ] [ p [ 1 ] ] , end = " ▁ " ) NEW_LINE if ( p [ 1 ] == 0 and p [ 0 ] + 1 < m ...
Find original sequence from Array containing the sequence merged many times in order | Function that returns the restored permutation ; List to store the result ; Map to mark the elements which are taken in result ; Checking if the element is coming first time ; Push in result vector ; Mark it in the map ; Return the a...
def restore ( arr , N ) : NEW_LINE INDENT result = [ ] NEW_LINE mp = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT if not arr [ i ] in mp : NEW_LINE INDENT result . append ( arr [ i ] ) NEW_LINE mp [ arr [ i ] ] = 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def print_result ( result ) : NEW_LINE INDENT...
Find original sequence from Array containing the sequence merged many times in order | Function that returns the restored permutation ; Vector to store the result ; Set to insert unique elements ; Check if the element is coming first time ; Push in result vector ; Function to print the result ; Driver Code ; Given Arra...
def restore ( arr , N ) : NEW_LINE INDENT result = [ ] NEW_LINE count1 = 1 NEW_LINE s = set ( [ ] ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT s . add ( arr [ i ] ) NEW_LINE if ( len ( s ) == count1 ) : NEW_LINE INDENT result . append ( arr [ i ] ) NEW_LINE count1 += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE...
Program to print the pattern 1020304017018019020 * * 50607014015016 * * * * 809012013 * * * * * * 10011. . . | Function to find the sum of N integers from 1 to N ; Function to print the given pattern ; Iterate over [ 0 , N - 1 ] ; Sub - Pattern - 1 ; Sub - Pattern - 2 ; Count the number of element in rows and sub - pat...
def sum ( n ) : NEW_LINE INDENT return n * ( n - 1 ) // 2 NEW_LINE DEDENT def BSpattern ( N ) : NEW_LINE INDENT Val = 0 NEW_LINE Pthree = 0 , NEW_LINE cnt = 0 NEW_LINE initial = - 1 NEW_LINE s = " * * " NEW_LINE for i in range ( N ) : NEW_LINE INDENT cnt = 0 NEW_LINE if ( i > 0 ) : NEW_LINE INDENT print ( s , end = " "...
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 ; Find the length of s1 and s2 ; Base case ; Traverse the string s1 and s2 ; If at any index characters are unequal then return False ; Return true ; Driver code ; Given numbers ; Function...
def checkprefix ( A , B ) : NEW_LINE INDENT s1 = str ( A ) NEW_LINE s2 = str ( B ) NEW_LINE n1 = len ( s1 ) NEW_LINE n2 = len ( s2 ) NEW_LINE if n1 < n2 : NEW_LINE INDENT return False NEW_LINE DEDENT for i in range ( 0 , n2 ) : NEW_LINE INDENT if s1 [ i ] != s2 [ i ] : NEW_LINE INDENT return False NEW_LINE DEDENT DEDEN...
Check if it is possible to reach ( x , y ) from origin in exactly Z steps using only plus movements | Function to check if it is possible to reach ( x , y ) from origin in exactly z steps ; Condition if we can 't reach in Z steps ; Driver Code ; Destination pocoordinate ; Number of steps allowed ; Function call
def possibleToReach ( x , y , z ) : NEW_LINE INDENT if ( z < abs ( x ) + abs ( y ) or ( z - abs ( x ) - abs ( y ) ) % 2 ) : NEW_LINE INDENT print ( " Not ▁ Possible " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Possible " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 5 NEW_LINE y...
Number of cycles in a Polygon with lines from Centroid to Vertices | Function to find the Number of Cycles ; Driver code
def nCycle ( N ) : NEW_LINE INDENT return ( N ) * ( N - 1 ) + 1 NEW_LINE DEDENT N = 4 NEW_LINE print ( nCycle ( N ) ) NEW_LINE
Sum of consecutive bit differences of first N non | Python3 program for the above problem ; Recursive function to count the sum of bit differences of numbers from 1 to pow ( 2 , ( i + 1 ) ) - 1 ; Base cases ; Recursion call if the sum of bit difference of numbers around i are not calculated ; Return the sum of bit diff...
import math NEW_LINE a = [ 0 ] * 65 NEW_LINE def Count ( i ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( i < 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT a [ i ] = ( i + 1 ) + 2 * Count ( i - 1 ) NEW_LINE return a [ i ] NEW_LINE DEDENT else :...
Count of total Heads and Tails after N flips in a coin | Function to find count of head and tail ; Check if initially all the coins are facing towards head ; Check if initially all the coins are facing towards tail ; Driver Code
import math NEW_LINE def count_ht ( s , N ) : NEW_LINE INDENT if s == " H " : NEW_LINE INDENT h = math . floor ( N / 2 ) NEW_LINE t = math . ceil ( N / 2 ) NEW_LINE DEDENT elif s == " T " : NEW_LINE INDENT h = math . ceil ( N / 2 ) NEW_LINE t = math . floor ( N / 2 ) NEW_LINE DEDENT return [ h , t ] NEW_LINE DEDENT if ...
Longest palindromic string possible after removal of a substring | Function to find the longest palindrome from the start of the string using KMP match ; Append S ( reverse of C ) to C ; Use KMP algorithm ; Function to return longest palindromic string possible from the given string after removal of any substring ; Ini...
def findPalindrome ( C ) : NEW_LINE INDENT S = C [ : : - 1 ] NEW_LINE C = C [ : ] + ' & ' + S NEW_LINE n = len ( C ) NEW_LINE longestPalindrome = [ 0 for i in range ( n ) ] NEW_LINE longestPalindrome [ 0 ] = 0 NEW_LINE ll = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( C [ i ] == C [ ll ] ) : NEW_LIN...
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ... | Function to find Nth term ; Nth term ; Driver Method
def nthTerm ( N ) : NEW_LINE INDENT nth = 0 ; NEW_LINE if ( N % 2 == 1 ) : NEW_LINE INDENT nth = ( N * N ) + 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT nth = ( N * N ) - 1 ; NEW_LINE DEDENT return nth ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( nthTerm ( N ) ) ; NEW_LINE...
Find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... | Function to find Nth term ; Nth term ; Driver Method
def nthTerm ( N ) : NEW_LINE INDENT nth = 0 ; first_term = 12 ; NEW_LINE nth = ( first_term * ( pow ( 2 , N - 1 ) ) ) + 11 * ( ( pow ( 2 , N - 1 ) ) - 1 ) ; NEW_LINE return nth ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( nthTerm ( N ) ) ; NEW_LINE DEDENT
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... | Function to find Nth term ; Nth term ; Driver code
def nthTerm ( N ) : NEW_LINE INDENT nth = 0 ; first_term = 4 ; NEW_LINE pi = 1 ; po = 1 ; NEW_LINE n = N ; NEW_LINE while ( n > 1 ) : NEW_LINE INDENT pi *= n - 1 ; NEW_LINE n -= 1 ; NEW_LINE po *= 2 ; NEW_LINE DEDENT nth = ( first_term * pi ) // po ; NEW_LINE return nth ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ "...
Find the final number obtained after performing the given operation | Python3 implementation of the approach ; Function to return the final number obtained after performing the given operation ; Find the gcd of the array elements ; Driver code
from math import gcd as __gcd NEW_LINE def finalNum ( arr , n ) : NEW_LINE INDENT result = arr [ 0 ] NEW_LINE for i in arr : NEW_LINE INDENT result = __gcd ( result , i ) NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 3 , 9 , 6 , 36 ] NEW_LINE n = len ( arr ) NEW_LINE print ( finalNum ( arr , n ) ) NEW_LINE
Check whether all the substrings have number of vowels atleast as that of consonants | Function that returns true if acter ch is a vowel ; Compares two integers according to their digit sum ; Check if there are two consecutive consonants ; Check if there is any vowel surrounded by two consonants ; Driver code
def isVowel ( ch ) : NEW_LINE INDENT if ch in [ ' i ' , ' a ' , ' e ' , ' o ' , ' u ' ] : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT def isSatisfied ( st , n ) : NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( isVowel ( st [ i ] ) == False and ...
Print the longest prefix of the given string which is also the suffix of the same string | Returns length of the longest prefix which is also suffix and the two do not overlap . This function mainly is copy of computeLPSArray ( ) in KMP Algorithm ; Length of the previous longest prefix suffix ; Loop to calculate lps [ ...
def LengthlongestPrefixSuffix ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE lps = [ 0 for i in range ( n ) ] NEW_LINE len1 = 0 NEW_LINE i = 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT if ( s [ i ] == s [ len1 ] ) : NEW_LINE INDENT len1 += 1 NEW_LINE lps [ i ] = len1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE IND...
Print a number as string of ' A ' and ' B ' in lexicographic order | Python 3 program to implement the above approach ; Function to calculate number of characters in corresponding string of ' A ' and 'B ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can rep...
from math import pow NEW_LINE ' NEW_LINE def no_of_characters ( M ) : NEW_LINE INDENT k = 1 NEW_LINE while ( True ) : NEW_LINE INDENT if ( pow ( 2 , k + 1 ) - 2 < M ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT return k NEW_LINE DEDENT ' NEW_LINE def print_string ( M ) :...
Replace two substrings ( of a string ) with each other | Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string...
def updateString ( S , A , B ) : NEW_LINE INDENT l = len ( A ) NEW_LINE i = 0 NEW_LINE while i + l <= len ( S ) : NEW_LINE INDENT curr = S [ i : i + l ] NEW_LINE if curr == A : NEW_LINE INDENT new_string = S [ 0 : i ] + B + S [ i + l : len ( S ) ] NEW_LINE S = new_string NEW_LINE i += l - 1 NEW_LINE DEDENT else : NEW_L...
Print n 0 s and m 1 s such that no two 0 s and no three 1 s are together | Function to print the required pattern ; When condition fails ; When m = n - 1 ; Driver Code
def printPattern ( n , m ) : NEW_LINE INDENT if ( m > 2 * ( n + 1 ) or m < n - 1 ) : NEW_LINE INDENT print ( " - 1" , end = " " ) NEW_LINE DEDENT elif ( abs ( n - m ) <= 1 ) : NEW_LINE INDENT while ( n > 0 and m > 0 ) : NEW_LINE INDENT print ( "01" , end = " " ) ; NEW_LINE n -= 1 NEW_LINE m -= 1 NEW_LINE DEDENT if ( n ...
Find the count of Strictly decreasing Subarrays | Function to count the number of strictly decreasing subarrays ; Initialize length of current decreasing subarray ; Traverse through the array ; If arr [ i + 1 ] is less than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more ...
def countDecreasing ( A , n ) : NEW_LINE INDENT len = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( A [ i + 1 ] < A [ i ] ) : NEW_LINE INDENT len += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt += ( ( ( len - 1 ) * len ) // 2 ) ; NEW_LINE len = 1 NEW_LINE DEDENT DEDENT if ( len > 1 ) : NEW_LINE INDENT cnt ...
Minimum changes required to make first string substring of second string | Python3 program to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Function to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Get th...
import sys NEW_LINE def minimumChar ( S1 , S2 ) : NEW_LINE INDENT n , m = len ( S1 ) , len ( S2 ) NEW_LINE ans = sys . maxsize NEW_LINE for i in range ( m - n + 1 ) : NEW_LINE INDENT minRemovedChar = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT if ( S1 [ j ] != S2 [ i + j ] ) : NEW_LINE INDENT minRemovedChar += 1 ...
Frequency of a substring in a string | Simple python program to count occurrences of pat in txt . ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver Code
def countFreq ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE res = 0 NEW_LINE for i in range ( N - M + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while j < M : NEW_LINE INDENT if ( txt [ i + j ] != pat [ j ] ) : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if ( j == M ) : NE...
Optimized Naive Algorithm for Pattern Searching | A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if j == M : if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ;...
def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE i = 0 NEW_LINE while i <= N - M : NEW_LINE INDENT for j in xrange ( M ) : NEW_LINE INDENT if txt [ i + j ] != pat [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE print " Pattern ▁ found ▁ at ▁ index ▁ " + str ( i ...
Find the missing digit in given product of large positive integers | Function to find the replaced digit in the product of a * b ; Keeps track of the sign of the current digit ; Stores the value of a % 11 ; Find the value of a mod 11 for large value of a as per the derived formula ; Stores the value of b % 11 ; Find th...
def findMissingDigit ( a , b , c ) : NEW_LINE INDENT w = 1 NEW_LINE a_mod_11 = 0 NEW_LINE for i in range ( len ( a ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT a_mod_11 = ( a_mod_11 + w * ( ord ( a [ i ] ) - ord ( '0' ) ) ) % 11 NEW_LINE w = w * - 1 NEW_LINE DEDENT b_mod_11 = 0 NEW_LINE w = 1 NEW_LINE for i in range ( len ( b...
Check if a string can be made empty by repeatedly removing given subsequence | Function to check if a string can be made empty by removing all subsequences of the form " GFG " or not ; Driver Code
def findIfPossible ( N , str_ ) : NEW_LINE INDENT countG = 0 NEW_LINE countF = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if str_ [ i ] == ' G ' : NEW_LINE INDENT countG += 1 NEW_LINE DEDENT else : NEW_LINE INDENT countF += 1 NEW_LINE DEDENT DEDENT if 2 * countF != countG : NEW_LINE INDENT print ( " NO " ) NEW_L...
Check whether second string can be formed from characters of first string used any number of times | Function to check if str2 can be made by characters of str1 or not ; To store the occurrence of every character ; Length of the two strings ; Assume that it is possible to compose the string str2 from str1 ; Iterate ove...
def isPossible ( str1 , str2 ) : NEW_LINE INDENT arr = { } NEW_LINE l1 = len ( str1 ) NEW_LINE l2 = len ( str2 ) NEW_LINE possible = True NEW_LINE for i in range ( l1 ) : NEW_LINE INDENT arr [ str1 [ i ] ] = 1 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT if str2 [ i ] != ' ▁ ' : NEW_LINE INDENT if arr [ str2...
Minimum number of flipping adjacent bits required to make given Binary Strings equal | Function to find the minimum number of inversions required . ; Initializing the answer ; Iterate over the range ; If s1 [ i ] != s2 [ i ] , then inverse the characters at i snd ( i + 1 ) positions in s1 . ; Adding 1 to counter if cha...
def find_Min_Inversion ( n , s1 , s2 ) : NEW_LINE INDENT count = 0 NEW_LINE s1 = list ( s1 ) NEW_LINE s2 = list ( s2 ) NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( s1 [ i ] != s2 [ i ] ) : NEW_LINE INDENT if ( s1 [ i ] == '1' ) : NEW_LINE INDENT s1 [ i ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT s1 [ i ]...
Longest subsequence with consecutive English alphabets | Function to find the length of subsequence starting with character ch ; Length of the string ; Stores the maximum length ; Traverse the given string ; If s [ i ] is required character ch ; Increment ans by 1 ; Increment character ch ; Return the current maximum l...
def findSubsequence ( S , ch ) : NEW_LINE INDENT N = len ( S ) NEW_LINE ans = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == ch ) : NEW_LINE INDENT ans += 1 NEW_LINE ch = chr ( ord ( ch ) + 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT def findMaxSubsequence ( S ) : NEW_LINE INDENT ans = 0 NE...
Minimum number of alternate subsequences required to be removed to empty a Binary String | Function to find the minimum number of operations to empty a binary string ; Stores the resultant number of operations ; Stores the number of 0 s ; Stores the number of 1 s ; Traverse the given string ; To balance 0 with 1 if pos...
def minOpsToEmptyString ( s ) : NEW_LINE INDENT ans = - 10 ** 9 NEW_LINE cn0 = 0 NEW_LINE cn1 = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT if ( cn1 > 0 ) : NEW_LINE INDENT cn1 -= 1 NEW_LINE DEDENT cn0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( cn0 > 0 ) : NEW...
Longest Non | Function to find the length of the longest non - increasing subsequence ; Stores the prefix and suffix count of 1 s and 0 s respectively ; Store the number of '1' s up to current index i in pre ; Find the prefix sum ; If the current element is '1' , update the pre [ i ] ; Store the number of '0' s over th...
def findLength ( str , n ) : NEW_LINE INDENT pre = [ 0 ] * n NEW_LINE post = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( i != 0 ) : NEW_LINE INDENT pre [ i ] += pre [ i - 1 ] NEW_LINE DEDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT pre [ i ] += 1 NEW_LINE DEDENT DEDENT for i in range ( n - 1 , - 1 ,...
Number of substrings having an equal number of lowercase and uppercase letters | Function to find the count of substrings having an equal number of uppercase and lowercase characters ; Stores the count of prefixes having sum S considering uppercase and lowercase characters as 1 and - 1 ; Stores the count of substrings ...
def countSubstring ( S , N ) : NEW_LINE INDENT prevSum = { } NEW_LINE res = 0 NEW_LINE currentSum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] >= ' A ' and S [ i ] <= ' Z ' ) : NEW_LINE INDENT currentSum += 1 NEW_LINE DEDENT else : NEW_LINE INDENT currentSum -= 1 NEW_LINE DEDENT if ( currentSum == 0...
Number of substrings with each character occurring even times | Function to count substrings having even frequency of each character ; Stores the total count of substrings ; Traverse the range [ 0 , N ] : ; Traverse the range [ i + 1 , N ] ; Stores the substring over the range of indices [ i , len ] ; Stores the freque...
def subString ( s , n ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for len in range ( i + 1 , n + 1 ) : NEW_LINE INDENT test_str = ( s [ i : len ] ) NEW_LINE res = { } NEW_LINE for keys in test_str : NEW_LINE INDENT res [ keys ] = res . get ( keys , 0 ) + 1 NEW_LINE DEDENT flag = 0 NEW_...
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | Function to count new pairs of strings that can be obtained by swapping first characters of any pair of strings ; Stores the count of pairs ; Generate all possible pairs of strings from the array arr [ ] ...
def countStringPairs ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n , 1 ) : NEW_LINE INDENT p = a [ i ] NEW_LINE q = a [ j ] NEW_LINE if ( p [ 0 ] != q [ 0 ] ) : NEW_LINE INDENT p = list ( p ) NEW_LINE q = list ( q ) NEW_LINE temp = p [ 0 ] NEW_LINE p [ 0 ...
Check if it is possible to reach any point on the circumference of a given circle from origin | Function to check if it is possible to reach any point on circumference of the given circle from ( 0 , 0 ) ; Stores the count of ' L ' , 'R ; Stores the count of ' U ' , 'D ; Traverse the string S ; Update the count of L ; U...
def isPossible ( S , R , N ) : NEW_LINE ' NEW_LINE INDENT cntl = 0 NEW_LINE cntr = 0 NEW_LINE DEDENT ' NEW_LINE INDENT cntu = 0 NEW_LINE cntd = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == ' L ' ) : NEW_LINE INDENT cntl += 1 NEW_LINE DEDENT elif ( S [ i ] == ' R ' ) : NEW_LINE INDENT cntr += 1 NEW_...
Modify characters of a string by adding integer values of same | Function to modify a given string by adding ASCII value of characters from a string S to integer values of same indexed characters in string N ; Traverse the string ; Stores integer value of character in string N ; Stores ASCII value of character in strin...
def addASCII ( S , N ) : NEW_LINE INDENT for i in range ( len ( S ) ) : NEW_LINE INDENT a = ord ( N [ i ] ) - ord ( '0' ) NEW_LINE b = ord ( S [ i ] ) + a NEW_LINE if ( b > 122 ) : NEW_LINE INDENT b -= 26 NEW_LINE DEDENT S = S . replace ( S [ i ] , chr ( b ) ) NEW_LINE DEDENT print ( S ) NEW_LINE DEDENT if __name__ == ...
Modify array by removing characters from their Hexadecimal representations which are present in a given string | Function to convert a decimal number to its equivalent hexadecimal number ; Function to convert hexadecimal number to its equavalent decimal number ; Stores characters with their respective hexadecimal value...
def decHex ( n ) : NEW_LINE INDENT alpha = [ ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' ] NEW_LINE ans = ' ' NEW_LINE while n : NEW_LINE INDENT if n % 16 < 10 : NEW_LINE INDENT ans += str ( n % 16 ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += alpha [ n % 16 - 10 ] NEW_LINE DEDENT n //= 16 NEW_LINE DEDENT ans = ans...
Modify string by inserting characters such that every K | Function to replace all ' ? ' characters in a string such that the given conditions are satisfied ; Traverse the string to Map the characters with respective positions ; Traverse the string again and replace all unknown characters ; If i % k is not found in the ...
def fillString ( s , k ) : NEW_LINE INDENT mp = { } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] != ' ? ' ) : NEW_LINE INDENT mp [ i % k ] = s [ i ] NEW_LINE DEDENT DEDENT s = list ( s ) NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( ( i % k ) not in mp ) : NEW_LINE INDENT print ( ...
Rearrange a string S1 such that another given string S2 is not its subsequence | Function to rearrange characters in S1 such that S2 is not a subsequence of it ; Store the frequencies of characters of s2 ; Traverse the s2 ; Update the frequency ; Find the number of unique characters in s2 ; Increment unique by 1 if the...
def rearrangeString ( s1 , s2 ) : NEW_LINE INDENT cnt = [ 0 ] * 26 NEW_LINE for i in range ( len ( s2 ) ) : NEW_LINE INDENT cnt [ ord ( s2 [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT unique = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( cnt [ i ] != 0 ) : NEW_LINE INDENT unique += 1 NEW_LINE DEDENT DEDENT...
Check if a string can be emptied by removing all subsequences of the form "10" | Function to find if string is reducible to NULL ; Length of string ; Stack to store all 1 s ; Iterate over the characters of the string ; If current character is 1 ; Push it into the stack ; Pop from the stack ; If the stack is empty ; Dri...
def isReducible ( Str ) : NEW_LINE INDENT N = len ( Str ) NEW_LINE s = [ ] NEW_LINE for i in range ( N ) : NEW_LINE if ( Str [ i ] == '1' ) : NEW_LINE INDENT s . append ( Str [ i ] ) NEW_LINE DEDENT elif ( len ( s ) > 0 ) : NEW_LINE INDENT del s [ len ( s ) - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_...
Rearrange a string to maximize the minimum distance between any pair of vowels | Function to rearrange the string such that the minimum distance between any of vowels is maximum . ; store vowels and consonants ; Iterate over the characters of string ; if current character is a vowel ; if current character is consonant ...
def solution ( S ) : NEW_LINE INDENT vowels = [ ] NEW_LINE consonants = [ ] NEW_LINE for i in S : NEW_LINE INDENT if ( i == ' a ' or i == ' e ' or i == ' i ' or i == ' o ' or i == ' u ' ) : NEW_LINE INDENT vowels . append ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT consonants . append ( i ) NEW_LINE DEDENT DEDENT Nc =...
Lexicographically smallest string possible by performing K operations on a given string | Function to find the lexicographically smallest possible string by performing K operations on string S ; Store the size of string , s ; Check if k >= n , if true , convert every character to 'a ; Iterate in range [ 0 , n - 1 ] usi...
def smallestlexicographicstring ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE DEDENT ' NEW_LINE INDENT if ( k >= n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT s [ i ] = ' a ' ; NEW_LINE DEDENT print ( s , end = ' ' ) NEW_LINE return ; NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT if ( k == ...
Maximize palindromic strings of length 3 possible from given count of alphabets | Function to count maximum number of palindromic string of length 3 ; Stores the final count of palindromic strings ; Traverse the array ; Increment res by arr [ i ] / 3 , i . e forming string of only i + ' a ' character ; Store remainder ...
def maximum_pallindromic ( arr ) : NEW_LINE INDENT res = 0 NEW_LINE c1 = 0 NEW_LINE c2 = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT res += arr [ i ] // 3 NEW_LINE arr [ i ] = arr [ i ] % 3 NEW_LINE if ( arr [ i ] == 1 ) : NEW_LINE INDENT c1 += 1 NEW_LINE DEDENT elif ( arr [ i ] == 2 ) : NEW_LINE INDENT c2 += 1 ...
Find the winner of game of repeatedly removing the first character to empty given string | Function to find the winner of a game of repeatedly removing the first character to empty a string ; Store characters of each string of the array arr [ ] ; Stores count of strings in arr [ ] ; Traverse the array arr [ ] ; Stores ...
def find_Winner ( arr , N ) : NEW_LINE INDENT Q = [ 0 ] * N NEW_LINE for i in range ( N ) : NEW_LINE INDENT Q [ i ] = [ ] NEW_LINE DEDENT M = len ( arr ) NEW_LINE for i in range ( M ) : NEW_LINE INDENT Len = len ( arr [ i ] ) NEW_LINE for j in range ( Len ) : NEW_LINE INDENT Q [ i ] . append ( ord ( arr [ i ] [ j ] ) -...
Longest Substring that can be made a palindrome by swapping of characters | Function to find the Longest substring that can be made a palindrome by swapping of characters ; Initialize dp array of size 1024 ; Initializing mask and res ; Traverse the string ; Find the mask of the current character ; Finding the length of...
def longestSubstring ( s ) : NEW_LINE INDENT dp = [ 1024 for i in range ( 1024 ) ] NEW_LINE res , mask = 0 , 0 NEW_LINE dp [ 0 ] = - 1 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT mask ^= 1 << ( ord ( s [ i ] ) - ord ( '0' ) ) NEW_LINE res = max ( res , i - dp [ mask ] ) NEW_LINE for j in range ( 10 ) : NEW_...
Convert given string to a valid mobile number | Function to print valid and formatted phone number ; Length of given ; Store digits in temp ; Iterate given M ; If any digit : append it to temp ; Find new length of ; If length is not equal to 10 ; Store final result ; Make groups of 3 digits and enclose them within ( ) ...
def Validate ( M ) : NEW_LINE INDENT lenn = len ( M ) NEW_LINE temp = " " NEW_LINE for i in range ( lenn ) : NEW_LINE INDENT if ( M [ i ] . isdigit ( ) ) : NEW_LINE INDENT temp += M [ i ] NEW_LINE DEDENT DEDENT nwlenn = len ( temp ) NEW_LINE if ( nwlenn != 10 ) : NEW_LINE INDENT print ( " Invalid " ) NEW_LINE return NE...
Modulus of two Hexadecimal Numbers | Function to calculate modulus of two Hexadecimal numbers ; Store all possible hexadecimal digits ; Iterate over the range [ '0' , '9' ] ; Convert given string to long ; Base to get 16 power ; Store N % K ; Iterate over the digits of N ; Stores i - th digit of N ; Update ans ; Update...
def hexaModK ( s , k ) : NEW_LINE INDENT mp = { } ; NEW_LINE for i in range ( 1 , 10 ) : NEW_LINE INDENT mp [ chr ( i + ord ( '0' ) ) ] = i ; NEW_LINE DEDENT mp [ ' A ' ] = 10 ; NEW_LINE mp [ ' B ' ] = 11 ; NEW_LINE mp [ ' C ' ] = 12 ; NEW_LINE mp [ ' D ' ] = 13 ; NEW_LINE mp [ ' E ' ] = 14 ; NEW_LINE mp [ ' F ' ] = 15...
Print all combinations generated by characters of a numeric string which does not exceed N | Store the current sequence of s ; Store the all the required sequences ; Function to print all sequences of S satisfying the required condition ; Print all strings in the set ; Function to generate all sequences of string S tha...
combination = " " ; NEW_LINE combinations = [ ] ; NEW_LINE def printSequences ( combinations ) : NEW_LINE INDENT for s in ( combinations ) : NEW_LINE INDENT print ( s , end = ' ▁ ' ) ; NEW_LINE DEDENT DEDENT def generateCombinations ( s , n ) : NEW_LINE INDENT global combination ; NEW_LINE for i in range ( len ( s ) ) ...
Count Distinct Strings present in an array using Polynomial rolling hash function | Function to find the hash value of a ; Traverse the ; Update hash_val ; Update mul ; Return hash_val of str ; Function to find the count of distinct strings present in the given array ; Store the hash values of the strings ; Traverse th...
def compute_hash ( str ) : NEW_LINE INDENT p = 31 NEW_LINE MOD = 10 ** 9 + 7 NEW_LINE hash_val = 0 NEW_LINE mul = 1 NEW_LINE for ch in str : NEW_LINE INDENT hash_val = ( hash_val + ( ord ( ch ) - ord ( ' a ' ) + 1 ) * mul ) % MOD NEW_LINE mul = ( mul * p ) % MOD NEW_LINE DEDENT return hash_val NEW_LINE DEDENT def disti...
Remove characters from given string whose frequencies are a Prime Number | Function to perform the seive of eratosthenes algorithm ; Initialize all entries in prime [ ] as true ; Initialize 0 and 1 as non prime ; Traversing the prime array ; If i is prime ; All multiples of i must be marked false as they are non prime ...
def SieveOfEratosthenes ( prime , n ) : NEW_LINE INDENT for i in range ( n + 1 ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT prime [ 0 ] = prime [ 1 ] = False NEW_LINE i = 2 NEW_LINE while i * i <= n : NEW_LINE INDENT if ( prime [ i ] == True ) : NEW_LINE INDENT j = 2 NEW_LINE while i * j <= n : NEW_LINE INDEN...
Rearrange string such that no pair of adjacent characters are of the same type | Function to rearrange given alphanumeric such that no two adjacent characters are of the same type ; Stores alphabets and digits ; Store the alphabets and digits separately in the strings ; Stores the count of alphabets and digits ; If res...
def rearrange ( s ) : NEW_LINE INDENT s1 = [ ] NEW_LINE s2 = [ ] NEW_LINE for x in s : NEW_LINE INDENT if x . isalpha ( ) : NEW_LINE INDENT s1 . append ( x ) NEW_LINE DEDENT else : NEW_LINE INDENT s2 . append ( x ) NEW_LINE DEDENT DEDENT n = len ( s1 ) NEW_LINE m = len ( s2 ) NEW_LINE if ( abs ( n - m ) > 1 ) : NEW_LIN...
Find value after N operations to remove N characters of string S with given constraints | Function to find the value after N operations to remove all the N characters of String S ; Iterate till N ; Remove character at ind and decrease n ( size of String ) ; Increase count by ind + 1 ; Driver Code ; Given String str ; F...
def charactersCount ( str , n ) : NEW_LINE INDENT count = 0 ; NEW_LINE while ( n > 0 ) : NEW_LINE INDENT cur = str [ 0 ] ; NEW_LINE ind = 0 ; NEW_LINE for j in range ( 1 , n ) : NEW_LINE INDENT if ( str [ j ] < cur ) : NEW_LINE INDENT cur = str [ j ] ; NEW_LINE ind = j ; NEW_LINE DEDENT DEDENT str = str [ 0 : ind ] + s...
Print the middle character of a string | Function that prints the middle character of a string ; Finding string length ; Finding middle index of string ; Prthe middle character of the string ; Given string str ; Function Call
def printMiddleCharacter ( str ) : NEW_LINE INDENT length = len ( str ) ; NEW_LINE middle = length // 2 ; NEW_LINE print ( str [ middle ] ) ; NEW_LINE DEDENT str = " GeeksForGeeks " ; NEW_LINE printMiddleCharacter ( str ) ; NEW_LINE
Maximize length of the String by concatenating characters from an Array of Strings | Function to check if all the string characters are unique ; Check for repetition in characters ; Function to generate all possible strings from the given array ; Base case ; Consider every string as a starting substring and store the g...
def check ( s ) : NEW_LINE INDENT a = set ( ) NEW_LINE for i in s : NEW_LINE INDENT if i in a : NEW_LINE INDENT return False NEW_LINE DEDENT a . add ( i ) NEW_LINE DEDENT return True NEW_LINE DEDENT def helper ( arr , ind ) : NEW_LINE INDENT if ( ind == len ( arr ) ) : NEW_LINE INDENT return [ " " ] NEW_LINE DEDENT tmp...
Perform range sum queries on string as per given condition | Function to perform range sum queries on string as per the given condition ; Initialize N by string size ; Create array A [ ] for prefix sum ; Iterate till N ; Traverse the queries ; Check if if L == 1 range sum will be A [ R - 1 ] ; Condition if L > 1 range ...
def Range_sum_query ( S , Query ) : NEW_LINE INDENT N = len ( S ) NEW_LINE A = [ 0 ] * N NEW_LINE A [ 0 ] = ord ( S [ 0 ] ) - ord ( ' a ' ) + 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT A [ i ] = ord ( S [ i ] ) - ord ( ' a ' ) + 1 NEW_LINE A [ i ] = A [ i ] + A [ i - 1 ] NEW_LINE DEDENT for i in range ( len ...