Problem Description
Given a string s consisting of lowercase English letters, find and return the first letter that appears twice. A letter a appears twice before another letter b if the second occurrence of a is before the second occurrence of b. The string is guaranteed to have at least one repeated letter.
Key Insights
- Use a hash set to track letters that have been seen.
- Traverse the string and check if the current letter has already been seen.
- The moment a letter is seen for the second time, return it as the answer.
- Since the string length is at most 100, a simple linear scan is efficient.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), as there is at most 26 lowercase letters stored in the set.
Solution
The solution involves iterating over each character in the input string and checking if it has already been encountered. To do this, we use a hash set:
- Initialize an empty set.
- Walk through each character in the string.
- For each character, check if it exists in the set:
- If it does, that's the first letter to appear twice, so return it.
- Otherwise, add the character to the set. This approach ensures that we only traverse the string once, yielding a linear time solution with constant space usage due to the limited alphabet size.