31. Next Permutation

#permutation #array #two-pointers

Problem

Intuition

1. Longest Non-Increasing Suffix

The suffix represents a sub-sequence that is already at its maximum permutation rank. No rearrangement of these elements can increase the value.

  • Key Point: Finding the first A[iβˆ’1]<A[i]A[i-1] < A[i] from the right identifies the rightmost possible position where an increase can occur.

2. The Boundary Case

If the suffix encompasses the entire array (i=0i=0), the permutation is the absolute maximum. Reversing it yields the absolute minimum, completing the circular property of permutations.

3. Finding the Successor (Min-Max)

You seek the smallest value in the suffix that is strictly greater than the pivot (A[iβˆ’1]A[i-1]).

  • Mathematical Invariant: Because the suffix is non-increasing, the first element found from the right that is >A[iβˆ’1]> A[i-1] is guaranteed to be the smallest such element. This maintains the "minimal change" requirement.

4. The Swap and Suffix Property

After swapping the pivot with its successor, the suffix remains non-increasing.

  • Proof: The successor was the smallest element larger than the pivot. Replacing it with the pivot (which is smaller) does not break the descending order of the remaining elements.

5. Minimizing the Suffix

A non-increasing suffix is the "largest" version of that sequence. To make the entire number the "next" smallest possible, the suffix must be converted to the "smallest" version (non-decreasing).

  • Optimization: Since the suffix is already sorted (descending), a O(k)O(k) reverse is used instead of an O(klog⁑k)O(k \log k) sort.

Time Complexity

O(n)O(n)

n βž” Length of the array

O(k) βž” To find the non increasing array suffix and reversing

Space Complexity

O(1)O(1) No extra space is used

Solution

Last updated