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 arr [ ] ; count all possible sub - sequences by the digits less than arr [ i ] digit ; store sum of all sub - sequences plus 1 in count [ ] array ; Now sum up the all sequences possible in count [ ] array ; Driver Code | 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 ( 10 ) : NEW_LINE INDENT result += count [ i ] NEW_LINE DEDENT return result NEW_LINE DEDENT arr = [ 3 , 2 , 4 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE print ( countSub ( arr , n ) ) NEW_LINE |
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 store minimum possible sum when arr [ i ] is part of the solution . ; When there are less than or equal to 3 elements ; Iterate through all other elements ; Driver code | 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 . append ( arr [ i ] + minimum ( sum [ i - 3 ] , sum [ i - 2 ] , sum [ i - 1 ] ) ) NEW_LINE DEDENT return minimum ( sum [ n - 1 ] , sum [ n - 2 ] , sum [ n - 3 ] ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 20 , 2 , 10 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Min β Sum β is β " , findMinSum ( arr , n ) ) NEW_LINE |
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 particular character isn 't taken ; Driver Code ; Output array for storing the generating subsequences in each call ; Function Call ; Output will be the number of elements in the set | 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 ] = s [ i ] NEW_LINE subsequences ( s , op , i + 1 , j + 1 ) NEW_LINE subsequences ( s , op , i + 1 , j ) NEW_LINE return NEW_LINE DEDENT DEDENT str = " ggg " NEW_LINE m = len ( str ) NEW_LINE n = int ( math . pow ( 2 , m ) + 1 ) NEW_LINE op = [ None for i in range ( n ) ] NEW_LINE subsequences ( str , op , 0 , 0 ) NEW_LINE print ( len ( set ( sn ) ) ) NEW_LINE |
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_LINE levelCount = 1 NEW_LINE continue NEW_LINE DEDENT levelCount = allCount + 1 NEW_LINE if ( Map < 0 ) : NEW_LINE INDENT allCount = allCount + levelCount NEW_LINE DEDENT else : NEW_LINE INDENT allCount = allCount + levelCount - Map NEW_LINE DEDENT Map = levelCount NEW_LINE DEDENT return allCount NEW_LINE DEDENT List = [ " abab " , " gfg " ] NEW_LINE for s in List : NEW_LINE INDENT cnt = countSub ( s ) NEW_LINE withEmptyString = cnt + 1 NEW_LINE print ( " With β empty β string β count β for " , s , " is " , withEmptyString ) NEW_LINE print ( " Without β empty β string β count β for " , s , " is " , cnt ) NEW_LINE DEDENT |
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 orange ; traverse the original cost [ ] array and skip unavailable packets and make val [ ] and wt [ ] array . size variable tells the available number of distinct weighted packets . ; fill 0 th row with infinity ; fill 0 th column with 0 ; now check for each weight one by one and fill the matrix according to the condition ; wt [ i - 1 ] > j means capacity of bag is less than weight of item ; here we check we get minimum cost either by including it or excluding it ; exactly weight W can not be made by given weights ; Driver program to run the test case | 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 DEDENT n = size NEW_LINE min_cost = [ [ 0 for i in range ( W + 1 ) ] for j in range ( n + 1 ) ] NEW_LINE for i in range ( W + 1 ) : NEW_LINE INDENT min_cost [ 0 ] [ i ] = INF NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT min_cost [ i ] [ 0 ] = 0 NEW_LINE DEDENT for i in range ( 1 , n + 1 ) : NEW_LINE INDENT for j in range ( 1 , W + 1 ) : NEW_LINE INDENT if ( wt [ i - 1 ] > j ) : NEW_LINE INDENT min_cost [ i ] [ j ] = min_cost [ i - 1 ] [ j ] NEW_LINE DEDENT else : NEW_LINE INDENT min_cost [ i ] [ j ] = min ( min_cost [ i - 1 ] [ j ] , min_cost [ i ] [ j - wt [ i - 1 ] ] + val [ i - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT if ( min_cost [ n ] [ W ] == INF ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return min_cost [ n ] [ W ] NEW_LINE DEDENT DEDENT cost = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE W = 5 NEW_LINE n = len ( cost ) NEW_LINE print ( MinimumCost ( cost , n , W ) ) NEW_LINE |
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 and second string is not empty , return 0 ; If last characters are same Recur for remaining strings by 1. considering last characters of both strings 2. ignoring last character of first string ; If last characters are different , ignore last char of first string and recur for remaining string ; Driver code | 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 DEDENT else : NEW_LINE INDENT return count ( a , b , m - 1 , n ) NEW_LINE DEDENT DEDENT a = " GeeksforGeeks " NEW_LINE b = " Gks " NEW_LINE print ( count ( a , b , len ( a ) , len ( b ) ) ) NEW_LINE |
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 - 1 ] and Y [ 0. . m - 1 ] ; Returns cost of making X [ ] and Y [ ] identical . costX is cost of removing a character from X [ ] and costY is cost of removing a character from Y [ ] ; Find LCS of X [ ] and Y [ ] ; Cost of making two strings identical is SUM of following two 1 ) Cost of removing extra characters from first string 2 ) Cost of removing extra characters from second string ; Driver Code | 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 INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT def findMinCost ( X , Y , costX , costY ) : NEW_LINE INDENT m = len ( X ) NEW_LINE n = len ( Y ) NEW_LINE len_LCS = lcs ( X , Y , m , n ) NEW_LINE return ( costX * ( m - len_LCS ) + costY * ( n - len_LCS ) ) NEW_LINE DEDENT X = " ef " NEW_LINE Y = " gh " NEW_LINE print ( ' Minimum β Cost β to β make β two β strings β ' , end = ' ' ) NEW_LINE print ( ' identical β is β = β ' , findMinCost ( X , Y , 10 , 20 ) ) NEW_LINE |
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. . m - 2 ] and Y [ 0. . n - 2 ] in the matrix ; append current character to all possible LCS of substring X [ 0. . m - 2 ] and Y [ 0. . n - 2 ] . ; If the last characters of X and Y are not same ; If LCS can be constructed from top side of the matrix , recurse for X [ 0. . m - 2 ] and Y [ 0. . n - 1 ] ; If LCS can be constructed from left side of the matrix , recurse for X [ 0. . m - 1 ] and Y [ 0. . n - 2 ] ; merge two sets if L [ m - 1 ] [ n ] == L [ m ] [ n - 1 ] Note s will be empty if L [ m - 1 ] [ n ] != L [ m ] [ n - 1 ] ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Build L [ m + 1 ] [ n + 1 ] in bottom up fashion ; Driver Code | 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 - 1 ) NEW_LINE for string in tmp : NEW_LINE INDENT s . add ( string + x [ m - 1 ] ) NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if L [ m - 1 ] [ n ] >= L [ m ] [ n - 1 ] : NEW_LINE INDENT s = findLCS ( x , y , m - 1 , n ) NEW_LINE DEDENT if L [ m ] [ n - 1 ] >= L [ m - 1 ] [ n ] : NEW_LINE INDENT tmp = findLCS ( x , y , m , n - 1 ) NEW_LINE for i in tmp : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT DEDENT DEDENT return s NEW_LINE DEDENT def LCS ( x , y , m , n ) : NEW_LINE INDENT 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 INDENT L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return L [ m ] [ n ] NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT x = " AGTGATG " NEW_LINE y = " GTTAG " NEW_LINE m = len ( x ) NEW_LINE n = len ( y ) NEW_LINE print ( " LCS β length β is " , LCS ( x , y , m , n ) ) NEW_LINE s = findLCS ( x , y , m , n ) NEW_LINE for i in s : NEW_LINE INDENT print ( i ) NEW_LINE DEDENT DEDENT |
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 NEW_LINE print ( countIntegralSolutions ( n ) ) NEW_LINE |
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 β algorithm . β This β version β of β Kadane ' s Algorithm will work if all numbers are negative ; The function finds two non - overlapping contiguous sub - arrays such that the absolute difference between the sum of two sub - array is maximum . ; create and build an array that stores maximum sums of subarrays that lie in arr [ 0. . . i ] ; create and build an array that stores maximum sums of subarrays that lie in arr [ i + 1. . . n - 1 ] ; Invert array ( change sign ) to find minumum sum subarrays . ; create and build an array that stores minimum sums of subarrays that lie in arr [ 0. . . i ] ; create and build an array that stores minimum sums of subarrays that lie in arr [ i + 1. . . n - 1 ] ; For each index i , take maximum of 1. abs ( max sum subarray that lies in arr [ 0. . . i ] - min sum subarray that lies in arr [ i + 1. . . n - 1 ] ) 2. abs ( min sum subarray that lies in arr [ 0. . . i ] - max sum subarray that lies in arr [ i + 1. . . n - 1 ] ) ; Driver Code | 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_so_far NEW_LINE DEDENT return max_so_far NEW_LINE DEDENT def maxRightSubArraySum ( a , n , sum ) : NEW_LINE INDENT max_so_far = a [ n ] NEW_LINE curr_max = a [ n ] NEW_LINE sum [ n ] = max_so_far NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : 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_so_far NEW_LINE DEDENT return max_so_far NEW_LINE DEDENT def findMaxAbsDiff ( arr , n ) : NEW_LINE INDENT leftMax = [ 0 for i in range ( n ) ] NEW_LINE maxLeftSubArraySum ( arr , n , leftMax ) NEW_LINE rightMax = [ 0 for i in range ( n ) ] NEW_LINE maxRightSubArraySum ( arr , n - 1 , rightMax ) NEW_LINE invertArr = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT invertArr [ i ] = - arr [ i ] NEW_LINE DEDENT leftMin = [ 0 for i in range ( n ) ] NEW_LINE maxLeftSubArraySum ( invertArr , n , leftMin ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT leftMin [ i ] = - leftMin [ i ] NEW_LINE DEDENT rightMin = [ 0 for i in range ( n ) ] NEW_LINE maxRightSubArraySum ( invertArr , n - 1 , rightMin ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT rightMin [ i ] = - rightMin [ i ] NEW_LINE DEDENT result = - 2147483648 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT absValue = max ( abs ( leftMax [ i ] - rightMin [ i + 1 ] ) , abs ( leftMin [ i ] - rightMax [ i + 1 ] ) ) NEW_LINE if ( absValue > result ) : NEW_LINE INDENT result = absValue NEW_LINE DEDENT DEDENT return result NEW_LINE DEDENT a = [ - 2 , - 3 , 4 , - 1 , - 2 , 1 , 5 , - 3 ] NEW_LINE n = len ( a ) NEW_LINE print ( findMaxAbsDiff ( a , n ) ) NEW_LINE |
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 and the number of balls of P type is 1 while number of balls of other color is 0 the number of ways is 1. ; Same case as above for ' q ' and 'r ; if last ball required is P and the number of ways is the sum of number of ways to form sequence with ' p - 1' P balls , q Q Balls and r R balls ending with Q and R . ; Same as above case for ' q ' and 'r ; Returns count of required arrangements ; Three cases arise : Last required balls is type P Last required balls is type Q Last required balls is type R ; Driver Code | ' 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 INDENT return 1 ; NEW_LINE DEDENT if ( p == 0 and q == 0 and r == 1 and last == 2 ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT if ( last == 0 ) : NEW_LINE INDENT return ( countWays ( p - 1 , q , r , 1 ) + countWays ( p - 1 , q , r , 2 ) ) ; NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT if ( last == 1 ) : NEW_LINE INDENT return ( countWays ( p , q - 1 , r , 0 ) + countWays ( p , q - 1 , r , 2 ) ) ; NEW_LINE DEDENT if ( last == 2 ) : NEW_LINE INDENT return ( countWays ( p , q , r - 1 , 0 ) + countWays ( p , q , r - 1 , 1 ) ) ; NEW_LINE DEDENT DEDENT def countUtil ( p , q , r ) : NEW_LINE INDENT return ( countWays ( p , q , r , 0 ) + countWays ( p , q , r , 1 ) + countWays ( p , q , r , 2 ) ) ; NEW_LINE DEDENT p = 1 ; NEW_LINE q = 1 ; NEW_LINE r = 1 ; NEW_LINE print ( countUtil ( p , q , r ) ) ; 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 two choices ( 1 ) We do not include it first set ( 2 ) We include it in first set We return minimum of two choices ; Returns minimum possible difference between sums of two subsets ; Compute total sum of elements ; Compute result using recursive function ; Driver code | 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 ) ) NEW_LINE DEDENT def findMin ( arr , n ) : NEW_LINE INDENT sumTotal = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT sumTotal += arr [ i ] NEW_LINE DEDENT return findMinRec ( arr , n , 0 , sumTotal ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 1 , 4 , 2 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The β minimum β difference β " + " between β two β sets β is β " , findMin ( arr , n ) ) NEW_LINE DEDENT |
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 ( countP ( 3 , 2 ) ) NEW_LINE DEDENT |
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 j in range ( 1 , k + 1 ) : NEW_LINE INDENT if ( j == 1 or i == j ) : NEW_LINE INDENT dp [ i ] [ j ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] [ j ] = ( j * dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j - 1 ] ) NEW_LINE DEDENT DEDENT DEDENT return dp [ n ] [ k ] NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT print ( countP ( 5 , 2 ) ) NEW_LINE DEDENT |
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 ( dist ) ) NEW_LINE |
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 ways [ n % 3 ] NEW_LINE DEDENT dist = 4 NEW_LINE print ( prCountDP ( dist ) ) NEW_LINE |
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 return True NEW_LINE DEDENT x = x // 10 NEW_LINE DEDENT return False NEW_LINE DEDENT n = 328 NEW_LINE print ( " Count β of β numbers β from β 1 β to β " , n , " β that β have β 4 β as β a β a β digit β is β " , countNumbersWith4 ( n ) ) NEW_LINE |
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 ] = count of numbers from 0 to 9 = 1 d = 2 a [ 2 ] = count of numbers from 0 to 99 = a [ 1 ] * 9 + 10 = 19 d = 3 a [ 3 ] = count of numbers from 0 to 999 = a [ 2 ] * 19 + 100 = 171 ; Computing 10 ^ d ; Most significant digit ( msd ) of n , For 328 , msd is 3 which can be obtained using 328 / 100 ; If MSD is 4. For example if n = 428 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 399 2 ) Count of numbers from 400 to 428 which is 29. ; IF MSD > 4. For example if n is 728 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 399 and count of numbers from 500 to 699 , i . e . , " a [ 2 ] β * β 6" 2 ) Count of numbers from 400 to 499 , i . e . 100 3 ) Count of numbers from 700 to 728 , recur for 28 ; IF MSD < 4. For example if n is 328 , then count of numbers is sum of following . 1 ) Count of numbers from 1 to 299 a 2 ) Count of numbers from 300 to 328 , recur for 28 ; Driver Code | 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 + 1 ) : NEW_LINE INDENT a [ i ] = a [ i - 1 ] * 9 + mt . ceil ( pow ( 10 , i - 1 ) ) NEW_LINE DEDENT p = mt . ceil ( pow ( 10 , d ) ) NEW_LINE msd = n // p NEW_LINE if ( msd == 4 ) : NEW_LINE INDENT return ( msd ) * a [ d ] + ( n % p ) + 1 NEW_LINE DEDENT if ( msd > 4 ) : NEW_LINE INDENT return ( ( msd - 1 ) * a [ d ] + p + countNumbersWith4 ( n % p ) ) NEW_LINE DEDENT return ( msd ) * a [ d ] + countNumbersWith4 ( n % p ) NEW_LINE DEDENT n = 328 NEW_LINE print ( " Count β of β numbers β from β 1 β to " , n , " that β have β 4 β as β a β digit β is " , countNumbersWith4 ( n ) ) NEW_LINE |
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 maximum sized subarray with property 2 * min > max ; Choose different elements as starting point ; Initialize min and max for the current start ; Choose different ending points for current start ; Update min and max if necessary ; If the property is violated , then no point to continue for a bigger array ; Update longest_start and longest_end if needed ; If not even a single element follow the property , then return n ; Return the number of elements to be removed ; Driver Code | 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 ( val < min ) : NEW_LINE INDENT min = val ; NEW_LINE DEDENT if ( val > max ) : NEW_LINE INDENT max = val ; NEW_LINE DEDENT if ( 2 * min <= max ) : NEW_LINE INDENT break ; NEW_LINE DEDENT if ( end - start > longest_end - longest_start or longest_start == - 1 ) : NEW_LINE INDENT longest_start = start ; NEW_LINE longest_end = end ; NEW_LINE DEDENT DEDENT DEDENT if ( longest_start == - 1 ) : NEW_LINE INDENT return n ; NEW_LINE DEDENT return ( n - ( longest_end - longest_start + 1 ) ) ; NEW_LINE DEDENT arr = [ 4 , 5 , 100 , 9 , 10 , 11 , 12 , 15 , 200 ] ; NEW_LINE n = len ( arr ) ; NEW_LINE print ( minRemovalsDP ( arr , n ) ) ; NEW_LINE |
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 i and k that form AP with j as middle element | 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 -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT k += 1 NEW_LINE DEDENT DEDENT DEDENT return False NEW_LINE DEDENT |
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 : goo . gl / PQqoS ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; Here x is value of F ( i + 2 , j ) , y is F ( i + 1 , j - 1 ) and z is F ( i , j - 2 ) in above recursive formula ; Driver Code | 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_LINE DEDENT y = 0 NEW_LINE if ( ( i + 1 ) <= ( j - 1 ) ) : NEW_LINE INDENT y = table [ i + 1 ] [ j - 1 ] NEW_LINE DEDENT z = 0 NEW_LINE if ( i <= ( j - 2 ) ) : NEW_LINE INDENT z = table [ i ] [ j - 2 ] NEW_LINE DEDENT table [ i ] [ j ] = max ( arr [ i ] + min ( x , y ) , arr [ j ] + min ( y , z ) ) NEW_LINE DEDENT DEDENT return table [ 0 ] [ n - 1 ] NEW_LINE DEDENT arr1 = [ 8 , 15 , 3 , 7 ] NEW_LINE n = len ( arr1 ) NEW_LINE print ( optimalStrategyOfGame ( arr1 , n ) ) NEW_LINE arr2 = [ 2 , 2 , 2 , 2 ] NEW_LINE n = len ( arr2 ) NEW_LINE print ( optimalStrategyOfGame ( arr2 , n ) ) NEW_LINE arr3 = [ 20 , 30 , 2 , 2 , 2 , 10 ] NEW_LINE n = len ( arr3 ) NEW_LINE print ( optimalStrategyOfGame ( arr3 , n ) ) NEW_LINE |
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 ] + arr [ i ] ) : NEW_LINE INDENT msis [ i ] = msis [ j ] + arr [ i ] NEW_LINE DEDENT DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if max < msis [ i ] : NEW_LINE INDENT max = msis [ i ] NEW_LINE DEDENT DEDENT return max NEW_LINE DEDENT arr = [ 1 , 101 , 2 , 3 , 100 , 4 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Sum β of β maximum β sum β increasing β " + " subsequence β is β " + str ( maxSumIS ( arr , n ) ) ) NEW_LINE |
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 the range ; Store the first element of G . P . series in the variable temp ; Return position of middle element of the G . P . series if the first element is in G . P . of common ratio k ; Else return 0 ; if middle element is not found in arr [ ] ; Driver Code ; Given array | 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 * ( Sum // R ) NEW_LINE for i in range ( 1 , N - 1 ) : NEW_LINE INDENT temp += arr [ i - 1 ] NEW_LINE if ( arr [ i ] == Mid ) : NEW_LINE INDENT if ( temp == Mid // k ) : NEW_LINE INDENT return i + 1 NEW_LINE DEDENT else : NEW_LINE INDENT return 0 NEW_LINE DEDENT DEDENT DEDENT return 0 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 1 , 4 , 20 , 6 , 15 , 9 , 10 ] NEW_LINE N = len ( arr ) NEW_LINE K = 2 NEW_LINE print ( checkArray ( arr , N , K ) ) NEW_LINE DEDENT |
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 between 0 and 9 ; If str [ i ] is between a and z ; If str [ i ] is between A and Z ; Iterate over the range ; If str [ i ] is between a and z and i is the last occurence in str ; If str [ i ] is between A and Z and i is the last occurence in str ; If str [ i ] is between 0 and 9 and i is the last occurence in str ; Print the result ; Driver Code | 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 INDENT num [ ord ( str [ i ] ) - 48 ] = i NEW_LINE DEDENT elif ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) : NEW_LINE INDENT small [ ord ( str [ i ] ) - 97 ] = i NEW_LINE DEDENT elif ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) : NEW_LINE INDENT capital [ ord ( str [ i ] ) - 65 ] = i NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT if ( ( str [ i ] >= ' a ' and str [ i ] <= ' z ' ) and small [ ord ( str [ i ] ) - 97 ] == i ) : NEW_LINE INDENT occ = ord ( str [ i ] ) - 96 NEW_LINE while ( occ > 0 ) : NEW_LINE INDENT res += str [ i ] NEW_LINE occ -= 1 NEW_LINE DEDENT DEDENT elif ( ( str [ i ] >= ' A ' and str [ i ] <= ' Z ' ) and capital [ ord ( str [ i ] ) - 65 ] == i ) : NEW_LINE INDENT occ = ord ( str [ i ] ) - 64 NEW_LINE while ( occ > 0 ) : NEW_LINE INDENT res += str [ i ] NEW_LINE occ -= 1 NEW_LINE DEDENT DEDENT elif ( ( str [ i ] >= '0' and str [ i ] <= '9' ) and num [ ord ( str [ i ] ) - 48 ] == i ) : NEW_LINE INDENT occ = ord ( str [ i ] ) - 48 NEW_LINE while ( occ > 0 ) : NEW_LINE INDENT res += str [ i ] NEW_LINE occ -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT res += str [ i ] NEW_LINE DEDENT DEDENT print ( res ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = " Ea2 , β 0 , β E " NEW_LINE encodeString ( str ) NEW_LINE DEDENT |
Make Array elements equal by replacing adjacent elements with their XOR | Function to check if it is possible to make all the array elements equal using the given operation ; Stores the 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 divide the array into three non empty subarrays ; XOR of Middle Block ; XOR of Left Block ; XOR of Right Block ; Not Possible ; Driver Code ; Function Call | 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 cur_xor = 0 NEW_LINE i = N - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT cur_xor ^= A [ i ] NEW_LINE for j in range ( i ) : NEW_LINE INDENT if ( j ) : NEW_LINE INDENT middle_xor = pref [ j - 1 ] ^ pref [ i - 1 ] NEW_LINE left_xor = pref [ j - 1 ] NEW_LINE right_xor = cur_xor NEW_LINE if ( left_xor == middle_xor and middle_xor == right_xor ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE return NEW_LINE DEDENT DEDENT DEDENT i -= 1 NEW_LINE DEDENT print ( " NO " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 0 , 2 , 2 ] NEW_LINE N = len ( A ) NEW_LINE possibleEqualArray ( A , N ) 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 INDENT N = 4 NEW_LINE X = 3 NEW_LINE print ( " The β generated β array β is β " , end = " " ) NEW_LINE GenerateArray ( N , X ) NEW_LINE DEDENT |
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 ; Driver Code | 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 % 2 == 0 ) : NEW_LINE INDENT is1 = True if is1 == False else False NEW_LINE DEDENT DEDENT DEDENT def testGrid ( testGrid , Grid , N , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT if ( Grid [ i ] [ j ] != ' * ' ) : NEW_LINE INDENT if ( Grid [ i ] [ j ] != testGrid [ i ] [ j ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def printGrid ( grid , N , M ) : NEW_LINE INDENT for i in range ( N ) : NEW_LINE INDENT for j in range ( M ) : NEW_LINE INDENT print ( grid [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT print ( " " , end β = β " " ) NEW_LINE DEDENT DEDENT def findPossibleGrid ( N , M , grid ) : NEW_LINE INDENT gridTest1 = [ [ ' ' for i in range ( 1001 ) ] for j in range ( N ) ] NEW_LINE gridTest2 = [ [ ' ' for i in range ( 1001 ) ] for j in range ( N ) ] NEW_LINE createGrid ( gridTest1 , True , N , M ) NEW_LINE createGrid ( gridTest2 , False , N , M ) NEW_LINE if ( testGrid ( gridTest1 , grid , N , M ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE printGrid ( gridTest1 , N , M ) NEW_LINE DEDENT elif ( testGrid ( gridTest2 , grid , N , M ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE printGrid ( gridTest2 , N , M ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 4 NEW_LINE M = 4 NEW_LINE grid = [ [ ' * ' , ' * ' , '1' , '0' ] , [ ' * ' , ' * ' , ' * ' , ' * ' ] , [ ' * ' , ' * ' , ' * ' , ' * ' ] , [ ' * ' , ' * ' , '0' , '1' ] ] NEW_LINE findPossibleGrid ( N , M , grid ) NEW_LINE DEDENT |
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 other indices . ; Driver Code | 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 sys . exit ( ) NEW_LINE DEDENT for i in range ( l , arr [ ind ] // 2 + 1 , 1 ) : NEW_LINE INDENT if ( arr [ ind ] - i <= r ) : NEW_LINE INDENT brr [ ind ] = i NEW_LINE brr [ n - ind - 1 ] = arr [ ind ] - i NEW_LINE brute ( ind + 1 , i , arr [ ind ] - i ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 2 NEW_LINE n *= 2 NEW_LINE arr [ 0 ] = 5 NEW_LINE arr [ 1 ] = 6 NEW_LINE INF64 = 1000000000000000000 NEW_LINE brute ( 0 , 0 , INF64 ) NEW_LINE DEDENT |
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 digit i ; Minimum steps to create a number ending with digit i ; If N < SmallestNumber then , return - 1 ; Otherwise , return answer ; Driver Code | 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 ( 1 , 11 , 1 ) : NEW_LINE INDENT num = K * i NEW_LINE SmallestNumber [ num % 10 ] = min ( SmallestNumber [ num % 10 ] , num ) NEW_LINE MinimumSteps [ num % 10 ] = min ( MinimumSteps [ num % 10 ] , i ) NEW_LINE DEDENT if ( N < SmallestNumber [ N % 10 ] ) : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return MinimumSteps [ N % 10 ] NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 42 NEW_LINE K = 7 NEW_LINE print ( minCount ( N , K ) ) NEW_LINE DEDENT |
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 the answer ; Driver Code ; Given input ; Function call | 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 DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 7 , 6 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( countMinSteps ( arr , N ) ) NEW_LINE DEDENT |
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 ( L , R , K ) : NEW_LINE INDENT if ( R - L >= 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT minval = L ^ ( L + 1 ) ^ ( L + 2 ) ^ ( L + 3 ) NEW_LINE return min ( minval , func3 ( L , R , K ) ) NEW_LINE DEDENT def minimumXor ( L , R , K ) : NEW_LINE INDENT if ( K > 4 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT elif ( K == 4 ) : NEW_LINE INDENT return func4 ( L , R , K ) NEW_LINE DEDENT elif ( K == 3 ) : NEW_LINE INDENT return func3 ( L , R , K ) NEW_LINE DEDENT elif ( K == 2 ) : NEW_LINE INDENT return func2 ( L , R , K ) NEW_LINE DEDENT else : NEW_LINE INDENT return L NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L , R , K = 1 , 3 , 3 NEW_LINE print ( minimumXor ( L , R , K ) ) NEW_LINE DEDENT |
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" ; Stores the average ; Stores the count of operations ; Traverse the array arr [ ] ; Update number of moves required to make current element equal to avg ; Update the overall count ; Return the minimum operations required ; Driver Code | 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 += ( arr [ i ] - avg ) NEW_LINE total = max ( max ( abs ( needCount ) , arr [ i ] - avg ) , total ) NEW_LINE DEDENT return total NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE print ( findMinMoves ( arr , N ) ) NEW_LINE DEDENT |
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 ; Print the amount ; Driver Code ; Function call to calculate the amount of coins 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 ] [ siz // 2 ] ) NEW_LINE DEDENT DEDENT mid_odd . sort ( reverse = True ) NEW_LINE for i in range ( len ( mid_odd ) ) : NEW_LINE INDENT if i % 2 == 0 : NEW_LINE INDENT amount = amount + mid_odd [ i ] NEW_LINE DEDENT DEDENT print ( amount ) NEW_LINE DEDENT N = 2 NEW_LINE Arr = [ [ 5 , 2 , 3 , 4 ] , [ 1 , 6 ] ] NEW_LINE find ( N , Arr ) NEW_LINE |
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 t of pattern matched by 1 ; Check if t is equal to m , increment count of total repeated pattern ; Return true if length of total repeated pattern is k ; Update length of the current pattern ; Update count to 1 ; Finally return false if no pattern found ; Driver Code | 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 " NEW_LINE DEDENT DEDENT DEDENT else : NEW_LINE INDENT t = 0 NEW_LINE count = 1 NEW_LINE DEDENT DEDENT return " No " NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 6 , 1 , 3 , 3 , 3 , 3 ] NEW_LINE M = 1 NEW_LINE K = 3 NEW_LINE N = len ( arr ) NEW_LINE print ( checkPattern ( arr , M , K , N ) ) NEW_LINE DEDENT |
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 substring match with prefix ; Update R ; Update Z [ i ] ; Update R ; Update k ; if Z [ k ] is less than remaining interval ; Update Z [ i ] ; Start from R and check manually ; Update R ; Update Z [ i ] ; Update R ; Function to remove all the occurrences of word from str ; Create concatenated string " P $ T " ; Store Z array of concat ; Stores string , str by removing all the occurrences of word from str ; Stores length of word ; Traverse the array , Z [ ] ; if Z [ i + pSize + 1 ] equal to length of word ; Update i ; Driver Code | 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 NEW_LINE DEDENT else : NEW_LINE INDENT k = i - L NEW_LINE if ( Z [ k ] < R - i + 1 ) : NEW_LINE INDENT Z [ i ] = Z [ k ] NEW_LINE DEDENT else : NEW_LINE INDENT L = 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 NEW_LINE DEDENT DEDENT DEDENT DEDENT def goodStr ( st , word ) : NEW_LINE INDENT concat = word + " $ " + st NEW_LINE l = len ( concat ) NEW_LINE Z = [ 0 ] * l NEW_LINE getZarr ( concat , Z ) NEW_LINE res = " " NEW_LINE pSize = len ( word ) NEW_LINE for i in range ( l ) : NEW_LINE INDENT if ( i + pSize < l - 1 and Z [ i + pSize + 1 ] == pSize ) : NEW_LINE INDENT i += pSize - 1 NEW_LINE DEDENT elif ( i < len ( st ) ) : NEW_LINE INDENT res += st [ i ] NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " Z - kmalgorithmkmiskmkmkmhelpfulkminkmsearching " NEW_LINE word = " km " NEW_LINE print ( goodStr ( st , word ) ) NEW_LINE DEDENT |
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 , n1 - n2 ] ; Check if subfrom i to i + n2 is equal to T ; Check if subfrom i to i + n2 is equal to T ; Mark chk as false and break the loop ; If chk is true ; Add ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) to answer ; Update the last to i + 1 ; Prthe answer ; Driver code ; Function Call | 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_LINE DEDENT DEDENT if ( chk ) : NEW_LINE INDENT ans += ( i + 1 - last ) * ( n1 - ( i + n2 - 1 ) ) NEW_LINE last = i + 1 NEW_LINE DEDENT DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S , T = " dabc " , " ab " NEW_LINE findOccurrences ( S , T ) NEW_LINE DEDENT |
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 as 1 ; Stores the resultant sequence ; Store the high value ; Maintain strictly decreasing sequence from index high_index to 0 starting with temp ; Store the value and decrement the temp variable by 1 ; Maintain the strictly decreasing sequence from index high_index + 1 to N - 1 starting with high - 1 ; Store the value and decrement high by 1 ; Print the resultant sequence ; Driver Code ; Function Call | 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 NEW_LINE for i in range ( high_index , - 1 , - 1 ) : NEW_LINE INDENT A [ i ] = temp NEW_LINE temp = temp - 1 NEW_LINE DEDENT high -= 1 NEW_LINE for i in range ( high_index + 1 , N ) : NEW_LINE INDENT A [ i ] = high NEW_LINE high = high - 1 NEW_LINE DEDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT N = 5 NEW_LINE low = 2 NEW_LINE high = 6 NEW_LINE LargestArray ( N , low , high ) NEW_LINE |
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 vector of vectors arr ; Function Call | 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 ( len ( nums ) ) : NEW_LINE INDENT for j in range ( len ( nums [ i ] ) ) : NEW_LINE INDENT v [ i + j ] . append ( nums [ i ] [ j ] ) NEW_LINE DEDENT DEDENT for i in range ( len ( v ) ) : NEW_LINE INDENT v [ i ] = v [ i ] [ : : - 1 ] NEW_LINE for j in range ( len ( v [ i ] ) ) : NEW_LINE INDENT print ( v [ i ] [ j ] , end = " β " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] , [ 7 , 8 , 9 ] ] NEW_LINE printDiagonalTraversal ( arr ) NEW_LINE DEDENT |
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 print ( " No " ) NEW_LINE return NEW_LINE DEDENT x -= 1 NEW_LINE y += 1 NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT str = " abacdaeaafaghaia " NEW_LINE isValid ( str ) NEW_LINE |
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 to return the sum of all resulting strings ; Precompute powers of 10 ; Precompute prefix sum ; Initialize result ; Apply the above general formula for every i ; Return the answer ; Driver Code ; Function Call | 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 def precomputePrefix ( st , n ) : NEW_LINE INDENT pref [ 0 ] = ( ord ( st [ 0 ] ) - ord ( '0' ) ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT pref [ i ] = ( pref [ i - 1 ] + toDigit ( st [ i ] ) ) NEW_LINE DEDENT DEDENT def triangularNumber ( i ) : NEW_LINE INDENT res = i * ( i + 1 ) // 2 NEW_LINE return res NEW_LINE DEDENT def sumOfSubstrings ( st ) : NEW_LINE INDENT n = len ( st ) NEW_LINE powerOf10 ( ) NEW_LINE precomputePrefix ( st , n ) NEW_LINE ans = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT ans += ( ( pref [ n - i - 2 ] * ( i + 1 ) + toDigit ( st [ n - i - 1 ] ) * triangularNumber ( n - i - 1 ) ) * power [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = "1234" NEW_LINE print ( sumOfSubstrings ( st ) ) NEW_LINE 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 INDENT arr = [ 1 , 2 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE sumOfSubarrayProd ( arr , N ) NEW_LINE DEDENT |
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 , 2 ] NEW_LINE print ( OddLengthSum ( arr ) ) NEW_LINE |
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 Code | 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 ) : NEW_LINE INDENT return a if b == 0 else __gcd ( b , a % b ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 13 NEW_LINE if ( sameEulerTotient ( N ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT |
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 ; Function call | 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 INDENT print ( it , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 5 , 2 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE solve ( arr , N ) NEW_LINE DEDENT |
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 string ; Given number in form of string ; Function call | 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 result_str = ( result_str [ : x + 1 ] + ' - ' + result_str [ x + 1 : ] ) NEW_LINE num_str = result_str NEW_LINE x += 1 NEW_LINE DEDENT x += 1 NEW_LINE DEDENT return result_str NEW_LINE DEDENT str = "1745389" NEW_LINE print ( Insert_dash ( str ) ) NEW_LINE |
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 column wise ; Generate an array consisting of elements of the current column ; Driver Code | 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 INDENT f = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( i == n ) : NEW_LINE INDENT return True NEW_LINE DEDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( arr [ j ] > arr [ j - 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 INDENT if ( f == 1 ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT DEDENT return True NEW_LINE DEDENT def check ( arr ) : NEW_LINE INDENT f = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( not checkReverseBitonic ( arr [ i ] , M ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT temp = [ 0 ] * N NEW_LINE for j in range ( N ) : NEW_LINE INDENT temp [ j ] = arr [ j ] [ i ] NEW_LINE DEDENT if ( not checkReverseBitonic ( temp , N ) ) : NEW_LINE INDENT print ( " No " ) NEW_LINE return NEW_LINE DEDENT DEDENT print ( " Yes " ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = [ [ 2 , 3 , 4 ] , [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] NEW_LINE check ( m ) NEW_LINE DEDENT |
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 ) : NEW_LINE INDENT r = x * x NEW_LINE return ( r - y + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT r = ( x - 1 ) * ( x - 1 ) NEW_LINE return ( r + y ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 2 NEW_LINE y = 3 NEW_LINE print ( SpiralElement ( x , y ) ) NEW_LINE DEDENT |
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 find out the differences between consecutive elements and storing them in the set ; Checks if any character of the string disobeys the pattern ; Constructing the strings with all possible values of consecutive difference and comparing them with staring string S . ; Driver code | 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 ) ) : NEW_LINE INDENT difference . add ( ord ( s [ i ] ) - ord ( s [ i - 1 ] ) ) NEW_LINE DEDENT if ( len ( difference ) == 1 ) : NEW_LINE INDENT print ( " No β modifications β required " ) NEW_LINE return NEW_LINE DEDENT for it in difference : NEW_LINE INDENT index = ord ( s [ 0 ] ) - ord ( ' a ' ) NEW_LINE reconstruct = " " NEW_LINE flag = 0 NEW_LINE i = 0 NEW_LINE while ( ( i < len ( s ) ) and ( flag <= 1 ) ) : NEW_LINE INDENT reconstruct += alphabets [ index ] NEW_LINE index += it NEW_LINE if ( index < 0 ) : NEW_LINE INDENT index += 26 NEW_LINE DEDENT index %= 26 NEW_LINE if ( reconstruct [ i ] != s [ i ] ) : NEW_LINE INDENT flag += 1 NEW_LINE hold_i = i NEW_LINE hold_l = s [ i ] NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if ( flag == 1 ) : NEW_LINE INDENT s [ hold_i ] = reconstruct [ hold_i ] NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag > 1 ) : NEW_LINE INDENT hold_i = 0 NEW_LINE hold_l = s [ 0 ] NEW_LINE temp = ( ord ( s [ 1 ] ) - ord ( ' a ' ) - ( ord ( s [ 2 ] ) - ord ( s [ 1 ] ) ) ) % 26 NEW_LINE if ( temp < 0 ) : NEW_LINE INDENT temp += 26 NEW_LINE DEDENT s [ 0 ] = alphabets [ temp ] NEW_LINE DEDENT print ( hold_i , " - > " , hold_l ) NEW_LINE print ( " " . join ( s ) ) NEW_LINE DEDENT s = list ( " aeimqux " ) NEW_LINE string_modify ( s ) NEW_LINE |
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 consecutive even ; Given order of matrix ; Function call | 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_LINE odd += 2 NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 4 NEW_LINE evenSubMatrix ( N ) NEW_LINE |
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 ; right pointer in the array ; Doing k operations ; Incrementing ans by number of inversions increase due to this swapping ; Driver Code ; Input 1 ; Input 2 | 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_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 ; NEW_LINE K = 3 ; NEW_LINE maximum_inversion ( N , K ) ; NEW_LINE N = 4 ; NEW_LINE K = 1 ; NEW_LINE maximum_inversion ( N , K ) ; NEW_LINE DEDENT |
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 has the least significant set bit ; Otherwise ; Driver code | 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 if ( steps_a > steps_b ) : NEW_LINE INDENT return b NEW_LINE DEDENT if ( steps_a < steps_b ) : NEW_LINE INDENT return a NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT a = 10 NEW_LINE b = 8 NEW_LINE print ( oddFirst ( a , b ) ) 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 string ; If generating desired substrings is not possible ; Driver Code | 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 ] ) - 48 NEW_LINE if ( i + 1 + num > size ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( helper ( s , i + 1 + num ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT s = "123abc4db1c " ; NEW_LINE if ( helper ( s , 0 ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
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 range ( 50 , - 1 , - 1 ) : NEW_LINE INDENT if ( n - N_bonacci [ i ] >= 0 ) : NEW_LINE INDENT ans . append ( N_bonacci [ i ] ) NEW_LINE n -= N_bonacci [ i ] NEW_LINE DEDENT DEDENT if ( len ( ans ) == 1 ) : NEW_LINE INDENT ans . append ( 0 ) NEW_LINE DEDENT print ( len ( ans ) ) NEW_LINE for i in ans : NEW_LINE INDENT print ( i , end = " , β " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 21 NEW_LINE k = 5 NEW_LINE N_bonacci_nums ( n , k ) NEW_LINE DEDENT |
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 Call | 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 solve ( n , k ) ; 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 INDENT return True ; NEW_LINE DEDENT for j in range ( i + 1 , len ( s ) ) : NEW_LINE INDENT if ( s [ j ] < s [ j - 1 ] ) : NEW_LINE INDENT continue ; NEW_LINE DEDENT if ( s [ j ] >= s [ j - 1 ] ) : NEW_LINE INDENT break ; NEW_LINE DEDENT DEDENT i = j ; NEW_LINE if ( i != len ( s ) - 1 ) : NEW_LINE INDENT return False ; NEW_LINE DEDENT return True ; NEW_LINE DEDENT s = " abcdfgcba " NEW_LINE if ( checkBitonic ( s ) ) : NEW_LINE INDENT print ( " YES " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " NO " ) NEW_LINE DEDENT |
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 ; Stores the index chosen to distribute its element ; Traverse the array cyclically and find the index whose element was distributed ; If any index has its value reduced to 0 ; Index whose element was distributed ; Store the number of increments at the starting index ; Print the original array ; Driver Code | 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 start = i NEW_LINE break NEW_LINE DEDENT a [ i ] -= 1 NEW_LINE ctr += 1 NEW_LINE i = ( i - 1 + n ) % n NEW_LINE DEDENT a [ start ] = ctr NEW_LINE print ( * a , sep = ' , β ' ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE P = 2 NEW_LINE arr = [ 3 , 2 , 0 , 2 , 7 ] NEW_LINE findArray ( arr , N , P ) NEW_LINE DEDENT |
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 over every pattern of the array ; Index of the first " * " ; Index of Last " * " ; Iterate over the first " * " ; Prefix till first most * without conflicts ; Iterate till last most * from last ; Make suffix till last most * without conflicts ; Take all middle characters in between first and last most * ; Driver Code ; Take all the strings ; Method for finding common string | 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 INDENT if ( pref [ z ] != S [ i ] [ z ] ) : NEW_LINE INDENT return " * " NEW_LINE DEDENT DEDENT DEDENT for z in range ( len ( pref ) , first ) : NEW_LINE INDENT pref += S [ i ] [ z ] ; NEW_LINE DEDENT for z in range ( len ( suff ) ) : NEW_LINE INDENT if ( len ( S [ i ] ) - 1 - z > last ) : NEW_LINE INDENT if ( suff [ z ] != S [ i ] [ len ( S [ i ] ) - 1 - z ] ) : NEW_LINE INDENT return " * " NEW_LINE DEDENT DEDENT DEDENT for z in range ( len ( suff ) , len ( S [ i ] ) - 1 - last ) : NEW_LINE INDENT suff += S [ i ] [ len ( S [ i ] ) - 1 - z ] NEW_LINE DEDENT for z in range ( first , last + 1 ) : NEW_LINE INDENT if ( S [ i ] [ z ] != ' * ' ) : NEW_LINE INDENT mid += S [ i ] [ z ] NEW_LINE DEDENT DEDENT DEDENT suff = suff [ : : - 1 ] NEW_LINE return pref + mid + suff NEW_LINE DEDENT N = 3 NEW_LINE s = [ " " for i in range ( N ) ] NEW_LINE s [ 0 ] = " pq * du * q " NEW_LINE s [ 1 ] = " pq * abc * q " NEW_LINE s [ 2 ] = " p * d * q " NEW_LINE print ( find ( s , N ) ) NEW_LINE |
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_LINE DEDENT return 0 NEW_LINE DEDENT if ( i >= 3 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT if ( j > k2 ) : NEW_LINE INDENT k1 += gap NEW_LINE k2 += gap NEW_LINE DEDENT if ( j >= k1 and j <= k2 or i == 2 ) : NEW_LINE INDENT print ( " * " , end = " " ) NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT else : NEW_LINE INDENT print ( " β " , end = " " ) NEW_LINE DEDENT if ( printPattern ( i , j + 1 , n ) == 1 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT print ( ) NEW_LINE return ( printPattern ( i + 1 , 0 , n ) ) NEW_LINE DEDENT N = 3 NEW_LINE printPattern ( 0 , 0 , N * 5 ) NEW_LINE |
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 transition to D if the character is 0 ; Function for transition state C ; Function for transition state D ; State transition to D if the character is 1 ; State transition to E if the character is 0 ; Function for transition state E ; State transition to E if the character is 0 ; State transition to F if the character is 1 ; Function for transition state F ; State transition to D if the character is 1 ; State transition to E if the character is 0 ; Driver code | 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 : NEW_LINE INDENT if ( n [ 0 ] == '1' ) : NEW_LINE INDENT stateC ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateD ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT DEDENT def stateC ( n ) : NEW_LINE INDENT print ( " String β accepted " ) NEW_LINE DEDENT def stateD ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " string β not β accepted " ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n [ 0 ] == '1' ) : NEW_LINE INDENT stateD ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateE ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT DEDENT def stateE ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " string β not β accepted " ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n [ 0 ] == '0' ) : NEW_LINE INDENT stateE ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateF ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT DEDENT def stateF ( n ) : NEW_LINE INDENT if ( len ( n ) == 0 ) : NEW_LINE INDENT print ( " string β accepred " ) NEW_LINE DEDENT else : NEW_LINE INDENT if ( n [ 0 ] == '1' ) : NEW_LINE INDENT stateD ( n [ 1 : ] ) NEW_LINE DEDENT else : NEW_LINE INDENT stateE ( n [ 1 : ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = "0100101" NEW_LINE checkstateA ( n ) NEW_LINE DEDENT |
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 INDENT print ( " No " ) NEW_LINE DEDENT DEDENT S = " papa " NEW_LINE check_string_exist ( S ) 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_LINE INDENT p = 1 NEW_LINE for i in range ( l , r + 1 ) : NEW_LINE INDENT p = p * getProduct ( i ) NEW_LINE DEDENT return p NEW_LINE DEDENT DEDENT l = 11 NEW_LINE r = 15 NEW_LINE print ( productinRange ( l , r ) , end = ' ' ) NEW_LINE l = 1 NEW_LINE r = 15 NEW_LINE print ( productinRange ( l , r ) ) NEW_LINE |
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 the same row of the qwerty keypad ; Driver Code | 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 ' , ' p ' ] NEW_LINE third_row = [ ' A ' , ' S ' , ' D ' , ' F ' , ' G ' , ' H ' , ' J ' , ' K ' , ' L ' , ' ; ' , ' : ' , ' a ' , ' s ' , ' d ' , ' f ' , ' g ' , ' h ' , ' j ' , ' k ' , ' l ' ] NEW_LINE fourth_row = [ ' Z ' , ' X ' , ' C ' , ' V ' , ' B ' , ' N ' , ' M ' , ' , ' , ' . ' , ' / ' , ' z ' , ' x ' , ' c ' , ' v ' , ' b ' , ' n ' , ' m ' ] NEW_LINE if ( first_row . count ( x ) > 0 ) : NEW_LINE INDENT return 1 NEW_LINE DEDENT elif ( second_row . count ( x ) > 0 ) : NEW_LINE INDENT return 2 NEW_LINE DEDENT elif ( third_row . count ( x ) > 0 ) : NEW_LINE INDENT return 3 NEW_LINE DEDENT elif ( fourth_row . count ( x ) > 0 ) : NEW_LINE INDENT return 4 NEW_LINE DEDENT return 0 NEW_LINE DEDENT def checkValidity ( str ) : NEW_LINE INDENT x = str [ 0 ] NEW_LINE row = checkQwertyRow ( x ) NEW_LINE for i in range ( len ( str ) ) : NEW_LINE INDENT x = str [ i ] NEW_LINE if ( row != checkQwertyRow ( x ) ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT str = " GeeksforGeeks " NEW_LINE if ( checkValidity ( str ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
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 code | 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_LINE INDENT f = ( f0 + f1 ) % 60 NEW_LINE f0 = f1 NEW_LINE f1 = f NEW_LINE DEDENT s = f1 - 1 NEW_LINE return ( s ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT m = 10087887 NEW_LINE n = 2983097899 NEW_LINE final = fib ( n ) - fib ( m - 1 ) NEW_LINE print ( final % 10 ) NEW_LINE DEDENT |
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 ; increment by 710 ; Driver Code ; Function Call | 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 ) ) , " " ) ; NEW_LINE num += 1 ; NEW_LINE Xi += 710 ; NEW_LINE N = N - 1 ; NEW_LINE DEDENT DEDENT N = 5 ; NEW_LINE printSinX ( N ) NEW_LINE |
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 all the sum stored in A ; If there is no such element print - 1 ; Driver Code ; Function call | 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 INDENT A . append ( sum ) NEW_LINE sum = 0 NEW_LINE DEDENT else : NEW_LINE INDENT sum += arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( len ( A ) ) : NEW_LINE INDENT print ( A [ i ] , end = ' β ' ) NEW_LINE DEDENT if ( len ( A ) == 0 ) : NEW_LINE INDENT print ( " - 1" ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 0 , 3 , 4 , 0 , 4 , 4 , 0 , 2 , 1 , 4 , 0 , 3 ] NEW_LINE N = len ( arr ) NEW_LINE sumBetweenZero ( arr , N ) NEW_LINE DEDENT |
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 frequency ; Find the maximum length on the basis of two cases in the approach ; Driver Code ; Function call | 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 DEDENT print ( max ( min ( distinct_size , maxFreq - 1 ) , min ( distinct_size - 1 , maxFreq ) ) ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 4 , 4 , 4 , 4 , 5 ] NEW_LINE N = len ( arr ) NEW_LINE maximumSubsequence ( arr , N ) NEW_LINE DEDENT |
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 ; Adds the length of string if all characters are present ; Return the final result ; Driver code | 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 freq ) : NEW_LINE INDENT flag = False NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag ) : NEW_LINE INDENT res += len ( st ) NEW_LINE DEDENT DEDENT return res NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ " hi " , " data " , " geeksforgeeks " ] NEW_LINE chars = " tiadhae " NEW_LINE print ( countCharacters ( arr , chars ) ) NEW_LINE DEDENT |
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 ; Function to construct the required array ; check if size is multiple of 4 then array exist ; function call to construct array ; Driver code | 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 % 4 == 0 ) : NEW_LINE INDENT arrayConstruct ( N ) NEW_LINE DEDENT else : NEW_LINE INDENT cout << - 1 << endl NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 8 NEW_LINE createArray ( N ) NEW_LINE DEDENT |
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 substring ; check if sum of characters is <= K insert in Hashmap ; Driver code ; initialise string ; initialise weight | 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 INDENT S . add ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return len ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " abcde " NEW_LINE W = "12345678912345678912345678" NEW_LINE K = 5 NEW_LINE N = len ( S ) NEW_LINE print ( distinctSubstring ( S , W , K , N ) ) NEW_LINE DEDENT |
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 digits are present ; If no upper case alphabet is present ; If no lower case alphabet is present ; If no special character is is present ; Check if the string length after adding the required characters is less than 8 ; Add the number of characters to be added ; Driver code | 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 , password ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( not re . search ( upper , password ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( not re . search ( lower , password ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( not re . search ( spChar , password ) ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT if ( ( count + len ( password ) ) < 8 ) : NEW_LINE INDENT count = count + 8 - ( count + len ( password ) ) NEW_LINE DEDENT return count NEW_LINE DEDENT password1 = " Geeksforgeeks " NEW_LINE print ( countCharacters ( password1 ) ) NEW_LINE password2 = " Geeks1" NEW_LINE print ( countCharacters ( password2 ) ) NEW_LINE |
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 ; Add weight to current sum ; Add current character to substring ; If sum of characters is <= K then insert in into the set ; Finding the size of the set ; Driver code | 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 ) : NEW_LINE INDENT S . add ( s ) NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT return len ( S ) NEW_LINE DEDENT P = " abcde " NEW_LINE Q = "12345678912345678912345678" NEW_LINE K = 5 NEW_LINE N = len ( P ) NEW_LINE print ( distinctSubstring ( P , Q , K , N ) ) NEW_LINE |
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 ) ) : NEW_LINE INDENT print ( " * β " , end = " " ) NEW_LINE DEDENT elif ( i == n or ( i == n - 4 and j >= n - ( n - 2 * 4 ) and j <= n + n - 2 * 4 ) ) : NEW_LINE INDENT print ( " * β " , end = " " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " β " + " β " , end = " " ) NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT DEDENT N = 9 NEW_LINE printPattern ( N ) NEW_LINE |
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 ; Driver code | 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 checker = checker | ( 1 << bitAtIndex ) NEW_LINE DEDENT for i in range ( k , len ( s ) ) : NEW_LINE INDENT if ( s [ i - k ] != s [ i ] ) : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT st = " acdeac " NEW_LINE K = 4 NEW_LINE if ( isKAlternating ( st , K ) ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT 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 ; Check divisibility by 2 ; Store the factors twice ; Check for other prime factors other than 2 ; If j is a prime factor ; Store the prime factor twice ; If j is prime number left other than 2 ; Store j twice ; Initialise Matrix M to to store all the factors ; tpc for rows tpr for column ; Initialise M [ 0 ] [ 0 ] = 1 as it also factor of N ; Traversing factor array ; If current and previous factors are not same then move to next row and insert the current factor ; If current and previous factors are same then , Insert the factor with previous factor inserted in matrix M ; The arr1 [ ] and arr2 [ ] used to store all the factors of N ; Initialise arrays as 1 ; Traversing the matrix M print ( " tpr β " , tpr ) ; Traversing till column element doesn 't become 0 ; Store the product of every element of current row with every element in arr1 [ ] ; Copying every element of arr2 [ ] in arr1 [ ] ; length of arr2 [ ] and arr1 [ ] are equal after copying ; Print all the factors ; Drivers Code | 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 //= 2 NEW_LINE DEDENT sqt = math . sqrt ( temp ) NEW_LINE for j in range ( 3 , math . ceil ( sqt ) , 2 ) : NEW_LINE INDENT while ( temp % j == 0 ) : NEW_LINE INDENT factor [ len1 ] = j NEW_LINE len1 += 1 NEW_LINE factor [ len1 ] = j NEW_LINE len1 += 1 NEW_LINE temp //= j NEW_LINE DEDENT DEDENT if ( temp > 2 ) : NEW_LINE INDENT factor [ len1 ] = temp NEW_LINE len1 += 1 NEW_LINE factor [ len1 ] = temp NEW_LINE len1 += 1 NEW_LINE DEDENT M = [ [ 0 for x in range ( MAX ) ] for y in range ( len1 ) ] NEW_LINE tpc , tpr = 0 , 0 NEW_LINE M [ 0 ] [ 0 ] = 1 NEW_LINE j = 1 NEW_LINE while ( j < len1 ) : NEW_LINE INDENT if ( factor [ j ] != factor [ j - 1 ] ) : NEW_LINE INDENT tpr += 1 NEW_LINE M [ tpr ] [ 0 ] = factor [ j ] NEW_LINE j += 1 NEW_LINE tpc = 1 NEW_LINE DEDENT else : NEW_LINE INDENT M [ tpr ] [ tpc ] = M [ tpr ] [ tpc - 1 ] * factor [ j ] NEW_LINE j += 1 NEW_LINE tpc += 1 NEW_LINE DEDENT DEDENT arr1 = [ 0 ] * MAX NEW_LINE arr2 = [ 0 ] * MAX NEW_LINE l1 = l2 = 1 NEW_LINE arr1 [ 0 ] = 1 NEW_LINE arr2 [ 0 ] = 1 NEW_LINE for i in range ( 1 , tpr + 1 ) : NEW_LINE INDENT j = 0 NEW_LINE while M [ i ] [ j ] != 0 : NEW_LINE INDENT for k in range ( l1 ) : NEW_LINE INDENT arr2 [ l2 ] = arr1 [ k ] * M [ i ] [ j ] NEW_LINE l2 += 1 NEW_LINE DEDENT j += 1 NEW_LINE DEDENT for j in range ( l1 , l2 ) : NEW_LINE INDENT arr1 [ j ] = arr2 [ j ] NEW_LINE DEDENT l1 = l2 NEW_LINE DEDENT for i in range ( l2 ) : NEW_LINE INDENT print ( arr2 [ i ] , end = " β " ) NEW_LINE DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT N = 900 NEW_LINE findFactors ( N ) NEW_LINE DEDENT |
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 elements of the matrix can be N itself . ; Assign values at desired place in the matrix ; Loop to add N in the lower half of the matrix such that it contains elements from 1 to 2 * N - 1 ; Loop to print the matrix ; Driver Code | 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 INDENT matrix [ i ] [ i ] = n ; NEW_LINE DEDENT u = n - 1 ; NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT matrix [ i ] [ u ] = i + 1 ; NEW_LINE for j in range ( 1 , n // 2 ) : NEW_LINE INDENT a = ( i + j ) % ( n - 1 ) ; NEW_LINE b = ( i - j + n - 1 ) % ( n - 1 ) ; NEW_LINE if ( a < b ) : NEW_LINE INDENT a , b = b , a NEW_LINE DEDENT matrix [ b ] [ a ] = i + 1 ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( i ) : NEW_LINE INDENT matrix [ i ] [ j ] = matrix [ j ] [ i ] + n ; NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( n ) : NEW_LINE INDENT print ( matrix [ i ] [ j ] , end = " β " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT DEDENT print ( ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 1 ; NEW_LINE printRequiredMatrix ( n ) ; NEW_LINE n = 3 ; NEW_LINE printRequiredMatrix ( n ) ; NEW_LINE n = 6 ; NEW_LINE printRequiredMatrix ( n ) ; NEW_LINE DEDENT |
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 β for β β consecutive β 1' s ; Counting consecutive 1 's ; Counting subarrays of type "10" ; Count consecutive 1 's ; If consecutive 1 ' s β β ends β then β check β for β β consecutive β 0' s ; Count consecutive 0 's ; Update the total count of substrings with minimum of ( cnt0 , cnt1 ) ; Return answer ; Driver code ; Function to print the count of substrings | 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 and S [ j ] == '1' ) : NEW_LINE INDENT cnt1 += 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT while ( i < n and S [ i ] == '1' ) : NEW_LINE INDENT cnt1 += 1 ; NEW_LINE i += 1 ; NEW_LINE DEDENT j = i ; NEW_LINE while ( j < n and S [ j ] == '0' ) : NEW_LINE INDENT cnt0 += 1 ; NEW_LINE j += 1 ; NEW_LINE DEDENT DEDENT ans += min ( cnt0 , cnt1 ) ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = "0001110010" ; NEW_LINE n = len ( S ) ; NEW_LINE print ( countSubstring ( S , n ) ) ; NEW_LINE DEDENT |
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 array in reverse order ; Largest n - digit perfect square ; Driver Code | 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 ] , end = " " ) ; NEW_LINE DEDENT print ( ) ; NEW_LINE DEDENT def nDigitPerfectSquares ( n ) : NEW_LINE INDENT decimal = pow ( ceil ( sqrt ( pow ( 8 , n ) ) ) - 1 , 2 ) ; NEW_LINE decToOctal ( decimal ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 2 ; NEW_LINE nDigitPerfectSquares ( n ) ; NEW_LINE DEDENT |
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 [ n - 1 ] to length ; Driver Code | 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 ( 1 , n ) : NEW_LINE INDENT reverseStr ( s , A [ i - 1 ] , A [ i ] ) NEW_LINE DEDENT reverseStr ( s , A [ n - 1 ] , len ( s ) ) NEW_LINE DEDENT s = " abcdefgh " NEW_LINE s = [ i for i in s ] NEW_LINE A = [ 2 , 4 , 6 ] NEW_LINE n = len ( A ) NEW_LINE reverseString ( s , A , n ) NEW_LINE print ( " " . join ( s ) ) NEW_LINE |
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 , k ) ) ; NEW_LINE DEDENT |
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 DEDENT if cnt == 0 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT return cnt NEW_LINE DEDENT str = "0100110101" NEW_LINE n = len ( str ) NEW_LINE print ( maxSubStr ( str , n ) ) NEW_LINE |
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 contain same characters in same order ; Get the first character of both strings ; Now if there are adjacent similar character remove that character from s1 ; Now if there are adjacent similar character remove that character from s2 ; If both the strings are equal then return true ; Driver code | 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 DEDENT for i in range ( 1 , len ( s2 ) ) : NEW_LINE INDENT if s2 [ i ] != s2 [ i - 1 ] : NEW_LINE INDENT b += getString ( s2 [ i ] ) NEW_LINE DEDENT DEDENT if a == b : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT s1 = " Geeks " NEW_LINE s2 = " Geks " NEW_LINE if solve ( s1 , s2 ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT |
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 ; Print the result ; Driver Code | 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 result = set ( ) ; NEW_LINE result . add ( hash ) ; NEW_LINE for i in range ( l , len ( s ) ) : NEW_LINE INDENT hash = ( ( hash - pow_l * ( ord ( s [ i - l ] ) - 97 ) + 2 * mod ) * x + ( ord ( s [ i ] ) - 97 ) ) % mod ; NEW_LINE result . add ( hash ) ; NEW_LINE DEDENT print ( len ( result ) ) ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = " abcba " ; NEW_LINE l = 2 ; NEW_LINE CntSubstr ( s , l ) ; NEW_LINE DEDENT |
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 to return the count of required str1ings ; If current str1ing ends with the given pattern ; Driver code | 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 INDENT return False NEW_LINE DEDENT patLen -= 1 NEW_LINE str1Len -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT def countOfstr1ings ( pat , n , sArr ) : NEW_LINE INDENT count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( endsWith ( sArr [ i ] , pat ) == True ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT DEDENT return count NEW_LINE DEDENT pat = " ks " NEW_LINE n = 4 NEW_LINE sArr = [ " geeks " , " geeksforgeeks " , " games " , " unit " ] NEW_LINE print ( countOfstr1ings ( pat , n , sArr ) ) NEW_LINE |
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 sub - str1ing of consecutive characters from str1 ; Valid sub - str1ing exists from index i to end ; Update the Length ; Driver code | 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_LINE DEDENT DEDENT return i - 1 NEW_LINE DEDENT def largestSubstr1 ( str1 , n ) : NEW_LINE INDENT Len = 0 NEW_LINE i = 0 NEW_LINE while ( i < n ) : NEW_LINE INDENT end = getEndingIndex ( str1 , n , i ) NEW_LINE Len = max ( end - i + 1 , Len ) NEW_LINE i = end + 1 NEW_LINE DEDENT return Len NEW_LINE DEDENT str1 = " abcabcdefabc " NEW_LINE n = len ( str1 ) NEW_LINE print ( largestSubstr1 ( str1 , n ) ) NEW_LINE |
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 = 3 NEW_LINE print ( getSum ( n , d ) ) NEW_LINE DEDENT |
Subsets and Splits