DEV Community

loading...

Day 31 - Next Permutation

Ruairí O'Brien
・1 min read

The Problem

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

Example 1:

Input: nums = [1,2,3]
Output: [1,3,2]
Enter fullscreen mode Exit fullscreen mode

Example 2:

Input: nums = [3,2,1]
Output: [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Example 3:

Input: nums = [1,1,5]
Output: [1,5,1]
Enter fullscreen mode Exit fullscreen mode

Example 4:

Input: nums = [1]
Output: [1]
Enter fullscreen mode Exit fullscreen mode

Constraints:

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

Tests

import pytest
from .Day31_NextPermutation import Solution

s = Solution()


@pytest.mark.parametrize(
    "nums,expected",
    [
        ([1, 2, 3], [1, 3, 2]),
        ([3, 2, 1], [1, 2, 3]),
        ([1, 1, 5], [1, 5, 1]),
        ([1], [1]),
    ],
)
def test_next_permutation(nums, expected):
    s.nextPermutation(nums)

    assert nums == expected
Enter fullscreen mode Exit fullscreen mode

Solution

from typing import List


class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        i = len(nums) - 2
        while i >= 0 and nums[i + 1] <= nums[i]:
            i -= 1

        if i >= 0:
            j = len(nums) - 1
            while j >= 0 and nums[j] <= nums[i]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]

        k = len(nums) - 1
        while i < k:
            i += 1
            nums[i], nums[k] = nums[k], nums[i]
            k -= 1
Enter fullscreen mode Exit fullscreen mode

Analysis

Alt Text

Discussion (0)