Backend Engineer
Senior
programming
Implement a function that returns all unique permutations of a given string, ensuring that the output is sorted lexicographically.
Constraints:
- Str length from 1 to 8. Each character is a lowercase letter.
Examples:
1. Input: 'zyx'
Output: ['xyz', 'xzy', 'yxz', 'yzx', 'zxy', 'zyx']
2. Input: 'bca'
Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
```
def sorted_unique_permutations(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(sorted_unique_permutations('zyx')) # ['xyz', 'xzy', 'yxz', 'yzx', 'zxy', 'zyx']
print(sorted_unique_permutations('bca')) # ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
```
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