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:
|
|
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.