#2351
First Letter to Appear Twice
newbie · 230 · lc easy +17 · verified · 74.9% accepted · 1,182 likes · top 86%
Description
Given a string s of lowercase English letters, find and return the character whose second occurrence comes earliest in the string.
Notes:
- Character a is considered to appear twice before character b if a's second occurrence precedes b's second occurrence.
- It is guaranteed that at least one character repeats in s.
Example 1:
Input: s = "abccbaacz"
Output: "c"
Explanation:
The letter 'a' appears on the indexes 0, 5 and 6.
The letter 'b' appears on the indexes 1 and 4.
The letter 'c' appears on the indexes 2, 3 and 7.
The letter 'z' appears on the index 8.
The letter 'c' is the first letter to appear twice, because out of all the letters the index of its second occurrence is the smallest.
Example 2:
Input: s = "abcdd"
Output: "d"
Explanation:
The only letter that appears twice is 'd' so we return 'd'.
Code
1
2
3