Array techniquesAnimated
Next Permutation
Find the next arrangement in lexicographic order in place.
Time
O(n)
Extra space
O(1)
Use it for
Enumerating permutations in order.
How it works
- Find the rightmost position i where a[i] < a[i+1] (the "pivot"). If none, the list is the last permutation: reverse it.
- Find the rightmost item after the pivot that is larger than the pivot.
- Swap the two.
- Reverse everything after the pivot position to make it as small as possible. That gives the very next arrangement.
Watch it run
Loading animation…