Next Permutation — LeetCode 31 Python Solution
- Problem
- #31
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
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
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.