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_LINE for j in range ( l , n ) : NEW_LINE INDENT i += 1 NEW_LINE if ( s [ i ] == ' ( ' and s [ j ] == ' ) ' ) : NEW_LINE INDENT dp [ i ] [ j ] = 2 + dp [ i + 1 ] [ j - 1 ] NEW_LINE DEDENT for k in range ( i , j ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k + 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ 0 ] [ n - 1 ] NEW_LINE DEDENT s = " ( ) ( ( ( ( ( ( ) " NEW_LINE n = len ( s ) NEW_LINE print ( maxLength ( s , n ) ) NEW_LINE
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 . ; Find the longest decreasing subarray starting at j . ; Now we know that a [ j . . k ] is a decreasing subarray . Remove non - positive elements from the right side as much as possible . last is needed to keep the last seen element . ; Compute the max sum of the increasing part . ; Compute the max sum of the decreasing part . ; The overall max sum is the sum of both parts minus the peak element , because it was counted twice . ; If the next element is equal to the current , i . e . arr [ i + 1 ] == arr [ i ] , last == i . To ensure the algorithm has progress , get the max of last and i + 1. ; required maximum sum ; The example from the article , the answer is 19. ; Always increasing , the answer is 15. ; Always decreasing , the answer is 15. ; All are equal , the answer is 5. ; The whole array is bitonic , but the answer is 7. ; The answer is 4 ( the tail ) .
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 NEW_LINE while ( k + 1 < n and arr [ k ] > arr [ k + 1 ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT last = k NEW_LINE while ( k > j and arr [ k ] <= 0 ) : NEW_LINE INDENT k -= 1 NEW_LINE DEDENT nn = arr [ i : j + 1 ] NEW_LINE sum_inc = sum ( nn ) NEW_LINE nn = arr [ j : k + 1 ] NEW_LINE sum_dec = sum ( nn ) NEW_LINE sum_all = sum_inc + sum_dec - arr [ j ] NEW_LINE max_sum = max ( [ max_sum , sum_inc , sum_dec , sum_all ] ) NEW_LINE i = max ( last , i + 1 ) NEW_LINE DEDENT return max_sum NEW_LINE DEDENT arr = [ 5 , 3 , 9 , 2 , 7 , 6 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( arr , n ) ) NEW_LINE arr2 = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( arr2 , n2 ) ) NEW_LINE arr3 = [ 5 , 4 , 3 , 2 , 1 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( arr3 , n3 ) ) NEW_LINE arr4 = [ 5 , 5 , 5 , 5 ] NEW_LINE n4 = len ( arr4 ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( arr4 , n4 ) ) NEW_LINE arr5 = [ - 1 , 0 , 1 , 2 , 3 , 1 , 0 , - 1 , - 10 ] NEW_LINE n5 = len ( arr5 ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( arr5 , n5 ) ) NEW_LINE arr6 = [ - 1 , 0 , 1 , 2 , 0 , - 1 , - 2 , 0 , 1 , 3 ] NEW_LINE n6 = len ( arr6 ) NEW_LINE print ( " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( arr6 , n6 ) ) NEW_LINE
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 > 0 , then it could not possibly contribute to the minimum sum further ; else add the value arr [ i ] to min_ending_here ; update min_so_far ; required smallest sum contiguous subarray value ; Driver code
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 += arr [ i ] NEW_LINE DEDENT min_so_far = min ( min_so_far , min_ending_here ) NEW_LINE DEDENT return min_so_far NEW_LINE DEDENT arr = [ 3 , - 4 , 2 , - 3 , - 1 , 7 , - 5 ] NEW_LINE n = len ( arr ) NEW_LINE print " Smallest ▁ sum : ▁ " , smallestSumSubarr ( arr , n ) NEW_LINE
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 ) NEW_LINE print ( answer ) NEW_LINE DEDENT
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 square ; If the answer for the given rectangle is previously calculated return that answer ; The rectangle is cut horizontally and vertically into two parts and the cut with minimum value is found for every recursive call . ; Calculating the minimum answer for the rectangles with width equal to n and length less than m for finding the cut point for the minimum answer ; Calculating the minimum answer for the rectangles with width equal to n and length less than m for finding the cut point for the minimum answer ; Minimum of the vertical cut or horizontal cut to form a square is the answer ; Driver code ; Function call
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 return 6 NEW_LINE DEDENT if m == n : NEW_LINE INDENT return 1 NEW_LINE DEDENT if dp [ m ] [ n ] != 0 : NEW_LINE INDENT return dp [ m ] [ n ] NEW_LINE DEDENT for i in range ( 1 , m // 2 + 1 ) : NEW_LINE INDENT horizontal_min = min ( minimumSquare ( i , n ) + minimumSquare ( m - i , n ) , horizontal_min ) NEW_LINE DEDENT for j in range ( 1 , n // 2 + 1 ) : NEW_LINE INDENT vertical_min = min ( minimumSquare ( m , j ) + minimumSquare ( m , n - j ) , vertical_min ) NEW_LINE DEDENT dp [ m ] [ n ] = min ( vertical_min , horizontal_min ) NEW_LINE return dp [ m ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 30 NEW_LINE n = 35 NEW_LINE print ( minimumSquare ( m , n ) ) NEW_LINE DEDENT
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 ▁ digits : ▁ " , nCr ( n + 9 , 9 ) ) NEW_LINE
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 choices for next post ; Total choices till i . ; Driver code
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 if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n , k = 3 , 2 NEW_LINE print ( countWays ( n , k ) ) 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 the three factors as explained above . int ( s [ i ] ) is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver code to test above methods
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 INDENT num = "6759" NEW_LINE print ( sumOfSubstrings ( num ) ) NEW_LINE DEDENT
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-contiguous-subarray/ ; Sum of first k elements ; Use the concept of sliding window ; Compute sum of k elements ending with a [ i ] . ; Update result if required ; Include maximum sum till [ i - k ] also if it increases overall max . ; Driver code
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 range ( k ) : NEW_LINE INDENT sum += a [ i ] NEW_LINE DEDENT result = sum NEW_LINE for i in range ( k , n ) : NEW_LINE INDENT sum = sum + a [ i ] - a [ i - k ] NEW_LINE result = max ( result , sum ) NEW_LINE result = max ( result , sum + maxSum [ i - k ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT a = [ 1 , 2 , 3 , - 10 , - 3 ] NEW_LINE k = 4 NEW_LINE n = len ( a ) NEW_LINE print ( maxSumWithK ( a , n , k ) ) NEW_LINE
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 ) Reduce last element value ( 2 ) Consider last element as m and reduce number of terms ; Driver Code
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__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 10 NEW_LINE n = 4 NEW_LINE print ( ' Total ▁ number ▁ of ▁ possible ▁ sequences : ' , getTotalNumberOfSequences ( m , n ) ) NEW_LINE DEDENT
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 , there cannot exist any special sequence ; if length of sequence is more than the maximum value , special sequence cannot exist ; If length of sequence is 1 then the number of special sequences is equal to the maximum value For example with maximum value 2 and length 1 , there can be 2 special sequences { 1 } , { 2 } ; otherwise calculate ; Driver Code
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 [ i ] [ j ] = 0 NEW_LINE DEDENT elif j == 1 : NEW_LINE INDENT T [ i ] [ j ] = i NEW_LINE DEDENT else : NEW_LINE INDENT T [ i ] [ j ] = T [ i - 1 ] [ j ] + T [ i // 2 ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT return T [ m ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 10 NEW_LINE n = 4 NEW_LINE print ( ' Total ▁ number ▁ of ▁ possible ▁ sequences ▁ ' , getTotalNumberOfSequences ( m , n ) ) NEW_LINE DEDENT
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 [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; function to find minimum number of deletions and insertions ; Driver Code ; Function Call
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 - 1 ] ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT def printMinDelAndInsert ( str1 , str2 ) : NEW_LINE INDENT m = len ( str1 ) NEW_LINE n = len ( str2 ) NEW_LINE leng = lcs ( str1 , str2 , m , n ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ deletions ▁ = ▁ " , m - leng , sep = ' ▁ ' ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ insertions ▁ = ▁ " , n - leng , sep = ' ▁ ' ) NEW_LINE DEDENT str1 = " heap " NEW_LINE str2 = " pea " NEW_LINE printMinDelAndInsert ( str1 , str2 ) NEW_LINE
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 ; Find longest increasing subsequence ; After removing elements other than the lis , we get sorted sequence . ; Driver Code
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 INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( result < lis [ i ] ) : NEW_LINE INDENT result = lis [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def minimumNumberOfDeletions ( arr , n ) : NEW_LINE INDENT len = lis ( arr , n ) NEW_LINE return ( n - len ) NEW_LINE DEDENT arr = [ 30 , 40 , 2 , 5 , 1 , 7 , 45 , 50 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Minimum ▁ number ▁ of ▁ deletions ▁ = ▁ " , minimumNumberOfDeletions ( arr , n ) ) 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 partition cost for arr [ 0. . i - 1 ] and j partitions ; Fill dp [ ] [ ] in bottom up manner ; Current ending position ( After i - th iteration result for a [ 0. . i - 1 ] is computed . ; j is number of partitions ; Picking previous partition for current i . ; Driver code
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_LINE INDENT dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ m ] [ j - 1 ] + ( a [ i - 1 ] - a [ m ] ) * ( a [ i - 1 ] - a [ m ] ) ) ; NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ k ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT k = 2 ; NEW_LINE a = [ 1 , 5 , 8 , 10 ] ; NEW_LINE n = len ( a ) ; NEW_LINE print ( minCost ( a , n , k ) ) ; NEW_LINE DEDENT
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 process . c1 is length of substring ; length of longest palindromic subseq ; function to calculate minimum number of deletions ; Find longest palindromic subsequence ; After removing characters other than the lps , we get palindrome . ; Driver Code
' 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 NEW_LINE if ( str [ i ] == str [ j ] and cl == 2 ) : NEW_LINE INDENT L [ i ] [ j ] = 2 NEW_LINE DEDENT elif ( str [ i ] == str [ j ] ) : NEW_LINE INDENT L [ i ] [ j ] = L [ i + 1 ] [ j - 1 ] + 2 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i ] [ j - 1 ] , L [ i + 1 ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ 0 ] [ n - 1 ] NEW_LINE DEDENT def minimumNumberOfDeletions ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE l = lps ( str ) NEW_LINE return ( n - l ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE print ( " Minimum ▁ number ▁ of ▁ deletions ▁ = ▁ " , minimumNumberOfDeletions ( str ) ) NEW_LINE DEDENT
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_LINE DEDENT DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( templeHeight [ j ] < templeHeight [ j - 1 ] ) : NEW_LINE INDENT right += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT sum += max ( right , left ) + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT arr1 = [ 1 , 2 , 2 ] NEW_LINE print ( offeringNumber ( 3 , arr1 ) ) NEW_LINE arr2 = [ 1 , 4 , 3 , 6 , 2 , 1 ] NEW_LINE print ( offeringNumber ( 6 , arr2 ) ) NEW_LINE
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 encounter a sum divisible by m , we are done ; To store all the new encountered sum ( after modulo ) . It is used to make sure that arr [ i ] is added only to those entries for which DP [ j ] was true before current iteration . ; For each element of arr [ ] , we loop through all elements of DP table from 1 to m and we add current element i . e . , arr [ i ] to all those elements which are true in DP table ; if an element is true in DP table ; We update it in temp and update to DP once loop of j is over ; Updating all the elements of temp to DP table since iteration over j is over ; Also since arr [ i ] is a single element subset , arr [ i ] % m is one of the possible sum ; Driver code
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 ) : NEW_LINE INDENT if ( DP [ j ] == True ) : NEW_LINE INDENT if ( DP [ ( j + arr [ i ] ) % m ] == False ) : NEW_LINE INDENT temp [ ( j + arr [ i ] ) % m ] = True NEW_LINE DEDENT DEDENT DEDENT for j in range ( m ) : NEW_LINE INDENT if ( temp [ j ] ) : NEW_LINE INDENT DP [ j ] = True NEW_LINE DEDENT DEDENT DP [ arr [ i ] % m ] = True NEW_LINE DEDENT return DP [ 0 ] NEW_LINE DEDENT arr = [ 1 , 7 ] NEW_LINE n = len ( arr ) NEW_LINE m = 5 NEW_LINE print ( " YES " ) if ( modularSum ( arr , n , m ) ) else print ( " NO " ) NEW_LINE
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 combinations of sum of the paths ; array at n - 1 index ( tri [ i ] ) stores all possible adding combination , finding the maximum one out of them ; driver program
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 ] = tri [ i ] [ i ] + tri [ i - 1 ] [ i - 1 ] NEW_LINE for j in range ( 1 , i ) : NEW_LINE INDENT if tri [ i ] [ j ] + tri [ i - 1 ] [ j - 1 ] >= tri [ i ] [ j ] + tri [ i - 1 ] [ j ] : NEW_LINE INDENT tri [ i ] [ j ] = tri [ i ] [ j ] + tri [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT tri [ i ] [ j ] = tri [ i ] [ j ] + tri [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT print max ( tri [ n - 1 ] ) NEW_LINE DEDENT tri = [ [ 1 ] , [ 2 , 1 ] , [ 3 , 3 , 2 ] ] NEW_LINE maxSum ( tri , 3 ) NEW_LINE
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 ] + abs ( 1 - arr [ i ] ) ; for [ i + 1 ] [ 1 ] ( i . e . current modified value is arr [ i + 1 ] ) , choose maximum from dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) and dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ; Driver Code
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 ] ) ) NEW_LINE dp [ i + 1 ] [ 1 ] = max ( dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) , dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ) NEW_LINE DEDENT return max ( dp [ N - 1 ] [ 0 ] , dp [ N - 1 ] [ 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 3 , 2 , 1 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( maximumDifferenceSum ( arr , N ) ) NEW_LINE DEDENT
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 wrapper over countStrUtil ( ) ; Driver code ; Total number of characters
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 ] != - 1 ) : NEW_LINE INDENT return dp [ n ] [ bCount ] [ cCount ] NEW_LINE DEDENT res = countStrUtil ( dp , n - 1 , bCount , cCount ) NEW_LINE res += countStrUtil ( dp , n - 1 , bCount - 1 , cCount ) NEW_LINE res += countStrUtil ( dp , n - 1 , bCount , cCount - 1 ) NEW_LINE dp [ n ] [ bCount ] [ cCount ] = res NEW_LINE return dp [ n ] [ bCount ] [ cCount ] NEW_LINE DEDENT def countStr ( n ) : NEW_LINE INDENT dp = [ [ [ - 1 for x in range ( n + 2 ) ] for y in range ( 3 ) ] for z in range ( 4 ) ] NEW_LINE return countStrUtil ( dp , n ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( countStr ( n ) ) NEW_LINE DEDENT
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 every number of steps s ; for every position ( x , y ) after s number of steps ; For every position reachable from ( x , y ) ; if this position lie inside the board ; store the result ; return the result ; number of steps ; Function Call
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 ( N + 5 ) ] for j in range ( N + 5 ) ] for k in range ( steps + 5 ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT dp1 [ i ] [ j ] [ 0 ] = 1 NEW_LINE DEDENT DEDENT for s in range ( 1 , steps + 1 ) : NEW_LINE INDENT for x in range ( N ) : NEW_LINE INDENT for y in range ( N ) : NEW_LINE INDENT prob = 0.0 NEW_LINE for i in range ( 8 ) : NEW_LINE INDENT nx = x + dx [ i ] NEW_LINE ny = y + dy [ i ] NEW_LINE if ( inside ( nx , ny ) ) : NEW_LINE INDENT prob += dp1 [ nx ] [ ny ] [ s - 1 ] / 8.0 NEW_LINE DEDENT DEDENT dp1 [ x ] [ y ] [ s ] = prob NEW_LINE DEDENT DEDENT DEDENT return dp1 [ start_x ] [ start_y ] [ steps ] NEW_LINE DEDENT K = 3 NEW_LINE print ( findProb ( 0 , 0 , K ) ) NEW_LINE
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 each element is less than equal to k . ; Suming number of subarray whose maximum element is less than equal to k . ; Driver code
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 DEDENT s = s + ( ( count * ( count + 1 ) ) // 2 ) NEW_LINE DEDENT return ( n * ( n + 1 ) // 2 - s ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print ( countSubarray ( arr , n , k ) ) NEW_LINE
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 ; each element occurs nCr ( N - 1 , n - 1 ) times while considering subset of size n ; Driver code
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 ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return C [ n ] [ k ] NEW_LINE DEDENT def resultOfAllSubsets ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT for n in range ( 1 , N + 1 ) : NEW_LINE INDENT result += ( sum * ( nCr ( N - 1 , n - 1 ) ) ) / n NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 2 , 3 , 5 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( resultOfAllSubsets ( arr , N ) ) NEW_LINE
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 three cases ; Driver code
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 [ n ] = arr [ 0 ] NEW_LINE return sum [ n ] NEW_LINE DEDENT if ( n == 2 ) : NEW_LINE INDENT sum [ n ] = arr [ 1 ] + arr [ 0 ] NEW_LINE return sum [ n ] NEW_LINE DEDENT sum [ n ] = max ( max ( maxSumWO3Consec ( n - 1 ) , maxSumWO3Consec ( n - 2 ) + arr [ n ] ) , arr [ n ] + arr [ n - 1 ] + maxSumWO3Consec ( n - 3 ) ) NEW_LINE return sum [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = len ( arr ) NEW_LINE print ( maxSumWO3Consec ( n ) ) NEW_LINE DEDENT
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 . ; Case I : Diff of arr [ i ] and arr [ i - 1 ] is less then K , add to maxSum Case II : Diff between arr [ i ] and arr [ i - 1 ] is not less then K , move to next i since with sorting we know , arr [ i ] - arr [ i - 1 ] < arr [ i ] - arr [ i - 2 ] and so on . ; Assuming only positive numbers . ; When a match is found skip this pair ; Driver Code
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_LINE DEDENT return maxSum NEW_LINE DEDENT arr = [ 3 , 5 , 10 , 15 , 17 , 12 , 9 ] NEW_LINE N = len ( arr ) NEW_LINE K = 4 NEW_LINE print ( maxSumPairWithDifferenceLessThanK ( arr , N , K ) ) NEW_LINE
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 previous sum ; Total number of subgroups till the current position ; Driver Code
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 res = res + countGroups ( i + 1 , sum , length , num ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT num = "1119" NEW_LINE len = len ( num ) NEW_LINE print ( countGroups ( 0 , 0 , len , num ) ) NEW_LINE DEDENT
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 for a given sub problem then return the value ; countGroups for current sub - group is 0 ; 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 previous sum ; total number of subgroups till the current position ; Driver Code
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 [ position ] [ previous_sum ] NEW_LINE DEDENT dp [ position ] [ previous_sum ] = 0 NEW_LINE res = 0 NEW_LINE sum = 0 NEW_LINE for i in range ( position , length ) : NEW_LINE INDENT sum += ( ord ( num [ i ] ) - ord ( '0' ) ) NEW_LINE if ( sum >= previous_sum ) : NEW_LINE INDENT res += countGroups ( i + 1 , sum , length , num ) NEW_LINE DEDENT DEDENT dp [ position ] [ previous_sum ] = res NEW_LINE return res NEW_LINE DEDENT num = "1119" NEW_LINE len = len ( num ) NEW_LINE print ( countGroups ( 0 , 0 , len , num ) ) NEW_LINE
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 ; above line finds out maximum of dp [ j ] ( excluding ith element value ) and val [ i ] + dp [ j - wt [ i ] ] ( including ith element value and the profit with " KnapSack ▁ capacity ▁ - ▁ ith ▁ element ▁ weight " ) * ; Driver program to test the cases
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 ] ; NEW_LINE wt = [ 3 , 8 , 6 ] ; NEW_LINE W = 10 ; n = 3 ; NEW_LINE print ( KnapSack ( val , wt , n , W ) ) ; NEW_LINE
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 lookup [ ] [ ] in bottom up manner ; If last characters are same , we have two options - 1. consider last characters of both strings in solution 2. ignore last character of first string ; If last character are different , ignore last character of first string ; Driver code
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 in range ( 1 , m + 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 ) : NEW_LINE INDENT if a [ i - 1 ] == b [ j - 1 ] : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i - 1 ] [ j - 1 ] + lookup [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return lookup [ m ] [ n ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = " GeeksforGeeks " NEW_LINE b = " Gks " NEW_LINE print ( count ( a , b ) ) NEW_LINE DEDENT
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 values of last column ; Consider every element as second element of GP ; Search for i and k for j ; Two cases when i , j and k don 't form a GP. ; i , j and k form GP , LLGP with i and j as first two elements is equal to LLGP with j and k as first two elements plus 1. L [ j ] [ k ] must have been filled before as we run the loop from right side ; Update overall LLGP ; Change i and k to fill more L [ i ] [ j ] values for current j ; If the loop was stopped due to k becoming more than n - 1 , set the remaining entries in column j as 1 or 2 based on divisibility of sett [ j ] by sett [ i ] ; Return result ; Driver code
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 ( 0 , n - 1 ) : NEW_LINE INDENT if sett [ n - 1 ] % sett [ i ] == 0 : NEW_LINE INDENT L [ i ] [ n - 1 ] = 2 NEW_LINE if 2 > llgp : NEW_LINE INDENT llgp = 2 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT L [ i ] [ n - 1 ] = 1 NEW_LINE DEDENT DEDENT L [ n - 1 ] [ n - 1 ] = 1 NEW_LINE for j in range ( n - 2 , 0 , - 1 ) : NEW_LINE INDENT i = j - 1 NEW_LINE k = j + 1 NEW_LINE while i >= 0 and k <= n - 1 : NEW_LINE INDENT if sett [ i ] * sett [ k ] < sett [ j ] * sett [ j ] : NEW_LINE INDENT k += 1 NEW_LINE DEDENT elif sett [ i ] * sett [ k ] > sett [ j ] * sett [ j ] : NEW_LINE INDENT if sett [ j ] % sett [ i ] == 0 : NEW_LINE INDENT L [ i ] [ j ] = 2 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT if sett [ j ] % sett [ i ] == 0 : NEW_LINE INDENT L [ i ] [ j ] = L [ j ] [ k ] + 1 NEW_LINE if L [ i ] [ j ] > llgp : NEW_LINE INDENT llgp = L [ i ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = 1 NEW_LINE DEDENT i -= 1 NEW_LINE k += 1 NEW_LINE DEDENT DEDENT while i >= 0 : NEW_LINE INDENT if sett [ j ] % sett [ i ] == 0 : NEW_LINE INDENT L [ i ] [ j ] = 2 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT DEDENT return llgp NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT set1 = [ 1 , 3 , 9 , 27 , 81 , 243 ] NEW_LINE n1 = len ( set1 ) NEW_LINE print ( lenOfLongestGP ( set1 , n1 ) ) NEW_LINE set2 = [ 1 , 3 , 4 , 9 , 7 , 27 ] NEW_LINE n2 = len ( set2 ) NEW_LINE print ( lenOfLongestGP ( set2 , n2 ) ) NEW_LINE set3 = [ 2 , 3 , 5 , 7 , 11 , 13 ] NEW_LINE n3 = len ( set3 ) NEW_LINE print ( lenOfLongestGP ( set3 , n3 ) ) NEW_LINE DEDENT
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 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; L [ i ] = { Max ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] . b < arr [ i ] . a ; print max length vector ; Driver Code
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 ( len ( arr ) ) ] NEW_LINE L [ 0 ] . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , len ( arr ) ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ j ] . b < arr [ i ] . a and len ( L [ j ] ) > len ( L [ i ] ) ) : NEW_LINE INDENT L [ i ] = L [ j ] NEW_LINE DEDENT DEDENT L [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT maxChain = [ ] NEW_LINE for x in L : NEW_LINE INDENT if len ( x ) > len ( maxChain ) : NEW_LINE INDENT maxChain = x NEW_LINE DEDENT DEDENT for pair in maxChain : NEW_LINE INDENT print ( " ( { a } , { b } ) " . format ( a = pair . a , b = pair . b ) , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ Pair ( 5 , 29 ) , Pair ( 39 , 40 ) , Pair ( 15 , 28 ) , Pair ( 27 , 40 ) , Pair ( 50 , 90 ) ] NEW_LINE n = len ( arr ) NEW_LINE maxChainLength ( arr ) NEW_LINE DEDENT
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 ; for every j less than i ; LDS [ i ] stores the length of the longest decreasing subsequence starting with arr [ i ] ; initialize LDS [ n - 1 ] to arr [ n - 1 ] ; Compute LDS values from right to left ; for every j greater than i ; reverse as vector as we 're inserting at end ; LDS [ i ] now stores Maximum Decreasing Subsequence of arr [ i . . n ] that starts with arr [ i ] ; Find maximum value of size of LIS [ i ] + size of LDS [ i ] - 1 ; print all but last element of LIS [ maxIndex ] vector ; print all elements of LDS [ maxIndex ] vector ; Driver Code
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 ] . append ( arr [ 0 ] ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( ( arr [ j ] < arr [ i ] ) and ( len ( LIS [ j ] ) > len ( LIS [ i ] ) ) ) : NEW_LINE INDENT LIS [ i ] = LIS [ j ] . copy ( ) NEW_LINE DEDENT DEDENT LIS [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT LDS = [ 0 ] * n NEW_LINE for i in range ( n ) : NEW_LINE INDENT LDS [ i ] = [ ] NEW_LINE DEDENT LDS [ n - 1 ] . append ( arr [ n - 1 ] ) NEW_LINE for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT for j in range ( n - 1 , i , - 1 ) : NEW_LINE INDENT if ( ( arr [ j ] < arr [ i ] ) and ( len ( LDS [ j ] ) > len ( LDS [ i ] ) ) ) : NEW_LINE INDENT LDS [ i ] = LDS [ j ] . copy ( ) NEW_LINE DEDENT DEDENT LDS [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT LDS [ i ] = list ( reversed ( LDS [ i ] ) ) NEW_LINE DEDENT max = 0 NEW_LINE maxIndex = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( len ( LIS [ i ] ) + len ( LDS [ i ] ) - 1 > max ) : NEW_LINE INDENT max = len ( LIS [ i ] ) + len ( LDS [ i ] ) - 1 NEW_LINE maxIndex = i NEW_LINE DEDENT DEDENT _print ( LIS [ maxIndex ] , len ( LIS [ maxIndex ] ) - 1 ) NEW_LINE _print ( LDS [ maxIndex ] , len ( LDS [ maxIndex ] ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 11 , 2 , 10 , 4 , 5 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE printLBS ( arr , n ) NEW_LINE DEDENT
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 string ; If last characters are same , ignore last character and recur for remaining string ; If last character are different , remove it and find minimum ; dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , Remove from str1 ( dp [ i ] [ j - 1 ] ) ) Remove from str2 ; Returns true if str is k palindrome . ; Driver program
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 ] = dp [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE DEDENT DEDENT return dp [ m ] [ n ] NEW_LINE DEDENT def isKPal ( string , k ) : NEW_LINE INDENT revStr = string [ : : - 1 ] NEW_LINE l = len ( string ) NEW_LINE return ( isKPalDP ( string , revStr , l , l ) <= k * 2 ) NEW_LINE DEDENT string = " acdcb " NEW_LINE k = 2 NEW_LINE print ( " Yes " if isKPal ( string , k ) else " No " ) NEW_LINE
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 ] [ j ] = 0 NEW_LINE DEDENT elif ( X [ i ] == Y [ j - 1 ] ) : NEW_LINE INDENT L [ bi ] [ j ] = L [ 1 - bi ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ bi ] [ j ] = max ( L [ 1 - bi ] [ j ] , L [ bi ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ bi ] [ n ] NEW_LINE DEDENT X = " AGGTAB " NEW_LINE Y = " GXTXAYB " NEW_LINE print ( " Length ▁ of ▁ LCS ▁ is " , lcs ( X , Y ) ) NEW_LINE
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 values of dp [ i ] [ j ] as 0 ; The xor of empty subset is 0 ; Fill the dp table ; The answer is the number of subset from set arr [ 0. . n - 1 ] having XOR of elements as k ; Driver Code
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 return 0 NEW_LINE dp = [ [ 0 for i in range ( m + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE dp [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( m + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = ( dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j ^ arr [ i - 1 ] ] ) NEW_LINE DEDENT DEDENT return dp [ n ] [ k ] NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE k = 4 NEW_LINE n = len ( arr ) NEW_LINE print ( " Count ▁ of ▁ subsets ▁ is " , subsetXOR ( arr , n , k ) ) NEW_LINE
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 first column as true . 0 sum is possible with all elements . ; Initialize top row , except dp [ 0 ] [ 0 ] , as false . With 0 elements , no other sum except 0 is possible ; Fill the partition table in bottom up manner ; If i 'th element is excluded ; If i 'th element is included ; Initialize difference of two sums . ; Find the largest j such that dp [ n ] [ j ] is true where j loops from sum / 2 t0 0 ; Driver code
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 ] = False NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , su + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE if a [ i - 1 ] <= j : NEW_LINE INDENT dp [ i ] [ j ] |= dp [ i - 1 ] [ j - a [ i - 1 ] ] NEW_LINE DEDENT DEDENT DEDENT diff = sys . maxsize NEW_LINE for j in range ( su // 2 , - 1 , - 1 ) : NEW_LINE INDENT if dp [ n ] [ j ] == True : NEW_LINE INDENT diff = su - ( 2 * j ) NEW_LINE break NEW_LINE DEDENT DEDENT return diff NEW_LINE DEDENT a = [ 3 , 1 , 4 , 2 , 2 , 1 ] NEW_LINE n = len ( a ) NEW_LINE print ( " The ▁ minimum ▁ difference ▁ between ▁ " "2 ▁ sets ▁ is ▁ " , findMin ( a , n ) ) NEW_LINE
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 invalid row or column indexes ; If current cell is top left itself ; If 0 turns left ; If direction is row , then we can reach here only if direction is row and row is 0. ; If direction is column , then we can reach here only if direction is column and column is 0. ; If this subproblem is already evaluated ; If current direction is row , then count paths for two cases 1 ) We reach here through previous row . 2 ) We reach here through previous column , so number of turns k reduce by 1. ; Similar to above if direction is column ; This function mainly initializes ' dp ' array as - 1 and calls countPathsUtil ( ) ; If ( 0 , 0 ) is target itself ; Recur for two cases : moving along row and along column ; Driver Code
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 1 NEW_LINE DEDENT if ( k == 0 ) : NEW_LINE INDENT if ( d == 0 and i == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( d == 1 and j == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return 0 NEW_LINE DEDENT if ( dp [ i ] [ j ] [ k ] [ d ] != - 1 ) : NEW_LINE INDENT return dp [ i ] [ j ] [ k ] [ d ] NEW_LINE DEDENT if ( d == 0 ) : NEW_LINE INDENT dp [ i ] [ j ] [ k ] [ d ] = countPathsUtil ( i , j - 1 , k , d ) + countPathsUtil ( i - 1 , j , k - 1 , not d ) NEW_LINE return dp [ i ] [ j ] [ k ] [ d ] NEW_LINE DEDENT dp [ i ] [ j ] [ k ] [ d ] = countPathsUtil ( i - 1 , j , k , d ) + countPathsUtil ( i , j - 1 , k - 1 , not d ) NEW_LINE return dp [ i ] [ j ] [ k ] [ d ] NEW_LINE DEDENT def countPaths ( i , j , k ) : NEW_LINE INDENT if ( i == 0 and j == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return countPathsUtil ( i - 1 , j , k , 1 ) + countPathsUtil ( i , j - 1 , k , 0 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 3 NEW_LINE n = 3 NEW_LINE k = 2 NEW_LINE print ( " Number ▁ of ▁ paths ▁ is " , countPaths ( m - 1 , n - 1 , k ) ) NEW_LINE DEDENT
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 less than 3 ; Initialize result as the case when first element is separated ( not removed using given rules ) ; Now consider all cases when first element forms a triplet and removed . Check for all possible triplets ( low , i , j ) ; Check if this triplet follows the given rules of removal . And elements between ' low ' and ' i ' , and between ' i ' and ' j ' can be recursively removed . ; Insert value in table and return result ; This function mainly initializes dp table and calls recursive function minSizeRec ; Driver program to test above function
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 DEDENT res = 1 + minSizeRec ( arr , low + 1 , high , k ) NEW_LINE for i in range ( low + 1 , high ) : NEW_LINE INDENT for j in range ( i + 1 , high + 1 ) : NEW_LINE INDENT if ( arr [ i ] == ( arr [ low ] + k ) and arr [ j ] == ( arr [ low ] + 2 * k ) and minSizeRec ( arr , low + 1 , i - 1 , k ) == 0 and minSizeRec ( arr , i + 1 , j - 1 , k ) == 0 ) : NEW_LINE INDENT res = min ( res , minSizeRec ( arr , j + 1 , high , k ) ) NEW_LINE DEDENT DEDENT DEDENT dp [ low ] [ high ] = res NEW_LINE return res NEW_LINE DEDENT def minSize ( arr , n , k ) : NEW_LINE INDENT dp = [ [ - 1 for i in range ( MAX ) ] for i in range ( MAX ) ] NEW_LINE return minSizeRec ( arr , 0 , n - 1 , k ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 4 , 5 , 6 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE k = 1 NEW_LINE print ( minSize ( arr , n , k ) ) NEW_LINE DEDENT
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 return result NEW_LINE DEDENT coeff = [ 2 , 2 , 5 ] NEW_LINE rhs = 4 NEW_LINE n = len ( coeff ) NEW_LINE print ( countSol ( coeff , 0 , n - 1 , rhs ) ) NEW_LINE
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 . Since toggle cost is 1 so overall weight gain becomes 3 ; save and return maximum of above cases ; Initializes lookup table and calls getMaxRec ( ) ; Create and initialize lookup table ; Call recursive function ; Driver Code
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 ] : NEW_LINE INDENT ans = max ( 4 + getMaxRec ( string , i + 2 , n , lookup ) , ans ) NEW_LINE DEDENT else : NEW_LINE INDENT ans = max ( 3 + getMaxRec ( string , i + 2 , n , lookup ) , ans ) NEW_LINE DEDENT DEDENT lookup [ i ] = ans NEW_LINE return ans NEW_LINE DEDENT def getMaxWeight ( string ) : NEW_LINE INDENT n = len ( string ) NEW_LINE lookup = [ - 1 ] * ( n ) NEW_LINE return getMaxRec ( string , 0 , len ( string ) , lookup ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " AAAAABB " NEW_LINE print ( " Maximum ▁ weight ▁ of ▁ a ▁ transformation ▁ of " , string , " is " , getMaxWeight ( string ) ) NEW_LINE DEDENT
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 - 1 , step + 1 , dest ) NEW_LINE return min ( pos , neg ) NEW_LINE DEDENT dest = 11 ; NEW_LINE print ( " No . ▁ of ▁ steps ▁ required " , " ▁ to ▁ reach ▁ " , dest , " ▁ is ▁ " , steps ( 0 , 0 , dest ) ) ; NEW_LINE
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 ) % 2 ] [ j - 1 ] + 1 NEW_LINE if ( dp [ i % 2 ] [ j ] > res ) : NEW_LINE INDENT res = dp [ i % 2 ] [ j ] NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT dp [ i % 2 ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT return res NEW_LINE DEDENT X = " OldSite : GeeksforGeeks . org " NEW_LINE Y = " NewSite : GeeksQuiz . com " NEW_LINE m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE print ( LCSubStr ( X , Y , m , n ) ) NEW_LINE
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 count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT X = " abcdxyz " NEW_LINE Y = " xyzabcd " NEW_LINE n = len ( X ) NEW_LINE m = len ( Y ) NEW_LINE print ( lcs ( n , m , 0 ) ) NEW_LINE DEDENT
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 ; Iterate over the array ; If the current XOR is equal to the total XOR increment the count and initialize current XOR as 0 ; Print Answer ; Driver Code ; Function Call
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 ^= A [ i ] NEW_LINE if ( cur_XOR == tot_XOR ) : NEW_LINE INDENT cnt += 1 NEW_LINE cur_XOR = 0 NEW_LINE DEDENT DEDENT if ( cnt > 2 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 0 , 2 , 2 ] NEW_LINE N = len ( A ) NEW_LINE possibleEqualArray ( A , N ) NEW_LINE DEDENT
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 ] ] ) ) : NEW_LINE INDENT Z [ i ] += 1 NEW_LINE DEDENT if ( ( i + Z [ i ] - 1 ) > r ) : NEW_LINE INDENT l = ir = i + Z [ i ] - 1 NEW_LINE DEDENT DEDENT sum = 0 NEW_LINE for i in range ( 0 , len ( Z ) ) : NEW_LINE INDENT sum += Z [ i ] + 1 NEW_LINE DEDENT return sum NEW_LINE DEDENT S = " abab " NEW_LINE print ( countPalindrome ( S ) ) NEW_LINE
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 . pop ( ) ; NEW_LINE length = i - 1 - pos ; NEW_LINE ans = string [ pos + 1 : pos + 1 + length ] ; NEW_LINE print ( ans ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " [ This ▁ is ▁ first ] ▁ ignored ▁ text ▁ [ This ▁ is ▁ second ] " ; NEW_LINE printSubsInDelimeters ( string ) ; NEW_LINE DEDENT
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 right neighbour if it exists ; Driver Code ; Given vector of vectors arr ; Function call
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 ) : NEW_LINE INDENT q . append ( [ p [ 0 ] + 1 , p [ 1 ] ] ) ; NEW_LINE DEDENT if ( p [ 1 ] + 1 < len ( nums [ p [ 0 ] ] ) ) : NEW_LINE INDENT q . append ( [ p [ 0 ] , p [ 1 ] + 1 ] ) ; NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE printDiagonalTraversal ( arr ) ; NEW_LINE DEDENT
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 answer ; Function to print the result ; Driver code ; Given array ; Function call
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 for i in range ( len ( result ) ) : NEW_LINE INDENT print ( result [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT def main ( ) : NEW_LINE INDENT arr = [ 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print_result ( restore ( arr , N ) ) NEW_LINE DEDENT main ( ) NEW_LINE
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 Array ; Function Call
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 DEDENT def print_result ( result ) : NEW_LINE INDENT for i in range ( len ( result ) ) : NEW_LINE INDENT print ( result [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE print_result ( restore ( arr , N ) ) NEW_LINE DEDENT
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 - pattern 2 and 3 will have same rows ; Increment Val to print the series 1 , 2 , 3 , 4 , 5 ... ; Finally , add the ( N - 1 ) th element i . e . , 5 and increment it by 1 ; Initial is used to give the initial value of the row in Sub - Pattern 3 ; Sub - Pattern 3 ; Skip printing zero at the last ; Given N ; Function call
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 = " " ) NEW_LINE s += " * * " NEW_LINE DEDENT for j in range ( i , N ) : NEW_LINE INDENT if ( i > 0 ) : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT Val += 1 NEW_LINE print ( Val , end = " " ) NEW_LINE print ( 0 , end = " " ) NEW_LINE DEDENT if ( i == 0 ) : NEW_LINE INDENT Sumbeforelast = sum ( Val ) * 2 NEW_LINE Pthree = Val + Sumbeforelast + 1 NEW_LINE initial = Pthree NEW_LINE DEDENT initial = initial - cnt NEW_LINE Pthree = initial NEW_LINE for k in range ( i , N ) : NEW_LINE INDENT print ( Pthree , end = " " ) NEW_LINE Pthree += 1 NEW_LINE if ( k != N - 1 ) : NEW_LINE INDENT print ( 0 , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE BSpattern ( N ) NEW_LINE
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 call ; If B is a prefix of A , then print Yes
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 DEDENT return True NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = 12345 NEW_LINE B = 12 NEW_LINE result = checkprefix ( A , B ) NEW_LINE if result : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT
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 = 5 NEW_LINE z = 11 NEW_LINE possibleToReach ( x , y , z ) NEW_LINE DEDENT
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 differences if already calculated ; Function to calculate the sum of bit differences up to N ; Nearest smaller power of 2 ; Remaining numbers ; Calculate the count of bit diff ; Driver code
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 : NEW_LINE INDENT return a [ i ] NEW_LINE DEDENT DEDENT def solve ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT i = int ( math . log2 ( n ) ) NEW_LINE n = n - pow ( 2 , i ) NEW_LINE sum = sum + ( i + 1 ) + Count ( i - 1 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT n = 7 NEW_LINE print ( solve ( n ) ) NEW_LINE
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 __name__ == " _ _ main _ _ " : NEW_LINE INDENT C = " H " NEW_LINE N = 5 NEW_LINE l = count_ht ( C , n ) NEW_LINE print ( " Head ▁ = ▁ " , l [ 0 ] ) NEW_LINE print ( " Tail ▁ = ▁ " , l [ 1 ] ) NEW_LINE DEDENT
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 ; Initialize three strings A , B AND F ; Loop to find longest substrings from both ends which are reverse of each other ; Proceed to third step of our approach ; Remove the substrings A and B ; Find the longest palindromic substring from beginning of C ; Find the longest palindromic substring from end of C ; Store the maximum of D and E in F ; Find the final answer ; Driver code
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_LINE INDENT ll += 1 NEW_LINE longestPalindrome [ i ] = ll NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT if ( ll != 0 ) : NEW_LINE INDENT ll = longestPalindrome [ ll - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT longestPalindrome [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT ans = C [ 0 : longestPalindrome [ n - 1 ] ] NEW_LINE return ans NEW_LINE DEDENT def findAns ( s ) : NEW_LINE INDENT A = " " NEW_LINE B = " " NEW_LINE F = " " NEW_LINE i = 0 NEW_LINE j = len ( s ) - 1 NEW_LINE ll = len ( s ) NEW_LINE while ( i < j and s [ i ] == s [ j ] ) : NEW_LINE INDENT i = i + 1 NEW_LINE j = j - 1 NEW_LINE DEDENT if ( i > 0 ) : NEW_LINE INDENT A = s [ 0 : i ] NEW_LINE B = s [ ll - i : ll ] NEW_LINE DEDENT if ( ll > 2 * i ) : NEW_LINE INDENT C = s [ i : i + ( len ( s ) - 2 * i ) ] NEW_LINE D = findPalindrome ( C ) NEW_LINE C = C [ : : - 1 ] NEW_LINE E = findPalindrome ( C ) NEW_LINE if ( len ( D ) > len ( E ) ) : NEW_LINE INDENT F = D NEW_LINE DEDENT else : NEW_LINE INDENT F = E NEW_LINE DEDENT DEDENT answer = A + F + B NEW_LINE return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " abcdefghiedcba " NEW_LINE print ( findAns ( str ) ) NEW_LINE DEDENT
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 DEDENT
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 _ _ " : NEW_LINE INDENT N = 5 ; NEW_LINE print ( nthTerm ( N ) ) ; NEW_LINE DEDENT
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 isVowel ( st [ i - 1 ] ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( isVowel ( st [ i ] ) and isVowel ( st [ i - 1 ] ) == False and isVowel ( st [ i + 1 ] ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT st = " acaba " NEW_LINE n = len ( st ) NEW_LINE if ( isSatisfied ( st , n ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 [ i ] for i = 1 to n - 1 ; This is tricky . Consider the example . AAACAAAA and i = 7. The idea is similar to search step . ; If len = 0 ; Since we are looking for non overlapping parts ; Function that returns the prefix ; Get the length of the longest prefix ; Stores the prefix ; Traverse and add characters ; Returns the prefix ; Driver code
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 INDENT if ( len1 != 0 ) : NEW_LINE INDENT len1 = lps [ len1 - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lps [ i ] = 0 NEW_LINE i += 1 NEW_LINE DEDENT DEDENT DEDENT res = lps [ n - 1 ] NEW_LINE if ( res > int ( n / 2 ) ) : NEW_LINE INDENT return int ( n / 2 ) NEW_LINE DEDENT else : NEW_LINE INDENT return res NEW_LINE DEDENT DEDENT def longestPrefixSuffix ( s ) : NEW_LINE INDENT len1 = LengthlongestPrefixSuffix ( s ) NEW_LINE prefix = " " NEW_LINE for i in range ( len1 ) : NEW_LINE INDENT prefix += s [ i ] NEW_LINE DEDENT return prefix NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " abcab " NEW_LINE ans = longestPrefixSuffix ( s ) NEW_LINE if ( ans == " " ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ans ) NEW_LINE DEDENT DEDENT
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 represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and 'B ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code
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 ) : NEW_LINE INDENT k = no_of_characters ( M ) NEW_LINE N = M - ( pow ( 2 , k ) - 2 ) NEW_LINE while ( k > 0 ) : NEW_LINE INDENT num = pow ( 2 , k - 1 ) NEW_LINE if ( num >= N ) : NEW_LINE INDENT print ( " A " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " B " , end = " " ) NEW_LINE N -= num NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT print ( " " , ▁ end ▁ = ▁ " " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = 30 ; NEW_LINE print_string ( M ) NEW_LINE M = 55 NEW_LINE print_string ( M ) NEW_LINE M = 100 NEW_LINE print_string ( M ) NEW_LINE DEDENT
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 ; Driver code
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_LINE INDENT new_string = S [ 0 : i ] + A + S [ i + l : len ( S ) ] NEW_LINE S = new_string NEW_LINE i += l - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return S NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aab " NEW_LINE A = " aa " NEW_LINE B = " bb " NEW_LINE print ( updateString ( S , A , B ) ) NEW_LINE DEDENT
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 != 0 ) : NEW_LINE INDENT print ( "0" , end = " " ) NEW_LINE DEDENT if ( m != 0 ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while ( m - n > 1 and n > 0 ) : NEW_LINE INDENT print ( "110" , end = " " ) NEW_LINE m = m - 2 NEW_LINE n = n - 1 NEW_LINE DEDENT while ( n > 0 ) : NEW_LINE INDENT print ( "10" , end = " " ) NEW_LINE n -= 1 NEW_LINE m -= 1 NEW_LINE DEDENT while ( m > 0 ) : NEW_LINE INDENT print ( "1" , end = " " ) NEW_LINE m -= 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE m = 8 NEW_LINE printPattern ( n , m ) NEW_LINE DEDENT
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 than 1 ; Driver Code
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 += ( ( ( len - 1 ) * len ) // 2 ) NEW_LINE DEDENT return cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ 100 , 3 , 1 , 13 ] NEW_LINE n = len ( A ) NEW_LINE print ( countDecreasing ( A , n ) ) NEW_LINE DEDENT
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 the sizes of both strings ; Traverse the string S2 ; From every index in S2 , check the number of mis - matching characters in substring of length of S1 ; Take minimum of prev and current mis - match ; return answer ; Driver Code
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 NEW_LINE DEDENT DEDENT ans = min ( minRemovedChar , ans ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S1 = " abc " NEW_LINE S2 = " paxzk " NEW_LINE print ( minimumChar ( S1 , S2 ) ) NEW_LINE DEDENT
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 ) : NEW_LINE INDENT res += 1 NEW_LINE j = 0 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT txt = " dhimanman " NEW_LINE pat = " man " NEW_LINE print ( countFreq ( pat , txt ) ) NEW_LINE DEDENT
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 ; Driver program to test the above function
def search ( pat , txt ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE i = 0 NEW_LINE while i <= N - M : NEW_LINE INDENT for j in xrange ( M ) : NEW_LINE INDENT if txt [ i + j ] != pat [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE print " Pattern ▁ found ▁ at ▁ index ▁ " + str ( i ) NEW_LINE i = i + M NEW_LINE DEDENT elif j == 0 : NEW_LINE INDENT i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT i = i + j NEW_LINE DEDENT DEDENT DEDENT txt = " ABCEABCDABCEABCD " NEW_LINE pat = " ABCD " NEW_LINE search ( pat , txt ) NEW_LINE
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 the value of b mod 11 for large value of a as per the derived formula ; Stores the value of c % 11 ; Keeps track of the sign of x ; If the current digit is the missing digit , then keep the track of its sign ; Find the value of x using the derived equation ; Check if x has a negative sign ; Return positive equivaluent of x mod 11 ; Driver Code
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 ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT b_mod_11 = ( b_mod_11 + w * ( ord ( b [ i ] ) - ord ( '0' ) ) ) % 11 NEW_LINE w = w * - 1 NEW_LINE DEDENT c_mod_11 = 0 NEW_LINE xSignIsPositive = True NEW_LINE w = 1 NEW_LINE for i in range ( len ( c ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( c [ i ] == ' x ' ) : NEW_LINE INDENT xSignIsPositive = ( w == 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT c_mod_11 = ( c_mod_11 + w * ( ord ( c [ i ] ) - ord ( '0' ) ) ) % 11 NEW_LINE DEDENT w = w * - 1 NEW_LINE DEDENT x = ( ( a_mod_11 * b_mod_11 ) - c_mod_11 ) % 11 NEW_LINE if ( not xSignIsPositive ) : NEW_LINE INDENT x = - x NEW_LINE DEDENT return ( x % 11 + 11 ) % 11 NEW_LINE DEDENT A = "123456789" NEW_LINE B = "987654321" NEW_LINE C = "12193263111x635269" NEW_LINE print ( findMissingDigit ( A , B , C ) ) NEW_LINE
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_LINE DEDENT else : NEW_LINE INDENT id = 0 NEW_LINE flag = True NEW_LINE for i in range ( N ) : NEW_LINE INDENT if str_ [ i ] == ' G ' : NEW_LINE INDENT countG -= 1 NEW_LINE id += 1 NEW_LINE DEDENT else : NEW_LINE INDENT countF -= 1 NEW_LINE id -= 1 NEW_LINE DEDENT if id < 0 : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT if countG < countF : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if flag : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT DEDENT n = 6 NEW_LINE str_ = " GFGFGG " NEW_LINE findIfPossible ( n , str_ ) NEW_LINE
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 over str1 ; Store the presence or every element ; Iterate over str2 ; Ignore the spaces ; Check for the presence of character in str1 ; If it is possible to make str2 from str1 ; Given strings ; Function call .
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 [ i ] ] == 1 : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT possible = False NEW_LINE break NEW_LINE DEDENT DEDENT DEDENT if possible : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT str1 = " we ▁ all ▁ love ▁ geeksforgeeks " NEW_LINE str2 = " we ▁ all ▁ love ▁ geeks " NEW_LINE isPossible ( str1 , str2 ) NEW_LINE
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 characters are not same ; Driver Code
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 ] = '1' NEW_LINE DEDENT if ( s1 [ i + 1 ] == '1' ) : NEW_LINE INDENT s1 [ i + 1 ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT s1 [ i + 1 ] = '1' NEW_LINE DEDENT count += 1 NEW_LINE DEDENT DEDENT s1 = ' ' . join ( s1 ) NEW_LINE s2 = ' ' . join ( s2 ) NEW_LINE if ( s1 == s2 ) : NEW_LINE INDENT return count NEW_LINE DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 4 NEW_LINE s1 = "0101" NEW_LINE s2 = "1111" NEW_LINE print ( find_Min_Inversion ( n , s1 , s2 ) ) NEW_LINE DEDENT
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 length with character ch ; Function to find the maximum length of subsequence of consecutive characters ; Stores the maximum length of consecutive characters ; Update ans ; Return the maximum length of subsequence ; Driver Code ; Input ; Function Call
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 NEW_LINE for ch in range ( ord ( ' a ' ) , ord ( ' z ' ) + 1 ) : NEW_LINE INDENT ans = max ( ans , findSubsequence ( S , chr ( ch ) ) ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcabefghijk " NEW_LINE print ( findMaxSubsequence ( S ) ) NEW_LINE DEDENT
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 possible ; Increment the value of cn0 by 1 ; To balance 1 with 0 if possible ; Increment the value of cn1 ; Update the maximum number of unused 0 s and 1 s ; Print resultant count ; Driver Code
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_LINE INDENT cn0 -= 1 NEW_LINE DEDENT cn1 += 1 NEW_LINE DEDENT ans = max ( [ ans , cn0 , cn1 ] ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "010101" NEW_LINE minOpsToEmptyString ( S ) NEW_LINE DEDENT
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 the range [ i , N - 1 ] ; Find the suffix sum ; If the current element is '0' , update post [ i ] ; Stores the maximum length ; Find the maximum value of pre [ i ] + post [ i ] ; Return the answer ; Driver Code
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 , - 1 ) : NEW_LINE INDENT if ( i != ( n - 1 ) ) : NEW_LINE INDENT post [ i ] += post [ i + 1 ] NEW_LINE DEDENT if ( str [ i ] == '0' ) : NEW_LINE INDENT post [ i ] += 1 NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans = max ( ans , pre [ i ] + post [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT S = "0101110110100001011" NEW_LINE n = len ( S ) NEW_LINE print ( findLength ( S , n ) ) NEW_LINE
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 having equal number of lowercase and uppercase characters ; Stores the sum obtained so far ; If the character is uppercase ; Otherwise ; If currsum is o ; If the current sum exists in the HashMap prevSum ; Increment the resultant count by 1 ; Update the frequency of the current sum by 1 ; Return the resultant count of the subarrays ; Driver Code
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 ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT if ( currentSum in prevSum ) : NEW_LINE INDENT res += ( prevSum [ currentSum ] ) NEW_LINE DEDENT if currentSum in prevSum : NEW_LINE INDENT prevSum [ currentSum ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT prevSum [ currentSum ] = 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " gEEk " NEW_LINE print ( countSubstring ( S , len ( S ) ) ) NEW_LINE DEDENT
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 frequency of characters ; Count frequency of each character ; Traverse the dictionary ; If any of the keys have odd count ; Otherwise ; Return count ; Driver Code
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_LINE for keys in res : NEW_LINE INDENT if res [ keys ] % 2 != 0 : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if flag == 0 : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT DEDENT return count NEW_LINE DEDENT S = " abbaa " NEW_LINE N = len ( S ) NEW_LINE print ( subString ( S , N ) ) NEW_LINE
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 [ ] ; Stores the current pair of strings ; Swap the first characters ; Check if they are already present in the array or not ; If both the strings are not present ; Increment the ans by 1 ; Print the resultant count ; Driver Code
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 ] = q [ 0 ] NEW_LINE q [ 0 ] = temp NEW_LINE p = ' ' . join ( p ) NEW_LINE q = ' ' . join ( q ) NEW_LINE flag1 = 0 NEW_LINE flag2 = 0 NEW_LINE for k in range ( n ) : NEW_LINE INDENT if ( a [ k ] == p ) : NEW_LINE INDENT flag1 = 1 NEW_LINE DEDENT if ( a [ k ] == q ) : NEW_LINE INDENT flag2 = 1 NEW_LINE DEDENT DEDENT if ( flag1 == 0 and flag2 == 0 ) : NEW_LINE INDENT ans = ans + 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " good " , " bad " , " food " ] NEW_LINE N = len ( arr ) NEW_LINE countStringPairs ( arr , N ) NEW_LINE DEDENT
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 ; Update the count of R ; Update the count of U ; Update the count of D ; Condition 1 for reaching the circumference ; Store the the value of ( i * i ) in the Map ; Check if ( r_square - i * i ) already present in HashMap ; If it is possible to reach the point ( mp [ r_square - i * i ] , i ) ; If it is possible to reach the point ( i , mp [ r_square - i * i ] ) ; If it is impossible to reach ; Driver Code
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_LINE DEDENT elif ( S [ i ] == ' U ' ) : NEW_LINE INDENT cntu += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cntd += 1 NEW_LINE DEDENT DEDENT if ( max ( max ( cntl , cntr ) , max ( cntu , cntd ) ) >= R ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT mp = { } NEW_LINE r_square = R * R NEW_LINE i = 1 NEW_LINE while i * i <= r_square : NEW_LINE INDENT mp [ i * i ] = i NEW_LINE if ( ( r_square - i * i ) in mp ) : NEW_LINE INDENT if ( max ( cntl , cntr ) >= mp [ r_square - i * i ] and max ( cntu , cntd ) >= i ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT if ( max ( cntl , cntr ) >= i and max ( cntu , cntd ) >= mp [ r_square - i * i ] ) : NEW_LINE INDENT return " Yes " NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT return " No " NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " RDLLDDLDU " NEW_LINE R = 5 NEW_LINE N = len ( S ) NEW_LINE print ( isPossible ( S , R , N ) ) NEW_LINE DEDENT
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 string S ; If b exceeds 122 ; Replace the character ; Print resultant string ; Driver Code ; Given strings ; Function call to modify string S by given operations
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__ == " _ _ main _ _ " : NEW_LINE INDENT S = " sun " NEW_LINE N = "966" NEW_LINE addASCII ( S , N ) NEW_LINE DEDENT
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 values ; Stores answer ; Traverse the string ; If digit ; If character ; Return the answer ; Function to move all the alphabets to front ; Function to modify each array element by removing characters from their hexadecimal representation which are present in a given string ; Traverse the array ; Stores hexadecimal value ; Remove the characters from hexadecimal representation present in string S ; Stores decimal value ; Replace array element ; Print the modified array ; Given array ; Given string ; Function call to modify array by given operations
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 [ : : - 1 ] NEW_LINE return ans NEW_LINE DEDENT def hexDec ( convertedHex ) : NEW_LINE INDENT mp = { " A " : 10 , " B " : 11 , " C " : 12 , " D " : 13 , " E " : 14 , " F " : 15 } NEW_LINE ans = 0 NEW_LINE pos = 0 NEW_LINE for i in convertedHex [ : : - 1 ] : NEW_LINE INDENT if i . isdigit ( ) : NEW_LINE INDENT ans += ( 16 ** pos ) * int ( i ) NEW_LINE DEDENT else : NEW_LINE INDENT ans += ( 16 ** pos ) * mp [ i ] NEW_LINE DEDENT pos += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT def removeChars ( hexaVal , S ) : NEW_LINE INDENT setk = set ( ) NEW_LINE for i in S : NEW_LINE INDENT setk . add ( i ) NEW_LINE DEDENT ans = ' ' NEW_LINE for i in hexaVal : NEW_LINE INDENT if i in setk : NEW_LINE INDENT continue NEW_LINE DEDENT ans += i NEW_LINE DEDENT return ans NEW_LINE DEDENT def convertArr ( arr , S ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT hexaVal = decHex ( arr [ i ] ) NEW_LINE convertedHex = removeChars ( hexaVal , S ) NEW_LINE decVal = hexDec ( convertedHex ) NEW_LINE arr [ i ] = decVal NEW_LINE DEDENT print ( arr ) NEW_LINE DEDENT arr = [ 74 , 91 , 31 , 122 ] NEW_LINE S = "1AB " NEW_LINE convertArr ( arr , S ) NEW_LINE
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 Map M , then return - 1 ; Update S [ i ] ; Print the string S ; Driver Code
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 ( - 1 ) NEW_LINE return NEW_LINE DEDENT s [ i ] = mp [ i % k ] NEW_LINE DEDENT s = ' ' . join ( s ) NEW_LINE print ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ? ? ? ? abcd " NEW_LINE K = 4 NEW_LINE fillString ( S , K ) NEW_LINE DEDENT
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 condition satisfies ; Check if the number of unique characters in s2 is 1 ; Store the unique character frequency ; Store occurence of it in s1 ; Find count of that character in the s1 ; Increment count by 1 if that unique character is same as current character ; If count count_in_s1 is less than count_in_s2 , then prs1 and return ; Otherwise , there is no possible arrangement ; Checks if any character in s2 is less than its next character ; Iterate the string , s2 ; If s [ i ] is greater than the s [ i + 1 ] ; Set inc to 0 ; If inc = 1 , prs1 in decreasing order ; Otherwise , prs1 in increasing order ; Driver code
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 if ( unique == 1 ) : NEW_LINE INDENT count_in_s2 = len ( s2 ) NEW_LINE count_in_s1 = 0 NEW_LINE for i in range ( len ( s1 ) ) : NEW_LINE INDENT if ( s1 [ i ] == s2 [ 0 ] ) : NEW_LINE INDENT count_in_s1 += 1 NEW_LINE DEDENT DEDENT if ( count_in_s1 < count_in_s2 ) : NEW_LINE INDENT print ( s1 , end = " " ) NEW_LINE return NEW_LINE DEDENT print ( - 1 , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT inc = 1 NEW_LINE for i in range ( len ( s2 ) - 1 ) : NEW_LINE INDENT if ( s2 [ i ] > s2 [ i + 1 ] ) : NEW_LINE INDENT inc = 0 NEW_LINE DEDENT DEDENT if ( inc == 1 ) : NEW_LINE INDENT s1 = sorted ( s1 ) [ : : - 1 ] NEW_LINE print ( " " . join ( s1 ) , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT s1 = sorted ( s1 ) NEW_LINE print ( " " . join ( s1 ) , end = " " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s1 , s2 = " abcd " , " ab " NEW_LINE rearrangeString ( s1 , s2 ) NEW_LINE 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 ; Driver code
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_LINE DEDENT if ( len ( s ) == 0 ) : NEW_LINE return True NEW_LINE else : NEW_LINE return False NEW_LINE DEDENT Str = "11011000" NEW_LINE if ( isReducible ( Str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT
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 ; store count of vowels and consonants respectively ; store the resultant string ; store count of consonants append into ans ; Append vowel to ans ; Append consonants ; Appendconsonant to ans ; update temp ; Remove the taken elements of consonant ; return final answer ; Driver code ; Function Call
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 = len ( consonants ) NEW_LINE Nv = len ( vowels ) NEW_LINE M = Nc // ( Nv - 1 ) NEW_LINE ans = " " NEW_LINE consonant_till = 0 NEW_LINE for i in vowels : NEW_LINE INDENT ans += i NEW_LINE temp = 0 NEW_LINE for j in range ( consonant_till , min ( Nc , consonant_till + M ) ) : NEW_LINE INDENT ans += consonants [ j ] NEW_LINE temp += 1 NEW_LINE DEDENT consonant_till += temp NEW_LINE DEDENT return ans NEW_LINE DEDENT S = " aaaabbbcc " NEW_LINE print ( solution ( S ) ) NEW_LINE
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 ] using i ; When k reaches 0 , break the loop ; If current character is ' a ' , continue ; Otherwise , iterate in the range [ i + 1 , n - 1 ] using j ; Check if s [ j ] > s [ i ] ; If true , set s [ j ] = s [ i ] and break out of the loop ; Check if j reaches the last index ; Update S [ i ] ; Decrement k by 1 ; Print string ; Driver Code ; Given String , s ; Given k ; Function Call
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 == 0 ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( s [ j ] > s [ i ] ) : NEW_LINE INDENT s [ j ] = s [ i ] ; NEW_LINE break ; NEW_LINE DEDENT elif ( j == n - 1 ) : NEW_LINE INDENT s [ j ] = s [ i ] ; NEW_LINE DEDENT DEDENT s [ i ] = ' a ' ; NEW_LINE k -= 1 NEW_LINE DEDENT print ( ' ' . join ( s ) , end = ' ' ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = list ( " geeksforgeeks " ) ; NEW_LINE k = 6 ; NEW_LINE smallestlexicographicstring ( s , k ) ; NEW_LINE DEDENT
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 ; Increment c1 by one , if current frequency is 1 ; Increment c2 by one , if current frequency is 2 ; Count palindromic strings of length 3 having the character at the ends different from that present in the middle ; Update c1 and c2 ; Increment res by 2 * c2 / 3 ; Finally print the result ; Driver Code ; Given array ; Function Call
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 NEW_LINE DEDENT DEDENT res += min ( c1 , c2 ) NEW_LINE t = min ( c1 , c2 ) NEW_LINE c1 -= t NEW_LINE c2 -= t NEW_LINE res += 2 * ( c2 // 3 ) NEW_LINE c2 %= 3 NEW_LINE res += c2 // 2 NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 4 , 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] NEW_LINE maximum_pallindromic ( arr ) NEW_LINE DEDENT
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 length of current string ; Traverse the string ; Insert arr [ i ] [ j ] ; 1 st Player starts the game ; Stores the player number for the next turn ; Remove 1 st character of current string ; Update player number for the next turn ; Driver Code
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 ] ) - 1 ) NEW_LINE DEDENT DEDENT player = 0 NEW_LINE while ( len ( Q [ player ] ) > 0 ) : NEW_LINE INDENT nextPlayer = Q [ player ] [ 0 ] - ord ( '0' ) NEW_LINE del Q [ player ] [ 0 ] NEW_LINE player = nextPlayer NEW_LINE DEDENT print ( " Player " , ( player + 1 ) ) NEW_LINE DEDENT N = 3 NEW_LINE arr = [ "323" , "2" , "2" ] NEW_LINE find_Winner ( arr , N ) NEW_LINE
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 the longest substring in s which is a palindrome for even count ; Finding the length of the longest substring in s which is a palindrome for one odd count ; Finding maximum length of substring having one odd count ; dp [ mask ] is minimum of current i and dp [ mask ] ; Return longest length of the substring which forms a palindrome with swaps ; Driver Code ; Input String ; Function Call
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_LINE INDENT res = max ( res , i - dp [ mask ^ ( 1 << j ) ] ) NEW_LINE DEDENT dp [ mask ] = min ( dp [ mask ] , i ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "3242415" NEW_LINE print ( longestSubstring ( s ) ) NEW_LINE DEDENT
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 ( ) and separate them with " - " 0 to 2 index 1 st group ; 3 to 5 index 2 nd group ; 6 to 8 index 3 rd group ; 9 to 9 index last group ; Print final result ; Driver Code ; Given ; Function Call
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 NEW_LINE DEDENT res = " " NEW_LINE x = temp [ 0 : 3 ] NEW_LINE res += " ( " + x + " ) - " NEW_LINE x = temp [ 3 : 3 + 3 ] NEW_LINE res += " ( " + x + " ) - " NEW_LINE x = temp [ 6 : 3 + 6 ] NEW_LINE res += " ( " + x + " ) - " NEW_LINE x = temp [ 9 : 1 + 9 ] NEW_LINE res += " ( " + x + " ) " NEW_LINE print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT M = "91 ▁ 234rt5%34*0 ▁ 3" NEW_LINE Validate ( M ) NEW_LINE DEDENT
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 base ; Print the answer converting into hexadecimal ; Driver Code ; Given string N and K ; Function Call
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 ; NEW_LINE m = int ( k ) ; NEW_LINE base = 1 ; NEW_LINE ans = 0 ; NEW_LINE for i in range ( len ( s ) - 1 , - 1 , - 1 ) : NEW_LINE INDENT n = mp [ s [ i ] ] % m ; NEW_LINE ans = ( ans + ( base % m * n % m ) % m ) % m ; NEW_LINE base = ( base % m * 16 % m ) % m ; NEW_LINE DEDENT ans = hex ( int ( ans ) ) [ - 1 ] . upper ( ) NEW_LINE print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = "3E8" ; NEW_LINE k = "13" ; NEW_LINE hexaModK ( n , k ) ; NEW_LINE DEDENT
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 that are at most N ; Iterate over string s ; Push ith character to combination ; Convert the string to number ; Check if the condition is true ; Push the current string to the final set of sequences ; Recursively call function ; Backtrack to its previous state ; Driver Code ; Function Call ; Print required sequences
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 ) ) : NEW_LINE INDENT combination += s [ i ] ; NEW_LINE x = int ( combination ) ; NEW_LINE if ( x <= n ) : NEW_LINE INDENT combinations . append ( combination ) ; NEW_LINE generateCombinations ( s , n ) ; NEW_LINE DEDENT combination = combination [ : - 1 ] ; NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "124" ; NEW_LINE N = 100 ; NEW_LINE generateCombinations ( S , N ) ; NEW_LINE printSequences ( combinations ) ; NEW_LINE DEDENT
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 the array ; Stores hash value of arr [ i ] ; Sort hash [ ] array ; Stores count of distinct strings in the array ; Traverse hash [ ] array ; Update cntElem ; Driver Code
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 distinct_str ( arr , n ) : NEW_LINE INDENT hash = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ i ] = compute_hash ( arr [ i ] ) NEW_LINE DEDENT hash = sorted ( hash ) NEW_LINE cntElem = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( hash [ i ] != hash [ i - 1 ] ) : NEW_LINE INDENT cntElem += 1 NEW_LINE DEDENT DEDENT return cntElem NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " abcde " , " abcce " , " abcdf " , " abcde " ] NEW_LINE N = len ( arr ) NEW_LINE print ( distinct_str ( arr , N ) ) NEW_LINE DEDENT
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 ; Function to remove characters which have prime frequency in the String ; Length of the String ; Create a bool array prime ; Sieve of Eratosthenes ; Stores the frequency of character ; Storing the frequencies ; New String that will be formed ; Removing the characters which have prime frequencies ; If the character has prime frequency then skip ; Else concatenate the character to the new String ; Print the modified String ; Driver Code ; Function Call
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 INDENT prime [ i * j ] = False NEW_LINE j += 1 NEW_LINE DEDENT DEDENT i += 1 NEW_LINE DEDENT DEDENT def removePrimeFrequencies ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE prime = [ False ] * ( n + 1 ) NEW_LINE SieveOfEratosthenes ( prime , n ) NEW_LINE m = { } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if s [ i ] in m : NEW_LINE INDENT m [ s [ i ] ] += 1 NEW_LINE DEDENT else : NEW_LINE INDENT m [ s [ i ] ] = 1 NEW_LINE DEDENT DEDENT new_String = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( prime [ m [ s [ i ] ] ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT new_String += s [ i ] NEW_LINE DEDENT print ( new_String , end = " " ) NEW_LINE DEDENT Str = " geeksforgeeks " NEW_LINE removePrimeFrequencies ( list ( Str ) ) NEW_LINE
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 respective counts differ by 1 ; Desired arrangement not possible ; Stores the indexes ; Check if first character should be alphabet or digit ; Place alphabets and digits alternatively ; If current character needs to be alphabet ; If current character needs to be a digit ; Flip flag for alternate arrangement ; Return resultant string ; Driver Code ; Given String ; Function call
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_LINE INDENT return " - 1" NEW_LINE DEDENT i = 0 NEW_LINE j = 0 NEW_LINE k = 0 NEW_LINE flag = 0 NEW_LINE if ( n >= m ) : NEW_LINE INDENT flag = 1 NEW_LINE DEDENT else : NEW_LINE INDENT flag = 0 NEW_LINE DEDENT while ( i < n and j < m ) : NEW_LINE INDENT if ( flag ) : NEW_LINE INDENT s [ k ] = s1 [ i ] NEW_LINE k += 1 NEW_LINE i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT s [ k ] = s2 [ j ] NEW_LINE k += 1 NEW_LINE j += 1 NEW_LINE DEDENT flag = not flag NEW_LINE DEDENT return " " . join ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeks2020" NEW_LINE str1 = [ i for i in str ] NEW_LINE print ( rearrange ( str1 ) ) NEW_LINE DEDENT
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 ; Function call
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 ] + str [ ind + 1 : ] ; NEW_LINE n -= 1 ; NEW_LINE count += ind + 1 ; NEW_LINE DEDENT print ( count ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aabbc " ; NEW_LINE n = 5 ; NEW_LINE charactersCount ( str , n ) ; NEW_LINE DEDENT
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 generated string ; Add current string to result of other strings and check if characters are unique or not ; Function to find the maximum possible length of a string ; Return max length possible ; Return the answer ; Driver Code
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 = helper ( arr , ind + 1 ) NEW_LINE ret = tmp NEW_LINE for i in tmp : NEW_LINE INDENT test = i + arr [ ind ] NEW_LINE if ( check ( test ) ) : NEW_LINE INDENT ret . append ( test ) NEW_LINE DEDENT DEDENT return ret NEW_LINE DEDENT def maxLength ( arr ) : NEW_LINE INDENT tmp = helper ( arr , 0 ) NEW_LINE l = 0 NEW_LINE for i in tmp : NEW_LINE INDENT l = l if l > len ( i ) else len ( i ) NEW_LINE DEDENT return l NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = [ ] NEW_LINE s . append ( " abcdefgh " ) NEW_LINE print ( maxLength ( s ) ) NEW_LINE DEDENT
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 sum will be A [ R - 1 ] - A [ L - 2 ] ; Given string ; Given Queries ; Function call
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 ( Query ) ) : NEW_LINE INDENT if ( Query [ i ] [ 0 ] == 1 ) : NEW_LINE INDENT print ( A [ Query [ i ] [ 1 ] - 1 ] ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( A [ Query [ i ] [ 1 ] - 1 ] - A [ Query [ i ] [ 0 ] - 2 ] ) NEW_LINE DEDENT DEDENT DEDENT S = " abcd " NEW_LINE Query = [ ] NEW_LINE Query . append ( [ 2 , 4 ] ) NEW_LINE Query . append ( [ 1 , 3 ] ) NEW_LINE Range_sum_query ( S , Query ) NEW_LINE