Voltar para os desafios
Fácil 0 resolvidos 0% de aceitação

First Unique Character

Find the first character that appears only once.

O que você vai aprender

  • Count characters with a dictionary
  • Make a second pass to find the first unique one
  • Solve it in linear time

Problema

Ver tradução

Return the index of the first character in text that appears exactly once. Case matters.

Implement first_unique_index(text).

Input

text: The text to inspect.

Output

Return the index, or -1 if every character repeats.

Restrições

0 ≤ length ≤ 100,000

Exemplos

Exemplo 1
Entrada:
text = "swiss"

Saída esperada:
expected = 1
Entrada:
std::string text = "swiss";

Saída esperada:
long long expected = 1;
Entrada:
string text = "swiss";

Saída esperada:
long expected = 1;

Explicação

s repeats, w appears once at index 1.

Exemplo 2
Entrada:
text = "aabb"

Saída esperada:
expected = -1
Entrada:
std::string text = "aabb";

Saída esperada:
long long expected = -1;
Entrada:
string text = "aabb";

Saída esperada:
long expected = -1;

Explicação

Every character repeats: -1.

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

You need characters that appear exactly once, not just the first different one.

Dica 2

Count all character frequencies first, then find the earliest position with frequency one.

Dica 3

Remember that uppercase and lowercase letters are different characters.

Complexidade esperada

O(n) time, O(k) extra space

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.