Bird
Raised Fist0
Interview PrepbacktrackingmediumAmazonGoogleFacebook

Next Permutation

Choose your preparation mode3 modes available
Steps
setup

Initialize pointer i to find pivot

Set pointer i to the second last index (1) to start scanning from right to left to find the pivot where nums[i] < nums[i+1].

💡 Starting from the right helps find the first place where the sequence stops increasing, which is the pivot point for the next permutation.
Line:i = len(nums) - 2
💡 The pivot is the first element from the right that can be increased to get the next permutation.
📊
Next Permutation - Watch the Algorithm Execute, Step by Step
Watching each pointer move and swap helps you understand how the algorithm transforms the array in-place to the next permutation without generating all permutations.
Step 1/10
·Active fillAnswer cell
setup
1
0
i
2
1
3
2
compare
1
0
i
2
1
3
2
setup
1
0
i
2
1
j
3
2
compare
1
0
i
2
1
j
3
2
swap
1
0
i
3
1
j
2
2
setup
1
0
3
1
right
2
2
compare
1
0
3
1
right
2
2
move_left
1
0
3
1
right
2
2
reconstruct
1
0
3
1
2
2
Result: [1,3,2]
reconstruct
1
0
3
1
2
2
Result: [1,3,2]

Key Takeaways

The pivot is the first element from the right that breaks the descending order.

This is hard to see from code alone because the while loop hides the scanning process.

Swapping the pivot with the rightmost successor greater than it ensures the next permutation is just one step higher.

Visualizing the pointers shows why the successor must be the rightmost element greater than the pivot.

Reversing the suffix after the pivot places it in ascending order, completing the next permutation.

Without visualization, it's not obvious why reversing the suffix is necessary after swapping.