Backend Engineer
Senior
programming
Implement a function that takes a string as input and returns all unique permutations of the string sorted in lexicographical order.
Constraints:
- The input string will contain lowercase letters only and will have at most length 9.
Examples:
1. Input: 'abb'
Output: ['abb', 'bab', 'bba']
2. Input: 'a'
Output: ['a']
```
def unique_permutations(s):
from collections import Counter
res = []
def backtrack(path, counter):
if len(path) == len(s):
res.append(''.join(path))
return
for char in counter:
if counter[char] > 0:
path.append(char)
counter[char] -= 1
backtrack(path, counter)
path.pop()
counter[char] += 1
backtrack([], Counter(s))
return sorted(res)
# Example usages:
print(unique_permutations('abb')) # ['abb', 'bab', 'bba']
print(unique_permutations('a')) # ['a']
```
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