Permutations of a String
The problem
Given a string s, return all unique permutations of its characters in sorted order.
- The output should be a list of strings, where each string is a valid permutation of s.
- If the string contains duplicate characters, each permutation should appear only once.
- The list should be sorted lexicographically.
You must return a list of strings, where each string is a valid permutation of s.
Input: s = "abc" Output: ["abc","acb","bac","bca","cab","cba"] **Explanation: **All 6 permutations of 3 distinct characters.
**Input: **s = "aab" Output: ["aab","aba","baa"] Explanation: Only 3 unique permutations due to duplicate 'a'.
Input: s = "aa"
- 1 <= s.length <= 8
- s consists of lowercase English letters (a to z)
- Return only unique permutations if the input string has duplicate characters
cpp
class Solution {
public:
vector<string> permuteUnique(string s) {
// Your code goes here
}
};java
class Solution {
public List<String> permuteUnique(String s) {
// Your code goes here
}
}python
class Solution:
def permuteUnique(self, s: str) -> list:
# Your code goes herejavascript
class Solution {
permuteUnique(s) {
// Your code goes here
}
}csharp
class Solution {
public IList<string> PermuteUnique(string s) {
// Your code goes here
}
}go
func permuteUnique(s string) []string {
// Your code goes here
}Stuck? Show a way to structure it+
- 01Sort the characters first.
- 02Track which indices are currently used.
- 03Build one permutation left to right.
- 04Skip an equal character when its previous equal copy was not used.
- 05Emit a copy when the path reaches the string length.
Reference answer
Then expect these follow-ups
How would you implement this by repeatedly calling next permutation?
Tests: implementation extension
What is the output count for character frequencies c1, c2, and so on?
Tests: follow-up reasoning
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question