First Letter to Appear Twice Problem
#2351
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2351.
Given a string s consisting of lowercase English letters, return the first letter to appear twice.
Note:
- A letter
aappears twice before another letterbif the second occurrence ofais before the second occurrence ofb. swill contain at least one letter that appears twice.
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'.
Constraints:
2 <= s.length <= 100sconsists of lowercase English letters.shas at least one repeated letter.
Solution
Approach: Set of Seen Letters
Scan the string from left to right and remember the letters seen so far. The first letter that is already in the set is the one whose second occurrence comes first, so return it. Otherwise add the letter to the set.
Complexity: O(n) time and O(C) extra space, where C = 26 is the alphabet size.
class Solution:
def repeatedCharacter(self, s: str) -> str:
seen = set()
for c in s:
if c in seen:
return c
seen.add(c)
return ' '