array and hashmap November 18, 2022

First letter to appear twice

Time O(n) Space O(n) Open original problem

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)