LeetCode #31: Next Permutation — Solved in Java
Basic Suffix Sort and In Place Reverse With Two Pointers
The Next Permutation LeetCode problem asks you to move an array of numbers to the next ordering that is larger than the one you start with. That change happens in place, and when no higher ordering exists the array rolls back to the smallest sorted version.
Solving this problem in Java starts with spotting where the array begins to fall near the end. That moment tells you where the current ordering can move forward. A scan from the right can help you find that point, and from there it becomes a small sequence of actions. Swap the value at that spot with a slightly larger one farther to the right, then bring the tail back into its smallest rising form.
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 ofarr:[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 ofnums.The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3] Output: [1,3,2]Example 2:
Input: nums = [3,2,1] Output: [1,2,3]Example 3:
Input: nums = [1,1,5] Output: [1,5,1]Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
Solution 1: Basic Suffix Sort
This answer follows the classic next permutation logic but leans on Arrays.sort for the tail of the array. That keeps the control flow easier to read, at the cost of a slightly higher time cost on the suffix.
Keep reading with a 7-day free trial
Subscribe to Alexander Obregon's Substack to keep reading this post and get 7 days of free access to the full post archives.

