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

Two-pass frequency scan
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