text stringlengths 17 3.65k | code stringlengths 70 5.84k |
|---|---|
Count all increasing subsequences | Function To Count all the sub - sequences possible in which digit is greater than all previous digits arr [ ] is array of n digits ; count [ ] array is used to store all sub - sequences possible using that digit count [ ] array covers all the digit from 0 to 9 ; scan each digit in ar... | def countSub ( arr , n ) : NEW_LINE INDENT count = [ 0 for i in range ( 10 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( arr [ i ] - 1 , - 1 , - 1 ) : NEW_LINE INDENT count [ arr [ i ] ] += count [ j ] NEW_LINE DEDENT count [ arr [ i ] ] += 1 NEW_LINE DEDENT result = 0 NEW_LINE for i in range ( 1... |
Find minimum sum such that one of every three consecutive elements is taken | A utility function to find minimum of 3 elements ; Returns minimum possible sum of elements such that an element out of every three consecutive elements is picked . ; Create a DP table to store results of subproblems . sum [ i ] is going to s... | def minimum ( a , b , c ) : NEW_LINE INDENT return min ( min ( a , b ) , c ) ; NEW_LINE DEDENT def findMinSum ( arr , n ) : NEW_LINE INDENT sum = [ ] NEW_LINE sum . append ( arr [ 0 ] ) NEW_LINE sum . append ( arr [ 1 ] ) NEW_LINE sum . append ( arr [ 2 ] ) NEW_LINE for i in range ( 3 , n ) : NEW_LINE INDENT sum . appe... |
Count Distinct Subsequences | Python3 program to print distinct subsequences of a given string ; Create an empty set to store the subsequences ; Function for generating the subsequences ; Base Case ; Insert each generated subsequence into the set ; Recursive Case ; When a particular character is taken ; When a particul... | import math NEW_LINE sn = [ ] NEW_LINE global m NEW_LINE m = 0 NEW_LINE def subsequences ( s , op , i , j ) : NEW_LINE INDENT if ( i == m ) : NEW_LINE INDENT op [ j ] = None NEW_LINE temp = " " . join ( [ i for i in op if i ] ) NEW_LINE sn . append ( temp ) NEW_LINE return NEW_LINE DEDENT else : NEW_LINE INDENT op [ j ... |
Count Distinct Subsequences | Returns count of distinct subsequences of str . ; Iterate from 0 to length of s ; Iterate from 0 to length of s ; Check if i equal to 0 ; Replace levelCount withe allCount + 1 ; If map is less than 0 ; Return answer ; Driver Code | def countSub ( s ) : NEW_LINE INDENT Map = { } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT Map [ s [ i ] ] = - 1 NEW_LINE DEDENT allCount = 0 NEW_LINE levelCount = 0 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT c = s [ i ] NEW_LINE if ( i == 0 ) : NEW_LINE INDENT allCount = 1 NEW_LINE Map = 1 NEW... |
Minimum cost to fill given weight in a bag | Python program to find minimum cost to get exactly W Kg with given packets ; cost [ ] initial cost array including unavailable packet W capacity of bag ; val [ ] and wt [ ] arrays val [ ] array to store cost of ' i ' kg packet of orange wt [ ] array weight of packet of orang... | INF = 1000000 NEW_LINE def MinimumCost ( cost , n , W ) : NEW_LINE INDENT val = list ( ) NEW_LINE wt = list ( ) NEW_LINE size = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( cost [ i ] != - 1 ) : NEW_LINE INDENT val . append ( cost [ i ] ) NEW_LINE wt . append ( i + 1 ) NEW_LINE size += 1 NEW_LINE DEDENT DEDEN... |
Find number of times a string occurs as a subsequence in given string | Recursive function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; If both first and second string is empty , or if second string is empty , return 1 ; If only first string is empty a... | def count ( a , b , m , n ) : NEW_LINE INDENT if ( ( m == 0 and n == 0 ) or n == 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( m == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( a [ m - 1 ] == b [ n - 1 ] ) : NEW_LINE INDENT return ( count ( a , b , m - 1 , n - 1 ) + count ( a , b , m - 1 , n ) ) NEW_LINE D... |
Minimum Cost To Make Two Strings Identical | 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 [ 0. . n - ... | def lcs ( X , Y , m , n ) : NEW_LINE INDENT L = [ [ 0 for i in range ( n + 1 ) ] for i in range ( m + 1 ) ] NEW_LINE for i in range ( m + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT if i == 0 or j == 0 : NEW_LINE INDENT L [ i ] [ j ] = 0 NEW_LINE DEDENT elif X [ i - 1 ] == Y [ j - 1 ] : NEW_LINE IN... |
Printing Longest Common Subsequence | Set 2 ( Printing All ) | Maximum string length ; Returns set containing all LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; construct a set to store possible LCS ; If we reaches end of either string , return a empty set ; If the last characters of X and Y are same ; recurse for X [ 0... | N = 100 NEW_LINE L = [ [ 0 for i in range ( N ) ] for j in range ( N ) ] NEW_LINE def findLCS ( x , y , m , n ) : NEW_LINE INDENT s = set ( ) NEW_LINE if m == 0 or n == 0 : NEW_LINE INDENT s . add ( " " ) NEW_LINE return s NEW_LINE DEDENT if x [ m - 1 ] == y [ n - 1 ] : NEW_LINE INDENT tmp = findLCS ( x , y , m - 1 , n... |
Number of non | Returns count of solutions of a + b + c = n ; Initialize result ; Consider all triplets and increment result whenever sum of a triplet is n . ; Driver code | def countIntegralSolutions ( n ) : NEW_LINE INDENT result = 0 NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT for j in range ( n + 1 ) : NEW_LINE INDENT for k in range ( n + 1 ) : NEW_LINE INDENT if i + j + k == n : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT DEDENT DEDENT return result NEW_LINE DEDENT n = 3... |
Number of non | Returns count of solutions of a + b + c = n ; Driver code | def countIntegralSolutions ( n ) : NEW_LINE INDENT return int ( ( ( n + 1 ) * ( n + 2 ) ) / 2 ) NEW_LINE DEDENT n = 3 NEW_LINE print ( countIntegralSolutions ( n ) ) NEW_LINE |
Maximum absolute difference between sum of two contiguous sub | Find maximum subarray sum for subarray [ 0. . i ] using standard Kadane ' s β algorithm . β This β version β β of β Kadane ' s Algorithm will work if all numbers are negative . ; Find maximum subarray sum for subarray [ i . . n ] using Kadane ' s β algorit... | def maxLeftSubArraySum ( a , size , sum ) : NEW_LINE INDENT max_so_far = a [ 0 ] NEW_LINE curr_max = a [ 0 ] NEW_LINE sum [ 0 ] = max_so_far NEW_LINE for i in range ( 1 , size ) : NEW_LINE INDENT curr_max = max ( a [ i ] , curr_max + a [ i ] ) NEW_LINE max_so_far = max ( max_so_far , curr_max ) NEW_LINE sum [ i ] = max... |
Ways to arrange Balls such that adjacent balls are of different types | Returns count of arrangements where last placed ball is ' last ' . ' last ' is 0 for ' p ' , 1 for ' q ' and 2 for 'r ; if number of balls of any color becomes less than 0 the number of ways arrangements is 0. ; If last ball required is of type P a... | ' NEW_LINE def countWays ( p , q , r , last ) : NEW_LINE INDENT if ( p < 0 or q < 0 or r < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( p == 1 and q == 0 and r == 0 and last == 0 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( p == 0 and q == 1 and r == 0 and last == 1 ) : NEW_LINE... |
Partition a set into two subsets such that the difference of subset sums is minimum | Function to find the minimum sum ; If we have reached last element . Sum of one subset is sumCalculated , sum of other subset is sumTotal - sumCalculated . Return absolute difference of two sums . ; For every item arr [ i ] , we have ... | def findMinRec ( arr , i , sumCalculated , sumTotal ) : NEW_LINE INDENT if ( i == 0 ) : NEW_LINE INDENT return abs ( ( sumTotal - sumCalculated ) - sumCalculated ) NEW_LINE DEDENT return min ( findMinRec ( arr , i - 1 , sumCalculated + arr [ i - 1 ] , sumTotal ) , findMinRec ( arr , i - 1 , sumCalculated , sumTotal ) )... |
Count number of ways to partition a set into k subsets | Returns count of different partitions of n elements in k subsets ; Base cases ; S ( n + 1 , k ) = k * S ( n , k ) + S ( n , k - 1 ) ; Driver Code | def countP ( n , k ) : NEW_LINE INDENT if ( n == 0 or k == 0 or k > n ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( k == 1 or k == n ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( k * countP ( n - 1 , k ) + countP ( n - 1 , k - 1 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( c... |
Count number of ways to partition a set into k subsets | Returns count of different partitions of n elements in k subsets ; Table to store results of subproblems ; Base cases ; Fill rest of the entries in dp [ ] [ ] in bottom up manner ; Driver Code | def countP ( n , k ) : NEW_LINE INDENT dp = [ [ 0 for i in range ( k + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( n + 1 ) : NEW_LINE INDENT dp [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( k + 1 ) : NEW_LINE INDENT dp [ 0 ] [ k ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for ... |
Count number of ways to cover a distance | Returns count of ways to cover 'dist ; Base cases ; Recur for all previous 3 and add the results ; Driver code | ' NEW_LINE def printCountRec ( dist ) : NEW_LINE INDENT if dist < 0 : NEW_LINE INDENT return 0 NEW_LINE DEDENT if dist == 0 : NEW_LINE INDENT return 1 NEW_LINE DEDENT return ( printCountRec ( dist - 1 ) + printCountRec ( dist - 2 ) + printCountRec ( dist - 3 ) ) NEW_LINE DEDENT dist = 4 NEW_LINE print ( printCountRec (... |
Count number of ways to cover a distance | A Dynamic Programming based C ++ program to count number of ways ; Create the array of size 3. ; Initialize the bases cases ; Run a loop from 3 to n Bottom up approach to fill the array ; driver program | def prCountDP ( dist ) : NEW_LINE INDENT ways = [ 0 ] * 3 NEW_LINE n = dist NEW_LINE ways [ 0 ] = 1 NEW_LINE ways [ 1 ] = 1 NEW_LINE ways [ 2 ] = 2 NEW_LINE for i in range ( 3 , n + 1 ) : NEW_LINE INDENT ways [ i % 3 ] = ways [ ( i - 1 ) % 3 ] + ways [ ( i - 2 ) % 3 ] + ways [ ( i - 3 ) % 3 ] NEW_LINE DEDENT return way... |
Count numbers from 1 to n that have 4 as a digit | Returns sum of all digits in numbers from 1 to n ; One by one compute sum of digits in every number from 1 to n ; A utility function to compute sum of digits in a given number x ; Driver Program | def countNumbersWith4 ( n ) : NEW_LINE INDENT for x in range ( 1 , n + 1 ) : NEW_LINE INDENT if ( has4 ( x ) == True ) : NEW_LINE INDENT result = result + 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def has4 ( x ) : NEW_LINE INDENT while ( x != 0 ) : NEW_LINE INDENT if ( x % 10 == 4 ) : NEW_LINE INDENT retur... |
Count numbers from 1 to n that have 4 as a digit | Python3 program to count numbers having 4 as a digit ; Function to count numbers from 1 to n that have 4 as a digit ; Base case ; d = number of digits minus one in n . For 328 , d is 2 ; computing count of numbers from 1 to 10 ^ d - 1 , d = 0 a [ 0 ] = 0 d = 1 a [ 1 ] ... | import math as mt NEW_LINE def countNumbersWith4 ( n ) : NEW_LINE INDENT if ( n < 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT d = int ( mt . log10 ( n ) ) NEW_LINE a = [ 1 for i in range ( d + 1 ) ] NEW_LINE a [ 0 ] = 0 NEW_LINE if len ( a ) > 1 : NEW_LINE INDENT a [ 1 ] = 1 NEW_LINE DEDENT for i in range ( 2 , d + ... |
Remove minimum elements from either side such that 2 * min becomes more than max | A O ( n * n ) solution to find the minimum of elements to be removed ; Returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; Initialize starting and ending indexes of the m... | import sys ; NEW_LINE def minRemovalsDP ( arr , n ) : NEW_LINE INDENT longest_start = - 1 ; NEW_LINE longest_end = 0 ; NEW_LINE for start in range ( n ) : NEW_LINE INDENT min = sys . maxsize ; NEW_LINE max = - sys . maxsize ; NEW_LINE for end in range ( start , n ) : NEW_LINE INDENT val = arr [ end ] ; NEW_LINE if ( va... |
Longest Arithmetic Progression | DP | The function returns true if there exist three elements in AP Assumption : set [ 0. . n - 1 ] is sorted . The code strictly implements the algorithm provided in the reference . ; One by fix every element as middle element ; Initialize i and k for the current j ; Find if there exist... | def arithematicThree ( set_ , n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT i , k = j - 1 , j + 1 NEW_LINE while i > - 1 and k < n : NEW_LINE INDENT if set_ [ i ] + set_ [ k ] == 2 * set_ [ j ] : NEW_LINE INDENT return True NEW_LINE DEDENT elif set_ [ i ] + set_ [ k ] < 2 * set_ [ j ] : NEW_LINE INDENT i... |
Optimal Strategy for a Game | DP | Returns optimal value possible that a player can collect from an array of coins of size n . Note than n must be even ; 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 : go... | def optimalStrategyOfGame ( arr , n ) : NEW_LINE INDENT table = [ [ 0 for i in range ( n ) ] for i in range ( n ) ] NEW_LINE for gap in range ( n ) : NEW_LINE INDENT for j in range ( gap , n ) : NEW_LINE INDENT i = j - gap NEW_LINE x = 0 NEW_LINE if ( ( i + 2 ) <= j ) : NEW_LINE INDENT x = table [ i + 2 ] [ j ] NEW_LIN... |
Maximum Sum Increasing Subsequence | DP | maxSumIS ( ) returns the maximum sum of increasing subsequence in arr [ ] of size n ; Initialize msis values for all indexes ; Compute maximum sum values in bottom up manner ; Pick maximum of all msis values ; Driver Code | def maxSumIS ( arr , n ) : NEW_LINE INDENT max = 0 NEW_LINE msis = [ 0 for x in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT msis [ i ] = arr [ i ] NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT if ( arr [ i ] > arr [ j ] and msis [ i ] < msis [ j ] + ... |
Overlapping Subproblems Property in Dynamic Programming | DP | a simple recursive program for Fibonacci numbers | def fib ( n ) : NEW_LINE INDENT if n <= 1 : NEW_LINE INDENT return n NEW_LINE DEDENT return fib ( n - 1 ) + fib ( n - 2 ) NEW_LINE DEDENT |
Find position i to split Array such that prefix sum till i | Function to check if there is an element forming G . P . series having common ratio k ; If size of array is less than three then return - 1 ; Initialize the variables ; Calculate total sum of array ; Calculate Middle element of G . P . series ; Iterate over t... | def checkArray ( arr , N , k ) : NEW_LINE INDENT if ( N < 3 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT Sum = 0 NEW_LINE temp = 0 NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT Sum += arr [ i ] NEW_LINE DEDENT R = ( k * k + k + 1 ) NEW_LINE if ( Sum % R != 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT Mid = k ... |
Repeat last occurrence of each alphanumeric character to their position in character family times | Function to encode the given string ; Variable string to store the result ; Arrays to store the last occuring index of every character in the string ; Length of the string ; Iterate over the range ; If str [ i ] is betwe... | def encodeString ( str ) : NEW_LINE INDENT res = " " NEW_LINE small = [ 0 for i in range ( 26 ) ] NEW_LINE capital = [ 0 for i in range ( 26 ) ] NEW_LINE num = [ 0 for i in range ( 10 ) ] NEW_LINE n = len ( str ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( str [ i ] >= '0' and str [ i ] <= '9' ) : NEW_LINE IND... |
Make Array elements equal by replacing adjacent elements with their XOR | Function to check if it is possible to make all the array elements equal using the given operation ; Stores the prefix XOR array ; Calculate prefix [ i ] ; Case 1 , check if the XOR of the input array is 0 ; Case 2 Iterate over all the ways to di... | def possibleEqualArray ( A , N ) : NEW_LINE INDENT pref = [ 0 for i in range ( N ) ] NEW_LINE pref [ 0 ] = A [ 0 ] NEW_LINE for i in range ( 1 , N , 1 ) : NEW_LINE INDENT pref [ i ] = pref [ i - 1 ] ^ A [ i ] NEW_LINE DEDENT if ( pref [ N - 1 ] == 0 ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return NEW_LINE DEDENT ... |
Construct an array whose Prefix XOR array starting from X is an N | Function to print the required array ; Iteratie from 1 to N ; Print the i - th element ; Update prev_xor to i ; Driver Code ; Given Input ; Function Call | def GenerateArray ( N , X ) : NEW_LINE INDENT prev_xor = X NEW_LINE for i in range ( 1 , N + 1 , 1 ) : NEW_LINE INDENT print ( i ^ prev_xor , end = " " ) NEW_LINE if ( i != N ) : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT prev_xor = i NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE IN... |
Check if elements of a Binary Matrix can be made alternating | Function to create the possible grids ; Function to test if any one of them matches with the given 2 - D array ; Function to print the grid , if possible ; Function to check if the grid can be made alternating or not ; Grids to store the possible grids ; Dr... | def createGrid ( grid , is1 , N , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( is1 ) : NEW_LINE INDENT grid [ i ] [ j ] = '0' NEW_LINE is1 = False NEW_LINE DEDENT else : NEW_LINE INDENT grid [ i ] [ j ] = '1' NEW_LINE is1 = True NEW_LINE DEDENT DEDENT if ( M %... |
Find non | Python 3 program for the above approach . ; Function to find the possible output array ; Base case for the recursion ; If ind becomes half of the size then print the array . ; Exit the function . ; Iterate in the range . ; Put the values in the respective indices . ; Call the function to find values for othe... | N = 200 * 1000 + 13 NEW_LINE n = 0 NEW_LINE arr = [ 0 for i in range ( N ) ] NEW_LINE brr = [ 0 for i in range ( N ) ] NEW_LINE import sys NEW_LINE def brute ( ind , l , r ) : NEW_LINE INDENT if ( ind == n / 2 ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( brr [ i ] , end = " β " ) NEW_LINE DEDENT s... |
Count of minimum numbers having K as the last digit required to obtain sum N | Python3 program for the above approach ; Stores the smallest number that ends with digit i ( 0 , 9 ) ; Stores the minimum number of steps to create a number ending with digit i ; Initialize elements as infinity ; Minimum number ending with d... | import sys NEW_LINE def minCount ( N , K ) : NEW_LINE INDENT SmallestNumber = [ 0 for i in range ( 10 ) ] NEW_LINE MinimumSteps = [ 0 for i in range ( 10 ) ] NEW_LINE for i in range ( 10 ) : NEW_LINE INDENT SmallestNumber [ i ] = sys . maxsize ; NEW_LINE MinimumSteps [ i ] = sys . maxsize NEW_LINE DEDENT for i in range... |
Minimum number of operations required to make an array non | Function to count the minimum number of steps required to make arr non - decreasing ; Stores differences ; Stores the max number ; Traverse the array arr [ ] ; Update mx ; Update val ; Stores the result ; Iterate until 2 ^ res - 1 is less than val ; Return th... | def countMinSteps ( arr , N ) : NEW_LINE INDENT val = 0 NEW_LINE mx = - 10 ** 9 NEW_LINE for i in range ( N ) : NEW_LINE INDENT curr = arr [ i ] NEW_LINE mx = max ( mx , curr ) NEW_LINE val = max ( val , mx - curr ) NEW_LINE DEDENT res = 0 NEW_LINE while ( ( 1 << res ) - 1 < val ) : NEW_LINE INDENT res += 1 NEW_LINE DE... |
Minimum XOR of at most K elements in range [ L , R ] | Function for K = 2 ; Function for K = 2 ; Function for K = 2 ; Function to calculate the minimum XOR of at most K elements in [ L , R ] ; Driver code ; Input ; Function call | def func2 ( L , R , K ) : NEW_LINE INDENT if ( R - L >= 2 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT return min ( L , L ^ R ) NEW_LINE DEDENT def func3 ( L , R , K ) : NEW_LINE INDENT if ( ( R ^ L ) > L and ( R ^ L ) < R ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return func2 ( L , R , K ) NEW_LINE DEDENT def func4... |
Nth term of Ruler Function Series | Function to count the number of set bits in the number N ; Store the number of setbits ; Update the value of n ; Update the count ; Return the total count ; Function to find the Nth term of the Ruler Function Series ; Store the result ; Print the result ; Driver Code | def setBits ( n ) : NEW_LINE INDENT count = 0 NEW_LINE while ( n > 0 ) : NEW_LINE INDENT n = n & ( n - 1 ) NEW_LINE count += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT def findNthTerm ( N ) : NEW_LINE INDENT x = setBits ( N ^ ( N - 1 ) ) NEW_LINE print ( x ) NEW_LINE DEDENT N = 8 NEW_LINE findNthTerm ( N ) NEW_LINE |
Quadratic equation whose roots are reciprocal to the roots of given equation | Function to find the quadratic equation having reciprocal roots ; Print quadratic equation ; Driver Code ; Given coefficients ; Function call to find the quadratic equation having reciprocal roots | def findEquation ( A , B , C ) : NEW_LINE INDENT print ( " ( " + str ( C ) + " ) " + " x ^ 2 β + ( " + str ( B ) + " ) x β + β ( " + str ( A ) + " ) β = β 0" ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = 1 NEW_LINE B = - 5 NEW_LINE C = 6 NEW_LINE findEquation ( A , B , C ) NEW_LINE DEDENT |
Minimize subtraction followed by increments of adjacent elements required to make all array elements equal | Function to find the minimum number of moves required to make all array elements equal ; Store the total sum of the array ; Calculate total sum of the array ; If the sum is not divisible by N , then print " - 1"... | def findMinMoves ( arr , N ) : NEW_LINE INDENT sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT if ( sum % N != 0 ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT avg = sum // N NEW_LINE total = 0 NEW_LINE needCount = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT needCount += (... |
Maximum amount of money that can be collected by a player in a game of coins | Function to calculate the maximum amount collected by A ; Stores the money obtained by A ; Stores mid elements of odd sized rows ; Size of current row ; Increase money collected by A ; Add coins at even indices to the amount collected by A ;... | def find ( N , Arr ) : NEW_LINE INDENT amount = 0 NEW_LINE mid_odd = [ ] NEW_LINE for i in range ( N ) : NEW_LINE INDENT siz = len ( Arr [ i ] ) NEW_LINE for j in range ( 0 , siz // 2 ) : NEW_LINE INDENT amount = amount + Arr [ i ] [ j ] NEW_LINE DEDENT if ( siz % 2 == 1 ) : NEW_LINE INDENT mid_odd . append ( Arr [ i ]... |
Check if an array can be split into K consecutive non | Function to check if array can be split into K consecutive and non - overlapping subarrays of length M consisting of a single distinct element ; Traverse over the range [ 0 , N - M - 1 ] ; Check if arr [ i ] is the same as arr [ i + m ] ; Increment current length ... | def checkPattern ( arr , m , k , n ) : NEW_LINE INDENT count = 1 NEW_LINE t = 0 NEW_LINE for i in range ( n - m ) : NEW_LINE INDENT if ( arr [ i ] == arr [ i + m ] ) : NEW_LINE INDENT t += 1 NEW_LINE if ( t == m ) : NEW_LINE INDENT t = 0 NEW_LINE count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT return " Yes " NE... |
Remove all occurrences of a word from a given string using Z | Function to fill the Z - array for str ; L Stores start index of window which matches with prefix of str ; R Stores end index of window which matches with prefix of str ; Iterate over the characters of str ; If i is greater thn R ; Update L and R ; If subst... | def getZarr ( st , Z ) : NEW_LINE INDENT n = len ( st ) NEW_LINE k = 0 NEW_LINE L = 0 NEW_LINE R = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( i > R ) : NEW_LINE INDENT L = R = i NEW_LINE while ( R < n and st [ R - L ] == st [ R ] ) : NEW_LINE INDENT R += 1 NEW_LINE DEDENT Z [ i ] = R - L NEW_LINE R -= 1... |
Count of substrings of a string containing another given string as a substring | Set 2 | Function to count the substrings of containing another given as a sub ; Store length of S ; Store length of T ; Store the required count of substrings ; Store the starting index of last occurence of T in S ; Iterate in range [ 0 , ... | def findOccurrences ( S , T ) : NEW_LINE INDENT n1 = len ( S ) NEW_LINE n2 = len ( T ) NEW_LINE ans = 0 NEW_LINE last = 0 NEW_LINE for i in range ( n1 - n2 + 1 ) : NEW_LINE INDENT chk = True NEW_LINE for j in range ( n2 ) : NEW_LINE INDENT if ( T [ j ] != S [ i + j ] ) : NEW_LINE INDENT chk = False NEW_LINE break NEW_L... |
Lexicographically largest N | Function to find the lexicographically largest bitonic sequence of size N elements lies in the range [ low , high ] ; Store index of highest element ; If high_index > ( N - 1 ) / 2 , then remaining N / 2 elements cannot be placed in bitonic order ; If high_index <= 0 , then set high_index ... | def LargestArray ( N , low , high ) : NEW_LINE INDENT high_index = N - ( high - low + 1 ) NEW_LINE if ( high_index > ( N - 1 ) // 2 ) : NEW_LINE INDENT print ( " Not β Possible " ) NEW_LINE return NEW_LINE DEDENT if ( high_index <= 0 ) : NEW_LINE INDENT high_index = 1 NEW_LINE DEDENT A = [ 0 ] * N NEW_LINE temp = high ... |
Print matrix elements from top | Function to traverse the matrix diagonally upwards ; Stores the maximum size of vector from all row of matrix nums [ ] [ ] ; Store elements in desired order ; Store every element on the basis of sum of index ( i + j ) ; Print the stored result ; Reverse all sublist ; Driver code ; Given... | def printDiagonalTraversal ( nums ) : NEW_LINE INDENT max_size = len ( nums ) NEW_LINE for i in range ( len ( nums ) ) : NEW_LINE INDENT if ( max_size < len ( nums [ i ] ) ) : NEW_LINE INDENT max_size = len ( nums [ i ] ) NEW_LINE DEDENT DEDENT v = [ [ ] for i in range ( 2 * max_size - 1 ) ] NEW_LINE for i in range ( l... |
Check if given string satisfies the following conditions | Python3 program for the above approach ; Function to check if given string satisfies the given conditions ; Dimensions ; Left diagonal ; Right diagonal ; Conditions not satisfied ; Print Yes ; Given String ; Function call | import math NEW_LINE def isValid ( s ) : NEW_LINE INDENT n = int ( math . sqrt ( len ( s ) ) ) NEW_LINE check = s [ 0 ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT x = i NEW_LINE y = i NEW_LINE while ( x >= 0 and y < n ) : NEW_LINE INDENT if ( s [ n * x + y ] != check or s [ n * x + x ] != check ) : NEW_LINE INDENT... |
Sum of all possible strings obtained by removal of non | Python 3 program for the above approach ; Function to convert a character to its equivalent digit ; Function to precompute powers of 10 ; Function to precompute prefix sum of numerical strings ; Function to return the i - th term of Triangular Number ; Function t... | N = 10 NEW_LINE pref = [ 0 ] * N NEW_LINE power = [ 0 ] * N NEW_LINE def toDigit ( ch ) : NEW_LINE INDENT return ( ord ( ch ) - ord ( '0' ) ) NEW_LINE DEDENT def powerOf10 ( ) : NEW_LINE INDENT power [ 0 ] = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT power [ i ] = power [ i - 1 ] * 10 NEW_LINE DEDENT DEDENT ... |
Sum of products of all possible Subarrays | Function that finds the sum of products of all subarray of arr [ ] ; Stores sum of all subarrays ; Iterate array from behind ; Update the ans ; Update the res ; Print the final sum ; Driver Code ; Given array arr [ ] ; Size of array ; Function call | def sumOfSubarrayProd ( arr , n ) : NEW_LINE INDENT ans = 0 NEW_LINE res = 0 NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT incr = arr [ i ] * ( 1 + res ) NEW_LINE ans += incr NEW_LINE res = incr NEW_LINE i -= 1 NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE IND... |
Sum of all odd length subarrays | Function to calculate the sum of all odd length subarrays ; Stores the sum ; Size of array ; Traverse the array ; Generate all subarray of odd length ; Add the element to sum ; Return the final sum ; Given array arr [ ] ; Function call | def OddLengthSum ( arr ) : NEW_LINE INDENT sum = 0 NEW_LINE l = len ( arr ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT for j in range ( i , l , 2 ) : NEW_LINE INDENT for k in range ( i , j + 1 , 1 ) : NEW_LINE INDENT sum += arr [ k ] NEW_LINE DEDENT DEDENT DEDENT return sum NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 1 , ... |
Sum of all odd length subarrays | Function that finds the sum of all the element of subarrays of odd length ; Stores the sum ; Size of array ; Traverse the given array arr [ ] ; Add to the sum for each contribution of the arr [ i ] ; Return the final sum ; Given array arr [ ] ; Function call | def OddLengthSum ( arr ) : NEW_LINE INDENT Sum = 0 NEW_LINE l = len ( arr ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT Sum += ( ( ( ( i + 1 ) * ( l - i ) + 1 ) // 2 ) * arr [ i ] ) NEW_LINE DEDENT return Sum NEW_LINE DEDENT arr = [ 1 , 5 , 3 , 1 , 2 ] NEW_LINE print ( OddLengthSum ( arr ) ) NEW_LINE |
Check if Euler Totient Function is same for a given number and twice of that number | Function to find the Euler 's Totient Function ; Initialize result as N ; Consider all prime factors of n and subtract their multiples from result ; Return the count ; Function to check if phi ( n ) is equals phi ( 2 * n ) ; Driver Co... | def phi ( n ) : NEW_LINE INDENT result = 1 NEW_LINE for p in range ( 2 , n ) : NEW_LINE INDENT if ( __gcd ( p , n ) == 1 ) : NEW_LINE INDENT result += 1 NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT def sameEulerTotient ( n ) : NEW_LINE INDENT return phi ( n ) == phi ( 2 * n ) NEW_LINE DEDENT def __gcd ( a , b )... |
Check if Euler Totient Function is same for a given number and twice of that number | Function to check if phi ( n ) is equals phi ( 2 * n ) ; Return if N is odd ; Driver code ; Function call | def sameEulerTotient ( N ) : NEW_LINE INDENT return ( N & 1 ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 13 ; NEW_LINE if ( sameEulerTotient ( N ) == 1 ) : NEW_LINE INDENT print ( " Yes " ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) ; NEW_LINE DEDENT DEDENT |
Smallest occurring element in each subsequence | Function that count the subsequence such that each element as the minimum element in the subsequence ; Store index in a map ; Sort the array ; To store count of subsequence ; Traverse the array ; Store count of subsequence ; Print the count of subsequence ; Driver code ;... | def solve ( arr , N ) : NEW_LINE INDENT M = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT M [ i ] = arr [ i ] NEW_LINE DEDENT arr . sort ( ) NEW_LINE Count = { } NEW_LINE for i in range ( N ) : NEW_LINE INDENT Count [ arr [ i ] ] = pow ( 2 , N - i - 1 ) NEW_LINE DEDENT for it in Count . values ( ) : NEW_LINE INDE... |
Program to insert dashes between two adjacent odd digits in given Number | Function to check if char ch is odd or not ; Function to insert dash - between any 2 consecutive digit in string str ; Traverse the string character by character ; Compare every consecutive character with the odd value ; Print the resultant stri... | def checkOdd ( ch ) : NEW_LINE INDENT return ( ( ord ( ch ) - 48 ) & 1 ) NEW_LINE DEDENT def Insert_dash ( num_str ) : NEW_LINE INDENT result_str = num_str NEW_LINE x = 0 NEW_LINE while ( x < len ( num_str ) - 1 ) : NEW_LINE INDENT if ( checkOdd ( num_str [ x ] ) and checkOdd ( num_str [ x + 1 ] ) ) : NEW_LINE INDENT r... |
Check if a Matrix is Reverse Bitonic or Not | Python3 program to check if a matrix is Reverse Bitonic or not ; Function to check if an array is Reverse Bitonic or not ; Check for decreasing sequence ; Check for increasing sequence ; Function to check whether given matrix is bitonic or not ; Check row - wise ; Check col... | N = 3 NEW_LINE M = 3 NEW_LINE def checkReverseBitonic ( arr , n ) : NEW_LINE INDENT f = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT if ( arr [ i ] < arr [ i - 1 ] ) : NEW_LINE INDENT continue NEW_LINE DEDENT if ( arr [ i ] == arr [ i - 1 ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT else : NEW_LINE INDEN... |
Find the element at the specified index of a Spirally Filled Matrix | Function to return the element at ( x , y ) ; If y is greater ; If y is odd ; If y is even ; If x is even ; If x is odd ; Driver code | def SpiralElement ( x , y ) : NEW_LINE INDENT r = 0 NEW_LINE if ( x < y ) : NEW_LINE INDENT if ( y % 2 == 1 ) : NEW_LINE INDENT r = y * y NEW_LINE return ( r - x + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT r = ( y - 1 ) * ( y - 1 ) NEW_LINE return ( r + x ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( x % 2 == 0... |
Make the string in AP by changing a character | Function to modify the given string and find the index where modification is needed ; Array to store the ASCII values of alphabets ; Loop to compute the ASCII values of characters a - z ; Set to store all the possible differences between consecutive elements ; Loop to fin... | def string_modify ( s ) : NEW_LINE INDENT alphabets = [ ] NEW_LINE flag , hold_i = 0 , 0 NEW_LINE hold_l = s [ 0 ] NEW_LINE for i in range ( 26 ) : NEW_LINE INDENT alphabets . append ( chr ( i + ord ( ' a ' ) ) ) NEW_LINE DEDENT difference = set ( ) NEW_LINE reconstruct = " " NEW_LINE for i in range ( 1 , len ( s ) ) :... |
Create matrix whose sum of diagonals in each sub matrix is even | Function to prN * N order matrix with all sub - matrix of even order is sum of its diagonal also even ; Even index ; Odd index ; Iterate two nested loop ; For even index the element should be consecutive odd ; For odd index the element should be consecut... | def evenSubMatrix ( N ) : NEW_LINE INDENT even = 1 NEW_LINE odd = 2 NEW_LINE for i in range ( N ) : NEW_LINE INDENT for j in range ( N ) : NEW_LINE INDENT if ( ( i + j ) % 2 == 0 ) : NEW_LINE INDENT print ( even , end = " β " ) NEW_LINE even += 2 NEW_LINE DEDENT else : NEW_LINE INDENT print ( odd , end = " β " ) NEW_LI... |
Remove leading zeros from a Number given as a string | Python3 Program to implement the above approach ; Function to remove all leading zeros from a a given string ; Regex to remove leading zeros from a string ; Replaces the matched value with given string ; Driver Code | import re NEW_LINE def removeLeadingZeros ( str ) : NEW_LINE INDENT regex = " ^ 0 + ( ? ! $ ) " NEW_LINE str = re . sub ( regex , " " , str ) NEW_LINE print ( str ) NEW_LINE DEDENT str = "0001234" NEW_LINE removeLeadingZeros ( str ) NEW_LINE |
Maximum inversions in a sequence of 1 to N after performing given operations at most K times | Function which computes the maximum number of inversions ; ' answer ' will store the required number of inversions ; We do this because we will never require more than floor ( n / 2 ) operations ; left pointer in the array ; ... | def maximum_inversion ( n , k ) : NEW_LINE INDENT answer = 0 ; NEW_LINE k = min ( k , n // 2 ) ; NEW_LINE left = 1 ; NEW_LINE right = n ; NEW_LINE while ( k > 0 ) : NEW_LINE INDENT k -= 1 ; NEW_LINE answer += 2 * ( right - left ) - 1 ; NEW_LINE left += 1 ; NEW_LINE right -= 1 ; NEW_LINE DEDENT print ( answer ) ; NEW_LI... |
First number to leave an odd remainder after repetitive division by 2 | Python3 program to implement the above approach ; Function to return the position least significant set bit ; Function return the first number to be converted to an odd integer ; Stores the positions of the first set bit ; If both are same ; If A h... | from math import log NEW_LINE def getFirstSetBitPos ( n ) : NEW_LINE INDENT return log ( n & - n , 2 ) + 1 NEW_LINE DEDENT def oddFirst ( a , b ) : NEW_LINE INDENT steps_a = getFirstSetBitPos ( a ) NEW_LINE steps_b = getFirstSetBitPos ( b ) NEW_LINE if ( steps_a == steps_b ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT... |
Check if a string can be split into substrings starting with N followed by N characters | Function to check if the given can be split into desired substrings ; Length of the string ; Traverse the string ; Extract the digit ; Check if the extracted number does not exceed the remaining length ; Check for the remaining st... | def helper ( s , pos ) : NEW_LINE INDENT size = len ( s ) NEW_LINE if ( pos >= size ) : NEW_LINE INDENT return True NEW_LINE DEDENT if ( s [ pos ] . isdigit ( ) == False ) : NEW_LINE INDENT return False NEW_LINE DEDENT num = 0 NEW_LINE for i in range ( pos , size ) : NEW_LINE INDENT num = num * 10 + ord ( s [ pos ] ) -... |
Represent K as sum of N | Array to store the N - Bonacci series ; Function to express K as sum of several N_bonacci numbers ; Driver code | N_bonacci = [ 0 ] * 100 NEW_LINE def N_bonacci_nums ( n , k ) : NEW_LINE INDENT N_bonacci [ 0 ] = 1 NEW_LINE for i in range ( 1 , 51 ) : NEW_LINE INDENT j = i - 1 NEW_LINE while j >= i - k and j >= 0 : NEW_LINE INDENT N_bonacci [ i ] += N_bonacci [ j ] NEW_LINE j -= 1 NEW_LINE DEDENT DEDENT ans = [ ] NEW_LINE for i in ... |
Divide N into K parts in the form ( X , 2 X , ... , KX ) for some value of X | Function to find the division ; Calculating value of x1 ; Print - 1 if division is not possible ; Get the first number ie x1 then successively multiply it by x1 k times by index number to get the required answer ; Given N and K ; Function Ca... | def solve ( n , k ) : NEW_LINE INDENT d = k * ( k + 1 ) ; NEW_LINE if ( ( 2 * n ) % d != 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE return ; NEW_LINE DEDENT x1 = 2 * n // d ; NEW_LINE for i in range ( 1 , k + 1 ) : NEW_LINE INDENT print ( x1 * i , end = " β " ) ; NEW_LINE DEDENT DEDENT n = 10 ; k = 4 ; NEW_LINE ... |
Bitonic string | Function to check if the given string is bitonic ; Check for increasing sequence ; If end of string has been reached ; Check for decreasing sequence ; If the end of string hasn 't been reached ; Return true if bitonic ; Given string ; Function Call | def checkBitonic ( s ) : NEW_LINE INDENT i = 0 NEW_LINE j = 0 NEW_LINE for i in range ( 1 , 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 INDE... |
Find pair with maximum GCD for integers in range 2 to N | Function to find the required pair whose GCD is maximum ; If N is even ; If N is odd ; Driver Code | def solve ( N ) : NEW_LINE INDENT if ( N % 2 == 0 ) : NEW_LINE INDENT print ( N // 2 , N ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( ( N - 1 ) // 2 , ( N - 1 ) ) NEW_LINE DEDENT DEDENT N = 10 NEW_LINE solve ( N ) NEW_LINE |
Find initial sequence that produces a given Array by cyclic increments upto index P | Function to generate and return the required initial arrangement ; Store the minimum element in the array ; Store the number of increments ; Subtract mi - 1 from every index ; Start from the last index which had been incremented ; Sto... | def findArray ( a , n , P ) : NEW_LINE INDENT mi = min ( a ) NEW_LINE ctr = 0 NEW_LINE mi = max ( 0 , mi - 1 ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT a [ i ] -= mi NEW_LINE ctr += mi NEW_LINE DEDENT i = P - 1 NEW_LINE start = - 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT star... |
Generate a unique Array of length N with sum of all subarrays divisible by N | Function to print the required array ; Print Array ; Driver code | def makeArray ( n ) : NEW_LINE INDENT for i in range ( n ) : NEW_LINE INDENT print ( ( i + 1 ) * n , end = " β " ) NEW_LINE DEDENT DEDENT n = 6 ; NEW_LINE makeArray ( n ) ; NEW_LINE |
Find elements in a given range having at least one odd divisor | Function to prints all numbers with at least one odd divisor ; Check if the number is not a power of two ; Driver Code | def printOddFactorNumber ( n , m ) : NEW_LINE INDENT for i in range ( n , m + 1 ) : NEW_LINE INDENT if ( ( i > 0 ) and ( ( i & ( i - 1 ) ) != 0 ) ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT N = 2 NEW_LINE M = 10 NEW_LINE printOddFactorNumber ( N , M ) NEW_LINE |
Print the first N terms of the series 6 , 28 , 66 , 120 , 190 , 276 , ... | Function to print the series ; Initialise the value of k with 2 ; Iterate from 1 to n ; Print each number ; Increment the value of K by 2 for next number ; Given number ; Function Call | def PrintSeries ( n ) : NEW_LINE INDENT k = 2 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT print ( k * ( 2 * k - 1 ) , end = ' β ' ) NEW_LINE k = k + 2 NEW_LINE DEDENT DEDENT n = 12 NEW_LINE PrintSeries ( n ) NEW_LINE |
Find a string which matches all the patterns in the given array | Function to find a common string which matches all the pattern ; For storing prefix till first most * without conflicts ; For storing suffix till last most * without conflicts ; For storing all middle characters between first and last * ; Loop to iterate... | def find ( S , N ) : NEW_LINE INDENT pref = " " NEW_LINE suff = " " NEW_LINE mid = " " NEW_LINE for i in range ( N ) : NEW_LINE INDENT first = int ( S [ i ] . index ( " * " ) ) NEW_LINE last = int ( S [ i ] . rindex ( " * " ) ) NEW_LINE for z in range ( len ( pref ) ) : NEW_LINE INDENT if ( z < first ) : NEW_LINE INDEN... |
Mountain Sequence Pattern | Python3 program for the above approach ; Function to print pattern recursively ; Base Case ; Condition to check row limit ; Condition for assigning gaps ; Conditions to print * ; Else print ' ; Recursive call for columns ; Recursive call for rows ; Given Number N ; Function Call | k1 = 2 NEW_LINE k2 = 2 NEW_LINE gap = 5 NEW_LINE def printPattern ( i , j , n ) : NEW_LINE INDENT global k1 NEW_LINE global k2 NEW_LINE global gap NEW_LINE if ( j >= n ) : NEW_LINE INDENT k1 = 2 NEW_LINE k2 = 2 NEW_LINE k1 -= 1 NEW_LINE k2 += 1 NEW_LINE if ( i == 2 ) : NEW_LINE INDENT k1 = 0 NEW_LINE k2 = n - 1 NEW_LIN... |
Build a DFA to accept Binary strings that starts or ends with "01" | Function for transition state A ; State transition to B if the character is 0 ; State transition to D if the character is 1 ; Function for transition state B ; Check if the string has ended ; State transition to C if the character is 1 ; State transit... | def checkstateA ( n ) : NEW_LINE INDENT if ( n [ 0 ] == '0' ) : NEW_LINE INDENT stateB ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateD ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT def stateB ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " string β not β accepted " ) NEW_LINE DEDENT else : ... |
Find the Nth Hogben Numbers | Function returns N - th Hogben Number ; Driver code | def HogbenNumber ( a ) : NEW_LINE INDENT p = ( pow ( a , 2 ) - a + 1 ) NEW_LINE return p NEW_LINE DEDENT N = 10 NEW_LINE print ( HogbenNumber ( N ) ) NEW_LINE |
Check if left and right shift of any string results into given string | Function to check string exist or not as per above approach ; Check if any character at position i and i + 2 are not equal , then string doesnot exist ; Driver Code | def check_string_exist ( S ) : NEW_LINE INDENT size = len ( S ) NEW_LINE check = True NEW_LINE for i in range ( size ) : NEW_LINE INDENT if S [ i ] != S [ ( i + 2 ) % size ] : NEW_LINE INDENT check = False NEW_LINE break NEW_LINE DEDENT DEDENT if check : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE... |
Cumulative product of digits of all numbers in the given range | Function to get product of digits ; Function to find the product of digits of all natural numbers in range L to R ; Iterate between L to R ; Driver Code | def getProduct ( n ) : NEW_LINE INDENT product = 1 NEW_LINE while ( n != 0 ) : NEW_LINE INDENT product = product * ( n % 10 ) NEW_LINE n = int ( n / 10 ) NEW_LINE DEDENT return product NEW_LINE DEDENT def productinRange ( l , r ) : NEW_LINE INDENT if ( r - l > 9 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT else : NEW_L... |
Check whether the string can be printed using same row of qwerty keypad | Function to find the row of the character in the qwerty keypad ; Sets to include the characters from the same row of the qwerty keypad ; Condition to check the row of the current character of the string ; Function to check the characters are from... | def checkQwertyRow ( x ) : NEW_LINE INDENT first_row = [ '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , '0' , ' - ' , ' = ' ] NEW_LINE second_row = [ ' Q ' , ' W ' , ' E ' , ' R ' , ' T ' , ' Y ' , ' U ' , ' I ' , ' O ' , ' P ' , ' [ ' , ' ] ' , ' q ' , ' w ' , ' e ' , ' r ' , ' t ' , ' y ' , ' u ' , ' i ' , ' o... |
Last digit of sum of numbers in the given range in the Fibonacci series | Calculate the sum of the first N Fibonacci numbers using Pisano period ; The first two Fibonacci numbers ; Base case ; Pisano Period for % 10 is 60 ; Checking the remainder ; The loop will range from 2 to two terms after the remainder ; Driver co... | def fib ( n ) : NEW_LINE INDENT f0 = 0 NEW_LINE f1 = 1 NEW_LINE if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( n == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT else : NEW_LINE INDENT rem = n % 60 NEW_LINE if ( rem == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT for i in range ( 2 , rem + 3 ) : NEW_L... |
Find N values of X1 , X2 , ... Xn such that X1 < X2 < ... < XN and sin ( X1 ) < sin ( X2 ) < ... < sin ( XN ) | Python3 program for the above approach ; Function to print all such Xi s . t . all Xi and sin ( Xi ) are strictly increasing ; Till N becomes zero ; Find the value of sin ( ) using inbuilt function ; incremen... | import math NEW_LINE def printSinX ( N ) : NEW_LINE INDENT Xi = 0 ; NEW_LINE num = 1 ; NEW_LINE while ( N > 0 ) : NEW_LINE INDENT print ( " X " , num , " = " , Xi , end = " β " ) ; NEW_LINE print ( " sin ( X " , num , " ) β = " , end = " β " ) ; NEW_LINE print ( " { : . 6f } " . format ( math . sin ( Xi ) ) , " " ) ;... |
Sum of all elements in an array between zeros | Function to find the sum between two zeros in the given array arr [ ] ; To store the sum of the element between two zeros ; To store the sum ; Find first index of 0 ; Traverse the given array arr [ ] ; If 0 occurs then add it to A [ ] ; Else add element to the sum ; Print... | def sumBetweenZero ( arr , N ) : NEW_LINE INDENT i = 0 NEW_LINE A = [ ] NEW_LINE sum = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT i += 1 NEW_LINE break NEW_LINE DEDENT DEDENT k = i NEW_LINE for i in range ( k , N , 1 ) : NEW_LINE INDENT if ( arr [ i ] == 0 ) : NEW_LINE IND... |
Find the Nth term of the series 2 , 15 , 41 , 80 , 132. . . | Recursive function to find Nth term ; Base Case ; Recursive Call according to Nth term of the series ; Driver Code ; Input Nth term ; Function call | def nthTerm ( N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT return ( ( N - 1 ) * 13 ) + nthTerm ( N - 1 ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 17 NEW_LINE print ( nthTerm ( N ) ) NEW_LINE DEDENT |
Subsequence pair from given Array having all unique and all same elements respectively | Function to find the maximum length of subsequences with given property ; To store the frequency ; Traverse the array to store the frequency ; M . size ( ) given count of distinct element in arr [ ] ; Traverse map to find max frequ... | def maximumSubsequence ( arr , N ) : NEW_LINE INDENT M = { i : 0 for i in range ( 100 ) } NEW_LINE for i in range ( N ) : NEW_LINE INDENT M [ arr [ i ] ] += 1 NEW_LINE DEDENT distinct_size = len ( M ) NEW_LINE maxFreq = 1 NEW_LINE for value in M . values ( ) : NEW_LINE INDENT maxFreq = max ( maxFreq , value ) NEW_LINE ... |
Total length of string from given Array of strings composed using given characters | Function to count the total length ; Unordered_map for keeping frequency of characters ; Calculate the frequency ; Iterate in the N strings ; Iterates in the string ; Checks if given character of string string appears in it or not ; Ad... | def countCharacters ( arr , chars ) : NEW_LINE INDENT res = 0 NEW_LINE freq = dict ( ) NEW_LINE for i in range ( len ( chars ) ) : NEW_LINE INDENT freq [ chars [ i ] ] = freq . get ( chars [ i ] , 0 ) + 1 NEW_LINE DEDENT for st in arr : NEW_LINE INDENT flag = True NEW_LINE for c in st : NEW_LINE INDENT if ( c not in fr... |
Construct an Array of size N in which sum of odd elements is equal to sum of even elements | Function to construct the required array ; To construct first half , distinct even numbers ; To construct second half , distinct odd numbers ; Calculate the last number of second half so as to make both the halves equal ; Funct... | def arrayConstruct ( N ) : NEW_LINE INDENT for i in range ( 2 , N + 1 , 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT for i in range ( 1 , N - 1 , 2 ) : NEW_LINE INDENT print ( i , end = " β " ) NEW_LINE DEDENT print ( N - 1 + ( N // 2 ) ) NEW_LINE DEDENT def createArray ( N ) : NEW_LINE INDENT if ( N... |
Count of all sub | Function to count all substrings ; Hashmap to store substrings ; iterate over all substrings ; variable to maintain sum of all characters encountered ; variable to maintain substring till current position ; get position of character in string W ; add weight to current sum ; add current character to s... | def distinctSubstring ( P , Q , K , N ) : NEW_LINE INDENT S = set ( ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum = 0 NEW_LINE s = " " NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT pos = ord ( P [ j ] ) - 97 NEW_LINE sum += ord ( Q [ pos ] ) - 48 NEW_LINE s += P [ j ] NEW_LINE if ( sum <= K ) : NEW_LINE I... |
Minimum characters required to make a password strong | Python3 program to find minimum number of characters required to be added to make a password strong ; Function to count minimum number of characters ; Create the patterns to search digit , upper case alphabet , lower case alphabet and special character ; If no dig... | import re NEW_LINE def countCharacters ( password ) : NEW_LINE INDENT count = 0 NEW_LINE digit = re . compile ( " ( \\d ) " ) NEW_LINE upper = re . compile ( " ( [ A - Z ] ) " ) NEW_LINE lower = re . compile ( " ( [ a - z ] ) " ) NEW_LINE spChar = re . compile ( " ( \\W ) " ) NEW_LINE if ( not re . search ( digit , pas... |
Count all sub | Function to find the count of all the substrings with weight of characters atmost K ; Hashmap to store all substrings ; Iterate over all substrings ; Maintain the sum of all characters encountered so far ; Maintain the substring till the current position ; Get the position of the character in string Q ;... | def distinctSubstring ( P , Q , K , N ) : NEW_LINE INDENT S = set ( ) NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT sum = 0 ; NEW_LINE s = ' ' NEW_LINE for j in range ( i , N ) : NEW_LINE INDENT pos = ord ( P [ j ] ) - 97 NEW_LINE sum = sum + ord ( Q [ pos ] ) - 48 NEW_LINE s += P [ j ] NEW_LINE if ( sum <= K ) :... |
Program to print a Hollow Triangle inside a Triangle | Function to print the pattern ; Loop for rows ; Loop for column ; For printing equal sides of outer triangle ; For printing equal sides of inner triangle ; For printing base of both triangle ; For spacing between the triangle ; Driver Code | def printPattern ( n ) : NEW_LINE INDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , 2 * n ) : NEW_LINE INDENT if ( j == ( n - i + 1 ) or j == ( n + i - 1 ) ) : NEW_LINE INDENT print ( " * β " , end = " " ) NEW_LINE DEDENT elif ( ( i >= 4 and i <= n - 4 ) and ( j == n - i + 4 or j == n + i - 4 )... |
Check if a string is made up of K alternating characters | Function to check if a string is made up of k alternating characters ; Check if all the characters at indices 0 to K - 1 are different ; If that bit is already set in checker , return false ; Otherwise update and continue by setting that bit in the checker ; Dr... | def isKAlternating ( s , k ) : NEW_LINE INDENT if ( len ( s ) < k ) : NEW_LINE INDENT return False NEW_LINE DEDENT checker = 0 NEW_LINE for i in range ( k ) : NEW_LINE INDENT bitAtIndex = ord ( s [ i ] ) - ord ( ' a ' ) NEW_LINE if ( ( checker & ( 1 << bitAtIndex ) ) > 0 ) : NEW_LINE INDENT return False NEW_LINE DEDENT... |
Find all Factors of Large Perfect Square Natural Number in O ( sqrt ( sqrt ( N ) ) | Python 3 program to find the factors of large perfect square number in O ( sqrt ( sqrt ( N ) ) ) time ; Function that find all the prime factors of N ; Store the sqrt ( N ) in temp ; Initialise factor array with 1 as a factor in it ; C... | import math NEW_LINE MAX = 100000 NEW_LINE def findFactors ( N ) : NEW_LINE INDENT temp = int ( math . sqrt ( N ) ) NEW_LINE factor = [ 1 ] * MAX NEW_LINE len1 = 1 NEW_LINE while ( temp % 2 == 0 ) : NEW_LINE INDENT factor [ len1 ] = 2 NEW_LINE len1 += 1 NEW_LINE factor [ len1 ] = 2 NEW_LINE len1 += 1 NEW_LINE temp //= ... |
Construct a matrix such that union of ith row and ith column contains every element from 1 to 2 N | Python3 implementation of the above approach ; Function to find the square matrix ; For Matrix of order 1 , it will contain only 1 ; For Matrix of odd order , it is not possible ; For Matrix of even order ; All diagonal ... | import numpy as np ; NEW_LINE matrix = np . zeros ( ( 100 , 100 ) ) ; NEW_LINE def printRequiredMatrix ( n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT print ( "1" ) ; NEW_LINE DEDENT elif ( n % 2 != 0 ) : NEW_LINE INDENT print ( " - 1" ) ; NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( n ) : NEW_LINE I... |
Count of sub | Function to find the count of substrings with equal no . of consecutive 0 ' s β and β 1' s ; To store the total count of substrings ; Traversing the string ; Count of consecutive 0 ' s β & β 1' s ; Counting subarrays of type "01" ; Count the consecutive 0 's ; If consecutive 0 ' s β β ends β then β check... | def countSubstring ( S , n ) : NEW_LINE INDENT ans = 0 ; NEW_LINE i = 0 ; NEW_LINE while ( i < n ) : NEW_LINE INDENT cnt0 = 0 ; cnt1 = 0 ; NEW_LINE if ( S [ i ] == '0' ) : NEW_LINE INDENT while ( i < n and S [ i ] == '0' ) : NEW_LINE INDENT cnt0 += 1 ; NEW_LINE i += 1 ; NEW_LINE DEDENT j = i ; NEW_LINE while ( j < n an... |
Print N numbers such that their sum is a Perfect Cube | Function to find the N numbers such that their sum is a perfect cube ; Loop to find the Ith term of the Centered Hexagonal number ; Driver Code ; Function Call | def findNumbers ( n ) : NEW_LINE INDENT i = 1 NEW_LINE while ( i <= n ) : NEW_LINE INDENT print ( ( 3 * i * ( i - 1 ) + 1 ) , end = " β " ) NEW_LINE i += 1 NEW_LINE DEDENT DEDENT n = 4 NEW_LINE findNumbers ( n ) NEW_LINE |
Largest N digit Octal number which is a Perfect square | Python3 implementation to find the maximum N - digit octal number which is perfect square ; Function to convert decimal number to a octal number ; Array to store octal number ; Counter for octal number array ; Store remainder in octal array ; Print octal number a... | from math import sqrt , ceil NEW_LINE def decToOctal ( n ) : NEW_LINE INDENT octalNum = [ 0 ] * 100 ; NEW_LINE i = 0 ; NEW_LINE while ( n != 0 ) : NEW_LINE INDENT octalNum [ i ] = n % 8 ; NEW_LINE n = n // 8 ; NEW_LINE i += 1 ; NEW_LINE DEDENT for j in range ( i - 1 , - 1 , - 1 ) : NEW_LINE INDENT print ( octalNum [ j ... |
Reverse the substrings of the given String according to the given Array of indices | Function to reverse a string ; Swap character starting from two corners ; Function to reverse the string with the given array of indices ; Reverse the from 0 to A [ 0 ] ; Reverse the for A [ i ] to A [ i + 1 ] ; Reverse String for A [ ... | def reverseStr ( str , l , h ) : NEW_LINE INDENT n = h - l NEW_LINE for i in range ( n // 2 ) : NEW_LINE INDENT str [ i + l ] , str [ n - i - 1 + l ] = str [ n - i - 1 + l ] , str [ i + l ] NEW_LINE DEDENT DEDENT def reverseString ( s , A , n ) : NEW_LINE INDENT reverseStr ( s , 0 , A [ 0 ] ) NEW_LINE for i in range ( ... |
Maximize the sum of differences of consecutive elements after removing exactly K elements | Function to return the maximized sum ; Remove any k internal elements ; Driver code | def findSum ( arr , n , k ) : NEW_LINE INDENT if ( k <= n - 2 ) : NEW_LINE INDENT return ( arr [ n - 1 ] - arr [ 0 ] ) ; NEW_LINE DEDENT return 0 ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE k = 1 ; NEW_LINE print ( findSum ( arr , n ,... |
Split the binary string into substrings with equal number of 0 s and 1 s | Function to return the count of maximum substrings str can be divided into ; To store the count of 0 s and 1 s ; To store the count of maximum substrings str can be divided into ; It is not possible to split the string ; Driver code | def maxSubStr ( str , n ) : NEW_LINE INDENT count0 = 0 NEW_LINE count1 = 0 NEW_LINE cnt = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if str [ i ] == '0' : NEW_LINE INDENT count0 += 1 NEW_LINE DEDENT else : NEW_LINE INDENT count1 += 1 NEW_LINE DEDENT if count0 == count1 : NEW_LINE INDENT cnt += 1 NEW_LINE DEDENT ... |
Sum of the digits of square of the given number which has only 1 's as its digits | Function to return the sum of the digits of num ^ 2 ; To store the number of 1 's ; Find the sum of the digits of num ^ 2 ; Driver code | def squareDigitSum ( num ) : NEW_LINE INDENT lengthN = len ( num ) NEW_LINE result = ( lengthN // 9 ) * 81 + ( lengthN % 9 ) ** 2 NEW_LINE return result NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = "1111" NEW_LINE print ( squareDigitSum ( N ) ) NEW_LINE DEDENT |
Check whether two strings contain same characters in same order | Python3 implementation of the approach ; string class has a constructor that allows us to specify the size of string as first parameter and character to be filled in given size as the second parameter . ; Function that returns true if the given strings c... | def getString ( x ) : NEW_LINE INDENT return x NEW_LINE DEDENT def solve ( s1 , s2 ) : NEW_LINE INDENT a = getString ( s1 [ 0 ] ) NEW_LINE b = getString ( s2 [ 0 ] ) NEW_LINE for i in range ( 1 , len ( s1 ) ) : NEW_LINE INDENT if s1 [ i ] != s1 [ i - 1 ] : NEW_LINE INDENT a += getString ( s1 [ i ] ) NEW_LINE DEDENT DED... |
Count number of distinct substrings of a given length | Python3 implementation of above approach ; Function to find the required count ; Variable to the hash ; Finding hash of substring ( 0 , l - 1 ) using random number x ; Computing x ^ ( l - 1 ) ; Unordered set to add hash values ; Generating all possible hash values... | x = 26 NEW_LINE mod = 3001 NEW_LINE def CntSubstr ( s , l ) : NEW_LINE INDENT hash = 0 ; NEW_LINE for i in range ( l ) : NEW_LINE INDENT hash = ( hash * x + ( ord ( s [ i ] ) - 97 ) ) % mod ; NEW_LINE DEDENT pow_l = 1 ; NEW_LINE for i in range ( l - 1 ) : NEW_LINE INDENT pow_l = ( pow_l * x ) % mod ; NEW_LINE DEDENT re... |
Count strings that end with the given pattern | Function that return true if str1 ends with pat ; Pattern is larger in length than the str1ing ; We match starting from the end while patLen is greater than or equal to 0. ; If at any index str1 doesn 't match with pattern ; If str1 ends with the given pattern ; Function... | def endsWith ( str1 , pat ) : NEW_LINE INDENT patLen = len ( pat ) NEW_LINE str1Len = len ( str1 ) NEW_LINE if ( patLen > str1Len ) : NEW_LINE INDENT return False NEW_LINE DEDENT patLen -= 1 NEW_LINE str1Len -= 1 NEW_LINE while ( patLen >= 0 ) : NEW_LINE INDENT if ( pat [ patLen ] != str1 [ str1Len ] ) : NEW_LINE INDEN... |
Length of the longest substring with consecutive characters | Function to return the ending index for the largest valid sub - str1ing starting from index i ; If the current character appears after the previous character according to the given circular alphabetical order ; Function to return the length of the longest su... | def getEndingIndex ( str1 , n , i ) : NEW_LINE INDENT i += 1 NEW_LINE while ( i < n ) : NEW_LINE INDENT curr = str1 [ i ] NEW_LINE prev = str1 [ i - 1 ] NEW_LINE if ( ( curr == ' a ' and prev == ' z ' ) or ( ord ( curr ) - ord ( prev ) == 1 ) ) : NEW_LINE INDENT i += 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_L... |
Sum of integers upto N with given unit digit ( Set 2 ) | Function to return the required sum ; Decrement N ; Driver code | def getSum ( n , d ) : NEW_LINE INDENT if ( n < d ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT while ( n % 10 != d ) : NEW_LINE INDENT n -= 1 NEW_LINE DEDENT k = n // 10 NEW_LINE return ( ( k + 1 ) * d + ( k * 10 + 10 * k * k ) // 2 ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 30 NEW_LINE d =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.