text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Count and Print the alphabets having ASCII value not in the range [ l , r ] | C ++ implementation of the above approach ; Function to count the number of characters whose ascii value not in range [ l , r ] ; Initializing the count to 0 ; using map to print a character only once ; Increment the count if the value is less ; return the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountCharacters ( string str , int l , int r ) { int cnt = 0 ; unordered_map < char , int > m ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( ! ( l <= str [ i ] and str [ i ] <= r ) ) { cnt ++ ; if ( m [ str [ i ] ] != 1 ) { cout << str [ i ] << " ▁ " ; m [ str [ i ] ] ++ ; } } } return cnt ; } int main ( ) { string str = " geeksforgeeks " ; int l = 102 , r = 111 ; cout << " Characters ▁ with ▁ ASCII ▁ values " " ▁ not ▁ in ▁ the ▁ range ▁ [ l , ▁ r ] ▁ STRNEWLINE in ▁ the ▁ given ▁ string ▁ are : ▁ " ; cout << " and their count is " << CountCharacters ( str , l , r ) ; return 0 ; }
Final state of the string after modification | C ++ implementation of above approach ; Function to return final positions of the boxes ; Populate forces going from left to right ; Populate forces going from right to left ; return final state of boxes ; Driver code ; Function call to print answer
#include <bits/stdc++.h> NEW_LINE using namespace std ; string pushBoxes ( string S ) { int N = S . length ( ) ; vector < int > force ( N , 0 ) ; int f = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] == ' R ' ) { f = N ; } else if ( S [ i ] == ' L ' ) { f = 0 ; } else { f = max ( f - 1 , 0 ) ; } force [ i ] += f ; } f = 0 ; for ( int i = N - 1 ; i >= 0 ; i -- ) { if ( S [ i ] == ' L ' ) { f = N ; } else if ( S [ i ] == ' R ' ) { f = 0 ; } else { f = max ( f - 1 , 0 ) ; } force [ i ] -= f ; } string ans ; for ( int f : force ) { ans += f == 0 ? ' . ' : f > 0 ? ' R ' : ' L ' ; } return ans ; } int main ( ) { string S = " . L . R . . . LR . . L . . " ; cout << pushBoxes ( S ) ; }
Count the number of words having sum of ASCII values less than and greater than k | C ++ implementation of the above approach ; Function to count the words ; Sum of ascii values ; Number of words having sum of ascii less than k ; If character is a space ; Add the ascii value to sum ; Handling the Last word separately ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void CountWords ( string str , int k ) { int sum = 0 ; int NumberOfWords = 0 ; int counter = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( str [ i ] == ' ▁ ' ) { if ( sum < k ) counter ++ ; sum = 0 ; NumberOfWords ++ ; } else sum += str [ i ] ; } NumberOfWords ++ ; if ( sum < k ) counter ++ ; cout << " Number ▁ of ▁ words ▁ having ▁ sum ▁ of ▁ ASCII " " ▁ values ▁ less ▁ than ▁ k ▁ = ▁ " << counter << endl ; cout << " Number ▁ of ▁ words ▁ having ▁ sum ▁ of ▁ ASCII ▁ values " " ▁ greater ▁ than ▁ or ▁ equal ▁ to ▁ k ▁ = ▁ " << NumberOfWords - counter ; } int main ( ) { string str = " Learn ▁ how ▁ to ▁ code " ; int k = 400 ; CountWords ( str , k ) ; return 0 ; }
Minimum number of given operations required to make two strings equal | C ++ implementation of the above approach ; Function to return the minimum number of operations to convert string A to B ; If both the strings are equal then no operation needs to be performed ; store the position of ' _ ' ; to store the generated string at every move and the position of ' _ ' within it ; vis will store the minimum operations to reach that particular string ; minimum moves to reach the string ss ; if ' _ ' can be swapped with the character on it 's left ; swap with the left character ; if the string is generated for the first time ; if generated string is the required string ; update the distance for the currently generated string ; restore the string before it was swapped to check other cases ; swap ' _ ' with the character on it 's right this time ; if ' _ ' can be swapped with the character ' i + 2' ; if ' _ ' can be swapped with the character at ' i + 2' ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string s , string f ) { if ( s == f ) return 0 ; unordered_map < string , int > vis ; int n ; n = s . length ( ) ; int pos = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' _ ' ) { pos = i ; break ; } } queue < pair < string , int > > q ; q . push ( { s , pos } ) ; vis [ s ] = 0 ; while ( ! q . empty ( ) ) { string ss = q . front ( ) . first ; int pp = q . front ( ) . second ; int dist = vis [ ss ] ; q . pop ( ) ; if ( pp > 0 ) { swap ( ss [ pp ] , ss [ pp - 1 ] ) ; if ( ! vis . count ( ss ) ) { if ( ss == f ) { return dist + 1 ; break ; } vis [ ss ] = dist + 1 ; q . push ( { ss , pp - 1 } ) ; } swap ( ss [ pp ] , ss [ pp - 1 ] ) ; } if ( pp < n - 1 ) { swap ( ss [ pp ] , ss [ pp + 1 ] ) ; if ( ! vis . count ( ss ) ) { if ( ss == f ) { return dist + 1 ; break ; } vis [ ss ] = dist + 1 ; q . push ( { ss , pp + 1 } ) ; } swap ( ss [ pp ] , ss [ pp + 1 ] ) ; } if ( pp > 1 && ss [ pp - 1 ] != ss [ pp - 2 ] ) { swap ( ss [ pp ] , ss [ pp - 2 ] ) ; if ( ! vis . count ( ss ) ) { if ( ss == f ) { return dist + 1 ; break ; } vis [ ss ] = dist + 1 ; q . push ( { ss , pp - 2 } ) ; } swap ( ss [ pp ] , ss [ pp - 2 ] ) ; } if ( pp < n - 2 && ss [ pp + 1 ] != ss [ pp + 2 ] ) { swap ( ss [ pp ] , ss [ pp + 2 ] ) ; if ( ! vis . count ( ss ) ) { if ( ss == f ) { return dist + 1 ; break ; } vis [ ss ] = dist + 1 ; q . push ( { ss , pp + 2 } ) ; } swap ( ss [ pp ] , ss [ pp + 2 ] ) ; } } } int main ( ) { string A = " aba _ a " ; string B = " _ baaa " ; cout << minOperations ( A , B ) ; return 0 ; }
Rearrange a string in the form of integer sum followed by the minimized character | C ++ implementation of the above approach ; function to return maximum volume ; separate digits and alphabets ; change digit sum to string ; change alphabet sum to string ; concatenate sum to alphabets string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string separateChar ( string str ) { int n = str . size ( ) , digitSum = 0 ; int alphabetSum = 0 , j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isdigit ( str [ i ] ) ) digitSum += str [ i ] - '0' ; else { alphabetSum += str [ i ] - ' a ' + 1 ; alphabetSum %= 26 ; } } string sumStr = to_string ( digitSum ) ; char alphabetStr = char ( alphabetSum + ' a ' - 1 ) ; sumStr += alphabetStr ; return sumStr ; } int main ( ) { string str = "3652adyz3423" ; cout << separateChar ( str ) ; return 0 ; }
Find the count of palindromic sub | CPP program to find the count of palindromic sub - string of a string in it 's ascending form ; function to return count of palindromic sub - string ; calculate frequency ; calculate count of palindromic sub - string ; return result ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; int countPalindrome ( string str ) { int n = str . size ( ) ; int sum = 0 ; int hashTable [ MAX_CHAR ] ; for ( int i = 0 ; i < n ; i ++ ) hashTable [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( hashTable [ i ] ) sum += ( hashTable [ i ] * ( hashTable [ i ] + 1 ) / 2 ) ; } return sum ; } int main ( ) { string str = " ananananddd " ; cout << countPalindrome ( str ) ; return 0 ; }
Minimum number of elements to be removed so that pairwise consecutive elements are same | C ++ implementation of the above approach ; Function to count the minimum number of elements to remove from a number so that pairwise two consecutive digits are same . ; initialize counting variable ; check if two consecutive digits are same ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countConsecutive ( string s ) { int count = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) i ++ ; else count ++ ; } return count ; } int main ( ) { string str = "44522255" ; cout << countConsecutive ( str ) ; return 0 ; }
Smallest odd digits number not less than N | CPP program to print the smallest integer not less than N with all odd digits ; function to check if all digits are odd of a given number ; iterate for all digits ; if ( ( n % 10 ) % 2 == 0 ) if digit is even ; all digits are odd ; function to return the smallest number with all digits odd ; iterate till we find a number with all digits odd ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check_digits ( int n ) { while ( n ) { return 0 ; n /= 10 ; } return 1 ; } int smallest_number ( int n ) { for ( int i = n ; ; i ++ ) if ( check_digits ( i ) ) return i ; } int main ( ) { int N = 2397 ; cout << smallest_number ( N ) ; return 0 ; }
Smallest odd digits number not less than N | CPP program to print the smallest integer not less than N with all odd digits ; function to return the smallest number with all digits odd ; convert the number to string to perform operations ; find out the first even number ; if no even numbers are there , than n is the answer ; add all digits till first even ; increase the even digit by 1 ; add 1 to the right of the even number ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int smallestNumber ( int n ) { int num = 0 ; string s = " " ; int duplicate = n ; while ( n ) { s = char ( n % 10 + 48 ) + s ; n /= 10 ; } int index = -1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int digit = s [ i ] - '0' ; if ( ( digit & 1 ) == 0 ) { index = i ; break ; } } if ( index == -1 ) return duplicate ; for ( int i = 0 ; i < index ; i ++ ) num = num * 10 + ( s [ i ] - '0' ) ; num = num * 10 + ( s [ index ] - '0' + 1 ) ; for ( int i = index + 1 ; i < s . length ( ) ; i ++ ) num = num * 10 + 1 ; return num ; } int main ( ) { int N = 2397 ; cout << smallestNumber ( N ) ; return 0 ; }
Count and Print the alphabets having ASCII value in the range [ l , r ] | C ++ implementation of the above approach ; Function to count the number of characters whose ascii value is in range [ l , r ] ; Initializing the count to 0 ; Increment the count if the value is less ; return the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountCharacters ( string str , int l , int r ) { int cnt = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( l <= str [ i ] and str [ i ] <= r ) { cnt ++ ; cout << str [ i ] << " ▁ " ; } } return cnt ; } int main ( ) { string str = " geeksforgeeks " ; int l = 102 , r = 111 ; cout << " Characters ▁ with ▁ ASCII ▁ values " " ▁ in ▁ the ▁ range ▁ [ l , ▁ r ] ▁ are ▁ STRNEWLINE " ; cout << " and their count is " << CountCharacters ( str , l , r ) ; return 0 ; }
Minimum steps to remove substring 010 from a binary string | CPP program to calculate steps to remove substring 010 from a binary string ; Function to find the minimum steps ; substring "010" found ; Driver code ; Get the binary string ; Find the minimum steps
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minSteps ( string str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) - 2 ; i ++ ) { if ( str [ i ] == '0' ) { if ( str [ i + 1 ] == '1' ) { if ( str [ i + 2 ] == '0' ) { count ++ ; i += 2 ; } } } } return count ; } int main ( ) { string str = "0101010" ; cout << minSteps ( str ) ; return 0 ; }
XOR of Prime Frequencies of Characters in a String | C ++ program to find XOR of Prime Frequencies of Characters in a String ; Function to create Sieve to check primes ; false here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to find XOR of prime frequencies ; map is used to store character frequencies ; Traverse the map ; Calculate XOR of all prime frequencies ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SieveOfEratosthenes ( bool prime [ ] , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } int xorOfPrime ( string s ) { bool prime [ 100005 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , 10005 ) ; int i , j ; map < char , int > m ; for ( i = 0 ; i < s . length ( ) ; i ++ ) m [ s [ i ] ] ++ ; int result = 0 ; int flag = 0 ; for ( auto it = m . begin ( ) ; it != m . end ( ) ; it ++ ) { if ( prime [ it -> second ] ) { result ^= it -> second ; flag = 1 ; } } if ( ! flag ) return -1 ; return result ; } int main ( ) { string s = " gggggeeekkkks " ; cout << xorOfPrime ( s ) ; return 0 ; }
Count of alphabets having ASCII value less than and greater than k | C ++ implementation of the above approach ; Function to count the number of characters whose ascii value is less than k ; Initialising the count to 0 ; Incrementing the count if the value is less ; return the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountCharacters ( string str , int k ) { int cnt = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] < k ) cnt ++ ; } return cnt ; } int main ( ) { string str = " GeeksForGeeks " ; int k = 90 ; int count = CountCharacters ( str , k ) ; cout << " Characters ▁ with ▁ ASCII ▁ values " " ▁ less ▁ than ▁ K ▁ are ▁ " << count ; cout << " Characters with ASCII values " STRNEWLINE TABSYMBOL TABSYMBOL TABSYMBOL " greater than or equal to K are " << str . length ( ) - count ; return 0 ; }
De Bruijn sequence | Set 1 | C ++ implementation of the above approach ; Modified DFS in which no edge is traversed twice ; Function to find a de Bruijn sequence of order n on k characters ; Clearing global variables ; Number of edges ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_set < string > seen ; vector < int > edges ; void dfs ( string node , int & k , string & A ) { for ( int i = 0 ; i < k ; ++ i ) { string str = node + A [ i ] ; if ( seen . find ( str ) == seen . end ( ) ) { seen . insert ( str ) ; dfs ( str . substr ( 1 ) , k , A ) ; edges . push_back ( i ) ; } } } string deBruijn ( int n , int k , string A ) { seen . clear ( ) ; edges . clear ( ) ; string startingNode = string ( n - 1 , A [ 0 ] ) ; dfs ( startingNode , k , A ) ; string S ; int l = pow ( k , n ) ; for ( int i = 0 ; i < l ; ++ i ) S += A [ edges [ i ] ] ; S += startingNode ; return S ; } int main ( ) { int n = 3 , k = 2 ; string A = "01" ; cout << deBruijn ( n , k , A ) ; return 0 ; }
Shortest distance to every other character from given character | C ++ implementation of above approach ; Function to return required vector of distances ; list to hold position of c in s ; list to hold the result ; length of string ; Iterate over string to create list ; max value of p2 ; Initialize the pointers ; Create result array ; Values at current pointers ; Current Index is before than p1 ; Current Index is between p1 and p2 ; Current Index is nearer to p1 ; Current Index is nearer to p2 ; Move pointer 1 step ahead ; Current index is after p2 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > shortestToChar ( string s , char c ) { vector < int > list ; vector < int > res ; int len = s . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( s [ i ] == c ) { list . push_back ( i ) ; } } int p1 , p2 , v1 , v2 ; int l = list . size ( ) - 1 ; p1 = 0 ; p2 = l > 0 ? 1 : 0 ; for ( int i = 0 ; i < len ; i ++ ) { v1 = list [ p1 ] ; v2 = list [ p2 ] ; if ( i <= v1 ) { res . push_back ( v1 - i ) ; } else if ( i <= v2 ) { if ( i - v1 < v2 - i ) { res . push_back ( i - v1 ) ; } else { res . push_back ( v2 - i ) ; p1 = p2 ; p2 = p2 < l ? ( p2 + 1 ) : p2 ; } } else { res . push_back ( i - v2 ) ; } } return res ; } int main ( ) { string s = " geeksforgeeks " ; char c = ' e ' ; vector < int > res = shortestToChar ( s , c ) ; for ( auto i : res ) cout << i << " ▁ " ; return 0 ; }
Number of words in a camelcase sequence | CPP code to find the count of words in a CamelCase sequence ; Function to find the count of words in a CamelCase sequence ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countWords ( string str ) { int count = 1 ; for ( int i = 1 ; i < str . length ( ) - 1 ; i ++ ) { if ( isupper ( str [ i ] ) ) count ++ ; } return count ; } int main ( ) { string str = " geeksForGeeks " ; cout << countWords ( str ) ; return 0 ; }
Check whether frequency of characters in a string makes Fibonacci Sequence | C ++ program to check whether frequency of characters in a string makes Fibonacci Sequence ; Function to check if the frequencies are in Fibonacci series ; map to store the frequencies of character ; Vector to store first n fibonacci numbers ; Get the size of the map ; a and b are first and second terms of fibonacci series ; vector v contains elements of fibonacci series ; Compare vector elements with values in Map ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string isFibonacci ( string s ) { map < char , int > m ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { m [ s [ i ] ] ++ ; } vector < int > v ; int n = m . size ( ) ; int a = 1 , b = 1 ; int c ; v . push_back ( a ) ; v . push_back ( b ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { v . push_back ( a + b ) ; c = a + b ; a = b ; b = c ; } int flag = 1 ; int i = 0 ; for ( auto itr = m . begin ( ) ; itr != m . end ( ) ; itr ++ ) { if ( itr -> second != v [ i ] ) { flag = 0 ; break ; } i ++ ; } if ( flag == 1 ) return " YES " ; else return " NO " ; } int main ( ) { string s = " abeeedd " ; cout << isFibonacci ( s ) ; return 0 ; }
Lexicographically smallest string formed by removing at most one character | C ++ program to find the lexicographically smallest string by removing at most one character ; Function to return the smallest string ; iterate the string ; first point where s [ i ] > s [ i + 1 ] ; append the string without i - th character in it ; leave the last character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string smallest ( string s ) { int l = s . length ( ) ; string ans = " " ; for ( int i = 0 ; i < l - 1 ; i ++ ) { if ( s [ i ] > s [ i + 1 ] ) { for ( int j = 0 ; j < l ; j ++ ) { if ( i != j ) ans += s [ j ] ; } return ans ; } } ans = s . substr ( 0. , l - 1 ) ; return ans ; } int main ( ) { string s = " abcda " ; cout << smallest ( s ) ; return 0 ; }
Arrangement of the characters of a word such that all vowels are at odd places | C ++ program to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Function to return the factorial of a number ; calculating nPr ; Function to find the number of ways in which the characters of the word can be arranged such that the vowels occupy only the odd positions ; Get total even positions ; Get total odd positions ; Store frequency of each character of the string ; Count total number of vowels ; Count total number of consonants ; Calculate the total number of ways ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int f = 1 ; for ( int i = 2 ; i <= n ; i ++ ) { f = f * i ; } return f ; } int npr ( int n , int r ) { return fact ( n ) / fact ( n - r ) ; } int countPermutations ( string str ) { int even = floor ( str . length ( ) / 2 ) ; int odd = str . length ( ) - even ; int ways = 0 ; int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { ++ freq [ str [ i ] - ' a ' ] ; } int nvowels = freq [ 0 ] + freq [ 4 ] + freq [ 8 ] + freq [ 14 ] + freq [ 20 ] ; int nconsonants = str . length ( ) - nvowels ; ways = npr ( odd , nvowels ) * npr ( nconsonants , nconsonants ) ; return ways ; } int main ( ) { string str = " geeks " ; cout << countPermutations ( str ) ; return 0 ; }
Replace all consonants with nearest vowels in a string | C ++ program to replace all consonants with nearest vowels in a string ; Function to replace consonant with nearest vowels ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string replacingConsonants ( string s ) { char nVowel [ ] = " aaaeeeeiiiiioooooouuuuuuuu " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) s [ i ] = nVowel [ s [ i ] - ' a ' ] ; return s ; } int main ( ) { string s = " geeksforgeeks " ; cout << replacingConsonants ( s ) ; return 0 ; }
Replace consonants with next immediate consonants alphabetically in a String | C ++ program of above approach ; Function to check if a character is vowel or not ; Function that replaces consonant with next immediate consonant alphabatically ; Start traversing the string ; if character is z , than replace it with character b ; if the alphabet is not z ; replace the element with next immediate alphabet ; if next immediate alphabet is vowel , than take next 2 nd immediate alphabet ( since no two vowels occurs consecutively in alphabets ) hence no further checking is required ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { if ( ch != ' a ' && ch != ' e ' && ch != ' i ' && ch != ' o ' && ch != ' u ' ) return false ; return true ; } string replaceConsonants ( string s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( ! isVowel ( s [ i ] ) ) { if ( s [ i ] == ' z ' ) s [ i ] = ' b ' ; else { s [ i ] = ( char ) ( s [ i ] + 1 ) ; if ( isVowel ( s [ i ] ) ) s [ i ] = ( char ) ( s [ i ] + 1 ) ; } } } return s ; } int main ( ) { string s = " geeksforgeeks " ; cout << replaceConsonants ( s ) ; return 0 ; }
Remove characters from string that appears strictly less than K times | C ++ program to reduce the string by removing the characters which appears less than k times ; Function to reduce the string by removing the characters which appears less than k times ; Hash table initialised to 0 ; Increment the frequency of the character ; create a new empty string ; Append the characters which appears more than equal to k times ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; string removeChars ( string str , int k ) { int hash [ MAX_CHAR ] = { 0 } ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; ++ i ) hash [ str [ i ] - ' a ' ] ++ ; string res = " " ; for ( int i = 0 ; i < n ; ++ i ) { if ( hash [ str [ i ] - ' a ' ] >= k ) { res += str [ i ] ; } } return res ; } int main ( ) { string str = " geeksforgeeks " ; int k = 2 ; cout << removeChars ( str , k ) ; return 0 ; }
Count changes in Led Lights to display digits one by one | CPP program to count number of on offs to display digits of a number . ; store the led lights required to display a particular number . ; compute the change in led and keep on adding the change ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOnOff ( string n ) { int Led [ ] = { 6 , 2 , 5 , 5 , 4 , 5 , 6 , 3 , 7 , 5 } ; int len = n . length ( ) ; int sum = Led [ n [ 0 ] - '0' ] ; for ( int i = 1 ; i < len ; i ++ ) { sum = sum + abs ( Led [ n [ i ] - '0' ] - Led [ n [ i - 1 ] - '0' ] ) ; } return sum ; } int main ( ) { string n = "082" ; cout << countOnOff ( n ) ; return 0 ; }
Program to check if all characters have even frequency | C ++ implementation of the above approach ; creating a frequency array ; Finding length of s ; counting frequency of all characters ; checking if any odd frequency is there or not ; Driver Code
#include <iostream> NEW_LINE using namespace std ; bool check ( string s ) { int freq [ 26 ] = { 0 } ; int n = s . length ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) freq [ s [ i ] - 97 ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) if ( freq [ i ] % 2 == 1 ) return false ; return true ; } int main ( ) { string s = " abaccaba " ; check ( s ) ? cout << " Yes " << endl : cout << " No " << endl ; return 0 ; }
Maximum Consecutive Zeroes in Concatenated Binary String | C ++ program to find maximum number of consecutive zeroes after concatenating a binary string ; returns the maximum size of a substring consisting only of zeroes after k concatenation ; stores the maximum length of the required substring ; if the current character is 0 ; stores maximum length of current substrings with zeroes ; if the whole string is filled with zero ; computes the length of the maximal prefix which contains only zeroes ; computes the length of the maximal suffix which contains only zeroes ; if more than 1 concatenations are to be made ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_length_substring ( string st , int n , int k ) { int max_len = 0 ; int len = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( st [ i ] == '0' ) len ++ ; else len = 0 ; max_len = max ( max_len , len ) ; } if ( max_len == n ) return n * k ; int pref = 0 , suff = 0 ; for ( int i = 0 ; st [ i ] == '0' ; ++ i , ++ pref ) ; for ( int i = n - 1 ; st [ i ] == '0' ; -- i , ++ suff ) ; if ( k > 1 ) max_len = max ( max_len , pref + suff ) ; return max_len ; } int main ( ) { int n = 6 ; int k = 3 ; string st = "110010" ; int ans = max_length_substring ( st , n , k ) ; cout << ans ; }
Sub | C ++ implementation of the approach ; Function that checks if the string contain exactly K characters having ASCII value greater than p ; if ASCII value is greater than ' p ' ; if count of satisfying characters is equal to ' K ' then return true ; otherwise return false ; function to count sub - strings ; length of the string ; count of sub - strings ; ' i ' is the starting index for the sub - string ; ' j ' is the no . of characters to include in the sub - string ; check if the sub - string satisfies the condition ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValidSubString ( string r , int K , int p ) { int c = 0 ; for ( int i = 0 ; i < r . length ( ) ; i ++ ) { if ( ( int ) r [ i ] > p ) c ++ ; } if ( c == K ) return true ; else return false ; } void countSubStrings ( string s , int K , int p ) { int l = s . length ( ) ; int count = 0 ; for ( int i = 0 ; i < l ; i ++ ) { for ( int j = K ; ( i + j ) <= l ; j ++ ) { string r = s . substr ( i , j ) ; if ( isValidSubString ( r , K , p ) ) count ++ ; } } cout << count << " STRNEWLINE " ; } int main ( ) { string s = " abepztydba " ; int K = 4 ; int p = 110 ; countSubStrings ( s , K , p ) ; return 0 ; }
Count number of substrings with numeric value greater than X | C ++ implementation of the approach ; Function that counts valid sub - strings ; Only take those numbers that do not start with '0' . ; converting the sub - string starting from index ' i ' and having length ' len ' to int and checking if it is greater than X or not ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string S , int X ) { int count = 0 ; const int N = S . length ( ) ; for ( int i = 0 ; i < N ; ++ i ) { if ( S [ i ] != '0' ) { for ( int len = 1 ; ( i + len ) <= N ; ++ len ) { if ( stoi ( S . substr ( i , len ) ) > X ) count ++ ; } } } return count ; } int main ( ) { string S = "2222" ; int X = 97 ; cout << count ( S , X ) ; return 0 ; }
Check whether a binary string can be formed by concatenating given N numbers sequentially | C ++ implementation of the approach ; Function that returns false if the number passed as argument contains digit ( s ) other than '0' or '1' ; Function that checks whether the binary string can be formed or not ; Empty string for storing the binary number ; check if a [ i ] can be a part of the binary string ; Conversion of int into string ; if a [ i ] can 't be a part then break the loop ; possible to create binary string ; impossible to create binary string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isBinary ( int n ) { while ( n != 0 ) { int temp = n % 10 ; if ( temp != 0 && temp != 1 ) { return false ; } n = n / 10 ; } return true ; } void formBinaryStr ( int n , int a [ ] ) { bool flag = true ; string s = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( isBinary ( a [ i ] ) ) s += to_string ( a [ i ] ) ; else { flag = false ; break ; } } if ( flag ) cout << s << " STRNEWLINE " ; else cout << " - 1 STRNEWLINE " ; } int main ( ) { int a [ ] = { 10 , 1 , 0 , 11 , 10 } ; int N = sizeof ( a ) / sizeof ( a [ 0 ] ) ; formBinaryStr ( N , a ) ; return 0 ; }
Check if all the palindromic sub | C ++ implementation of the approach # include < bitsstdc ++ . h > ; Function to check if the string is palindrome ; Function that checks whether all the palindromic sub - strings are of odd length . ; Creating each substring ; If the sub - string is of even length and is a palindrome then , we return False ; Driver code
using namespace std ; bool checkPalindrome ( string s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] != s [ s . length ( ) - i - 1 ] ) return false ; } return true ; } bool CheckOdd ( string s ) { int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { string x = " " ; for ( int j = i ; j < n ; j ++ ) { x += s [ j ] ; if ( x . length ( ) % 2 == 0 && checkPalindrome ( x ) == true ) return false ; } } return true ; } int main ( ) { string s = " geeksforgeeks " ; if ( CheckOdd ( s ) ) cout << ( " YES " ) ; else cout << ( " NO " ) ; }
Number of permutations of a string in which all the occurrences of a given character occurs together | C ++ implementation of the approach ; Function to return factorial of the number passed as argument ; Function to get the total permutations which satisfy the given condition ; Create has to store count of each character ; Store character occurrences ; Count number of times Particular character comes ; If particular character isn 't present in the string then return 0 ; Remove count of particular character ; Total length of the string ; Assume all occurrences of particular character as a single character . ; Compute factorial of the length ; Divide by the factorials of the no . of occurrences of all the characters . ; return the result ; Driver Code ; Assuming the string and the character are all in uppercase
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long int fact ( int n ) { long long result = 1 ; for ( int i = 1 ; i <= n ; i ++ ) result *= i ; return result ; } int getResult ( string str , char ch ) { int has [ 26 ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) has [ str [ i ] - ' A ' ] ++ ; int particular = has [ ch - ' A ' ] ; if ( particular == 0 ) return 0 ; has [ ch - ' A ' ] = 0 ; int total = str . length ( ) ; total = total - particular + 1 ; long long int result = fact ( total ) ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( has [ i ] > 1 ) { result = result / fact ( has [ i ] ) ; } } return result ; } int main ( ) { string str = " MISSISSIPPI " ; cout << getResult ( str , ' S ' ) << endl ; return 0 ; }
Check if there exists any sub | C ++ program to check if there exists at least 1 sub - sequence in a string which is not palindrome ; Function to check if there exists at least 1 sub - sequence in a string which is not palindrome ; use set to count number of distinct characters ; insert each character in set ; If there is more than 1 unique characters , return true ; Else , return false ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isAnyNotPalindrome ( string s ) { set < char > unique ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) unique . insert ( s [ i ] ) ; if ( unique . size ( ) > 1 ) return true ; else return false ; } int main ( ) { string s = " aaaaab " ; if ( isAnyNotPalindrome ( s ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Arrangement of words without changing the relative position of vowel and consonants | C ++ program for Arrangement of words without changing the relative position of vowel and consonants ; this function return n ! ; this will return total number of ways ; freq maintains frequency of each character in word ; check character is vowel or not ; the characters that are not vowel must be consonant ; number of ways to arrange vowel ; multiply both as these are independent ; Driver function ; string contains only capital letters ; this will contain ans
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll long int NEW_LINE ll factorial ( ll n ) { ll res = 1 ; for ( int i = 1 ; i <= n ; i ++ ) res = res * i ; return res ; } ll count ( string word ) { ll freq [ 27 ] = { 0 } ; ll vowel = 0 , consonant = 0 ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { freq [ word [ i ] - ' A ' ] ++ ; if ( word [ i ] == ' A ' word [ i ] == ' E ' word [ i ] == ' I ' word [ i ] == ' O ' word [ i ] == ' U ' ) { vowel ++ ; } else consonant ++ ; } ll vowelArrange ; vowelArrange = factorial ( vowel ) ; vowelArrange /= factorial ( freq [ 0 ] ) ; vowelArrange /= factorial ( freq [ 4 ] ) ; vowelArrange /= factorial ( freq [ 8 ] ) ; vowelArrange /= factorial ( freq [ 14 ] ) ; vowelArrange /= factorial ( freq [ 20 ] ) ; ll consonantArrange ; consonantArrange = factorial ( consonant ) ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( i != 0 && i != 4 && i != 8 && i != 14 && i != 20 ) consonantArrange /= factorial ( freq [ i ] ) ; } ll total = vowelArrange * consonantArrange ; return total ; } int main ( ) { string word = " COMPUTER " ; ll ans = count ( word ) ; cout << ans << endl ; return 0 ; }
Check if it is possible to create a palindrome string from given N | C ++ implementation of the above approach ; Function to check if a string is palindrome or not ; String that stores characters of s in reverse order ; Length of the string s ; String used to form substring using N ; Variable to store sum of digits of N ; Forming the substring by traversing N ; Appending the substr to str till it 's length becomes equal to sum ; Trimming the string str so that it 's length becomes equal to sum ; Driver code ; Calling function isPalindrome to check if str is Palindrome or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string s ) { string s1 = " " ; int N = s . length ( ) ; for ( int i = N - 1 ; i >= 0 ; i -- ) s1 += s [ i ] ; if ( s == s1 ) return true ; return false ; } bool createString ( int N ) { string str = " " ; string s = to_string ( N ) ; string letters = " abcdefghij " ; int sum = 0 ; string substr = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int digit = s [ i ] - '0' ; substr += letters [ digit ] ; sum += digit ; } while ( str . length ( ) <= sum ) { str += substr ; } str = str . substr ( 0 , sum ) ; return isPalindrome ( str ) ; } int main ( ) { int N = 61 ; bool flag = createString ( N ) ; if ( flag ) cout << " YES " ; else cout << " NO " ; }
Program to find the product of ASCII values of characters in a string | C ++ program to find product of ASCII value of characters in string ; Function to find product of ASCII value of characters in string ; Traverse string to find the product ; Return the product ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long productAscii ( string str ) { long long prod = 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { prod *= ( int ) str [ i ] ; } return prod ; } int main ( ) { string str = " GfG " ; cout << productAscii ( str ) ; return 0 ; }
Check if a large number can be divided into two or more segments of equal sum | C ++ program to Check if a large number can be divided into two or more segments of equal sum ; Function to check if a number can be divided into segments ; length of string ; array to store prefix sum ; first index ; calculate the prefix ; iterate for all number from second number ; sum from 0 th index to i - 1 th index ; counter turns true when sum is obtained from a segment ; iterate till the last number ; sum of segments ; if segment sum is equal to first segment ; when greater than not possible ; if at the end all values are traversed and all segments have sum equal to first segment then it is possible ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s ) { int n = s . length ( ) ; int Presum [ n ] ; Presum [ 0 ] = s [ 0 ] - '0' ; for ( int i = 1 ; i < n ; i ++ ) { Presum [ i ] = Presum [ i - 1 ] + ( s [ i ] - '0' ) ; } for ( int i = 1 ; i <= n - 1 ; i ++ ) { int sum = Presum [ i - 1 ] ; int presum = 0 ; int it = i ; int flag = 0 ; while ( it < n ) { presum += s [ it ] - '0' ; if ( presum == sum ) { presum = 0 ; flag = 1 ; } else if ( presum > sum ) { break ; } it ++ ; } if ( presum == 0 && it == n && flag == 1 ) { return true ; } } return false ; } int main ( ) { string s = "73452" ; if ( check ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Balance a string after removing extra brackets | C ++ implementation of above approach ; Print balanced and remove extra brackets from string ; Maintain a count for opening brackets Traversing string ; check if opening bracket ; print str [ i ] and increment count by 1 ; check if closing bracket and count != 0 ; decrement count by 1 ; if str [ i ] not a closing brackets print it ; balanced brackets if opening brackets are more then closing brackets ; print remaining closing brackets ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void balancedString ( string str ) { int count = 0 , i ; int n = str . length ( ) ; for ( i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' ( ' ) { cout << str [ i ] ; count ++ ; } else if ( str [ i ] == ' ) ' && count != 0 ) { cout << str [ i ] ; count -- ; } else if ( str [ i ] != ' ) ' ) cout << str [ i ] ; } if ( count != 0 ) for ( i = 0 ; i < count ; i ++ ) cout << " ) " ; } int main ( ) { string str = " gau ) ra ) v ( ku ( mar ( rajput ) ) " ; balancedString ( str ) ; return 0 ; }
Minimum operation require to make first and last character same | CPP program to minimum operation require to make first and last character same ; Recursive function call ; Decrement ending index only ; Increment starting index only ; Increment starting index and decrement index ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 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 ] ) return count ; if ( i >= s . size ( ) ) return minOperation ( s , i , j - 1 , count + 1 ) ; else if ( j < 0 ) return minOperation ( s , i + 1 , j , count + 1 ) ; else return min ( minOperation ( s , i , j - 1 , count + 1 ) , minOperation ( s , i + 1 , j , count + 1 ) ) ; } int main ( ) { string s = " bacdefghipalop " ; int ans = minOperation ( s , 0 , s . size ( ) - 1 , 0 ) ; if ( ans == MAX ) cout << -1 ; else cout << ans ; return 0 ; }
Count strings with consonants and vowels at alternate position | C ++ implementation of above approach ; Function to find the count of strings ; Variable to store the final result ; Loop iterating through string ; If ' $ ' is present at the even position in the string ; ' sum ' is multiplied by 21 ; If ' $ ' is present at the odd position in the string ; ' sum ' is multiplied by 5 ; Driver code ; Let the string ' str ' be s$$e$ ; Print result
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countStrings ( string s ) { long sum = 1 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( i % 2 == 0 && s [ i ] == ' $ ' ) sum *= 21 ; else if ( s [ i ] == ' $ ' ) sum *= 5 ; } return sum ; } int main ( ) { string str = " s $ $ e $ " ; cout << countStrings ( str ) << endl ; return 0 ; }
Remove duplicates from a string in O ( 1 ) extra space | C ++ implementation of above approach ; Function to remove duplicates ; keeps track of visited characters ; gets character value ; keeps track of length of resultant string ; check if Xth bit of counter is unset ; mark current character as visited ; Driver code
#include <bits/stdc++.h> NEW_LINE #include <string> NEW_LINE using namespace std ; string removeDuplicatesFromString ( string str ) { int counter = 0 ; int i = 0 ; int size = str . size ( ) ; int x ; int length = 0 ; while ( i < size ) { x = str [ i ] - 97 ; if ( ( counter & ( 1 << x ) ) == 0 ) { str [ length ] = ' a ' + x ; counter = counter | ( 1 << x ) ; length ++ ; } i ++ ; } return str . substr ( 0 , length ) ; } int main ( ) { string str = " geeksforgeeks " ; cout << removeDuplicatesFromString ( str ) ; return 0 ; }
Remove duplicates from a string in O ( 1 ) extra space | C ++ implementation of above approach ; Method to remove duplicates ; Table to keep track of visited characters ; To keep track of end index of resultant string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicatesFromString ( string str ) { vector < int > table ( 256 , 0 ) ; vector < char > chars ; for ( auto i : str ) chars . push_back ( i ) ; int endIndex = 0 ; for ( int i = 0 ; i < chars . size ( ) ; i ++ ) { if ( table [ chars [ i ] ] == 0 ) { table [ chars [ i ] ] = -1 ; chars [ endIndex ++ ] = chars [ i ] ; } } string ans = " " ; for ( int i = 0 ; i < endIndex ; i ++ ) ans += chars [ i ] ; return ans ; } int main ( ) { string str = " geeksforgeeks " ; cout << ( removeDuplicatesFromString ( str ) ) << endl ; }
Check if the characters in a string form a Palindrome in O ( 1 ) extra space | CPP program to check if the characters in the given string forms a Palindrome in O ( 1 ) extra space ; Utility function to get the position of first character in the string ; Get the position of first character in the string ; Utility function to get the position of last character in the string ; Get the position of last character in the string ; Function to check if the characters in the given string forms a Palindrome in O ( 1 ) extra space ; break , when all letters are checked ; if mismatch found , break the loop ; Driver code
#include <iostream> NEW_LINE using namespace std ; int firstPos ( string str , int start , int end ) { int firstChar = -1 ; for ( int i = start ; i <= end ; i ++ ) { if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { firstChar = i ; break ; } } return firstChar ; } int lastPos ( string str , int start , int end ) { int lastChar = -1 ; for ( int i = start ; i >= end ; i -- ) { if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) { lastChar = i ; break ; } } return lastChar ; } bool isPalindrome ( string str ) { int firstChar = 0 , lastChar = str . length ( ) - 1 ; bool ch = true ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { firstChar = firstPos ( str , firstChar , lastChar ) ; lastChar = lastPos ( str , lastChar , firstChar ) ; if ( lastChar < 0 firstChar < 0 ) break ; if ( str [ firstChar ] == str [ lastChar ] ) { firstChar ++ ; lastChar -- ; continue ; } ch = false ; break ; } return ( ch ) ; } int main ( ) { string str = " m TABSYMBOL a ▁ 343 ▁ la ▁ y ▁ a ▁ l ▁ am " ; if ( isPalindrome ( str ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Maximum length subsequence possible of the form R ^ N K ^ N | C ++ program to find the maximum length of a substring of form R ^ nK ^ n ; function to calculate the maximum length of substring of the form R ^ nK ^ n ; Count no . Of R 's before a K ; Count no . Of K 's after a K ; Update maximum length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( string s ) { int max = 0 , i , j = 0 , countk = 0 , countr = 0 ; int table [ s . length ( ) ] [ 2 ] ; for ( i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' R ' ) countr ++ ; else table [ j ++ ] [ 0 ] = countr ; } j -- ; for ( i = s . length ( ) - 1 ; i >= 0 ; i -- ) { if ( s [ i ] == ' K ' ) { countk ++ ; table [ j -- ] [ 1 ] = countk ; } if ( min ( table [ j + 1 ] [ 0 ] , table [ j + 1 ] [ 1 ] ) > max ) max = min ( table [ j + 1 ] [ 0 ] , table [ j + 1 ] [ 1 ] ) ; } return max ; } int main ( ) { string s = " RKRRRKKRRKKKKRR " ; int n = find ( s ) ; cout << ( n ) ; }
Longest common anagram subsequence from N strings | C ++ program to find longest possible subsequence anagram of N strings . ; function to store frequency of each character in each string ; function to Find longest possible sequence of N strings which is anagram to each other ; to get lexicographical largest sequence . ; find minimum of that character ; print that character minimum number of times ; Driver code ; to store frequency of each character in each string ; to get frequency of each character ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void frequency ( int fre [ ] [ MAX_CHAR ] , string s [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { string str = s [ i ] ; for ( int j = 0 ; j < str . size ( ) ; j ++ ) fre [ i ] [ str [ j ] - ' a ' ] ++ ; } } void LongestSequence ( int fre [ ] [ MAX_CHAR ] , int n ) { for ( int i = MAX_CHAR - 1 ; i >= 0 ; i -- ) { int mi = fre [ 0 ] [ i ] ; for ( int j = 1 ; j < n ; j ++ ) mi = min ( fre [ j ] [ i ] , mi ) ; while ( mi -- ) cout << ( char ) ( ' a ' + i ) ; } } int main ( ) { string s [ ] = { " loo " , " lol " , " olive " } ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; int fre [ n ] [ 26 ] = { 0 } ; frequency ( fre , s , n ) ; LongestSequence ( fre , n ) ; return 0 ; }
Check if two strings are permutation of each other | C ++ program to check whether two strings are Permutations of each other ; function to check whether two strings are Permutation of each other ; Get lengths of both strings ; If length of both strings is not same , then they cannot be Permutation ; Sort both strings ; Compare sorted strings ; Driver program to test to print printDups
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool arePermutation ( string str1 , string str2 ) { int n1 = str1 . length ( ) ; int n2 = str2 . length ( ) ; if ( n1 != n2 ) return false ; sort ( str1 . begin ( ) , str1 . end ( ) ) ; sort ( str2 . begin ( ) , str2 . end ( ) ) ; for ( int i = 0 ; i < n1 ; i ++ ) if ( str1 [ i ] != str2 [ i ] ) return false ; return true ; } int main ( ) { string str1 = " test " ; string str2 = " ttew " ; if ( arePermutation ( str1 , str2 ) ) printf ( " Yes " ) ; else printf ( " No " ) ; return 0 ; }
Check if two strings are permutation of each other | C ++ function to check whether two strings are Permutations of each other ; Create a count array and initialize all values as 0 ; For each character in input strings , increment count in the corresponding count array ; If both strings are of different length . Removing this condition will make the program fail for strings like " aaca " and " aca " ; See if there is any non - zero value in count array
bool arePermutation ( string str1 , string str2 ) { int count [ NO_OF_CHARS ] = { 0 } ; int i ; for ( i = 0 ; str1 [ i ] && str2 [ i ] ; i ++ ) { count [ str1 [ i ] ] ++ ; count [ str2 [ i ] ] -- ; } if ( str1 [ i ] str2 [ i ] ) return false ; for ( i = 0 ; i < NO_OF_CHARS ; i ++ ) if ( count [ i ] ) return false ; return true ; }
Maximum power of jump required to reach the end of string | C ++ program to calculate power of jump ; Function to calculate the maximum power of the jump ; Initialize the count with 1 ; Find the character at last index ; Start traversing the string ; Check if the current char is equal to the last character ; max_so_far stores maximum value of the power of the jump from starting to ith position ; Reset the count to 1 ; Else , increment the number of jumps / count ; Return the maximum number of jumps ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int powerOfJump ( string s ) { int count = 1 ; int max_so_far = INT_MIN ; char ch = s [ s . length ( ) - 1 ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ch ) { if ( count > max_so_far ) { max_so_far = count ; } count = 1 ; } else count ++ ; } return max_so_far ; } int main ( ) { string st = "1010101" ; cout << powerOfJump ( st ) ; }
Longest substring with count of 1 s more than 0 s | CPP program to find largest substring having count of 1 s more than count count of 0 s . ; Function to find longest substring having count of 1 s more than count of 0 s . ; To store sum . ; To store first occurrence of each sum value . ; To store maximum length . ; To store current substring length . ; Add 1 if current character is 1 else subtract 1. ; If sum is positive , then maximum length substring is bin [ 0. . i ] ; If sum is negative , then maximum length substring is bin [ j + 1. . i ] , where sum of substring bin [ 0. . j ] is sum - 1. ; Make entry for this sum value in hash table if this value is not present . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findLongestSub ( string bin ) { int n = bin . length ( ) , i ; int sum = 0 ; unordered_map < int , int > prevSum ; int maxlen = 0 ; int currlen ; for ( i = 0 ; i < n ; i ++ ) { if ( bin [ i ] == '1' ) sum ++ ; else sum -- ; if ( sum > 0 ) { maxlen = i + 1 ; } else if ( sum <= 0 ) { if ( prevSum . find ( sum - 1 ) != prevSum . end ( ) ) { currlen = i - prevSum [ sum - 1 ] ; maxlen = max ( maxlen , currlen ) ; } } if ( prevSum . find ( sum ) == prevSum . end ( ) ) prevSum [ sum ] = i ; } return maxlen ; } int main ( ) { string bin = "1010" ; cout << findLongestSub ( bin ) ; return 0 ; }
Average of ASCII values of characters of a given string | C ++ code to find average of ASCII characters ; Function to find average of ASCII value of chars ; loop to sum the ascii value of chars ; Returning average of chars ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int averageValue ( string s ) { int sum_char = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { sum_char += ( int ) s [ i ] ; } return sum_char / s . length ( ) ; } int main ( ) { string s = " GeeksforGeeks " ; cout << averageValue ( s ) ; return 0 ; }
Check if two same sub | C ++ program to Check if similar subsequences exist or not ; Function to check if similar subsequences occur in a string or not ; iterate and count the frequency ; freq [ s [ i ] - ' a ' ] ++ ; counting frequency of the letters ; check if frequency is more than once of any character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s , int l ) { int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < l ; i ++ ) { } for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] >= 2 ) return true ; } return false ; } int main ( ) { string s = " geeksforgeeks " ; int l = s . length ( ) ; if ( check ( s , l ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Find the winner of a game where scores are given as a binary string | Cpp program for predicting winner ; function for winner prediction ; increase count ; check losing condition ; check winning condition ; check tie on n - 1 point ; increase count ; check for 2 point lead ; condition of lost ; condition of win ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void predictWinner ( string score , int n ) { int count [ 2 ] = { 0 } , i ; for ( i = 0 ; i < score . size ( ) ; i ++ ) { count [ score [ i ] - '0' ] ++ ; if ( count [ 0 ] == n && count [ 1 ] < n - 1 ) { cout << " GEEKS ▁ lost " ; return ; } if ( count [ 1 ] == n && count [ 0 ] < n - 1 ) { cout << " GEEKS ▁ won " ; return ; } if ( count [ 0 ] == n - 1 && count [ 1 ] == n - 1 ) { count [ 0 ] = 0 ; count [ 1 ] = 0 ; break ; } } for ( i ++ ; i < score . size ( ) ; i ++ ) { count [ score [ i ] - '0' ] ++ ; if ( abs ( count [ 0 ] - count [ 1 ] ) == 2 ) { if ( count [ 0 ] > count [ 1 ] ) cout << " GEEKS ▁ lost " ; else cout << " GEEKS ▁ won " ; return ; } } } int main ( ) { string score = "1001010101111011101111" ; int n = 15 ; predictWinner ( score , n ) ; return 0 ; }
Number of Counterclockwise shifts to make a string palindrome | C ++ program to find counter clockwise shifts to make string palindrome . ; Function to check if given string is palindrome or not . ; Function to find counter clockwise shifts to make string palindrome . ; Pointer to starting of current shifted string . ; Pointer to ending of current shifted string . ; Concatenate string with itself ; To store counterclockwise shifts ; Move left and right pointers one step at a time . ; Check if current shifted string is palindrome or not ; If string is not palindrome then increase count of number of shifts by 1. ; Driver code .
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str , int l , int r ) { while ( l < r ) { if ( str [ l ] != str [ r ] ) return false ; l ++ ; r -- ; } return true ; } int CyclicShifts ( string str ) { int n = str . length ( ) ; int left = 0 ; int right = n - 1 ; str = str + str ; int cnt = 0 ; while ( right < 2 * n - 1 ) { if ( isPalindrome ( str , left , right ) ) break ; cnt ++ ; left ++ ; right ++ ; } return cnt ; } int main ( ) { string str = " bccbbaab " ; cout << CyclicShifts ( str ) ; return 0 ; }
Find a string such that every character is lexicographically greater than its immediate next character | C ++ program to print a string in reverse alphabetical order upto given number ; Function that prints the required string ; Find modulus with 26 ; Print extra characters required ; Print the given reverse string countOfStr times ; Driver Code ; Initialize a string in reverse order
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printString ( int n , string str ) { string str2 = " " ; int extraChar = n % 26 ; if ( extraChar >= 1 ) { for ( int i = 26 - ( extraChar + 1 ) ; i <= 25 ; i ++ ) str2 += str [ i ] ; } int countOfStr = n / 26 ; for ( int i = 1 ; i <= countOfStr ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) str2 += str [ j ] ; } return str2 ; } int main ( ) { int n = 30 ; string str = " zyxwvutsrqponmlkjihgfedcba " ; cout << printString ( n , str ) ; return 0 ; }
Longest Common Prefix Matching | Set | A C ++ Program to find the longest common prefix ; A Utility Function to find the common prefix between first and last strings ; Compare str1 and str2 ; A Function that returns the longest common prefix from the array of strings ; sorts the N set of strings ; prints the common prefix of the first and the last string of the set of strings ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string commonPrefixUtil ( string str1 , string str2 ) { string result ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; for ( int i = 0 , j = 0 ; i <= n1 - 1 && j <= n2 - 1 ; i ++ , j ++ ) { if ( str1 [ i ] != str2 [ j ] ) break ; result . push_back ( str1 [ i ] ) ; } return ( result ) ; } void commonPrefix ( string arr [ ] , int n ) { sort ( arr , arr + n ) ; cout << commonPrefixUtil ( arr [ 0 ] , arr [ n - 1 ] ) ; } int main ( ) { string arr [ ] = { " geeksforgeeks " , " geeks " , " geek " , " geezer " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; commonPrefix ( arr , n ) ; return 0 ; }
Square of large number represented as String | C ++ program to multiply two numbers represented as strings . ; Multiplies str1 and str2 , and prints result . ; will keep the result number in vector in reverse order ; Below two indexes are used to find positions in result . ; Go from right to left in num1 ; To shift position to left after every multiplication of a digit in num2 ; Go from right to left in num2 ; Take current digit of second number ; Multiply with current digit of first number and add result to previously stored result at current position . ; Carry for next iteration ; Store result ; store carry in next cell ; To shift position to left after every multiplication of a digit in num1 . ; ignore '0' s from the right ; If all were '0' s - means either both or one of num1 or num2 were '0' ; generate the result string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string multiply ( string num1 , string num2 ) { int n1 = num1 . size ( ) ; int n2 = num2 . size ( ) ; if ( n1 == 0 n2 == 0 ) return "0" ; vector < int > result ( n1 + n2 , 0 ) ; int i_n1 = 0 ; int i_n2 = 0 ; for ( int i = n1 - 1 ; i >= 0 ; i -- ) { int carry = 0 ; int n1 = num1 [ i ] - '0' ; i_n2 = 0 ; for ( int j = n2 - 1 ; j >= 0 ; j -- ) { int n2 = num2 [ j ] - '0' ; int sum = n1 * n2 + result [ i_n1 + i_n2 ] + carry ; carry = sum / 10 ; result [ i_n1 + i_n2 ] = sum % 10 ; i_n2 ++ ; } if ( carry > 0 ) result [ i_n1 + i_n2 ] += carry ; i_n1 ++ ; } int i = result . size ( ) - 1 ; while ( i >= 0 && result [ i ] == 0 ) i -- ; if ( i == -1 ) return "0" ; string s = " " ; while ( i >= 0 ) s += std :: to_string ( result [ i -- ] ) ; return s ; } int main ( ) { string str1 = "454545454545454545" ; cout << multiply ( str1 , str1 ) ; return 0 ; }
Perform n steps to convert every digit of a number in the format [ count ] [ digit ] | C ++ program to convert number to the format [ count ] [ digit ] at every step ; Function to perform every step ; perform N steps ; Traverse in the string ; for last digit ; recur for current string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countDigits ( string st , int n ) { if ( n > 0 ) { int cnt = 1 , i ; string st2 = " " ; for ( i = 1 ; i < st . length ( ) ; i ++ ) { if ( st [ i ] == st [ i - 1 ] ) cnt ++ ; else { st2 += ( '0' + cnt ) ; st2 += st [ i - 1 ] ; cnt = 1 ; } } st2 += ( '0' + cnt ) ; st2 += st [ i - 1 ] ; countDigits ( st2 , -- n ) ; } else cout << st ; } int main ( ) { string num = "123" ; int n = 3 ; countDigits ( num , n ) ; return 0 ; }
Sudo Placement | Special Subsequences | C ++ Program to find all special subsequences of the given type ; Function to generate the required subsequences ; If the index pointer has reached the end of input string ; Skip empty ( " ▁ " ) subsequence ; Exclude current character in output string ; Include current character in output string ; Remove the current included character and and include it in its uppercase form ; Function to print the required subsequences ; Output String to store every subsequence ; Set of strings that will store all special subsequences in lexicographical sorted order ; Sort the strings to print in sorted order ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generateSubsequences ( string input , string output , int idx , vector < string > & ans ) { if ( input [ idx ] == ' \0' ) { if ( output . size ( ) ) ans . push_back ( output ) ; return ; } generateSubsequences ( input , output , idx + 1 , ans ) ; output += input [ idx ] ; generateSubsequences ( input , output , idx + 1 , ans ) ; output . pop_back ( ) ; char upper = input [ idx ] ; upper = toupper ( upper ) ; output += upper ; generateSubsequences ( input , output , idx + 1 , ans ) ; } void printSubsequences ( string S ) { string output ; vector < string > ans ; generateSubsequences ( S , output , 0 , ans ) ; sort ( ans . begin ( ) , ans . end ( ) ) ; for ( auto str : ans ) cout << str << " ▁ " ; } int main ( ) { string S = " ab " ; printSubsequences ( S ) ; return 0 ; }
Check if the given string of words can be formed from words present in the dictionary | C ++ program to check if a sentence can be formed from a given set of words . ; Function to check if the word is in the dictionary or not ; map to store all words in dictionary with their count ; adding all words in map ; search in map for all words in the sentence ; all words of sentence are present ; Driver Code ; Calling function to check if words are present in the dictionary or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool match_words ( string dictionary [ ] , string sentence [ ] , int n , int m ) { unordered_map < string , int > mp ; for ( int i = 0 ; i < n ; i ++ ) { mp [ dictionary [ i ] ] ++ ; } for ( int i = 0 ; i < m ; i ++ ) { if ( mp [ sentence [ i ] ] ) mp [ sentence [ i ] ] -= 1 ; else return false ; } return true ; } int main ( ) { string dictionary [ ] = { " find " , " a " , " geeks " , " all " , " for " , " on " , " geeks " , " answers " , " inter " } ; int n = sizeof ( dictionary ) / sizeof ( dictionary [ 0 ] ) ; string sentence [ ] = { " find " , " all " , " answers " , " on " , " geeks " , " for " , " geeks " } ; int m = sizeof ( sentence ) / sizeof ( sentence [ 0 ] ) ; if ( match_words ( dictionary , sentence , n , m ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
Print all 3 digit repeating numbers in a very large number | CPP program to print 3 digit repeating numbers ; function to print 3 digit repeating numbers ; Hashmap to store the frequency of a 3 digit number ; first three digit number ; if key already exists increase value by 1 ; Output the three digit numbers with frequency > 1 ; Driver Code ; Input string ; Calling Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNum ( string s ) { int i = 0 , j = 0 , val = 0 ; map < int , int > mp ; val = ( s [ 0 ] - '0' ) * 100 + ( s [ 1 ] - '0' ) * 10 + ( s [ 2 ] - '0' ) ; mp [ val ] = 1 ; for ( i = 3 ; i < s . length ( ) ; i ++ ) { val = ( val % 100 ) * 10 + s [ i ] - '0' ; if ( mp . find ( val ) != mp . end ( ) ) { mp [ val ] = mp [ val ] + 1 ; } else { mp [ val ] = 1 ; } } for ( auto m : mp ) { int key = m . first ; int value = m . second ; if ( value > 1 ) cout << key << " ▁ - ▁ " << value << " ▁ times " << endl ; } } int main ( ) { string input = "123412345123456" ; printNum ( input ) ; }
Count occurrences of a substring recursively | Recursive C ++ program for counting number of substrings ; Recursive function to count the number of occurrences of " hi " in str . ; Base Case ; Recursive Case Checking if the first substring matches ; Otherwise , return the count from the remaining index ; Driver function
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int countSubstrig ( string str1 , string str2 ) { int n1 = str1 . length ( ) ; int n2 = str2 . length ( ) ; if ( n1 == 0 n1 < n2 ) return 0 ; if ( str1 . substr ( 0 , n2 ) . compare ( str2 ) == 0 ) return countSubstrig ( str1 . substr ( n2 - 1 ) , str2 ) + 1 ; return countSubstrig ( str1 . substr ( n2 - 1 ) , str2 ) ; } int main ( ) { string str1 = " geeksforgeeks " , str2 = " geeks " ; cout << countSubstrig ( str1 , str2 ) << endl ; str1 = " hikakashi " , str2 = " hi " ; cout << countSubstrig ( str1 , str2 ) << endl ; return 0 ; }
Check if a binary string contains all permutations of length k | C ++ Program to Check If a String Contains All Binary Codes of Size K ; Unordered map of type string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define int long long NEW_LINE bool hasAllcodes ( string s , int k ) { unordered_set < string > us ; for ( int i = 0 ; i + k <= s . size ( ) ; i ++ ) { us . insert ( s . substr ( i , k ) ) ; } return us . size ( ) == 1 << k ; } signed main ( ) { string s = "00110110" ; int k = 2 ; if ( hasAllcodes ) { cout << " YES STRNEWLINE " ; } else { cout << " NO STRNEWLINE " ; } }
Add n binary strings | C ++ program to add n binary strings ; This function adds two binary strings and return result as a third string ; Initialize result ; Initialize digit sum ; Traverse both strings starting from last characters ; Compute sum of last digits and carry ; If current digit sum is 1 or 3 , add 1 to result ; Compute carry ; Move to next digits ; function to add n binary strings ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; string addBinaryUtil ( string a , string b ) { string result = " " ; int s = 0 ; int i = a . size ( ) - 1 , j = b . size ( ) - 1 ; while ( i >= 0 j >= 0 s == 1 ) { s += ( ( i >= 0 ) ? a [ i ] - '0' : 0 ) ; s += ( ( j >= 0 ) ? b [ j ] - '0' : 0 ) ; result = char ( s % 2 + '0' ) + result ; s /= 2 ; i -- ; j -- ; } return result ; } string addBinary ( string arr [ ] , int n ) { string result = " " ; for ( int i = 0 ; i < n ; i ++ ) result = addBinaryUtil ( result , arr [ i ] ) ; return result ; } int main ( ) { string arr [ ] = { "1" , "10" , "11" } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << addBinary ( arr , n ) << endl ; return 0 ; }
Reverse String according to the number of words | C ++ program to reverse string according to the number of words ; Reverse the letters of the word ; Temporary variable to store character ; Swapping the first and last character ; This function forms the required string ; Checking the number of words present in string to reverse ; Reverse the letter of the words ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( char str [ ] , int start , int end ) { char temp ; while ( start <= end ) { temp = str [ start ] ; str [ start ] = str [ end ] ; str [ end ] = temp ; start ++ ; end -- ; } } void reverseletter ( char str [ ] , int start , int end ) { int wstart , wend ; for ( wstart = wend = start ; wend < end ; wend ++ ) { if ( str [ wend ] == ' ▁ ' ) continue ; while ( str [ wend ] != ' ▁ ' && wend <= end ) wend ++ ; wend -- ; reverse ( str , wstart , wend ) ; } } int main ( ) { char str [ 1000 ] = " Ashish ▁ Yadav ▁ Abhishek ▁ Rajput ▁ Sunil ▁ Pundir " ; reverseletter ( str , 0 , strlen ( str ) - 1 ) ; cout << str ; return 0 ; }
Minimum bit changes in Binary Circular array to reach a index | CPP program to find direction with minimum flips ; finding which path have minimum flip bit and the minimum flip bits ; concatenating given string to itself , to make it circular ; check x is greater than y . marking if output need to be opposite . ; iterate Clockwise ; if current bit is not equal to next index bit . ; iterate Anti - Clockwise ; if current bit is not equal to next index bit . ; Finding whether Clockwise or Anti - clockwise path take minimum flip . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minimumFlip ( string s , int x , int y ) { s = s + s ; bool isOpposite = false ; if ( x > y ) { swap ( x , y ) ; isOpposite = true ; } int valClockwise = 0 ; char cur = s [ x ] ; for ( int i = x ; i <= y ; i ++ ) { if ( s [ i ] != cur ) { cur = s [ i ] ; valClockwise ++ ; } } int valAnticlockwise = 0 ; cur = s [ y ] ; x += s . length ( ) ; for ( int i = y ; i <= x ; i ++ ) { if ( s [ i ] != cur ) { cur = s [ i ] ; valAnticlockwise ++ ; } } if ( valClockwise <= valAnticlockwise ) { if ( ! isOpposite ) cout << " Clockwise ▁ " << valClockwise << endl ; else cout << " Anti - clockwise ▁ " << valAnticlockwise << endl ; } else { if ( ! isOpposite ) cout << " Anti - clockwise ▁ " << valAnticlockwise << endl ; else cout << " Clockwise ▁ " << valClockwise << endl ; } } int main ( ) { int x = 0 , y = 8 ; string s = "000110" ; minimumFlip ( s , x , y ) ; return 0 ; }
Prefixes with more a than b | CPP code to count the prefixes with more a than b ; Function to count prefixes ; calculating for string S ; count == 0 or when N == 1 ; when all characters are a or a - b == 0 ; checking for saturation of string after repetitive addition ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int prefix ( string k , int n ) { int a = 0 , b = 0 , count = 0 ; int i = 0 ; int len = k . size ( ) ; for ( i = 0 ; i < len ; i ++ ) { if ( k [ i ] == ' a ' ) a ++ ; if ( k [ i ] == ' b ' ) b ++ ; if ( a > b ) { count ++ ; } } if ( count == 0 n == 1 ) { cout << count << endl ; return 0 ; } if ( count == len a - b == 0 ) { cout << count * n << endl ; return 0 ; } int n2 = n - 1 , count2 = 0 ; while ( n2 != 0 ) { for ( i = 0 ; i < len ; i ++ ) { if ( k [ i ] == ' a ' ) a ++ ; if ( k [ i ] == ' b ' ) b ++ ; if ( a > b ) { count2 ++ ; } } count += count2 ; n2 -- ; if ( count2 == 0 ) break ; if ( count2 == len ) { count += ( n2 * count2 ) ; break ; } count2 = 0 ; } return count ; } int main ( ) { string S = " aba " ; int N = 2 ; cout << prefix ( S , N ) << endl ; S = " baa " ; N = 3 ; cout << prefix ( S , N ) << endl ; return 0 ; }
Pairs whose concatenation contain all digits | C ++ Program to find number of pairs whose concatenation contains all digits from 0 to 9. ; Function to return number of pairs whose concatenation contain all digits from 0 to 9 ; making the mask for each of the number . ; for each of the possible pair which can make OR value equal to 1023 ; finding the count of pair from the given numbers . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 20 NEW_LINE int countPair ( char str [ N ] [ N ] , int n ) { int cnt [ 1 << 10 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { int mask = 0 ; for ( int j = 0 ; str [ i ] [ j ] != ' \0' ; ++ j ) mask |= ( 1 << ( str [ i ] [ j ] - '0' ) ) ; cnt [ mask ] ++ ; } int ans = 0 ; for ( int m1 = 0 ; m1 <= 1023 ; m1 ++ ) for ( int m2 = 0 ; m2 <= 1023 ; m2 ++ ) if ( ( m1 m2 ) == 1023 ) { ans += ( ( m1 == m2 ) ? ( cnt [ m1 ] * ( cnt [ m1 ] - 1 ) ) : ( cnt [ m1 ] * cnt [ m2 ] ) ) ; } return ans / 2 ; } int main ( ) { int n = 5 ; char str [ ] [ N ] = { "129300455" , "5559948277" , "012334556" , "56789" , "123456879" } ; cout << countPair ( str , n ) << endl ; return 0 ; }
Count binary strings with twice zeros in first half | CPP for finding number of binary strings number of '0' in first half is double the number of '0' in second half of string ; pre define some constant ; global values for pre computation ; function to print number of required string ; calculate answer using proposed algorithm ; Driver code
#include <bits/stdc++.h> NEW_LINE #define mod 1000000007 NEW_LINE #define max 1001 NEW_LINE using namespace std ; long long int nCr [ 1003 ] [ 1003 ] ; void preComputeCoeff ( ) { for ( int i = 0 ; i < max ; i ++ ) { for ( int j = 0 ; j <= i ; j ++ ) { if ( j == 0 j == i ) nCr [ i ] [ j ] = 1 ; else nCr [ i ] [ j ] = ( nCr [ i - 1 ] [ j - 1 ] + nCr [ i - 1 ] [ j ] ) % mod ; } } } long long int computeStringCount ( int N ) { int n = N / 2 ; long long int ans = 0 ; for ( int i = 2 ; i <= n ; i += 2 ) ans = ( ans + ( ( nCr [ n ] [ i ] * nCr [ n ] [ i / 2 ] ) % mod ) ) % mod ; return ans ; } int main ( ) { preComputeCoeff ( ) ; int N = 3 ; cout << computeStringCount ( N ) << endl ; return 0 ; }
Count of ' GFG ' Subsequences in the given string | CPP Program to find the " GFG " subsequence in the given string ; Print the count of " GFG " subsequence in the string ; Traversing the given string ; If the character is ' G ' , increment the count of ' G ' , increase the result and update the array . ; If the character is ' F ' , increment the count of ' F ' and update the array . ; Ignore other character . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 100 NEW_LINE void countSubsequence ( char s [ ] , int n ) { int cntG = 0 , cntF = 0 , result = 0 , C = 0 ; for ( int i = 0 ; i < n ; i ++ ) { switch ( s [ i ] ) { case ' G ' : cntG ++ ; result += C ; break ; case ' F ' : cntF ++ ; C += cntG ; break ; default : continue ; } } cout << result << endl ; } int main ( ) { char s [ ] = " GFGFG " ; int n = strlen ( s ) ; countSubsequence ( s , n ) ; return 0 ; }
Lexicographical Maximum substring of string | CPP program to find the lexicographically maximum substring . ; loop to find the max leicographic substring in the substring array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string LexicographicalMaxString ( string str ) { string mx = " " ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) mx = max ( mx , str . substr ( i ) ) ; return mx ; } int main ( ) { string str = " ababaa " ; cout << LexicographicalMaxString ( str ) ; return 0 ; }
Lexicographical Maximum substring of string | C ++ program to find the lexicographically maximum substring . ; We store all the indexes of maximum characters we have in the string ; We form a substring from that maximum character index till end and check if its greater that maxstring ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string LexicographicalMaxString ( string str ) { char maxchar = ' a ' ; vector < int > index ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] >= maxchar ) { maxchar = str [ i ] ; index . push_back ( i ) ; } } string maxstring = " " ; for ( int i = 0 ; i < index . size ( ) ; i ++ ) { if ( str . substr ( index [ i ] , str . length ( ) ) > maxstring ) { maxstring = str . substr ( index [ i ] , str . length ( ) ) ; } } return maxstring ; } int main ( ) { string str = " acbacbc " ; cout << LexicographicalMaxString ( str ) ; return 0 ; }
Print longest palindrome word in a sentence | C ++ program to print longest palindrome word in a sentence and its length ; Function to check if a word is palindrome ; making the check case case insensitive word = word . toLowerCase ( ) ; ; loop to check palindrome ; Function to find longest palindrome word ; to check last word for palindrome ; to store each word ; extracting each word ; Driver code
#include <iostream> NEW_LINE #include <algorithm> NEW_LINE #include <string> NEW_LINE using namespace std ; bool checkPalin ( string word ) { int n = word . length ( ) ; transform ( word . begin ( ) , word . end ( ) , word . begin ( ) , :: tolower ) ; for ( int i = 0 ; i < n ; i ++ , n -- ) if ( word [ i ] != word [ n - 1 ] ) return false ; return true ; } string longestPalin ( string str ) { str = str + " ▁ " ; string longestword = " " , word = " " ; int length , length1 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str [ i ] ; if ( ch != ' ▁ ' ) word = word + ch ; else { length = word . length ( ) ; if ( checkPalin ( word ) && length > length1 ) { length1 = length ; longestword = word ; } word = " " ; } } return longestword ; } int main ( ) { string s = " My ▁ name ▁ is ▁ ava ▁ and ▁ i ▁ love " " ▁ Geeksforgeeks " ; if ( longestPalin ( s ) == " " ) cout << " No ▁ Palindrome " << " ▁ Word " ; else cout << longestPalin ( s ) ; return 0 ; }
Number of common base strings for two strings | CPP program to count common base strings of s1 and s2 . ; function for finding common divisor . ; Checking if ' base ' is base string of ' s1' ; Checking if ' base ' is base string of ' s2' ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCommonBase ( string base , string s1 , string s2 ) { for ( int j = 0 ; j < s1 . length ( ) ; ++ j ) if ( base [ j % base . length ( ) ] != s1 [ j ] ) return false ; for ( int j = 0 ; j < s2 . length ( ) ; ++ j ) if ( base [ j % base . length ( ) ] != s2 [ j ] ) return false ; return true ; } int countCommonBases ( string s1 , string s2 ) { int n1 = s1 . length ( ) , n2 = s2 . length ( ) ; int count = 0 ; for ( int i = 1 ; i <= min ( n1 , n2 ) ; i ++ ) { string base = s1 . substr ( 0 , i ) ; if ( isCommonBase ( base , s1 , s2 ) ) count ++ ; } return count ; } int main ( ) { string s1 = " pqrspqrs " ; string s2 = " pqrspqrspqrspqrs " ; cout << countCommonBases ( s1 , s2 ) << endl ; return 0 ; }
Removing elements between the two zeros | C ++ program to delete elements between zeros ; Function to find the string after operation ; Travesing through string ; Checking for character Between two zeros ; deleting the character At specific position ; updating the length of the string ; Drivers code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findstring ( string s ) { int n = s . length ( ) ; for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( ( s . at ( i - 1 ) == '0' && s . at ( i + 1 ) == '0' ) ) { s . erase ( i , 1 ) ; i -- ; if ( i > 0 && s . at ( i - 1 ) == '0' ) i -- ; n = s . length ( ) ; } } return s ; } int main ( ) { cout << findstring ( "100100" ) ; return 0 ; }
Perfect Square String | C ++ program to find if string is a perfect square or not . ; calculating the length of the string ; calculating the ASCII value of the string ; Find floating point value of square root of x . ; If square root is an integer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquareString ( string str ) { int sum = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) sum += ( int ) str [ i ] ; long double squareRoot = sqrt ( sum ) ; return ( ( squareRoot - floor ( squareRoot ) ) == 0 ) ; } int main ( ) { string str = " d " ; if ( isPerfectSquareString ( str ) ) cout << " Yes " ; else cout << " No " ; }
Count substrings with each character occurring at most k times | CPP program to count number of substrings in which each character has count less than or equal to k . ; function to find number of substring in which each character has count less than or equal to k . ; initialize left and right pointer to 0 ; an array to keep track of count of each alphabet ; decrement the count ; increment left pointer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_sub ( string s , int k ) { int len = s . length ( ) ; int lp = 0 , rp = 0 ; int ans = 0 ; int hash_char [ 26 ] = { 0 } ; for ( ; rp < len ; rp ++ ) { hash_char [ s [ rp ] - ' a ' ] ++ ; while ( hash_char [ s [ rp ] - ' a ' ] > k ) { hash_char [ s [ lp ] - ' a ' ] -- ; lp ++ ; } ans += rp - lp + 1 ; } return ans ; } int main ( ) { string s = " aaabb " ; int k = 2 ; cout << find_sub ( s , k ) << endl ; }
Remove consecutive vowels from string | C ++ program for printing sentence without repetitive vowels ; function which returns True or False for occurrence of a vowel ; this compares vowel with character ' c ' ; function to print resultant string ; print 1 st character ; loop to check for each character ; comparison of consecutive characters ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_vow ( char c ) { return ( c == ' a ' ) || ( c == ' e ' ) || ( c == ' i ' ) || ( c == ' o ' ) || ( c == ' u ' ) ; } void removeVowels ( string str ) { printf ( " % c " , str [ 0 ] ) ; for ( int i = 1 ; str [ i ] ; i ++ ) if ( ( ! is_vow ( str [ i - 1 ] ) ) || ( ! is_vow ( str [ i ] ) ) ) printf ( " % c " , str [ i ] ) ; } int main ( ) { char str [ ] = " ▁ geeks ▁ for ▁ geeks " ; removeVowels ( str ) ; }
Find the Number which contain the digit d | CPP program to print the number which contain the digit d from 0 to n ; function to display the values ; Converting d to character ; Loop to check each digit one by one . ; initialize the string ; checking for digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printNumbers ( int n , int d ) { string st = " " ; st += to_string ( d ) ; char ch = st [ 0 ] ; string p = " " ; p += ch ; for ( int i = 0 ; i <= n ; i ++ ) { st = " " ; st = st + to_string ( i ) ; int idx = st . find ( p ) ; if ( i == d idx != -1 ) cout << ( i ) << " ▁ " ; } } int main ( ) { int n = 100 , d = 5 ; printNumbers ( n , d ) ; }
Transform a string such that it has abcd . . z as a subsequence | C Plus Plus Program to transform the given string to contain the required subsequence ; function to transform string with string passed as reference ; initializing the variable ch to ' a ' ; if the length of string is less than 26 , we can 't obtain the required subsequence ; if ch has reached ' z ' , it means we have transformed our string such that required subsequence can be obtained ; current character is not greater than ch , then replace it with ch and increment ch ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool transformString ( string & s ) { char ch = ' a ' ; if ( s . size ( ) < 26 ) return false ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( int ( ch ) > int ( ' z ' ) ) break ; if ( s [ i ] <= ch ) { s [ i ] = ch ; ch = char ( int ( ch ) + 1 ) ; } } if ( ch <= ' z ' ) return false ; return true ; } int main ( ) { string str = " aaaaaaaaaaaaaaaaaaaaaaaaaa " ; if ( transformString ( str ) ) cout << str << endl ; else cout << " Not ▁ Possible " << endl ; return 0 ; }
Number of pairs with Pandigital Concatenation | C ++ program to find all Pandigital concatenations of two strings . ; Checks if a given string is Pandigital ; digit i is not present thus not pandigital ; Returns number of pairs of strings resulting in Pandigital Concatenations ; iterate over all pair of strings ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPanDigital ( string s ) { bool digits [ 10 ] = { false } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) digits [ s [ i ] - '0' ] = true ; for ( int i = 0 ; i <= 9 ; i ++ ) if ( digits [ i ] == false ) return false ; return true ; } int countPandigitalPairs ( vector < string > & v ) { int pairs = 0 ; for ( int i = 0 ; i < v . size ( ) ; i ++ ) for ( int j = i + 1 ; j < v . size ( ) ; j ++ ) if ( isPanDigital ( v [ i ] + v [ j ] ) ) pairs ++ ; return pairs ; } int main ( ) { vector < string > v = { "123567" , "098234" , "14765" , "19804" } ; cout << countPandigitalPairs ( v ) << endl ; return 0 ; }
Number of pairs with Pandigital Concatenation | C ++ program to count PanDigital pairs ; Stores digits present in string v [ i ] atleast once . We use a set as we only need digits which exist only once ( irrespective of reputation ) ; Calculate the mask by considering all digits existing atleast once ; Increment the frequency of this mask ; Returns number of pairs of strings resulting in Pandigital Concatenations ; All possible strings lie between 1 and 1023 so we iterate over every possible mask ; if the concatenation results in mask of Pandigital Concatenation , calculate all pairs formed with Masks i and j ; since every pair is considers twice , we get rid of half of these ; Find frequencies of all masks in given vector of strings ; Return all possiblg concatenations . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int pandigitalMask = ( ( 1 << 10 ) - 1 ) ; void computeMaskFrequencies ( vector < string > v , map < int , int > & freq ) { for ( int i = 0 ; i < v . size ( ) ; i ++ ) { int mask = 0 ; unordered_set < int > digits ; for ( int j = 0 ; j < v [ i ] . size ( ) ; j ++ ) digits . insert ( v [ i ] [ j ] - '0' ) ; for ( auto it = digits . begin ( ) ; it != digits . end ( ) ; it ++ ) { int digit = ( * it ) ; mask += ( 1 << digit ) ; } freq [ mask ] ++ ; } } int pandigitalConcatenations ( map < int , int > freq ) { int ans = 0 ; for ( int i = 1 ; i <= 1023 ; i ++ ) { for ( int j = 1 ; j <= 1023 ; j ++ ) { if ( ( i j ) == pandigitalMask ) { if ( i == j ) ans += ( freq [ i ] * ( freq [ i ] - 1 ) ) ; else ans += ( freq [ i ] * freq [ j ] ) ; } } } return ans / 2 ; } int countPandigitalPairs ( vector < string > v ) { map < int , int > freq ; computeMaskFrequencies ( v , freq ) ; return pandigitalConcatenations ( freq ) ; } int main ( ) { vector < string > v = { "123567" , "098234" , "14765" , "19804" } ; cout << countPandigitalPairs ( v ) << endl ; return 0 ; }
Print the arranged positions of characters to make palindrome | CPP program to print original positions of characters in a string after rearranging and forming a palindrome ; Maximum number of characters ; Insert all positions of every character in the given string . ; find the number of odd elements . Takes O ( n ) ; A palindrome cannot contain more than 1 odd characters ; Print positions in first half of palindrome ; Consider one instance odd character ; Print positions in second half of palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 256 ; void printPalindromePos ( string & str ) { vector < int > pos [ MAX ] ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) pos [ str [ i ] ] . push_back ( i + 1 ) ; int oddCount = 0 ; char oddChar ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( pos [ i ] . size ( ) % 2 != 0 ) { oddCount ++ ; oddChar = i ; } } if ( oddCount > 1 ) cout << " NO ▁ PALINDROME " ; for ( int i = 0 ; i < MAX ; i ++ ) { int mid = pos [ i ] . size ( ) / 2 ; for ( int j = 0 ; j < mid ; j ++ ) cout << pos [ i ] [ j ] << " ▁ " ; } if ( oddCount > 0 ) { int last = pos [ oddChar ] . size ( ) - 1 ; cout << pos [ oddChar ] [ last ] << " ▁ " ; pos [ oddChar ] . pop_back ( ) ; } for ( int i = MAX - 1 ; i >= 0 ; i -- ) { int count = pos [ i ] . size ( ) ; for ( int j = count / 2 ; j < count ; j ++ ) cout << pos [ i ] [ j ] << " ▁ " ; } } int main ( ) { string s = " geeksgk " ; printPalindromePos ( s ) ; return 0 ; }
Minimum changes to a string to make all substrings distinct | CPP program to count number of changes to make all substrings distinct . ; Returns minimum changes to str so that no substring is repeated . ; If length is more than maximum allowed characters , we cannot get the required string . ; Variable to store count of distinct characters ; To store counts of different characters ; Answer is , n - number of distinct char ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; int minChanges ( string & str ) { int n = str . length ( ) ; if ( n > MAX_CHAR ) return -1 ; int dist_count = 0 ; int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( count [ str [ i ] - ' a ' ] == 0 ) dist_count ++ ; count [ ( str [ i ] - ' a ' ) ] ++ ; } return ( n - dist_count ) ; } int main ( ) { string str = " aebaecedabbee " ; cout << minChanges ( str ) ; return 0 ; }
Reverse each word in a linked list node | C ++ program to reverse each word in a linked list ; Linked list Node structure ; Function to create newNode in a linked list ; reverse each node data ; iterate each node and call reverse_word for each node data ; printing linked list ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { string c ; struct Node * next ; } ; struct Node * newNode ( string c ) { Node * temp = new Node ; temp -> c = c ; temp -> next = NULL ; return temp ; } ; void reverse_word ( string & str ) { reverse ( str . begin ( ) , str . end ( ) ) ; } void reverse ( struct Node * head ) { struct Node * ptr = head ; while ( ptr != NULL ) { reverse_word ( ptr -> c ) ; ptr = ptr -> next ; } } void printList ( struct Node * head ) { while ( head != NULL ) { cout << head -> c << " ▁ " ; head = head -> next ; } } int main ( ) { Node * head = newNode ( " Geeksforgeeks " ) ; head -> next = newNode ( " a " ) ; head -> next -> next = newNode ( " computer " ) ; head -> next -> next -> next = newNode ( " science " ) ; head -> next -> next -> next -> next = newNode ( " portal " ) ; head -> next -> next -> next -> next -> next = newNode ( " for " ) ; head -> next -> next -> next -> next -> next -> next = newNode ( " geeks " ) ; cout << " List ▁ before ▁ reverse : ▁ STRNEWLINE " ; printList ( head ) ; reverse ( head ) ; cout << " List after reverse : " ; printList ( head ) ; return 0 ; }
Number of strings of length N with no palindromic sub string | CPP program to count number of strings of size m such that no substring is palindrome . ; Return the count of strings with no palindromic substring . ; Driven Program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int numofstring ( int n , int m ) { if ( n == 1 ) return m ; if ( n == 2 ) return m * ( m - 1 ) ; return m * ( m - 1 ) * pow ( m - 2 , n - 2 ) ; } int main ( ) { int n = 2 , m = 3 ; cout << numofstring ( n , m ) << endl ; return 0 ; }
Count special palindromes in a String | C ++ program to count special Palindromic substring ; Function to count special Palindromic susbstring ; store count of special Palindromic substring ; it will store the count of continues same char ; traverse string character from left to right ; store same character count ; count smiler character ; Case : 1 so total number of substring that we can generate are : K * ( K + 1 ) / 2 here K is sameCharCount ; store current same char count in sameChar [ ] array ; increment i ; Case 2 : Count all odd length Special Palindromic substring ; if current character is equal to previous one then we assign Previous same character count to current one ; case 2 : odd length ; subtract all single length substring ; driver program to test above fun
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CountSpecialPalindrome ( string str ) { int n = str . length ( ) ; int result = 0 ; int sameChar [ n ] = { 0 } ; int i = 0 ; while ( i < n ) { int sameCharCount = 1 ; int j = i + 1 ; while ( str [ i ] == str [ j ] && j < n ) sameCharCount ++ , j ++ ; result += ( sameCharCount * ( sameCharCount + 1 ) / 2 ) ; sameChar [ i ] = sameCharCount ; i = j ; } for ( int j = 1 ; j < n ; j ++ ) { if ( str [ j ] == str [ j - 1 ] ) sameChar [ j ] = sameChar [ j - 1 ] ; if ( j > 0 && j < ( n - 1 ) && ( str [ j - 1 ] == str [ j + 1 ] && str [ j ] != str [ j - 1 ] ) ) result += min ( sameChar [ j - 1 ] , sameChar [ j + 1 ] ) ; } return result - n ; } int main ( ) { string str = " abccba " ; cout << CountSpecialPalindrome ( str ) << endl ; return 0 ; }
Print Bracket Number | C ++ implementation to print the bracket number ; function to print the bracket number ; used to print the bracket number for the left bracket ; used to obtain the bracket number for the right bracket ; traverse the given expression ' exp ' ; if current character is a left bracket ; print ' left _ bnum ' , ; push ' left _ bum ' on to the stack ' right _ bnum ' ; increment ' left _ bnum ' by 1 ; else if current character is a right bracket ; print the top element of stack ' right _ bnum ' it will be the right bracket number ; pop the top element from the stack ; Driver program to test above
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printBracketNumber ( string exp , int n ) { int left_bnum = 1 ; stack < int > right_bnum ; for ( int i = 0 ; i < n ; i ++ ) { if ( exp [ i ] == ' ( ' ) { cout << left_bnum << " ▁ " ; right_bnum . push ( left_bnum ) ; left_bnum ++ ; } else if ( exp [ i ] == ' ) ' ) { cout << right_bnum . top ( ) << " ▁ " ; right_bnum . pop ( ) ; } } } int main ( ) { string exp = " ( a + ( b * c ) ) + ( d / e ) " ; int n = exp . size ( ) ; printBracketNumber ( exp , n ) ; return 0 ; }
Find if a string starts and ends with another given string | CPP program to find if a given corner string is present at corners . ; If length of corner string is more , it cannot be present at corners . ; Return true if corner string is present at both corners of given string . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isCornerPresent ( string str , string corner ) { int n = str . length ( ) ; int cl = corner . length ( ) ; if ( n < cl ) return false ; return ( str . substr ( 0 , cl ) . compare ( corner ) == 0 && str . substr ( n - cl , cl ) . compare ( corner ) == 0 ) ; } int main ( ) { string str = " geeksforgeeks " ; string corner = " geeks " ; if ( isCornerPresent ( str , corner ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find i 'th Index character in a binary string obtained after n iterations | C ++ Program to find ith character in a binary string . ; Function to store binary Representation ; Function to find ith character ; Function to change decimal to binary ; Assign s1 string in s string ; Driver Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void binary_conversion ( string & s , int m ) { while ( m ) { int tmp = m % 2 ; s += tmp + '0' ; m = m / 2 ; } reverse ( s . begin ( ) , s . end ( ) ) ; } int find_character ( int n , int m , int i ) { string s ; binary_conversion ( s , m ) ; string s1 = " " ; for ( int x = 0 ; x < n ; x ++ ) { for ( int y = 0 ; y < s . length ( ) ; y ++ ) { if ( s [ y ] == '1' ) s1 += "10" ; else s1 += "01" ; } s = s1 ; s1 = " " ; } return s [ i ] - '0' ; } int main ( ) { int m = 5 , n = 2 , i = 8 ; cout << find_character ( n , m , i ) ; return 0 ; }
Maximum segment value after putting k breakpoints in a number | CPP program to find the maximum segment value after putting k breaks . ; Function to Find Maximum Number ; Maximum segment length ; Find value of first segment of seg_len ; Find value of remaining segments using sliding window ; To find value of current segment , first remove leading digit from previous value ; Then add trailing digit ; Driver 's Function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findMaxSegment ( string & s , int k ) { int seg_len = s . length ( ) - k ; int res = 0 ; for ( int i = 0 ; i < seg_len ; i ++ ) res = res * 10 + ( s [ i ] - '0' ) ; int seg_len_pow = pow ( 10 , seg_len - 1 ) ; int curr_val = res ; for ( int i = 1 ; i <= ( s . length ( ) - seg_len ) ; i ++ ) { curr_val = curr_val - ( s [ i - 1 ] - '0' ) * seg_len_pow ; curr_val = curr_val * 10 + ( s [ i + seg_len - 1 ] - '0' ) ; res = max ( res , curr_val ) ; } return res ; } int main ( ) { string s = "8754" ; int k = 2 ; cout << " Maximum ▁ number ▁ = ▁ " << findMaxSegment ( s , k ) ; return 0 ; }
Consecutive sequenced numbers in a string | CPP Program to check whether a string contains consecutive sequential numbers or not ; function to check consecutive sequential number ; variable to store starting number ; length of the input string ; find the number till half of the string ; new string containing the starting substring of input string ; converting starting substring into number ; backing up the starting number in start ; while loop until the new_string is smaller than input string ; next number ; concatenate the next number ; check if new string becomes equal to input string ; if string doesn 't contains consecutive numbers ; Driver 's Code
#include <iostream> NEW_LINE using namespace std ; int isConsecutive ( string str ) { int start ; int length = str . size ( ) ; for ( int i = 0 ; i < length / 2 ; i ++ ) { string new_str = str . substr ( 0 , i + 1 ) ; int num = atoi ( new_str . c_str ( ) ) ; start = num ; while ( new_str . size ( ) < length ) { num ++ ; new_str = new_str + to_string ( num ) ; } if ( new_str == str ) return start ; } return -1 ; } int main ( ) { string str = "99100" ; cout << " String : ▁ " << str << endl ; int start = isConsecutive ( str ) ; if ( start != -1 ) cout << " Yes ▁ STRNEWLINE " << start << endl ; else cout << " No " << endl ; string str1 = "121315" ; cout << " String : " start = isConsecutive ( str1 ) ; if ( start != -1 ) cout << " Yes ▁ STRNEWLINE " << start << endl ; else cout << " No " << endl ; return 0 ; }
Converting one string to other using append and delete last operations | CPP Program to convert str1 to str2 in exactly k operations ; Returns true if it is possible to convert str1 to str2 using k operations . ; Case A ( i ) ; finding common length of both string ; Case A ( ii ) - ; Case B - ; driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isConvertible ( string str1 , string str2 , int k ) { if ( ( str1 . length ( ) + str2 . length ( ) ) < k ) return true ; int commonLength = 0 ; for ( int i = 0 ; i < min ( str1 . length ( ) , str2 . length ( ) ) ; i ++ ) { if ( str1 [ i ] == str2 [ i ] ) commonLength ++ ; else break ; } if ( ( k - str1 . length ( ) - str2 . length ( ) + 2 * commonLength ) % 2 == 0 ) return true ; return false ; } int main ( ) { string str1 = " geek " , str2 = " geek " ; int k = 7 ; if ( isConvertible ( str1 , str2 , k ) ) cout << " Yes " ; else cout << " No " ; str1 = " geeks " , str2 = " geek " ; k = 5 ; cout << endl ; if ( isConvertible ( str1 , str2 , k ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Maximum distinct lowercase alphabets between two uppercase | CPP Program to find maximum lowercase alphabets present between two uppercase alphabets ; Function which computes the maximum number of distinct lowercase alphabets between two uppercase alphabets ; Ignoring lowercase characters in the beginning . ; We start from next of first capital letter and traverse through remaining character . ; If character is in uppercase , ; Count all distinct lower case characters ; Update maximum count ; Reset count array ; If character is in lowercase ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX_CHAR 26 NEW_LINE int maxLower ( string str ) { int n = str . length ( ) ; int i = 0 ; for ( ; i < n ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { i ++ ; break ; } } int maxCount = 0 ; int count [ MAX_CHAR ] = { 0 } ; for ( ; i < n ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { int currCount = 0 ; for ( int j = 0 ; j < MAX_CHAR ; j ++ ) if ( count [ j ] > 0 ) currCount ++ ; maxCount = max ( maxCount , currCount ) ; memset ( count , 0 , sizeof ( count ) ) ; } if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) count [ str [ i ] - ' a ' ] ++ ; } return maxCount ; } int main ( ) { string str = " zACaAbbaazzC " ; cout << maxLower ( str ) ; return 0 ; }
Maximum distinct lowercase alphabets between two uppercase | CPP Program to find maximum lowercase alphabets present between two uppercase alphabets ; Function which computes the maximum number of distinct lowercase alphabets between two uppercase alphabets ; Ignoring lowercase characters in the beginning . ; We start from next of first capital letter and traverse through remaining character . ; If character is in uppercase , ; Update maximum count if lowercase character before this is more . ; clear the set ; If character is in lowercase ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLower ( string str ) { int n = str . length ( ) ; int i = 0 ; for ( ; i < n ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { i ++ ; break ; } } int maxCount = 0 ; unordered_set < int > s ; for ( ; i < n ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) { maxCount = max ( maxCount , ( int ) s . size ( ) ) ; s . clear ( ) ; } if ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) s . insert ( str [ i ] ) ; } return maxCount ; } int main ( ) { string str = " zACaAbbaazzC " ; cout << maxLower ( str ) ; return 0 ; }
First uppercase letter in a string ( Iterative and Recursive ) | C ++ program to find the first uppercase letter using linear search ; Function to find string which has first character of each word . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char first ( string str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( isupper ( str [ i ] ) ) return str [ i ] ; return 0 ; } int main ( ) { string str = " geeksforGeeKS " ; char res = first ( str ) ; if ( res == 0 ) cout << " No ▁ uppercase ▁ letter " ; else cout << res << " STRNEWLINE " ; return 0 ; }
Count maximum | C ++ implementation for counting maximum length palindromes ; factorial of a number ; function to count maximum length palindromes . ; Count number of occurrence of a charterer in the string ; int k = 0 ; Count of singles int num = 0 ; numerator of result int den = 1 ; denominator of result ; if frequency is even fi = ci / 2 ; if frequency is odd fi = ci - 1 / 2. ; sum of all frequencies ; product of factorial of every frequency ; if all character are unique so there will be no pallindrome , so if num != 0 then only we are finding the factorial ; k are the single elements that can be placed in middle ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int ans = 1 ; for ( int i = 1 ; i <= n ; i ++ ) ans = ans * i ; return ( ans ) ; } int numberOfPossiblePallindrome ( string str , int n ) { unordered_map < char , int > mp ; for ( int i = 0 ; i < n ; i ++ ) mp [ str [ i ] ] ++ ; int fi ; for ( auto it = mp . begin ( ) ; it != mp . end ( ) ; ++ it ) { if ( it -> second % 2 == 0 ) fi = it -> second / 2 ; else { fi = ( it -> second - 1 ) / 2 ; k ++ ; } num = num + fi ; den = den * fact ( fi ) ; } if ( num != 0 ) num = fact ( num ) ; int ans = num / den ; if ( k != 0 ) { ans = ans * k ; } return ( ans ) ; } int main ( ) { char str [ ] = " ababab " ; int n = strlen ( str ) ; cout << numberOfPossiblePallindrome ( str , n ) ; return 0 ; }
Counting even decimal value substrings in a binary string | C ++ code to generate all possible substring and count even decimal value substring . ; generate all substring in arr [ 0. . n - 1 ] ; store the count ; Pick starting point ; Pick ending point ; substring between current starting and ending points ; increment power of 2 by one ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int evenDecimalValue ( string str , int n ) { int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { int decimalValue = 0 ; int powerOf2 = 1 ; for ( int k = i ; k <= j ; k ++ ) { decimalValue += ( ( str [ k ] - '0' ) * powerOf2 ) ; powerOf2 *= 2 ; } if ( decimalValue % 2 == 0 ) result ++ ; } } return result ; } int main ( ) { string str = "10010" ; int n = 5 ; cout << evenDecimalValue ( str , n ) << endl ; return 0 ; }
Create a new string by alternately combining the characters of two halves of the string in reverse | C ++ program for creating a string by alternately combining the characters of two halves in reverse ; Function performing calculations ; Calculating the two halves of string s as first and second . The final string p ; It joins the characters to final string in reverse order ; It joins the characters to final string in reverse order ; Driver code ; Calling function
#include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( string s ) { int l = s . length ( ) ; int x = l / 2 ; int y = l ; string p = " " ; while ( x > 0 && y > l / 2 ) { p += s [ x - 1 ] ; x -- ; p += s [ y - 1 ] ; y -- ; } if ( y > l / 2 ) { p += s [ y - 1 ] ; y -- ; } cout << p ; } int main ( ) { string s = " sunshine " ; solve ( s ) ; return 0 ; }
Make a lexicographically smallest palindrome with minimal changes | CPP code for changing a string into lexicographically smallest pallindromic string ; Function to create a palindrome ; Count the occurrences of every character in the string ; Create a string of characters with odd occurrences ; Change the created string upto middle element and update count to make sure that only one odd character exists . ; decrease the count of character updated ; Create three strings to make first half second half and middle one . ; characters with even occurrences ; fill the first half . ; character with odd occurrence ; fill the first half with half of occurrence except one ; For middle element ; create the second half by reversing the first half . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Palindrome ( string s , int n ) { unordered_map < char , int > cnt ; string R = " " ; for ( int i = 0 ; i < n ; i ++ ) { char a = s [ i ] ; cnt [ a ] ++ ; } for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( cnt [ i ] % 2 != 0 ) R += i ; } int l = R . length ( ) ; int j = 0 ; for ( int i = l - 1 ; i >= l / 2 ; i -- ) { cnt [ R [ i ] ] -- ; R [ i ] = R [ j ] ; cnt [ R [ j ] ] ++ ; j ++ ; } string first , middle , second ; for ( char i = ' a ' ; i <= ' z ' ; i ++ ) { if ( cnt [ i ] != 0 ) { if ( cnt [ i ] % 2 == 0 ) { int j = 0 ; while ( j < cnt [ i ] / 2 ) { first += i ; j ++ ; } } else { int j = 0 ; while ( j < ( cnt [ i ] - 1 ) / 2 ) { first += i ; j ++ ; } middle += i ; } } } second = first ; reverse ( second . begin ( ) , second . end ( ) ) ; string resultant = first + middle + second ; cout << resultant << endl ; } int main ( ) { string S = " geeksforgeeks " ; int n = S . length ( ) ; Palindrome ( S , n ) ; return 0 ; }
Program for length of a string using recursion | CPP program to calculate length of a string using recursion ; Function to calculate length ; if we reach at the end of the string ; Driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; int recLen ( char * str ) { if ( * str == ' \0' ) return 0 ; else return 1 + recLen ( str + 1 ) ; } int main ( ) { char str [ ] = " GeeksforGeeks " ; cout << recLen ( str ) ; return 0 ; }
Count consonants in a string ( Iterative and recursive methods ) | Iterative CPP program to count total number of consonants ; Function to check for consonant ; To handle lower case ; To check is character is Consonant ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isConsonant ( char ch ) { ch = toupper ( ch ) ; return ! ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) && ch >= 65 && ch <= 90 ; } int totalConsonants ( string str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( isConsonant ( str [ i ] ) ) ++ count ; return count ; } int main ( ) { string str = " abc ▁ de " ; cout << totalConsonants ( str ) ; return 0 ; }
Count consonants in a string ( Iterative and recursive methods ) | Recursive CPP program to count total number of consonants ; Function to check for consonant ; To handle lower case ; to count total number of consonants from 0 to n - 1 ; Driver code
#include <iostream> NEW_LINE using namespace std ; bool isConsonant ( char ch ) { ch = toupper ( ch ) ; return ! ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) && ch >= 65 && ch <= 90 ; } int totalConsonants ( string str , int n ) { if ( n == 1 ) return isConsonant ( str [ 0 ] ) ; return totalConsonants ( str , n - 1 ) + isConsonant ( str [ n - 1 ] ) ; } int main ( ) { string str = " abc ▁ de " ; cout << totalConsonants ( str , str . length ( ) ) ; return 0 ; }