text
stringlengths
17
4.49k
code
stringlengths
49
5.46k
Find the maximum possible Binary Number from given string | C ++ implementation of the approach ; Function to return maximum number that can be formed from the string ; To store the frequency of ' z ' and ' n ' in the given string ; Number of zeroes ; Number of ones ; To store the required number ; Add all the ones ; Add all the zeroes ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string maxNumber ( string str , int n ) { int freq [ 2 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ' z ' ) { freq [ 0 ] ++ ; } else if ( str [ i ] == ' n ' ) { freq [ 1 ] ++ ; } } string num = " " ; for ( int i = 0 ; i < freq [ 1 ] ; i ++ ) num += '1' ; for ( int i = 0 ; i < freq [ 0 ] ; i ++ ) num += '0' ; return num ; } int main ( ) { string str = " roenenzooe " ; int n = str . length ( ) ; cout << maxNumber ( str , n ) ; return 0 ; }
Contiguous unique substrings with the given length L | C ++ implementation ; Function to print the unique sub - string of length n ; set to store the strings ; if the size of the string is equal to 1 then insert ; inserting unique sub - string of length L ; Printing the set of strings ; Driver Code ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; void result ( string s , int n ) { unordered_set < string > st ; for ( int i = 0 ; i < ( int ) s . size ( ) ; i ++ ) { string ans = " " ; for ( int j = i ; j < ( int ) s . size ( ) ; j ++ ) { ans += s [ j ] ; if ( ans . size ( ) == n ) { st . insert ( ans ) ; break ; } } } for ( auto it : st ) cout << it << " ▁ " ; } int main ( ) { string s = " abca " ; int n = 3 ; result ( s , n ) ; return 0 ; }
Find the occurrence of the given binary pattern in the binary representation of the array elements | C ++ implementation of the approach ; Function to return the binary representation of n ; Array to store binary representation ; Counter for binary array ; Storing remainder in binary array ; To store the binary representation as a string ; Function to return the frequency of pat in the given string txt ; A loop to slide pat [ ] one by one ; For current index i , check for pattern match ; If pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; Function to find the occurrence of the given pattern in the binary representation of elements of arr [ ] ; For every element of the array ; Find its binary representation ; Print the occurrence of the given pattern in its binary representation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decToBinary ( int n ) { int binaryNum [ 32 ] ; int i = 0 ; while ( n > 0 ) { binaryNum [ i ] = n % 2 ; n = n / 2 ; i ++ ; } string binary = " " ; for ( int j = i - 1 ; j >= 0 ; j -- ) binary += to_string ( binaryNum [ j ] ) ; return binary ; } int countFreq ( string & pat , string & txt ) { int M = pat . length ( ) ; int N = txt . length ( ) ; int res = 0 ; for ( int i = 0 ; i <= N - M ; i ++ ) { int j ; for ( j = 0 ; j < M ; j ++ ) if ( txt [ i + j ] != pat [ j ] ) break ; if ( j == M ) { res ++ ; j = 0 ; } } return res ; } void findOccurrence ( int arr [ ] , int n , string pattern ) { for ( int i = 0 ; i < n ; i ++ ) { string binary = decToBinary ( arr [ i ] ) ; cout << countFreq ( pattern , binary ) << " ▁ " ; } } int main ( ) { int arr [ ] = { 5 , 106 , 7 , 8 } ; string pattern = "10" ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; findOccurrence ( arr , n , pattern ) ; return 0 ; }
Check if the bracket sequence can be balanced with at most one change in the position of a bracket | CPP implementation of the approach ; Function that returns true if the sequence can be balanced by changing the position of at most one bracket ; Odd length string can never be balanced ; Add ' ( ' in the beginning and ' ) ' in the end of the string ; If its an opening bracket then append it to the temp string ; If its a closing bracket ; There was an opening bracket to match it with ; No opening bracket to match it with ; Sequence is balanced ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool canBeBalanced ( string s , int n ) { if ( n % 2 == 1 ) return false ; string k = " ( " ; k += s + " ) " ; vector < string > d ; int cnt = 0 ; for ( int i = 0 ; i < k . length ( ) ; i ++ ) { if ( k [ i ] == ' ( ' ) d . push_back ( " ( " ) ; else { if ( d . size ( ) != 0 ) d . pop_back ( ) ; else return false ; } } if ( d . empty ( ) ) return true ; return false ; } int main ( int argc , char const * argv [ ] ) { string s = " ) ( ( ) " ; int n = s . length ( ) ; ( canBeBalanced ( s , n ) ) ? cout << " Yes " << endl : cout << " No " << endl ; return 0 ; }
Find the winner of the game | C ++ implementation of the approach ; Function to find the winner of the game ; To store the strings for both the players ; If the index is even ; Append the current character to player A 's string ; If the index is odd ; Append the current character to player B 's string ; Sort both the strings to get the lexicographically smallest string possible ; Copmpare both the strings to find the winner of the game ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void find_winner ( string str , int n ) { string str1 = " " , str2 = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { str1 += str [ i ] ; } else { str2 += str [ i ] ; } } sort ( str1 . begin ( ) , str1 . end ( ) ) ; sort ( str2 . begin ( ) , str2 . end ( ) ) ; if ( str1 < str2 ) cout << " A " ; else if ( str2 < str1 ) cout << " B " ; else cout << " Tie " ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . length ( ) ; find_winner ( str , n ) ; return 0 ; }
Count of characters in str1 such that after deleting anyone of them str1 becomes str2 | Below is C ++ implementation of the approach ; Function to return the count of required indices ; Solution doesn 't exist ; Find the length of the longest common prefix of strings ; Find the length of the longest common suffix of strings ; If solution does not exist ; Return the count of indices ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Find_Index ( string str1 , string str2 ) { int n = str1 . size ( ) ; int m = str2 . size ( ) ; int l = 0 ; int r = 0 ; if ( n != m + 1 ) { return -1 ; } for ( int i = 0 ; i < m ; i ++ ) { if ( str1 [ i ] == str2 [ i ] ) { l += 1 ; } else { break ; } } int i = n - 1 ; int j = m - 1 ; while ( i >= 0 && j >= 0 && str1 [ i ] == str2 [ j ] ) { r += 1 ; i -= 1 ; j -= 1 ; } if ( l + r < m ) { return -1 ; } else { i = max ( n - r , 1 ) ; j = min ( l + 1 , n ) ; return ( j - i + 1 ) ; } } int main ( ) { string str1 = " aaa " , str2 = " aa " ; cout << Find_Index ( str1 , str2 ) ; return 0 ; }
Expand the string according to the given conditions | C ++ implementation of the approach ; Function to expand and print the given string ; Subtract '0' to convert char to int ; Characters within brackets ; Expanding ; Reset the variables ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void expandString ( string strin ) { string temp = " " ; int j ; for ( int i = 0 ; i < strin . length ( ) ; i ++ ) { if ( strin [ i ] >= 0 ) { int num = strin [ i ] - '0' ; if ( strin [ i + 1 ] == ' ( ' ) { for ( j = i + 1 ; strin [ j ] != ' ) ' ; j ++ ) { if ( ( strin [ j ] >= ' a ' && strin [ j ] <= ' z ' ) || ( strin [ j ] >= ' A ' && strin [ j ] <= ' Z ' ) ) { temp += strin [ j ] ; } } for ( int k = 1 ; k <= num ; k ++ ) { cout << ( temp ) ; } num = 0 ; temp = " " ; if ( j < strin . length ( ) ) { i = j ; } } } } } int main ( ) { string strin = "3 ( ab ) 4 ( cd ) " ; expandString ( strin ) ; }
Largest substring of str2 which is a prefix of str1 | C ++ implementation of the approach ; Function to return the largest substring in str2 which is a prefix of str1 ; To store the index in str2 which matches the prefix in str1 ; While there are characters left in str1 ; If the prefix is not found in str2 ; Remove the last character ; Prefix found ; No substring found in str2 that matches the prefix of str1 ; Driver code
#include <iostream> NEW_LINE using namespace std ; string findPrefix ( string str1 , string str2 ) { int pos = -1 ; while ( ! str1 . empty ( ) ) { if ( str2 . find ( str1 ) == string :: npos ) str1 . pop_back ( ) ; else { pos = str2 . find ( str1 ) ; break ; } } if ( pos == -1 ) return " - 1" ; return str1 ; } int main ( ) { string str1 = " geeksfor " ; string str2 = " forgeeks " ; cout << findPrefix ( str1 , str2 ) ; return 0 ; }
Lexicographically smallest string formed by appending a character from first K characters of a string | Set 2 | C ++ implementation of the approach ; Function to return the lexicographically smallest required string ; Initially empty string ; min heap of characters ; Length of the string ; K cannot be greater than the size of the string ; First push the first K characters into the priority_queue ; While there are characters to append ; Append the top of priority_queue to X ; Remove the top element ; Push only if i is less than the size of string ; Return the generated string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string getSmallestStr ( string S , int K ) { string X = " " ; priority_queue < char , vector < char > , greater < char > > pq ; int i , n = S . length ( ) ; K = min ( K , n ) ; for ( i = 0 ; i < K ; i ++ ) pq . push ( S [ i ] ) ; while ( ! pq . empty ( ) ) { X += pq . top ( ) ; pq . pop ( ) ; if ( i < S . length ( ) ) pq . push ( S [ i ] ) ; i ++ ; } return X ; } int main ( ) { string S = " geeksforgeeks " ; int K = 5 ; cout << getSmallestStr ( S , K ) ; return 0 ; }
Round the given number to nearest multiple of 10 | Set | C ++ implementation of the approach ; Function to round the given number to the nearest multiple of 10 ; If string is empty ; If the last digit is less then or equal to 5 then it can be rounded to the nearest ( previous ) multiple of 10 by just replacing the last digit with 0 ; Set the last digit to 0 ; Print the updated number ; The number hast to be rounded to the next multiple of 10 ; To store the carry ; Replace the last digit with 0 ; Starting from the second last digit , add 1 to digits while there is carry ; While there are digits to consider and there is carry to add ; Get the current digit ; Add the carry ; If the digit exceeds 9 then the carry will be generated ; Else there will be no carry ; Update the current digit ; Get to the previous digit ; If the carry is still 1 then it must be inserted at the beginning of the string ; Prin the rest of the number ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void roundToNearest ( string str , int n ) { if ( str == " " ) return ; if ( str [ n - 1 ] - '0' <= 5 ) { str [ n - 1 ] = '0' ; cout << str . substr ( 0 , n ) ; } else { int carry = 0 ; str [ n - 1 ] = '0' ; int i = n - 2 ; carry = 1 ; while ( i >= 0 && carry == 1 ) { int currentDigit = str [ i ] - '0' ; currentDigit += carry ; if ( currentDigit > 9 ) { carry = 1 ; currentDigit = 0 ; } else carry = 0 ; str [ i ] = ( char ) ( currentDigit + '0' ) ; i -- ; } if ( carry == 1 ) cout << carry ; cout << str . substr ( 0 , n ) ; } } int main ( ) { string str = "99999999999999993" ; int n = str . length ( ) ; roundToNearest ( str , n ) ; return 0 ; }
Repeat substrings of the given String required number of times | C ++ implementation of the approach ; Function that returns true if the passed character is a digit ; Function to return the next index of a non - digit character in the string starting at the index i ( returns - 1 ifno such index is found ) ; If the character at index i is a digit then skip to the next character ; If no such index was found ; Function to append str the given number of times to the StringBuilder ; Function to return the string after performing the given operations ; To build the resultant string ; Index of the first non - digit character in the string ; While there are substrings that do not consist of digits ; Find the ending of the substring ; Starting index of the number ; If no digit appears after the current substring ; Find the index at which the current number ends ; Parse the number from the substring ; Repeat the current substring required number of times ; Find the next non - digit character index ; Return the resultant string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isDigit ( char ch ) { if ( ch >= '0' && ch <= '9' ) return true ; return false ; } int nextNonDigit ( string str , int i ) { while ( i < str . length ( ) && isDigit ( str [ i ] ) ) { i ++ ; } if ( i >= str . length ( ) ) return -1 ; return i ; } void appendRepeated ( string & sb , string str , int times ) { for ( int i = 0 ; i < times ; i ++ ) sb . append ( str ) ; } string findString ( string str , int n ) { string sb = " " ; int startStr = nextNonDigit ( str , 0 ) ; while ( startStr != -1 ) { int endStr = startStr ; while ( ( endStr + 1 ) < n && ! isDigit ( str [ endStr + 1 ] ) ) { endStr ++ ; } int startNum = endStr + 1 ; if ( startNum == -1 ) break ; int endNum = startNum ; while ( ( endNum + 1 ) < n && isDigit ( str [ endNum + 1 ] ) ) { endNum ++ ; } int num = str [ startNum ] - '0' ; appendRepeated ( sb , str . substr ( startStr , endStr + 1 - startStr ) , num ) ; startStr = nextNonDigit ( str , endStr + 1 ) ; } return sb ; } int main ( ) { string str = " g1ee1ks1for1g1e2ks1" ; int n = str . length ( ) ; cout << findString ( str , n ) << endl ; return 0 ; }
Recursive program to replace all occurrences of pi with 3.14 in a given string | C ++ program for above approach ; A simple recursive approach to replace all pi in a given function with "3.14" . Firstly function is declared we don 't need any helper function one function is enough ; Base case if s is empty or length of s is 1 return the s ; If the 0 th and 1 st element of s are p and i we have to handle them for rest we have to call recursion it will give the result ; Smalloutput is a variable used to store recursion result ; And we have to add the recursion result with the first part we handled and return the answer ; If 1 st & 2 nd element aren 't "p" & "i", then keep 1st index as it is & call recursion for rest of the string. ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string replacePi ( string s ) { if ( s . length ( ) == 0 || s . length ( ) == 1 ) return s ; if ( s [ 0 ] == ' p ' && s [ 1 ] == ' i ' ) { string smallOutput = replacePi ( s . substr ( 2 ) ) ; return "3.14" + smallOutput ; } else { return s [ 0 ] + replacePi ( s . substr ( 1 ) ) ; } } int main ( ) { string s = " pipppiiipi " ; string result = replacePi ( s ) ; cout << result << endl ; return 0 ; }
Check if the given string is vowel prime | C ++ implementation of the approach ; Function that returns true if c is a vowel ; Function that returns true if all the vowels in the given string are only at prime indices ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; 0 and 1 are not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; For every character of the given string ; If current character is vowel and the index is not prime ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } bool isVowelPrime ( string str , int n ) { bool prime [ n ] ; memset ( prime , true , sizeof ( prime ) ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p < n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i < n ; i += p ) prime [ i ] = false ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( isVowel ( str [ i ] ) && ! prime [ i ] ) return false ; } return true ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . length ( ) ; if ( isVowelPrime ( str , n ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Swap all occurrences of two characters to get lexicographically smallest string | C ++ implementation of the approach ; Function to return the lexicographically smallest string after swapping all the occurrences of any two characters ; To store the first index of every character of str ; Store the first occurring index every character ; If current character is appearing for the first time in str ; Starting from the leftmost character ; For every character smaller than str [ i ] ; If there is a character in str which is smaller than str [ i ] and appears after it ; If the required character pair is found ; If swapping is possible ; Characters to be swapped ; For every character ; Replace every ch1 with ch2 and every ch2 with ch1 ; Driver code
#include <iostream> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE string smallestStr ( string str , int n ) { int i , j ; int chk [ MAX ] ; for ( i = 0 ; i < MAX ; i ++ ) chk [ i ] = -1 ; for ( i = 0 ; i < n ; i ++ ) { if ( chk [ str [ i ] - ' a ' ] == -1 ) chk [ str [ i ] - ' a ' ] = i ; } for ( i = 0 ; i < n ; i ++ ) { bool flag = false ; for ( j = 0 ; j < str [ i ] - ' a ' ; j ++ ) { if ( chk [ j ] > chk [ str [ i ] - ' a ' ] ) { flag = true ; break ; } } if ( flag ) break ; } if ( i < n ) { char ch1 = str [ i ] ; char ch2 = char ( j + ' a ' ) ; for ( i = 0 ; i < n ; i ++ ) { if ( str [ i ] == ch1 ) str [ i ] = ch2 ; else if ( str [ i ] == ch2 ) str [ i ] = ch1 ; } } return str ; } int main ( ) { string str = " ccad " ; int n = str . length ( ) ; cout << smallestStr ( str , n ) ; return 0 ; }
Longest sub string of 0 's in a binary string which is repeated K times | C ++ program to find the find the Longest continuous sequence of '0' after repeating Given string K time ; Function to find the longest substring of 0 's ; To store size of the string ; To store the required answer ; Find the longest substring of 0 's ; Run a loop upto s [ i ] is zero ; Check the conditions ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longest_substring ( string s , int k ) { int n = s . size ( ) ; if ( k > 1 ) { s += s ; n *= 2 ; } int ans = 0 ; int i = 0 ; while ( i < n ) { int x = 0 ; while ( s [ i ] == '0' && i < n ) x ++ , i ++ ; ans = max ( ans , x ) ; i ++ ; } if ( k == 1 or ans != n ) return ans ; else return ( ans / 2 ) * k ; } int main ( ) { string s = "010001000" ; int k = 4 ; cout << longest_substring ( s , k ) ; return 0 ; }
Find the number of occurrences of a character upto preceding position | CPP program to find the number of occurrences of a character at position P upto p - 1 ; Function to find the number of occurrences of a character at position P upto p - 1 ; Return the required count ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Occurrence ( string s , int position ) { int count = 0 ; for ( int i = 0 ; i < position - 1 ; i ++ ) if ( s [ i ] == s [ position - 1 ] ) count ++ ; return count ; } int main ( ) { string s = " ababababab " ; int p = 9 ; cout << Occurrence ( s , p ) ; return 0 ; }
Find the number of occurrences of a character upto preceding position | CPP program to find the number of occurrences of a character at position P upto p - 1 ; Function to find the number of occurrences of a character at position P upto p - 1 ; Iterate over the string ; Store the Occurrence of same character ; Increase its frequency ; Return the required count ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOccurrence ( string s , int position ) { int alpha [ 26 ] = { 0 } , b [ s . size ( ) ] = { 0 } ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { b [ i ] = alpha [ ( int ) s [ i ] - 97 ] ; alpha [ ( int ) s [ i ] - 97 ] ++ ; } return b [ position - 1 ] ; } int main ( ) { string s = " ababababab " ; int p = 9 ; cout << countOccurrence ( s , p ) ; return 0 ; }
Map every character of one string to another such that all occurrences are mapped to the same character | C ++ implementation of the approach ; Function that returns true if the mapping is possible ; Both the strings are of un - equal lengths ; To store the frequencies of the characters in both the string ; Update frequencies of the characters ; For every character of s1 ; If current character is not present in s1 ; Find a character in s2 that has frequency equal to the current character 's frequency in s1 ; If such character is found ; Set the frequency to - 1 so that it doesn 't get picked again ; Set found to true ; If there is no character in s2 that could be mapped to the current character in s1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE bool canBeMapped ( string s1 , int l1 , string s2 , int l2 ) { if ( l1 != l2 ) return false ; int freq1 [ MAX ] = { 0 } ; int freq2 [ MAX ] = { 0 } ; for ( int i = 0 ; i < l1 ; i ++ ) freq1 [ s1 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < l2 ; i ++ ) freq2 [ s2 [ i ] - ' a ' ] ++ ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq1 [ i ] == 0 ) continue ; bool found = false ; for ( int j = 0 ; j < MAX ; j ++ ) { if ( freq1 [ i ] == freq2 [ j ] ) { freq2 [ j ] = -1 ; found = true ; break ; } } if ( ! found ) return false ; } return true ; } int main ( ) { string s1 = " axx " ; string s2 = " cbc " ; int l1 = s1 . length ( ) ; int l2 = s2 . length ( ) ; if ( canBeMapped ( s1 , l1 , s2 , l2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Distinct strings such that they contains given strings as sub | C ++ implementation of the approach ; Set to store strings and avoid duplicates ; Recursive function to generate the required strings ; If current string is part of the result ; Insert it into the set ; If character from str1 can be chosen ; If character from str2 can be chosen ; Function to print the generated strings from the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; set < string > stringSet ; void find_permutation ( string & str1 , string & str2 , int len1 , int len2 , int i , int j , string res ) { if ( res . length ( ) == len1 + len2 ) { stringSet . insert ( res ) ; return ; } if ( i < len1 ) find_permutation ( str1 , str2 , len1 , len2 , i + 1 , j , res + str1 [ i ] ) ; if ( j < len2 ) find_permutation ( str1 , str2 , len1 , len2 , i , j + 1 , res + str2 [ j ] ) ; } void print_set ( ) { set < string > :: iterator itr ; for ( itr = stringSet . begin ( ) ; itr != stringSet . end ( ) ; itr ++ ) cout << ( * itr ) << endl ; } int main ( ) { string str1 = " aa " , str2 = " ab " ; int len1 = str1 . length ( ) ; int len2 = str2 . length ( ) ; find_permutation ( str1 , str2 , len1 , len2 , 0 , 0 , " " ) ; print_set ( ) ; return 0 ; }
Generate all possible strings such that char at index i is either str1 [ i ] or str2 [ i ] | C ++ implementation of the approach ; Recursive function to generate the required strings ; If length of the current string is equal to the length of the given strings then the current string is part of the result ; Choosing the current character from the string a ; Choosing the current character from the string b ; Driver code ; Third argument is an empty string that we will be appended in the recursion calls Fourth arguments is the length of the resultant string so far
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generateStr ( char * a , char * b , string s , int count , int len ) { if ( count == len ) { cout << s << endl ; return ; } generateStr ( a + 1 , b + 1 , s + ( * a ) , count + 1 , len ) ; generateStr ( a + 1 , b + 1 , s + ( * b ) , count + 1 , len ) ; } int main ( ) { char * a = " abc " , * b = " def " ; int n = strlen ( a ) ; generateStr ( a , b , " " , 0 , n ) ; return 0 ; }
Program to generate all possible valid IP addresses from given string | Set 2 | C ++ implementation of the approach ; Function to get all the valid ip - addresses ; If index greater than givenString size and we have four block ; Remove the last dot ; Add ip - address to the results ; To add one index to ip - address ; Select one digit and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove two index ( one for the digit and other for the dot ) from the end ; Select two consecutive digits and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove three index from the end ; Select three consecutive digits and call the same function for other blocks ; Backtrack to generate another possible ip address So we remove four index from the end ; Driver code ; Fill result vector with all valid ip - addresses ; Print all the generated ip - addresses
#include <iostream> NEW_LINE #include <vector> NEW_LINE using namespace std ; void GetAllValidIpAddress ( vector < string > & result , string givenString , int index , int count , string ipAddress ) { if ( givenString . size ( ) == index && count == 4 ) { ipAddress . pop_back ( ) ; result . push_back ( ipAddress ) ; return ; } if ( givenString . size ( ) < index + 1 ) return ; ipAddress = ipAddress + givenString . substr ( index , 1 ) + ' . ' ; GetAllValidIpAddress ( result , givenString , index + 1 , count + 1 , ipAddress ) ; ipAddress . erase ( ipAddress . end ( ) - 2 , ipAddress . end ( ) ) ; if ( givenString . size ( ) < index + 2 givenString [ index ] == '0' ) return ; ipAddress = ipAddress + givenString . substr ( index , 2 ) + ' . ' ; GetAllValidIpAddress ( result , givenString , index + 2 , count + 1 , ipAddress ) ; ipAddress . erase ( ipAddress . end ( ) - 3 , ipAddress . end ( ) ) ; if ( givenString . size ( ) < index + 3 || stoi ( givenString . substr ( index , 3 ) ) > 255 ) return ; ipAddress += givenString . substr ( index , 3 ) + ' . ' ; GetAllValidIpAddress ( result , givenString , index + 3 , count + 1 , ipAddress ) ; ipAddress . erase ( ipAddress . end ( ) - 4 , ipAddress . end ( ) ) ; } int main ( ) { string givenString = "25525511135" ; vector < string > result ; GetAllValidIpAddress ( result , givenString , 0 , 0 , " " ) ; for ( int i = 0 ; i < result . size ( ) ; i ++ ) { cout << result [ i ] << " STRNEWLINE " ; } }
Count of non | C ++ implementation of the approach ; Function to return the count of required non - overlapping sub - strings ; To store the required count ; If "010" matches the sub - string starting at current index i ; If "101" matches the sub - string starting at current index i ; Driver code
#include <iostream> NEW_LINE using namespace std ; int countSubStr ( string s , int n ) { int count = 0 ; for ( int i = 0 ; i < n - 2 ; ) { if ( s [ i ] == '0' && s [ i + 1 ] == '1' && s [ i + 2 ] == '0' ) { count ++ ; i += 3 ; } else if ( s [ i ] == '1' && s [ i + 1 ] == '0' && s [ i + 2 ] == '1' ) { count ++ ; i += 3 ; } else { i ++ ; } } return count ; } int main ( ) { string s = "10101010101" ; int n = s . length ( ) ; cout << countSubStr ( s , n ) ; return 0 ; }
Find distinct characters in distinct substrings of a string | C ++ implementation of the approach ; Function to return the count of distinct characters in all the distinct sub - strings of the given string ; To store all the sub - strings ; To store the current sub - string ; To store the characters of the current sub - string ; If current sub - string hasn 't been stored before ; Insert it into the set ; Update the count of distinct characters ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countTotalDistinct ( string str ) { int cnt = 0 ; set < string > items ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { string temp = " " ; set < char > ans ; for ( int j = i ; j < str . length ( ) ; ++ j ) { temp = temp + str [ j ] ; ans . insert ( str [ j ] ) ; if ( items . find ( temp ) == items . end ( ) ) { items . insert ( temp ) ; cnt += ans . size ( ) ; } } } return cnt ; } int main ( ) { string str = " ABCA " ; cout << countTotalDistinct ( str ) ; return 0 ; }
Partition the string in two parts such that both parts have at least k different characters | C ++ implementation of the above approach ; Function to find the partition of the string such that both parts have at least k different characters ; Length of the string ; To check if the current character is already found ; Count number of different characters in the left part ; If current character is not already found , increase cnt by 1 ; If count becomes equal to k , we 've got the first part, therefore, store current index and break the loop ; Increment i by 1 ; Clear the map ; Assign cnt as 0 ; If the current character is not already found , increase cnt by 1 ; If cnt becomes equal to k , the second part also have k different characters so break it ; If the second part has less than k different characters , then print " Not ▁ Possible " ; Otherwise print both parts ; Driver code ; Function call
#include <iostream> NEW_LINE #include <map> NEW_LINE using namespace std ; void division_of_string ( string str , int k ) { int n = str . size ( ) ; map < char , bool > has ; int ans , cnt = 0 , i = 0 ; while ( i < n ) { if ( ! has [ str [ i ] ] ) { cnt ++ ; has [ str [ i ] ] = true ; } if ( cnt == k ) { ans = i ; break ; } i ++ ; } i ++ ; has . clear ( ) ; cnt = 0 ; while ( i < n ) { if ( ! has [ str [ i ] ] ) { cnt ++ ; has [ str [ i ] ] = true ; } if ( cnt == k ) { break ; } i ++ ; } if ( cnt < k ) { cout << " Not ▁ possible " << endl ; } else { i = 0 ; while ( i <= ans ) { cout << str [ i ] ; i ++ ; } cout << endl ; while ( i < n ) { cout << str [ i ] ; i ++ ; } cout << endl ; } cout << endl ; } int main ( ) { string str = " geeksforgeeks " ; int k = 4 ; division_of_string ( str , k ) ; return 0 ; }
Count substrings that contain all vowels | SET 2 | C ++ implementation of the approach ; Function that returns true if c is a vowel ; Function to return the count of sub - strings that contain every vowel at least once and no consonant ; Map is used to store count of each vowel ; Start index is set to 0 initially ; If substring till now have all vowels atleast once increment start index until there are all vowels present between ( start , i ) and add n - i each time ; Function to extract all maximum length sub - strings in s that contain only vowels and then calls the countSubstringsUtil ( ) to find the count of valid sub - strings in that string ; If current character is a vowel then append it to the temp string ; The sub - string containing all vowels ends here ; If there was a valid sub - string ; Reset temp string ; For the last valid sub - string ; 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 countSubstringsUtil ( string s ) { int count = 0 ; map < char , int > mp ; int n = s . length ( ) ; int start = 0 ; for ( int i = 0 ; i < n ; i ++ ) { mp [ s [ i ] ] ++ ; while ( mp [ ' a ' ] > 0 && mp [ ' e ' ] > 0 && mp [ ' i ' ] > 0 && mp [ ' o ' ] > 0 && mp [ ' u ' ] > 0 ) { count += n - i ; mp [ s [ start ] ] -- ; start ++ ; } } return count ; } int countSubstrings ( string s ) { int count = 0 ; string temp = " " ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( isVowel ( s [ i ] ) ) { temp += s [ i ] ; } else { if ( temp . length ( ) > 0 ) count += countSubstringsUtil ( temp ) ; temp = " " ; } } if ( temp . length ( ) > 0 ) count += countSubstringsUtil ( temp ) ; return count ; } int main ( ) { string s = " aeouisddaaeeiouua " ; cout << countSubstrings ( s ) << endl ; return 0 ; }
Remove first adjacent pairs of similar characters until possible | C ++ implementation of the above approach ; Function to remove adjacent duplicates ; Iterate for every character in the string ; If ans string is empty or its last character does not match with the current character then append this character to the string ; Matches with the previous one ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeDuplicates ( string S ) { string ans = " " ; for ( auto it : S ) { if ( ans . empty ( ) or ans . back ( ) != it ) ans . push_back ( it ) ; else if ( ans . back ( ) == it ) ans . pop_back ( ) ; } return ans ; } int main ( ) { string str = " keexxllx " ; cout << removeDuplicates ( str ) ; }
Reverse individual words with O ( 1 ) extra space | C ++ implementation of the approach ; Function to resturn the string after reversing the individual words ; Pointer to the first character of the first word ; If the current word has ended ; Pointer to the last character of the current word ; Reverse the current word ; Pointer to the first character of the next word ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string reverseWords ( string str ) { int start = 0 ; for ( int i = 0 ; i <= str . size ( ) ; i ++ ) { if ( str [ i ] == ' ▁ ' || i == str . size ( ) ) { int end = i - 1 ; while ( start < end ) { swap ( str [ start ] , str [ end ] ) ; start ++ ; end -- ; } start = i + 1 ; } } return str ; } int main ( ) { string str = " Geeks ▁ for ▁ Geeks " ; cout << reverseWords ( str ) ; return 0 ; }
Reverse the Words of a String using Stack | C ++ implementation of the approach ; Function to reverse the words of the given sentence ; Create an empty character array stack ; Push words into the stack ; Get the words in reverse order ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void reverse ( char k [ ] ) { stack < char * > s ; char * token = strtok ( k , " ▁ " ) ; while ( token != NULL ) { s . push ( token ) ; token = strtok ( NULL , " ▁ " ) ; } while ( ! s . empty ( ) ) { cout << s . top ( ) << " ▁ " ; s . pop ( ) ; } } int main ( ) { char k [ ] = " geeks ▁ for ▁ geeks " ; reverse ( k ) ; return 0 ; }
Count of substrings which contains a given character K times | C ++ program to count the number of substrings which contains the character C exactly K times ; Function to count the number of substrings which contains the character C exactly K times ; left and right counters for characters on both sides of substring window ; left and right pointer on both sides of substring window ; initialize the frequency ; result and length of string ; initialize the left pointer ; initialize the right pointer ; traverse all the window substrings ; counting the characters on leftSide of substring window ; counting the characters on rightSide of substring window ; Add the possible substrings on both sides to result ; Setting the frequency for next substring window ; reset the left , right counters ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubString ( string s , char c , int k ) { int leftCount = 0 , rightCount = 0 ; int left = 0 , right = 0 ; int freq = 0 ; int result = 0 , len = s . length ( ) ; while ( s [ left ] != c && left < len ) { left ++ ; leftCount ++ ; } right = left + 1 ; while ( freq != ( k - 1 ) && ( right - 1 ) < len ) { if ( s [ right ] == c ) freq ++ ; right ++ ; } while ( left < len && ( right - 1 ) < len ) { while ( s [ left ] != c && left < len ) { left ++ ; leftCount ++ ; } while ( right < len && s [ right ] != c ) { if ( s [ right ] == c ) freq ++ ; right ++ ; rightCount ++ ; } result = result + ( leftCount + 1 ) * ( rightCount + 1 ) ; freq = k - 1 ; leftCount = 0 ; rightCount = 0 ; left ++ ; right ++ ; } return result ; } int main ( ) { string s = "3123231" ; char c = '3' ; int k = 2 ; cout << countSubString ( s , c , k ) ; return 0 ; }
Count of sub | C ++ implementation of the approach ; Function to return the total required sub - sequences ; Find ways for all values of x ; x + 1 ; Removing all unnecessary digits ; Prefix Sum Array for X + 1 digit ; Sum of squares ; Previous sum of all possible pairs ; To find sum of multiplication of all possible pairs ; To prevent overcounting ; Adding ways for all possible x ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE #define MOD 1000000007 NEW_LINE using namespace std ; int solve ( string test ) { int size = test . size ( ) ; int total = 0 ; for ( int i = 0 ; i <= 8 ; i ++ ) { int x = i ; int y = i + 1 ; string newtest ; for ( int j = 0 ; j < size ; j ++ ) { if ( test [ j ] == x + 48 test [ j ] == y + 48 ) { newtest += test [ j ] ; } } if ( newtest . size ( ) > 0 ) { int size1 = newtest . size ( ) ; int prefix [ size1 ] = { 0 } ; for ( int j = 0 ; j < size1 ; j ++ ) { if ( newtest [ j ] == y + 48 ) { prefix [ j ] ++ ; } } for ( int j = 1 ; j < size1 ; j ++ ) { prefix [ j ] += prefix [ j - 1 ] ; } int count = 0 ; int firstcount = 0 ; int ss = 0 ; int prev = 0 ; for ( int j = 0 ; j < size1 ; j ++ ) { if ( newtest [ j ] == x + 48 ) { count ++ ; firstcount ++ ; } else { ss += count * count ; int pairsum = ( firstcount * firstcount - ss ) / 2 ; int temp = pairsum ; pairsum -= prev ; prev = temp ; int secondway = prefix [ size1 - 1 ] ; if ( j != 0 ) secondway -= prefix [ j - 1 ] ; int answer = count * ( count - 1 ) * secondway * ( secondway - 1 ) ; answer /= 4 ; answer += ( pairsum * secondway * ( secondway - 1 ) ) / 2 ; total += answer ; count = 0 ; } } } } return total ; } int main ( ) { string test = "13134422" ; cout << solve ( test ) << endl ; return 0 ; }
Find if it is possible to make a binary string which contanins given number of "0" , "1" , "01" and "10" as sub sequences | C ++ implementation of the approach ; Function that returns true if it is possible to make a binary string consisting of l 0 ' s , ▁ m ▁ 1' s , x "01" sub - sequences and y "10" sub - sequences ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPossible ( int l , int m , int x , int y ) { if ( l * m == x + y ) return true ; return false ; } int main ( ) { int l = 3 , m = 2 , x = 4 , y = 2 ; if ( isPossible ( l , m , x , y ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Count pairs of characters in a string whose ASCII value difference is K | C ++ implementation of the approach ; Function to return the count of required pairs of characters ; Length of the string ; To store the frequency of each character ; Update the frequency of each character ; To store the required count of pairs ; If ascii value difference is zero ; If there exists similar characters more than once ; If there exits characters with ASCII value difference as k ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 26 NEW_LINE int countPairs ( string str , int k ) { int n = str . size ( ) ; int freq [ MAX ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < n ; i ++ ) freq [ str [ i ] - ' a ' ] ++ ; int cnt = 0 ; if ( k == 0 ) { for ( int i = 0 ; i < MAX ; i ++ ) if ( freq [ i ] > 1 ) cnt += ( ( freq [ i ] * ( freq [ i ] - 1 ) ) / 2 ) ; } else { for ( int i = 0 ; i < MAX ; i ++ ) if ( freq [ i ] > 0 && i + k < MAX && freq [ i + k ] > 0 ) cnt += ( freq [ i ] * freq [ i + k ] ) ; ; } return cnt ; } int main ( ) { string str = " abcdab " ; int k = 0 ; cout << countPairs ( str , k ) ; return 0 ; }
Count of three non | C ++ implementation of the approach ; Function that returns true if s [ i ... j ] + s [ k ... l ] + s [ p ... q ] is a palindrome ; Function to return the count of valid sub - strings ; To store the count of required sub - strings ; For choosing the first sub - string ; For choosing the second sub - string ; For choosing the third sub - string ; Check if the concatenation is a palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalin ( int i , int j , int k , int l , int p , int q , string s ) { int start = i , end = q ; while ( start < end ) { if ( s [ start ] != s [ end ] ) return false ; start ++ ; if ( start == j + 1 ) start = k ; end -- ; if ( end == p - 1 ) end = l ; } return true ; } int countSubStr ( string s ) { int count = 0 ; int n = s . size ( ) ; for ( int i = 0 ; i < n - 2 ; i ++ ) { for ( int j = i ; j < n - 2 ; j ++ ) { for ( int k = j + 1 ; k < n - 1 ; k ++ ) { for ( int l = k ; l < n - 1 ; l ++ ) { for ( int p = l + 1 ; p < n ; p ++ ) { for ( int q = p ; q < n ; q ++ ) { if ( isPalin ( i , j , k , l , p , q , s ) ) { count ++ ; } } } } } } } return count ; } int main ( ) { string s = " abca " ; cout << countSubStr ( s ) ; return 0 ; }
Find the sum of the ascii values of characters which are present at prime positions | C ++ implementation of the approach ; Function that returns true if n is prime ; Function to return the sum of the ascii values of the characters which are present at prime positions ; To store the sum ; For every character ; If current position is prime then add the ASCII value of the character at the current position ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrime ( int n ) { if ( n == 0 n == 1 ) return false ; for ( int i = 2 ; i * i <= n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } int sumAscii ( string str , int n ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPrime ( i + 1 ) ) sum += ( int ) ( str [ i ] ) ; } return sum ; } int main ( ) { string str = " geeksforgeeks " ; int n = str . size ( ) ; cout << sumAscii ( str , n ) ; return 0 ; }
Count the nodes of the tree which make a pangram when concatenated with the sub | C ++ implementation of the approach ; Function that returns if the string x is a pangram ; Function to return the count of nodes which make pangram with the sub - tree nodes ; Function to perform dfs and update the nodes such that weight [ i ] will store the weight [ i ] concatenated with the weights of all the nodes in the sub - tree ; Driver code ; Weights of the nodes ; Edges of the tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > graph [ 100 ] ; vector < string > weight ( 100 ) ; bool Pangram ( string x ) { map < char , int > mp ; int n = x . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) mp [ x [ i ] ] ++ ; if ( mp . size ( ) == 26 ) return true ; else return false ; } int countTotalPangram ( int n ) { int cnt = 0 ; for ( int i = 1 ; i <= n ; i ++ ) if ( Pangram ( weight [ i ] ) ) cnt ++ ; return cnt ; } void dfs ( int node , int parent ) { for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; weight [ node ] += weight [ to ] ; } } int main ( ) { int n = 6 ; weight [ 1 ] = " abcde " ; weight [ 2 ] = " fghijkl " ; weight [ 3 ] = " abcdefg " ; weight [ 4 ] = " mnopqr " ; weight [ 5 ] = " stuvwxy " ; weight [ 6 ] = " zabcdef " ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; graph [ 5 ] . push_back ( 6 ) ; dfs ( 1 , 1 ) ; cout << countTotalPangram ( n ) ; return 0 ; }
Count the nodes of a tree whose weighted string does not contain any duplicate characters | C ++ implementation of the approach ; Function that returns true if the string contains unique characters ; Function to perform dfs ; If weighted string of the current node contains unique characters ; Driver code ; Weights of the nodes ; Edges of the tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; int cnt = 0 ; vector < int > graph [ 100 ] ; vector < string > weight ( 100 ) ; bool uniqueChars ( string x ) { map < char , int > mp ; int n = x . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) mp [ x [ i ] ] ++ ; if ( mp . size ( ) == x . size ( ) ) return true ; else return false ; } void dfs ( int node , int parent ) { if ( uniqueChars ( weight [ node ] ) ) cnt += 1 ; for ( int to : graph [ node ] ) { if ( to == parent ) continue ; dfs ( to , node ) ; } } int main ( ) { weight [ 1 ] = " abc " ; weight [ 2 ] = " aba " ; weight [ 3 ] = " bcb " ; weight [ 4 ] = " moh " ; weight [ 5 ] = " aa " ; graph [ 1 ] . push_back ( 2 ) ; graph [ 2 ] . push_back ( 3 ) ; graph [ 2 ] . push_back ( 4 ) ; graph [ 1 ] . push_back ( 5 ) ; dfs ( 1 , 1 ) ; cout << cnt ; return 0 ; }
Check if a string contains two non overlapping sub | C ++ implementation of the approach ; Function that returns true if s contains two non overlapping sub strings " geek " and " keeg " ; If " geek " and " keeg " are both present in s without over - lapping and " keeg " starts after " geek " ends ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( char s [ ] ) { char * p ; if ( ( p = strstr ( s , " geek " ) ) && ( strstr ( p + 4 , " keeg " ) ) ) return true ; return false ; } int main ( ) { char s [ ] = " geekeekeeg " ; if ( isValid ( s ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Find the last non repeating character in string | C ++ implementation of the approach ; Maximum distinct characters possible ; Function to return the last non - repeating character ; To store the frequency of each of the character of the given string ; Update the frequencies ; Starting from the last character ; Current character ; If frequency of the current character is 1 then return the character ; All the characters of the string are repeating ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX = 256 ; static string lastNonRepeating ( string str , int n ) { int freq [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) freq [ str . at ( i ) ] ++ ; for ( int i = n - 1 ; i >= 0 ; i -- ) { char ch = str . at ( i ) ; if ( freq [ ch ] == 1 ) { string res ; res += ch ; return res ; } } return " - 1" ; } int main ( ) { string str = " GeeksForGeeks " ; int n = str . size ( ) ; cout << lastNonRepeating ( str , n ) ; return 0 ; }
Minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B | C ++ implementation of the approach ; Function to return the minimum number of operations on a binary string such that it gives 10 ^ A as remainder when divided by 10 ^ B ; Initialize result ; Loop through last b digits ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findCount ( string s , int n , int a , int b ) { int res = 0 ; for ( int i = 0 ; i < b ; i ++ ) { if ( i == a ) res += ( s [ n - i - 1 ] != '1' ) ; else res += ( s [ n - i - 1 ] != '0' ) ; } return res ; } int main ( ) { string str = "1001011001" ; int N = str . size ( ) ; int A = 3 , B = 6 ; cout << findCount ( str , N , A , B ) ; return 0 ; }
Find letter 's position in Alphabet using Bit operation | C ++ implementation of the approach ; Function to calculate the position of characters ; Performing AND operation with number 31 ; Driver code
#include <iostream> NEW_LINE using namespace std ; const int NUM = 31 ; void positions ( string str , int n ) { for ( int i = 0 ; i < n ; i ++ ) { cout << ( str [ i ] & NUM ) << " ▁ " ; } } int main ( ) { string str = " Geeks " ; int n = str . length ( ) ; positions ( str , n ) ; return 0 ; }
Generate all permutations of a string that follow given constraints | Simple C ++ program to print all permutations of a string that follow given constraint ; Check if current permutation is valid ; Recursively generate all permutation ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void permute ( string & str , int l , int r ) { if ( l == r ) { if ( str . find ( " AB " ) == string :: npos ) cout << str << " ▁ " ; return ; } for ( int i = l ; i <= r ; i ++ ) { swap ( str [ l ] , str [ i ] ) ; permute ( str , l + 1 , r ) ; swap ( str [ l ] , str [ i ] ) ; } } int main ( ) { string str = " ABC " ; permute ( str , 0 , str . length ( ) - 1 ) ; return 0 ; }
Length of the longest substring that do not contain any palindrome | C ++ implementation of the above approach ; Function to find the length of the longest substring ; initializing the variables ; checking palindrome of size 2 example : aa ; checking palindrome of size 3 example : aba ; else incrementing length of substring ; max1 = max ( max1 , len + 1 ) ; finding maximum ; if there exits single character then it is always palindrome ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int lenoflongestnonpalindrome ( string s ) { int max1 = 1 , len = 0 ; for ( int i = 0 ; i < s . length ( ) - 1 ; i ++ ) { if ( s [ i ] == s [ i + 1 ] ) len = 0 ; else if ( s [ i + 1 ] == s [ i - 1 ] && i > 0 ) len = 1 ; len ++ ; } if ( max1 == 1 ) return 0 ; else return max1 ; } int main ( ) { string s = " synapse " ; cout << lenoflongestnonpalindrome ( s ) << " STRNEWLINE " ; return 0 ; }
Make lexicographically smallest palindrome by substituting missing characters | C ++ implementation of the approach ; Function to return the lexicographically smallest palindrome that can be made from the given string after replacing the required characters ; If characters are missing at both the positions then substitute it with ' a ' ; If only str [ j ] = ' * ' then update it with the value at str [ i ] ; If only str [ i ] = ' * ' then update it with the value at str [ j ] ; If characters at both positions are not equal and != ' * ' then the string cannot be made palindrome ; Return the required palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string makePalindrome ( string str ) { int i = 0 , j = str . length ( ) - 1 ; while ( i <= j ) { if ( str [ i ] == ' * ' && str [ j ] == ' * ' ) { str [ i ] = ' a ' ; str [ j ] = ' a ' ; } else if ( str [ j ] == ' * ' ) str [ j ] = str [ i ] ; else if ( str [ i ] == ' * ' ) str [ i ] = str [ j ] ; else if ( str [ i ] != str [ j ] ) return " - 1" ; i ++ ; j -- ; } return str ; } int main ( ) { string str = " na * an " ; cout << makePalindrome ( str ) ; return 0 ; }
Calculate score for the given binary string | C ++ implementation of the approach ; Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcScore ( string str ) { int score = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ) { int chunkSize = 1 ; char currentChar = str [ i ++ ] ; while ( i < len && str [ i ] == currentChar ) { chunkSize ++ ; i ++ ; } if ( currentChar == '1' ) score += pow ( chunkSize , 2 ) ; else score -= pow ( chunkSize , 2 ) ; } return score ; } int main ( ) { string str = "11011" ; cout << calcScore ( str ) ; return 0 ; }
Number of sub | C ++ implementation of the approach ; Function to return the count of required sub - strings ; Left and right counters for characters on both sides of sub - string window ; Left and right pointer on both sides of sub - string window ; Initialize the frequency ; Result and length of string ; Initialize the left pointer ; Initialize the right pointer ; Traverse all the window sub - strings ; Counting the characters on left side of the sub - string window ; Counting the characters on right side of the sub - string window ; Add the possible sub - strings on both sides to result ; Setting the frequency for next sub - string window ; Reset the left and right counters ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubString ( string s , char c , int k ) { int leftCount = 0 , rightCount = 0 ; int left = 0 , right = 0 ; int freq = 0 ; int result = 0 , len = s . length ( ) ; while ( s [ left ] != c && left < len ) { left ++ ; leftCount ++ ; } right = left + 1 ; while ( freq != ( k - 1 ) && ( right - 1 ) < len ) { if ( s [ right ] == c ) freq ++ ; right ++ ; } while ( left < len && ( right - 1 ) < len ) { while ( s [ left ] != c && left < len ) { left ++ ; leftCount ++ ; } while ( right < len && s [ right ] != c ) { if ( s [ right ] == c ) freq ++ ; right ++ ; rightCount ++ ; } result = result + ( leftCount + 1 ) * ( rightCount + 1 ) ; freq = k - 1 ; leftCount = 0 ; rightCount = 0 ; left ++ ; right ++ ; } return result ; } int main ( ) { string s = " abada " ; char c = ' a ' ; int k = 2 ; cout << countSubString ( s , c , k ) << " STRNEWLINE " ; return 0 ; }
Maximum length palindrome that can be created with characters in range L and R | C ++ implementation of the approach ; Function to return the length of the longest palindrome that can be formed using the characters in the range [ l , r ] ; 0 - based indexing ; Marks if there is an odd frequency character ; Length of the longest palindrome possible from characters in range ; Traverse for all characters and count their frequencies ; Find the frequency in range 1 - r ; Exclude the frequencies in range 1 - ( l - 1 ) ; If frequency is odd , then add 1 less than the original frequency to make it even ; Else completely add if even ; If any odd frequency character is present then add 1 ; Function to pre - calculate the frequencies of the characters to reduce complexity ; Iterate and increase the count ; Create a prefix type array ; Driver code ; Pre - calculate prefix array ; Perform queries
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N 4 NEW_LINE int performQueries ( int l , int r , int prefix [ N ] [ 26 ] ) { l -- ; r -- ; bool flag = false ; int count = 0 ; for ( int i = 0 ; i < 26 ; i ++ ) { int cnt = prefix [ r ] [ i ] ; if ( l > 0 ) cnt -= prefix [ l - 1 ] [ i ] ; if ( cnt % 2 == 1 ) { flag = true ; count += cnt - 1 ; } else count += cnt ; } if ( flag ) count += 1 ; return count ; } void preCalculate ( string s , int prefix [ N ] [ 26 ] ) { int n = s . size ( ) ; for ( int i = 0 ; i < n ; i ++ ) { prefix [ i ] [ s [ i ] - ' a ' ] ++ ; } for ( int i = 1 ; i < n ; i ++ ) { for ( int j = 0 ; j < 26 ; j ++ ) prefix [ i ] [ j ] += prefix [ i - 1 ] [ j ] ; } } int main ( ) { string s = " amim " ; int prefix [ N ] [ 26 ] ; memset ( prefix , 0 , sizeof prefix ) ; preCalculate ( s , prefix ) ; int queries [ ] [ 2 ] = { { 1 , 4 } , { 3 , 4 } } ; int q = sizeof ( queries ) / sizeof ( queries [ 0 ] ) ; for ( int i = 0 ; i < q ; i ++ ) { cout << performQueries ( queries [ i ] [ 0 ] , queries [ i ] [ 1 ] , prefix ) << endl ; } return 0 ; }
Number of times the given string occurs in the array in the range [ l , r ] | C ++ implementation of the approach ; Function to return the number of occurrences of ; To store the indices of strings in the array ; If current string doesn 't have an entry in the map then create the entry ; If the given string is not present in the array ; If the given string is present in the array ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int NumOccurrences ( string arr [ ] , int n , string str , int L , int R ) { unordered_map < string , vector < int > > M ; for ( int i = 0 ; i < n ; i ++ ) { string temp = arr [ i ] ; auto it = M . find ( temp ) ; if ( it == M . end ( ) ) { vector < int > A ; A . push_back ( i + 1 ) ; M . insert ( make_pair ( temp , A ) ) ; } else { it -> second . push_back ( i + 1 ) ; } } auto it = M . find ( str ) ; if ( it == M . end ( ) ) return 0 ; vector < int > A = it -> second ; int y = upper_bound ( A . begin ( ) , A . end ( ) , R ) - A . begin ( ) ; int x = upper_bound ( A . begin ( ) , A . end ( ) , L - 1 ) - A . begin ( ) ; return ( y - x ) ; } int main ( ) { string arr [ ] = { " abc " , " abcabc " , " abc " } ; int n = sizeof ( arr ) / sizeof ( string ) ; int L = 1 ; int R = 3 ; string str = " abc " ; cout << NumOccurrences ( arr , n , str , L , R ) ; return 0 ; }
Check whether the given string is a valid identifier | C ++ implementation of the approach ; Function that returns true if str is a valid identifier ; If first character is invalid ; Traverse the string for the rest of the characters ; String is a valid identifier ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( string str , int n ) { if ( ! ( ( str [ 0 ] >= ' a ' && str [ 0 ] <= ' z ' ) || ( str [ 0 ] >= ' A ' && str [ 0 ] <= ' Z ' ) str [ 0 ] == ' _ ' ) ) return false ; for ( int i = 1 ; i < str . length ( ) ; i ++ ) { if ( ! ( ( str [ i ] >= ' a ' && str [ i ] <= ' z ' ) || ( str [ i ] >= ' A ' && str [ i ] <= ' Z ' ) || ( str [ i ] >= '0' && str [ i ] <= '9' ) str [ i ] == ' _ ' ) ) return false ; } return true ; } int main ( ) { string str = " _ geeks123" ; int n = str . length ( ) ; if ( isValid ( str , n ) ) cout << " Valid " ; else cout << " Invalid " ; return 0 ; }
Check if all the 1 's in a binary string are equidistant or not | C ++ implementation of the approach ; Function that returns true if all the 1 's in the binary string s are equidistant ; Initialize vector to store the position of 1 's ; Store the positions of 1 's ; Size of the position vector ; If condition isn 't satisfied ; Drivers code
#include <bits/stdc++.h> NEW_LINE #include <stdio.h> NEW_LINE using namespace std ; bool check ( string s , int l ) { vector < int > pos ; for ( int i = 0 ; i < l ; i ++ ) { if ( s [ i ] == '1' ) pos . push_back ( i ) ; } int t = pos . size ( ) ; for ( int i = 1 ; i < t ; i ++ ) { if ( ( pos [ i ] - pos [ i - 1 ] ) != ( pos [ 1 ] - pos [ 0 ] ) ) return false ; } return true ; } int main ( ) { string s = "100010001000" ; int l = s . length ( ) ; if ( check ( s , l ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Capitalize the first and last character of each word in a string | CPP program to capitalise the first and last character of each word in a string . ; Create an equivalent string of the given string ; k stores index of first character and i is going to store index of last character . ; Check if the character is a small letter If yes , then Capitalise ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string FirstAndLast ( string str ) { string ch = str ; for ( int i = 0 ; i < ch . length ( ) ; i ++ ) { int k = i ; while ( i < ch . length ( ) && ch [ i ] != ' ▁ ' ) i ++ ; ch [ k ] = ( char ) ( ch [ k ] >= ' a ' && ch [ k ] <= ' z ' ? ( ( int ) ch [ k ] - 32 ) : ( int ) ch [ k ] ) ; ch [ i - 1 ] = ( char ) ( ch [ i - 1 ] >= ' a ' && ch [ i - 1 ] <= ' z ' ? ( ( int ) ch [ i - 1 ] - 32 ) : ( int ) ch [ i - 1 ] ) ; } return ch ; } int main ( ) { string str = " Geeks ▁ for ▁ Geeks " ; cout << str << " STRNEWLINE " ; cout << FirstAndLast ( str ) ; }
Find the number of players who roll the dice when the dice output sequence is given | C ++ implementation of the approach ; Function to return the number of players ; Initialize cnt as 0 ; Iterate in the string ; Check for numbers other than x ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findM ( string s , int x ) { int cnt = 0 ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( s [ i ] - '0' != x ) cnt ++ ; } return cnt ; } int main ( ) { string s = "3662123" ; int x = 6 ; cout << findM ( s , x ) ; return 0 ; }
Print the first and last character of each word in a String | CPP program to print the first and last character of each word in a String ' ; Function to print the first and last character of each word . ; If it is the first word of the string then print it . ; If it is the last word of the string then also print it . ; If there is a space print the successor and predecessor to space . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void FirstAndLast ( string str ) { int i ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { if ( i == 0 ) cout << str [ i ] ; if ( i == str . length ( ) - 1 ) cout << str [ i ] ; if ( str [ i ] == ' ▁ ' ) { cout << str [ i - 1 ] << " ▁ " << str [ i + 1 ] ; } } } int main ( ) { string str = " Geeks ▁ for ▁ Geeks " ; FirstAndLast ( str ) ; }
Find the longest sub | C ++ implementation of the approach ; Function to find longest prefix suffix ; To store longest prefix suffix ; Length of the previous longest prefix suffix ; lps [ 0 ] is always 0 ; Loop calculates lps [ i ] for i = 1 to n - 1 ; ( pat [ i ] != pat [ len ] ) ; If len = 0 ; Function to find the longest substring which is prefix as well as a sub - string of s [ 1. . . n - 2 ] ; Find longest prefix suffix ; If lps of n - 1 is zero ; At any position lps [ i ] equals to lps [ n - 1 ] ; If answer is not possible ; Driver code ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > compute_lps ( string s ) { int n = s . size ( ) ; vector < int > lps ( n ) ; int len = 0 ; lps [ 0 ] = 0 ; int i = 1 ; while ( i < n ) { if ( s [ i ] == s [ len ] ) { len ++ ; lps [ i ] = len ; i ++ ; } else { if ( len != 0 ) len = lps [ len - 1 ] ; else { lps [ i ] = 0 ; i ++ ; } } } return lps ; } void Longestsubstring ( string s ) { vector < int > lps = compute_lps ( s ) ; int n = s . size ( ) ; if ( lps [ n - 1 ] == 0 ) { cout << -1 ; return ; } for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( lps [ i ] == lps [ n - 1 ] ) { cout << s . substr ( 0 , lps [ i ] ) ; return ; } } if ( lps [ lps [ n - 1 ] - 1 ] == 0 ) cout << -1 ; else cout << s . substr ( 0 , lps [ lps [ n - 1 ] - 1 ] ) ; } int main ( ) { string s = " fixprefixsuffix " ; Longestsubstring ( s ) ; return 0 ; }
Pairs of strings which on concatenating contains each character of " string " | C ++ implementation of the approach ; Function to return the bitmask for the string ; Function to return the count of pairs ; bitMask [ i ] will store the count of strings from the array whose bitmask is i ; To store the count of pairs ; MAX - 1 = 63 i . e . 111111 in binary ; arr [ i ] cannot make s pair with itself i . e . ( arr [ i ] , arr [ i ] ) ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX 64 NEW_LINE int getBitmask ( string s ) { int temp = 0 ; for ( int j = 0 ; j < s . length ( ) ; j ++ ) { if ( s [ j ] == ' s ' ) { temp = temp | ( 1 ) ; } else if ( s [ j ] == ' t ' ) { temp = temp | ( 2 ) ; } else if ( s [ j ] == ' r ' ) { temp = temp | ( 4 ) ; } else if ( s [ j ] == ' i ' ) { temp = temp | ( 8 ) ; } else if ( s [ j ] == ' n ' ) { temp = temp | ( 16 ) ; } else if ( s [ j ] == ' g ' ) { temp = temp | ( 32 ) ; } } return temp ; } int countPairs ( string arr [ ] , int n ) { int bitMask [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) bitMask [ getBitmask ( arr [ i ] ) ] ++ ; int cnt = 0 ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = i ; j < MAX ; j ++ ) { if ( ( i j ) == ( MAX - 1 ) ) { if ( i == j ) cnt += ( ( bitMask [ i ] * bitMask [ i ] - 1 ) / 2 ) ; else cnt += ( bitMask [ i ] * bitMask [ j ] ) ; } } } return cnt ; } int main ( ) { string arr [ ] = { " strrr " , " string " , " gstrin " } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << countPairs ( arr , n ) ; return 0 ; }
Find the count of sub | CPP implementation of the approach ; Function to return the count of required occurrence ; To store the count of occurrences ; Check first four characters from ith position ; Variables for counting the required characters ; Check the four contiguous characters which can be reordered to form ' clap ' ; If all four contiguous characters are present then increment cnt variable ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countOcc ( string s ) { int cnt = 0 ; for ( int i = 0 ; i < s . length ( ) - 3 ; i ++ ) { int c = 0 , l = 0 , a = 0 , p = 0 ; for ( int j = i ; j < i + 4 ; j ++ ) { switch ( s [ j ] ) { case ' c ' : c ++ ; break ; case ' l ' : l ++ ; break ; case ' a ' : a ++ ; break ; case ' p ' : p ++ ; break ; } } if ( c == 1 && l == 1 && a == 1 && p == 1 ) cnt ++ ; } return cnt ; } int main ( ) { string s = " clapc " ; transform ( s . begin ( ) , s . end ( ) , s . begin ( ) , :: tolower ) ; cout << ( countOcc ( s ) ) ; }
Count of pairs of strings which differ in exactly one position | CPP implementation of the approach ; Function to return the count of same pairs ; Function to return total number of strings which satisfy required condition ; Dictionary changed will store strings with wild cards Dictionary same will store strings that are equal ; Iterating for all strings in the given array ; If we found the string then increment by 1 Else it will get default value 0 ; Iterating on a single string ; Incrementing the string if found Else it will get default value 0 ; Return counted pairs - equal pairs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pairCount ( map < string , int > & d ) { int sum = 0 ; for ( auto i : d ) sum += ( i . second * ( i . second - 1 ) ) / 2 ; return sum ; } int difference ( vector < string > & array , int m ) { map < string , int > changed , same ; for ( auto s : array ) { same [ s ] ++ ; for ( int i = 0 ; i < m ; i ++ ) { changed [ t ] ++ ; } } return pairCount ( changed ) - pairCount ( same ) * m ; } int main ( ) { int n = 3 , m = 3 ; vector < string > array = { " abc " , " abd " , " bbd " } ; cout << difference ( array , m ) << endl ; return 0 ; }
Number of ways in which the substring in range [ L , R ] can be formed using characters out of the range | C ++ implementation of the approach ; Function to return the number of ways to form the sub - string ; Initialize a hash - table with 0 ; Iterate in the string and count the frequency of characters that do not lie in the range L and R ; Out of range characters ; Stores the final number of ways ; Iterate for the sub - string in the range L and R ; If exists then multiply the number of ways and decrement the frequency ; If does not exist the sub - string cannot be formed ; Return the answer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calculateWays ( string s , int n , int l , int r ) { int freq [ 26 ] ; memset ( freq , 0 , sizeof freq ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < l i > r ) freq [ s [ i ] - ' a ' ] ++ ; } int ways = 1 ; for ( int i = l ; i <= r ; i ++ ) { if ( freq [ s [ i ] - ' a ' ] ) { ways = ways * freq [ s [ i ] - ' a ' ] ; freq [ s [ i ] - ' a ' ] -- ; } else { ways = 0 ; break ; } } return ways ; } int main ( ) { string s = " cabcaab " ; int n = s . length ( ) ; int l = 1 , r = 3 ; cout << calculateWays ( s , n , l , r ) ; return 0 ; }
Program to find the kth character after decrypting a string | C ++ implementation of the approach ; Function to print kth character of String s after decrypting it ; Get the length of string ; Initialise pointer to character of input string to zero ; Total length of resultant string ; Traverse the string from starting and check if each character is alphabet then increment total_len ; If total_leg equal to k then return string else increment i ; Parse the number ; Update next_total_len ; Get the position of kth character ; Position not found then update position with total_len ; Recursively find the kth position ; Else update total_len by next_total_len ; Return - 1 if character not found ; Driver code
#include <cstdlib> NEW_LINE #include <iostream> NEW_LINE using namespace std ; char findKthChar ( string s , int k ) { int len = s . length ( ) ; int i = 0 ; int total_len = 0 ; while ( i < len ) { if ( isalpha ( s [ i ] ) ) { total_len ++ ; if ( total_len == k ) return s [ i ] ; i ++ ; } else { int n = 0 ; while ( i < len && ! isalpha ( s [ i ] ) ) { n = n * 10 + ( s [ i ] - '0' ) ; i ++ ; } int next_total_len = total_len * n ; if ( k <= next_total_len ) { int pos = k % total_len ; if ( ! pos ) { pos = total_len ; } return findKthChar ( s , pos ) ; } else { total_len = next_total_len ; } } } return -1 ; } int main ( ) { string s = " ab2c3" ; int k = 5 ; cout << findKthChar ( s , k ) ; return 0 ; }
Check whether the Average Character of the String is present or not | CPP program to check if the average character is present in the string or not ; Checks if the character is present ; Get the length of string ; Iterate from i = 0 to the length of the string to check if the character is present in the string ; Finds the average character of the string ; Calculate the sum of ASCII values of each character ; Calculate average of ascii values ; Convert the ASCII value to character and return it ; Driver code ; Get the average character ; Check if the average character is present in string or not
#include <bits/stdc++.h> NEW_LINE #include <math.h> NEW_LINE using namespace std ; bool check_char ( char * st , char ch ) { int l = strlen ( st ) ; for ( int i = 0 ; i < l ; i ++ ) { if ( st [ i ] == ch ) return true ; } return false ; } char find_avg ( char * st ) { int i , sm = 0 ; int l = strlen ( st ) ; char ch ; for ( i = 0 ; i < l ; i ++ ) { ch = st [ i ] ; sm = sm + ( int ) ( ch ) ; } int avg = ( int ) ( floor ( sm / l ) ) ; return ( ( char ) ( avg ) ) ; } int main ( ) { char st [ ] = " ag23sdfa " ; char ch = find_avg ( st ) ; cout << ch << endl ; if ( check_char ( st , ch ) == true ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Convert the ASCII value sentence to its equivalent string | C ++ implementation of the approach ; Function to print the character sequence for the given ASCII sentence ; Append the current digit ; If num is within the required range ; Convert num to char ; Reset num to 0 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void asciiToSentence ( string str , int len ) { int num = 0 ; for ( int i = 0 ; i < len ; i ++ ) { num = num * 10 + ( str [ i ] - '0' ) ; if ( num >= 32 && num <= 122 ) { char ch = ( char ) num ; cout << ch ; num = 0 ; } } } int main ( ) { string str = "7110110110711510211111471101101107115" ; int len = str . length ( ) ; asciiToSentence ( str , len ) ; return 0 ; }
Distinct state codes that appear in a string as contiguous sub | C ++ implementation of the approach ; Function to return the count of distinct state codes ; Insert every sub - string of length 2 in the set ; Return the size of the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countDistinctCode ( string str ) { set < string > codes ; for ( int i = 0 ; i < str . length ( ) - 1 ; i ++ ) codes . insert ( str . substr ( i , 2 ) ) ; return codes . size ( ) ; } int main ( ) { string str = " UPUP " ; cout << countDistinctCode ( str ) ; return 0 ; }
Count of buttons pressed in a keypad mobile | C ++ implementation of the approach ; Array to store how many times a button has to be pressed for typing a particular character ; Function to return the count of buttons pressed to type the given string ; Count the key presses ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int arr [ ] = { 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3 , 4 , 1 , 2 , 3 , 1 , 2 , 3 , 4 } ; int countKeyPressed ( string str , int len ) { int count = 0 ; for ( int i = 0 ; i < len ; i ++ ) count = count + arr [ str [ i ] - ' a ' ] ; return count ; } int main ( ) { string str = " abcdef " ; int len = str . length ( ) ; cout << countKeyPressed ( str , len ) ; return 0 ; }
First string from the given array whose reverse is also present in the same array | CPP implementation of the approach ; Function that returns true if s1 is equal to reverse of s2 ; If both the strings differ in length ; In case of any character mismatch ; Function to return the first word whose reverse is also present in the array ; Check every string ; Pair with every other string appearing after the current string ; If first string is equal to the reverse of the second string ; No such string exists ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isReverseEqual ( string s1 , string s2 ) { if ( s1 . length ( ) != s2 . length ( ) ) return false ; int len = s1 . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) if ( s1 [ i ] != s2 [ len - i - 1 ] ) return false ; return true ; } string getWord ( string str [ ] , int n ) { for ( int i = 0 ; i < n - 1 ; i ++ ) for ( int j = i + 1 ; j < n ; j ++ ) if ( isReverseEqual ( str [ i ] , str [ j ] ) ) return str [ i ] ; return " - 1" ; } int main ( ) { string str [ ] = { " geeks " , " for " , " skeeg " } ; cout << ( getWord ( str , 3 ) ) ; }
Check if the given string is K | CPP implementation of the approach ; Function that return true if sub - string of length k starting at index i is also a prefix of the string ; k length sub - string cannot start at index i ; Character mismatch between the prefix and the sub - string starting at index i ; Function that returns true if str is K - periodic ; Check whether all the sub - strings str [ 0 , k - 1 ] , str [ k , 2 k - 1 ] ... are equal to the k length prefix of the string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPrefix ( string str , int len , int i , int k ) { if ( i + k > len ) return false ; for ( int j = 0 ; j < k ; j ++ ) { if ( str [ i ] != str [ j ] ) return false ; i ++ ; } return true ; } bool isKPeriodic ( string str , int len , int k ) { for ( int i = k ; i < len ; i += k ) if ( ! isPrefix ( str , len , i , k ) ) return false ; return true ; } int main ( ) { string str = " geeksgeeks " ; int len = str . length ( ) ; int k = 5 ; if ( isKPeriodic ( str , len , k ) ) cout << ( " Yes " ) ; else cout << ( " No " ) ; }
Minimum number of letters needed to make a total of n | C ++ implementation of the approach ; Function to return the minimum letters required to make a total of n ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minLettersNeeded ( int n ) { if ( n % 26 == 0 ) return ( n / 26 ) ; else return ( ( n / 26 ) + 1 ) ; } int main ( ) { int n = 52 ; cout << minLettersNeeded ( n ) ; return 0 ; }
Find the first maximum length even word from a string | C ++ program to find maximum length even word ; Function to find maximum length even word ; To store length of current word . ; To store length of maximum length word . ; To store starting index of maximum length word . ; If current character is space then word has ended . Check if it is even length word or not . If yes then compare length with maximum length found so far . ; Set currlen to zero for next word . ; Update length of current word . ; Check length of last word . ; If no even length word is present then return - 1. ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findMaxLenEven ( string str ) { int n = str . length ( ) ; int i = 0 ; int currlen = 0 ; int maxlen = 0 ; int st = -1 ; while ( i < n ) { if ( str [ i ] == ' ▁ ' ) { if ( currlen % 2 == 0 ) { if ( maxlen < currlen ) { maxlen = currlen ; st = i - currlen ; } } currlen = 0 ; } else { currlen ++ ; } i ++ ; } if ( currlen % 2 == 0 ) { if ( maxlen < currlen ) { maxlen = currlen ; st = i - currlen ; } } if ( st == -1 ) return " - 1" ; return str . substr ( st , maxlen ) ; } int main ( ) { string str = " this ▁ is ▁ a ▁ test ▁ string " ; cout << findMaxLenEven ( str ) ; return 0 ; }
Minimum length substring with exactly K distinct characters | C ++ program to find minimum length substring having exactly k distinct character . ; Function to find minimum length substring having exactly k distinct character . ; Starting index of sliding window . ; Ending index of sliding window . ; To store count of character . ; To store count of distinct character in current sliding window . ; To store length of current sliding window . ; To store minimum length . ; To store starting index of minimum length substring . ; Increment count of current character If this count is one then a new distinct character is found in sliding window . ; If number of distinct characters is is greater than k , then move starting point of sliding window forward , until count is k . ; Remove characters from the beginning of sliding window having count more than 1 to minimize length . ; Compare length with minimum length and update if required . ; Return minimum length substring . ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findMinLenStr ( string str , int k ) { int n = str . length ( ) ; int st = 0 ; int end = 0 ; int cnt [ 26 ] ; memset ( cnt , 0 , sizeof ( cnt ) ) ; int distEle = 0 ; int currlen ; int minlen = n ; int startInd = -1 ; while ( end < n ) { cnt [ str [ end ] - ' a ' ] ++ ; if ( cnt [ str [ end ] - ' a ' ] == 1 ) distEle ++ ; if ( distEle > k ) { while ( st < end && distEle > k ) { if ( cnt [ str [ st ] - ' a ' ] == 1 ) distEle -- ; cnt [ str [ st ] - ' a ' ] -- ; st ++ ; } } if ( distEle == k ) { while ( st < end && cnt [ str [ st ] - ' a ' ] > 1 ) { cnt [ str [ st ] - ' a ' ] -- ; st ++ ; } currlen = end - st + 1 ; if ( currlen < minlen ) { minlen = currlen ; startInd = st ; } } end ++ ; } return str . substr ( startInd , minlen ) ; } int main ( ) { string str = " efecfefd " ; int k = 4 ; cout << findMinLenStr ( str , k ) ; return 0 ; }
Minimum number of replacements to make the binary string alternating | Set 2 | C ++ implementation of the approach ; Function to return the minimum number of characters of the given binary string to be replaced to make the string alternating ; If there is 1 at even index positions ; If there is 0 at odd index positions ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minReplacement ( string s , int len ) { int ans = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( i % 2 == 0 && s [ i ] == '1' ) ans ++ ; if ( i % 2 == 1 && s [ i ] == '0' ) ans ++ ; } return min ( ans , len - ans ) ; } int main ( ) { string s = "1100" ; int len = s . size ( ) ; cout << minReplacement ( s , len ) ; return 0 ; }
Deletions of "01" or "10" in binary string to make it free from "01" or "10" | C ++ implementation of the approach ; Function to return the count of deletions of sub - strings "01" or "10" ; To store the count of 0 s and 1 s ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int substrDeletion ( string str , int len ) { int count0 = 0 , count1 = 0 ; for ( int i = 0 ; i < len ; i ++ ) { if ( str [ i ] == '0' ) count0 ++ ; else count1 ++ ; } return min ( count0 , count1 ) ; } int main ( ) { string str = "010" ; int len = str . length ( ) ; cout << substrDeletion ( str , len ) ; return 0 ; }
Group consecutive characters of same type in a string | C ++ implementation of the approach ; Function to return the modified string ; Store original string ; Remove all white spaces ; To store the resultant string ; Traverse the string ; Group upper case characters ; Group numeric characters ; Group arithmetic operators ; Return the resultant string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string groupCharacters ( string s , int len ) { string temp = " " ; for ( int i = 0 ; i < len ; i ++ ) if ( s [ i ] != ' ▁ ' ) temp = temp + s [ i ] ; len = temp . length ( ) ; string ans = " " ; int i = 0 ; while ( i < len ) { if ( int ( temp [ i ] ) >= int ( ' A ' ) && int ( temp [ i ] ) <= int ( ' Z ' ) ) { while ( i < len && int ( temp [ i ] ) >= int ( ' A ' ) && int ( temp [ i ] ) <= int ( ' Z ' ) ) { ans = ans + temp [ i ] ; i ++ ; } ans = ans + " ▁ " ; } else if ( int ( temp [ i ] ) >= int ( '0' ) && int ( temp [ i ] ) <= int ( '9' ) ) { while ( i < len && int ( temp [ i ] ) >= int ( '0' ) && int ( temp [ i ] ) <= int ( '9' ) ) { ans = ans + temp [ i ] ; i ++ ; } ans = ans + " ▁ " ; } else { while ( i < len && int ( temp [ i ] ) >= int ( ' * ' ) && int ( temp [ i ] ) <= int ( ' / ' ) ) { ans = ans + temp [ i ] ; i ++ ; } ans = ans + " ▁ " ; } } return ans ; } int main ( ) { string s = "34FTG234 + ▁ + - ▁ * " ; int len = s . length ( ) ; cout << groupCharacters ( s , len ) ; return 0 ; }
Find the minimum number of preprocess moves required to make two strings equal | C ++ implementation of the approach ; Function to return the minimum number of pre - processing moves required on string A ; Length of the given strings ; To store the required answer ; Run a loop upto n / 2 ; To store frequency of 4 characters ; If size is 4 ; If size is 3 ; If size is 2 ; If n is odd ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int Preprocess ( string A , string B ) { int n = A . size ( ) ; int ans = 0 ; for ( int i = 0 ; i < n / 2 ; i ++ ) { map < char , int > mp ; mp [ A [ i ] ] ++ ; mp [ A [ n - i - 1 ] ] ++ ; mp [ B [ i ] ] ++ ; mp [ B [ n - i - 1 ] ] ++ ; int sz = mp . size ( ) ; if ( sz == 4 ) ans += 2 ; else if ( sz == 3 ) ans += 1 + ( A [ i ] == A [ n - i - 1 ] ) ; else if ( sz == 2 ) ans += mp [ A [ i ] ] != 2 ; } if ( n % 2 == 1 && A [ n / 2 ] != B [ n / 2 ] ) ans ++ ; return ans ; } int main ( ) { string A = " abacaba " , B = " bacabaa " ; cout << Preprocess ( A , B ) ; return 0 ; }
Check whether two strings are equivalent or not according to given condition | CPP Program to find whether two strings are equivalent or not according to given condition ; This function returns the least lexicogr aphical string obtained from its two halves ; Base Case - If string size is 1 ; Divide the string into its two halves ; Form least lexicographical string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string leastLexiString ( string s ) { if ( s . size ( ) & 1 ) return s ; string x = leastLexiString ( s . substr ( 0 , s . size ( ) / 2 ) ) ; string y = leastLexiString ( s . substr ( s . size ( ) / 2 ) ) ; return min ( x + y , y + x ) ; } bool areEquivalent ( string a , string b ) { return ( leastLexiString ( a ) == leastLexiString ( b ) ) ; } int main ( ) { string a = " aaba " ; string b = " abaa " ; if ( areEquivalent ( a , b ) ) cout << " YES " << endl ; else cout << " NO " << endl ; a = " aabb " ; b = " abab " ; if ( areEquivalent ( a , b ) ) cout << " YES " << endl ; else cout << " NO " << endl ; return 0 ; }
Check if a string can be converted to another string by replacing vowels and consonants | C ++ program to check if a string can be converted to other string by replacing vowels and consonants ; Function to check if the character is vowel or not ; Function that checks if a string can be converted to another string ; Find length of string ; If length is not same ; Iterate for every character ; If both vowel ; Both are consonants ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isVowel ( char c ) { if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } bool checkPossibility ( string s1 , string s2 ) { int l1 = s1 . length ( ) ; int l2 = s2 . length ( ) ; if ( l1 != l2 ) return false ; for ( int i = 0 ; i < l1 ; i ++ ) { if ( isVowel ( s1 [ i ] ) && isVowel ( s2 [ i ] ) ) continue ; else if ( ! ( isVowel ( s1 [ i ] ) ) && ! ( isVowel ( s2 [ i ] ) ) ) continue ; else return false ; } return true ; } int main ( ) { string S1 = " abcgle " , S2 = " ezggli " ; if ( checkPossibility ( S1 , S2 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }
Generate a string consisting of characters ' a ' and ' b ' that satisfy the given conditions | C ++ implementation of the approach ; Function to generate and print the required string ; More ' b ' , append " bba " ; More ' a ' , append " aab " ; Equal number of ' a ' and ' b ' append " ab " ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void generateString ( int A , int B ) { string rt ; while ( 0 < A 0 < B ) { if ( A < B ) { if ( 0 < B -- ) rt . push_back ( ' b ' ) ; if ( 0 < B -- ) rt . push_back ( ' b ' ) ; if ( 0 < A -- ) rt . push_back ( ' a ' ) ; } else if ( B < A ) { if ( 0 < A -- ) rt . push_back ( ' a ' ) ; if ( 0 < A -- ) rt . push_back ( ' a ' ) ; if ( 0 < B -- ) rt . push_back ( ' b ' ) ; } else { if ( 0 < A -- ) rt . push_back ( ' a ' ) ; if ( 0 < B -- ) rt . push_back ( ' b ' ) ; } } cout << rt ; } int main ( ) { int A = 2 , B = 6 ; generateString ( A , B ) ; return 0 ; }
Number of strings that satisfy the given condition | C ++ implementation of the approach ; Function to return the count of valid strings ; Set to store indices of valid strings ; Find the maximum digit for current position ; Add indices of all the strings in the set that contain maximal digit ; Return number of strings in the set ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countStrings ( int n , int m , string s [ ] ) { unordered_set < int > ind ; for ( int j = 0 ; j < m ; j ++ ) { int mx = 0 ; for ( int i = 0 ; i < n ; i ++ ) mx = max ( mx , ( int ) s [ i ] [ j ] - '0' ) ; for ( int i = 0 ; i < n ; i ++ ) if ( s [ i ] [ j ] - '0' == mx ) ind . insert ( i ) ; } return ind . size ( ) ; } int main ( ) { string s [ ] = { "223" , "232" , "112" } ; int m = s [ 0 ] . length ( ) ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; cout << countStrings ( n , m , s ) ; }
Lexicographically largest sub | C ++ implementation of the approach ; Function to return the lexicographically largest sub - sequence of s ; Get the max character from the string ; Use all the occurrences of the current maximum character ; Repeat the steps for the remaining string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string getSubSeq ( string s , int n ) { string res = " " ; int cr = 0 ; while ( cr < n ) { char mx = s [ cr ] ; for ( int i = cr + 1 ; i < n ; i ++ ) mx = max ( mx , s [ i ] ) ; int lst = cr ; for ( int i = cr ; i < n ; i ++ ) if ( s [ i ] == mx ) { res += s [ i ] ; lst = i ; } cr = lst + 1 ; } return res ; } int main ( ) { string s = " geeksforgeeks " ; int n = s . length ( ) ; cout << getSubSeq ( s , n ) ; }
Validation of Equation Given as String | C ++ implementation of the approach ; Function that returns true if the equation is valid ; If it is an integer then add it to another string array ; Evaluation of 1 st operator ; Evaluation of 2 nd operator ; Evaluation of 3 rd operator ; If the LHS result is equal to the RHS ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isValid ( string str ) { int k = 0 ; string operands [ 5 ] = " " ; char operators [ 4 ] ; long ans = 0 , ans1 = 0 , ans2 = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != ' + ' && str [ i ] != ' = ' && str [ i ] != ' - ' ) operands [ k ] += str [ i ] ; else { operators [ k ] = str [ i ] ; if ( k == 1 ) { if ( operators [ k - 1 ] == ' + ' ) ans += stol ( operands [ k - 1 ] ) + stol ( operands [ k ] ) ; if ( operators [ k - 1 ] == ' - ' ) ans += stol ( operands [ k - 1 ] ) - stol ( operands [ k ] ) ; } if ( k == 2 ) { if ( operators [ k - 1 ] == ' + ' ) ans1 += ans + stol ( operands [ k ] ) ; if ( operators [ k - 1 ] == ' - ' ) ans1 -= ans - stol ( operands [ k ] ) ; } if ( k == 3 ) { if ( operators [ k - 1 ] == ' + ' ) ans2 += ans1 + stol ( operands [ k ] ) ; if ( operators [ k - 1 ] == ' - ' ) ans2 -= ans1 - stol ( operands [ k ] ) ; } k ++ ; } } if ( ans2 == stol ( operands [ 4 ] ) ) return true ; else return false ; } int main ( ) { string str = "2 + 5 + 3 + 1 = 11" ; if ( isValid ( str ) ) cout << " Valid " ; else cout << " Invalid " ; return 0 ; }
Minimum replacements such that the difference between the index of the same characters is divisible by 3 | C ++ program to find minimum replacements such that the difference between the index of the same characters is divisible by 3 ; Function to count the number of minimal replacements ; Generate all permutations ; Count the replacements ; Return the replacements ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinimalReplacements ( string s ) { int n = s . length ( ) ; int mini = INT_MAX ; string dup = "012" ; do { int dif = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( s [ i ] != dup [ i % 3 ] ) dif ++ ; mini = min ( mini , dif ) ; } while ( next_permutation ( dup . begin ( ) , dup . end ( ) ) ) ; return mini ; } int main ( ) { string s = "2101200" ; cout << countMinimalReplacements ( s ) ; return 0 ; }
Count of sub | C ++ implementation of the approach ; Function to return the count of sub - strings of str that are divisible by k ; Take all sub - strings starting from i ; If current sub - string is divisible by k ; Return the required count ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countSubStr ( string str , int len , int k ) { int count = 0 ; for ( int i = 0 ; i < len ; i ++ ) { int n = 0 ; for ( int j = i ; j < len ; j ++ ) { n = n * 10 + ( str [ j ] - '0' ) ; if ( n % k == 0 ) count ++ ; } } return count ; } int main ( ) { string str = "33445" ; int len = str . length ( ) ; int k = 11 ; cout << countSubStr ( str , len , k ) ; return 0 ; }
Find the resulting Colour Combination | C ++ program to find the resultant colour combination ; Function to return Colour Combination ; Check for B * G = Y ; Check for B * Y = G ; Check for Y * G = B ; Driver Code
#include <iostream> NEW_LINE using namespace std ; char Colour_Combination ( string s ) { char temp = s [ 0 ] ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( temp != s [ i ] ) { if ( ( temp == ' B ' temp == ' G ' ) && ( s [ i ] == ' G ' s [ i ] == ' B ' ) ) temp = ' Y ' ; else if ( ( temp == ' B ' temp == ' Y ' ) && ( s [ i ] == ' Y ' s [ i ] == ' B ' ) ) temp = ' G ' ; else temp = ' B ' ; } } return temp ; } int main ( int argc , char * * argv ) { string s = " GBYGB " ; cout << Colour_Combination ( s ) ; }
Reverse Middle X Characters | C ++ implementation of the approach ; Function to reverse the middle x characters in a string ; Find the position from where the characters have to be reversed ; Print the first n characters ; Print the middle x characters in reverse ; Print the last n characters ; Driver code
#include <iostream> NEW_LINE using namespace std ; void reverse ( string str , int x ) { int n = ( str . length ( ) - x ) / 2 ; for ( int i = 0 ; i < n ; i ++ ) cout << str [ i ] ; for ( int i = n + x - 1 ; i >= n ; i -- ) cout << str [ i ] ; for ( int i = n + x ; i < str . length ( ) ; i ++ ) cout << str [ i ] ; } int main ( ) { string str = " geeksforgeeks " ; int x = 3 ; reverse ( str , x ) ; return 0 ; }
Minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | CPP program to Minimize the number of replacements to get a string with same number of a , b and c in it ; Function to count numbers ; Count the number of ' a ' , ' b ' and ' c ' in string ; If equal previously ; If not a multiple of 3 ; Increase the number of a ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' b ' and ;c; ; Check if it is ' b ' and it more than n / 3 ; Check if it is ' c ' and it more than n / 3 ; Increase the number of b ' s ▁ by ▁ ▁ removing ▁ extra ▁ ' c ' ; Check if it is ' c ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of b 's from back ; Check if it is ' a ' and it more than n / 3 ; Increase the number of c 's from back ; Check if it is ' b ' and it more than n / 3 ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string lexoSmallest ( string s , int n ) { int ca = 0 , cb = 0 , cc = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' a ' ) ca ++ ; else if ( s [ i ] == ' b ' ) cb ++ ; else cc ++ ; } if ( ca == cb && cb == cc ) { return s ; } int cnt = n / 3 ; if ( cnt * 3 != n ) { return " - 1" ; } int i = 0 ; while ( ca < cnt && i < n ) { if ( s [ i ] == ' b ' && cb > cnt ) { cb -- ; s [ i ] = ' a ' ; ca ++ ; } else if ( s [ i ] == ' c ' && cc > cnt ) { cc -- ; s [ i ] = ' a ' ; ca ++ ; } i ++ ; } i = 0 ; while ( cb < cnt && i < n ) { if ( s [ i ] == ' c ' && cc > cnt ) { cc -- ; s [ i ] = '1' ; cb ++ ; } i ++ ; } i = n - 1 ; while ( cc < cnt && i >= 0 ) { if ( s [ i ] == ' a ' && ca > cnt ) { ca -- ; s [ i ] = ' c ' ; cc ++ ; } i -- ; } i = n - 1 ; while ( cb < cnt && i >= 0 ) { if ( s [ i ] == ' a ' && ca > cnt ) { ca -- ; s [ i ] = ' b ' ; cb ++ ; } i -- ; } i = n - 1 ; while ( cc < cnt && i >= 0 ) { if ( s [ i ] == ' b ' && cb > cnt ) { cb -- ; s [ i ] = ' c ' ; cc ++ ; } i -- ; } return s ; } int main ( ) { string s = " aaaaaa " ; int n = s . size ( ) ; cout << lexoSmallest ( s , n ) ; return 0 ; }
Minimum moves to reach from i to j in a cyclic string | C ++ implementation of the approach ; Function to return the count of steps required to move from i to j ; Starting from i + 1 ; Count of steps ; Current character ; If current character is different from previous ; Increment steps ; Update current character ; Return total steps ; Function to return the minimum number of steps required to reach j from i ; Swap the values so that i <= j ; Steps to go from i to j ( left to right ) ; While going from i to j ( right to left ) First go from i to 0 then from ( n - 1 ) to j ; If first and last character is different then it 'll add a step to stepsToLeft ; Return the minimum of two paths ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getSteps ( string str , int i , int j , int n ) { int k = i + 1 ; int steps = 0 ; char ch = str [ i ] ; while ( k <= j ) { if ( str [ k ] != ch ) { steps ++ ; ch = str [ k ] ; } k ++ ; } return steps ; } int getMinSteps ( string str , int i , int j , int n ) { if ( j < i ) { int temp = i ; i = j ; j = temp ; } int stepsToRight = getSteps ( str , i , j , n ) ; int stepsToLeft = getSteps ( str , 0 , i , n ) + getSteps ( str , j , n - 1 , n ) ; if ( str [ 0 ] != str [ n - 1 ] ) stepsToLeft ++ ; return min ( stepsToLeft , stepsToRight ) ; } int main ( ) { string str = " SSNSS " ; int n = str . length ( ) ; int i = 0 , j = 3 ; cout << getMinSteps ( str , i , j , n ) ; return 0 ; }
Count distinct substrings that contain some characters at most k times | C ++ implementation of the approach ; Function to return the count of valid sub - strings ; Store all characters of anotherStr in a direct index table for quick lookup . ; To store distinct output substrings ; Traverse through the given string and one by one generate substrings beginning from s [ i ] . ; One by one generate substrings ending with s [ j ] ; If character is illegal ; If current substring is valid ; If current substring is invalid , adding more characters would not help . ; Return the count of distinct sub - strings ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int MAX_CHAR = 256 ; int countSubStrings ( string s , string anotherStr , int k ) { bool illegal [ MAX_CHAR ] = { false } ; for ( int i = 0 ; i < anotherStr . size ( ) ; i ++ ) illegal [ anotherStr [ i ] ] = true ; unordered_set < string > us ; for ( int i = 0 ; i < s . size ( ) ; ++ i ) { string ss = " " ; int count = 0 ; for ( int j = i ; j < s . size ( ) ; ++ j ) { if ( illegal [ s [ j ] ] ) ++ count ; ss = ss + s [ j ] ; if ( count <= k ) { us . insert ( ss ) ; } else break ; } } return us . size ( ) ; } int main ( ) { string str = " acbacbacaa " ; string anotherStr = " abcdefghijklmnopqrstuvwxyz " ; int k = 2 ; cout << countSubStrings ( str , anotherStr , k ) ; return 0 ; }
Count pairs of parentheses sequences such that parentheses are balanced | C ++ program to count the number of pairs of balanced parentheses ; Function to count the number of pairs ; Hashing function to count the opening and closing brackets ; Traverse for all bracket sequences ; Get the string ; Counts the opening and closing required ; Traverse in the string ; If it is a opening bracket ; else Closing bracket ; If openings are there , then close it ; else Else increase count of closing ; If requirements of openings are there and no closing ; If requirements of closing are there and no opening ; Perfect ; Divide by two since two perfect makes one pair ; Traverse in the open and find corresponding minimum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countPairs ( string bracks [ ] , int num ) { unordered_map < int , int > open , close ; int cnt = 0 ; for ( int i = 0 ; i < num ; i ++ ) { string s = bracks [ i ] ; int l = s . length ( ) ; int op = 0 , cl = 0 ; for ( int j = 0 ; j < l ; j ++ ) { if ( s [ j ] == ' ( ' ) op ++ ; { if ( op ) op -- ; cl ++ ; } } if ( op && ! cl ) open [ op ] ++ ; if ( cl && ! op ) close [ cl ] ++ ; if ( ! op && ! cl ) cnt ++ ; } cnt = cnt / 2 ; for ( auto it : open ) cnt += min ( it . second , close [ it . first ] ) ; return cnt ; } int main ( ) { string bracks [ ] = { " ) ( ) ) " , " ) " , " ( ( " , " ( ( " , " ( " , " ) " , " ) " } ; int num = sizeof ( bracks ) / sizeof ( bracks [ 0 ] ) ; cout << countPairs ( bracks , num ) ; }
Decrypt a string according to given rules | C ++ program to decrypt the original string ; Function to return the original string after decryption ; Stores the decrypted string ; If length is odd ; Step counter ; Starting and ending index ; Iterate till all characters are decrypted ; Even step ; Odd step ; If length is even ; Step counter ; Starting and ending index ; Even step ; Odd step ; Reverse the decrypted string ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string decrypt ( string s , int l ) { string ans = " " ; if ( l % 2 ) { int cnt = 0 ; int indl = 0 , indr = l - 1 ; while ( ans . size ( ) != l ) { if ( cnt % 2 == 0 ) ans += s [ indl ++ ] ; else ans += s [ indr -- ] ; cnt ++ ; } } else { int cnt = 0 ; int indl = 0 , indr = l - 1 ; while ( ans . size ( ) != l ) { if ( cnt % 2 == 0 ) ans += s [ indr -- ] ; else ans += s [ indl ++ ] ; cnt ++ ; } } reverse ( ans . begin ( ) , ans . end ( ) ) ; return ans ; } int main ( ) { string s = " segosegekfrek " ; int l = s . length ( ) ; cout << decrypt ( s , l ) ; return 0 ; }
Remove consecutive alphabets which are in same case | C ++ program to remove the consecutive characters from a string that are in same case ; Function to return the modified string ; Traverse through the remaining characters in the string ; If the current and the previous characters are not in the same case then take the character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string removeChars ( string s ) { string modifiedStr = " " ; modifiedStr += s [ 0 ] ; for ( int i = 1 ; i < s . length ( ) ; i ++ ) { if ( isupper ( s [ i ] ) && islower ( s [ i - 1 ] ) || islower ( s [ i ] ) && isupper ( s [ i - 1 ] ) ) modifiedStr += s [ i ] ; } return modifiedStr ; } int main ( ) { string s = " GeeksForGeeks " ; cout << removeChars ( s ) ; return 0 ; }
Cost to make a string Panagram | C ++ program to find the cost to make a string Panagram ; Function to return the total cost required to make the string Pangram ; Mark all the alphabets that occurred in the string ; Calculate the total cost for the missing alphabets ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int pangramCost ( int arr [ ] , string str ) { int cost = 0 ; bool occurred [ 26 ] = { false } ; for ( int i = 0 ; i < str . size ( ) ; i ++ ) occurred [ str [ i ] - ' a ' ] = true ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( ! occurred [ i ] ) cost += arr [ i ] ; } return cost ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23 , 24 , 25 , 26 } ; string str = " abcdefghijklmopqrstuvwz " ; cout << pangramCost ( arr , str ) ; return 0 ; }
Recursive program to insert a star between pair of identical characters | Recursive CPP program to insert * between two consecutive same characters . ; Function to insert * at desired position ; Append current character ; If we reached last character ; If next character is same , append ' * ' ; Driver code
#include <iostream> NEW_LINE using namespace std ; void pairStar ( string & input , string & output , int i = 0 ) { output = output + input [ i ] ; if ( i == input . length ( ) - 1 ) return ; if ( input [ i ] == input [ i + 1 ] ) output = output + ' * ' ; pairStar ( input , output , i + 1 ) ; } int main ( ) { string input = " geeks " , output = " " ; pairStar ( input , output ) ; cout << output << endl ; return 0 ; }
Maximum number of removals of given subsequence from a string | C ++ implementation of the approach ; Function to return max possible operation of the given type that can be performed on str ; Increment count of sub - sequence ' g ' ; Increment count of sub - sequence ' gk ' if ' g ' is available ; Increment count of sub - sequence ' gks ' if sub - sequence ' gk ' appeared previously ; Return the count of sub - sequence ' gks ' ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maxOperations ( string str ) { int i , g , gk , gks ; i = g = gk = gks = 0 ; for ( i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] == ' g ' ) { g ++ ; } else if ( str [ i ] == ' k ' ) { if ( g > 0 ) { g -- ; gk ++ ; } } else if ( str [ i ] == ' s ' ) { if ( gk > 0 ) { gk -- ; gks ++ ; } } } return gks ; } int main ( ) { string a = " ggkssk " ; cout << maxOperations ( a ) ; return 0 ; }
Split a string in equal parts such that all parts are palindromes | C ++ implementation of the approach ; Function to return the frequency array for the given string ; Function to return the required count ; Add frequencies of the even appearing characters ; Count of the characters that appeared odd number of times ; If there are no characters with odd frequency ; If there are no characters with even frequency ; Only a single character with odd frequency ; More than 1 character with odd frequency string isn 't a palindrome ; All odd appearing characters can also contribute to the even length palindrome if one character is removed from the frequency leaving it as even ; If k palindromes are possible where k is the number of characters with odd frequency ; Current character can no longer be an element in a string other than the mid character ; If current character has odd frequency > 1 take two characters which can be used in any of the parts ; Update the frequency ; If not possible , then every character of the string will act as a separate palindrome ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int * getFrequencies ( string str ) { static int freq [ 26 ] = { 0 } ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) { freq [ str [ i ] - ' a ' ] ++ ; } return freq ; } int countMinParts ( string str ) { int n = str . length ( ) ; int * freq = getFrequencies ( str ) ; vector < int > oddFreq , evenFreq ; int i , sumEven = 0 ; for ( i = 0 ; i < 26 ; i ++ ) { if ( freq [ i ] == 0 ) continue ; if ( freq [ i ] % 2 == 0 ) evenFreq . push_back ( freq [ i ] ) ; else oddFreq . push_back ( freq [ i ] ) ; } for ( i = 0 ; i < evenFreq . size ( ) ; i ++ ) { sumEven += evenFreq [ i ] ; } if ( oddFreq . size ( ) == 0 ) return 1 ; if ( sumEven == 0 ) { if ( oddFreq . size ( ) == 1 ) return 1 ; return 0 ; } i = 0 ; while ( i < oddFreq . size ( ) ) { if ( ( sumEven / 2 ) % oddFreq . size ( ) == 0 ) return oddFreq . size ( ) ; if ( oddFreq [ i ] == 1 ) { i ++ ; continue ; } sumEven += 2 ; oddFreq [ i ] = oddFreq [ i ] - 2 ; } return n ; } int main ( ) { string s = " noonpeep " ; cout << countMinParts ( s ) ; }
Substring Reverse Pattern | C ++ program to print the required pattern ; Function to print the required pattern ; Print the unmodified string ; Reverse the string ; Replace the first and last character by ' * ' then second and second last character and so on until the string has characters remaining ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printPattern ( char s [ ] , int n ) { cout << s << " STRNEWLINE " ; int i = 0 , j = n - 2 ; while ( i < j ) { char c = s [ i ] ; s [ i ] = s [ j ] ; s [ j ] = c ; i ++ ; j -- ; } i = 0 ; j = n - 2 ; while ( j - i > 1 ) { s [ i ] = s [ j ] = ' * ' ; cout << s << " STRNEWLINE " ; i ++ ; j -- ; } } int main ( ) { char s [ ] = " geeks " ; int n = sizeof ( s ) / sizeof ( s [ 0 ] ) ; printPattern ( s , n ) ; return 0 ; }
Check if the string satisfies the given condition | C ++ implementation of the approach ; Function that returns true if n is prime ; Corner cases ; This is checked so that we can skip middle five numbers in below loop ; Function that returns true if c is a vowel ; Function that returns true if the count of vowels in word is prime ; If count of vowels is prime ; Driver code
#include <bits/stdc++.h> NEW_LINE #define ll long long int NEW_LINE using namespace std ; bool prime ( int n ) { if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) return false ; for ( int i = 5 ; i * i <= n ; i = i + 6 ) if ( n % i == 0 || n % ( i + 2 ) == 0 ) return false ; return true ; } bool isVowel ( char c ) { c = tolower ( c ) ; if ( c == ' a ' c == ' e ' c == ' i ' c == ' o ' c == ' u ' ) return true ; return false ; } bool isValidString ( string word ) { int cnt = 0 ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { if ( isVowel ( word [ i ] ) ) cnt ++ ; } if ( prime ( cnt ) ) return true ; else return false ; } int main ( ) { string s = " geeksforgeeks " ; if ( isValidString ( s ) ) cout << " YES " ; else cout << " NO " ; return 0 ; }
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 ) { string suff = " " ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { suff = suff + str [ i ] ; cout << suff ; } } int main ( ) { string str = " geeks " ; printExpansion ( str ) ; return 0 ; }
Solve the Logical Expression given by string | C ++ program to solve the logical expression . ; Function to evaluate the logical expression ; traversing string from the end . ; for NOT operation ; for AND and OR operation ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; char logicalExpressionEvaluation ( string str ) { stack < char > arr ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' [ ' ) { vector < char > s ; while ( arr . top ( ) != ' ] ' ) { s . push_back ( arr . top ( ) ) ; arr . pop ( ) ; } arr . pop ( ) ; if ( s . size ( ) == 3 ) { s [ 2 ] == '1' ? arr . push ( '0' ) : arr . push ( '1' ) ; } else if ( s . size ( ) == 5 ) { int a = s [ 0 ] - 48 , b = s [ 4 ] - 48 , c ; s [ 2 ] == ' & ' ? c = a && b : c = a || b ; arr . push ( ( char ) c + 48 ) ; } } else { arr . push ( str [ i ] ) ; } } return arr . top ( ) ; } int main ( ) { string str = " [ [0 , & ,1 ] , | , [ ! ,1 ] ] " ; cout << logicalExpressionEvaluation ( str ) << endl ; return 0 ; }
Find number of substrings of length k whose sum of ASCII value of characters is divisible by k | C ++ program to find number of substrings of length k whose sum of ASCII value of characters is divisible by k ; Finding length of string ; finding sum of ASCII value of first substring ; Using sliding window technique to find sum of ASCII value of rest of the substring ; checking if sum is divisible by k ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int count ( string s , int k ) { int n = s . length ( ) ; int d = 0 , i ; int count = 0 ; for ( i = 0 ; i < n ; i ++ ) d += s [ i ] ; if ( d % k == 0 ) count += 1 ; for ( i = k ; i < n ; i ++ ) { int prev = s [ i - k ] ; d -= prev ; d += s [ i ] ; if ( d % k == 0 ) count += 1 ; } return count ; } int main ( ) { string s = " bcgabc " ; int k = 3 ; int ans = count ( s , k ) ; cout << ( ans ) ; }
Final string after performing given operations | C ++ implementation of the approach ; Function to return the modified string ; Count number of ' x ' ; Count number of ' y ' ; min ( x , y ) number of ' x ' and ' y ' will be deleted ; Driver Program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; string printFinalString ( string s ) { int i , n ; n = s . length ( ) ; int x = 0 , y = 0 ; for ( i = 0 ; i < n ; i ++ ) { if ( s [ i ] == ' x ' ) x ++ ; else y ++ ; } string finalString = " " ; if ( x > y ) for ( i = 0 ; i < x - y ; i ++ ) finalString += " x " ; else for ( i = 0 ; i < y - x ; i ++ ) finalString += " y " ; return finalString ; } int main ( ) { string s = " xxyyxyy " ; cout << printFinalString ( s ) ; }
String which when repeated exactly K times gives a permutation of S | C ++ program to find a string which when repeated exactly k times gives a permutation of the given string ; Function to return a string which when repeated exactly k times gives a permutation of s ; size of string ; to frequency of each character ; get frequency of each character ; to store final answer ; check if frequency is divisible by k ; add to answer ; if frequency is not divisible by k ; Driver code ; function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; string K_String ( string s , int k ) { int n = s . size ( ) ; int fre [ 26 ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) fre [ s [ i ] - ' a ' ] ++ ; string str = " " ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( fre [ i ] % k == 0 ) { int x = fre [ i ] / k ; while ( x -- ) { str += ( char ) ( i + ' a ' ) ; } } else { return " - 1" ; } } return str ; } int main ( ) { string s = " aabb " ; int k = 2 ; cout << K_String ( s , k ) ; return 0 ; }
Maximum even length sub | C ++ code to find the maximum length of sub - string ( of even length ) which can be arranged into a Palindrome ; function that returns true if the given sub - string can be arranged into a Palindrome ; This function returns the maximum length of the sub - string ( of even length ) which can be arranged into a Palindrome ; If we reach end of the string ; if string is of even length ; if string can be arranged into a palindrome ; Even length sub - string ; Check if current sub - string can be arranged into a palindrome ; Odd length sub - string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; unordered_map < int , int > countt ; bool canBePalindrome ( unordered_map < int , int > & countt ) { for ( auto key : countt ) { if ( key . second & 1 ) return false ; } return true ; } int maxPal ( string str , unordered_map < int , int > & countt , int start , int end ) { if ( end == str . length ( ) ) { if ( ( end - start ) % 2 == 0 ) if ( canBePalindrome ( countt ) ) return end - start ; return 0 ; } else { if ( ( end - start ) % 2 == 0 ) { if ( canBePalindrome ( countt ) ) { countt [ str [ end ] ] ++ ; return max ( end - start , maxPal ( str , countt , start , end + 1 ) ) ; } else { countt [ str [ end ] ] ++ ; return maxPal ( str , countt , start , end + 1 ) ; } } else { countt [ str [ end ] ] ++ ; unordered_map < int , int > c ( countt . begin ( ) , countt . end ( ) ) ; int length = maxPal ( str , c , start , end + 1 ) ; countt [ str [ end ] ] -- ; countt [ str [ start ] ] -- ; return max ( length , maxPal ( str , countt , start + 1 , end ) ) ; } } } int main ( int argc , char const * argv [ ] ) { string str = "124565463" ; int start = 0 , end = 0 ; cout << maxPal ( str , countt , start , end ) << endl ; return 0 ; }
Minimum deletions from string to reduce it to string with at most 2 unique characters | C ++ implementation of the above approach ; Function to find the minimum deletions ; Array to store the occurrences of each characters ; Length of the string ; ASCII of the character ; Increasing the frequency for this character ; Choosing two character ; Finding the minimum deletion ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int check ( string s ) { int i , j ; int fr [ 26 ] = { 0 } ; int n = s . size ( ) ; for ( i = 0 ; i < n ; i ++ ) { char x = s [ i ] ; fr [ x - ' a ' ] += 1 ; } int minimum = INT_MAX ; for ( i = 0 ; i < 26 ; i ++ ) { for ( j = i + 1 ; j < 26 ; j ++ ) { int z = fr [ i ] + fr [ j ] ; minimum = min ( minimum , n - z ) ; } } return minimum ; } int main ( ) { string s = " geeksforgeeks " ; cout << check ( s ) ; }