Return the set of distinct characters in a Python string and check whether all characters are unique. O(n) time with set() and live tests.
The problem
Return the set of distinct characters in s.
Examples
Example 1
Input
unique_chars('programming')Expected output
{'m', 'i', 'g', 'p', 'n', 'a', 'o', 'r'}Example 2
Input
unique_chars('aaa')Expected output
{'a'}
+ 2 hidden tests on Submit — case-sensitive.
Edge cases to ask about
- Empty string → set()
- Case
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and measure your code against the optimal one at growing input sizes.
Pick both to reveal the answer.
Measure it
Runs the function on inputs of size 250 up to 16,000 and records the time and peak memory. Slow solutions stop early — a short curve is itself the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Manual loop with a set | O(n) | O(k) | |
| bestset(s) | O(n) | O(k) | A string is an iterable of characters. |
Walkthrough of the optimal approach (try it yourself first)
set(s) iterates the characters and keeps one of each. A popular follow-up is "are all characters unique?" — len(set(s)) == len(s). Remember that {} is an empty dict; the empty set is set().
Complexity: O(n) time, O(k) space. Each character is hashed once; the set holds k distinct characters.
Reveal the reference solution
def unique_chars(s): return set(s)
Follow-ups interviewers ask
- Are all characters unique, without extra memory?
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Get Unique Characters of a String in Python?
The optimal solution runs in O(n) time and O(k) auxiliary space. Each character is hashed once; the set holds k distinct characters.
What is the brute-force approach, and how do you optimise it?
Manual loop with a set: O(n) time, O(k) space. set(s): O(n) time, O(k) space. A string is an iterable of characters.
What follow-up questions do interviewers ask about Get Unique Characters of a String?
Are all characters unique, without extra memory?
