How to find the first repeated character in a string with Python

1 Answer

0 votes
def find_first_repeated_character(s: str) -> str | None:
    """
    Finds the first repeated character in a string.

    Examples:
        "abca"         -> "a"
        "abcbd"        -> "b"
        "abcde"        -> None
        "abcdxypcbop"  -> "c"

    Time Complexity: O(n)
    Space Complexity: O(n)

    Args:
        s: Input string.

    Returns:
        The first repeated character, or None if no character repeats.
    """
    seen = set()

    for ch in s:
        # If we've seen the character before,
        # it is the first repeated character.
        if ch in seen:
            return ch

        seen.add(ch)

    # No repeated character found.
    return None


# Test cases
print(find_first_repeated_character("abca"))         
print(find_first_repeated_character("abcbd"))       
print(find_first_repeated_character("abcde"))       
print(find_first_repeated_character("abcdxypcbop")) 
 
 
'''
run:
 
a
b
None
c

'''

 



answered Sep 4, 2022 by avibootz
edited 6 days ago by avibootz
...