Next Permutation
A medium Arrays problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 1
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Given an array of integers, rearrange it to its next lexicographically greater permutation. If no greater permutation exists, return the smallest permutation.
Example 1
- Input
- [1,2,3]
- Output
- [1,3,2]
Example 2
- Input
- [3,2,1]
- Output
- [1,2,3]
Example 3
- Input
- [1,1,5]
- Output
- [1,5,1]
Constraints
- 1 <= n <= 100
- 0 <= arr[i] <= 100
How to think about it
Updated 2026-09-09To make the number minimally larger, the modification must happen as far to the right as possible. The first position from the right that can increase is the first dip where arr[i] < arr[i + 1]; swapping it with the smallest strictly larger value to its right, then reversing the remaining suffix into ascending order, ensures the smallest step up.
Approaches, worst first
All permutations search
time O(n! * n) · space O(n!)
Generate every permutation in lexicographical order, locate the input sequence, and take the next entry in line. Factorial complexity renders this completely unworkable even for modest array sizes.
Pivot swap and suffix reversalWrite this one
time O(n) · space O(1)
Scan right-to-left to find the first index i where arr[i] < arr[i + 1]. If none exists, reverse the whole array. Otherwise, scan right-to-left again to find the smallest element larger than arr[i], swap them, and reverse the suffix starting at i + 1.
Where people lose marks · 3
- Reversing the entire array when no pivot is found must be handled cleanly without crashing on arrays that are already in strictly descending order.
- When finding the swap partner to the right of the pivot, picking an element equal to the pivot instead of strictly greater produces no lexicographical advancement.
- Failing to reverse the suffix after the swap leaves the suffix in descending order instead of minimal ascending order.
Full solution
Pivot swap and suffix reversal: find the rightmost dip, swap it with the smallest strictly larger value to its right, then reverse the descending tail. One pass in place, O(n) time and O(1) space; a fully descending input has no pivot and reverses to the smallest permutation.
Python
def next_permutation(arr: list[int]) -> list[int]:
n = len(arr)
# pivot: first index from the right where the sequence stops descending
i = n - 2
while i >= 0 and arr[i] >= arr[i + 1]:
i -= 1
if i >= 0:
# smallest value strictly greater than the pivot lives in the descending suffix
j = n - 1
while arr[j] <= arr[i]:
j -= 1
arr[i], arr[j] = arr[j], arr[i]
# the suffix is descending; reversing makes it the smallest possible tail
arr[i + 1:] = arr[i + 1:][::-1]
return arr
JavaScript
function nextPermutation(arr) {
const n = arr.length;
let i = n - 2;
while (i >= 0 && arr[i] >= arr[i + 1]) i--;
if (i >= 0) {
let j = n - 1;
while (arr[j] <= arr[i]) j--;
[arr[i], arr[j]] = [arr[j], arr[i]];
}
for (let lo = i + 1, hi = n - 1; lo < hi; lo++, hi--) {
[arr[lo], arr[hi]] = [arr[hi], arr[lo]];
}
return arr;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .