text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Maximize count of 3 | C ++ program to implement the above approach ; Function to count the maximum number oaf palindrome subsequences of length 3 considering the same index only once ; Index of the string S ; Stores the frequency of every character ; Stores the pair of frequency containing same characters ; Number of subsequences having length 3 ; Counts the frequency ; Counts the pair of frequency ; Returns the minimum value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxNumPalindrome ( string S ) { int i = 0 ; int freq [ 26 ] = { 0 } ; int freqPair = 0 ; int len = S . length ( ) / 3 ; while ( i < S . length ( ) ) { freq [ S [ i ] - ' a ' ] ++ ; i ++ ; } for ( i = 0 ; i < 26 ; i ++ ) { freqPair += ( freq [ i ] / 2 ) ; } return min ( freqPair , len ) ; } int main ( ) { string S = " geeksforg " ; cout << maxNumPalindrome ( S ) << endl ; return 0 ; }
Minimum Bipartite Groups | Function to find the height sizeof the current component with vertex s ; Visit the current Node ; Call DFS recursively to find the maximum height of current CC ; If the node is not visited then the height recursively for next element ; Function to find the minimum Groups ; Initialise with visited array ; To find the minimum groups ; Traverse all the non visited Node and calculate the height of the tree with current node as a head ; If the current is not visited therefore , we get another CC ; Return the minimum bipartite matching ; Function that adds the current edges in the given graph ; Drivers Code ; Adjacency List ; Adding edges to List
#include <bits/stdc++.h> NEW_LINE using namespace std ; int height ( int s , vector < int > adj [ ] , int * visited ) { visited [ s ] = 1 ; int h = 0 ; for ( auto & child : adj [ s ] ) { if ( visited [ child ] == 0 ) { h = max ( h , 1 + height ( child , adj , visited ) ) ; } } return h ; } int minimumGroups ( vector < int > adj [ ] , int N ) { int visited [ N + 1 ] = { 0 } ; int groups = INT_MIN ; for ( int i = 1 ; i <= N ; i ++ ) { if ( visited [ i ] == 0 ) { int comHeight ; comHeight = height ( i , adj , visited ) ; groups = max ( groups , comHeight ) ; } } return groups ; } void addEdge ( vector < int > adj [ ] , int u , int v ) { adj [ u ] . push_back ( v ) ; adj [ v ] . push_back ( u ) ; } int main ( ) { int N = 5 ; vector < int > adj [ N + 1 ] ; addEdge ( adj , 1 , 2 ) ; addEdge ( adj , 3 , 2 ) ; addEdge ( adj , 4 , 3 ) ; cout << minimumGroups ( adj , N ) ; }
Sum of subsets of all the subsets of an array | O ( 2 ^ N ) | C ++ implementation of the approach ; Function to sum of all subsets of a given array ; Function to generate the subsets ; Base - case ; Finding the sum of all the subsets of the generated subset ; Recursively accepting and rejecting the current number ; Driver code ; To store the final ans
#include <bits/stdc++.h> NEW_LINE using namespace std ; void subsetSum ( vector < int > & c , int & ans ) { int L = c . size ( ) ; int mul = ( int ) pow ( 2 , L - 1 ) ; for ( int i = 0 ; i < c . size ( ) ; i ++ ) ans += c [ i ] * mul ; } void subsetGen ( int * arr , int i , int n , int & ans , vector < int > & c ) { if ( i == n ) { subsetSum ( c , ans ) ; return ; } subsetGen ( arr , i + 1 , n , ans , c ) ; c . push_back ( arr [ i ] ) ; subsetGen ( arr , i + 1 , n , ans , c ) ; c . pop_back ( ) ; } int main ( ) { int arr [ ] = { 1 , 1 } ; int n = sizeof ( arr ) / sizeof ( int ) ; int ans = 0 ; vector < int > c ; subsetGen ( arr , 0 , n , ans , c ) ; cout << ans ; return 0 ; }
Find the maximum possible value of a [ i ] % a [ j ] over all pairs of i and j | C ++ implementation of the approach ; Function that returns the second largest element in the array if exists , else 0 ; There must be at least two elements ; To store the maximum and the second maximum element from the array ; If current element is greater than first then update both first and second ; If arr [ i ] is in between first and second then update second ; No second maximum found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMaxValue ( int arr [ ] , int arr_size ) { int i , first , second ; if ( arr_size < 2 ) { return 0 ; } first = second = INT_MIN ; for ( i = 0 ; i < arr_size ; i ++ ) { if ( arr [ i ] > first ) { second = first ; first = arr [ i ] ; } else if ( arr [ i ] > second && arr [ i ] != first ) second = arr [ i ] ; } if ( second == INT_MIN ) return 0 ; else return second ; } int main ( ) { int arr [ ] = { 4 , 5 , 1 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << getMaxValue ( arr , n ) ; return 0 ; }
Maximize the value of the given expression | C ++ implementation of the approach ; Function to return the maximum result ; To store the count of negative integers ; Sum of all the three integers ; Product of all the three integers ; To store the smallest and the largest among all the three integers ; Calculate the count of negative integers ; Depending upon count of negatives ; When all three are positive integers ; For single negative integer ; For two negative integers ; For three negative integers ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumResult ( int a , int b , int c ) { int countOfNegative = 0 ; int sum = a + b + c ; int product = a * b * c ; int largest = max ( a , max ( b , c ) ) ; int smallest = min ( a , min ( b , c ) ) ; if ( a < 0 ) countOfNegative ++ ; if ( b < 0 ) countOfNegative ++ ; if ( c < 0 ) countOfNegative ++ ; switch ( countOfNegative ) { case 0 : return ( sum - largest ) * largest ; case 1 : return ( product / smallest ) + smallest ; case 2 : return ( product / largest ) + largest ; case 3 : return ( sum - smallest ) * smallest ; } } int main ( ) { int a = -2 , b = -1 , c = -4 ; cout << maximumResult ( a , b , c ) ; return 0 ; }
Maximum students to pass after giving bonus to everybody and not exceeding 100 marks | C ++ Implementation of above approach . ; Function to return the number of students that can pass ; maximum marks ; maximum bonus marks that can be given ; counting the number of students that can pass ; Driver code
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; int check ( int n , int marks [ ] ) { int * x = std :: max_element ( marks , marks + 5 ) ; int bonus = 100 - ( int ) ( * x ) ; int c = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( marks [ i ] + bonus >= 50 ) c += 1 ; } return c ; } int main ( ) { int n = 5 ; int marks [ ] = { 0 , 21 , 83 , 45 , 64 } ; cout << check ( n , marks ) << endl ; return 0 ; }
Sum of first N natural numbers which are not powers of K | C ++ program to find the sum of first n natural numbers which are not positive powers of k ; Function to return the sum of first n natural numbers which are not positive powers of k ; sum of first n natural numbers ; subtract all positive powers of k which are less than n ; next power of k ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_sum ( int n , int k ) { int total_sum = ( n * ( n + 1 ) ) / 2 ; int power = k ; while ( power <= n ) { total_sum -= power ; power *= k ; } return total_sum ; } int main ( ) { int n = 11 , k = 2 ; cout << find_sum ( n , k ) ; return 0 ; }
Minimum number of operations required to delete all elements of the array | C ++ implementation of the above approach ; function to find minimum operations ; sort array ; prepare hash of array ; Driver program
#include <bits/stdc++.h> NEW_LINE #define MAX 10000 NEW_LINE using namespace std ; int hashTable [ MAX ] ; int minOperations ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; for ( int i = 0 ; i < n ; i ++ ) hashTable [ arr [ i ] ] ++ ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( hashTable [ arr [ i ] ] ) { for ( int j = i ; j < n ; j ++ ) if ( arr [ j ] % arr [ i ] == 0 ) hashTable [ arr [ j ] ] = 0 ; res ++ ; } } return res ; } int main ( ) { int arr [ ] = { 4 , 6 , 2 , 8 , 7 , 21 , 24 , 49 , 44 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , n ) ; return 0 ; }
Sorting array with reverse around middle | CPP program to find possibility to sort by multiple subarray reverse operarion ; making the copy of the original array ; sorting the copied array ; checking mirror image of elements of sorted copy array and equivalent element of original array ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool ifPossible ( int arr [ ] , int n ) { int cp [ n ] ; copy ( arr , arr + n , cp ) ; sort ( cp , cp + n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! ( arr [ i ] == cp [ i ] ) && ! ( arr [ n - 1 - i ] == cp [ i ] ) ) return false ; } return true ; } int main ( ) { int arr [ ] = { 1 , 7 , 6 , 4 , 5 , 3 , 2 , 8 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( ifPossible ( arr , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Program for Shortest Job First ( SJF ) scheduling | Set 2 ( Preemptive ) | C ++ program to implement Shortest Remaining Time First Shortest Remaining Time First ( SRTF ) ; int pid ; Process ID int bt ; Burst Time int art ; Arrival Time ; Function to find the waiting time for all processes ; Copy the burst time into rt [ ] ; Process until all processes gets completed ; Find process with minimum remaining time among the processes that arrives till the current time ` ; Reduce remaining time by one ; Update minimum ; If a process gets completely executed ; Increment complete ; Find finish time of current process ; Calculate waiting time ; Increment time ; Function to calculate turn around time ; calculating turnaround time by adding bt [ i ] + wt [ i ] ; Function to calculate average time ; Function to find waiting time of all processes ; Function to find turn around time for all processes ; Display processes along with all details ; Calculate total waiting time and total turnaround time ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Process { } ; void findWaitingTime ( Process proc [ ] , int n , int wt [ ] ) { int rt [ n ] ; for ( int i = 0 ; i < n ; i ++ ) rt [ i ] = proc [ i ] . bt ; int complete = 0 , t = 0 , minm = INT_MAX ; int shortest = 0 , finish_time ; bool check = false ; while ( complete != n ) { for ( int j = 0 ; j < n ; j ++ ) { if ( ( proc [ j ] . art <= t ) && ( rt [ j ] < minm ) && rt [ j ] > 0 ) { minm = rt [ j ] ; shortest = j ; check = true ; } } if ( check == false ) { t ++ ; continue ; } rt [ shortest ] -- ; minm = rt [ shortest ] ; if ( minm == 0 ) minm = INT_MAX ; if ( rt [ shortest ] == 0 ) { complete ++ ; check = false ; finish_time = t + 1 ; wt [ shortest ] = finish_time - proc [ shortest ] . bt - proc [ shortest ] . art ; if ( wt [ shortest ] < 0 ) wt [ shortest ] = 0 ; } t ++ ; } } void findTurnAroundTime ( Process proc [ ] , int n , int wt [ ] , int tat [ ] ) { for ( int i = 0 ; i < n ; i ++ ) tat [ i ] = proc [ i ] . bt + wt [ i ] ; } void findavgTime ( Process proc [ ] , int n ) { int wt [ n ] , tat [ n ] , total_wt = 0 , total_tat = 0 ; findWaitingTime ( proc , n , wt ) ; findTurnAroundTime ( proc , n , wt , tat ) ; cout << " Processes ▁ " << " ▁ Burst ▁ time ▁ " << " ▁ Waiting ▁ time ▁ " << " ▁ Turn ▁ around ▁ time STRNEWLINE " ; for ( int i = 0 ; i < n ; i ++ ) { total_wt = total_wt + wt [ i ] ; total_tat = total_tat + tat [ i ] ; cout << " ▁ " << proc [ i ] . pid << " TABSYMBOL TABSYMBOL " << proc [ i ] . bt << " TABSYMBOL TABSYMBOL ▁ " << wt [ i ] << " TABSYMBOL TABSYMBOL ▁ " << tat [ i ] << endl ; } cout << " Average waiting time = " << ( float ) total_wt / ( float ) n ; cout << " Average turn around time = " << ( float ) total_tat / ( float ) n ; } int main ( ) { Process proc [ ] = { { 1 , 6 , 1 } , { 2 , 8 , 1 } , { 3 , 7 , 2 } , { 4 , 3 , 3 } } ; int n = sizeof ( proc ) / sizeof ( proc [ 0 ] ) ; findavgTime ( proc , n ) ; return 0 ; }
Minimum deletions in Array to make difference of adjacent elements non | the maximum value of A [ i ] ; Function for finding minimum deletions so that the array becomes non - decreasing and the difference between adjacent elements is also non - decreasing ; initializing the dp table and setting all values to 0 ; Find the maximum size valid set that can be taken and then subtract its size from N to get minimum number of deletions ; when selecting only current element and deleting all elements from 0 to i - 1 inclusive ; if this is true moving from index j to i is possible ; iterate over all elements from 0 to diff and find the max ; take the max set size from dp [ N - 1 ] [ 0 ] to dp [ N - 1 ] [ MAX ] ; Driver code ; Input ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100001 NEW_LINE int minimumDeletions ( int A [ ] , int N ) { int dp [ N ] [ MAX ] ; for ( int i = 0 ; i < N ; i ++ ) for ( int j = 0 ; j < MAX ; j ++ ) dp [ i ] [ j ] = 0 ; for ( int i = 0 ; i < N ; i ++ ) { dp [ i ] [ 0 ] = 1 ; for ( int j = i - 1 ; j >= 0 ; j -- ) { if ( A [ i ] >= A [ j ] ) { int diff = A [ i ] - A [ j ] ; for ( int k = 0 ; k <= diff ; k ++ ) { dp [ i ] = max ( dp [ i ] , dp [ j ] [ k ] + 1 ) ; } } } } int maxSetSize = -1 ; for ( int i = 0 ; i < MAX ; i ++ ) maxSetSize = max ( maxSetSize , dp [ N - 1 ] [ i ] ) ; return N - maxSetSize ; } int main ( ) { int A [ ] = { 1 , 4 , 5 , 7 , 20 , 21 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << minimumDeletions ( A , N ) << endl ; return 0 ; }
Count N | Function to count N - length strings consisting of vowels only sorted lexicographically ; Initializing vector to store count of strings . ; Summing up the total number of combinations . ; Return the result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNumberOfStrings ( int N ) { vector < int > counts ( 5 , 1 ) ; for ( int i = 2 ; i <= N ; i ++ ) { for ( int j = 3 ; j >= 0 ; j -- ) counts [ j ] += counts [ j + 1 ] ; } int ans = 0 ; for ( auto c : counts ) ans += c ; return ans ; } int main ( ) { int N = 2 ; cout << findNumberOfStrings ( N ) ; return 0 ; }
Count N | C ++ program for the above approach ; Stores the value of overlapping states ; Function to check whether a number have only digits X or Y or not ; Until sum is positive ; If any digit is not X or Y then return 0 ; Return 1 ; Function to find the count of numbers that are formed by digits X and Y and whose sum of digit also have digit X or Y ; Initialize dp array ; Base Case ; Check if sum of digits formed by only X or Y ; Return the already computed ; Place the digit X at the current position ; Place the digit Y at the current position ; Update current state result ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dp [ 1000 + 5 ] [ 9000 + 5 ] ; int mod = 1000000007 ; int check ( int sum , int x , int y ) { while ( sum > 0 ) { int ln = sum % 10 ; if ( ln != x && ln != y ) { return 0 ; } sum /= 10 ; } return 1 ; } int countNumbers ( int n , int x , int y , int sum ) { memset ( dp , -1 , sizeof ( dp ) ) ; if ( n == 0 ) { return check ( sum , x , y ) ; } if ( dp [ n ] [ sum ] != -1 ) { return dp [ n ] [ sum ] % mod ; } int option1 = countNumbers ( n - 1 , x , y , sum + x ) % mod ; int option2 = countNumbers ( n - 1 , x , y , sum + y ) % mod ; return dp [ n ] [ sum ] = ( option1 + option2 ) % mod ; } int main ( ) { int N = 3 , X = 1 , Y = 5 ; cout << countNumbers ( N , X , Y , 0 ) % mod ; }
Minimum cost to generate any permutation of the given string | C ++ program for the above approach ; Function that returns true if the current bit is set ; Function to find the minimum cost to form any permutation of string s ; Base Case ; Return the precomputed state ; Iterate over the string and check all possible characters available for current position ; Check if character can be placed at current position ; As there is no previous character so the cost for 1 st character is 0 ; Find the cost of current character and move to next position ; Store the answer for each current state ; Function that generates any permutation of the given string with minimum cost ; Initialize dp table ; Set all the bits of the current character id ; Minimum cost of generating the permutation ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int mask , int i ) { int c = ( mask & ( 1 << i ) ) ; return c != 0 ; } int solve ( vector < vector < int > > a , string s , int n , int prev , int mask , vector < vector < int > > dp ) { if ( mask == 0 ) return 0 ; if ( dp [ mask ] [ prev + 1 ] != -1 ) return dp [ mask ] [ prev + 1 ] ; int ans = 10000 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int id = s [ i ] - ' a ' ; if ( check ( mask , id ) ) { if ( prev == -1 ) { ans = min ( ans , solve ( a , s , n , id , mask ^ ( 1 << id ) , dp ) ) ; } else { ans = min ( ans , a [ prev ] [ id ] + solve ( a , s , n , id , mask ^ ( 1 << id ) , dp ) ) ; } } } dp [ mask ] [ prev + 1 ] = ans ; return ans ; } void generatePermutation ( int mask , int n , vector < vector < int > > a , string s ) { vector < vector < int > > dp ( ( 1 << n ) + 5 , vector < int > ( n + 5 , -1 ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int id = s [ i ] - ' a ' ; mask |= ( 1 << id ) ; } cout << solve ( a , s , n , -1 , mask , dp ) << endl ; } int main ( ) { int N = 5 ; string str = " abcde " ; vector < vector < int > > mat = { { 0 , 5 , 1 , 5 , 3 } , { 4 , 0 , 9 , 4 , 2 } , { 7 , 9 , 0 , 10 , 7 } , { 1 , 2 , 8 , 0 , 2 } , { 3 , 9 , 7 , 7 , 0 } } ; generatePermutation ( 0 , N , mat , str ) ; return 0 ; }
Minimize Cost to reduce the Array to a single element by given operations | C ++ program for the above approach ; Function to generate the cost using Prefix Sum Array technique ; Function to combine the sum of the two subproblems ; Function to minimize the cost to add the array elements to a single element ; Check if the value is already stored in the array ; Compute left subproblem ; Compute left subproblem ; Calculate minimum cost ; Store the answer to avoid recalculation ; Driver code ; Initialise dp array ; Preprocessing the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; int inf = 10000000 ; vector < int > preprocess ( vector < int > a , int n ) { vector < int > p ( n ) ; p [ 0 ] = a [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { p [ i ] = p [ i - 1 ] + a [ i ] ; } return p ; } int Combine ( vector < int > p , int i , int j ) { if ( i == 0 ) return p [ j ] ; else return p [ j ] - p [ i - 1 ] ; } int minCost ( vector < int > a , int i , int j , int k , vector < int > prefix , vector < vector < int > > dp ) { if ( i >= j ) return 0 ; if ( dp [ i ] [ j ] != -1 ) return dp [ i ] [ j ] ; int best_cost = inf ; for ( int pos = i ; pos < j ; pos ++ ) { int left = minCost ( a , i , pos , k , prefix , dp ) ; int right = minCost ( a , pos + 1 , j , k , prefix , dp ) ; best_cost = min ( best_cost , left + right + ( k * Combine ( prefix , i , j ) ) ) ; } return dp [ i ] [ j ] = best_cost ; } int main ( ) { int n = 4 ; vector < int > a = { 4 , 5 , 6 , 7 } ; int k = 3 ; vector < vector < int > > dp ; dp . resize ( n + 1 , vector < int > ( n + 1 ) ) ; for ( int i = 0 ; i < n + 1 ; i ++ ) { for ( int j = 0 ; j < n + 1 ; j ++ ) { dp [ i ] [ j ] = -1 ; } } vector < int > prefix = preprocess ( a , n ) ; cout << minCost ( a , 0 , n - 1 , k , prefix , dp ) << endl ; return 0 ; }
Minimize operations required to obtain N | Function to find the minimum number of operations ; Storing the minimum operations to obtain all numbers up to N ; Initilal state ; Iterate for the remaining numbers ; If the number can be obtained by multiplication by 2 ; If the number can be obtained by multiplication by 3 ; Obtaining the number by adding 1 ; Return the minm operations to obtain n ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int n ) { int dp [ n + 1 ] ; dp [ 1 ] = 0 ; for ( int i = 2 ; i <= n ; i ++ ) { dp [ i ] = INT_MAX ; if ( i % 2 == 0 ) { int x = dp [ i / 2 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } if ( i % 3 == 0 ) { int x = dp [ i / 3 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } int x = dp [ i - 1 ] ; if ( x + 1 < dp [ i ] ) { dp [ i ] = x + 1 ; } } return dp [ n ] ; } int main ( ) { int n = 15 ; cout << minOperations ( n ) ; return 0 ; }
Longest Reverse Bitonic Sequence | C ++ program to find the longest Reverse bitonic Subsequence ; Function to return the length of the Longest Reverse Bitonic Subsequence in the array ; Allocate memory for LIS [ ] and initialize LIS values as 1 for all indexes ; Compute LIS values from left to right for every index ; Initialize LDS for all indexes as 1 ; Compute LDS values for every index from right to left ; Find the maximum value of lis [ i ] + lds [ i ] - 1 in the array ; Return the maximum ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int ReverseBitonic ( int arr [ ] , int N ) { int i , j ; int lds [ N ] ; for ( i = 0 ; i < N ; i ++ ) { lds [ i ] = 1 ; } for ( i = 1 ; i < N ; i ++ ) { for ( j = 0 ; j < i ; j ++ ) { if ( arr [ i ] < arr [ j ] && lds [ i ] < lds [ j ] + 1 ) { lds [ i ] = lds [ j ] + 1 ; } } } int lis [ N ] ; for ( i = 0 ; i < N ; i ++ ) { lis [ i ] = 1 ; } for ( i = N - 2 ; i >= 0 ; i -- ) { for ( j = N - 1 ; j > i ; j -- ) { if ( arr [ i ] < arr [ j ] && lis [ i ] < lis [ j ] + 1 ) { lis [ i ] = lis [ 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 " , ReverseBitonic ( arr , N ) ) ; return 0 ; }
Maze With N doors and 1 Key | C ++ implementation of the approach ; Recursive function to check whether there is a path from the top left cell to the bottom right cell of the maze ; Check whether the current cell is within the maze ; If key is required to move further ; If the key hasn 't been used before ; If current cell is the destination ; Either go down or right ; Key has been used before ; If current cell is the destination ; Either go down or right ; Driver code ; If there is a path from the cell ( 0 , 0 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool findPath ( vector < vector < int > > maze , int xpos , int ypos , bool key ) { if ( xpos < 0 || xpos >= maze . size ( ) || ypos < 0 || ypos >= maze . size ( ) ) return false ; if ( maze [ xpos ] [ ypos ] == '1' ) { if ( key == true ) if ( xpos == maze . size ( ) - 1 && ypos == maze . size ( ) - 1 ) return true ; return findPath ( maze , xpos + 1 , ypos , false ) || findPath ( maze , xpos , ypos + 1 , false ) ; return false ; } if ( xpos == maze . size ( ) - 1 && ypos == maze . size ( ) - 1 ) return true ; return findPath ( maze , xpos + 1 , ypos , key ) || findPath ( maze , xpos , ypos + 1 , key ) ; } bool mazeProb ( vector < vector < int > > maze , int xpos , int ypos ) { bool key = true ; if ( findPath ( maze , xpos , ypos , key ) ) return true ; return false ; } int main ( ) { vector < vector < int > > maze = { { '0' , '0' , '1' } , { '1' , '0' , '1' } , { '1' , '1' , '0' } } ; int n = maze . size ( ) ; if ( mazeProb ( maze , 0 , 0 ) ) cout << " Yes " ; else cout << " No " ; }
Minimum cost to reach end of array array when a maximum jump of K index is allowed | C ++ implementation of the approach ; Function to return the minimum cost to reach the last index ; If we reach the last index ; Already visited state ; Initially maximum ; Visit all possible reachable index ; If inside range ; We cannot move any further ; Memoize ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FindMinimumCost ( int ind , int a [ ] , int n , int k , int dp [ ] ) { if ( ind == ( n - 1 ) ) return 0 ; else if ( dp [ ind ] != -1 ) return dp [ ind ] ; else { int ans = INT_MAX ; for ( int i = 1 ; i <= k ; i ++ ) { if ( ind + i < n ) ans = min ( ans , abs ( a [ ind + i ] - a [ ind ] ) + FindMinimumCost ( ind + i , a , n , k , dp ) ) ; else break ; } return dp [ ind ] = ans ; } } int main ( ) { int a [ ] = { 10 , 30 , 40 , 50 , 20 } ; int k = 3 ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int dp [ n ] ; memset ( dp , -1 , sizeof dp ) ; cout << FindMinimumCost ( 0 , a , n , k , dp ) ; return 0 ; }
Sum of all even factors of numbers in the range [ l , r ] | C ++ implementation of the approach ; Function to calculate the prefix sum of all the even factors ; Add i to all the multiples of i ; Update the prefix sum ; Function to return the sum of all the even factors of the numbers in the given range ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long long int NEW_LINE const int MAX = 100000 ; ll prefix [ MAX ] ; void sieve_modified ( ) { for ( int i = 2 ; i < MAX ; i += 2 ) { for ( int j = i ; j < MAX ; j += i ) prefix [ j ] += i ; } for ( int i = 1 ; i < MAX ; i ++ ) prefix [ i ] += prefix [ i - 1 ] ; } ll sumEvenFactors ( int L , int R ) { return ( prefix [ R ] - prefix [ L - 1 ] ) ; } int main ( ) { sieve_modified ( ) ; int l = 6 , r = 10 ; cout << sumEvenFactors ( l , r ) ; return 0 ; }
Count of numbers between range having only non | C ++ implementation of the approach ; states - position , sum , rem , tight sum can have values upto 162 , if we are dealing with numbers upto 10 ^ 18 when all 18 digits are 9 , then sum is 18 * 9 = 162 ; n is the sum of digits and number should be divisible by m ; Function to return the count of required numbers from 0 to num ; Last position ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current digit is zero and nonz is 1 , we can 't place it ; Function to convert x into its digit vector and uses count ( ) function to return the required count ; Initialize dp ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 20 ; int dp [ M ] [ 165 ] [ M ] [ 2 ] ; int n , m ; int count ( int pos , int sum , int rem , int tight , int nonz , vector < int > num ) { if ( pos == num . size ( ) ) { if ( rem == 0 && sum == n ) return 1 ; return 0 ; } if ( dp [ pos ] [ sum ] [ rem ] [ tight ] != -1 ) return dp [ pos ] [ sum ] [ rem ] [ tight ] ; int ans = 0 ; int limit = ( tight ? 9 : num [ pos ] ) ; for ( int d = 0 ; d <= limit ; d ++ ) { if ( d == 0 && nonz ) continue ; int currSum = sum + d ; int currRem = ( rem * 10 + d ) % m ; int currF = tight || ( d < num [ pos ] ) ; ans += count ( pos + 1 , currSum , currRem , currF , nonz d , num ) ; } return dp [ pos ] [ sum ] [ rem ] [ tight ] = ans ; } int solve ( int x ) { vector < int > num ; while ( x ) { num . push_back ( x % 10 ) ; x /= 10 ; } reverse ( num . begin ( ) , num . end ( ) ) ; memset ( dp , -1 , sizeof ( dp ) ) ; return count ( 0 , 0 , 0 , 0 , 0 , num ) ; } int main ( ) { int L = 1 , R = 100 ; n = 8 , m = 2 ; cout << solve ( R ) - solve ( L ) ; return 0 ; }
Count of Numbers in Range where the number does not contain more than K non zero digits | CPP Program to find the count of numbers in a range where the number does not contain more than K non zero digits ; states - position , count , tight ; K is the number of non zero digits ; This function returns the count of required numbers from 0 to num ; Last position ; If count of non zero digits is less than or equal to K ; If this result is already computed simply return it ; Maximum limit upto which we can place digit . If tight is 1 , means number has already become smaller so we can place any digit , otherwise num [ pos ] ; If the current digit is nonzero increment currCnt ; At this position , number becomes smaller ; Next recursive call ; This function converts a number into its digit vector and uses above function to compute the answer ; Initialize dp ; Driver Code to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int M = 20 ; int dp [ M ] [ M ] [ 2 ] ; int K ; int countInRangeUtil ( int pos , int cnt , int tight , vector < int > num ) { if ( pos == num . size ( ) ) { if ( cnt <= K ) return 1 ; return 0 ; } if ( dp [ pos ] [ cnt ] [ tight ] != -1 ) return dp [ pos ] [ cnt ] [ tight ] ; int ans = 0 ; int limit = ( tight ? 9 : num [ pos ] ) ; for ( int dig = 0 ; dig <= limit ; dig ++ ) { int currCnt = cnt ; if ( dig != 0 ) currCnt ++ ; int currTight = tight ; if ( dig < num [ pos ] ) currTight = 1 ; ans += countInRangeUtil ( pos + 1 , currCnt , currTight , num ) ; } return dp [ pos ] [ cnt ] [ tight ] = ans ; } int countInRange ( int x ) { vector < int > num ; while ( x ) { num . push_back ( x % 10 ) ; x /= 10 ; } reverse ( num . begin ( ) , num . end ( ) ) ; memset ( dp , -1 , sizeof ( dp ) ) ; return countInRangeUtil ( 0 , 0 , 0 , num ) ; } int main ( ) { int L = 1 , R = 1000 ; K = 3 ; cout << countInRange ( R ) - countInRange ( L - 1 ) << endl ; L = 9995 , R = 10005 , K = 2 ; cout << countInRange ( R ) - countInRange ( L - 1 ) << endl ; return 0 ; }
Balanced expressions such that given positions have opening brackets | Set 2 | C ++ implementation of above approach using memoization ; Function to find Number of proper bracket expressions ; If open - closed brackets < 0 ; If index reaches the end of expression ; If brackets are balanced ; If already stored in dp ; If the current index has assigned open bracket ; Move forward increasing the length of open brackets ; Move forward by inserting open as well as closed brackets on that index ; return the answer ; Driver Code ; DP array to precompute the answer ; Open brackets at position 1 ; Calling the find function to calculate the answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 1000 NEW_LINE int find ( int index , int openbrk , int n , int dp [ N ] [ N ] , int adj [ ] ) { if ( openbrk < 0 ) return 0 ; if ( index == n ) { if ( openbrk == 0 ) return 1 ; else return 0 ; } if ( dp [ index ] [ openbrk ] != -1 ) return dp [ index ] [ openbrk ] ; if ( adj [ index ] == 1 ) { dp [ index ] [ openbrk ] = find ( index + 1 , openbrk + 1 , n , dp , adj ) ; } else { dp [ index ] [ openbrk ] = find ( index + 1 , openbrk + 1 , n , dp , adj ) + find ( index + 1 , openbrk - 1 , n , dp , adj ) ; } return dp [ index ] [ openbrk ] ; } int main ( ) { int dp [ N ] [ N ] ; int n = 2 ; memset ( dp , -1 , sizeof ( dp ) ) ; int adj [ 4 ] = { 1 , 0 , 0 , 0 } ; cout << find ( 0 , 0 , 2 * n , dp , adj ) << endl ; return 0 ; }
Maximize array elements upto given number | CPP code to find maximum value of number obtained by using array elements recursively . ; Utility function to find maximum possible value ; If entire array is traversed , then compare current value in num to overall maximum obtained so far . ; Case 1 : Subtract current element from value so far if result is greater than or equal to zero . ; Case 2 : Add current element to value so far if result is less than or equal to maxLimit . ; Function to find maximum possible value that can be obtained using array elements and given number . ; variable to store maximum value that can be obtained . ; variable to store current index position . ; call to utility function to find maximum possible value that can be obtained . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void findMaxValUtil ( int arr [ ] , int n , int num , int maxLimit , int ind , int & ans ) { if ( ind == n ) { ans = max ( ans , num ) ; return ; } if ( num - arr [ ind ] >= 0 ) { findMaxValUtil ( arr , n , num - arr [ ind ] , maxLimit , ind + 1 , ans ) ; } if ( num + arr [ ind ] <= maxLimit ) { findMaxValUtil ( arr , n , num + arr [ ind ] , maxLimit , ind + 1 , ans ) ; } } int findMaxVal ( int arr [ ] , int n , int num , int maxLimit ) { int ans = 0 ; int ind = 0 ; findMaxValUtil ( arr , n , num , maxLimit , ind , ans ) ; return ans ; } int main ( ) { int num = 1 ; int arr [ ] = { 3 , 10 , 6 , 4 , 5 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int maxLimit = 15 ; cout << findMaxVal ( arr , n , num , maxLimit ) ; return 0 ; }
Print equal sum sets of array ( Partition problem ) | Set 1 | CPP program to print equal sum two subsets of an array if it can be partitioned into subsets . ; / Function to print the equal sum sets of the array . ; / Print set 1. ; / Print set 2. ; / Utility function to find the sets of the array which / have equal sum . ; / If entire array is traversed , compare both the sums . ; / If sums are equal print both sets and return / true to show sets are found . ; / If sums are not equal then return sets are not / found . ; / Add current element to set 1. ; / Recursive call after adding current element to / set 1. ; / If this inclusion results in equal sum sets / partition then return true to show desired sets are / found . ; / If not then backtrack by removing current element / from set1 and include it in set 2. ; / Recursive call after including current element to / set 2. ; / Return true if array arr can be partitioned / into two equal sum sets or not . ; / Calculate sum of elements in array . ; / If sum is odd then array cannot be / partitioned . ; / Declare vectors to store both the sets . ; / Find both the sets . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printSets ( vector < int > set1 , vector < int > set2 ) { int i ; for ( i = 0 ; i < set1 . size ( ) ; i ++ ) { cout << set1 [ i ] << " ▁ " ; } cout << " STRNEWLINE " ; for ( i = 0 ; i < set2 . size ( ) ; i ++ ) { cout << set2 [ i ] << " ▁ " ; } } bool findSets ( int arr [ ] , int n , vector < int > & set1 , vector < int > & set2 , int sum1 , int sum2 , int pos ) { if ( pos == n ) { if ( sum1 == sum2 ) { printSets ( set1 , set2 ) ; return true ; } else return false ; } set1 . push_back ( arr [ pos ] ) ; bool res = findSets ( arr , n , set1 , set2 , sum1 + arr [ pos ] , sum2 , pos + 1 ) ; if ( res ) return res ; set1 . pop_back ( ) ; set2 . push_back ( arr [ pos ] ) ; res = findSets ( arr , n , set1 , set2 , sum1 , sum2 + arr [ pos ] , pos + 1 ) ; if ( res == false ) if ( ! set2 . empty ( ) ) set2 . pop_back ( ) ; return res ; } bool isPartitionPoss ( int arr [ ] , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += arr [ i ] ; if ( sum % 2 != 0 ) return false ; vector < int > set1 , set2 ; return findSets ( arr , n , set1 , set2 , 0 , 0 , 0 ) ; } int main ( ) { int arr [ ] = { 5 , 5 , 1 , 11 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; if ( ! isPartitionPoss ( arr , n ) ) { cout << " - 1" ; } return 0 ; }
Maximum subarray sum in O ( n ) using prefix sum | C ++ program to find out maximum subarray sum in linear time using prefix sum . ; Function to compute maximum subarray sum in linear time . ; Initialize minimum prefix sum to 0. ; Initialize maximum subarray sum so far to - infinity . ; Initialize and compute the prefix sum array . ; loop through the array , keep track of minimum prefix sum so far and maximum subarray sum . ; Driver Program ; Test case 1 ; Test case 2
#include <iostream> NEW_LINE #include <limits> NEW_LINE using namespace std ; int maximumSumSubarray ( int arr [ ] , int n ) { int min_prefix_sum = 0 ; int res = numeric_limits < int > :: min ( ) ; int prefix_sum [ n ] ; prefix_sum [ 0 ] = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) prefix_sum [ i ] = prefix_sum [ i - 1 ] + arr [ i ] ; for ( int i = 0 ; i < n ; i ++ ) { res = max ( res , prefix_sum [ i ] - min_prefix_sum ) ; min_prefix_sum = min ( min_prefix_sum , prefix_sum [ i ] ) ; } return res ; } int main ( ) { int arr1 [ ] = { -2 , -3 , 4 , -1 , -2 , 1 , 5 , -3 } ; int n1 = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; cout << maximumSumSubarray ( arr1 , n1 ) << endl ; int arr2 [ ] = { 4 , -8 , 9 , -4 , 1 , -8 , -1 , 6 } ; int n2 = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << maximumSumSubarray ( arr2 , n2 ) ; return 0 ; }
Counting numbers of n digits that are monotone | CPP program to count numbers of n digits that are monotone . ; Considering all possible digits as { 1 , 2 , 3 , . .9 } ; DP [ i ] [ j ] is going to store monotone numbers of length i + 1 considering j + 1 digits . ; Unit length numbers ; Single digit numbers ; Filling rest of the entries in bottom up manner . ; Driver code .
#include <cstring> NEW_LINE #include <iostream> NEW_LINE int static const DP_s = 9 ; int getNumMonotone ( int len ) { int DP [ len ] [ DP_s ] ; memset ( DP , 0 , sizeof ( DP ) ) ; for ( int i = 0 ; i < DP_s ; ++ i ) DP [ 0 ] [ i ] = i + 1 ; for ( int i = 0 ; i < len ; ++ i ) DP [ i ] [ 0 ] = 1 ; for ( int i = 1 ; i < len ; ++ i ) for ( int j = 1 ; j < DP_s ; ++ j ) DP [ i ] [ j ] = DP [ i - 1 ] [ j ] + DP [ i ] [ j - 1 ] ; return DP [ len - 1 ] [ DP_s - 1 ] ; } int main ( ) { std :: cout << getNumMonotone ( 10 ) ; return 0 ; }
Newman | C ++ program to find the n - th element of Newman - Conway Sequence ; Function to find the n - th element ; Declare array to store sequence ; Driver Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sequence ( int n ) { int f [ n + 1 ] ; int i ; f [ 0 ] = 0 ; f [ 1 ] = 1 ; f [ 2 ] = 1 ; for ( i = 3 ; i <= n ; i ++ ) f [ i ] = f [ f [ i - 1 ] ] + f [ i - f [ i - 1 ] ] ; return f [ n ] ; } int main ( ) { int n = 10 ; cout << sequence ( n ) ; return 0 ; }
Maximum product of an increasing subsequence | Dynamic programming C ++ implementation of maximum product of an increasing subsequence ; Returns product of maximum product increasing subsequence . ; Initialize MPIS values ; Compute optimized MPIS values considering every element as ending element of sequence ; Pick maximum of all product values ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; ll lis ( ll arr [ ] , ll n ) { ll mpis [ n ] ; for ( int i = 0 ; i < n ; i ++ ) mpis [ i ] = arr [ i ] ; for ( int i = 1 ; i < n ; i ++ ) for ( int j = 0 ; j < i ; j ++ ) if ( arr [ i ] > arr [ j ] && mpis [ i ] < ( mpis [ j ] * arr [ i ] ) ) mpis [ i ] = mpis [ j ] * arr [ i ] ; return * max_element ( mpis , mpis + n ) ; } int main ( ) { ll arr [ ] = { 3 , 100 , 4 , 5 , 150 , 6 } ; ll n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printf ( " % lld " , lis ( arr , n ) ) ; return 0 ; }
Hosoya 's Triangle | CPP Program to print Hosoya 's triangle of height n. ; Base case ; Recursive step ; Print the Hosoya triangle of height n . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Hosoya ( int n , int m ) { if ( ( n == 0 && m == 0 ) || ( n == 1 && m == 0 ) || ( n == 1 && m == 1 ) || ( n == 2 && m == 1 ) ) return 1 ; if ( n > m ) return Hosoya ( n - 1 , m ) + Hosoya ( n - 2 , m ) ; else if ( m == n ) return Hosoya ( n - 1 , m - 1 ) + Hosoya ( n - 2 , m - 2 ) ; else return 0 ; } void printHosoya ( int n ) { for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) cout << Hosoya ( i , j ) << " ▁ " ; cout << endl ; } } int main ( ) { int n = 5 ; printHosoya ( n ) ; return 0 ; }
Eulerian Number | CPP Program to find Eulerian number A ( n , m ) ; Return euleriannumber A ( n , m ) ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int eulerian ( int n , int m ) { if ( m >= n n == 0 ) return 0 ; if ( m == 0 ) return 1 ; return ( n - m ) * eulerian ( n - 1 , m - 1 ) + ( m + 1 ) * eulerian ( n - 1 , m ) ; } int main ( ) { int n = 3 , m = 1 ; cout << eulerian ( n , m ) << endl ; return 0 ; }
Largest divisible pairs subset | CPP program to find the largest subset which where each pair is divisible . ; function to find the longest Subsequence ; dp [ i ] is going to store size of largest divisible subset beginning with a [ i ] . ; Since last element is largest , d [ n - 1 ] is 1 ; Fill values for smaller elements . ; Find all multiples of a [ i ] and consider the multiple that has largest subset beginning with it . ; Return maximum value from dp [ ] ; driver code to check the above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int largestSubset ( int a [ ] , int n ) { int dp [ n ] ; dp [ n - 1 ] = 1 ; for ( int i = n - 2 ; i >= 0 ; i -- ) { int mxm = 0 ; for ( int j = i + 1 ; j < n ; j ++ ) if ( a [ j ] % a [ i ] == 0 a [ i ] % a [ j ] == 0 ) mxm = max ( mxm , dp [ j ] ) ; dp [ i ] = 1 + mxm ; } return * max_element ( dp , dp + n ) ; } int main ( ) { int a [ ] = { 1 , 3 , 6 , 13 , 17 , 18 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << largestSubset ( a , n ) << endl ; return 0 ; }
How to solve a Dynamic Programming Problem ? | initialize to - 1 ; this function returns the number of arrangements to form ' n ' ; base case ; checking if already calculated ; storing the result and returning
int dp [ MAXN ] ; int solve ( int n ) { if ( n < 0 ) return 0 ; if ( n == 0 ) return 1 ; if ( dp [ n ] != -1 ) return dp [ n ] ; return dp [ n ] = solve ( n - 1 ) + solve ( n - 3 ) + solve ( n - 5 ) ; }
Friends Pairing Problem | C ++ program for solution of friends pairing problem ; Returns count of ways n people can remain single or paired up . ; Filling dp [ ] in bottom - up manner using recursive formula explained above . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFriendsPairings ( int n ) { int dp [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) { if ( i <= 2 ) dp [ i ] = i ; else dp [ i ] = dp [ i - 1 ] + ( i - 1 ) * dp [ i - 2 ] ; } return dp [ n ] ; } int main ( ) { int n = 4 ; cout << countFriendsPairings ( n ) << endl ; return 0 ; }
Friends Pairing Problem | Returns count of ways n people can remain single or paired up . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countFriendsPairings ( int n ) { int a = 1 , b = 2 , c = 0 ; if ( n <= 2 ) { return n ; } for ( int i = 3 ; i <= n ; i ++ ) { c = b + ( i - 1 ) * a ; a = b ; b = c ; } return c ; } int main ( ) { int n = 4 ; cout << countFriendsPairings ( n ) ; return 0 ; }
Check whether row or column swaps produce maximum size binary sub | C ++ program to find maximum binary sub - matrix with row swaps and column swaps . ; Precompute the number of consecutive 1 below the ( i , j ) in j - th column and the number of consecutive 1 s on right side of ( i , j ) in i - th row . ; Travesing the 2d matrix from top - right . ; If ( i , j ) contain 0 , do nothing ; Counting consecutive 1 on right side ; Travesing the 2d matrix from bottom - left . ; If ( i , j ) contain 0 , do nothing ; Counting consecutive 1 down to ( i , j ) . ; Return maximum size submatrix with row swap allowed . ; Copying the column ; Sort the copied array ; Find maximum submatrix size . ; Return maximum size submatrix with column swap allowed . ; Copying the row . ; Sort the copied array ; Find maximum submatrix size . ; Solving for row swap and column swap ; Comparing both . ; Driven Program
#include <bits/stdc++.h> NEW_LINE #define R 5 NEW_LINE #define C 3 NEW_LINE using namespace std ; void precompute ( int mat [ R ] [ C ] , int ryt [ ] [ C + 2 ] , int dwn [ R + 2 ] [ C + 2 ] ) { for ( int j = C - 1 ; j >= 0 ; j -- ) { for ( int i = 0 ; i < R ; ++ i ) { if ( mat [ i ] [ j ] == 0 ) ryt [ i ] [ j ] = 0 ; else ryt [ i ] [ j ] = ryt [ i ] [ j + 1 ] + 1 ; } } for ( int i = R - 1 ; i >= 0 ; i -- ) { for ( int j = 0 ; j < C ; ++ j ) { if ( mat [ i ] [ j ] == 0 ) dwn [ i ] [ j ] = 0 ; else dwn [ i ] [ j ] = dwn [ i + 1 ] [ j ] + 1 ; } } } int solveRowSwap ( int ryt [ R + 2 ] [ C + 2 ] ) { int b [ R ] = { 0 } , ans = 0 ; for ( int j = 0 ; j < C ; j ++ ) { for ( int i = 0 ; i < R ; i ++ ) b [ i ] = ryt [ i ] [ j ] ; sort ( b , b + R ) ; for ( int i = 0 ; i < R ; ++ i ) ans = max ( ans , b [ i ] * ( R - i ) ) ; } return ans ; } int solveColumnSwap ( int dwn [ R + 2 ] [ C + 2 ] ) { int b [ C ] = { 0 } , ans = 0 ; for ( int i = 0 ; i < R ; ++ i ) { for ( int j = 0 ; j < C ; ++ j ) b [ j ] = dwn [ i ] [ j ] ; sort ( b , b + C ) ; for ( int i = 0 ; i < C ; ++ i ) ans = max ( ans , b [ i ] * ( C - i ) ) ; } return ans ; } void findMax1s ( int mat [ R ] [ C ] ) { int ryt [ R + 2 ] [ C + 2 ] , dwn [ R + 2 ] [ C + 2 ] ; memset ( ryt , 0 , sizeof ryt ) ; memset ( dwn , 0 , sizeof dwn ) ; precompute ( mat , ryt , dwn ) ; int rswap = solveRowSwap ( ryt ) ; int cswap = solveColumnSwap ( dwn ) ; ( rswap > cswap ) ? ( cout << " Row ▁ Swap STRNEWLINE " << rswap << endl ) : ( cout << " Column ▁ Swap STRNEWLINE " << cswap << endl ) ; } int main ( ) { int mat [ R ] [ C ] = { { 0 , 0 , 0 } , { 1 , 1 , 0 } , { 1 , 1 , 0 } , { 0 , 0 , 0 } , { 1 , 1 , 0 } } ; findMax1s ( mat ) ; return 0 ; }
LCS ( Longest Common Subsequence ) of three strings | C ++ program to find LCS of three strings ; Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] and Z [ 0. . o - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] [ o + 1 ] in bottom up fashion . Note that L [ i ] [ j ] [ k ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] and Z [ 0. . ... k - 1 ] ; L [ m ] [ n ] [ o ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] and Z [ 0. . o - 1 ] ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lcsOf3 ( string X , string Y , string Z , int m , int n , int o ) { int L [ m + 1 ] [ n + 1 ] [ o + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { for ( int k = 0 ; k <= o ; k ++ ) { if ( i == 0 j == 0 k == 0 ) L [ i ] [ j ] [ k ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] && X [ i - 1 ] == Z [ k - 1 ] ) L [ i ] [ j ] [ k ] = L [ i - 1 ] [ j - 1 ] [ k - 1 ] + 1 ; else L [ i ] [ j ] [ k ] = max ( max ( L [ i - 1 ] [ j ] [ k ] , L [ i ] [ j - 1 ] [ k ] ) , L [ i ] [ j ] [ k - 1 ] ) ; } } } return L [ m ] [ n ] [ o ] ; } int main ( ) { string X = " AGGT12" ; string Y = "12TXAYB " ; string Z = "12XBA " ; int m = X . length ( ) ; int n = Y . length ( ) ; int o = Z . length ( ) ; cout << " Length ▁ of ▁ LCS ▁ is ▁ " << lcsOf3 ( X , Y , Z , m , n , o ) ; return 0 ; }
Longest subsequence such that difference between adjacents is one | Longest subsequence with one difference is { 1 , 2 , 3 , 4 , 3 , 2 }
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubsequence ( int n , int arr [ ] ) { if ( n == 1 ) return 1 ; int dp [ n ] ; unordered_map < int , int > mapp ; dp [ 0 ] = 1 ; mapp [ arr [ 0 ] ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( abs ( arr [ i ] - arr [ i - 1 ] ) == 1 ) dp [ i ] = dp [ i - 1 ] + 1 ; else { if ( mapp . count ( arr [ i ] + 1 ) > 0 || mapp . count ( arr [ i ] - 1 ) ) { dp [ i ] = 1 + max ( mapp [ arr [ i ] + 1 ] , mapp [ arr [ i ] - 1 ] ) ; } else dp [ i ] = 1 ; } mapp [ arr [ i ] ] = dp [ i ] ; } return ( * max_element ( dp , dp + n ) ) ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSubsequence ( n , arr ) ; return 0 ; }
Printing Shortest Common Supersequence | A dynamic programming based C ++ program print shortest supersequence of two strings ; returns shortest supersequence of X and Y ; dp [ i ] [ j ] contains length of shortest supersequence for X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; Fill table in bottom up manner ; Below steps follow recurrence relation ; string to store the shortest supersequence ; Start from the bottom right corner and one by one push characters in output string ; If current character in X and Y are same , then current character is part of shortest supersequence ; Put current character in result ; reduce values of i , j and index ; If current character in X and Y are different ; Put current character of Y in result ; reduce values of j and index ; Put current character of X in result ; reduce values of i and index ; If Y reaches its end , put remaining characters of X in the result string ; If X reaches its end , put remaining characters of Y in the result string ; reverse the string and return it ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printShortestSuperSeq ( string X , string Y ) { int m = X . length ( ) ; int n = Y . length ( ) ; int dp [ m + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 ) dp [ i ] [ j ] = j ; else if ( j == 0 ) dp [ i ] [ j ] = i ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = 1 + min ( dp [ i - 1 ] [ j ] , dp [ i ] [ j - 1 ] ) ; } } string str ; int i = m , j = n ; while ( i > 0 && j > 0 ) { if ( X [ i - 1 ] == Y [ j - 1 ] ) { str . push_back ( X [ i - 1 ] ) ; i -- , j -- ; } else if ( dp [ i - 1 ] [ j ] > dp [ i ] [ j - 1 ] ) { str . push_back ( Y [ j - 1 ] ) ; j -- ; } else { str . push_back ( X [ i - 1 ] ) ; i -- ; } } while ( i > 0 ) { str . push_back ( X [ i - 1 ] ) ; i -- ; } while ( j > 0 ) { str . push_back ( Y [ j - 1 ] ) ; j -- ; } reverse ( str . begin ( ) , str . end ( ) ) ; return str ; } int main ( ) { string X = " AGGTAB " ; string Y = " GXTXAYB " ; cout << printShortestSuperSeq ( X , Y ) ; return 0 ; }
Longest Repeating Subsequence | C ++ program to find the longest repeating subsequence ; This function mainly returns LCS ( str , str ) with a condition that same characters at same index are not considered . ; Create and initialize DP table ; Fill dp table ( similar to LCS loops ) ; If characters match and indexes are not same ; If characters do not match ; Driver Program
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int findLongestRepeatingSubSeq ( string str ) { int n = str . length ( ) ; int dp [ n + 1 ] [ n + 1 ] ; for ( int i = 0 ; i <= n ; i ++ ) for ( int j = 0 ; j <= n ; j ++ ) dp [ i ] [ j ] = 0 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( str [ i - 1 ] == str [ j - 1 ] && i != j ) dp [ i ] [ j ] = 1 + dp [ i - 1 ] [ j - 1 ] ; else dp [ i ] [ j ] = max ( dp [ i ] [ j - 1 ] , dp [ i - 1 ] [ j ] ) ; } } return dp [ n ] [ n ] ; } int main ( ) { string str = " aabb " ; cout << " The ▁ length ▁ of ▁ the ▁ largest ▁ subsequence ▁ that " " ▁ repeats ▁ itself ▁ is ▁ : ▁ " << findLongestRepeatingSubSeq ( str ) ; return 0 ; }
Count total number of N digit numbers such that the difference between sum of even and odd digits is 1 | A memoization based recursive program to count numbers with difference between odd and even digit sums as 1 ; A lookup table used for memoization . ; Memoization based recursive function to count numbers with even and odd digit sum difference as 1. This function considers leading zero as a digit ; Base Case ; If current subproblem is already computed ; Initialize result ; If the current digit is odd , then add it to odd sum and recur ; else Add to even sum and recur ; Store current result in lookup table and return the same ; This is mainly a wrapper over countRec . It explicitly handles leading digit and calls countRec ( ) for remaining digits . ; Initialize number digits considered so far ; Initialize all entries of lookup table ; Initialize final answer ; Initialize even and odd sums ; Explicitly handle first digit and call recursive function countRec for remaining digits . Note that the first digit is considered as even digit . ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long int lookup [ 50 ] [ 1000 ] [ 1000 ] [ 2 ] ; unsigned long long int countRec ( int digits , int esum , int osum , bool isOdd , int n ) { if ( digits == n ) return ( esum - osum == 1 ) ; if ( lookup [ digits ] [ esum ] [ osum ] [ isOdd ] != -1 ) return lookup [ digits ] [ esum ] [ osum ] [ isOdd ] ; unsigned long long int ans = 0 ; if ( isOdd ) for ( int i = 0 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum , osum + i , false , n ) ; for ( int i = 0 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum + i , osum , true , n ) ; return lookup [ digits ] [ esum ] [ osum ] [ isOdd ] = ans ; } unsigned long long int finalCount ( int n ) { int digits = 0 ; memset ( lookup , -1 , sizeof lookup ) ; unsigned long long int ans = 0 ; int esum = 0 , osum = 0 ; for ( int i = 1 ; i <= 9 ; i ++ ) ans += countRec ( digits + 1 , esum + i , osum , true , n ) ; return ans ; } int main ( ) { int n = 3 ; cout << " Count ▁ of ▁ " << n << " ▁ digit ▁ numbers ▁ is ▁ " << finalCount ( n ) ; return 0 ; }
Count all possible paths from top left to bottom right of a mXn matrix | 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 ) ; Create a 1D array to store results of subproblems ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfPaths ( int m , int n ) { int dp [ n ] = { 1 } ; dp [ 0 ] = 1 ; for ( int i = 0 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) { dp [ j ] += dp [ j - 1 ] ; } } return dp [ n - 1 ] ; } int main ( ) { cout << numberOfPaths ( 3 , 3 ) ; }
Longest Arithmetic Progression | DP | C ++ program to find Length of the Longest AP ( llap ) in a given sorted set . ; Returns length of the longest AP subset in a given set ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Solution ( vector < int > A ) { int ans = 2 ; int n = A . size ( ) ; if ( n <= 2 ) return n ; vector < int > llap ( n , 2 ) ; sort ( A . begin ( ) , A . end ( ) ) ; for ( int j = n - 2 ; j >= 0 ; j -- ) { int i = j - 1 ; int k = j + 1 ; while ( i >= 0 && k < n ) { if ( A [ i ] + A [ k ] == 2 * A [ j ] ) { llap [ j ] = max ( llap [ k ] + 1 , llap [ j ] ) ; ans = max ( ans , llap [ j ] ) ; i -= 1 ; k += 1 ; } else if ( A [ i ] + A [ k ] < 2 * A [ j ] ) k += 1 ; else i -= 1 ; } } return ans ; } int main ( ) { vector < int > a ( { 9 , 4 , 7 , 2 , 10 } ) ; cout << Solution ( a ) << endl ; return 0 ; }
Minimum numbers to be appended such that mean of Array is equal to 1 | C ++ program for above approach ; Function to calculate minimum Number of operations ; Storing sum of array arr [ ] ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minumumOperation ( int N , int arr [ ] ) { int sum_arr = 0 ; sum_arr = accumulate ( arr , arr + N , sum_arr ) ; if ( sum_arr >= N ) cout << sum_arr - N << endl ; else cout << 1 << endl ; } int main ( ) { int N = 4 ; int arr [ ] = { 8 , 4 , 6 , 2 } ; minumumOperation ( N , arr ) ; }
Find Nth term of series 1 , 4 , 15 , 72 , 420. . . | CPP program to find N - th term of the series : 1 , 4 , 15 , 72 , 420 Aa Using recursion ; Function to find factorial of N with recursion ; base condition ; use recursion ; calculate Nth term of series ; Driver Function
#include <iostream> NEW_LINE using namespace std ; int factorial ( int N ) { if ( N == 0 N == 1 ) return 1 ; return N * factorial ( N - 1 ) ; } int nthTerm ( int N ) { return ( factorial ( N ) * ( N + 2 ) / 2 ) ; } int main ( ) { int N = 6 ; cout << nthTerm ( N ) ; return 0 ; }
Check if a string is substring of another | int counter = 0 ; pointing s2 ; Special case where character preceding the i 'th character is duplicate ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Substr ( string s2 , string s1 ) { int i = 0 ; for ( ; i < s1 . length ( ) ; i ++ ) { if ( counter == s2 . length ( ) ) break ; if ( s2 [ counter ] == s1 [ i ] ) { counter ++ ; } else { if ( counter > 0 ) { i -= counter ; } counter = 0 ; } } return counter < s2 . length ( ) ? -1 : i - counter ; } int main ( ) { string s1 = " geeksfffffoorrfoorforgeeks " ; cout << Substr ( " for " , s1 ) ; return 0 ; }
Count anagrams having first character as a consonant and no pair of consonants or vowels placed adjacently | C ++ program for the above approach ; Function to compute factorials till N ; Iterate in the range [ 1 , N ] ; Update ans to ans * i ; Store the value of ans in fac [ i ] ; Function to check whether the current character is a vowel or not ; Function to count the number of anagrams of S satisfying the given condition ; Store the factorials upto N ; Function Call to generate all factorials upto n ; Create a hashmap to store frequencies of all characters ; Store the count of vowels and consonants ; Iterate through all characters in the string ; Update the frequency of current character ; Check if the character is vowel or consonant ; Check if C == V + 1 or C == V ; Store the denominator ; Calculate the denominator of the expression ; Multiply denominator by factorial of counts of all letters ; Store the numerator ; Store the answer by dividing numerator by denominator ; Print the answer ; Otherwise , print 0 ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define ll long long NEW_LINE #define mod 1000000007 NEW_LINE #define N 1000001 NEW_LINE using namespace std ; void Precomputefact ( unordered_map < ll , ll > & fac ) { ll ans = 1 ; for ( ll i = 1 ; i <= N ; i ++ ) { ans = ( ans * i ) % mod ; fac [ i ] = ans ; } return ; } bool isVowel ( char a ) { if ( a == ' A ' a == ' E ' a == ' I ' a == ' O ' a == ' U ' ) return true ; else return false ; } void countAnagrams ( string s , int n ) { unordered_map < ll , ll > fac ; Precomputefact ( fac ) ; unordered_map < char , ll > count ; int vo = 0 , co = 0 ; for ( int i = 0 ; i < n ; i ++ ) { count [ s [ i ] ] ++ ; if ( isVowel ( s [ i ] ) ) vo ++ ; else co ++ ; } if ( ( co == vo + 1 ) || ( co == vo ) ) { ll deno = 1 ; for ( auto c : count ) { deno = ( deno * fac [ c . second ] ) % mod ; } ll nume = fac [ co ] % mod ; nume = ( nume * fac [ vo ] ) % mod ; ll ans = nume / deno ; cout << ans ; } else { cout << 0 ; } } int main ( ) { string S = " GADO " ; int l = S . size ( ) ; countAnagrams ( S , l ) ; return 0 ; }
Hamming code Implementation in C / C ++ | C ++ program for the above approach ; Function to generate hamming code ; Stores the Hamming Code ; Find positions of redundant bits ; Placing - 1 at redundant bits place to identify it later ; Iterate to update the code ; Placing msgBits where - 1 is absent i . e . , except redundant bits all positions are msgBits ; If current bit is not redundant bit then continue ; Find msg bits containing set bit at x 'th position ; Generating hamming code for even parity ; Return the generated code ; Function to find the hamming code of the given message bit msgBit [ ] ; Message bit size ; r is the number of redundant bits ; Find no . of redundant bits ; Generating Code ; Print the code ; Driver Code ; Given message bits ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > generateHammingCode ( vector < int > msgBits , int m , int r ) { vector < int > hammingCode ( r + m ) ; for ( int i = 0 ; i < r ; ++ i ) { hammingCode [ pow ( 2 , i ) - 1 ] = -1 ; } int j = 0 ; for ( int i = 0 ; i < ( r + m ) ; i ++ ) { if ( hammingCode [ i ] != -1 ) { hammingCode [ i ] = msgBits [ j ] ; j ++ ; } } for ( int i = 0 ; i < ( r + m ) ; i ++ ) { if ( hammingCode [ i ] != -1 ) continue ; int x = log2 ( i + 1 ) ; int one_count = 0 ; for ( int j = i + 2 ; j <= ( r + m ) ; ++ j ) { if ( j & ( 1 << x ) ) { if ( hammingCode [ j - 1 ] == 1 ) { one_count ++ ; } } } if ( one_count % 2 == 0 ) { hammingCode [ i ] = 0 ; } else { hammingCode [ i ] = 1 ; } } return hammingCode ; } void findHammingCode ( vector < int > & msgBit ) { int m = msgBit . size ( ) ; int r = 1 ; while ( pow ( 2 , r ) < ( m + r + 1 ) ) { r ++ ; } vector < int > ans = generateHammingCode ( msgBit , m , r ) ; cout << " Message ▁ bits ▁ are : ▁ " ; for ( int i = 0 ; i < msgBit . size ( ) ; i ++ ) cout << msgBit [ i ] << " ▁ " ; cout << " Hamming code is : " ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { vector < int > msgBit = { 0 , 1 , 0 , 1 } ; findHammingCode ( msgBit ) ; return 0 ; }
Modify string by increasing each character by its distance from the end of the word | C ++ implementation of the above approach ; Function to transform and return the transformed word ; Stores resulting word ; Iterate over the word ; Add the position value to the letter ; Convert it back to character ; Add it to the string ; Function to transform the given string ; Size of string ; Stores resultant string ; Iterate over given string ; End of word is reached ; Append the word ; For the last word ; Driver code ; Given string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string util ( string sub ) { int n = sub . length ( ) ; int i = 0 ; string ret = " " ; while ( i < n ) { int t = ( sub [ i ] - ' a ' ) + n - 1 - i ; char ch = ( char ) ( t % 26 + 97 ) ; ret = ret + ch ; i ++ ; } return ret ; } void manipulate ( string s ) { int n = s . length ( ) ; int i = 0 , j = 0 ; string res = " " ; while ( i < n ) { if ( s [ i ] == ' ▁ ' ) { res += util ( s . substr ( j , i ) ) ; res = res + " ▁ " ; j = i + 1 ; i = j + 1 ; } else { i ++ ; } } res = res + util ( s . substr ( j , i ) ) ; cout << res << endl ; } int main ( ) { string s = " acm ▁ fkz " ; manipulate ( s ) ; return 0 ; }
Check if given words are present in a string | Find the small string at that index in the array of small strings is contained in the big string ; Function to the multiStringSearch ; iterate in the smallString ; calling the isInBigString Function ; Function to the bigString ; iterate in the bigString ; Check if length of smallString + i is greater than the length of bigString ; call the function isInBigStringHelper ; Helper Function to the Finding bigString ; Initialize leftBigIdx and rightBigIdx and leftSmallIdx variables ; Iterate until leftBigIdx variable reaches less than or equal to rightBigIdx ; Check if bigString [ leftBigIdx ] is not equal to smallString [ leftSmallIdx ] or Check if bigString [ rightBigIdx ] is not equal to smallString [ rightSmallIdx ] than return false otherwise increment leftBigIdx and leftSmallIdx decrement rightBigIdx and rightSmallIdx ; Driver code ; initialize string ; initialize vector string ; Function call ; Print answers ; Check if ans [ i ] is equal to 1 then Print true otherwise print false
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isInBigString ( string bigString , string smallString ) ; bool isInBigStringHelper ( string bigString , string smallString , int startIdx ) ; vector < bool > multiStringSearch ( string bigString , vector < string > smallStrings ) { vector < bool > solution ; for ( string smallString : smallStrings ) { solution . push_back ( isInBigString ( bigString , smallString ) ) ; } return solution ; } bool isInBigString ( string bigString , string smallString ) { for ( int i = 0 ; i < bigString . length ( ) ; i ++ ) { if ( i + smallString . length ( ) > bigString . length ( ) ) { break ; } if ( isInBigStringHelper ( bigString , smallString , i ) ) { return true ; } } return false ; } bool isInBigStringHelper ( string bigString , string smallString , int startIdx ) { int leftBigIdx = startIdx ; int rightBigIdx = startIdx + smallString . length ( ) - 1 ; int leftSmallIdx = 0 ; int rightSmallIdx = smallString . length ( ) - 1 ; while ( leftBigIdx <= rightBigIdx ) { if ( bigString [ leftBigIdx ] != smallString [ leftSmallIdx ] bigString [ rightBigIdx ] != smallString [ rightSmallIdx ] ) { return false ; } leftBigIdx ++ ; rightBigIdx -- ; leftSmallIdx ++ ; rightSmallIdx -- ; } return true ; } int main ( int argc , char * argv [ ] ) { string str = " this ▁ is ▁ a ▁ big ▁ string " ; vector < string > substr = { " this " , " yo " , " is " , " a " , " bigger " , " string " , " kappa " } ; vector < bool > ans = multiStringSearch ( str , substr ) ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans [ i ] == 1 ) { cout << " true " << " ▁ " ; } else { cout << " false " << " ▁ " ; } } return 0 ; }
Count of lexicographically smaller characters on right | Function to count the smaller characters on the right of index i ; store the length of string ; initialize each elements of arr to zero ; array to store count of smaller characters on the right side of that index ; initialize the variable to store the count of characters smaller than that at index i ; adding the count of characters smaller than index i ; print the count of characters smaller than index i stored in ans array ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countSmaller ( string str ) { int n = str . length ( ) ; int arr [ 26 ] = { 0 } ; int ans [ n ] ; for ( int i = n - 1 ; i >= 0 ; i -- ) { arr [ str [ i ] - ' a ' ] ++ ; int ct = 0 ; for ( int j = 0 ; j < str [ i ] - ' a ' ; j ++ ) { ct += arr [ j ] ; } ans [ i ] = ct ; } for ( int i = 0 ; i < n ; i ++ ) { cout << ans [ i ] << " ▁ " ; } } int main ( ) { string str = " edcbaa " ; countSmaller ( str ) ; return 0 ; }
Find the longest sub | C ++ program to find that substring which is its suffix prefix and also found somewhere in between ; Z - algorithm function ; BIT array ; bit update function which updates values from index " idx " to last by value " val " ; Query function in bit ; Driver Code ; Making the z array ; update in the bit array from index z [ i ] by increment of 1 ; if the value in z [ i ] is not equal to ( n - i ) then no need to move further ; queryng for the maximum length substring from bit array
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > z_function ( string s ) { int n = s . size ( ) ; vector < int > z ( n ) ; for ( int i = 1 , l = 0 , r = 0 ; i < n ; i ++ ) { if ( i <= r ) z [ i ] = min ( r - i + 1 , z [ i - l ] ) ; while ( i + z [ i ] < n && s [ z [ i ] ] == s [ i + z [ i ] ] ) z [ i ] ++ ; if ( i + z [ i ] - 1 > r ) l = i , r = i + z [ i ] - 1 ; } return z ; } int n , len = 0 ; int bit [ 1000005 ] ; string s ; vector < int > z ; map < int , int > m ; void update ( int idx , int val ) { if ( idx == 0 ) return ; while ( idx <= n ) { bit [ idx ] += val ; idx += ( idx & - idx ) ; } } int pref ( int idx ) { int ans = 0 ; while ( idx > 0 ) { ans += bit [ idx ] ; idx -= ( idx & - idx ) ; } return ans ; } int main ( ) { s = " geeksisforgeeksinplatformgeeks " ; n = s . size ( ) ; z = z_function ( s ) ; for ( int i = 1 ; i < n ; i ++ ) { update ( z [ i ] , 1 ) ; } for ( int i = n - 1 ; i > 1 ; i -- ) { if ( z [ i ] != ( n - i ) ) continue ; if ( pref ( n ) - pref ( z [ i ] - 1 ) >= 2 ) { len = max ( len , z [ i ] ) ; } } if ( ! len ) cout << " - 1" ; else cout << s . substr ( 0 , len ) ; return 0 ; }
Count of words ending at the given suffix in Java | C ++ implementation of the approach ; Function to return the count of words in the given sentence that end with the given suffix ; To store the count ; Extract words from the sentence ; For every word ; If it ends with the given suffix ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; template < size_t N > void splitString ( string ( & arr ) [ N ] , string str ) { int n = 0 ; istringstream iss ( str ) ; for ( auto it = istream_iterator < string > ( iss ) ; it != istream_iterator < string > ( ) && n < N ; ++ it , ++ n ) arr [ n ] = * it ; } inline bool ends_with ( std :: string const & value , std :: string const & ending ) { if ( ending . size ( ) > value . size ( ) ) return false ; return std :: equal ( ending . rbegin ( ) , ending . rend ( ) , value . rbegin ( ) ) ; } int endingWith ( string str , string suff ) { int cnt = 0 ; const int size = 50 ; string words [ size ] ; splitString ( words , str ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( ends_with ( words [ i ] , suff ) ) cnt ++ ; } return cnt ; } int main ( ) { string str = " GeeksForGeeks ▁ is ▁ a ▁ computer ▁ " " science ▁ portal ▁ for ▁ geeks " ; string suff = " ks " ; cout << endingWith ( str , suff ) ; }
Character whose frequency is equal to the sum of frequencies of other characters of the given string | C ++ implementation of the approach ; Function that returns true if some character exists in the given string whose frequency is equal to the sum frequencies of other characters of the string ; If string is of odd length ; To store the frequency of each character of the string ; Update the frequencies of the characters ; No such character exists ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isFrequencyEqual ( string str , int len ) { if ( len % 2 == 1 ) return false ; int i , freq [ 26 ] = { 0 } ; for ( i = 0 ; i < len ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; for ( i = 0 ; i < 26 ; i ++ ) if ( freq [ i ] == len / 2 ) return true ; return false ; } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; if ( isFrequencyEqual ( str , len ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimum replacements to make adjacent characters unequal in a ternary string | C ++ program to count the minimal replacements such that adjacent characters are unequal ; Function to count the number of minimal replacements ; Find the length of the string ; Iterate in the string ; Check if adjacent is similar ; If not the last pair ; Check for character which is not same in i + 1 and i - 1 ; else Last pair ; Check for character which is not same in i - 1 index ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinimalReplacements ( string s ) { int n = s . length ( ) ; int cnt = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == s [ i - 1 ] ) { cnt += 1 ; if ( i != ( n - 1 ) ) { for ( auto it : "012" ) { if ( it != s [ i + 1 ] && it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } { for ( auto it : "012" ) { if ( it != s [ i - 1 ] ) { s [ i ] = it ; break ; } } } } } return cnt ; } int main ( ) { string s = "201220211" ; cout << countMinimalReplacements ( s ) ; return 0 ; }
Sub | C ++ implementation of the approach ; Function that returns the index of next occurrence of the character c in string str starting from index start ; Starting from start ; If current character = c ; Not found ; Function to return the count of required sub - strings ; Stores running count of ' x ' starting from the end ; Next index of ' x ' starting from index 0 ; Next index of ' y ' starting from index 0 ; To store the count of required sub - strings ; If ' y ' appears before ' x ' it won 't contribute to a valid sub-string ; Find next occurrence of ' y ' ; If ' y ' appears after ' x ' every sub - string ending at an ' x ' appearing after this ' y ' and starting with the current ' x ' is a valid sub - string ; Find next occurrence of ' x ' ; Return the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int nextIndex ( string str , int start , char c ) { for ( int i = start ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == c ) return i ; } return -1 ; } int countSubStrings ( string str ) { int i , n = str . length ( ) ; int countX [ n ] ; int count = 0 ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' x ' ) count ++ ; countX [ i ] = count ; } int nextIndexX = nextIndex ( str , 0 , ' x ' ) ; int nextIndexY = nextIndex ( str , 0 , ' y ' ) ; count = 0 ; while ( nextIndexX != -1 && nextIndexY != -1 ) { if ( nextIndexX > nextIndexY ) { nextIndexY = nextIndex ( str , nextIndexY + 1 , ' y ' ) ; continue ; } else { count += countX [ nextIndexY ] ; nextIndexX = nextIndex ( str , nextIndexX + 1 , ' x ' ) ; } } return count ; } int main ( ) { string s = " xyyxx " ; cout << countSubStrings ( s ) ; }
Check whether the frequencies of all the characters in a string are prime or not | C ++ implementation of above approach ; function that returns true if n is prime else false ; 1 is not prime ; check if there is any factor or not ; function that returns true if the frequencies of all the characters of s are prime ; create a map to store the frequencies of characters ; update the frequency ; check whether all the frequencies are prime or not ; Driver code ; if all the frequencies are prime
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { int i ; if ( n == 1 ) return false ; for ( i = 2 ; i <= sqrt ( n ) ; i ++ ) if ( n % i == 0 ) return false ; return true ; } bool check_frequency ( string s ) { map < char , int > m ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) m [ s [ i ] ] ++ ; for ( char ch = ' a ' ; ch <= ' z ' ; ch ++ ) if ( m [ ch ] > 0 && ! isPrime ( m [ ch ] ) ) return false ; return true ; } int main ( ) { string s = " geeksforgeeks " ; if ( check_frequency ( s ) ) cout << " Yes " << endl ; else cout << " No " << endl ; return 0 ; }
Find the count of substrings in alphabetic order | CPP to find the number of substrings in alphabetical order ; Function to find number of substrings ; Iterate over string length ; if any two chars are in alphabetic order ; find next char not in order ; return the result ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findSubstringCount ( string str ) { int result = 0 ; int n = str . size ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( str [ i ] + 1 == str [ i + 1 ] ) { result ++ ; while ( str [ i ] + 1 == str [ i + 1 ] ) { i ++ ; } } } return result ; } int main ( ) { string str = " alphabet " ; cout << findSubstringCount ( str ) << endl ; return 0 ; }
Reduce the string by removing K consecutive identical characters | CPP program for the above approach ; Basic Approach is to create a Stack that store the Character and its continuous repetition number This is done using pair < char , int > Further we check at each iteration , whether the character matches the top of stack if it does then check for number of repetitions else add to top of stack with count 1 ; Base Case If k = 1 then all characters can be removed at each instance ; initialize string ; create a stack using pair < > for storing each character and corresponding repetition ; iterate through the string ; if stack is empty then simply add the character with count 1 else check if character is same as top of stack ; if character at top of stack is same as current character increase the number of repetitions in the top of stack by 1 ; if character at top of stack is not same as current character push the character along with count 1 into the top of stack ; Iterate through the stack Use string ( int , char ) in order to replicate the character multiple times and convert into string then add in front of output string ; Driver Code
#include <bits/stdc++.h> NEW_LINE #include <iostream> NEW_LINE using namespace std ; class Solution { public : string remove_k_char ( int k , string s ) { if ( k == 1 ) return " " ; string output = " " ; stack < pair < char , int > > stk ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( stk . empty ( ) == true ) { stk . push ( make_pair ( s [ i ] , 1 ) ) ; } else { if ( s [ i ] == ( stk . top ( ) ) . first ) { stk . push ( { s [ i ] , stk . top ( ) . second + 1 } ) ; if ( stk . top ( ) . second == k ) { int x = k ; while ( x ) { stk . pop ( ) ; x -- ; } } } else { stk . push ( make_pair ( s [ i ] , 1 ) ) ; } } } while ( ! stk . empty ( ) ) { output += stk . top ( ) . first ; stk . pop ( ) ; } reverse ( output . begin ( ) , output . end ( ) ) ; return output ; } } ; int main ( ) { string s = " geeksforgeeks " ; int k = 2 ; Solution obj ; cout << obj . remove_k_char ( k , s ) << " STRNEWLINE " ; return 0 ; }
First non | CPP program to find first non - repeating character using 1D array and one traversal . ; The function returns index of the first non - repeating character in a string . If all characters are repeating then returns INT_MAX ; Initialize all characters as absent . ; After below loop , the value of arr [ x ] is going to be index of of x if x appears only once . Else the value is going to be either - 1 or - 2. ; If this character occurs only once and appears before the current result , then update the result ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int firstNonRepeating ( char * str ) { int arr [ NO_OF_CHARS ] ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) arr [ i ] = -1 ; for ( int i = 0 ; str [ i ] ; i ++ ) { if ( arr [ str [ i ] ] == -1 ) arr [ str [ i ] ] = i ; else arr [ str [ i ] ] = -2 ; } int res = INT_MAX ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( arr [ i ] >= 0 ) res = min ( res , arr [ i ] ) ; return res ; } int main ( ) { char str [ ] = " geeksforgeeks " ; int index = firstNonRepeating ( str ) ; if ( index == INT_MAX ) cout << " Either ▁ all ▁ characters ▁ are ▁ " " repeating ▁ or ▁ string ▁ is ▁ empty " ; else cout << " First ▁ non - repeating ▁ character " " ▁ is ▁ " << str [ index ] ; return 0 ; }
Character replacement after removing duplicates from a string | C ++ program for character replacement after string minimization ; Function to minimize string ; duplicate characters are removed ; checks if character has previously occurred or not if not then add it to the minimized string ' mstr ' ; return mstr ; minimized string ; Utility function to print the minimized , replaced string ; Creating final string by replacing character ; index calculation ; cout << " Final ▁ string : ▁ " << finalStr ; final string ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string minimize ( string str ) { string mstr = " ▁ " ; int l , i , flagchar [ 26 ] = { 0 } ; char ch ; l = str . length ( ) ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { ch = str . at ( i ) ; if ( flagchar [ ch - 97 ] == 0 ) { mstr = mstr + ch ; flagchar [ ch - 97 ] = 1 ; } } } void replaceMinimizeUtil ( string str ) { string minimizedStr , finalStr = " " ; int i , index , l ; char ch ; l = str . length ( ) ; for ( i = 0 ; i < minimizedStr . length ( ) ; i ++ ) { ch = minimizedStr . at ( i ) ; index = ( ch * ch ) % l ; finalStr = finalStr + str . at ( index ) ; } } int main ( ) { string str = " geeks " ; replaceMinimizeUtil ( str ) ; return 0 ; }
Latin alphabet cipher | Latin Alphabet Cipher Encryption header files ; function for calculating the encryption ; driver code
#include <bits/stdc++.h> NEW_LINE void cipher ( char str [ ] ) { for ( int i = 0 ; str [ i ] != ' \0' ; i ++ ) { if ( isalpha ( str [ i ] ) == 0 && str [ i ] != ' ▁ ' ) { printf ( " Enter ▁ only ▁ alphabets ▁ and ▁ space STRNEWLINE " ) ; return ; } } printf ( " Encrypted ▁ Code ▁ using ▁ Latin ▁ Alphabet STRNEWLINE " ) ; for ( int i = 0 ; str [ i ] != ' \0' ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) printf ( " % d ▁ " , str [ i ] - ' A ' + 1 ) ; else if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) printf ( " % d ▁ " , str [ i ] - ' a ' + 1 ) ; if ( str [ i ] == ' ▁ ' ) printf ( " % c " , str [ i ] ) ; } printf ( " STRNEWLINE " ) ; } int main ( ) { char str [ ] = " geeksforgeeks " ; cipher ( str ) ; return 0 ; }
Count palindrome words in a sentence | C ++ program to count number of palindrome words in a sentence ; Function to check if a word is palindrome ; Function to count palindrome words ; to check last word for palindrome ; to store each word ; extracting each word ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkPalin ( string word ) { int n = word . length ( ) ; transform ( word . begin ( ) , word . end ( ) , word . begin ( ) , :: tolower ) ; for ( int i = 0 ; i < n ; i ++ , n -- ) if ( word . at ( i ) != word . at ( n - 1 ) ) return false ; return true ; } int countPalin ( string str ) { str = str + " ▁ " ; string word = " " ; int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str . at ( i ) ; if ( ch != ' ▁ ' ) word = word + ch ; else { if ( checkPalin ( word ) ) count ++ ; word = " " ; } } return count ; } int main ( ) { cout << countPalin ( " Madam ▁ Arora ▁ teaches ▁ malayalam " ) << endl ; cout << countPalin ( " Nitin ▁ speaks ▁ malayalam " ) << endl ; }
Remove the forbidden strings | CPP program to remove the forbidden strings ; pre [ ] keeps record of the characters of w that need to be changed ; number of forbidden strings ; given string ; stores the forbidden strings ; letter to replace and occur max number of times ; Function to check if the particula r substring is present in w at position ; If length of substring from this position is greater than length of w then return ; n and n1 are used to check for substring without considering the case of the letters in w by comparing the difference of ASCII values ; If same == true then it means a substring was found starting at position therefore all characters from position to length of substring found need to be changed therefore they needs to be marked ; Function implementing logic ; To verify if any substring is starting from index i ; Modifying the string w according to th rules ; This condition checks if w [ i ] = upper ( letter ) ; This condition checks if w [ i ] is any lowercase letter apart from letter . If true replace it with letter ; This condition checks if w [ i ] is any uppercase letter apart from letter . If true then replace it with upper ( letter ) . ; Driver function for the program ; Calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool pre [ 100 ] ; int n ; string w ; string s [ 110 ] ; char letter ; void verify ( int position , int index ) { int l = w . length ( ) ; int k = s [ index ] . length ( ) ; if ( position + k > l ) return ; bool same = true ; for ( int i = position ; i < position + k ; i ++ ) { int n , n1 ; char ch = w [ i ] ; char ch1 = s [ index ] [ i - position ] ; if ( ch >= ' a ' && ch <= ' z ' ) n = ch - ' a ' ; else n = ch - ' A ' ; if ( ch1 >= ' a ' && ch1 <= ' z ' ) n1 = ch1 - ' a ' ; else n1 = ch1 - ' A ' ; if ( n != n1 ) same = false ; } if ( same == true ) { for ( int i = position ; i < position + k ; i ++ ) pre [ i ] = true ; return ; } } void solve ( ) { int l = w . length ( ) ; int p = letter - ' a ' ; for ( int i = 0 ; i < 100 ; i ++ ) pre [ i ] = false ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) verify ( i , j ) ; } for ( int i = 0 ; i < l ; i ++ ) { if ( pre [ i ] == true ) { if ( w [ i ] == letter ) w [ i ] = ( letter == ' a ' ) ? ' b ' : ' a ' ; else if ( w [ i ] == ' A ' + p ) w [ i ] = ( letter == ' a ' ) ? ' B ' : ' A ' ; else if ( w [ i ] >= ' a ' && w [ i ] <= ' z ' ) w [ i ] = letter ; else if ( w [ i ] >= ' A ' && w [ i ] <= ' Z ' ) w [ i ] = ' A ' + p ; } } cout << w ; } int main ( ) { n = 3 ; s [ 0 ] = " etr " ; s [ 1 ] = " ed " ; s [ 2 ] = " ied " ; w = " PEtrUnited " ; letter = ' d ' ; solve ( ) ; return 0 ; }
Round the given number to nearest multiple of 10 | C ++ program to round the given integer to a whole number which ends with zero . ; function to round the number ; Smaller multiple ; Larger multiple ; Return of closest of two ; driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int round ( int n ) { int a = ( n / 10 ) * 10 ; int b = a + 10 ; return ( n - a > b - n ) ? b : a ; } int main ( ) { int n = 4722 ; cout << round ( n ) << endl ; return 0 ; }
Breaking a number such that first part is integral division of second by a power of 10 | c ++ function to count ways to divide a string in two parts a and b such that b / pow ( 10 , p ) == a ; substring representing int a ; no of digits in a ; consider only most significant l1 characters of remaining string for int b ; if any of a or b contains leading 0 s discard this combination ; if both are equal ; driver function to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculate ( string N ) { int len = N . length ( ) ; int l = ( len ) / 2 ; int count = 0 ; for ( int i = 1 ; i <= l ; i ++ ) { string s = N . substr ( 0 , i ) ; int l1 = s . length ( ) ; string t = N . substr ( i , l1 ) ; if ( s [ 0 ] == '0' t [ 0 ] == '0' ) continue ; if ( s . compare ( t ) == 0 ) count ++ ; } return count ; } int main ( ) { string N = "2202200" ; cout << calculate ( N ) ; return 0 ; }
Number of subsequences as " ab " in a string repeated K times | CPP code to find number of subsequences of " ab " in the string S which is repeated K times . ; Count of ' a ' s ; Count of ' b ' s ; occurrence of " ab " s in string S ; Add following two : 1 ) K * ( Occurrences of " ab " in single string ) 2 ) a is from one string and b is from other . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrences ( string s , int K ) { int n = s . length ( ) ; int C , c1 = 0 , c2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' ) c1 ++ ; if ( s [ i ] == ' b ' ) { c2 ++ ; C += c1 ; } } return C * K + ( K * ( K - 1 ) / 2 ) * c1 * c2 ; } int main ( ) { string S = " abcb " ; int k = 2 ; cout << countOccurrences ( S , k ) << endl ; return 0 ; }
Program to check Strength of Password | C ++ program to check if a given password is strong or not . ; Checking lower alphabet in string ; Strength of password ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printStrongNess ( string & input ) { int n = input . length ( ) ; bool hasLower = false , hasUpper = false ; bool hasDigit = false , specialChar = false ; string normalChars = " abcdefghijklmnopqrstu " " vwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ▁ " ; for ( int i = 0 ; i < n ; i ++ ) { if ( islower ( input [ i ] ) ) hasLower = true ; if ( isupper ( input [ i ] ) ) hasUpper = true ; if ( isdigit ( input [ i ] ) ) hasDigit = true ; size_t special = input . find_first_not_of ( normalChars ) ; if ( special != string :: npos ) specialChar = true ; } cout << " Strength ▁ of ▁ password : - " ; if ( hasLower && hasUpper && hasDigit && specialChar && ( n >= 8 ) ) cout << " Strong " << endl ; else if ( ( hasLower hasUpper ) && specialChar && ( n >= 6 ) ) cout << " Moderate " << endl ; else cout << " Weak " << endl ; } int main ( ) { string input = " GeeksforGeeks ! @12" ; printStrongNess ( input ) ; return 0 ; }
String with k distinct characters and no same characters adjacent | CPP program to construct a n length string with k distinct characters such that no two same characters are adjacent . ; Function to find a string of length n with k distinct characters . ; Initialize result with first k Latin letters ; Fill remaining n - k letters by repeating k letters again and again . ; Driver code
#include <iostream> NEW_LINE using namespace std ; string findString ( int n , int k ) { string res = " " ; for ( int i = 0 ; i < k ; i ++ ) res = res + ( char ) ( ' a ' + i ) ; int count = 0 ; for ( int i = 0 ; i < n - k ; i ++ ) { res = res + ( char ) ( ' a ' + count ) ; count ++ ; if ( count == k ) count = 0 ; } return res ; } int main ( ) { int n = 5 , k = 2 ; cout << findString ( n , k ) ; return 0 ; }
Program for credit card number validation | C ++ program to check if a given credit card is valid or not . ; Return this number if it is a single digit , otherwise , return the sum of the two digits ; Return the number of digits in d ; Return the first k number of digits from number . If the number of digits in number is less than k , return number . ; Return true if the digit d is a prefix for number ; Get the result from Step 2 ; Return sum of odd - place digits in number ; Return true if the card number is valid ; Driver Code
#include <iostream> NEW_LINE using namespace std ; int getDigit ( int number ) { if ( number < 9 ) return number ; return number / 10 + number % 10 ; } int getSize ( long d ) { string num = to_string ( d ) ; return num . length ( ) ; } long getPrefix ( long number , int k ) { if ( getSize ( number ) > k ) { string num = to_string ( number ) ; return stol ( num . substr ( 0 , k ) ) ; } return number ; } bool prefixMatched ( long number , int d ) { return getPrefix ( number , getSize ( d ) ) == d ; } int sumOfDoubleEvenPlace ( long int number ) { int sum = 0 ; string num = to_string ( number ) ; for ( int i = getSize ( number ) - 2 ; i >= 0 ; i -= 2 ) sum += getDigit ( int ( num [ i ] - '0' ) * 2 ) ; return sum ; } int sumOfOddPlace ( long number ) { int sum = 0 ; string num = to_string ( number ) ; for ( int i = getSize ( number ) - 1 ; i >= 0 ; i -= 2 ) sum += num [ i ] - '0' ; return sum ; } bool isValid ( long int number ) { return ( getSize ( number ) >= 13 && getSize ( number ) <= 16 ) && ( prefixMatched ( number , 4 ) || prefixMatched ( number , 5 ) || prefixMatched ( number , 37 ) || prefixMatched ( number , 6 ) ) && ( ( sumOfDoubleEvenPlace ( number ) + sumOfOddPlace ( number ) ) % 10 == 0 ) ; } int main ( ) { long int number = 5196081888500645L ; cout << number << " ▁ is ▁ " << ( isValid ( number ) ? " valid " : " invalid " ) ; return 0 ; }
Find substrings that contain all vowels | C ++ program to find all substring that contain all vowels ; Returns true if x is vowel . ; Function to check whether a character is vowel or not ; Function to FindSubstrings of string ; set < char > hash ; To store vowels ; If current character is vowel then insert into hash , ; If all vowels are present in current substring ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char x ) { return ( x == ' a ' x == ' e ' x == ' i ' x == ' o ' x == ' u ' ) ; } void FindSubstring ( string str ) { int start = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( isVowel ( str [ i ] ) == true ) { hash . insert ( str [ i ] ) ; if ( hash . size ( ) == 5 ) cout << str . substr ( start , i - start + 1 ) << " ▁ " ; } else { start = i + 1 ; hash . clear ( ) ; } } } int main ( ) { string str = " aeoibsddaeiouudb " ; FindSubstring ( str ) ; return 0 ; }
Concatenated string with uncommon characters of two strings | C ++ program Find concatenated string with uncommon characters of given strings ; store all characters of s2 in map ; Find characters of s1 that are not present in s2 and append to result ; Find characters of s2 that are not present in s1 . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string concatenetedString ( string s1 , string s2 ) { unordered_map < char , int > m ; for ( int i = 0 ; i < s2 . size ( ) ; i ++ ) m [ s2 [ i ] ] = 1 ; for ( int i = 0 ; i < s1 . size ( ) ; i ++ ) { if ( m . find ( s1 [ i ] ) == m . end ( ) ) res += s1 [ i ] ; else m [ s1 [ i ] ] = 2 ; } for ( int i = 0 ; i < s2 . size ( ) ; i ++ ) if ( m [ s2 [ i ] ] == 1 ) res += s2 [ i ] ; return res ; } int main ( ) { string s1 = " abcs " ; string s2 = " cxzca " ; cout << concatenetedString ( s1 , s2 ) ; return 0 ; }
Print all Subsequences of String which Start with Vowel and End with Consonant . | C ++ program to generate all the subse - quence starting with vowel and ending with consonant . ; Set to store all the subsequences ; Utility method to check vowel ; Utility method to check consonant ; It computes all the possible substring that starts with vowel and end with consonent ; iterate over the entire string ; test ith character for vowel ; if the ith character is vowel iterate from end of the string and check for consonant . ; test jth character for consonant . ; once we get a consonant add it to the hashset ; drop each character of the substring and recur to generate all subsequence of the substring ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; set < string > st ; bool isVowel ( char c ) { return ( c == ' a ' or c == ' e ' or c == ' i ' or c == ' o ' or c == ' u ' ) ; } bool isConsonant ( char c ) { return ! isVowel ( c ) ; } void subsequence ( string str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( isVowel ( str [ i ] ) ) { for ( int j = str . length ( ) - 1 ; j >= i ; j -- ) { if ( isConsonant ( str [ j ] ) ) { string str_sub = str . substr ( i , j + 1 ) ; st . insert ( str_sub ) ; for ( int k = 1 ; k < str_sub . length ( ) - 1 ; k ++ ) { string sb = str_sub ; sb . erase ( sb . begin ( ) + k ) ; subsequence ( sb ) ; } } } } } } int main ( ) { string s = " xabcef " ; subsequence ( s ) ; for ( auto i : st ) cout << i << " ▁ " ; cout << endl ; return 0 ; }
Null Cipher | CPP program to decode NULL CIPHER ; Store the decoded string . ; found variable is used to tell that the encoded encoded character is found in that particular word . ; Set found variable to false whenever we find whitespace , meaning that encoded character for new word is not found ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decode ( string str ) { string res = " " ; bool found = false ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) { if ( str [ i ] == ' ▁ ' ) { found = false ; continue ; } if ( ! found ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { res += str [ i ] + 32 ; found = true ; } else if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { res += str [ i ] ; found = true ; } } } return res ; } int main ( ) { string in ; in = " A ▁ Step ▁ by ▁ Step ▁ Guide ▁ for ▁ Placement ▁ Preparation ▁ by ▁ GeeksforGeeks " ; cout << " Enciphered ▁ Message : ▁ " ; cout << decode ( in ) << endl ; return 0 ; }
Program to count vowels in a string ( Iterative and Recursive ) | Recursive C ++ program to count the total number of vowels using recursion ; Function to check the Vowel ; to count total number of vowel from 0 to n ; Main Calling Function ; string object ; Total numbers of Vowel
#include <iostream> NEW_LINE using namespace std ; bool isVowel ( char ch ) { ch = toupper ( ch ) ; return ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) ; } int countVovels ( string str , int n ) { if ( n == 1 ) return isVowel ( str [ n - 1 ] ) ; return countVovels ( str , n - 1 ) + isVowel ( str [ n - 1 ] ) ; } int main ( ) { string str = " abc ▁ de " ; cout << countVovels ( str , str . length ( ) ) << endl ; return 0 ; }
Smallest window that contains all characters of string itself | C ++ program to find the smallest window containing all characters of a pattern . ; Function to find smallest window containing all distinct characters ; Count all distinct characters . ; Now follow the algorithm discussed in below ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHARS = 256 ; string findSubString ( string str ) { int n = str . length ( ) ; int dist_count = 0 ; unordered_map < int , int > hash_map ; for ( int i = 0 ; i < n ; i ++ ) { hash_map [ str [ i ] ] ++ ; } dist_count = hash_map . size ( ) ; int size = INT_MAX ; string res ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int visited [ 256 ] = { 0 } ; string sub_str = " " ; for ( int j = i ; j < n ; j ++ ) { if ( visited [ str [ j ] ] == 0 ) { count ++ ; visited [ str [ j ] ] = 1 ; } sub_str += str [ j ] ; if ( count == dist_count ) break ; } if ( sub_str . length ( ) < size && count == dist_count ) { res = sub_str ; size = res . length ( ) ; } } return res ; } int main ( ) { string str = " aabcbcdbca " ; cout << " Smallest ▁ window ▁ containing ▁ all ▁ distinct " " ▁ characters ▁ is : ▁ " << findSubString ( str ) ; return 0 ; }
Generate all rotations of a given string | An efficient C ++ program to print all rotations of a string . ; Print all the rotated string . ; Concatenate str with itself ; Print all substrings of size n . Note that size of temp is 2 n ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printRotatedString ( char str [ ] ) { int n = strlen ( str ) ; char temp [ 2 * n + 1 ] ; strcpy ( temp , str ) ; strcat ( temp , str ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j != n ; j ++ ) printf ( " % c " , temp [ i + j ] ) ; printf ( " STRNEWLINE " ) ; } } int main ( ) { char str [ ] = " geeks " ; printRotatedString ( str ) ; return 0 ; }
Check if frequency of all characters can become same by one removal | C ++ program to get same frequency character string by removal of at most one char ; Utility method to get index of character ch in lower alphabet characters ; Returns true if all non - zero elements values are same ; get first non - zero element ; check equality of each element with variable same ; Returns true if we can make all character frequencies same ; fill frequency array ; if all frequencies are same , then return true ; Try decreasing frequency of all character by one and then check all equality of all non - zero frequencies ; Check character only if it occurs in str ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 26 NEW_LINE int getIdx ( char ch ) { return ( ch - ' a ' ) ; } bool allSame ( int freq [ ] , int N ) { int same ; int i ; for ( i = 0 ; i < N ; i ++ ) { if ( freq [ i ] > 0 ) { same = freq [ i ] ; break ; } } for ( int j = i + 1 ; j < N ; j ++ ) if ( freq [ j ] > 0 && freq [ j ] != same ) return false ; return true ; } bool possibleSameCharFreqByOneRemoval ( string str ) { int l = str . length ( ) ; int freq [ M ] = { 0 } ; for ( int i = 0 ; i < l ; i ++ ) freq [ getIdx ( str [ i ] ) ] ++ ; if ( allSame ( freq , M ) ) return true ; for ( char c = ' a ' ; c <= ' z ' ; c ++ ) { int i = getIdx ( c ) ; if ( freq [ i ] > 0 ) { freq [ i ] -- ; if ( allSame ( freq , M ) ) return true ; freq [ i ] ++ ; } } return false ; } int main ( ) { string str = " xyyzz " ; if ( possibleSameCharFreqByOneRemoval ( str ) ) cout << " Yes " ; else cout << " No " ; }
Check if a large number is divisible by 11 or not | C ++ program to find if a number is divisible by 11 or not ; Function to find that number divisible by 11 or not ; Compute sum of even and odd digit sums ; When i is even , position of digit is odd ; Check its difference is divisible by 11 or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( string str ) { int n = str . length ( ) ; int oddDigSum = 0 , evenDigSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) oddDigSum += ( str [ i ] - '0' ) ; else evenDigSum += ( str [ i ] - '0' ) ; } return ( ( oddDigSum - evenDigSum ) % 11 == 0 ) ; } int main ( ) { string str = "76945" ; check ( str ) ? cout << " Yes " : cout << " No ▁ " ; return 0 ; }
Palindrome pair in an array of words ( or strings ) | C ++ program to check if there is a pair that of above method using Trie ; Alphabet size ( # of symbols ) ; Converts key current character into index use only ' a ' through ' z ' and lower case ; Trie node ; vector < int > pos ; To store palindromic positions in str ; isLeaf is true if the node represents end of a word ; Returns new Trie node ( initialized to NULLs ) ; Utility function to check if a string is a palindrome ; compare each character from starting with its corresponding character from last ; If not present , inserts reverse of key into Trie . If the key is prefix of a Trie node , just mark leaf node ; Start traversing word from the last ; If it is not available in Trie , then store it ; If current word is palindrome till this level , store index of current word . ; mark last node as leaf ; Returns true if key presents in Trie , else false ; If it is present also check upto which index it is palindrome ; If not present then return ; Function to check if a palindrome pair exists ; Construct trie ; Search for different keys ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ARRAY_SIZE ( a ) sizeof(a)/sizeof(a[0]) NEW_LINE #define ALPHABET_SIZE (26) NEW_LINE #define CHAR_TO_INDEX ( c ) ((int)c - (int)'a') NEW_LINE struct TrieNode { struct TrieNode * children [ ALPHABET_SIZE ] ; int id ; bool isLeaf ; } ; struct TrieNode * getNode ( void ) { struct TrieNode * pNode = new TrieNode ; pNode -> isLeaf = false ; for ( int i = 0 ; i < ALPHABET_SIZE ; i ++ ) pNode -> children [ i ] = NULL ; return pNode ; } bool isPalindrome ( string str , int i , int len ) { while ( i < len ) { if ( str [ i ] != str [ len ] ) return false ; i ++ , len -- ; } return true ; } void insert ( struct TrieNode * root , string key , int id ) { struct TrieNode * pCrawl = root ; for ( int level = key . length ( ) - 1 ; level >= 0 ; level -- ) { int index = CHAR_TO_INDEX ( key [ level ] ) ; if ( ! pCrawl -> children [ index ] ) pCrawl -> children [ index ] = getNode ( ) ; if ( isPalindrome ( key , 0 , level ) ) ( pCrawl -> pos ) . push_back ( id ) ; pCrawl = pCrawl -> children [ index ] ; } pCrawl -> id = id ; pCrawl -> pos . push_back ( id ) ; pCrawl -> isLeaf = true ; } void search ( struct TrieNode * root , string key , int id , vector < vector < int > > & result ) { struct TrieNode * pCrawl = root ; for ( int level = 0 ; level < key . length ( ) ; level ++ ) { int index = CHAR_TO_INDEX ( key [ level ] ) ; if ( pCrawl -> id >= 0 && pCrawl -> id != id && isPalindrome ( key , level , key . size ( ) - 1 ) ) result . push_back ( { id , pCrawl -> id } ) ; if ( ! pCrawl -> children [ index ] ) return ; pCrawl = pCrawl -> children [ index ] ; } for ( int i : pCrawl -> pos ) { if ( i == id ) continue ; result . push_back ( { id , i } ) ; } } bool checkPalindromePair ( vector < string > vect ) { struct TrieNode * root = getNode ( ) ; for ( int i = 0 ; i < vect . size ( ) ; i ++ ) insert ( root , vect [ i ] , i ) ; vector < vector < int > > result ; for ( int i = 0 ; i < vect . size ( ) ; i ++ ) { search ( root , vect [ i ] , i , result ) ; if ( result . size ( ) > 0 ) return true ; } return false ; } int main ( ) { vector < string > vect = { " geekf " , " geeks " , " or " , " keeg " , " abc " , " bc " } ; checkPalindromePair ( vect ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Hamming Distance between two strings | C ++ program to find hamming distance b / w two string ; function to calculate Hamming distance ; driver code ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int hammingDist ( char * str1 , char * str2 ) { int i = 0 , count = 0 ; while ( str1 [ i ] != ' \0' ) { if ( str1 [ i ] != str2 [ i ] ) count ++ ; i ++ ; } return count ; } int main ( ) { char str1 [ ] = " geekspractice " ; char str2 [ ] = " nerdspractise " ; cout << hammingDist ( str1 , str2 ) ; return 0 ; }
Check if two strings are k | C ++ program to check if two strings are k anagram or not . ; Function to check that string is k - anagram or not ; If both strings are not of equal length then return false ; Store the occurrence of all characters in a hash_array ; Count number of characters that are different in both strings ; Return true if count is less than or equal to k ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool arekAnagrams ( string str1 , string str2 , int k ) { int n = str1 . length ( ) ; if ( str2 . length ( ) != n ) return false ; int count1 [ MAX_CHAR ] = { 0 } ; int count2 [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count1 [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) count2 [ str2 [ i ] - ' a ' ] ++ ; int count = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( count1 [ i ] > count2 [ i ] ) count = count + abs ( count1 [ i ] - count2 [ i ] ) ; return ( count <= k ) ; } int main ( ) { string str1 = " anagram " ; string str2 = " grammar " ; int k = 2 ; if ( arekAnagrams ( str1 , str2 , k ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Remove spaces from a given string | An efficient C ++ program to remove all spaces from a string ; Function to remove all spaces from a given string ; To keep track of non - space character count ; Traverse the given string . If current character is not space , then place it at index ' count + + ' ; str [ count ++ ] = str [ i ] ; here count is incremented ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; void removeSpaces ( char * str ) { int count = 0 ; for ( int i = 0 ; str [ i ] ; i ++ ) if ( str [ i ] != ' ▁ ' ) str [ count ] = ' \0' ; } int main ( ) { char str [ ] = " g ▁ eeks ▁ for ▁ ge ▁ eeks ▁ " ; removeSpaces ( str ) ; cout << str ; return 0 ; }
Given a binary string , count number of substrings that start and end with 1. | A O ( n ) C ++ program to count number of substrings starting and ending with 1 ; Traverse input string and count of 1 's in it ; Return count of possible pairs among m 1 's ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int countSubStr ( char str [ ] ) { for ( int i = 0 ; str [ i ] != ' \0' ; i ++ ) { if ( str [ i ] == '1' ) m ++ ; } return m * ( m - 1 ) / 2 ; } int main ( ) { char str [ ] = "00100101" ; cout << countSubStr ( str ) ; return 0 ; }
Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | C ++ program to count substrings with recursive sum equal to 9 ; int count = 0 ; To store result ; Consider every character as beginning of substring ; int sum = number [ i ] - '0' ; sum of digits in current substring ; One by one choose every character as an ending character ; Add current digit to sum , if sum becomes multiple of 5 then increment count . Let us do modular arithmetic to avoid overflow for big strings ; driver program to test above function
#include <iostream> NEW_LINE #include <cstring> NEW_LINE using namespace std ; int count9s ( char number [ ] ) { int n = strlen ( number ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( number [ i ] == '9' ) count ++ ; for ( int j = i + 1 ; j < n ; j ++ ) { sum = ( sum + number [ j ] - '0' ) % 9 ; if ( sum == 0 ) count ++ ; } } return count ; } int main ( ) { cout << count9s ( "4189" ) << endl ; cout << count9s ( "1809" ) ; return 0 ; }
Generate n | C ++ program to generate n - bit Gray codes ; This function generates all n bit Gray codes and prints the generated codes ; base case ; ' arr ' will store all generated codes ; start with one - bit pattern ; Every iteration of this loop generates 2 * i codes from previously generated i codes . ; Enter the prviously generated codes again in arr [ ] in reverse order . Nor arr [ ] has double number of codes . ; append 0 to the first half ; append 1 to the second half ; print contents of arr [ ] ; Driver program to test above function
#include <iostream> NEW_LINE #include <string> NEW_LINE #include <vector> NEW_LINE using namespace std ; void generateGrayarr ( int n ) { if ( n <= 0 ) return ; vector < string > arr ; arr . push_back ( "0" ) ; arr . push_back ( "1" ) ; int i , j ; for ( i = 2 ; i < ( 1 << n ) ; i = i << 1 ) { for ( j = i - 1 ; j >= 0 ; j -- ) arr . push_back ( arr [ j ] ) ; for ( j = 0 ; j < i ; j ++ ) arr [ j ] = "0" + arr [ j ] ; for ( j = i ; j < 2 * i ; j ++ ) arr [ j ] = "1" + arr [ j ] ; } for ( i = 0 ; i < arr . size ( ) ; i ++ ) cout << arr [ i ] << endl ; } int main ( ) { generateGrayarr ( 3 ) ; return 0 ; }
Divide a string in N equal parts | if ( start < str . length ( ) ) cout << endl ; to ignore final new line
#include <iostream> NEW_LINE using namespace std ; void divide ( string str , int n ) { if ( str . length ( ) % n != 0 ) { cout << " Invalid ▁ Input : ▁ String ▁ size " ; cout << " ▁ is ▁ not ▁ divisible ▁ by ▁ n " ; return ; } int parts = str . length ( ) / n ; int start = 0 ; while ( start < str . length ( ) ) { cout << str . substr ( start , parts ) << endl ; start += parts ; } } int main ( ) { string str = " a _ simple _ divide _ string _ quest " ; divide ( str , 4 ) ; }
Least count of words required to construct a target String | C ++ program of the above approach ; countMap [ ] [ ] to store count of characters ; Function to get minimum number of stickers for a particular state ; If an optimal solution is already there , return ; If Target has been constructed update cnt and return ; Update charAvailable [ ] ; Recursizevely function call for ( pos + 1 ) ; Update charAvailable [ ] ; Update charAvailable [ ] ; Recursizeve Call ; Update charAvailable [ ] ; Function to find the minimum number of stickers ; Base Case ; Fill the countMap Array ; Recusizeve function call to get minimum number of stickers ; Driver Code ; Given Input ; Function Call ; Print the result
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > countMap ; int cnt = INT_MAX ; void count ( int curCnt , int pos , vector < int > charAvailable , string target , vector < string > stickers ) { if ( curCnt >= cnt ) return ; int m = stickers . size ( ) ; int n = target . size ( ) ; if ( pos == n ) { cnt = min ( cnt , curCnt ) ; return ; } char c = target [ pos ] ; if ( charAvailable > 0 ) { charAvailable -- ; count ( curCnt , pos + 1 , charAvailable , target , stickers ) ; charAvailable ++ ; } else { for ( int i = 0 ; i < m ; i ++ ) { if ( countMap [ i ] == 0 ) continue ; for ( int j = 0 ; j < 26 ; j ++ ) { charAvailable [ j ] += countMap [ i ] [ j ] ; } count ( curCnt + 1 , pos , charAvailable , target , stickers ) ; for ( int j = 0 ; j < 26 ; j ++ ) { charAvailable [ j ] -= countMap [ i ] [ j ] ; } } } } int minStickers ( vector < string > stickers , string target ) { if ( target == " " ) return -1 ; if ( target . size ( ) == 0 ) return 0 ; if ( stickers . size ( ) == 0 ) return -1 ; int m = stickers . size ( ) ; countMap . resize ( m , vector < int > ( 26 , 0 ) ) ; for ( int i = 0 ; i < stickers . size ( ) ; i ++ ) { string s = stickers [ i ] ; for ( char c : s ) { countMap [ i ] ++ ; } } vector < int > temp ( 26 ) ; count ( 0 , 0 , temp , target , stickers ) ; return cnt == INT_MAX ? -1 : cnt ; } int main ( ) { vector < string > str = { " with " , " example " , " science " } ; string target = " thehat " ; int Result = minStickers ( str , target ) ; cout << Result ; }
Rat in a Maze Problem when movement in all possible directions is allowed | C ++ implementation of the above approach ; Function returns true if the move taken is valid else it will return false . ; Function to print all the possible paths from ( 0 , 0 ) to ( n - 1 , n - 1 ) . ; This will check the initial point ( i . e . ( 0 , 0 ) ) to start the paths . ; If reach the last cell ( n - 1 , n - 1 ) then store the path and return ; Mark the cell as visited ; Check if downward move is valid ; Check if the left move is valid ; Check if the right move is valid ; Check if the upper move is valid ; Mark the cell as unvisited for other possible paths ; Function to store and print all the valid paths ; vector to store all the possible paths ; Call the utility function to find the valid paths ; Print all possible paths ; Driver code
#include <bits/stdc++.h> NEW_LINE #define MAX 5 NEW_LINE using namespace std ; bool isSafe ( int row , int col , int m [ ] [ MAX ] , int n , bool visited [ ] [ MAX ] ) { if ( row == -1 row == n col == -1 col == n visited [ row ] [ col ] m [ row ] [ col ] == 0 ) return false ; return true ; } void printPathUtil ( int row , int col , int m [ ] [ MAX ] , int n , string & path , vector < string > & possiblePaths , bool visited [ ] [ MAX ] ) { if ( row == -1 row == n col == -1 col == n visited [ row ] [ col ] m [ row ] [ col ] == 0 ) return ; if ( row == n - 1 && col == n - 1 ) { possiblePaths . push_back ( path ) ; return ; } visited [ row ] [ col ] = true ; if ( isSafe ( row + 1 , col , m , n , visited ) ) { path . push_back ( ' D ' ) ; printPathUtil ( row + 1 , col , m , n , path , possiblePaths , visited ) ; path . pop_back ( ) ; } if ( isSafe ( row , col - 1 , m , n , visited ) ) { path . push_back ( ' L ' ) ; printPathUtil ( row , col - 1 , m , n , path , possiblePaths , visited ) ; path . pop_back ( ) ; } if ( isSafe ( row , col + 1 , m , n , visited ) ) { path . push_back ( ' R ' ) ; printPathUtil ( row , col + 1 , m , n , path , possiblePaths , visited ) ; path . pop_back ( ) ; } if ( isSafe ( row - 1 , col , m , n , visited ) ) { path . push_back ( ' U ' ) ; printPathUtil ( row - 1 , col , m , n , path , possiblePaths , visited ) ; path . pop_back ( ) ; } visited [ row ] [ col ] = false ; } void printPath ( int m [ MAX ] [ MAX ] , int n ) { vector < string > possiblePaths ; string path ; bool visited [ n ] [ MAX ] ; memset ( visited , false , sizeof ( visited ) ) ; printPathUtil ( 0 , 0 , m , n , path , possiblePaths , visited ) ; for ( int i = 0 ; i < possiblePaths . size ( ) ; i ++ ) cout << possiblePaths [ i ] << " ▁ " ; } int main ( ) { int m [ MAX ] [ MAX ] = { { 1 , 0 , 0 , 0 , 0 } , { 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 1 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 } , { 0 , 0 , 0 , 0 , 1 } } ; int n = sizeof ( m ) / sizeof ( m [ 0 ] ) ; printPath ( m , n ) ; return 0 ; }
N Queen in O ( n ) space | CPP code to for n Queen placement ; Function to check queens placement ; Helper Function to check if queen can be placed ; Function to display placed queen ; Driver Code
#include <bits/stdc++.h> NEW_LINE #define breakLine cout << " NEW_LINE -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - " #define MAX 10 using namespace std ; int arr [ MAX ] , no ; void nQueens ( int k , int n ) ; bool canPlace ( int k , int i ) ; void display ( int n ) ; void nQueens ( int k , int n ) { for ( int i = 1 ; i <= n ; i ++ ) { if ( canPlace ( k , i ) ) { arr [ k ] = i ; if ( k == n ) display ( n ) ; else nQueens ( k + 1 , n ) ; } } } bool canPlace ( int k , int i ) { for ( int j = 1 ; j <= k - 1 ; j ++ ) { if ( arr [ j ] == i || ( abs ( arr [ j ] - i ) == abs ( j - k ) ) ) return false ; } return true ; } void display ( int n ) { breakLine cout < < " Arrangement ▁ No . ▁ " << ++ no ; breakLine for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 1 ; j <= n ; j ++ ) { if ( arr [ i ] != j ) cout << " TABSYMBOL _ " ; else cout << " TABSYMBOL Q " ; } cout << endl ; } breakLine } int main ( ) { int n = 4 ; nQueens ( 1 , n ) ; return 0 ; }
Longest Possible Route in a Matrix with Hurdles | C ++ program to find Longest Possible Route in a matrix with hurdles ; A Pair to store status of a cell . found is set to true of destination is reachable and value stores distance of longest path ; true if destination is found ; stores cost of longest path from current cell to destination cell ; Function to find Longest Possible Route in the matrix with hurdles . If the destination is not reachable the function returns false with cost INT_MAX . ( i , j ) is source cell and ( x , y ) is destination cell . ; if ( i , j ) itself is destination , return true ; if not a valid cell , return false ; include ( i , j ) in current path i . e . set visited ( i , j ) to true ; res stores longest path from current cell ( i , j ) to destination cell ( x , y ) ; go left from current cell ; if destination can be reached on going left from current cell , update res ; go right from current cell ; if destination can be reached on going right from current cell , update res ; go up from current cell ; if destination can be reached on going up from current cell , update res ; go down from current cell ; if destination can be reached on going down from current cell , update res ; Backtrack ; if destination can be reached from current cell , return true ; if destination can 't be reached from current cell, return false ; A wrapper function over findLongestPathUtil ( ) ; create a boolean matrix to store info about cells already visited in current route ; initialize visited to false ; find longest route from ( i , j ) to ( x , y ) and print its maximum cost ; If the destination is not reachable ; Driver code ; input matrix with hurdles shown with number 0 ; find longest path with source ( 0 , 0 ) and destination ( 1 , 7 )
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define R 3 NEW_LINE #define C 10 NEW_LINE struct Pair { bool found ; int value ; } ; Pair findLongestPathUtil ( int mat [ R ] [ C ] , int i , int j , int x , int y , bool visited [ R ] [ C ] ) { if ( i == x && j == y ) { Pair p = { true , 0 } ; return p ; } if ( i < 0 i > = R j < 0 j > = C mat [ i ] [ j ] == 0 visited [ i ] [ j ] ) { Pair p = { false , INT_MAX } ; return p ; } visited [ i ] [ j ] = true ; int res = INT_MIN ; Pair sol = findLongestPathUtil ( mat , i , j - 1 , x , y , visited ) ; if ( sol . found ) res = max ( res , sol . value ) ; sol = findLongestPathUtil ( mat , i , j + 1 , x , y , visited ) ; if ( sol . found ) res = max ( res , sol . value ) ; sol = findLongestPathUtil ( mat , i - 1 , j , x , y , visited ) ; if ( sol . found ) res = max ( res , sol . value ) ; sol = findLongestPathUtil ( mat , i + 1 , j , x , y , visited ) ; if ( sol . found ) res = max ( res , sol . value ) ; visited [ i ] [ j ] = false ; if ( res != INT_MIN ) { Pair p = { true , 1 + res } ; return p ; } else { Pair p = { false , INT_MAX } ; return p ; } } void findLongestPath ( int mat [ R ] [ C ] , int i , int j , int x , int y ) { bool visited [ R ] [ C ] ; memset ( visited , false , sizeof visited ) ; Pair p = findLongestPathUtil ( mat , i , j , x , y , visited ) ; if ( p . found ) cout << " Length ▁ of ▁ longest ▁ possible ▁ route ▁ is ▁ " << p . value ; else cout << " Destination ▁ not ▁ reachable ▁ from ▁ given ▁ " " source " ; } int main ( ) { int mat [ R ] [ C ] = { { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } , { 1 , 1 , 0 , 1 , 1 , 0 , 1 , 1 , 0 , 1 } , { 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 } } ; findLongestPath ( mat , 0 , 0 , 1 , 7 ) ; return 0 ; }
Numbers that are bitwise AND of at least one non | C ++ implementation of the approach ; Set to store all possible AND values . ; Starting index of the sub - array . ; Ending index of the sub - array . ; AND value is added to the set . ; The set contains all possible AND values .
#include <bits/stdc++.h> NEW_LINE using namespace std ; int main ( ) { int A [ ] = { 11 , 15 , 7 , 19 } ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; unordered_set < int > s ; int i , j , res ; for ( i = 0 ; i < N ; ++ i ) for ( j = i , res = INT_MAX ; j < N ; ++ j ) { res &= A [ j ] ; s . insert ( res ) ; } for ( int i : s ) cout << i << " ▁ " ; return 0 ; }
Sudo Placement | Range Queries | CPP program to find the numbers having atmost 3 set bits within a given range ; This function prints the required answer for each query ; Set of Numbers having at most 3 set bits arranged in non - descending order ; 0 set bits ; Iterate over all possible combinations of i , j and k for 60 bits ; 1 set bit ; 2 set bits ; 3 set bits ; Answer Queries by applying binary search ; Swap both the numbers if L is greater than R ; Driver Code ; Number of Queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define LL long long int NEW_LINE void answerQueries ( LL Q , vector < pair < LL , LL > > query ) { set < LL > s ; s . insert ( 0 ) ; for ( int i = 0 ; i <= 60 ; i ++ ) { for ( int j = i ; j <= 60 ; j ++ ) { for ( int k = j ; k <= 60 ; k ++ ) { if ( j == i && i == k ) s . insert ( 1LL << i ) ; else if ( j == k && i != j ) { LL x = ( 1LL << i ) + ( 1LL << j ) ; s . insert ( x ) ; } else if ( i == j && i != k ) { LL x = ( 1LL << i ) + ( 1LL << k ) ; s . insert ( x ) ; } else if ( i == k && i != j ) { LL x = ( 1LL << k ) + ( 1LL << j ) ; s . insert ( x ) ; } else { LL x = ( 1LL << i ) + ( 1LL << j ) + ( 1LL << k ) ; s . insert ( x ) ; } } } } vector < LL > validNumbers ; for ( auto val : s ) validNumbers . push_back ( val ) ; for ( int i = 0 ; i < Q ; i ++ ) { LL L = query [ i ] . first ; LL R = query [ i ] . second ; if ( R < L ) swap ( L , R ) ; if ( L == 0 ) cout << ( upper_bound ( validNumbers . begin ( ) , validNumbers . end ( ) , R ) - validNumbers . begin ( ) ) << endl ; else cout << ( upper_bound ( validNumbers . begin ( ) , validNumbers . end ( ) , R ) - upper_bound ( validNumbers . begin ( ) , validNumbers . end ( ) , L - 1 ) ) << endl ; } } int main ( ) { int Q = 2 ; vector < pair < LL , LL > > query ( Q ) ; query [ 0 ] . first = 3 ; query [ 0 ] . second = 7 ; query [ 1 ] . first = 10 ; query [ 1 ] . second = 16 ; answerQueries ( Q , query ) ; return 0 ; }
Collect all coins in minimum number of steps | C ++ program to find minimum number of steps to collect stack of coins ; recursive method to collect coins from height array l to r , with height h already collected ; if l is more than r , no steps needed ; loop over heights to get minimum height index ; choose minimum from , 1 ) collecting coins using all vertical lines ( total r - l ) 2 ) collecting coins using lower horizontal lines and recursively on left and right segments ; method returns minimum number of step to collect coin from stack , with height in height [ ] array ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minStepsRecur ( int height [ ] , int l , int r , int h ) { if ( l >= r ) return 0 ; int m = l ; for ( int i = l ; i < r ; i ++ ) if ( height [ i ] < height [ m ] ) m = i ; return min ( r - l , minStepsRecur ( height , l , m , height [ m ] ) + minStepsRecur ( height , m + 1 , r , height [ m ] ) + height [ m ] - h ) ; } int minSteps ( int height [ ] , int N ) { return minStepsRecur ( height , 0 , N , 0 ) ; } int main ( ) { int height [ ] = { 2 , 1 , 2 , 5 , 1 } ; int N = sizeof ( height ) / sizeof ( int ) ; cout << minSteps ( height , N ) << endl ; return 0 ; }
Count of Unique Direct Path Between N Points On a Plane | C ++ program for the above approach ; Function to count the total number of direct paths ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDirectPath ( int N ) { return N + ( N * ( N - 3 ) ) / 2 ; } int main ( ) { int N = 5 ; cout << countDirectPath ( N ) ; return 0 ; }
Find the coordinate that does not belong to any square | C ++ program for the above approach ; Function to find the point that is not a part of the side of a square ; Traverse each pair of coordinates ; Minimize x - coordinate in all the points except current point ; Maximize x - coordinate in all the points except the current point ; Minimize y - coordinate in all the points except current point ; Maximize y - coordinate in all the points except current point ; If x - coordinate matches with other same line ; If y coordinate matches with other same line ; Check if the condition for square exists or not ; Print the output ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; #define fi first NEW_LINE #define se second NEW_LINE void findPoint ( int n , vector < pair < int , int > > p ) { for ( int i = 0 ; i < n * 4 + 1 ; ++ i ) { int x1 = 2e9 , x2 = -2e9 ; int y1 = 2e9 , y2 = -2e9 ; for ( int j = 0 ; j < n * 4 + 1 ; ++ j ) if ( i != j ) { x1 = min ( x1 , p [ j ] . fi ) ; x2 = max ( x2 , p [ j ] . fi ) ; y1 = min ( y1 , p [ j ] . se ) ; y2 = max ( y2 , p [ j ] . se ) ; } bool ok = 1 ; int c1 = 0 , c2 = 0 ; int c3 = 0 , c4 = 0 ; for ( int j = 1 ; j <= n * 4 + 1 ; ++ j ) if ( i != j ) { if ( ( p [ j ] . fi == x1 p [ j ] . fi == x2 ) || ( ( p [ j ] . se == y1 p [ j ] . se == y2 ) ) ) { if ( p [ j ] . fi == x1 ) ++ c1 ; if ( p [ j ] . fi == x2 ) ++ c2 ; if ( p [ j ] . se == y1 ) ++ c3 ; if ( p [ j ] . se == y2 ) ++ c4 ; } else ok = 0 ; } if ( ok && c1 >= n && c2 >= n && c3 >= n && c4 >= n && x2 - x1 == y2 - y1 ) { cout << p [ i ] . fi << " ▁ " << p [ i ] . se << " STRNEWLINE " ; } } } int main ( ) { int N = 2 ; vector < pair < int , int > > arr = { { 0 , 0 } , { 0 , 1 } , { 0 , 2 } , { 1 , 0 } , { 1 , 1 } , { 1 , 2 } , { 2 , 0 } , { 2 , 1 } , { 2 , 2 } } ; findPoint ( N , arr ) ; return 0 ; }
Triacontagon Number | C ++ program for above approach ; Finding the nth triacontagonal number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int triacontagonalNum ( int n ) { return ( 28 * n * n - 26 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ triacontagonal ▁ Number ▁ is ▁ = ▁ " << triacontagonalNum ( n ) ; return 0 ; }
Hexacontagon Number | C ++ program for above approach ; Finding the nth hexacontagon number ; Driver code
#include <iostream> NEW_LINE using namespace std ; int hexacontagonNum ( int n ) { return ( 58 * n * n - 56 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ hexacontagon ▁ Number ▁ is ▁ = ▁ " << hexacontagonNum ( n ) ; return 0 ; }
Enneacontagon Number | C ++ program for above approach ; Finding the nth enneacontagon Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int enneacontagonNum ( int n ) { return ( 88 * n * n - 86 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ enneacontagon ▁ Number ▁ is ▁ = ▁ " << enneacontagonNum ( n ) ; return 0 ; }
Triacontakaidigon Number | C ++ program for above approach ; Finding the nth triacontakaidigon Number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int triacontakaidigonNum ( int n ) { return ( 30 * n * n - 28 * n ) / 2 ; } int main ( ) { int n = 3 ; cout << "3rd ▁ triacontakaidigon ▁ Number ▁ is ▁ = ▁ " << triacontakaidigonNum ( n ) ; return 0 ; }