← DiffPush

Next permutation

Standard Bar Arrays · Medium O(n) · O(1)

Advancing a Licensing Key by One Arrangement

A license generator walks through every arrangement of a fixed set of key segments in lexicographic order, one arrangement per issued license. Given the arrangement currently in use, produce the very next one. If the current arrangement is already the largest possible, wrap around to the smallest arrangement instead.

Input: An array nums of n integers representing the current arrangement.

Output: The same array mutated in place into the next lexicographically greater arrangement, or into ascending order when no greater arrangement exists.

Constraints

Examples

Example 1

Input: {"nums":[1,2,3]}
Output: [1,3,2]
Swapping the final pair gives the smallest arrangement larger than 1,2,3.

Example 2

Input: {"nums":[3,2,1]}
Output: [1,2,3]
The arrangement is already the largest, so the key wraps around to ascending order.

Solve this in your browser →

Also on LeetCode ↗