text
stringlengths 17
4.49k
| code
stringlengths 49
5.46k
|
---|---|
Check if actual binary representation of a number is palindrome | C ++ implementation to check whether binary representation of a number is palindrome or not ; function to reverse bits of a number ; traversing bits of ' n ' from the right ; bitwise left shift ' rev ' by 1 ; if current bit is '1' ; bitwise right shift ' n ' by 1 ; required number ; function to check whether binary representation of a number is palindrome or not ; get the number by reversing bits in the binary representation of ' n ' ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned int reverseBits ( unsigned int n ) { unsigned int rev = 0 ; while ( n > 0 ) { rev <<= 1 ; if ( n & 1 == 1 ) rev ^= 1 ; n >>= 1 ; } return rev ; } bool isPalindrome ( unsigned int n ) { unsigned int rev = reverseBits ( n ) ; return ( n == rev ) ; } int main ( ) { unsigned int n = 9 ; if ( isPalindrome ( n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Reduce Hamming distance by swapping two characters | C ++ code to decrease hamming distance using swap . ; Function to return the swapped indexes to get minimum hamming distance . ; Find the initial hamming distance ; Case - I : To decrease distance by two ; ASCII values of present character . ; If two same letters appear in different positions print their indexes ; Store the index of letters which is in wrong position ; Case : II ; If misplaced letter is found , print its original index and its new index ; Store the index of letters in wrong position ; Case - III ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE void Swap ( string s , string t , int n ) { int dp [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof dp ) ; int tot = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( s [ i ] != t [ i ] ) tot ++ ; for ( int i = 0 ; i < n ; i ++ ) { int a = s [ i ] - ' a ' ; int b = t [ i ] - ' a ' ; if ( a == b ) continue ; if ( dp [ a ] [ b ] != -1 ) { cout << i + 1 << " β " << dp [ a ] [ b ] + 1 << endl ; return ; } dp [ b ] [ a ] = i ; } int A [ MAX ] , B [ MAX ] ; memset ( A , -1 , sizeof A ) ; memset ( B , -1 , sizeof B ) ; for ( int i = 0 ; i < n ; i ++ ) { int a = s [ i ] - ' a ' ; int b = t [ i ] - ' a ' ; if ( a == b ) continue ; if ( A [ b ] != -1 ) { cout << i + 1 << " β " << A [ b ] + 1 << endl ; return ; } if ( B [ a ] != -1 ) { cout << i + 1 << " β " << B [ a ] + 1 << endl ; return ; } A [ a ] = i ; B [ b ] = i ; } cout << -1 << endl ; } int main ( ) { string S = " permanent " ; string T = " pergament " ; int n = S . length ( ) ; if ( S == " " T == " " ) cout << " Required β string β is β empty . " ; else Swap ( S , T , n ) ; return 0 ; } |
Convert string X to an anagram of string Y with minimum replacements | C ++ program to convert string X to string Y which minimum number of changes . ; Function that converts string X into lexicographically smallest anagram of string Y with minimal changes ; Counting frequency of characters in each string . ; We maintain two more counter arrays ctrx [ ] and ctry [ ] Ctrx [ ] maintains the count of extra elements present in string X than string Y Ctry [ ] maintains the count of characters missing from string X which should be present in string Y . ; This means that we cannot edit the current character as it 's frequency in string X is equal to or less than the frequency in string Y. Thus, we go to the next position ; Here , we try to find that character , which has more frequency in string Y and less in string X . We try to find this character in lexicographical order so that we get lexicographically smaller string ; This portion deals with the lexicographical property . Now , we put a character in string X when either this character has smaller value than the character present there right now or if this is the last position for it to exchange , else we fix the character already present here in this position . ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE void printAnagramAndChanges ( string X , string Y ) { int countx [ MAX ] = { 0 } , county [ MAX ] = { 0 } , ctrx [ MAX ] = { 0 } , ctry [ MAX ] = { 0 } ; int change = 0 ; int l = X . length ( ) ; for ( int i = 0 ; i < l ; i ++ ) { countx [ X [ i ] - ' A ' ] ++ ; county [ Y [ i ] - ' A ' ] ++ ; } for ( int i = 0 ; i < MAX ; i ++ ) { if ( countx [ i ] > county [ i ] ) ctrx [ i ] += ( countx [ i ] - county [ i ] ) ; else if ( countx [ i ] < county [ i ] ) ctry [ i ] += ( county [ i ] - countx [ i ] ) ; change += abs ( county [ i ] - countx [ i ] ) ; } for ( int i = 0 ; i < l ; i ++ ) { if ( ctrx [ X [ i ] - ' A ' ] == 0 ) continue ; int j ; for ( j = 0 ; j < MAX ; j ++ ) if ( ( ctry [ j ] ) > 0 ) break ; if ( countx [ X [ i ] - ' A ' ] == ctrx [ X [ i ] - ' A ' ] X [ i ] - ' A ' > j ) { countx [ X [ i ] - ' A ' ] -- ; ctrx [ X [ i ] - ' A ' ] -- ; ctry [ j ] -- ; X [ i ] = ' A ' + j ; } else countx [ X [ i ] - ' A ' ] -- ; } cout << " Anagram β : β " << X << endl ; cout << " Number β of β changes β made β : β " << change / 2 ; } int main ( ) { string x = " CDBABC " , y = " ADCABD " ; printAnagramAndChanges ( x , y ) ; return 0 ; } |
Count number of equal pairs in a string | CPP program to count the number of pairs ; Function to count the number of equal pairs ; Hash table ; Traverse the string and count occurrence ; Stores the answer ; Traverse and check the occurrence of every character ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 256 NEW_LINE int countPairs ( string s ) { int cnt [ MAX ] = { 0 } ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) cnt [ s [ i ] ] ++ ; int ans = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) ans += cnt [ i ] * cnt [ i ] ; return ans ; } int main ( ) { string s = " geeksforgeeks " ; cout << countPairs ( s ) ; return 0 ; } |
Find a string in lexicographic order which is in between given two strings | CPP program to find the string in lexicographic order which is in between given two strings ; Function to find the lexicographically next string ; Iterate from last character ; If not ' z ' , increase by one ; if ' z ' , change it to ' a ' ; Driver Code ; If not equal , print the resultant string | #include <bits/stdc++.h> NEW_LINE using namespace std ; string lexNext ( string s , int n ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] != ' z ' ) { s [ i ] ++ ; return s ; } s [ i ] = ' a ' ; } } int main ( ) { string S = " abcdeg " , T = " abcfgh " ; int n = S . length ( ) ; string res = lexNext ( S , n ) ; if ( res != T ) cout << res << endl ; else cout << " - 1" << endl ; return 0 ; } |
Find the arrangement of queue at given time | CPP program to find the arrangement of queue at time = t ; prints the arrangement at time = t ; Checking the entire queue for every moment from time = 1 to time = t . ; If current index contains ' B ' and next index contains ' G ' then swap ; Driver function for the program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void solve ( int n , int t , string s ) { for ( int i = 0 ; i < t ; i ++ ) for ( int j = 0 ; j < n - 1 ; j ++ ) if ( s [ j ] == ' B ' && s [ j + 1 ] == ' G ' ) { char temp = s [ j ] ; s [ j ] = s [ j + 1 ] ; s [ j + 1 ] = temp ; j ++ ; } cout << s ; } int main ( ) { int n = 6 , t = 2 ; string s = " BBGBBG " ; solve ( n , t , s ) ; return 0 ; } |
Add two numbers represented by two arrays | CPP program to sum two numbers represented two arrays . ; Return sum of two number represented by the arrays . Size of a [ ] is greater than b [ ] . It is made sure be the wrapper function ; array to store sum . ; Until we reach beginning of array . we are comparing only for second array because we have already compare the size of array in wrapper function . ; find sum of corresponding element of both arrays . ; Finding carry for next sum . ; If second array size is less the first array size . ; Add carry to first array elements . ; If there is carry on adding 0 index elements . append 1 to total sum . ; Converting array into number . ; Wrapper Function ; Making first array which have greater number of element ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int calSumUtil ( int a [ ] , int b [ ] , int n , int m ) { int sum [ n ] ; int i = n - 1 , j = m - 1 , k = n - 1 ; int carry = 0 , s = 0 ; while ( j >= 0 ) { s = a [ i ] + b [ j ] + carry ; sum [ k ] = ( s % 10 ) ; carry = s / 10 ; k -- ; i -- ; j -- ; } while ( i >= 0 ) { s = a [ i ] + carry ; sum [ k ] = ( s % 10 ) ; carry = s / 10 ; i -- ; k -- ; } int ans = 0 ; if ( carry ) ans = 10 ; for ( int i = 0 ; i <= n - 1 ; i ++ ) { ans += sum [ i ] ; ans *= 10 ; } return ans / 10 ; } int calSum ( int a [ ] , int b [ ] , int n , int m ) { if ( n >= m ) return calSumUtil ( a , b , n , m ) ; else return calSumUtil ( b , a , m , n ) ; } int main ( ) { int a [ ] = { 9 , 3 , 9 } ; int b [ ] = { 6 , 1 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int m = sizeof ( b ) / sizeof ( b [ 0 ] ) ; cout << calSum ( a , b , n , m ) << endl ; return 0 ; } |
Longest Common Anagram Subsequence | C ++ implementation to find the length of the longest common anagram subsequence ; function to find the length of the longest common anagram subsequence ; hash tables for storing frequencies of each character ; calculate frequency of each character of ' str1 [ ] ' ; calculate frequency of each character of ' str2 [ ] ' ; for each character add its minimum frequency out of the two strings in ' len ' ; required length ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; #define SIZE 26 NEW_LINE int longCommomAnagramSubseq ( char str1 [ ] , char str2 [ ] , int n1 , int n2 ) { int freq1 [ SIZE ] , freq2 [ SIZE ] ; memset ( freq1 , 0 , sizeof ( freq1 ) ) ; memset ( freq2 , 0 , sizeof ( freq2 ) ) ; int len = 0 ; for ( int i = 0 ; i < n1 ; i ++ ) freq1 [ str1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n2 ; i ++ ) freq2 [ str2 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < SIZE ; i ++ ) len += min ( freq1 [ i ] , freq2 [ i ] ) ; return len ; } int main ( ) { char str1 [ ] = " abdacp " ; char str2 [ ] = " ckamb " ; int n1 = strlen ( str1 ) ; int n2 = strlen ( str2 ) ; cout << " Length β = β " << longCommomAnagramSubseq ( str1 , str2 , n1 , n2 ) ; return 0 ; } |
Panalphabetic window in a string | CPP Program to check whether given string contain panalphabetic window or not ; Return if given string contain panalphabetic window . ; traversing the string ; if character of string is equal to ch , increment ch . ; if all characters are found , return true . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPanalphabeticWindow ( char s [ ] , int n ) { char ch = ' a ' ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ch ) ch ++ ; if ( ch == ' z ' + 1 ) return true ; } return false ; } int main ( ) { char s [ ] = " abujm β zvcd β acefc β deghf β gijkle " " β m β n β o β p β pafqrstuvwxyzfap " ; int n = strlen ( s ) ; ( isPanalphabeticWindow ( s , n ) ) ? ( cout << " YES " ) : ( cout << " NO " ) ; return 0 ; } |
Program to print characters present at prime indexes in a given string | C ++ Program to print Characters at Prime index in a given String ; Corner case ; Check from 2 to n - 1 ; Function to print character at prime index ; Loop to check if index prime or not ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i < n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } void prime_index ( string input ) { int n = input . length ( ) ; for ( int i = 2 ; i <= n ; i ++ ) if ( isPrime ( i ) ) cout << input [ i - 1 ] ; } int main ( ) { string input = " GeeksforGeeks " ; prime_index ( input ) ; return 0 ; } |
Check whether a given string is Heterogram or not | C ++ Program to check whether the given string is Heterogram or not . ; traversing the string . ; ignore the space ; if already encountered ; else return false . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isHeterogram ( char s [ ] , int n ) { int hash [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] != ' β ' ) { if ( hash [ s [ i ] - ' a ' ] == 0 ) hash [ s [ i ] - ' a ' ] = 1 ; else return false ; } } return true ; } int main ( ) { char s [ ] = " the β big β dwarf β only β jumps " ; int n = strlen ( s ) ; ( isHeterogram ( s , n ) ) ? ( cout << " YES " ) : ( cout << " NO " ) ; return 0 ; } |
Print given sentence into its equivalent ASCII form | C ++ implementation for converting a string into it 's ASCII equivalent sentence ; Function to compute the ASCII value of each character one by one ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void ASCIISentence ( std :: string str ) { int l = str . length ( ) ; int convert ; for ( int i = 0 ; i < l ; i ++ ) { convert = str [ i ] - NULL ; cout << convert ; } } int main ( ) { string str = " GeeksforGeeks " ; cout << " ASCII β Sentence : " << std :: endl ; ASCIISentence ( str ) ; return 0 ; } |
Snake case of a given sentence | CPP program to convert given sentence / to snake case ; Function to replace spaces and convert into snake case ; Converting space to underscor ; If not space , convert into lower character ; Driver program ; Calling function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void convert ( string str ) { int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . at ( i ) == ' β ' ) str . at ( i ) = ' _ ' ; else str . at ( i ) = tolower ( str . at ( i ) ) ; } cout << str ; } int main ( ) { string str = " I β got β intern β at β geeksforgeeks " ; convert ( str ) ; return 0 ; } |
Find the size of largest subset of anagram words | C ++ Program to find the size of largest subset of anagram ; Utility function to find size of largest subset of anagram ; sort the string ; Increment the count of string ; Compute the maximum size of string ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int largestAnagramSet ( string arr [ ] , int n ) { int maxSize = 0 ; unordered_map < string , int > count ; for ( int i = 0 ; i < n ; ++ i ) { sort ( arr [ i ] . begin ( ) , arr [ i ] . end ( ) ) ; count [ arr [ i ] ] += 1 ; maxSize = max ( maxSize , count [ arr [ i ] ] ) ; } return maxSize ; } int main ( ) { string arr [ ] = { " ant " , " magenta " , " magnate " , " tan " , " gnamate " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << largestAnagramSet ( arr , n ) << " STRNEWLINE " ; string arr1 [ ] = { " cars " , " bikes " , " arcs " , " steer " } ; n = sizeof ( arr1 ) / sizeof ( arr [ 0 ] ) ; cout << largestAnagramSet ( arr1 , n ) ; return 0 ; } |
Program to count vowels , consonant , digits and special characters in string . | Program to count vowels , consonant , digits and special character in a given string . ; Function to count number of vowels , consonant , digitsand special character in a string . ; Declare the variable vowels , consonant , digit and special characters ; str . length ( ) function to count number of character in given string . ; To handle upper case letters ; Driver function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; void countCharacterType ( string str ) { int vowels = 0 , consonant = 0 , specialChar = 0 , digit = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { char ch = str [ i ] ; if ( ( ch >= ' a ' && ch <= ' z ' ) || ( ch >= ' A ' && ch <= ' Z ' ) ) { ch = tolower ( ch ) ; if ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) vowels ++ ; else consonant ++ ; } else if ( ch >= '0' && ch <= '9' ) digit ++ ; else specialChar ++ ; } cout << " Vowels : β " << vowels << endl ; cout << " Consonant : β " << consonant << endl ; cout << " Digit : β " << digit << endl ; cout << " Special β Character : β " << specialChar << endl ; } int main ( ) { string str = " geeks β for β geeks121" ; countCharacterType ( str ) ; return 0 ; } |
Next word that does not contain a palindrome and has characters from first k | CPP program to find lexicographically next word which contains first K letters of the English alphabet and does not contain a palindrome as it 's substring of length more than one. ; function to return lexicographically next word ; we made m as m + 97 that means our required string contains not more than m + 97 ( as per ASCII value ) in it . ; increment last alphabet to make next lexicographically next word . ; if i - th alphabet not in first k letters then make it as " a " and then increase ( i - 1 ) th letter ; to check whether formed string palindrome or not . ; increment i . ; if i less than or equals to one that means we not formed such word . ; Driver code for above function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; void findNextWord ( string s , int m ) { m += 97 ; int n = s . length ( ) ; int i = s . length ( ) - 1 ; s [ i ] ++ ; while ( i >= 0 && i <= n - 1 ) { if ( s [ i ] >= m ) { s [ i ] = ' a ' ; s [ -- i ] ++ ; } else if ( s [ i ] == s [ i - 1 ] s [ i ] == s [ i - 2 ] ) s [ i ] ++ ; else i ++ ; } if ( i <= -1 ) cout << " - 1" ; else cout << s ; } int main ( ) { string str = " abcd " ; int k = 4 ; findNextWord ( str , k ) ; return 0 ; } |
Program to implement ASCII lookup table | C ++ implementation of ASCII lookup table ; Function to convert decimal value to equivalent octal value ; Function to convert decimal value to equivalent hexadecimal value ; Function to convert decimal value to equivalent HTML value ; ASCII lookup table ; Implicit typecasting converts the character into it 's equivalent ASCII ; Driver function | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int Octal ( int decimal ) { int octal = 0 ; string temp = " " ; while ( decimal > 0 ) { int remainder = decimal % 8 ; temp = to_string ( remainder ) + temp ; decimal /= 8 ; } for ( int i = 0 ; i < temp . length ( ) ; i ++ ) octal = ( octal * 10 ) + ( temp [ i ] - '0' ) ; return octal ; } string Hexadecimal ( int decimal ) { string hex = " " ; while ( decimal > 0 ) { int remainder = decimal % 16 ; if ( remainder >= 0 && remainder <= 9 ) hex = to_string ( remainder ) + hex ; else hex = ( char ) ( ' A ' + remainder % 10 ) + hex ; decimal /= 16 ; } return hex ; } string HTML ( int decimal ) { string html = to_string ( decimal ) ; html = " & # " + html + " ; " ; return html ; } void ASCIIlookuptable ( char ch ) { int decimal = ch ; cout << " Octal β value : β " << Octal ( decimal ) << endl ; cout << " Decimal β value : β " << decimal << endl ; cout << " Hexadecimal β value : β " << Hexadecimal ( decimal ) << endl ; cout << " HTML β value : β " << HTML ( decimal ) ; } int main ( ) { char ch = ' @ ' ; ASCIIlookuptable ( ch ) ; return 0 ; } |
Replace a character c1 with c2 and c2 with c1 in a string S | CPP program to replace c1 with c2 and c2 with c1 ; loop to traverse in the string ; check for c1 and replace ; check for c2 and replace ; Driver code to check the above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string replace ( string s , char c1 , char c2 ) { int l = s . length ( ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( s [ i ] == c1 ) s [ i ] = c2 ; else if ( s [ i ] == c2 ) s [ i ] = c1 ; } return s ; } int main ( ) { string s = " grrksfoegrrks " ; char c1 = ' e ' , c2 = ' r ' ; cout << replace ( s , c1 , c2 ) ; return 0 ; } |
Fibonacci Word | program for nth Fibonacci word ; Returns n - th Fibonacci word ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string fibWord ( int n ) { string Sn_1 = "0" ; string Sn = "01" ; string tmp ; for ( int i = 2 ; i <= n ; i ++ ) { tmp = Sn ; Sn += Sn_1 ; Sn_1 = tmp ; } return Sn ; } int main ( ) { int n = 6 ; cout << fibWord ( n ) ; return 0 ; } |
Decimal to octal conversion with minimum use of arithmetic operators | C ++ implementation of decimal to octal conversion with minimum use of arithmetic operators ; function for decimal to binary conversion without using arithmetic operators ; to store the binary equivalent of decimal ; to get the last binary digit of the number ' n ' and accumulate it at the beginning of ' bin ' ; right shift ' n ' by 1 ; required binary number ; Function to find octal equivalent of binary ; add min 0 's in the beginning to make string length divisible by 3 ; create map between binary and its equivalent octal code ; one by one extract from left , substring of size 3 and add its octal code ; required octal number ; function to find octal equivalent of decimal ; convert decimal to binary ; convert binary to octal required octal equivalent of decimal ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; string decToBin ( int n ) { if ( n == 0 ) return "0" ; string bin = " " ; while ( n > 0 ) { bin = ( ( n & 1 ) == 0 ? '0' : '1' ) + bin ; n >>= 1 ; } return bin ; } string convertBinToOct ( string bin ) { int l = bin . size ( ) ; for ( int i = 1 ; i <= ( 3 - l % 3 ) % 3 ; i ++ ) bin = '0' + bin ; unordered_map < string , char > bin_oct_map ; bin_oct_map [ "000" ] = '0' ; bin_oct_map [ "001" ] = '1' ; bin_oct_map [ "010" ] = '2' ; bin_oct_map [ "011" ] = '3' ; bin_oct_map [ "100" ] = '4' ; bin_oct_map [ "101" ] = '5' ; bin_oct_map [ "110" ] = '6' ; bin_oct_map [ "111" ] = '7' ; int i = 0 ; string octal = " " ; while ( 1 ) { octal += bin_oct_map [ bin . substr ( i , 3 ) ] ; i += 3 ; if ( i == bin . size ( ) ) break ; } return octal ; } string decToOctal ( int n ) { string bin = decToBin ( n ) ; return convertBinToOct ( bin ) ; } int main ( ) { int n = 151 ; cout << decToOctal ( n ) ; return 0 ; } |
Split the string into substrings using delimiter | C ++ implementation to split string into substrings on the basis of delimiter ; function to split string into substrings on the basis of delimiter and return the substrings after split ; to count the number of split strings ; adding delimiter character at the end of ' str ' ; length of ' str ' ; traversing ' str ' from left to right ; if str [ i ] is not equal to the delimiter character then accumulate it to ' word ' ; if ' word ' is not an empty string , then add this ' word ' to the array ' substr _ list [ ] ' ; reset ' word ' ; return the splitted strings ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; vector < string > splitStrings ( string str , char dl ) { string word = " " ; int num = 0 ; str = str + dl ; int l = str . size ( ) ; vector < string > substr_list ; for ( int i = 0 ; i < l ; i ++ ) { if ( str [ i ] != dl ) word = word + str [ i ] ; else { if ( ( int ) word . size ( ) != 0 ) substr_list . push_back ( word ) ; word = " " ; } } return substr_list ; } int main ( ) { string str = " geeks ; for ; geeks " ; char dl = ' ; ' ; vector < string > res = splitStrings ( str , dl ) ; for ( auto x : res ) cout << x << endl ; return 0 ; } |
Construct lexicographically smallest palindrome | CPP for constructing smallest palindrome ; function for printing palindrome ; iterate till i < j ; continue if str [ i ] == str [ j ] ; update str [ i ] = str [ j ] = ' a ' if both are ' * ' ; update str [ i ] = str [ j ] if only str [ i ] = ' * ' ; update str [ j ] = str [ i ] if only str [ j ] = ' * ' ; else print not possible and return ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string constructPalin ( string str , int len ) { int i = 0 , j = len - 1 ; for ( ; i < j ; i ++ , j -- ) { if ( str [ i ] == str [ j ] && str [ i ] != ' * ' ) continue ; else if ( str [ i ] == str [ j ] && str [ i ] == ' * ' ) { str [ i ] = ' a ' ; str [ j ] = ' a ' ; continue ; } else if ( str [ i ] == ' * ' ) { str [ i ] = str [ j ] ; continue ; } else if ( str [ j ] == ' * ' ) { str [ j ] = str [ i ] ; continue ; } cout << " Not β Possible " ; return " " ; } return str ; } int main ( ) { string str = " bca * xc * * b " ; int len = str . size ( ) ; cout << constructPalin ( str , len ) ; return 0 ; } |
Change string to a new character set | CPP program to change the sentence with virtual dictionary ; Converts str to given character set ; hashing for new character set ; conversion of new character set ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void conversion ( char charSet [ ] , string & str ) { int n = str . length ( ) ; char hashChar [ 26 ] ; for ( int i = 0 ; i < 27 ; i ++ ) hashChar [ charSet [ i ] - ' a ' ] = ' a ' + i ; for ( int i = 0 ; i < n ; i ++ ) str [ i ] = hashChar [ str [ i ] - ' a ' ] ; } int main ( ) { char charSet [ 27 ] = " qwertyuiopasdfghjklzxcvbnm " ; string str = " egrt " ; conversion ( charSet , str ) ; cout << str ; return 0 ; } |
Different substrings in a string that start and end with given strings | Cpp program to find number of different sub strings ; function to return number of different sub - strings ; initially our answer is zero . ; find the length of given strings ; currently make array and initially put zero . ; find occurrence of " a " and " b " in string " s " ; We use a hash to make sure that same substring is not counted twice . ; go through all the positions to find occurrence of " a " first . ; if we found occurrence of " a " . ; then go through all the positions to find occurrence of " b " . ; if we do found " b " at index j then add it to already existed substring . ; if we found occurrence of " b " . ; now add string " b " to already existed substring . ; If current substring is not included already . ; put any non negative integer to make this string as already existed . ; make substring null . ; return answer . ; Driver program for above function . | #include <bits/stdc++.h> NEW_LINE using namespace std ; int numberOfDifferentSubstrings ( string s , string a , string b ) { int ans = 0 ; int ls = s . size ( ) , la = a . size ( ) , lb = b . size ( ) ; int x [ ls ] = { 0 } , y [ ls ] = { 0 } ; for ( int i = 0 ; i < ls ; i ++ ) { if ( s . substr ( i , la ) == a ) x [ i ] = 1 ; if ( s . substr ( i , lb ) == b ) y [ i ] = 1 ; } unordered_set < string > hash ; string curr_substr = " " ; for ( int i = 0 ; i < ls ; i ++ ) { if ( x [ i ] ) { for ( int j = i ; j < ls ; j ++ ) { if ( ! y [ j ] ) curr_substr += s [ j ] ; if ( y [ j ] ) { curr_substr += s . substr ( j , lb ) ; if ( hash . find ( curr_substr ) == hash . end ( ) ) ans ++ ; hash . insert ( curr_substr ) ; } } curr_substr = " " ; } } return ans ; } int main ( ) { string s = " codecppforfood " ; string begin = " c " ; string end = " d " ; cout << numberOfDifferentSubstrings ( s , begin , end ) << endl ; return 0 ; } |
Printing string in plus β + β pattern in the matrix | CPP program to print the string in ' plus ' pattern ; Function to make a cross in the matrix ; As , it is not possible to make the cross exactly in the middle of the matrix with an even length string . ; declaring a 2D array i . e a matrix ; Now , we will fill all the elements of the array with ' X ' ; Now , we will place the characters of the string in the matrix , such that a cross is formed in it . ; here the characters of the string will be added in the middle column of our array . ; here the characters of the string will be added in the middle row of our array . ; Now finally , we will print the array ; driver code | #include <bits/stdc++.h> NEW_LINE #define max 100 NEW_LINE using namespace std ; void carveCross ( string str ) { int n = str . length ( ) ; if ( n % 2 == 0 ) { cout << " Not β possible . β Please β enter β " << " odd β length β string . STRNEWLINE " ; } else { char arr [ max ] [ max ] ; int m = n / 2 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { arr [ i ] [ j ] = ' X ' ; } } for ( int i = 0 ; i < n ; i ++ ) { arr [ i ] [ m ] = str [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { arr [ m ] [ i ] = str [ i ] ; } for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < n ; j ++ ) { cout << arr [ i ] [ j ] << " β " ; } cout << " STRNEWLINE " ; } } } int main ( ) { string str = " PICTURE " ; carveCross ( str ) ; return 0 ; } |
Binary String of given length that without a palindrome of size 3 | CPP program find a binary string of given length that doesn 't contain a palindrome of size 3. ; Printing the character according to i ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generatestring ( int n ) { for ( int i = 0 ; i < n ; i ++ ) putchar ( i & 2 ? ' b ' : ' a ' ) ; puts ( " " ) ; } int main ( ) { int n = 5 ; generatestring ( n ) ; n = 8 ; generatestring ( n ) ; n = 10 ; generatestring ( n ) ; } |
Print all subsequences of a string | Iterative Method | C ++ program to print all Subsequences of a string in iterative manner ; function to find subsequence ; check if jth bit in binary is 1 ; if jth bit is 1 , include it in subsequence ; function to print all subsequences ; map to store subsequence lexicographically by length ; Total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; subsequence for binary pattern i ; storing sub in map ; it . first is length of Subsequence it . second is set < string > ; ii is iterator of type set < string > ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string subsequence ( string s , int binary , int len ) { string sub = " " ; for ( int j = 0 ; j < len ; j ++ ) if ( binary & ( 1 << j ) ) sub += s [ j ] ; return sub ; } void possibleSubsequences ( string s ) { map < int , set < string > > sorted_subsequence ; int len = s . size ( ) ; int limit = pow ( 2 , len ) ; for ( int i = 1 ; i <= limit - 1 ; i ++ ) { string sub = subsequence ( s , i , len ) ; sorted_subsequence [ sub . length ( ) ] . insert ( sub ) ; } for ( auto it : sorted_subsequence ) { cout << " Subsequences β of β length β = β " << it . first << " β are : " << endl ; for ( auto ii : it . second ) cout << ii << " β " ; cout << endl ; } } int main ( ) { string s = " aabc " ; possibleSubsequences ( s ) ; return 0 ; } |
Print all subsequences of a string | Iterative Method | C ++ code all Subsequences of a string in iterative manner ; function to find subsequence ; loop while binary is greater than 0 ; get the position of rightmost set bit ; append at beginning as we are going from LSB to MSB ; resets bit at pos in binary ; function to print all subsequences ; map to store subsequence lexicographically by length ; Total number of non - empty subsequence in string is 2 ^ len - 1 ; i = 0 , corresponds to empty subsequence ; subsequence for binary pattern i ; storing sub in map ; it . first is length of Subsequence it . second is set < string > ; ii is iterator of type set < string > ; driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; string subsequence ( string s , int binary ) { string sub = " " ; int pos ; while ( binary > 0 ) { pos = log2 ( binary & - binary ) + 1 ; sub = s [ pos - 1 ] + sub ; binary = ( binary & ~ ( 1 << ( pos - 1 ) ) ) ; } reverse ( sub . begin ( ) , sub . end ( ) ) ; return sub ; } void possibleSubsequences ( string s ) { map < int , set < string > > sorted_subsequence ; int len = s . size ( ) ; int limit = pow ( 2 , len ) ; for ( int i = 1 ; i <= limit - 1 ; i ++ ) { string sub = subsequence ( s , i ) ; sorted_subsequence [ sub . length ( ) ] . insert ( sub ) ; } for ( auto it : sorted_subsequence ) { cout << " Subsequences β of β length β = β " << it . first << " β are : " << endl ; for ( auto ii : it . second ) cout << ii << " β " ; cout << endl ; } } int main ( ) { string s = " aabc " ; possibleSubsequences ( s ) ; return 0 ; } |
Program to find remainder when large number is divided by 11 | CPP implementation to find remainder when a large number is divided by 11 ; Function to return remainder ; len is variable to store the length of number string . ; loop that find remainder ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int remainder ( string str ) { int len = str . length ( ) ; int num , rem = 0 ; for ( int i = 0 ; i < len ; i ++ ) { num = rem * 10 + ( str [ i ] - '0' ) ; rem = num % 11 ; } return rem ; } int main ( ) { string str = "3435346456547566345436457867978" ; cout << remainder ( str ) ; return 0 ; } |
Longest subsequence of the form 0 * 1 * 0 * in a binary string | CPP program to find longest subsequence of the form 0 * 1 * 0 * in a binary string ; Returns length of the longest subsequence of the form 0 * 1 * 0 * ; Precomputing values in three arrays pre_count_0 [ i ] is going to store count of 0 s in prefix str [ 0. . i - 1 ] pre_count_1 [ i ] is going to store count of 1 s in prefix str [ 0. . i - 1 ] post_count_0 [ i ] is going to store count of 0 s in suffix str [ i - 1. . n - 1 ] ; string is made up of all 0 s or all 1 s ; Compute result using precomputed values ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubseq ( string s ) { int n = s . length ( ) ; int pre_count_0 [ n + 2 ] ; int pre_count_1 [ n + 1 ] ; int post_count_0 [ n + 1 ] ; pre_count_0 [ 0 ] = 0 ; post_count_0 [ n + 1 ] = 0 ; pre_count_1 [ 0 ] = 0 ; for ( int j = 1 ; j <= n ; j ++ ) { pre_count_0 [ j ] = pre_count_0 [ j - 1 ] ; pre_count_1 [ j ] = pre_count_1 [ j - 1 ] ; post_count_0 [ n - j + 1 ] = post_count_0 [ n - j + 2 ] ; if ( s [ j - 1 ] == '0' ) pre_count_0 [ j ] ++ ; else pre_count_1 [ j ] ++ ; if ( s [ n - j ] == '0' ) post_count_0 [ n - j + 1 ] ++ ; } if ( pre_count_0 [ n ] == n pre_count_0 [ n ] == 0 ) return n ; int ans = 0 ; for ( int i = 1 ; i <= n ; i ++ ) for ( int j = i ; j <= n ; j ++ ) ans = max ( pre_count_0 [ i - 1 ] + pre_count_1 [ j ] - pre_count_1 [ i - 1 ] + post_count_0 [ j + 1 ] , ans ) ; return ans ; } int main ( ) { string s = "000011100000" ; cout << longestSubseq ( s ) ; return 0 ; } |
Distinct permutations of the string | Set 2 | C ++ program to distinct permutations of the string ; Returns true if str [ curr ] does not matches with any of the characters after str [ start ] ; Prints all distinct permutations in str [ 0. . n - 1 ] ; Proceed further for str [ i ] only if it doesn 't match with any of the characters after str[index] ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool shouldSwap ( char str [ ] , int start , int curr ) { for ( int i = start ; i < curr ; i ++ ) if ( str [ i ] == str [ curr ] ) return 0 ; return 1 ; } void findPermutations ( char str [ ] , int index , int n ) { if ( index >= n ) { cout << str << endl ; return ; } for ( int i = index ; i < n ; i ++ ) { bool check = shouldSwap ( str , index , i ) ; if ( check ) { swap ( str [ index ] , str [ i ] ) ; findPermutations ( str , index + 1 , n ) ; swap ( str [ index ] , str [ i ] ) ; } } } int main ( ) { char str [ ] = " ABCA " ; int n = strlen ( str ) ; findPermutations ( str , 0 , n ) ; return 0 ; } |
Generate permutations with only adjacent swaps allowed | CPP program to generate permutations with only one swap allowed . ; don 't swap the current position ; Swap with the next character and revert the changes . As explained above , swapping with previous is is not needed as it anyways happens for next character . ; Driver code | #include <cstring> NEW_LINE #include <iostream> NEW_LINE using namespace std ; void findPermutations ( char str [ ] , int index , int n ) { if ( index >= n || ( index + 1 ) >= n ) { cout << str << endl ; return ; } findPermutations ( str , index + 1 , n ) ; swap ( str [ index ] , str [ index + 1 ] ) ; findPermutations ( str , index + 2 , n ) ; swap ( str [ index ] , str [ index + 1 ] ) ; } int main ( ) { char str [ ] = { "12345" } ; int n = strlen ( str ) ; findPermutations ( str , 0 , n ) ; return 0 ; } |
Decode a median string to the original string | C ++ program to decode a median string to the original string ; function to calculate the median back string ; length of string ; initialize a blank string ; Flag to check if length is even or odd ; traverse from first to last ; if len is even then add first character to beginning of new string and second character to end ; if current length is odd and is greater than 1 ; add first character to end and second character to beginning ; if length is 1 , add character to end ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string decodeMedianString ( string s ) { int l = s . length ( ) ; string s1 = " " ; bool isEven = ( l % 2 == 0 ) ? true : false ; for ( int i = 0 ; i < l ; i += 2 ) { if ( isEven ) { s1 = s [ i ] + s1 ; s1 += s [ i + 1 ] ; } else { if ( l - i > 1 ) { s1 += s [ i ] ; s1 = s [ i + 1 ] + s1 ; } else { s1 += s [ i ] ; } } } return s1 ; } int main ( ) { string s = " eekgs " ; cout << decodeMedianString ( s ) ; return 0 ; } |
Maximum number of characters between any two same character in a string | Simple C ++ program to find maximum number of characters between two occurrences of same character ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumChars ( string & str ) { int n = str . length ( ) ; int res = -1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( str [ i ] == str [ j ] ) res = max ( res , abs ( j - i - 1 ) ) ; return res ; } int main ( ) { string str = " abba " ; cout << maximumChars ( str ) ; return 0 ; } |
Maximum number of characters between any two same character in a string | Efficient C ++ program to find maximum number of characters between two occurrences of same character ; Initialize all indexes as - 1. ; If this is first occurrence ; Else find distance from previous occurrence and update result ( if required ) . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; int maximumChars ( string & str ) { int n = str . length ( ) ; int res = -1 ; int firstInd [ MAX_CHAR ] ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) firstInd [ i ] = -1 ; for ( int i = 0 ; i < n ; i ++ ) { int first_ind = firstInd [ str [ i ] ] ; if ( first_ind == -1 ) firstInd [ str [ i ] ] = i ; else res = max ( res , abs ( i - first_ind - 1 ) ) ; } return res ; } int main ( ) { string str = " abba " ; cout << maximumChars ( str ) ; return 0 ; } |
Check if an encoding represents a unique binary string | C ++ program to check if given encoding represents a single string . ; Return true if sum becomes k ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isUnique ( int a [ ] , int n , int k ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) sum += a [ i ] ; sum += n - 1 ; return ( sum == k ) ; } int main ( ) { int a [ ] = { 3 , 3 , 3 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; int k = 12 ; if ( isUnique ( a , n , k ) ) cout << " Yes " ; else cout << " No " ; return 0 ; } |
Lexicographically next string | C ++ program to find lexicographically next string ; If string is empty . ; Find first character from right which is not z . ; If all characters are ' z ' , append an ' a ' at the end . ; If there are some non - z characters ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string nextWord ( string s ) { if ( s == " " ) return " a " ; int i = s . length ( ) - 1 ; while ( s [ i ] == ' z ' && i >= 0 ) i -- ; if ( i == -1 ) s = s + ' a ' ; else s [ i ] ++ ; return s ; } int main ( ) { string str = " samez " ; cout << nextWord ( str ) ; return 0 ; } |
Length of the longest substring with equal 1 s and 0 s | C ++ program to find the length of the longest balanced substring ; Function to check if a string contains equal number of one and zeros or not ; Function to find the length of the longest balanced substring ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( string p ) { int n = p . length ( ) ; int c1 = 0 , c0 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( p [ i ] == '0' ) c0 ++ ; if ( p [ i ] == '1' ) c1 ++ ; } return ( c0 == c1 ) ? true : false ; } int longestSub ( string s ) { int max_len = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i ; j < n ; j ++ ) { if ( isValid ( s . substr ( i , j - i + 1 ) ) && max_len < j - i + 1 ) max_len = j - i + 1 ; } } return max_len ; } int main ( ) { string s = "101001000" ; cout << longestSub ( s ) ; return 0 ; } |
Common characters in n strings | CPP Program to find all the common characters in n strings ; primary array for common characters we assume all characters are seen before . ; for each string ; secondary array for common characters Initially marked false ; for every character of ith string ; if character is present in all strings before , mark it . ; copy whole secondary array into primary ; displaying common characters ; Driver 's Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void commonCharacters ( string str [ ] , int n ) { bool prim [ MAX_CHAR ] ; memset ( prim , true , sizeof ( prim ) ) ; for ( int i = 0 ; i < n ; i ++ ) { bool sec [ MAX_CHAR ] = { false } ; for ( int j = 0 ; str [ i ] [ j ] ; j ++ ) { if ( prim [ str [ i ] [ j ] - ' a ' ] ) sec [ str [ i ] [ j ] - ' a ' ] = true ; } memcpy ( prim , sec , MAX_CHAR ) ; } for ( int i = 0 ; i < 26 ; i ++ ) if ( prim [ i ] ) printf ( " % c β " , i + ' a ' ) ; } int main ( ) { string str [ ] = { " geeksforgeeks " , " gemkstones " , " acknowledges " , " aguelikes " } ; int n = sizeof ( str ) / sizeof ( str [ 0 ] ) ; commonCharacters ( str , n ) ; return 0 ; } |
Number of positions where a letter can be inserted such that a string becomes palindrome | CPP code to find the no . of positions where a letter can be inserted to make it a palindrome ; Function to check if the string is palindrome ; to know the length of string ; if the given string is a palindrome ( Case - I ) ; Sub - case - III ) ; if ( n % 2 == 0 ) if the length is even ; count = 2 * count + 1 ; sub - case - I ; count = 2 * count + 2 ; sub - case - II ; insertion point ; Case - I ; Case - II ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string & s , int i , int j ) { int p = j ; for ( int k = i ; k <= p ; k ++ ) { if ( s [ k ] != s [ p ] ) return false ; p -- ; } return true ; } int countWays ( string & s ) { int n = s . length ( ) ; int count = 0 ; if ( isPalindrome ( s , 0 , n - 1 ) ) { for ( int i = n / 2 ; i < n ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) count ++ ; else break ; } { count ++ ; } else } else { for ( int i = 0 ; i < n / 2 ; i ++ ) { if ( s [ i ] != s [ n - 1 - i ] ) { int j = n - 1 - i ; if ( isPalindrome ( s , i , n - 2 - i ) ) { for ( int k = i - 1 ; k >= 0 ; k -- ) { if ( s [ k ] != s [ j ] ) break ; count ++ ; } count ++ ; } if ( isPalindrome ( s , i + 1 , n - 1 - i ) ) { for ( int k = n - i ; k < n ; k ++ ) { if ( s [ k ] != s [ i ] ) break ; count ++ ; } count ++ ; } break ; } } } return count ; } int main ( ) { string s = " abca " ; cout << countWays ( s ) << endl ; return 0 ; } |
Count of substrings of a binary string containing K ones | C ++ program to find count of substring containing exactly K ones ; method returns total number of substring having K ones ; initialize index having zero sum as 1 ; loop over binary characters of string ; update countOfOne variable with value of ith character ; if value reaches more than K , then update result ; add frequency of indices , having sum ( current sum - K ) , to the result ; update frequency of one 's count ; Driver code to test above methods | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countOfSubstringWithKOnes ( string s , int K ) { int N = s . length ( ) ; int res = 0 ; int countOfOne = 0 ; int freq [ N + 1 ] = { 0 } ; freq [ 0 ] = 1 ; for ( int i = 0 ; i < N ; i ++ ) { countOfOne += ( s [ i ] - '0' ) ; if ( countOfOne >= K ) { res += freq [ countOfOne - K ] ; } freq [ countOfOne ] ++ ; } return res ; } int main ( ) { string s = "10010" ; int K = 1 ; cout << countOfSubstringWithKOnes ( s , K ) << endl ; return 0 ; } |
Generate two output strings depending upon occurrence of character in input string . | CPP program to print two strings made of character occurring once and multiple times ; function to print two strings generated from single string one with characters occurring onces other with character occurring multiple of times ; initialize hashtable with zero entry ; perform hashing for input string ; generate string ( str1 ) consisting char occurring once and string ( str2 ) consisting char occurring multiple times ; print both strings ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; void printDuo ( string & str ) { int countChar [ MAX_CHAR ] = { 0 } ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) countChar [ str [ i ] - ' a ' ] ++ ; string str1 = " " , str2 = " " ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( countChar [ i ] > 1 ) str2 = str2 + ( char ) ( i + ' a ' ) ; else if ( countChar [ i ] == 1 ) str1 = str1 + ( char ) ( i + ' a ' ) ; } cout << " String β with β characters β occurring β " << " once : STRNEWLINE " ; cout << str1 << " STRNEWLINE " ; cout << " String β with β characters β occurring β " << " multiple β times : STRNEWLINE " ; cout << str2 << " STRNEWLINE " ; } int main ( ) { string str = " lovetocode " ; printDuo ( str ) ; return 0 ; } |
Next higher palindromic number using the same set of digits | C ++ implementation to find next higher palindromic number using the same set of digits ; function to reverse the digits in the range i to j in ' num ' ; function to find next higher palindromic number using the same set of digits ; if length of number is less than '3' then no higher palindromic number can be formed ; find the index of last digit in the 1 st half of ' num ' ; Start from the ( mid - 1 ) th digit and find the first digit that is smaller than the digit next to it . ; If no such digit is found , then all digits are in descending order which means there cannot be a greater palindromic number with same set of digits ; Find the smallest digit on right side of ith digit which is greater than num [ i ] up to index ' mid ' ; swap num [ i ] with num [ smallest ] ; as the number is a palindrome , the same swap of digits should be performed in the 2 nd half of ' num ' ; reverse digits in the range ( i + 1 ) to mid ; if n is even , then reverse digits in the range mid + 1 to n - i - 2 ; else if n is odd , then reverse digits in the range mid + 2 to n - i - 2 ; required next higher palindromic number ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( char num [ ] , int i , int j ) { while ( i < j ) { swap ( num [ i ] , num [ j ] ) ; i ++ ; j -- ; } } void nextPalin ( char num [ ] , int n ) { if ( n <= 3 ) { cout << " Not β Possible " ; return ; } int mid = n / 2 - 1 ; int i , j ; for ( i = mid - 1 ; i >= 0 ; i -- ) if ( num [ i ] < num [ i + 1 ] ) break ; if ( i < 0 ) { cout << " Not β Possible " ; return ; } int smallest = i + 1 ; for ( j = i + 2 ; j <= mid ; j ++ ) if ( num [ j ] > num [ i ] && num [ j ] <= num [ smallest ] ) smallest = j ; swap ( num [ i ] , num [ smallest ] ) ; swap ( num [ n - i - 1 ] , num [ n - smallest - 1 ] ) ; reverse ( num , i + 1 , mid ) ; if ( n % 2 == 0 ) reverse ( num , mid + 1 , n - i - 2 ) ; else reverse ( num , mid + 2 , n - i - 2 ) ; cout << " Next β Palindrome : β " << num ; } int main ( ) { char num [ ] = "4697557964" ; int n = strlen ( num ) ; nextPalin ( num , n ) ; return 0 ; } |
Print N | C ++ program to print all N - bit binary ; function to generate n digit numbers ; if number generated ; Append 1 at the current number and reduce the remaining places by one ; If more ones than zeros , append 0 to the current number and reduce the remaining places by one ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRec ( string number , int extraOnes , int remainingPlaces ) { if ( 0 == remainingPlaces ) { cout << number << " β " ; return ; } printRec ( number + "1" , extraOnes + 1 , remainingPlaces - 1 ) ; if ( 0 < extraOnes ) printRec ( number + "0" , extraOnes - 1 , remainingPlaces - 1 ) ; } void printNums ( int n ) { string str = " " ; printRec ( str , 0 , n ) ; } int main ( ) { int n = 4 ; printNums ( n ) ; return 0 ; } |
Longest Common Substring in an Array of Strings | C ++ program to find the stem of given list of words ; function to find the stem ( longest commonsubstring ) from the string array ; Determine size of the array ; Take first word from array as reference ; generating all possible substrings of our reference string arr [ 0 ] i . e s ; Check if the generated stem is common to all words ; If current substring is present in all strings and its length is greater than current result ; Driver code ; Function call | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findstem ( vector < string > arr ) { int n = arr . size ( ) ; string s = arr [ 0 ] ; int len = s . length ( ) ; string res = " " ; for ( int i = 0 ; i < len ; i ++ ) { for ( int j = i + 1 ; j <= len ; j ++ ) { string stem = s . substr ( i , j ) ; int k = 1 ; for ( k = 1 ; k < n ; k ++ ) { if ( arr [ k ] . find ( stem ) == std :: string :: npos ) break ; } if ( k == n && res . length ( ) < stem . length ( ) ) res = stem ; } } return res ; } int main ( ) { vector < string > arr { " grace " , " graceful " , " disgraceful " , " gracefully " } ; string stems = findstem ( arr ) ; cout << stems << endl ; } |
Make a string from another by deletion and rearrangement of characters | CPP program to find if it is possible to make a string from characters present in other string . ; Returns true if it is possible to make s1 from characters present in s2 . ; Count occurrences of all characters present in s2 . . ; For every character , present in s1 , reduce its count if count is more than 0. ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; bool isPossible ( string & s1 , string & s2 ) { int count [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < s2 . length ( ) ; i ++ ) count [ s2 [ i ] ] ++ ; for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) { if ( count [ s1 [ i ] ] == 0 ) return false ; count [ s1 [ i ] ] -- ; } return true ; } int main ( ) { string s1 = " GeeksforGeeks " , s2 = " rteksfoGrdsskGeggehes " ; if ( isPossible ( s1 , s2 ) ) cout << " Possible " ; else cout << " Not β Possible STRNEWLINE " ; return 0 ; } |
Next higher number using atmost one swap operation | C ++ implementation to find the next higher number using atmost one swap operation ; function to find the next higher number using atmost one swap operation ; to store the index of the largest digit encountered so far from the right ; to store the index of rightmost digit which has a digit greater to it on its right side ; finding the ' index ' of rightmost digit which has a digit greater to it on its right side ; required digit found , store its ' index ' and break ; if no such digit is found which has a larger digit on its right side ; to store the index of the smallest digit greater than the digit at ' index ' and right to it ; finding the index of the smallest digit greater than the digit at ' index ' and right to it ; swapping the digits ; required number ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; string nxtHighUsingAtMostOneSwap ( string num ) { int l = num . size ( ) ; int posRMax = l - 1 ; int index = -1 ; for ( int i = l - 2 ; i >= 0 ; i -- ) { if ( num [ i ] >= num [ posRMax ] ) posRMax = i ; else { index = i ; break ; } } if ( index == -1 ) return " Not β Possible " ; int greatSmallDgt = -1 ; for ( int i = l - 1 ; i > index ; i -- ) { if ( num [ i ] > num [ index ] ) { if ( greatSmallDgt == -1 ) greatSmallDgt = i ; else if ( num [ i ] <= num [ greatSmallDgt ] ) greatSmallDgt = i ; } } char temp = num [ index ] ; num [ index ] = num [ greatSmallDgt ] ; num [ greatSmallDgt ] = temp ; return num ; } int main ( ) { string num = "218765" ; cout << " Original β number : β " << num << endl ; cout << " Next β higher β number : β " << nxtHighUsingAtMostOneSwap ( num ) ; return 0 ; } |
Longest substring of vowels | CPP program to find the longest substring of vowels . ; Increment current count if s [ i ] is vowel ; check previous value is greater then or not ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { return ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) ; } int longestVowel ( string s ) { int count = 0 , res = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( isVowel ( s [ i ] ) ) count ++ ; else { res = max ( res , count ) ; count = 0 ; } } return max ( res , count ) ; } int main ( ) { string s = " theeare " ; cout << longestVowel ( s ) << endl ; return 0 ; } |
Number of substrings with count of each character as k | C ++ program to count number of substrings with counts of distinct characters as k . ; Returns true if all values in freq [ ] are either 0 or k . ; Returns count of substrings where frequency of every present character is k ; Pick a starting point ; Initialize all frequencies as 0 for this starting point ; One by one pick ending points ; Increment frequency of current char ; If frequency becomes more than k , we can 't have more substrings starting with i ; If frequency becomes k , then check other frequencies as well . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool check ( int freq [ ] , int k ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( freq [ i ] && freq [ i ] != k ) return false ; return true ; } int substrings ( string s , int k ) { for ( int i = 0 ; s [ i ] ; i ++ ) { int freq [ MAX_CHAR ] = { 0 } ; for ( int j = i ; s [ j ] ; j ++ ) { int index = s [ j ] - ' a ' ; freq [ index ] ++ ; if ( freq [ index ] > k ) break ; else if ( freq [ index ] == k && check ( freq , k ) == true ) res ++ ; } } return res ; } int main ( ) { string s = " aabbcc " ; int k = 2 ; cout << substrings ( s , k ) << endl ; s = " aabbc " ; k = 2 ; cout << substrings ( s , k ) << endl ; } |
Number of substrings with count of each character as k | | #include <iostream> NEW_LINE #include <map> NEW_LINE #include <set> NEW_LINE #include <string> NEW_LINE int min ( int a , int b ) { return a < b ? a : b ; } using namespace std ; bool have_same_frequency ( map < char , int > & freq , int k ) { for ( auto & pair : freq ) { if ( pair . second != k && pair . second != 0 ) { return false ; } } return true ; } int count_substrings ( string s , int k ) { int count = 0 ; int distinct = ( set < char > ( s . begin ( ) , s . end ( ) ) ) . size ( ) ; for ( int length = 1 ; length <= distinct ; length ++ ) { int window_length = length * k ; map < char , int > freq ; int window_start = 0 ; int window_end = window_start + window_length - 1 ; for ( int i = window_start ; i <= min ( window_end , s . length ( ) - 1 ) ; i ++ ) { freq [ s [ i ] ] ++ ; } while ( window_end < s . length ( ) ) { if ( have_same_frequency ( freq , k ) ) { count ++ ; } freq [ s [ window_start ] ] -- ; window_start ++ ; window_end ++ ; if ( window_length < s . length ( ) ) { freq [ s [ window_end ] ] ++ ; } } } return count ; } int main ( ) { string s = " aabbcc " ; int k = 2 ; cout << count_substrings ( s , k ) << endl ; s = " aabbc " ; k = 2 ; cout << count_substrings ( s , k ) << endl ; return 0 ; } |
Frequency of a string in an array of strings | C ++ program to count number of times a string appears in an array of strings ; To store number of times a string is present . It is 0 is string is not present ; function to insert a string into the Trie ; calculation ascii value ; If the given node is not already present in the Trie than create the new node ; Returns count of occurrences of s in Trie ; inserting in Trie ; searching the strings in Trie ; Driver code | #include <iostream> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; struct Trie { int cnt ; Trie * node [ MAX_CHAR ] ; Trie ( ) { for ( int i = 0 ; i < MAX_CHAR ; i ++ ) node [ i ] = NULL ; cnt = 0 ; } } ; Trie * insert ( Trie * root , string s ) { Trie * temp = root ; int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int index = s [ i ] - ' a ' ; if ( ! root -> node [ index ] ) root -> node [ index ] = new Trie ( ) ; root = root -> node [ index ] ; } root -> cnt ++ ; return temp ; } int search ( Trie * root , string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int index = s [ i ] - ' a ' ; if ( ! root -> node [ index ] ) return 0 ; root = root -> node [ index ] ; } return root -> cnt ; } void answerQueries ( string arr [ ] , int n , string q [ ] , int m ) { Trie * root = new Trie ( ) ; for ( int i = 0 ; i < n ; i ++ ) root = insert ( root , arr [ i ] ) ; for ( int i = 0 ; i < m ; i ++ ) cout << search ( root , q [ i ] ) << " β " ; } int main ( ) { string arr [ ] = { " aba " , " baba " , " aba " , " xzxb " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; string q [ ] = { " aba " , " xzxb " , " ab " } ; int m = sizeof ( q ) / sizeof ( q [ 0 ] ) ; answerQueries ( arr , n , q , m ) ; return 0 ; } |
Longest subsequence where every character appears at | C ++ program to Find longest subsequence where every character appears at - least k times ; Count frequencies of all characters ; Traverse given string again and print all those characters whose frequency is more than or equal to k . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHARS = 26 ; void longestSubseqWithK ( string str , int k ) { int n = str . size ( ) ; int freq [ MAX_CHARS ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < n ; i ++ ) if ( freq [ str [ i ] - ' a ' ] >= k ) cout << str [ i ] ; } int main ( ) { string str = " geeksforgeeks " ; int k = 2 ; longestSubseqWithK ( str , k ) ; return 0 ; } |
Generating distinct subsequences of a given string in lexicographic order | C ++ program to print all distinct subsequences of a string . ; Finds and stores result in st for a given string s . ; If current string is not already present . ; Traverse current string , one by one remove every character and recur . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void generate ( set < string > & st , string s ) { if ( s . size ( ) == 0 ) return ; if ( st . find ( s ) == st . end ( ) ) { st . insert ( s ) ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { string t = s ; t . erase ( i , 1 ) ; generate ( st , t ) ; } } return ; } int main ( ) { string s = " xyz " ; set < string > st ; set < string > :: iterator it ; generate ( st , s ) ; for ( auto it = st . begin ( ) ; it != st . end ( ) ; it ++ ) cout << * it << endl ; return 0 ; } |
Print all subsequences of a string | CPP program to print all subsequence of a given string . ; set to store all the subsequences ; Function computes all the subsequence of an string ; Iterate over the entire string ; Iterate from the end of the string to generate substrings ; Drop kth character in the substring and if its not in the set then recur ; Drop character from the string ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_set < string > st ; void subsequence ( string str ) { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { for ( int j = str . length ( ) ; j > i ; j -- ) { string sub_str = str . substr ( i , j ) ; st . insert ( sub_str ) ; for ( int k = 1 ; k < sub_str . length ( ) ; k ++ ) { string sb = sub_str ; sb . erase ( sb . begin ( ) + k ) ; subsequence ( sb ) ; } } } } int main ( ) { string s = " aabc " ; subsequence ( s ) ; for ( auto i : st ) cout << i << " β " ; cout << endl ; return 0 ; } |
Print all subsequences of a string | CPP program to generate power set in lexicographic order . ; str : Stores input string n : Length of str . curr : Stores current permutation index : Index in current permutation , curr ; base case ; backtracking ; Generates power set in lexicographic order . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printSubSeqRec ( string str , int n , int index = -1 , string curr = " " ) { if ( index == n ) return ; if ( ! curr . empty ( ) ) { cout << curr << " STRNEWLINE " ; } for ( int i = index + 1 ; i < n ; i ++ ) { curr += str [ i ] ; printSubSeqRec ( str , n , i , curr ) ; curr = curr . erase ( curr . size ( ) - 1 ) ; } return ; } void printSubSeq ( string str ) { printSubSeqRec ( str , str . size ( ) ) ; } int main ( ) { string str = " cab " ; printSubSeq ( str ) ; return 0 ; } |
Recursive solution to count substrings with same first and last characters | c ++ program to count substrings with same first and last characters ; Function to count substrings with same first and last characters ; base cases ; driver code | #include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; int countSubstrs ( string str , int i , int j , int n ) { if ( n == 1 ) return 1 ; if ( n <= 0 ) return 0 ; int res = countSubstrs ( str , i + 1 , j , n - 1 ) + countSubstrs ( str , i , j - 1 , n - 1 ) - countSubstrs ( str , i + 1 , j - 1 , n - 2 ) ; if ( str [ i ] == str [ j ] ) res ++ ; return res ; } int main ( ) { string str = " abcab " ; int n = str . length ( ) ; cout << countSubstrs ( str , 0 , n - 1 , n ) ; } |
Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | C ++ Program to find minimum number of manipulations required to make two strings identical ; Counts the no of manipulations required ; store the count of character ; iterate though the first String and update count ; iterate through the second string update char_count . if character is not found in char_count then increase count ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countManipulations ( string s1 , string s2 ) { int count = 0 ; int char_count [ 26 ] ; for ( int i = 0 ; i < 26 ; i ++ ) { char_count [ i ] = 0 ; } for ( int i = 0 ; i < s1 . length ( ) ; i ++ ) char_count [ s1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < s2 . length ( ) ; i ++ ) { char_count [ s2 [ i ] - ' a ' ] -- ; } for ( int i = 0 ; i < 26 ; ++ i ) { if ( char_count [ i ] != 0 ) { count += abs ( char_count [ i ] ) ; } } return count / 2 ; } int main ( ) { string s1 = " ddcf " ; string s2 = " cedk " ; cout << countManipulations ( s1 , s2 ) ; } |
Least number of manipulations needed to ensure two strings have identical characters | C ++ program to count least number of manipulations to have two strings set of same characters ; return the count of manipulations required ; count the number of different characters in both strings ; check the difference in characters by comparing count arrays ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; int leastCount ( string s1 , string s2 , int n ) { int count1 [ MAX_CHAR ] = { 0 } ; int count2 [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { count1 [ s1 [ i ] - ' a ' ] += 1 ; count2 [ s2 [ i ] - ' a ' ] += 1 ; } int res = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( count1 [ i ] != 0 ) { res += abs ( count1 [ i ] - count2 [ i ] ) ; } } return res ; } int main ( ) { string s1 = " abc " ; string s2 = " cdd " ; int len = s1 . length ( ) ; int res = leastCount ( s1 , s2 , len ) ; cout << res << endl ; return 0 ; } |
Given two strings check which string makes a palindrome first | Given two strings , check which string makes palindrome first . ; returns winner of two strings ; Count frequencies of characters in both given strings ; Check if there is a character that appears more than once in A and does not appear in B ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; char stringPalindrome ( string A , string B ) { int countA [ MAX_CHAR ] = { 0 } ; int countB [ MAX_CHAR ] = { 0 } ; int l1 = A . length ( ) , l2 = B . length ( ) ; for ( int i = 0 ; i < l1 ; i ++ ) countA [ A [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < l2 ; i ++ ) countB [ B [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < 26 ; i ++ ) if ( ( countA [ i ] > 1 && countB [ i ] == 0 ) ) return ' A ' ; return ' B ' ; } int main ( ) { string a = " abcdea " ; string b = " bcdesg " ; cout << stringPalindrome ( a , b ) ; return 0 ; } |
Print the longest common substring | C ++ implementation to print the longest common substring ; function to find and print the longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of longest common suffix of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] . The first row and first column entries have no logical meaning , they are used only for simplicity of program ; To store length of the longest common substring ; To store the index of the cell which contains the maximum value . This cell 's index helps in building up the longest common substring from right to left. ; Following steps build LCSuff [ m + 1 ] [ n + 1 ] in bottom up fashion . ; if true , then no common substring exists ; allocate space for the longest common substring ; traverse up diagonally form the ( row , col ) cell until LCSuff [ row ] [ col ] != 0 ; move diagonally up to previous cell ; required longest common substring ; Driver program to test above function | #include <iostream> NEW_LINE #include <stdlib.h> NEW_LINE #include <string.h> NEW_LINE using namespace std ; void printLCSubStr ( char * X , char * Y , int m , int n ) { int LCSuff [ m + 1 ] [ n + 1 ] ; int len = 0 ; int row , col ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) LCSuff [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) { LCSuff [ i ] [ j ] = LCSuff [ i - 1 ] [ j - 1 ] + 1 ; if ( len < LCSuff [ i ] [ j ] ) { len = LCSuff [ i ] [ j ] ; row = i ; col = j ; } } else LCSuff [ i ] [ j ] = 0 ; } } if ( len == 0 ) { cout << " No β Common β Substring " ; return ; } char * resultStr = ( char * ) malloc ( ( len + 1 ) * sizeof ( char ) ) ; while ( LCSuff [ row ] [ col ] != 0 ) { row -- ; col -- ; } cout << resultStr ; } int main ( ) { char X [ ] = " OldSite : GeeksforGeeks . org " ; char Y [ ] = " NewSite : GeeksQuiz . com " ; int m = strlen ( X ) ; int n = strlen ( Y ) ; printLCSubStr ( X , Y , m , n ) ; return 0 ; } |
Find the first repeated word in a string | CPP program for finding first repeated word in a string ; returns first repeated word ; break string into tokens and then each string into set if a word appeared before appears again , return the word and break ; hashmap for storing word and its count in sentence ; store all the words of string and the count of word in hashmap ; setOfWords [ token ] += 1 ; word exists ; insert new word to set ; either take a new stream or store the words in vector of strings in previous loop ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findFirstRepeated ( string s ) { istringstream iss ( s ) ; string token ; unordered_map < string , int > setOfWords ; while ( getline ( iss , token , ' β ' ) ) { if ( setOfWords . find ( token ) != setOfWords . end ( ) ) else setOfWords . insert ( make_pair ( token , 1 ) ) ; } istringstream iss2 ( s ) ; while ( getline ( iss2 , token , ' β ' ) ) { int count = setOfWords [ token ] ; if ( count > 1 ) { return token ; } } return " NoRepetition " ; } int main ( ) { string s ( " Ravi β had β been β saying β that β he β had β been β there " ) ; string firstWord = findFirstRepeated ( s ) ; if ( firstWord != " NoRepetition " ) cout << " First β repeated β word β : : β " << firstWord << endl ; else cout << " No β Repetitionn " ; return 0 ; } |
Find the first repeated word in a string | CPP program for finding first repeated word in a string ; returns first repeated word ; break string into tokens and then each string into set if a word appeared before appears again , return the word and break ; hashset for storing word and its count in sentence ; store all the words of string and the count of word in hashset ; if word exists return ; insert new word to set ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string findFirstRepeated ( string s ) { istringstream iss ( s ) ; string token ; set < string > setOfWords ; while ( getline ( iss , token , ' β ' ) ) { if ( setOfWords . find ( token ) != setOfWords . end ( ) ) { return token ; } setOfWords . insert ( token ) ; } return " NoRepetition " ; } int main ( ) { string s ( " Ravi β had β been β saying β that β he β had β been β there " ) ; string firstWord = findFirstRepeated ( s ) ; if ( firstWord != " NoRepetition " ) cout << " First β repeated β word β : : β " << firstWord << endl ; else cout << " No β Repetitionn " ; return 0 ; } |
Convert all substrings of length ' k ' from base ' b ' to decimal | Simple C ++ program to convert all substrings from decimal to given base . ; Saving substring in sub ; Evaluating decimal for current substring and printing it . ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; int substringConversions ( string str , int k , int b ) { for ( int i = 0 ; i + k <= str . size ( ) ; i ++ ) { string sub = str . substr ( i , k ) ; int sum = 0 , counter = 0 ; for ( int i = sub . size ( ) - 1 ; i >= 0 ; i -- ) { sum = sum + ( ( sub . at ( i ) - '0' ) * pow ( b , counter ) ) ; counter ++ ; } cout << sum << " β " ; } } int main ( ) { string str = "12212" ; int b = 3 , k = 3 ; substringConversions ( str , b , k ) ; return 0 ; } |
Find numbers of balancing positions in string | C ++ program to find number of balancing points in string ; function to return number of balancing points ; hash array for storing hash of string initialized by 0 being global ; process string initially for rightVisited ; check for balancing points ; for every position inc left hash & dec rightVisited ; check whether both hash have same character or not ; Either both leftVisited [ j ] and rightVisited [ j ] should have none zero value or both should have zero value ; if both have same character increment count ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; int countBalance ( char * str ) { int leftVisited [ MAX_CHAR ] = { 0 } ; int rightVisited [ MAX_CHAR ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) rightVisited [ str [ i ] ] ++ ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { leftVisited [ str [ i ] ] ++ ; rightVisited [ str [ i ] ] -- ; int j ; for ( j = 0 ; j < MAX_CHAR ; j ++ ) { if ( ( leftVisited [ j ] == 0 && rightVisited [ j ] != 0 ) || ( leftVisited [ j ] != 0 && rightVisited [ j ] == 0 ) ) break ; } if ( j == MAX_CHAR ) res ++ ; } return res ; } int main ( ) { char str [ ] = " abaababa " ; cout << countBalance ( str ) ; return 0 ; } |
Min flips of continuous characters to make all characters same in a string | CPP program to find min flips in binary string to make all characters equal ; To find min number of flips in binary string ; If last character is not equal to str [ i ] increase res ; To return min flips ; Driver program to check findFlips ( ) | #include <bits/stdc++.h> NEW_LINE using namespace std ; int findFlips ( char str [ ] , int n ) { char last = ' β ' ; int res = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( last != str [ i ] ) res ++ ; last = str [ i ] ; } return res / 2 ; } int main ( ) { char str [ ] = "00011110001110" ; int n = strlen ( str ) ; cout << findFlips ( str , n ) ; return 0 ; } |
Maximum length substring having all same characters after k changes | C ++ program to find maximum length equal character string with k changes ; function to find the maximum length of substring having character ch ; traverse the whole string ; if character is not same as ch increase count ; While count > k traverse the string again until count becomes less than k and decrease the count when characters are not same ; length of substring will be rightIndex - leftIndex + 1. Compare this with the maximum length and return maximum length ; function which returns maximum length of substring ; Driver code | #include <iostream> NEW_LINE using namespace std ; int findLen ( string & A , int n , int k , char ch ) { int maxlen = 1 ; int cnt = 0 ; int l = 0 , r = 0 ; while ( r < n ) { if ( A [ r ] != ch ) ++ cnt ; while ( cnt > k ) { if ( A [ l ] != ch ) -- cnt ; ++ l ; } maxlen = max ( maxlen , r - l + 1 ) ; ++ r ; } return maxlen ; } int answer ( string & A , int n , int k ) { int maxlen = 1 ; for ( int i = 0 ; i < 26 ; ++ i ) { maxlen = max ( maxlen , findLen ( A , n , k , i + ' A ' ) ) ; maxlen = max ( maxlen , findLen ( A , n , k , i + ' a ' ) ) ; } return maxlen ; } int main ( ) { int n = 5 , k = 2 ; string A = " ABABA " ; cout << " Maximum β length β = β " << answer ( A , n , k ) << endl ; n = 6 , k = 4 ; string B = " HHHHHH " ; cout << " Maximum β length β = β " << answer ( B , n , k ) << endl ; return 0 ; } |
Given a sequence of words , print all anagrams together using STL | C ++ program for finding all anagram pairs in the given array ; Utility function for printing anagram list ; Utility function for storing the vector of strings into HashMap ; sort the string ; make hash of a sorted string ; print utility function for printing all the anagrams ; Driver code ; initialize vector of strings ; utility function for storing strings into hashmap | #include <algorithm> NEW_LINE #include <iostream> NEW_LINE #include <unordered_map> NEW_LINE #include <vector> NEW_LINE using namespace std ; void printAnagram ( unordered_map < string , vector < string > > & store ) { for ( auto it : store ) { vector < string > temp_vec ( it . second ) ; int size = temp_vec . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) cout << temp_vec [ i ] << " β " ; cout << " STRNEWLINE " ; } } void storeInMap ( vector < string > & vec ) { unordered_map < string , vector < string > > store ; for ( int i = 0 ; i < vec . size ( ) ; i ++ ) { string tempString ( vec [ i ] ) ; sort ( tempString . begin ( ) , tempString . end ( ) ) ; store [ tempString ] . push_back ( vec [ i ] ) ; } printAnagram ( store ) ; } int main ( ) { vector < string > arr ; arr . push_back ( " geeksquiz " ) ; arr . push_back ( " geeksforgeeks " ) ; arr . push_back ( " abcd " ) ; arr . push_back ( " forgeeksgeeks " ) ; arr . push_back ( " zuiqkeegs " ) ; arr . push_back ( " cat " ) ; arr . push_back ( " act " ) ; arr . push_back ( " tca " ) ; storeInMap ( arr ) ; return 0 ; } |
Quick way to check if all the characters of a string are same | C ++ program for above approach ; Function to check is all the characters in string are or not ; Insert characters in the set ; If all characters are same Size of set will always be 1 ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void allCharactersSame ( string s ) { set < char > s1 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) s1 . insert ( s [ i ] ) ; if ( s1 . size ( ) == 1 ) cout << " YES " ; else cout << " NO " ; } int main ( ) { string str = " nnnn " ; allCharactersSame ( str ) ; return 0 ; } |
Find the character in first string that is present at minimum index in second string | C ++ implementation to find the character in first string that is present at minimum index in second string ; function to find the minimum index character ; to store the index of character having minimum index ; lengths of the two strings ; traverse ' patt ' ; for each character of ' patt ' traverse ' str ' ; if patt [ i ] is found in ' str ' , check if it has the minimum index or not . If yes , then update ' minIndex ' and break ; print the minimum index character ; if no character of ' patt ' is present in ' str ' ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinIndexChar ( string str , string patt ) { int minIndex = INT_MAX ; int m = str . size ( ) ; int n = patt . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { if ( patt [ i ] == str [ j ] && j < minIndex ) { minIndex = j ; break ; } } } if ( minIndex != INT_MAX ) cout << " Minimum β Index β Character β = β " << str [ minIndex ] ; else cout << " No β character β present " ; } int main ( ) { string str = " geeksforgeeks " ; string patt = " set " ; printMinIndexChar ( str , patt ) ; return 0 ; } |
Find the character in first string that is present at minimum index in second string | C ++ implementation to find the character in first string that is present at minimum index in second string ; function to find the minimum index character ; unordered_map ' um ' implemented as hash table ; to store the index of character having minimum index ; lengths of the two strings ; store the first index of each character of ' str ' ; traverse the string ' patt ' ; if patt [ i ] is found in ' um ' , check if it has the minimum index or not accordingly update ' minIndex ' ; print the minimum index character ; if no character of ' patt ' is present in ' str ' ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printMinIndexChar ( string str , string patt ) { unordered_map < char , int > um ; int minIndex = INT_MAX ; int m = str . size ( ) ; int n = patt . size ( ) ; - for ( int i = 0 ; i < m ; i ++ ) if ( um . find ( str [ i ] ) == um . end ( ) ) um [ str [ i ] ] = i ; for ( int i = 0 ; i < n ; i ++ ) if ( um . find ( patt [ i ] ) != um . end ( ) && um [ patt [ i ] ] < minIndex ) minIndex = um [ patt [ i ] ] ; if ( minIndex != INT_MAX ) cout << " Minimum β Index β Character β = β " << str [ minIndex ] ; else cout << " No β character β present " ; } int main ( ) { string str = " geeksforgeeks " ; string patt = " set " ; printMinIndexChar ( str , patt ) ; return 0 ; } |
Check if both halves of the string have same set of characters | C ++ program to check if it is possible to split string or not ; function to check if we can split string or not ; Counter array initialized with 0 ; Length of the string ; traverse till the middle element is reached ; First half ; Second half ; Checking if values are different set flag to 1 ; Driver program to test above function ; String to be checked | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; bool checkCorrectOrNot ( string s ) { int count1 [ MAX_CHAR ] = { 0 } ; int count2 [ MAX_CHAR ] = { 0 } ; int n = s . length ( ) ; if ( n == 1 ) return true ; for ( int i = 0 , j = n - 1 ; i < j ; i ++ , j -- ) { count1 [ s [ i ] - ' a ' ] ++ ; count2 [ s [ j ] - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( count1 [ i ] != count2 [ i ] ) return false ; return true ; } int main ( ) { string s = " abab " ; if ( checkCorrectOrNot ( s ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; } |
Given a number as a string , find the number of contiguous subsequences which recursively add up to 9 | Set 2 | C ++ program to count substrings with recursive sum equal to 9 ; to store no . of previous encountered modular sums ; no . of modular sum ( == 0 ) encountered till now = 1 ; if number is 0 increase ; no . of continuous_zero by 1 ; else continuous_zero is 0 ; increase d value of this mod_sum ; subtract no . of cases where there are only zeroes in substring ; driver program to test above function | #include <iostream> NEW_LINE #include <cstring> NEW_LINE using namespace std ; int count9s ( char number [ ] ) { int n = strlen ( number ) ; int d [ 9 ] ; memset ( d , 0 , sizeof ( d ) ) ; d [ 0 ] = 1 ; int result = 0 ; int mod_sum = 0 , continuous_zero = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! int ( number [ i ] - '0' ) ) continuous_zero ++ ; else continuous_zero = 0 ; mod_sum += int ( number [ i ] - '0' ) ; mod_sum %= 9 ; result += d [ mod_sum ] ; d [ mod_sum ] ++ ; result -= continuous_zero ; } return result ; } int main ( ) { cout << count9s ( "01809" ) << endl ; cout << count9s ( "1809" ) << endl ; cout << count9s ( "4189" ) ; return 0 ; } |
Extract maximum numeric value from a given string | Set 1 ( General approach ) | C ++ program for above implementation ; Utility function to find maximum string ; If both having equal lengths ; Reach first unmatched character / value ; Return string with maximum value ; If different lengths return string with maximum length ; Function to extract the maximum value ; Start traversing the string ; Ignore leading zeroes ; Store numeric value into a string ; Update maximum string ; To handle the case if there is only 0 numeric value ; Return maximum string ; Drivers program | #include <bits/stdc++.h> NEW_LINE using namespace std ; string maximumNum ( string curr_num , string res ) { int len1 = curr_num . length ( ) ; int len2 = res . length ( ) ; if ( len1 == len2 ) { int i = 0 ; while ( curr_num [ i ] == res [ i ] ) i ++ ; if ( curr_num [ i ] < res [ i ] ) return res ; else return curr_num ; } return len1 < len2 ? res : curr_num ; } string extractMaximum ( string str ) { int n = str . length ( ) ; string curr_num = " " ; string res ; for ( int i = 0 ; i < n ; i ++ ) { while ( i < n && str [ i ] == '0' ) i ++ ; while ( i < n && str [ i ] >= '0' && str [ i ] <= '9' ) { curr_num = curr_num + str [ i ] ; i ++ ; } if ( i == n ) break ; if ( curr_num . size ( ) > 0 ) i -- ; res = maximumNum ( curr_num , res ) ; curr_num = " " ; } if ( curr_num . size ( ) == 0 && res . size ( ) == 0 ) res = res + '0' ; return maximumNum ( curr_num , res ) ; } int main ( ) { string str = "100klh564abc365bg " ; cout << extractMaximum ( str ) << endl ; return 0 ; } |
To check divisibility of any large number by 999 | CPP for divisibility of number by 999 ; function to check divisibility ; Append required 0 s at the beginning . ; add digits in group of three in gSum ; group saves 3 - digit group ; calculate result till 3 digit sum ; driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDivisible999 ( string num ) { int n = num . length ( ) ; if ( n == 0 && num [ 0 ] == '0' ) return true ; if ( n % 3 == 1 ) num = "00" + num ; if ( n % 3 == 2 ) num = "0" + num ; int gSum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int group = 0 ; group += ( num [ i ++ ] - '0' ) * 100 ; group += ( num [ i ++ ] - '0' ) * 10 ; group += num [ i ] - '0' ; gSum += group ; } if ( gSum > 1000 ) { num = to_string ( gSum ) ; n = num . length ( ) ; gSum = isDivisible999 ( num ) ; } return ( gSum == 999 ) ; } int main ( ) { string num = "1998" ; int n = num . length ( ) ; if ( isDivisible999 ( num ) ) cout << " Divisible " ; else cout << " Not β divisible " ; return 0 ; } |
Rearrange a string in sorted order followed by the integer sum | C ++ program for above implementation ; Function to return string in lexicographic order followed by integers sum ; Traverse the string ; Count occurrence of uppercase alphabets ; Store sum of integers ; Traverse for all characters A to Z ; Append the current character in the string no . of times it occurs in the given string ; Append the sum of integers ; return resultant string ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; string arrangeString ( string str ) { int char_count [ MAX_CHAR ] = { 0 } ; int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) char_count [ str [ i ] - ' A ' ] ++ ; else sum = sum + ( str [ i ] - '0' ) ; } string res = " " ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { char ch = ( char ) ( ' A ' + i ) ; while ( char_count [ i ] -- ) res = res + ch ; } if ( sum > 0 ) res = res + to_string ( sum ) ; return res ; } int main ( ) { string str = " ACCBA10D2EW30" ; cout << arrangeString ( str ) ; return 0 ; } |
Program to print all substrings of a given string | C ++ program to print all possible substrings of a given string ; Function to print all sub strings ; Pick starting point ; Pick ending point ; Print characters from current starting point to current ending point . ; Driver program to test above function | #include <bits/stdc++.h> NEW_LINE using namespace std ; void subString ( char str [ ] , int n ) { for ( int len = 1 ; len <= n ; len ++ ) { for ( int i = 0 ; i <= n - len ; i ++ ) { int j = i + len - 1 ; for ( int k = i ; k <= j ; k ++ ) cout << str [ k ] ; cout << endl ; } } } int main ( ) { char str [ ] = " abc " ; subString ( str , strlen ( str ) ) ; return 0 ; } |
Reverse a string preserving space positions | C ++ program to reverse a string preserving spaces . ; Function to reverse the string and preserve the space position ; Mark spaces in result ; Traverse input string from beginning and put characters in result from end ; Ignore spaces in input string ; ignore spaces in result . ; Driver code | #include <iostream> NEW_LINE using namespace std ; string reverses ( string str ) { int n = str . size ( ) ; string result ( n , ' \0' ) ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == ' β ' ) result [ i ] = ' β ' ; int j = n - 1 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != ' β ' ) { if ( result [ j ] == ' β ' ) j -- ; result [ j ] = str [ i ] ; j -- ; } } return result ; } int main ( ) { string str = " internship β at β geeks β for β geeks " ; cout << reverses ( str ) << endl ; return 0 ; } |
Find uncommon characters of the two strings | C ++ implementation to find the uncommon characters of the two strings ; size of the hash table ; function to find the uncommon characters of the two strings ; mark presence of each character as 0 in the hash table ' present [ ] ' ; for each character of str1 , mark its presence as 1 in ' present [ ] ' ; for each character of str2 ; if a character of str2 is also present in str1 , then mark its presence as - 1 ; else mark its presence as 2 ; print all the uncommon characters ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 26 ; void findAndPrintUncommonChars ( string str1 , string str2 ) { int present [ MAX_CHAR ] ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) present [ i ] = 0 ; int l1 = str1 . size ( ) ; int l2 = str2 . size ( ) ; for ( int i = 0 ; i < l1 ; i ++ ) present [ str1 [ i ] - ' a ' ] = 1 ; for ( int i = 0 ; i < l2 ; i ++ ) { if ( present [ str2 [ i ] - ' a ' ] == 1 present [ str2 [ i ] - ' a ' ] == -1 ) present [ str2 [ i ] - ' a ' ] = -1 ; else present [ str2 [ i ] - ' a ' ] = 2 ; } for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( present [ i ] == 1 present [ i ] == 2 ) cout << ( char ( i + ' a ' ) ) << " β " ; } int main ( ) { string str1 = " characters " ; string str2 = " alphabets " ; findAndPrintUncommonChars ( str1 , str2 ) ; return 0 ; } |
Length Of Last Word in a String | C ++ program for implementation of simple approach to find length of last word ; String a is ' final ' -- can not be modified So , create a copy and trim the spaces from both sides ; Driver code | #include <bits/stdc++.h> NEW_LINE #include <boost/algorithm/string.hpp> NEW_LINE using namespace std ; int lengthOfLastWord ( string a ) { int len = 0 ; string str ( a ) ; boost :: trim_right ( str ) ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . at ( i ) == ' β ' ) len = 0 ; else len ++ ; } return len ; } int main ( ) { string input = " Geeks β For β Geeks β " ; cout << " The β length β of β last β word β is β " << lengthOfLastWord ( input ) ; } |
Program to count vowels in a string ( Iterative and Recursive ) | C ++ program to count vowels in a string ; Function to check the Vowel ; Returns count of vowels in str ; if ( isVowel ( str [ i ] ) ) Check for vowel ; Main Calling Function ; string object ; Total numbers of Vowel | #include <iostream> NEW_LINE using namespace std ; bool isVowel ( char ch ) { ch = toupper ( ch ) ; return ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) ; } int countVowels ( string str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) ++ count ; return count ; } int main ( ) { string str = " abc β de " ; cout << countVowels ( str ) << endl ; return 0 ; } |
Toggle case of a string using Bitwise Operators | C ++ program to get toggle case of a string ; tOGGLE cASE = swaps CAPS to lower case and lower case to CAPS ; Bitwise EXOR with 32 ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; char * toggleCase ( char * a ) { for ( int i = 0 ; a [ i ] != ' \0' ; i ++ ) { a [ i ] ^= 32 ; } return a ; } int main ( ) { char str [ ] = " CheRrY " ; cout << " Toggle β case : β " << toggleCase ( str ) << endl ; cout << " Original β string : β " << toggleCase ( str ) << endl ; return 0 ; } |
Determine if a string has all Unique Characters | C ++ program to illustrate String with unique characters using set data structure ; Inserting character of string into set ; If length of set is equal to len of string then it will have unique characters ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool uniqueCharacters ( string str ) { set < char > char_set ; for ( char c : str ) { char_set . insert ( c ) ; } if ( char_set . size ( ) == str . size ( ) ) { return true ; } else { return false ; } } int main ( ) { string str = " GeeksforGeeks " ; if ( uniqueCharacters ( str ) ) { cout << " The β String β " << str << " β has β all β unique β characters STRNEWLINE " ; } else { cout << " The β String β " << str << " β has β duplicate β characters STRNEWLINE " ; } return 0 ; } |
Ropes Data Structure ( Fast String Concatenation ) | Simple C ++ program to concatenate two strings ; Function that concatenates strings a [ 0. . n1 - 1 ] and b [ 0. . n2 - 1 ] and stores the result in c [ ] ; Copy characters of A [ ] to C [ ] ; Copy characters of B [ ] ; Driver code ; Concatenate a [ ] and b [ ] and store result in c [ ] | #include <iostream> NEW_LINE using namespace std ; void concatenate ( char a [ ] , char b [ ] , char c [ ] , int n1 , int n2 ) { int i ; for ( i = 0 ; i < n1 ; i ++ ) c [ i ] = a [ i ] ; for ( int j = 0 ; j < n2 ; j ++ ) c [ i ++ ] = b [ j ] ; c [ i ] = ' \0' ; } int main ( ) { char a [ ] = " Hi β This β is β geeksforgeeks . β " ; int n1 = sizeof ( a ) / sizeof ( a [ 0 ] ) ; char b [ ] = " You β are β welcome β here . " ; int n2 = sizeof ( b ) / sizeof ( b [ 0 ] ) ; char c [ n1 + n2 - 1 ] ; concatenate ( a , b , c , n1 , n2 ) ; for ( int i = 0 ; i < n1 + n2 - 1 ; i ++ ) cout << c [ i ] ; return 0 ; } |
Convert characters of a string to opposite case | C ++ program to toggle all characters ; Function to toggle characters ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void toggleChars ( string & S ) { for ( auto & it : S ) { if ( isalpha ( it ) ) { it ^= ( 1 << 5 ) ; } } } int main ( ) { string S = " GeKf @ rGeek $ " ; toggleChars ( S ) ; cout << " String β after β toggle β " << endl ; cout << S << endl ; return 0 ; } |
Binary representation of next greater number with same number of 1 ' s β and β 0' s | C ++ program to find next permutation in a binary string . ; Function to find the next greater number with same number of 1 ' s β and β 0' s ; locate first ' i ' from end such that bnum [ i ] == '0' and bnum [ i + 1 ] == '1' swap these value and break ; ; if no swapping performed ; Since we want the smallest next value , shift all 1 ' s β at β the β end β in β the β binary β β substring β starting β from β index β ' i + 2 ' ; special case while swapping if '0' occurs then break ; required next greater number ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; string nextGreaterWithSameDigits ( string bnum ) { int l = bnum . size ( ) ; int i ; for ( int i = l - 2 ; i >= 1 ; i -- ) { if ( bnum . at ( i ) == '0' && bnum . at ( i + 1 ) == '1' ) { char ch = bnum . at ( i ) ; bnum . at ( i ) = bnum . at ( i + 1 ) ; bnum . at ( i + 1 ) = ch ; break ; } } if ( i == 0 ) " no β greater β number " ; int j = i + 2 , k = l - 1 ; while ( j < k ) { if ( bnum . at ( j ) == '1' && bnum . at ( k ) == '0' ) { char ch = bnum . at ( j ) ; bnum . at ( j ) = bnum . at ( k ) ; bnum . at ( k ) = ch ; j ++ ; k -- ; } else if ( bnum . at ( i ) == '0' ) break ; else j ++ ; } return bnum ; } int main ( ) { string bnum = "10010" ; cout << " Binary β representation β of β next β greater β number β = β " << nextGreaterWithSameDigits ( bnum ) ; return 0 ; } |
Generate all rotations of a given string | A simple C ++ program to generate all rotations of a given string ; Print all the rotated string . ; Generate all rotations one by one and print ; Current index in str ; Current index in temp ; Copying the second part from the point of rotation . ; Copying the first part from the point of rotation . ; Driven Program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printRotatedString ( char str [ ] ) { int len = strlen ( str ) ; char temp [ len ] ; for ( int i = 0 ; i < len ; i ++ ) { int j = i ; int k = 0 ; while ( str [ j ] != ' \0' ) { temp [ k ] = str [ j ] ; k ++ ; j ++ ; } j = 0 ; while ( j < i ) { temp [ k ] = str [ j ] ; j ++ ; k ++ ; } printf ( " % s STRNEWLINE " , temp ) ; } } int main ( ) { char str [ ] = " geeks " ; printRotatedString ( str ) ; return 0 ; } |
All possible strings of any length that can be formed from a given string | C ++ code to generate all possible strings that can be formed from given string ; Number of subsequences is ( 2 * * n - 1 ) ; Generate all subsequences of a given string . using counter 000. . 1 to 111. . 1 ; Check if jth bit in the counter is set If set then print jth element from arr [ ] ; Print all permutations of current subsequence ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; void printAll ( string str ) { int n = str . length ( ) ; unsigned int opsize = pow ( 2 , n ) ; for ( int counter = 1 ; counter < opsize ; counter ++ ) { string subs = " " ; for ( int j = 0 ; j < n ; j ++ ) { if ( counter & ( 1 << j ) ) subs . push_back ( str [ j ] ) ; } do { cout << subs << " β " ; } while ( next_permutation ( subs . begin ( ) , subs . end ( ) ) ) ; } } int main ( ) { string str = " abc " ; printSubsequences ( str ) ; return 0 ; } |
Longest Non | C ++ implementation to find maximum length substring which is not palindrome ; utility function to check whether a string is palindrome or not ; Check for palindrome . ; palindrome string ; function to find maximum length substring which is not palindrome ; to check whether all characters of the string are same or not ; All characters are same , we can 't make a non-palindromic string. ; If string is palindrome , we can make it non - palindrome by removing any corner character ; Complete string is not a palindrome . ; Driver program to test above | #include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int n = str . size ( ) ; for ( int i = 0 ; i < n / 2 ; i ++ ) if ( str . at ( i ) != str . at ( n - i - 1 ) ) return false ; return true ; } int maxLengthNonPalinSubstring ( string str ) { int n = str . size ( ) ; char ch = str . at ( 0 ) ; int i = 1 ; for ( i = 1 ; i < n ; i ++ ) if ( str . at ( i ) != ch ) break ; if ( i == n ) return 0 ; if ( isPalindrome ( str ) ) return n - 1 ; return n ; } int main ( ) { string str = " abba " ; cout << " Maximum β length β = β " << maxLengthNonPalinSubstring ( str ) ; return 0 ; } |
Move spaces to front of string in single traversal | C ++ program to bring all spaces in front of string using swapping technique ; Function to find spaces and move to beginning ; Traverse from end and swap spaces ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void moveSpaceInFront ( char str [ ] ) { int i = strlen ( str ) - 1 ; for ( int j = i ; j >= 0 ; j -- ) if ( str [ j ] != ' β ' ) swap ( str [ i -- ] , str [ j ] ) ; } int main ( ) { char str [ ] = " Hey β there , β it ' s β GeeksforGeeks " ; moveSpaceInFront ( str ) ; cout << str ; return 0 ; } |
Move spaces to front of string in single traversal | CPP program to bring all spaces in front of string using swapping technique ; Function to find spaces and move to beginning ; Keep copying non - space characters ; Move spaces to be beginning ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; void moveSpaceInFront ( char str [ ] ) { int i = strlen ( str ) ; for ( int j = i ; j >= 0 ; j -- ) if ( str [ j ] != ' β ' ) str [ i -- ] = str [ j ] ; while ( i >= 0 ) str [ i -- ] = ' β ' ; } int main ( ) { char str [ ] = " Hey β there , β it ' s β GeeksforGeeks " ; moveSpaceInFront ( str ) ; cout << str ; return 0 ; } |
Minimum number of Appends needed to make a string palindrome | C program to find minimum number of appends needed to make a string Palindrome ; Checking if the string is palindrome or not ; single character is always palindrome ; pointing to first character ; pointing to last character ; Recursive function to count number of appends ; Removing first character of string by incrementing base address pointer . ; Driver program to test above functions | #include <stdio.h> NEW_LINE #include <string.h> NEW_LINE #include <stdbool.h> NEW_LINE bool isPalindrome ( char * str ) { int len = strlen ( str ) ; if ( len == 1 ) return true ; char * ptr1 = str ; char * ptr2 = str + len - 1 ; while ( ptr2 > ptr1 ) { if ( * ptr1 != * ptr2 ) return false ; ptr1 ++ ; ptr2 -- ; } return true ; } int noOfAppends ( char s [ ] ) { if ( isPalindrome ( s ) ) return 0 ; s ++ ; return 1 + noOfAppends ( s ) ; } int main ( ) { char s [ ] = " abede " ; printf ( " % d STRNEWLINE " , noOfAppends ( s ) ) ; return 0 ; } |
Find Excel column number from column title | C ++ program to return title to result of excel sheet . ; Returns resul when we pass title . ; This process is similar to binary - to - decimal conversion ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int titleToNumber ( string s ) { int result = 0 ; for ( const auto & c : s ) { result *= 26 ; result += c - ' A ' + 1 ; } return result ; } int main ( ) { cout << titleToNumber ( " CDA " ) << endl ; return 0 ; } |
Check whether K | CPP program to check if k - th bit of a given number is set or not using right shift operator . ; Driver code | #include <iostream> NEW_LINE using namespace std ; void isKthBitSet ( int n , int k ) { if ( ( n >> ( k - 1 ) ) & 1 ) cout << " SET " ; else cout << " NOT β SET " ; } int main ( ) { int n = 5 , k = 1 ; isKthBitSet ( n , k ) ; return 0 ; } |
Reverse string without using any temporary variable | C ++ Program to reverse a string without using temp variable ; Function to reverse string and return revesed string ; Iterate loop upto start not equal to end ; XOR for swapping the variable ; Driver Code | #include <bits/stdc++.h> NEW_LINE using namespace std ; string reversingString ( string str , int start , int end ) { while ( start < end ) { str [ start ] ^= str [ end ] ; str [ end ] ^= str [ start ] ; str [ start ] ^= str [ end ] ; ++ start ; -- end ; } return str ; } int main ( ) { string s = " GeeksforGeeks " ; cout << reversingString ( s , 0 , 12 ) ; return 0 ; } |
Check if a string follows a ^ nb ^ n pattern or not | C ++ code to check a ^ nb ^ n pattern ; Returns " Yes " str is of the form a ^ nb ^ n . ; check first half is ' a ' and other half is full of ' b ' ; Driver code ; Function call | #include <iostream> NEW_LINE using namespace std ; string isAnBn ( string str ) { int n = str . length ( ) ; if ( n & 1 ) return " No " ; int i ; for ( i = 0 ; i < n / 2 ; i ++ ) if ( str [ i ] != ' a ' str [ n - i - 1 ] != ' b ' ) return " No " ; return " Yes " ; } int main ( ) { string str = " ab " ; cout << isAnBn ( str ) ; return 0 ; } |
Number of substrings divisible by 6 in a string of integers | C ++ program to calculate number of substring divisible by 6. ; Return the number of substring divisible by 6 and starting at index i in s [ ] and previous sum of digits modulo 3 is m . ; End of the string . ; If already calculated , return the stored value . ; Converting into integer . ; Increment result by 1 , if current digit is divisible by 2 and sum of digits is divisible by 3. And recur for next index with new modulo . ; Returns substrings divisible by 6. ; For storing the value of all states . ; If string contain 0 , increment count by 1. ; Else calculate using recursive function . Pass previous sum modulo 3 as 0. ; Driven Program | #include <bits/stdc++.h> NEW_LINE #define MAX 100002 NEW_LINE using namespace std ; int f ( int i , int m , char s [ ] , int memoize [ ] [ 3 ] ) { if ( i == strlen ( s ) ) return 0 ; if ( memoize [ i ] [ m ] != -1 ) return memoize [ i ] [ m ] ; int x = s [ i ] - '0' ; int ans = ( ( x + m ) % 3 == 0 && x % 2 == 0 ) + f ( i + 1 , ( m + x ) % 3 , s , memoize ) ; return memoize [ i ] [ m ] = ans ; } int countDivBy6 ( char s [ ] ) { int n = strlen ( s ) ; int memoize [ n + 1 ] [ 3 ] ; memset ( memoize , -1 , sizeof memoize ) ; int ans = 0 ; for ( int i = 0 ; i < strlen ( s ) ; i ++ ) { if ( s [ i ] == '0' ) ans ++ ; else ans += f ( i , 0 , s , memoize ) ; } return ans ; } int main ( ) { char s [ ] = "4806" ; cout << countDivBy6 ( s ) << endl ; return 0 ; } |
Lexicographically first palindromic string | C ++ program to find first palindromic permutation of given string ; Function to count frequency of each char in the string . freq [ 0 ] for ' a ' , ... . , freq [ 25 ] for ' z ' ; Cases to check whether a palindr0mic string can be formed or not ; count_odd to count no of chars with odd frequency ; For even length string no odd freq character ; For odd length string one odd freq character ; Function to find odd freq char and reducing its freq by 1 returns " " if odd freq char is not present ; To find lexicographically first palindromic string . ; Assigning odd freq character if present else empty string . ; Traverse characters in increasing order ; Divide all occurrences into two halves . Note that odd character is removed by findOddAndRemoveItsFreq ( ) ; creating front string ; creating rear string ; Final palindromic string which is lexicographically first ; Driver program | #include <bits/stdc++.h> NEW_LINE using namespace std ; const char MAX_CHAR = 26 ; void countFreq ( string str , int freq [ ] , int len ) { for ( int i = 0 ; i < len ; i ++ ) freq [ str . at ( i ) - ' a ' ] ++ ; } bool canMakePalindrome ( int freq [ ] , int len ) { int count_odd = 0 ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) if ( freq [ i ] % 2 != 0 ) count_odd ++ ; if ( len % 2 == 0 ) { if ( count_odd > 0 ) return false ; else return true ; } if ( count_odd != 1 ) return false ; return true ; } string findOddAndRemoveItsFreq ( int freq [ ] ) { string odd_str = " " ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { if ( freq [ i ] % 2 != 0 ) { freq [ i ] -- ; odd_str = odd_str + ( char ) ( i + ' a ' ) ; return odd_str ; } } return odd_str ; } string findPalindromicString ( string str ) { int len = str . length ( ) ; int freq [ MAX_CHAR ] = { 0 } ; countFreq ( str , freq , len ) ; if ( ! canMakePalindrome ( freq , len ) ) return " No β Palindromic β String " ; string odd_str = findOddAndRemoveItsFreq ( freq ) ; string front_str = " " , rear_str = " β " ; for ( int i = 0 ; i < MAX_CHAR ; i ++ ) { string temp = " " ; if ( freq [ i ] != 0 ) { char ch = ( char ) ( i + ' a ' ) ; for ( int j = 1 ; j <= freq [ i ] / 2 ; j ++ ) temp = temp + ch ; front_str = front_str + temp ; rear_str = temp + rear_str ; } } return ( front_str + odd_str + rear_str ) ; } int main ( ) { string str = " malayalam " ; cout << findPalindromicString ( str ) ; return 0 ; } |
Count substrings with same first and last characters | C ++ program to count all substrings with same first and last characters . ; Returns true if first and last characters of s are same . ; Starting point of substring ; Length of substring ; Check if current substring has same starting and ending characters . ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int checkEquality ( string s ) { return ( s [ 0 ] == s [ s . size ( ) - 1 ] ) ; } int countSubstringWithEqualEnds ( string s ) { int result = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int len = 1 ; len <= n - i ; len ++ ) if ( checkEquality ( s . substr ( i , len ) ) ) result ++ ; return result ; } int main ( ) { string s ( " abcab " ) ; cout << countSubstringWithEqualEnds ( s ) ; return 0 ; } |
Count substrings with same first and last characters | Space efficient C ++ program to count all substrings with same first and last characters . ; Iterating through all substrings in way so that we can find first and last character easily ; Driver function | #include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstringWithEqualEnds ( string s ) { int result = 0 ; int n = s . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = i ; j < n ; j ++ ) if ( s [ i ] == s [ j ] ) result ++ ; return result ; } int main ( ) { string s ( " abcab " ) ; cout << countSubstringWithEqualEnds ( s ) ; return 0 ; } |
Find the missing number in a string of numbers with no separator | C ++ program to find a missing number in a string of consecutive numbers without any separator . ; gets the integer at position i with length m , returns it or - 1 , if none ; Find value at index i and length m . ; Returns value of missing number ; Try all lengths for first number ; Get value of first number with current length / ; To store missing number of current length ; To indicate whether the sequence failed anywhere for current length . ; Find subsequent numbers with previous number as n ; If we haven 't yet found the missing number for current length. Next number is n+2. Note that we use Log10 as (n+2) may have more length than n. ; If next value is ( n + 1 ) ; return - 1 ; not found or no missing number ; Driver code | #include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_DIGITS = 6 ; int getValue ( const string & str , int i , int m ) { if ( i + m > str . length ( ) ) return -1 ; int value = 0 ; for ( int j = 0 ; j < m ; j ++ ) { int c = str [ i + j ] - '0' ; if ( c < 0 c > 9 ) return -1 ; value = value * 10 + c ; } return value ; } int findMissingNumber ( const string & str ) { for ( int m = 1 ; m <= MAX_DIGITS ; ++ m ) { int n = getValue ( str , 0 , m ) ; if ( n == -1 ) break ; int missingNo = -1 ; bool fail = false ; for ( int i = m ; i != str . length ( ) ; i += 1 + log10l ( n ) ) { if ( ( missingNo == -1 ) && ( getValue ( str , i , 1 + log10l ( n + 2 ) ) == n + 2 ) ) { missingNo = n + 1 ; n += 2 ; } else if ( getValue ( str , i , 1 + log10l ( n + 1 ) ) == n + 1 ) n ++ ; else { fail = true ; break ; } } if ( ! fail ) return missingNo ; } } int main ( ) { cout << findMissingNumber ( "99101102" ) ; return 0 ; } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.