← All questions
MediumCoding

Next Permutation

Asked atNvidia
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

A permutation of an array of integers is an arrangement of its members into a sequence or linear order.

For example, for arr = [1,2,3], the following are all the permutations of arr: [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1].

The next permutation of an array of integers is the next lexicographically greater permutation of its integers. More formally, if all the permutations of the array are sorted in lexicographical order, then the next permutation of that array is the permutation that follows it in the sorted order.

If such arrangement is not possible (i.e., the array is the last permutation), then rearrange it to the lowest possible order (i.e., sorted in ascending order).

You must rearrange the numbers in-place and use only constant extra memory.

Input: nums = [1,2,3] Output: [1,3,2] Explanation: The next permutation of [1,2,3] is [1,3,2].

Input: nums = [3,2,1] Output: [1,2,3] **Explanation: ** [3,2,1] is the last permutation. So we return the first: [1,2,3].

Input: nums = [1,1,5]

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 100

cpp

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        // Your code goes here
    }
};

java

class Solution {
    public void nextPermutation(int[] nums) {
        // Your code goes here
    }
}

python

class Solution:
    def nextPermutation(self, nums):
        # Your code goes here

javascript

class Solution {
    nextPermutation(nums) {
        // Your code goes here
    }
}

csharp

public class Solution {
    public void NextPermutation(List<int> nums) {
        // Your code goes here
    }
}

go

func nextPermutation(nums []int) {
	//your code goes here
}
Solve on LeetCode →
Stuck? Show a way to structure it+
  1. 01Find rightmost ascending pivot
  2. 02Handle fully descending case
  3. 03Find rightmost successor greater than pivot
  4. 04Swap them
  5. 05Reverse decreasing suffix

Reference answer

Then expect these follow-ups

  • Why is the suffix decreasing before reversal?

    Tests: correctness reasoning

  • How do duplicates affect successor choice?

    Tests: follow-up reasoning

Hiring now

Nvidia has 1,936 open roles right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior System Software Engineer

    India, Pune

  • Senior E2E Hardware Architect, AI Networking

    Israel, Yokneam

  • Senior Software Engineer - Infrastructure

    India, Pune

Or practice this question first

Next question