Next Permutation
MediumP2Coding
A permutation of an array is an ordering of its elements. The next permutation is the next larger ordering in lexicographic (dictionary) order. If the array is already the largest ordering (descending), wrap around to the smallest one (ascending).
Rearrange nums into its next permutation, in place, using O(1) extra memory. The array may contain duplicates.
Example 1
- Input
- nums = [1,2,3]
- Output
- [1,3,2]
- Why
- The next ordering after 123 is 132.
Example 2
- Input
- nums = [3,2,1]
- Output
- [1,2,3]
- Why
- 321 is the largest, so it wraps to 123.
Example 3
- Input
- nums = [1,1,5]
- Output
- [1,5,1]
- Why
- 115 -> 151.
Constraints
- 1 <= nums.length <= 100
- 0 <= nums[i] <= 100
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 10. ⌘Enter runs, ⌘⇧Enter submits.