Print all the permutations of the given string
Pattern: Permutations
Sort the letters, then fill positions one at a time with any unused letter. To avoid repeats, a letter may be used only if the equal letter before it is already used, so equal letters always appear in their original order.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given a string, return all of its distinct permutations (each arrangement of its letters, listed once). For example,
"abc" gives abc acb bac bca cab cba, and "aab" gives aab aba baa.
This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name
permutations is this guide's own. The tests compare the answers after sorting.
Think first
- How many permutations do
ndifferent letters have? - Why does
"aab"produce repeats if you treat bothas as different? - What rule makes each distinct arrangement come out once?
Hints
Brute force, and why it fails
Generate all n! orderings and remove duplicates with a set: same time, plus memory for the set, and repeated work. The
skip rule never builds a duplicate.
The key insight
A repeated arrangement comes from picking equal letters in a different order. Fixing that order removes exactly the repeats.
Dry run
s = aab, sorted already. used is all false.
The plan
sort c
function build(cur):
if len(cur) == n: record cur; return
for i in 0..n-1:
if used[i]: continue
if i > 0 and c[i] == c[i - 1] and not used[i - 1]: continue
used[i] = true; build(cur + c[i]); used[i] = false
build("")
Complexity
- Time
O(n! × n)- Space
O(n)
At most n! results of length n. The recursion is n deep.
Edge cases
- One letter: itself.
- All letters equal: one permutation.
- Distinct letters:
n!permutations.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<String> permutations(String s) {
char[] c = s.toCharArray();
Arrays.sort(c); // equal letters side by side
List<String> out = new ArrayList<>();
build(c, new boolean[c.length], new StringBuilder(), out);
return out;
}
private void build(char[] c, boolean[] used, StringBuilder cur, List<String> out) {
if (cur.length() == c.length) { out.add(cur.toString()); return; }
for (int i = 0; i < c.length; i++) {
if (used[i]) continue;
if (i > 0 && c[i] == c[i - 1] && !used[i - 1]) continue; // use equal letters only in order: no repeats
used[i] = true;
cur.append(c[i]);
build(c, used, cur, out);
cur.deleteCharAt(cur.length() - 1);
used[i] = false;
}
}
}C++
class Solution {
public:
vector<string> permutations(string s) {
sort(s.begin(), s.end()); // equal letters side by side
vector<string> out;
vector<bool> used(s.size(), false);
string cur;
build(s, used, cur, out);
return out;
}
void build(const string& c, vector<bool>& used, string& cur, vector<string>& out) {
if (cur.size() == c.size()) { out.push_back(cur); return; }
for (size_t i = 0; i < c.size(); i++) {
if (used[i]) continue;
if (i > 0 && c[i] == c[i - 1] && !used[i - 1]) continue; // use equal letters only in order: no repeats
used[i] = true;
cur.push_back(c[i]);
build(c, used, cur, out);
cur.pop_back();
used[i] = false;
}
}
};Python
class Solution:
def permutations(self, s: str) -> list[str]:
c = sorted(s) # equal letters side by side
used, out = [False] * len(c), []
def build(cur: list) -> None:
if len(cur) == len(c):
out.append("".join(cur))
return
for i in range(len(c)):
if used[i] or (i > 0 and c[i] == c[i - 1] and not used[i - 1]):
continue # use equal letters only in order: no repeats
used[i] = True
cur.append(c[i])
build(cur)
cur.pop()
used[i] = False
build([])
return outCommon mistakes
- Forgetting to sort before applying the skip rule.
- Testing
used[i - 1]in one place andnot used[i - 1]in another. Either rule works on its own; mixed, it drops or repeats arrangements. - Swapping in place without restoring the order, which can still produce duplicates.