19. Find the First Repeated Character
Given a string, find the first character that appears more than once.
How It Works & Algorithmic Design
Use a set to remember characters already encountered:
- Create an empty set.
- Traverse the string from left to right.
- If the current character already exists in the set, return it immediately.
- Otherwise, add it to the set.
- If no character repeats, return
nullor an equivalent empty value.
Why This Approach Works Best
A set provides efficient membership checking. The expected time complexity is $O(n)$ and the additional space complexity is $O(n)$.
Example Walkthrough
Input
"programming"
Characters are inspected from left to right.
Trace
p -> r -> o -> g -> r (already seen)
The second occurrence of r is the first repeated character.
Output
"r"
r is the first character encountered for the second time.
Answer: Find first repeated character
function firstRepeated(str) {
const seen = new Set();
for (const char of str) {
if (seen.has(char)) return char;
seen.add(char);
}
return null;
}Use a hash set to remember characters that have already appeared.
Key Takeaways
A hash set provides efficient membership checking.
Returning immediately ensures the first repeated character is found.
Expected time is O(n) with O(n) additional space.