19. Find the First Repeated Character

Difficulty:EasyPattern:Hash SetTime:O(n)Space:O(n)

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:

  1. Create an empty set.
  2. Traverse the string from left to right.
  3. If the current character already exists in the set, return it immediately.
  4. Otherwise, add it to the set.
  5. If no character repeats, return null or 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.