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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code