First Letter to Appear Twice - Problem

Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:

  • A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
  • s will contain at least one letter that appears twice.

Input & Output

Example 1 — Basic Case
$ Input: s = "abccba"
Output: c
💡 Note: The first letter to appear twice is 'c' - it appears at positions 2 and 3
Example 2 — Early Duplicate
$ Input: s = "abba"
Output: b
💡 Note: The first letter to appear twice is 'b' - it appears at positions 1 and 2
Example 3 — Immediate Repeat
$ Input: s = "aab"
Output: a
💡 Note: The first letter to appear twice is 'a' - it appears at positions 0 and 1

Constraints

  • 2 ≤ s.length ≤ 100
  • s consists of lowercase English letters
  • s has at least one repeating letter

Visualization

Tap to expand
First Letter to Appear TwiceInput: "abccba"abccba012345First duplicate!Character 'c' appears at positions 2 and 3This is the first letter to appear twiceOutput: c
Understanding the Visualization
1
Input
String with lowercase letters
2
Process
Track seen characters while iterating
3
Output
Return first duplicate found
Key Takeaway
🎯 Key Insight: Use a hash set to remember which characters you've seen - the first repeat is your answer
Asked in
Meta 15 Amazon 12
28.0K Views
Medium Frequency
~8 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen