Skip to content
StackDecode
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

  1. Find the rightmost position i where a[i] < a[i+1] (the "pivot"). If none, the list is the last permutation: reverse it.
  2. Find the rightmost item after the pivot that is larger than the pivot.
  3. Swap the two.
  4. Reverse everything after the pivot position to make it as small as possible. That gives the very next arrangement.

Watch it run

Loading animation…