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 Subsequ... | #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... |
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... | #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 - ... |
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 in... | #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 ... |
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... | #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 ] [ ... |
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 ... | #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 ... |
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... |
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 - p... | #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 [ ... |
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_he... | #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... |
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 ... | #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 ] ... |
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 β... |
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... | #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 ( ) { ... |
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 . ... | #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 ) ... |
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[] Bel... | #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 ... |
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 ... | #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 ] ] ; retu... |
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 ,... | #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 β p... |
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... | #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 ]... |
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... | #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 ] ... |
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 ; P... | #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 ] + ... |
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 partitio... | #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 <... |
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 ... | #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 == ... |
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 ) ... |
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 ... | #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 ++... |
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 ... | #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... |
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... | #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... |
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 choo... | #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 ] [ bCou... |
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 ... | #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 ... |
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 arra... | #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 *... |
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 e... | #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 [... |
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 ... | #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... |
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 larges... | #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... |
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 fro... | #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 += countGrou... |
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 leng... | #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 [ ... |
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 ] stor... | #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 [... |
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... | #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 ... |
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 ... | #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 ... |
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 ]... | #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 ( ... |
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 ] ; initi... | #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 ++ )... |
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 str... | #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 ... |
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... | #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... |
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 t... | #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 ] ;... |
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... | #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... |
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 r... | #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 ) retu... |
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 le... | #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 , l... |
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 solutio... | #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 (... |
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 , ... | #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 + g... |
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 ( ... |
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 (... |
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 ; }... |
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 ; Maintain... | #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 ] ; i... |
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... |
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 ... | #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 ( ) ; in... |
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 e... | #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 .... |
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 vecto... | #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 ( vec... |
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... | #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... |
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 ; ... | #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 ++ ... |
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 ; Retur... | #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 ] ) { retur... |
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 ; Numbe... | #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 ( ... |
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 differe... | #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 ... |
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 ; } in... |
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... | #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 [ l... |
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 << finalNu... |
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... | #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 ( st... |
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... | #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 ] ; } e... |
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 repr... | #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 ) ; whil... |
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 r... | #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 ... |
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 ... |
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 ] , th... | #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 ; } ... |
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 si... | #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 ++ ;... |
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 = ... |
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 c... | #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 ... |
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 ... | #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 ( ) ... |
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 ... |
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 com... | #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 ... |
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 ) position... | #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' ; ... |
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 chara... | #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 ... |
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 giv... | #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 , cn... |
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... | #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... |
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 '... | #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 ]... |
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... | #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... |
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 pa... | #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... |
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 ... | #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 (... |
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 ' ; Trave... | #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 ++ ; }... |
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 ; St... | #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" ; addA... |
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 w... | #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 .... |
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 numbe... | #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 " ; cou... |
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 char... | #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 ( ) ) {... |
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 numbe... | #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... |
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 t... | #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 ( ) ... |
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 c... | #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... |
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 vowe... | #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 = ... |
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 chara... | #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 ' ) contin... |
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 t... | #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 == c... |
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 D... | #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 "... |
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 ... | #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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.