Problem

Given a string s consisting of lowercase English letters, return the first letter to appear twice.

Note:

  • A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b.
  • s will contain at least one letter that appears twice.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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:

1
2
3
4
5
6
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

  1. Initialize an empty set to store seen letters.
  2. Iterate through each character in s:
    • If the character is already in the set, return it.
    • Otherwise, add it to the set.
  3. The problem guarantees there is at least one repeated letter, so we will always find an answer.

Complexity

  • ⏰ Time complexity: O(n), where n is the length of s, since we process each character once.
  • 🧺 Space complexity: O(1), since the set can contain at most 26 letters.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
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
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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
    }
};
1
2
3
4
5
6
7
class Solution:
    def repeatedCharacter(self, s: str) -> str:
        seen = set()
        for c in s:
            if c in seen:
                return c
            seen.add(c)