First Letter to Appear Twice — LeetCode 2351 Python Solution

EasyBit ManipulationHash TableStringCounting
Problem
#2351
Reading time
2 min

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

Python
class Solution:
    def repeatedCharacter(self, s: str) -> str:
        cnt = Counter()
        for c in s:
            cnt[c] += 1
            if cnt[c] == 2:
                return c

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview