Lexicographically next greater string using same character set | C ++ implementation of above algorithm . ; function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; return ; end the program ; searching the first character left of index k and not equal to greatest character of the string ; finding the just next greater character than s [ i ] ; suffix with smallest character ; if we reach here then all indices to the left of k had the greatest character ; Driver code ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void lexoString ( string s , int k ) { int n = s . size ( ) ; vector < char > v ; map < char , int > mp ; for ( int i = 0 ; i < s . size ( ) ; i ++ ) { if ( mp [ s [ i ] ] == 0 ) { mp [ s [ i ] ] = 1 ; v . push_back ( s [ i ] ) ; } } sort ( v . begin ( ) , v . end ( ) ) ; if ( k > n ) { cout << s ; for ( int i = n ; i < k ; i ++ ) { cout << v [ 0 ] ; } } for ( int i = k - 1 ; i >= 0 ; i -- ) { if ( s [ i ] != v [ v . size ( ) - 1 ] ) { for ( int j = 0 ; j < i ; j ++ ) { cout << s [ j ] ; } for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v [ j ] > s [ i ] ) { cout << v [ j ] ; break ; } } for ( int j = i + 1 ; j < k ; j ++ ) cout << v [ 0 ] ; return ; } } cout << " No ▁ lexicographically ▁ greater ▁ string ▁ of ▁ length ▁ " << k << " ▁ possible ▁ here . " ; } int main ( ) { string s = " gi " ; int k = 3 ; lexoString ( s , k ) ; return 0 ; }