v9.1.1
Menu

Next Permutation

mediumFREEArrays & StringsGoogle DSA

Given an array of integers nums, rearrange the numbers into the next lexicographically greater permutation. If no such permutation exists (the array is in descending order), rearrange it as the lowest possible order (ascending).

The replacement must be in-place with only constant extra memory.

Output the resulting array as space-separated integers.

Example

Input
1,2,3
Output
1 3 2
Reasoning
  • First, we identify the largest index kk such that nums[k]<nums[k+1]nums[k] < nums[k + 1], which is k=1k = 1 because 2<32 < 3.
  • Then, we find the largest index l>kl > k such that nums[k]<nums[l]nums[k] < nums[l], which is l=2l = 2 because 2<32 < 3.
  • Next, we swap the values at indices kk and ll, resulting in the array 1,3,21, 3, 2.
  • The final output is the rearranged array as space-separated integers: 1321 3 2.

Constraints

  • 1 <= len(nums) <= 100
  • 0 <= nums[i] <= 100

More from Google DSA

solution.py

Test results

Sign in to run your code against the test cases.