Make delicious recipes!

Next lexicographical string

Problem: Write code to print the lexicographical next string for a given string.

(As in dictionary, next word after this word but having similar letters) For ex:

i/p abcd

o/p abdc

i/p abcged

o/p abdceg


Find the number of characters at the end of string that are sorted

decreasingly e.g. in "abcgda" the length of such sub-string is 3 ( "gda" ).

Then look at the char before this sub-string (here it is 'c' ).

This character must be replaced with the smallest character in

the decreasing sub-sequence which is bigger than this char (here it's 'd').

Then sort the decreasing sub-string to be increasing

So the next lexicographical string of "abcgda" is "abdacg" ('d' is replaced

with 'c' and then "gca" is sorted to be "acg")

Note If a string is sorted decreasingly like "dcba" it's next char does

not exist so it's next string doesn't exist

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Email: (Your email is not shared with anybody)

Facebook comments:

Site Owner: Sachin Goyal