mediumArrayArrays & Hashing

Next Permutation

mediumTime: O(n)Space: O(1)

Recognize the pattern

rearrange to next lexicographic permutationin-placefind the pivot point

Brute force idea

If you approach Next Permutation in the most literal way possible, you get this: Generate all permutations in order, find the current one, return the next. Catastrophically slow. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in Next Permutation comes when you notice this: Three steps: (1) Find the rightmost pair where nums[i] < nums[i+1] — that's the pivot. (2) Find the smallest element to the right of i that's larger than nums[i], swap them. (3) Reverse everything after position i. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Next Permutation is this: The rightmost ascending pair marks where the permutation can be incremented. Swapping with the next larger element advances the digit, and reversing the suffix resets it to the smallest arrangement. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

The trap in Next Permutation usually looks like this: If no ascending pair exists (array is fully descending), the answer is the first permutation — reverse the entire array. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Arrays & Hashing Pattern