[1, 2, 3] the order is [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1].
Given an array values, return the arrangement that comes next in this order. If values is already the last one, return the first one, that is, the elements sorted ascending.
Can you do it with constant extra memory, rearranging the elements right inside values?values=[2, 4, 3, 1] → [3, 1, 2, 4]
The tail 4, 3, 1 is descending. Swap the 2 for the smallest larger value in the tail, 3, and sort the rest (1, 2, 4) ascending: [3, 1, 2, 4].
values=[5, 5, 2] → [2, 5, 5]
This is the last arrangement in order, so the array wraps around to the first one: [2, 5, 5].
values=[1, 3, 3] → [3, 1, 3]
The arrangements in order are [1, 3, 3], [3, 1, 3], [3, 3, 1], so the next one is [3, 1, 3].
values=[2, 4, 3, 1]
[3, 1, 2, 4]
Run checks the first 3 tests in your browser. Submit checks all 38 tests on the server, hidden ones included.