First non-repeating character in a string
Filed under Goldman Sachs · Also reported at BlackRock, GE Vernova, HCLTech, NielsenIQ, Optum (UnitedHealth Group), Raja Software Labs, Teradata, Vuram Technology
Free read 2 of 3Ask what to return (character or index), what to return when none exists, and the alphabet (ASCII, Unicode, case).
The question
Given a string, return the first character that does not repeat anywhere in the string. Return None if every character repeats. The solution had to pass all test cases supplied by the interviewer.
Constraints
- 1 <= len(s) <= 10^5
- Characters are case-sensitive; assume ASCII or lowercase letters unless told otherwise
Examples
- Input
- swiss
- Output
- w
- Why
- s appears three times, w appears once and comes first among the unique characters.
- Input
- aabb
- Output
- None
- Why
- Every character repeats, so there is no answer.
Approach
Ask what to return (character or index), what to return when none exists, and the alphabet (ASCII, Unicode, case).
For each character scan the rest of the string for another copy: O(n^2) time, O(1) space. Fine for tiny inputs only.
First pass builds a frequency map; second pass walks the string in order and returns the first character whose count is 1. O(n) time, O(k) space for k distinct characters.
Empty string, all characters equal, all distinct (answer is the first character), mixed case, and a unique character at the very end. Write these as test cases up front.
Solution
O(n) time, O(k) space
from collections import Counter
def first_unique(s):
counts = Counter(s) # pass 1: frequencies
for ch in s: # pass 2: original order
if counts[ch] == 1:
return ch
return None
Tips
- What they are testing: Counting versus ordering: you need frequencies and the original order, so two passes (count, then scan) or an ordered map.
- Common mistake: Returning the first character with count 1 from a dictionary or set that loses insertion order, or returning an index when the character is asked for.
Related Goldman Sachs questions
Collected from public candidate posts and coding forums. Updated Nov 2026.