First Letter to Appear Twice
EasyUpdated: Jul 27, 2025
Practice on:
Problem
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.
Examples
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'.
Solution
Method 1 – Hash Set for First Repeated Letter
Intuition
We need to find the first letter that appears twice in the string. By iterating through the string and keeping track of seen letters in a hash set, we can immediately return the first letter that is already in the set.
Approach
- Initialize an empty set to store seen letters.
- Iterate through each character in
s:- If the character is already in the set, return it.
- Otherwise, add it to the set.
- The problem guarantees there is at least one repeated letter, so we will always find an answer.
Complexity
- ⏰ Time complexity:
O(n), wherenis the length ofs, since we process each character once. - 🧺 Space complexity:
O(1), since the set can contain at most 26 letters.
Code
Java
class Solution {
public char repeatedCharacter(String s) {
Set<Character> seen = new HashSet<>();
for (char c : s.toCharArray()) {
if (seen.contains(c)) return c;
seen.add(c);
}
return 'a'; // guaranteed to find a repeated character
}
}
C++
class Solution {
public:
char repeatedCharacter(string s) {
unordered_set<char> seen;
for (char c : s) {
if (seen.count(c)) return c;
seen.insert(c);
}
return 'a'; // guaranteed to find a repeated character
}
};
Python
class Solution:
def repeatedCharacter(self, s: str) -> str:
seen = set()
for c in s:
if c in seen:
return c
seen.add(c)