Java String Program · S49
Print All Permutations of a String in Java
List every ordering of a string's characters, once each, even when some characters repeat. Sorting first lets the code skip duplicate choices cleanly.
Problem Statement
Write a method that returns every distinct permutation of a string, in lexicographic (dictionary) order.
If the string contains repeated characters, each different arrangement must appear only once. A string of n distinct characters has n! permutations.
Input/Output Examples
"ABC"Output[ABC, ACB, BAC, BCA, CAB, CBA] (6)Explanation: 3! = 6 orderings."AAB"Output[AAB, ABA, BAA] (3)Explanation: 3! / 2! = 3, because swapping the two A's changes nothing."Z"Output[Z] (1)Explanation: one character has one ordering.Visual Explanation
- SortedcharsAABequal letters are neighbours
- Position 0choicesAABsecond A skipped avoids a duplicate branch
- Under AresultsAABABArecurse on the rest
- Under BresultsBAArecurse on the rest
- Done3 permutations
"AAB": after sorting, the second A is skipped at a position where the first A was not used yet, so each distinct permutation is produced once.The rule chars[i] == chars[i - 1] && !used[i - 1] makes sure equal characters are always used in their original order. That removes every duplicate branch before it is explored.
Approaches
Both approaches produce the distinct permutations in sorted order. One recurses; the other steps from one permutation to the next.
Approach 1: Backtracking With Duplicate Skip (Recommended)
Idea: sort the characters, then build permutations position by position, skipping a character equal to an unused previous one.
- Sort the characters.
- At each step, try every unused character.
- Skip
chars[i]if it equalschars[i - 1]andchars[i - 1]is unused. - Append, recurse, then undo the choice.
Time: O(n! × n) · Space: O(n). Space excludes the output list.
Approach 2: Next Lexicographic Permutation
Idea: start from the sorted string and repeatedly transform it into the next larger arrangement until none exists.
- Find the rightmost index
iwitha[i] < a[i + 1]; if there is none, stop. - Find the rightmost
jwitha[j] > a[i]and swap them. - Reverse the part after
i.
Time: O(n! × n) · Space: O(1). Excluding the output.
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: Backtracking With Duplicate Skip (Recommended)
The used array and one shared StringBuilder keep the working memory proportional to n.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PermutationsBacktrack {
// Sorting first puts equal characters side by side, so duplicates can be skipped
static List<String> permutations(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
List<String> result = new ArrayList<>();
build(chars, new boolean[chars.length], new StringBuilder(), result);
return result;
}
private static void build(char[] chars, boolean[] used, StringBuilder current, List<String> result) {
if (current.length() == chars.length) {
result.add(current.toString());
return;
}
for (int i = 0; i < chars.length; i++) {
if (used[i]) {
continue;
}
if (i > 0 && chars[i] == chars[i - 1] && !used[i - 1]) {
continue; // same letter at this position already tried
}
used[i] = true;
current.append(chars[i]);
build(chars, used, current, result);
current.deleteCharAt(current.length() - 1);
used[i] = false;
}
}
public static void main(String[] args) {
String[] inputs = {"ABC", "AAB", "Z"};
for (String s : inputs) {
List<String> r = permutations(s);
System.out.println("\"" + s + "\" -> " + r + " (" + r.size() + ")");
}
}
}
"ABC" -> [ABC, ACB, BAC, BCA, CAB, CBA] (6) "AAB" -> [AAB, ABA, BAA] (3) "Z" -> [Z] (1)
Time complexity: O(n! × n) · Space complexity: O(n).
Approach 2: Next Lexicographic Permutation
No recursion, and duplicates are handled automatically because equal arrangements are never generated twice.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PermutationsNext {
// Starts from the smallest arrangement and repeatedly steps to the next larger one
static List<String> permutations(String s) {
char[] chars = s.toCharArray();
Arrays.sort(chars);
List<String> result = new ArrayList<>();
do {
result.add(new String(chars));
} while (nextPermutation(chars));
return result;
}
private static boolean nextPermutation(char[] a) {
int i = a.length - 2;
while (i >= 0 && a[i] >= a[i + 1]) {
i--; // find the rightmost ascent
}
if (i < 0) {
return false; // already the largest arrangement
}
int j = a.length - 1;
while (a[j] <= a[i]) {
j--; // smallest character on the right that is larger
}
swap(a, i, j);
for (int l = i + 1, r = a.length - 1; l < r; l++, r--) {
swap(a, l, r); // make the suffix as small as possible
}
return true;
}
private static void swap(char[] a, int i, int j) {
char t = a[i];
a[i] = a[j];
a[j] = t;
}
public static void main(String[] args) {
String[] inputs = {"ABC", "AAB", "Z"};
for (String s : inputs) {
List<String> r = permutations(s);
System.out.println("\"" + s + "\" -> " + r + " (" + r.size() + ")");
}
}
}
"ABC" -> [ABC, ACB, BAC, BCA, CAB, CBA] (6) "AAB" -> [AAB, ABA, BAA] (3) "Z" -> [Z] (1)
Time complexity: O(n! × n) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Backtracking With Duplicate Skip | O(n! × n) | O(n) |
| Next Lexicographic Permutation | O(n! × n) | O(1) |
Here n is the length of the string. There can be up to n! permutations, each of length n, so any solution that lists them all needs at least O(n! × n) time.
Interview Tips and Recommended Approach
- Ask about duplicates. Using a
Setto remove them works but still generates every duplicate first. - Explain the skip rule. It is the part interviewers probe most often.
- Know the output size. 10 characters already give 3,628,800 permutations.
- Mention
nextPermutation. It is a classic algorithm and useful when you need permutations one at a time.
Recommended Approach: Backtracking With Duplicate Skip
Why: it shows the general backtracking pattern, removes duplicates without a set and keeps only the current path in memory.