DSA AnimatorDSA animations
Next Permutation LC #31 Medium Arrays ยท Two Pointers
Problem

Rearrange nums into the next greater permutation in dictionary order. If it's already the largest arrangement, wrap around to the smallest (sorted ascending). Do it in place with O(1) extra memory.

Example 1
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2
Input: nums = [3,2,1]
Output: [1,2,3] (largest โ†’ wraps to smallest)
Example 3
Input: nums = [1,1,5]
Output: [1,5,1]
Constraints: 1 โ‰ค nums.length โ‰ค 100  |  0 โ‰ค nums[i] โ‰ค 100
๐Ÿ“Š Array as bars
โ‘  find the dip ๐Ÿ”ปโ‘ก find next bigger ๐Ÿ”โ‘ข swap ๐Ÿ”„โ‘ฃ reverse the downhill โ†ฉ๏ธ
descending suffix
i ๐Ÿ”ปjlohi
descending suffix (already max) ๐Ÿ”ป pivot (the dip) next bigger number finished part
Variables
i (dip)
โ€”
j (next bigger)
โ€”
comparison
โ€”
nums
โ€”
๐Ÿ’ก Step Logic
Press โ–ถ Play or Next to begin.
โœ“
Ready
0 / 0
Pick an example and press Play.
Algorithm
1
From the right, find the first i with nums[i] < nums[i+1] ๐Ÿ”ป
2
If none exists, the array is the largest โ†’ skip to step 4 (reverse everything)
3
From the right, find the first j with nums[j] > nums[i], then swap them ๐Ÿ”„
4
Reverse nums[i+1..] so the suffix becomes ascending โ†ฉ๏ธ
Time
O(n)
Space
O(1)
๐Ÿง  Why reverse, not sort?

After the swap, the suffix is still descending: the new value at j fits between its neighbours because it's the smallest number bigger than the pivot. So "sort the suffix ascending" is just reversing it, O(n) instead of O(n log n). And the first j from the right with nums[j] > nums[i] is automatically the smallest such number, because the suffix is descending.

โš ๏ธ Edge cases

Fully descending ([3,2,1]) โ†’ no dip, reverse everything to get [1,2,3]. Duplicates ([1,1,5], [1,5,1]) โ†’ use >= when looking for the dip and <= when looking for j, or equal values get swapped for nothing. Single element โ†’ unchanged.

How to solve Next Permutation

LeetCode 31 ยท Medium ยท Arrays ยท Pattern: Array Manipulation

Why the obvious approach is slow

Listing every permutation and finding the next one is O(n) factorial. We only need to change as little as possible, as far right as possible.

The key idea

Scan from the right to find the first number that is smaller than the number after it. This is the pivot: everything to its right is in decreasing order, so that part is already at its maximum. Swap the pivot with the smallest number on its right that is still bigger than it. Then reverse the part after the pivot, so it becomes as small as possible.

Remember

Find the pivot from the right, swap it with the next bigger value, then reverse the suffix. The suffix after the pivot is always decreasing.

Run the animation above on your own input, or watch the 1:52 video explanation of Next Permutation with a dry run and Java code.

More Arrays problems