First Letter to Appear Twice

To solve this problem, we need to track the occurrences of each letter. Since we are interested in finding the first letter that appears twice, we can use two dictionaries to store the first occurrence index and the second occurrence index of each letter.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
    def repeatedCharacter(self, s: str) -> str:
        first_occurrence = {}
        second_occurrence = {}

        for i, letter in enumerate(s):
            if letter not in first_occurrence:
                first_occurrence[letter] = i
            elif letter not in second_occurrence:
                second_occurrence[letter] = i

        # sort by index of second occurrence and return the first key
        second_occurrence_sorted = sorted(second_occurrence.items(), key=lambda item: item[1])

        if len(second_occurrence_sorted) > 0:
            return second_occurrence_sorted[0][0]
        else:
            return ""

In this code, we initialize two dictionaries first_occurrence and second_occurrence. As we iterate over the string s, we update these dictionaries. If a letter is not in first_occurrence, we add it. If it’s already in first_occurrence but not in second_occurrence, we add it to second_occurrence.

After the iteration, we sort second_occurrence by values (indices) in ascending order. If second_occurrence_sorted is not empty, we return the first key (i.e., the letter that has the smallest index of the second occurrence). Otherwise, we return an empty string.