#2351
First Letter to Appear Twice
EasyHash TableStringBit ManipulationCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Using a set to track seen characters allows us to check for duplicates in constant time, making the solution efficient as we only traverse the string once.
⚙️
Algorithm
4 steps- 1Step 1: Initialize an empty set to keep track of seen characters.
- 2Step 2: Iterate through each character in the string.
- 3Step 3: For each character, check if it is in the set. If it is, return that character.
- 4Step 4: If not, add the character to the set.
solution.py6 lines
1def firstLetterToAppearTwice(s):
2 seen = set()
3 for char in s:
4 if char in seen:
5 return char
6 seen.add(char)ℹ
Complexity note: The time complexity is O(n) because we traverse the string once. The space complexity is O(n) due to the set storing characters we've seen.
- 1Using a set allows for O(1) average time complexity for lookups.
- 2The order of characters matters; we need to return the first duplicate.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.