Katkat

Compute the next lexicographic permutation

MetaMachine Learning Engineer · Onsite

Last updated

This problem tests your ability to manipulate array elements in-place to find the next lexicographically ordered sequence, focusing on understanding the properties of permutations.

Problem Statement

Given an array of integers nums, find the next lexicographically greater permutation of these numbers. If such an arrangement is impossible (i.e., the array is sorted in descending order), you must rearrange it to the lowest possible order (i.e., sorted in ascending order).

The operation must be done in-place, using only O(1) extra memory.

Function Signature

def next_permutation(nums: List[int]) -> None:
    """Do not return anything, modify nums in-place instead."""

Constraints

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

Examples

Example 1: Input: nums = [1, 2, 3] Output: [1, 3, 2] Explanation: The next permutation after 123 is 132.

Example 2: Input: nums = [3, 2, 1] Output: [1, 2, 3] Explanation: Since the input is the largest permutation, we return the smallest possible arrangement.

Example 3: Input: nums = [1, 1, 5] Output: [1, 5, 1] Explanation: Handling duplicate values ensures the correct lexicographical jump.

Edge Cases

  • Single element arrays.
  • Arrays with all identical elements.
  • Arrays already in descending order.

Hints

Hint 1

Scan the array from right to left to find the first pair of adjacent elements where the left element is smaller than the right element.

Hint 2

If such a pair is found, find the smallest element to the right of that position that is strictly greater than the left element, and swap them.

Hint 3

After swapping, reverse the subarray to the right of the original 'left' position to ensure the smallest possible increment.

Follow-up questions

  • How would your approach change if you needed to find the previous lexicographical permutation instead of the next?
  • What is the time complexity of this approach, and can it be optimized further?
  • How would you modify your solution to handle cases where the input array contains a very large number of duplicate values?