Back to challenges
Easy 0 solved 0% acceptance

First Unique Character

Find the first character that appears only once.

What you'll learn

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

Problem

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.

Constraints

0 ≤ length ≤ 100,000

Examples

Example 1
Input:
text = "swiss"

Expected output:
expected = 1
Input:
std::string text = "swiss";

Expected output:
long long expected = 1;
Input:
string text = "swiss";

Expected output:
long expected = 1;

Explanation

s repeats, w appears once at index 1.

Example 2
Input:
text = "aabb"

Expected output:
expected = -1
Input:
std::string text = "aabb";

Expected output:
long long expected = -1;
Input:
string text = "aabb";

Expected output:
long expected = -1;

Explanation

Every character repeats: -1.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

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

Hint 2

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

Hint 3

Remember that uppercase and lowercase letters are different characters.

Expected complexity

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

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.