First Letter to Appear Twice - Problem

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

The twist here is in understanding what "first" means: A letter a appears twice before another letter b if the second occurrence of a comes before the second occurrence of b.

Example: In the string "abccba", both 'c' and 'b' appear twice, but 'c' completes its second occurrence at index 3, while 'b' completes its second occurrence at index 4. Therefore, 'c' is the answer.

You are guaranteed that the input string contains at least one letter that appears twice.

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abccba"
โ€บ Output: "c"
๐Ÿ’ก Note: The letter 'c' appears at indices 2 and 3. The letter 'b' appears at indices 1 and 4. The letter 'a' appears at indices 0 and 5. Since 'c' completes its second occurrence first (at index 3), it is the first letter to appear twice.
example_2.py โ€” Early Duplicate
$ Input: s = "abcdd"
โ€บ Output: "d"
๐Ÿ’ก Note: The letter 'd' appears at indices 3 and 4, making it the first (and only) letter to appear twice in this string.
example_3.py โ€” Multiple Duplicates
$ Input: s = "abcabc"
โ€บ Output: "a"
๐Ÿ’ก Note: Letters 'a', 'b', and 'c' all appear twice. 'a' completes its second occurrence at index 3, 'b' at index 4, and 'c' at index 5. Therefore, 'a' is the first to appear twice.

Constraints

  • 2 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters only
  • s has at least one repeated letter

Visualization

Tap to expand
๐ŸŽฏ Party Attendance AnalogyGuest Arrival Queue1. Alice (a) โ†’ โœ“ Add to list2. Bob (b) โ†’ โœ“ Add to list3. Carol (c) โ†’ โœ“ Add to list4. Carol (c) โ†’ โŒ Already here!5. Bob (b) โ†’ (not checked)6. Alice (a) โ†’ (not checked)Attendance Sheetโœ“ Alice (a)โœ“ Bob (b)โœ“ Carol (c)๐Ÿšจ Carol trying to enter again!๐ŸŽ‰ Answer: Carol (c)First guest to attempt entering twice!No need to check remaining guests
Understanding the Visualization
1
Setup Guest List
Prepare an empty attendance sheet (hash set)
2
Check Each Guest
As each guest arrives, check if they're already on the list
3
Spot the Duplicate
The first guest already on the list is your answer!
Key Takeaway
๐ŸŽฏ Key Insight: Just like a bouncer at a party instantly recognizes repeat visitors, our hash set gives us instant O(1) lookup to detect the first character attempting a 'second entry' into our string!
Asked in
Google 28 Amazon 23 Meta 19 Microsoft 15
23.4K Views
Medium Frequency
~15 min Avg. Time
892 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