AlgoInsight

DSA problem

Next Permutation

MediumArraysPattern: Array Manipulationtop600AmazonGoogleFacebookMicrosoftAppleBloomberg

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

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 one container according to their lexicographical order, then the next permutation of that array is the permutation that follows it. If such an arrangement is not possible, the array must be rearranged to the lowest possible order (sorted in ascending order).

Given an array of integers nums, find the next permutation of nums. The replacement must be done in-place and use only constant extra memory.

The algorithm works by finding the rightmost ascending pair, swapping the pivot with the smallest larger value to its right, and then reversing the tail to make it as small as possible.

Examples

Example 1
Input: nums = [1,2,3]
Output: [1,3,2]
Explanation: The next lexicographically greater permutation of [1,2,3] is [1,3,2].
Example 2
Input: nums = [3,2,1]
Output: [1,2,3]
Explanation: [3,2,1] is the largest permutation, so it wraps around to the smallest, [1,2,3].
Example 3
Input: nums = [1,1,5]
Output: [1,5,1]
Explanation: The next permutation after [1,1,5] is [1,5,1].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraytwo-pointers

Browse all DSA problems