InternDoor

The next arrangement of the letters

Mediumstrings · permutations · greedy

Reported in interviews at (where)

Every rearrangement of the letters of s is a string, and those strings can be put in dictionary order. Return the one that comes right after s: the smallest rearrangement of its letters that is larger than s.

If s is already the largest rearrangement, start again from the smallest: return its letters in increasing order.

Example 1
Input
s = "plan"
Output
"plna"

Only the last two letters need to change: "na" is the next arrangement of "an".

Example 2
Input
s = "sun"
Output
"uns"

Nothing after "s" can grow on its own, so the "s" is replaced by the next larger letter after it, "u", and the rest is put in increasing order.

Example 3
Input
s = "zza"
Output
"azz"

"zza" is the largest arrangement of a, z, z, so the answer wraps round to the smallest.

Example 4
Input
s = "aa"
Output
"aa"

There is only one arrangement.

Limits

  • 1 <= s.length <= 100000
  • s holds lowercase English letters

Hints

Hint 1

From the right, find the first letter that is smaller than the letter after it. Everything to its right is in decreasing order and cannot grow by itself.

Hint 2

Swap that letter with the smallest letter to its right that is larger than it, then reverse the part to its right so it becomes as small as possible.

Where this was reported

Our own problem on the task these candidates describe; the wording, examples and tests are InternDoor’s.

Run your code to check it on the examples. Submit runs every hidden test.

Ready for the real one?

Engineering internships and entry-level jobs in India, newest first.