DSA Tracker

Problem

Medium

Next Permutation

A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
1
Core for
26 roles

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
[2,4,3,1]
Output
[3,1,2,4]

Example 2

Input
[4,3,2,1]
Output
[1,2,3,4]

Example 3

Input
[2,2,7]
Output
[2,7,2]

Constraints

  • 1 <= n <= 100
  • 0 <= arr[i] <= 100

How to think about it

Updated 2026-09-29

To 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

  1. 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.

  2. 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;
}
Try it in the editor

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.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .