text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Newman Shanks Williams prime | CPP Program to find Newman Shanks Williams prime ; return nth Newman Shanks Williams prime ; Base case ; Finding nth Newman Shanks Williams prime ; Driver Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nswp ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = dp [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) dp [ i ] = 2 * dp [ i - 1 ] + dp [ i - 2 ] ; return dp [ n ] ; } int main ( ) { int n = 3 ; cout << nswp ( n ) << endl ; return 0 ; } |
Number of ways to insert a character to increase the LCS by one | CPP Program to Number of ways to insert a character to increase LCS by one ; Return the Number of ways to insert a character to increase the Longest Common Subsequence by one ; Insert all positions of all characters in string B . ; Longest Common Subsequence ; Longest Common Subsequence from reverse ; inserting character between position i and i + 1 ; Driver Program | #include <bits/stdc++.h> NEW_LINE #define MAX 256 NEW_LINE using namespace std ; int numberofways ( string A , string B , int N , int M ) { vector < int > pos [ MAX ] ; for ( int i = 0 ; i < M ; i ++ ) pos [ B [ i ] ] . push_back ( i + 1 ) ; int dpl [ N + 2 ] [ M + 2 ] ; memset ( dpl , 0 , sizeof ( dpl ) ) ; for ( int i = 1 ; i <= N ; i ++ ) { for ( int j = 1 ; j <= M ; j ++ ) { if ( A [ i - 1 ] == B [ j - 1 ] ) dpl [ i ] [ j ] = dpl [ i - 1 ] [ j - 1 ] + 1 ; else dpl [ i ] [ j ] = max ( dpl [ i - 1 ] [ j ] , dpl [ i ] [ j - 1 ] ) ; } } int LCS = dpl [ N ] [ M ] ; int dpr [ N + 2 ] [ M + 2 ] ; memset ( dpr , 0 , sizeof ( dpr ) ) ; for ( int i = N ; i >= 1 ; i -- ) { for ( int j = M ; j >= 1 ; j -- ) { if ( A [ i - 1 ] == B [ j - 1 ] ) dpr [ i ] [ j ] = dpr [ i + 1 ] [ j + 1 ] + 1 ; else dpr [ i ] [ j ] = max ( dpr [ i + 1 ] [ j ] , dpr [ i ] [ j + 1 ] ) ; } } int ans = 0 ; for ( int i = 0 ; i <= N ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { for ( auto x : pos [ j ] ) { if ( dpl [ i ] [ x - 1 ] + dpr [ i + 1 ] [ x + 1 ] == LCS ) { ans ++ ; break ; } } } } return ans ; } int main ( ) { string A = " aa " , B = " baaa " ; int N = A . length ( ) , M = B . length ( ) ; cout << numberofways ( A , B , N , M ) << endl ; return 0 ; } |
Minimum cost to make two strings identical by deleting the digits | C ++ code to find minimum cost to make two strings identical ; Function to returns cost of removing the identical characters in 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 cost of removing identical characters in LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; If both characters are same , add both of them ; Otherwise find the maximum cost among them ; Returns cost of making X [ ] and Y [ ] identical ; Find LCS of X [ ] and Y [ ] ; Initialize the cost variable ; Find cost of all characters in both strings ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( char * X , char * Y , int m , int n ) { int L [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; ++ i ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 2 * ( X [ i - 1 ] - '0' ) ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } int findMinCost ( char X [ ] , char Y [ ] ) { int m = strlen ( X ) , n = strlen ( Y ) ; int cost = 0 ; for ( int i = 0 ; i < m ; ++ i ) cost += X [ i ] - '0' ; for ( int i = 0 ; i < n ; ++ i ) cost += Y [ i ] - '0' ; return cost - lcs ( X , Y , m , n ) ; } int main ( ) { char X [ ] = "3759" ; char Y [ ] = "9350" ; cout << " Minimum β Cost β to β make β two β strings β " << " identical β is β = β " << findMinCost ( X , Y ) ; return 0 ; } |
Given a large number , check if a subsequence of digits is divisible by 8 | C ++ program to check if a subsequence of digits is divisible by 8. ; Function to calculate any permutation divisible by 8. If such permutation exists , the function will return that permutation else it will return - 1 ; Converting string to integer array for ease of computations ( Indexing in arr [ ] is considered to be starting from 1 ) ; Generating all possible permutations and checking if any such permutation is divisible by 8 ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubSeqDivisible ( string str ) { int l = str . length ( ) ; int arr [ l ] ; for ( int i = 0 ; i < l ; i ++ ) arr [ i ] = str [ i ] - '0' ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = i ; j < l ; j ++ ) { for ( int k = j ; k < l ; k ++ ) { if ( arr [ i ] % 8 == 0 ) return true ; else if ( ( arr [ i ] * 10 + arr [ j ] ) % 8 == 0 && i != j ) return true ; else if ( ( arr [ i ] * 100 + arr [ j ] * 10 + arr [ k ] ) % 8 == 0 && i != j && j != k && i != k ) return true ; } } } return false ; } int main ( ) { string str = "3144" ; if ( isSubSeqDivisible ( str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Given a large number , check if a subsequence of digits is divisible by 8 | C ++ program to find if there is a subsequence of digits divisible by 8. ; Function takes in an array of numbers , dynamically goes on the location and makes combination of numbers . ; Converting string to integer array for ease of computations ( Indexing in arr [ ] is considered to be starting from 1 ) ; If we consider the number in our combination , we add it to the previous combination ; If we exclude the number from our combination ; If at dp [ i ] [ 0 ] , we find value 1 / true , it shows that the number exists at the value of ' i ' ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubSeqDivisible ( string str ) { int n = str . length ( ) ; int dp [ n + 1 ] [ 10 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; int arr [ n + 1 ] ; for ( int i = 1 ; i <= n ; i ++ ) arr [ i ] = str [ i - 1 ] - '0' ; for ( int i = 1 ; i <= n ; i ++ ) { dp [ i ] [ arr [ i ] % 8 ] = 1 ; for ( int j = 0 ; j < 8 ; j ++ ) { if ( dp [ i - 1 ] [ j ] > dp [ i ] [ ( j * 10 + arr [ i ] ) % 8 ] ) dp [ i ] [ ( j * 10 + arr [ i ] ) % 8 ] = dp [ i - 1 ] [ j ] ; if ( dp [ i - 1 ] [ j ] > dp [ i ] [ j ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; } } for ( int i = 1 ; i <= n ; i ++ ) { if ( dp [ i ] [ 0 ] == 1 ) return true ; } return false ; } int main ( ) { string str = "3144" ; if ( isSubSeqDivisible ( str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Given a large number , check if a subsequence of digits is divisible by 8 | C ++ program to check if given string has a subsequence divisible by 8 ; Driver function ; map key will be tens place digit of number that is divisible by 8 and value will be units place digit ; For filling the map let start with initial value 8 ; key is digit at tens place and value is digit at units place mp . insert ( { key , value } ) ; Create a hash to check if we visited a number ; Iterate from last index to 0 th index ; If 8 is present in string then 8 divided 8 hence print yes ; considering present character as the second digit of two digits no we check if the value of this key is marked in hash or not If marked then we a have a number divisible by 8 ; If no subsequence divisible by 8 | #include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { string str = "129365" ; map < int , int > mp ; int no = 8 ; while ( no < 100 ) { no = no + 8 ; mp . insert ( { ( no / 10 ) % 10 , no % 10 } ) ; } vector < bool > visited ( 10 , false ) ; int i ; for ( i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '8' ) { cout << " Yes " ; break ; } if ( visited [ mp [ str [ i ] - '0' ] ] ) { cout << " Yes " ; break ; } visited [ str [ i ] - '0' ] = true ; } if ( i == -1 ) cout << " No " ; return 0 ; } |
Length of Longest Balanced Subsequence | C ++ program to find length of the longest balanced subsequence ; Considering all balanced substrings of length 2 ; Considering all other substrings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( char s [ ] , int n ) { int dp [ n ] [ n ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) if ( s [ i ] == ' ( ' && s [ i + 1 ] == ' ) ' ) dp [ i ] [ i + 1 ] = 2 ; for ( int l = 2 ; l < n ; l ++ ) { for ( int i = 0 , j = l ; j < n ; i ++ , j ++ ) { if ( s [ i ] == ' ( ' && s [ j ] == ' ) ' ) dp [ i ] [ j ] = 2 + dp [ i + 1 ] [ j - 1 ] ; for ( int k = i ; k < j ; k ++ ) dp [ i ] [ j ] = max ( dp [ i ] [ j ] , dp [ i ] [ k ] + dp [ k + 1 ] [ j ] ) ; } } return dp [ 0 ] [ n - 1 ] ; } int main ( ) { char s [ ] = " ( ) ( ( ( ( ( ( ) " ; int n = strlen ( s ) ; cout << maxLength ( s , n ) << endl ; return 0 ; } |
Maximum sum bitonic subarray | C ++ implementation to find the maximum sum bitonic subarray ; Function to find the maximum sum bitonic subarray . ; to store the maximum sum bitonic subarray ; Find the longest increasing subarray starting at i . ; Now we know that a [ i . . j ] is an increasing subarray . Remove non - positive elements from the left side as much as possible . ; Find the longest decreasing subarray starting at j . ; Now we know that a [ j . . k ] is a decreasing subarray . Remove non - positive elements from the right side as much as possible . last is needed to keep the last seen element . ; Compute the max sum of the increasing part . ; Compute the max sum of the decreasing part . ; The overall max sum is the sum of both parts minus the peak element , because it was counted twice . ; If the next element is equal to the current , i . e . arr [ i + 1 ] == arr [ i ] , last == i . To ensure the algorithm has progress , get the max of last and i + 1. ; required maximum sum ; Driver program to test above ; The example from the article , the answer is 19. ; Always increasing , the answer is 15. ; Always decreasing , the answer is 15. ; All are equal , the answer is 5. ; The whole array is bitonic , but the answer is 7. ; The answer is 4 ( the tail ) . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumBitonicSubArr ( int arr [ ] , int n ) { int max_sum = INT_MIN ; int i = 0 ; while ( i < n ) { int j = i ; while ( j + 1 < n && arr [ j ] < arr [ j + 1 ] ) j ++ ; while ( i < j && arr [ i ] <= 0 ) i ++ ; int k = j ; while ( k + 1 < n && arr [ k ] > arr [ k + 1 ] ) k ++ ; int last = k ; while ( k > j && arr [ k ] <= 0 ) k -- ; int sum_inc = accumulate ( arr + i , arr + j + 1 , 0 ) ; int sum_dec = accumulate ( arr + j , arr + k + 1 , 0 ) ; int sum_all = sum_inc + sum_dec - arr [ j ] ; max_sum = max ( { max_sum , sum_inc , sum_dec , sum_all } ) ; i = max ( last , i + 1 ) ; } return max_sum ; } int main ( ) { int arr [ ] = { 5 , 3 , 9 , 2 , 7 , 6 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum β Sum β = β " << maxSumBitonicSubArr ( arr , n ) << endl ; int arr2 [ ] = { 1 , 2 , 3 , 4 , 5 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << " Maximum β Sum β = β " << maxSumBitonicSubArr ( arr2 , n2 ) << endl ; int arr3 [ ] = { 5 , 4 , 3 , 2 , 1 } ; int n3 = sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ; cout << " Maximum β Sum β = β " << maxSumBitonicSubArr ( arr3 , n3 ) << endl ; int arr4 [ ] = { 5 , 5 , 5 , 5 } ; int n4 = sizeof ( arr4 ) / sizeof ( arr4 [ 0 ] ) ; cout << " Maximum β Sum β = β " << maxSumBitonicSubArr ( arr4 , n4 ) << endl ; int arr5 [ ] = { -1 , 0 , 1 , 2 , 3 , 1 , 0 , -1 , -10 } ; int n5 = sizeof ( arr5 ) / sizeof ( arr5 [ 0 ] ) ; cout << " Maximum β Sum β = β " << maxSumBitonicSubArr ( arr5 , n5 ) << endl ; int arr6 [ ] = { -1 , 0 , 1 , 2 , 0 , -1 , -2 , 0 , 1 , 3 } ; int n6 = sizeof ( arr6 ) / sizeof ( arr6 [ 0 ] ) ; cout << " Maximum β Sum β = β " << maxSumBitonicSubArr ( arr6 , n6 ) << endl ; return 0 ; } |
Smallest sum contiguous subarray | C ++ implementation to find the smallest sum contiguous subarray ; function to find the smallest sum contiguous subarray ; to store the minimum value that is ending up to the current index ; to store the minimum value encountered so far ; traverse the array elements ; if min_ending_here > 0 , then it could not possibly contribute to the minimum sum further ; else add the value arr [ i ] to min_ending_here ; update min_so_far ; required smallest sum contiguous subarray value ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestSumSubarr ( int arr [ ] , int n ) { int min_ending_here = INT_MAX ; int min_so_far = INT_MAX ; for ( int i = 0 ; i < n ; i ++ ) { if ( min_ending_here > 0 ) min_ending_here = arr [ i ] ; else min_ending_here += arr [ i ] ; min_so_far = min ( min_so_far , min_ending_here ) ; } return min_so_far ; } int main ( ) { int arr [ ] = { 3 , -4 , 2 , -3 , -1 , 7 , -5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Smallest β sum : β " << smallestSumSubarr ( arr , n ) ; return 0 ; } |
n | C ++ code to find nth number with digits 0 , 1 , 2 , 3 , 4 , 5 ; If the Number is less than 6 return the number as it is . ; Call the function again and again the get the desired result . And convert the number to base 6. ; Decrease the Number by 1 and Call ans function to convert N to base 6 ; Driver code | #include <iostream> NEW_LINE using namespace std ; int ans ( int n ) { if ( n < 6 ) { return n ; } return n % 6 + 10 * ( ans ( n / 6 ) ) ; } int getSpecialNumber ( int N ) { return ans ( -- N ) ; } int main ( ) { int N = 17 ; int answer = getSpecialNumber ( N ) ; cout << answer << endl ; return 0 ; } |
Paper Cut into Minimum Number of Squares | Set 2 | C ++ program to find minimum number of squares to cut a paper using Dynamic Programming ; Returns min number of squares needed ; Initializing max values to vertical_min and horizontal_min ; N = 11 & M = 13 is a special case ; If the given rectangle is already a square ; If the answer for the given rectangle is previously calculated return that answer ; The rectangle is cut horizontally and vertically into two parts and the cut with minimum value is found for every recursive call . ; Calculating the minimum answer for the rectangles with width equal to n and length less than m for finding the cut point for the minimum answer ; Calculating the minimum answer for the rectangles with width less than n and length equal to m for finding the cut point for the minimum answer ; Minimum of the vertical cut or horizontal cut to form a square is the answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 300 ; int dp [ MAX ] [ MAX ] ; int minimumSquare ( int m , int n ) { int vertical_min = INT_MAX ; int horizontal_min = INT_MAX ; if ( n == 13 && m == 11 ) return 6 ; if ( m == 13 && n == 11 ) return 6 ; if ( m == n ) return 1 ; if ( dp [ m ] [ n ] ) return dp [ m ] [ n ] ; for ( int i = 1 ; i <= m / 2 ; i ++ ) { horizontal_min = min ( minimumSquare ( i , n ) + minimumSquare ( m - i , n ) , horizontal_min ) ; } for ( int j = 1 ; j <= n / 2 ; j ++ ) { vertical_min = min ( minimumSquare ( m , j ) + minimumSquare ( m , n - j ) , vertical_min ) ; } dp [ m ] [ n ] = min ( vertical_min , horizontal_min ) ; return dp [ m ] [ n ] ; } int main ( ) { int m = 30 , n = 35 ; cout << minimumSquare ( m , n ) ; return 0 ; } |
Number of n | CPP program To calculate Number of n - digits non - decreasing integers Contributed by Parishrut Kushwaha ; Returns factorial of n ; returns nCr ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long int fact ( int n ) { long long int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } long long int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } int main ( ) { int n = 2 ; cout << " Number β of β Non - Decreasing β digits : β " << nCr ( n + 9 , 9 ) ; return 0 ; } |
Painting Fence Algorithm | C ++ program for Painting Fence Algorithm ; Returns count of ways to color k posts using k colors ; There are k ways to color first post ; There are 0 ways for single post to violate ( same color ) and k ways to not violate ( different color ) ; Fill for 2 posts onwards ; Current same is same as previous diff ; We always have k - 1 choices for next post ; Total choices till i . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long countWays ( int n , int k ) { long total = k ; int mod = 1000000007 ; int same = 0 , diff = k ; for ( int i = 2 ; i <= n ; i ++ ) { same = diff ; diff = total * ( k - 1 ) ; diff = diff % mod ; total = ( same + diff ) % mod ; } return total ; } int main ( ) { int n = 3 , k = 2 ; cout << countWays ( n , k ) << endl ; return 0 ; } |
Sum of all substrings of a string representing a number | Set 2 ( Constant Extra Space ) | C ++ program to print sum of all substring of a number represented as a string ; Returns sum of all substring of num ; Here traversing the array in reverse order . Initializing loop from last element . mf is multiplying factor . ; Each time sum is added to its previous sum . Multiplying the three factors as explained above . s [ i ] - '0' is done to convert char to int . ; Making new multiplying factor as explained above . ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sumOfSubstrings ( string num ) { long long int mf = 1 ; for ( int i = num . size ( ) - 1 ; i >= 0 ; i -- ) { sum += ( num [ i ] - '0' ) * ( i + 1 ) * mf ; mf = mf * 10 + 1 ; } return sum ; } int main ( ) { string num = "6759" ; cout << sumOfSubstrings ( num ) << endl ; return 0 ; } |
Largest sum subarray with at | C ++ program to find largest subarray sum with at - least k elements in it . ; Returns maximum sum of a subarray with at - least k elements . ; maxSum [ i ] is going to store maximum sum till index i such that a [ i ] is part of the sum . ; We use Kadane 's algorithm to fill maxSum[] Below code is taken from method 3 of https:www.geeksforgeeks.org/largest-sum-contiguous-subarray/ ; Sum of first k elements ; Use the concept of sliding window ; Compute sum of k elements ending with a [ i ] . ; Update result if required ; Include maximum sum till [ i - k ] also if it increases overall max . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumWithK ( int a [ ] , int n , int k ) { int maxSum [ n ] ; maxSum [ 0 ] = a [ 0 ] ; int curr_max = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { curr_max = max ( a [ i ] , curr_max + a [ i ] ) ; maxSum [ i ] = curr_max ; } int sum = 0 ; for ( int i = 0 ; i < k ; i ++ ) sum += a [ i ] ; int result = sum ; for ( int i = k ; i < n ; i ++ ) { sum = sum + a [ i ] - a [ i - k ] ; result = max ( result , sum ) ; result = max ( result , sum + maxSum [ i - k ] ) ; } return result ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , -10 , -3 } ; int k = 4 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << maxSumWithK ( a , n , k ) ; return 0 ; } |
Ways to sum to N using array elements with repetition allowed | C ++ implementation to count ways to sum up to a given value N ; function to count the total number of ways to sum up to ' N ' ; base case ; count ways for all values up to ' N ' and store the result ; if i >= arr [ j ] then accumulate count for value ' i ' as ways to form value ' i - arr [ j ] ' ; required number of ways ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countWays ( int arr [ ] , int m , int N ) { int count [ N + 1 ] ; memset ( count , 0 , sizeof ( count ) ) ; count [ 0 ] = 1 ; for ( int i = 1 ; i <= N ; i ++ ) for ( int j = 0 ; j < m ; j ++ ) if ( i >= arr [ j ] ) count [ i ] += count [ i - arr [ j ] ] ; return count [ N ] ; } int main ( ) { int arr [ ] = { 1 , 5 , 6 } ; int m = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int N = 7 ; cout << " Total β number β of β ways β = β " << countWays ( arr , m , N ) ; return 0 ; } |
Sequences of given length where every element is more than or equal to twice of previous | C ++ program to count total number of special sequences of length n where ; Recursive function to find the number of special sequences ; A special sequence cannot exist if length n is more than the maximum value m . ; If n is 0 , found an empty special sequence ; There can be two possibilities : ( 1 ) Reduce last element value ( 2 ) Consider last element as m and reduce number of terms ; Driver code | #include <iostream> NEW_LINE using namespace std ; int getTotalNumberOfSequences ( int m , int n ) { if ( m < n ) return 0 ; if ( n == 0 ) return 1 ; return getTotalNumberOfSequences ( m - 1 , n ) + getTotalNumberOfSequences ( m / 2 , n - 1 ) ; } int main ( ) { int m = 10 ; int n = 4 ; cout << " Total β number β of β possible β sequences β " << getTotalNumberOfSequences ( m , n ) ; return 0 ; } |
Sequences of given length where every element is more than or equal to twice of previous | C program to count total number of special sequences of length N where ; DP based function to find the number of special sequences ; define T and build in bottom manner to store number of special sequences of length n and maximum value m ; Base case : If length of sequence is 0 or maximum value is 0 , there cannot exist any special sequence ; if length of sequence is more than the maximum value , special sequence cannot exist ; If length of sequence is 1 then the number of special sequences is equal to the maximum value For example with maximum value 2 and length 1 , there can be 2 special sequences { 1 } , { 2 } ; otherwise calculate ; Driver Code | #include <stdio.h> NEW_LINE int getTotalNumberOfSequences ( int m , int n ) { int T [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i < m + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { if ( i == 0 j == 0 ) T [ i ] [ j ] = 0 ; else if ( i < j ) T [ i ] [ j ] = 0 ; else if ( j == 1 ) T [ i ] [ j ] = i ; else T [ i ] [ j ] = T [ i - 1 ] [ j ] + T [ i / 2 ] [ j - 1 ] ; } } return T [ m ] [ n ] ; } int main ( ) { int m = 10 ; int n = 4 ; printf ( " Total β number β of β possible β sequences β % d " , getTotalNumberOfSequences ( m , n ) ) ; return 0 ; } |
Minimum number of deletions and insertions to transform one string into another | Dynamic Programming C ++ implementation to find minimum number of deletions and insertions ; Returns length of length common subsequence for str1 [ 0. . m - 1 ] , str2 [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of str1 [ 0. . i - 1 ] and str2 [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; function to find minimum number of deletions and insertions ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( string str1 , string str2 , int m , int n ) { int L [ m + 1 ] [ n + 1 ] ; int i , j ; for ( i = 0 ; i <= m ; i ++ ) { for ( j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ i ] [ j ] = 0 ; else if ( str1 . at ( i - 1 ) == str2 . at ( j - 1 ) ) L [ i ] [ j ] = L [ i - 1 ] [ j - 1 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } void printMinDelAndInsert ( string str1 , string str2 ) { int m = str1 . size ( ) ; int n = str2 . size ( ) ; int len = lcs ( str1 , str2 , m , n ) ; cout << " Minimum β number β of β deletions β = β " << ( m - len ) << endl ; cout << " Minimum β number β of β insertions β = β " << ( n - len ) << endl ; } int main ( ) { string str1 = " heap " ; string str2 = " pea " ; printMinDelAndInsert ( str1 , str2 ) ; return 0 ; } |
Minimum number of deletions to make a sorted sequence | C ++ implementation to find minimum number of deletions to make a sorted sequence ; lis ( ) returns the length of the longest increasing subsequence in arr [ ] of size n ; Initialize LIS values for all indexes ; Compute optimized LIS values in bottom up manner ; Pick resultimum of all LIS values ; function to calculate minimum number of deletions ; Find longest increasing subsequence ; After removing elements other than the lis , we get sorted sequence . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lis ( int arr [ ] , int n ) { int result = 0 ; int lis [ n ] ; for ( int i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( result < lis [ i ] ) result = lis [ i ] ; return result ; } int minimumNumberOfDeletions ( int arr [ ] , int n ) { int len = lis ( arr , n ) ; return ( n - len ) ; } int main ( ) { int arr [ ] = { 30 , 40 , 2 , 5 , 1 , 7 , 45 , 50 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Minimum β number β of β deletions β = β " << minimumNumberOfDeletions ( arr , n ) ; return 0 ; } |
Clustering / Partitioning an array such that sum of square differences is minimum | C ++ program to find minimum cost k partitions of array . ; Returns minimum cost of partitioning a [ ] in k clusters . ; Create a dp [ ] [ ] table and initialize all values as infinite . dp [ i ] [ j ] is going to store optimal partition cost for arr [ 0. . i - 1 ] and j partitions ; Fill dp [ ] [ ] in bottom up manner ; Current ending position ( After i - th iteration result for a [ 0. . i - 1 ] is computed . ; j is number of partitions ; Picking previous partition for current i . ; Driver code | #include <iostream> NEW_LINE using namespace std ; const int inf = 1000000000 ; int minCost ( int a [ ] , int n , int k ) { int dp [ n + 1 ] [ k + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= k ; j ++ ) dp [ i ] [ j ] = inf ; dp [ 0 ] [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 1 ; j <= k ; j ++ ) for ( int m = i - 1 ; m >= 0 ; m -- ) dp [ i ] [ j ] = min ( dp [ i ] [ j ] , dp [ m ] [ j - 1 ] + ( a [ i - 1 ] - a [ m ] ) * ( a [ i - 1 ] - a [ m ] ) ) ; return dp [ n ] [ k ] ; } int main ( ) { int k = 2 ; int a [ ] = { 1 , 5 , 8 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << minCost ( a , n , k ) << endl ; return 0 ; } |
Minimum number of deletions to make a string palindrome | C ++ implementation to find minimum number of deletions to make a string palindromic ; Returns the length of the longest palindromic subsequence in ' str ' ; Create a table to store results of subproblems ; Strings of length 1 are palindrome of length 1 ; Build the table . Note that the lower diagonal values of table are useless and not filled in the process . c1 is length of substring ; length of longest palindromic subseq ; function to calculate minimum number of deletions ; Find longest palindromic subsequence ; After removing characters other than the lps , we get palindrome . ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lps ( string str ) { int n = str . size ( ) ; int L [ n ] [ n ] ; for ( int i = 0 ; i < n ; i ++ ) L [ i ] [ i ] = 1 ; for ( int cl = 2 ; cl <= n ; cl ++ ) { for ( int i = 0 ; i < n - cl + 1 ; i ++ ) { int j = i + cl - 1 ; if ( str [ i ] == str [ j ] && cl == 2 ) L [ i ] [ j ] = 2 ; else if ( str [ i ] == str [ j ] ) L [ i ] [ j ] = L [ i + 1 ] [ j - 1 ] + 2 ; else L [ i ] [ j ] = max ( L [ i ] [ j - 1 ] , L [ i + 1 ] [ j ] ) ; } } return L [ 0 ] [ n - 1 ] ; } int minimumNumberOfDeletions ( string str ) { int n = str . size ( ) ; int len = lps ( str ) ; return ( n - len ) ; } int main ( ) { string str = " geeksforgeeks " ; cout << " Minimum β number β of β deletions β = β " << minimumNumberOfDeletions ( str ) ; return 0 ; } |
Temple Offerings | Program to find minimum total offerings required ; Returns minimum offerings required ; Go through all templs one by one ; Go to left while height keeps increasing ; Go to right while height keeps increasing ; This temple should offer maximum of two values to follow the rule . ; Driver code | #include <iostream> NEW_LINE using namespace std ; int offeringNumber ( int n , int templeHeight [ ] ) { for ( int i = 0 ; i < n ; ++ i ) { int left = 0 , right = 0 ; for ( int j = i - 1 ; j >= 0 ; -- j ) { if ( templeHeight [ j ] < templeHeight [ j + 1 ] ) ++ left ; else break ; } for ( int j = i + 1 ; j < n ; ++ j ) { if ( templeHeight [ j ] < templeHeight [ j - 1 ] ) ++ right ; else break ; } sum += max ( right , left ) + 1 ; } return sum ; } int main ( ) { int arr1 [ 3 ] = { 1 , 2 , 2 } ; cout << offeringNumber ( 3 , arr1 ) << " STRNEWLINE " ; int arr2 [ 6 ] = { 1 , 4 , 3 , 6 , 2 , 1 } ; cout << offeringNumber ( 6 , arr2 ) << " STRNEWLINE " ; return 0 ; } |
Subset with sum divisible by m | C ++ program to check if there is a subset with sum divisible by m . ; Returns true if there is a subset of arr [ ] with sum divisible by m ; This array will keep track of all the possible sum ( after modulo m ) which can be made using subsets of arr [ ] initialising boolean array with all false ; we 'll loop through all the elements of arr[] ; anytime we encounter a sum divisible by m , we are done ; To store all the new encountered sum ( after modulo ) . It is used to make sure that arr [ i ] is added only to those entries for which DP [ j ] was true before current iteration . ; For each element of arr [ ] , we loop through all elements of DP table from 1 to m and we add current element i . e . , arr [ i ] to all those elements which are true in DP table ; if an element is true in DP table ; We update it in temp and update to DP once loop of j is over ; Updating all the elements of temp to DP table since iteration over j is over ; Also since arr [ i ] is a single element subset , arr [ i ] % m is one of the possible sum ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool modularSum ( int arr [ ] , int n , int m ) { if ( n > m ) return true ; bool DP [ m ] ; memset ( DP , false , m ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( DP [ 0 ] ) return true ; bool temp [ m ] ; memset ( temp , false , m ) ; for ( int j = 0 ; j < m ; j ++ ) { if ( DP [ j ] == true ) { if ( DP [ ( j + arr [ i ] ) % m ] == false ) temp [ ( j + arr [ i ] ) % m ] = true ; } } for ( int j = 0 ; j < m ; j ++ ) if ( temp [ j ] ) DP [ j ] = true ; DP [ arr [ i ] % m ] = true ; } return DP [ 0 ] ; } int main ( ) { int arr [ ] = { 1 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int m = 5 ; modularSum ( arr , n , m ) ? cout << " YES STRNEWLINE " : cout << " NO STRNEWLINE " ; return 0 ; } |
Maximum sum of a path in a Right Number Triangle | C ++ program to print maximum sum in a right triangle of numbers ; function to find maximum sum path ; Adding the element of row 1 to both the elements of row 2 to reduce a step from the loop ; Traverse remaining rows ; Loop to traverse columns ; tri [ i ] would store the possible combinations of sum of the paths ; array at n - 1 index ( tri [ i ] ) stores all possible adding combination , finding the maximum one out of them ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSum ( int tri [ ] [ 3 ] , int n ) { if ( n > 1 ) tri [ 1 ] [ 1 ] = tri [ 1 ] [ 1 ] + tri [ 0 ] [ 0 ] ; tri [ 1 ] [ 0 ] = tri [ 1 ] [ 0 ] + tri [ 0 ] [ 0 ] ; for ( int i = 2 ; i < n ; i ++ ) { tri [ i ] [ 0 ] = tri [ i ] [ 0 ] + tri [ i - 1 ] [ 0 ] ; tri [ i ] [ i ] = tri [ i ] [ i ] + tri [ i - 1 ] [ i - 1 ] ; for ( int j = 1 ; j < i ; j ++ ) { if ( tri [ i ] [ j ] + tri [ i - 1 ] [ j - 1 ] >= tri [ i ] [ j ] + tri [ i - 1 ] [ j ] ) tri [ i ] [ j ] = tri [ i ] [ j ] + tri [ i - 1 ] [ j - 1 ] ; else tri [ i ] [ j ] = tri [ i ] [ j ] + tri [ i - 1 ] [ j ] ; } } int max = tri [ n - 1 ] [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { if ( max < tri [ n - 1 ] [ i ] ) max = tri [ n - 1 ] [ i ] ; } return max ; } int main ( ) { int tri [ 3 ] [ 3 ] = { { 1 } , { 2 , 1 } , { 3 , 3 , 2 } } ; cout << maxSum ( tri , 3 ) ; return 0 ; } |
Modify array to maximize sum of adjacent differences | C ++ program to get maximum consecutive element difference sum ; Returns maximum - difference - sum with array modifications allowed . ; Initialize dp [ ] [ ] with 0 values . ; for [ i + 1 ] [ 0 ] ( i . e . current modified value is 1 ) , choose maximum from dp [ i ] [ 0 ] + abs ( 1 - 1 ) = dp [ i ] [ 0 ] and dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] ) ; for [ i + 1 ] [ 1 ] ( i . e . current modified value is arr [ i + 1 ] ) , choose maximum from dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) and dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumDifferenceSum ( int arr [ ] , int N ) { int dp [ N ] [ 2 ] ; for ( int i = 0 ; i < N ; i ++ ) dp [ i ] [ 0 ] = dp [ i ] [ 1 ] = 0 ; for ( int i = 0 ; i < ( N - 1 ) ; i ++ ) { dp [ i + 1 ] [ 0 ] = max ( dp [ i ] [ 0 ] , dp [ i ] [ 1 ] + abs ( 1 - arr [ i ] ) ) ; dp [ i + 1 ] [ 1 ] = max ( dp [ i ] [ 0 ] + abs ( arr [ i + 1 ] - 1 ) , dp [ i ] [ 1 ] + abs ( arr [ i + 1 ] - arr [ i ] ) ) ; } return max ( dp [ N - 1 ] [ 0 ] , dp [ N - 1 ] [ 1 ] ) ; } int main ( ) { int arr [ ] = { 3 , 2 , 1 , 4 , 5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << maximumDifferenceSum ( arr , N ) << endl ; return 0 ; } |
Count of strings that can be formed using a , b and c under given constraints | C ++ program to count number of strings of n characters with ; n is total number of characters . bCount and cCount are counts of ' b ' and ' c ' respectively . ; Base cases ; if we had saw this combination previously ; Three cases , we choose , a or b or c In all three cases n decreases by 1. ; A wrapper over countStrUtil ( ) ; Driver code ; Total number of characters | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countStrUtil ( int dp [ ] [ 2 ] [ 3 ] , int n , int bCount = 1 , int cCount = 2 ) { if ( bCount < 0 cCount < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( bCount == 0 && cCount == 0 ) return 1 ; if ( dp [ n ] [ bCount ] [ cCount ] != -1 ) return dp [ n ] [ bCount ] [ cCount ] ; int res = countStrUtil ( dp , n - 1 , bCount , cCount ) ; res += countStrUtil ( dp , n - 1 , bCount - 1 , cCount ) ; res += countStrUtil ( dp , n - 1 , bCount , cCount - 1 ) ; return ( dp [ n ] [ bCount ] [ cCount ] = res ) ; } int countStr ( int n ) { int dp [ n + 1 ] [ 2 ] [ 3 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; return countStrUtil ( dp , n ) ; } int main ( ) { int n = 3 ; cout << countStr ( n ) ; return 0 ; } |
Probability of Knight to remain in the chessboard | C ++ program to find the probability of the Knight to remain inside the chessboard after taking exactly K number of steps ; size of the chessboard ; direction vector for the Knight ; returns true if the knight is inside the chessboard ; Bottom up approach for finding the probability to go out of chessboard . ; dp array ; for 0 number of steps , each position will have probability 1 ; for every number of steps s ; for every position ( x , y ) after s number of steps ; for every position reachable from ( x , y ) ; if this position lie inside the board ; store the result ; return the result ; Driver Code ; number of steps ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 8 NEW_LINE int dx [ ] = { 1 , 2 , 2 , 1 , -1 , -2 , -2 , -1 } ; int dy [ ] = { 2 , 1 , -1 , -2 , -2 , -1 , 1 , 2 } ; bool inside ( int x , int y ) { return ( x >= 0 and x < N and y > = 0 and y < N ) ; } double findProb ( int start_x , int start_y , int steps ) { double dp1 [ N ] [ N ] [ steps + 1 ] ; for ( int i = 0 ; i < N ; ++ i ) for ( int j = 0 ; j < N ; ++ j ) dp1 [ i ] [ j ] [ 0 ] = 1 ; for ( int s = 1 ; s <= steps ; ++ s ) { for ( int x = 0 ; x < N ; ++ x ) { for ( int y = 0 ; y < N ; ++ y ) { double prob = 0.0 ; for ( int i = 0 ; i < 8 ; ++ i ) { int nx = x + dx [ i ] ; int ny = y + dy [ i ] ; if ( inside ( nx , ny ) ) prob += dp1 [ nx ] [ ny ] [ s - 1 ] / 8.0 ; } dp1 [ x ] [ y ] [ s ] = prob ; } } } return dp1 [ start_x ] [ start_y ] [ steps ] ; } int main ( ) { int K = 3 ; cout << findProb ( 0 , 0 , K ) << endl ; return 0 ; } |
Count of subarrays whose maximum element is greater than k | C ++ program to count number of subarrays whose maximum element is greater than K . ; Return number of subarrays whose maximum element is less than or equal to K . ; To store count of subarrays with all elements less than or equal to k . ; Traversing the array . ; If element is greater than k , ignore . ; Counting the subarray length whose each element is less than equal to k . ; Suming number of subarray whose maximum element is less than equal to k . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubarray ( int arr [ ] , int n , int k ) { int s = 0 ; int i = 0 ; while ( i < n ) { if ( arr [ i ] > k ) { i ++ ; continue ; } int count = 0 ; while ( i < n && arr [ i ] <= k ) { i ++ ; count ++ ; } s += ( ( count * ( count + 1 ) ) / 2 ) ; } return ( n * ( n + 1 ) / 2 - s ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int k = 2 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countSubarray ( arr , n , k ) ; return 0 ; } |
Sum of average of all subsets | C ++ program to get sum of average of all subsets ; Returns value of Binomial Coefficient C ( n , k ) ; Calculate value of Binomial Coefficient in bottom up manner ; Base Cases ; Calculate value using previously stored values ; method returns sum of average of all subsets ; Find sum of elements ; looping once for all subset of same size ; each element occurs nCr ( N - 1 , n - 1 ) times while considering subset of size n ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nCr ( int n , int k ) { int C [ n + 1 ] [ k + 1 ] ; int i , j ; for ( i = 0 ; i <= n ; i ++ ) { for ( j = 0 ; j <= min ( i , k ) ; j ++ ) { if ( j == 0 j == i ) C [ i ] [ j ] = 1 ; else C [ i ] [ j ] = C [ i - 1 ] [ j - 1 ] + C [ i - 1 ] [ j ] ; } } return C [ n ] [ k ] ; } double resultOfAllSubsets ( int arr [ ] , int N ) { int sum = 0 ; for ( int i = 0 ; i < N ; i ++ ) sum += arr [ i ] ; for ( int n = 1 ; n <= N ; n ++ ) result += ( double ) ( sum * ( nCr ( N - 1 , n - 1 ) ) ) / n ; return result ; } int main ( ) { int arr [ ] = { 2 , 3 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( int ) ; cout << resultOfAllSubsets ( arr , N ) << endl ; return 0 ; } |
Maximum subsequence sum such that no three are consecutive | C ++ program to find the maximum sum such that no three are consecutive using recursion . ; Returns maximum subsequence sum such that no three elements are consecutive ; Base cases ( process first three elements ) ; Process rest of the elements We have three cases ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int arr [ ] = { 100 , 1000 , 100 , 1000 , 1 } ; int sum [ 10000 ] ; int maxSumWO3Consec ( int n ) { if ( sum [ n ] != -1 ) return sum [ n ] ; if ( n == 0 ) return sum [ n ] = 0 ; if ( n == 1 ) return sum [ n ] = arr [ 0 ] ; if ( n == 2 ) return sum [ n ] = arr [ 1 ] + arr [ 0 ] ; return sum [ n ] = max ( max ( maxSumWO3Consec ( n - 1 ) , maxSumWO3Consec ( n - 2 ) + arr [ n ] ) , arr [ n ] + arr [ n - 1 ] + maxSumWO3Consec ( n - 3 ) ) ; } int main ( ) { int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; memset ( sum , -1 , sizeof ( sum ) ) ; cout << maxSumWO3Consec ( n ) ; return 0 ; } |
Maximum sum of pairs with specific difference | C ++ program to find maximum pair sum whose difference is less than K ; Method to return maximum sum we can get by finding less than K difference pairs ; Sort elements to ensure every i and i - 1 is closest possible pair ; To get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; Case I : Diff of arr [ i ] and arr [ i - 1 ] is less then K , add to maxSum Case II : Diff between arr [ i ] and arr [ i - 1 ] is not less then K , move to next i since with sorting we know , arr [ i ] - arr [ i - 1 ] < rr [ i ] - arr [ i - 2 ] and so on . ; Assuming only positive numbers . ; When a match is found skip this pair ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxSumPair ( int arr [ ] , int N , int k ) { int maxSum = 0 ; sort ( arr , arr + N ) ; for ( int i = N - 1 ; i > 0 ; -- i ) { if ( arr [ i ] - arr [ i - 1 ] < k ) { maxSum += arr [ i ] ; maxSum += arr [ i - 1 ] ; -- i ; } } return maxSum ; } int main ( ) { int arr [ ] = { 3 , 5 , 10 , 15 , 17 , 12 , 9 } ; int N = sizeof ( arr ) / sizeof ( int ) ; int K = 4 ; cout << maxSumPair ( arr , N , K ) ; return 0 ; } |
Count digit groupings of a number with given constraints | C ++ program to count number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Function to find the subgroups ; Terminating Condition ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; Total number of subgroups till current position ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countGroups ( int position , int previous_sum , int length , char * num ) { if ( position == length ) return 1 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num [ i ] - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } return res ; } int main ( ) { char num [ ] = "1119" ; int len = strlen ( num ) ; cout << countGroups ( 0 , 0 , len , num ) ; return 0 ; } |
Count digit groupings of a number with given constraints | C ++ program to count number of ways to group digits of a number such that sum of digits in every subgroup is less than or equal to its immediate right subgroup . ; Maximum length of input number string ; A memoization table to store results of subproblems length of string is 40 and maximum sum will be 9 * 40 = 360. ; Function to find the count of splits with given condition ; Terminating Condition ; If already evaluated for a given sub problem then return the value ; countGroups for current sub - group is 0 ; sum of digits ; Traverse all digits from current position to rest of the length of string ; If forward_sum is greater than the previous sum , then call the method again ; Note : We pass current sum as previous sum ; total number of subgroups till current position ; Driver Code ; Initialize dp table | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 40 ; int dp [ MAX ] [ 9 * MAX + 1 ] ; int countGroups ( int position , int previous_sum , int length , char * num ) { if ( position == length ) return 1 ; if ( dp [ position ] [ previous_sum ] != -1 ) return dp [ position ] [ previous_sum ] ; dp [ position ] [ previous_sum ] = 0 ; int res = 0 ; int sum = 0 ; for ( int i = position ; i < length ; i ++ ) { sum += ( num [ i ] - '0' ) ; if ( sum >= previous_sum ) res += countGroups ( i + 1 , sum , length , num ) ; } dp [ position ] [ previous_sum ] = res ; return res ; } int main ( ) { char num [ ] = "1119" ; int len = strlen ( num ) ; memset ( dp , -1 , sizeof ( dp ) ) ; cout << countGroups ( 0 , 0 , len , num ) ; return 0 ; } |
A Space Optimized DP solution for 0 | C ++ program of a space optimized DP solution for 0 - 1 knapsack problem . ; val [ ] is for storing maximum profit for each weight wt [ ] is for storing weights n number of item W maximum capacity of bag dp [ W + 1 ] to store final result ; array to store final result dp [ i ] stores the profit with KnapSack capacity " i " ; initially profit with 0 to W KnapSack capacity is 0 ; iterate through all items ; traverse dp array from right to left ; above line finds out maximum of dp [ j ] ( excluding ith element value ) and val [ i ] + dp [ j - wt [ i ] ] ( including ith element value and the profit with " KnapSack β capacity β - β ith β element β weight " ) ; Driver program to test the cases | #include <bits/stdc++.h> NEW_LINE using namespace std ; int KnapSack ( int val [ ] , int wt [ ] , int n , int W ) { int dp [ W + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = W ; j >= wt [ i ] ; j -- ) dp [ j ] = max ( dp [ j ] , val [ i ] + dp [ j - wt [ i ] ] ) ; return dp [ W ] ; } int main ( ) { int val [ ] = { 7 , 8 , 4 } , wt [ ] = { 3 , 8 , 6 } , W = 10 , n = 3 ; cout << KnapSack ( val , wt , n , W ) << endl ; return 0 ; } |
Find number of times a string occurs as a subsequence in given string | A Dynamic Programming based C ++ program to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Iterative DP function to find the number of times the second string occurs in the first string , whether continuous or discontinuous ; Create a table to store results of sub - problems ; If first string is empty ; If second string is empty ; Fill lookup [ ] [ ] in bottom up manner ; If last characters are same , we have two options - 1. consider last characters of both strings in solution 2. ignore last character of first string ; If last character are different , ignore last character of first string ; Driver code | #include <iostream> NEW_LINE using namespace std ; int count ( string a , string b ) { int m = a . length ( ) ; int n = b . length ( ) ; int lookup [ m + 1 ] [ n + 1 ] = { { 0 } } ; for ( int i = 0 ; i <= n ; ++ i ) lookup [ 0 ] [ i ] = 0 ; for ( int i = 0 ; i <= m ; ++ i ) lookup [ i ] [ 0 ] = 1 ; for ( int i = 1 ; i <= m ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( a [ i - 1 ] == b [ j - 1 ] ) lookup [ i ] [ j ] = lookup [ i - 1 ] [ j - 1 ] + lookup [ i - 1 ] [ j ] ; else lookup [ i ] [ j ] = lookup [ i - 1 ] [ j ] ; } } return lookup [ m ] [ n ] ; } int main ( ) { string a = " GeeksforGeeks " ; string b = " Gks " ; cout << count ( a , b ) ; return 0 ; } |
Longest Geometric Progression | C ++ program to find length of the longest geometric progression in a given set ; Returns length of the longest GP subset of set [ ] ; Base cases ; Let us sort the set first ; An entry L [ i ] [ j ] in this table stores LLGP with set [ i ] and set [ j ] as first two elements of GP and j > i . ; Initialize result ( A single element is always a GP ) ; Initialize values of last column ; Consider every element as second element of GP ; Search for i and k for j ; Two cases when i , j and k don 't form a GP. ; i , j and k form GP , LLGP with i and j as first two elements is equal to LLGP with j and k as first two elements plus 1. L [ j ] [ k ] must have been filled before as we run the loop from right side ; Update overall LLGP ; Change i and k to fill more L [ i ] [ j ] values for current j ; If the loop was stopped due to k becoming more than n - 1 , set the remaining entries in column j as 1 or 2 based on divisibility of set [ j ] by set [ i ] ; Return result ; Driver code | #include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; int lenOfLongestGP ( int set [ ] , int n ) { if ( n < 2 ) return n ; if ( n == 2 ) return ( set [ 1 ] % set [ 0 ] == 0 ) ? 2 : 1 ; sort ( set , set + n ) ; int L [ n ] [ n ] ; int llgp = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( set [ n - 1 ] % set [ i ] == 0 ) { L [ i ] [ n - 1 ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else { L [ i ] [ n - 1 ] = 1 ; } } L [ n - 1 ] [ n - 1 ] = 1 ; for ( int j = n - 2 ; j >= 1 ; -- j ) { int i = j - 1 , k = j + 1 ; while ( i >= 0 && k <= n - 1 ) { if ( set [ i ] * set [ k ] < set [ j ] * set [ j ] ) { ++ k ; } else if ( set [ i ] * set [ k ] > set [ j ] * set [ j ] ) { if ( set [ j ] % set [ i ] == 0 ) { L [ i ] [ j ] = 2 ; } else { L [ i ] [ j ] = 1 ; } -- i ; } else { if ( set [ j ] % set [ i ] == 0 ) { L [ i ] [ j ] = L [ j ] [ k ] + 1 ; if ( L [ i ] [ j ] > llgp ) llgp = L [ i ] [ j ] ; } else { L [ i ] [ j ] = 1 ; } -- i ; ++ k ; } } while ( i >= 0 ) { if ( set [ j ] % set [ i ] == 0 ) { L [ i ] [ j ] = 2 ; if ( 2 > llgp ) llgp = 2 ; } else L [ i ] [ j ] = 1 ; -- i ; } } return llgp ; } int main ( ) { int set1 [ ] = { 1 , 3 , 9 , 27 , 81 , 243 } ; int n1 = sizeof ( set1 ) / sizeof ( set1 [ 0 ] ) ; cout << lenOfLongestGP ( set1 , n1 ) << " STRNEWLINE " ; int set2 [ ] = { 1 , 3 , 4 , 9 , 7 , 27 } ; int n2 = sizeof ( set2 ) / sizeof ( set2 [ 0 ] ) ; cout << lenOfLongestGP ( set2 , n2 ) << " STRNEWLINE " ; int set3 [ ] = { 2 , 3 , 5 , 7 , 11 , 13 } ; int n3 = sizeof ( set3 ) / sizeof ( set3 [ 0 ] ) ; cout << lenOfLongestGP ( set3 , n3 ) << " STRNEWLINE " ; return 0 ; } |
Print Maximum Length Chain of Pairs | Dynamic Programming solution to construct Maximum Length Chain of Pairs ; comparator function for sort function ; Function to construct Maximum Length Chain of Pairs ; Sort by start time ; L [ i ] stores maximum length of chain of arr [ 0. . i ] that ends with arr [ i ] . ; L [ 0 ] is equal to arr [ 0 ] ; start from index 1 ; for every j less than i ; L [ i ] = { Max ( L [ j ] ) } + arr [ i ] where j < i and arr [ j ] . b < arr [ i ] . a ; print max length vector ; Driver Function | #include <bits/stdc++.h> NEW_LINE using namespace std ; struct Pair { int a ; int b ; } ; int compare ( Pair x , Pair y ) { return x . a < y . a ; } void maxChainLength ( vector < Pair > arr ) { sort ( arr . begin ( ) , arr . end ( ) , compare ) ; vector < vector < Pair > > L ( arr . size ( ) ) ; L [ 0 ] . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < arr . size ( ) ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] . b < arr [ i ] . a ) && ( L [ j ] . size ( ) > L [ i ] . size ( ) ) ) L [ i ] = L [ j ] ; } L [ i ] . push_back ( arr [ i ] ) ; } vector < Pair > maxChain ; for ( vector < Pair > x : L ) if ( x . size ( ) > maxChain . size ( ) ) maxChain = x ; for ( Pair pair : maxChain ) cout << " ( " << pair . a << " , β " << pair . b << " ) β " ; } int main ( ) { Pair a [ ] = { { 5 , 29 } , { 39 , 40 } , { 15 , 28 } , { 27 , 40 } , { 50 , 90 } } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; vector < Pair > arr ( a , a + n ) ; maxChainLength ( arr ) ; return 0 ; } |
Printing Longest Bitonic Subsequence | Dynamic Programming solution to print Longest Bitonic Subsequence ; Utility function to print Longest Bitonic Subsequence ; Function to construct and print Longest Bitonic Subsequence ; LIS [ i ] stores the length of the longest increasing subsequence ending with arr [ i ] ; initialize LIS [ 0 ] to arr [ 0 ] ; Compute LIS values from left to right ; for every j less than i ; LDS [ i ] stores the length of the longest decreasing subsequence starting with arr [ i ] ; initialize LDS [ n - 1 ] to arr [ n - 1 ] ; Compute LDS values from right to left ; for every j greater than i ; reverse as vector as we 're inserting at end ; LDS [ i ] now stores Maximum Decreasing Subsequence of arr [ i . . n ] that starts with arr [ i ] ; Find maximum value of size of LIS [ i ] + size of LDS [ i ] - 1 ; print all but last element of LIS [ maxIndex ] vector ; print all elements of LDS [ maxIndex ] vector ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void print ( vector < int > & arr , int size ) { for ( int i = 0 ; i < size ; i ++ ) cout << arr [ i ] << " β " ; } void printLBS ( int arr [ ] , int n ) { vector < vector < int > > LIS ( n ) ; LIS [ 0 ] . push_back ( arr [ 0 ] ) ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ j ] < arr [ i ] ) && ( LIS [ j ] . size ( ) > LIS [ i ] . size ( ) ) ) LIS [ i ] = LIS [ j ] ; } LIS [ i ] . push_back ( arr [ i ] ) ; } vector < vector < int > > LDS ( n ) ; LDS [ n - 1 ] . push_back ( arr [ n - 1 ] ) ; for ( int i = n - 2 ; i >= 0 ; i -- ) { for ( int j = n - 1 ; j > i ; j -- ) { if ( ( arr [ j ] < arr [ i ] ) && ( LDS [ j ] . size ( ) > LDS [ i ] . size ( ) ) ) LDS [ i ] = LDS [ j ] ; } LDS [ i ] . push_back ( arr [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) reverse ( LDS [ i ] . begin ( ) , LDS [ i ] . end ( ) ) ; int max = 0 ; int maxIndex = -1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( LIS [ i ] . size ( ) + LDS [ i ] . size ( ) - 1 > max ) { max = LIS [ i ] . size ( ) + LDS [ i ] . size ( ) - 1 ; maxIndex = i ; } } print ( LIS [ maxIndex ] , LIS [ maxIndex ] . size ( ) - 1 ) ; print ( LDS [ maxIndex ] , LDS [ maxIndex ] . size ( ) ) ; } int main ( ) { int arr [ ] = { 1 , 11 , 2 , 10 , 4 , 5 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printLBS ( arr , n ) ; return 0 ; } |
Find if string is K | C ++ program to find if given string is K - Palindrome or not ; find if given string is K - Palindrome or not ; Create a table to store results of subproblems ; Fill dp [ ] [ ] in bottom up manner ; If first string is empty , only option is to remove all characters of second string ; If second string is empty , only option is to remove all characters of first string ; If last characters are same , ignore last character and recur for remaining string ; If last character are different , remove it and find minimum ; dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , Remove from str1 dp [ i ] [ j - 1 ] ) ; Remove from str2 ; Returns true if str is k palindrome . ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isKPalDP ( string str1 , string str2 , int m , int n ) { int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 ) else if ( j == 0 ) else if ( str1 [ i - 1 ] == str2 [ j - 1 ] ) dp [ i ] [ j ] = dp [ i - 1 ] [ j - 1 ] ; else } } return dp [ m ] [ n ] ; } bool isKPal ( string str , int k ) { string revStr = str ; reverse ( revStr . begin ( ) , revStr . end ( ) ) ; int len = str . length ( ) ; return ( isKPalDP ( str , revStr , len , len ) <= k * 2 ) ; } int main ( ) { string str = " acdcb " ; int k = 2 ; isKPal ( str , k ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
A Space Optimized Solution of LCS | Space optimized C ++ implementation of LCS problem ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Binary index , used to index current row and previous row . ; Compute current binary index ; Last filled entry contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lcs ( string & X , string & Y ) { int m = X . length ( ) , n = Y . length ( ) ; int L [ 2 ] [ n + 1 ] ; bool bi ; for ( int i = 0 ; i <= m ; i ++ ) { bi = i & 1 ; for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) L [ bi ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) L [ bi ] [ j ] = L [ 1 - bi ] [ j - 1 ] + 1 ; else L [ bi ] [ j ] = max ( L [ 1 - bi ] [ j ] , L [ bi ] [ j - 1 ] ) ; } } return L [ bi ] [ n ] ; } int main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; printf ( " Length β of β LCS β is β % d STRNEWLINE " , lcs ( X , Y ) ) ; return 0 ; } |
Count number of subsets having a particular XOR value | arr dynamic programming solution to finding the number of subsets having xor of their elements as k ; Returns count of subsets of arr [ ] with XOR value equals to k . ; Find maximum element in arr [ ] ; Maximum possible XOR value ; The value of dp [ i ] [ j ] is the number of subsets having XOR of their elements as j from the set arr [ 0. . . i - 1 ] ; Initializing all the values of dp [ i ] [ j ] as 0 ; The xor of empty subset is 0 ; Fill the dp table ; The answer is the number of subset from set arr [ 0. . n - 1 ] having XOR of elements as k ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int subsetXOR ( int arr [ ] , int n , int k ) { int max_ele = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) if ( arr [ i ] > max_ele ) max_ele = arr [ i ] ; int m = ( 1 << ( int ) ( log2 ( max_ele ) + 1 ) ) - 1 ; if ( k > m ) return 0 ; int dp [ n + 1 ] [ m + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) dp [ i ] [ j ] = 0 ; dp [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = 0 ; j <= m ; j ++ ) dp [ i ] [ j ] = dp [ i - 1 ] [ j ] + dp [ i - 1 ] [ j ^ arr [ i - 1 ] ] ; return dp [ n ] [ k ] ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 } ; int k = 4 ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Count β of β subsets β is β " << subsetXOR ( arr , n , k ) ; return 0 ; } |
Partition a set into two subsets such that the difference of subset sums is minimum | A Recursive C program to solve minimum sum partition problem . ; Returns the minimum value of the difference of the two sets . ; Calculate sum of all elements ; Create an array to store results of subproblems ; Initialize first column as true . 0 sum is possible with all elements . ; Initialize top row , except dp [ 0 ] [ 0 ] , as false . With 0 elements , no other sum except 0 is possible ; Fill the partition table in bottom up manner ; If i 'th element is excluded ; If i 'th element is included ; Initialize difference of two sums . ; Find the largest j such that dp [ n ] [ j ] is true where j loops from sum / 2 t0 0 ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMin ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; bool dp [ n + 1 ] [ sum + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) dp [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= sum ; i ++ ) dp [ 0 ] [ i ] = false ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= sum ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; if ( arr [ i - 1 ] <= j ) dp [ i ] [ j ] |= dp [ i - 1 ] [ j - arr [ i - 1 ] ] ; } } int diff = INT_MAX ; for ( int j = sum / 2 ; j >= 0 ; j -- ) { if ( dp [ n ] [ j ] == true ) { diff = sum - 2 * j ; break ; } } return diff ; } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 2 , 2 , 1 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " The β minimum β difference β between β 2 β sets β is β " << findMin ( arr , n ) ; return 0 ; } |
Count number of paths with at | C ++ program to count number of paths with maximum k turns allowed ; table to store results of subproblems ; Returns count of paths to reach ( i , j ) from ( 0 , 0 ) using at - most k turns . d is current direction d = 0 indicates along row , d = 1 indicates along column . ; If invalid row or column indexes ; If current cell is top left itself ; If 0 turns left ; If direction is row , then we can reach here only if direction is row and row is 0. ; If direction is column , then we can reach here only if direction is column and column is 0. ; If this subproblem is already evaluated ; If current direction is row , then count paths for two cases 1 ) We reach here through previous row . 2 ) We reach here through previous column , so number of turns k reduce by 1. ; Similar to above if direction is column ; This function mainly initializes ' dp ' array as - 1 and calls countPathsUtil ( ) ; If ( 0 , 0 ) is target itself ; Initialize ' dp ' array ; Recur for two cases : moving along row and along column return countPathsUtil ( i - 1 , j , k , 1 ) + Moving along row countPathsUtil ( i , j - 1 , k , 0 ) ; Moving along column ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int dp [ MAX ] [ MAX ] [ MAX ] [ 2 ] ; int countPathsUtil ( int i , int j , int k , int d ) { if ( i < 0 j < 0 ) return 0 ; if ( i == 0 && j == 0 ) return 1 ; if ( k == 0 ) { if ( d == 0 && i == 0 ) return 1 ; if ( d == 1 && j == 0 ) return 1 ; return 0 ; } if ( dp [ i ] [ j ] [ k ] [ d ] != -1 ) return dp [ i ] [ j ] [ k ] [ d ] ; if ( d == 0 ) return dp [ i ] [ j ] [ k ] [ d ] = countPathsUtil ( i , j - 1 , k , d ) + countPathsUtil ( i - 1 , j , k - 1 , ! d ) ; return dp [ i ] [ j ] [ k ] [ d ] = countPathsUtil ( i - 1 , j , k , d ) + countPathsUtil ( i , j - 1 , k - 1 , ! d ) ; } int countPaths ( int i , int j , int k ) { if ( i == 0 && j == 0 ) return 1 ; memset ( dp , -1 , sizeof dp ) ; } int main ( ) { int m = 3 , n = 3 , k = 2 ; cout << " Number β of β paths β is β " << countPaths ( m - 1 , n - 1 , k ) << endl ; return 0 ; } |
Find minimum possible size of array with given rules for removing elements | C ++ program to find size of minimum possible array after removing elements according to given rules ; dp [ i ] [ j ] denotes the minimum number of elements left in the subarray arr [ i . . j ] . ; If already evaluated ; If size of array is less than 3 ; Initialize result as the case when first element is separated ( not removed using given rules ) ; Now consider all cases when first element forms a triplet and removed . Check for all possible triplets ( low , i , j ) ; Check if this triplet follows the given rules of removal . And elements between ' low ' and ' i ' , and between ' i ' and ' j ' can be recursively removed . ; Insert value in table and return result ; This function mainly initializes dp table and calls recursive function minSizeRec ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 1000 NEW_LINE int dp [ MAX ] [ MAX ] ; int minSizeRec ( int arr [ ] , int low , int high , int k ) { if ( dp [ low ] [ high ] != -1 ) return dp [ low ] [ high ] ; if ( ( high - low + 1 ) < 3 ) return high - low + 1 ; int res = 1 + minSizeRec ( arr , low + 1 , high , k ) ; for ( int i = low + 1 ; i <= high - 1 ; i ++ ) { for ( int j = i + 1 ; j <= high ; j ++ ) { if ( arr [ i ] == ( arr [ low ] + k ) && arr [ j ] == ( arr [ low ] + 2 * k ) && minSizeRec ( arr , low + 1 , i - 1 , k ) == 0 && minSizeRec ( arr , i + 1 , j - 1 , k ) == 0 ) { res = min ( res , minSizeRec ( arr , j + 1 , high , k ) ) ; } } } return ( dp [ low ] [ high ] = res ) ; } int minSize ( int arr [ ] , int n , int k ) { memset ( dp , -1 , sizeof ( dp ) ) ; return minSizeRec ( arr , 0 , n - 1 , k ) ; } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 4 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 1 ; cout << minSize ( arr , n , k ) << endl ; return 0 ; } |
Find number of solutions of a linear equation of n variables | A naive recursive C ++ program to find number of non - negative solutions for a given linear equation ; Recursive function that returns count of solutions for given rhs value and coefficients coeff [ start . . end ] ; Base case ; Initialize count of solutions ; One by subtract all smaller or equal coefficiants and recur ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSol ( int coeff [ ] , int start , int end , int rhs ) { if ( rhs == 0 ) return 1 ; int result = 0 ; for ( int i = start ; i <= end ; i ++ ) if ( coeff [ i ] <= rhs ) result += countSol ( coeff , i , end , rhs - coeff [ i ] ) ; return result ; } int main ( ) { int coeff [ ] = { 2 , 2 , 5 } ; int rhs = 4 ; int n = sizeof ( coeff ) / sizeof ( coeff [ 0 ] ) ; cout << countSol ( coeff , 0 , n - 1 , rhs ) ; return 0 ; } |
Maximum weight transformation of a given string | C ++ program to find maximum weight transformation of a given string ; Returns weight of the maximum weight transformation ; Base case ; If this subproblem is already solved ; Don 't make pair, so weight gained is 1 ; If we can make pair ; If elements are dissimilar , weight gained is 4 ; if elements are similar so for making a pair we toggle any of them . Since toggle cost is 1 so overall weight gain becomes 3 ; save and return maximum of above cases ; Initializes lookup table and calls getMaxRec ( ) ; Create and initialize lookup table ; Call recursive function ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxRec ( string & str , int i , int n , int lookup [ ] ) { if ( i >= n ) return 0 ; if ( lookup [ i ] != -1 ) return lookup [ i ] ; int ans = 1 + getMaxRec ( str , i + 1 , n , lookup ) ; if ( i + 1 < n ) { if ( str [ i ] != str [ i + 1 ] ) ans = max ( 4 + getMaxRec ( str , i + 2 , n , lookup ) , ans ) ; else ans = max ( 3 + getMaxRec ( str , i + 2 , n , lookup ) , ans ) ; } return lookup [ i ] = ans ; } int getMaxWeight ( string str ) { int n = str . length ( ) ; int lookup [ n ] ; memset ( lookup , -1 , sizeof lookup ) ; return getMaxRec ( str , 0 , str . length ( ) , lookup ) ; } int main ( ) { string str = " AAAAABB " ; cout << " Maximum β weight β of β a β transformation β of β " << str << " β is β " << getMaxWeight ( str ) ; return 0 ; } |
Minimum steps to reach a destination | C ++ program to count number of steps to reach a point ; source -> source vertex step -> value of last step taken dest -> destination vertex ; base cases ; if we go on positive side ; if we go on negative side ; minimum of both cases ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int steps ( int source , int step , int dest ) { if ( abs ( source ) > ( dest ) ) return INT_MAX ; if ( source == dest ) return step ; int pos = steps ( source + step + 1 , step + 1 , dest ) ; int neg = steps ( source - step - 1 , step + 1 , dest ) ; return min ( pos , neg ) ; } int main ( ) { int dest = 11 ; cout << " No . β of β steps β required β to β reach β " << dest << " β is β " << steps ( 0 , 0 , dest ) ; return 0 ; } |
Longest Common Substring | DP | C ++ implementation of the above approach ; Function to find the length of the longest LCS ; Create DP table ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LCSubStr ( string s , string t , int n , int m ) { int dp [ 2 ] [ m + 1 ] ; int res = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= m ; j ++ ) { if ( s [ i - 1 ] == t [ j - 1 ] ) { dp [ i % 2 ] [ j ] = dp [ ( i - 1 ) % 2 ] [ j - 1 ] + 1 ; if ( dp [ i % 2 ] [ j ] > res ) res = dp [ i % 2 ] [ j ] ; } else dp [ i % 2 ] [ j ] = 0 ; } } return res ; } int main ( ) { string X = " OldSite : GeeksforGeeks . org " ; string Y = " NewSite : GeeksQuiz . com " ; int m = X . length ( ) ; int n = Y . length ( ) ; cout << LCSubStr ( X , Y , m , n ) ; return 0 ; cout << " GFG ! " ; return 0 ; } |
Longest Common Substring | DP | C ++ program using to find length of the longest common substring recursion ; Returns length of function f or longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Driver code | #include <iostream> NEW_LINE using namespace std ; string X , Y ; int lcs ( int i , int j , int count ) { if ( i == 0 j == 0 ) return count ; if ( X [ i - 1 ] == Y [ j - 1 ] ) { count = lcs ( i - 1 , j - 1 , count + 1 ) ; } count = max ( count , max ( lcs ( i , j - 1 , 0 ) , lcs ( i - 1 , j , 0 ) ) ) ; return count ; } int main ( ) { int n , m ; X = " abcdxyz " ; Y = " xyzabcd " ; n = X . size ( ) ; m = Y . size ( ) ; cout << lcs ( n , m , 0 ) ; return 0 ; } |
Make Array elements equal by replacing adjacent elements with their XOR | C ++ Program of the above approach ; Function to check if it is possible to make all the array elements equal using the given operation ; Stores the XOR of all elements of array A [ ] ; Case 1 , check if the XOR of the array A [ ] is 0 ; Maintains the XOR till the current element ; Iterate over the array ; If the current XOR is equal to the total XOR increment the count and initialize current XOR as 0 ; Print Answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleEqualArray ( int A [ ] , int N ) { int tot_XOR = 0 ; for ( int i = 0 ; i < N ; i ++ ) { tot_XOR ^= A [ i ] ; } if ( tot_XOR == 0 ) { cout << " YES " ; return ; } int cur_XOR = 0 ; int cnt = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cur_XOR ^= A [ i ] ; if ( cur_XOR == tot_XOR ) { cnt ++ ; cur_XOR = 0 ; } } if ( cnt > 2 ) { cout << " YES " ; } else { cout << " NO " ; } } int main ( ) { int A [ ] = { 0 , 2 , 2 } ; int N = sizeof ( A ) / sizeof ( int ) ; possibleEqualArray ( A , N ) ; return 0 ; } |
Count of palindromes that can be obtained by concatenating equal length prefix and substrings | C ++ program the above approach ; Function to calculate the number of palindromes ; Calculation of Z - array ; Calculation of sigma ( Z [ i ] + 1 ) ; Return the count ; Driver Code ; Given String | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countPalindromes ( string S ) { int N = ( int ) S . length ( ) ; vector < int > Z ( N ) ; int l = 0 , r = 0 ; for ( int i = 1 ; i < N ; i ++ ) { if ( i <= r ) Z [ i ] = min ( r - i + 1 , Z [ i - l ] ) ; while ( i + Z [ i ] < N && S [ Z [ i ] ] == S [ i + Z [ i ] ] ) { Z [ i ] ++ ; } if ( i + Z [ i ] - 1 > r ) { l = i ; r = i + Z [ i ] - 1 ; } } int sum = 0 ; for ( int i = 0 ; i < Z . size ( ) ; i ++ ) { sum += Z [ i ] + 1 ; } return sum ; } int main ( ) { string S = " abab " ; cout << countPalindromes ( S ) ; return 0 ; } |
Extract substrings between any pair of delimiters | C ++ Program to implement the above approach ; Function to print strings present between any pair of delimeters ; Stores the indices of ; If opening delimeter is encountered ; If closing delimeter is encountered ; Extract the position of opening delimeter ; Length of substring ; Extract the substring ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubsInDelimeters ( string str ) { stack < int > dels ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( str [ i ] == ' [ ' ) { dels . push ( i ) ; } else if ( str [ i ] == ' ] ' && ! dels . empty ( ) ) { int pos = dels . top ( ) ; dels . pop ( ) ; int len = i - 1 - pos ; string ans = str . substr ( pos + 1 , len ) ; cout << ans << endl ; } } } int main ( ) { string str = " [ This β is β first ] β ignored β text β [ This β is β second ] " ; printSubsInDelimeters ( str ) ; return 0 ; } |
Print matrix elements from top | C ++ program for the above approach ; Function to traverse the matrix diagonally upwards ; Store the number of rows ; Initialize queue ; Push the index of first element i . e . , ( 0 , 0 ) ; Get the front element ; Pop the element at the front ; Insert the element below if the current element is in first column ; Insert the right neighbour if it exists ; Driver Code ; Given vector of vectors arr ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printDiagonalTraversal ( vector < vector < int > > & nums ) { int m = nums . size ( ) ; queue < pair < int , int > > q ; q . push ( { 0 , 0 } ) ; while ( ! q . empty ( ) ) { pair < int , int > p = q . front ( ) ; q . pop ( ) ; cout << nums [ p . first ] [ p . second ] << " β " ; if ( p . second == 0 && p . first + 1 < m ) { q . push ( { p . first + 1 , p . second } ) ; } if ( p . second + 1 < nums [ p . first ] . size ( ) ) q . push ( { p . first , p . second + 1 } ) ; } } int main ( ) { vector < vector < int > > arr = { { 1 , 2 , 3 } , { 4 , 5 , 6 } , { 7 , 8 , 9 } } ; printDiagonalTraversal ( arr ) ; return 0 ; } |
Find original sequence from Array containing the sequence merged many times in order | C ++ program for the above approach ; Function that returns the restored permutation ; Vector to store the result ; Map to mark the elements which are taken in result ; Check if the element is coming first time ; Push in result vector ; Mark it in the map ; Return the answer ; Function to print the result ; Driver Code ; Given Array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > restore ( int arr [ ] , int N ) { vector < int > result ; map < int , int > mp ; for ( int i = 0 ; i < N ; i ++ ) { if ( mp [ arr [ i ] ] == 0 ) { result . push_back ( arr [ i ] ) ; mp [ arr [ i ] ] ++ ; } } return result ; } void print_result ( vector < int > result ) { for ( int i = 0 ; i < result . size ( ) ; i ++ ) cout << result [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; print_result ( restore ( arr , N ) ) ; return 0 ; } |
Find original sequence from Array containing the sequence merged many times in order | C ++ program for the above approach ; Function that returns the restored permutation ; Vector to store the result ; Set to insert unique elements ; Check if the element is coming first time ; Push in result vector ; Function to print the result ; Driver Code ; Given Array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > restore ( int arr [ ] , int N ) { vector < int > result ; int count1 = 1 ; set < int > s ; for ( int i = 0 ; i < N ; i ++ ) { s . insert ( arr [ i ] ) ; if ( s . size ( ) == count1 ) { result . push_back ( arr [ i ] ) ; count1 ++ ; } } return result ; } void print_result ( vector < int > result ) { for ( int i = 0 ; i < result . size ( ) ; i ++ ) cout << result [ i ] << " β " ; } int main ( ) { int arr [ ] = { 1 , 13 , 1 , 24 , 13 , 24 , 2 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; print_result ( restore ( arr , N ) ) ; return 0 ; } |
Program to print the pattern 1020304017018019020 * * 50607014015016 * * * * 809012013 * * * * * * 10011. . . | C ++ implementation to print the given pattern ; Function to find the sum of N integers from 1 to N ; Function to print the given pattern ; Iterate over [ 0 , N - 1 ] ; Sub - Pattern - 1 ; Sub - Pattern - 2 ; Count the number of element in rows and sub - pattern 2 and 3 will have same rows ; Increment Val to print the series 1 , 2 , 3 , 4 , 5 ... ; Finally , add the ( N - 1 ) th element i . e . , 5 and increment it by 1 ; Initial is used to give the initial value of the row in Sub - Pattern 3 ; Sub - Pattern 3 ; Skip printing zero at the last ; Driver Code ; Given N ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int sum ( int n ) { return n * ( n - 1 ) / 2 ; } void BSpattern ( int N ) { int Val = 0 , Pthree = 0 , cnt = 0 , initial ; string s = " * * " ; for ( int i = 0 ; i < N ; i ++ ) { cnt = 0 ; if ( i > 0 ) { cout << s ; s += " * * " ; } for ( int j = i ; j < N ; j ++ ) { if ( i > 0 ) { cnt ++ ; } cout << ++ Val ; cout << 0 ; } if ( i == 0 ) { int Sumbeforelast = sum ( Val ) * 2 ; Pthree = Val + Sumbeforelast + 1 ; initial = Pthree ; } initial = initial - cnt ; Pthree = initial ; for ( int k = i ; k < N ; k ++ ) { cout << Pthree ++ ; if ( k != N - 1 ) { cout << 0 ; } } cout << " STRNEWLINE " ; } } int main ( ) { int N = 5 ; BSpattern ( N ) ; return 0 ; } |
Check if a number starts with another number or not | C ++ program for the above approach ; Function to check if B is a prefix of A or not ; Convert numbers into strings ; Find the lengths of strings s1 and s2 ; Base Case ; Traverse the strings s1 & s2 ; If at any index characters are unequals then return false ; Return true ; Driver Code ; Given numbers ; Function Call ; If B is a prefix of A , then print " Yes " | #include " bits / stdc + + . h " NEW_LINE using namespace std ; bool checkprefix ( int A , int B ) { string s1 = to_string ( A ) ; string s2 = to_string ( B ) ; int n1 = s1 . length ( ) ; int n2 = s2 . length ( ) ; if ( n1 < n2 ) { return false ; } for ( int i = 0 ; i < n2 ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { return false ; } } return true ; } int main ( ) { int A = 12345 , B = 12 ; bool result = checkprefix ( A , B ) ; if ( result ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Check if it is possible to reach ( x , y ) from origin in exactly Z steps using only plus movements | C ++ program for the above approach ; Function to check if it is possible to reach ( x , y ) from origin in exactly z steps ; Condition if we can 't reach in Z steps ; Driver Code ; Destination point coordinate ; Number of steps allowed ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleToReach ( int x , int y , int z ) { if ( z < abs ( x ) + abs ( y ) || ( z - abs ( x ) - abs ( y ) ) % 2 ) { cout << " Not β Possible " << endl ; } else cout << " Possible " << endl ; } int main ( ) { int x = 5 , y = 5 ; int z = 11 ; possibleToReach ( x , y , z ) ; return 0 ; } |
Number of cycles in a Polygon with lines from Centroid to Vertices | C ++ program to find number of cycles in a Polygon with lines from Centroid to Vertices ; Function to find the Number of Cycles ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nCycle ( int N ) { return ( N ) * ( N - 1 ) + 1 ; } int main ( ) { int N = 4 ; cout << nCycle ( N ) << endl ; return 0 ; } |
Sum of consecutive bit differences of first N non | C ++ program for the above problem ; Recursive function to count the sum of bit differences of numbers from 1 to pow ( 2 , ( i + 1 ) ) - 1 ; base cases ; Recursion call if the sum of bit difference of numbers around i are not calculated ; return the sum of bit differences if already calculated ; Function to calculate the sum of bit differences up to N ; nearest smaller power of 2 ; remaining numbers ; calculate the count of bit diff ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long a [ 65 ] = { 0 } ; long long Count ( int i ) { if ( i == 0 ) return 1 ; else if ( i < 0 ) return 0 ; if ( a [ i ] == 0 ) { a [ i ] = ( i + 1 ) + 2 * Count ( i - 1 ) ; return a [ i ] ; } else return a [ i ] ; } long long solve ( long long n ) { long long i , sum = 0 ; while ( n > 0 ) { i = log2 ( n ) ; n = n - pow ( 2 , i ) ; sum = sum + ( i + 1 ) + Count ( i - 1 ) ; } return sum ; } int main ( ) { long long n = 7 ; cout << solve ( n ) << endl ; return 0 ; } |
Count of total Heads and Tails after N flips in a coin | C ++ program to count total heads and tails after N flips in a coin ; Function to find count of head and tail ; Check if initially all the coins are facing towards head ; Check if initially all the coins are facing towards tail ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; pair < int , int > count_ht ( char s , int N ) { pair < int , int > p ; if ( s == ' H ' ) { p . first = floor ( N / 2.0 ) ; p . second = ceil ( N / 2.0 ) ; } else if ( s == ' T ' ) { p . first = ceil ( N / 2.0 ) ; p . second = floor ( N / 2.0 ) ; } return p ; } int main ( ) { char C = ' H ' ; int N = 5 ; pair < int , int > p = count_ht ( C , N ) ; cout << " Head β = β " << ( p . first ) << " STRNEWLINE " ; cout << " Tail β = β " << ( p . second ) << " STRNEWLINE " ; } |
Longest palindromic string possible after removal of a substring | C ++ Implementation of the above approach ; Function to find the longest palindrome from the start of the string using KMP match ; Append S ( reverse of C ) to C ; Use KMP algorithm ; Function to return longest palindromic string possible from the given string after removal of any substring ; Initialize three strings A , B AND F ; Loop to find longest substrings from both ends which are reverse of each other ; Proceed to third step of our approach ; Remove the substrings A and B ; Find the longest palindromic substring from beginning of C ; Find the longest palindromic substring from end of C ; Store the maximum of D and E in F ; Find the final answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findPalindrome ( string C ) { string S = C ; reverse ( S . begin ( ) , S . end ( ) ) ; C = C + " & " + S ; int n = C . length ( ) ; int longestPalindrome [ n ] ; longestPalindrome [ 0 ] = 0 ; int len = 0 ; int i = 1 ; while ( i < n ) { if ( C [ i ] == C [ len ] ) { len ++ ; longestPalindrome [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = longestPalindrome [ len - 1 ] ; } else { longestPalindrome [ i ] = 0 ; i ++ ; } } } string ans = C . substr ( 0 , longestPalindrome [ n - 1 ] ) ; return ans ; } string findAns ( string s ) { string A = " " ; string B = " " ; string F = " " ; int i = 0 ; int j = s . length ( ) - 1 ; int len = s . length ( ) ; while ( i < j && s [ i ] == s [ j ] ) { i = i + 1 ; j = j - 1 ; } if ( i > 0 ) { A = s . substr ( 0 , i ) ; B = s . substr ( len - i , i ) ; } if ( len > 2 * i ) { string C = s . substr ( i , s . length ( ) - 2 * i ) ; string D = findPalindrome ( C ) ; reverse ( C . begin ( ) , C . end ( ) ) ; string E = findPalindrome ( C ) ; if ( D . length ( ) > E . length ( ) ) { F = D ; } else { F = E ; } } string answer = A + F + B ; return answer ; } int main ( ) { string str = " abcdefghiedcba " ; cout << findAns ( str ) << endl ; } |
Find Nth term of the series 2 , 3 , 10 , 15 , 26. ... | C ++ program to find Nth term of the series 2 , 3 , 10 , 15 , 26. ... ; Function to find Nth term ; Nth term ; Driver Method | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthTerm ( int N ) { int nth = 0 ; if ( N % 2 == 1 ) nth = ( N * N ) + 1 ; else nth = ( N * N ) - 1 ; return nth ; } int main ( ) { int N = 5 ; cout << nthTerm ( N ) << endl ; return 0 ; } |
Find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... | C ++ program to find the Nth term in series 12 , 35 , 81 , 173 , 357 , ... ; Function to find Nth term ; Nth term ; Driver Method | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthTerm ( int N ) { int nth = 0 , first_term = 12 ; nth = ( first_term * ( pow ( 2 , N - 1 ) ) ) + 11 * ( ( pow ( 2 , N - 1 ) ) - 1 ) ; return nth ; } int main ( ) { int N = 5 ; cout << nthTerm ( N ) << endl ; return 0 ; } |
Find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... | C ++ program to find Nth term of the series 4 , 2 , 2 , 3 , 6 , ... ; Function to find Nth term ; Nth term ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nthTerm ( int N ) { int nth = 0 , first_term = 4 ; int pi = 1 , po = 1 ; int n = N ; while ( n > 1 ) { pi *= n - 1 ; n -- ; po *= 2 ; } nth = ( first_term * pi ) / po ; return nth ; } int main ( ) { int N = 5 ; cout << nthTerm ( N ) << endl ; return 0 ; } |
Find the final number obtained after performing the given operation | C ++ implementation of the approach ; Function to return the final number obtained after performing the given operation ; Find the gcd of the array elements ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int finalNum ( int arr [ ] , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { result = __gcd ( result , arr [ i ] ) ; } return result ; } int main ( ) { int arr [ ] = { 3 , 9 , 6 , 36 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << finalNum ( arr , n ) ; return 0 ; } |
Check whether all the substrings have number of vowels atleast as that of consonants | C ++ implementation of the approach ; Function that returns true if character ch is a vowel ; Compares two integers according to their digit sum ; Check if there are two consecutive consonants ; Check if there is any vowel surrounded by two consonants ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { switch ( ch ) { case ' a ' : case ' e ' : case ' i ' : case ' o ' : case ' u ' : return true ; } return false ; } bool isSatisfied ( string str , int n ) { for ( int i = 1 ; i < n ; i ++ ) { if ( ! isVowel ( str [ i ] ) && ! isVowel ( str [ i - 1 ] ) ) { return false ; } } for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( isVowel ( str [ i ] ) && ! isVowel ( str [ i - 1 ] ) && ! isVowel ( str [ i + 1 ] ) ) { return false ; } } return true ; } int main ( ) { string str = " acaba " ; int n = str . length ( ) ; if ( isSatisfied ( str , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Print the longest prefix of the given string which is also the suffix of the same string | C ++ implementation of the approach ; Returns length of the longest prefix which is also suffix and the two do not overlap . This function mainly is copy of computeLPSArray ( ) in KMP Algorithm ; lps [ 0 ] is always 0 ; Length of the previous longest prefix suffix ; Loop to calculate lps [ i ] for i = 1 to n - 1 ; This is tricky . Consider the example . AAACAAAA and i = 7. The idea is similar to search step . ; Also , note that we do not increment i here ; If len = 0 ; Since we are looking for non overlapping parts ; Function that returns the prefix ; Get the length of the longest prefix ; Stores the prefix ; Traverse and add characters ; Returns the prefix ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int LengthlongestPrefixSuffix ( string s ) { int n = s . length ( ) ; int lps [ n ] ; lps [ 0 ] = 0 ; int len = 0 ; int i = 1 ; while ( i < n ) { if ( s [ i ] == s [ len ] ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) { len = lps [ len - 1 ] ; } else { lps [ i ] = 0 ; i ++ ; } } } int res = lps [ n - 1 ] ; return ( res > n / 2 ) ? n / 2 : res ; } string longestPrefixSuffix ( string s ) { int len = LengthlongestPrefixSuffix ( s ) ; string prefix = " " ; for ( int i = 0 ; i < len ; i ++ ) prefix += s [ i ] ; return prefix ; } int main ( ) { string s = " abcab " ; string ans = longestPrefixSuffix ( s ) ; if ( ans == " " ) cout << " - 1" ; else cout << ans ; return 0 ; } |
Print a number as string of ' A ' and ' B ' in lexicographic order | C ++ program to implement the above approach ; Function to calculate number of characters in corresponding string of ' A ' and ' B ' ; Since the minimum number of characters will be 1 ; Calculating number of characters ; Since k length string can represent at most pow ( 2 , k + 1 ) - 2 that is if k = 4 , it can represent at most pow ( 2 , 4 + 1 ) - 2 = 30 so we have to calculate the length of the corresponding string ; return the length of the corresponding string ; Function to print corresponding string of ' A ' and ' B ' ; Find length of string ; Since the first number that can be represented by k length string will be ( pow ( 2 , k ) - 2 ) + 1 and it will be AAA ... A , k times , therefore , N will store that how much we have to print ; At a particular time , we have to decide whether we have to print ' A ' or ' B ' , this can be check by calculating the value of pow ( 2 , k - 1 ) ; Print new line ; Driver code | #include <cmath> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int no_of_characters ( int M ) { int k = 1 ; while ( true ) { if ( pow ( 2 , k + 1 ) - 2 < M ) k ++ ; else break ; } return k ; } void print_string ( int M ) { int k , num , N ; k = no_of_characters ( M ) ; N = M - ( pow ( 2 , k ) - 2 ) ; while ( k > 0 ) { num = pow ( 2 , k - 1 ) ; if ( num >= N ) cout << " A " ; else { cout << " B " ; N -= num ; } k -- ; } cout << endl ; } int main ( ) { int M ; M = 30 ; print_string ( M ) ; M = 55 ; print_string ( M ) ; M = 100 ; print_string ( M ) ; return 0 ; } |
Replace two substrings ( of a string ) with each other | C ++ implementation of the approach ; Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string updateString ( string S , string A , string B ) { int l = A . length ( ) ; for ( int i = 0 ; i + l <= S . length ( ) ; i ++ ) { string curr = S . substr ( i , i + l ) ; if ( curr == A ) { string new_string = " " ; new_string += S . substr ( 0 , i ) + B + S . substr ( i + l , S . length ( ) ) ; S = new_string ; i += l - 1 ; } else { string new_string = " " ; new_string += S . substr ( 0 , i ) + A + S . substr ( i + l , S . length ( ) ) ; S = new_string ; i += l - 1 ; } } return S ; } int main ( ) { string S = " aab " ; string A = " aa " ; string B = " bb " ; cout << ( updateString ( S , A , B ) ) << endl ; } |
Print n 0 s and m 1 s such that no two 0 s and no three 1 s are together | C ++ implementation of the approach ; Function to print the required pattern ; When condition fails ; When m = n - 1 ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPattern ( int n , int m ) { if ( m > 2 * ( n + 1 ) m < n - 1 ) { cout << " - 1" ; } else if ( abs ( n - m ) <= 1 ) { while ( n > 0 && m > 0 ) { cout << "01" ; n -- ; m -- ; } if ( n != 0 ) { cout << "0" ; } if ( m != 0 ) { cout << "1" ; } } else { while ( m - n > 1 && n > 0 ) { cout << "110" ; m = m - 2 ; n = n - 1 ; } while ( n > 0 ) { cout << "10" ; n -- ; m -- ; } while ( m > 0 ) { cout << "1" ; m -- ; } } } int main ( ) { int n = 4 , m = 8 ; printPattern ( n , m ) ; return 0 ; } |
Find the count of Strictly decreasing Subarrays | C ++ program to count number of strictly decreasing subarrays in O ( n ) time . ; Function to count the number of strictly decreasing subarrays ; Initialize length of current decreasing subarray ; Traverse through the array ; If arr [ i + 1 ] is less than arr [ i ] , then increment length ; Else Update count and reset length ; If last length is more than 1 ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countDecreasing ( int A [ ] , int n ) { int len = 1 ; for ( int i = 0 ; i < n - 1 ; ++ i ) { if ( A [ i + 1 ] < A [ i ] ) len ++ ; else { cnt += ( ( ( len - 1 ) * len ) / 2 ) ; len = 1 ; } } if ( len > 1 ) cnt += ( ( ( len - 1 ) * len ) / 2 ) ; return cnt ; } int main ( ) { int A [ ] = { 100 , 3 , 1 , 13 } ; int n = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << countDecreasing ( A , n ) ; return 0 ; } |
Minimum changes required to make first string substring of second string | CPP program to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Function to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Get the sizes of both strings ; Traverse the string S2 ; From every index in S2 , check the number of mis - matching characters in substring of length of S1 ; Take minimum of prev and current mis - match ; return answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumChar ( string S1 , string S2 ) { int n = S1 . size ( ) , m = S2 . size ( ) ; int ans = INT_MAX ; for ( int i = 0 ; i < m - n + 1 ; i ++ ) { int minRemovedChar = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( S1 [ j ] != S2 [ i + j ] ) { minRemovedChar ++ ; } } ans = min ( minRemovedChar , ans ) ; } return ans ; } int main ( ) { string S1 = " abc " ; string S2 = " paxzk " ; cout << minimumChar ( S1 , S2 ) ; return 0 ; } |
Frequency of a substring in a string | Simple C ++ program to count occurrences of pat in txt . ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countFreq ( string & pat , string & txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int res = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { res ++ ; j = 0 ; } } return res ; } int main ( ) { string txt = " dhimanman " ; string pat = " man " ; cout << countFreq ( pat , txt ) ; return 0 ; } |
Optimized Naive Algorithm for Pattern Searching | C ++ program for A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; A modified Naive Pattern Searching algorithm that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if ( j == M ) if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void search ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int i = 0 ; while ( i <= N - M ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; { cout << " Pattern β found β at β index β " << i << endl ; i = i + M ; } else if ( j == 0 ) i = i + 1 ; else i = i + j ; } } int main ( ) { string txt = " ABCEABCDABCEABCD " ; string pat = " ABCD " ; search ( pat , txt ) ; return 0 ; } |
Find the missing digit in given product of large positive integers | C ++ program for the above approach ; Function to find the replaced digit in the product of a * b ; Keeps track of the sign of the current digit ; Stores the value of a % 11 ; Find the value of a mod 11 for large value of a as per the derived formula ; Stores the value of b % 11 ; Find the value of b mod 11 for large value of a as per the derived formula ; Stores the value of c % 11 ; Keeps track of the sign of x ; If the current digit is the missing digit , then keep the track of its sign ; Find the value of x using the derived equation ; Check if x has a negative sign ; Return positive equivaluent of x mod 11 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMissingDigit ( string a , string b , string c ) { int w = 1 ; int a_mod_11 = 0 ; for ( int i = a . size ( ) - 1 ; i >= 0 ; i -- ) { a_mod_11 = ( a_mod_11 + w * ( a [ i ] - '0' ) ) % 11 ; w = w * -1 ; } int b_mod_11 = 0 ; w = 1 ; for ( int i = b . size ( ) - 1 ; i >= 0 ; i -- ) { b_mod_11 = ( b_mod_11 + w * ( b [ i ] - '0' ) ) % 11 ; w = w * -1 ; } int c_mod_11 = 0 ; bool xSignIsPositive = true ; w = 1 ; for ( int i = c . size ( ) - 1 ; i >= 0 ; i -- ) { if ( c [ i ] == ' x ' ) { xSignIsPositive = ( w == 1 ) ; } else { c_mod_11 = ( c_mod_11 + w * ( c [ i ] - '0' ) ) % 11 ; } w = w * -1 ; } int x = ( ( a_mod_11 * b_mod_11 ) - c_mod_11 ) % 11 ; if ( ! xSignIsPositive ) { x = - x ; } return ( x % 11 + 11 ) % 11 ; } int main ( ) { string A = "123456789" ; string B = "987654321" ; string C = "12193263111x635269" ; cout << findMissingDigit ( A , B , C ) ; return 0 ; } |
Check if a string can be made empty by repeatedly removing given subsequence | C ++ program for the above approach ; Function to check if a string can be made empty by removing all subsequences of the form " GFG " or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findIfPossible ( int N , string str ) { int countG = 0 , countF = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' G ' ) countG ++ ; else countF ++ ; } if ( 2 * countF != countG ) { cout << " NO STRNEWLINE " ; } else { int id = 0 ; bool flag = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' G ' ) { countG -- ; id ++ ; } else { countF -- ; id -- ; } if ( id < 0 ) { flag = false ; break ; } if ( countG < countF ) { flag = false ; break ; } } if ( flag ) { cout << " YES STRNEWLINE " ; } else { cout << " NO STRNEWLINE " ; } } } int main ( ) { int n = 6 ; string str = " GFGFGG " ; findIfPossible ( n , str ) ; return 0 ; } |
Check whether second string can be formed from characters of first string used any number of times | C ++ implementation of the above approach ; Function to check if str2 can be made by characters of str1 or not ; To store the occurrence of every character ; Length of the two strings ; Assume that it is possible to compose the string str2 from str1 ; Iterate over str1 ; Store the presence of every character ; Iterate over str2 ; Ignore the spaces ; Check for the presence of character in str1 ; If it is possible to make str2 from str1 ; Driver Code ; Given strings ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( string str1 , string str2 ) { int arr [ 256 ] = { 0 } ; int l1 = str1 . size ( ) ; int l2 = str2 . size ( ) ; int i , j ; bool possible = true ; for ( i = 0 ; i < l1 ; i ++ ) { arr [ str1 [ i ] ] = 1 ; } for ( i = 0 ; i < l2 ; i ++ ) { if ( str2 [ i ] != ' β ' ) { if ( arr [ str2 [ i ] ] == 1 ) continue ; else { possible = false ; break ; } } } if ( possible ) { cout << " Yes " << endl ; } else { cout << " No " << endl ; } } int main ( ) { string str1 = " we β all β love β geeksforgeeks " ; string str2 = " we β all β love β geeks " ; isPossible ( str1 , str2 ) ; return 0 ; } |
Minimum number of flipping adjacent bits required to make given Binary Strings equal | C ++ program for the above approach ; Function to find the minimum number of inversions required . ; Initializing the answer ; Iterate over the range ; If s1 [ i ] != s2 [ i ] , then inverse the characters at i snd ( i + 1 ) positions in s1 . ; Adding 1 to counter if characters are not same ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int find_Min_Inversion ( int n , string s1 , string s2 ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( s1 [ i ] != s2 [ i ] ) { if ( s1 [ i ] == '1' ) { s1 [ i ] = '0' ; } else { s1 [ i ] = '1' ; } if ( s1 [ i + 1 ] == '1' ) { s1 [ i + 1 ] = '0' ; } else { s1 [ i + 1 ] = '1' ; } count ++ ; } } if ( s1 == s2 ) { return count ; } return -1 ; } int main ( ) { int n = 4 ; string s1 = "0101" ; string s2 = "1111" ; cout << find_Min_Inversion ( n , s1 , s2 ) << endl ; return 0 ; } |
Longest subsequence with consecutive English alphabets | C ++ program for the above approach ; Function to find the length of subsequence starting with character ch ; Length of the string ; Stores the maximum length ; Traverse the given string ; If s [ i ] is required character ch ; Increment ans by 1 ; Increment character ch ; Return the current maximum length with character ch ; Function to find the maximum length of subsequence of consecutive characters ; Stores the maximum length of consecutive characters ; Update ans ; Return the maximum length of subsequence ; Driver Code ; Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubsequence ( string S , char ch ) { int N = S . length ( ) ; int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ch ) { ans ++ ; ch ++ ; } } return ans ; } int findMaxSubsequence ( string S ) { int ans = 0 ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) { ans = max ( ans , findSubsequence ( S , ch ) ) ; } return ans ; } int main ( ) { string S = " abcabefghijk " ; cout << findMaxSubsequence ( S ) ; return 0 ; } |
Minimum number of alternate subsequences required to be removed to empty a Binary String | C ++ program for the above approach ; Function to find the minimum number of operations to empty a binary string ; Stores the resultant number of operations ; Stores the number of 0 s ; Stores the number of 1 s ; Traverse the given string ; To balance 0 with 1 if possible ; Increment the value of cn0 by 1 ; To balance 1 with 0 if possible ; Increment the value of cn1 ; Update the maximum number of unused 0 s and 1 s ; Print the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOpsToEmptyString ( string s ) { int ans = INT_MIN ; int cn0 = 0 ; int cn1 = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '0' ) { if ( cn1 > 0 ) cn1 -- ; cn0 ++ ; } else { if ( cn0 > 0 ) cn0 -- ; cn1 ++ ; } ans = max ( { ans , cn0 , cn1 } ) ; } cout << ans ; } int main ( ) { string S = "010101" ; minOpsToEmptyString ( S ) ; return 0 ; } |
Smallest string obtained by removing all occurrences of 01 and 11 from Binary String | Set 2 | C ++ program for the above approach ; Function to find the length of the smallest string possible by removing substrings "01" and "11" ; Stores the length of the smallest string ; Traverse the string S ; If st is greater than 0 and S [ i ] is '1' ; Delete the last character and decrement st by 1 ; Otherwise ; Increment st by 1 ; Return the answer in st ; Driver Code ; Input ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int shortestString ( string S , int N ) { int st = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( st && S [ i ] == '1' ) { st -- ; } else { st ++ ; } } return st ; } int main ( ) { string S = "1010" ; int N = S . length ( ) ; cout << shortestString ( S , N ) ; return 0 ; } |
Longest Non | C ++ program for the above approach ; Function to find the length of the longest non - increasing subsequence ; Stores the prefix and suffix count of 1 s and 0 s respectively ; Initialize the array ; Store the number of '1' s up to current index i in pre ; Find the prefix sum ; If the current element is '1' , update the pre [ i ] ; Store the number of '0' s over the range [ i , N - 1 ] ; Find the suffix sum ; If the current element is '0' , update post [ i ] ; Stores the maximum length ; Find the maximum value of pre [ i ] + post [ i ] ; Return the answer ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findLength ( string str , int n ) { int pre [ n ] , post [ n ] ; memset ( pre , 0 , sizeof ( pre ) ) ; memset ( post , 0 , sizeof ( post ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i != 0 ) { pre [ i ] += pre [ i - 1 ] ; } if ( str [ i ] == '1' ) { pre [ i ] += 1 ; } } for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i != n - 1 ) post [ i ] += post [ i + 1 ] ; if ( str [ i ] == '0' ) post [ i ] += 1 ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans = max ( ans , pre [ i ] + post [ i ] ) ; } return ans ; } int main ( ) { string S = "0101110110100001011" ; cout << findLength ( S , S . length ( ) ) ; return 0 ; } |
Number of substrings having an equal number of lowercase and uppercase letters | C ++ program for the above approach ; Function to find the count of substrings having an equal number of uppercase and lowercase characters ; Stores the count of prefixes having sum S considering uppercase and lowercase characters as 1 and - 1 ; Stores the count of substrings having equal number of lowercase and uppercase characters ; Stores the sum obtained so far ; If the character is uppercase ; Otherwise ; If currsum is o ; If the current sum exists in the HashMap prevSum ; Increment the resultant count by 1 ; Update the frequency of the current sum by 1 ; Return the resultant count of the subarrays ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstring ( string & S , int N ) { unordered_map < int , int > prevSum ; int res = 0 ; int currentSum = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] >= ' A ' and S [ i ] <= ' Z ' ) { currentSum ++ ; } else currentSum -- ; if ( currentSum == 0 ) res ++ ; if ( prevSum . find ( currentSum ) != prevSum . end ( ) ) { res += ( prevSum [ currentSum ] ) ; } prevSum [ currentSum ] ++ ; } return res ; } int main ( ) { string S = " gEEk " ; cout << countSubstring ( S , S . length ( ) ) ; return 0 ; } |
Count new pairs of strings that can be obtained by swapping first characters of pairs of strings from given array | C ++ program for the above approach ; Function to count new pairs of strings that can be obtained by swapping first characters of any pair of strings ; Stores the count of pairs ; Generate all possible pairs of strings from the array arr [ ] ; Stores the current pair of strings ; Swap the first characters ; Check if they are already present in the array or not ; If both the strings are not present ; Increment the ans by 1 ; Print the resultant count ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countStringPairs ( string a [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { string p = a [ i ] , q = a [ j ] ; if ( p [ 0 ] != q [ 0 ] ) { swap ( p [ 0 ] , q [ 0 ] ) ; int flag1 = 0 ; int flag2 = 0 ; for ( int k = 0 ; k < n ; k ++ ) { if ( a [ k ] == p ) { flag1 = 1 ; } if ( a [ k ] == q ) { flag2 = 1 ; } } if ( flag1 == 0 && flag2 == 0 ) { ans = ans + 1 ; } } } } cout << ans ; } int main ( ) { string arr [ ] = { " good " , " bad " , " food " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; countStringPairs ( arr , N ) ; return 0 ; } |
Modify string by replacing characters by alphabets whose distance from that character is equal to its frequency | C ++ program for the above approach ; Function to modify string by replacing characters by the alphabet present at distance equal to frequency of the string ; Stores frequency of characters ; Stores length of the string ; Traverse the given string S ; Increment frequency of current character by 1 ; Traverse the string ; Store the value to be added to the current character ; Check if after adding the frequency , the character is less than ' z ' or not ; Otherwise , update the value of add so that s [ i ] doesn ' t β exceed β ' z ' ; Print the modified string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addFrequencyToCharacter ( string s ) { int frequency [ 26 ] = { 0 } ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { frequency [ s [ i ] - ' a ' ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { int add = frequency [ s [ i ] - ' a ' ] % 26 ; if ( int ( s [ i ] ) + add <= int ( ' z ' ) ) s [ i ] = char ( int ( s [ i ] ) + add ) ; else { add = ( int ( s [ i ] ) + add ) - ( int ( ' z ' ) ) ; s [ i ] = char ( int ( ' a ' ) + add - 1 ) ; } } cout << s ; } int main ( ) { string str = " geeks " ; addFrequencyToCharacter ( str ) ; return 0 ; } |
Check if it is possible to reach any point on the circumference of a given circle from origin | C ++ program for the above approach ; Function to check if it is possible to reach any point on circumference of the given circle from ( 0 , 0 ) ; Stores the count of ' L ' , ' R ' ; Stores the count of ' U ' , ' D ' ; Traverse the string S ; Update the count of L ; Update the count of R ; Update the count of U ; Update the count of D ; Condition 1 for reaching the circumference ; Store the the value of ( i * i ) in the Map ; Check if ( r_square - i * i ) already present in HashMap ; If it is possible to reach the point ( mp [ r_square - i * i ] , i ) ; If it is possible to reach the point ( i , mp [ r_square - i * i ] ) ; If it is impossible to reach ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string isPossible ( string S , int R , int N ) { int cntl = 0 , cntr = 0 ; int cntu = 0 , cntd = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' L ' ) cntl ++ ; else if ( S [ i ] == ' R ' ) cntr ++ ; else if ( S [ i ] == ' U ' ) cntu ++ ; else cntd ++ ; } if ( max ( max ( cntl , cntr ) , max ( cntu , cntd ) ) >= R ) return " Yes " ; unordered_map < int , int > mp ; int r_square = R * R ; for ( int i = 1 ; i * i <= r_square ; i ++ ) { mp [ i * i ] = i ; if ( mp . find ( r_square - i * i ) != mp . end ( ) ) { if ( max ( cntl , cntr ) >= mp [ r_square - i * i ] && max ( cntu , cntd ) >= i ) return " Yes " ; if ( max ( cntl , cntr ) >= i && max ( cntu , cntd ) >= mp [ r_square - i * i ] ) return " Yes " ; } } return " No " ; } int main ( ) { string S = " RDLLDDLDU " ; int R = 5 ; int N = S . length ( ) ; cout << isPossible ( S , R , N ) ; return 0 ; } |
Modify characters of a string by adding integer values of same | C ++ program for the above approach ; Function to modify a given string by adding ASCII value of characters from a string S to integer values of same indexed characters in string N ; Traverse the string ; Stores integer value of character in string N ; Stores ASCII value of character in string S ; If b exceeds 122 ; Replace the character ; Print resultant string ; Driver Code ; Given strings ; Function call to modify string S by given operations | #include <bits/stdc++.h> NEW_LINE using namespace std ; void addASCII ( string S , string N ) { for ( int i = 0 ; i < S . size ( ) ; i ++ ) { int a = int ( N [ i ] ) - '0' ; int b = int ( S [ i ] ) + a ; if ( b > 122 ) b -= 26 ; S [ i ] = char ( b ) ; } cout << S ; } int main ( ) { string S = " sun " , N = "966" ; addASCII ( S , N ) ; return 0 ; } |
Modify array by removing characters from their Hexadecimal representations which are present in a given string | C ++ program for the above approach ; Function to convert a decimal number to its equivalent hexadecimal number ; Function to convert hexadecimal number to its equavalent decimal number ; Stores characters with their respective hexadecimal values ; Stores answer ; Traverse the string ; If digit ; If character ; Return the answer ; Function to move all the alphabets to front ; Function to modify each array element by removing characters from their hexadecimal representation which are present in a given string ; Traverse the array ; Stores hexadecimal value ; Remove the characters from hexadecimal representation present in string S ; Stores decimal value ; Replace array element ; Print the modified array ; Driven Program ; Given array ; Given string ; Function call to modify array by given operations | #include <bits/stdc++.h> NEW_LINE using namespace std ; string decHex ( int n ) { char alpha [ ] = { ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F ' } ; string ans ; while ( n > 0 ) { if ( n % 16 < 10 ) { ans += to_string ( n % 16 ) ; } else { ans += alpha [ n % 16 - 10 ] ; } n /= 16 ; } reverse ( ans . begin ( ) , ans . end ( ) ) ; return ans ; } int hexDec ( string convertedHex ) { char mp [ ] = { 10 , 11 , 12 , 13 , 14 , 15 } ; int ans = 0 ; int pos = 0 ; reverse ( convertedHex . begin ( ) , convertedHex . end ( ) ) ; for ( char ch : convertedHex ) { if ( isdigit ( ch ) ) { ans += ( ( int ) pow ( 16 , pos ) ) * ( ch - '0' ) ; } else { ans += ( ( int ) pow ( 16 , pos ) ) * mp [ ch - ' A ' ] ; } pos += 1 ; } return ans ; } string removeChars ( string hexaVal , string S ) { set < char > setk ; for ( char ch : S ) { setk . insert ( ch ) ; } string ans = " " ; for ( char ch : hexaVal ) { if ( setk . find ( ch ) != setk . end ( ) ) { continue ; } ans += ch ; } return ans ; } void convertArr ( int arr [ ] , int N , string S ) { for ( int i = 0 ; i < N ; i ++ ) { string hexaVal = decHex ( arr [ i ] ) ; string convertedHex = removeChars ( hexaVal , S ) ; int decVal = hexDec ( convertedHex ) ; arr [ i ] = decVal ; } for ( int i = 0 ; i < N ; i ++ ) { cout << arr [ i ] << " β " ; } } int main ( ) { int arr [ ] = { 74 , 91 , 31 , 122 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string S = "1AB " ; convertArr ( arr , N , S ) ; return 0 ; } |
Minimum number of chairs required to ensure that every worker is seated at any instant | C ++ implementation of the above approach ; Function to find the minimum number of chairs required to ensure that every worker is seated at any time ; Stores the number of chairs required ; Pointer to iterate ; Stores minimum number of chairs required ; Iterate over every character ; If character is ' E ' ; Increase the count ; Otherwise ; Update maximum value of count obtained at any given time ; Return mini ; Driver Code ; Given String ; Function call to find the minimum number of chairs | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinimumChairs ( string s ) { int count = 0 ; int i = 0 ; int mini = INT_MIN ; while ( i < s . length ( ) ) { if ( s [ i ] == ' E ' ) count ++ ; else count -- ; mini = max ( count , mini ) ; i ++ ; } return mini ; } int main ( ) { string s = " EELEE " ; cout << findMinimumChairs ( s ) ; } |
Modify string by inserting characters such that every K | C ++ program for the above approach ; Function to replace all ' ? ' characters in a string such that the given conditions are satisfied ; Traverse the string to Map the characters with respective positions ; Traverse the string again and replace all unknown characters ; If i % k is not found in the Map M , then return - 1 ; Update S [ i ] ; Print the string S ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void fillString ( string s , int k ) { unordered_map < int , char > mp ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] != ' ? ' ) { mp [ i % k ] = s [ i ] ; } } for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( mp . find ( i % k ) == mp . end ( ) ) { cout << -1 ; return ; } s [ i ] = mp [ i % k ] ; } cout << s ; } int main ( ) { string S = " ? ? ? ? abcd " ; int K = 4 ; fillString ( S , K ) ; return 0 ; } |
Rearrange a string S1 such that another given string S2 is not its subsequence | C ++ program for the above approach ; Function to rearrange characters in string S1 such that S2 is not a subsequence of it ; Store the frequencies of characters of string s2 ; Traverse the string s2 ; Update the frequency ; Find the number of unique characters in s2 ; Increment unique by 1 if the condition satisfies ; Check if the number of unique characters in string s2 is 1 ; Store the unique character frequency ; Store occurence of it in s1 ; Find count of that character in the string s1 ; Increment count by 1 if that unique character is same as current character ; If count count_in_s1 is less than count_in_s2 , then print s1 and return ; Otherwise , there is no possible arrangement ; Checks if any character in s2 is less than its next character ; Iterate the string , s2 ; If s [ i ] is greater than the s [ i + 1 ] ; Set inc to 0 ; If inc = 1 , print s1 in decreasing order ; Otherwise , print s1 in increasing order ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void rearrangeString ( string s1 , string s2 ) { int cnt [ 26 ] = { 0 } ; for ( int i = 0 ; i < s2 . size ( ) ; i ++ ) cnt [ s2 [ i ] - ' a ' ] ++ ; int unique = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( cnt [ i ] != 0 ) unique ++ ; if ( unique == 1 ) { int count_in_s2 = s2 . size ( ) ; int count_in_s1 = 0 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) if ( s1 [ i ] == s2 [ 0 ] ) count_in_s1 ++ ; if ( count_in_s1 < count_in_s2 ) { cout << s1 ; return ; } cout << -1 ; } else { int inc = 1 ; for ( int i = 0 ; i < s2 . size ( ) - 1 ; i ++ ) if ( s2 [ i ] > s2 [ i + 1 ] ) inc = 0 ; if ( inc == 1 ) { sort ( s1 . begin ( ) , s1 . end ( ) , greater < char > ( ) ) ; cout << s1 ; } else { sort ( s1 . begin ( ) , s1 . end ( ) ) ; cout << s1 ; } } } int main ( ) { string s1 = " abcd " , s2 = " ab " ; rearrangeString ( s1 , s2 ) ; return 0 ; } |
Check if a string can be emptied by removing all subsequences of the form "10" | C ++ program for the above approach ; Function to find if string is reducible to NULL ; Length of string ; Stack to store all 1 s ; Iterate over the characters of the string ; If current character is 1 ; Push it into the stack ; Pop from the stack ; If the stack is empty ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isReducible ( string str ) { int N = str . size ( ) ; stack < char > s ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == '1' ) s . push ( str [ i ] ) ; else if ( ! s . empty ( ) ) s . pop ( ) ; else return false ; } return s . empty ( ) ; } int main ( ) { string str = "11011000" ; if ( isReducible ( str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Minimize flips required such that string does not any pair of consecutive 0 s | C ++ program for the above approach ; Function to find minimum flips required such that a string does not contain any pair of consecutive 0 s ; Stores minimum count of flips ; Iterate over the characters of the string ; If two consecutive characters are equal to '0' ; Update S [ i + 1 ] ; Update cntOp ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool cntMinOperation ( string S , int N ) { int cntOp = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( S [ i ] == '0' && S [ i + 1 ] == '0' ) { S [ i + 1 ] = '1' ; cntOp += 1 ; } } return cntOp ; } int main ( ) { string S = "10001" ; int N = S . length ( ) ; cout << cntMinOperation ( S , N ) ; return 0 ; } |
Rearrange a string to maximize the minimum distance between any pair of vowels | C ++ program for the above approach ; Function to rearrange the string such that the minimum distance between any of vowels is maximum . ; Store vowels and consonants ; Iterate over the characters of string ; If current character is a vowel ; If current character is a consonant ; Stores count of vowels and consonants respectively ; Stores the resultant string ; Stores count of consonants appended into ans ; Append vowel to ans ; Append consonants ; Append consonant to ans ; Update temp ; Remove the taken elements of consonant ; Return final ans ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string solution ( string s ) { vector < char > vowel , consonant ; for ( auto i : s ) { if ( i == ' a ' i == ' e ' i == ' i ' i == ' o ' i == ' u ' ) { vowel . push_back ( i ) ; } else { consonant . push_back ( i ) ; } } int Nc , Nv ; Nv = vowel . size ( ) ; Nc = consonant . size ( ) ; int M = Nc / ( Nv - 1 ) ; string ans = " " ; int consotnant_till = 0 ; for ( auto i : vowel ) { ans += i ; int temp = 0 ; for ( int j = consotnant_till ; j < min ( Nc , consotnant_till + M ) ; j ++ ) { ans += consonant [ j ] ; temp ++ ; } consotnant_till += temp ; } return ans ; } int main ( ) { string str = " aaaabbbcc " ; cout << solution ( str ) ; return 0 ; } |
Lexicographically smallest string possible by performing K operations on a given string | C ++ program to implement the above approach ; Function to find the lexicographically smallest possible string by performing K operations on string S ; Store the size of string , s ; Check if k >= n , if true , convert every character to ' a ' ; Iterate in range [ 0 , n - 1 ] using i ; When k reaches 0 , break the loop ; If current character is ' a ' , continue ; Otherwise , iterate in the range [ i + 1 , n - 1 ] using j ; Check if s [ j ] > s [ i ] ; If true , set s [ j ] = s [ i ] and break out of the loop ; Check if j reaches the last index ; Update S [ i ] ; Decrement k by 1 ; Print string ; Driver Code ; Given String , s ; Given k ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void smallestlexicographicstring ( string s , int k ) { int n = s . size ( ) ; if ( k >= n ) { for ( int i = 0 ; i < n ; i ++ ) { s [ i ] = ' a ' ; } cout << s ; return ; } for ( int i = 0 ; i < n ; i ++ ) { if ( k == 0 ) { break ; } if ( s [ i ] == ' a ' ) continue ; for ( int j = i + 1 ; j < n ; j ++ ) { if ( s [ j ] > s [ i ] ) { s [ j ] = s [ i ] ; break ; } else if ( j == n - 1 ) s [ j ] = s [ i ] ; } s [ i ] = ' a ' ; k -- ; } cout << s ; } int main ( ) { string s = " geeksforgeeks " ; int k = 6 ; smallestlexicographicstring ( s , k ) ; return 0 ; } |
Minimize removal of non | C ++ program for the above approach ; Function to find minimum count of steps required ot make string S an empty string ; Stores count of occurences ' ( ' ; Stores count of occurences ' ) ' ; Traverse the string , str ; If current character is ' ( ' ; Update count_1 ; Update count_2 ; If all the characters are same , then print - 1 ; If the count of occurence of ' ) ' and ' ( ' are same then print 0 ; If length of string is Odd ; Driver Code ; Given string ; Size of the string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void canReduceString ( string S , int N ) { int count_1 = 0 ; int count_2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' ( ' ) { count_1 ++ ; } else { count_2 ++ ; } } if ( count_1 == 0 count_2 == 0 ) { cout << " - 1" << endl ; } else if ( count_1 == count_2 ) { cout << "0" << endl ; } else if ( N % 2 != 0 ) { cout << " - 1" ; } else { cout << abs ( count_1 - count_2 ) / 2 ; } } int main ( ) { string S = " ) ) ) ( ( ( " ; int N = S . length ( ) ; canReduceString ( S , N ) ; return 0 ; } |
Program to construct a DFA which accepts the language L = { aN | N Γ’ β°Β₯ 1 } | C ++ program for the above approach ; Function to check whether the string S satisfy the given DFA or not ; Stores the count of characters ; Iterate over the range [ 0 , N ] ; Count and check every element for ' a ' ; If string matches with DFA ; If not matches ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isAcceptedDFA ( string s , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( s [ i ] == ' a ' ) count ++ ; } if ( count == N && count != 0 ) { cout << " Accepted " ; } else { cout << " Not β Accepted " ; } } int main ( ) { string S = " aaaaa " ; isAcceptedDFA ( S , S . size ( ) ) ; return 0 ; } |
Maximize palindromic strings of length 3 possible from given count of alphabets | C ++ program for the above approach ; Function to count maximum number of palindromic string of length 3 ; Stores the final count of palindromic strings ; Traverse the array ; Increment res by arr [ i ] / 3 , i . e forming string of only i + ' a ' character ; Store remainder ; Increment c1 by one , if current frequency is 1 ; Increment c2 by one , if current frequency is 2 ; Count palindromic strings of length 3 having the character at the ends different from that present in the middle ; Update c1 and c2 ; Increment res by 2 * c2 / 3 ; Finally print the result ; Driver Code ; Given array ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maximum_pallindromic ( int arr [ ] ) { int res = 0 ; int c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { res += arr [ i ] / 3 ; arr [ i ] = arr [ i ] % 3 ; if ( arr [ i ] == 1 ) c1 ++ ; else if ( arr [ i ] == 2 ) c2 ++ ; } res += min ( c1 , c2 ) ; int t = min ( c1 , c2 ) ; c1 -= t ; c2 -= t ; res += 2 * ( c2 / 3 ) ; c2 %= 3 ; res += c2 / 2 ; cout << res ; } int main ( ) { int arr [ ] = { 4 , 5 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ; maximum_pallindromic ( arr ) ; return 0 ; } |