Next Permutation - 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 integer. 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 in the sorted container.

If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).

For example:

  • The next permutation of arr = [1,2,3] is [1,3,2]
  • Similarly, the next permutation of arr = [2,3,1] is [3,1,2]
  • While the next permutation of arr = [3,2,1] is [1,2,3] because [3,2,1] does not have a lexicographical larger rearrangement

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: [1,3,2]
💡 Note: Find pivot at index 1 (2 < 3), find successor at index 2 (3), swap them to get [1,3,2], no suffix to reverse
Example 2 — Larger Array
$ Input: nums = [2,3,1]
Output: [3,1,2]
💡 Note: Find pivot at index 0 (2 < 3), find successor at index 1 (3), swap to get [3,2,1], reverse suffix [2,1] to get [3,1,2]
Example 3 — Last Permutation
$ Input: nums = [3,2,1]
Output: [1,2,3]
💡 Note: No pivot found (descending order), this is the last permutation, so reverse entire array to get first permutation [1,2,3]

Constraints

  • 1 ≤ nums.length ≤ 100
  • 0 ≤ nums[i] ≤ 100

Visualization

Tap to expand
Next Permutation: Transform to Next Lexicographical OrderFind the next permutation that comes after current one in sorted orderInput Array123Current: [1,2,3]Apply AlgorithmOutput Array132Next: [1,3,2]Algorithm: Find pivot (2), find successor (3), swap them, reverse suffixIf no next permutation exists (e.g., [3,2,1]), return first permutation [1,2,3]Time Complexity: O(n) | Space Complexity: O(1)
Understanding the Visualization
1
Input
Current permutation array
2
Process
Apply next permutation algorithm
3
Output
Next lexicographically larger permutation
Key Takeaway
🎯 Key Insight: Next permutation follows a mathematical pattern that can be computed in O(n) time
Asked in
Google 25 Amazon 20 Microsoft 15 Facebook 12
314.5K Views
Medium Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen