text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Find if string is K | A Naive recursive C ++ program to find if given string is K - Palindrome or not ; find if given string is K - Palindrome or not ; If first string is empty , the only option is to remove all characters of second string ; If second string is empty , the only option is to remove all characters of first string ; If last characters of two strings are same , ignore last characters and get count for remaining strings . ; If last characters are not same , 1. Remove last char from str1 and recur for m - 1 and n 2. Remove last char from str2 and recur for m and n - 1 Take minimum of above two operations return 1 + min ( isKPalRec ( str1 , str2 , m - 1 , n ) , Remove from str1 isKPalRec ( str1 , str2 , m , n - 1 ) ) ; Remove from str2 ; Returns true if str is k palindrome . ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int isKPalRec ( string str1 , string str2 , int m , int n ) { if ( m == 0 ) return n ; if ( n == 0 ) return m ; if ( str1 [ m - 1 ] == str2 [ n - 1 ] ) return isKPalRec ( str1 , str2 , m - 1 , n - 1 ) ; } bool isKPal ( string str , int k ) { string revStr = str ; reverse ( revStr . begin ( ) , revStr . end ( ) ) ; int len = str . length ( ) ; return ( isKPalRec ( str , revStr , len , len ) <= k * 2 ) ; } int main ( ) { string str = " acdcb " ; int k = 2 ; isKPal ( str , k ) ? cout << " Yes " : cout << " No " ; return 0 ; } |
Minimum time to finish tasks without skipping two consecutive | C ++ program to find minimum time to finish tasks such that no two consecutive tasks are skipped . ; arr [ ] represents time taken by n given tasks ; Corner Cases ; Initialize value for the case when there is only one task in task list . First task is included ; First task is exluded ; Process remaining n - 1 tasks ; Time taken if current task is included There are two possibilities ( a ) Previous task is also included ( b ) Previous task is not included ; Time taken when current task is not included . There is only one possibility that previous task is also included . ; Update incl and excl for next iteration ; Return maximum of two values for last task ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minTime ( int arr [ ] , int n ) { if ( n <= 0 ) return 0 ; int incl = arr [ 0 ] ; int excl = 0 ; for ( int i = 1 ; i < n ; i ++ ) { int incl_new = arr [ i ] + min ( excl , incl ) ; int excl_new = incl ; incl = incl_new ; excl = excl_new ; } return min ( incl , excl ) ; } int main ( ) { int arr1 [ ] = { 10 , 5 , 2 , 7 , 10 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << minTime ( arr1 , n1 ) << endl ; int arr2 [ ] = { 10 , 5 , 7 , 10 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << minTime ( arr2 , n2 ) << endl ; int arr3 [ ] = { 10 , 5 , 2 , 4 , 8 , 6 , 7 , 10 } ; int n3 = sizeof ( arr3 ) / sizeof ( arr3 [ 0 ] ) ; cout << minTime ( arr3 , n3 ) << endl ; return 0 ; } |
A Space Optimized Solution of LCS | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Find lengths of two strings ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] | int lcs ( string & X , string & Y ) { int m = X . length ( ) , n = Y . length ( ) ; 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 ] + 1 ; else L [ i ] [ j ] = max ( L [ i - 1 ] [ j ] , L [ i ] [ j - 1 ] ) ; } } return L [ m ] [ n ] ; } |
Matrix Exponentiation | C ++ program to find value of f ( n ) where f ( n ) is defined as F ( n ) = F ( n - 1 ) + F ( n - 2 ) + F ( n - 3 ) , n >= 3 Base Cases : F ( 0 ) = 0 , F ( 1 ) = 1 , F ( 2 ) = 1 ; A utility function to multiply two matrices a [ ] [ ] and b [ ] [ ] . Multiplication result is stored back in b [ ] [ ] ; Creating an auxiliary matrix to store elements of the multiplication matrix ; storing the multiplication result in a [ ] [ ] ; Updating our matrix ; Function to compute F raise to power n - 2. ; Multiply it with initial values i . e with F ( 0 ) = 0 , F ( 1 ) = 1 , F ( 2 ) = 1 ; Multiply it with initial values i . e with F ( 0 ) = 0 , F ( 1 ) = 1 , F ( 2 ) = 1 ; Return n 'th term of a series defined using below recurrence relation. f(n) is defined as f(n) = f(n-1) + f(n-2) + f(n-3), n>=3 Base Cases : f(0) = 0, f(1) = 1, f(2) = 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void multiply ( int a [ 3 ] [ 3 ] , int b [ 3 ] [ 3 ] ) { int mul [ 3 ] [ 3 ] ; for ( int i = 0 ; i < 3 ; i ++ ) { for ( int j = 0 ; j < 3 ; j ++ ) { mul [ i ] [ j ] = 0 ; for ( int k = 0 ; k < 3 ; k ++ ) mul [ i ] [ j ] += a [ i ] [ k ] * b [ k ] [ j ] ; } } for ( int i = 0 ; i < 3 ; i ++ ) for ( int j = 0 ; j < 3 ; j ++ ) a [ i ] [ j ] = mul [ i ] [ j ] ; } int power ( int F [ 3 ] [ 3 ] , int n ) { int M [ 3 ] [ 3 ] = { { 1 , 1 , 1 } , { 1 , 0 , 0 } , { 0 , 1 , 0 } } ; if ( n == 1 ) return F [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] ; power ( F , n / 2 ) ; multiply ( F , F ) ; if ( n % 2 != 0 ) multiply ( F , M ) ; return F [ 0 ] [ 0 ] + F [ 0 ] [ 1 ] ; } int findNthTerm ( int n ) { int F [ 3 ] [ 3 ] = { { 1 , 1 , 1 } , { 1 , 0 , 0 } , { 0 , 1 , 0 } } ; if ( n == 0 ) return 0 ; if ( n == 1 n == 2 ) return 1 ; return power ( F , n - 2 ) ; } int main ( ) { int n = 5 ; cout << " F ( 5 ) β is β " << findNthTerm ( n ) ; return 0 ; } |
Count number of ways to fill a " n β x β 4" grid using "1 β x β 4" tiles | C ++ program to count of ways to place 1 x 4 tiles on n x 4 grid . ; Returns count of count of ways to place 1 x 4 tiles on n x 4 grid . ; Create a table to store results of subproblems dp [ i ] stores count of ways for i x 4 grid . ; Fill the table from d [ 1 ] to dp [ n ] ; Base cases ; dp ( i - 1 ) : Place first tile horizontally dp ( n - 4 ) : Place first tile vertically which means 3 more tiles have to be placed vertically . ; Driver program to test above | #include <iostream> NEW_LINE using namespace std ; int count ( int n ) { int dp [ n + 1 ] ; dp [ 0 ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { if ( i >= 1 && i <= 3 ) dp [ i ] = 1 ; else if ( i == 4 ) dp [ i ] = 2 ; else dp [ i ] = dp [ i - 1 ] + dp [ i - 4 ] ; } return dp [ n ] ; } int main ( ) { int n = 5 ; cout << " Count β of β ways β is β " << count ( n ) ; return 0 ; } |
Compute nCr % p | Set 1 ( Introduction and Dynamic Programming Solution ) | A Dynamic Programming based solution to compute nCr % p ; Returns nCr % p ; Optimization for the cases when r is large ; The array C is going to store last row of pascal triangle at the end . And last entry of last row is nCr ; Top row of Pascal Triangle ; One by constructs remaining rows of Pascal Triangle from top to bottom ; Fill entries of current row using previous row values ; nCj = ( n - 1 ) Cj + ( n - 1 ) C ( j - 1 ) ; ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int nCrModp ( int n , int r , int p ) { if ( r > n - r ) r = n - r ; int C [ r + 1 ] ; memset ( C , 0 , sizeof ( C ) ) ; C [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = min ( i , r ) ; j > 0 ; j -- ) C [ j ] = ( C [ j ] + C [ j - 1 ] ) % p ; } return C [ r ] ; } int main ( ) { int n = 10 , r = 2 , p = 13 ; cout << " Value β of β nCr β % β p β is β " << nCrModp ( n , r , p ) ; return 0 ; } |
Count Derangements ( Permutation such that no element appears in its original position ) | C ++ implementation of the above approach ; Function to count derangements ; base case ; Variable for just storing previous values ; using above recursive formula ; Return result for n ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int countDer ( int n ) { if ( n == 1 or n == 2 ) { return n - 1 ; } int a = 0 ; int b = 1 ; for ( int i = 3 ; i <= n ; ++ i ) { int cur = ( i - 1 ) * ( a + b ) ; a = b ; b = cur ; } return b ; } int main ( ) { cout << " Count β of β Dearrangements β is β " << countDer ( 4 ) ; return 0 ; } |
Bell Numbers ( Number of ways to Partition a Set ) | A C ++ program to find n 'th Bell number ; Function to find n 'th Bell Number ; Explicitly fill for j = 0 ; Fill for remaining values of j ; Driver program | #include <iostream> NEW_LINE using namespace std ; int bellNumber ( int n ) { int bell [ n + 1 ] [ n + 1 ] ; bell [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { int bellNumber ( int n ) { int bell [ n + 1 ] [ n + 1 ] ; bell [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { bell [ i ] [ 0 ] = bell [ i - 1 ] [ i - 1 ] ; for ( int j = 1 ; j <= i ; j ++ ) bell [ i ] [ j ] = bell [ i - 1 ] [ j - 1 ] + bell [ i ] [ j - 1 ] ; } return bell [ n ] [ 0 ] ; } int main ( ) { for ( int n = 0 ; n <= 5 ; n ++ ) cout << " Bell β Number β " << n << " β is β " << bellNumber ( n ) << endl ; return 0 ; } |
Count number of ways to cover a distance | A Dynamic Programming based C ++ program to count number of ways to cover a distance with 1 , 2 and 3 steps ; Function returns count of ways to cover ' dist ' ; Initialize base values . There is one way to cover 0 and 1 distances and two ways to cover 2 distance ; Fill the count array in bottom up manner ; driver program | #include <iostream> NEW_LINE using namespace std ; int printCountDP ( int dist ) { int count [ dist + 1 ] ; count [ 0 ] = 1 ; if ( dist >= 1 ) count [ 1 ] = 1 ; if ( dist >= 2 ) count [ 2 ] = 2 ; for ( int i = 3 ; i <= dist ; i ++ ) count [ i ] = count [ i - 1 ] + count [ i - 2 ] + count [ i - 3 ] ; return count [ dist ] ; } int main ( ) { int dist = 4 ; cout << printCountDP ( dist ) ; return 0 ; } |
Count even length binary sequences with same sum of first and second half bits | C ++ program to find remaining chocolates after k iterations ; Returns the count of even length sequences ; Calculate SUM ( ( nCr ) ^ 2 ) ; Compute nCr using nC ( r - 1 ) nCr / nC ( r - 1 ) = ( n + 1 - r ) / r ; ; Driver code | #include <iostream> NEW_LINE using namespace std ; int countSeq ( int n ) { int nCr = 1 , res = 1 ; for ( int r = 1 ; r <= n ; r ++ ) { nCr = ( nCr * ( n + 1 - r ) ) / r ; res += nCr * nCr ; } return res ; } int main ( ) { int n = 2 ; cout << " Count β of β sequences β is β " << countSeq ( n ) ; return 0 ; } |
Remove minimum elements from either side such that 2 * min becomes more than max | C ++ program of above approach ; A utility function to find minimum of two numbers ; A utility function to find minimum in arr [ l . . h ] ; A utility function to find maximum in arr [ l . . h ] ; Returns the minimum number of removals from either end in arr [ l . . h ] so that 2 * min becomes greater than max . ; Create a table to store solutions of subproblems ; Fill table using above recursive formula . Note that the table is filled in diagonal fashion ( similar to http : goo . gl / PQqoS ) , from diagonal elements to table [ 0 ] [ n - 1 ] which is the result . ; Driver program to test above functions | #include <iostream> NEW_LINE using namespace std ; int min ( int a , int b ) { return ( a < b ) ? a : b ; } int min ( int arr [ ] , int l , int h ) { int mn = arr [ l ] ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( mn > arr [ i ] ) mn = arr [ i ] ; return mn ; } int max ( int arr [ ] , int l , int h ) { int mx = arr [ l ] ; for ( int i = l + 1 ; i <= h ; i ++ ) if ( mx < arr [ i ] ) mx = arr [ i ] ; return mx ; } int minRemovalsDP ( int arr [ ] , int n ) { int table [ n ] [ n ] , gap , i , j , mn , mx ; for ( gap = 0 ; gap < n ; ++ gap ) { for ( i = 0 , j = gap ; j < n ; ++ i , ++ j ) { mn = min ( arr , i , j ) ; mx = max ( arr , i , j ) ; table [ i ] [ j ] = ( 2 * mn > mx ) ? 0 : min ( table [ i ] [ j - 1 ] + 1 , table [ i + 1 ] [ j ] + 1 ) ; } } return table [ 0 ] [ n - 1 ] ; } int main ( ) { int arr [ ] = { 20 , 4 , 1 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minRemovalsDP ( arr , n ) ; return 0 ; } |
Count all possible paths from top left to bottom right of a mXn matrix | A C ++ program to count all possible paths from top left to bottom right ; Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; If either given row number is first or given column number is first ; If diagonal movements are allowed then the last addition is required . ; Driver Code | #include <iostream> NEW_LINE using namespace std ; int numberOfPaths ( int m , int n ) { if ( m == 1 n == 1 ) return 1 ; return numberOfPaths ( m - 1 , n ) + numberOfPaths ( m , n - 1 ) ; } int main ( ) { cout << numberOfPaths ( 3 , 3 ) ; return 0 ; } |
Count all possible paths from top left to bottom right of a mXn matrix | A C ++ program to count all possible paths from top left to top bottom using combinatorics ; We have to calculate m + n - 2 C n - 1 here which will be ( m + n - 2 ) ! / ( n - 1 ) ! ( m - 1 ) ! ; Driver code | #include <iostream> NEW_LINE using namespace std ; int numberOfPaths ( int m , int n ) { int path = 1 ; for ( int i = n ; i < ( m + n - 1 ) ; i ++ ) { path *= i ; path /= ( i - n + 1 ) ; } return path ; } int main ( ) { cout << numberOfPaths ( 3 , 3 ) ; return 0 ; } |
Longest Arithmetic Progression | DP | C ++ program to find Length of the Longest AP ( llap ) in a given sorted set . The code strictly implements the algorithm provided in the reference . ; Returns length of the longest AP subset in a given set ; Create a table and initialize all values as 2. The value of L [ i ] [ j ] stores LLAP with set [ i ] and set [ j ] as first two elements of AP . Only valid entries are the entries where j > i ; Initialize the result ; Fill entries in last column as 2. There will always be two elements in AP with last number of set as second element in AP ; Consider every element as second element of AP ; Search for i and k for j ; Before changing i , set L [ i ] [ j ] as 2 ; Found i and k for j , LLAP with i and j as first two elements is equal to LLAP 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 LLAP , if needed ; 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 entities in column j as 2 ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; int lenghtOfLongestAP ( int set [ ] , int n ) { if ( n <= 2 ) return n ; int L [ n ] [ n ] ; int llap = 2 ; for ( int i = 0 ; i < n ; i ++ ) L [ i ] [ n - 1 ] = 2 ; 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 ] < 2 * set [ j ] ) k ++ ; else if ( set [ i ] + set [ k ] > 2 * set [ j ] ) { L [ i ] [ j ] = 2 , i -- ; } else { L [ i ] [ j ] = L [ j ] [ k ] + 1 ; llap = max ( llap , L [ i ] [ j ] ) ; i -- ; k ++ ; } } while ( i >= 0 ) { L [ i ] [ j ] = 2 ; i -- ; } } return llap ; } int main ( ) { int set1 [ ] = { 1 , 7 , 10 , 13 , 14 , 19 } ; int n1 = sizeof ( set1 ) / sizeof ( set1 [ 0 ] ) ; cout << lenghtOfLongestAP ( set1 , n1 ) << endl ; int set2 [ ] = { 1 , 7 , 10 , 15 , 27 , 29 } ; int n2 = sizeof ( set2 ) / sizeof ( set2 [ 0 ] ) ; cout << lenghtOfLongestAP ( set2 , n2 ) << endl ; int set3 [ ] = { 2 , 4 , 6 , 8 , 10 } ; int n3 = sizeof ( set3 ) / sizeof ( set3 [ 0 ] ) ; cout << lenghtOfLongestAP ( set3 , n3 ) << endl ; return 0 ; } |
Maximum Manhattan distance between a distinct pair from N coordinates | C ++ program for the above approach ; Function to calculate the maximum Manhattan distance ; Vectors to store maximum and minimum of all the four forms ; Sorting both the vectors ; Driver Code ; Given Co - ordinates ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void MaxDist ( vector < pair < int , int > > & A , int N ) { vector < int > V ( N ) , V1 ( N ) ; for ( int i = 0 ; i < N ; i ++ ) { V [ i ] = A [ i ] . first + A [ i ] . second ; V1 [ i ] = A [ i ] . first - A [ i ] . second ; } sort ( V . begin ( ) , V . end ( ) ) ; sort ( V1 . begin ( ) , V1 . end ( ) ) ; int maximum = max ( V . back ( ) - V . front ( ) , V1 . back ( ) - V1 . front ( ) ) ; cout << maximum << endl ; } int main ( ) { int N = 3 ; vector < pair < int , int > > A = { { 1 , 2 } , { 2 , 3 } , { 3 , 4 } } ; MaxDist ( A , N ) ; return 0 ; } |
Optimal Binary Search Tree | DP | A naive recursive implementation of optimal binary search tree problem ; A recursive function to calculate cost of optimal binary search tree ; Base cases if ( j < i ) no elements in this subarray ; one element in this subarray ; Get sum of freq [ i ] , freq [ i + 1 ] , ... freq [ j ] ; Initialize minimum value ; One by one consider all elements as root and recursively find cost of the BST , compare the cost with min and update min if needed ; Return minimum value ; The main function that calculates minimum cost of a Binary Search Tree . It mainly uses optCost ( ) to find the optimal cost . ; Here array keys [ ] is assumed to be sorted in increasing order . If keys [ ] is not sorted , then add code to sort keys , and rearrange freq [ ] accordingly . ; A utility function to get sum of array elements freq [ i ] to freq [ j ] ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int optCost ( int freq [ ] , int i , int j ) { return 0 ; if ( j == i ) return freq [ i ] ; int fsum = sum ( freq , i , j ) ; int min = INT_MAX ; for ( int r = i ; r <= j ; ++ r ) { int cost = optCost ( freq , i , r - 1 ) + optCost ( freq , r + 1 , j ) ; if ( cost < min ) min = cost ; } return min + fsum ; } int optimalSearchTree ( int keys [ ] , int freq [ ] , int n ) { return optCost ( freq , 0 , n - 1 ) ; } int sum ( int freq [ ] , int i , int j ) { int s = 0 ; for ( int k = i ; k <= j ; k ++ ) s += freq [ k ] ; return s ; } int main ( ) { int keys [ ] = { 10 , 12 , 20 } ; int freq [ ] = { 34 , 8 , 50 } ; int n = sizeof ( keys ) / sizeof ( keys [ 0 ] ) ; cout << " Cost β of β Optimal β BST β is β " << optimalSearchTree ( keys , freq , n ) ; return 0 ; } |
Word Wrap Problem | DP | A Dynamic programming solution for Word Wrap Problem ; A utility function to print the solution ; l [ ] represents lengths of different words in input sequence . For example , l [ ] = { 3 , 2 , 2 , 5 } is for a sentence like " aaa β bb β cc β ddddd " . n is size of l [ ] and M is line width ( maximum no . of characters that can fit in a line ) ; extras [ i ] [ j ] will have number of extra spaces if words from i to j are put in a single line ; lc [ i ] [ j ] will have cost of a line which has words from i to j ; c [ i ] will have total cost of optimal arrangement of words from 1 to i ; p [ ] is used to print the solution . ; calculate extra spaces in a single line . The value extra [ i ] [ j ] indicates extra spaces if words from word number i to j are placed in a single line ; Calculate line cost corresponding to the above calculated extra spaces . The value lc [ i ] [ j ] indicates cost of putting words from word number i to j in a single line ; Calculate minimum cost and find minimum cost arrangement . The value c [ j ] indicates optimized cost to arrange words from word number 1 to j . ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define INF INT_MAX NEW_LINE int printSolution ( int p [ ] , int n ) ; void solveWordWrap ( int l [ ] , int n , int M ) { int extras [ n + 1 ] [ n + 1 ] ; int lc [ n + 1 ] [ n + 1 ] ; int c [ n + 1 ] ; int p [ n + 1 ] ; int i , j ; for ( i = 1 ; i <= n ; i ++ ) { extras [ i ] [ i ] = M - l [ i - 1 ] ; for ( j = i + 1 ; j <= n ; j ++ ) extras [ i ] [ j ] = extras [ i ] [ j - 1 ] - l [ j - 1 ] - 1 ; } for ( i = 1 ; i <= n ; i ++ ) { for ( j = i ; j <= n ; j ++ ) { if ( extras [ i ] [ j ] < 0 ) lc [ i ] [ j ] = INF ; else if ( j == n && extras [ i ] [ j ] >= 0 ) lc [ i ] [ j ] = 0 ; else lc [ i ] [ j ] = extras [ i ] [ j ] * extras [ i ] [ j ] ; } } c [ 0 ] = 0 ; for ( j = 1 ; j <= n ; j ++ ) { c [ j ] = INF ; for ( i = 1 ; i <= j ; i ++ ) { if ( c [ i - 1 ] != INF && lc [ i ] [ j ] != INF && ( c [ i - 1 ] + lc [ i ] [ j ] < c [ j ] ) ) { c [ j ] = c [ i - 1 ] + lc [ i ] [ j ] ; p [ j ] = i ; } } } printSolution ( p , n ) ; } int printSolution ( int p [ ] , int n ) { int k ; if ( p [ n ] == 1 ) k = 1 ; else k = printSolution ( p , p [ n ] - 1 ) + 1 ; cout << " Line β number β " << k << " : β From β word β no . β " << p [ n ] << " β to β " << n << endl ; return k ; } int main ( ) { int l [ ] = { 3 , 2 , 2 , 5 } ; int n = sizeof ( l ) / sizeof ( l [ 0 ] ) ; int M = 6 ; solveWordWrap ( l , n , M ) ; return 0 ; } |
Palindrome Partitioning | DP | C ++ Code for Palindrome Partitioning Problem ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string String , int i , int j ) { while ( i < j ) { if ( String [ i ] != String [ j ] ) return false ; i ++ ; j -- ; } return true ; } int minPalPartion ( string String , int i , int j ) { if ( i >= j || isPalindrome ( String , i , j ) ) return 0 ; int ans = INT_MAX , count ; for ( int k = i ; k < j ; k ++ ) { count = minPalPartion ( String , i , k ) + minPalPartion ( String , k + 1 , j ) + 1 ; ans = min ( ans , count ) ; } return ans ; } int main ( ) { string str = " ababbbabbababa " ; cout << " Min β cuts β needed β for β " << " Palindrome β Partitioning β is β " << minPalPartion ( str , 0 , str . length ( ) - 1 ) << endl ; return 0 ; } |
Palindrome Partitioning | DP | Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minCut ( string a ) { int cut [ a . length ( ) ] ; bool palindrome [ a . length ( ) ] [ a . length ( ) ] ; memset ( palindrome , false , sizeof ( palindrome ) ) ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) { int minCut = i ; for ( int j = 0 ; j <= i ; j ++ ) { if ( a [ i ] == a [ j ] && ( i - j < 2 palindrome [ j + 1 ] [ i - 1 ] ) ) { palindrome [ j ] [ i ] = true ; minCut = min ( minCut , j == 0 ? 0 : ( cut [ j - 1 ] + 1 ) ) ; } } cut [ i ] = minCut ; } return cut [ a . length ( ) - 1 ] ; } int main ( ) { cout << minCut ( " aab " ) << endl ; cout << minCut ( " aabababaxx " ) << endl ; return 0 ; } |
Palindrome Partitioning | DP | Using memoizatoin to solve the partition problem . ; Function to check if input string is pallindrome or not ; Using two pointer technique to check pallindrome ; Function to find keys for the Hashmap ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Key for the Input String ; If the no of partitions for string " ij " is already calculated then return the calculated value using the Hashmap ; Every String of length 1 is a pallindrome ; Make a cut at every possible location starting from i to j ; If left cut is found already ; If right cut is found already ; Recursively calculating for left and right strings ; Taking minimum of all k possible cuts ; Return the min cut value for complete string . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool ispallindrome ( string input , int start , int end ) { while ( start < end ) { if ( input [ start ] != input [ end ] ) return false ; start ++ ; end -- ; } return true ; } string convert ( int a , int b ) { return to_string ( a ) + " " + to_string ( b ) ; } int minpalparti_memo ( string input , int i , int j , unordered_map < string , int > & memo ) { if ( i > j ) return 0 ; string ij = convert ( i , j ) ; if ( memo . find ( ij ) != memo . end ( ) ) { return memo [ ij ] ; } if ( i == j ) { memo [ ij ] = 0 ; return 0 ; } if ( ispallindrome ( input , i , j ) ) { memo [ ij ] = 0 ; return 0 ; } int minimum = INT_MAX ; for ( int k = i ; k < j ; k ++ ) { int left_min = INT_MAX ; int right_min = INT_MAX ; string left = convert ( i , k ) ; string right = convert ( k + 1 , j ) ; if ( memo . find ( left ) != memo . end ( ) ) { left_min = memo [ left ] ; } if ( memo . find ( right ) != memo . end ( ) ) { right_min = memo [ right ] ; } if ( left_min == INT_MAX ) left_min = minpalparti_memo ( input , i , k , memo ) ; if ( right_min == INT_MAX ) right_min = minpalparti_memo ( input , k + 1 , j , memo ) ; minimum = min ( minimum , left_min + 1 + right_min ) ; } memo [ ij ] = minimum ; return memo [ ij ] ; } int main ( ) { string input = " ababbbabbababa " ; unordered_map < string , int > memo ; cout << minpalparti_memo ( input , 0 , input . length ( ) - 1 , memo ) << endl ; return 0 ; } |
Longest Bitonic Subsequence | DP | Dynamic Programming implementation of longest bitonic subsequence problem ; lbs ( ) returns the length of the Longest Bitonic Subsequence in arr [ ] of size n . The function mainly creates two temporary arrays lis [ ] and lds [ ] and returns the maximum lis [ i ] + lds [ i ] - 1. lis [ i ] == > Longest Increasing subsequence ending with arr [ i ] lds [ i ] == > Longest decreasing subsequence starting with arr [ i ] ; Allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right ; Allocate memory for lds and initialize LDS values for all indexes ; Compute LDS values from right to left ; Return the maximum value of lis [ i ] + lds [ i ] - 1 ; Driver program to test above function | #include <stdio.h> NEW_LINE #include <stdlib.h> NEW_LINE int lbs ( int arr [ ] , int n ) { int i , j ; int * lis = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) lis [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && lis [ i ] < lis [ j ] + 1 ) lis [ i ] = lis [ j ] + 1 ; int * lds = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) lds [ i ] = 1 ; for ( i = n - 2 ; i >= 0 ; i -- ) for ( j = n - 1 ; j > i ; j -- ) if ( arr [ i ] > arr [ j ] && lds [ i ] < lds [ j ] + 1 ) lds [ i ] = lds [ j ] + 1 ; int max = lis [ 0 ] + lds [ 0 ] - 1 ; for ( i = 1 ; i < n ; i ++ ) if ( lis [ i ] + lds [ i ] - 1 > max ) max = lis [ i ] + lds [ i ] - 1 ; return max ; } int main ( ) { int arr [ ] = { 0 , 8 , 4 , 12 , 2 , 10 , 6 , 14 , 1 , 9 , 5 , 13 , 3 , 11 , 7 , 15 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " Length β of β LBS β is β % d STRNEWLINE " , lbs ( arr , n ) ) ; return 0 ; } |
Egg Dropping Puzzle | DP | A Dynamic Programming based for the Egg Dropping Puzzle ; A utility function to get maximum of two integers ; Function to get minimum number of trials needed in worst case with n eggs and k floors ; A 2D table where entry eggFloor [ i ] [ j ] will represent minimum number of trials needed for i eggs and j floors . ; We need one trial for one floor and 0 trials for 0 floors ; We always need j trials for one egg and j floors . ; Fill rest of the entries in table using optimal substructure property ; eggFloor [ n ] [ k ] holds the result ; Driver program to test to pront printDups | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int eggDrop ( int n , int k ) { int eggFloor [ n + 1 ] [ k + 1 ] ; int res ; int i , j , x ; for ( i = 1 ; i <= n ; i ++ ) { eggFloor [ i ] [ 1 ] = 1 ; eggFloor [ i ] [ 0 ] = 0 ; } for ( j = 1 ; j <= k ; j ++ ) eggFloor [ 1 ] [ j ] = j ; for ( i = 2 ; i <= n ; i ++ ) { for ( j = 2 ; j <= k ; j ++ ) { eggFloor [ i ] [ j ] = INT_MAX ; for ( x = 1 ; x <= j ; x ++ ) { res = 1 + max ( eggFloor [ i - 1 ] [ x - 1 ] , eggFloor [ i ] [ j - x ] ) ; if ( res < eggFloor [ i ] [ j ] ) eggFloor [ i ] [ j ] = res ; } } } return eggFloor [ n ] [ k ] ; } int main ( ) { int n = 2 , k = 36 ; cout << " Minimum number of trials " STRNEWLINE TABSYMBOL TABSYMBOL " in worst case with " << n << " β eggs β and β " << k << " β floors β is β " << eggDrop ( n , k ) ; return 0 ; } |
0 | A Naive recursive implementation of 0 - 1 Knapsack problem ; A utility function that returns maximum of two integers ; Returns the maximum value that can be put in a knapsack of capacity W ; Base Case ; If weight of the nth item is more than Knapsack capacity W , then this item cannot be included in the optimal solution ; Return the maximum of two cases : ( 1 ) nth item included ( 2 ) not included ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int a , int b ) { return ( a > b ) ? a : b ; } int knapSack ( int W , int wt [ ] , int val [ ] , int n ) { if ( n == 0 W == 0 ) return 0 ; if ( wt [ n - 1 ] > W ) return knapSack ( W , wt , val , n - 1 ) ; else return max ( val [ n - 1 ] + knapSack ( W - wt [ n - 1 ] , wt , val , n - 1 ) , knapSack ( W , wt , val , n - 1 ) ) ; } int main ( ) { int val [ ] = { 60 , 100 , 120 } ; int wt [ ] = { 10 , 20 , 30 } ; int W = 50 ; int n = sizeof ( val ) / sizeof ( val [ 0 ] ) ; cout << knapSack ( W , wt , val , n ) ; return 0 ; } |
Min Cost Path | DP | C ++ program for the above approach ; for 1 st column ; for 1 st row ; for rest of the 2d matrix ; returning the value in last cell ; Driver code | #include <bits/stdc++.h> NEW_LINE #define endl " NEW_LINE " using namespace std ; const int row = 3 ; const int col = 3 ; int minCost ( int cost [ row ] [ col ] ) { for ( int i = 1 ; i < row ; i ++ ) { cost [ i ] [ 0 ] += cost [ i - 1 ] [ 0 ] ; } for ( int j = 1 ; j < col ; j ++ ) { cost [ 0 ] [ j ] += cost [ 0 ] [ j - 1 ] ; } for ( int i = 1 ; i < row ; i ++ ) { for ( int j = 1 ; j < col ; j ++ ) { cost [ i ] [ j ] += min ( cost [ i - 1 ] [ j - 1 ] , min ( cost [ i - 1 ] [ j ] , cost [ i ] [ j - 1 ] ) ) ; } } return cost [ row - 1 ] [ col - 1 ] ; } int main ( int argc , char const * argv [ ] ) { int cost [ row ] [ col ] = { { 1 , 2 , 3 } , { 4 , 8 , 2 } , { 1 , 5 , 3 } } ; cout << minCost ( cost ) << endl ; return 0 ; } |
Longest Increasing Subsequence | DP | A Naive C ++ recursive implementation of LIS problem ; stores the LIS ; To make use of recursive calls , thisfunction must return two things : 1 ) Length of LIS ending with element arr [ n - 1 ] . We use max_ending_here for this purpose2 ) Overall maximum as the LIS may end with an element before arr [ n - 1 ] max_ref is used this purpose . The value of LIS of full array of size n is stored in * max_ref which is our final result ; Base case ; ' max _ ending _ here ' is length of LIS ending with arr [ n - 1 ] ; Recursively get all LIS ending with arr [ 0 ] , arr [ 1 ] ... arr [ n - 2 ] . If arr [ i - 1 ] is smaller than arr [ n - 1 ] , and max ending with arr [ n - 1 ] needs to be updated , then update it ; Compare max_ending_here with the overall max . And update the overall max if needed ; Return length of LIS ending with arr [ n - 1 ] ; The wrapper function for _lis ( ) ; The max variable holds the result ; The function _lis ( ) stores its result in max ; returns max ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; static int max_ref ; int _lis ( int arr [ ] , int n , int * max_ref ) { if ( n == 1 ) return 1 ; int res , max_ending_here = 1 ; for ( int i = 1 ; i < n ; i ++ ) { res = _lis ( arr , i , max_ref ) ; if ( arr [ i - 1 ] < arr [ n - 1 ] && res + 1 > max_ending_here ) max_ending_here = res + 1 ; } if ( * max_ref < max_ending_here ) * max_ref = max_ending_here ; return max_ending_here ; } int lis ( int arr [ ] , int n ) { int max = 1 ; _lis ( arr , n , & max ) ; return max ; } int main ( ) { int arr [ ] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Length β of β lis β is β " << lis ( arr , n ) ; return 0 ; } |
Total number of possible Binary Search Trees and Binary Trees with n keys | See https : www . geeksforgeeks . org / program - nth - catalan - number / for reference of below code . ; A function to find factorial of a given number ; Calculate value of [ 1 * ( 2 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; Since C ( n , k ) = C ( n , n - k ) ; Calculate value of [ n * ( n - 1 ) * -- - * ( n - k + 1 ) ] / [ k * ( k - 1 ) * -- - * 1 ] ; A Binomial coefficient based function to find nth catalan number in O ( n ) time ; Calculate value of 2 nCn ; return 2 nCn / ( n + 1 ) ; A function to count number of BST with n nodes using catalan ; find nth catalan number ; return nth catalan number ; A function to count number of binary trees with n nodes ; find count of BST with n numbers ; return count * n ! ; Driver Program to test above functions ; find count of BST and binary trees with n nodes ; print count of BST and binary trees with n nodes | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long int factorial ( unsigned int n ) { unsigned long int res = 1 ; for ( int i = 1 ; i <= n ; ++ i ) { res *= i ; } return res ; } unsigned long int binomialCoeff ( unsigned int n , unsigned int k ) { unsigned long int res = 1 ; if ( k > n - k ) k = n - k ; for ( int i = 0 ; i < k ; ++ i ) { res *= ( n - i ) ; res /= ( i + 1 ) ; } return res ; } unsigned long int catalan ( unsigned int n ) { unsigned long int c = binomialCoeff ( 2 * n , n ) ; return c / ( n + 1 ) ; } unsigned long int countBST ( unsigned int n ) { unsigned long int count = catalan ( n ) ; return count ; } unsigned long int countBT ( unsigned int n ) { unsigned long int count = catalan ( n ) ; return count * factorial ( n ) ; } int main ( ) { int count1 , count2 , n = 5 ; count1 = countBST ( n ) ; count2 = countBT ( n ) ; cout << " Count β of β BST β with β " << n << " β nodes β is β " << count1 << endl ; cout << " Count β of β binary β trees β with β " << n << " β nodes β is β " << count2 ; return 0 ; } |
Find all numbers in range [ 1 , N ] that are not present in given Array | C ++ program for above approach ; Function to find the missing numbers ; traverse the array arr [ ] ; Update ; Traverse the array arr [ ] ; If Num is not present ; Driver Code ; Given Input ; Function Call | #include <iostream> NEW_LINE using namespace std ; void getMissingNumbers ( int arr [ ] , int N ) { for ( int i = 0 ; i < N ; i ++ ) { arr [ abs ( arr [ i ] ) - 1 ] = - ( abs ( arr [ abs ( arr [ i ] ) - 1 ] ) ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] > 0 ) cout << i + 1 << " β " ; } } int main ( ) { int N = 5 ; int arr [ ] = { 5 , 5 , 4 , 4 , 2 } ; getMissingNumbers ( arr , N ) ; return 0 ; } |
Check if elements of a Binary Matrix can be made alternating | C ++ program for the above approach ; Function to check for the grid in one of the alternating ways ; Iterate over the range ; Iterate over the range ; ( i + j ) % 2 == 1 cells should be with the character check and the rest should be with the other character ; Function to fill the grid in a possible way ; Function to find if the grid can be made alternating ; If grid contains atleast one 1 or 0 ; Fill the grid in any possible way ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool PosCheck ( char a [ ] [ 1001 ] , int n , int m , char check ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] == ' * ' ) { continue ; } else { if ( ( ( i + j ) & 1 ) && a [ i ] [ j ] != check ) { return false ; } if ( ! ( ( i + j ) & 1 ) && a [ i ] [ j ] == check ) { return false ; } } } } return true ; } void fill ( char a [ ] [ 1001 ] , int n , int m , char odd , char even ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( ( i + j ) & 1 ) { a [ i ] [ j ] = odd ; } else { a [ i ] [ j ] = even ; } } } } void findPossibleGrid ( int n , int m , char a [ ] [ 1001 ] ) { bool flag = true ; int k = -1 , o = -1 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( a [ i ] [ j ] != ' * ' ) { k = i ; o = j ; break ; } } if ( k != -1 ) { break ; } } if ( k != -1 ) { flag = PosCheck ( a , n , m , '1' ) ; if ( flag ) { fill ( a , n , m , '1' , '0' ) ; } else { flag = PosCheck ( a , n , m , '0' ) ; if ( flag ) { fill ( a , n , m , '0' , '1' ) ; } } } else { char h = '1' ; for ( int i = 0 ; i < m ; i ++ ) { a [ 0 ] [ i ] = h ; if ( h == '1' ) { h = '0' ; } else { h = '1' ; } } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( i - 1 < 0 ) { continue ; } if ( a [ i - 1 ] [ j ] == '1' ) { a [ i ] [ j ] = '0' ; } else { a [ i ] [ j ] = '1' ; } } } flag = true ; } if ( ! flag ) { cout << " NO STRNEWLINE " ; } else { cout << " YES STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { cout << a [ i ] [ j ] ; } cout << endl ; } } } int main ( ) { int n = 4 , m = 4 ; char grid [ ] [ 1001 ] = { { ' * ' , ' * ' , '1' , '0' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , ' * ' , ' * ' } , { ' * ' , ' * ' , '0' , '1' } } ; findPossibleGrid ( n , m , grid ) ; return 0 ; } |
Find the Kth smallest odd length palindrome number | C ++ program for the above approach ; Function to find the Kth smallest odd length palindrome ; Store the original number K ; Removing the last digit of K ; Generate the palindrome by appending the reverse of K except last digit to itself ; Find the remainder ; Add the digit to palin ; Divide K by 10 ; Return the resultant palindromic number formed ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int oddLengthPalindrome ( int k ) { int palin = k ; k = k / 10 ; while ( k > 0 ) { int rev = k % 10 ; palin = ( palin * 10 ) + rev ; k = k / 10 ; } return palin ; } int main ( ) { int k = 504 ; cout << oddLengthPalindrome ( k ) ; } |
Length of the longest substring consisting only of vowels in non | C ++ program for the above approach ; Function to find length of the longest substring consisting only of vowels in non - increasing order ; Stores all vowels in decreasing order ; Stores current index of array ch [ ] ; Stores the result ; Stores the count of current substring ; Declare a HashSet to store the vowels ; Traverse the string , S ; If S [ i ] is equal to ch [ j ] ; Increment count by 1 ; Add S [ i ] in the mp ; If length of mp is 5 , update res ; Else if j + 1 is less than 5 and S [ i ] is equal to ch [ j + 1 ] ; Add the S [ i ] in the mp ; Increment count by 1 ; Increment j by 1 ; If length of mp is 5 , update res ; Clear the mp ; If S [ i ] is ' u ' ; Add S [ i ] in the mp ; Update j and assign 1 to count ; Else assign 0 to j and count ; Return the result ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string S , int N ) { char ch [ ] = { ' u ' , ' o ' , ' i ' , ' e ' , ' a ' } ; int j = 0 ; int res = 0 ; int count = 0 ; unordered_set < char > mp ; for ( int i = 0 ; i < N ; ++ i ) { if ( S [ i ] == ch [ j ] ) { ++ count ; mp . insert ( S [ i ] ) ; if ( mp . size ( ) == 5 ) { res = max ( res , count ) ; } } else if ( j + 1 < 5 && S [ i ] == ch [ j + 1 ] ) { mp . insert ( S [ i ] ) ; ++ count ; j ++ ; if ( mp . size ( ) == 5 ) { res = max ( res , count ) ; } } else { mp . clear ( ) ; if ( S [ i ] == ' u ' ) { mp . insert ( ' u ' ) ; j = 0 ; count = 1 ; } else { j = 0 ; count = 0 ; } } } return res ; } int main ( ) { string S = " ueiaoaeiouuoiea " ; int N = S . size ( ) ; cout << count ( S , N ) ; return 0 ; } |
Maximize length of subsequence consisting of single distinct character possible by K increments in a string | C ++ program for the above approach ; Function to find the maximum length of a subsequence of same characters after at most K increment operations ; Store the size of S ; Sort the given string ; Stores the maximum length and the sum of the sliding window ; Traverse the string S ; Add the current character to the window ; Decrease the window size ; Update the value of sum ; Increment the value of start ; Update the maximum window size ; Print the resultant maximum length of the subsequence ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void maxSubsequenceLen ( string S , int K ) { int N = S . length ( ) ; int start = 0 , end = 0 ; sort ( S . begin ( ) , S . end ( ) ) ; int ans = INT_MIN , sum = 0 ; for ( end = 0 ; end < N ; end ++ ) { sum = sum + ( S [ end ] - ' a ' ) ; while ( sum + K < ( S [ end ] - ' a ' ) * ( end - start + 1 ) ) { sum = sum - ( S [ start ] - ' a ' ) ; start ++ ; } ans = max ( ans , end - start + 1 ) ; } cout << ans ; } int main ( ) { string S = " acscbcca " ; int K = 1 ; maxSubsequenceLen ( S , K ) ; return 0 ; } |
Check if a given integer is the product of K consecutive integers | C ++ program for the above approach ; Function to check if N can be expressed as the product of K consecutive integers ; Stores the K - th root of N ; Stores the product of K consecutive integers ; Traverse over the range [ 1 , K ] ; Update the product ; If product is N , then return " Yes " ; Otherwise , traverse over the range [ 2 , Kthroot ] ; Update the value of product ; If product is equal to N ; Otherwise , return " No " ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string checkPro ( int n , int k ) { double exp = 1.0 / k ; int KthRoot = ( int ) pow ( n , exp ) ; int product = 1 ; for ( int i = 1 ; i < k + 1 ; i ++ ) { product = product * i ; } if ( product == n ) return " Yes " ; else { for ( int j = 2 ; j < KthRoot + 1 ; j ++ ) { product = product * ( j + k - 1 ) ; product = product / ( j - 1 ) ; if ( product == n ) return " Yes " ; } } return " No " ; } int main ( ) { int N = 210 ; int K = 3 ; cout << checkPro ( N , K ) ; return 0 ; } |
Convert a Binary String to another by flipping prefixes minimum number of times | C ++ program for the above approach ; Function to count minimum number of operations required to convert string a to another string b ; Store the lengths of each prefixes selected ; Traverse the string ; If first character is same as b [ i ] ; Insert 1 to ops [ ] ; And , flip the bit ; Reverse the prefix string of length i + 1 ; Flip the characters in this prefix length ; Push ( i + 1 ) to array ops [ ] ; Print the number of operations ; Print the length of each prefixes stored ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( string a , string b , int n ) { vector < int > ops ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( a [ i ] != b [ i ] ) { if ( a [ 0 ] == b [ i ] ) { ops . push_back ( 1 ) ; a [ 0 ] = '0' + ! ( a [ 0 ] - '0' ) ; } reverse ( a . begin ( ) , a . begin ( ) + i + 1 ) ; for ( int j = 0 ; j <= i ; j ++ ) { a [ j ] = '0' + ! ( a [ j ] - '0' ) ; } ops . push_back ( i + 1 ) ; } } cout << ops . size ( ) << " STRNEWLINE " ; for ( int x : ops ) { cout << x << ' β ' ; } } int main ( ) { string a = "10" , b = "01" ; int N = a . size ( ) ; minOperations ( a , b , N ) ; return 0 ; } |
Count possible removals to make absolute difference between the sum of odd and even indexed elements equal to K | C ++ program for the above approach ; Function to check if difference between the sum of odd and even indexed elements after removing the first element is K or not ; Stores the sum of elements at odd and even indices ; Return 1 if difference is K ; Function to check if difference between the sum of odd and even indexed elements after removing the second element is K or not ; Stores the sum of elements at odd and even indices ; Return 1 if difference is K ; Function to count number of elements to be removed to make sum of differences between odd and even indexed elements equal to K ; Size of given array ; Base Conditions ; Stores prefix and suffix sums ; Base assignments ; Store prefix sums of even indexed elements ; Store prefix sums of odd indexed elements ; Similarly , store suffix sums of elements at even and odd indices ; Stores the count of possible removals ; Traverse and remove the ith element ; If the current element is excluded , then previous index ( i - 1 ) points to ( i + 2 ) and ( i - 2 ) points to ( i + 1 ) ; Find count when 0 th element is removed ; Find count when 1 st element is removed ; Count gives the required answer ; Driver Code ; Function call | #include " bits / stdc + + . h " NEW_LINE using namespace std ; int findCount0th ( vector < int > & arr , int N , int K ) { int oddsum = 0 , evensum = 0 ; for ( int i = 1 ; i < N ; i += 2 ) { oddsum += arr [ i ] ; } for ( int i = 2 ; i < N ; i += 2 ) { evensum += arr [ i ] ; } if ( abs ( oddsum - evensum ) == K ) return 1 ; else return 0 ; } int findCount1st ( vector < int > & arr , int N , int K ) { int evensum = arr [ 0 ] , oddsum = 0 ; for ( int i = 3 ; i < N ; i += 2 ) { evensum += arr [ i ] ; } for ( int i = 2 ; i < N ; i += 2 ) { oddsum += arr [ i ] ; } if ( abs ( oddsum - evensum ) == K ) return 1 ; else return 0 ; } int countTimes ( vector < int > & arr , int K ) { int N = ( int ) arr . size ( ) ; if ( N == 1 ) return 1 ; if ( N < 3 ) return 0 ; if ( N == 3 ) { int cnt = 0 ; cnt += ( abs ( arr [ 0 ] - arr [ 1 ] ) == K ? 1 : 0 ) + ( abs ( arr [ 2 ] - arr [ 1 ] ) == K ? 1 : 0 ) + ( abs ( arr [ 0 ] - arr [ 2 ] ) == K ? 1 : 0 ) ; return cnt ; } vector < int > prefix ( N + 2 , 0 ) ; vector < int > suffix ( N + 2 , 0 ) ; prefix [ 0 ] = arr [ 0 ] ; prefix [ 1 ] = arr [ 1 ] ; suffix [ N - 1 ] = arr [ N - 1 ] ; suffix [ N - 2 ] = arr [ N - 2 ] ; for ( int i = 2 ; i < N ; i += 2 ) { prefix [ i ] = arr [ i ] + prefix [ i - 2 ] ; } for ( int i = 3 ; i < N ; i += 2 ) { prefix [ i ] = arr [ i ] + prefix [ i - 2 ] ; } for ( int i = N - 3 ; i >= 0 ; i -= 2 ) { suffix [ i ] = arr [ i ] + suffix [ i + 2 ] ; } for ( int i = N - 4 ; i >= 0 ; i -= 2 ) { suffix [ i ] = arr [ i ] + suffix [ i + 2 ] ; } int count = 0 ; for ( int i = 2 ; i < N ; i ++ ) { if ( abs ( prefix [ i - 1 ] + suffix [ i + 2 ] - prefix [ i - 2 ] - suffix [ i + 1 ] ) == K ) { count ++ ; } } count += findCount0th ( arr , N , K ) ; count += findCount1st ( arr , N , K ) ; return count ; } int main ( ) { vector < int > arr = { 1 , 2 , 4 , 5 , 6 } ; int K = 2 ; cout << countTimes ( arr , K ) ; return 0 ; } |
Divide Matrix into K groups of adjacent cells having minimum difference between maximum and minimum sized groups | C ++ program for the above approach ; Function to fill the matrix with the given conditions ; Count of parts with size sizeOfPart ; Assigning the cell with no of groups ; Update row ; Update col ; Increment count ; For new group increment start ; Function to return the reference of the matrix to be filled ; Create matrix of size N * M ; Starting index of the matrix ; Size of one group ; Element to assigned to matrix ; Fill the matrix that have rem no of parts with size size + 1 ; Fill the remaining number of parts with each part size is ' size ' ; Return the matrix ; Function to print the matrix ; Traverse the rows ; Traverse the columns ; Driver Code ; Given N , M , K ; Function Call ; Function Call to print matrix | #include <bits/stdc++.h> NEW_LINE using namespace std ; void fillMatrix ( int * * mat , int & row , int & col , int sizeOfpart , int noOfPart , int & start , int m , int & flag ) { for ( int i = 0 ; i < noOfPart ; ++ i ) { int count = 0 ; while ( count < sizeOfpart ) { mat [ row ] [ col ] = start ; if ( col == m - 1 && flag == 1 ) { row ++ ; col = m ; flag = 0 ; } else if ( col == 0 && flag == 0 ) { row ++ ; col = -1 ; flag = 1 ; } if ( flag == 1 ) { col ++ ; } else { col -- ; } count ++ ; } start ++ ; } } int * * findMatrix ( int N , int M , int k ) { int * * mat = ( int * * ) malloc ( N * sizeof ( int * ) ) ; for ( int i = 0 ; i < N ; ++ i ) { mat [ i ] = ( int * ) malloc ( M * sizeof ( int ) ) ; } int row = 0 , col = 0 ; int size = ( N * M ) / k ; int rem = ( N * M ) % k ; int start = 1 , flag = 1 ; fillMatrix ( mat , row , col , size + 1 , rem , start , M , flag ) ; fillMatrix ( mat , row , col , size , k - rem , start , M , flag ) ; return mat ; } void printMatrix ( int * * mat , int N , int M ) { for ( int i = 0 ; i < N ; ++ i ) { for ( int j = 0 ; j < M ; ++ j ) { cout << mat [ i ] [ j ] << " β " ; } cout << endl ; } } int main ( ) { int N = 5 , M = 5 , K = 6 ; int * * mat = findMatrix ( N , M , K ) ; printMatrix ( mat , N , M ) ; return 0 ; } |
Replace ' ? ' in a string such that no two adjacent characters are same | C ++ program for the above approach ; Function that replace all ' ? ' with lowercase alphabets such that each adjacent character is different ; Store the given string ; If the first character is ' ? ' ; Traverse the string [ 1 , N - 1 ] ; If the current character is ' ? ' ; Change the character ; Check equality with the previous character ; Check equality with the next character ; Check equality with the previous character ; If the last character is ' ? ' ; Change character ; Check with previous character ; Return the resultant string ; Driver Code ; Given string S ; Function Call | #include " bits / stdc + + . h " NEW_LINE using namespace std ; string changeString ( string S ) { string s = S ; int N = ( int ) s . length ( ) ; if ( s [ 0 ] == ' ? ' ) { s [ 0 ] = ' a ' ; if ( s [ 0 ] == s [ 1 ] ) { s [ 0 ] ++ ; } } for ( int i = 1 ; i < N - 1 ; i ++ ) { if ( s [ i ] == ' ? ' ) { s [ i ] = ' a ' ; if ( s [ i ] == s [ i - 1 ] ) { s [ i ] ++ ; } if ( s [ i ] == s [ i + 1 ] ) { s [ i ] ++ ; } if ( s [ i ] == s [ i - 1 ] ) { s [ i ] ++ ; } } } if ( s [ N - 1 ] == ' ? ' ) { s [ N - 1 ] = ' a ' ; if ( s [ N - 1 ] == s [ N - 2 ] ) { s [ N - 1 ] ++ ; } } return s ; } int main ( ) { string S = " ? a ? a " ; cout << changeString ( S ) ; return 0 ; } |
Check if a given string is a Reverse Bitonic String or not | C ++ program to implement the above approach ; Function to check if the given string is reverse bitonic ; Check for decreasing sequence ; If end of string has been reached ; Check for increasing sequence ; If the end of string hasn 't been reached ; If the string is reverse bitonic ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkReverseBitonic ( string s ) { int i , j ; for ( i = 1 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] < s [ i - 1 ] ) continue ; if ( s [ i ] >= s [ i - 1 ] ) break ; } if ( i == s . size ( ) - 1 ) return 1 ; for ( j = i + 1 ; j < s . size ( ) ; j ++ ) { if ( s [ j ] > s [ j - 1 ] ) continue ; if ( s [ j ] <= s [ j - 1 ] ) break ; } i = j ; if ( i != s . size ( ) ) return 0 ; return 1 ; } int main ( ) { string s = " abcdwef " ; ( checkReverseBitonic ( s ) == 1 ) ? cout << " YES " : cout << " NO " ; return 0 ; } |
Smallest number whose square has N digits | C ++ Program to find the smallest number whose square has N digits ; Function to return smallest number whose square has N digits ; Calculate N - th term of the series ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNum ( int N ) { float x = pow ( 10.0 , ( N - 1 ) / 2.0 ) ; return ceil ( x ) ; } int main ( ) { int N = 4 ; cout << smallestNum ( N ) ; return 0 ; } |
Count of K | C ++ code for the above program . ; Function to to count the number of K - countdowns for multiple queries ; flag which stores the current value of value in the countdown ; count of K - countdowns ; Loop to iterate over the elements of the array ; condition check if the elements of the array is equal to K ; condition check if the elements of the array is in continuous order ; condition check if the elements of the array are not in continuous order ; condition check to increment the counter if the there is a K - countdown present in the array ; returning the count of K - countdowns ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countKCountdown ( int arr [ ] , int N , int K ) { int flag = -1 ; int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] == K ) flag = K ; if ( arr [ i ] == flag ) flag -- ; else flag = -1 ; if ( flag == 0 ) count ++ ; } return count ; } int main ( ) { int N = 8 ; int K = 3 ; int arr [ N ] = { 4 , 3 , 2 , 1 , 5 , 3 , 2 , 1 } ; cout << countKCountdown ( arr , N , K ) ; } |
Convert the given RGB color code to Hex color code | C ++ code to convert the given RGB color code to Hex color code ; function to convert decimal to hexadecimal ; char array to store hexadecimal number ; counter for hexadecimal number array ; temporary variable to store remainder ; storing remainder in temp variable . ; check if temp < 10 ; Return the equivalent hexadecimal color code ; Function to convert the RGB code to Hex color code ; The hex color code doesn 't exist ; Driver program to test above function | #include <iostream> NEW_LINE using namespace std ; string decToHexa ( int n ) { char hexaDeciNum [ 2 ] ; int i = 0 ; while ( n != 0 ) { int temp = 0 ; temp = n % 16 ; if ( temp < 10 ) { hexaDeciNum [ i ] = temp + 48 ; i ++ ; } else { hexaDeciNum [ i ] = temp + 55 ; i ++ ; } n = n / 16 ; } string hexCode = " " ; if ( i == 2 ) { hexCode . push_back ( hexaDeciNum [ 0 ] ) ; hexCode . push_back ( hexaDeciNum [ 1 ] ) ; } else if ( i == 1 ) { hexCode = "0" ; hexCode . push_back ( hexaDeciNum [ 0 ] ) ; } else if ( i == 0 ) hexCode = "00" ; return hexCode ; } string convertRGBtoHex ( int R , int G , int B ) { if ( ( R >= 0 && R <= 255 ) && ( G >= 0 && G <= 255 ) && ( B >= 0 && B <= 255 ) ) { string hexCode = " # " ; hexCode += decToHexa ( R ) ; hexCode += decToHexa ( G ) ; hexCode += decToHexa ( B ) ; return hexCode ; } else return " - 1" ; } int main ( ) { int R = 0 , G = 0 , B = 0 ; cout << convertRGBtoHex ( R , G , B ) << endl ; R = 255 , G = 255 , B = 255 ; cout << convertRGBtoHex ( R , G , B ) << endl ; R = 25 , G = 56 , B = 123 ; cout << convertRGBtoHex ( R , G , B ) << endl ; R = 2 , G = 3 , B = 4 ; cout << convertRGBtoHex ( R , G , B ) << endl ; R = 255 , G = 255 , B = 256 ; cout << convertRGBtoHex ( R , G , B ) << endl ; return 0 ; } |
Check whether an array can be made strictly decreasing by modifying at most one element | C ++ implementation of the approach ; Function that returns true if the array can be made strictly decreasing with at most one change ; To store the number of modifications required to make the array strictly decreasing ; Check whether the last element needs to be modify or not ; Check whether the first element needs to be modify or not ; Loop from 2 nd element to the 2 nd last element ; Check whether arr [ i ] needs to be modified ; Modifying arr [ i ] ; Check if arr [ i ] is equal to any of arr [ i - 1 ] or arr [ i + 1 ] ; If more than 1 modification is required ; Driver code | #include <iostream> NEW_LINE using namespace std ; bool check ( int * arr , int n ) { int modify = 0 ; if ( arr [ n - 1 ] >= arr [ n - 2 ] ) { arr [ n - 1 ] = arr [ n - 2 ] - 1 ; modify ++ ; } if ( arr [ 0 ] <= arr [ 1 ] ) { arr [ 0 ] = arr [ 1 ] + 1 ; modify ++ ; } for ( int i = n - 2 ; i > 0 ; i -- ) { if ( ( arr [ i - 1 ] <= arr [ i ] && arr [ i + 1 ] <= arr [ i ] ) || ( arr [ i - 1 ] >= arr [ i ] && arr [ i + 1 ] >= arr [ i ] ) ) { arr [ i ] = ( arr [ i - 1 ] + arr [ i + 1 ] ) / 2 ; modify ++ ; if ( arr [ i ] == arr [ i - 1 ] arr [ i ] == arr [ i + 1 ] ) return false ; } } if ( modify > 1 ) return false ; return true ; } int main ( ) { int arr [ ] = { 10 , 5 , 11 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( check ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Program to build a DFA to accept strings that start and end with same character | C ++ Program for DFA that accepts string if it starts and ends with same character ; States of DFA ; Function for the state Q1 ; Condition to check end of string ; State transitions ' a ' takes to q1 , and ' b ' takes to q2 ; Function for the state Q2 ; Condition to check end of string ; State transitions ' a ' takes to q1 , and ' b ' takes to q2 ; Function for the state Q3 ; Condition to check end of string ; State transitions ' a ' takes to q4 , and ' b ' takes to q3 ; Function for the state Q4 ; Condition to check end of string ; State transitions ' a ' takes to q4 , and ' b ' takes to q3 ; Function for the state Q0 ; Condition to check end of string ; State transitions ' a ' takes to q1 , and ' b ' takes to q3 ; Driver Code ; Since q0 is the starting state Send the string to q0 | #include <bits/stdc++.h> NEW_LINE using namespace std ; void q1 ( string , int ) ; void q2 ( string , int ) ; void q3 ( string , int ) ; void q4 ( string , int ) ; void q1 ( string s , int i ) { if ( i == s . length ( ) ) { cout << " Yes β STRNEWLINE " ; return ; } if ( s [ i ] == ' a ' ) q1 ( s , i + 1 ) ; else q2 ( s , i + 1 ) ; } void q2 ( string s , int i ) { if ( i == s . length ( ) ) { cout << " No β STRNEWLINE " ; return ; } if ( s [ i ] == ' a ' ) q1 ( s , i + 1 ) ; else q2 ( s , i + 1 ) ; } void q3 ( string s , int i ) { if ( i == s . length ( ) ) { cout << " Yes β STRNEWLINE " ; return ; } if ( s [ i ] == ' a ' ) q4 ( s , i + 1 ) ; else q3 ( s , i + 1 ) ; } void q4 ( string s , int i ) { if ( i == s . length ( ) ) { cout << " No β STRNEWLINE " ; return ; } if ( s [ i ] == ' a ' ) q4 ( s , i + 1 ) ; else q3 ( s , i + 1 ) ; } void q0 ( string s , int i ) { if ( i == s . length ( ) ) { cout << " No β STRNEWLINE " ; return ; } if ( s [ i ] == ' a ' ) q1 ( s , i + 1 ) ; else q3 ( s , i + 1 ) ; } int main ( ) { string s = " abbaabb " ; q0 ( s , 0 ) ; } |
Longest prefix in a string with highest frequency | C ++ implementation of the above approach ; Function to find Longest prefix string with the highest frequency ; storing all indices where first element is found ; if the first letter in the string does not occur again then answer will be the whole string ; loop till second appearance of the first element ; check one letter after every stored index ; If there is no mismatch we move forward ; otherwise we stop ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void prefix ( string str ) { int k = 1 , j ; int n = str . length ( ) ; vector < int > g ; int flag = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( str [ i ] == str [ 0 ] ) { g . push_back ( i ) ; flag = 1 ; } } if ( flag == 0 ) { cout << str << endl ; } else { int len = g . size ( ) ; while ( k < g [ 0 ] ) { int cnt = 0 ; for ( j = 0 ; j < len ; j ++ ) { if ( str [ g [ j ] + k ] == str [ k ] ) { cnt ++ ; } } if ( cnt == len ) { k ++ ; } else { break ; } } for ( int i = 0 ; i < k ; i ++ ) { cout << str [ i ] ; } cout << endl ; } } int main ( ) { string str = " abcab " ; prefix ( str ) ; return 0 ; } |
Generate permutation of 1 to N such that absolute difference of consecutive numbers give K distinct integers | C ++ implementation of the approach ; Function to generate a permutation of integers from 1 to N such that the absolute difference of all the two consecutive integers give K distinct integers ; To store the permutation ; For sequence 1 2 3. . . ; For sequence N , N - 1 , N - 2. . . ; Flag is used to alternate between the above if else statements ; If last element added was r + 1 ; If last element added was l - 1 ; Print the permutation ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printPermutation ( int N , int K ) { vector < int > res ; int l = 1 , r = N , flag = 0 ; for ( int i = 0 ; i < K ; i ++ ) { if ( ! flag ) { res . push_back ( l ) ; l ++ ; } else { res . push_back ( r ) ; r -- ; } flag ^= 1 ; } if ( ! flag ) { for ( int i = r ; i >= l ; i -- ) res . push_back ( i ) ; } else { for ( int i = l ; i <= r ; i ++ ) res . push_back ( i ) ; } for ( auto i : res ) cout << i << " β " ; } int main ( ) { int N = 10 , K = 4 ; printPermutation ( N , K ) ; return 0 ; } |
Find Nth term of the series 1 , 8 , 54 , 384. . . | CPP program to find N - th term of the series : 1 , 8 , 54 , 384. . . ; calculate factorial of N ; calculate Nth term of series ; Driver Function | #include <iostream> NEW_LINE using namespace std ; int fact ( int N ) { int i , product = 1 ; for ( i = 1 ; i <= N ; i ++ ) product = product * i ; return product ; } int nthTerm ( int N ) { return ( N * N ) * fact ( N ) ; } int main ( ) { int N = 4 ; cout << nthTerm ( N ) ; return 0 ; } |
Rabin | Following program is a C ++ implementation of Rabin Karp Algorithm given in the CLRS book ; d is the number of characters in the input alphabet ; pat -> pattern txt -> text q -> A prime number ; hash value for pattern int t = 0 ; hash value for txt ; The value of h would be " pow ( d , β M - 1 ) % q " ; Calculate the hash value of pattern and first window of text ; Slide the pattern over text one by one ; Check the hash values of current window of text and pattern . If the hash values match then only check for characters one by one ; Check for characters one by one ; if p == t and pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Calculate hash value for next window of text : Remove leading digit , add trailing digit ; We might get negative value of t , converting it to positive ; Driver code ; A prime number ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define d 256 NEW_LINE void search ( char pat [ ] , char txt [ ] , int q ) { int M = strlen ( pat ) ; int N = strlen ( txt ) ; int i , j ; int h = 1 ; for ( i = 0 ; i < M - 1 ; i ++ ) h = ( h * d ) % q ; for ( i = 0 ; i < M ; i ++ ) { p = ( d * p + pat [ i ] ) % q ; t = ( d * t + txt [ i ] ) % q ; } for ( i = 0 ; i <= N - M ; i ++ ) { if ( p == t ) { bool flag = true ; for ( j = 0 ; j < M ; j ++ ) { if ( txt [ i + j ] != pat [ j ] ) { flag = false ; break ; } if ( flag ) cout << i << " β " ; } if ( j == M ) cout << " Pattern β found β at β index β " << i << endl ; } if ( i < N - M ) { t = ( d * ( t - txt [ i ] * h ) + txt [ i + M ] ) % q ; if ( t < 0 ) t = ( t + q ) ; } } } int main ( ) { char txt [ ] = " GEEKS β FOR β GEEKS " ; char pat [ ] = " GEEK " ; int q = 101 ; search ( pat , txt , q ) ; return 0 ; } |
Find the final string after flipping bits at the indices that are multiple of prime factors of array elements | C ++ program for the above approach ; Stores smallest prime factor ; Function to find the smallest prime factor for every number till MAXN ; Marking smallest prime factor for every number to be itself ; Separately marking spf for every even number as 2 ; Checking if i is prime ; Marking SPF for all numbers divisible by i ; Function to find all the distinct prime factors of the given number x ; Find the prime factors for X ; Find the spf [ ] of x ; Return the prime factors for x ; Function to find string after flipping the characters at indices of prime factors of array elements arr [ ] ; Precalculating Smallest Prime Factor ; Stores the frequency of each prime factor ; Iterate over all elements of the array arr [ ] ; Stores prime factors of arr [ i ] ; Increment the frequency of all prime factors of arr [ i ] ; Iterate over all elements of the array frequency [ ] ; If frequency [ i ] is odd ; Flip bits of all indices that are multiple of i ; Return Answer ; Driver Code | #include " bits / stdc + + . h " NEW_LINE using namespace std ; #define MAXN 100001 NEW_LINE int spf [ MAXN ] ; void sieve ( ) { spf [ 1 ] = 1 ; for ( int i = 2 ; i < MAXN ; i ++ ) spf [ i ] = i ; for ( int i = 4 ; i < MAXN ; i += 2 ) spf [ i ] = 2 ; for ( int i = 3 ; i * i < MAXN ; i ++ ) { if ( spf [ i ] == i ) { for ( int j = i * i ; j < MAXN ; j += i ) { if ( spf [ j ] == j ) spf [ j ] = i ; } } } } vector < int > getFactorization ( int x ) { vector < int > ret ; while ( x != 1 ) { ret . push_back ( spf [ x ] ) ; int value = spf [ x ] ; while ( x % value == 0 ) x = x / value ; } return ret ; } string flipString ( string S , int arr [ ] , int M ) { sieve ( ) ; int frequency [ MAXN ] = { 0 } ; for ( int i = 0 ; i < M ; i ++ ) { vector < int > primeFactors = getFactorization ( arr [ i ] ) ; for ( auto & factors : primeFactors ) { frequency [ factors ] ++ ; frequency [ factors ] %= 2 ; } } int N = S . length ( ) ; for ( int i = 0 ; i < MAXN ; i ++ ) { if ( frequency [ i ] & 1 ) { for ( int j = i ; j <= N ; j += i ) { S [ j - 1 ] = ( S [ j - 1 ] == '1' ? '0' : '1' ) ; } } } return S ; } int main ( ) { string S = "000000" ; int arr [ ] = { 2 , 4 , 6 } ; int M = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << flipString ( S , arr , M ) ; return 0 ; } |
Check if count of 1 s can be made greater in a Binary string by changing 0 s adjacent to 1 s | C ++ program for the above approach ; Function to check whether in a given binary string can we make number of 1 ' s β greater β than β the β number β of β 0' s by doing the given operation ; Stores the count of 0 's ; Stores the count of 1 's ; Traverse through the string S ; Check current character is 1 ; Update cnt1 ; Update cnt0 ; Traverse through the string S ; Check curretn character is 1 ; Check if left adjacent character is 0 ; Change the left adjacent character to _ ; Update the cnt0 ; Check if right adjacent character is 0 ; Change the right adjacent character to _ ; Update the cnt0 ; Check count of 1 ' s β is β greater β β than β the β count β of β 0' s ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void isOnesGreater ( string S , int N ) { int cnt0 = 0 ; int cnt1 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) cnt1 ++ ; else cnt0 ++ ; } for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) { if ( i > 0 && S [ i - 1 ] == '0' ) { S [ i - 1 ] = ' _ ' ; cnt0 -- ; } else if ( i < N && S [ i + 1 ] == '0' ) { S [ i + 1 ] = ' _ ' ; cnt0 -- ; } } } if ( cnt1 > cnt0 ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string S = "01" ; int N = S . length ( ) ; isOnesGreater ( S , N ) ; return 0 ; } |
Minimize flips to make binary string as all 1 s by flipping characters in substring of size K repeatedly | C ++ program for the above approach ; Function to find the minimum number of operations required to convert all the characters to 1 by flipping the substrings of size K ; Stores the minimum number of operations required ; Traverse the string S ; If the character is 0 ; Flip the substrings of size K starting from i ; Increment the minimum count of operations required ; After performing the operations check if string S contains any 0 s ; If S contains only 1 's ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperation ( string S , int K , int N ) { int min = 0 ; int i ; for ( i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '0' && i + K <= N ) { for ( int j = i ; j < i + K ; j ++ ) { if ( S [ j ] == '1' ) S [ j ] = '0' ; else S [ j ] = '1' ; } min ++ ; } } for ( i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '0' ) break ; } if ( i == N ) cout << min ; else cout << -1 ; } int main ( ) { string S = "00010110" ; int K = 3 ; int N = S . length ( ) ; minOperation ( S , K , N ) ; return 0 ; } |
Check if string S1 can be formed using repeated insertions of another string S2 | C ++ implementation for the above approach ; Function to check a valid insertion ; Store the size of string ; Maintain a stack for characters ; Iterate through the string ; push the current character on top of the stack ; If the current character is the last character of string S2 then pop characters until S2 is not formed ; index of last character of the string S2 ; pop characters till 0 - th index ; Check if stack in non - empty ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool validInsertionstring ( string S1 , string S2 ) { int N = S1 . length ( ) ; int M = S2 . length ( ) ; stack < char > st ; for ( int i = 0 ; i < N ; i ++ ) { st . push ( S1 [ i ] ) ; if ( S1 [ i ] == S2 [ M - 1 ] ) { int idx = M - 1 ; while ( idx >= 0 ) { if ( st . empty ( ) ) { return false ; } char c = st . top ( ) ; st . pop ( ) ; if ( c != S2 [ idx ] ) { return false ; } idx -- ; } } } if ( ! st . empty ( ) ) { return false ; } else { return true ; } } int main ( ) { string S1 = " aabb " ; string S2 = " ab " ; validInsertionstring ( S1 , S2 ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; } |
Minimum number of towers required such that every house is in the range of at least one tower | C ++ implementation of above approach ; Function to count the number of tower ; first we sort the house numbers ; for count number of towers ; for iterate all houses ; count number of towers ; find find the middle location ; traverse till middle location ; this is point to middle house where we insert the tower ; now find the last location ; traverse till last house of the range ; return the number of tower ; Driver code ; given elements ; print number of towers | #include <bits/stdc++.h> NEW_LINE using namespace std ; int number_of_tower ( int house [ ] , int range , int n ) { sort ( house , house + n ) ; int numOfTower = 0 ; int i = 0 ; while ( i < n ) { numOfTower ++ ; int loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; -- i ; loc = house [ i ] + range ; while ( i < n && house [ i ] <= loc ) i ++ ; } return numOfTower ; } int main ( ) { int house [ ] = { 7 , 2 , 4 , 6 , 5 , 9 , 12 , 11 } ; int range = 2 ; int n = sizeof ( house ) / sizeof ( house [ 0 ] ) ; cout << number_of_tower ( house , range , n ) ; } |
Check if rearranging Array elements can form a Palindrome or not | C ++ implementation of the above approach ; Function to check whether elements of an array can form a palindrome ; create an empty string to append elements of an array ; append each element to the string str to form a string so that we can solve it in easy way ; Create a freq array and initialize all values as 0 ; For each character in formed string , increment freq in the corresponding freq array ; Count odd occurring characters ; Return true if odd count is 0 or 1 , ; Drive code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 256 NEW_LINE bool can_form_palindrome ( int arr [ ] , int n ) { string str = " " ; for ( int i = 0 ; i < n ; i ++ ) { str += arr [ i ] ; } int freq [ MAX ] = { 0 } ; for ( int i = 0 ; str [ i ] ; i ++ ) { freq [ str [ i ] ] ++ ; } int count = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] & 1 ) { count ++ ; } if ( count > 1 ) { return false ; } } return true ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 1 , 2 } ; int n = sizeof ( arr ) / sizeof ( int ) ; can_form_palindrome ( arr , n ) ? cout << " YES " : cout << " NO " ; return 0 ; } |
Minimum number of flips to make a Binary String increasing | C ++ program for the above approach ; ; Function to find the minimum number of flips required to make string increasing ; Length of s ; Total number of zero in s ; Stores count of 1 s till ith index ; stores the minimum count of flip ; Traverse the given string ; Update the value of res and count of 1 s ; Return the minimum number of flips ; Driver code ; Given string ; function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minimumFlips ( string s ) { int n = s . size ( ) ; int cnt0 = count ( s . begin ( ) , s . end ( ) , '0' ) ; int cnt1 = 0 ; int res = n - cnt0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '0' ) { cnt0 -= 1 ; } else if ( s [ i ] == '1' ) { res = min ( res , cnt1 + cnt0 ) ; cnt1 ++ ; } } return res ; } int main ( ) { string S = "000110" ; cout << minimumFlips ( S ) ; return 0 ; } |
Lexicographically shortest string of length at most K which is not a substring of given String | C ++ implementation for above approach ; Function to return a set of all substrings of given string which have length less than or equal to k ; Function to print the lexicographically smallest substring of length atmost k which is not present in given string s ; All substrings of length atmost k present in string s are stored in this set ; Loop to change length of substring ; String with length = len which has all characters as ' a ' ; If the substrings set does not contain this string then we have found the answer ; Changing the likes of ' azz ' and ' daz ' to ' baa ' and ' dba ' respectively ; Reached a string like ' zz ' or ' zzz ' increase the length of the substring ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; set < string > presentSubstring ( string s , int k ) { set < string > st ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { string s1 = " " ; for ( int j = 0 ; j < k && i + j < n ; j ++ ) { s1 . push_back ( s [ i + j ] ) ; st . insert ( s1 ) ; } } return st ; } string smallestSubstring ( string s , int k ) { set < string > st ; st = presentSubstring ( s , k ) ; int index ; for ( int len = 1 ; len <= k ; len ++ ) { string t ( len , ' a ' ) ; while ( true ) { if ( st . count ( t ) == 0 ) { return t ; } index = len - 1 ; while ( index >= 0 && t [ index ] == ' z ' ) { t [ index ] = ' a ' ; index -- ; } if ( index >= 0 ) t [ index ] ++ ; else break ; } } return " - 1" ; } int main ( ) { string s = " sdhaacbdefghijklmnopqrstuvwxyz " ; int K = 3 ; cout << smallestSubstring ( s , K ) << endl ; return 0 ; } |
Maximum length of a substring required to be flipped repeatedly to make all characters of binary string equal to 0 | C ++ program for the above approach ; Function to find the maximum value of K such that flipping substrings of size at least K make all characters 0 s ; Stores the maximum value of K ; Traverse the given string S ; Store the minimum of the maximum of LHS and RHS length ; Flip performed ; If no flips performed ; Return the possible value of K ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumK ( string & S ) { int N = S . length ( ) ; int ans = N ; int flag = 0 ; for ( int i = 0 ; i < N - 1 ; i ++ ) { if ( S [ i ] != S [ i + 1 ] ) { flag = 1 ; ans = min ( ans , max ( i + 1 , N - i - 1 ) ) ; } } if ( flag == 0 ) return 0 ; return ans ; } int main ( ) { string S = "010" ; cout << maximumK ( S ) ; return 0 ; } |
Check if a pair of strings exists that starts with and without the character K or not | C ++ program for the above approach ; Function to check whether a pair of strings exists satisfying the conditions ; Stores the visited strings ; Iterate over the array arr [ ] ; If first character of current string is K ; Otherwise ; Adding to the visited ; Driver Code ; Given Input | #include <bits/stdc++.h> NEW_LINE using namespace std ; string checkhappy ( vector < string > arr , char K , int N ) { set < string > visited ; for ( string s : arr ) { if ( s [ 0 ] == K ) if ( visited . find ( s . substr ( 1 ) ) != visited . end ( ) ) return " Yes " ; else if ( visited . find ( ( K + s ) ) != visited . end ( ) ) return " Yes " ; visited . insert ( s ) ; } return " No " ; } int main ( ) { vector < string > arr = { " a " , " ! β a " , " b " , " ! β c " , " d " , " ! β d " } ; char K = ' ! ' ; int N = arr . size ( ) ; cout << checkhappy ( arr , K , N ) << endl ; return 0 ; } |
Minimum moves to make count of lowercase and uppercase letters equal | C ++ program for the above approach ; Function to calculate minimum number of moves required to convert the string ; Stores Count of upper and lower case characters ; Traverse the string S ; If current character is uppercase ; Increment count of Uppercase characters ; Otherwise , ; Increment count of Lowercase characters ; Stores minimum number of moves needed ; If there are more upper case characters ; Iterate until upper is greater than N / 2 ; Convert uppercase into lowercase until upper = N / 2 ; Increment the pointer ; If there are more lower case characters ; Iterate until lower is greater than N / 2 ; Convert lowercase into uppercase until lower = N / 2 ; Increment the pointer ; Print moves required ; Print resultant string ; Driver Code ; Given string ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumTimeToConvertString ( string S , int N ) { int upper = 0 , lower = 0 ; for ( int i = 0 ; i < N ; i ++ ) { char c = S [ i ] ; if ( isupper ( c ) ) { upper ++ ; } else { lower ++ ; } } int moves = 0 ; if ( upper > N / 2 ) { int i = 0 ; while ( upper > N / 2 && i < N ) { if ( isupper ( S [ i ] ) ) { S [ i ] += 32 ; moves ++ ; upper -- ; lower ++ ; } i ++ ; } } else if ( lower > N / 2 ) { int i = 0 ; while ( lower > N / 2 && i < N ) { if ( islower ( S [ i ] ) ) { S [ i ] -= 32 ; moves ++ ; upper ++ ; lower -- ; } i ++ ; } } cout << moves << endl ; cout << S << endl ; } int main ( ) { string S = " AbcdEf " ; int N = S . length ( ) ; minimumTimeToConvertString ( S , N ) ; return 0 ; } |
Program to print a string in vertical zigzag manner | C ++ program for the above approach ; Function to print any string in zigzag fashion ; Store the gap between the major columns ; Traverse through rows ; Store the step value for each row ; Iterate in the range [ 1 , N - 1 ] ; Print the character ; Print the spaces before character s [ j + step ] ; Print the character ; Print the spaces after character after s [ j + step ] ; Print the spaces for first and last rows ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void zigzag ( string s , int rows ) { int interval = 2 * rows - 2 ; for ( int i = 0 ; i < rows ; i ++ ) { int step = interval - 2 * i ; for ( int j = i ; j < s . length ( ) ; j = j + interval ) { cout << s [ j ] ; if ( step > 0 && step < interval && step + j < s . length ( ) ) { for ( int k = 0 ; k < ( interval - rows - i ) ; k ++ ) cout << " β " ; cout << s [ j + step ] ; for ( int k = 0 ; k < i - 1 ; k ++ ) cout << " β " ; } else { for ( int k = 0 ; k < ( interval - rows ) ; k ++ ) cout << " β " ; } } cout << endl ; } } int main ( ) { string s = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefgh " " ijklmnopqrstuvwxyz " ; int rows = 9 ; zigzag ( s , rows ) ; } |
Number of substrings with each character occurring even times | C ++ program for the above approach ; Function to count substrings having even frequency of each character ; Stores the count of a character ; Stores bitmask ; Stores the count of substrings with even count of each character ; Traverse the string S ; Flip the ord ( i ) - 97 bits in pre ; Increment the count by hash [ pre ] ; Increment count of pre in hash ; Return the total count obtained ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int subString ( string s , int n ) { map < int , int > hash ; hash [ 0 ] = 1 ; int pre = 0 ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { pre ^= ( 1 << int ( s [ i ] ) - 97 ) ; count += hash [ pre ] ; hash [ pre ] = hash [ pre ] + 1 ; } return count ; } int main ( ) { string S = " abbaa " ; int N = S . length ( ) ; cout << ( subString ( S , N ) ) ; } |
Count number of substrings having at least K distinct characters | C ++ program for the above approach ; Function to count number of substrings having atleast k distinct characters ; Stores the size of the string ; Initialize a HashMap ; Stores the start and end indices of sliding window ; Stores the required result ; Iterate while the end pointer is less than n ; Include the character at the end of the window ; Increment end pointer by 1 ; Iterate until count of distinct characters becomes less than K ; Remove the character from the beginning of window ; If its frequency is 0 , remove it from the map ; Update the answer ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void atleastkDistinctChars ( string s , int k ) { int n = s . size ( ) ; unordered_map < char , int > mp ; int begin = 0 , end = 0 ; int ans = 0 ; while ( end < n ) { char c = s [ end ] ; mp ++ ; end ++ ; while ( mp . size ( ) >= k ) { char pre = s [ begin ] ; mp [ pre ] -- ; if ( mp [ pre ] == 0 ) { mp . erase ( pre ) ; } ans += s . length ( ) - end + 1 ; begin ++ ; } } cout << ans ; } int main ( ) { string S = " abcca " ; int K = 3 ; atleastkDistinctChars ( S , K ) ; return 0 ; } |
Rearrange characters of a string to make it a concatenation of palindromic substrings | C ++ program for the above approach ; Function to check if a string can be modified such that it can be split into palindromic substrings of length >= 2 ; Stores frequencies of characters ; Traverse the string ; Update frequency of each character ; Traverse the frequency array ; Update values of odd and eve ; Print the result ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void canSplit ( string & S ) { vector < int > frequency ( 26 , 0 ) ; int cnt_singles = 0 ; int k = 0 ; for ( int i = 0 ; i < S . length ( ) ; i ++ ) frequency [ S [ i ] - ' a ' ] ++ ; int odd = 0 , eve = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( frequency [ i ] ) { odd += ( frequency [ i ] & 1 ) ; eve += frequency [ i ] / 2 ; } } if ( eve >= odd ) cout << " Yes " ; else cout << " No " ; } int main ( ) { string S = " aaabbbccc " ; canSplit ( S ) ; return 0 ; } |
Smallest element in an array that is repeated exactly ' k ' times . | C ++ program to find smallest number in array that is repeated exactly ' k ' times . ; finds the smallest number in arr [ ] that is repeated k times ; Computing frequencies of all elements ; Finding the smallest element with frequency as k ; If frequency of any of the number is equal to k starting from 0 then return the number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 1000 ; int findDuplicate ( int arr [ ] , int n , int k ) { int freq [ MAX ] ; memset ( freq , 0 , sizeof ( freq ) ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] < 1 && arr [ i ] > MAX ) { cout << " Out β of β range " ; return -1 ; } freq [ arr [ i ] ] += 1 ; } for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] == k ) return i ; } return -1 ; } int main ( ) { int arr [ ] = { 2 , 2 , 1 , 3 , 1 } ; int k = 2 ; int n = sizeof ( arr ) / ( sizeof ( arr [ 0 ] ) ) ; cout << findDuplicate ( arr , n , k ) ; return 0 ; } |
Maximize count of occurrences of S2 in S1 as a subsequence by concatenating N1 and N2 times respectively | C ++ program for the above approach ; Function to count maximum number of occurrences of s2 as subsequence in s1 by concatenating s1 , n1 times and s2 , n2 times ; Stores number of times s1 is traversed ; Stores number of times s2 is traversed ; Mapping index of s2 to number of times s1 and s2 are traversed ; Stores index of s1 circularly ; Stores index of s2 circularly ; Traverse the string s1 , n1 times ; If current character of both the string are equal ; Update j ; Update i ; If j is length of s2 ; Update j for circular traversal ; Update s2_reps ; If i is length of s1 ; Update i for circular traversal ; Update s1_reps ; If already mapped j to ( s1_reps , s2_reps ) ; Mapping j to ( s1_reps , s2_reps ) ; If s1 already traversed n1 times ; Otherwis , traverse string s1 by multiple of s1_reps and update both s1_reps and s2_reps ; Update s2_reps ; Update s1_reps ; If s1 is traversed less than n1 times ; If current character in both the string are equal ; Update j ; Update i ; If i is length of s1 ; Update i for circular traversal ; Update s1_reps ; If j is length of ss ; Update j for circular traversal ; Update s2_reps ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxRepetitions ( string s1 , int n1 , string s2 , int n2 ) { int temp1 [ 26 ] = { 0 } , temp2 [ 26 ] = { 0 } ; for ( char i : s1 ) temp1 [ i - ' a ' ] ++ ; for ( char i : s2 ) temp2 [ i - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( temp2 [ i ] > temp1 [ i ] ) return 0 ; } int s1_reps = 0 ; int s2_reps = 0 ; map < int , pair < int , int > > s2_index_to_reps ; s2_index_to_reps [ 0 ] = { 0 , 0 } ; int i = 0 ; int j = 0 ; while ( s1_reps < n1 ) { if ( s1 [ i ] == s2 [ j ] ) j += 1 ; i += 1 ; if ( j == s2 . size ( ) ) { j = 0 ; s2_reps += 1 ; } if ( i == s1 . size ( ) ) { i = 0 ; s1_reps += 1 ; if ( s2_index_to_reps . find ( j ) != s2_index_to_reps . end ( ) ) break ; s2_index_to_reps [ j ] = { s1_reps , s2_reps } ; } } if ( s1_reps == n1 ) return s2_reps / n2 ; int initial_s1_reps = s2_index_to_reps [ j ] . first , initial_s2_reps = s2_index_to_reps [ j ] . second ; int loop_s1_reps = s1_reps - initial_s1_reps ; int loop_s2_reps = s2_reps - initial_s2_reps ; int loops = ( n1 - initial_s1_reps ) ; s2_reps = initial_s2_reps + loops * loop_s2_reps ; s1_reps = initial_s1_reps + loops * loop_s1_reps ; while ( s1_reps < n1 ) { if ( s1 [ i ] == s2 [ j ] ) j += 1 ; i += 1 ; if ( i == s1 . size ( ) ) { i = 0 ; s1_reps += 1 ; } if ( j == s2 . size ( ) ) { j = 0 ; s2_reps += 1 ; } } return s2_reps / n2 ; } int main ( ) { string s1 = " acb " ; int n1 = 4 ; string s2 = " ab " ; int n2 = 2 ; cout << ( getMaxRepetitions ( s1 , n1 , s2 , n2 ) ) ; return 0 ; } |
Shortest string possible after removal of all pairs of similar adjacent characters | C ++ program for the above approach ; Function to delete pair of adjacent characters which are equal ; Base Case ; Stores the update string ; Traverse the string s ; If two unequal pair of adjacent characters are found ; If two equal pair of adjacent characters are found ; Append the remaining string after removing the pair ; Return the final String ; Function to find the shortest string after repeatedly removing pairs of adjacent characters which are equal ; Stores the resultant String ; Keeps track of previously iterated string ; Update the result after deleting adjacent pair of characters which are similar ; Termination Conditions ; Update pre variable with the value of result ; Case for " Empty β String " ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string removeAdjacent ( string s ) { if ( s . length ( ) == 1 ) return s ; string sb = " " ; for ( int i = 0 ; i < s . length ( ) - 1 ; i ++ ) { char c = s [ i ] ; char d = s [ i + 1 ] ; if ( c != d ) { sb = sb + c ; if ( i == s . length ( ) - 2 ) { sb = sb + d ; } } else { for ( int j = i + 2 ; j < s . length ( ) ; j ++ ) sb = sb + s [ j ] ; return sb ; } } return sb ; } void reduceString ( string s ) { string result = " " ; string pre = s ; while ( true ) { result = removeAdjacent ( pre ) ; if ( result == pre ) break ; pre = result ; } if ( result . length ( ) != 0 ) cout << ( result ) << endl ; else cout << " Empty β String " << endl ; } int main ( ) { string S = " aaabccddd " ; reduceString ( S ) ; return 0 ; } |
Minimum removals required such that a string can be rearranged to form a palindrome | C ++ program for the above approach ; Function to find the number of deletions required such that characters of the string can be rearranged to form a palindrome ; Stores frequency of characters ; Store the frequency of each character in frequency array ; Count number of characters with odd frequency ; If count is 1 or 0 , return 0 ; Otherwise , return count - 1 ; Driver Code ; Function call to find minimum number of deletions required | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minDeletions ( string str ) { int fre [ 26 ] ; memset ( fre , 0 , sizeof ( fre ) ) ; int n = str . size ( ) ; cout << n ; for ( int i = 0 ; i < n ; i ++ ) { fre [ str [ i ] - ' a ' ] += 1 ; } for ( int i = 0 ; i < n ; i ++ ) { cout << fre [ i ] ; } int count = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( fre [ i ] % 2 ) { count += 1 ; } } if ( count == 0 count == 1 ) { return 0 ; } else { return count - 1 ; } } int main ( ) { string str = " ababbccca " ; cout << minDeletions ( str ) << endl ; } |
Program to print an array in Pendulum Arrangement | C ++ program for pendulum arrangement of numbers ; Prints pendulum arrangement of arr [ ] ; sorting the elements ; Auxiliary array to store output ; calculating the middle index ; storing the minimum element in the middle i is index for output array and j is for input array . ; adjustment for when no . of elements is even ; Printing the pendulum arrangement ; Driver function ; input Array ; calculating the length of array A ; calling pendulum function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void pendulumArrangement ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int op [ n ] ; int mid = ( n - 1 ) / 2 ; int j = 1 , i = 1 ; op [ mid ] = arr [ 0 ] ; for ( i = 1 ; i <= mid ; i ++ ) { op [ mid + i ] = arr [ j ++ ] ; op [ mid - i ] = arr [ j ++ ] ; } if ( n % 2 == 0 ) op [ mid + i ] = arr [ j ] ; cout << " Pendulum β arrangement : " << endl ; for ( i = 0 ; i < n ; i ++ ) cout << op [ i ] << " β " ; cout << endl ; } int main ( ) { int arr [ ] = { 14 , 6 , 19 , 21 , 12 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; pendulumArrangement ( arr , n ) ; return 0 ; } |
Calculate score of parentheses from a given string | C ++ program for the above approach ; Function to calculate the score of the parentheses using stack ; To keep track of the score ; Initially , push 0 to stack ; Traverse the string s ; If ' ( ' is encountered , then push 0 to stack ; Otherwise ; Balance the last ' ( ' , and store the score of inner parentheses ; If tmp is not zero , it means inner parentheses exists ; Otherwise , it means no inner parentheses exists ; Pass the score of this level to parent parentheses ; Print the score ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void scoreOfParentheses ( string s ) { stack < int > stack ; stack . push ( 0 ) ; for ( char c : s ) { if ( c == ' ( ' ) stack . push ( 0 ) ; else { int tmp = stack . top ( ) ; stack . pop ( ) ; int val = 0 ; if ( tmp > 0 ) val = tmp * 2 ; else val = 1 ; stack . top ( ) += val ; } } cout << stack . top ( ) ; } int main ( ) { string S = " ( ( ) ( ( ) ) ) " ; scoreOfParentheses ( S ) ; return 0 ; } |
Count unique substrings of a string S present in a wraparound string | C ++ program for the above approach ; Function to find the count of non - empty substrings of p present in s ; Stores the required answer ; Stores the length of substring present in p ; Stores the current length of substring that is present in string s starting from each character of p ; Iterate over the characters of the string ; Check if the current character can be added with previous substring to form the required substring ; Increment current length ; To avoid repetition ; Update arr [ cur ] ; Print the answer ; Driver Code ; Function call to find the count of non - empty substrings of p present in s | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubstringInWraproundString ( string p ) { int ans = 0 ; int curLen = 0 ; int arr [ 26 ] = { 0 } ; for ( int i = 0 ; i < ( int ) p . length ( ) ; i ++ ) { int curr = p [ i ] - ' a ' ; if ( i > 0 && ( p [ i - 1 ] != ( ( curr + 26 - 1 ) % 26 + ' a ' ) ) ) { curLen = 0 ; } curLen ++ ; if ( curLen > arr [ curr ] ) { ans += ( curLen - arr [ curr ] ) ; arr [ curr ] = curLen ; } } cout << ans ; } int main ( ) { string p = " zab " ; findSubstringInWraproundString ( p ) ; return 0 ; } |
Minimize sum of given array by removing all occurrences of a single digit | C ++ program for super ugly number ; Function to remove each digit from the given integer ; Convert into string ; Stores final string ; Traverse the string ; Append it to the final string ; Return integer value ; Function to find the minimum sum by removing occurences of each digit ; Iterate in range [ 0 , 9 ] ; Traverse the array ; Update the minimum sum ; Print the minimized sum ; Driver program to test above functions | #include <bits/stdc++.h> NEW_LINE using namespace std ; int remove ( int N , int digit ) { string strN = to_string ( N ) ; string ans = " " ; for ( char i : strN ) { if ( ( i - '0' ) == digit ) { continue ; } ans += i ; } return stoi ( ans ) ; } void getMin ( vector < int > arr ) { int minSum = INT_MAX ; for ( int i = 0 ; i < 10 ; i ++ ) { int curSum = 0 ; for ( int num : arr ) curSum += remove ( num , i ) ; minSum = min ( minSum , curSum ) ; } cout << minSum ; } int main ( ) { vector < int > arr = { 34 , 23 , 85 , 93 } ; getMin ( arr ) ; return 0 ; } |
Split a string into maximum number of unique substrings | CPP program for the above approach ; Utility function to find maximum count of unique substrings by splitting the string ; Stores maximum count of unique substring by splitting the string into substrings ; Iterate over the characters of the string ; Stores prefix substring ; Check if the current substring already exists ; Insert tmp into set ; Recursively call for remaining characters of string ; Remove from the set ; Return answer ; Function to find the maximum count of unique substrings by splitting a string into maximum number of unique substrings ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maxUnique ( string S , set < string > st ) { int mx = 0 ; for ( int i = 1 ; i <= S . length ( ) ; i ++ ) { string tmp = S . substr ( 0 , i ) ; if ( st . find ( tmp ) == st . end ( ) ) { st . insert ( tmp ) ; mx = max ( mx , maxUnique ( S . substr ( i ) , st ) + 1 ) ; st . erase ( tmp ) ; } } return mx ; } int maxUniqueSplit ( string S ) { set < string > st ; return maxUnique ( S , st ) ; } int main ( ) { string S = " ababccc " ; int res = maxUniqueSplit ( S ) ; cout << res ; } |
Minimize length of a given string by removing subsequences forming valid parenthesis | C ++ program of the above approach ; Function to remove all possible valid bracket subsequences ; Stores indexes of ' ( ' in valid subsequences ; Stores indexes of ' { ' in valid subsequences ; Stores indexes of ' [ ' in valid subsequences ; vis [ i ] : Check if character at i - th index is removed or not ; Mark vis [ i ] as not removed ; Iterate over the characters of string ; If current character is ' ( ' ; If current character is ' { ' ; If current character is ' [ ' ; If current character is ' ) ' and top element of A is ' ( ' ; Mark the top element of A as removed ; Mark current chacracter as removed ; If current character is ' } ' and top element of B is ' { ' ; Mark the top element of B as removed ; Mark current chacracter as removed ; If current character is ' ] ' and top element of B is ' [ ' ; Mark the top element of C as removed ; Mark current chacracter as removed ; Print the remaining characters which is not removed from S ; Driver Code ; Given string ; Size of the string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void removeValidBracketSequences ( string & str , int N ) { stack < int > A ; stack < int > B ; stack < int > C ; bool vis [ N ] ; memset ( vis , true , sizeof ( vis ) ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( str [ i ] == ' ( ' ) { A . push ( i ) ; } else if ( str [ i ] == ' { ' ) { B . push ( i ) ; } else if ( str [ i ] == ' [ ' ) { C . push ( i ) ; } else if ( str [ i ] == ' ) ' && ! A . empty ( ) ) { vis [ A . top ( ) ] = false ; A . pop ( ) ; vis [ i ] = false ; } else if ( str [ i ] == ' } ' && ! B . empty ( ) ) { vis [ B . top ( ) ] = false ; B . pop ( ) ; vis [ i ] = false ; } else if ( str [ i ] == ' ] ' && ! C . empty ( ) ) { vis [ C . top ( ) ] = false ; C . pop ( ) ; vis [ i ] = false ; } } for ( int i = 0 ; i < N ; ++ i ) { if ( vis [ i ] ) cout << str [ i ] ; } } int main ( ) { string str = " ( ( ) { ( ) ( { } ) " ; int N = str . length ( ) ; removeValidBracketSequences ( str , N ) ; return 0 ; } |
Queries to calculate difference between the frequencies of the most and least occurring characters in specified substring | C ++ program for the above approach ; Function to update frequency of a character in Fenwick tree ; Update frequency of ( idx + ' a ' ) ; Update i ; Function to find the frequency of a character ( idx + ' a ' ) in range [ 1 , i ] ; Stores frequency of character , ( idx + ' a ' ) in range [ 1 , i ] ; Update ans ; Update i ; Function to find difference between maximum and minimum frequency of a character in given range ; BIT [ i ] [ j ] : Stores frequency of ( i + ' a ' ) If j is a power of 2 , then it stores the frequency ( i + ' a ' ) of from [ 1 , j ] ; Stores length of string ; Iterate over the characters of the string ; Update the frequency of s [ i ] in fenwick tree ; Stores count of queries ; Iterate over all the queries ; Stores maximum frequency of a character in range [ l , r ] ; Stores minimum frequency of a character in range [ l , r ] ; Iterate over all possible characters ; Stores frequency of ( j + ' a ' ) in range [ 1 , r ] ; Stores frequency of ( j + ' a ' ) in range [ 1 , l - 1 ] ; Update mx ; If a character ( i + ' a ' ) present in range [ l , r ] ; Update mn ; Print the difference between max and min freq ; Driver Code ; Given string ; Given queries ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void update ( int BIT [ 26 ] [ 10005 ] , int idx , int i , int val ) { while ( i < 10005 ) { BIT [ idx ] [ i ] += val ; i = i + ( i & ( - i ) ) ; } } int query ( int BIT [ 26 ] [ 10005 ] , int idx , int i ) { int ans = 0 ; while ( i > 0 ) { ans += BIT [ idx ] [ i ] ; i = i - ( i & ( - i ) ) ; } return ans ; } void maxDiffFreq ( string s , vector < pair < int , int > > queries ) { int BIT [ 26 ] [ 10005 ] ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { update ( BIT , s [ i ] - ' a ' , i + 1 , 1 ) ; } int Q = queries . size ( ) ; for ( int i = 0 ; i < Q ; ++ i ) { int mx = 0 ; int mn = INT_MAX ; int l = queries [ i ] . first ; int r = queries [ i ] . second ; for ( int j = 0 ; j < 26 ; j ++ ) { int p = query ( BIT , j , r ) ; int q = query ( BIT , j , l - 1 ) ; mx = max ( mx , p - q ) ; if ( p > 0 ) { mn = min ( mn , p - q ) ; } } cout << mx - mn << endl ; } } int main ( ) { string S = " abaabac " ; vector < pair < int , int > > queries = { { 2 , 6 } , { 1 , 7 } } ; maxDiffFreq ( S , queries ) ; } |
Make all strings from a given array equal by replacing minimum number of characters | C ++ program to implement the above approach ; Function to find the minimum count of operations required to make all strings equal by replacing characters of strings ; Stores minimum count of operations required to make all strings equal ; Stores length of the string ; hash [ i ] [ j ] : Stores frequency of character i present at j - th index of all strings ; Traverse the array arr [ ] ; Iterate over characters of current string ; Update frequency of arr [ i ] [ j ] ; Traverse hash [ ] [ ] array ; Stores sum of i - th column ; Stores the largest element of i - th column ; Iterate over all possible characters ; Update Sum ; Update Max ; Update cntMinOP ; Driver Code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperation ( string arr [ ] , int N ) { int cntMinOP = 0 ; int M = arr [ 0 ] . length ( ) ; int hash [ 256 ] [ M ] ; memset ( hash , 0 , sizeof ( hash ) ) ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { hash [ arr [ i ] [ j ] ] [ j ] ++ ; } } for ( int i = 0 ; i < M ; i ++ ) { int Sum = 0 ; int Max = 0 ; for ( int j = 0 ; j < 256 ; j ++ ) { Sum += hash [ j ] [ i ] ; Max = max ( Max , hash [ j ] [ i ] ) ; } cntMinOP += ( Sum - Max ) ; } return cntMinOP ; } int main ( ) { string arr [ ] = { " abcd " , " bcde " , " cdef " } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperation ( arr , N ) << " STRNEWLINE " ; } |
Maximize count of distinct strings generated by replacing similar adjacent digits having sum K with K | C ++ program for the above approach ; Function to find the desired number of strings ; Store the count of strings ; Store the length of the string ; Initialize variable to indicate the start of the substring ; Store the starting index of the substring ; Traverse the string ; If sum of adjacent characters is K mark the starting index and set flag to 1 ; If sum of adjacent characters is not K and the flag variable is set , end the substring here ; Set flag to 0 denoting the end of substring ; Check if the length of the substring formed is odd ; Update the answer ; If flag is set and end of string is reached , mark the end of substring ; Update the answer ; Print the answer ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countStrings ( string s , int k ) { int ans = 1 ; int len = s . size ( ) ; int flag = 0 ; int start_ind ; for ( int i = 0 ; i < len - 1 ; i ++ ) { if ( s [ i ] - '0' + s [ i + 1 ] - '0' == k && flag == 0 ) { flag = 1 ; start_ind = i ; } if ( flag == 1 && s [ i ] - '0' + s [ i + 1 ] - '0' != k ) { flag = 0 ; if ( ( i - start_ind + 1 ) % 2 != 0 ) ans *= ( i - start_ind + 1 - 1 ) / 2 + 1 ; } } if ( flag == 1 && ( len - start_ind ) % 2 != 0 ) ans *= ( len - start_ind ) / 2 + 1 ; cout << ans ; } int main ( ) { string S = "313" ; int K = 4 ; countStrings ( S , K ) ; } |
Smallest number whose product with N has sum of digits equal to that of N | C ++ program for the above approach ; Function to find the minimum integer having sum of digits of a number multiplied by n equal to sum of digits of n ; Initialize answer ; Find sum of digits of N ; Multiply N with x ; Sum of digits of the new number ; If condition satisfies ; Print answer ; Driver Code ; Function call | #include <iostream> NEW_LINE using namespace std ; void find_num ( string n ) { int ans = 0 ; int sumOfDigitsN = 0 ; for ( int c = 0 ; c < n . length ( ) ; c ++ ) { sumOfDigitsN += n - '0' ; } int x = 11 ; while ( true ) { int newNum = x * stoi ( n ) ; int tempSumDigits = 0 ; string temp = to_string ( newNum ) ; for ( int c = 0 ; c < temp . length ( ) ; c ++ ) { tempSumDigits += temp - '0' ; } if ( tempSumDigits == sumOfDigitsN ) { ans = x ; break ; } x ++ ; } cout << ans << endl ; } int main ( ) { string N = "3029" ; find_num ( N ) ; return 0 ; } |
Print all distinct strings from a given array | C ++ program to implement the above approach ; Function to find the distinct strings from the given array ; Stores distinct strings from the given array ; Traverse the array ; If current string not present into the set ; Insert current string into the set ; Traverse the set DistString ; Print distinct string ; Driver Code ; Stores length of the array | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findDisStr ( vector < string > & arr , int N ) { unordered_set < string > DistString ; for ( int i = 0 ; i < N ; i ++ ) { if ( ! DistString . count ( arr [ i ] ) ) { DistString . insert ( arr [ i ] ) ; } } for ( auto String : DistString ) { cout << String << " β " ; } } int main ( ) { vector < string > arr = { " Geeks " , " For " , " Geeks " , " Code " , " Coder " } ; int N = arr . size ( ) ; findDisStr ( arr , N ) ; return 0 ; } |
Reverse substrings of given string according to specified array indices | C ++ program for the above approach ; Function to perform the reversal operation on the given string ; Size of string ; Stores the count of indices ; Count the positions where reversals will begin ; Store the count of reversals beginning at position i ; Check if the count [ i ] is odd the swap the character ; Return the updated string ; Driver Code ; Given string str ; Given array of reversing index ; Function Call | #include <iostream> NEW_LINE using namespace std ; string modifyString ( int A [ ] , string str , int K ) { int N = str . size ( ) ; int count [ N + 1 ] = { 0 } ; for ( int i = 0 ; i < K ; i ++ ) { count [ A [ i ] ] ++ ; } for ( int i = 1 ; i <= N / 2 ; i ++ ) { count [ i ] = count [ i ] + count [ i - 1 ] ; if ( count [ i ] & 1 ) { swap ( str [ i - 1 ] , str [ N - i ] ) ; } } return str ; } int main ( ) { string str = " abcdef " ; int arr [ ] = { 1 , 2 , 3 } ; int K = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << modifyString ( arr , str , K ) ; return 0 ; } |
Convert given Float value to equivalent Fraction | C ++ program for the above approach ; Function to convert the floating values into fraction ; Initialize variables ; Traverse the floating string ; Check if decimal part exist ; Check if recurrence sequence exist ; Retrieve decimal part and recurrence re sequence ; Traverse the string ; Convert string to integer ; If no recurrence sequence exist ; Initialize numerator & denominator ; No reccuring term ; Print the result ; If reccuring term exist ; Convert reccuring term to integer ; reccu . size ( ) is num of digit in reccur term ; eq 2 - eq 1 ; Print the result ; Driver Code ; Given string str ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findFraction ( string s ) { string be_deci = " " , af_deci = " " , reccu = " " ; bool x = true , y = false , z = false ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { if ( s [ i ] == ' . ' ) { x = false ; y = true ; continue ; } if ( s [ i ] == ' ( ' ) { z = true ; y = false ; continue ; } if ( x ) be_deci += s [ i ] ; if ( y ) af_deci += s [ i ] ; if ( z ) { for ( ; i < s . size ( ) && s [ i ] != ' ) ' ; ++ i ) reccu += s [ i ] ; break ; } } int num_be_deci = stoi ( be_deci ) ; int num_af_deci = 0 ; if ( af_deci . size ( ) != 0 ) num_af_deci = stoi ( af_deci ) ; int numr = num_be_deci * pow ( 10 , af_deci . size ( ) ) + num_af_deci ; int deno = pow ( 10 , af_deci . size ( ) ) ; if ( reccu . size ( ) == 0 ) { int gd = __gcd ( numr , deno ) ; cout << numr / gd << " β / β " << deno / gd ; } else { int reccu_num = stoi ( reccu ) ; int numr1 = numr * pow ( 10 , reccu . size ( ) ) + reccu_num ; int deno1 = deno * pow ( 10 , reccu . size ( ) ) ; int res_numr = numr1 - numr , res_deno = deno1 - deno ; int gd = __gcd ( res_numr , res_deno ) ; cout << res_numr / gd << " β / β " << res_deno / gd ; } } int main ( ) { string str = "23.98(231 ) " ; findFraction ( str ) ; return 0 ; } |
Lexicographically largest string possible for a given cost of appending characters | C ++ Program to implement the above approach ; Function to find the lexicographically largest String possible ; If sum is less than 0 ; If sum is equal to 0 ; If sum is less than 0 ; Add current character ; Check if selecting current character generates lexicographically largest String ; Backtrack if solution not found ; Find the lexicographically largest String excluding the current character ; Function to print the lexicographically largest String generated ; Function call ; Stores the String ; Print the lexicographically largest String formed ; Driver code ; Cost of adding each alphabet ; Cost of generating the String | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool lexi_largest_String ( int a [ ] , int i , int sum , vector < int > & v ) { if ( sum < 0 ) return false ; if ( sum == 0 ) return true ; if ( i < 0 ) return false ; v . push_back ( i ) ; if ( lexi_largest_String ( a , i , sum - a [ i ] , v ) ) return true ; auto it = v . end ( ) ; it -- ; v . erase ( it ) ; return lexi_largest_String ( a , i - 1 , sum , v ) ; } void generateString ( int a [ ] , int sum ) { vector < int > v ; lexi_largest_String ( a , 25 , sum , v ) ; string s = " " ; for ( int j = 0 ; j < v . size ( ) ; j ++ ) s += ( char ) ( v [ j ] + ' a ' ) ; cout << s << endl ; } int main ( ) { int a [ ] = { 1 , 1 , 2 , 33 , 4 , 6 , 9 , 7 , 36 , 32 , 58 , 32 , 28 , 904 , 22 , 255 , 47 , 69 , 558 , 544 , 21 , 36 , 48 , 85 , 48 , 58 } ; int sum = 236 ; generateString ( a , sum ) ; return 0 ; } |
Count of distinct permutations of every possible length of given string | C ++ implementation of the above approach ; Function to find the factorial of a number ; Loop to find the factorial of the given number ; Function to find the number of permutations possible for a given string ; Function to find the total number of combinations possible ; Driver Code | #include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int fact ( int a ) { int i , f = 1 ; for ( i = 2 ; i <= a ; i ++ ) f = f * i ; return f ; } int permute ( int n , int r ) { int ans = 0 ; ans = ( fact ( n ) / fact ( n - r ) ) ; return ans ; } int findPermutations ( int n ) { int sum = 0 , P ; for ( int r = 1 ; r <= n ; r ++ ) { P = permute ( n , r ) ; sum = sum + P ; } return sum ; } int main ( ) { string str = " xz " ; int result , n ; n = str . length ( ) ; cout << findPermutations ( n ) ; return 0 ; } |
Cycles of length n in an undirected and connected graph | CPP Program to count cycles of length n in a given graph . ; Number of vertices ; mark the vertex vert as visited ; if the path of length ( n - 1 ) is found ; mark vert as un - visited to make it usable again . ; Check if vertex vert can end with vertex start ; For searching every possible path of length ( n - 1 ) ; DFS for searching path by decreasing length by 1 ; marking vert as unvisited to make it usable again . ; Counts cycles of length N in an undirected and connected graph . ; all vertex are marked un - visited initially . ; Searching for cycle by using v - n + 1 vertices ; ith vertex is marked as visited and will not be visited again . ; driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int V = 5 ; void DFS ( bool graph [ ] [ V ] , bool marked [ ] , int n , int vert , int start , int & count ) { marked [ vert ] = true ; if ( n == 0 ) { marked [ vert ] = false ; if ( graph [ vert ] [ start ] ) { count ++ ; return ; } else return ; } for ( int i = 0 ; i < V ; i ++ ) if ( ! marked [ i ] && graph [ vert ] [ i ] ) DFS ( graph , marked , n - 1 , i , start , count ) ; marked [ vert ] = false ; } int countCycles ( bool graph [ ] [ V ] , int n ) { bool marked [ V ] ; memset ( marked , 0 , sizeof ( marked ) ) ; int count = 0 ; for ( int i = 0 ; i < V - ( n - 1 ) ; i ++ ) { DFS ( graph , marked , n - 1 , i , i , count ) ; marked [ i ] = true ; } return count / 2 ; } int main ( ) { bool graph [ ] [ V ] = { { 0 , 1 , 0 , 1 , 0 } , { 1 , 0 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 , 0 } , { 1 , 0 , 1 , 0 , 1 } , { 0 , 1 , 0 , 1 , 0 } } ; int n = 4 ; cout << " Total β cycles β of β length β " << n << " β are β " << countCycles ( graph , n ) ; return 0 ; } |
String hashing using Polynomial rolling hash function | C ++ implementation of the Polynomial Rolling Hash Function ; Function to calculate the hash of a string ; P and M ; Loop to calculate the hash value by iterating over the elements of string ; / Driver Code ; Given strings | #include <bits/stdc++.h> NEW_LINE using namespace std ; long long polynomialRollingHash ( string const & str ) { int p = 31 ; int m = 1e9 + 9 ; long long power_of_p = 1 ; long long hash_val = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { hash_val = ( hash_val + ( str [ i ] - ' a ' + 1 ) * power_of_p ) % m ; power_of_p = ( power_of_p * p ) % m ; } return ( hash_val % m + m ) % m ; } int main ( ) { string str1 = " geeksforgeeks " ; string str2 = " geeks " ; cout << " Hash β of β ' " << str1 << " ' β = β " << polynomialRollingHash ( str1 ) ; cout << endl ; } |
Find first non | C ++ implementation to find the first non - repeating element of the string using Linked List ; Function to find the first non - repeating element of the given string using Linked List ; Driver Code ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void firstNonRepElement ( string str ) { map < char , int > mpp ; for ( auto i : str ) { mpp [ i ] ++ ; } for ( auto i : str ) { if ( mpp [ i ] == 1 ) { cout << i << endl ; return ; } } return ; } int main ( ) { string str = " geeksforgeeks " ; firstNonRepElement ( str ) ; } |
Count of substrings of length K with exactly K distinct characters | C ++ program to find the count of k length substrings with k distinct characters using sliding window ; Function to return the required count of substrings ; Store the count ; Store the count of distinct characters in every window ; Store the frequency of the first K length substring ; Increase frequency of i - th character ; If K distinct characters exist ; Traverse the rest of the substring ; Increase the frequency of the last character of the current substring ; Decrease the frequency of the first character of the previous substring ; If the character is not present in the current substring ; If the count of distinct characters is 0 ; Return the count ; Driver code ; string str ; integer K ; Print the count of K length substrings with k distinct characters | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string str , int K ) { int N = str . size ( ) ; int answer = 0 ; unordered_map < char , int > map ; for ( int i = 0 ; i < K ; i ++ ) { map [ str [ i ] ] ++ ; } if ( map . size ( ) == K ) answer ++ ; for ( int i = K ; i < N ; i ++ ) { map [ str [ i ] ] ++ ; map [ str [ i - K ] ] -- ; if ( map [ str [ i - K ] ] == 0 ) { map . erase ( str [ i - K ] ) ; } if ( map . size ( ) == K ) { answer ++ ; } } return answer ; } int main ( ) { string str = " aabcdabbcdc " ; int K = 3 ; cout << countSubstrings ( str , K ) << endl ; return 0 ; } |
Minimum operations to make Array equal by repeatedly adding K from an element and subtracting K from other | C ++ program for the above approach ; Function to find the minimum number of operations to make all the elements of the array equal ; Store the sum of the array arr [ ] ; Traverse through the array ; If it is not possible to make all array element equal ; Store the minimum number of operations needed ; Traverse through the array ; Finally , print the minimum number operation to make array elements equal ; Driver Code ; Given Input ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void miniOperToMakeAllEleEqual ( int arr [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; } if ( sum % n ) { cout << -1 ; return ; } int valueAfterDivision = sum / n ; int count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( abs ( valueAfterDivision - arr [ i ] ) % k != 0 ) { cout << -1 ; return ; } count += abs ( valueAfterDivision - arr [ i ] ) / k ; } cout << count / 2 << endl ; } int main ( ) { int n = 3 , k = 3 ; int arr [ 3 ] = { 5 , 8 , 11 } ; miniOperToMakeAllEleEqual ( arr , n , k ) ; return 0 ; } |
Check if a string is a scrambled form of another string | C ++ Program to check if a given string is a scrambled form of another string ; map declaration for storing key value pair means for storing subproblem result ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Check for the condition of anagram ; make key of type string for search in map ; checking if both string are before calculated or not if calculated means find in map then return it 's value ; declaring flag variable to store result ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ 0. . . i ] and if S2 [ i + 1. . . n ] is a scrambled string of S1 [ i + 1. . . n ] ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ n - i ... n ] and S2 [ i + 1. . . n ] is a scramble string of S1 [ 0. . . n - i - 1 ] ; add key & flag value to map ( store for future use ) so next time no required to calculate it again ; If none of the above conditions are satisfied ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < string , bool > mp ; bool isScramble ( string S1 , string S2 ) { if ( S1 . length ( ) != S2 . length ( ) ) { return false ; } int n = S1 . length ( ) ; if ( n == 0 ) { return true ; } if ( S1 == S2 ) { return true ; } string copy_S1 = S1 , copy_S2 = S2 ; sort ( copy_S1 . begin ( ) , copy_S1 . end ( ) ) ; sort ( copy_S2 . begin ( ) , copy_S2 . end ( ) ) ; if ( copy_S1 != copy_S2 ) { return false ; } string key = ( S1 + " β " + S2 ) ; if ( mp . find ( key ) != mp . end ( ) ) { return mp [ key ] ; } bool flag = false ; for ( int i = 1 ; i < n ; i ++ ) { if ( isScramble ( S1 . substr ( 0 , i ) , S2 . substr ( 0 , i ) ) && isScramble ( S1 . substr ( i , n - i ) , S2 . substr ( i , n - i ) ) ) { flag = true ; return true ; } if ( isScramble ( S1 . substr ( 0 , i ) , S2 . substr ( n - i , i ) ) && isScramble ( S1 . substr ( i , n - i ) , S2 . substr ( 0 , n - i ) ) ) { flag = true ; return true ; } } mp [ key ] = flag ; return false ; } int main ( ) { string S1 = " coder " ; string S2 = " ocred " ; if ( isScramble ( S1 , S2 ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; } |
Print the longest palindromic prefix of a given string | C ++ program for the above approach ; Function to find the longest prefix which is palindromic ; Find the length of the given string ; For storing the length of longest prefix palindrome ; Loop to check the substring of all length from 1 to N which is palindrome ; String of length i ; To store the reversed of temp ; Reversing string temp2 ; If string temp is palindromic then update the length ; Print the palindromic string of max_len ; Driver Code ; Given string ; Function Call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void LongestPalindromicPrefix ( string s ) { int n = s . length ( ) ; int max_len = 0 ; for ( int len = 1 ; len <= n ; len ++ ) { string temp = s . substr ( 0 , len ) ; string temp2 = temp ; reverse ( temp2 . begin ( ) , temp2 . end ( ) ) ; if ( temp == temp2 ) { max_len = len ; } } cout << s . substr ( 0 , max_len ) ; } int main ( ) { string str = " abaab " ; LongestPalindromicPrefix ( str ) ; } |
Minimum operations to make product of adjacent element pair of prefix sum negative | C ++ code for the above approach ; Function to find minimum operations needed to make the product of any two adjacent elements in prefix sum array negative ; Stores the minimum operations ; Stores the prefix sum and number of operations ; Traverse the array ; Update the value of sum ; Check if i + r is odd ; Check if prefix sum is not positive ; Update the value of ans and sum ; Check if prefix sum is not negative ; Update the value of ans and sum ; Update the value of res ; Print the value of res ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void minOperations ( vector < int > a ) { int res = INT_MAX ; int N = a . size ( ) ; for ( int r = 0 ; r < 2 ; r ++ ) { int sum = 0 , ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { sum += a [ i ] ; if ( ( i + r ) % 2 ) { if ( sum <= 0 ) { ans += - sum + 1 ; sum = 1 ; } } else { if ( sum >= 0 ) { ans += sum + 1 ; sum = -1 ; } } } res = min ( res , ans ) ; } cout << res ; } int main ( ) { vector < int > a { 1 , -3 , 1 , 0 } ; minOperations ( a ) ; return 0 ; } |
K | C ++ program to find the K - th lexicographical string of length N ; Initialize the array to store the base 26 representation of K with all zeroes , that is , the initial String consists of N a 's ; Start filling all the N slots for the base 26 representation of K ; Store the remainder ; Reduce K ; If K is greater than the possible number of strings that can be represented by a string of length N ; Store the Kth lexicographical string ; Driver Code ; Reducing k value by 1 because our stored value starts from 0 | #include <bits/stdc++.h> NEW_LINE using namespace std ; string find_kth_String_of_n ( int n , int k ) { int d [ n ] = { 0 } ; for ( int i = n - 1 ; i > -1 ; i -- ) { d [ i ] = k % 26 ; k /= 26 ; } if ( k > 0 ) return " - 1" ; string s = " " ; for ( int i = 0 ; i < n ; i ++ ) s += ( d [ i ] + ( ' a ' ) ) ; return s ; } int main ( ) { int n = 3 ; int k = 10 ; k -= 1 ; cout << find_kth_String_of_n ( n , k ) ; return 0 ; } |
Length of the smallest substring which contains all vowels | C ++ Program to find the length of the smallest substring of which contains all vowels ; Map to store the frequency of vowels ; Store the indices which contains the vowels ; If all vowels are not present in the string ; If the frequency of the vowel at i - th index exceeds 1 ; Decrease the frequency of that vowel ; Move to the left ; Otherwise set flag1 ; If the frequency of the vowel at j - th index exceeds 1 ; Decrease the frequency of that vowel ; Move to the right ; Otherwise set flag2 ; If both flag1 and flag2 are set , break out of the loop as the substring length cannot be minimized ; Return the length of the substring ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinLength ( string s ) { int n = s . size ( ) ; map < char , int > counts ; vector < int > indices ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' o ' s [ i ] == ' i ' s [ i ] == ' u ' ) { counts [ s [ i ] ] ++ ; indices . push_back ( i ) ; } } if ( counts . size ( ) < 5 ) return -1 ; int flag1 = 0 , flag2 = 0 ; int i = 0 ; int j = indices . size ( ) - 1 ; while ( ( j - i ) >= 4 ) { if ( ! flag1 && counts [ s [ indices [ i ] ] ] > 1 ) { counts [ s [ indices [ i ] ] ] -- ; i ++ ; } else flag1 = 1 ; if ( ! flag2 && counts [ s [ indices [ j ] ] ] > 1 ) { counts [ s [ indices [ j ] ] ] -- ; j -- ; } else flag2 = 1 ; if ( flag1 && flag2 ) break ; } return ( indices [ j ] - indices [ i ] + 1 ) ; } int main ( ) { string s = " aaeebbeaccaaoiuooooooooiuu " ; cout << findMinLength ( s ) ; return 0 ; } |
Longest Subsequence of a String containing only Consonants | C ++ program to find the longest subsequence which contain all consonants ; Returns true if x is consonants . ; Function to check whether a character is consonants or not ; Function to find the longest subsequence which contain all consonants ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isConsonants ( char x ) { x = tolower ( x ) ; return ! ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } string longestConsonantsSubsequence ( string str ) { string answer = " " ; int n = str . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( isConsonants ( str [ i ] ) ) { answer += str [ i ] ; } } return answer ; } int main ( ) { string str = " geeksforgeeks " ; cout << longestConsonantsSubsequence ( str ) << endl ; return 0 ; } |
Find the length of the longest subsequence with first K alphabets having same frequency | C ++ program to find the longest subsequence with first K alphabets having same frequency ; Function to return the length of the longest subsequence with first K alphabets having same frequency ; Map to store frequency of all characters in the string ; Variable to store the frequency of the least frequent of first K alphabets ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int lengthOfSubsequence ( string str , int K ) { map < char , int > mp ; for ( char ch : str ) { mp [ ch ] ++ ; } int minimum = mp [ ' A ' ] ; for ( int i = 1 ; i < K ; i ++ ) { minimum = min ( minimum , mp [ ( char ) ( i + ' A ' ) ] ) ; } return minimum * K ; } int main ( ) { string str = " ACAABCCAB " ; int K = 3 ; cout << lengthOfSubsequence ( str , K ) ; return 0 ; } |
Detecting negative cycle using Floyd Warshall | C ++ Program to check if there is a negative weight cycle using Floyd Warshall Algorithm ; Number of vertices in the graph ; ; Define Infinite as a large enough value . This value will be used for vertices not connected to each other ; Returns true if graph has negative weight cycle else false . ; dist [ ] [ ] will be the output matrix that will finally have the shortest distances between every pair of vertices ; Initialize the solution matrix same as input graph matrix . Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex . ; Add all vertices one by one to the set of intermediate vertices . -- -> Before start of a iteration , we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set { 0 , 1 , 2 , . . k - 1 } as intermediate vertices . -- -- > After the end of a iteration , vertex no . k is added to the set of intermediate vertices and the set becomes { 0 , 1 , 2 , . . k } ; Pick all vertices as source one by one ; Pick all vertices as destination for the above picked source ; If vertex k is on the shortest path from i to j , then update the value of dist [ i ] [ j ] ; If distance of any verex from itself becomes negative , then there is a negative weight cycle . ; driver program ; Let us create the following weighted graph 1 ( 0 ) -- -- -- -- -- -> ( 1 ) / | \ | | | - 1 | | - 1 | \ | / ( 3 ) < -- -- -- -- -- - ( 2 ) - 1 | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define V 4 NEW_LINE void printSolution ( int dist [ ] [ V ] ) ; #define INF 99999 NEW_LINE bool negCyclefloydWarshall ( int graph [ ] [ V ] ) { int dist [ V ] [ V ] , i , j , k ; for ( i = 0 ; i < V ; i ++ ) for ( j = 0 ; j < V ; j ++ ) dist [ i ] [ j ] = graph [ i ] [ j ] ; for ( k = 0 ; k < V ; k ++ ) { for ( i = 0 ; i < V ; i ++ ) { for ( j = 0 ; j < V ; j ++ ) { if ( dist [ i ] [ k ] + dist [ k ] [ j ] < dist [ i ] [ j ] ) dist [ i ] [ j ] = dist [ i ] [ k ] + dist [ k ] [ j ] ; } } } for ( int i = 0 ; i < V ; i ++ ) if ( dist [ i ] [ i ] < 0 ) return true ; return false ; } int main ( ) { int graph [ V ] [ V ] = { { 0 , 1 , INF , INF } , { INF , 0 , -1 , INF } , { INF , INF , 0 , -1 } , { -1 , INF , INF , 0 } } ; if ( negCyclefloydWarshall ( graph ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Digital Root of a given large integer using Recursion | C ++ program to print the digital root of a given very large number ; Function to convert given sum into string ; Loop to extract digit one by one from the given sum and concatenate into the string ; Type casting for concatenation ; Return converted string ; Function to get individual digit sum from string ; Loop to get individual digit sum ; Function call to convert sum into string ; Function to calculate the digital root of a very large number ; Base condition ; Function call to get individual digit sum ; Recursive function to get digital root of a very large number ; Driver code ; Function to print final digit | #include <iostream> NEW_LINE using namespace std ; string convertToString ( int sum ) { string str = " " ; while ( sum ) { str = str + ( char ) ( ( sum % 10 ) + '0' ) ; sum = sum / 10 ; } return str ; } string GetIndividulaDigitSum ( string str , int len ) { int sum = 0 ; for ( int i = 0 ; i < len ; i ++ ) { sum = sum + str [ i ] - '0' ; } return convertToString ( sum ) ; } int GetDigitalRoot ( string str ) { if ( str . length ( ) == 1 ) { return str [ 0 ] - '0' ; } str = GetIndividulaDigitSum ( str , str . length ( ) ) ; return GetDigitalRoot ( str ) ; } int main ( ) { string str = "675987890789756545689070986776987" ; cout << GetDigitalRoot ( str ) ; } |
Count the Number of matching characters in a pair of strings | C ++ code to count number of matching characters in a pair of strings ; Function to count the matching characters ; Traverse the string 1 char by char ; This will check if str1 [ i ] is present in str2 or not str2 . find ( str1 [ i ] ) returns - 1 if not found otherwise it returns the starting occurrence index of that character in str2 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void count ( string str1 , string str2 ) { int c = 0 , j = 0 ; for ( int i = 0 ; i < str1 . length ( ) ; i ++ ) { if ( str2 . find ( str1 [ i ] ) >= 0 and j == str1 . find ( str1 [ i ] ) ) c += 1 ; j += 1 ; } cout << " No . β of β matching β characters β are : β " << c / 2 ; } int main ( ) { string str1 = " aabcddekll12 @ " ; string str2 = " bb2211@55k " ; count ( str1 , str2 ) ; } |
Check if count of Alphabets and count of Numbers are equal in the given String | C ++ program to check if the count of alphabets and numbers in a string are equal or not . ; Function to count the number of alphabets ; Counter to store the number of alphabets in the string ; Every character in the string is iterated ; To check if the character is an alphabet or not ; Function to count the number of numbers ; Counter to store the number of alphabets in the string ; Every character in the string is iterated ; To check if the character is a digit or not ; Function to check if the count of alphabets is equal to the count of numbers or not ; Driver code | #include <iostream> NEW_LINE using namespace std ; int countOfLetters ( string str ) { int letter = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) || ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) ) letter ++ ; } return letter ; } int countOfNumbers ( string str ) { int number = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] >= '0' && str [ i ] <= '9' ) number ++ ; } return number ; } void check ( string str ) { if ( countOfLetters ( str ) == countOfNumbers ( str ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; } int main ( ) { string str = " GeeKs01324" ; check ( str ) ; return 0 ; } |
Minimum cost to traverse from one index to another in the String | C ++ implementation of the above approach . ; function to find the minimum cost ; graph ; adjacency matrix ; initialising adjacency matrix ; creating adjacency list ; pushing left adjacent elelemt for index ' k ' ; pushing right adjacent element for index ' k ' ; queue to perform BFS ; visited array ; variable to store depth of BFS ; BFS ; number of elements in the current level ; inner loop ; current element ; popping queue ; base case ; checking if the current node is required node ; iterating through the current node ; updating depth ; Driver Code ; input variables ; function to find the minimum cost | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinCost ( string s , int i , int j ) { vector < vector < int > > gr ( 26 ) ; bool edge [ 26 ] [ 26 ] ; for ( int k = 0 ; k < 26 ; k ++ ) for ( int l = 0 ; l < 26 ; l ++ ) edge [ k ] [ l ] = 0 ; for ( int k = 0 ; k < s . size ( ) ; k ++ ) { if ( k - 1 >= 0 and ! edge [ s [ k ] - 97 ] [ s [ k - 1 ] - 97 ] ) gr [ s [ k ] - 97 ] . push_back ( s [ k - 1 ] - 97 ) , edge [ s [ k ] - 97 ] [ s [ k - 1 ] - 97 ] = 1 ; if ( k + 1 <= s . size ( ) - 1 and ! edge [ s [ k ] - 97 ] [ s [ k + 1 ] - 97 ] ) gr [ s [ k ] - 97 ] . push_back ( s [ k + 1 ] - 97 ) , edge [ s [ k ] - 97 ] [ s [ k + 1 ] - 97 ] = 1 ; } queue < int > q ; q . push ( s [ i ] - 97 ) ; bool v [ 26 ] = { 0 } ; int d = 0 ; while ( q . size ( ) ) { int cnt = q . size ( ) ; while ( cnt -- ) { int curr = q . front ( ) ; q . pop ( ) ; if ( v [ curr ] ) continue ; v [ curr ] = 1 ; if ( curr == s [ j ] - 97 ) return d ; for ( auto it : gr [ curr ] ) q . push ( it ) ; } d ++ ; } return -1 ; } int main ( ) { string s = " abcde " ; int i = 0 ; int j = 4 ; cout << findMinCost ( s , i , j ) ; } |
Check if there is a cycle with odd weight sum in an undirected graph | C ++ program to check if there is a cycle of total odd weight ; This function returns true if the current subpart of the forest is two colorable , else false . ; Assign first color to source ; Create a queue ( FIFO ) of vertex numbers and enqueue source vertex for BFS traversal ; Run while there are vertices in queue ( Similar to BFS ) ; Find all non - colored adjacent vertices ; An edge from u to v exists and destination v is not colored ; Assign alternate color to this adjacent v of u ; An edge from u to v exists and destination v is colored with same color as u ; This function returns true if graph G [ V ] [ V ] is two colorable , else false ; Create a color array to store colors assigned to all veritces . Vertex number is used as index in this array . The value ' - 1' of colorArr [ i ] is used to indicate that no color is assigned to vertex ' i ' . The value 1 is used to indicate first color is assigned and value 0 indicates second color is assigned . ; As we are dealing with graph , the input might come as a forest , thus start coloring from a node and if true is returned we 'll know that we successfully colored the subpart of our forest and we start coloring again from a new uncolored node. This way we cover the entire forest. ; Returns false if an odd cycle is present else true int info [ ] [ ] is the information about our graph int n is the number of nodes int m is the number of informations given to us ; Declaring adjacency list of a graph Here at max , we can encounter all the edges with even weight thus there will be 1 pseudo node for each edge ; For odd weight edges , we directly add it in our graph ; For even weight edges , we break it ; Entering a pseudo node between u -- - v ; Keeping a record of number of pseudo nodes inserted ; Making a new pseudo node for next time ; We pass number graph G [ ] [ ] and total number of node = actual number of nodes + number of pseudo nodes added . ; Driver function ; ' n ' correspond to number of nodes in our graph while ' m ' correspond to the number of information about this graph . ; This function break the even weighted edges in two parts . Makes the adjacency representation of the graph and sends it for two coloring . | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool twoColorUtil ( vector < int > G [ ] , int src , int N , int colorArr [ ] ) { colorArr [ src ] = 1 ; queue < int > q ; q . push ( src ) ; while ( ! q . empty ( ) ) { int u = q . front ( ) ; q . pop ( ) ; for ( int v = 0 ; v < G [ u ] . size ( ) ; ++ v ) { if ( colorArr [ G [ u ] [ v ] ] == -1 ) { colorArr [ G [ u ] [ v ] ] = 1 - colorArr [ u ] ; q . push ( G [ u ] [ v ] ) ; } else if ( colorArr [ G [ u ] [ v ] ] == colorArr [ u ] ) return false ; } } return true ; } bool twoColor ( vector < int > G [ ] , int N ) { int colorArr [ N ] ; for ( int i = 1 ; i <= N ; ++ i ) colorArr [ i ] = -1 ; for ( int i = 1 ; i <= N ; i ++ ) if ( colorArr [ i ] == -1 ) if ( twoColorUtil ( G , i , N , colorArr ) == false ) return false ; return true ; } bool isOddSum ( int info [ ] [ 3 ] , int n , int m ) { vector < int > G [ 2 * n ] ; int pseudo = n + 1 ; int pseudo_count = 0 ; for ( int i = 0 ; i < m ; i ++ ) { if ( info [ i ] [ 2 ] % 2 == 1 ) { int u = info [ i ] [ 0 ] ; int v = info [ i ] [ 1 ] ; G [ u ] . push_back ( v ) ; G [ v ] . push_back ( u ) ; } else { int u = info [ i ] [ 0 ] ; int v = info [ i ] [ 1 ] ; G [ u ] . push_back ( pseudo ) ; G [ pseudo ] . push_back ( u ) ; G [ v ] . push_back ( pseudo ) ; G [ pseudo ] . push_back ( v ) ; pseudo_count ++ ; pseudo ++ ; } } return twoColor ( G , n + pseudo_count ) ; } int main ( ) { int n = 4 , m = 3 ; int info [ 4 ] [ 3 ] = { { 1 , 2 , 12 } , { 2 , 3 , 1 } , { 4 , 3 , 1 } , { 4 , 1 , 20 } } ; if ( isOddSum ( info , n , m ) == true ) cout << " No STRNEWLINE " ; else cout << " Yes STRNEWLINE " ; return 0 ; } |
Index of character depending on frequency count in string | C ++ implementation of the approach ; Function to perform the queries ; L [ i ] [ j ] stores the largest i such that ith character appears exactly jth times in str [ 0. . . i ] ; F [ i ] [ j ] stores the smallest i such that ith character appears exactly jth times in str [ 0. . . i ] ; To store the frequency of each of the character of str ; Current character of str ; Update its frequency ; For every lowercase character of the English alphabet ; If it is equal to the character under consideration then update L [ ] [ ] and R [ ] [ ] as it is cnt [ j ] th occurrence of character k ; Only update L [ ] [ ] as k has not been occurred so only index has to be incremented ; Perform the queries ; Type 1 query ; Type 2 query ; Driver code ; Queries ; Perform the queries | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; void performQueries ( string str , int q , int type [ ] , char ch [ ] , int freq [ ] ) { int n = str . length ( ) ; int L [ MAX ] [ n ] ; int F [ MAX ] [ n ] ; int cnt [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int k = str [ i ] - ' a ' ; cnt [ k ] ++ ; for ( int j = 0 ; j < MAX ; j ++ ) { if ( k == j ) { L [ j ] [ cnt [ j ] ] = i ; F [ j ] [ cnt [ j ] ] = i ; } else L [ j ] [ cnt [ j ] ] = L [ j ] [ cnt [ j ] ] + 1 ; } } for ( int i = 0 ; i < q ; i ++ ) { if ( type [ i ] == 1 ) { cout << L [ ch [ i ] - ' a ' ] [ freq [ i ] ] ; } else { cout << F [ ch [ i ] - ' a ' ] [ freq [ i ] ] ; } cout << " STRNEWLINE " ; } } int main ( ) { string str = " geeksforgeeks " ; int type [ ] = { 1 , 2 } ; char ch [ ] = { ' e ' , ' k ' } ; int freq [ ] = { 2 , 2 } ; int q = sizeof ( type ) / sizeof ( int ) ; performQueries ( str , q , type , ch , freq ) ; return 0 ; } |
Number of index pairs such that s [ i ] and s [ j ] are anagrams | CPP program to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; Function to find number of pairs of integers i , j such that s [ i ] is an anagram of s [ j ] . ; To store count of strings ; Traverse all strings and store in the map ; Sort the string ; Store in the map ; To store the number of pairs ; Traverse through the map ; Count the pairs for each string ; Return the required answer ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; int anagram_pairs ( vector < string > s , int n ) { map < string , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { sort ( s [ i ] . begin ( ) , s [ i ] . end ( ) ) ; mp [ s [ i ] ] ++ ; } int ans = 0 ; for ( auto i = mp . begin ( ) ; i != mp . end ( ) ; i ++ ) { int k = i -> second ; ans += ( k * ( k - 1 ) ) / 2 ; } return ans ; } int main ( ) { vector < string > s = { " aaab " , " aaba " , " baaa " , " cde " , " dec " } ; int n = s . size ( ) ; cout << anagram_pairs ( s , n ) ; return 0 ; } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.