List every way to arrange the numbers of nums and sort those arrangements in dictionary order: compare two arrangements at the first position where they differ, and the one with the smaller number there comes first. Rearrange nums into the arrangement that comes right after it in that order.
If nums is already the last arrangement (its numbers never increase from left to right), wrap around to the first one: the numbers sorted from smallest to largest.
Change nums itself and return nothing: the answer is what nums holds once your function finishes. Use only a constant amount of extra memory.
No arrangement starting with 2 comes after [2,5,4,1], because 5, 4, 1 is already the largest way to order its tail. So the first number grows to the next larger value in the tail, 4, and the remaining 1, 2, 5 follow in their smallest order.
The numbers never increase, so this is the last arrangement; the next one wraps around to the first.
Repeated numbers count once per distinct arrangement: in order they are [6,8,8], [8,6,8], [8,8,6].
Constraints
1 <= nums.length <= 1000 <= nums[i] <= 100Look from the right. A tail whose numbers only fall is already in its largest order, so the change has to happen at the number just before that tail.
Think of an arrangement as a number written digit by digit, and the next arrangement as the next larger number you can write with the same digits. To make the smallest possible increase, change the number as far to the right as you can. A change at the left end jumps over every arrangement that differs only further right.
Time O(n)Space O(1)
The full walkthrough and code are part of Premium