InferenceAI

Enter at least two characters to search.

Start free

Next Arrangement

mediumArrays & Strings25 min25 XP

Return the next permutation of nums in lexicographic order. If nums is the last permutation (descending), return the first one (ascending).

Requirements

  • O(n)O(n) time.

Examples

EXAMPLE WALKTHROUGHsimple

A guided view of the published example, not a trace of your code.

INPUT[[1,2,3]]
TASKnext_arrangement()
EXPECTED OUTPUT[1,3,2]

Start with the input values shown in this example.

Example 1 of 3

Input: nums = [1,2,3]

Output: [1,3,2]

Explanation: simple

Input: nums = [3,2,1]

Output: [1,2,3]

Explanation: wraps around

Input: nums = [1,1,5]

Output: [1,5,1]

Explanation: duplicates

Hint 1

From the right, find the first i with nums[i] < nums[i + 1].

Hint 2

Swap nums[i] with the smallest larger value to its right, then reverse the suffix.

Topics

DSAArrays & StringsPython