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 Twice INPUT String s = "abccba" a 0 b 1 c 2 c 3 b 4 a 5 Hash Set (seen) Tracks characters we've already seen { a, b, c } Approach: Hash Set ALGORITHM STEPS 1 Initialize Set Create empty hash set 2 Iterate String Loop through each char 3 Check Set If char in set, return it 4 Add to Set Otherwise add char to set Execution Trace: char set action a {a} add b {a,b} add c {a,b,c} add c in set! RETURN FINAL RESULT First duplicate found: c Output: "c" Character 'c' at index 3 was already in the set (added at index 2) OK Key Insight: A Hash Set provides O(1) lookup time. By checking if each character exists in the set before adding it, we can detect the first duplicate in O(n) time with O(k) space, where k is the alphabet size (26 letters). TutorialsPoint - First Letter to Appear Twice | Hash Set Approach
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