← Questions
Next permutation in lexicographic order, in place
0
I was asked this
No reports yet. Sign in to say where you were asked it.
Rearrange an array of integers into the next permutation in lexicographic order. If the array is already the largest permutation, rearrange it into the smallest one (sorted ascending). Do it in place with constant extra memory.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
next_permutation(nums: list[int]) -> None— modifiesnumsin place.
Example
[1, 2, 3] -> [1, 3, 2]
[1, 3, 2] -> [2, 1, 3]
[2, 3, 1] -> [3, 1, 2]
[3, 2, 1] -> [1, 2, 3] # last permutation wraps around
[1, 1, 5] -> [1, 5, 1] # duplicates allowed
Constraints
-
1 <= len(nums) <= 100. -
0 <= nums[i] <= 100; values may repeat.
Clarifying questions
- Can the array contain duplicates?
- Should the last permutation wrap around, or report that there is no next one?
- Must it be in place?
What a strong answer covers
- Find the pivot: the rightmost index
iwithnums[i] < nums[i + 1]. Everything after it is non-increasing. - If there is no pivot, reverse the whole array.
- Otherwise swap
nums[i]with the rightmost element greater than it, then reverse the suffix afteri. - Why this gives the next permutation and not a later one; strict comparisons so duplicates work.
-
O(n)time,O(1)extra space. - Tests: one element, two elements, all equal, the last permutation, duplicates.
Follow-ups
- Return the previous permutation instead.
- Return the
k-th permutation of1..ndirectly, without stepping through all of them. - Find the smallest number larger than a given integer that uses the same digits, or
-1if none fits in 32 bits.
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
