How do you find the next lexicographical permutation of an array in O(n) time and O(1) space? | A1Lab@mossabshafqat to DSAEnglish • 14 hours ago

How do you find the next lexicographical permutation of an array in O(n) time and O(1) space?

message-square
0

Next Lexicographical Permutation: $O(n)$ Time and $O(1)$ Space

The Next Permutation algorithm rearranges an array of numbers into the lexicographically next greater permutation. If no greater permutation is possible (i.e., the array is sorted in descending order), it rearranges the array into the lowest possible order (sorted ascending).

The algorithm, formalized by Narayana Pandita in the 14th century, runs strictly in $O(n)$ time and requires only $O(1)$ auxiliary space using a three-step suffix manipulation.


The Underlying Mathematical Intuition

To produce the smallest possible increase in lexicographical value:

  1. We must preserve the largest possible prefix intact.
  2. We must modify digits as far to the right (least significant positions) as possible.
  3. Any suffix sorted in strictly descending order (e.g., [... 7, 5, 3, 1]) is already at its absolute maximum permutation and cannot be made larger without modifying the digit immediately preceding it.

The Three-Step Algorithm

Example: [1, 5, 8, 4, 7, 6, 5, 3, 1]
                     ^
                  pivot (index i = 3, value = 4)

Step 1: Find the Pivot (First Decreasing Element from the Right)

Scan from right to left to locate the first index i where: $$\text{nums}[i] < \text{nums}[i + 1]$$

  • The subarray $\text{nums}[i + 1 \dots n - 1]$ forms a monotonically non-increasing sequence (the maximal suffix).
  • If no such index exists ($i < 0$), the entire array is in descending order. Jump directly to Step 3 to reverse the entire array into ascending order.

Step 2: Find Successor and Swap

Scan from the right end of the array backward to find the first index j such that: $$\text{nums}[j] > \text{nums}[i]$$

  • Swap $\text{nums}[i]$ with $\text{nums}[j]$.
  • Because the suffix was descending, this replaces $\text{nums}[i]$ with the smallest possible value that is strictly greater than it.
  • After the swap, the suffix $\text{nums}[i + 1 \dots n - 1]$ is guaranteed to remain in non-increasing order.

Step 3: Reverse the Suffix

Reverse the subarray from index $i + 1$ to $n - 1$:

  • Converting the descending suffix into ascending order minimizes its value, ensuring the overall permutation is the immediate next in lexicographical order.

Concrete Walkthrough: [1, 2, 7, 4, 3, 1]

  1. Locate Pivot i:
    • Compare backwards: $1 < 3$, $3 < 4$, $4 < 7$, but $7 > 2$.
    • First dip occurs where $\text{nums}[i] < \text{nums}[i + 1]$ at index $i = 1$ (value 2).
  2. Find Successor j:
    • Scan from right to find first element $> 2$:
    • $1 \ngtr 2$, but $3 > 2$. Hence, $j = 4$ (value 3).
  3. Swap nums[i] and nums[j]:
    • Swap 2 and 3: Array becomes [1, 3, 7, 4, 2, 1].
  4. Reverse Suffix from $i + 1$ to end:
    • Subarray starting at index 2 is [7, 4, 2, 1].
    • Reversing it yields [1, 2, 4, 7].
  • Final Result: [1, 3, 1, 2, 4, 7]

Implementation (C++ and Python)

C++ Implementation

#include <vector>
#include <algorithm>

void nextPermutation(std::vector<int>& nums) {
    int n = nums.size();
    int i = n - 2;

    // Step 1: Find the first element from the right that breaks descending order
    while (i >= 0 && nums[i] >= nums[i + 1]) {
        i--;
    }

    // Step 2: If a valid pivot is found, find the smallest element greater than nums[i]
    if (i >= 0) {
        int j = n - 1;
        while (nums[j] <= nums[i]) {
            j--;
        }
        std::swap(nums[i], nums[j]);
    }

    // Step 3: Reverse the suffix starting at i + 1 to make it ascending
    std::reverse(nums.begin() + i + 1, nums.end());
}

Python Implementation

def next_permutation(nums: list[int]) -> None:
    """
    Modifies nums in-place to the next lexicographical permutation.
    Uses O(1) auxiliary space and O(n) time.
    """
    n = len(nums)
    i = n - 2

    # Step 1: Find the first decreasing element from the back
    while i >= 0 and nums[i] >= nums[i + 1]:
        i -= 1

    # Step 2: Find the element just larger than nums[i] to swap
    if i >= 0:
        j = n - 1
        while nums[j] <= nums[i]:
            j -= 1
        nums[i], nums[j] = nums[j], nums[i]

    # Step 3: Reverse the elements after index i
    left, right = i + 1, n - 1
    while left < right:
        nums[left], nums[right] = nums[right], nums[left]
        left += 1
        right -= 1

Complexity Analysis

Metric Complexity Explanation
Time Complexity $O(n)$ Step 1 takes at most $n$ comparisons. Step 2 takes at most $n$ comparisons. Step 3 reverses at most $n$ elements in $n/2$ swaps. Overall time is strictly linear: $O(n) + O(n) + O(n) = O(n)$.
Auxiliary Space $O(1)$ All operations are in-place pointer swaps without dynamic memory allocation.

Key Edge Cases Handled

  • Strictly Decreasing Array (e.g., [5, 4, 3, 2, 1]): Index i reaches -1. The if (i >= 0) check is bypassed, and the entire array is reversed to [1, 2, 3, 4, 5], wrapping cleanly to the smallest permutation.
  • Duplicates Present (e.g., [1, 5, 1] or [3, 3, 1, 3]): Using >= in nums[i] >= nums[i + 1] and <= in nums[j] <= nums[i] ensures the algorithm skips duplicate values and does not stall in infinite loops or make redundant zero-delta swaps.