First letter to appear twice

November 18, 2022

array-and-hashmap

Problem URL: First letter to appear twice

We will use a hashset to keep track of the letters we have seen. If we see a letter that is already in the hashset, we return it. Otherwise we add it to the hashset.

class Solution:
    def firstRepeatedCharacter(self, s: str) -> str:
        seen = set()
        for c in s:
            if c in seen:
                return c
            seen.add(c)

Time complexity: O(n)
Space complexity: O(n)