Java Array Program · A34
Next Permutation of an Array in Java
Find the rightmost place where the array can still grow, make it grow by the smallest step, then make everything after it as small as possible.
Problem Statement
Rearrange an array of integers into the next larger arrangement in lexicographic (dictionary) order, in place.
If the array is already the largest arrangement, rearrange it into the smallest, which is ascending order. Duplicates are allowed.
Input/Output Examples
[1, 2, 3]Output[1, 3, 2]Explanation: only the last two elements need to change.[2, 4, 3, 1]Output[3, 1, 2, 4]Explanation: 2 is replaced by 3, and the rest becomes as small as possible.[3, 2, 1]Output[1, 2, 3]Explanation: it wraps around to the smallest arrangement.Visual Explanation
- Find ascentarray24312 < 4; the suffix 4 3 1 is decreasing
- Swaparray3421swap 2 with 3, the smallest value larger than 2 in the suffix
- Reverse suffixarray31244 2 1 becomes 1 2 4
- Done[3, 1, 2, 4]
[2, 4, 3, 1]: the rightmost ascent is at 2; swap it with 3, then reverse the suffix to make it as small as possible.A decreasing suffix is already the largest arrangement of its values, so the change must happen just before it. After the swap the suffix is still decreasing, so reversing it makes it increasing, which is the smallest order.
Approaches
The standard algorithm works in place in linear time. The brute force lists every arrangement and is only suitable for tiny arrays.
Approach 1: Pivot, Swap, Reverse (Recommended)
Idea: find the rightmost i with a[i] < a[i + 1], swap a[i] with the rightmost larger value, and reverse everything after i.
- Scan from the right for the first
a[i] < a[i + 1]. - If found, scan from the right for the first
a[j] > a[i]and swap them. - Reverse the suffix after
i(the whole array if noiwas found).
Time: O(n) · Space: O(1).
Approach 2: List All Permutations
Idea: generate every distinct arrangement in sorted order and pick the one after the current array.
- Generate all permutations into a sorted set.
- Find the next larger one with
higher(). - Wrap to the first one if there is none.
Time: O(n! × n) · Space: O(n! × n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Pivot, Swap, Reverse (Recommended)
Using ≥ and ≤ in the scans handles duplicate values correctly.
import java.util.Arrays;
public class NextPermArray {
// Find the rightmost ascent, swap it with the next larger value to its right, reverse the suffix
static void nextPermutation(int[] a) {
int i = a.length - 2;
while (i >= 0 && a[i] >= a[i + 1]) {
i--;
}
if (i >= 0) {
int j = a.length - 1;
while (a[j] <= a[i]) {
j--;
}
swap(a, i, j);
}
for (int l = i + 1, r = a.length - 1; l < r; l++, r--) {
swap(a, l, r); // largest arrangement -> wraps to smallest
}
}
private static void swap(int[] a, int i, int j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void main(String[] args) {
int[][] inputs = {{1, 2, 3}, {2, 4, 3, 1}, {3, 2, 1}, {1, 1, 5}};
for (int[] a : inputs) {
String before = Arrays.toString(a);
nextPermutation(a);
System.out.println(before + " -> " + Arrays.toString(a));
}
}
}
[1, 2, 3] -> [1, 3, 2] [2, 4, 3, 1] -> [3, 1, 2, 4] [3, 2, 1] -> [1, 2, 3] [1, 1, 5] -> [1, 5, 1]
Time complexity: O(n) · Space complexity: O(1).
Approach 2: List All Permutations
Only practical for very short arrays; it exists here to cross-check the linear algorithm.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class NextPermBrute {
// Lists every distinct arrangement in sorted order and picks the one after the input
static void nextPermutation(int[] a) {
TreeSet<List<Integer>> all = new TreeSet<>((x, y) -> {
for (int k = 0; k < x.size(); k++) {
if (!x.get(k).equals(y.get(k))) {
return x.get(k) - y.get(k);
}
}
return 0;
});
permute(a, 0, all);
List<Integer> current = new ArrayList<>();
for (int v : a) {
current.add(v);
}
List<Integer> next = all.higher(current);
if (next == null) {
next = all.first(); // wrap around to the smallest
}
for (int k = 0; k < a.length; k++) {
a[k] = next.get(k);
}
}
private static void permute(int[] a, int k, TreeSet<List<Integer>> out) {
if (k == a.length) {
List<Integer> p = new ArrayList<>();
for (int v : a) {
p.add(v);
}
out.add(p);
return;
}
for (int i = k; i < a.length; i++) {
int t = a[k]; a[k] = a[i]; a[i] = t;
permute(a, k + 1, out);
t = a[k]; a[k] = a[i]; a[i] = t;
}
}
public static void main(String[] args) {
int[][] inputs = {{1, 2, 3}, {2, 4, 3, 1}, {3, 2, 1}, {1, 1, 5}};
for (int[] a : inputs) {
String before = Arrays.toString(a);
nextPermutation(a);
System.out.println(before + " -> " + Arrays.toString(a));
}
}
}
[1, 2, 3] -> [1, 3, 2] [2, 4, 3, 1] -> [3, 1, 2, 4] [3, 2, 1] -> [1, 2, 3] [1, 1, 5] -> [1, 5, 1]
Time complexity: O(n! × n) · Space complexity: O(n! × n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Pivot, Swap, Reverse | O(n) | O(1) |
| List All Permutations | O(n! × n) | O(n! × n) |
Here n is the array length. The standard algorithm scans and reverses at most once; the brute force grows factorially.
Interview Tips and Recommended Approach
- Explain the decreasing suffix. It is the key insight behind the whole algorithm.
- Swap with the rightmost larger value, which is the smallest value larger than the pivot because the suffix is decreasing.
- Reverse, do not sort. The suffix is already ordered, so reversing is enough and costs
O(n). - Handle the last permutation. Reversing the whole array wraps around to the first one.
Recommended Approach: Pivot, Swap, Reverse
Why: it runs in linear time with constant memory and is the same algorithm C++'s std::next_permutation uses.