2351. First Letter to Appear Twice
Description
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.
Solutions
Solution 1: Array or Hash Table
Thinking
We want the first letter whose count reaches two. \(s\) is short and has a duplicate, so one scan suffices.
Increment a map or array; return as soon as some key becomes \(2\).
We traverse the string \(s\), using an array or hash table cnt to record the occurrence of each letter. When a letter appears twice, we return that letter.
The time complexity is \(O(n)\) and the space complexity is \(O(C)\). Here, \(n\) is the length of the string \(s\), and \(C\) is the size of the character set. In this problem, \(C = 26\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 | |
Solution 2: Bit Manipulation
Thinking
Method 1 stores counts. We only need “seen or not”, so one bit per letter in an integer mask, in constant space.
We can also use an integer mask to record whether each letter has appeared, where the \(i\)-th bit of mask indicates whether the \(i\)-th letter has appeared. When a letter appears twice, we return that letter.
The time complexity is \(O(n)\) and the space complexity is \(O(1)\). Here, \(n\) is the length of the string \(s\).
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 | |