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 ;... | 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 INDE... |
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 <... |
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 ... |
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 fo... | 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... |
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 ... |
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 ... | 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 DED... |
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 sub... | 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... |
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... |
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 fir... | ' 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_... |
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 gettin... | 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 pr... |
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 re... | 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 ) : N... |
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 . ;... | 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 -... |
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 ) ) ;... | 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 ]... |
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 ... | 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 ... |
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 v... | 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 , -... |
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 DEDE... |
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 , th... | 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 ... |
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 c... | 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... |
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... | 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 ... |
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 le... | 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 ) : N... |
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 ... | 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 ] [ ... |
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 c... | 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 ] == ' * '... |
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 an... | 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 ... |
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... | 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 mi... |
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 rai... | 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 DE... |
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 fir... | 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 ... |
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 remaini... | 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 NE... |
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 ... |
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... |
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 ] + cou... |
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 ( ... |
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 . ; Cre... | / * 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 ) ... |
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... | 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 en... | 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 INDEN... |
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 =... |
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 [ ... | 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_LI... |
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 ... |
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 (... |
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 ... | 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 )... |
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 ] ==... | 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 DE... |
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 ... | 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 eggFlo... |
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 ) , kna... |
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 ,... |
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... | 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 + ... |
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 * ... | 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... |
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 ,... |
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... | 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 ( oddLengthP... |
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 ... | 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 ' ) ) *... |
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... | 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 + ... |
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... | 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... |
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 char... | 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 ... |
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 INDEN... |
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... | 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_LI... |
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 co... | 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... |
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 consecut... | 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 st... |
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 ' ta... | 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 ... |
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 ; chec... | 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 ... |
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. . . ; ... | 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 = f... |
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 pri... |
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 ; C... | 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_L... |
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 ; Sep... | 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 ... |
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 ... | 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 ] =... |
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 th... | 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... |
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 t... | 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 ) ==... |
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... | 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 [... |
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 initializ... | 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... |
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 coun... | 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 ... |
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 m... | 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... |
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... | 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... |
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 c... | 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 = ... |
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... | 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_LI... |
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 ; Incre... | 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_L... |
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 resul... | 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 ... |
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 frequenc... | 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 ] ) ... |
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 r... | 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 fo... |
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 ; Mappi... | 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 ... |
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 ... | 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... |
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 ... | 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 ] = a... |
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 pare... | 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 (... |
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 ... | 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 I... |
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 digi... | 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 fo... |
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 characte... | 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 & ( - ... |
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 ] ... | 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 DEDE... |
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 ... | 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 =... |
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 n... | 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_... |
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 ... | 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... |
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 od... | 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 ) : N... |
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 ; Tr... | 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 ... |
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 st... | 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 ]... |
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 s... |
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 f... | 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 cou... |
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 NE... |
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 ... |
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 bec... | 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... |
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 ex... | 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 ) : NE... |
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 e... | 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_LIN... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.