MediumNo. 0031

Next Permutation — LeetCode 31 Python Solution

Topics
Array, Two Pointers
Reading time
2 min

The problem

A permutation of an array of integers is an arrangement of its members into a sequence or linear order. For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2, 1, 3], [2, 3, 1], [3,1,2], [3,2,1].

Example

Input
nums = [1,2,3]
Output
[1,3,2]

Python solution

PythonSolution
class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        n = len(nums)
        i = next((i for i in range(n - 2, -1, -1) if nums[i] < nums[i + 1]), -1)
        if ~i:
            j = next((j for j in range(n - 1, i, -1) if nums[j] > nums[i]))
            nums[i], nums[j] = nums[j], nums[i]
        nums[i + 1 :] = nums[i + 1 :][::-1]

Complexity

Time
O(n)
Space · auxiliary
O(1)

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 31. Next Permutation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0027Remove ElementEasy
0026Remove Duplicates from Sorted ArrayEasy
00153SumMedium
00163Sum ClosestMedium
00184SumMedium
0075Sort ColorsMedium

Frequently asked questions

How hard is LeetCode 31. Next Permutation?

LeetCode 31. Next Permutation is rated Medium on LeetCode.

What is the time complexity of LeetCode 31. Next Permutation?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 31. Next Permutation?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 31. Next Permutation cover?

LeetCode 31. Next Permutation is tagged Array and Two Pointers on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.