Ir al contenido
Ayotl

← Todos los retos

Interview challenge · easy · string, hash-map, counting

First Non-Repeating Character

El reto

El enunciado va en inglés, igual que en el vídeo.

Given a string, return the first character that occurs exactly once in it, or -1 if every character repeats.

Example

"swiss"     ->  w    (s appears three times, w once)
"leetcode"  ->  l
"aabb"      ->  -1

Idea: two passes. The first one counts how many times each character appears; the second walks the string again, in order, and returns the first character whose count is 1. Both passes are O(n), and the counts take O(1) space for a fixed alphabet: a dictionary in Python, an array of 256 counters in C.

La solución

# First Non-Repeating Character - ayotl.dev
def first_unique(s):
    count = {}
    for c in s:  # 1st pass: count
        count[c] = count.get(c, 0) + 1
    for c in s:  # 2nd pass: first with 1
        if count[c] == 1:
            return c
    return -1


for s in ["swiss", "leetcode", "aabb"]:
    print(s, first_unique(s))

$ python3 first_non_repeating_character.py

swiss w

leetcode l

aabb -1

El vídeo

Ver en YouTube →