The Lone Character
An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.
- Domain
- Python
- Difficulty
- easy
- Seniority
- L5
Problem
Given a string, return the first character that appears exactly once. Return '' if no such character exists.
It appeared exactly one time. That made it special.
Example 1
Input:
s = "aabbc"
Output:
"c"
Example 2
Input:
s = "abcabc"
Output:
""
Worked solution and explanation
Why this problem exists in real interviews
This tests frequency counting and order-preserving lookup. The challenge is not just finding a unique character but finding the *first* one, which requires a second pass through the string in its original order.
Break down the requirements
Step 1: Count character frequencies
Build a dictionary mapping each character to how many times it appears in the string.
Step 2: Scan the string again in order
Walk through the original string and return the first character whose count is exactly 1.
Step 3: Handle the all-repeats case
If no character has a count of 1, return an empty string.
The solution
def first_unique_char(s):
counts = {}
for ch in s:
if ch in counts:
counts[ch] += 1
else:
counts[ch] = 1
for ch in s:
if counts[ch] == 1:
return ch
return '' Common follow-up questions
- Could you solve this with a single pass using an OrderedDict? (Tests knowledge of ordered data structures and when they add value.)
- What if the string contained Unicode characters beyond ASCII? (Tests awareness that the alphabet size k could be much larger than 26.)
- How would you find the first character that appears exactly k times? (Tests generalizing the frequency threshold.)