a | C ++ implementation of the approach ; Function to return the modified string ; To store the previous character ; To store the starting indices of all the groups ; Starting index of the first group ; If the current character and the previous character differ ; Push the starting index of the new group ; The current character now becomes previous ; Sort the first group ; Sort all the remaining groups ; cout << str << endl ; Sort the last group ; Return the modified string ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string get_string ( string str , int n ) { char prev = str [ 0 ] ; vector < int > result ; result . push_back ( 0 ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( isdigit ( str [ i ] ) != isdigit ( prev ) ) { result . push_back ( i ) ; } prev = str [ i ] ; } sort ( str . begin ( ) , str . begin ( ) + result [ 0 ] ) ; for ( int i = 0 ; i < result . size ( ) - 1 ; i ++ ) { sort ( str . begin ( ) + result [ i ] , str . begin ( ) + result [ i + 1 ] ) ; } sort ( str . begin ( ) + result [ result . size ( ) - 1 ] , str . end ( ) ) ; return str ; } int main ( ) { string str = "121geeks21" ; int n = str . length ( ) ; cout << get_string ( str , n ) ; return 0 ; }