ExamAdda Logo

Next Permutation

Medium

Given an array of integers nums, rearrange the numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, rearrange the array into the lowest possible order (ascending order).

The rearrangement must be performed in-place and use only constant extra memory.

Example 1

Input

n = 3
nums = [1, 2, 3]

Output

[1, 3, 2]

Explanation

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

Example 2

Input

n = 3
nums = [3, 2, 1]

Output

[1, 2, 3]

Explanation

There is no greater permutation, so the array is rearranged into ascending order.

Constraints

1 <= n <= 10^5
-10^9 <= nums[i] <= 10^9
The rearrangement must be performed in-place.
Use constant extra memory.

Hints:

Hint 1

Starting from the right, find the first index where:

nums[i] < nums[i + 1]

Hint 2

Find the smallest element to the right of i that is greater than nums[i], then swap them.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 27, 2026

Last updated

Aug 28, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output