Picture every way to order the numbers in nums, listed in dictionary order: compare two orderings at the first position where they differ, and the smaller number there comes first. For [4, 5, 6] that list is [4, 5, 6], [4, 6, 5], [5, 4, 6], [5, 6, 4], [6, 4, 5], [6, 5, 4].
Change nums into the ordering that comes right after it in that list. If nums is already the last one, wrap around to the first: the numbers in ascending order.
Do it in place, using only a constant amount of extra memory. The function returns nothing; the caller reads nums.
Example 1
Input: nums = [2, 4, 3, 1] Output: [3, 1, 2, 4] Why: 3 replaces 2, then the rest goes smallest first
2 more examples and the constraints
Example 2
Input: nums = [5, 4, 2] Output: [2, 4, 5] Why: [5, 4, 2] is the last order, so wrap to the first
Example 3
Input: nums = [1, 3, 3] Output: [3, 1, 3] Why: repeats count once: [1, 3, 3] then [3, 1, 3]
Constraints
- 1 ≤ length of nums ≤ 100
- 0 ≤ nums[i] ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Scan, then sort the tailO(n²)
- Pivot, swap, reverseO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 numbers | Verdict |
|---|---|---|---|
| Scan, then sort the tail | O(n²) | Passes; does extra scans | |
| Pivot, swap, reverse | O(n) | Best; three short passes |
n = how many numbers are in the list.
Edge cases to test
- Last arrangement. [5, 4, 2] has no pivot; reversing the whole list gives [2, 4, 5].
- One number. [7] stays [7]: i starts at −1 and the reverse does nothing.
- Repeated values. [1, 3, 3] becomes [3, 1, 3]; strict comparisons would pick the wrong pivot or swap equal values.
- All equal. [0, 0, 0] has only one arrangement, so it stays the same.
Common mistakes
- Sorting or reversing from the pivot itself instead of from the position after it.
- Swapping the pivot with the first bigger value from the left instead of the smallest bigger one.
- Returning a new list when the caller expects
numsto be changed in place.
How to talk through it
- 1Clarify. Can values repeat? Must it be in place? What happens after the last arrangement?
- 2Reason about the order. To make the smallest increase, change as far right as you can.
- 3Find the pivot. A falling tail is already at its maximum, so the pivot is the first value that breaks it.
- 4Swap and reverse. Swap in the smallest bigger tail value, then reverse the tail, which is still falling.
- 5Test out loud. Run the last arrangement, a single number and [1, 3, 3] before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?