DEV Community

Ruairí O'Brien
Ruairí O'Brien

Posted on

1

Day 31 - Next Permutation

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay