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.