First Letter to Appear Twice — LeetCode 2351 Python Solution
- Problem
- #2351
- Pattern
- Bit Manipulation
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- s = "abccbaacz"
- Output
- "c"
- Explanation
- The letter 'a' appears on the indexes 0, 5 and 6.
Python solution
class Solution:
def repeatedCharacter(self, s: str) -> str:
cnt = Counter()
for c in s:
cnt[c] += 1
if cnt[c] == 2:
return cComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(C) auxiliary |
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 2351. First Letter to Appear Twice is filed here because LeetCode tags it Bit Manipulation, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2351. First Letter to Appear Twice?
- LeetCode 2351. First Letter to Appear Twice is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2351. First Letter to Appear Twice?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2351. First Letter to Appear Twice?
- The Python solution on this page uses O(C) auxiliary space.
- What topics does LeetCode 2351. First Letter to Appear Twice cover?
- LeetCode 2351. First Letter to Appear Twice is tagged Bit Manipulation, Hash Table, String and Counting on LeetCode.