FIND THE FIRST
REPEATED CHARACTER
IN A GIVEN STRING
When I interview junior developers, I love throwing small-but-smart problems at them. Not because I want to see them sweat but because these little puzzles tell me how someone thinks.
One of my favorites: “Find the first repeated character inside a string.”
Most people overthink it.
Some start building maps.
Others loop twice.
A few bring out regex like they’re going to war.
Let me walk you through it like I would with a teammate.
The Thought Process
The job is simple: We scan characters one by one and return the first character that has appeared before.
So naturally, we need something that:
- check_circle Stores things we’ve seen
- check_circle Lets us check quickly whether something is already there
- check_circle Doesn’t allow duplicates
Sounds familiar? That’s exactly what a Set is made for.
The Clean Java Solution
Here’s the simplest version using only a Set
public Character firstRepeatedChar(String input) {
if (input == null || input.isEmpty()) return null;
Set<Character> seen = new HashSet<>();
for (char c : input.toCharArray()) {
if (!seen.add(c)) {
// add() returns false when element already exists
return c;
}
}
return null; // no repeated character
}Why I like this:
- check_circle No extra complexity
- check_circle add() returning false becomes your “ding ding!” signal
- check_circle Runs in O(n) time
- check_circle Easy to explain in code review or interviews
Example
Input: "abcaadef"
Output: 'a'