Backend Engineer
Senior
programming
Create a function that returns all possible permutations of a given string, ensuring that no permutation is repeated in the result.
Constraints:
- The input string will only consist of lowercase English letters. Its length will not exceed 8 characters.
Examples:
1. Input: 'a'
Output: ['a']
2. Input: 'aba'
Output: ['aab', 'aba', 'baa']
```
def permute_unique(s):
results = []
def backtrack(path, used):
if len(path) == len(s):
results.append(''.join(path))
return
for i in range(len(s)):
if used[i]:
continue
if i > 0 and s[i] == s[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(s[i])
backtrack(path, used)
path.pop()
used[i] = False
s = sorted(s)
backtrack([], [False] * len(s))
return results
# Example usages:
print(permute_unique('a')) # ['a']
print(permute_unique('aba')) # ['aab', 'aba', 'baa']
```
Trusted by 100+ professionals preparing for interviews
Trusted by 100+ professionals
50+ Company Question Banks
5+ Supported Languages
Practice More Questions Like This
Generate unlimited interview questions with structured answers, code runner, and AI-powered walkthroughs.
Get Started Free