text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Find the winner of game of repeatedly removing the first character to empty given string | C ++ program to implement the above approach ; Function to find the winner of a game of repeatedly removing the first character to empty a string ; Store characters of each string of the array arr [ ] ; Stores count of strings in arr [ ] ; Traverse the array arr [ ] ; Stores length of current string ; Traverse the string ; Insert arr [ i ] [ j ] ; 1 st Player starts the game ; Stores the player number for the next turn ; Remove 1 st character of current string ; Update player number for the next turn ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_Winner ( vector < string > & arr , int N ) { vector < queue < char > > Q ( N ) ; int M = arr . size ( ) ; for ( int i = 0 ; i < M ; i ++ ) { int len = arr [ i ] . length ( ) ; for ( int j = 0 ; j < len ; j ++ ) { Q [ i ] . push ( arr [ i ] [ j ] - 1 ) ; } } int player = 0 ; while ( Q [ player ] . size ( ) > 0 ) { int nextPlayer = Q [ player ] . front ( ) - '0' ; Q [ player ] . pop ( ) ; player = nextPlayer ; } cout << " Player ▁ " << ( player + 1 ) ; } int main ( ) { int N = 3 ; vector < string > arr = { "323" , "2" , "2" } ; find_Winner ( arr , N ) ; return 0 ; }
Longest Substring that can be made a palindrome by swapping of characters | C ++ program for the above approach ; Function to find the Longest substring that can be made a palindrome by swapping of characters ; Initialize dp array of size 1024 ; Initializeing dp array with length of s ; Initializing mask and res ; Traverse the string ; Find the mask of the current character ; Finding the length of the longest substring in s which is a palindrome for even count ; Finding the length of the longest substring in s which is a palindrome for one odd count ; Finding maximum length of substring having one odd count ; dp [ mask ] is minimum of current i and dp [ mask ] ; Return longest length of the substring which forms a palindrome with swaps ; Driver Code ; Input String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestSubstring ( string s ) { int dp [ 1024 ] ; fill ( dp , dp + 1024 , s . size ( ) ) ; int res = 0 , mask = 0 ; dp [ 0 ] = -1 ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { mask ^= 1 << ( s [ i ] - 48 ) ; res = max ( res , i - dp [ mask ] ) ; for ( int j = 0 ; j <= 9 ; ++ j ) res = max ( res , i - dp [ mask ^ ( 1 << j ) ] ) ; dp [ mask ] = min ( dp [ mask ] , i ) ; } return res ; } int main ( ) { string s = "3242415" ; cout << longestSubstring ( s ) ; return 0 ; }
Convert given string to a valid mobile number | C ++ program for the above approach ; Function to print the valid and formatted phone number ; Length of given string ; Store digits in temp ; Iterate given M ; If any digit , append it to temp ; Find new length of string ; If length is not equal to 10 ; Store final result ; Make groups of 3 digits and enclose them within ( ) and separate them with " - " 0 to 2 index 1 st group ; 3 to 5 index 2 nd group ; 6 to 8 index 3 rd group ; 9 to 9 index last group ; Print final result ; Driver Code ; Given string ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Validate ( string M ) { int len = M . size ( ) ; string temp = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( isdigit ( M [ i ] ) ) temp += M [ i ] ; } int nwlen = temp . size ( ) ; if ( nwlen != 10 ) { cout << " Invalid STRNEWLINE " ; return ; } string res = " " ; string x = temp . substr ( 0 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substr ( 3 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substr ( 6 , 3 ) ; res += " ( " + x + " ) - " ; x = temp . substr ( 9 , 1 ) ; res += " ( " + x + " ) " ; cout << res << " STRNEWLINE " ; } int main ( ) { string M = "91 ▁ 234rt5%34*0 ▁ 3" ; Validate ( M ) ; }
Modulus of two Hexadecimal Numbers | C ++ program to implement the above approach ; Function to calculate modulus of two Hexadecimal numbers ; Store all possible hexadecimal digits ; Iterate over the range [ '0' , '9' ] ; Convert given string to long ; Base to get 16 power ; Store N % K ; Iterate over the digits of N ; Stores i - th digit of N ; Update ans ; Update base ; Print the answer converting into hexadecimal ; Driver Code ; Given string N and K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void hexaModK ( string s , string k ) { map < char , int > mp ; for ( char i = 1 ; i <= 9 ; i ++ ) { mp [ i + '0' ] = i ; } mp [ ' A ' ] = 10 ; mp [ ' B ' ] = 11 ; mp [ ' C ' ] = 12 ; mp [ ' D ' ] = 13 ; mp [ ' E ' ] = 14 ; mp [ ' F ' ] = 15 ; long m = stoi ( k , 0 , 16 ) ; long base = 1 ; long ans = 0 ; for ( int i = s . length ( ) - 1 ; i >= 0 ; i -- ) { long n = mp [ s [ i ] ] % m ; ans = ( ans + ( base % m * n % m ) % m ) % m ; base = ( base % m * 16 % m ) % m ; } stringstream ss ; ss << hex << ans ; string su = ss . str ( ) ; transform ( su . begin ( ) , su . end ( ) , su . begin ( ) , :: toupper ) ; cout << ( su ) ; } int main ( ) { string n = "3E8" ; string k = "13" ; hexaModK ( n , k ) ; return 0 ; }
Print all combinations generated by characters of a numeric string which does not exceed N | C ++ program for the above approach ; Store the current sequence of s ; Store the all the required sequences ; Function to print all sequences of S satisfying the required condition ; Print all strings in the set ; Function to generate all sequences of string S that are at most N ; Iterate over string s ; Push ith character to combination ; Convert the string to number ; Check if the condition is true ; Push the current string to the final set of sequences ; Recursively call function ; Backtrack to its previous state ; Driver Code ; Function Call ; Print required sequences
#include <bits/stdc++.h> NEW_LINE using namespace std ; string combination ; set < string > combinations ; void printSequences ( set < string > combinations ) { for ( string s : combinations ) { cout << s << ' ▁ ' ; } } void generateCombinations ( string & s , int n ) { for ( int i = 0 ; i < s . size ( ) ; i ++ ) { combination . push_back ( s [ i ] ) ; long x = stol ( combination ) ; if ( x <= n ) { combinations . insert ( combination ) ; generateCombinations ( s , n ) ; } combination . pop_back ( ) ; } } int main ( ) { string S = "124" ; int N = 100 ; generateCombinations ( S , N ) ; printSequences ( combinations ) ; return 0 ; }
Count Distinct Strings present in an array using Polynomial rolling hash function | C ++ program to implement the above approach ; Function to find the hash value of a string ; Traverse the string ; Update hash_val ; Update mul ; Return hash_val of str ; Function to find the count of distinct strings present in the given array ; Store the hash values of the strings ; Traverse the array ; Stores hash value of arr [ i ] ; Sort hash [ ] array ; Stores count of distinct strings in the array ; Traverse hash [ ] array ; Update cntElem ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long long compute_hash ( string str ) { int p = 31 ; int MOD = 1e9 + 7 ; long long hash_val = 0 ; long long mul = 1 ; for ( char ch : str ) { hash_val = ( hash_val + ( ch - ' a ' + 1 ) * mul ) % MOD ; mul = ( mul * p ) % MOD ; } return hash_val ; } int distinct_str ( vector < string > & arr , int n ) { vector < long long > hash ( n ) ; for ( int i = 0 ; i < n ; i ++ ) { hash [ i ] = compute_hash ( arr [ i ] ) ; } sort ( hash . begin ( ) , hash . end ( ) ) ; int cntElem = 1 ; for ( int i = 1 ; i < n ; i ++ ) { if ( hash [ i ] != hash [ i - 1 ] ) { cntElem ++ ; } } return cntElem ; } int main ( ) { vector < string > arr = { " abcde " , " abcce " , " abcdf " , abcde " } ; int N = arr . size ( ) ; cout << distinct_str ( arr , N ) << endl ; return 0 ; }
Remove characters from given string whose frequencies are a Prime Number | C ++ program for the above approach ; Function to perform the seive of eratosthenes algorithm ; Initialize all entries in prime [ ] as true ; Initialize 0 and 1 as non prime ; Traversing the prime array ; If i is prime ; All multiples of i must be marked false as they are non prime ; Function to remove characters which have prime frequency in the string ; Length of the string ; Create a boolean array prime ; Sieve of Eratosthenes ; Stores the frequency of character ; Storing the frequencies ; New string that will be formed ; Removing the characters which have prime frequencies ; If the character has prime frequency then skip ; Else concatenate the character to the new string ; Print the modified string ; Driver Code ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void SieveOfEratosthenes ( bool * prime , int n ) { for ( int i = 0 ; i <= n ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( int i = 2 ; i * i <= n ; i ++ ) { if ( prime [ i ] == true ) { for ( int j = 2 ; i * j <= n ; j ++ ) { prime [ i * j ] = false ; } } } } void removePrimeFrequencies ( string s ) { int n = s . length ( ) ; bool prime [ n + 1 ] ; SieveOfEratosthenes ( prime , n ) ; unordered_map < char , int > m ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { m [ s [ i ] ] ++ ; } string new_string = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( prime [ m [ s [ i ] ] ] ) continue ; new_string += s [ i ] ; } cout << new_string ; } int main ( ) { string str = " geeksforgeeks " ; removePrimeFrequencies ( str ) ; return 0 ; }
Rearrange string such that no pair of adjacent characters are of the same type | C ++ program to implement the above approach ; Function to rearrange given alphanumeric string such that no two adjacent characters are of the same type ; Stores alphabets and digits ; Store the alphabets and digits separately in the strings ; Stores the count of alphabets and digits ; If respective counts differ by 1 ; Desired arrangement not possible ; Stores the indexes ; Check if first character should be alphabet or digit ; Place alphabets and digits alternatively ; If current character needs to be alphabet ; If current character needs to be a digit ; Flip flag for alternate arrangement ; Return resultant string ; Driver Code ; Given String ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string rearrange ( string s ) { string s1 = " " , s2 = " " ; for ( char x : s ) { isalpha ( x ) ? s1 . push_back ( x ) : s2 . push_back ( x ) ; } int n = s1 . size ( ) ; int m = s2 . size ( ) ; if ( abs ( n - m ) > 1 ) return " - 1" ; int i = 0 , j = 0 , k = 0 ; int flag = ( n >= m ) ? 1 : 0 ; while ( i < n and j < m ) { if ( flag ) s [ k ++ ] = s1 [ i ++ ] ; else s [ k ++ ] = s2 [ j ++ ] ; flag = ! flag ; } return s ; } int main ( ) { string str = " geeks2020" ; cout << rearrange ( str ) << endl ; return 0 ; }
Find value after N operations to remove N characters of string S with given constraints | C ++ program for the above approach ; Function to find the value after N operations to remove all the N characters of string S ; Iterate till N ; Remove character at ind and decrease n ( size of string ) ; Increase count by ind + 1 ; Driver Code ; Given string str ; Function call
#include <iostream> NEW_LINE #include <string> NEW_LINE using namespace std ; void charactersCount ( string str , int n ) { int count = 0 ; while ( n > 0 ) { char cur = str [ 0 ] ; int ind = 0 ; for ( int j = 1 ; j < n ; j ++ ) { if ( str [ j ] < cur ) { cur = str [ j ] ; ind = j ; } } str . erase ( str . begin ( ) + ind ) ; n -- ; count += ind + 1 ; } cout << count << endl ; } int main ( ) { string str = " aabbc " ; int n = 5 ; charactersCount ( str , n ) ; return 0 ; }
Print the middle character of a string | C ++ program to implement the above approach ; Function that prints the middle character of a string ; Finding string length ; Finding middle index of string ; Print the middle character of the string ; Driver Code ; Given string str ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMiddleCharacter ( string str ) { int len = str . size ( ) ; int middle = len / 2 ; cout << str [ middle ] ; } int main ( ) { string str = " GeeksForGeeks " ; printMiddleCharacter ( str ) ; return 0 ; }
Maximize length of the String by concatenating characters from an Array of Strings | C ++ Program to implement the above approach ; Function to check if all the string characters are unique ; Check for repetition in characters ; Function to generate all possible strings from the given array ; Base case ; Consider every string as a starting substring and store the generated string ; Add current string to result of other strings and check if characters are unique or not ; Function to find the maximum possible length of a string ; Return max length possible ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s ) { set < char > a ; for ( auto i : s ) { if ( a . count ( i ) ) return false ; a . insert ( i ) ; } return true ; } vector < string > helper ( vector < string > & arr , int ind ) { if ( ind == arr . size ( ) ) return { " " } ; vector < string > tmp = helper ( arr , ind + 1 ) ; vector < string > ret ( tmp . begin ( ) , tmp . end ( ) ) ; for ( auto i : tmp ) { string test = i + arr [ ind ] ; if ( check ( test ) ) ret . push_back ( test ) ; } return ret ; } int maxLength ( vector < string > & arr ) { vector < string > tmp = helper ( arr , 0 ) ; int len = 0 ; for ( auto i : tmp ) { len = len > i . size ( ) ? len : i . size ( ) ; } return len ; } int main ( ) { vector < string > s ; s . push_back ( " abcdefgh " ) ; cout << maxLength ( s ) ; return 0 ; }
Perform range sum queries on string as per given condition | C ++ program for the above approach ; Function to perform range sum queries on string as per the given condition ; Initialize N by string size ; Create array A [ ] for prefix sum ; Iterate till N ; Traverse the queries ; Check if if L == 1 range sum will be A [ R - 1 ] ; Condition if L > 1 range sum will be A [ R - 1 ] - A [ L - 2 ] ; Driver Code ; Given string ; Given Queries ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void Range_sum_query ( string S , vector < pair < int , int > > Query ) { int N = S . length ( ) ; int A [ N ] ; A [ 0 ] = S [ 0 ] - ' a ' + 1 ; for ( int i = 1 ; i < N ; i ++ ) { A [ i ] = S [ i ] - ' a ' + 1 ; A [ i ] = A [ i ] + A [ i - 1 ] ; } for ( int i = 0 ; i < Query . size ( ) ; i ++ ) { if ( Query [ i ] . first == 1 ) { cout << A [ ( Query [ i ] . second ) - 1 ] << endl ; } else { cout << A [ ( Query [ i ] . second ) - 1 ] - A [ ( Query [ i ] . first ) - 2 ] << endl ; } } } int main ( ) { string S = " abcd " ; vector < pair < int , int > > Query ; Query . push_back ( make_pair ( 2 , 4 ) ) ; Query . push_back ( make_pair ( 1 , 3 ) ) ; Range_sum_query ( S , Query ) ; return 0 ; }
Generate all possible permutations of a Number divisible by N | C ++ Program to implement the above approach ; Function to Swap two characters ; Function to generate all permutations and print the ones that are divisible by the N ; Convert string to integer ; Check for divisibility and print it ; Print all the permutations ; Swap characters ; Permute remaining characters ; Revoke the swaps ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap_ ( char & a , char & b ) { char temp ; temp = a ; a = b ; b = temp ; } void permute ( char * str , int l , int r , int n ) { int i ; if ( l == r ) { int j = atoi ( str ) ; if ( j % n == 0 ) cout << str << endl ; return ; } for ( i = l ; i < r ; i ++ ) { swap_ ( str [ l ] , str [ i ] ) ; permute ( str , l + 1 , r , n ) ; swap_ ( str [ l ] , str [ i ] ) ; } } int main ( ) { char str [ 100 ] = "125" ; int n = 5 ; int len = strlen ( str ) ; if ( len > 0 ) permute ( str , 0 , len , n ) ; return 0 ; }
Check if binary representations of 0 to N are present as substrings in given binary string | C ++ program for the above approach ; Function to convert decimal to binary representation ; Iterate over all bits of N ; If bit is 1 ; Return binary representation ; Function to check if binary conversion of numbers from N to 1 exists in the string as a substring or not ; To store the count of number exists as a substring ; Traverse from N to 1 ; If current number is not present in map ; Store current number ; Find binary of t ; If the string s is a substring of str ; Mark t as true ; Increment the count ; Update for t / 2 ; Special judgment '0' ; If the count is N + 1 , return " yes " ; Driver Code ; Given String ; Given Number ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decimalToBinary ( int N ) { string ans = " " ; while ( N > 0 ) { if ( N & 1 ) { ans = '1' + ans ; } else { ans = '0' + ans ; } N /= 2 ; } return ans ; } string checkBinaryString ( string & str , int N ) { int map [ N + 10 ] , cnt = 0 ; memset ( map , 0 , sizeof ( map ) ) ; for ( int i = N ; i > 0 ; i -- ) { if ( ! map [ i ] ) { int t = i ; string s = decimalToBinary ( t ) ; if ( str . find ( s ) != str . npos ) { while ( t && ! map [ t ] ) { map [ t ] = 1 ; cnt ++ ; t >>= 1 ; } } } } for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == '0' ) { cnt ++ ; break ; } } if ( cnt == N + 1 ) return " True " ; else return " False " ; } int main ( ) { string str = "0110" ; int N = 3 ; cout << checkBinaryString ( str , N ) ; return 0 ; }
Find the word with most anagrams in a given sentence | C ++ Program to find the word with most anagrams in a sentence ; Function to find the word with maximum number of anagrams ; Primes assigned to 26 alphabets ; Stores the product and word mappings ; Stores the frequencies of products ; Calculate the product of primes assigned ; If product already exists ; Otherwise ; Fetch the most frequent product ; Return a string with that product ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string largestAnagramGrp ( vector < string > arr ) { int prime [ ] = { 2 , 3 , 5 , 7 , 11 , 13 , 17 , 19 , 23 , 29 , 31 , 37 , 41 , 43 , 47 , 53 , 59 , 61 , 67 , 71 , 73 , 79 , 83 , 89 , 97 , 101 } ; int max = -1 ; long maxpdt = -1 ; unordered_map < long long , string > W ; unordered_map < long long , long > P ; for ( string temp : arr ) { long pdt = 1 ; for ( char t : temp ) { pdt *= prime [ t - ' a ' ] ; } if ( P . find ( pdt ) != P . end ( ) ) { P [ pdt ] ++ ; } else { W [ pdt ] = temp ; P [ pdt ] = 1 ; } } for ( auto e : P ) { if ( max < e . second ) { max = e . second ; maxpdt = e . first ; } } return W [ maxpdt ] ; } int main ( ) { char S [ ] = " please ▁ be ▁ silent ▁ and ▁ listen ▁ to ▁ what ▁ the ▁ professor ▁ says ▁ " ; vector < string > arr ; char * token = strtok ( S , " ▁ " ) ; while ( token != NULL ) { arr . push_back ( token ) ; token = strtok ( NULL , " ▁ " ) ; } cout << largestAnagramGrp ( arr ) << endl ; return 0 ; }
Replace every vowels with lexicographically next vowel in a String | C ++ program to convert all the vowels in in the string to the next vowel ; Function to replace every vowel with next vowel lexicographically ; Storing the vowels in the map with custom numbers showing their index ; Iterate over the string ; If the current character is a vowel Find the index in Hash and Replace it with next vowel from Hash ; Driver function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string print_next_vovel_string ( string str ) { map < char , int > m ; m [ ' a ' ] = 0 ; m [ ' e ' ] = 1 ; m [ ' i ' ] = 2 ; m [ ' o ' ] = 3 ; m [ ' u ' ] = 4 ; char arr [ 5 ] = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' } ; int N = str . length ( ) ; for ( int i = 0 ; i < N ; i ++ ) { char c = str [ i ] ; if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) { int index = m + 1 ; int newindex = index % 5 ; str [ i ] = arr [ newindex ] ; } } return str ; } int main ( ) { string str = " geeksforgeeks " ; cout << print_next_vovel_string ( str ) ; return 0 ; }
Check if string is palindrome after removing all consecutive duplicates | C ++ program for the above approach ; Function to check if a string is palindrome or not ; Length of the string ; Check if its a palindrome ; If the palindromic condition is not met ; Return true as str is palindromic ; Function to check if string str is palindromic after removing every consecutive characters from the str ; Length of the string str ; Create an empty compressed string ; The first character will always be included in the final string ; Check all the characters of the string ; If the current character is not same as its previous one , then insert it in the final string ; Check if the compressed string is a palindrome ; Driver Code ; Given string ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string str ) { int len = str . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] != str [ len - i - 1 ] ) return false ; } return true ; } bool isCompressablePalindrome ( string str ) { int len = str . length ( ) ; string compressed = " " ; compressed . push_back ( str [ 0 ] ) ; for ( int i = 1 ; i < len ; i ++ ) { if ( str [ i ] != str [ i - 1 ] ) compressed . push_back ( str [ i ] ) ; } return isPalindrome ( compressed ) ; } int main ( ) { string str = " abbcbbbaaa " ; if ( isCompressablePalindrome ( str ) ) cout << " Yes STRNEWLINE " ; else cout << " No STRNEWLINE " ; return 0 ; }
Count of substrings consisting only of vowels | C ++ program to Count all substrings in a string which contains only vowels ; Function to check vowel or not ; Function to Count all substrings in a string which contains only vowels ; Check if current character is vowel ; Increment length of substring ; Calculate possible substrings of calculated length ; Reset the length ; Add remaining possible substrings consisting of vowels occupying last indices of the string ; Driver Program
#include <iostream> NEW_LINE using namespace std ; bool isvowel ( char ch ) { return ( ch == ' a ' or ch == ' e ' or ch == ' i ' or ch == ' o ' or ch == ' u ' ) ; } int CountTotal ( string & s ) { int ans = 0 ; int n = s . length ( ) ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isvowel ( s [ i ] ) ) cnt += 1 ; else { ans += ( cnt * ( cnt + 1 ) / 2 ) ; cnt = 0 ; } } if ( cnt != 0 ) { ans += ( cnt * ( cnt + 1 ) / 2 ) ; } return ans ; } int main ( ) { string s = " geeksforgeeks " ; cout << ( CountTotal ( s ) ) << endl ; return 0 ; }
Number formed by flipping all bits to the left of rightmost set bit | C ++ program to find the integer formed after flipping all bits to the left of the rightmost set bit ; Function to get the total count ; Moving until we get the rightmost set bit ; To get total number of bits in a number ; Function to find the integer formed after flipping all bits to the left of the rightmost set bit ; Find the total count of bits and the rightmost set bit ; XOR given number with the number which has is made up of only totbits set ; To avoid flipping the bits to the right of the set bit , take XOR with the number made up of only set firstbits ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int totCount ; int firstCount ; void getTotCount ( int num ) { totCount = 1 ; firstCount = 1 ; int temp = 1 ; while ( ( num & temp ) == 0 ) { temp = temp << 1 ; totCount += 1 ; } firstCount = totCount ; temp = num >> totCount ; while ( temp != 0 ) { totCount += 1 ; temp = temp >> 1 ; } } int flipBitsFromRightMostSetBit ( int num ) { getTotCount ( num ) ; int num1 = num ^ ( ( 1 << totCount ) - 1 ) ; num1 = num1 ^ ( ( 1 << firstCount ) - 1 ) ; return num1 ; } int main ( ) { int n = 120 ; cout << flipBitsFromRightMostSetBit ( n ) << endl ; return 0 ; }
Longest substring of vowels with no two adjacent alphabets same | C ++ implementation of the above approach ; Function to check a character is vowel or not ; Function to find length of longest substring consisting only of vowels and no similar adjacent alphabets ; Stores max length of valid subString ; Stores length of current valid subString ; If curr and prev character are not same , include it ; If same as prev one , start new subString from here ; Store max in maxLen ; 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 findMaxLen ( string & s ) { int maxLen = 0 ; int cur = 0 ; if ( isvowel ( s [ 0 ] ) ) cur = maxLen = 1 ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( isvowel ( s [ i ] ) ) { if ( s [ i ] != s [ i - 1 ] ) cur += 1 ; else cur = 1 ; } else { cur = 0 ; } maxLen = max ( cur , maxLen ) ; } return maxLen ; } int main ( ) { string Str = " aeoibsddaeiouudb " ; cout << findMaxLen ( Str ) << endl ; return 0 ; }
Count of non | C ++ Program to count non - palindromic strings of length M using N distinct characters ; Iterative Function to calculate base ^ pow in O ( log y ) ; Function to return the count of non palindromic strings ; Count of strings using n characters with repetitions allowed ; Count of palindromic strings ; Count of non - palindromic strings ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unsigned long long power ( unsigned long long base , unsigned long long pow ) { unsigned long long res = 1 ; while ( pow > 0 ) { if ( pow & 1 ) res = ( res * base ) ; base = ( base * base ) ; pow >>= 1 ; } return res ; } unsigned long long countNonPalindromicString ( unsigned long long n , unsigned long long m ) { unsigned long long total = power ( n , m ) ; unsigned long long palindrome = power ( n , m / 2 + m % 2 ) ; unsigned long long count = total - palindrome ; return count ; } int main ( ) { int n = 3 , m = 5 ; cout << countNonPalindromicString ( n , m ) ; return 0 ; }
Count of K | C ++ program for the above approach ; To store the frequency array ; Function to check palindromic of of any substring using frequency array ; Initialise the odd count ; Traversing frequency array to compute the count of characters having odd frequency ; Returns true if odd count is atmost 1 ; Function to count the total number substring whose any permutations are palindromic ; Computing the frequency of first K character of the string ; To store the count of palindromic permutations ; Checking for the current window if it has any palindromic permutation ; Start and end point of window ; Decrementing count of first element of the window ; Incrementing count of next element of the window ; Checking current window character frequency count ; Return the final count ; Driver Code ; Given string str ; Window of size K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > freq ( 26 ) ; bool checkPalindrome ( ) { int oddCnt = 0 ; for ( auto x : freq ) { if ( x % 2 == 1 ) oddCnt ++ ; } return oddCnt <= 1 ; } int countPalindromePermutation ( string s , int k ) { for ( int i = 0 ; i < k ; i ++ ) { freq [ s [ i ] - 97 ] ++ ; } int ans = 0 ; if ( checkPalindrome ( ) ) { ans ++ ; } int i = 0 , j = k ; while ( j < s . size ( ) ) { freq [ s [ i ++ ] - 97 ] -- ; freq [ s [ j ++ ] - 97 ] ++ ; if ( checkPalindrome ( ) ) { ans ++ ; } } return ans ; } int main ( ) { string str = " abbaca " ; int K = 3 ; cout << countPalindromePermutation ( str , K ) << endl ; return 0 ; }
Minimum flips required to form given binary string where every flip changes all bits to its right as well | C ++ program for the above approach ; Function to return the count of minimum flips required ; If curr occurs in the final string ; Switch curr to '0' if '1' or vice - versa ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minFlips ( string target ) { char curr = '1' ; int count = 0 ; for ( int i = 0 ; i < target . length ( ) ; i ++ ) { if ( target [ i ] == curr ) { count ++ ; curr = ( char ) ( 48 + ( curr + 1 ) % 2 ) ; } } return count ; } int main ( ) { string S = "011000" ; cout << ( minFlips ( S ) ) ; }
Check if a number ends with another number or not | C ++ program for the above approach ; Function to check if B is a suffix of A or not ; Find the number of digit in B ; Subtract B from A ; Returns true , if B is a suffix of A ; Driver Code ; Given numbers ; Function Call ; If B is a suffix of A , then print " Yes "
#include <bits/stdc++.h> NEW_LINE #include <boost/algorithm/string.hpp> NEW_LINE using namespace std ; bool checkSuffix ( int A , int B ) { int digit_B = log10 ( B ) + 1 ; A -= B ; return ( A % int ( pow ( 10 , digit_B ) ) ) ; } int main ( ) { int A = 12345 , B = 45 ; bool result = checkSuffix ( A , B ) ; if ( ! result ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }
Minimum length of substring whose rotation generates a palindromic substring | C ++ Program to find the minimum length of substring whose rotation generates a palindromic substring ; Function to return the minimum length of substring ; Store the index of previous occurrence of the character ; Variable to store the maximum length of substring ; If the current character hasn 't appeared yet ; If the character has occured within one or two previous index , a palindromic substring already exists ; Update the maximum ; Replace the previous index of the character by the current index ; If character appeared at least twice ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_min_length ( string s ) { int hash [ 26 ] ; int ans = INT_MAX ; for ( int i = 0 ; i < 26 ; i ++ ) hash [ i ] = -1 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( hash [ s [ i ] - ' a ' ] == -1 ) hash [ s [ i ] - ' a ' ] = i ; else { if ( hash [ s [ i ] - ' a ' ] == i - 1 hash [ s [ i ] - ' a ' ] == i - 2 ) return 0 ; ans = min ( ans , i - hash [ s [ i ] - ' a ' ] - 1 ) ; hash [ s [ i ] - ' a ' ] = i ; } } if ( ans == INT_MAX ) return -1 ; return ans ; } int main ( ) { string str = " abcdeba " ; cout << count_min_length ( str ) ; }
Program to remove HTML tags from a given String | C ++ program for the above approach ; Function to remove the HTML tags from the given string ; Use regex_replace function in regex to erase every tags enclosed in < > ; Print string after removing tags ; Driver Code ; Given String ; Function call to print the HTML string after removing tags
#include <iostream> NEW_LINE #include <regex> NEW_LINE using namespace std ; void RemoveHTMLTags ( string s ) { const regex pattern ( " \\ < . * ? \\ > " ) ; s = regex_replace ( s , pattern , " " ) ; cout << s ; return ; } int main ( ) { string str = " < div > < b > Geeks ▁ for ▁ Geeks < / b > < / div > " ; RemoveHTMLTags ( str ) ; return 0 ; }
Score of Parentheses using Tree | C ++ program to find the score of parentheses using Tree ; Customized tree class or struct , contains all required methods . ; Function to add a child into the list of children ; Function to change the parent pointer to the node passed ; Function to return the parent of the current node ; Function to compute the score recursively . ; Base case ; Adds scores of all children ; Function to create the tree structure ; Creating a node for every " ( ) " ; If we find " ( " we add a node as a child ; On finding " ) " which confirms that a pair is closed , we go back to the parent ; Driver code ; Generating the tree ; Computing the score
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; class TreeNode { TreeNode * parent = NULL ; vector < TreeNode * > children ; public : void addChild ( TreeNode * node ) { children . push_back ( node ) ; } void setParent ( TreeNode * node ) { parent = node ; } TreeNode * getParent ( ) { return parent ; } int computeScore ( ) { if ( children . size ( ) == 0 ) return 1 ; int res = 0 ; for ( TreeNode * curr : children ) res += curr -> computeScore ( ) ; if ( parent == NULL ) return res ; else return 2 * res ; } } ; TreeNode * computeTree ( string s ) { TreeNode * current = new TreeNode ( ) ; TreeNode * root = current ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] == ' ( ' ) { TreeNode * child = new TreeNode ( ) ; child -> setParent ( current ) ; current -> addChild ( child ) ; current = child ; } else { current = current -> getParent ( ) ; } } return root ; } int main ( ) { string s = " ( ( ) ( ( ) ) ) " ; TreeNode * root = computeTree ( s ) ; cout << root -> computeScore ( ) ; return 0 ; }
Move all occurrence of letter ' x ' from the string s to the end using Recursion | C ++ program for above approach ; Recursive program to bring ' x ' to the end ; When the string is completed from reverse direction end of recursion ; If the character x is found ; Transverse the whole string ; Swap the x so that it moves to the last ; call to the smaller problem now ; Driver Code ; Size of a ; Call to rec
#include <bits/stdc++.h> NEW_LINE using namespace std ; void rec ( char * a , int i ) { if ( i == 0 ) { cout << a << endl ; return ; } if ( a [ i ] == ' x ' ) { int j = i ; while ( a [ j ] != ' \0' && a [ j + 1 ] != ' \0' ) { swap ( a [ j ] , a [ j + 1 ] ) ; j ++ ; } } rec ( a , i - 1 ) ; } int main ( ) { char a [ ] = { ' g ' , ' e ' , ' e ' , ' k ' , ' x ' , ' s ' , ' x ' , ' x ' , ' k ' , ' s ' , ' \0' } ; int n = 10 ; rec ( a , n - 1 ) ; }
Generate a string of size N whose each substring of size M has exactly K distinct characters | C ++ program to generate a string of size N whose each substring of size M has exactly K distinct characters ; Function to generate the string ; Declare empty string ; counter for M ; counter for K ; Loop to generate string size of N ; Generating K distinct letters one by one ; After generating b distinct letters , append rest a - b letters as ' a ' ; Reset the counter value and repeat the process ; return final result string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string generateString ( int N , int M , int K ) { string s = " " ; int cnt1 = 0 ; int cnt2 = 0 ; for ( int i = 0 ; i < N ; i ++ ) { cnt1 ++ ; cnt2 ++ ; if ( cnt1 <= M ) { if ( cnt2 <= K ) { s = s + char ( 96 + cnt1 ) ; } else { s = s + ' a ' ; } } else { cnt1 = 1 ; cnt2 = 1 ; s = s + ' a ' ; } } return s ; } int main ( ) { int N = 7 , M = 5 , K = 3 ; cout << generateString ( N , M , K ) << endl ; return 0 ; }
Print string after removing all ( β€œ 10 ” or β€œ 01 ” ) from the binary string | C ++ program to print the final string after removing all the occurrences of "10" and "01" from the given binary string ; Function to print the final string after removing all the occurrences of "10" and "01" from the given binary string ; Variables to store the count of 1 ' s ▁ and ▁ 0' s ; Variable left will store whether 0 ' s ▁ or ▁ 1' s is left in the final string ; Length of the string ; For loop to count the occurrences of 1 ' s ▁ and ▁ 0' s in the string ; To check if the count of 1 ' s ▁ is ▁ ▁ greater ▁ than ▁ the ▁ count ▁ of ▁ 0' s or not . If x is greater , then those many 1 's are printed. ; Length of the final remaining string after removing all the occurrences ; Printing the final string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void finalString ( string str ) { int x = 0 , y = 0 ; int left ; int n = str . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '1' ) x ++ ; else y ++ ; } if ( x > y ) left = 1 ; else left = 0 ; int length = n - 2 * min ( x , y ) ; for ( int i = 0 ; i < length ; i ++ ) { cout << left ; } } int main ( ) { string str = "010110100100000" ; finalString ( str ) ; return 0 ; }
Longest palindrome formed by concatenating and reordering strings of equal length | C ++ program to find the Longest palindrome that can be formed by concatenating and reordering given N strings of equal length ; Function to print the longest palindrome ; Printing every string in left vector ; Printing the palindromic string in the middle ; Printing the reverse of the right vector to make the final output palindromic ; Function to find and print the longest palindrome that can be formed ; Inserting each string in the set ; Vectors to add the strings in the left and right side ; To add the already present palindrome string in the middle of the solution ; Iterating through all the given strings ; If the string is a palindrome it is added in the middle ; Checking if the reverse of the string is already present in the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPalindrome ( vector < string > left , string mid , vector < string > right ) { for ( string x : left ) cout << x ; cout << mid ; reverse ( right . begin ( ) , right . end ( ) ) ; for ( string x : right ) cout << x ; cout << endl ; } void findPalindrome ( vector < string > & S , int N , int M ) { set < string > dict ; for ( int i = 0 ; i < M ; i ++ ) { cin >> S [ i ] ; dict . insert ( S [ i ] ) ; } vector < string > left , right ; string mid ; for ( int i = 0 ; i < N ; i ++ ) { string t = S [ i ] ; reverse ( t . begin ( ) , t . end ( ) ) ; if ( t == S [ i ] ) mid = t ; else if ( dict . find ( t ) != dict . end ( ) ) { left . push_back ( S [ i ] ) ; right . push_back ( t ) ; dict . erase ( S [ i ] ) ; dict . erase ( t ) ; } } printPalindrome ( left , mid , right ) ; } int main ( ) { vector < string > S { " tab " , " one " , " bat " } ; int M = 3 ; int N = S . size ( ) ; findPalindrome ( S , N , M ) ; }
Lexicographically smaller string by swapping at most one character pair | C ++ program check whether is it possible to make string A lexicographically smaller than string B ; Swap function ; Function that finds whether is it possible to make string A lexicographically smaller than string B ; Condition if string A is already smaller than B ; Sorting temp string ; Condition for first changed character of string A and temp ; Condition if string A is already sorted ; Finding first changed character from last of string A ; Swap the two characters ; Condition if string A is smaller than B ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void swap ( char & x , char & y ) { char temp = x ; x = y ; y = temp ; } bool IsLexicographicallySmaller ( string A , string B ) { if ( A < B ) { return true ; } string temp = A ; sort ( temp . begin ( ) , temp . end ( ) ) ; int index = -1 ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A [ i ] != temp [ i ] ) { index = i ; break ; } } if ( index == -1 ) { return false ; } int j ; for ( int i = 0 ; i < A . length ( ) ; i ++ ) { if ( A [ i ] == temp [ index ] ) j = i ; } swap ( A [ index ] , A [ j ] ) ; if ( A < B ) { return true ; } else { return false ; } } int main ( ) { string A = " AGAIN " ; string B = " ACTION " ; if ( IsLexicographicallySmaller ( A , B ) ) { cout << " Yes " << " STRNEWLINE " ; } else { cout << " No " << " STRNEWLINE " ; } return 0 ; }
Length of longest palindromic sub | C ++ implementation to find the length of longest palindromic sub - string using Recursion ; Function to find maximum of the two variables ; Function to find the longest palindromic substring : Recursion ; Base condition when the start index is greater than end index ; Base condition when both the start and end index are equal ; Condition when corner characters are equal in the string ; Recursive call to find the longest Palindromic string by excluding the corner characters ; Recursive call to find the longest Palindromic string by including one corner character at a time ; Function to find the longest palindromic sub - string ; Utility function call ; Driver Code ; Function Call
#include <iostream> NEW_LINE using namespace std ; int max ( int x , int y ) { return ( x > y ) ? x : y ; } int longestPalindromic ( string str , int i , int j , int count ) { if ( i > j ) return count ; if ( i == j ) return ( count + 1 ) ; if ( str [ i ] == str [ j ] ) { count = longestPalindromic ( str , i + 1 , j - 1 , count + 2 ) ; return max ( count , max ( longestPalindromic ( str , i + 1 , j , 0 ) , longestPalindromic ( str , i , j - 1 , 0 ) ) ) ; } return max ( longestPalindromic ( str , i + 1 , j , 0 ) , longestPalindromic ( str , i , j - 1 , 0 ) ) ; } int longest_palindromic_substr ( string str ) { return longestPalindromic ( str , 0 , str . length ( ) - 1 , 0 ) ; } int main ( ) { string str = " aaaabbaa " ; cout << longest_palindromic_substr ( str ) ; return 0 ; }
Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency | C ++ implementation to find the prefix of the s such that occurrence of each character is atmost the count of minimum frequency in the s ; Function to find the maximum possible prefix of the s ; Hash map to store the frequency of the characters in the s ; Iterate over the s to find the occurence of each Character ; Minimum frequency of the Characters ; Loop to find the count of minimum frequency in the hash - map ; Loop to find the maximum possible length of the prefix in the s ; Condition to check if the frequency is greater than minimum possible freq ; maxprefix s and its length . ; Driver code ; s is initialize . ; str is passed in MaxPrefix function .
#include <bits/stdc++.h> NEW_LINE using namespace std ; void MaxPrefix ( string s ) { map < char , int > Dict ; for ( char i : s ) { Dict [ i ] ++ ; } int minfrequency = INT_MAX ; for ( auto x : Dict ) { minfrequency = min ( minfrequency , x . second ) ; } int countminFrequency = 0 ; for ( auto x : Dict ) { if ( x . second == minfrequency ) countminFrequency += 1 ; } map < char , int > mapper ; int indi = 0 ; for ( char i : s ) { mapper [ i ] += 1 ; if ( mapper [ i ] > countminFrequency ) break ; indi += 1 ; } cout << ( s . substr ( 0 , indi ) ) ; } int main ( ) { string str = " aabcdaab " ; MaxPrefix ( str ) ; }
Count of Substrings that can be formed without using the given list of Characters | C ++ implementation of the above approach ; Function to find the Number of sub - strings without using given character ; Mark the given characters in the freq array ; Count variable to store the count of the characters until a character from given L is encountered ; If a character from L is encountered , then the answer variable is incremented by the value obtained by using the mentioned formula and count is set to 0 ; For last remaining characters ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstring ( string & S , char L [ ] , int & n ) { int freq [ 26 ] = { 0 } , ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { freq [ ( int ) ( L [ i ] - ' a ' ) ] = 1 ; } int count = 0 ; for ( auto x : S ) { if ( freq [ ( int ) ( x - ' a ' ) ] ) { ans += ( count * count + count ) / 2 ; count = 0 ; } else count ++ ; } ans += ( count * count + count ) / 2 ; return ans ; } int main ( ) { string S = " abcpxyz " ; char L [ ] = { ' a ' , ' p ' , ' q ' } ; int n = sizeof ( L ) / sizeof ( L [ 0 ] ) ; cout << countSubstring ( S , L , n ) ; return 0 ; }
Program to accept Strings starting with a Vowel | C ++ program to accept String starting with Vowel ; Function to check if first character is vowel ; Function to check ; Driver function
#include <iostream> NEW_LINE using namespace std ; int checkIfStartsWithVowels ( string str ) { if ( ! ( str [ 0 ] == ' A ' str [ 0 ] == ' a ' str [ 0 ] == ' E ' str [ 0 ] == ' e ' str [ 0 ] == ' I ' str [ 0 ] == ' i ' str [ 0 ] == ' O ' str [ 0 ] == ' o ' str [ 0 ] == ' U ' str [ 0 ] == ' u ' ) ) return 1 ; else return 0 ; } void check ( string str ) { if ( checkIfStartsWithVowels ( str ) ) cout << " Not ▁ Accepted STRNEWLINE " ; else cout << " Accepted STRNEWLINE " ; } int main ( ) { string str = " animal " ; check ( str ) ; str = " zebra " ; check ( str ) ; return 0 ; }
Find the Nth occurrence of a character in the given String | C ++ implementation to find the Nth occurrence of a character ; Function to find the Nth occurrence of a character ; Loop to find the Nth occurrence of the character ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findNthOccur ( string str , char ch , int N ) { int occur = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ch ) { occur += 1 ; } if ( occur == N ) return i ; } return -1 ; } int main ( ) { string str = " geeks " ; char ch = ' e ' ; int N = 2 ; cout << findNthOccur ( str , ch , N ) ; }
Longest equal substring with cost less than K | C ++ program to find the maximum length of equal substring within a given cost ; Function to find the maximum length ; Fill the prefix array with the difference of letters ; Update the maximum length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( string X , string Y , int N , int K ) { int count [ N + 1 ] = { 0 } ; int sol = 0 ; count [ 0 ] = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { count [ i ] = count [ i - 1 ] + abs ( X [ i - 1 ] - Y [ i - 1 ] ) ; } int j = 0 ; for ( int i = 1 ; i <= N ; i ++ ) { while ( ( count [ i ] - count [ j ] ) > K ) { j ++ ; } sol = max ( sol , i - j ) ; } return sol ; } int main ( ) { int N = 4 ; string X = " abcd " , Y = " bcde " ; int K = 3 ; cout << solve ( X , Y , N , K ) << " STRNEWLINE " ; return 0 ; }
Jaro and Jaro | C ++ implementation of above approach ; Function to calculate the Jaro Similarity of two strings ; If the strings are equal ; Length of two strings ; Maximum distance upto which matching is allowed ; Count of matches ; Hash for matches ; Traverse through the first string ; Check if there is any matches ; If there is a match ; If there is no match ; Number of transpositions ; Count number of occurrences where two characters match but there is a third matched character in between the indices ; Find the next matched character in second string ; Return the Jaro Similarity ; Jaro Winkler Similarity ; If the jaro Similarity is above a threshold ; Find the length of common prefix ; If the characters match ; Else break ; Maximum of 4 characters are allowed in prefix ; Calculate jaro winkler Similarity ; Driver code ; Print Jaro - Winkler Similarity of two strings
#include <bits/stdc++.h> NEW_LINE using namespace std ; double jaro_distance ( string s1 , string s2 ) { if ( s1 == s2 ) return 1.0 ; int len1 = s1 . length ( ) , len2 = s2 . length ( ) ; if ( len1 == 0 len2 == 0 ) return 0.0 ; int max_dist = floor ( max ( len1 , len2 ) / 2 ) - 1 ; int match = 0 ; int hash_s1 [ s1 . length ( ) ] = { 0 } , hash_s2 [ s2 . length ( ) ] = { 0 } ; for ( int i = 0 ; i < len1 ; i ++ ) { for ( int j = max ( 0 , i - max_dist ) ; j < min ( len2 , i + max_dist + 1 ) ; j ++ ) if ( s1 [ i ] == s2 [ j ] && hash_s2 [ j ] == 0 ) { hash_s1 [ i ] = 1 ; hash_s2 [ j ] = 1 ; match ++ ; break ; } } if ( match == 0 ) return 0.0 ; double t = 0 ; int point = 0 ; for ( int i = 0 ; i < len1 ; i ++ ) if ( hash_s1 [ i ] ) { while ( hash_s2 [ point ] == 0 ) point ++ ; if ( s1 [ i ] != s2 [ point ++ ] ) t ++ ; } t /= 2 ; return ( ( ( double ) match ) / ( ( double ) len1 ) + ( ( double ) match ) / ( ( double ) len2 ) + ( ( double ) match - t ) / ( ( double ) match ) ) / 3.0 ; } double jaro_Winkler ( string s1 , string s2 ) { double jaro_dist = jaro_distance ( s1 , s2 ) ; if ( jaro_dist > 0.7 ) { int prefix = 0 ; for ( int i = 0 ; i < min ( s1 . length ( ) , s2 . length ( ) ) ; i ++ ) { if ( s1 [ i ] == s2 [ i ] ) prefix ++ ; else break ; } prefix = min ( 4 , prefix ) ; jaro_dist += 0.1 * prefix * ( 1 - jaro_dist ) ; } return jaro_dist ; } int main ( ) { string s1 = " TRATE " , s2 = " TRACE " ; cout << " Jaro - Winkler ▁ Similarity ▁ = " << jaro_Winkler ( s1 , s2 ) << endl ; return 0 ; }
Check if a word is present in a sentence | C ++ implementation of the approach ; Function that returns true if the word is found ; To break the sentence in words ; To temporarily store each individual word ; Comparing the current word with the word to be searched ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isWordPresent ( string sentence , string word ) { stringstream s ( sentence ) ; string temp ; while ( s >> temp ) { if ( temp . compare ( word ) == 0 ) { return true ; } } return false ; } int main ( ) { string s = " Geeks ▁ for ▁ Geeks " ; string word = " Geeks " ; if ( isWordPresent ( s , word ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Check if a word is present in a sentence | C ++ implementation of the approach ; Function that returns true if the word is found ; To convert the word in uppercase ; To convert the complete sentence in uppercase ; To break the sentence in words ; To store the individual words of the sentence ; Compare the current word with the word to be searched ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isWordPresent ( string sentence , string word ) { transform ( word . begin ( ) , word . end ( ) , word . begin ( ) , :: toupper ) ; transform ( sentence . begin ( ) , sentence . end ( ) , sentence . begin ( ) , :: toupper ) ; stringstream s ( sentence ) ; string temp ; while ( s >> temp ) { if ( temp . compare ( word ) == 0 ) { return true ; } } return false ; } int main ( ) { string s = " Geeks ▁ for ▁ Geeks " ; string word = " geeks " ; if ( isWordPresent ( s , word ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of 1 | C ++ implementation of the approach ; Function to return the count of required characters ; While there are characters left ; Single bit character ; Two - bit character ; Update the count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countChars ( string str , int n ) { int i = 0 , cnt = 0 ; while ( i < n ) { if ( str [ i ] == '0' ) i ++ ; else i += 2 ; cnt ++ ; } return cnt ; } int main ( ) { string str = "11010" ; int n = str . length ( ) ; cout << countChars ( str , n ) ; return 0 ; }
Print the frequency of each character in Alphabetical order | C ++ implementation of the approach ; Function to print the frequency of each of the characters of s in alphabetical order ; To store the frequency of the characters ; Update the frequency array ; Print the frequency in alphatecial order ; If the current alphabet doesn 't appear in the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; void compressString ( string s , int n ) { int freq [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] == 0 ) continue ; cout << ( char ) ( i + ' a ' ) << freq [ i ] ; } } int main ( ) { string s = " geeksforgeeks " ; int n = s . length ( ) ; compressString ( s , n ) ; return 0 ; }
Find the number obtained after concatenation of binary representation of M and N | C ++ implementation of the approach ; Function to convert decimal number n to its binary representation stored as an array arr [ ] ; Funtion to convert the number represented as a binary array arr [ ] into its decimal equivalent ; Function to concatenate the binary numbers and return the decimal result ; Number of bits in both the numbers ; Convert the bits in both the integers to the arrays a [ ] and b [ ] ; c [ ] will be the binary array for the result ; Update the c [ ] array ; Return the decimal equivalent of the result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void decBinary ( int arr [ ] , int n ) { int k = log2 ( n ) ; while ( n > 0 ) { arr [ k -- ] = n % 2 ; n /= 2 ; } } int binaryDec ( int arr [ ] , int n ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) ans += arr [ i ] << ( n - i - 1 ) ; return ans ; } int concat ( int m , int n ) { int k = log2 ( m ) + 1 ; int l = log2 ( n ) + 1 ; int a [ k ] = { 0 } , b [ l ] = { 0 } ; int c [ k + l ] = { 0 } ; decBinary ( a , m ) ; decBinary ( b , n ) ; int in = 0 ; for ( int i = 0 ; i < k ; i ++ ) c [ in ++ ] = a [ i ] ; for ( int i = 0 ; i < l ; i ++ ) c [ in ++ ] = b [ i ] ; return ( binaryDec ( c , k + l ) ) ; } int main ( ) { int m = 4 , n = 5 ; cout << concat ( m , n ) ; return 0 ; }
Find the number obtained after concatenation of binary representation of M and N | C ++ implementation of the approach ; Utility function to calculate binary length of a number . ; Function to concatenate the binary numbers and return the decimal result ; find binary length of n ; left binary shift m and then add n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getBinaryLength ( int n ) { int length = 0 ; while ( n > 0 ) { length += 1 ; n /= 2 ; } return length ; } int concat ( int m , int n ) { int length = getBinaryLength ( n ) ; return ( m << length ) + n ; } int main ( ) { int m = 4 , n = 5 ; cout << concat ( m , n ) ; return 0 ; }
XOR two binary strings of unequal lengths | C ++ implementation of the approach ; Function to insert n 0 s in the beginning of the given string ; Function to return the XOR of the given strings ; Lengths of the given strings ; Make both the strings of equal lengths by inserting 0 s in the beginning ; Updated length ; To store the resultant XOR ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void addZeros ( string & str , int n ) { for ( int i = 0 ; i < n ; i ++ ) { str = "0" + str ; } } string getXOR ( string a , string b ) { int aLen = a . length ( ) ; int bLen = b . length ( ) ; if ( aLen > bLen ) { addZeros ( b , aLen - bLen ) ; } else if ( bLen > aLen ) { addZeros ( a , bLen - aLen ) ; } int len = max ( aLen , bLen ) ; string res = " " ; for ( int i = 0 ; i < len ; i ++ ) { if ( a [ i ] == b [ i ] ) res += "0" ; else res += "1" ; } return res ; } int main ( ) { string a = "11001" , b = "111111" ; cout << getXOR ( a , b ) ; return 0 ; }
Generate Binary Strings of length N using Branch and Bound | CPP Program to generate Binary Strings using Branch and Bound ; Creating a Node class ; Queue that maintains the list of live Nodes ; Utility function to generate binary strings of length n ; If list is full print combination ; Create a new vector for new combination ; iterate while length is not equal to n ; Driver Code ; Initiate Generation Create a root Node ; Instantiate the Queue
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int * soln ; int level ; vector < Node * > child ; Node * parent ; Node ( Node * parent , int level , int N ) { this -> parent = parent ; this -> level = level ; this -> soln = new int [ N ] ; } } ; queue < Node * > Q ; void generate ( Node * n , int & N , queue < Node * > & Q ) { if ( n -> level == N ) { for ( int i = 0 ; i < N ; i ++ ) cout << n -> soln [ i ] ; cout << endl ; } else { int l = n -> level ; for ( int i = 0 ; i <= 1 ; i ++ ) { Node * x = new Node ( n , l + 1 , N ) ; for ( int k = 0 ; k < l ; k ++ ) x -> soln [ k ] = n -> soln [ k ] ; x -> soln [ l ] = i ; n -> child . push_back ( x ) ; Q . push ( x ) ; } } } int main ( ) { int N = 3 ; Node * root ; root = new Node ( NULL , 0 , N ) ; Q . push ( root ) ; while ( ! Q . empty ( ) ) { Node * E = Q . front ( ) ; Q . pop ( ) ; generate ( E , N , Q ) ; } return 0 ; }
Minimum operations required to make the string satisfy the given condition | C ++ implementation of the approach ; Function to return the minimum operations required ; To store the first and the last occurrence of all the characters ; Set the first and the last occurrence of all the characters to - 1 ; Update the occurrences of the characters ; Only set the first occurrence if it hasn 't already been set ; To store the minimum operations ; If the frequency of the current character in the string is less than 2 ; Count of characters to be removed so that the string starts and ends at the current character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 26 ; int minOperation ( string str , int len ) { int first [ MAX ] , last [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { first [ i ] = -1 ; last [ i ] = -1 ; } for ( int i = 0 ; i < len ; i ++ ) { int index = ( str [ i ] - ' a ' ) ; if ( first [ index ] == -1 ) first [ index ] = i ; last [ index ] = i ; } int minOp = -1 ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( first [ i ] == -1 first [ i ] == last [ i ] ) continue ; int cnt = len - ( last [ i ] - first [ i ] + 1 ) ; if ( minOp == -1 cnt < minOp ) minOp = cnt ; } return minOp ; } int main ( ) { string str = " abcda " ; int len = str . length ( ) ; cout << minOperation ( str , len ) ; return 0 ; }
Queries to find the count of vowels in the substrings of the given string | C ++ implementation of the approach ; Function that returns true if ch is a vowel ; Function to return the count of vowels in the substring str [ l ... r ] ; To store the count of vowels ; For every character in the index range [ l , r ] ; If the current character is a vowel ; For every query ; Find the count of vowels for the current query ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 2 NEW_LINE bool isVowel ( char ch ) { return ( ch == ' a ' ch == ' e ' ch == ' i ' ch == ' o ' ch == ' u ' ) ; } int countVowels ( string str , int l , int r ) { int cnt = 0 ; for ( int i = l ; i <= r ; i ++ ) { if ( isVowel ( str [ i ] ) ) cnt ++ ; } return cnt ; } void performQueries ( string str , int queries [ ] [ N ] , int q ) { for ( int i = 0 ; i < q ; i ++ ) { cout << countVowels ( str , queries [ i ] [ 0 ] , queries [ i ] [ 1 ] ) << " STRNEWLINE " ; } } int main ( ) { string str = " geeksforgeeks " ; int queries [ ] [ N ] = { { 1 , 3 } , { 2 , 4 } , { 1 , 9 } } ; int q = ( sizeof ( queries ) / sizeof ( queries [ 0 ] ) ) ; performQueries ( str , queries , q ) ; return 0 ; }
Convert a String to a Singly Linked List | C ++ program to Convert a String to a Singly Linked List ; Structure for a Singly Linked List ; Function to add a new node to the Linked List ; Function to convert the string to Linked List . ; curr pointer points to the current node where the insertion should take place ; Function to print the data present in all the nodes ; Driver code
#include <iostream> NEW_LINE using namespace std ; struct node { char data ; node * next ; } ; node * add ( char data ) { node * newnode = new node ; newnode -> data = data ; newnode -> next = NULL ; return newnode ; } node * string_to_SLL ( string text , node * head ) { head = add ( text [ 0 ] ) ; node * curr = head ; for ( int i = 1 ; i < text . size ( ) ; i ++ ) { curr -> next = add ( text [ i ] ) ; curr = curr -> next ; } return head ; } void print ( node * head ) { node * curr = head ; while ( curr != NULL ) { cout << curr -> data << " ▁ - > ▁ " ; curr = curr -> next ; } } int main ( ) { string text = " GEEKS " ; node * head = NULL ; head = string_to_SLL ( text , head ) ; print ( head ) ; return 0 ; }
Reduce the string to minimum length with the given operation | C ++ implementation of the approach ; Function to return the minimum possible length str can be reduced to with the given operation ; Stack to store the characters of the given string ; For every character of the string ; If the stack is empty then push the current character in the stack ; Get the top character ; If the top element is not equal to the current element and it only differs in the case ; Pop the top element from stack ; Else push the current element ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLength ( string str , int len ) { stack < char > s ; for ( int i = 0 ; i < len ; i ++ ) { if ( s . empty ( ) ) { s . push ( str [ i ] ) ; } else { char c = s . top ( ) ; if ( c != str [ i ] && toupper ( c ) == toupper ( str [ i ] ) ) { s . pop ( ) ; } else { s . push ( str [ i ] ) ; } } } return s . size ( ) ; } int main ( ) { string str = " ASbBsd " ; int len = str . length ( ) ; cout << minLength ( str , len ) ; return 0 ; }
Check whether two strings can be made equal by copying their characters with the adjacent ones | C ++ implementation of the approach ; Function that returns true if both the strings can be made equal with the given operation ; Lengths of both the strings have to be equal ; To store the frequency of the characters of str1 ; For every character of str2 ; If current character of str2 also appears in str1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE bool canBeMadeEqual ( string str1 , string str2 ) { int len1 = str1 . length ( ) ; int len2 = str2 . length ( ) ; if ( len1 == len2 ) { int freq [ MAX ] ; for ( int i = 0 ; i < len1 ; i ++ ) { freq [ str1 [ i ] - ' a ' ] ++ ; } for ( int i = 0 ; i < len2 ; i ++ ) { if ( freq [ str2 [ i ] - ' a ' ] > 0 ) return true ; } } return false ; } int main ( ) { string str1 = " abc " , str2 = " defa " ; if ( canBeMadeEqual ( str1 , str2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Minimum characters that are to be inserted such that no three consecutive characters are same | C ++ implementation of the approach ; Function to return the count of characters that are to be inserted in str such that no three consecutive characters are same ; To store the count of operations required ; A character needs to be inserted after str [ i + 1 ] ; Current three consecutive characters are not same ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getCount ( string str , int n ) { int cnt = 0 ; int i = 0 ; while ( i < n - 2 ) { if ( str [ i ] == str [ i + 1 ] && str [ i ] == str [ i + 2 ] ) { cnt ++ ; i = i + 2 ; } else i ++ ; } return cnt ; } int main ( ) { string str = " aabbbcc " ; int n = str . length ( ) ; cout << getCount ( str , n ) ; return 0 ; }
Find the number of strings formed using distinct characters of a given string | C ++ implementation of the approach ; Function to return the factorial of n ; Function to return the count of all possible strings that can be formed with the characters of the given string without repeating characters ; To store the distinct characters of the string str ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int fact ( int n ) { int fact = 1 ; for ( int i = 1 ; i <= n ; i ++ ) fact *= i ; return fact ; } int countStrings ( string str , int n ) { set < char > distinct_char ; for ( int i = 0 ; i < n ; i ++ ) { distinct_char . insert ( str [ i ] ) ; } return fact ( distinct_char . size ( ) ) ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . length ( ) ; cout << countStrings ( str , n ) ; return 0 ; }
Find the character made by adding all the characters of the given string | C ++ implementation of the approach ; Function to return the required character ; To store the sum of the characters of the given string ; Add the current character to the sum ; Return the required character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char getChar ( string str ) { int sum = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { sum += ( str [ i ] - ' a ' + 1 ) ; } if ( sum % 26 == 0 ) return ' z ' ; else { sum = sum % 26 ; return ( char ) ( ' a ' + sum - 1 ) ; } } int main ( ) { string str = " gfg " ; cout << getChar ( str ) ; return 0 ; }
Reverse the given string in the range [ L , R ] | C ++ implementation of the approach ; Function to return the string after reversing characters in the range [ L , R ] ; Invalid range ; While there are characters to swap ; Swap ( str [ l ] , str [ r ] ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string reverse ( string str , int len , int l , int r ) { if ( l < 0 r > = len l > r ) return str ; while ( l < r ) { char c = str [ l ] ; str [ l ] = str [ r ] ; str [ r ] = c ; l ++ ; r -- ; } return str ; } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; int l = 5 , r = 7 ; cout << reverse ( str , len , l , r ) ; return 0 ; }
Program to Encrypt a String using ! and @ | C ++ program to Encrypt the String using ! and @ ; Function to encrypt the string ; evenPos is for storing encrypting char at evenPosition oddPos is for storing encrypting char at oddPosition ; Get the number of times the character is to be repeated ; if i is odd , print ' ! ' else print ' @ ' ; Driver code ; Encrypt the String
#include <bits/stdc++.h> NEW_LINE using namespace std ; void encrypt ( char input [ 100 ] ) { char evenPos = ' @ ' , oddPos = ' ! ' ; int repeat , ascii ; for ( int i = 0 ; i <= strlen ( input ) ; i ++ ) { ascii = input [ i ] ; repeat = ascii >= 97 ? ascii - 96 : ascii - 64 ; for ( int j = 0 ; j < repeat ; j ++ ) { if ( i % 2 == 0 ) cout << oddPos ; else cout << evenPos ; } } } int main ( ) { char input [ 100 ] = { ' A ' , ' b ' , ' C ' , ' d ' } ; encrypt ( input ) ; return 0 ; }
Check if expression contains redundant bracket or not | Set 2 | C ++ program to check for / redundant braces in the string ; Function to check for redundant braces ; count of no of signs ; Driver function
#include <iostream> NEW_LINE using namespace std ; bool IsRedundantBraces ( string A ) { int a = 0 , b = 0 ; for ( int i = 0 ; i < A . size ( ) ; i ++ ) { if ( A [ i ] == ' ( ' && A [ i + 2 ] == ' ) ' ) return 1 ; if ( A [ i ] == ' * ' A [ i ] == ' + ' A [ i ] == ' - ' A [ i ] == ' / ' ) a ++ ; if ( A [ i ] == ' ( ' ) b ++ ; } if ( b > a ) return 1 ; return 0 ; } int main ( ) { string A = " ( ( ( a + b ) ▁ + ▁ c ) ▁ + ▁ d ) " ; if ( IsRedundantBraces ( A ) ) { cout << " YES STRNEWLINE " ; } else { cout << " NO " ; } }
Convert an unbalanced bracket sequence to a balanced sequence | C ++ implementation of the approach ; Function to return balancedBrackets string ; Initializing dep to 0 ; Stores maximum negative depth ; if dep is less than minDep ; if minDep is less than 0 then there is need to add ' ( ' at the front ; Reinitializing to check the updated string ; if dep is not 0 then there is need to add ' ) ' at the back ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string balancedBrackets ( string str ) { int dep = 0 ; int minDep = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ( ' ) dep ++ ; else dep -- ; if ( minDep > dep ) minDep = dep ; } if ( minDep < 0 ) { for ( int i = 0 ; i < abs ( minDep ) ; i ++ ) str = ' ( ' + str ; } dep = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' ( ' ) dep ++ ; else dep -- ; } if ( dep != 0 ) { for ( int i = 0 ; i < dep ; i ++ ) str = str + ' ) ' ; } return str ; } int main ( ) { string str = " ) ) ) ( ) " ; cout << balancedBrackets ( str ) ; }
Minimum operations required to convert a binary string to all 0 s or all 1 s | C ++ implementation of the approach ; Function to return the count of minimum operations required ; Increment count when consecutive characters are different ; Answer is rounding off the ( count / 2 ) to lower ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( string str , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( str [ i ] != str [ i + 1 ] ) count ++ ; } return ( count + 1 ) / 2 ; } int main ( ) { string str = "000111" ; int n = str . length ( ) ; cout << minOperations ( str , n ) ; return 0 ; }
Append a digit in the end to make the number equal to the length of the remaining string | C ++ implementation of the approach ; Function to return the required digit ; To store the position of the first numeric digit in the string ; To store the length of the string without the numeric digits in the end ; pw stores the current power of 10 and num is to store the number which is appended in the end ; If current character is a numeric digit ; Get the current digit ; Build the number ; If number exceeds the length ; Next power of 10 ; Append 0 in the end ; Required number that must be added ; If number is not a single digit ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_digit ( string s , int n ) { int first_digit = -1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( s [ i ] < '0' s [ i ] > '9' ) { first_digit = i ; break ; } } first_digit ++ ; int s_len = first_digit ; int num = 0 , pw = 1 ; int i = n - 1 ; while ( i >= 0 ) { if ( s [ i ] >= '0' && s [ i ] <= '9' ) { int digit = s [ i ] - '0' ; num = num + ( pw * digit ) ; if ( num >= s_len ) return -1 ; pw = pw * 10 ; } i -- ; } num = num * 10 ; int req = s_len - num ; if ( req > 9 req < 0 ) return -1 ; return req ; } int main ( ) { string s = " abcd0" ; int n = s . length ( ) ; cout << find_digit ( s , n ) ; return 0 ; }
Check whether str1 can be converted to str2 with the given operations | C ++ implementation of the approach ; Function that returns true if str1 can be converted to str2 with the given operations ; Traverse from left to right ; If the two characters do not match ; If possible to combine ; If not possible to combine ; If the two characters match ; If possible to convert one string to another ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canConvert ( string str1 , string str2 ) { int i = 0 , j = 0 ; while ( i < str1 . size ( ) && j < str2 . size ( ) ) { if ( str1 [ i ] != str2 [ j ] ) { if ( str1 [ i ] == '0' && str2 [ j ] == '1' && i + 1 < str1 . size ( ) && str1 [ i + 1 ] == '0' ) { i += 2 ; j ++ ; } else { return false ; } } else { i ++ ; j ++ ; } } if ( i == str1 . size ( ) && j == str2 . size ( ) ) return true ; return false ; } int main ( ) { string str1 = "00100" , str2 = "111" ; if ( canConvert ( str1 , str2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Reverse the Words of a String using Stack | C ++ implementation of the above approach ; function to reverse the words of the given string without using strtok ( ) . ; create an empty string stack ; create an empty temporary string ; traversing the entire string ; push the temporary variable into the stack ; assigning temporary variable as empty ; for the last word of the string ; Get the words in reverse order ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( string s ) { stack < string > stc ; string temp = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == ' ▁ ' ) { stc . push ( temp ) ; temp = " " ; } else { temp = temp + s [ i ] ; } } stc . push ( temp ) ; while ( ! stc . empty ( ) ) { temp = stc . top ( ) ; cout << temp << " ▁ " ; stc . pop ( ) ; } cout << endl ; } int main ( ) { string s = " I ▁ Love ▁ To ▁ Code " ; reverse ( s ) ; return 0 ; }
Print an N x M matrix such that each row and column has all the vowels in it | C ++ implementation of the approach ; Function to print the required matrix ; Impossible to generate the required matrix ; Store all the vowels ; Print the matrix ; Print vowels for every index ; Shift the vowels by one ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printMatrix ( int n , int m ) { if ( n < 5 m < 5 ) { cout << -1 ; return ; } string s = " aeiou " ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < m ; j ++ ) { cout << s [ j % 5 ] << " ▁ " ; } cout << endl ; char c = s [ 0 ] ; for ( int i = 0 ; i < 4 ; i ++ ) { s [ i ] = s [ i + 1 ] ; } s [ 4 ] = c ; } } int main ( ) { int n = 5 , m = 5 ; printMatrix ( n , m ) ; return 0 ; }
Check if a given string is made up of two alternating characters | C ++ implementation of the approach ; Function that returns true if the string is made up of two alternating characters ; Check if ith character matches with the character at index ( i + 2 ) ; If string consists of a single character repeating itself ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isTwoAlter ( string s ) { for ( int i = 0 ; i < s . length ( ) - 2 ; i ++ ) { if ( s [ i ] != s [ i + 2 ] ) { return false ; } } if ( s [ 0 ] == s [ 1 ] ) return false ; return true ; } int main ( ) { string str = " ABAB " ; if ( isTwoAlter ( str ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Number of character corrections in the given strings to make them equal | C ++ implementation of the approach ; Function to return the count of operations required ; To store the count of operations ; No operation required ; One operation is required when any two characters are equal ; Two operations are required when none of the characters are equal ; Return the minimum count of operations required ; Driver code
#include <iostream> NEW_LINE #include <bits/stdc++.h> NEW_LINE using namespace std ; const int minOperations ( int n , string a , string b , string c ) { int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { char x = a [ i ] ; char y = b [ i ] ; char z = c [ i ] ; if ( x == y && y == z ) ; else if ( x == y y == z x == z ) { ans ++ ; } else { ans += 2 ; } } return ans ; } int main ( ) { string a = " place " ; string b = " abcde " ; string c = " plybe " ; int n = a . size ( ) ; cout << minOperations ( n , a , b , c ) ; return 0 ; }
Check if string can be made lexicographically smaller by reversing any substring | C ++ implementation of the approach ; Function that returns true if s can be made lexicographically smaller by reversing a sub - string in s ; Traverse in the string ; Check if s [ i + 1 ] < s [ i ] ; Not possible ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( string s ) { int n = s . size ( ) ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( s [ i ] > s [ i + 1 ] ) return true ; } return false ; } int main ( ) { string s = " geeksforgeeks " ; if ( check ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count of sub | C ++ implementation of the approach ; Function to return the count of required sub - strings ; Number of sub - strings from position of current x to the end of str ; To store the number of characters before x ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubStr ( string str , int n , char x ) { int res = 0 , count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == x ) { res += ( ( count + 1 ) * ( n - i ) ) ; count = 0 ; } else count ++ ; } return res ; } int main ( ) { string str = " abcabc " ; int n = str . length ( ) ; char x = ' c ' ; cout << countSubStr ( str , n , x ) ; return 0 ; }
Count of sub | C ++ implementation of the approach ; Function to return the count of possible sub - strings of length n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubStr ( string str , int n ) { int len = str . length ( ) ; return ( len - n + 1 ) ; } int main ( ) { string str = " geeksforgeeks " ; int n = 5 ; cout << countSubStr ( str , n ) ; return 0 ; }
Count of sub | C ++ implementation of the approach ; Function to return the number of sub - strings that do not contain the given character c ; Length of the string ; Traverse in the string ; If current character is different from the given character ; Update the number of sub - strings ; Reset count to 0 ; For the characters appearing after the last occurrence of c ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubstrings ( string s , char c ) { int n = s . length ( ) ; int cnt = 0 ; int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] != c ) cnt ++ ; else { sum += ( cnt * ( cnt + 1 ) ) / 2 ; cnt = 0 ; } } sum += ( cnt * ( cnt + 1 ) ) / 2 ; return sum ; } int main ( ) { string s = " baa " ; char c = ' b ' ; cout << countSubstrings ( s , c ) ; return 0 ; }
Minimize ASCII values sum after removing all occurrences of one character | C ++ implementation of the approach ; Function to return the minimized sum ; To store the occurrences of each character of the string ; Update the occurrence ; Calculate the sum ; Get the character which is contributing the maximum value to the sum ; Count of occurrence of the character multiplied by its ASCII value ; Return the minimized sum ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimizedSum ( string str , int len ) { int i , maxVal = INT_MIN , sum = 0 ; int occurrences [ 26 ] = { 0 } ; for ( i = 0 ; i < len ; i ++ ) { occurrences [ str [ i ] - ' a ' ] ++ ; sum += ( int ) str [ i ] ; } for ( i = 0 ; i < 26 ; i ++ ) maxVal = max ( maxVal , occurrences [ i ] * ( i + ' a ' ) ) ; return ( sum - maxVal ) ; } int main ( ) { string str = " geeksforgeeks " ; int len = str . length ( ) ; cout << getMinimizedSum ( str , len ) ; return 0 ; }
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | C ++ implementation of the approach ; Function that returns true if s is palindrome ; Function to return the required index ; Copy the ith character in S ; Copy all the character of string s2 in Temp ; Check whether the string is palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string s ) { int i = 0 ; int j = s . length ( ) - 1 ; while ( i < j ) { if ( s [ i ] != s [ j ] ) return false ; i ++ ; j -- ; } return true ; } int getIndex ( string S1 , string S2 , int n ) { string S = " " ; for ( int i = 0 ; i < n ; i ++ ) { S = S + S1 [ i ] ; string Temp = " " ; for ( int j = i + 1 ; j < n ; j ++ ) Temp += S2 [ j ] ; if ( isPalindrome ( S + Temp ) ) { return i ; } } return -1 ; } int main ( ) { string S1 = " abcdf " , S2 = " sfgba " ; int n = S1 . length ( ) ; cout << getIndex ( S1 , S2 , n ) ; return 0 ; }
Find index i such that prefix of S1 and suffix of S2 till i form a palindrome when concatenated | C ++ program to implement the above approach ; Function that returns true if the sub - string starting from index i and ending at index j is a palindrome ; Function to get the required index ; Start comparing the two strings from both ends . ; Break from the loop at first mismatch ; If it is possible to concatenate the strings to form palindrome , return index ; If remaining part for s2 is palindrome ; If remaining part for s1 is palindrome ; If not possible , return - 1 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindrome ( string s , int i , int j ) { while ( i < j ) { if ( s [ i ] != s [ j ] ) return false ; i ++ ; j -- ; } return true ; } int getIndex ( string s1 , string s2 , int len ) { int i = 0 , j = len - 1 ; while ( i < j ) { if ( s1 [ i ] != s2 [ j ] ) { break ; } i ++ ; j -- ; } if ( i == j ) { return i - 1 ; } else if ( isPalindrome ( s2 , i , j ) ) return i - 1 ; else if ( isPalindrome ( s1 , i , j ) ) return j ; return -1 ; } int main ( ) { string s1 = " abcdf " , s2 = " sfgba " ; int len = s1 . length ( ) ; cout << getIndex ( s1 , s2 , len ) ; return 0 ; }
Acronym words | C ++ implementation of the approach ; Function to return the number of strings that can be an acronym for other strings ; Frequency array to store the frequency of the first character of every string in the array ; To store the count of required strings ; Current word ; Frequency array to store the frequency of each of the character of the current string ; Check if the frequency of every character in the current string is <= its value in freq [ ] ; First character of the current string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count_acronym ( int n , string arr [ ] ) { int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ arr [ i ] [ 0 ] - ' a ' ] ++ ; int cnt = 0 ; for ( int i = 0 ; i < n ; i ++ ) { string st = arr [ i ] ; int num [ 26 ] = { 0 } ; for ( int j = 0 ; j < st . length ( ) ; j ++ ) num [ st [ j ] - ' a ' ] ++ ; bool flag = true ; for ( int j = 1 ; j < 26 ; j ++ ) { if ( num [ j ] > freq [ j ] ) { flag = false ; break ; } } int x = st [ 0 ] - ' a ' ; if ( freq [ x ] - 1 < num [ x ] ) flag = false ; if ( flag ) cnt ++ ; } return cnt ; } int main ( ) { string arr [ ] = { " abc " , " bcad " , " cabd " , " cba " , " dzzz " } ; int n = 5 ; cout << count_acronym ( n , arr ) ; }
Sub | C ++ implementation of the approach ; Function that returns true if every lowercase character appears atmost once ; every character frequency must be not greater than one ; Function that returns the modified good string if possible ; If the length of the string is less than n ; Sub - strings of length 26 ; To store frequency of each character ; Get the frequency of each character in the current sub - string ; Check if we can get sub - string containing all the 26 characters ; Find which character is missing ; Fill with missing characters ; Find the next missing character ; Return the modified good string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool valid ( int cnt [ ] ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( cnt [ i ] >= 2 ) return false ; } return true ; } string getGoodString ( string s , int n ) { if ( n < 26 ) return " - 1" ; for ( int i = 25 ; i < n ; i ++ ) { int cnt [ 26 ] = { 0 } ; for ( int j = i ; j >= i - 25 ; j -- ) { cnt [ s [ j ] - ' a ' ] ++ ; } if ( valid ( cnt ) ) { int cur = 0 ; while ( cnt [ cur ] > 0 ) cur ++ ; for ( int j = i - 25 ; j <= i ; j ++ ) { if ( s [ j ] == ' ? ' ) { s [ j ] = cur + ' a ' ; cur ++ ; while ( cnt [ cur ] > 0 ) cur ++ ; } } return s ; } } return " - 1" ; } int main ( ) { string s = " abcdefghijkl ? nopqrstuvwxy ? " ; int n = s . length ( ) ; cout << getGoodString ( s , n ) ; return 0 ; }
Modify the string by swapping continuous vowels or consonants | C ++ implementation of the above approach ; Function to check if a character is a vowel ; Function to swap two consecutively repeated vowels or consonants ; Traverse through the length of the string ; Check if the two consecutive characters are vowels or consonants ; swap the two characters ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { c = tolower ( c ) ; if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } string swapRepeated ( string str ) { for ( int i = 0 ; i < str . length ( ) - 1 ; i ++ ) { if ( ( isVowel ( str [ i ] ) && isVowel ( str [ i + 1 ] ) ) || ( ! isVowel ( str [ i ] ) && ! isVowel ( str [ i + 1 ] ) ) ) swap ( str [ i ] , str [ i + 1 ] ) ; } return str ; } int main ( ) { string str = " geeksforgeeks " ; cout << swapRepeated ( str ) ; return 0 ; }
Find the lexicographically largest palindromic Subsequence of a String | CPP program to find the largest palindromic subsequence ; Function to find the largest palindromic subsequence ; Find the largest character ; Append all occurrences of largest character to the resultant string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string largestPalinSub ( string s ) { string res ; char mx = s [ 0 ] ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) mx = max ( mx , s [ i ] ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) if ( s [ i ] == mx ) res += s [ i ] ; return res ; } int main ( ) { string s = " geeksforgeeks " ; cout << largestPalinSub ( s ) ; }
Generate lexicographically smallest string of 0 , 1 and 2 with adjacent swaps allowed | C ++ implementation of the approach ; Function to print the required string ; count number of 1 s ; To check if the all the 1 s have been used or not ; Print all the 1 s if any 2 is encountered ; If str [ i ] = 0 or str [ i ] = 2 ; If 1 s are not printed yet ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printString ( string str , int n ) { int ones = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( str [ i ] == '1' ) ones ++ ; bool used = false ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == '2' && ! used ) { used = 1 ; for ( int j = 0 ; j < ones ; j ++ ) cout << "1" ; } if ( str [ i ] != '1' ) cout << str [ i ] ; } if ( ! used ) for ( int j = 0 ; j < ones ; j ++ ) cout << "1" ; } int main ( ) { string str = "100210" ; int n = str . length ( ) ; printString ( str , n ) ; return 0 ; }
K length words that can be formed from given characters without repetition | C ++ implementation of the approach ; Function to return the required count ; To store the count of distinct characters in str ; Traverse str character by character ; If current character is appearing for the first time in str ; Increment the distinct character count ; Update the appearance of the current character ; Since P ( n , r ) = n ! / ( n - r ) ! ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findPermutation ( string str , int k ) { bool has [ 26 ] = { false } ; int cnt = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( ! has [ str [ i ] - ' a ' ] ) { cnt ++ ; has [ str [ i ] - ' a ' ] = true ; } } long long int ans = 1 ; for ( int i = 2 ; i <= cnt ; i ++ ) ans *= i ; for ( int i = cnt - k ; i > 1 ; i -- ) ans /= i ; return ans ; } int main ( ) { string str = " geeksforgeeks " ; int k = 4 ; cout << findPermutation ( str , k ) ; return 0 ; }
Find the number in a range having maximum product of the digits | CPP Program to find the number in a range having maximum product of the digits ; Returns the product of digits of number x ; This function returns the number having maximum product of the digits ; Converting both integers to strings ; Let the current answer be r ; Stores the current number having current digit one less than current digit in b ; Replace all following digits with 9 to maximise the product ; Convert string to number ; Check if it lies in range and its product is greater than max product ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int product ( int x ) { int prod = 1 ; while ( x ) { prod *= ( x % 10 ) ; x /= 10 ; } return prod ; } int findNumber ( int l , int r ) { string a = to_string ( l ) ; string b = to_string ( r ) ; int ans = r ; for ( int i = 0 ; i < b . size ( ) ; i ++ ) { if ( b [ i ] == '0' ) continue ; string curr = b ; curr [ i ] = ( ( curr [ i ] - '0' ) - 1 ) + '0' ; for ( int j = i + 1 ; j < curr . size ( ) ; j ++ ) curr [ j ] = '9' ; int num = 0 ; for ( auto c : curr ) num = num * 10 + ( c - '0' ) ; if ( num >= l && product ( ans ) < product ( num ) ) ans = num ; } return ans ; } int main ( ) { int l = 1 , r = 10 ; cout << findNumber ( l , r ) << endl ; l = 51 , r = 62 ; cout << findNumber ( l , r ) << endl ; return 0 ; }
Longest Ordered Subsequence of Vowels | C ++ program to find the longest subsequence of vowels in the specified order ; Mapping values for vowels ; Function to check if given subsequence contains all the vowels or not ; not contain vowel ; Function to find the longest subsequence of vowels in the given string in specified order ; If we have reached the end of the string , return the subsequence if it is valid , else return an empty list ; If there is no vowel in the subsequence yet , add vowel at current index if it is ' a ' , else move on to the next character in the string ; If the last vowel in the subsequence until now is same as the vowel at current index , add it to the subsequence ; If the vowel at the current index comes right after the last vowel in the subsequence , we have two options : either to add the vowel in the subsequence , or move on to next character . We choose the one which gives the longest subsequence . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < char > vowels = { ' a ' , ' e ' , ' i ' , ' o ' , ' u ' } ; map < char , int > mapping = { { ' a ' , 0 } , { ' e ' , 1 } , { ' i ' , 2 } , { ' o ' , 3 } , { ' u ' , 4 } } ; bool isValidSequence ( string subList ) { for ( char c : vowels ) { if ( subList . find ( c ) == std :: string :: npos ) return 0 ; } return 1 ; } string longestSubsequence ( string str , string subList , int index ) { int len = str . length ( ) ; if ( index >= len ) { if ( isValidSequence ( subList ) ) return subList ; else return " " ; } else if ( subList . size ( ) == 0 ) { if ( str [ index ] != ' a ' ) return longestSubsequence ( str , " " , index + 1 ) ; else return longestSubsequence ( str , subList + str [ index ] , index + 1 ) ; } else if ( mapping [ subList [ subList . size ( ) - 1 ] ] == mapping [ str [ index ] ] ) return longestSubsequence ( str , subList + str [ index ] , index + 1 ) ; else if ( mapping [ subList [ subList . size ( ) - 1 ] ] + 1 == mapping [ str [ index ] ] ) { string sub1 = longestSubsequence ( str , subList + str [ index ] , index + 1 ) ; string sub2 = longestSubsequence ( str , subList , index + 1 ) ; if ( sub1 . length ( ) > sub2 . length ( ) ) return sub1 ; else return sub2 ; } else return longestSubsequence ( str , subList , index + 1 ) ; } int main ( ) { string str = " aeiaaioooauuaeiou " ; string subsequence = longestSubsequence ( str , " " , 0 ) ; if ( subsequence . length ( ) == 0 ) cout << " No ▁ subsequence ▁ possible STRNEWLINE " ; else cout << subsequence << " STRNEWLINE " ; }
Concatenate suffixes of a String | C ++ implementation of the approach ; Function to print the expansion of the string ; Take sub - string from i to n - 1 ; Print the sub - string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printExpansion ( string str ) { int size = 0 ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { string subStr = str . substr ( i , ++ size ) ; cout << subStr ; } } int main ( ) { string str = " geeks " ; printExpansion ( str ) ; return 0 ; }
Construct a binary string following the given constraints | C ++ implementation of the approach ; Function to print a binary string which has ' a ' number of 0 ' s , ▁ ' b ' ▁ number ▁ of ▁ 1' s and there are at least ' x ' indices such that s [ i ] != s [ i + 1 ] ; Divide index value by 2 and store it into d ; If index value x is even and x / 2 is not equal to a ; Loop for d for each d print 10 ; subtract d from a and b ; Loop for b to print remaining 1 's ; Loop for a to print remaining 0 's ; Driver code
#include <iostream> NEW_LINE using namespace std ; int constructBinString ( int a , int b , int x ) { int d , i ; d = x / 2 ; if ( x % 2 == 0 && x / 2 != a ) { d -- ; cout << 0 ; a -- ; } for ( i = 0 ; i < d ; i ++ ) cout << "10" ; a = a - d ; b = b - d ; for ( i = 0 ; i < b ; i ++ ) { cout << "1" ; } for ( i = 0 ; i < a ; i ++ ) { cout << "0" ; } } int main ( ) { int a = 4 , b = 3 , x = 2 ; constructBinString ( a , b , x ) ; return 0 ; }
Check If every group of a ' s ▁ is ▁ followed ▁ by ▁ a ▁ group ▁ of ▁ b ' s of same length | C ++ implementation of the approach ; Function to match whether there are always n consecutive b ' s ▁ followed ▁ by ▁ n ▁ consecutive ▁ a ' s throughout the string ; Traverse through the string ; Count a 's in current segment ; Count b 's in current segment ; If both counts are not same . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int matchPattern ( string s ) { int count = 0 ; int n = s . length ( ) ; int i = 0 ; while ( i < n ) { while ( i < n && s [ i ] == ' a ' ) { count ++ ; i ++ ; } while ( i < n && s [ i ] == ' b ' ) { count -- ; i ++ ; } if ( count != 0 ) return false ; } return true ; } int main ( ) { string s = " bb " ; if ( matchPattern ( s ) == true ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Length of longest consecutive ones by at most one swap in a Binary String | C ++ program to find length of longest consecutive ones by at most one swap in a Binary String ; Function to calculate the length of the longest consecutive 1 's ; To count all 1 's in the string ; To store cumulative 1 's ; Counting cumulative 1 's from left ; If 0 then start new cumulative one from that i ; perform step 3 of the approach ; step 3 ; Driver Code ; string
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximum_one ( string s , int n ) { int cnt_one = 0 ; int max_cnt = 0 , temp = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) { cnt_one ++ ; temp ++ ; } else { max_cnt = max ( temp , max_cnt ) ; temp = 0 ; } } max_cnt = max ( max_cnt , temp ) ; int left [ n ] , right [ n ] ; if ( s [ 0 ] == '1' ) left [ 0 ] = 1 ; else left [ 0 ] = 0 ; if ( s [ n - 1 ] == '1' ) right [ n - 1 ] = 1 ; else right [ n - 1 ] = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( s [ i ] == '1' ) left [ i ] = left [ i - 1 ] + 1 ; else left [ i ] = 0 ; } for ( int i = n - 2 ; i >= 0 ; i -- ) { if ( s [ i ] == '1' ) right [ i ] = right [ i + 1 ] + 1 ; else right [ i ] = 0 ; } for ( int i = 1 ; i < n - 1 ; i ++ ) { if ( s [ i ] == '0' ) { int sum = left [ i - 1 ] + right [ i + 1 ] ; if ( sum < cnt_one ) max_cnt = max ( max_cnt , sum + 1 ) ; else max_cnt = max ( max_cnt , sum ) ; } } return max_cnt ; } int main ( ) { string s = "111011101" ; cout << maximum_one ( s , s . length ( ) ) ; return 0 ; }
Maximum length substring with highest frequency in a string | C ++ program to find maximum occurred substring of a string ; function to return maximum occurred substring of a string ; size of the string ; to store maximum frequency ; to store string which has maximum frequency ; return substring which has maximum frequency ; Driver program ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string MaxFreq ( string str ) { int n = str . size ( ) ; unordered_map < string , int > m ; for ( int i = 0 ; i < n ; i ++ ) { string s = " " ; for ( int j = i ; j < n ; j ++ ) { s += str [ j ] ; m [ s ] ++ ; } } int maxi = 0 ; string s ; for ( auto i = m . begin ( ) ; i != m . end ( ) ; i ++ ) { if ( i -> second > maxi ) { maxi = i -> second ; s = i -> first ; } else if ( i -> second == maxi ) { string ss = i -> first ; if ( ss . size ( ) > s . size ( ) ) s = ss ; } } return s ; } int main ( ) { string str = " ababecdecd " ; cout << MaxFreq ( str ) ; return 0 ; }
Lexicographically smallest substring with maximum occurrences containing a ' s ▁ and ▁ b ' s only | CPP program to Find the lexicographically smallest substring in a given string with maximum frequency and contains a ' s ▁ and ▁ b ' s only ; Function to Find the lexicographically smallest substring in a given string with maximum frequency and contains a ' s ▁ and ▁ b ' s only . ; To store frequency of digits ; size of string ; Take lexicographically larger digit in b ; get frequency of each character ; If no such string exits ; Maximum frequency ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxFreq ( string s , int a , int b ) { int fre [ 10 ] = { 0 } ; int n = s . size ( ) ; if ( a > b ) swap ( a , b ) ; for ( int i = 0 ; i < n ; i ++ ) fre [ s [ i ] - '0' ] ++ ; if ( fre [ a ] == 0 and fre [ b ] == 0 ) return -1 ; else if ( fre [ a ] >= fre [ b ] ) return a ; else return b ; } int main ( ) { int a = 4 , b = 7 ; string s = "47744" ; cout << maxFreq ( s , a , b ) ; return 0 ; }
Minimum steps to convert one binary string to other only using negation | C ++ implementation of the above approach ; Function to find the minimum steps to convert string a to string b ; array to mark the positions needed to be negated ; If two character are not same then they need to be negated ; To count the blocks of 1 ; To count the number of 1 ' s ▁ in ▁ ▁ each ▁ block ▁ of ▁ 1' s ; For the last block of 1 's ; Driver code
#include <iostream> NEW_LINE using namespace std ; void convert ( int n , string a , string b ) { int l [ n ] ; int i ; for ( i = 0 ; i < n ; i ++ ) l [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] != b [ i ] ) l [ i ] = 1 ; } int cc = 0 ; int vl = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( l [ i ] == 0 ) { if ( vl != 0 ) cc += 1 ; vl = 0 ; } else vl += 1 ; } if ( vl != 0 ) cc += 1 ; cout << cc << endl ; } int main ( ) { string a = "101010" ; string b = "110011" ; int n = a . length ( ) ; convert ( n , a , b ) ; return 0 ; }
Generate a sequence with the given operations | C ++ Implementation of above approach ; function to find minimum required permutation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void StringMatch ( string s ) { int lo = 0 , hi = s . length ( ) , len = s . length ( ) ; vector < int > ans ; for ( int x = 0 ; x < len ; x ++ ) { if ( s [ x ] == ' I ' ) { ans . push_back ( lo ) ; lo += 1 ; } else { ans . push_back ( hi ) ; hi -= 1 ; } } ans . push_back ( lo ) ; cout << " [ " ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] ; if ( i != ans . size ( ) - 1 ) cout << " , " ; } cout << " ] " ; } int main ( ) { string S = " IDID " ; StringMatch ( S ) ; return 0 ; }
Number of ways to swap two bit of s1 so that bitwise OR of s1 and s2 changes | C ++ program to find no of ways to swap bits of s1 so that bitwise OR of s1 and s2 changes ; Function to find number of ways ; initialise result that store No . of swaps required ; Traverse both strings and check the bits as explained ; calculate result ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countWays ( string s1 , string s2 , int n ) { int a , b , c , d ; a = b = c = d = 0 ; int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s2 [ i ] == '0' ) { if ( s1 [ i ] == '0' ) { c ++ ; } else { d ++ ; } } else { if ( s1 [ i ] == '0' ) { a ++ ; } else { b ++ ; } } } result = a * d + b * c + c * d ; return result ; } int main ( ) { int n = 5 ; string s1 = "01011" ; string s2 = "11001" ; cout << countWays ( s1 , s2 , n ) ; return 0 ; }
Find the player who rearranges the characters to get a palindrome string first | C ++ program to print the winner of the game ; Function that returns the winner of the game ; Initialize the freq array to 0 ; Iterate and count the frequencies of each character in the string ; Count the odd occurring character ; If odd occurrence ; Check condition for Player - 1 winning the game ; Driver code ; Function call that returns the winner
#include <bits/stdc++.h> NEW_LINE using namespace std ; int returnWinner ( string s , int l ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < l ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; } int cnt = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] & 1 ) cnt ++ ; } if ( cnt == 0 cnt & 1 ) return 1 ; else return 2 ; } int main ( ) { string s = " abaaab " ; int l = s . length ( ) ; int winner = returnWinner ( s , l ) ; cout << " Player - " << winner ; return 0 ; }
Maximum sum and product of the M consecutive digits in a number | C ++ implementation of the above approach ; Function to find the maximum product ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxProductSum ( string str , int m ) { int n = str . length ( ) ; int maxProd = INT_MIN , maxSum = INT_MIN ; for ( int i = 0 ; i <= n - m ; i ++ ) { int product = 1 , sum = 0 ; for ( int j = i ; j < m + i ; j ++ ) { product = product * ( str [ j ] - '0' ) ; sum = sum + ( str [ j ] - '0' ) ; } maxProd = max ( maxProd , product ) ; maxSum = max ( maxSum , sum ) ; } cout << " Maximum ▁ Product ▁ = ▁ " << maxProd ; cout << " Maximum Sum = " } int main ( ) { string str = "3605356297" ; int m = 3 ; maxProductSum ( str , m ) ; }
Replace all consonants with nearest vowels in a string | C ++ program to replace all consonants with nearest vowels in a string ; Function to check if a character is vowel or not ; Function to replace consonant with nearest vowels ; if , string element is vowel , jump to next element ; check if consonant lies between two vowels , if it lies , than replace it with nearest vowel ; here the absolute difference of ascii value is considered ; when s [ i ] is equal to either ' v ' , ' w ' , ' x ' , ' y ' , ' z ' ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char ch ) { if ( ch != ' a ' && ch != ' e ' && ch != ' i ' && ch != ' o ' && ch != ' u ' ) return false ; return true ; } string replacingConsonants ( string s ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( isVowel ( s [ i ] ) ) continue ; else { if ( s [ i ] > ' a ' && s [ i ] < ' e ' ) { if ( abs ( s [ i ] - ' a ' ) > abs ( s [ i ] - ' e ' ) ) s [ i ] = ' e ' ; else s [ i ] = ' a ' ; } else if ( s [ i ] > ' e ' && s [ i ] < ' i ' ) { if ( abs ( s [ i ] - ' e ' ) > abs ( s [ i ] - ' i ' ) ) s [ i ] = ' i ' ; else s [ i ] = ' e ' ; } else if ( s [ i ] > ' i ' && s [ i ] < ' o ' ) { if ( abs ( s [ i ] - ' i ' ) > abs ( s [ i ] - ' o ' ) ) s [ i ] = ' o ' ; else s [ i ] = ' i ' ; } else if ( s [ i ] > ' o ' && s [ i ] < ' u ' ) { if ( abs ( s [ i ] - ' o ' ) > abs ( s [ i ] - ' u ' ) ) s [ i ] = ' u ' ; else s [ i ] = ' o ' ; } else if ( s [ i ] > ' u ' ) s [ i ] = ' u ' ; } } return s ; } int main ( ) { string s = " geeksforgeeks " ; cout << replacingConsonants ( s ) ; return 0 ; }
Find time taken for signal to reach all positions in a string | C ++ program to Find time taken for signal to reach all positions in a string ; Returns time needed for signal to traverse through complete string . ; for the calculation of last index ; for strings like oxoooo , xoxxoooo . . ; if coun is greater than max_length ; if ' x ' is present at the right side of max_length ; if ' x ' is present at left side of max_length ; We use ceiling function to handle odd number ' o ' s ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxLength ( string s , int n ) { int right = 0 , left = 0 ; int coun = 0 , max_length = INT_MIN ; s = s + '1' ; for ( int i = 0 ; i <= n ; i ++ ) { if ( s [ i ] == ' o ' ) coun ++ ; else { if ( coun > max_length ) { right = 0 ; left = 0 ; if ( s [ i ] == ' x ' ) right = 1 ; if ( ( ( i - coun ) > 0 ) && ( s [ i - coun - 1 ] == ' x ' ) ) left = 1 ; coun = ceil ( ( double ) coun / ( right + left ) ) ; max_length = max ( max_length , coun ) ; } coun = 0 ; } } return max_length ; } int main ( ) { string s = " oooxoooooooooxooo " ; int n = s . size ( ) ; cout << maxLength ( s , n ) ; return 0 ; }
Lexicographically largest string formed from the characters in range L and R | C ++ program to print the lexicographically largest string that can be formed from the characters in range L and R ; Function to return the lexicographically largest string ; hash array ; make 0 - based indexing ; iterate and count frequencies of character ; ans string ; iterate in frequency array ; add til all characters are added ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printLargestString ( string s , int l , int r ) { int freq [ 26 ] = { 0 } ; l -- ; r -- ; for ( int i = min ( l , r ) ; i <= max ( l , r ) ; i ++ ) { freq [ s [ i ] - ' a ' ] ++ ; } string ans = " " ; for ( int i = 25 ; i >= 0 ; i -- ) { while ( freq [ i ] ) { ans += char ( ' a ' + i ) ; freq [ i ] -- ; } } return ans ; } int main ( ) { string s = " striver " ; int l = 3 , r = 5 ; cout << printLargestString ( s , l , r ) ; return 0 ; }
Arrange a binary string to get maximum value within a range of indices | C ++ implementation of the approach ; Storing the count of 1 's in the string ; Query of l and r ; Applying range update technique . ; Taking prefix sum to get the range update values ; Final array which will store the arranged string ; if after maximizing the ranges any 1 is left then we maximize the string lexicographically . ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void arrange ( string s ) { int cc = 0 ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s [ i ] == '1' ) cc ++ ; } int a [ s . length ( ) + 1 ] = { 0 } ; int qq [ ] [ 2 ] = { { 2 , 3 } , { 5 , 5 } } ; int n = sizeof ( qq ) / sizeof ( qq [ 0 ] ) ; for ( int i = 0 ; i < n ; i ++ ) { int l = qq [ i ] [ 0 ] , r = qq [ i ] [ 1 ] ; l -- , r -- ; a [ l ] ++ ; a [ r + 1 ] -- ; } int len_a = sizeof ( a ) / sizeof ( a [ 0 ] ) ; for ( int i = 1 ; i < len_a ; i ++ ) { a [ i ] += a [ i - 1 ] ; } int zz [ s . length ( ) ] = { 0 } ; for ( int i = 0 ; i < len_a - 1 ; i ++ ) { if ( a [ i ] > 0 ) { if ( cc > 0 ) { zz [ i ] = 1 ; cc -- ; } else break ; } if ( cc == 0 ) break ; } if ( cc > 0 ) { for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( zz [ i ] == 0 ) { zz [ i ] = 1 ; cc -- ; } if ( cc == 0 ) break ; } } for ( int i = 0 ; i < s . length ( ) ; i ++ ) cout << zz [ i ] ; cout << endl ; } int main ( ) { string str = "11100" ; arrange ( str ) ; return 0 ; }
Check whether the vowels in a string are in alphabetical order or not | C ++ implementation of above approach ; Function that checks whether the vowel characters in a string are in alphabetical order or not ; ASCII Value 64 is less than all the alphabets so using it as a default value ; check if the vowels in the string are sorted or not ; if the vowel is smaller than the previous vowel ; store the vowel ; Driver code ; check whether the vowel characters in a string are in alphabetical order or not
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool areVowelsInOrder ( string s ) { int n = s . length ( ) ; char c = ( char ) 64 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' s [ i ] == ' e ' s [ i ] == ' i ' s [ i ] == ' o ' s [ i ] == ' u ' ) { if ( s [ i ] < c ) return false ; else { c = s [ i ] ; } } } return true ; } int main ( ) { string s = " aabbbddeecc " ; if ( areVowelsInOrder ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Rearrange the string to maximize the number of palindromic substrings | C ++ program to rearrange the string such to maximize the number of palindromic substrings ; Function to return the newString ; length of string ; hashing array ; iterate and count ; resulting string ; form the resulting string ; number of times character appears ; append to resulting string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string newString ( string s ) { int l = s . length ( ) ; int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < l ; i ++ ) { freq [ s [ i ] - ' a ' ] += 1 ; } string ans = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { for ( int j = 0 ; j < freq [ i ] ; j ++ ) { ans += ( char ) ( 97 + i ) ; } } return ans ; } int main ( ) { string s = " aabab " ; cout << newString ( s ) ; return 0 ; }
Program to find remainder when large number is divided by r | CPP implementation to find Remainder when a large Number is divided by R ; Function to Return Remainder ; len is variable to store the length of Number string . ; loop that find Remainder ; Return the remainder ; Driver code ; Get the large number as string ; Get the divisor R ; Find and print the remainder
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Remainder ( string str , int R ) { int len = str . length ( ) ; int Num , Rem = 0 ; for ( int i = 0 ; i < len ; i ++ ) { Num = Rem * 10 + ( str [ i ] - '0' ) ; Rem = Num % R ; } return Rem ; } int main ( ) { string str = "13589234356546756" ; int R = 13 ; cout << Remainder ( str , R ) ; return 0 ; }
Number of balanced bracket subsequence of length 2 and 4 | C ++ implementation of above approach ; Taking the frequency suffix sum of the number of 2 's present after every index ; Storing the count of subsequence ; Subsequence of length 2 ; Subsequence of length 4 of type 1 1 2 2 ; Subsequence of length 4 of type 1 2 1 2 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countWays ( int a [ ] , int n ) { int i , j ; long suff [ n ] ; if ( a [ n - 1 ] == 2 ) suff [ n - 1 ] = 1 ; for ( i = n - 2 ; i >= 0 ; i -- ) { if ( a [ i ] == 2 ) suff [ i ] = suff [ i + 1 ] + 1 ; else suff [ i ] = suff [ i + 1 ] ; } long ss = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 1 ) ss += suff [ i ] ; } for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( a [ i ] == 1 && a [ j ] == 1 && suff [ j ] >= 2 ) { ss += ( suff [ j ] ) * ( suff [ j ] - 1 ) / 2 ; } } } for ( i = 0 ; i < n ; i ++ ) { for ( j = i + 1 ; j < n ; j ++ ) { if ( a [ i ] == 1 && a [ j ] == 1 && ( suff [ i ] - suff [ j ] ) >= 1 && suff [ j ] >= 1 ) { ss += ( suff [ i ] - suff [ j ] ) * suff [ j ] ; } } } cout << ( ss ) ; } int main ( ) { int a [ ] = { 1 , 2 , 1 , 1 , 2 , 2 } ; int n = 6 ; countWays ( a , n ) ; return 0 ; }