Skip to main content
Back to problems
Leetcode
Medium
Arrays
Sorting
Stacks
Amazon
Google
Next Permutation

Rearrange an array into the next lexicographically greater permutation, or the smallest permutation if none exists.

Acceptance 50%
Problem Statement

Problem

Given an array of integers representing a permutation, rearrange the numbers in place so that they form the next lexicographically greater permutation.

If such a permutation does not exist, rearrange the array into the lowest possible order (sorted in ascending order).

A permutation aa is lexicographically smaller than permutation bb if at the first position where they differ, aa has a smaller value than bb.

Your task is to modify the input array directly and produce the next permutation in this ordering.

Notes

  • The result must use the same elements exactly once each.
  • You should aim for an O(n)O(n) time solution and constant extra space.

Input Format

  • An integer array nums of length n.
  • nums represents one permutation of some set of values.
  • The array should be modified in place.

Output Format

  • Return or update nums so it becomes the next lexicographically greater permutation.
  • If no greater permutation exists, transform it into the smallest permutation.

Constraints

  • 1n1 \le n
  • All elements are comparable for ordering.
  • Use constant extra space if possible.
  • Target linear time complexity.
Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,2,3]

Output

[1,3,2]

Explanation

The next permutation after [1,2,3] is [1,3,2].

Example 2

Input

nums = [3,2,1]

Output

[1,2,3]

Explanation

This is the last permutation, so the array is rearranged into the smallest order.

Show 1 more example

Example 3

Input

nums = [1,1,5]

Output

[1,5,1]

Explanation

Among distinct lexicographic permutations, [1,5,1] is the next one after [1,1,5].

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.