text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Longest subsequence such that difference between adjacents is one | C ++ program to find the longest subsequence such the difference between adjacent elements of the subsequence is one . ; Function to find the length of longest subsequence ; Initialize the dp [ ] array with 1 as a single element will be of 1 length ; Start traversing the given array ; Compare with all the previous elements ; If the element is consecutive then consider this subsequence and update dp [ i ] if required . ; Longest length will be the maximum value of dp array . ; Driver code ; Longest subsequence with one difference is { 1 , 2 , 3 , 4 , 3 , 2 }
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubseqWithDiffOne ( int arr [ ] , int n ) { int dp [ n ] ; for ( int i = 0 ; i < n ; i ++ ) dp [ i ] = 1 ; for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < i ; j ++ ) { if ( ( arr [ i ] == arr [ j ] + 1 ) || ( arr [ i ] == arr [ j ] - 1 ) ) dp [ i ] = max ( dp [ i ] , dp [ j ] + 1 ) ; } } int result = 1 ; for ( int i = 0 ; i < n ; i ++ ) if ( result < dp [ i ] ) result = dp [ i ] ; return result ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 3 , 2 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestSubseqWithDiffOne ( arr , n ) ; return 0 ; }
Non | C ++ program to count number of ways to connect n ( where nis even ) points on a circle such that no two connecting lines cross each other and every point is connected with one other point . ; A dynamic programming based function to find nth Catalan number ; Table to store results of subproblems ; Initialize first two values in table ; Fill entries in catalan [ ] using recursive formula ; Return last entry ; Returns count of ways to connect n points on a circle such that no two connecting lines cross each other and every point is connected with one other point . ; Throw error if n is odd ; Else return n / 2 'th Catalan number ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; unsigned long int catalanDP ( unsigned int n ) { unsigned long int catalan [ n + 1 ] ; catalan [ 0 ] = catalan [ 1 ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { catalan [ i ] = 0 ; for ( int j = 0 ; j < i ; j ++ ) catalan [ i ] += catalan [ j ] * catalan [ i - j - 1 ] ; } return catalan [ n ] ; } unsigned long int countWays ( unsigned long int n ) { if ( n & 1 ) { cout << " Invalid " ; return 0 ; } return catalanDP ( n / 2 ) ; } int main ( ) { cout << countWays ( 6 ) << " ▁ " ; return 0 ; }
Ways to arrange Balls such that adjacent balls are of different types | C ++ program to count number of ways to arrange three types of balls such that no two balls of same color are adjacent to each other ; table to store to store results of subproblems ; Returns count of arrangements where last placed ball is ' last ' . ' last ' is 0 for ' p ' , 1 for ' q ' and 2 for ' r ' ; if number of balls of any color becomes less than 0 the number of ways arrangements is 0. ; If last ball required is of type P and the number of balls of P type is 1 while number of balls of other color is 0 the number of ways is 1. ; Same case as above for ' q ' and ' r ' ; If this subproblem is already evaluated ; if last ball required is P and the number of ways is the sum of number of ways to form sequence with ' p - 1' P balls , q Q Balls and r R balls ending with Q and R . ; Same as above case for ' q ' and ' r ' ; else ( last == 2 ) ; Returns count of required arrangements ; Initialize ' dp ' array ; Three cases arise : return countWays ( p , q , r , 0 ) + Last required balls is type P countWays ( p , q , r , 1 ) + Last required balls is type Q countWays ( p , q , r , 2 ) ; Last required balls is type R ; Driver code to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE int dp [ MAX ] [ MAX ] [ MAX ] [ 3 ] ; int countWays ( int p , int q , int r , int last ) { if ( p < 0 q < 0 r < 0 ) return 0 ; if ( p == 1 && q == 0 && r == 0 && last == 0 ) return 1 ; if ( p == 0 && q == 1 && r == 0 && last == 1 ) return 1 ; if ( p == 0 && q == 0 && r == 1 && last == 2 ) return 1 ; if ( dp [ p ] [ q ] [ r ] [ last ] != -1 ) return dp [ p ] [ q ] [ r ] [ last ] ; if ( last == 0 ) dp [ p ] [ q ] [ r ] [ last ] = countWays ( p - 1 , q , r , 1 ) + countWays ( p - 1 , q , r , 2 ) ; else if ( last == 1 ) dp [ p ] [ q ] [ r ] [ last ] = countWays ( p , q - 1 , r , 0 ) + countWays ( p , q - 1 , r , 2 ) ; dp [ p ] [ q ] [ r ] [ last ] = countWays ( p , q , r - 1 , 0 ) + countWays ( p , q , r - 1 , 1 ) ; return dp [ p ] [ q ] [ r ] [ last ] ; } int countUtil ( int p , int q , int r ) { memset ( dp , -1 , sizeof ( dp ) ) ; } int main ( ) { int p = 1 , q = 1 , r = 1 ; printf ( " % d " , countUtil ( p , q , r ) ) ; return 0 ; }
Count Derangements ( Permutation such that no element appears in its original position ) | A Naive Recursive C ++ program to count derangements ; Function to count derangements ; Base cases ; countDer ( n ) = ( n - 1 ) [ countDer ( n - 1 ) + der ( n - 2 ) ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDer ( int n ) { if ( n == 1 ) return 0 ; if ( n == 2 ) return 1 ; return ( n - 1 ) * ( countDer ( n - 1 ) + countDer ( n - 2 ) ) ; } int main ( ) { int n = 4 ; cout << " Count ▁ of ▁ Derangements ▁ is ▁ " << countDer ( n ) ; return 0 ; }
Count Derangements ( Permutation such that no element appears in its original position ) | A Dynamic programming based C ++ program to count derangements ; Function to count derangements ; Create an array to store counts for subproblems ; Base cases ; Fill der [ 0. . n ] in bottom up manner using above recursive formula ; Return result for n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDer ( int n ) { int der [ n + 1 ] = { 0 } ; der [ 1 ] = 0 ; der [ 2 ] = 1 ; for ( int i = 3 ; i <= n ; ++ i ) der [ i ] = ( i - 1 ) * ( der [ i - 1 ] + der [ i - 2 ] ) ; return der [ n ] ; } int main ( ) { int n = 4 ; cout << " Count ▁ of ▁ Derangements ▁ is ▁ " << countDer ( n ) ; return 0 ; }
Find number of solutions of a linear equation of n variables | A Dynamic programming based C ++ program to find number of non - negative solutions for a given linear equation ; Returns count of solutions for given rhs and coefficients coeff [ 0. . n - 1 ] ; Create and initialize a table to store results of subproblems ; Fill table in bottom up manner ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSol ( int coeff [ ] , int n , int rhs ) { int dp [ rhs + 1 ] ; memset ( dp , 0 , sizeof ( dp ) ) ; dp [ 0 ] = 1 ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = coeff [ i ] ; j <= rhs ; j ++ ) dp [ j ] += dp [ j - coeff [ i ] ] ; return dp [ rhs ] ; } int main ( ) { int coeff [ ] = { 2 , 2 , 5 } ; int rhs = 4 ; int n = sizeof ( coeff ) / sizeof ( coeff [ 0 ] ) ; cout << countSol ( coeff , n , rhs ) ; return 0 ; }
Find all distinct palindromic sub | C ++ program to find all distinct palindrome sub - strings of a given string ; Function to print all distinct palindrome sub - strings of s ; table for storing results ( 2 rows for odd - and even - length palindromes ; Find all sub - string palindromes from the given input string insert ' guards ' to iterate easily over s ; int rp = 0 ; length of ' palindrome ▁ radius ' ; Attempt to expand palindrome centered at i ; Assigning the found palindromic length to odd / even length array ; remove ' guards ' ; Put all obtained palindromes in a hash map to find only distinct palindromess ; printing all distinct palindromes from hash map ; Driver program
#include <iostream> NEW_LINE #include <map> NEW_LINE using namespace std ; void palindromeSubStrs ( string s ) { map < string , int > m ; int n = s . size ( ) ; int R [ 2 ] [ n + 1 ] ; s = " @ " + s + " # " ; for ( int j = 0 ; j <= 1 ; j ++ ) { R [ j ] [ 0 ] = 0 ; int i = 1 ; while ( i <= n ) { while ( s [ i - rp - 1 ] == s [ i + j + rp ] ) R [ j ] [ i ] = rp ; int k = 1 ; while ( ( R [ j ] [ i - k ] != rp - k ) && ( k < rp ) ) { R [ j ] [ i + k ] = min ( R [ j ] [ i - k ] , rp - k ) ; k ++ ; } rp = max ( rp - k , 0 ) ; i += k ; } } s = s . substr ( 1 , n ) ; m [ string ( 1 , s [ 0 ] ) ] = 1 ; for ( int i = 1 ; i <= n ; i ++ ) { for ( int j = 0 ; j <= 1 ; j ++ ) for ( int rp = R [ j ] [ i ] ; rp > 0 ; rp -- ) m [ s . substr ( i - rp - 1 , 2 * rp + j ) ] = 1 ; m [ string ( 1 , s [ i ] ) ] = 1 ; } cout << " Below ▁ are ▁ " << m . size ( ) - 1 << " ▁ palindrome ▁ sub - strings " ; map < string , int > :: iterator ii ; for ( ii = m . begin ( ) ; ii != m . end ( ) ; ++ ii ) cout << ( * ii ) . first << endl ; } int main ( ) { palindromeSubStrs ( " abaaa " ) ; return 0 ; }
Largest value in each level of Binary Tree | Set | C ++ implementation to print largest value in each level of Binary Tree ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to print largest value in each level of Binary Tree ; if tree is empty ; push root to the queue ' q ' ; node count for the current level ; if true then all the nodes of the tree have been traversed ; maximum element for the current level ; get the front element from ' q ' ; remove front element from ' q ' ; if true , then update ' max ' ; if left child exists ; if right child exists ; print maximum element of current level ; Driver code ; Construct a Binary Tree 4 / \ 9 2 / \ \ 3 5 7 ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void largestValueInEachLevel ( Node * root ) { if ( ! root ) return ; queue < Node * > q ; int nc , max ; q . push ( root ) ; while ( 1 ) { nc = q . size ( ) ; if ( nc == 0 ) break ; max = INT_MIN ; while ( nc -- ) { Node * front = q . front ( ) ; q . pop ( ) ; if ( max < front -> data ) max = front -> data ; if ( front -> left ) q . push ( front -> left ) ; if ( front -> right ) q . push ( front -> right ) ; } cout << max << " ▁ " ; } } int main ( ) { Node * root = NULL ; root = newNode ( 4 ) ; root -> left = newNode ( 9 ) ; root -> right = newNode ( 2 ) ; root -> left -> left = newNode ( 3 ) ; root -> left -> right = newNode ( 5 ) ; root -> right -> right = newNode ( 7 ) ; largestValueInEachLevel ( root ) ; return 0 ; }
Populate Inorder Successor for all nodes | C ++ program to populate inorder traversal of all nodes ; A binary tree node ; Set next of p and all descendants of p by traversing them in reverse Inorder ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in left subtree ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Constructed binary tree is 10 / \ 8 12 / 3 ; Populates nextRight pointer in all nodes ; Let us see the populated values ; - 1 is printed if there is no successor
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node * next ; } ; void populateNext ( node * p ) { static node * next = NULL ; if ( p ) { populateNext ( p -> right ) ; p -> next = next ; next = p ; populateNext ( p -> left ) ; } } node * newnode ( int data ) { node * Node = new node ( ) ; Node -> data = data ; Node -> left = NULL ; Node -> right = NULL ; Node -> next = NULL ; return ( Node ) ; } int main ( ) { node * root = newnode ( 10 ) ; root -> left = newnode ( 8 ) ; root -> right = newnode ( 12 ) ; root -> left -> left = newnode ( 3 ) ; populateNext ( root ) ; node * ptr = root -> left -> left ; while ( ptr ) { cout << " Next ▁ of ▁ " << ptr -> data << " ▁ is ▁ " << ( ptr -> next ? ptr -> next -> data : -1 ) << endl ; ptr = ptr -> next ; } return 0 ; }
Maximum Product Cutting | DP | ; The main function that returns the max possible product ; n equals to 2 or 3 must be handled explicitly ; Keep removing parts of size 3 while n is greater than 4 ; Keep multiplying 3 to res ; The last part multiplied by previous parts ; Driver program to test above functions
#include <iostream> NEW_LINE using namespace std ; int maxProd ( int n ) { if ( n == 2 n == 3 ) return ( n - 1 ) ; int res = 1 ; while ( n > 4 ) { n -= 3 ; res *= 3 ; } return ( n * res ) ; } int main ( ) { cout << " Maximum ▁ Product ▁ is ▁ " << maxProd ( 10 ) ; return 0 ; }
Dice Throw | DP | C ++ program to find number of ways to get sum ' x ' with ' n ' dice where every dice has ' m ' faces ; The main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are never used . ; Table entries for only one dice ; Fill rest of the entries in table using recursive relation i : number of dice , j : sum ; Return value ; Driver program to test above functions
#include <iostream> NEW_LINE #include <string.h> NEW_LINE using namespace std ; int findWays ( int m , int n , int x ) { int table [ n + 1 ] [ x + 1 ] ; for ( int j = 1 ; j <= m && j <= x ; j ++ ) table [ 1 ] [ j ] = 1 ; for ( int i = 2 ; i <= n ; i ++ ) for ( int j = 1 ; j <= x ; j ++ ) for ( int k = 1 ; k <= m && k < j ; k ++ ) table [ i ] [ j ] += table [ i - 1 ] [ j - k ] ; return table [ n ] [ x ] ; } int main ( ) { cout << findWays ( 4 , 2 , 1 ) << endl ; cout << findWays ( 2 , 2 , 3 ) << endl ; cout << findWays ( 6 , 3 , 8 ) << endl ; cout << findWays ( 4 , 2 , 5 ) << endl ; cout << findWays ( 4 , 3 , 5 ) << endl ; return 0 ; }
Dice Throw | DP | C ++ program The main function that returns number of ways to get sum ' x ' with ' n ' dice and ' m ' with m faces . ; * * Count ways * * @ param f * @ param d * @ param s * @ return ; Create a table to store results of subproblems . One extra row and column are used for simpilicity ( Number of dice is directly used as row index and sum is directly used as column index ) . The entries in 0 th row and 0 th column are never used . ; Table entries for no dices If you do not have any data , then the value must be 0 , so the result is 1 ; Iterate over dices ; Iterate over sum ; The result is obtained in two ways , pin the current dice and spending 1 of the value , so we have mem [ i - 1 ] [ j - 1 ] remaining combinations , to find the remaining combinations we would have to pin the values ? ? above 1 then we use mem [ i ] [ j - 1 ] to sum all combinations that pin the remaining j - 1 's. But there is a way, when "j-f-1> = 0" we would be adding extra combinations, so we remove the combinations that only pin the extrapolated dice face and subtract the extrapolated combinations. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long findWays ( int f , int d , int s ) { long mem [ d + 1 ] [ s + 1 ] ; memset ( mem , 0 , sizeof mem ) ; mem [ 0 ] [ 0 ] = 1 ; for ( int i = 1 ; i <= d ; i ++ ) { for ( int j = i ; j <= s ; j ++ ) { mem [ i ] [ j ] = mem [ i ] [ j - 1 ] + mem [ i - 1 ] [ j - 1 ] ; if ( j - f - 1 >= 0 ) mem [ i ] [ j ] -= mem [ i - 1 ] [ j - f - 1 ] ; } } return mem [ d ] [ s ] ; } int main ( void ) { cout << findWays ( 4 , 2 , 1 ) << endl ; cout << findWays ( 2 , 2 , 3 ) << endl ; cout << findWays ( 6 , 3 , 8 ) << endl ; cout << findWays ( 4 , 2 , 5 ) << endl ; cout << findWays ( 4 , 3 , 5 ) << endl ; return 0 ; }
Minimum insertions to form a palindrome | DP | A Naive recursive program to find minimum number insertions needed to make a string palindrome ; Recursive function to find minimum number of insertions ; Base Cases ; Check if the first and last characters are same . On the basis of the comparison result , decide which subrpoblem ( s ) to call ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMinInsertions ( char str [ ] , int l , int h ) { if ( l > h ) return INT_MAX ; if ( l == h ) return 0 ; if ( l == h - 1 ) return ( str [ l ] == str [ h ] ) ? 0 : 1 ; return ( str [ l ] == str [ h ] ) ? findMinInsertions ( str , l + 1 , h - 1 ) : ( min ( findMinInsertions ( str , l , h - 1 ) , findMinInsertions ( str , l + 1 , h ) ) + 1 ) ; } int main ( ) { char str [ ] = " geeks " ; cout << findMinInsertions ( str , 0 , strlen ( str ) - 1 ) ; return 0 ; }
Longest Palindromic Subsequence | DP | C ++ program of above approach ; A utility function to get max of two integers ; Returns the length of the longest palindromic subsequence in seq ; Base Case 1 : If there is only 1 character ; Base Case 2 : If there are only 2 characters and both are same ; If the first and last characters match ; If the first and last characters do not match ; Driver program to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } int lps ( char * seq , int i , int j ) { if ( i == j ) return 1 ; if ( seq [ i ] == seq [ j ] && i + 1 == j ) return 2 ; if ( seq [ i ] == seq [ j ] ) return lps ( seq , i + 1 , j - 1 ) + 2 ; return max ( lps ( seq , i , j - 1 ) , lps ( seq , i + 1 , j ) ) ; } int main ( ) { char seq [ ] = " GEEKSFORGEEKS " ; int n = strlen ( seq ) ; cout << " The ▁ length ▁ of ▁ the ▁ LPS ▁ is ▁ " << lps ( seq , 0 , n - 1 ) ; return 0 ; }
Smallest value in each level of Binary Tree | CPP program to print smallest element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Inorder Traversal Search minimum element in each level and store it into vector array . ; height of tree for the size of vector array ; vector for store all minimum of every level ; save every level minimum using inorder traversal ; print every level minimum ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
#include <bits/stdc++.h> NEW_LINE #define INT_MAX 10e6 NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; int heightoftree ( Node * root ) { if ( root == NULL ) return 0 ; int left = heightoftree ( root -> left ) ; int right = heightoftree ( root -> right ) ; return ( ( left > right ? left : right ) + 1 ) ; } void printPerLevelMinimum ( Node * root , vector < int > & res , int level ) { if ( root != NULL ) { printPerLevelMinimum ( root -> left , res , level + 1 ) ; if ( root -> data < res [ level ] ) res [ level ] = root -> data ; printPerLevelMinimum ( root -> right , res , level + 1 ) ; } } void perLevelMinimumUtility ( Node * root ) { int n = heightoftree ( root ) , i ; vector < int > res ( n , INT_MAX ) ; printPerLevelMinimum ( root , res , 0 ) ; cout << " Every ▁ level ▁ minimum ▁ is STRNEWLINE " ; for ( i = 0 ; i < n ; i ++ ) { cout << " level ▁ " << i << " ▁ min ▁ is ▁ = ▁ " << res [ i ] << " STRNEWLINE " ; } } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; perLevelMinimumUtility ( root ) ; return 0 ; }
Smallest value in each level of Binary Tree | CPP program to print minimum element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order traversal ; push the root for Change the level ; for go level by level ; for check the level ; Get top of queue ; if node == NULL ( Means this is boundary between two levels ) ; here queue is empty represent no element in the actual queue ; increment level ; Reset min for next level minimum value ; get Minimum in every level ; Enqueue left child ; Enqueue right child ; Utility function to create a new tree node ; Driver program to test above functions ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1
#include <iostream> NEW_LINE #include <queue> NEW_LINE #include <vector> NEW_LINE #define INT_MAX 10e6 NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; int heightoftree ( Node * root ) { if ( root == NULL ) return 0 ; int left = heightoftree ( root -> left ) ; int right = heightoftree ( root -> right ) ; return ( ( left > right ? left : right ) + 1 ) ; } void printPerLevelMinimum ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; q . push ( NULL ) ; int min = INT_MAX ; int level = 0 ; while ( q . empty ( ) == false ) { Node * node = q . front ( ) ; q . pop ( ) ; if ( node == NULL ) { cout << " level ▁ " << level << " ▁ min ▁ is ▁ = ▁ " << min << " STRNEWLINE " ; if ( q . empty ( ) ) break ; q . push ( NULL ) ; level ++ ; min = INT_MAX ; continue ; } if ( min > node -> data ) min = node -> data ; if ( node -> left != NULL ) { q . push ( node -> left ) ; } if ( node -> right != NULL ) { q . push ( node -> right ) ; } } } Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = newNode ( 7 ) ; root -> left = newNode ( 6 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 2 ) ; root -> right -> right = newNode ( 1 ) ; cout << " Every ▁ Level ▁ minimum ▁ is " << " STRNEWLINE " ; printPerLevelMinimum ( root ) ; return 0 ; }
Count occurrences of a string that can be constructed from another given string | C ++ implementation of the above approach ; Function to find the count ; Initialize hash for both strings ; hash the frequency of letters of str1 ; hash the frequency of letters of str2 ; Find the count of str2 constructed from str1 ; Return answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( string str1 , string str2 ) { int len = str1 . size ( ) ; int len2 = str2 . size ( ) ; int ans = INT_MAX ; int hash1 [ 26 ] = { 0 } , hash2 [ 26 ] = { 0 } ; for ( int i = 0 ; i < len ; i ++ ) hash1 [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < len2 ; i ++ ) hash2 [ str2 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) if ( hash2 [ i ] ) ans = min ( ans , hash1 [ i ] / hash2 [ i ] ) ; return ans ; } int main ( ) { string str1 = " geeksclassesatnoida " ; string str2 = " sea " ; cout << findCount ( str1 , str2 ) ; return 0 ; }
Check if a string is the typed name of the given name | CPP program to implement run length encoding ; Check if the character is vowel or not ; Returns true if ' typed ' is a typed name given str ; Traverse through all characters of str . ; If current characters do not match ; If not vowel , simply move ahead in both ; Count occurrences of current vowel in str ; Count occurrences of current vowel in typed . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { string vowel = " aeiou " ; for ( int i = 0 ; i < vowel . length ( ) ; ++ i ) if ( vowel [ i ] == c ) return true ; return false ; } bool printRLE ( string str , string typed ) { int n = str . length ( ) , m = typed . length ( ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] != typed [ j ] ) return false ; if ( isVowel ( str [ i ] ) == false ) { j ++ ; continue ; } int count1 = 1 ; while ( i < n - 1 && str [ i ] == str [ i + 1 ] ) { count1 ++ ; i ++ ; } int count2 = 1 ; while ( j < m - 1 && typed [ j ] == str [ i ] ) { count2 ++ ; j ++ ; } if ( count1 > count2 ) return false ; } return true ; } int main ( ) { string name = " alex " , typed = " aaalaeex " ; if ( printRLE ( name , typed ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Get Level of a node in a Binary Tree | C ++ program to Get Level of a node in a Binary Tree ; A tree node structure ; Helper function for getLevel ( ) . It returns level of the data if data is present in tree , otherwise returns 0. ; Returns level of given data value ; Utility function to create a new Binary Tree node ; Driver Code ; Constructing tree given in the above figure
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; struct node * left ; struct node * right ; } ; int getLevelUtil ( struct node * node , int data , int level ) { if ( node == NULL ) return 0 ; if ( node -> data == data ) return level ; int downlevel = getLevelUtil ( node -> left , data , level + 1 ) ; if ( downlevel != 0 ) return downlevel ; downlevel = getLevelUtil ( node -> right , data , level + 1 ) ; return downlevel ; } int getLevel ( struct node * node , int data ) { return getLevelUtil ( node , data , 1 ) ; } struct node * newNode ( int data ) { struct node * temp = new struct node ; temp -> data = data ; temp -> left = NULL ; temp -> right = NULL ; return temp ; } int main ( ) { struct node * root = new struct node ; int x ; root = newNode ( 3 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 1 ) ; root -> left -> right = newNode ( 4 ) ; for ( x = 1 ; x <= 5 ; x ++ ) { int level = getLevel ( root , x ) ; if ( level ) cout << " Level ▁ of ▁ " << x << " ▁ is ▁ " << getLevel ( root , x ) << endl ; else cout << x << " is ▁ not ▁ present ▁ in ▁ tree " << endl ; } getchar ( ) ; return 0 ; }
Program to replace a word with asterisks in a sentence | C ++ program to censor a word with asterisks in a sentence ; Function takes two parameter ; Break down sentence by ' ▁ ' spaces and store each individual word in a different list ; A new string to store the result ; Creating the censor which is an asterisks " * " text of the length of censor word ; Iterating through our list of extracted words ; changing the censored word to created asterisks censor ; join the words ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <boost/algorithm/string.hpp> NEW_LINE using namespace std ; string censor ( string text , string word ) { vector < string > word_list ; boost :: split ( word_list , text , boost :: is_any_of ( " \\ ▁ + " ) ) ; string result = " " ; string stars = " " ; for ( int i = 0 ; i < word . size ( ) ; i ++ ) stars += ' * ' ; int index = 0 ; for ( string i : word_list ) { if ( i . compare ( word ) == 0 ) { word_list [ index ] = stars ; } index ++ ; } for ( string i : word_list ) { result += i + ' ▁ ' ; } return result ; } int main ( ) { string extract = " GeeksforGeeks ▁ is ▁ a ▁ computer ▁ science ▁ " " portal ▁ for ▁ geeks . ▁ I ▁ am ▁ pursuing ▁ my ▁ " " major ▁ in ▁ computer ▁ science . ▁ " ; string cen = " computer " ; cout << ( censor ( extract , cen ) ) ; }
Finite Automata algorithm for Pattern Searching | CPP program for Finite Automata Pattern searching Algorithm ; If the character c is same as next character in pattern , then simply increment state ; ns stores the result which is next state ; Start from the largest possible value and stop when you find a prefix which is also suffix ; This function builds the TF table which represents4 Finite Automata for a given pattern ; Prints all occurrences of pat in txt ; Process txt over FA . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int getNextState ( string pat , int M , int state , int x ) { if ( state < M && x == pat [ state ] ) return state + 1 ; int ns , i ; for ( ns = state ; ns > 0 ; ns -- ) { if ( pat [ ns - 1 ] == x ) { for ( i = 0 ; i < ns - 1 ; i ++ ) if ( pat [ i ] != pat [ state - ns + 1 + i ] ) break ; if ( i == ns - 1 ) return ns ; } } return 0 ; } void computeTF ( string pat , int M , int TF [ ] [ NO_OF_CHARS ] ) { int state , x ; for ( state = 0 ; state <= M ; ++ state ) for ( x = 0 ; x < NO_OF_CHARS ; ++ x ) TF [ state ] [ x ] = getNextState ( pat , M , state , x ) ; } void search ( string pat , string txt ) { int M = pat . size ( ) ; int N = txt . size ( ) ; int TF [ M + 1 ] [ NO_OF_CHARS ] ; computeTF ( pat , M , TF ) ; int i , state = 0 ; for ( i = 0 ; i < N ; i ++ ) { state = TF [ state ] [ txt [ i ] ] ; if ( state == M ) cout << " ▁ Pattern ▁ found ▁ at ▁ index ▁ " << i - M + 1 << endl ; } } int main ( ) { string txt = " AABAACAADAABAAABAA " ; string pat = " AABA " ; search ( pat , txt ) ; return 0 ; }
Longest Substring containing '1' | C ++ program for the above approach ; Function to find length of longest substring containing '1' ; Count the number of contiguous 1 's ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxlength ( string s ) { int n = s . length ( ) , i , j ; int ans = 0 ; for ( i = 0 ; i <= n - 1 ; i ++ ) { if ( s [ i ] == '1' ) { int count = 1 ; for ( j = i + 1 ; j <= n - 1 && s [ j ] == '1' ; j ++ ) count ++ ; ans = max ( ans , count ) ; } } return ans ; } int main ( ) { string s = "11101110" ; cout << maxlength ( s ) << endl ; return 0 ; }
Generate all possible strings formed by replacing letters with given respective symbols | C ++ program for the above approach ; Function to generate all possible string by replacing the characters with mapped symbols ; Base Case ; Function call with the P - th character not replaced ; Replace the P - th character ; Function call with the P - th character replaced ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generateLetters ( string S , int P , unordered_map < char , char > M ) { if ( P == S . size ( ) ) { cout << S << " STRNEWLINE " ; return ; } generateLetters ( S , P + 1 , M ) ; S [ P ] = M [ S [ P ] ] ; generateLetters ( S , P + 1 , M ) ; return ; } int main ( ) { string S = " aBc " ; unordered_map < char , char > M ; M [ ' a ' ] = ' $ ' ; M [ ' B ' ] = ' # ' ; M [ ' c ' ] = ' ^ ' ; M [ ' d ' ] = ' & ' ; M [ '1' ] = ' * ' ; M [ '2' ] = ' ! ' ; M [ ' E ' ] = ' @ ' ; generateLetters ( S , 0 , M ) ; return 0 ; }
Max count of N using digits of M such that 2 and 5 , and , 6 and 9 can be treated as same respectively | C ++ program for the above approach ; Function to find the count of numbers that can be formed using the given digits in the string ; Store the frequency of digits from the given string M ; Store length of the string M ; Loop to traverse the string ; Replace 5 with 2 ; Replace 9 with 6 ; Get the int form of the current character in the string ; Insert in the map ; Store all the digits of the required number N ; Loop to get all the digits from the number N ; Get the last digit as the remainder ; Replace 5 with 2 ; Replace 9 with 6 ; Insert the remainders in the rems map ; Store the resultant count ; Iterate through the rems map ; Get the key which is a digit from the number N to be formed ; If not present in the string M , number N that cannot be formed ; Divide the frequency of the digit from the string M with the frequency of the current remainder ; Choose the minimum ; Return the maximum count ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( int n , string str ) { map < int , int > mymap ; int len = str . size ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = str [ i ] ; if ( c == '5' ) c = '2' ; else if ( c == '9' ) c = '6' ; int c_int = c - ' a ' ; if ( mymap . find ( c_int ) != mymap . end ( ) ) mymap [ c_int ] += 1 ; else mymap [ c_int ] = 1 ; } map < int , int > rems ; while ( n > 0 ) { int rem = n % 10 ; if ( rem == 5 ) rem = 2 ; if ( rem == 9 ) rem = 6 ; if ( rems . find ( rem ) != rems . end ( ) ) rems [ rem ] += 1 ; else rems [ rem ] = 1 ; n = n / 10 ; } int cnt = 1e8 ; for ( auto ele : rems ) { int key = ele . first ; if ( mymap . find ( key ) == mymap . end ( ) ) return 0 ; int temp = mymap [ key ] / ele . second ; cnt = min ( cnt , temp ) ; } return cnt ; } int main ( ) { int N = 56 ; string M = "245769" ; cout << solve ( N , M ) << endl ; return 0 ; }
Minimize swaps of pairs of characters required such that no two adjacent characters in the string are same | C ++ program for the above approach ; Function to check if S contains any pair of adjacent characters that are same ; Traverse the string S ; If current pair of adjacent characters are the same ; Return true ; Utility function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; Check if the required string is formed already ; Traverse the string S ; Swap the characters at i and j position ; Swap for Backtracking Step ; Function to find the minimum number of swaps of pair of characters required to make all pairs of adjacent characters different ; Stores the resultant minimum number of swaps required ; Function call to find the minimum swaps required ; Print the result ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string & S ) { for ( int i = 1 ; i < S . length ( ) ; i ++ ) { if ( S [ i - 1 ] == S [ i ] ) { return false ; } } return true ; } void minimumSwaps ( string & S , int & ansSwaps , int swaps = 0 , int idx = 0 ) { if ( check ( S ) ) { ansSwaps = min ( ansSwaps , swaps ) ; } for ( int i = idx ; i < S . length ( ) ; i ++ ) { for ( int j = i + 1 ; j < S . length ( ) ; j ++ ) { swap ( S [ i ] , S [ j ] ) ; minimumSwaps ( S , ansSwaps , swaps + 1 , i + 1 ) ; swap ( S [ i ] , S [ j ] ) ; } } } void findMinimumSwaps ( string & S ) { int ansSwaps = INT_MAX ; minimumSwaps ( S , ansSwaps ) ; if ( ansSwaps == INT_MAX ) cout << " - 1" ; else cout << ansSwaps ; } int main ( ) { string S = " ABAACD " ; findMinimumSwaps ( S ) ; return 0 ; }
Maximum count of 0 s between two 1 s in given range for Q queries | ; Function to count the number of 0 s lying between the two 1 s for each query ; Stores count of 0 ' s ▁ that ▁ are ▁ ▁ right ▁ to ▁ the ▁ most ▁ recent ▁ 1' s ; Stores count of 0 ' s ▁ that ▁ are ▁ ▁ left ▁ to ▁ the ▁ most ▁ recent ▁ 1' s ; Stores the count of zeros in a prefix / suffix of array ; Stores the count of total 0 s ; Traverse the string S ; If current character is '1' ; Otherwise ; Update the rightBound [ i ] ; Update count and total to 0 ; Traverse the string S in reverse manner ; If current character is '1' ; Otherwise ; Update the leftBound [ i ] ; Traverse given query array ; Update the value of count ; Print the count as the result to the current query [ L , R ] ; Driver Code
#include <iostream> NEW_LINE using namespace std ; void countOsBetween1s ( string S , int N , int Q [ ] [ 2 ] ) { int leftBound [ N ] ; int rightBound [ N ] ; int count = 0 ; int total = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == '1' ) { count = total ; } else if ( S [ i ] == '0' ) { total ++ ; } rightBound [ i ] = count ; } count = 0 ; total = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == '1' ) { count = total ; } else if ( S [ i ] == '0' ) { total ++ ; } leftBound [ i ] = count ; } for ( int q = 0 ; q < 2 ; q ++ ) { int L = Q [ q ] [ 0 ] ; int R = Q [ q ] [ 1 ] ; count = leftBound [ L ] + rightBound [ R ] - total ; cout << count << " ▁ " ; } } int main ( ) { string S = "1001010" ; int Q [ ] [ 2 ] = { { 0 , 4 } , { 0 , 5 } } ; int N = S . length ( ) ; countOsBetween1s ( S , N , Q ) ; return 0 ; }
Get level of a node in binary tree | iterative approach | CPP program to print level of given node in binary tree iterative approach ; node of binary tree ; utility function to create a new node ; utility function to return level of given node ; extra NULL is pushed to keep track of all the nodes to be pushed before level is incremented by 1 ; Driver Code ; create a binary tree ; return level of node
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct node { int data ; node * left ; node * right ; } ; node * getnode ( int data ) { node * newnode = new node ( ) ; newnode -> data = data ; newnode -> left = NULL ; newnode -> right = NULL ; } int getlevel ( node * root , int data ) { queue < node * > q ; int level = 1 ; q . push ( root ) ; q . push ( NULL ) ; while ( ! q . empty ( ) ) { node * temp = q . front ( ) ; q . pop ( ) ; if ( temp == NULL ) { if ( q . front ( ) != NULL ) { q . push ( NULL ) ; } level += 1 ; } else { if ( temp -> data == data ) { return level ; } if ( temp -> left ) { q . push ( temp -> left ) ; } if ( temp -> right ) { q . push ( temp -> right ) ; } } } return 0 ; } int main ( ) { node * root = getnode ( 20 ) ; root -> left = getnode ( 10 ) ; root -> right = getnode ( 30 ) ; root -> left -> left = getnode ( 5 ) ; root -> left -> right = getnode ( 15 ) ; root -> left -> right -> left = getnode ( 12 ) ; root -> right -> left = getnode ( 25 ) ; root -> right -> right = getnode ( 40 ) ; int level = getlevel ( root , 30 ) ; ( level != 0 ) ? ( cout << " level ▁ of ▁ node ▁ 30 ▁ is ▁ " << level << endl ) : ( cout << " node ▁ 30 ▁ not ▁ found " << endl ) ; level = getlevel ( root , 12 ) ; ( level != 0 ) ? ( cout << " level ▁ of ▁ node ▁ 12 ▁ is ▁ " << level << endl ) : ( cout << " node ▁ 12 ▁ not ▁ found " << endl ) ; level = getlevel ( root , 25 ) ; ( level != 0 ) ? ( cout << " level ▁ of ▁ node ▁ 25 ▁ is ▁ " << level << endl ) : ( cout << " node ▁ 25 ▁ not ▁ found " << endl ) ; level = getlevel ( root , 27 ) ; ( level != 0 ) ? ( cout << " level ▁ of ▁ node ▁ 27 ▁ is ▁ " << level << endl ) : ( cout << " node ▁ 27 ▁ not ▁ found " << endl ) ; return 0 ; }
Lexicographically smallest Palindromic Path in a Binary Tree | C ++ program for the above approach ; Struct binary tree node ; Function to create a new node ; Function to check if the string is palindrome or not ; Function to find the lexicographically smallest palindromic path in the Binary Tree ; Base case ; Append current node 's data to the string ; Check if a node is leaf or not ; Check for the 1 st Palindromic Path ; Store lexicographically the smallest palindromic path ; Recursively traverse left subtree ; Recursively traverse right subtree ; Function to get smallest lexographical palindromic path ; Variable which stores the final result ; Function call to compute lexicographically smallest palindromic Path ; Driver Code ; Construct binary tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char data ; Node * left , * right ; } ; Node * newNode ( char data ) { Node * temp = new Node ( ) ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } bool checkPalindrome ( string s ) { int low = 0 , high = ( int ) s . size ( ) - 1 ; while ( low < high ) { if ( s [ low ] != s [ high ] ) return false ; low ++ ; high -- ; } return true ; } void lexicographicallySmall ( Node * root , string s , string & finalAns ) { if ( root == NULL ) return ; s += root -> data ; if ( ! root -> left and ! root -> right ) { if ( checkPalindrome ( s ) ) { if ( finalAns == " $ " ) finalAns = s ; else finalAns = min ( finalAns , s ) ; } return ; } lexicographicallySmall ( root -> left , s , finalAns ) ; lexicographicallySmall ( root -> right , s , finalAns ) ; } void getPalindromePath ( Node * root ) { string finalAns = " $ " ; lexicographicallySmall ( root , " " , finalAns ) ; if ( finalAns == " $ " ) cout << " No ▁ Palindromic ▁ Path ▁ exists " ; else cout << finalAns ; } int main ( ) { Node * root = newNode ( ' a ' ) ; root -> left = newNode ( ' c ' ) ; root -> left -> left = newNode ( ' a ' ) ; root -> left -> right = newNode ( ' g ' ) ; root -> right = newNode ( ' b ' ) ; root -> right -> left = newNode ( ' b ' ) ; root -> right -> right = newNode ( ' x ' ) ; root -> right -> left -> right = newNode ( ' a ' ) ; getPalindromePath ( root ) ; return 0 ; }
Find mirror of a given node in Binary tree | C ++ program to find the mirror Node in Binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; create new Node and initialize it ; recursive function to find mirror of Node ; if any of the Node is none then Node itself and decendent have no mirror , so return none , no need to further explore ! ; if left Node is target Node , then return right 's key (that is mirror) and vice versa ; first recur external Nodes ; if no mirror found , recur internal Nodes ; interface for mirror search ; Driver Code ; target Node whose mirror have to be searched
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; struct Node * newNode ( int key ) { struct Node * n = ( struct Node * ) malloc ( sizeof ( struct Node * ) ) ; if ( n != NULL ) { n -> key = key ; n -> left = NULL ; n -> right = NULL ; return n ; } else { cout << " Memory ▁ allocation ▁ failed ! " << endl ; exit ( 1 ) ; } } int findMirrorRec ( int target , struct Node * left , struct Node * right ) { if ( left == NULL right == NULL ) return 0 ; if ( left -> key == target ) return right -> key ; if ( right -> key == target ) return left -> key ; int mirror_val = findMirrorRec ( target , left -> left , right -> right ) ; if ( mirror_val ) return mirror_val ; findMirrorRec ( target , left -> right , right -> left ) ; } int findMirror ( struct Node * root , int target ) { if ( root == NULL ) return 0 ; if ( root -> key == target ) return target ; return findMirrorRec ( target , root -> left , root -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> left -> right = newNode ( 7 ) ; root -> right = newNode ( 3 ) ; root -> right -> left = newNode ( 5 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> left -> left = newNode ( 8 ) ; root -> right -> left -> right = newNode ( 9 ) ; int target = root -> left -> left -> key ; int mirror = findMirror ( root , target ) ; if ( mirror ) cout << " Mirror ▁ of ▁ Node ▁ " << target << " ▁ is ▁ Node ▁ " << mirror << endl ; else cout << " Mirror ▁ of ▁ Node ▁ " << target << " ▁ is ▁ NULL ! ▁ " << endl ; }
Smallest substring with each letter occurring both in uppercase and lowercase | C ++ program for the above approach ; Function to check if the current string is balanced or not ; For every character , check if there exists uppercase as well as lowercase characters ; Function to find smallest length substring in the given string which is balanced ; Store frequency of lowercase characters ; Stores frequency of uppercase characters ; Count frequency of characters ; Mark those characters which are not present in both lowercase and uppercase ; Initialize the frequencies back to 0 ; Marks the start and end of current substring ; Marks the start and end of required substring ; Stores the length of smallest balanced substring ; Remove all characters obtained so far ; Remove extra characters from front of the current substring ; If substring ( st , i ) is balanced ; No balanced substring ; Store answer string ; Driver Code ; Given string
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool balanced ( int small [ ] , int caps [ ] ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( small [ i ] != 0 && ( caps [ i ] == 0 ) ) return 0 ; else if ( ( small [ i ] == 0 ) && ( caps [ i ] != 0 ) ) return 0 ; } return 1 ; } void smallestBalancedSubstring ( string s ) { int small [ 26 ] ; int caps [ 26 ] ; memset ( small , 0 , sizeof ( small ) ) ; memset ( caps , 0 , sizeof ( caps ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] >= 65 && s [ i ] <= 90 ) caps [ s [ i ] - ' A ' ] ++ ; else small [ s [ i ] - ' a ' ] ++ ; } unordered_map < char , int > mp ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( small [ i ] && ! caps [ i ] ) mp [ char ( i + ' a ' ) ] = 1 ; else if ( caps [ i ] && ! small [ i ] ) mp [ char ( i + ' A ' ) ] = 1 ; } memset ( small , 0 , sizeof ( small ) ) ; memset ( caps , 0 , sizeof ( caps ) ) ; int i = 0 , st = 0 ; int start = -1 , end = -1 ; int minm = INT_MAX ; while ( i < s . length ( ) ) { if ( mp [ s [ i ] ] ) { while ( st < i ) { if ( s [ st ] >= 65 && s [ st ] <= 90 ) caps [ s [ st ] - ' A ' ] -- ; else small [ s [ st ] - ' a ' ] -- ; st ++ ; } i += 1 ; st = i ; } else { if ( s [ i ] >= 65 && s [ i ] <= 90 ) caps [ s [ i ] - ' A ' ] ++ ; else small [ s [ i ] - ' a ' ] ++ ; while ( 1 ) { if ( s [ st ] >= 65 && s [ st ] <= 90 && caps [ s [ st ] - ' A ' ] > 1 ) { caps [ s [ st ] - ' A ' ] -- ; st ++ ; } else if ( s [ st ] >= 97 && s [ st ] <= 122 && small [ s [ st ] - ' a ' ] > 1 ) { small [ s [ st ] - ' a ' ] -- ; st ++ ; } else break ; } if ( balanced ( small , caps ) ) { if ( minm > ( i - st + 1 ) ) { minm = i - st + 1 ; start = st ; end = i ; } } i += 1 ; } } if ( start == -1 end == -1 ) cout << -1 << endl ; else { string ans = " " ; for ( int i = start ; i <= end ; i ++ ) ans += s [ i ] ; cout << ans << endl ; } } int main ( ) { string s = " azABaabba " ; smallestBalancedSubstring ( s ) ; return 0 ; }
Pair of strings having longest common prefix of maximum length in given array | C ++ program to implement the above approach ; Structure of Trie ; Function to insert a string into Trie ; Stores length of the string ; Traverse the string str ; If str [ i ] is not present in current path of Trie ; Create a new node of Trie ; Update root ; Function to find the maximum length of longest common prefix in Trie with str ; Stores length of str ; Stores length of longest common prefix in Trie with str ; Traverse the string str ; If str [ i ] is present in the current path of Trie ; Update len ; Update root ; Function to print the pair having maximum length of the longest common prefix ; Stores index of the string having maximum length of longest common prefix ; Stores maximum length of longest common prefix . ; Create root node of Trie ; Insert arr [ 0 ] into Trie ; Traverse the array . ; Stores maximum length of longest common prefix in Trie with arr [ i ] ; If temp is greater than len ; Update len ; Update idx ; Traverse array arr [ ] ; Stores length of arr [ i ] ; Check if maximum length of longest common prefix > M ; Traverse string arr [ i ] and arr [ j ] ; If current character of both string does not match . ; Print pairs having maximum length of the longest common prefix ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct TrieNode { TrieNode * child [ 256 ] ; TrieNode ( ) { child [ 0 ] = child [ 1 ] = NULL ; } } ; void insertTrie ( TrieNode * root , string str ) { int M = str . length ( ) ; for ( int i = 0 ; i < M ; i ++ ) { if ( ! root -> child [ str [ i ] ] ) { root -> child [ str [ i ] ] = new TrieNode ( ) ; } root = root -> child [ str [ i ] ] ; } } int findStrLen ( TrieNode * root , string str ) { int M = str . length ( ) ; int len = 0 ; for ( int i = 0 ; i < M ; i ++ ) { if ( root -> child [ str [ i ] ] ) { len ++ ; root = root -> child [ str [ i ] ] ; } else { return len ; } } return len ; } void findMaxLenPair ( vector < string > & arr , int N ) { int idx = -1 ; int len = 0 ; TrieNode * root = new TrieNode ( ) ; insertTrie ( root , arr [ 0 ] ) ; for ( int i = 1 ; i < N ; i ++ ) { int temp = findStrLen ( root , arr [ i ] ) ; if ( temp > len ) { len = temp ; idx = i ; } insertTrie ( root , arr [ i ] ) ; } for ( int i = 0 ; i < N ; i ++ ) { int M = arr [ i ] . length ( ) ; if ( i != idx && M >= len ) { bool found = true ; for ( int j = 0 ; j < len ; j ++ ) { if ( arr [ i ] [ j ] != arr [ idx ] [ j ] ) { found = false ; break ; } } if ( found ) { cout << " ( " << arr [ i ] << " , ▁ " << arr [ idx ] << " ) " ; return ; } } } } int main ( ) { vector < string > arr = { " geeksforgeeks " , " geeks " , " geeksforcse " } ; int N = arr . size ( ) ; findMaxLenPair ( arr , N ) ; }
Convert given string to another by minimum replacements of subsequences by its smallest character | C ++ program for the above approach ; Function to return the minimum number of operation ; Storing data ; Initialize both arrays ; Stores the index of character ; Filling str1array , convChar and hashmap convertMap . ; Not possible to convert ; Calculate result Initializing return values ; Iterating the character from the end ; Increment the number of operations ; Not possible to convert ; to check whether the final element has been added in set S or not . ; Check if v1 [ j ] is present in hashmap or not ; Already converted then then continue ; Not possible to convert ; Print the result ; Driver Code ; Given strings ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void transformString ( string str1 , string str2 ) { int N = str1 . length ( ) ; vector < int > convChar [ 26 ] ; vector < int > str1array [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { vector < int > v ; convChar [ i ] = v ; str1array [ i ] = v ; } map < int , char > convertMap ; for ( int i = 0 ; i < N ; i ++ ) { str1array [ str1 [ i ] - ' a ' ] . push_back ( i ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( str1 [ i ] < str2 [ i ] ) { cout << -1 << endl ; return ; } else if ( str1 [ i ] == str2 [ i ] ) continue ; else { convChar [ str2 [ i ] - ' a ' ] . push_back ( i ) ; convertMap [ i ] = str2 [ i ] ; } } int ret = 0 ; vector < vector < int > > retv ; for ( int i = 25 ; i >= 0 ; i -- ) { vector < int > v = convChar [ i ] ; if ( v . size ( ) == 0 ) continue ; ret ++ ; vector < int > v1 = str1array [ i ] ; if ( v1 . size ( ) == 0 ) { cout << -1 << endl ; return ; } bool isScompleted = false ; for ( int j = 0 ; j < v1 . size ( ) ; j ++ ) { if ( convertMap . find ( v1 [ j ] ) != convertMap . end ( ) ) { char a = convertMap [ v1 [ j ] ] ; if ( a > i + ' a ' ) continue ; else { v . push_back ( v1 [ j ] ) ; isScompleted = true ; retv . push_back ( v ) ; break ; } } else { v . push_back ( v1 [ j ] ) ; isScompleted = true ; retv . push_back ( v ) ; break ; } } if ( ! isScompleted ) { cout << -1 << endl ; return ; } } cout << ret << endl ; } int main ( ) { string A = " abcab " ; string B = " aabab " ; transformString ( A , B ) ; return 0 ; }
Find largest subtree having identical left and right subtrees | C ++ program to find the largest subtree having identical left and right subtree ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Sets maxSize to size of largest subtree with identical left and right . maxSize is set with size of the maximum sized subtree . It returns size of subtree rooted with current node . This size is used to keep track of maximum size . ; string to store structure of left and right subtrees ; traverse left subtree and finds its size ; traverse right subtree and finds its size ; if left and right subtrees are similar update maximum subtree if needed ( Note that left subtree may have a bigger value than right and vice versa ) ; append left subtree data ; append current node data ; append right subtree data ; function to find the largest subtree having identical left and right subtree ; Driver program to test above functions ; Let us construct the following Tree 50 / \ 10 60 / \ / \ 5 20 70 70 / \ / \ 65 80 65 80
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int largestSubtreeUtil ( Node * root , string & str , int & maxSize , Node * & maxNode ) { if ( root == NULL ) return 0 ; string left = " " , right = " " ; int ls = largestSubtreeUtil ( root -> left , left , maxSize , maxNode ) ; int rs = largestSubtreeUtil ( root -> right , right , maxSize , maxNode ) ; int size = ls + rs + 1 ; if ( left . compare ( right ) == 0 ) { if ( size > maxSize ) { maxSize = size ; maxNode = root ; } } str . append ( " ▁ " ) . append ( left ) . append ( " ▁ " ) ; str . append ( " ▁ " ) . append ( to_string ( root -> data ) ) . append ( " ▁ " ) ; str . append ( " ▁ " ) . append ( right ) . append ( " ▁ " ) ; return size ; } int largestSubtree ( Node * node , Node * & maxNode ) { int maxSize = 0 ; string str = " " ; largestSubtreeUtil ( node , str , maxSize , maxNode ) ; return maxSize ; } int main ( ) { Node * root = newNode ( 50 ) ; root -> left = newNode ( 10 ) ; root -> right = newNode ( 60 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 20 ) ; root -> right -> left = newNode ( 70 ) ; root -> right -> left -> left = newNode ( 65 ) ; root -> right -> left -> right = newNode ( 80 ) ; root -> right -> right = newNode ( 70 ) ; root -> right -> right -> left = newNode ( 65 ) ; root -> right -> right -> right = newNode ( 80 ) ; Node * maxNode = NULL ; int maxSize = largestSubtree ( root , maxNode ) ; cout << " Largest ▁ Subtree ▁ is ▁ rooted ▁ at ▁ node ▁ " << maxNode -> data << " and its size is " << maxSize ; return 0 ; }
Smallest number containing all possible N length permutations using digits 0 to D | C ++ Program to find the minimum length string consisting of all permutations of length N of D digits ; Initialize set to see if all the possible permutations are present in the min length string ; To keep min length string ; Generate the required string ; Iterate over all the possible character ; Append to make a new string ; If the new string is not visited ; Add in set ; Call the dfs function on the last d characters ; Base case ; Append '0' n - 1 times ; Call the DFS Function ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; set < string > visited ; string ans ; void dfs ( string curr , int D ) { for ( int x = 0 ; x < D ; ++ x ) { char chr = x + '0' ; string neighbour = curr + chr ; if ( visited . find ( neighbour ) == visited . end ( ) ) { visited . insert ( neighbour ) ; dfs ( neighbour . substr ( 1 ) , D ) ; ans . push_back ( chr ) ; } } } string reqString ( int N , int D ) { if ( N == 1 && D == 1 ) return "0" ; visited . clear ( ) ; ans . clear ( ) ; string start ; for ( int i = 0 ; i < N - 1 ; i ++ ) start . append ( "0" ) ; dfs ( start , D ) ; ans . append ( start ) ; return ans ; } int main ( ) { int N = 2 ; int D = 2 ; cout << reqString ( N , D ) << ' ' ; return 0 ; }
Check if a string is a scrambled form of another string | C ++ Program to check if a given string is a scrambled form of another string ; Strings of non - equal length cant ' be scramble strings ; Empty strings are scramble strings ; Equal strings are scramble strings ; Check for the condition of anagram ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ 0. . . i ] and if S2 [ i + 1. . . n ] is a scrambled string of S1 [ i + 1. . . n ] ; Check if S2 [ 0. . . i ] is a scrambled string of S1 [ n - i ... n ] and S2 [ i + 1. . . n ] is a scramble string of S1 [ 0. . . n - i - 1 ] ; If none of the above conditions are satisfied ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isScramble ( string S1 , string S2 ) { if ( S1 . length ( ) != S2 . length ( ) ) { return false ; } int n = S1 . length ( ) ; if ( n == 0 ) { return true ; } if ( S1 == S2 ) { return true ; } string copy_S1 = S1 , copy_S2 = S2 ; sort ( copy_S1 . begin ( ) , copy_S1 . end ( ) ) ; sort ( copy_S2 . begin ( ) , copy_S2 . end ( ) ) ; if ( copy_S1 != copy_S2 ) { return false ; } for ( int i = 1 ; i < n ; i ++ ) { if ( isScramble ( S1 . substr ( 0 , i ) , S2 . substr ( 0 , i ) ) && isScramble ( S1 . substr ( i , n - i ) , S2 . substr ( i , n - i ) ) ) { return true ; } if ( isScramble ( S1 . substr ( 0 , i ) , S2 . substr ( n - i , i ) ) && isScramble ( S1 . substr ( i , n - i ) , S2 . substr ( 0 , n - i ) ) ) { return true ; } } return false ; } int main ( ) { string S1 = " coder " ; string S2 = " ocred " ; if ( isScramble ( S1 , S2 ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Smallest number possible by swapping adjacent even odd pairs | C ++ Program to find the smallest number possible by swapping adjacent digits of different parity ; Function to return the smallest number possible ; Arrays to store odd and even digits in the order of their appearance in the given string ; Insert the odd and even digits ; pointer to odd digit ; pointer to even digit ; In case number of even and odd digits are not equal If odd digits are remaining ; If even digits are remaining ; Removal of leading 0 's ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findAns ( string s ) { int digit ; vector < int > odd ; vector < int > even ; for ( auto c : s ) { digit = c - '0' ; if ( digit & 1 ) odd . push_back ( digit ) ; else even . push_back ( digit ) ; } int i = 0 ; int j = 0 ; string ans = " " ; while ( i < odd . size ( ) and j < even . size ( ) ) { if ( odd [ i ] < even [ j ] ) ans += ( char ) ( odd [ i ++ ] + '0' ) ; else ans += ( char ) ( even [ j ++ ] + '0' ) ; } while ( i < odd . size ( ) ) ans += ( char ) ( odd [ i ++ ] + '0' ) ; while ( j < even . size ( ) ) ans += ( char ) ( even [ j ++ ] + '0' ) ; while ( ans [ 0 ] == '0' ) { ans . erase ( ans . begin ( ) ) ; } return ans ; } int main ( ) { string s = "894687536" ; cout << findAns ( s ) ; return 0 ; }
Program to Convert BCD number into Decimal number | C ++ code to convert BCD to its decimal number ( base 10 ) . ; Function to convert BCD to Decimal ; Iterating through the bits backwards ; Forming the equivalent digit ( 0 to 9 ) from the group of 4. ; Reinitialize all variables and compute the number . ; update the answer ; Reverse the number formed . ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int bcdToDecimal ( string s ) { int len = s . length ( ) , check = 0 , check0 = 0 ; int num = 0 , sum = 0 , mul = 1 , rev = 0 ; for ( int i = len - 1 ; i >= 0 ; i -- ) { sum += ( s [ i ] - '0' ) * mul ; mul *= 2 ; check ++ ; if ( check == 4 i == 0 ) { if ( sum == 0 && check0 == 0 ) { num = 1 ; check0 = 1 ; } else { num = num * 10 + sum ; } check = 0 ; sum = 0 ; mul = 1 ; } } while ( num > 0 ) { rev = rev * 10 + ( num % 10 ) ; num /= 10 ; } if ( check0 == 1 ) return rev - 1 ; return rev ; } int main ( ) { string s = "100000101000" ; cout << bcdToDecimal ( s ) ; return 0 ; }
Find Count of Single Valued Subtrees | C ++ program to find count of single valued subtrees ; A Tree node ; Utility function to create a new node ; This function increments count by number of single valued subtrees under root . It returns true if subtree under root is Singly , else false . ; Return false to indicate NULL ; Recursively count in left and right subtrees also ; If any of the subtrees is not singly , then this cannot be singly . ; If left subtree is singly and non - empty , but data doesn 't match ; Same for right subtree ; If none of the above conditions is true , then tree rooted under root is single valued , increment count and return true . ; This function mainly calls countSingleRec ( ) after initializing count as 0 ; Initialize result ; Recursive function to count ; Driver program to test ; Let us construct the below tree 5 / \ 4 5 / \ \ 4 4 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return ( temp ) ; } bool countSingleRec ( Node * root , int & count ) { if ( root == NULL ) return true ; bool left = countSingleRec ( root -> left , count ) ; bool right = countSingleRec ( root -> right , count ) ; if ( left == false right == false ) return false ; if ( root -> left && root -> data != root -> left -> data ) return false ; if ( root -> right && root -> data != root -> right -> data ) return false ; count ++ ; return true ; } int countSingle ( Node * root ) { int count = 0 ; countSingleRec ( root , count ) ; return count ; } int main ( ) { Node * root = newNode ( 5 ) ; root -> left = newNode ( 4 ) ; root -> right = newNode ( 5 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 4 ) ; root -> right -> right = newNode ( 5 ) ; cout << " Count ▁ of ▁ Single ▁ Valued ▁ Subtrees ▁ is ▁ " << countSingle ( root ) ; return 0 ; }
Count minimum swap to make string palindrome | C ++ program to Count minimum swap to make string palindrome ; Function to Count minimum swap ; calculate length of string as n ; counter to count minimum swap ; A loop which run till mid of string ; Left pointer ; Right pointer ; A loop which run from right pointer towards left pointer ; if both char same then break the loop . If not , then we have to move right pointer to one position left ; If both pointers are at same position , it denotes that we don 't have sufficient characters to make palindrome string ; Driver code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSwap ( string s ) { int n = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) { int left = i ; int right = n - left - 1 ; while ( left < right ) { if ( s [ left ] == s [ right ] ) { break ; } else { right -- ; } } if ( left == right ) { return -1 ; } for ( int j = right ; j < n - left - 1 ; j ++ ) { swap ( s [ j ] , s [ j + 1 ] ) ; count ++ ; } } return count ; } int main ( ) { string s = " geeksfgeeks " ; int ans1 = countSwap ( s ) ; reverse ( s . begin ( ) , s . end ( ) ) ; int ans2 = countSwap ( s ) ; cout << max ( ans1 , ans2 ) ; return 0 ; }
Bitwise XOR of a Binary array | C ++ implementation of the approach ; Function to return the bitwise XOR of all the binary strings ; Get max size and reverse each string Since we have to perform XOR operation on bits from right to left Reversing the string will make it easier to perform operation from left to right ; Add 0 s to the end of strings if needed ; Perform XOR operation on each bit ; Reverse the resultant string to get the final string ; Return the final string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void strBitwiseXOR ( string * arr , int n ) { string result ; int max_len = INT_MIN ; for ( int i = 0 ; i < n ; i ++ ) { max_len = max ( max_len , ( int ) arr [ i ] . size ( ) ) ; reverse ( arr [ i ] . begin ( ) , arr [ i ] . end ( ) ) ; } for ( int i = 0 ; i < n ; i ++ ) { string s ; for ( int j = 0 ; j < max_len - arr [ i ] . size ( ) ; j ++ ) s += '0' ; arr [ i ] = arr [ i ] + s ; } for ( int i = 0 ; i < max_len ; i ++ ) { int pres_bit = 0 ; for ( int j = 0 ; j < n ; j ++ ) pres_bit = pres_bit ^ ( arr [ j ] [ i ] - '0' ) ; result += ( pres_bit + '0' ) ; } reverse ( result . begin ( ) , result . end ( ) ) ; cout << result ; } int main ( ) { string arr [ ] = { "1000" , "10001" , "0011" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; strBitwiseXOR ( arr , n ) ; return 0 ; }
Count of sticks required to represent the given string | C ++ implementation of the above approach ; stick [ ] stores the count of matchsticks required to represent the alphabets ; number [ ] stores the count of matchsticks required to represent the numerals ; Function that return the count of sticks required to represent the given string ; For every char of the given string ; Add the count of sticks required to represent the current character ; Driver code ; Function call to find the count of matchsticks
#include <bits/stdc++.h> NEW_LINE using namespace std ; int sticks [ ] = { 6 , 7 , 4 , 6 , 5 , 4 , 6 , 5 , 2 , 4 , 4 , 3 , 6 , 6 , 6 , 5 , 7 , 6 , 5 , 3 , 5 , 4 , 6 , 4 , 3 , 4 } ; int number [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; int countSticks ( string str ) { int cnt = 0 ; for ( int i = 0 ; str [ i ] ; i ++ ) { char ch = str [ i ] ; if ( ch >= ' A ' && ch <= ' Z ' ) { cnt += sticks [ ch - ' A ' ] ; } else { cnt += number [ ch - '0' ] ; } } return cnt ; } int main ( ) { string str = " GEEKSFORGEEKS " ; cout << countSticks ( str ) ; return 0 ; }
CamelCase Pattern Matching | ; Concatenating all array elements using Aggregate function of LINQ putting semicolon as delimiter after each element ; Map to store the hashing of each words with every uppercase letter found ; temporary Variables ; Traversing through concatenated String ; Identifying if the current Character is CamelCase If so , then adding to map accordingly ; If pattern matches then print the corresponding mapped words ; If delimiter has reached then reseting temporary string also incrementing word position value ; If pattern matches then print the corresponding mapped words ; Driver code ; Array of words ; Pattern to be found ; Function call to find the words that match to the given pattern
#include <bits/stdc++.h> NEW_LINE using namespace std ; void PrintMatchingCamelCase ( vector < string > arr , string pattern ) { string cctdString = " " ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) { cctdString += arr [ i ] ; if ( i != arr . size ( ) - 1 ) cctdString . push_back ( ' ; ' ) ; } unordered_map < string , vector < string > > maps ; int charPos = 0 ; int wordPos = 0 ; string strr = " " ; for ( ; charPos < cctdString . length ( ) ; charPos ++ ) { if ( cctdString [ charPos ] >= ' A ' && cctdString [ charPos ] <= ' Z ' ) { strr += cctdString [ charPos ] ; if ( maps . find ( strr ) != maps . end ( ) ) { vector < string > temp ; temp . insert ( temp . end ( ) , maps [ strr ] . begin ( ) , maps [ strr ] . end ( ) ) ; temp . push_back ( arr [ wordPos ] ) ; maps [ strr ] = temp ; } else { vector < string > vec = { arr [ wordPos ] } ; maps [ strr ] = vec ; } } else if ( cctdString [ charPos ] == ' ; ' ) { wordPos ++ ; strr = " " ; } } if ( maps . find ( pattern ) != maps . end ( ) ) { for ( int i = 0 ; i < maps [ pattern ] . size ( ) ; i ++ ) { cout << maps [ pattern ] [ i ] << endl ; } } else { cout << " No ▁ Match ▁ Found " << endl ; } } int main ( ) { vector < string > arr = { " Hi " , " Hello " , " HelloWorld " , " HiTech " , " HiGeek " , " HiTechWorld " , " HiTechCity " , " HiTechLab " } ; string pattern = " HT " ; PrintMatchingCamelCase ( arr , pattern ) ; }
Find the last remaining Character in the Binary String according to the given conditions | C ++ implementation of the above approach ; Delete counters for each to count the deletes ; Counters to keep track of characters left from each type ; Queue to simulate the process ; Initializing the queue ; Looping till at least 1 digit is left from both the type ; If there is a floating delete for current character we will delete it and move forward otherwise we will increase delete counter for opposite digit ; If 0 are left then answer is 0 else answer is 1 ; Driver Code ; Input String ; Length of String ; Printing answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; string remainingDigit ( string S , int N ) { int del [ ] = { 0 , 0 } ; int count [ ] = { 0 , 0 } ; queue < int > q ; for ( int i = 0 ; i < N ; i ++ ) { int x = S [ i ] == '1' ? 1 : 0 ; count [ x ] ++ ; q . push ( x ) ; } while ( count [ 0 ] > 0 && count [ 1 ] > 0 ) { int t = q . front ( ) ; q . pop ( ) ; if ( del [ t ] > 0 ) { del [ t ] -- ; count [ t ] -- ; } else { del [ t ^ 1 ] ++ ; q . push ( t ) ; } } if ( count [ 0 ] > 0 ) return "0" ; return "1" ; } int main ( ) { string S = "1010100100000" ; int N = S . length ( ) ; cout << remainingDigit ( S , N ) ; }
Closest leaf to a given node in Binary Tree | Find closest leaf to the given node x in a tree ; A Tree node ; Utility function to create a new node ; This function finds closest leaf to root . This distance is stored at * minDist . ; base case ; If this is a leaf node , then check if it is closer than the closest so far ; Recur for left and right subtrees ; This function finds if there is closer leaf to x through parent node . ; Base cases ; Search x in left subtree of root ; If left subtree has x ; Find closest leaf in right subtree ; Search x in right subtree of root ; If right subtree has x ; Find closest leaf in left subtree ; Returns minimum distance of a leaf from given node x ; Initialize result ( minimum distance from a leaf ) ; Find closest leaf down to x ; See if there is a closer leaf through parent ; Driver program ; Let us create Binary Tree shown in above example
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( int key ) { Node * temp = new Node ; temp -> key = key ; temp -> left = temp -> right = NULL ; return ( temp ) ; } void findLeafDown ( Node * root , int lev , int * minDist ) { if ( root == NULL ) return ; if ( root -> left == NULL && root -> right == NULL ) { if ( lev < ( * minDist ) ) * minDist = lev ; return ; } findLeafDown ( root -> left , lev + 1 , minDist ) ; findLeafDown ( root -> right , lev + 1 , minDist ) ; } int findThroughParent ( Node * root , Node * x , int * minDist ) { if ( root == NULL ) return -1 ; if ( root == x ) return 0 ; int l = findThroughParent ( root -> left , x , minDist ) ; if ( l != -1 ) { findLeafDown ( root -> right , l + 2 , minDist ) ; return l + 1 ; } int r = findThroughParent ( root -> right , x , minDist ) ; if ( r != -1 ) { findLeafDown ( root -> left , r + 2 , minDist ) ; return r + 1 ; } return -1 ; } int minimumDistance ( Node * root , Node * x ) { int minDist = INT_MAX ; findLeafDown ( x , 0 , & minDist ) ; findThroughParent ( root , x , & minDist ) ; return minDist ; } int main ( ) { Node * root = newNode ( 1 ) ; root -> left = newNode ( 12 ) ; root -> right = newNode ( 13 ) ; root -> right -> left = newNode ( 14 ) ; root -> right -> right = newNode ( 15 ) ; root -> right -> left -> left = newNode ( 21 ) ; root -> right -> left -> right = newNode ( 22 ) ; root -> right -> right -> left = newNode ( 23 ) ; root -> right -> right -> right = newNode ( 24 ) ; root -> right -> left -> left -> left = newNode ( 1 ) ; root -> right -> left -> left -> right = newNode ( 2 ) ; root -> right -> left -> right -> left = newNode ( 3 ) ; root -> right -> left -> right -> right = newNode ( 4 ) ; root -> right -> right -> left -> left = newNode ( 5 ) ; root -> right -> right -> left -> right = newNode ( 6 ) ; root -> right -> right -> right -> left = newNode ( 7 ) ; root -> right -> right -> right -> right = newNode ( 8 ) ; Node * x = root -> right ; cout << " The ▁ closest ▁ leaf ▁ to ▁ the ▁ node ▁ with ▁ value ▁ " << x -> key << " ▁ is ▁ at ▁ a ▁ distance ▁ of ▁ " << minimumDistance ( root , x ) << endl ; return 0 ; }
Find the closest leaf in a Binary Tree | A C ++ program to find the closesr leaf of a given key in Binary Tree ; A binary tree Node has key , pocharer to left and right children ; Helper function that allocates a new node with the given data and NULL left and right pocharers . ; A utility function to find minimum of x and y ; A utility function to find distance of closest leaf of the tree rooted under given root ; Base cases ; Return minimum of left and right , plus one ; Returns distance of the cloest leaf to a given key ' k ' . The array ancestors is used to keep track of ancestors of current node and ' index ' is used to keep track of curremt index in ' ancestors [ ] ' ; Base case ; If key found ; Find the cloest leaf under the subtree rooted with given key ; Traverse all ancestors and update result if any parent node gives smaller distance ; If key node found , store current node and recur for left and right childrens ; The main function that returns distance of the closest key to ' k ' . It mainly uses recursive function findClosestUtil ( ) to find the closes distance . ; Create an array to store ancestors Assumptiom : Maximum height of tree is 100 ; Driver program to test above functions ; Let us construct the BST shown in the above figure
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { char key ; struct Node * left , * right ; } ; Node * newNode ( char k ) { Node * node = new Node ; node -> key = k ; node -> right = node -> left = NULL ; return node ; } int getMin ( int x , int y ) { return ( x < y ) ? x : y ; } int closestDown ( struct Node * root ) { if ( root == NULL ) return INT_MAX ; if ( root -> left == NULL && root -> right == NULL ) return 0 ; return 1 + getMin ( closestDown ( root -> left ) , closestDown ( root -> right ) ) ; } int findClosestUtil ( struct Node * root , char k , struct Node * ancestors [ ] , int index ) { if ( root == NULL ) return INT_MAX ; if ( root -> key == k ) { int res = closestDown ( root ) ; for ( int i = index - 1 ; i >= 0 ; i -- ) res = getMin ( res , index - i + closestDown ( ancestors [ i ] ) ) ; return res ; } ancestors [ index ] = root ; return getMin ( findClosestUtil ( root -> left , k , ancestors , index + 1 ) , findClosestUtil ( root -> right , k , ancestors , index + 1 ) ) ; } int findClosest ( struct Node * root , char k ) { struct Node * ancestors [ 100 ] ; return findClosestUtil ( root , k , ancestors , 0 ) ; } int main ( ) { struct Node * root = newNode ( ' A ' ) ; root -> left = newNode ( ' B ' ) ; root -> right = newNode ( ' C ' ) ; root -> right -> left = newNode ( ' E ' ) ; root -> right -> right = newNode ( ' F ' ) ; root -> right -> left -> left = newNode ( ' G ' ) ; root -> right -> left -> left -> left = newNode ( ' I ' ) ; root -> right -> left -> left -> right = newNode ( ' J ' ) ; root -> right -> right -> right = newNode ( ' H ' ) ; root -> right -> right -> right -> left = newNode ( ' K ' ) ; char k = ' H ' ; cout << " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " << k << " ▁ is ▁ " << findClosest ( root , k ) << endl ; k = ' C ' ; cout << " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " << k << " ▁ is ▁ " << findClosest ( root , k ) << endl ; k = ' E ' ; cout << " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " << k << " ▁ is ▁ " << findClosest ( root , k ) << endl ; k = ' B ' ; cout << " Distance ▁ of ▁ the ▁ closest ▁ key ▁ from ▁ " << k << " ▁ is ▁ " << findClosest ( root , k ) << endl ; return 0 ; }
Find the time which is palindromic and comes after the given time | C ++ implementation of the approach ; Function to return the required time ; To store the resultant time ; Hours are stored in h as integer ; Minutes are stored in m as integer ; Reverse of h ; Reverse of h as a string ; If MM < reverse of ( HH ) ; 0 is added if HH < 10 ; 0 is added if rev_h < 10 ; Increment hours ; Reverse of the hour after incrementing 1 ; 0 is added if HH < 10 ; 0 is added if rev_h < 10 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; typedef long long ll ; string getTime ( string s , int n ) { string res ; int h = stoi ( s . substr ( 0 , 2 ) ) ; int m = stoi ( s . substr ( 3 , 2 ) ) ; int rev_h = ( h % 10 ) * 10 + ( ( h % 100 ) - ( h % 10 ) ) / 10 ; string rev_hs = to_string ( rev_h ) ; if ( h == 23 && m >= 32 ) { res = " - 1" ; } else if ( m < rev_h ) { string temp ; if ( h < 10 ) temp = "0" ; temp = temp + to_string ( h ) ; if ( rev_h < 10 ) res = res + temp + " : 0" + rev_hs ; else res = res + temp + " : " + rev_hs ; } else { h ++ ; rev_h = ( h % 10 ) * 10 + ( ( h % 100 ) - ( h % 10 ) ) / 10 ; rev_hs = to_string ( rev_h ) ; string temp ; if ( h < 10 ) temp = "0" ; temp = temp + to_string ( h ) ; if ( rev_h < 10 ) res = res + temp + " : 0" + rev_hs ; else res = res + temp + " : " + rev_hs ; } return res ; } int main ( ) { string s = "21:12" ; int n = s . length ( ) ; cout << getTime ( s , n ) ; return 0 ; }
Count of sub | C ++ implementation of the approach ; Function to return the count of valid sub - strings ; Variable ans to store all the possible substrings Initialize its value as total number of substrings that can be formed from the given string ; Stores recent index of the characters ; If character is a update a 's index and the variable ans ; If character is b update b 's index and the variable ans ; If character is c update c 's index and the variable ans ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSubstring ( char str [ ] , int n ) { int ans = ( n * ( n + 1 ) ) / 2 ; int a_index = 0 ; int b_index = 0 ; int c_index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' a ' ) { a_index = i + 1 ; ans -= min ( b_index , c_index ) ; } else if ( str [ i ] == ' b ' ) { b_index = i + 1 ; ans -= min ( a_index , c_index ) ; } else { c_index = i + 1 ; ans -= min ( a_index , b_index ) ; } } return ans ; } int main ( ) { char str [ ] = " babac " ; int n = strlen ( str ) ; cout << CountSubstring ( str , n ) ; return 0 ; }
Find the numbers of strings that can be formed after processing Q queries | C ++ program to implement above approach ; To store the size of string and number of queries ; To store parent and rank of ith place ; To store maximum interval ; Function for initialization ; Function to find parent ; Function to make union ; Power function to calculate a raised to m1 under modulo 10000007 ; Function to take maxmium interval ; Function to find different possible strings ; make union of all chracters which are meant to be same ; find number of different sets formed ; return the required answer ; Driver Code ; queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 2005 NEW_LINE #define mod (int)(1e9 + 7) NEW_LINE int n , q ; int par [ N ] , Rank [ N ] ; map < int , int > m ; void initialize ( ) { for ( int i = 0 ; i <= n ; i ++ ) { par [ i ] = i ; Rank [ i ] = 0 ; } } int find ( int x ) { if ( par [ x ] != x ) par [ x ] = find ( par [ x ] ) ; return par [ x ] ; } void Union ( int x , int y ) { int xpar = find ( x ) ; int ypar = find ( y ) ; if ( Rank [ xpar ] < Rank [ ypar ] ) par [ xpar ] = ypar ; else if ( Rank [ xpar ] > Rank [ ypar ] ) par [ ypar ] = xpar ; else { par [ ypar ] = xpar ; Rank [ xpar ] ++ ; } } int power ( long long a , long long m1 ) { if ( m1 == 0 ) return 1 ; else if ( m1 == 1 ) return a ; else if ( m1 == 2 ) return ( 1LL * a * a ) % mod ; else if ( m1 & 1 ) return ( 1LL * a * power ( power ( a , m1 / 2 ) , 2 ) ) % mod ; else return power ( power ( a , m1 / 2 ) , 2 ) % mod ; } void query ( int l , int r ) { m [ l + r ] = max ( m [ l + r ] , r ) ; } int possiblestrings ( ) { initialize ( ) ; for ( auto i = m . begin ( ) ; i != m . end ( ) ; i ++ ) { int x = i -> first - i -> second ; int y = i -> second ; while ( x < y ) { Union ( x , y ) ; x ++ ; y -- ; } } int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( par [ i ] == i ) ans ++ ; return power ( 26 , ans ) % mod ; } int main ( ) { n = 4 ; query ( 1 , 3 ) ; query ( 2 , 4 ) ; cout << possiblestrings ( ) ; return 0 ; }
Iterative Search for a key ' x ' in Binary Tree | Iterative level order traversal based method to search in Binary Tree ; A binary tree node has data , left child and right child ; Constructor that allocates a new node with the given data and NULL left and right pointers . ; An iterative process to search an element x in a given binary tree ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; Queue based level order traversal ; See if current node is same as x ; Remove current node and enqueue its children ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node ( int data ) { this -> data = data ; this -> left = NULL ; this -> right = NULL ; } } ; bool iterativeSearch ( node * root , int x ) { if ( root == NULL ) return false ; queue < node * > q ; q . push ( root ) ; while ( q . empty ( ) == false ) { node * node = q . front ( ) ; if ( node -> data == x ) return true ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; } return false ; } int main ( ) { node * NewRoot = NULL ; node * root = new node ( 2 ) ; root -> left = new node ( 7 ) ; root -> right = new node ( 5 ) ; root -> left -> right = new node ( 6 ) ; root -> left -> right -> left = new node ( 1 ) ; root -> left -> right -> right = new node ( 11 ) ; root -> right -> right = new node ( 9 ) ; root -> right -> right -> left = new node ( 4 ) ; iterativeSearch ( root , 6 ) ? cout << " Found STRNEWLINE " : cout << " Not ▁ Found STRNEWLINE " ; iterativeSearch ( root , 12 ) ? cout << " Found STRNEWLINE " : cout << " Not ▁ Found STRNEWLINE " ; return 0 ; }
Populate Inorder Successor for all nodes | C ++ program to populate inorder traversal of all nodes ; An implementation that doesn 't use static variable A wrapper over populateNextRecur ; The first visited node will be the rightmost node next of the rightmost node will be NULL ; Set next of all descendents of p by traversing them in reverse Inorder ; First set the next pointer in right subtree ; Set the next as previously visited node in reverse Inorder ; Change the prev for subsequent node ; Finally , set the next pointer in right subtree
#include <bits/stdc++.h> NEW_LINE using namespace std ; class node { public : int data ; node * left ; node * right ; node * next ; } ; void populateNext ( node * root ) { node * next = NULL ; populateNextRecur ( root , & next ) ; } void populateNextRecur ( node * p , node * * next_ref ) { if ( p ) { populateNextRecur ( p -> right , next_ref ) ; p -> next = * next_ref ; * next_ref = p ; populateNextRecur ( p -> left , next_ref ) ; } }
Check if a binary string contains consecutive same or not | C ++ implementation of the approach ; Function that returns true is str is valid ; Assuming the string is binary If any two consecutive characters are equal then the string is invalid ; If the string is alternating ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( string str , int len ) { for ( int i = 1 ; i < len ; i ++ ) { if ( str [ i ] == str [ i - 1 ] ) return false ; } return true ; } int main ( ) { string str = "0110" ; int len = str . length ( ) ; if ( isValid ( str , len ) ) cout << " Valid " ; else cout << " Invalid " ; return 0 ; }
Minimum K such that every substring of length atleast K contains a character c | CPP Program to find minimum K such that every substring of length atleast K contains some character c ; This function checks if there exists some character which appears in all K length substrings ; Iterate over all possible characters ; stores the last occurrence ; set answer as true ; ; No occurrence found of current character in first substring of length K ; Check for every last substring of length K where last occurr - ence exists in substring ; If last occ is not present in substring ; current character is K amazing ; This function performs binary search over the answer to minimise it ; Check if answer is found try to minimise it ; Driver Code to test above functions
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( string s , int K ) { for ( int ch = 0 ; ch < 26 ; ch ++ ) { char c = ' a ' + ch ; int last = -1 ; bool found = true ; for ( int i = 0 ; i < K ; i ++ ) if ( s [ i ] == c ) last = i ; if ( last == -1 ) continue ; for ( int i = K ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == c ) last = i ; if ( last <= ( i - K ) ) { found = false ; break ; } } if ( found ) return 1 ; } return 0 ; } int binarySearch ( string s ) { int low = 1 , high = ( int ) s . size ( ) ; int ans ; while ( low <= high ) { int mid = ( high + low ) >> 1 ; if ( check ( s , mid ) ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } int32_t main ( ) { string s = " abcde " ; cout << binarySearch ( s ) << endl ; s = " aaaa " ; cout << binarySearch ( s ) << endl ; return 0 ; }
Check if number can be displayed using seven segment led | C ++ implementation of above approach ; Pre - computed values of segment used by digit 0 to 9. ; Check if it is possible to display the number ; Finding sum of the segments used by each digit of the number ; Driven Program ; Function call to print required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int seg [ 10 ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 6 } ; string LedRequired ( string s , int led ) { int count = 0 ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { count += seg [ int ( s [ i ] ) - 48 ] ; } if ( count <= led ) return " YES " ; else return " NO " ; } int main ( ) { string S = "123456789" ; int led = 20 ; cout << LedRequired ( S , led ) << endl ; return 0 ; }
Count the number of vowels occurring in all the substrings of given string | C ++ implementation of the above approach ; Returns the total sum of occurrences of all vowels ; No . of occurrences of 0 th character in all the substrings ; No . of occurrences of the ith character in all the substrings ; Check if ith character is a vowel ; Return the total sum of occurrences of vowels ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int vowel_calc ( string s ) { int n = s . length ( ) ; vector < int > arr ; for ( int i = 0 ; i < n ; i ++ ) { if ( i == 0 ) arr . push_back ( n ) ; else arr . push_back ( ( n - i ) + arr [ i - 1 ] - i ) ; } int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) sum += arr [ i ] ; return sum ; } int main ( ) { string s = " daceh " ; cout << vowel_calc ( s ) << endl ; return 0 ; }
Iterative Search for a key ' x ' in Binary Tree | An iterative method to search an item in Binary Tree ; A binary tree node has data , left child and right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; iterative process to search an element x in a given binary tree ; Base Case ; Create an empty stack and push root to it ; Do iterative preorder traversal to search x ; See the top item from stack and check if it is same as x ; Push right and left children of the popped node to stack ; Driver program
#include <iostream> NEW_LINE #include <stack> NEW_LINE using namespace std ; struct node { int data ; struct node * left , * right ; } ; struct node * newNode ( int data ) { struct node * node = new struct node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } bool iterativeSearch ( node * root , int x ) { if ( root == NULL ) return false ; stack < node * > nodeStack ; nodeStack . push ( root ) ; while ( nodeStack . empty ( ) == false ) { struct node * node = nodeStack . top ( ) ; if ( node -> data == x ) return true ; nodeStack . pop ( ) ; if ( node -> right ) nodeStack . push ( node -> right ) ; if ( node -> left ) nodeStack . push ( node -> left ) ; } return false ; } int main ( void ) { struct node * NewRoot = NULL ; struct node * root = newNode ( 2 ) ; root -> left = newNode ( 7 ) ; root -> right = newNode ( 5 ) ; root -> left -> right = newNode ( 6 ) ; root -> left -> right -> left = newNode ( 1 ) ; root -> left -> right -> right = newNode ( 11 ) ; root -> right -> right = newNode ( 9 ) ; root -> right -> right -> left = newNode ( 4 ) ; iterativeSearch ( root , 6 ) ? cout << " Found STRNEWLINE " : cout << " Not ▁ Found STRNEWLINE " ; iterativeSearch ( root , 12 ) ? cout << " Found STRNEWLINE " : cout << " Not ▁ Found STRNEWLINE " ; return 0 ; }
Check whether two strings can be made equal by increasing prefixes | C ++ implementation of above approach ; check whether the first string can be converted to the second string by increasing the ASCII value of prefix string of first string ; length of two strings ; If lengths are not equal ; store the difference of ASCII values ; difference of first element ; traverse through the string ; the ASCII value of the second string should be greater than or equal to first string , if it is violated return false . ; store the difference of ASCII values ; the difference of ASCII values should be in descending order ; if the difference array is not in descending order ; if all the ASCII values of characters of first string is less than or equal to the second string and the difference array is in descending order , return true ; Driver code ; create two strings ; check whether the first string can be converted to the second string
#include <iostream> NEW_LINE using namespace std ; bool find ( string s1 , string s2 ) { int len = s1 . length ( ) , len_1 = s2 . length ( ) ; if ( len != len_1 ) return false ; int d [ len ] = { 0 } ; d [ 0 ] = s2 [ 0 ] - s1 [ 0 ] ; for ( int i = 1 ; i < len ; i ++ ) { if ( s1 [ i ] > s2 [ i ] ) return false ; else { d [ i ] = s2 [ i ] - s1 [ i ] ; } } for ( int i = 0 ; i < len - 1 ; i ++ ) { if ( d [ i ] < d [ i + 1 ] ) return false ; } return true ; } int main ( ) { string s1 = " abcd " , s2 = " bcdd " ; if ( find ( s1 , s2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count all palindrome which is square of a palindrome | C ++ implementation of the above approach ; check if a number is a palindrome ; Function to return required count of palindromes ; Upper limit ; count odd length palindromes ; if s = '1234' ; then , t = '1234321' ; count even length palindromes ; if s = '1234' ; then , t = '12344321' ; Return count of super - palindromes ; Driver Code ; function call to get required answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool ispalindrome ( int x ) { int ans = 0 ; int temp = x ; while ( temp > 0 ) { ans = 10 * ans + temp % 10 ; temp = temp / 10 ; } return ans == x ; } int SuperPalindromes ( int L , int R ) { int LIMIT = 100000 ; int ans = 0 ; for ( int i = 0 ; i < LIMIT ; i ++ ) { string s = to_string ( i ) ; string rs = s . substr ( 0 , s . size ( ) - 1 ) ; reverse ( rs . begin ( ) , rs . end ( ) ) ; string p = s + rs ; int p_sq = pow ( stoi ( p ) , 2 ) ; if ( p_sq > R ) break ; if ( p_sq >= L and ispalindrome ( p_sq ) ) ans = ans + 1 ; } for ( int i = 0 ; i < LIMIT ; i ++ ) { string s = to_string ( i ) ; string rs = s ; reverse ( rs . begin ( ) , rs . end ( ) ) ; string p = s + rs ; int p_sq = pow ( stoi ( p ) , 2 ) ; if ( p_sq > R ) break ; if ( p_sq >= L and ispalindrome ( p_sq ) ) ans = ans + 1 ; } return ans ; } int main ( ) { string L = "4" ; string R = "1000" ; printf ( " % d STRNEWLINE " , SuperPalindromes ( stoi ( L ) , stoi ( R ) ) ) ; return 0 ; }
N | C ++ program to find the N - th character in the string "1234567891011 . . " ; Function that returns the N - th character ; initially null string ; starting integer ; add integers in string ; one digit numbers added ; more than 1 digit number , generate equivalent number in a string s1 and concatenate s1 into s . ; add the number in string ; reverse the string ; attach the number ; if the length exceeds N ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char NthCharacter ( int n ) { string s = " " ; int c = 1 ; for ( int i = 1 ; ; i ++ ) { if ( c < 10 ) s += char ( 48 + c ) ; else { string s1 = " " ; int dup = c ; while ( dup ) { s1 += char ( ( dup % 10 ) + 48 ) ; dup /= 10 ; } reverse ( s1 . begin ( ) , s1 . end ( ) ) ; s += s1 ; } c ++ ; if ( s . length ( ) >= n ) { return s [ n - 1 ] ; } } } int main ( ) { int n = 11 ; cout << NthCharacter ( n ) ; return 0 ; }
Sub | C ++ implementation of above approach ; Function that counts all the sub - strings of length ' k ' which have all identical characters ; count of sub - strings , length , initial position of sliding window ; map to store the frequency of the characters of sub - string ; increase the frequency of the character and length of the sub - string ; if the length of the sub - string is greater than K ; remove the character from the beginning of sub - string ; if the length of the sub string is equal to k and frequency of one of its characters is equal to the length of the sub - string i . e . all the characters are same increase the count ; display the number of valid sub - strings ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string s , int k ) { int count = 0 , length = 0 , pos = 0 ; map < char , int > m ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { m [ s [ i ] ] ++ ; length ++ ; if ( length > k ) { m [ s [ pos ++ ] ] -- ; length -- ; } if ( length == k && m [ s [ i ] ] == length ) count ++ ; } cout << count << endl ; } int main ( ) { string s = " aaaabbbccdddd " ; int k = 4 ; solve ( s , k ) ; return 0 ; }
Program to replace every space in a string with hyphen | C ++ program to replace space with - ; Get the String ; Traverse the string character by character . ; Changing the ith character to ' - ' if it 's a space. ; Print the modified string .
#include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; int main ( ) { string str = " A ▁ computer ▁ science ▁ portal ▁ for ▁ geeks " ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { if ( str [ i ] == ' ▁ ' ) { str [ i ] = ' - ' ; } } cout << str << endl ; return 0 ; }
Minimum operation require to make first and last character same | CPP program to find minimum operation require to make first and last character same ; Function to find minimum operation require to make first and last character same ; Base conditions ; If answer found ; If string is already visited ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Store the minimum value ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = INT_MAX ; map < string , int > m ; int Min = INT_MAX ; int minOperation ( string & s , int i , int j , int count ) { if ( ( i >= s . size ( ) && j < 0 ) || ( i == j ) ) return MAX ; if ( s [ i ] == s [ j ] || ( count >= Min ) ) return count ; string str = to_string ( i ) + " | " + to_string ( j ) ; if ( m . find ( str ) == m . end ( ) ) { if ( i >= s . size ( ) ) m [ str ] = minOperation ( s , i , j - 1 , count + 1 ) ; else if ( j < 0 ) m [ str ] = minOperation ( s , i + 1 , j , count + 1 ) ; else m [ str ] = min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) ; } if ( m [ str ] < Min ) Min = m [ str ] ; return m [ str ] ; } int main ( ) { string s = " bacdefghipalop " ; int ans = minOperation ( s , 0 , s . size ( ) - 1 , 0 ) ; if ( ans == MAX ) cout << -1 ; else cout << ans ; }
Check if any permutation of a large number is divisible by 8 | C ++ program to check if any permutation of a large number is divisible by 8 or not ; Function to check if any permutation of a large number is divisible by 8 ; Less than three digit number can be checked directly . ; check for the reverse of a number ; Stores the Frequency of characters in the n . ; Iterates for all three digit numbers divisible by 8 ; stores the frequency of all single digit in three - digit number ; check if the original number has the digit ; when all are checked its not possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool solve ( string n , int l ) { if ( l < 3 ) { if ( stoi ( n ) % 8 == 0 ) return true ; reverse ( n . begin ( ) , n . end ( ) ) ; if ( stoi ( n ) % 8 == 0 ) return true ; return false ; } int hash [ 10 ] = { 0 } ; for ( int i = 0 ; i < l ; i ++ ) hash [ n [ i ] - '0' ] ++ ; for ( int i = 104 ; i < 1000 ; i += 8 ) { int dup = i ; int freq [ 10 ] = { 0 } ; freq [ dup % 10 ] ++ ; dup = dup / 10 ; freq [ dup % 10 ] ++ ; dup = dup / 10 ; freq [ dup % 10 ] ++ ; dup = i ; if ( freq [ dup % 10 ] > hash [ dup % 10 ] ) continue ; dup = dup / 10 ; if ( freq [ dup % 10 ] > hash [ dup % 10 ] ) continue ; dup = dup / 10 ; if ( freq [ dup % 10 ] > hash [ dup % 10 ] ) continue ; return true ; } return false ; } int main ( ) { string number = "31462708" ; int l = number . length ( ) ; if ( solve ( number , l ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Lexicographically smallest string formed by appending a character from the first K characters of a given string | C ++ program to find the new string after performing deletions and append operation in the string s ; Function to find the new string thus formed by removing characters ; new string ; Remove characters until the string is empty ; Traverse to find the smallest character in the first k characters ; append the smallest character ; removing the lexicographically smallest character from the string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string newString ( string s , int k ) { string X = " " ; while ( s . length ( ) > 0 ) { char temp = s [ 0 ] ; for ( long long i = 1 ; i < k and i < s . length ( ) ; i ++ ) { if ( s [ i ] < temp ) { temp = s [ i ] ; } } X = X + temp ; for ( long long i = 0 ; i < k ; i ++ ) { if ( s [ i ] == temp ) { s . erase ( s . begin ( ) + i ) ; break ; } } } return X ; } int main ( ) { string s = " gaurang " ; int k = 3 ; cout << newString ( s , k ) ; }
Palindrome by swapping only one character | C ++ program palindrome by swapping only one character ; counts the number of differences which prevents the string from being palindrome . ; keeps a record of the characters that prevents the string from being palindrome . ; loops from the start of a string till the midpoint of the string ; difference is encountered preventing the string from being palindrome ; 3 rd differences encountered and its no longer possible to make is palindrome by one swap ; record the different character ; store the different characters ; its already palindrome ; only one difference is found ; if the middleChar matches either of the difference producing characters , return true ; two differences are found ; if the characters contained in the two sets are same , return true ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindromePossible ( string input ) { int len = input . length ( ) ; int diffCount = 0 , i ; char diff [ 2 ] [ 2 ] ; for ( i = 0 ; i < len / 2 ; i ++ ) { if ( input [ i ] != input [ len - i - 1 ] ) { if ( diffCount == 2 ) return false ; diff [ diffCount ] [ 0 ] = input [ i ] ; diff [ diffCount ++ ] [ 1 ] = input [ len - i - 1 ] ; } } switch ( diffCount ) { case 0 : return true ; case 1 : { char midChar = input [ i ] ; if ( len % 2 != 0 and ( diff [ 0 ] [ 0 ] == midChar or diff [ 0 ] [ 1 ] == midChar ) ) return true ; } case 2 : if ( ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 0 ] and diff [ 0 ] [ 1 ] == diff [ 1 ] [ 1 ] ) or ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 1 ] and diff [ 0 ] [ 1 ] == diff [ 1 ] [ 0 ] ) ) return true ; } return false ; } int main ( ) { cout << boolalpha << isPalindromePossible ( " bbg " ) << endl ; cout << boolalpha << isPalindromePossible ( " bdababd " ) << endl ; cout << boolalpha << isPalindromePossible ( " gcagac " ) << endl ; return 0 ; }
Convert String into Binary Sequence | C ++ program to convert string into binary string ; utility function ; convert each char to ASCII value ; Convert ASCII value to binary ; driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void strToBinary ( string s ) { int n = s . length ( ) ; for ( int i = 0 ; i <= n ; i ++ ) { int val = int ( s [ i ] ) ; string bin = " " ; while ( val > 0 ) { ( val % 2 ) ? bin . push_back ( '1' ) : bin . push_back ( '0' ) ; val /= 2 ; } reverse ( bin . begin ( ) , bin . end ( ) ) ; cout << bin << " ▁ " ; } } int main ( ) { string s = " geeks " ; strToBinary ( s ) ; return 0 ; }
Sparse Search | C ++ program to implement binary search in a sparse array . ; Binary Search in an array with blanks ; Modified Part ; Search for both side for a non empty string ; No non - empty string on both sides ; Normal Binary Search ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int binarySearch ( string * arr , int low , int high , string x ) { if ( low > high ) return -1 ; int mid = ( low + high ) / 2 ; if ( arr [ mid ] == " " ) { int left = mid - 1 ; int right = mid + 1 ; while ( 1 ) { if ( left < low && right > high ) return -1 ; if ( left >= low && arr [ left ] != " " ) { mid = left ; break ; } else if ( right <= high && arr [ right ] != " " ) { mid = right ; break ; } left -- ; right ++ ; } } if ( arr [ mid ] == x ) return mid ; else if ( arr [ mid ] > x ) return binarySearch ( arr , low , mid - 1 , x ) ; else return binarySearch ( arr , mid + 1 , high , x ) ; } int sparseSearch ( string arr [ ] , string x , int n ) { return binarySearch ( arr , 0 , n - 1 , x ) ; } int main ( ) { ios_base :: sync_with_stdio ( false ) ; string arr [ ] = { " for " , " geeks " , " " , " " , " " , " " , " ide " , " practice " , " " , " " , " " , " quiz " } ; string x = " geeks " ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int index = sparseSearch ( arr , x , n ) ; if ( index != -1 ) cout << x << " ▁ found ▁ at ▁ index ▁ " << index << " STRNEWLINE " ; else cout << x << " ▁ not ▁ found STRNEWLINE " ; return 0 ; }
Print distinct sorted permutations with duplicates allowed in input | C ++ program to print all permutations of a string in sorted order . ; Calculating factorial of a number ; Method to find total number of permutations ; Building Map to store frequencies of all characters . ; Traversing map and finding duplicate elements . ; Start traversing from the end and find position ' i - 1' of the first character which is greater than its successor . ; Finding smallest character after ' i - 1' and greater than temp [ i - 1 ] ; Swapping the above found characters . ; Sort all digits from position next to ' i - 1' to end of the string . ; Print the String ; Sorting String ; Print first permutation ; Finding the total permutations ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int factorial ( int n ) { int f = 1 ; for ( int i = 1 ; i <= n ; i ++ ) f = f * i ; return f ; } int calculateTotal ( string temp , int n ) { int f = factorial ( n ) ; map < char , int > hm ; for ( int i = 0 ; i < temp . length ( ) ; i ++ ) { hm [ temp [ i ] ] ++ ; } for ( auto e : hm ) { int x = e . second ; if ( x > 1 ) { int temp5 = factorial ( x ) ; f /= temp5 ; } return f ; } } static void nextPermutation ( string & temp ) { int i ; for ( i = temp . length ( ) - 1 ; i > 0 ; i -- ) if ( temp [ i ] > temp [ i - 1 ] ) break ; int min = i ; int j , x = temp [ i - 1 ] ; for ( j = i + 1 ; j < temp . length ( ) ; j ++ ) if ( ( temp [ j ] < temp [ min ] ) and ( temp [ j ] > x ) ) min = j ; swap ( temp [ i - 1 ] , temp [ min ] ) ; sort ( temp . begin ( ) + i , temp . end ( ) ) ; cout << temp << endl ; } void printAllPermutations ( string s ) { string temp ( s ) ; sort ( temp . begin ( ) , temp . end ( ) ) ; cout << temp << endl ; int total = calculateTotal ( temp , temp . length ( ) ) ; for ( int i = 1 ; i < total ; i ++ ) { nextPermutation ( temp ) ; } } int main ( ) { string s = " AAB " ; printAllPermutations ( s ) ; }
Swap Nodes in Binary tree of every k 'th level | c ++ program swap nodes ; A Binary Tree Node ; function to create a new tree node ; swap two Node ; A utility function swap left - node & right node of tree of every k 'th level ; base case ; if current level + 1 is present in swap vector then we swap left & right node ; Recur for left and right subtrees ; This function mainly calls recursive function swapEveryKLevelUtil ( ) ; call swapEveryKLevelUtil function with initial level as 1. ; Utility method for inorder tree traversal ; Driver Code ; 1 / \ 2 3 / / \ 4 7 8
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; Node * newNode ( int data ) { Node * temp = new Node ; temp -> data = data ; temp -> left = temp -> right = NULL ; return temp ; } void Swap ( Node * * a , Node * * b ) { Node * temp = * a ; * a = * b ; * b = temp ; } void swapEveryKLevelUtil ( Node * root , int level , int k ) { if ( root == NULL || ( root -> left == NULL && root -> right == NULL ) ) return ; if ( ( level + 1 ) % k == 0 ) Swap ( & root -> left , & root -> right ) ; swapEveryKLevelUtil ( root -> left , level + 1 , k ) ; swapEveryKLevelUtil ( root -> right , level + 1 , k ) ; } void swapEveryKLevel ( Node * root , int k ) { swapEveryKLevelUtil ( root , 1 , k ) ; } void inorder ( Node * root ) { if ( root == NULL ) return ; inorder ( root -> left ) ; cout << root -> data << " ▁ " ; inorder ( root -> right ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> right -> right = newNode ( 8 ) ; root -> right -> left = newNode ( 7 ) ; int k = 2 ; cout << " Before ▁ swap ▁ node ▁ : " << endl ; inorder ( root ) ; swapEveryKLevel ( root , k ) ; cout << " After swap Node : " << endl ; inorder ( root ) ; return 0 ; }
Convert a sentence into its equivalent mobile numeric keypad sequence | C ++ implementation to convert a sentence into its equivalent mobile numeric keypad sequence ; Function which computes the sequence ; length of input string ; Checking for space ; Calculating index for each character ; Output sequence ; Driver function ; storing the sequence in array
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printSequence ( string arr [ ] , string input ) { string output = " " ; int n = input . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( input [ i ] == ' ▁ ' ) output = output + "0" ; else { int position = input [ i ] - ' A ' ; output = output + arr [ position ] ; } } return output ; } int main ( ) { string str [ ] = { "2" , "22" , "222" , "3" , "33" , "333" , "4" , "44" , "444" , "5" , "55" , "555" , "6" , "66" , "666" , "7" , "77" , "777" , "7777" , "8" , "88" , "888" , "9" , "99" , "999" , "9999" } ; string input = " GEEKSFORGEEKS " ; cout << printSequence ( str , input ) ; return 0 ; }
Longest Uncommon Subsequence | CPP program to find longest uncommon subsequence using naive method ; function to calculate length of longest uncommon subsequence ; creating an unordered map to map strings to their frequency ; traversing all elements of vector strArr ; Creating all possible subsequences , i . e 2 ^ n ; ( ( i >> j ) & 1 ) determines which character goes into string t ; If common subsequence is found , increment its frequency ; traversing the map ; if frequency equals 1 ; Driver code ; Input strings
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE #include <vector> NEW_LINE using namespace std ; int findLUSlength ( string a , string b ) { unordered_map < string , int > map ; vector < string > strArr ; strArr . push_back ( a ) ; strArr . push_back ( b ) ; for ( string s : strArr ) { for ( int i = 0 ; i < ( 1 << s . length ( ) ) ; i ++ ) { string t = " " ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { if ( ( ( i >> j ) & 1 ) != 0 ) t += s [ j ] ; } if ( map . count ( t ) ) map [ t ] ++ ; else map [ t ] = 1 ; } } int res = 0 ; for ( auto a : map ) { if ( a . second == 1 ) res = max ( res , ( int ) a . first . length ( ) ) ; } return res ; } int main ( ) { string a = " abcdabcd " , b = " abcabc " ; cout << findLUSlength ( a , b ) ; return 0 ; }
Round the given number to nearest multiple of 10 | C ++ code for above approach ; Program to round the number to the nearest number having one 's digit 0 ; last character is 0 then return the original string ; if last character is 1 or 2 or 3 or 4 or 5 make it 0 ; process carry ; return final string ; Driver code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string Round ( string s , int n ) { string c = s ; if ( c [ n - 1 ] == '0' ) return s ; else if ( c [ n - 1 ] == '1' c [ n - 1 ] == '2' c [ n - 1 ] == '3' c [ n - 1 ] == '4' c [ n - 1 ] == '5' ) { c [ n - 1 ] = '0' ; return c ; } else { c [ n - 1 ] = '0' ; for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( c [ i ] == '9' ) c [ i ] = '0' ; else { int t = c [ i ] - '0' + 1 ; c [ i ] = ( char ) ( 48 + t ) ; break ; } } } string s1 = c ; if ( s1 [ 0 ] == '0' ) s1 = "1" + s1 ; return s1 ; } int main ( ) { string s = "5748965412485599999874589965999" ; int n = s . length ( ) ; cout << Round ( s , n ) << endl ; return 0 ; }
Check whether given floating point number is even or odd | CPP program to check whether given floating point number is even or odd ; Function to check even or odd . ; Loop to traverse number from LSB ; We ignore trailing 0 s after dot ; If it is ' . ' we will check next digit and it means decimal part is traversed . ; If digit is divisible by 2 means even number . ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isEven ( string s ) { int l = s . length ( ) ; bool dotSeen = false ; for ( int i = l - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == '0' && dotSeen == false ) continue ; if ( s [ i ] == ' . ' ) { dotSeen = true ; continue ; } if ( ( s [ i ] - '0' ) % 2 == 0 ) return true ; return false ; } } int main ( ) { string s = "100.70" ; if ( isEven ( s ) ) cout << " Even " ; else cout << " Odd " ; return 0 ; }
Minimum cost to construct a string | C ++ Program to find minimum cost to construct a string ; Initially all characters are un - seen ; Marking seen characters ; Count total seen character , and that is the cost ; Driver Code ; s is the string that needs to be constructed
#include <iostream> NEW_LINE using namespace std ; int minCost ( string & s ) { bool alphabets [ 26 ] = { false } ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) alphabets [ s [ i ] - 97 ] = true ; int count = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) if ( alphabets [ i ] ) count ++ ; return count ; } int main ( ) { string s = " geeksforgeeks " ; cout << " Total ▁ cost ▁ to ▁ construct ▁ " << s << " ▁ is ▁ " << minCost ; return 0 ; }
Root to leaf paths having equal lengths in a Binary Tree | C ++ program to count root to leaf paths of different lengths . ; A binary tree node ; utility that allocates a new node with the given data and NULL left and right pointers . ; Function to store counts of different root to leaf path lengths in hash map m . ; Base condition ; If leaf node reached , increment count of path length of this root to leaf path . ; Recursively call for left and right subtrees with path lengths more than 1. ; A wrapper over pathCountUtil ( ) ; create an empty hash table ; Recursively check in left and right subtrees . ; Print all path lenghts and their counts . ; Driver program to run the case
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * left , * right ; } ; struct Node * newnode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } void pathCountUtil ( Node * node , unordered_map < int , int > & m , int path_len ) { if ( node == NULL ) return ; if ( node -> left == NULL && node -> right == NULL ) { m [ path_len ] ++ ; return ; } pathCountUtil ( node -> left , m , path_len + 1 ) ; pathCountUtil ( node -> right , m , path_len + 1 ) ; } void pathCounts ( Node * root ) { unordered_map < int , int > m ; pathCountUtil ( root , m , 1 ) ; for ( auto itr = m . begin ( ) ; itr != m . end ( ) ; itr ++ ) cout << itr -> second << " ▁ paths ▁ have ▁ length ▁ " << itr -> first << endl ; } int main ( ) { struct Node * root = newnode ( 8 ) ; root -> left = newnode ( 5 ) ; root -> right = newnode ( 4 ) ; root -> left -> left = newnode ( 9 ) ; root -> left -> right = newnode ( 7 ) ; root -> right -> right = newnode ( 11 ) ; root -> right -> right -> left = newnode ( 3 ) ; pathCounts ( root ) ; return 0 ; }
Simplify the directory path ( Unix like ) | C ++ implementation of optimized Approach 1 ; function to simplify a Unix - styled absolute path ; using vector in place of stack ; forming the current directory . ; if " . . " , we pop . ; do nothing ( added for better understanding . ) ; push the current directory into the vector . ; forming the ans ; vector is empty ; Driver Code ; absolute path which we have to simplify .
#include <bits/stdc++.h> NEW_LINE using namespace std ; string simplify ( string path ) { vector < string > v ; int n = path . length ( ) ; string ans ; for ( int i = 0 ; i < n ; i ++ ) { string dir = " " ; while ( i < n && path [ i ] != ' / ' ) { dir += path [ i ] ; i ++ ; } if ( dir == " . . " ) { if ( ! v . empty ( ) ) v . pop_back ( ) ; } else if ( dir == " . " dir == " " ) { } else { v . push_back ( dir ) ; } } for ( auto i : v ) { ans += " / " + i ; } if ( ans == " " ) return " / " ; return ans ; } int main ( ) { string str ( " / a / . / b / . . / . . / c / " ) ; string res = simplify ( str ) ; cout << res ; return 0 ; }
Length of the smallest sub | C ++ program to find the length of the smallest substring consisting of maximum distinct characters ; Find maximum distinct characters in any string ; Initialize all character 's count with 0 ; Increase the count in array if a character is found ; size of given string ; Find maximum distinct characters in any string ; result ; Brute force approach to find all substrings ; We have to check here both conditions together 1. substring ' s ▁ distinct ▁ characters ▁ is ▁ equal ▁ ▁ to ▁ maximum ▁ distinct ▁ characters ▁ ▁ 2 . ▁ substring ' s length should be minimum ; Driver program to test above function ; Input String
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define NO_OF_CHARS 256 NEW_LINE int max_distinct_char ( string str , int n ) { int count [ NO_OF_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) count [ str [ i ] ] ++ ; int max_distinct = 0 ; for ( int i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] != 0 ) max_distinct ++ ; return max_distinct ; } int smallesteSubstr_maxDistictChar ( string str ) { int n = str . size ( ) ; int max_distinct = max_distinct_char ( str , n ) ; int minl = n ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { string subs = str . substr ( i , j ) ; int subs_lenght = subs . size ( ) ; int sub_distinct_char = max_distinct_char ( subs , subs_lenght ) ; if ( subs_lenght < minl && max_distinct == sub_distinct_char ) { minl = subs_lenght ; } } } return minl ; } int main ( ) { string str = " AABBBCBB " ; int len = smallesteSubstr_maxDistictChar ( str ) ; cout << " ▁ The ▁ length ▁ of ▁ the ▁ smallest ▁ substring " " ▁ consisting ▁ of ▁ maximum ▁ distinct ▁ " " characters ▁ : ▁ " << len ; return 0 ; }
Evaluate a boolean expression represented as string | C ++ program to evaluate value of an expression . ; Evaluates boolean expression and returns the result ; Traverse all operands by jumping a character after every iteration . ; If operator next to current operand is AND . ; If operator next to current operand is OR . ; If operator next to current operand is XOR ( Assuming a valid input ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int evaluateBoolExpr ( string s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i += 2 ) { if ( s [ i + 1 ] == ' A ' ) { if ( s [ i + 2 ] == '0' s [ i ] == '0' ) s [ i + 2 ] = '0' ; else s [ i + 2 ] = '1' ; } else if ( s [ i + 1 ] == ' B ' ) { if ( s [ i + 2 ] == '1' s [ i ] == '1' ) s [ i + 2 ] = '1' ; else s [ i + 2 ] = '0' ; } else { if ( s [ i + 2 ] == s [ i ] ) s [ i + 2 ] = '0' ; else s [ i + 2 ] = '1' ; } } return s [ n - 1 ] - '0' ; } int main ( ) { string s = "1C1B1B0A0" ; cout << evaluateBoolExpr ( s ) ; return 0 ; }
Efficiently find first repeated character in a string without using any additional data structure in one traversal | Efficiently check First repeated character in C ++ program ; Returns - 1 if all characters of str are unique . Assumptions : ( 1 ) str contains only characters from ' a ' to ' z ' ( 2 ) integers are stored using 32 bits ; An integer to store presence / absence of 26 characters using its 32 bits . ; If bit corresponding to current character is already set ; set bit in checker ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int FirstRepeated ( string str ) { int checker = 0 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { int val = ( str [ i ] - ' a ' ) ; if ( ( checker & ( 1 << val ) ) > 0 ) return i ; checker |= ( 1 << val ) ; } return -1 ; } int main ( ) { string s = " abcfdeacf " ; int i = FirstRepeated ( s ) ; if ( i != -1 ) cout << " Char ▁ = ▁ " << s [ i ] << " ▁ and ▁ Index ▁ = ▁ " << i ; else cout << " No ▁ repeated ▁ Char " ; return 0 ; }
Check if a string is Pangrammatic Lipogram | C ++ program to check if a string is Pangrammatic Lipogram ; collection of letters ; function to check for a Pangrammatic Lipogram ; convert string to lowercase ; variable to keep count of all the letters not found in the string ; traverses the string for every letter of the alphabet ; if character not found in string then increment count ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string alphabets = " abcdefghijklmnopqrstuvwxyz " ; void panLipogramChecker ( string s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { s [ i ] = tolower ( s [ i ] ) ; } int counter = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int pos = s . find ( alphabets [ i ] ) ; if ( pos < 0 || pos > s . length ( ) ) counter += 1 ; } if ( counter == 0 ) cout << " Pangram " << endl ; else if ( counter >= 2 ) cout << " Not ▁ a ▁ pangram ▁ but ▁ might ▁ a ▁ lipogram " << endl ; else cout << " Pangrammatic ▁ Lipogram " << endl ; } int main ( ) { string str = " The ▁ quick ▁ brown ▁ fox ▁ jumped ▁ over ▁ the ▁ lazy ▁ dog " ; panLipogramChecker ( str ) ; str = " The ▁ quick ▁ brown ▁ fox ▁ jumps ▁ over ▁ the ▁ lazy ▁ dog " ; panLipogramChecker ( str ) ; str = " The ▁ quick ▁ brown ▁ fox ▁ jum ▁ over ▁ the ▁ lazy ▁ dog " ; panLipogramChecker ( str ) ; }
Lexicographically n | C ++ program to print nth permutation with using next_permute ( ) ; Function to print nth permutation using next_permute ( ) ; Sort the string in lexicographically ascending order ; Keep iterating until we reach nth position ; check for nth iteration ; print string after nth iteration ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void nPermute ( string str , long int n ) { sort ( str . begin ( ) , str . end ( ) ) ; long int i = 1 ; do { if ( i == n ) break ; i ++ ; } while ( next_permutation ( str . begin ( ) , str . end ( ) ) ) ; cout << str ; } int main ( ) { string str = " GEEKSFORGEEKS " ; long int n = 100 ; nPermute ( str , n ) ; return 0 ; }
Split numeric , alphabetic and special symbols from a String | CPP program to split an alphanumeric string using STL ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void splitString ( string str ) { string alpha , num , special ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( isdigit ( str [ i ] ) ) num . push_back ( str [ i ] ) ; else if ( ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) || ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) ) alpha . push_back ( str [ i ] ) ; else special . push_back ( str [ i ] ) ; } cout << alpha << endl ; cout << num << endl ; cout << special << endl ; } int main ( ) { string str = " geeks01 $ $ for02geeks03 ! @ ! ! " ; splitString ( str ) ; return 0 ; }
Program to print all substrings of a given string | C ++ program to print all possible substrings of a given string ; Function to print all sub strings ; Pick starting point in outer loop and lengths of different strings for a given starting point ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void subString ( string s , int n ) { for ( int i = 0 ; i < n ; i ++ ) for ( int len = 1 ; len <= n - i ; len ++ ) cout << s . substr ( i , len ) << endl ; } int main ( ) { string s = " abcd " ; subString ( s , s . length ( ) ) ; return 0 ; }
Program to print all substrings of a given string | CPP program for the above approach ; finding the length of the string ; outermost for loop this is for the selection of starting point ; 2 nd for loop is for selection of ending point ; 3 rd loop is for printing from starting point to ending point ; changing the line after printing from starting point to ending point ; Driver Code ; calling method for printing substring
#include <iostream> NEW_LINE using namespace std ; void printSubstrings ( string str ) { int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { for ( int k = i ; k <= j ; k ++ ) { cout << str [ k ] ; } cout << endl ; } } } int main ( ) { string str = " abcd " ; printSubstrings ( str ) ; return 0 ; }
Maximum Tip Calculator | C ++ implementation of the approach ; Recursive function to calculate sum of maximum tip order taken by X and Y ; When all orders have been taken ; When X cannot take more orders ; When Y cannot take more orders ; When both can take order calculate maximum out of two ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int n ; int solve ( int i , int X , int Y , int a [ ] , int b [ ] , int n ) { if ( i == n ) return 0 ; if ( X <= 0 ) return b [ i ] + solve ( i + 1 , X , Y - 1 , a , b , n ) ; if ( Y <= 0 ) return a [ i ] + solve ( i + 1 , X - 1 , Y , a , b , n ) ; else return max ( a [ i ] + solve ( i + 1 , X - 1 , Y , a , b , n ) , b [ i ] + solve ( i + 1 , X , Y - 1 , a , b , n ) ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 , 5 } ; int b [ ] = { 5 , 4 , 3 , 2 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int x = 3 , y = 3 ; cout << solve ( 0 , x , y , a , b , n ) ; return 0 ; }
Print Kth character in sorted concatenated substrings of a string | C ++ program to print Kth character in sorted concatenated substrings ; Structure to store information of a suffix ; To store original index ; To store ranks and next ; A comparison function used by sort ( ) to compare two suffixes . Compares two pairs , returns 1 if first pair is smaller ; This is the main function that takes a string ' txt ' of size n as an argument , builds and return the suffix array for the given string ; A structure to store suffixes and their indexes ; Store suffixes and their indexes in an array of structures . The structure is needed to sort the suffixes alphabatically and maintain their old indexes while sorting ; Sort the suffixes using the comparison function defined above . ; At his point , all suffixes are sorted according to first 2 characters . Let us sort suffixes according to first 4 characters , then first 8 and so on This array is needed to get the ; index in suffixes [ ] from original index . This mapping is needed to get next suffix . ; Assigning rank and index values to first suffix ; Assigning rank to suffixes ; If first rank and next ranks are same as that of previous suffix in array , assign the same new rank to this suffix ; Otherwise increment rank and assign ; Assign next rank to every suffix ; Sort the suffixes according to first k characters ; Store indexes of all sorted suffixes in the suffix array ; Return the suffix array ; To construct and return LCP ; To store LCP array ; An auxiliary array to store inverse of suffix array elements . For example if suffixArr [ 0 ] is 5 , the invSuff [ 5 ] would store 0. This is used to get next suffix string from suffix array . ; Fill values in invSuff [ ] ; Initialize length of previous LCP ; Process all suffixes one by one starting from first suffix in txt [ ] ; If the current suffix is at n - 1 , then we dont have next substring to consider . So lcp is not defined for this substring , we put zero . ; j contains index of the next substring to be considered to compare with the present substring , i . e . , next string in suffix array ; Directly start matching from k 'th index as at-least k-1 characters will match ; lcp for the present suffix . ; Deleting the starting character from the string . ; return the constructed lcp array ; Utility method to get sum of first N numbers ; Returns Kth character in sorted concatenated substrings of str ; calculating suffix array and lcp array ; skipping characters common to substring ( n - suffixArr [ i ] ) is length of current maximum substring lcp [ i ] will length of common substring ; if characters are more than K , that means Kth character belongs to substring corresponding to current lcp [ i ] ; loop from current lcp value to current string length ; Again reduce K by current substring 's length one by one and when it becomes less, print Kth character of current substring ; Driver code to test above methods
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct suffix { int index ; int rank [ 2 ] ; } ; int cmp ( struct suffix a , struct suffix b ) { return ( a . rank [ 0 ] == b . rank [ 0 ] ) ? ( a . rank [ 1 ] < b . rank [ 1 ] ? 1 : 0 ) : ( a . rank [ 0 ] < b . rank [ 0 ] ? 1 : 0 ) ; } vector < int > buildSuffixArray ( string txt , int n ) { struct suffix suffixes [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { suffixes [ i ] . index = i ; suffixes [ i ] . rank [ 0 ] = txt [ i ] - ' a ' ; suffixes [ i ] . rank [ 1 ] = ( ( i + 1 ) < n ) ? ( txt [ i + 1 ] - ' a ' ) : -1 ; } sort ( suffixes , suffixes + n , cmp ) ; int ind [ n ] ; for ( int k = 4 ; k < 2 * n ; k = k * 2 ) { int rank = 0 ; int prev_rank = suffixes [ 0 ] . rank [ 0 ] ; suffixes [ 0 ] . rank [ 0 ] = rank ; ind [ suffixes [ 0 ] . index ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( suffixes [ i ] . rank [ 0 ] == prev_rank && suffixes [ i ] . rank [ 1 ] == suffixes [ i - 1 ] . rank [ 1 ] ) { prev_rank = suffixes [ i ] . rank [ 0 ] ; suffixes [ i ] . rank [ 0 ] = rank ; } else { prev_rank = suffixes [ i ] . rank [ 0 ] ; suffixes [ i ] . rank [ 0 ] = ++ rank ; } ind [ suffixes [ i ] . index ] = i ; } for ( int i = 0 ; i < n ; i ++ ) { int nextindex = suffixes [ i ] . index + k / 2 ; suffixes [ i ] . rank [ 1 ] = ( nextindex < n ) ? suffixes [ ind [ nextindex ] ] . rank [ 0 ] : -1 ; } sort ( suffixes , suffixes + n , cmp ) ; } vector < int > suffixArr ; for ( int i = 0 ; i < n ; i ++ ) suffixArr . push_back ( suffixes [ i ] . index ) ; return suffixArr ; } vector < int > kasai ( string txt , vector < int > suffixArr ) { int n = suffixArr . size ( ) ; vector < int > lcp ( n , 0 ) ; vector < int > invSuff ( n , 0 ) ; for ( int i = 0 ; i < n ; i ++ ) invSuff [ suffixArr [ i ] ] = i ; int k = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( invSuff [ i ] == n - 1 ) { k = 0 ; continue ; } int j = suffixArr [ invSuff [ i ] + 1 ] ; while ( i + k < n && j + k < n && txt [ i + k ] == txt [ j + k ] ) k ++ ; lcp [ invSuff [ i ] ] = k ; if ( k > 0 ) k -- ; } return lcp ; } int sumOfFirstN ( int N ) { return ( N * ( N + 1 ) ) / 2 ; } char printKthCharInConcatSubstring ( string str , int K ) { int n = str . length ( ) ; vector < int > suffixArr = buildSuffixArray ( str , n ) ; vector < int > lcp = kasai ( str , suffixArr ) ; for ( int i = 0 ; i < lcp . size ( ) ; i ++ ) { int charToSkip = sumOfFirstN ( n - suffixArr [ i ] ) - sumOfFirstN ( lcp [ i ] ) ; if ( K <= charToSkip ) { for ( int j = lcp [ i ] + 1 ; j <= ( n - suffixArr [ i ] ) ; j ++ ) { int curSubstringLen = j ; if ( K <= curSubstringLen ) return str [ ( suffixArr [ i ] + K - 1 ) ] ; else K -= curSubstringLen ; } break ; } else K -= charToSkip ; } } int main ( ) { string str = " banana " ; int K = 10 ; cout << printKthCharInConcatSubstring ( str , K ) ; return 0 ; }
Number of even substrings in a string of digits | C ++ program to count number of substring which are even integer in a string of digits . ; Return the even number substrings . ; If current digit is even , add count of substrings ending with it . The count is ( i + 1 ) ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int evenNumSubstring ( char str [ ] ) { int len = strlen ( str ) ; int count = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int temp = str [ i ] - '0' ; if ( temp % 2 == 0 ) count += ( i + 1 ) ; } return count ; } int main ( ) { char str [ ] = "1234" ; cout << evenNumSubstring ( str ) << endl ; return 0 ; }
Maximum Consecutive Increasing Path Length in Binary Tree | C ++ Program to find Maximum Consecutive Path Length in a Binary Tree ; To represent a node of a Binary Tree ; Create a new Node and return its address ; Returns the maximum consecutive Path Length ; Get the value of Current Node The value of the current node will be prev Node for its left and right children ; If current node has to be a part of the consecutive path then it should be 1 greater than the value of the previous node ; a ) Find the length of the Left Path b ) Find the length of the Right Path Return the maximum of Left path and Right path ; Find length of the maximum path under subtree rooted with this node ( The path may or may not include this node ) ; Take the maximum previous path and path under subtree rooted with this node . ; A wrapper over maxPathLenUtil ( ) . ; Return 0 if root is NULL ; Else compute Maximum Consecutive Increasing Path Length using maxPathLenUtil . ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { Node * left , * right ; int val ; } ; Node * newNode ( int val ) { Node * temp = new Node ( ) ; temp -> val = val ; temp -> left = temp -> right = NULL ; return temp ; } int maxPathLenUtil ( Node * root , int prev_val , int prev_len ) { if ( ! root ) return prev_len ; int cur_val = root -> val ; if ( cur_val == prev_val + 1 ) { return max ( maxPathLenUtil ( root -> left , cur_val , prev_len + 1 ) , maxPathLenUtil ( root -> right , cur_val , prev_len + 1 ) ) ; } int newPathLen = max ( maxPathLenUtil ( root -> left , cur_val , 1 ) , maxPathLenUtil ( root -> right , cur_val , 1 ) ) ; return max ( prev_len , newPathLen ) ; } int maxConsecutivePathLength ( Node * root ) { if ( root == NULL ) return 0 ; return maxPathLenUtil ( root , root -> val - 1 , 0 ) ; } int main ( ) { Node * root = newNode ( 10 ) ; root -> left = newNode ( 11 ) ; root -> right = newNode ( 9 ) ; root -> left -> left = newNode ( 13 ) ; root -> left -> right = newNode ( 12 ) ; root -> right -> left = newNode ( 13 ) ; root -> right -> right = newNode ( 8 ) ; cout << " Maximum ▁ Consecutive ▁ Increasing ▁ Path ▁ Length ▁ is ▁ " << maxConsecutivePathLength ( root ) ; return 0 ; }
Find largest word in dictionary by deleting some characters of given string | C ++ program to find largest word in Dictionary by deleting some characters of given string ; Returns true if str1 [ ] is a subsequence of str2 [ ] . m is length of str1 and n is length of str2 ; Traverse str2 and str1 , and compare current character of str2 with first unmatched char of str1 , if matched then move ahead in str1 ; If all characters of str1 were found in str2 ; Returns the longest string in dictionary which is a subsequence of str . ; Traverse through all words of dictionary ; If current word is subsequence of str and is largest such word so far . ; Return longest string ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isSubSequence ( string str1 , string str2 ) { int m = str1 . length ( ) , n = str2 . length ( ) ; for ( int i = 0 ; i < n && j < m ; i ++ ) if ( str1 [ j ] == str2 [ i ] ) j ++ ; return ( j == m ) ; } string findLongestString ( vector < string > dict , string str ) { string result = " " ; int length = 0 ; for ( string word : dict ) { if ( length < word . length ( ) && isSubSequence ( word , str ) ) { result = word ; length = word . length ( ) ; } } return result ; } int main ( ) { vector < string > dict = { " ale " , " apple " , " monkey " , " plea " } ; string str = " abpcplea " ; cout << findLongestString ( dict , str ) << endl ; return 0 ; }
Count of distinct substrings of a string using Suffix Trie | A C ++ program to find the count of distinct substring of a string using trie data structure ; A Suffix Trie ( A Trie of all suffixes ) Node ; SuffixTrieNode ( ) Constructor ; Initialize all child pointers as NULL ; A recursive function to insert a suffix of the s in subtree rooted with this node ; If string has more characters ; Find the first character and convert it into 0 - 25 range . ; If there is no edge for this character , add a new edge ; Recur for next suffix ; A Trie of all suffixes ; Constructor ( Builds a trie of suffies of the given text ) ; Consider all suffixes of given string and insert them into the Suffix Trie using recursive function insertSuffix ( ) in SuffixTrieNode class ; A recursive function to count nodes in trie ; If all characters of pattern have been processed , ; if children is not NULL then find count of all nodes in this subtrie ; return count of nodes of subtrie and plus 1 because of node 's own count ; method to count total nodes in suffix trie ; Returns count of distinct substrings of str ; Construct a Trie of all suffixes ; Return count of nodes in Trie of Suffixes ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE #define MAX_CHAR 26 NEW_LINE using namespace std ; class SuffixTrieNode { public : SuffixTrieNode * children [ MAX_CHAR ] ; { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) children [ i ] = NULL ; } void SuffixTrieNode :: insertSuffix ( string s ) { if ( s . length ( ) > 0 ) { char cIndex = s . at ( 0 ) - ' a ' ; if ( children [ cIndex ] == NULL ) children [ cIndex ] = new SuffixTrieNode ( ) ; children [ cIndex ] -> insertSuffix ( s . substr ( 1 ) ) ; } } class SuffixTrie { SuffixTrieNode * root ; int _countNodesInTrie ( SuffixTrieNode * ) ; public : SuffixTrie ( string s ) { root = new SuffixTrieNode ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) root -> insertSuffix ( s . substr ( i ) ) ; } int SuffixTrie :: _countNodesInTrie ( SuffixTrieNode * node ) { if ( node == NULL ) return 0 ; int count = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( node -> children [ i ] != NULL ) count += _countNodesInTrie ( node -> children [ i ] ) ; } return ( 1 + count ) ; } int countNodesInTrie ( ) { return _countNodesInTrie ( root ) ; } } ; int countDistinctSubstring ( string str ) { SuffixTrie sTrie ( str ) ; return sTrie . countNodesInTrie ( ) ; } int main ( ) { string str = " ababa " ; cout << " Count ▁ of ▁ distinct ▁ substrings ▁ is ▁ " << countDistinctSubstring ( str ) ; return 0 ; }
XOR Cipher | C ++ program to implement XOR - Encryption ; The same function is used to encrypt and decrypt ; Define XOR key Any character value will work ; calculate length of input string ; perform XOR operation of key with every character in string ; Driver program to test above function ; Encrypt the string ; Decrypt the string
#include <bits/stdc++.h> NEW_LINE void encryptDecrypt ( char inpString [ ] ) { char xorKey = ' P ' ; int len = strlen ( inpString ) ; for ( int i = 0 ; i < len ; i ++ ) { inpString [ i ] = inpString [ i ] ^ xorKey ; printf ( " % c " , inpString [ i ] ) ; } } int main ( ) { char sampleString [ ] = " GeeksforGeeks " ; printf ( " Encrypted ▁ String : ▁ " ) ; encryptDecrypt ( sampleString ) ; printf ( " STRNEWLINE " ) ; printf ( " Decrypted ▁ String : ▁ " ) ; encryptDecrypt ( sampleString ) ; return 0 ; }
Compare two Version numbers | C / C ++ program to compare two version number ; Method to compare two versions . Returns 1 if v2 is smaller , - 1 if v1 is smaller , 0 if equal ; vnum stores each numeric part of version ; loop until both string are processed ; storing numeric part of version 1 in vnum1 ; storing numeric part of version 2 in vnum2 ; if equal , reset variables and go for next numeric part ; Driver method to check above comparison function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int versionCompare ( string v1 , string v2 ) { int vnum1 = 0 , vnum2 = 0 ; for ( int i = 0 , j = 0 ; ( i < v1 . length ( ) || j < v2 . length ( ) ) ; ) { while ( i < v1 . length ( ) && v1 [ i ] != ' . ' ) { vnum1 = vnum1 * 10 + ( v1 [ i ] - '0' ) ; i ++ ; } while ( j < v2 . length ( ) && v2 [ j ] != ' . ' ) { vnum2 = vnum2 * 10 + ( v2 [ j ] - '0' ) ; j ++ ; } if ( vnum1 > vnum2 ) return 1 ; if ( vnum2 > vnum1 ) return -1 ; vnum1 = vnum2 = 0 ; i ++ ; j ++ ; } return 0 ; } int main ( ) { string version1 = "1.0.3" ; string version2 = "1.0.7" ; if ( versionCompare ( version1 , version2 ) < 0 ) cout << version1 << " ▁ is ▁ smaller STRNEWLINE " ; else if ( versionCompare ( version1 , version2 ) > 0 ) cout << version2 << " ▁ is ▁ smaller STRNEWLINE " ; else cout << " Both ▁ version ▁ are ▁ equal STRNEWLINE " ; return 0 ; }
Repeated subsequence of length 2 or more | C ++ program to check if any repeated subsequence exists in the string ; A function to check if a string str is palindrome ; l and h are leftmost and rightmost corners of str Keep comparing characters while they are same ; The main function that checks if repeated subsequence exists in the string ; Find length of input string ; Create an array to store all characters and their frequencies in str [ ] ; Traverse the input string and store frequencies of all characters in freq [ ] array . ; If the character count is more than 2 we found a repetition ; In - place remove non - repeating characters from the string ; check if the resultant string is palindrome ; special case - if length is odd return true if the middle character is same as previous one ; return false if string is a palindrome ; return true if string is not a palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE #define MAX_CHAR 256 NEW_LINE using namespace std ; bool isPalindrome ( char str [ ] , int l , int h ) { while ( h > l ) if ( str [ l ++ ] != str [ h -- ] ) return false ; return true ; } int check ( char str [ ] ) { int n = strlen ( str ) ; int freq [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { freq [ str [ i ] ] ++ ; if ( freq [ str [ i ] ] > 2 ) return true ; } int k = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( freq [ str [ i ] ] > 1 ) str [ k ++ ] = str [ i ] ; str [ k ] = ' \0' ; if ( isPalindrome ( str , 0 , k - 1 ) ) { if ( k & 1 ) return str [ k / 2 ] == str [ k / 2 - 1 ] ; return false ; } return true ; } int main ( ) { char str [ ] = " ABCABD " ; if ( check ( str ) ) cout << " Repeated ▁ Subsequence ▁ Exists " ; else cout << " Repeated ▁ Subsequence ▁ Doesn ' t ▁ Exists " ; return 0 ; }
How to find Lexicographically previous permutation ? | C ++ program to print all permutations with duplicates allowed using prev_permutation ( ) ; Function to compute the previous permutation ; Find index of the last element of the string ; Find largest index i such that str [ i - 1 ] > str [ i ] ; if string is sorted in ascending order we 're at the last permutation ; Note - str [ i . . n ] is sorted in ascending order . Find rightmost element 's index that is less than str[i - 1] ; Swap character at i - 1 with j ; Reverse the substring [ i . . n ] ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool prevPermutation ( string & str ) { int n = str . length ( ) - 1 ; int i = n ; while ( i > 0 && str [ i - 1 ] <= str [ i ] ) i -- ; if ( i <= 0 ) return false ; int j = i - 1 ; while ( j + 1 <= n && str [ j + 1 ] < str [ i - 1 ] ) j ++ ; swap ( str [ i - 1 ] , str [ j ] ) ; reverse ( str . begin ( ) + i , str . end ( ) ) ; return true ; } int main ( ) { string str = "4321" ; if ( prevPermutation ( str ) ) cout << " Previous ▁ permutation ▁ is ▁ " << str ; else cout << " Previous ▁ permutation ▁ doesn ' t ▁ exist " ; return 0 ; }
Longest Path with Same Values in a Binary Tree | C ++ program to find the length of longest path with same values in a binary tree . ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to print the longest path of same values ; Recursive calls to check for subtrees ; Variables to store maximum lengths in two directions ; If curr node and it 's left child has same value ; If curr node and it 's right child has same value ; Driver function to find length of longest same value path ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Driver code ; Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int val ; struct Node * left , * right ; } ; int length ( Node * node , int * ans ) { if ( ! node ) return 0 ; int left = length ( node -> left , ans ) ; int right = length ( node -> right , ans ) ; int Leftmax = 0 , Rightmax = 0 ; if ( node -> left && node -> left -> val == node -> val ) Leftmax += left + 1 ; if ( node -> right && node -> right -> val == node -> val ) Rightmax += right + 1 ; * ans = max ( * ans , Leftmax + Rightmax ) ; return max ( Leftmax , Rightmax ) ; } int longestSameValuePath ( Node * root ) { int ans = 0 ; length ( root , & ans ) ; return ans ; } Node * newNode ( int data ) { Node * temp = new Node ; temp -> val = data ; temp -> left = temp -> right = NULL ; return temp ; } int main ( ) { Node * root = NULL ; root = newNode ( 4 ) ; root -> left = newNode ( 4 ) ; root -> right = newNode ( 4 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 9 ) ; root -> right -> right = newNode ( 5 ) ; cout << longestSameValuePath ( root ) ; return 0 ; }
Check if edit distance between two strings is one | C ++ program to check if given two strings are at distance one . ; Returns true if edit distance between s1 and s2 is one , else false ; Find lengths of given strings ; If difference between lengths is more than 1 , then strings can 't be at one distance ; int count = 0 ; Count of edits ; If current characters don 't match ; If length of one string is more , then only possible edit is to remove a character ; else Iflengths of both strings is same ; Increment count of edits ; else If current characters match ; If last character is extra in any string ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isEditDistanceOne ( string s1 , string s2 ) { int m = s1 . length ( ) , n = s2 . length ( ) ; if ( abs ( m - n ) > 1 ) return false ; int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( s1 [ i ] != s2 [ j ] ) { if ( count == 1 ) return false ; if ( m > n ) i ++ ; else if ( m < n ) j ++ ; { i ++ ; j ++ ; } count ++ ; } { i ++ ; j ++ ; } } if ( i < m j < n ) count ++ ; return count == 1 ; } int main ( ) { string s1 = " gfg " ; string s2 = " gf " ; isEditDistanceOne ( s1 , s2 ) ? cout << " Yes " : cout << " No " ; return 0 ; }
Count of numbers from range [ L , R ] whose sum of digits is Y | Set 2 | CPP program for the above approach ; Function to find the sum of digits of numbers in the range [ 0 , X ] ; Check if count of digits in a number greater than count of digits in X ; If sum of digits of a number is equal to Y ; Check if current subproblem has already been computed ; Stores count of numbers whose sum of digits is Y ; Check if the number exceeds Y or not ; Iterate over all possible values of i - th digits ; Update res ; Return res ; Utility function to count the numbers in the range [ L , R ] whose sum of digits is Y ; Base Case ; Stores numbers in the form of its equivalent string ; Stores overlapping subproblems ; Initialize dp [ ] [ ] [ ] ; Stores count of numbers in the range [ 0 , R ] ; Update str ; Initialize dp [ ] [ ] [ ] ; Stores count of numbers in the range [ 0 , L - 1 ] ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define M 1000 NEW_LINE int cntNum ( string X , int i , int sum , int tight , int dp [ M ] [ M ] [ 2 ] ) { if ( i >= X . length ( ) sum < 0 ) { if ( sum == 0 ) { return 1 ; } return 0 ; } if ( dp [ sum ] [ i ] [ tight ] != -1 ) { return dp [ sum ] [ i ] [ tight ] ; } int res = 0 ; int end = tight ? X [ i ] - '0' : 9 ; for ( int j = 0 ; j <= end ; j ++ ) { res += cntNum ( X , i + 1 , sum - j , ( tight & ( j == end ) ) , dp ) ; } return dp [ sum ] [ i ] [ tight ] = res ; } int UtilCntNumRange ( int L , int R , int Y ) { if ( R == 0 && Y == 0 ) { return 1 ; } string str = to_string ( R ) ; int dp [ M ] [ M ] [ 2 ] ; memset ( dp , -1 , sizeof ( dp ) ) ; int cntR = cntNum ( str , 0 , Y , true , dp ) ; str = to_string ( L - 1 ) ; memset ( dp , -1 , sizeof ( dp ) ) ; int cntL = cntNum ( str , 0 , Y , true , dp ) ; return ( cntR - cntL ) ; } int main ( ) { int L = 20 , R = 10000 , Y = 14 ; cout << UtilCntNumRange ( L , R , Y ) ; }
Remove spaces from a given string | CPP program to Remove spaces from a given string ; Function to remove all spaces from a given string ; Driver program to test above function
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE using namespace std ; string removeSpaces ( string str ) { str . erase ( remove ( str . begin ( ) , str . end ( ) , ' ▁ ' ) , str . end ( ) ) ; return str ; } int main ( ) { string str = " g ▁ eeks ▁ for ▁ ge ▁ eeks ▁ " ; str = removeSpaces ( str ) ; cout << str ; return 0 ; }
Given a binary string , count number of substrings that start and end with 1. | A simple C ++ program to count number of substrings starting and ending with 1 ; Initialize result ; Pick a starting point ; Search for all possible ending point ; Driver program to test above function
#include <iostream> NEW_LINE using namespace std ; int countSubStr ( char str [ ] ) { int res = 0 ; for ( int i = 0 ; str [ i ] != ' \0' ; i ++ ) { if ( str [ i ] == '1' ) { for ( int j = i + 1 ; str [ j ] != ' \0' ; j ++ ) if ( str [ j ] == '1' ) res ++ ; } } return res ; } int main ( ) { char str [ ] = "00100101" ; cout << countSubStr ( str ) ; return 0 ; }
An in | C ++ implementation of above approach ; A utility function to swap characters ; A utility function to reverse string str [ low . . high ] ; Cycle leader algorithm to move all even positioned elements at the end . ; odd index ; even index ; keep the back - up of element at new position ; The main function to transform a string . This function mainly uses cycleLeader ( ) to transform ; Step 1 : Find the largest prefix subarray of the form 3 ^ k + 1 ; Step 2 : Apply cycle leader algorithm for the largest subarrau ; Step 4.1 : Reverse the second half of first subarray ; Step 4.2 : Reverse the first half of second sub - string . ; Step 4.3 Reverse the second half of first sub - string and first half of second sub - string together ; Increase the length of first subarray ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( char * a , char * b ) { char t = * a ; * a = * b ; * b = t ; } void reverse ( char * str , int low , int high ) { while ( low < high ) { swap ( & str [ low ] , & str [ high ] ) ; ++ low ; -- high ; } } void cycleLeader ( char * str , int shift , int len ) { int j ; char item ; for ( int i = 1 ; i < len ; i *= 3 ) { j = i ; item = str [ j + shift ] ; do { if ( j & 1 ) j = len / 2 + j / 2 ; else j /= 2 ; swap ( & str [ j + shift ] , & item ) ; } while ( j != i ) ; } } void moveNumberToSecondHalf ( char * str ) { int k , lenFirst ; int lenRemaining = strlen ( str ) ; int shift = 0 ; while ( lenRemaining ) { k = 0 ; while ( pow ( 3 , k ) + 1 <= lenRemaining ) k ++ ; lenFirst = pow ( 3 , k - 1 ) + 1 ; lenRemaining -= lenFirst ; cycleLeader ( str , shift , lenFirst ) ; reverse ( str , shift / 2 , shift - 1 ) ; reverse ( str , shift , shift + lenFirst / 2 - 1 ) ; reverse ( str , shift / 2 , shift + lenFirst / 2 - 1 ) ; shift += lenFirst ; } } int main ( ) { char str [ ] = " a1b2c3d4e5f6g7" ; moveNumberToSecondHalf ( str ) ; cout << str ; return 0 ; }
Remove nodes on root to leaf paths of length < K | C ++ program to remove nodes on root to leaf paths of length < K ; New node of a tree ; Utility method that actually removes the nodes which are not on the pathLen >= k . This method can change the root as well . ; Base condition ; Traverse the tree in postorder fashion so that if a leaf node path length is shorter than k , then that node and all of its descendants till the node which are not on some other path are removed . ; If root is a leaf node and it 's level is less than k then remove this node. This goes up and check for the ancestor nodes also for the same condition till it finds a node which is a part of other path(s) too. ; Return root ; ; Method which calls the utitlity method to remove the short path nodes . ; Method to print the tree in inorder fashion . ; Driver method .
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; Node * newNode ( int data ) { Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return node ; } Node * removeShortPathNodesUtil ( Node * root , int level , int k ) { if ( root == NULL ) return NULL ; root -> left = removeShortPathNodesUtil ( root -> left , level + 1 , k ) ; root -> right = removeShortPathNodesUtil ( root -> right , level + 1 , k ) ; if ( root -> left == NULL && root -> right == NULL && level < k ) { delete root ; return NULL ; } return root ; } Node * removeShortPathNodes ( Node * root , int k ) { int pathLen = 0 ; return removeShortPathNodesUtil ( root , 1 , k ) ; } void printInorder ( Node * root ) { if ( root ) { printInorder ( root -> left ) ; cout << root -> data << " ▁ " ; printInorder ( root -> right ) ; } } int main ( ) { int k = 4 ; Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; root -> left -> left -> left = newNode ( 7 ) ; root -> right -> right = newNode ( 6 ) ; root -> right -> right -> left = newNode ( 8 ) ; cout << " Inorder ▁ Traversal ▁ of ▁ Original ▁ tree " << endl ; printInorder ( root ) ; cout << endl ; cout << " Inorder ▁ Traversal ▁ of ▁ Modified ▁ tree " << endl ; Node * res = removeShortPathNodes ( root , k ) ; printInorder ( res ) ; return 0 ; }