text
stringlengths 17
3.65k
| code
stringlengths 70
5.84k
|
---|---|
Minimum time to write characters using insert , delete and copy operation | Python3 program to write characters in minimum time by inserting , removing and copying operation ; method returns minimum time to write ' N ' characters ; declare dp array and initialize with zero ; first char will always take insertion time ; loop for ' N ' number of times ; if current char count is even then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy ; if current char count is odd then choose minimum from result for ( i - 1 ) chars and time for insertion and result for half of chars and time for copy and one extra character deletion ; Driver Code | def minTimeForWritingChars ( N , insert , remov , cpy ) : NEW_LINE INDENT if N == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if N == 1 : NEW_LINE INDENT return insert NEW_LINE DEDENT dp = [ 0 ] * ( N + 1 ) NEW_LINE dp [ 1 ] = insert NEW_LINE for i in range ( 2 , N + 1 ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 1 ] + insert , dp [ i // 2 ] + cpy ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = min ( dp [ i - 1 ] + insert , dp [ ( i + 1 ) // 2 ] + cpy + remov ) NEW_LINE DEDENT DEDENT return dp [ N ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 9 NEW_LINE insert = 1 NEW_LINE remov = 2 NEW_LINE cpy = 1 NEW_LINE print ( minTimeForWritingChars ( N , insert , remov , cpy ) ) NEW_LINE DEDENT |
Count the number of ways to tile the floor of size n x m using 1 x m size tiles | function to count the total number of ways ; table to store values of subproblems ; Fill the table upto value n ; recurrence relation ; base cases ; i = = m ; required number of ways ; Driver code | def countWays ( n , m ) : NEW_LINE INDENT count = [ ] NEW_LINE for i in range ( n + 2 ) : NEW_LINE INDENT count . append ( 0 ) NEW_LINE DEDENT count [ 0 ] = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( i > m ) : NEW_LINE INDENT count [ i ] = count [ i - 1 ] + count [ i - m ] NEW_LINE DEDENT elif ( i < m or i == 1 ) : NEW_LINE INDENT count [ i ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT count [ i ] = 2 NEW_LINE DEDENT DEDENT return count [ n ] NEW_LINE DEDENT n = 7 NEW_LINE m = 4 NEW_LINE print ( " Number β of β ways β = β " , countWays ( n , m ) ) NEW_LINE |
Longest alternating subsequence | Function for finding longest alternating subsequence ; " inc " and " dec " initialized as 1 as single element is still LAS ; Iterate from second element ; " inc " changes iff " dec " changes ; " dec " changes iff " inc " changes ; Return the maximum length ; Driver Code ; Function Call | def LAS ( arr , n ) : NEW_LINE INDENT inc = 1 NEW_LINE dec = 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] > arr [ i - 1 ] ) : NEW_LINE INDENT inc = dec + 1 NEW_LINE DEDENT elif ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT dec = inc + 1 NEW_LINE DEDENT DEDENT return max ( inc , dec ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 10 , 22 , 9 , 33 , 49 , 50 , 31 , 60 ] NEW_LINE n = len ( arr ) NEW_LINE print ( LAS ( arr , n ) ) NEW_LINE DEDENT |
Minimum number of deletions to make a string palindrome | Utility function for calculating Minimum element to delete ; Condition to compare characters ; Recursive function call ; Return value , increamenting by 1 return minimum Element between two values ; Function to calculate the minimum Element required to delete for Making string pelindrom ; Utility function call ; Driver code | def utility_fun_for_del ( Str , i , j ) : NEW_LINE INDENT if ( i >= j ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( Str [ i ] == Str [ j ] ) : NEW_LINE INDENT return utility_fun_for_del ( Str , i + 1 , j - 1 ) NEW_LINE DEDENT return ( 1 + min ( utility_fun_for_del ( Str , i + 1 , j ) , utility_fun_for_del ( Str , i , j - 1 ) ) ) NEW_LINE DEDENT def min_ele_del ( Str ) : NEW_LINE INDENT return utility_fun_for_del ( Str , 0 , len ( Str ) - 1 ) NEW_LINE DEDENT Str = " abefbac " NEW_LINE print ( " Minimum β element β of β deletions β = " , min_ele_del ( Str ) ) NEW_LINE |
Minimum number of deletions to make a string palindrome | function definition ; base cases ; checking the ndesired condition ; if yes increment the cunt ; if no ; return the value form the table ; else store the max tranforamtion from the subsequence ; return the dp [ - 1 ] [ - 1 ] ; ; initialize the array with - 1 | def transformation ( s1 , s2 , i , j , dp ) : NEW_LINE INDENT if i >= len ( s1 ) or j >= len ( s2 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if s1 [ i ] == s2 [ j ] : NEW_LINE INDENT dp [ i ] [ j ] = 1 + transformation ( s1 , s2 , i + 1 , j + 1 , dp ) NEW_LINE DEDENT if dp [ i ] [ j ] != - 1 : NEW_LINE INDENT return dp [ i ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = max ( transformation ( s1 , s2 , i , j + i , dp ) , transformation ( s1 , s2 , i + 1 , j , dp ) ) NEW_LINE DEDENT return dp [ - 1 ] [ - 1 ] NEW_LINE DEDENT s1 = " geeksforgeeks " NEW_LINE s2 = " geeks " NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE / * Driver code * / NEW_LINE dp = [ [ - 1 for _ in range ( len ( s1 ) + 1 ) ] for _ in range ( len ( s2 ) + 1 ) ] NEW_LINE print ( " MINIMUM β NUMBER β OF β DELETIONS : β " , len ( s1 ) - transformation ( s1 , s2 , 0 , 0 , dp ) , end = " β " ) NEW_LINE print ( " MINIMUM β NUMBER β OF β INSERTIONS : β " , len ( s2 ) - transformation ( s1 , s2 , 0 , 0 , dp ) , end = " β " ) NEW_LINE print ( " LCS β LENGTH : β " , transformation ( s1 , s2 , 0 , 0 , dp ) ) NEW_LINE |
Largest sum Zigzag sequence in a matrix | Python3 program to find the largest sum zigzag sequence ; Returns largest sum of a Zigzag sequence starting from ( i , j ) and ending at a bottom cell . ; If we have reached bottom ; Find the largest sum by considering all possible next elements in sequence . ; Returns largest possible sum of a Zizag sequence starting from top and ending at bottom . ; Consider all cells of top row as starting point ; Driver Code | MAX = 100 NEW_LINE def largestZigZagSumRec ( mat , i , j , n ) : NEW_LINE INDENT if ( i == n - 1 ) : NEW_LINE INDENT return mat [ i ] [ j ] NEW_LINE DEDENT zzs = 0 NEW_LINE for k in range ( n ) : NEW_LINE INDENT if ( k != j ) : NEW_LINE INDENT zzs = max ( zzs , largestZigZagSumRec ( mat , i + 1 , k , n ) ) NEW_LINE DEDENT DEDENT return zzs + mat [ i ] [ j ] NEW_LINE DEDENT def largestZigZag ( mat , n ) : NEW_LINE INDENT res = 0 NEW_LINE for j in range ( n ) : NEW_LINE INDENT res = max ( res , largestZigZagSumRec ( mat , 0 , j , n ) ) NEW_LINE DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE mat = [ [ 4 , 2 , 1 ] , [ 3 , 9 , 6 ] , [ 11 , 3 , 15 ] ] NEW_LINE print ( " Largest β zigzag β sum : β " , largestZigZag ( mat , n ) ) NEW_LINE DEDENT |
Count ways to increase LCS length of two strings by one | Python3 program to get number of ways to increase LCS by 1 ; Method returns total ways to increase LCS length by 1 ; Fill positions of each character in vector vector < int > position [ M ] ; ; Initializing 2D array by 0 values ; Filling LCS array for prefix substrings ; Filling LCS array for suffix substrings ; Looping for all possible insertion positions in first string ; Trying all possible lower case characters ; Now for each character , loop over same character positions in second string ; If both , left and right substrings make total LCS then increase result by 1 ; Driver code to test above methods | M = 26 NEW_LINE def waysToIncreaseLCSBy1 ( str1 , str2 ) : NEW_LINE INDENT m = len ( str1 ) NEW_LINE n = len ( str2 ) NEW_LINE position = [ [ ] for i in range ( M ) ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT position [ ord ( str2 [ i - 1 ] ) - 97 ] . append ( i ) NEW_LINE DEDENT lcsl = [ [ 0 for i in range ( n + 2 ) ] for j in range ( m + 2 ) ] NEW_LINE lcsr = [ [ 0 for i in range ( n + 2 ) ] for j in range ( m + 2 ) ] NEW_LINE for i in range ( 1 , m + 1 , 1 ) : NEW_LINE INDENT for j in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) : NEW_LINE INDENT lcsl [ i ] [ j ] = 1 + lcsl [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lcsl [ i ] [ j ] = max ( lcsl [ i - 1 ] [ j ] , lcsl [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT for i in range ( m , 0 , - 1 ) : NEW_LINE INDENT for j in range ( n , 0 , - 1 ) : NEW_LINE INDENT if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) : NEW_LINE INDENT lcsr [ i ] [ j ] = 1 + lcsr [ i + 1 ] [ j + 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lcsr [ i ] [ j ] = max ( lcsr [ i + 1 ] [ j ] , lcsr [ i ] [ j + 1 ] ) NEW_LINE DEDENT DEDENT DEDENT ways = 0 NEW_LINE for i in range ( 0 , m + 1 , 1 ) : NEW_LINE INDENT for C in range ( 0 , 26 , 1 ) : NEW_LINE INDENT for j in range ( 0 , len ( position [ C ] ) , 1 ) : NEW_LINE INDENT p = position [ C ] [ j ] NEW_LINE if ( lcsl [ i ] [ p - 1 ] + lcsr [ i + 1 ] [ p + 1 ] == lcsl [ m ] [ n ] ) : NEW_LINE INDENT ways += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return ways NEW_LINE DEDENT str1 = " abcabc " NEW_LINE str2 = " abcd " NEW_LINE print ( waysToIncreaseLCSBy1 ( str1 , str2 ) ) NEW_LINE |
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 ; Three cases , we choose , a or b or c In all three cases n decreases by 1. ; Driver code ; Total number of characters | def countStr ( n , bCount , cCount ) : 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 res = countStr ( n - 1 , bCount , cCount ) NEW_LINE res += countStr ( n - 1 , bCount - 1 , cCount ) NEW_LINE res += countStr ( n - 1 , bCount , cCount - 1 ) NEW_LINE return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE print ( countStr ( n , 1 , 2 ) ) NEW_LINE DEDENT |
Maximum path sum that starting with any cell of 0 | Python3 program to find Maximum path sum start any column in row '0' and ends up to any column in row 'n-1 ; function find maximum sum path ; create 2D matrix to store the sum of the path initialize all dp matrix as '0 ; ; copy all element of first column into dp first column ; Find maximum path sum that end ups at any column of last row 'N-1 ; return maximum sum path ; driver program to test above function | ' NEW_LINE N = 4 NEW_LINE def MaximumPath ( Mat ) : NEW_LINE INDENT result = 0 NEW_LINE DEDENT ' NEW_LINE INDENT dp = [ [ 0 for i in range ( N + 2 ) ] for j in range ( N ) ] NEW_LINE DEDENT / * initialize all dp matrix as '0' * / NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( 1 , N + 1 ) : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j - 1 ] , max ( dp [ i - 1 ] [ j ] , dp [ i - 1 ] [ j + 1 ] ) ) + Mat [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT for i in range ( N + 1 ) : NEW_LINE INDENT result = max ( result , dp [ N - 1 ] [ i ] ) NEW_LINE DEDENT return result NEW_LINE DEDENT Mat = [ [ 4 , 2 , 3 , 4 ] , [ 2 , 9 , 1 , 10 ] , [ 15 , 1 , 3 , 0 ] , [ 16 , 92 , 41 , 44 ] ] NEW_LINE print ( MaximumPath ( Mat ) ) NEW_LINE |
Probability of getting at least K heads in N tosses of Coins | Dynamic and Logarithm approach find probability of at least k heads ; dp [ i ] is going to store Log ( i ! ) in base 2 ; Initialize result ; Iterate from k heads to n heads ; Preprocess all the logarithm value on base 2 ; Driver code ; Probability of getting 2 head out of 3 coins ; Probability of getting 3 head out of 6 coins ; Probability of getting 500 head out of 10000 coins | from math import log2 NEW_LINE MAX = 100001 NEW_LINE dp = [ 0 ] * MAX NEW_LINE def probability ( k , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( k , n + 1 ) : NEW_LINE INDENT res = dp [ n ] - dp [ i ] - dp [ n - i ] - n NEW_LINE ans = ans + pow ( 2.0 , res ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def precompute ( ) : NEW_LINE INDENT for i in range ( 2 , MAX ) : NEW_LINE INDENT dp [ i ] = log2 ( i ) + dp [ i - 1 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT precompute ( ) NEW_LINE print ( probability ( 2 , 3 ) ) NEW_LINE print ( probability ( 3 , 6 ) ) NEW_LINE print ( probability ( 500 , 1000 ) ) NEW_LINE DEDENT |
Check if all people can vote on two machines | Function returns true if n people can vote using two machines in x time . ; dp [ i ] [ j ] stores maximum possible number of people among arr [ 0. . i - 1 ] can vote in j time . ; Find sum of all times ; Fill dp [ ] [ ] in bottom up manner ( Similar to knapsack ) . ; If remaining people can go to other machine . ; Driver Code | def canVote ( a , n , x ) : NEW_LINE INDENT dp = [ [ 0 ] * ( x + 1 ) for _ in range ( n + 1 ) ] NEW_LINE a = a [ : ] NEW_LINE a . append ( 0 ) NEW_LINE sm = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT sm += a [ i ] NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , x + 1 ) : NEW_LINE INDENT if a [ i ] <= j : NEW_LINE INDENT dp [ i ] [ j ] = max ( dp [ i - 1 ] [ j ] , a [ i ] + dp [ i - 1 ] [ j - a [ i ] ] ) NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = dp [ i - 1 ] [ j ] NEW_LINE DEDENT DEDENT DEDENT return ( sm - dp [ n ] [ x ] ) <= x NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 3 NEW_LINE x = 4 NEW_LINE a = [ 2 , 4 , 2 ] NEW_LINE print ( " YES " if canVote ( a , n , x ) else " NO " ) NEW_LINE DEDENT |
Maximum path sum for each position with jumps under divisibility condition | Python3 program to print maximum path sum ending with each position x such that all path step positions divide x . ; Create an array such that dp [ i ] stores maximum path sum ending with i . ; Calculating maximum sum path for each element . ; Finding previous step for arr [ i ] Moving from 1 to sqrt ( i + 1 ) since all the divisiors are present from sqrt ( i + 1 ) . ; Checking if j is divisior of i + 1. ; Checking which divisor will provide greater value . ; Printing the answer ( Maximum path sum ending with every position i + 1 ) . ; Driver Program ; | def printMaxSum ( arr , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE maxi = 0 NEW_LINE for j in range ( 1 , int ( ( i + 1 ) ** 0.5 ) + 1 ) : NEW_LINE INDENT if ( ( i + 1 ) % j == 0 and ( i + 1 ) != j ) : NEW_LINE INDENT if ( dp [ j - 1 ] > maxi ) : NEW_LINE INDENT maxi = dp [ j - 1 ] NEW_LINE DEDENT if ( dp [ ( i + 1 ) // j - 1 ] > maxi and j != 1 ) : NEW_LINE INDENT maxi = dp [ ( i + 1 ) // j - 1 ] NEW_LINE DEDENT DEDENT DEDENT dp [ i ] += maxi NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( dp [ i ] , end = ' β ' ) NEW_LINE DEDENT DEDENT arr = [ 2 , 3 , 1 , 4 , 6 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE / * Function calling * / NEW_LINE printMaxSum ( arr , n ) NEW_LINE |
Minimum sum subsequence such that at least one of every four consecutive elements is picked | function to calculate min sum using dp ; if elements are less than or equal to 4 ; save start four element as it is ; compute sum [ ] for all rest elements ; sum [ i ] = ar [ i ] + ( * min_element ( sum + i - 4 , sum + i ) ) ; ; Since one of the last 4 elements must be present ; Driver Code | def minSum ( ar , n ) : NEW_LINE INDENT if ( n <= 4 ) : NEW_LINE INDENT return min ( ar ) NEW_LINE DEDENT sum = [ 0 for i in range ( n ) ] NEW_LINE sum [ 0 ] = ar [ 0 ] NEW_LINE sum [ 1 ] = ar [ 1 ] NEW_LINE sum [ 2 ] = ar [ 2 ] NEW_LINE sum [ 3 ] = ar [ 3 ] NEW_LINE for i in range ( 4 , n ) : NEW_LINE INDENT sum [ i ] = ar [ i ] + min ( sum [ i - 4 : i ] ) NEW_LINE DEDENT return min ( sum [ n - 4 : n ] ) NEW_LINE DEDENT ar = [ 2 , 4 , 1 , 5 , 2 , 3 , 6 , 1 , 2 , 4 ] NEW_LINE n = len ( ar ) NEW_LINE print ( " Minimum β sum β = β " , minSum ( ar , n ) ) NEW_LINE |
Maximum sum alternating subsequence | Return sum of maximum sum alternating sequence starting with arr [ 0 ] and is first decreasing . ; handling the edge case ; Stores sum of decreasing and increasing sub - sequence ; store sum of increasing and decreasing sun - sequence ; As per question , first element must be part of solution . ; Traverse remaining elements of array ; IF current sub - sequence is decreasing the update dec [ j ] if needed . dec [ i ] by current inc [ j ] + arr [ i ] ; Revert the flag , if first decreasing is found ; If next element is greater but flag should be 1 i . e . this element should be counted after the first decreasing element gets counted ; If current sub - sequence is increasing then update inc [ i ] ; Find maximum sum in b / w inc [ ] and dec [ ] ; Return maximum sum alternate sun - sequence ; Driver program | def maxAlternateSum ( arr , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT min = arr [ 0 ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( min > arr [ i ] ) : NEW_LINE INDENT min = arr [ i ] NEW_LINE DEDENT DEDENT if ( arr [ 0 ] == min ) : NEW_LINE INDENT return arr [ 0 ] NEW_LINE DEDENT dec = [ 0 for i in range ( n + 1 ) ] NEW_LINE inc = [ 0 for i in range ( n + 1 ) ] NEW_LINE dec [ 0 ] = inc [ 0 ] = arr [ 0 ] NEW_LINE flag = 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 ] ) : NEW_LINE INDENT dec [ i ] = max ( dec [ i ] , inc [ j ] + arr [ i ] ) NEW_LINE flag = 1 NEW_LINE DEDENT elif ( arr [ j ] < arr [ i ] and flag == 1 ) : NEW_LINE INDENT inc [ i ] = max ( inc [ i ] , dec [ j ] + arr [ i ] ) NEW_LINE DEDENT DEDENT DEDENT result = - 2147483648 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( result < inc [ i ] ) : NEW_LINE INDENT result = inc [ i ] NEW_LINE DEDENT if ( result < dec [ i ] ) : NEW_LINE INDENT result = dec [ i ] NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT arr = [ 8 , 2 , 3 , 5 , 7 , 9 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Maximum β sum β = β " , maxAlternateSum ( arr , n ) ) NEW_LINE |
Padovan Sequence | Function to calculate padovan number P ( n ) ; 0 th , 1 st and 2 nd number of the series are 1 ; Driver Code | def pad ( n ) : NEW_LINE INDENT pPrevPrev , pPrev , pCurr , pNext = 1 , 1 , 1 , 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT pNext = pPrevPrev + pPrev NEW_LINE pPrevPrev = pPrev NEW_LINE pPrev = pCurr NEW_LINE pCurr = pNext NEW_LINE DEDENT return pNext ; NEW_LINE DEDENT print pad ( 12 ) NEW_LINE |
Find length of the largest region in Boolean Matrix | A function to check if a given cell ( row , col ) can be included in DFS ; row number is in range , column number is in range and value is 1 and not yet visited ; A utility function to do DFS for a 2D boolean matrix . It only considers the 8 neighbours as adjacent vertices ; These arrays are used to get row and column numbers of 8 neighbours of a given cell ; Mark this cell as visited ; Recur for all connected neighbours ; increment region length by one ; The main function that returns largest length region of a given boolean 2D matrix ; Make a bool array to mark visited cells . Initially all cells are unvisited ; Initialize result as 0 and travesle through the all cells of given matrix ; If a cell with value 1 is not ; visited yet , then new region found ; maximum region ; Driver Code ; Function call | def isSafe ( M , row , col , visited ) : NEW_LINE INDENT global ROW , COL NEW_LINE return ( ( row >= 0 ) and ( row < ROW ) and ( col >= 0 ) and ( col < COL ) and ( M [ row ] [ col ] and not visited [ row ] [ col ] ) ) NEW_LINE DEDENT def DFS ( M , row , col , visited , count ) : NEW_LINE INDENT rowNbr = [ - 1 , - 1 , - 1 , 0 , 0 , 1 , 1 , 1 ] NEW_LINE colNbr = [ - 1 , 0 , 1 , - 1 , 1 , - 1 , 0 , 1 ] NEW_LINE visited [ row ] [ col ] = True NEW_LINE for k in range ( 8 ) : NEW_LINE INDENT if ( isSafe ( M , row + rowNbr [ k ] , col + colNbr [ k ] , visited ) ) : NEW_LINE INDENT count [ 0 ] += 1 NEW_LINE DFS ( M , row + rowNbr [ k ] , col + colNbr [ k ] , visited , count ) NEW_LINE DEDENT DEDENT DEDENT def largestRegion ( M ) : NEW_LINE INDENT global ROW , COL NEW_LINE visited = [ [ 0 ] * COL for i in range ( ROW ) ] NEW_LINE result = - 999999999999 NEW_LINE for i in range ( ROW ) : NEW_LINE INDENT for j in range ( COL ) : NEW_LINE INDENT if ( M [ i ] [ j ] and not visited [ i ] [ j ] ) : NEW_LINE INDENT count = [ 1 ] NEW_LINE DFS ( M , i , j , visited , count ) NEW_LINE result = max ( result , count [ 0 ] ) NEW_LINE DEDENT DEDENT DEDENT return result NEW_LINE DEDENT ROW = 4 NEW_LINE COL = 5 NEW_LINE M = [ [ 0 , 0 , 1 , 1 , 0 ] , [ 1 , 0 , 1 , 1 , 0 ] , [ 0 , 1 , 0 , 0 , 0 ] , [ 0 , 0 , 0 , 0 , 1 ] ] NEW_LINE print ( largestRegion ( M ) ) NEW_LINE |
Lucas Numbers | Iterative function ; declaring base values for positions 0 and 1 ; generating number ; Driver Code | def lucas ( n ) : NEW_LINE INDENT a = 2 NEW_LINE b = 1 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT c = a + b NEW_LINE a = b NEW_LINE b = c NEW_LINE DEDENT return b NEW_LINE DEDENT n = 9 NEW_LINE print ( lucas ( n ) ) NEW_LINE |
Recursively break a number in 3 parts to get maximum sum | A Dynamic programming based Python program to find maximum sum by recursively breaking a number in 3 parts . ; Function to find the maximum sum ; base conditions ; Fill in bottom - up manner using recursive formula . ; Driver program to run the case | MAX = 1000000 NEW_LINE def breakSum ( n ) : NEW_LINE INDENT dp = [ 0 ] * ( n + 1 ) NEW_LINE dp [ 0 ] = 0 NEW_LINE dp [ 1 ] = 1 NEW_LINE for i in range ( 2 , n + 1 ) : NEW_LINE INDENT dp [ i ] = max ( dp [ int ( i / 2 ) ] + dp [ int ( i / 3 ) ] + dp [ int ( i / 4 ) ] , i ) ; NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT n = 24 NEW_LINE print ( breakSum ( n ) ) NEW_LINE |
Longest repeating and non | Returns the longest repeating non - overlapping substring in str ; building table in bottom - up manner ; ( j - i ) > LCSRe [ i - 1 ] [ j - 1 ] to remove overlapping ; updating maximum length of the substring and updating the finishing index of the suffix ; If we have non - empty result , then insert all characters from first character to last character of string ; Driver Code | def longestRepeatedSubstring ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE LCSRe = [ [ 0 for x in range ( n + 1 ) ] for y in range ( n + 1 ) ] NEW_LINE index = 0 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT if ( str [ i - 1 ] == str [ j - 1 ] and LCSRe [ i - 1 ] [ j - 1 ] < ( j - i ) ) : NEW_LINE INDENT LCSRe [ i ] [ j ] = LCSRe [ i - 1 ] [ j - 1 ] + 1 NEW_LINE if ( LCSRe [ i ] [ j ] > res_length ) : NEW_LINE INDENT res_length = LCSRe [ i ] [ j ] NEW_LINE index = max ( i , index ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT LCSRe [ i ] [ j ] = 0 NEW_LINE DEDENT DEDENT DEDENT if ( res_length > 0 ) : NEW_LINE INDENT for i in range ( index - res_length + 1 , index + 1 ) : NEW_LINE INDENT res = res + str [ i - 1 ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str = " geeksforgeeks " NEW_LINE print ( longestRepeatedSubstring ( str ) ) NEW_LINE DEDENT |
Minimum cost to fill given weight in a bag | Python3 program to find minimum cost to get exactly W Kg with given packets ; Returns the best obtainable price for a rod of length n and price [ ] as prices of different pieces ; Build the table val [ ] in bottom up manner and return the last entry from the table ; Driver code | import sys NEW_LINE def minCost ( cost , n ) : NEW_LINE INDENT dp = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT min_cost = sys . maxsize NEW_LINE for j in range ( i ) : NEW_LINE INDENT if j < len ( cost ) and cost [ j ] != - 1 : NEW_LINE INDENT min_cost = min ( min_cost , cost [ j ] + dp [ i - j - 1 ] ) NEW_LINE DEDENT DEDENT dp [ i ] = min_cost NEW_LINE DEDENT return dp [ n ] NEW_LINE DEDENT cost = [ 10 , - 1 , - 1 , - 1 , - 1 ] NEW_LINE W = len ( cost ) NEW_LINE print ( minCost ( cost , W ) ) NEW_LINE |
Printing Maximum Sum Increasing Subsequence | Utility function to calculate sum of all vector elements ; Function to construct Maximum Sum Increasing Subsequence ; L [ i ] - The Maximum Sum Increasing Subsequence that ends with arr [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; L [ i ] = { MaxSum ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; L [ i ] ends with arr [ i ] ; L [ i ] now stores Maximum Sum Increasing Subsequence of arr [ 0. . i ] that ends with arr [ i ] ; ; find max ; max will contain result ; Driver Code ; construct and prMax Sum IS of arr | def findSum ( arr ) : NEW_LINE INDENT summ = 0 NEW_LINE for i in arr : NEW_LINE INDENT summ += i NEW_LINE DEDENT return summ NEW_LINE DEDENT def printMaxSumIS ( arr , n ) : NEW_LINE INDENT L = [ [ ] for i in range ( n ) ] NEW_LINE L [ 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 [ i ] > arr [ j ] ) and ( findSum ( L [ i ] ) < findSum ( L [ j ] ) ) ) : NEW_LINE INDENT for e in L [ j ] : NEW_LINE INDENT if e not in L [ i ] : NEW_LINE INDENT L [ i ] . append ( e ) NEW_LINE DEDENT DEDENT DEDENT DEDENT L [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT res = L [ 0 ] NEW_LINE DEDENT / * res = L [ 0 ] ; * / NEW_LINE INDENT for x in L : NEW_LINE INDENT if ( findSum ( x ) > findSum ( res ) ) : NEW_LINE INDENT res = x NEW_LINE DEDENT DEDENT for i in res : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 3 , 2 , 6 , 4 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE printMaxSumIS ( arr , n ) NEW_LINE |
Construction of Longest Increasing Subsequence ( LIS ) and printing LIS sequence | Utility function to print LIS ; Function to construct and print Longest Increasing Subsequence ; L [ i ] - The longest increasing sub - sequence ends with arr [ i ] ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; do for every j less than i ; L [ i ] = { Max ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] < arr [ i ] ; L [ i ] ends with arr [ i ] ; L [ i ] now stores increasing sub - sequence of arr [ 0. . i ] that ends with arr [ i ] ; LIS will be max of all increasing sub - sequences of arr ; max will contain LIS ; Driver Code ; construct and print LIS of arr | def printLIS ( arr : list ) : NEW_LINE INDENT for x in arr : NEW_LINE INDENT print ( x , end = " β " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT def constructPrintLIS ( arr : list , n : int ) : NEW_LINE INDENT l = [ [ ] for i in range ( n ) ] NEW_LINE l [ 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 [ i ] > arr [ j ] and ( len ( l [ i ] ) < len ( l [ j ] ) + 1 ) : NEW_LINE INDENT l [ i ] = l [ j ] . copy ( ) NEW_LINE DEDENT DEDENT l [ i ] . append ( arr [ i ] ) NEW_LINE DEDENT maxx = l [ 0 ] NEW_LINE for x in l : NEW_LINE INDENT if len ( x ) > len ( maxx ) : NEW_LINE INDENT maxx = x NEW_LINE DEDENT DEDENT printLIS ( maxx ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 2 , 6 , 4 , 5 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE constructPrintLIS ( arr , n ) NEW_LINE DEDENT |
Find if string is K | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X and Y ; find if given string is K - Palindrome or not ; Find reverse of string ; find longest palindromic subsequence of given string ; If the difference between longest palindromic subsequence and the original string is less than equal to k , then the string is k - palindrome ; ; Driver program | def lcs ( X , Y , m , n ) : NEW_LINE INDENT L = [ [ 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 or not j : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif X [ i - 1 ] == Y [ 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 isKPal ( string , k ) : NEW_LINE INDENT n = len ( string ) NEW_LINE revStr = string [ : : - 1 ] NEW_LINE lps = lcs ( string , revStr , n , n ) NEW_LINE return ( n - lps <= k ) NEW_LINE DEDENT / * Swap values of left and right * / NEW_LINE string = " abcdeca " NEW_LINE k = 2 NEW_LINE print ( " Yes " if isKPal ( string , k ) else " No " ) NEW_LINE |
Wildcard Pattern Matching | Function that matches input strr with given wildcard pattern ; empty pattern can only match with empty string ; lookup table for storing results of subproblems ; empty pattern can match with empty string ; Only ' * ' can match with empty string ; fill the table in bottom - up fashion ; Two cases if we see a ' * ' a ) We ignore a * aTM character and move to next character in the pattern , i . e . , a * aTM indicates an empty sequence . b ) ' * ' character matches with ith character in input ; Current characters are considered as matching in two cases ( a ) current character of pattern is ' ? ' ( b ) characters actually match ; If characters don 't match ; Driver code ; char pattern [ ] = " ba * * * * * ab " char pattern [ ] = " ba * ab " char pattern [ ] = " a * ab " char pattern [ ] = " a * * * * * ab " char pattern [ ] = " * a * * * * * ab " char pattern [ ] = " ba * ab * * * * " char pattern [ ] = " * * * * " char pattern [ ] = " * " char pattern [ ] = " aa ? ab " char pattern [ ] = " b * b " char pattern [ ] = " a * a " char pattern [ ] = " baaabab " char pattern [ ] = " ? baaabab " char pattern [ ] = " * baaaba * " | def strrmatch ( strr , pattern , n , m ) : NEW_LINE INDENT if ( m == 0 ) : NEW_LINE INDENT return ( n == 0 ) NEW_LINE DEDENT lookup = [ [ False for i in range ( m + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE lookup [ 0 ] [ 0 ] = True NEW_LINE for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( pattern [ j - 1 ] == ' * ' ) : NEW_LINE INDENT lookup [ 0 ] [ j ] = lookup [ 0 ] [ j - 1 ] NEW_LINE DEDENT DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , m + 1 ) : NEW_LINE INDENT if ( pattern [ j - 1 ] == ' * ' ) : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i ] [ j - 1 ] or lookup [ i - 1 ] [ j ] NEW_LINE DEDENT elif ( pattern [ j - 1 ] == ' ? ' or strr [ i - 1 ] == pattern [ j - 1 ] ) : NEW_LINE INDENT lookup [ i ] [ j ] = lookup [ i - 1 ] [ j - 1 ] NEW_LINE DEDENT else : NEW_LINE INDENT lookup [ i ] [ j ] = False NEW_LINE DEDENT DEDENT DEDENT return lookup [ n ] [ m ] NEW_LINE DEDENT strr = " baaabab " NEW_LINE pattern = " * * * * * ba * * * * * ab " NEW_LINE if ( strrmatch ( strr , pattern , len ( strr ) , len ( pattern ) ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Find if string is K | Find if given string is K - Palindrome or not ; If first string is empty , the only option is to remove all characters of second string ; If second string is empty , the only option is to remove all characters of first string ; If last characters of two strings are same , ignore last characters and get count for remaining strings . ; If last characters are not same , 1. Remove last char from str1 and recur for m - 1 and n 2. Remove last char from str2 and recur for m and n - 1 Take minimum of above two operations res = 1 + min ( isKPalRec ( str1 , str2 , m - 1 , n ) , Remove from str1 ( isKPalRec ( str1 , str2 , m , n - 1 ) ) ) Remove from str2 ; Returns true if str is k palindrome . ; Driver program | def isKPalRec ( str1 , str2 , m , n ) : NEW_LINE INDENT if not m : return n NEW_LINE if not n : return m NEW_LINE if str1 [ m - 1 ] == str2 [ n - 1 ] : NEW_LINE INDENT return isKPalRec ( str1 , str2 , m - 1 , n - 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def isKPal ( string , k ) : NEW_LINE INDENT revStr = string [ : : - 1 ] NEW_LINE l = len ( string ) NEW_LINE return ( isKPalRec ( 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 |
Minimum time to finish tasks without skipping two consecutive | arr [ ] represents time taken by n given tasks ; Corner Cases ; Initialize value for the case when there is only one task in task list . First task is included ; First task is exluded ; Process remaining n - 1 tasks ; Time taken if current task is included There are two possibilities ( a ) Previous task is also included ( b ) Previous task is not included ; Time taken when current task is not included . There is only one possibility that previous task is also included . ; Update incl and excl for next iteration ; Return maximum of two values for last task ; Driver code | def minTime ( arr , n ) : NEW_LINE INDENT if ( n <= 0 ) : return 0 NEW_LINE DEDENT incl = arr [ 0 ] NEW_LINE excl = 0 NEW_LINE INDENT for i in range ( 1 , n ) : NEW_LINE INDENT incl_new = arr [ i ] + min ( excl , incl ) NEW_LINE excl_new = incl NEW_LINE incl = incl_new NEW_LINE excl = excl_new NEW_LINE DEDENT return min ( incl , excl ) NEW_LINE DEDENT arr1 = [ 10 , 5 , 2 , 7 , 10 ] NEW_LINE n1 = len ( arr1 ) NEW_LINE print ( minTime ( arr1 , n1 ) ) NEW_LINE arr2 = [ 10 , 5 , 7 , 10 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE print ( minTime ( arr2 , n2 ) ) NEW_LINE arr3 = [ 10 , 5 , 2 , 4 , 8 , 6 , 7 , 10 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE print ( minTime ( arr3 , n3 ) ) NEW_LINE |
Matrix Exponentiation | A utility function to multiply two matrices a [ ] [ ] and b [ ] [ ] . Multiplication result is stored back in b [ ] [ ] ; Creating an auxiliary matrix to store elements of the multiplication matrix ; storing the multiplication result in a [ ] [ ] ; Updating our matrix ; Function to compute F raise to power n - 2. ; Multiply it with initial values i . e with F ( 0 ) = 0 , F ( 1 ) = 1 , F ( 2 ) = 1 ; Multiply it with initial values i . e with F ( 0 ) = 0 , F ( 1 ) = 1 , F ( 2 ) = 1 ; Return n 'th term of a series defined using below recurrence relation. f(n) is defined as f(n) = f(n-1) + f(n-2) + f(n-3), n>=3 Base Cases : f(0) = 0, f(1) = 1, f(2) = 1 ; Driver code | def multiply ( a , b ) : NEW_LINE INDENT mul = [ [ 0 for x in range ( 3 ) ] for y in range ( 3 ) ] ; NEW_LINE for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE INDENT mul [ i ] [ j ] = 0 ; NEW_LINE for k in range ( 3 ) : NEW_LINE INDENT mul [ i ] [ j ] += a [ i ] [ k ] * b [ k ] [ j ] ; NEW_LINE DEDENT DEDENT DEDENT for i in range ( 3 ) : NEW_LINE INDENT for j in range ( 3 ) : NEW_LINE a [ i ] [ j ] = mul [ i ] [ j ] ; NEW_LINE DEDENT return a ; NEW_LINE DEDENT def power ( F , n ) : NEW_LINE INDENT M = [ [ 1 , 1 , 1 ] , [ 1 , 0 , 0 ] , [ 0 , 1 , 0 ] ] ; NEW_LINE if ( n == 1 ) : NEW_LINE INDENT return F [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] ; NEW_LINE DEDENT power ( F , int ( n / 2 ) ) ; NEW_LINE F = multiply ( F , F ) ; NEW_LINE if ( n % 2 != 0 ) : NEW_LINE INDENT F = multiply ( F , M ) ; NEW_LINE DEDENT return F [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] ; NEW_LINE DEDENT def findNthTerm ( n ) : NEW_LINE INDENT F = [ [ 1 , 1 , 1 ] , [ 1 , 0 , 0 ] , [ 0 , 1 , 0 ] ] ; NEW_LINE return power ( F , n - 2 ) ; NEW_LINE DEDENT n = 5 ; NEW_LINE print ( " F ( 5 ) β is " , findNthTerm ( n ) ) ; NEW_LINE |
Count number of ways to fill a " n β x β 4" grid using "1 β x β 4" tiles | Returns count of count of ways to place 1 x 4 tiles on n x 4 grid . ; Create a table to store results of subproblems dp [ i ] stores count of ways for i x 4 grid . ; Fill the table from d [ 1 ] to dp [ n ] ; Base cases ; dp ( i - 1 ) : Place first tile horizontally dp ( n - 4 ) : Place first tile vertically which means 3 more tiles have to be placed vertically . ; Driver code to test above | def count ( n ) : NEW_LINE INDENT dp = [ 0 for _ in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT if i <= 3 : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT elif i == 4 : NEW_LINE INDENT dp [ i ] = 2 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = dp [ i - 1 ] + dp [ i - 4 ] NEW_LINE DEDENT DEDENT return dp [ n ] NEW_LINE DEDENT n = 5 NEW_LINE print ( " Count β of β ways β is " ) , NEW_LINE print ( count ( n ) ) NEW_LINE |
Compute nCr % p | Set 1 ( Introduction and Dynamic Programming Solution ) | Returns nCr % p ; Optimization for the cases when r is large compared to n - r ; The array C is going to store last row of pascal triangle at the end . And last entry of last row is nCr . ; Top row of Pascal Triangle ; One by constructs remaining rows of Pascal Triangle from top to bottom ; Fill entries of current row using previous row values ; nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; Driver Program | def nCrModp ( n , r , p ) : NEW_LINE INDENT if ( r > n - r ) : NEW_LINE INDENT r = n - r NEW_LINE DEDENT C = [ 0 for i in range ( r + 1 ) ] NEW_LINE C [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( min ( i , r ) , 0 , - 1 ) : NEW_LINE INDENT C [ j ] = ( C [ j ] + C [ j - 1 ] ) % p NEW_LINE DEDENT DEDENT return C [ r ] NEW_LINE DEDENT n = 10 NEW_LINE r = 2 NEW_LINE p = 13 NEW_LINE print ( ' Value β of β nCr β % β p β is ' , nCrModp ( n , r , p ) ) NEW_LINE |
Count Derangements ( Permutation such that no element appears in its original position ) | ; Base Case ; Variables for storing previous values ; using above recursive formula ; Return result for n ; Driver Code | / * Function to count NEW_LINE derangements * / NEW_LINE def countDer ( n ) : NEW_LINE INDENT if n == 1 or n == 2 : NEW_LINE return n - 1 ; NEW_LINE a = 0 NEW_LINE b = 1 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT cur = ( i - 1 ) * ( a + b ) NEW_LINE a = b NEW_LINE b = cur NEW_LINE DEDENT return b NEW_LINE DEDENT n = 4 NEW_LINE print ( " Count β of β Dearrangements β is β " , countDer ( n ) ) NEW_LINE |
Bell Numbers ( Number of ways to Partition a Set ) | ; Explicitly fill for j = 0 ; Fill for remaining values of j ; Driver program | / * Function to find n ' th Bell Number * / NEW_LINE def bellNumber ( n ) : NEW_LINE INDENT bell = [ [ 0 for i in range ( n + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE bell [ 0 ] [ 0 ] = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT bell [ i ] [ 0 ] = bell [ i - 1 ] [ i - 1 ] NEW_LINE for j in range ( 1 , i + 1 ) : NEW_LINE INDENT bell [ i ] [ j ] = bell [ i - 1 ] [ j - 1 ] + bell [ i ] [ j - 1 ] NEW_LINE DEDENT DEDENT return bell [ n ] [ 0 ] NEW_LINE DEDENT for n in range ( 6 ) : NEW_LINE INDENT print ( ' Bell β Number ' , n , ' is ' , bellNumber ( n ) ) NEW_LINE DEDENT |
Count number of ways to cover a distance | Function returns count of ways to cover ' dist ' ; Initialize base values . There is one way to cover 0 and 1 distances and two ways to cover 2 distance ; Fill the count array in bottom up manner ; driver program | def printCountDP ( dist ) : NEW_LINE INDENT count = [ 0 ] * ( dist + 1 ) NEW_LINE count [ 0 ] = 1 NEW_LINE if dist >= 1 : NEW_LINE INDENT count [ 1 ] = 1 NEW_LINE DEDENT if dist >= 2 : NEW_LINE INDENT count [ 2 ] = 2 NEW_LINE DEDENT for i in range ( 3 , dist + 1 ) : NEW_LINE INDENT count [ i ] = ( count [ i - 1 ] + count [ i - 2 ] + count [ i - 3 ] ) NEW_LINE DEDENT return count [ dist ] ; NEW_LINE DEDENT dist = 4 ; NEW_LINE print ( printCountDP ( dist ) ) NEW_LINE |
Count even length binary sequences with same sum of first and second half bits | Returns the count of even length sequences ; Calculate SUM ( ( nCr ) ^ 2 ) ; Compute nCr using nC ( r - 1 ) nCr / nC ( r - 1 ) = ( n + 1 - r ) / r ; ; Driver Code | def countSeq ( n ) : NEW_LINE INDENT nCr = 1 NEW_LINE res = 1 NEW_LINE for r in range ( 1 , n + 1 ) : NEW_LINE INDENT nCr = ( nCr * ( n + 1 - r ) ) / r ; NEW_LINE res += nCr * nCr ; NEW_LINE DEDENT return res ; NEW_LINE DEDENT n = 2 NEW_LINE print ( " Count β of β sequences β is " ) , NEW_LINE print ( int ( countSeq ( n ) ) ) NEW_LINE |
Remove minimum elements from either side such that 2 * min becomes more than max | ; A utility function to find minimum in arr [ l . . h ] ; A utility function to find maximum in arr [ l . . h ] ; Returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; Create a table to store solutions of subproblems ; Fill table using above recursive formula . Note that the table is filled in diagonal fashion ( similar to http : goo . gl / PQqoS ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; Driver Code | / * A utility function to find minimum of two numbers * / NEW_LINE def min1 ( arr , l , h ) : NEW_LINE INDENT mn = arr [ l ] ; NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( mn > arr [ i ] ) : NEW_LINE INDENT mn = arr [ i ] ; NEW_LINE DEDENT DEDENT return mn ; NEW_LINE DEDENT def max1 ( arr , l , h ) : NEW_LINE INDENT mx = arr [ l ] ; NEW_LINE for i in range ( l + 1 , h + 1 ) : NEW_LINE INDENT if ( mx < arr [ i ] ) : NEW_LINE INDENT mx = arr [ i ] ; NEW_LINE DEDENT DEDENT return mx ; NEW_LINE DEDENT def minRemovalsDP ( arr , n ) : NEW_LINE INDENT table = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] ; NEW_LINE for gap in range ( n ) : NEW_LINE INDENT i = 0 ; NEW_LINE for j in range ( gap , n ) : NEW_LINE INDENT mn = min1 ( arr , i , j ) ; NEW_LINE mx = max1 ( arr , i , j ) ; NEW_LINE table [ i ] [ j ] = 0 if ( 2 * mn > mx ) else min ( table [ i ] [ j - 1 ] + 1 , table [ i + 1 ] [ j ] + 1 ) ; NEW_LINE i += 1 ; NEW_LINE DEDENT DEDENT return table [ 0 ] [ n - 1 ] ; NEW_LINE DEDENT arr = [ 20 , 4 , 1 , 3 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minRemovalsDP ( arr , n ) ) ; NEW_LINE |
Count all possible paths from top left to bottom right of a mXn matrix | function to return count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; If either given row number is first or given column number is first ; If diagonal movements are allowed then the last addition is required . ; Driver program to test above function | def numberOfPaths ( m , n ) : NEW_LINE INDENT if ( m == 1 or n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return numberOfPaths ( m - 1 , n ) + numberOfPaths ( m , n - 1 ) NEW_LINE DEDENT m = 3 NEW_LINE n = 3 NEW_LINE print ( numberOfPaths ( m , n ) ) NEW_LINE |
Count all possible paths from top left to bottom right of a mXn matrix | Python3 program to count all possible paths from top left to top bottom using combinatorics ; We have to calculate m + n - 2 C n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! path = 1 ; ; Driver code | def numberOfPaths ( m , n ) : NEW_LINE INDENT for i in range ( n , ( m + n - 1 ) ) : NEW_LINE INDENT path *= i ; NEW_LINE path //= ( i - n + 1 ) ; NEW_LINE DEDENT return path ; NEW_LINE DEDENT print ( numberOfPaths ( 3 , 3 ) ) ; NEW_LINE |
Longest Arithmetic Progression | DP | Returns length of the longest AP subset in a given set ; Create a table and initialize all values as 2. The value of L [ i ] [ j ] stores LLAP with set [ i ] and set [ j ] as first two elements of AP . Only valid entries are the entries where j > i ; Initialize the result ; Fill entries in last column as 2. There will always be two elements in AP with last number of set as second element in AP ; Consider every element as second element of AP ; Search for i and k for j ; Before changing i , set L [ i ] [ j ] as 2 ; Found i and k for j , LLAP with i and j as first two elements are equal to LLAP 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 LLAP , if needed ; 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 entities in column j as 2 ; Driver Code | def lenghtOfLongestAP ( set , n ) : NEW_LINE INDENT if ( n <= 2 ) : NEW_LINE INDENT return n NEW_LINE DEDENT L = [ [ 0 for x in range ( n ) ] for y in range ( n ) ] NEW_LINE llap = 2 NEW_LINE for i in range ( n ) : NEW_LINE INDENT L [ i ] [ n - 1 ] = 2 NEW_LINE DEDENT 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 ( set [ i ] + set [ k ] < 2 * set [ j ] ) : NEW_LINE INDENT k += 1 NEW_LINE DEDENT elif ( set [ i ] + set [ k ] > 2 * set [ j ] ) : NEW_LINE INDENT L [ i ] [ j ] = 2 NEW_LINE i -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = L [ j ] [ k ] + 1 NEW_LINE llap = max ( llap , L [ i ] [ j ] ) NEW_LINE i -= 1 NEW_LINE k += 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT L [ i ] [ j ] = 2 NEW_LINE i -= 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return llap NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT set1 = [ 1 , 7 , 10 , 13 , 14 , 19 ] NEW_LINE n1 = len ( set1 ) NEW_LINE print ( lenghtOfLongestAP ( set1 , n1 ) ) NEW_LINE set2 = [ 1 , 7 , 10 , 15 , 27 , 29 ] NEW_LINE n2 = len ( set2 ) NEW_LINE print ( lenghtOfLongestAP ( set2 , n2 ) ) NEW_LINE set3 = [ 2 , 4 , 6 , 8 , 10 ] NEW_LINE n3 = len ( set3 ) NEW_LINE print ( lenghtOfLongestAP ( set3 , n3 ) ) NEW_LINE DEDENT |
Maximum Manhattan distance between a distinct pair from N coordinates | Function to calculate the maximum Manhattan distance ; List to store maximum and minimum of all the four forms ; Sorting both the vectors ; Driver code ; Given Co - ordinates ; Function call | def MaxDist ( A , N ) : NEW_LINE INDENT V = [ 0 for i in range ( N ) ] NEW_LINE V1 = [ 0 for i in range ( N ) ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT V [ i ] = A [ i ] [ 0 ] + A [ i ] [ 1 ] NEW_LINE V1 [ i ] = A [ i ] [ 0 ] - A [ i ] [ 1 ] NEW_LINE DEDENT V . sort ( ) NEW_LINE V1 . sort ( ) NEW_LINE maximum = max ( V [ - 1 ] - V [ 0 ] , V1 [ - 1 ] - V1 [ 0 ] ) NEW_LINE print ( maximum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 3 NEW_LINE A = [ [ 1 , 2 ] , [ 2 , 3 ] , [ 3 , 4 ] ] NEW_LINE MaxDist ( A , N ) NEW_LINE DEDENT |
Word Wrap Problem | DP | A utility function to print the solution l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa β bb β cc β ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa β bb β cc β ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . The value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; Calculate line cost corresponding to the above calculated extra spaces . The value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; Driver Code | INF = 2147483647 NEW_LINE def printSolution ( p , n ) : NEW_LINE INDENT k = 0 NEW_LINE if p [ n ] == 1 : NEW_LINE INDENT k = 1 NEW_LINE DEDENT else : NEW_LINE INDENT k = printSolution ( p , p [ n ] - 1 ) + 1 NEW_LINE DEDENT print ( ' Line β number β ' , k , ' : β From β word β no . β ' , p [ n ] , ' to β ' , n ) NEW_LINE return k NEW_LINE DEDENT def solveWordWrap ( l , n , M ) : NEW_LINE INDENT extras = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE lc = [ [ 0 for i in range ( n + 1 ) ] for i in range ( n + 1 ) ] NEW_LINE c = [ 0 for i in range ( n + 1 ) ] NEW_LINE p = [ 0 for i in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT extras [ i ] [ i ] = M - l [ i - 1 ] NEW_LINE for j in range ( i + 1 , n + 1 ) : NEW_LINE INDENT extras [ i ] [ j ] = ( extras [ i ] [ j - 1 ] - l [ j - 1 ] - 1 ) NEW_LINE DEDENT DEDENT for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( i , n + 1 ) : NEW_LINE INDENT if extras [ i ] [ j ] < 0 : NEW_LINE INDENT lc [ i ] [ j ] = INF ; NEW_LINE DEDENT elif j == n and extras [ i ] [ j ] >= 0 : NEW_LINE INDENT lc [ i ] [ j ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT lc [ i ] [ j ] = ( extras [ i ] [ j ] * extras [ i ] [ j ] ) NEW_LINE DEDENT DEDENT DEDENT c [ 0 ] = 0 NEW_LINE for j in range ( 1 , n + 1 ) : NEW_LINE INDENT c [ j ] = INF NEW_LINE for i in range ( 1 , j + 1 ) : NEW_LINE INDENT if ( c [ i - 1 ] != INF and lc [ i ] [ j ] != INF and ( ( c [ i - 1 ] + lc [ i ] [ j ] ) < c [ j ] ) ) : NEW_LINE INDENT c [ j ] = c [ i - 1 ] + lc [ i ] [ j ] NEW_LINE p [ j ] = i NEW_LINE DEDENT DEDENT DEDENT printSolution ( p , n ) NEW_LINE DEDENT l = [ 3 , 2 , 2 , 5 ] NEW_LINE n = len ( l ) NEW_LINE M = 6 NEW_LINE solveWordWrap ( l , n , M ) NEW_LINE |
Palindrome Partitioning | DP | Python code for implementation of Naive Recursive approach ; Driver code | def isPalindrome ( x ) : NEW_LINE INDENT return x == x [ : : - 1 ] NEW_LINE DEDENT def minPalPartion ( string , i , j ) : NEW_LINE INDENT if i >= j or isPalindrome ( string [ i : j + 1 ] ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT ans = float ( ' inf ' ) NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT count = ( 1 + minPalPartion ( string , i , k ) + minPalPartion ( string , k + 1 , j ) ) NEW_LINE ans = min ( ans , count ) NEW_LINE DEDENT return ans NEW_LINE DEDENT def main ( ) : NEW_LINE INDENT string = " ababbbabbababa " NEW_LINE print ( " Min β cuts β needed β for β Palindrome β Partitioning β is β " , minPalPartion ( string , 0 , len ( string ) - 1 ) , ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT main ( ) NEW_LINE DEDENT |
Palindrome Partitioning | DP | Driver code | def minCut ( a ) : NEW_LINE INDENT cut = [ 0 for i in range ( len ( a ) ) ] NEW_LINE palindrome = [ [ False for i in range ( len ( a ) ) ] for j in range ( len ( a ) ) ] NEW_LINE for i in range ( len ( a ) ) : NEW_LINE INDENT minCut = i ; NEW_LINE for j in range ( i + 1 ) : NEW_LINE INDENT if ( a [ i ] == a [ j ] and ( i - j < 2 or palindrome [ j + 1 ] [ i - 1 ] ) ) : NEW_LINE INDENT palindrome [ j ] [ i ] = True ; NEW_LINE minCut = min ( minCut , 0 if j == 0 else ( cut [ j - 1 ] + 1 ) ) ; NEW_LINE DEDENT DEDENT cut [ i ] = minCut ; NEW_LINE DEDENT return cut [ len ( a ) - 1 ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( minCut ( " aab " ) ) NEW_LINE print ( minCut ( " aabababaxx " ) ) NEW_LINE DEDENT |
Palindrome Partitioning | DP | Function to check if input string is pallindrome or not ; Using two pointer technique to check pallindrome ; Function to find keys for the Hashmap ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Key for the Input String ; If the no of partitions for string " ij " is already calculated then return the calculated value using the Hashmap ; Every String of length 1 is a pallindrome ; Make a cut at every possible location starting from i to j ; If left cut is found already ; If right cut is found already ; Recursively calculating for left and right strings ; Taking minimum of all k possible cuts ; Return the min cut value for complete string . ; Driver code | def ispallindrome ( input , start , end ) : NEW_LINE INDENT while ( start < end ) : NEW_LINE INDENT if ( input [ start ] != input [ end ] ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT start += 1 NEW_LINE end -= 1 NEW_LINE DEDENT return True ; NEW_LINE DEDENT def convert ( a , b ) : NEW_LINE INDENT return str ( a ) + str ( b ) ; NEW_LINE DEDENT def minpalparti_memo ( input , i , j , memo ) : NEW_LINE INDENT if ( i > j ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT ij = convert ( i , j ) ; NEW_LINE if ( ij in memo ) : NEW_LINE INDENT return memo [ ij ] ; NEW_LINE DEDENT if ( i == j ) : NEW_LINE INDENT memo [ ij ] = 0 ; NEW_LINE return 0 ; NEW_LINE DEDENT if ( ispallindrome ( input , i , j ) ) : NEW_LINE INDENT memo [ ij ] = 0 ; NEW_LINE return 0 ; NEW_LINE DEDENT minimum = 1000000000 NEW_LINE for k in range ( i , j ) : NEW_LINE INDENT left_min = 1000000000 NEW_LINE right_min = 1000000000 NEW_LINE left = convert ( i , k ) ; NEW_LINE right = convert ( k + 1 , j ) ; NEW_LINE if ( left in memo ) : NEW_LINE INDENT left_min = memo [ left ] ; NEW_LINE DEDENT if ( right in memo ) : NEW_LINE INDENT right_min = memo [ right ] ; NEW_LINE DEDENT if ( left_min == 1000000000 ) : NEW_LINE INDENT left_min = minpalparti_memo ( input , i , k , memo ) ; NEW_LINE DEDENT if ( right_min == 1000000000 ) : NEW_LINE INDENT right_min = minpalparti_memo ( input , k + 1 , j , memo ) ; NEW_LINE DEDENT minimum = min ( minimum , left_min + 1 + right_min ) ; NEW_LINE DEDENT memo [ ij ] = minimum ; NEW_LINE return memo [ ij ] ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT input = " ababbbabbababa " ; NEW_LINE memo = dict ( ) NEW_LINE print ( minpalparti_memo ( input , 0 , len ( input ) - 1 , memo ) ) NEW_LINE DEDENT |
Longest Bitonic Subsequence | DP | lbs ( ) returns the length of the Longest Bitonic Subsequence in arr [ ] of size n . The function mainly creates two temporary arrays lis [ ] and lds [ ] and returns the maximum lis [ i ] + lds [ i ] - 1. lis [ i ] == > Longest Increasing subsequence ending with arr [ i ] lds [ i ] == > Longest decreasing subsequence starting with arr [ i ] ; allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right ; allocate memory for LDS and initialize LDS values for all indexes ; Compute LDS values from right to left for i in reversed ( range ( n - 1 ) ) : loop from n - 2 downto 0 for j in reversed ( range ( i - 1 , n ) ) : loop from n - 1 downto i - 1 ; Return the maximum value of ( lis [ i ] + lds [ i ] - 1 ) ; Driver program to test the above function | def lbs ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE lis = [ 1 for i in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( 0 , i ) : NEW_LINE INDENT if ( ( arr [ i ] > arr [ j ] ) and ( lis [ i ] < lis [ j ] + 1 ) ) : NEW_LINE INDENT lis [ i ] = lis [ j ] + 1 NEW_LINE DEDENT DEDENT DEDENT lds = [ 1 for i in range ( n + 1 ) ] NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and lds [ i ] < lds [ j ] + 1 ) : NEW_LINE INDENT lds [ i ] = lds [ j ] + 1 NEW_LINE DEDENT DEDENT maximum = lis [ 0 ] + lds [ 0 ] - 1 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT maximum = max ( ( lis [ i ] + lds [ i ] - 1 ) , maximum ) NEW_LINE DEDENT return maximum NEW_LINE DEDENT arr = [ 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 ] NEW_LINE print " Length β of β LBS β is " , lbs ( arr ) NEW_LINE |
Egg Dropping Puzzle | DP | A Dynamic Programming based Python Program for the Egg Dropping Puzzle ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; A 2D table where entry eggFloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; We need one trial for one floor and0 trials for 0 floors ; We always need j trials for one egg and j floors . ; Fill rest of the entries in table using optimal substructure property ; eggFloor [ n ] [ k ] holds the result ; Driver program to test to pront printDups | INT_MAX = 32767 NEW_LINE def eggDrop ( n , k ) : NEW_LINE INDENT eggFloor = [ [ 0 for x in range ( k + 1 ) ] for x in range ( n + 1 ) ] NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT eggFloor [ i ] [ 1 ] = 1 NEW_LINE eggFloor [ i ] [ 0 ] = 0 NEW_LINE DEDENT for j in range ( 1 , k + 1 ) : NEW_LINE INDENT eggFloor [ 1 ] [ j ] = j NEW_LINE DEDENT for i in range ( 2 , n + 1 ) : NEW_LINE INDENT for j in range ( 2 , k + 1 ) : NEW_LINE INDENT eggFloor [ i ] [ j ] = INT_MAX NEW_LINE for x in range ( 1 , j + 1 ) : NEW_LINE INDENT res = 1 + max ( eggFloor [ i - 1 ] [ x - 1 ] , eggFloor [ i ] [ j - x ] ) NEW_LINE if res < eggFloor [ i ] [ j ] : NEW_LINE INDENT eggFloor [ i ] [ j ] = res NEW_LINE DEDENT DEDENT DEDENT DEDENT return eggFloor [ n ] [ k ] NEW_LINE DEDENT n = 2 NEW_LINE k = 36 NEW_LINE print ( " Minimum β number β of β trials β in β worst β case β with " + str ( n ) + " eggs β and β " + str ( k ) + " β floors β is β " + str ( eggDrop ( n , k ) ) ) NEW_LINE |
0 | Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack of capacity W , then this item cannot be included in the optimal solution ; return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver Code | def knapSack ( W , wt , val , n ) : NEW_LINE INDENT if n == 0 or W == 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( wt [ n - 1 ] > W ) : NEW_LINE INDENT return knapSack ( W , wt , val , n - 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) NEW_LINE DEDENT DEDENT val = [ 60 , 100 , 120 ] NEW_LINE wt = [ 10 , 20 , 30 ] NEW_LINE W = 50 NEW_LINE n = len ( val ) NEW_LINE print knapSack ( W , wt , val , n ) NEW_LINE |
Min Cost Path | DP | Python3 program for the above approach ; For 1 st column ; For 1 st row ; For rest of the 2d matrix ; Returning the value in last cell ; Driver code | def minCost ( cost , row , col ) : NEW_LINE INDENT for i in range ( 1 , row ) : NEW_LINE INDENT cost [ i ] [ 0 ] += cost [ i - 1 ] [ 0 ] NEW_LINE DEDENT for j in range ( 1 , col ) : NEW_LINE INDENT cost [ 0 ] [ j ] += cost [ 0 ] [ j - 1 ] NEW_LINE DEDENT for i in range ( 1 , row ) : NEW_LINE INDENT for j in range ( 1 , col ) : NEW_LINE INDENT cost [ i ] [ j ] += ( min ( cost [ i - 1 ] [ j - 1 ] , min ( cost [ i - 1 ] [ j ] , cost [ i ] [ j - 1 ] ) ) ) NEW_LINE DEDENT DEDENT return cost [ row - 1 ] [ col - 1 ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT row = 3 NEW_LINE col = 3 NEW_LINE cost = [ [ 1 , 2 , 3 ] , [ 4 , 8 , 2 ] , [ 1 , 5 , 3 ] ] NEW_LINE print ( minCost ( cost , row , col ) ) ; NEW_LINE DEDENT |
Longest Increasing Subsequence | DP | To make use of recursive calls , this function must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose 2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base Case ; maxEndingHere is the length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] . . arr [ n - 2 ] IF arr [ n - 1 ] is maller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare maxEndingHere with overall maximum . And update the overall maximum if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; maximum variable holds the result ; The function _lis ( ) stores its result in maximum ; returns max ; Driver program to test the above function | global maximum NEW_LINE def _lis ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT return 1 NEW_LINE DEDENT maxEndingHere = 1 NEW_LINE for i in xrange ( 1 , n ) : NEW_LINE INDENT res = _lis ( arr , i ) NEW_LINE if arr [ i - 1 ] < arr [ n - 1 ] and res + 1 > maxEndingHere : NEW_LINE INDENT maxEndingHere = res + 1 NEW_LINE DEDENT DEDENT maximum = max ( maximum , maxEndingHere ) NEW_LINE return maxEndingHere NEW_LINE DEDENT def lis ( arr ) : NEW_LINE INDENT n = len ( arr ) NEW_LINE maximum = 1 NEW_LINE _lis ( arr , n ) NEW_LINE return maximum NEW_LINE DEDENT arr = [ 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 ] NEW_LINE n = len ( arr ) NEW_LINE print " Length β of β lis β is β " , lis ( arr ) NEW_LINE |
Total number of possible Binary Search Trees and Binary Trees with n keys | A function to find factorial of a given number ; Calculate value of [ 1 * ( 2 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; A function to count number of BST with n nodes using catalan ; find nth catalan number ; return nth catalan number ; A function to count number of binary trees with n nodes ; find count of BST with n numbers ; return count * n ! ; Driver Code ; find count of BST and binary trees with n nodes ; print count of BST and binary trees with n nodes | def factorial ( n ) : NEW_LINE INDENT res = 1 NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT res *= i NEW_LINE DEDENT return res NEW_LINE DEDENT def binomialCoeff ( n , k ) : NEW_LINE INDENT res = 1 NEW_LINE if ( k > n - k ) : NEW_LINE INDENT k = n - k NEW_LINE DEDENT for i in range ( k ) : NEW_LINE INDENT res *= ( n - i ) NEW_LINE res //= ( i + 1 ) NEW_LINE DEDENT return res NEW_LINE DEDENT def catalan ( n ) : NEW_LINE INDENT c = binomialCoeff ( 2 * n , n ) NEW_LINE return c // ( n + 1 ) NEW_LINE DEDENT def countBST ( n ) : NEW_LINE INDENT count = catalan ( n ) NEW_LINE return count NEW_LINE DEDENT def countBT ( n ) : NEW_LINE INDENT count = catalan ( n ) NEW_LINE return count * factorial ( n ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 NEW_LINE count1 = countBST ( n ) NEW_LINE count2 = countBT ( n ) NEW_LINE print ( " Count β of β BST β with " , n , " nodes β is " , count1 ) NEW_LINE print ( " Count β of β binary β trees β with " , n , " nodes β is " , count2 ) NEW_LINE DEDENT |
Find all numbers in range [ 1 , N ] that are not present in given Array | Function to find the missing numbers ; Traverse the array arr [ ] ; Update ; Traverse the array arr [ ] ; If Num is not present ; Given Input ; Function Call | def getMissingNumbers ( arr ) : NEW_LINE INDENT for num in arr : NEW_LINE INDENT arr [ abs ( num ) - 1 ] = - ( abs ( arr [ abs ( num ) - 1 ] ) ) NEW_LINE DEDENT for pos , num in enumerate ( arr ) : NEW_LINE INDENT if num > 0 : NEW_LINE INDENT print ( pos + 1 , end = ' β ' ) NEW_LINE DEDENT DEDENT DEDENT arr = [ 5 , 5 , 4 , 4 , 2 ] NEW_LINE getMissingNumbers ( arr ) NEW_LINE |
Find the Kth smallest odd length palindrome number | Function to find the Kth smallest odd length palindrome number ; Store the original number K ; Removing the last digit of K ; Generate the palindrome by appending the reverse of K except last digit to itself ; Find the remainder ; Add the digit to palin ; Divide K by 10 ; Return the resultant palindromic number formed ; Driver Code | def oddLengthPalindrome ( K ) : NEW_LINE INDENT palin = K NEW_LINE K = K // 10 NEW_LINE while ( K > 0 ) : NEW_LINE INDENT rev = K % 10 NEW_LINE palin = palin * 10 + rev NEW_LINE K = K // 10 NEW_LINE DEDENT return palin NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT K = 504 NEW_LINE print ( oddLengthPalindrome ( K ) ) NEW_LINE DEDENT |
Maximize length of subsequence consisting of single distinct character possible by K increments in a string | Function to find the maximum length of a subsequence of same characters after at most K increment operations ; Store the size of S ; sort tempArray ; Stores the maximum length and the sum of the sliding window ; Traverse the S ; Add the current character to the window ; Decrease the window size ; Update the value of sum ; Increment the value of start ; Update the maximum window size ; Print the resultant maximum length of the subsequence ; Driver Code | def maxSubsequenceLen ( S , K ) : NEW_LINE INDENT N = len ( S ) NEW_LINE start , end = 0 , 0 NEW_LINE S = sorted ( S ) NEW_LINE ans , sum = - 10 ** 9 , 0 NEW_LINE for end in range ( N ) : NEW_LINE INDENT sum = sum + ( ord ( S [ end ] ) - ord ( ' a ' ) ) NEW_LINE while ( sum + K < ( ord ( S [ end ] ) - ord ( ' a ' ) ) * ( end - start + 1 ) ) : NEW_LINE INDENT sum = sum - ( ord ( S [ start ] ) - ord ( ' a ' ) ) NEW_LINE start += 1 NEW_LINE DEDENT ans = max ( ans , end - start + 1 ) NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " acscbcca " NEW_LINE K = 1 NEW_LINE maxSubsequenceLen ( S , K ) NEW_LINE DEDENT |
Check if a given integer is the product of K consecutive integers | Function to check if N can be expressed as the product of K consecutive integers ; Stores the K - th root of N ; Stores the product of K consecutive integers ; Traverse over the range [ 1 , K ] ; Update the product ; If product is N , then return " Yes " ; Otherwise , traverse over the range [ 2 , Kthroot ] ; Update the value of product ; If product is equal to N ; Otherwise , return " No " ; Driver Code | def checkPro ( n , k ) : NEW_LINE INDENT KthRoot = int ( n ** ( 1 / k ) ) NEW_LINE product = 1 NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT product = product * i NEW_LINE DEDENT print ( product ) NEW_LINE if ( product == N ) : NEW_LINE INDENT return ( " Yes " ) NEW_LINE DEDENT for i in range ( 2 , KthRoot + 1 ) : NEW_LINE INDENT product = product * ( i + k - 1 ) NEW_LINE product = product / ( i - 1 ) NEW_LINE print ( product ) NEW_LINE if ( product == N ) : NEW_LINE INDENT return ( " Yes " ) NEW_LINE DEDENT DEDENT return ( " No " ) NEW_LINE DEDENT N = 210 NEW_LINE K = 3 NEW_LINE print ( checkPro ( N , K ) ) NEW_LINE |
Count possible removals to make absolute difference between the sum of odd and even indexed elements equal to K | Function to check if difference between the sum of odd and even indexed elements after removing the first element is K or not ; Stores the sum of elements at odd and even indices ; Return 1 if difference is K ; Function to check if difference between the sum of odd and even indexed elements after removing the second element is K or not ; Stores the sum of elements at odd and even indices ; Return 1 if difference is K ; Function to count number of elements to be removed to make sum of differences between odd and even indexed elements equal to K ; Size of given array ; Base Conditions ; Stores prefix and suffix sums ; Base assignments ; Store prefix sums of even indexed elements ; Store prefix sums of odd indexed elements ; Similarly , store suffix sums of elements at even and odd indices ; Stores the count of possible removals ; Traverse and remove the ith element ; If the current element is excluded , then previous index ( i - 1 ) points to ( i + 2 ) and ( i - 2 ) points to ( i + 1 ) ; Find count when 0 th element is removed ; Find count when 1 st element is removed ; Count gives the required answer ; Driver Code ; Function call | def findCount0th ( arr , N , K ) : NEW_LINE INDENT oddsum = 0 NEW_LINE evensum = 0 NEW_LINE for i in range ( 1 , N , 2 ) : NEW_LINE INDENT oddsum += arr [ i ] NEW_LINE DEDENT for i in range ( 2 , N , 2 ) : NEW_LINE INDENT evensum += arr [ i ] NEW_LINE DEDENT if ( abs ( oddsum - evensum ) == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def findCount1st ( arr , N , K ) : NEW_LINE INDENT evensum = arr [ 0 ] NEW_LINE oddsum = 0 NEW_LINE for i in range ( 3 , N , 2 ) : NEW_LINE INDENT evensum += arr [ i ] NEW_LINE DEDENT for i in range ( 2 , N , 2 ) : NEW_LINE INDENT oddsum += arr [ i ] NEW_LINE DEDENT if ( abs ( oddsum - evensum ) == K ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT def countTimes ( arr , K ) : NEW_LINE INDENT N = len ( arr ) NEW_LINE if ( N == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( N < 3 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( N == 3 ) : NEW_LINE INDENT cnt = 0 NEW_LINE if abs ( arr [ 0 ] - arr [ 1 ] ) == K : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if abs ( arr [ 2 ] - arr [ 1 ] ) == K : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT if abs ( arr [ 0 ] - arr [ 2 ] ) == K : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT prefix = [ 0 ] * ( N + 2 ) NEW_LINE suffix = [ 0 ] * ( N + 2 ) NEW_LINE prefix [ 0 ] = arr [ 0 ] NEW_LINE prefix [ 1 ] = arr [ 1 ] NEW_LINE suffix [ N - 1 ] = arr [ N - 1 ] NEW_LINE suffix [ N - 2 ] = arr [ N - 2 ] NEW_LINE for i in range ( 2 , N , 2 ) : NEW_LINE INDENT prefix [ i ] = arr [ i ] + prefix [ i - 2 ] NEW_LINE DEDENT for i in range ( 3 , N , 2 ) : NEW_LINE INDENT prefix [ i ] = arr [ i ] + prefix [ i - 2 ] NEW_LINE DEDENT for i in range ( N - 3 , - 1 , - 2 ) : NEW_LINE INDENT suffix [ i ] = arr [ i ] + suffix [ i + 2 ] NEW_LINE DEDENT for i in range ( N - 4 , - 1 , - 2 ) : NEW_LINE INDENT suffix [ i ] = arr [ i ] + suffix [ i + 2 ] NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 2 , N ) : NEW_LINE INDENT if ( abs ( prefix [ i - 1 ] + suffix [ i + 2 ] - prefix [ i - 2 ] - suffix [ i + 1 ] ) == K ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT count += findCount0th ( arr , N , K ) NEW_LINE count += findCount1st ( arr , N , K ) NEW_LINE return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 4 , 5 , 6 ] NEW_LINE K = 2 NEW_LINE print ( countTimes ( arr , K ) ) NEW_LINE DEDENT |
Replace ' ? ' in a string such that no two adjacent characters are same | Function that replace all ' ? ' with lowercase alphabets such that each adjacent character is different ; Store the given String ; If the first character is '? ; Traverse the String [ 1 , N - 1 ] ; If the current character is '? ; Change the character ; Check equality with the previous character ; Check equality with the next character ; Check equality with the previous character ; If the last character is '? ; Change character ; Check with previous character ; Return the resultant String ; Driver Code ; Given String S ; Function Call | def changeString ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE s = [ ' β ' ] * ( len ( S ) ) NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT s [ i ] = S [ i ] NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( s [ 0 ] == ' ? ' ) : NEW_LINE INDENT s [ 0 ] = ' a ' NEW_LINE if ( s [ 0 ] == s [ 1 ] ) : NEW_LINE INDENT s [ 0 ] = chr ( ord ( s [ 0 ] ) + 1 ) NEW_LINE DEDENT DEDENT for i in range ( 1 , N - 1 ) : NEW_LINE DEDENT ' NEW_LINE INDENT if ( s [ i ] == ' ? ' ) : NEW_LINE INDENT s [ i ] = ' a ' NEW_LINE if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT if ( s [ i ] == s [ i + 1 ] ) : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT if ( s [ i ] == s [ i - 1 ] ) : NEW_LINE INDENT s [ i ] = chr ( ord ( s [ i ] ) + 1 ) NEW_LINE DEDENT DEDENT DEDENT ' NEW_LINE INDENT if ( s [ N - 1 ] == ' ? ' ) : NEW_LINE INDENT s [ N - 1 ] = ' a ' NEW_LINE if ( s [ N - 1 ] == s [ N - 2 ] ) : NEW_LINE INDENT s [ N - 1 ] += 1 NEW_LINE DEDENT DEDENT ans = " " NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT ans += s [ i ] NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ? a ? a " NEW_LINE print ( changeString ( S ) ) NEW_LINE DEDENT |
Check if a given string is a Reverse Bitonic String or not | Function to check if the given string is reverse bitonic ; Check for decreasing sequence ; If end of string has been reached ; Check for increasing sequence ; If the end of string hasn 't been reached ; If reverse bitonic ; Driver Code | def checkReverseBitonic ( s ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] < s [ i - 1 ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( s [ i ] >= s [ i - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT if ( i == len ( s ) - 1 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ j ] > s [ j - 1 ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( s [ j ] <= s [ j - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT i = j ; NEW_LINE if ( i != len ( s ) ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT return 1 ; NEW_LINE DEDENT s = " abcdwef " NEW_LINE if ( checkReverseBitonic ( s ) == 1 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
Smallest number whose square has N digits | Python3 Program to find the smallest number whose square has N digits ; Function to return smallest number whose square has N digits ; Calculate N - th term of the series ; Driver Code | import math ; NEW_LINE def smallestNum ( N ) : NEW_LINE INDENT x = pow ( 10.0 , ( N - 1 ) / 2.0 ) ; NEW_LINE return math . ceil ( x ) ; NEW_LINE DEDENT N = 4 ; NEW_LINE print ( smallestNum ( N ) ) ; NEW_LINE |
Count of K | Function to to count the number of K - countdowns for multiple queries ; flag which stores the current value of value in the countdown ; count of K - countdowns ; Loop to iterate over the elements of the array ; condition check if the elements of the array is equal to K ; condition check if the elements of the array is in continuous order ; condition check if the elements of the array are not in continuous order ; condition check to increment the counter if the there is a K - countdown present in the array ; returning the count of K - countdowns ; Driver Code ; Function Call | def countKCountdown ( arr , N , K ) : NEW_LINE INDENT flag = - 1 ; NEW_LINE count = 0 ; NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] == K ) : NEW_LINE INDENT flag = K ; NEW_LINE DEDENT if ( arr [ i ] == flag ) : NEW_LINE INDENT flag -= 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT flag = - 1 ; NEW_LINE DEDENT if ( flag == 0 ) : NEW_LINE INDENT count += 1 ; NEW_LINE DEDENT DEDENT return count ; NEW_LINE DEDENT N = 8 ; NEW_LINE K = 3 ; NEW_LINE arr = [ 4 , 3 , 2 , 1 , 5 , 3 , 2 , 1 ] ; NEW_LINE print ( countKCountdown ( arr , N , K ) ) NEW_LINE |
Convert the given RGB color code to Hex color code | Function to convert decimal to hexadecimal ; char array to store hexadecimal number ; Counter for hexadecimal number array ; Temporary variable to store remainder ; Storing remainder in temp variable . ; Check if temp < 10 ; Return the equivalent hexadecimal color code ; Function to convert the RGB code to Hex color code ; The hex color code doesn 't exist ; Driver Code | def decToHexa ( n ) : NEW_LINE INDENT hexaDeciNum = [ '0' ] * 100 NEW_LINE i = 0 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT temp = 0 NEW_LINE temp = n % 16 NEW_LINE if ( temp < 10 ) : NEW_LINE INDENT hexaDeciNum [ i ] = chr ( temp + 48 ) NEW_LINE i = i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT hexaDeciNum [ i ] = chr ( temp + 55 ) NEW_LINE i = i + 1 NEW_LINE DEDENT n = int ( n / 16 ) NEW_LINE DEDENT hexCode = " " NEW_LINE if ( i == 2 ) : NEW_LINE INDENT hexCode = hexCode + hexaDeciNum [ 0 ] NEW_LINE hexCode = hexCode + hexaDeciNum [ 1 ] NEW_LINE DEDENT elif ( i == 1 ) : NEW_LINE INDENT hexCode = "0" NEW_LINE hexCode = hexCode + hexaDeciNum [ 0 ] NEW_LINE DEDENT elif ( i == 0 ) : NEW_LINE INDENT hexCode = "00" NEW_LINE DEDENT return hexCode NEW_LINE DEDENT def convertRGBtoHex ( R , G , B ) : NEW_LINE INDENT if ( ( R >= 0 and R <= 255 ) and ( G >= 0 and G <= 255 ) and ( B >= 0 and B <= 255 ) ) : NEW_LINE INDENT hexCode = hexCode + decToHexa ( R ) NEW_LINE hexCode = hexCode + decToHexa ( G ) NEW_LINE hexCode = hexCode + decToHexa ( B ) NEW_LINE return hexCode NEW_LINE DEDENT else : NEW_LINE INDENT return " - 1" NEW_LINE DEDENT DEDENT R = 0 NEW_LINE G = 0 NEW_LINE B = 0 NEW_LINE print ( convertRGBtoHex ( R , G , B ) ) NEW_LINE R = 255 NEW_LINE G = 255 NEW_LINE B = 255 NEW_LINE print ( convertRGBtoHex ( R , G , B ) ) NEW_LINE R = 25 NEW_LINE G = 56 NEW_LINE B = 123 NEW_LINE print ( convertRGBtoHex ( R , G , B ) ) NEW_LINE R = 2 NEW_LINE G = 3 NEW_LINE B = 4 NEW_LINE print ( convertRGBtoHex ( R , G , B ) ) NEW_LINE R = 255 NEW_LINE G = 255 NEW_LINE B = 256 NEW_LINE print ( convertRGBtoHex ( R , G , B ) ) NEW_LINE |
Strings formed from given characters without any consecutive repeating characters | Function to print the strings which satisfy the mentioned conditions ; Iterate through all the strings in the array . ; check function to check the conditions for every string ; Function to check whether the string contains any consecutive repetitive characters and any characters other than those in str ; Valid characters check ; Nonrepetitive check ; Driver code | def getStrings ( strr , arr ) : NEW_LINE INDENT for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( check ( arr [ i ] , strr ) ) : NEW_LINE INDENT print ( arr [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT def check ( s , strr ) : NEW_LINE INDENT chars = s NEW_LINE for c in chars : NEW_LINE INDENT if c not in strr : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT for i in range ( len ( chars ) - 1 ) : NEW_LINE INDENT if ( chars [ i ] == chars [ i + 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT strr = " ABCD " NEW_LINE arr = [ " AABCDA " , " ABCDZADC " , " ABCDBCA " , " ABCDABDCA " ] NEW_LINE getStrings ( strr , arr ) NEW_LINE |
Program to build a DFA to accept strings that start and end with same character | Function for the state Q1 ; Condition to check end of string ; State transitions ' a ' takes to q1 , and ' b ' takes to q2 ; Function for the state Q2 ; Condition to check end of string ; State transitions ' a ' takes to q1 , and ' b ' takes to q2 ; Function for the state Q3 ; Condition to check end of string ; State transitions ' a ' takes to q4 , and ' b ' takes to q3 ; Function for the state Q4 ; Condition to check end of string ; State transitions ' a ' takes to q4 , and ' b ' takes to q3 ; Function for the state Q0 ; Condition to check end of string ; State transitions ' a ' takes to q1 , and ' b ' takes to q3 ; Driver Code ; Since q0 is the starting state Send the string to q0 | def q1 ( s , i ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE return ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT q1 ( s , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT q2 ( s , i + 1 ) ; NEW_LINE DEDENT DEDENT def q2 ( s , i ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE return ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT q1 ( s , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT q2 ( s , i + 1 ) ; NEW_LINE DEDENT DEDENT def q3 ( s , i ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE return ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT q4 ( s , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT q3 ( s , i + 1 ) ; NEW_LINE DEDENT DEDENT def q4 ( s , i ) : NEW_LINE INDENT if ( i == s . length ( ) ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE return ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT q4 ( s , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT q3 ( s , i + 1 ) ; NEW_LINE DEDENT DEDENT def q0 ( s , i ) : NEW_LINE INDENT if ( i == len ( s ) ) : NEW_LINE INDENT print ( " No " ) ; NEW_LINE return ; NEW_LINE DEDENT if ( s [ i ] == ' a ' ) : NEW_LINE INDENT q1 ( s , i + 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT q3 ( s , i + 1 ) ; NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " abbaabb " ; NEW_LINE q0 ( s , 0 ) ; NEW_LINE DEDENT |
Longest prefix in a string with highest frequency | Function to find Longest prefix string with the highest frequency ; storing all indices where first element is found ; if the first letter in the string does not occur again then answer will be the whole string ; loop till second appearance of the first element ; check one letter after every stored index ; If there is no mismatch we move forward ; otherwise we stop ; Driver Code | def prefix ( string ) : NEW_LINE INDENT k = 1 ; NEW_LINE n = len ( string ) ; NEW_LINE g = [ ] ; NEW_LINE flag = 0 ; NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( string [ i ] == string [ 0 ] ) : NEW_LINE INDENT g . append ( i ) ; NEW_LINE flag = 1 ; NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( string ) ; NEW_LINE DEDENT else : NEW_LINE INDENT length = len ( g ) ; NEW_LINE while ( k < g [ 0 ] ) : NEW_LINE INDENT cnt = 0 ; NEW_LINE for j in range ( length ) : NEW_LINE INDENT if ( string [ g [ j ] + k ] == string [ k ] ) : NEW_LINE INDENT cnt += 1 ; NEW_LINE DEDENT DEDENT if ( cnt == len ) : NEW_LINE INDENT k += 1 ; NEW_LINE DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT for i in range ( k + 1 ) : NEW_LINE INDENT print ( string [ i ] , end = " " ) ; NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " abcab " ; NEW_LINE prefix ( string ) ; NEW_LINE DEDENT |
Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers | Function to generate a permutation of integers from 1 to N such that the absolute difference of all the two consecutive integers give K distinct integers ; To store the permutation ; For sequence 1 2 3. . . ; For sequence N , N - 1 , N - 2. . . ; Flag is used to alternate between the above if else statements ; If last element added was r + 1 ; If last element added was l - 1 ; Print the permutation ; Driver code | def printPermutation ( N , K ) : NEW_LINE INDENT res = list ( ) ; NEW_LINE l , r , flag = 1 , N , 0 NEW_LINE for i in range ( K ) : NEW_LINE INDENT if flag == False : NEW_LINE INDENT res . append ( l ) NEW_LINE l += 1 NEW_LINE DEDENT else : NEW_LINE INDENT res . append ( r ) ; NEW_LINE r -= 1 ; NEW_LINE DEDENT flag = flag ^ 1 ; NEW_LINE DEDENT if flag == False : NEW_LINE INDENT for i in range ( r , 2 , - 1 ) : NEW_LINE INDENT res . append ( i ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for i in range ( l , r ) : NEW_LINE INDENT res . append ( i ) NEW_LINE DEDENT DEDENT for i in res : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT N , K = 10 , 4 NEW_LINE printPermutation ( N , K ) NEW_LINE |
Find Nth term of the series 1 , 8 , 54 , 384. . . | calculate factorial of N ; calculate Nth term of series ; Driver Code | def fact ( N ) : NEW_LINE INDENT product = 1 NEW_LINE for i in range ( 1 , N + 1 ) : NEW_LINE INDENT product = product * i NEW_LINE DEDENT return product NEW_LINE DEDENT def nthTerm ( N ) : NEW_LINE INDENT return ( N * N ) * fact ( N ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 4 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE DEDENT |
Rabin | d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern t = 0 hash value for txt ; The value of h would be " pow ( d , β M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern if the hash values match then only check for characters on by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative values of t , converting it to positive ; Driver Code ; A prime number ; Function Call | d = 256 NEW_LINE def search ( pat , txt , q ) : NEW_LINE INDENT M = len ( pat ) NEW_LINE N = len ( txt ) NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE h = 1 NEW_LINE for i in xrange ( M - 1 ) : NEW_LINE INDENT h = ( h * d ) % q NEW_LINE DEDENT for i in xrange ( M ) : NEW_LINE INDENT p = ( d * p + ord ( pat [ i ] ) ) % q NEW_LINE t = ( d * t + ord ( txt [ i ] ) ) % q NEW_LINE DEDENT for i in xrange ( N - M + 1 ) : NEW_LINE INDENT if p == t : NEW_LINE INDENT for j in xrange ( M ) : NEW_LINE INDENT if txt [ i + j ] != pat [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT else : j += 1 NEW_LINE DEDENT if j == M : NEW_LINE INDENT print " Pattern β found β at β index β " + str ( i ) NEW_LINE DEDENT DEDENT if i < N - M : NEW_LINE INDENT t = ( d * ( t - ord ( txt [ i ] ) * h ) + ord ( txt [ i + M ] ) ) % q NEW_LINE if t < 0 : NEW_LINE INDENT t = t + q NEW_LINE DEDENT DEDENT DEDENT DEDENT txt = " GEEKS β FOR β GEEKS " NEW_LINE pat = " GEEK " NEW_LINE q = 101 NEW_LINE search ( pat , txt , q ) NEW_LINE |
Find the final string after flipping bits at the indices that are multiple of prime factors of array elements | Python program for the above approach ; Stores smallest prime factor ; Function to find the smallest prime factor for every number till MAXN ; Marking smallest prime factor for every number to be itself ; Separately marking spf for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Function to find all the distinct prime factors of the given number x ; Find the prime factors for X ; Find the spf [ ] of x ; Return the prime factors for x ; Function to find string after flipping the characters at indices of prime factors of array elements arr [ ] ; Precalculating Smallest Prime Factor ; Stores the frequency of each prime factor ; Iterate over all elements of the array arr [ ] ; Stores prime factors of arr [ i ] ; Increment the frequency of all prime factors of arr [ i ] ; Iterate over all elements of the array frequency [ ] ; If frequency [ i ] is odd ; Flip bits of all indices that are multiple of i ; Return Answer ; Driver Code | MAXN = 100001 NEW_LINE spf = [ 0 ] * MAXN NEW_LINE def sieve ( ) : NEW_LINE INDENT spf [ 1 ] = 1 NEW_LINE for i in range ( 2 , MAXN ) : NEW_LINE INDENT spf [ i ] = i NEW_LINE DEDENT for i in range ( 4 , MAXN , 2 ) : NEW_LINE INDENT spf [ i ] = 2 NEW_LINE DEDENT i = 3 NEW_LINE while ( i * 8 < MAXN ) : NEW_LINE INDENT i += 1 NEW_LINE if ( spf [ i ] == i ) : NEW_LINE INDENT for j in range ( i * i , MAXN , i ) : NEW_LINE INDENT if ( spf [ j ] == j ) : NEW_LINE INDENT spf [ j ] = i NEW_LINE DEDENT DEDENT DEDENT DEDENT DEDENT def getFactorization ( x ) : NEW_LINE INDENT ret = [ ] NEW_LINE while ( x != 1 ) : NEW_LINE INDENT ret . append ( spf [ x ] ) NEW_LINE value = spf [ x ] NEW_LINE while ( x % value == 0 ) : NEW_LINE INDENT x = x // value NEW_LINE DEDENT DEDENT return ret NEW_LINE DEDENT def flipString ( S , arr , M ) : NEW_LINE INDENT sieve ( ) ; NEW_LINE frequency = [ 0 ] * MAXN NEW_LINE for i in range ( 0 , M ) : NEW_LINE INDENT primeFactors = getFactorization ( arr [ i ] ) NEW_LINE for factors in primeFactors : NEW_LINE INDENT frequency [ factors ] += 1 NEW_LINE frequency [ factors ] %= 2 NEW_LINE DEDENT DEDENT N = len ( S ) NEW_LINE for i in range ( 0 , MAXN ) : NEW_LINE INDENT if ( frequency [ i ] & 1 ) : NEW_LINE INDENT for j in range ( i , N + 1 , i ) : NEW_LINE INDENT S [ j - 1 ] = ( '0' if S [ j - 1 ] == '1' else '1' ) NEW_LINE DEDENT DEDENT DEDENT return S NEW_LINE DEDENT S = "000000" NEW_LINE S = list ( S ) NEW_LINE arr = [ 2 , 4 , 6 ] NEW_LINE M = len ( arr ) NEW_LINE print ( " " . join ( flipString ( S , arr , M ) ) ) NEW_LINE |
Check if count of 1 s can be made greater in a Binary string by changing 0 s adjacent to 1 s | Function to check whether in a given binary string can we make number of 1 ' s β greater β than β the β number β of β 0' s by doing the given operation ; Stores the count of 0 's ; Stores the count of 1 's ; Traverse through the string S ; Check current character is 1 ; Update cnt1 ; Update cnt0 ; Traverse through the string S ; Check curretn character is 1 ; Check if left adjacent character is 0 ; Change the left adjacent character to _ ; Update the cnt0 ; Check if right adjacent character is 0 ; Change the right adjacent character to _ ; Update the cnt0 ; Check count of 1 ' s β is β greater β β than β the β count β of β 0' s ; Driver Code | def isOnesGreater ( S , N ) : NEW_LINE INDENT S = list ( S ) NEW_LINE cnt0 = 0 NEW_LINE cnt1 = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT cnt1 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT cnt0 += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT if ( S [ i ] == '1' ) : NEW_LINE INDENT if ( i > 0 and S [ i - 1 ] == '0' ) : NEW_LINE INDENT S [ i - 1 ] = ' _ ' NEW_LINE cnt0 -= 1 NEW_LINE DEDENT elif ( i < N and S [ i + 1 ] == '0' ) : NEW_LINE INDENT S [ i + 1 ] = ' _ ' NEW_LINE cnt0 -= 1 NEW_LINE DEDENT DEDENT DEDENT if ( cnt1 > cnt0 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT S = "01" NEW_LINE N = len ( S ) NEW_LINE isOnesGreater ( S , N ) NEW_LINE |
Minimize flips to make binary string as all 1 s by flipping characters in substring of size K repeatedly | Function to find the minimum number of operations required to convert all the characters to 1 by flipping the substrings of size K ; Stores the minimum number of operations required ; Traverse the string S ; If the character is 0 ; Flip the substrings of size K starting from i ; Increment the minimum count of operations required ; After performing the operations check if string S contains any 0 s ; If S contains only 1 's ; Driver Code | def minOperation ( St , K , N ) : NEW_LINE INDENT S = list ( St ) NEW_LINE min = 0 NEW_LINE i = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( S [ i ] == '0' and i + K <= N ) : NEW_LINE INDENT j = i NEW_LINE while ( j < i + K ) : NEW_LINE INDENT if ( S [ j ] == '1' ) : NEW_LINE INDENT S [ j ] = '0' NEW_LINE DEDENT else : NEW_LINE INDENT S [ j ] = '1' NEW_LINE DEDENT j += 1 NEW_LINE DEDENT min += 1 NEW_LINE DEDENT DEDENT temp = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT temp += 1 NEW_LINE if ( S [ i ] == '0' ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( temp == N ) : NEW_LINE INDENT print ( min ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( - 1 ) NEW_LINE DEDENT DEDENT S = "00010110" NEW_LINE K = 3 NEW_LINE N = len ( S ) NEW_LINE minOperation ( S , K , N ) NEW_LINE |
Check if string S1 can be formed using repeated insertions of another string S2 | Function to check a valid insertion ; Store the size of string ; Maintain a stack for characters ; Iterate through the string ; push the current character on top of the stack ; If the current character is the last character of string S2 then pop characters until S2 is not formed ; index of last character of the string S2 ; pop characters till 0 - th index ; Check if stack in non - empty ; Driver Code | def validInsertionstring ( S1 , S2 ) : NEW_LINE INDENT N = len ( S1 ) NEW_LINE M = len ( S2 ) NEW_LINE st = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT st . append ( S1 [ i ] ) NEW_LINE if ( S1 [ i ] == S2 [ M - 1 ] ) : NEW_LINE INDENT idx = M - 1 NEW_LINE while ( idx >= 0 ) : NEW_LINE INDENT if ( len ( st ) == 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT c = st [ - 1 ] NEW_LINE st . pop ( ) NEW_LINE if ( c != S2 [ idx ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT idx -= 1 NEW_LINE DEDENT DEDENT DEDENT if ( len ( st ) != 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT S1 = " aabb " NEW_LINE S2 = " ab " NEW_LINE if validInsertionstring ( S1 , S2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
Minimum number of towers required such that every house is in the range of at least one tower | Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; Driver code ; given elements ; print number of towers | def number_of_tower ( house , r , n ) : NEW_LINE INDENT house . sort ( ) NEW_LINE numOfTower = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT numOfTower += 1 NEW_LINE loc = house [ i ] + r NEW_LINE while ( i < n and house [ i ] <= loc ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT i -= 1 NEW_LINE loc = house [ i ] + r NEW_LINE while ( i < n and house [ i ] <= loc ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT DEDENT return numOfTower NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT house = [ 7 , 2 , 4 , 6 , 5 , 9 , 12 , 11 ] NEW_LINE r = 2 NEW_LINE n = len ( house ) NEW_LINE print ( number_of_tower ( house , r , n ) ) NEW_LINE DEDENT |
Check if rearranging Array elements can form a Palindrome or not | Function to check whether elements of an array can form a palindrome ; create an empty string to append elements of an array ; append each element to the string str to form a string so that we can solve it in easy way ; Create a freq array and initialize all values as 0 ; For each character in formed string , increment freq in the corresponding freq array ; Count odd occurring characters ; Return true if odd count is 0 or 1 , ; Driver Code | def can_form_palindrome ( arr , n ) : NEW_LINE INDENT MAX = 256 NEW_LINE s = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT s = s + str ( arr [ i ] ) NEW_LINE DEDENT freq = [ 0 ] * MAX NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] ] = freq [ arr [ i ] ] + 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] & 1 ) : NEW_LINE INDENT count = count + 1 NEW_LINE DEDENT if ( count > 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE if ( can_form_palindrome ( arr , N ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT DEDENT |
Minimum number of flips to make a Binary String increasing | Function to find the minimum number of flips required to make string increasing ; Length of s ; Total number of zero in s ; Stores count of 1 s till ith index ; Stores the minimum count of flips ; Traverse the given string S ; Update the value of res and count of 1 s ; Return the minimum number of flips ; Given String ; Function Call | def minimumFlips ( s ) : NEW_LINE INDENT n = len ( s ) NEW_LINE cnt0 = s . count ( '0' ) NEW_LINE cnt1 = 0 NEW_LINE res = n - cnt0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if s [ i ] == '0' : NEW_LINE INDENT cnt0 -= 1 NEW_LINE DEDENT elif s [ i ] == '1' : NEW_LINE INDENT res = min ( res , cnt1 + cnt0 ) NEW_LINE cnt1 += 1 NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT S = '000110' NEW_LINE print ( minimumFlips ( S ) ) NEW_LINE |
Maximum length of a substring required to be flipped repeatedly to make all characters of binary string equal to 0 | Function to find the maximum value of K such that flipping substrings of size at least K make all characters 0 s ; Stores the maximum value of K ; Traverse the given string S ; Store the minimum of the maximum of LHS and RHS length ; Flip performed ; If no flips performed ; Return the possible value of K ; Driver Code | def maximumK ( S ) : NEW_LINE INDENT N = len ( S ) NEW_LINE ans = N NEW_LINE flag = 0 NEW_LINE for i in range ( N - 1 ) : NEW_LINE INDENT if ( S [ i ] != S [ i + 1 ] ) : NEW_LINE INDENT flag = 1 NEW_LINE ans = min ( ans , max ( i + 1 , N - i - 1 ) ) NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = "010" NEW_LINE print ( maximumK ( S ) ) NEW_LINE DEDENT |
Check if a pair of strings exists that starts with and without the character K or not | Function to check whether a pair of strings exists satisfying the conditions ; Stores the visited strings ; Iterate over the array arr [ ] ; If first character of current string is K ; Otherwise ; Adding to the visited ; Driver Code ; Given Input | def checkhappy ( arr , K , N ) : NEW_LINE INDENT visited = set ( ) NEW_LINE for s in arr : NEW_LINE INDENT if ( s [ 0 ] == K ) : NEW_LINE INDENT if s [ 1 : ] in visited : NEW_LINE INDENT return ' Yes ' NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( K + s ) in visited : NEW_LINE INDENT return ' Yes ' NEW_LINE DEDENT DEDENT visited . add ( s ) NEW_LINE DEDENT return " No " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ ' a ' , ' ! β a ' , ' b ' , ' ! β c ' , ' d ' , ' ! β d ' ] NEW_LINE K = ' ! ' NEW_LINE N = len ( arr ) NEW_LINE print ( checkhappy ( arr , K , N ) ) NEW_LINE DEDENT |
Minimum moves to make count of lowercase and uppercase letters equal | Function to calculate minimum number of moves required to convert the string ; Stores Count of upper and lower case characters ; Traverse the S ; If current character is uppercase ; Increment count of Uppercase characters ; Otherwise , ; Increment count of Lowercase characters ; Stores minimum number of moves needed ; If there are more upper case characters ; Iterate until upper is greater than N / 2 ; Convert uppercase into lowercase until upper = N / 2 ; Increment the pointer ; If there are more lower case characters ; Iterate until lower is greater than N / 2 ; Convert lowercase into uppercase until lower = N / 2 ; Increment the pointer ; Print moves required ; Print resultant string ; Driver Code ; Given string ; Function call | def minimumTimeToConvertString ( S , N ) : NEW_LINE INDENT S = [ i for i in S ] NEW_LINE upper = 0 NEW_LINE lower = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT c = S [ i ] NEW_LINE if ( c . isupper ( ) ) : NEW_LINE INDENT upper += 1 NEW_LINE DEDENT else : NEW_LINE INDENT lower += 1 NEW_LINE DEDENT DEDENT moves = 0 NEW_LINE if ( upper > N // 2 ) : NEW_LINE INDENT i = 0 NEW_LINE while ( upper > N // 2 and i < N ) : NEW_LINE INDENT if ( S [ i ] . isupper ( ) ) : NEW_LINE INDENT S [ i ] += 32 NEW_LINE moves += 1 NEW_LINE upper -= 1 NEW_LINE lower += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT elif ( lower > N // 2 ) : NEW_LINE INDENT i = 0 NEW_LINE while ( lower > N // 2 and i < N ) : NEW_LINE INDENT if ( S [ i ] . islower ( ) ) : NEW_LINE INDENT S [ i ] = chr ( ord ( S [ i ] ) - 32 ) NEW_LINE moves += 1 NEW_LINE upper += 1 NEW_LINE lower -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT print ( moves ) NEW_LINE print ( " " . join ( S ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " AbcdEf " NEW_LINE N = len ( S ) NEW_LINE minimumTimeToConvertString ( S , N ) NEW_LINE DEDENT |
Program to print a string in vertical zigzag manner | Function to print any string in zigzag fashion ; Store the gap between the major columns ; Traverse through rows ; Store the step value for each row ; Iterate in the range [ 1 , N - 1 ] ; Print the character ; Print the spaces before character s [ j + step ] ; Print the character ; Print the spaces after character after s [ j + step ] ; Print the spaces for first and last rows ; Driver Code ; Given Input ; Function Call | def zigzag ( s , rows ) : NEW_LINE INDENT interval = 2 * rows - 2 NEW_LINE for i in range ( rows ) : NEW_LINE INDENT step = interval - 2 * i NEW_LINE for j in range ( i , len ( s ) , interval ) : NEW_LINE INDENT print ( s [ j ] , end = " " ) NEW_LINE if ( step > 0 and step < interval and step + j < len ( s ) ) : NEW_LINE INDENT for k in range ( ( interval - rows - i ) ) : NEW_LINE INDENT print ( end = " β " ) NEW_LINE DEDENT print ( s [ j + step ] , end = " " ) NEW_LINE for k in range ( i - 1 ) : NEW_LINE INDENT print ( end = " β " ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT for k in range ( interval - rows ) : NEW_LINE INDENT print ( end = " β " ) NEW_LINE DEDENT DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = "123456789ABCDEFGHIJKL " " MNOPQRSTUVWXYZabcdefghi " rows = 9 NEW_LINE zigzag ( s , rows ) NEW_LINE DEDENT |
Number of substrings with each character occurring even times | Function to count substrings having even frequency of each character ; Stores the count of a character ; Stores bitmask ; Stores the count of substrings with even count of each character ; Traverse the string S ; Flip the ord ( i ) - 97 bits in pre ; Increment the count by hash [ pre ] ; Increment count of pre in hash ; Return the total count obtained ; Driver Code | def subString ( s , n ) : NEW_LINE INDENT hash = { 0 : 1 } NEW_LINE pre = 0 NEW_LINE count = 0 NEW_LINE for i in s : NEW_LINE INDENT pre ^= ( 1 << ord ( i ) - 97 ) NEW_LINE count += hash . get ( pre , 0 ) NEW_LINE hash [ pre ] = hash . get ( pre , 0 ) + 1 NEW_LINE DEDENT return count NEW_LINE DEDENT S = " abbaa " NEW_LINE N = len ( S ) NEW_LINE print ( subString ( S , N ) ) NEW_LINE |
Count number of substrings having at least K distinct characters | Python 3 program for the above approach ; Function to count number of substrings having atleast k distinct characters ; Stores the size of the string ; Initialize a HashMap ; Stores the start and end indices of sliding window ; Stores the required result ; Iterate while the end pointer is less than n ; Include the character at the end of the window ; Increment end pointer by 1 ; Iterate until count of distinct characters becomes less than K ; Remove the character from the beginning of window ; If its frequency is 0 , remove it from the map ; Update the answer ; Print the result ; Driver Code | from collections import defaultdict NEW_LINE def atleastkDistinctChars ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE mp = defaultdict ( int ) NEW_LINE begin = 0 NEW_LINE end = 0 NEW_LINE ans = 0 NEW_LINE while ( end < n ) : NEW_LINE INDENT c = s [ end ] NEW_LINE mp += 1 NEW_LINE end += 1 NEW_LINE while ( len ( mp ) >= k ) : NEW_LINE INDENT pre = s [ begin ] NEW_LINE mp [ pre ] -= 1 NEW_LINE if ( mp [ pre ] == 0 ) : NEW_LINE INDENT del mp [ pre ] NEW_LINE DEDENT ans += len ( s ) - end + 1 NEW_LINE begin += 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " abcca " NEW_LINE K = 3 NEW_LINE atleastkDistinctChars ( S , K ) NEW_LINE DEDENT |
Rearrange characters of a string to make it a concatenation of palindromic substrings | Function to check if a string can be modified such that it can be split into palindromic substrings of length >= 2 ; Stores frequencies of characters ; Traverse the string ; Update frequency of each character ; Traverse the frequency array ; Update values of odd and eve ; Print the result ; Driver Code | def canSplit ( S ) : NEW_LINE INDENT frequency = [ 0 ] * 26 NEW_LINE cnt_singles = 0 NEW_LINE k = 0 NEW_LINE for i in range ( len ( S ) ) : NEW_LINE INDENT frequency [ ord ( S [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT odd = 0 NEW_LINE eve = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( frequency [ i ] ) : NEW_LINE INDENT odd += ( frequency [ i ] & 1 ) NEW_LINE eve += frequency [ i ] // 2 NEW_LINE DEDENT DEDENT if ( eve >= odd ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aaabbbccc " NEW_LINE canSplit ( S ) NEW_LINE DEDENT |
Smallest element in an array that is repeated exactly ' k ' times . | Python program to find smallest number in array that is repeated exactly ' k ' times . ; Computing frequencies of all elements ; Finding the smallest element with frequency as k ; If frequency of any of the number is equal to k starting from 0 then return the number ; Driver code | MAX = 1000 NEW_LINE def findDuplicate ( arr , n , k ) : NEW_LINE INDENT freq = [ 0 for i in range ( MAX ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] < 1 and arr [ i ] > MAX ) : NEW_LINE INDENT print " Out β of β range " NEW_LINE return - 1 NEW_LINE DEDENT freq [ arr [ i ] ] += 1 NEW_LINE DEDENT for i in range ( MAX ) : NEW_LINE INDENT if ( freq [ i ] == k ) : NEW_LINE INDENT return i NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT arr = [ 2 , 2 , 1 , 3 , 1 ] NEW_LINE k = 2 NEW_LINE n = len ( arr ) NEW_LINE print findDuplicate ( arr , n , k ) NEW_LINE |
Maximize count of occurrences of S2 in S1 as a subsequence by concatenating N1 and N2 times respectively | Function to count maximum number of occurrences of s2 as subsequence in s1 by concatenating s1 , n1 times and s2 , n2 times ; Stores number of times s1 is traversed ; Stores number of times s2 is traversed ; Mapping index of s2 to number of times s1 and s2 are traversed ; Stores index of s1 circularly ; Stores index of s2 circularly ; Traverse the string s1 , n1 times ; If current character of both the string are equal ; Update j ; Update i ; If j is length of s2 ; Update j for circular traversal ; Update s2_reps ; If i is length of s1 ; Update i for circular traversal ; Update s1_reps ; If already mapped j to ( s1_reps , s2_reps ) ; Mapping j to ( s1_reps , s2_reps ) ; If s1 already traversed n1 times ; Otherwis , traverse string s1 by multiple of s1_reps and update both s1_reps and s2_reps ; Update s2_reps ; Update s1_reps ; If s1 is traversed less than n1 times ; If current character in both the string are equal ; Update j ; Update i ; If i is length of s1 ; Update i for circular traversal ; Update s1_reps ; If j is length of ss ; Update j for circular traversal ; Update s2_reps ; Function to count maximum number of occurrences of s2 as subsequence in s1 by concatenating s1 , n1 times and s2 , n2 times | def getMaxRepetitions ( s1 , n1 , s2 , n2 ) : NEW_LINE INDENT if any ( c for c in set ( s2 ) if c not in set ( s1 ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT s1_reps = 0 NEW_LINE DEDENT + Y4E4 : Z4C4E4 : W4E4 : Y4E4 : Z4E4 : AA4E4 : Z4E4 : Y4E4 : X4E4 : W4 NEW_LINE INDENT s2_reps = 0 NEW_LINE s2_index_to_reps = { 0 : ( 0 , 0 ) } NEW_LINE i = 0 NEW_LINE j = 0 NEW_LINE while s1_reps < n1 : NEW_LINE INDENT if s1 [ i ] == s2 [ j ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT i += 1 NEW_LINE if j == len ( s2 ) : NEW_LINE INDENT j = 0 NEW_LINE s2_reps += 1 NEW_LINE DEDENT if i == len ( s1 ) : NEW_LINE INDENT i = 0 NEW_LINE s1_reps += 1 NEW_LINE if j in s2_index_to_reps : NEW_LINE INDENT break NEW_LINE DEDENT s2_index_to_reps [ j ] = ( s1_reps , s2_reps ) NEW_LINE DEDENT DEDENT if s1_reps == n1 : NEW_LINE INDENT return s2_reps // n2 NEW_LINE DEDENT initial_s1_reps , initial_s2_reps = s2_index_to_reps [ j ] NEW_LINE loop_s1_reps = s1_reps - initial_s1_reps NEW_LINE loop_s2_reps = s2_reps - initial_s2_reps NEW_LINE loops = ( n1 - initial_s1_reps ) NEW_LINE s2_reps = initial_s2_reps + loops * loop_s2_reps NEW_LINE s1_reps = initial_s1_reps + loops * loop_s1_reps NEW_LINE while s1_reps < n1 : NEW_LINE INDENT if s1 [ i ] == s2 [ j ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT i += 1 NEW_LINE if i == len ( s1 ) : NEW_LINE INDENT i = 0 NEW_LINE s1_reps += 1 NEW_LINE DEDENT if j == len ( s2 ) : NEW_LINE INDENT j = 0 NEW_LINE s2_reps += 1 NEW_LINE DEDENT DEDENT return s2_reps // n2 NEW_LINE DEDENT def getMaxRepetitions ( s1 , n1 , s2 , n2 ) : A4 : AJ4 NEW_LINE INDENT if any ( c for c in set ( s2 ) if c not in set ( s1 ) ) : NEW_LINE INDENT return 0 + E4 : W4 NEW_LINE DEDENT DEDENT |
Minimum removals required such that a string can be rearranged to form a palindrome | Function to find the number of deletions required such that characters of the string can be rearranged to form a palindrome ; Stores frequency of characters ; Store the frequency of each character in frequency array ; Count number of characters with odd frequency ; If count is 1 or 0 , return 0 ; Otherwise , return count - 1 ; Driver Code ; Function call to find minimum number of deletions required | def minDeletions ( str ) : NEW_LINE INDENT fre = [ 0 ] * 26 NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT fre [ ord ( str [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT if ( fre [ i ] % 2 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT if ( count == 0 or count == 1 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_LINE INDENT return count - 1 NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " ababbccca " NEW_LINE print ( minDeletions ( str ) ) NEW_LINE DEDENT |
Program to print an array in Pendulum Arrangement | Prints pendulam arrangement of arr [ ] ; sorting the elements ; Auxiliary array to store output ; calculating the middle index ; storing the minimum element in the middle i is index for output array and j is for input array . ; adjustment for when no . of elements is even ; Printing the pendulum arrangement ; input Array ; calculating the length of array A ; calling pendulum function | def pendulumArrangement ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE op = [ 0 ] * n NEW_LINE mid = int ( ( n - 1 ) / 2 ) NEW_LINE j = 1 NEW_LINE i = 1 NEW_LINE op [ mid ] = arr [ 0 ] NEW_LINE for i in range ( 1 , mid + 1 ) : NEW_LINE INDENT op [ mid + i ] = arr [ j ] NEW_LINE j += 1 NEW_LINE op [ mid - i ] = arr [ j ] NEW_LINE j += 1 NEW_LINE DEDENT if ( int ( n % 2 ) == 0 ) : NEW_LINE INDENT op [ mid + i ] = arr [ j ] NEW_LINE DEDENT print ( " Pendulum β arrangement : " ) NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( op [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT arr = [ 14 , 6 , 19 , 21 , 12 ] NEW_LINE n = len ( arr ) NEW_LINE pendulumArrangement ( arr , n ) NEW_LINE |
Calculate score of parentheses from a given string | Function to calculate the score of the parentheses using stack ; To keep track of the score ; Initially , push 0 to stack ; Traverse the string s ; If ' ( ' is encountered , then push 0 to stack ; Otherwise ; Balance the last ' ( ' , and store the score of inner parentheses ; If tmp is not zero , it means inner parentheses exists ; Otherwise , it means no inner parentheses exists ; Pass the score of this level to parent parentheses ; Print the score ; Driver Code ; Function call | def scoreOfParentheses ( s ) : NEW_LINE INDENT stack = [ ] NEW_LINE stack . append ( 0 ) NEW_LINE for c in s : NEW_LINE INDENT if ( c == ' ( ' ) : NEW_LINE INDENT stack . append ( 0 ) NEW_LINE DEDENT else : NEW_LINE INDENT tmp = stack [ len ( stack ) - 1 ] NEW_LINE stack = stack [ : - 1 ] NEW_LINE val = 0 NEW_LINE if ( tmp > 0 ) : NEW_LINE INDENT val = tmp * 2 NEW_LINE DEDENT else : NEW_LINE INDENT val = 1 NEW_LINE DEDENT stack [ len ( stack ) - 1 ] += val NEW_LINE DEDENT DEDENT print ( stack [ len ( stack ) - 1 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " ( ( ) ( ( ) ) ) " NEW_LINE scoreOfParentheses ( S ) NEW_LINE DEDENT |
Count unique substrings of a string S present in a wraparound string | Function to find the count of non - empty substrings of p present in s ; Stores the required answer ; Stores the length of substring present in p ; Stores the current length of substring that is present in string s starting from each character of p ; Iterate over the characters of the string ; Check if the current character can be added with previous substring to form the required substring ; Increment current length ; To avoid repetition ; Update arr [ cur ] ; Print the answer ; Driver Code ; Function call to find the count of non - empty substrings of p present in s | def findSubstringInWraproundString ( p ) : NEW_LINE INDENT ans = 0 NEW_LINE curLen = 0 NEW_LINE arr = [ 0 ] * 26 NEW_LINE for i in range ( 0 , len ( p ) ) : NEW_LINE INDENT curr = ord ( p [ i ] ) - ord ( ' a ' ) NEW_LINE if ( i > 0 and ( ord ( p [ i - 1 ] ) != ( ( curr + 26 - 1 ) % 26 + ord ( ' a ' ) ) ) ) : NEW_LINE INDENT curLen = 0 NEW_LINE DEDENT curLen += 1 NEW_LINE if ( curLen > arr [ curr ] ) : NEW_LINE INDENT ans += ( curLen - arr [ curr ] ) NEW_LINE arr [ curr ] = curLen NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT p = " zab " NEW_LINE findSubstringInWraproundString ( p ) NEW_LINE |
Minimize sum of given array by removing all occurrences of a single digit | Function to remove each digit from the given integer ; Convert into string ; Stores final string ; Traverse the string ; Append it to the final string ; Return integer value ; Function to find the minimum sum by removing occurences of each digit ; Iterate in range [ 0 , 9 ] ; Traverse the array ; Update the minimum sum ; Print the minimized sum ; Driver code | def remove ( N , digit ) : NEW_LINE INDENT strN = str ( N ) NEW_LINE ans = ' ' NEW_LINE for i in strN : NEW_LINE INDENT if int ( i ) == digit : NEW_LINE INDENT continue NEW_LINE DEDENT ans += i NEW_LINE DEDENT return int ( ans ) NEW_LINE DEDENT def getMin ( arr ) : NEW_LINE INDENT minSum = float ( ' inf ' ) NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT curSum = 0 NEW_LINE for num in arr : NEW_LINE INDENT curSum += remove ( num , i ) NEW_LINE DEDENT minSum = min ( minSum , curSum ) NEW_LINE DEDENT print ( minSum ) NEW_LINE DEDENT arr = [ 34 , 23 , 85 , 93 ] NEW_LINE getMin ( arr ) NEW_LINE |
Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | Python3 program for the above approach ; Function to update frequency of a character in Fenwick tree ; Update frequency of ( idx + ' a ' ) ; Update i ; Function to find the frequency of a character ( idx + ' a ' ) in range [ 1 , i ] ; Stores frequency of character , ( idx + ' a ' ) in range [ 1 , i ] ; Update ans ; Update i ; Function to find difference between maximum and minimum frequency of a character in given range ; BIT [ i ] [ j ] : Stores frequency of ( i + ' a ' ) If j is a power of 2 , then it stores the frequency ( i + ' a ' ) of from [ 1 ] [ j ] ; Stores length of String ; Iterate over the characters of the String ; Update the frequency of s [ i ] in fenwick tree ; Stores count of queries ; Iterate over all the queries ; Stores maximum frequency of a character in range [ l , r ] ; Stores minimum frequency of a character in range [ l , r ] ; Iterate over all possible characters ; Stores frequency of ( j + ' a ' ) in range [ 1 , r ] ; Stores frequency of ( j + ' a ' ) in range [ 1 , l - 1 ] ; Update mx ; If a character ( i + ' a ' ) present in range [ l , r ] ; Update mn ; Print the difference between max and min freq ; Given String ; Given queries ; Function Call | import sys NEW_LINE def update ( BIT , idx , i , val ) : NEW_LINE INDENT while ( i < 10005 ) : NEW_LINE BIT [ idx ] [ i ] += val NEW_LINE i = i + ( i & ( - i ) ) NEW_LINE DEDENT def query ( BIT , idx , i ) : NEW_LINE INDENT ans = 0 NEW_LINE while ( i > 0 ) : NEW_LINE ans += BIT [ idx ] [ i ] NEW_LINE i = i - ( i & ( - i ) ) NEW_LINE return ans NEW_LINE DEDENT def maxDiffFreq ( s , queries ) : NEW_LINE INDENT BIT = [ [ 0 for i in range ( 10005 ) ] for j in range ( 26 ) ] NEW_LINE n = len ( s ) NEW_LINE for i in range ( n ) : NEW_LINE update ( BIT , ord ( s [ i ] ) - ord ( ' a ' ) , i + 1 , 1 ) NEW_LINE Q = len ( queries ) NEW_LINE for i in range ( Q ) : NEW_LINE mx = 0 NEW_LINE mn = sys . maxsize NEW_LINE l = queries [ i ] [ 0 ] NEW_LINE r = queries [ i ] [ 1 ] NEW_LINE for j in range ( 26 ) : NEW_LINE INDENT p = query ( BIT , j , r ) NEW_LINE q = query ( BIT , j , l - 1 ) NEW_LINE mx = max ( mx , p - q ) NEW_LINE if ( p > 0 ) : NEW_LINE mn = min ( mn , p - q ) NEW_LINE DEDENT print ( mx - mn ) NEW_LINE DEDENT S = " abaabac " NEW_LINE queries = [ [ 2 , 6 ] , [ 1 , 7 ] ] NEW_LINE maxDiffFreq ( S , queries ) NEW_LINE |
Make all strings from a given array equal by replacing minimum number of characters | Function to find the minimum count of operations required to make all Strings equal by replacing characters of Strings ; Stores minimum count of operations required to make all Strings equal ; Stores length of the String ; hash [ i ] [ j ] : Stores frequency of character i present at j - th index of all Strings ; Traverse the array arr ; Iterate over characters of current String ; Update frequency of arr [ i ] [ j ] ; Traverse hash array ; Stores sum of i - th column ; Stores the largest element of i - th column ; Iterate over all possible characters ; Update Sum ; Update Max ; Update cntMinOP ; Driver Code ; Function call | def minOperation ( arr , N ) : NEW_LINE INDENT cntMinOP = 0 ; NEW_LINE M = len ( arr [ 0 ] ) ; NEW_LINE hash = [ [ 0 for i in range ( M ) ] for j in range ( 256 ) ] ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT hash [ ord ( arr [ i ] [ j ] ) ] [ j ] += 1 ; NEW_LINE DEDENT DEDENT for i in range ( M ) : NEW_LINE INDENT Sum = 0 ; NEW_LINE Max = 0 ; NEW_LINE for j in range ( 256 ) : NEW_LINE INDENT Sum += hash [ j ] [ i ] ; NEW_LINE Max = max ( Max , hash [ j ] [ i ] ) ; NEW_LINE DEDENT cntMinOP += ( Sum - Max ) ; NEW_LINE DEDENT return cntMinOP ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " abcd " , " bcde " , " cdef " ] ; NEW_LINE N = len ( arr ) ; NEW_LINE print ( minOperation ( arr , N ) ) ; NEW_LINE DEDENT |
Maximize count of distinct strings generated by replacing similar adjacent digits having sum K with K | Function to find the desired number of strings ; Store the count of strings ; Store the length of the string ; Initialize variable to indicate the start of the substring ; ; Traverse the string ; If sum of adjacent characters is K mark the starting index and set flag to 1 ; If sum of adjacent characters is not K and the flag variable is set , end the substring here ; Set flag to 0 denoting the end of substring ; Check if the length of the substring formed is odd ; Update the answer ; If flag is set and end of string is reached , mark the end of substring ; Update the answer ; Print the answer ; Driver Code ; Function Call | def countStrings ( s , k ) : NEW_LINE INDENT ans = 1 NEW_LINE lenn = len ( s ) NEW_LINE flag = 0 NEW_LINE DEDENT / * Store the starting index of NEW_LINE INDENT the substring * / NEW_LINE for i in range ( lenn - 1 ) : NEW_LINE INDENT if ( ord ( s [ i ] ) - ord ( '0' ) + ord ( s [ i + 1 ] ) - ord ( '0' ) == k and flag == 0 ) : NEW_LINE INDENT flag = 1 NEW_LINE start_ind = i NEW_LINE DEDENT if ( flag == 1 and ord ( s [ i ] ) - ord ( '0' ) + ord ( s [ i + 1 ] ) - ord ( '0' ) != k ) : NEW_LINE INDENT flag = 0 NEW_LINE if ( ( i - start_ind + 1 ) % 2 != 0 ) : NEW_LINE INDENT ans *= ( i - start_ind + 1 - 1 ) // 2 + 1 NEW_LINE DEDENT DEDENT DEDENT if ( flag == 1 and ( lenn - start_ind ) % 2 != 0 ) : NEW_LINE INDENT ans *= ( lenn - start_ind ) // 2 + 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT S = "313" NEW_LINE K = 4 NEW_LINE countStrings ( S , K ) NEW_LINE |
Smallest number whose product with N has sum of digits equal to that of N | Function to find the minimum integer having sum of digits of a number multiplied by n equal to sum of digits of n ; Initialize answer ; Convert string to character array ; Find sum of digits of N ; Multiply N with x ; Sum of digits of the new number ; If condition satisfies ; Print answer ; Driver Code ; Function call | def find_num ( n ) : NEW_LINE INDENT ans = 0 NEW_LINE digitsOfN = str ( n ) NEW_LINE sumOfDigitsN = 0 NEW_LINE for c in digitsOfN : NEW_LINE INDENT sumOfDigitsN += int ( c ) NEW_LINE DEDENT for x in range ( 11 , 50 ) : NEW_LINE INDENT newNum = x * int ( n ) NEW_LINE tempSumDigits = 0 NEW_LINE temp = str ( newNum ) NEW_LINE for c in temp : NEW_LINE INDENT tempSumDigits += int ( c ) NEW_LINE DEDENT if ( tempSumDigits == sumOfDigitsN ) : NEW_LINE INDENT ans = x NEW_LINE break NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = "3029" NEW_LINE find_num ( N ) NEW_LINE DEDENT |
Print all distinct strings from a given array | Function to find the distinct strings from the given array ; Stores distinct strings from the given array ; Traverse the array ; If current string not present into the set ; Insert current string into the set ; Traverse the set DistString ; Print distinct string ; Driver Code ; Stores length of the array | def findDisStr ( arr , N ) : NEW_LINE INDENT DistString = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] not in DistString ) : NEW_LINE INDENT DistString . add ( arr [ i ] ) NEW_LINE DEDENT DEDENT for string in DistString : NEW_LINE INDENT print ( string , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ " Geeks " , " For " , " Geeks " , " Code " , " Coder " ] NEW_LINE N = len ( arr ) NEW_LINE findDisStr ( arr , N ) NEW_LINE DEDENT |
Reverse substrings of given string according to specified array indices | Function to perform the reversal operation on the given string ; Size of string ; Stores the count of indices ; Count the positions where reversals will begin ; Store the count of reversals beginning at position i ; Check if the count [ i ] is odd the swap the character ; Return the updated string ; Driver Code ; Given str ; Given array of reversing index ; Function Call | def modifyString ( A , str , K ) : NEW_LINE INDENT N = len ( str ) NEW_LINE count = [ 0 ] * ( N + 1 ) NEW_LINE for i in range ( K ) : NEW_LINE INDENT count [ A [ i ] ] += 1 NEW_LINE DEDENT for i in range ( 1 , N // 2 + 1 ) : NEW_LINE INDENT count [ i ] = count [ i ] + count [ i - 1 ] NEW_LINE if ( count [ i ] & 1 ) : NEW_LINE INDENT str [ i - 1 ] , str [ N - i ] = str [ N - i ] , str [ i - 1 ] NEW_LINE DEDENT DEDENT return " " . join ( str ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " abcdef " NEW_LINE str = [ i for i in str1 ] NEW_LINE arr = [ 1 , 2 , 3 ] NEW_LINE K = len ( arr ) NEW_LINE print ( modifyString ( arr , str , K ) ) NEW_LINE DEDENT |
Convert given Float value to equivalent Fraction | Python3 program for the above approach ; Function to convert the floating values into fraction ; Initialize variables ; Traverse the floating string ; Check if decimal part exist ; Check if recurrence sequence exist ; Retrieve decimal part and recurrence resquence ; Traverse the string ; Convert to integer ; If no recurrence sequence exist ; Initialize numerator & denominator ; No reccuring term ; Print the result ; If reccuring term exist ; Convert reccuring term to integer ; reccu . size ( ) is num of digit in reccur term ; eq 2 - eq 1 ; Print the result ; Driver Code ; Given str ; Function Call | from math import gcd NEW_LINE def findFraction ( s ) : NEW_LINE INDENT be_deci = " " NEW_LINE af_deci = " " NEW_LINE reccu = " " NEW_LINE x = True NEW_LINE y = False NEW_LINE z = False NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( s [ i ] == ' . ' ) : NEW_LINE INDENT x = False NEW_LINE y = True NEW_LINE continue NEW_LINE DEDENT if ( s [ i ] == ' ( ' ) : NEW_LINE INDENT z = True NEW_LINE y = False NEW_LINE continue NEW_LINE DEDENT if ( x ) : NEW_LINE INDENT be_deci += s [ i ] NEW_LINE DEDENT if ( y ) : NEW_LINE INDENT af_deci += s [ i ] NEW_LINE DEDENT if ( z ) : NEW_LINE INDENT while i < len ( s ) and s [ i ] != ' ) ' : NEW_LINE INDENT reccu += s [ i ] NEW_LINE i += 1 NEW_LINE DEDENT break NEW_LINE DEDENT DEDENT num_be_deci = int ( be_deci ) NEW_LINE num_af_deci = 0 NEW_LINE if len ( af_deci ) != 0 : NEW_LINE INDENT num_af_deci = int ( af_deci ) NEW_LINE DEDENT numr = ( num_be_deci * pow ( 10 , len ( af_deci ) ) + num_af_deci ) NEW_LINE deno = pow ( 10 , len ( af_deci ) ) NEW_LINE if len ( reccu ) == 0 : NEW_LINE INDENT gd = gcd ( numr , deno ) NEW_LINE print ( numr // gd , " / " , deno // gd ) NEW_LINE DEDENT else : NEW_LINE INDENT reccu_num = int ( reccu ) NEW_LINE numr1 = ( numr * pow ( 10 , len ( reccu ) ) + reccu_num ) NEW_LINE deno1 = deno * pow ( 10 , len ( reccu ) ) NEW_LINE res_numr = numr1 - numr NEW_LINE res_deno = deno1 - deno NEW_LINE gd = gcd ( res_numr , res_deno ) NEW_LINE print ( res_numr // gd , " β / β " , res_deno // gd ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "23.98(231 ) " NEW_LINE findFraction ( str ) NEW_LINE DEDENT |
Lexicographically largest string possible for a given cost of appending characters | Function to find the lexicographically largest string possible ; If sum is less than 0 ; If sum is equal to 0 ; If sum is less than 0 ; Add current character ; Check if selecting current character generates lexicographically largest string ; Backtrack if solution not found ; Find the lexicographically largest string excluding the current character ; Function to print the lexicographically largest string generated ; Function call ; Stores the string ; Print the lexicographically largest string formed ; Driver code ; Cost of adding each alphabet ; Cost of generating the string | def lexi_largest_string ( a , i , sum , v ) : NEW_LINE INDENT if ( sum < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( sum == 0 ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( i < 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT v . append ( i ) NEW_LINE if ( lexi_largest_string ( a , i , sum - a [ i ] , v ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT v . pop ( - 1 ) NEW_LINE return lexi_largest_string ( a , i - 1 , sum , v ) NEW_LINE DEDENT def generateString ( a , sum ) : NEW_LINE INDENT v = [ ] NEW_LINE lexi_largest_string ( a , 25 , sum , v ) NEW_LINE s = " " NEW_LINE for j in range ( len ( v ) ) : NEW_LINE INDENT s += chr ( v [ j ] + ord ( ' a ' ) ) NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = [ 1 , 1 , 2 , 33 , 4 , 6 , 9 , 7 , 36 , 32 , 58 , 32 , 28 , 904 , 22 , 255 , 47 , 69 , 558 , 544 , 21 , 36 , 48 , 85 , 48 , 58 ] NEW_LINE sum = 236 NEW_LINE generateString ( a , sum ) NEW_LINE DEDENT |
Count of distinct permutations of every possible length of given string | Function to find the factorial of a number ; Loop to find the factorial of the given number ; Function to find the number of permutations possible for a given string ; Function to find the total number of combinations possible ; Driver Code | def fact ( a ) : NEW_LINE INDENT f = 1 NEW_LINE for i in range ( 2 , a + 1 ) : NEW_LINE INDENT f = f * i NEW_LINE DEDENT return f NEW_LINE DEDENT def permute ( n , r ) : NEW_LINE INDENT ans = 0 NEW_LINE ans = fact ( n ) // fact ( n - r ) NEW_LINE return ans NEW_LINE DEDENT def findPermutations ( n ) : NEW_LINE INDENT sum = 0 NEW_LINE for r in range ( 1 , n + 1 ) : NEW_LINE INDENT P = permute ( n , r ) NEW_LINE sum = sum + P NEW_LINE DEDENT return sum NEW_LINE DEDENT str = " xz " NEW_LINE n = len ( str ) NEW_LINE print ( findPermutations ( n ) ) NEW_LINE |
Cycles of length n in an undirected and connected graph | Number of vertices ; mark the vertex vert as visited ; if the path of length ( n - 1 ) is found ; mark vert as un - visited to make it usable again . ; Check if vertex vert can end with vertex start ; For searching every possible path of length ( n - 1 ) ; DFS for searching path by decreasing length by 1 ; marking vert as unvisited to make it usable again . ; Counts cycles of length N in an undirected and connected graph . ; all vertex are marked un - visited initially . ; Searching for cycle by using v - n + 1 vertices ; ith vertex is marked as visited and will not be visited again . ; main : | V = 5 NEW_LINE def DFS ( graph , marked , n , vert , start , count ) : NEW_LINE INDENT marked [ vert ] = True NEW_LINE if n == 0 : NEW_LINE INDENT marked [ vert ] = False NEW_LINE if graph [ vert ] [ start ] == 1 : NEW_LINE INDENT count = count + 1 NEW_LINE return count NEW_LINE DEDENT else : NEW_LINE INDENT return count NEW_LINE DEDENT DEDENT for i in range ( V ) : NEW_LINE INDENT if marked [ i ] == False and graph [ vert ] [ i ] == 1 : NEW_LINE INDENT count = DFS ( graph , marked , n - 1 , i , start , count ) NEW_LINE DEDENT DEDENT marked [ vert ] = False NEW_LINE return count NEW_LINE DEDENT def countCycles ( graph , n ) : NEW_LINE INDENT marked = [ False ] * V NEW_LINE count = 0 NEW_LINE for i in range ( V - ( n - 1 ) ) : NEW_LINE INDENT count = DFS ( graph , marked , n - 1 , i , i , count ) NEW_LINE marked [ i ] = True NEW_LINE DEDENT return int ( count / 2 ) NEW_LINE DEDENT graph = [ [ 0 , 1 , 0 , 1 , 0 ] , [ 1 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 1 , 0 ] , [ 1 , 0 , 1 , 0 , 1 ] , [ 0 , 1 , 0 , 1 , 0 ] ] NEW_LINE n = 4 NEW_LINE print ( " Total β cycles β of β length β " , n , " β are β " , countCycles ( graph , n ) ) NEW_LINE |
String hashing using Polynomial rolling hash function | Function to calculate the hash of a string ; P and M ; Loop to calculate the hash value by iterating over the elements of string ; Driver Code ; Given string | def polynomialRollingHash ( str ) : NEW_LINE INDENT p = 31 NEW_LINE m = 1e9 + 9 NEW_LINE power_of_p = 1 NEW_LINE hash_val = 0 NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT hash_val = ( ( hash_val + ( ord ( str [ i ] ) - ord ( ' a ' ) + 1 ) * power_of_p ) % m ) NEW_LINE power_of_p = ( power_of_p * p ) % m NEW_LINE DEDENT return int ( hash_val ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str1 = " geeksforgeeks " NEW_LINE print ( " Hash β of β ' { } ' β = β { } " . format ( str1 , polynomialRollingHash ( str1 ) ) ) NEW_LINE DEDENT |
Find first non | Python3 implementation to find the first non - repeating element of the string using Linked List ; Function to find the first non - repeating element of the given string using Linked List ; Driver Code ; Function Call | import collections NEW_LINE def firstNonRepElement ( str ) : NEW_LINE INDENT list . append ( str [ 0 ] ) NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT if str [ i ] in list : NEW_LINE INDENT list . remove ( str [ i ] ) NEW_LINE DEDENT else : NEW_LINE INDENT list . append ( str [ i ] ) NEW_LINE DEDENT DEDENT print ( list [ 0 ] ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " geeksforgeeks " ; NEW_LINE firstNonRepElement ( str ) ; NEW_LINE DEDENT |
DFA that begins with ' a ' but does not contain substring ' aab ' | Function for state A transition ; If at index 0 ' a ' if found then call stateB function with passing n [ 1 : ] to it ; If at index 0 ' b ' if found then call stateQ function with passing n to it ; Function for state B transition ; Length of string become 0 then print Accepted ; If at index 0 ' a ' if found then call stateC function with passing n [ 1 : ] to it ; If at index 0 ' b ' if found then call stateD function with passing n [ 1 : ] to it ; Function for state C transition ; Length of string become 0 then print Accepted ; If at index 0 ' a ' if found then call stateC function with passing n [ 1 : ] to it ; If at index 0 ' b ' if found then call stateQ function with passing n to it ; Function for state D transition ; Length of string become 0 then print Accepted ; If at index 0 ' a ' if found then call stateB function with passing n [ 1 : ] to it ; If at index 0 ' b ' if found then call stateD function with passing n [ 1 : ] to it ; Function for state Q transition ; In dead state it shows string not accepted ; Take string input ; Call stateA to check the input | def stateA ( n ) : NEW_LINE INDENT if ( n [ 0 ] == ' a ' ) : NEW_LINE INDENT stateB ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateQ ( n ) NEW_LINE DEDENT DEDENT def stateB ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " Accepted " ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n [ 0 ] == ' a ' ) : NEW_LINE INDENT stateC ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateD ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT DEDENT def stateC ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " Accepted " ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n [ 0 ] == ' a ' ) : NEW_LINE INDENT stateC ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateQ ( n ) NEW_LINE DEDENT DEDENT DEDENT def stateD ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " Accepted " ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n [ 0 ] == ' a ' ) : NEW_LINE INDENT stateB ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateD ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT DEDENT def stateQ ( n ) : NEW_LINE INDENT print ( " Not β Accepted " ) NEW_LINE DEDENT n = " aaaba " NEW_LINE stateA ( n ) NEW_LINE |
Count of substrings of length K with exactly K distinct characters | Function to return the required count of substrings ; Store the count ; Store the count of distinct characters in every window ; Store the frequency of the first K length substring ; Increase frequency of i - th character ; If K distinct characters exist ; Traverse the rest of the substring ; Increase the frequency of the last character of the current substring ; Decrease the frequency of the first character of the previous substring ; If the character is not present in the current substring ; If the count of distinct characters is 0 ; Return the count ; Driver code ; string str ; Integer K ; Print the count of K length substrings with k distinct characters | def countSubstrings ( str , K ) : NEW_LINE INDENT N = len ( str ) NEW_LINE answer = 0 NEW_LINE map = { } NEW_LINE for i in range ( K ) : NEW_LINE INDENT map [ str [ i ] ] = map . get ( str [ i ] , 0 ) + 1 NEW_LINE DEDENT if ( len ( map ) == K ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT for i in range ( K , N ) : NEW_LINE INDENT map [ str [ i ] ] = map . get ( str [ i ] , 0 ) + 1 NEW_LINE map [ str [ i - K ] ] -= 1 NEW_LINE if ( map [ str [ i - K ] ] == 0 ) : NEW_LINE INDENT del map [ str [ i - K ] ] NEW_LINE DEDENT if ( len ( map ) == K ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " aabcdabbcdc " NEW_LINE K = 3 NEW_LINE print ( countSubstrings ( str , K ) ) NEW_LINE DEDENT |
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | Function to find the minimum number of operations to make all the elements of the array equal ; Store the sum of the array arr [ ] ; Traverse through the array ; If it is not possible to make all array element equal ; Store the minimum number of operations needed ; Traverse through the array ; Finally , print the minimum number operation to make array elements equal ; Driver Code ; Given Input ; Function Call | def miniOperToMakeAllEleEqual ( arr , n , k ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % n ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT valueAfterDivision = sum // n NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( abs ( valueAfterDivision - arr [ i ] ) % k != 0 ) : NEW_LINE INDENT print ( - 1 ) NEW_LINE return NEW_LINE DEDENT count += abs ( valueAfterDivision - arr [ i ] ) // k NEW_LINE DEDENT print ( count // 2 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE k = 3 NEW_LINE arr = [ 5 , 8 , 11 ] NEW_LINE miniOperToMakeAllEleEqual ( arr , n , k ) NEW_LINE DEDENT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.