Volver a los desafíos
Fácil 0 resueltos 0% de aceptación

First Unique Character

Find the first character that appears only once.

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

0 ≤ length ≤ 100,000

Ejemplos

Ejemplo 1
Entrada:
text = "swiss"

Salida esperada:
expected = 1
Entrada:
std::string text = "swiss";

Salida esperada:
long long expected = 1;
Entrada:
string text = "swiss";

Salida esperada:
long expected = 1;

Explicación

s repeats, w appears once at index 1.

Ejemplo 2
Entrada:
text = "aabb"

Salida esperada:
expected = -1
Entrada:
std::string text = "aabb";

Salida esperada:
long long expected = -1;
Entrada:
string text = "aabb";

Salida esperada:
long expected = -1;

Explicación

Every character repeats: -1.

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

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

Pista 2

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

Pista 3

Remember that uppercase and lowercase letters are different characters.

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.