First Lone Character

EasyArrays & Hashing

Problem

A support system tags every ticket with a single lowercase letter for its queue. The dashboard wants to highlight the first ticket whose queue letter appears only once in the whole list.

Given the string s, return the index of the first character that occurs exactly once in s. If no such character exists, return -1.

Example 1

Input:
s = "swiss"
Output:
1

's' appears three times, 'w' once and 'i' once; 'w' at index 1 comes first.

Example 2

Input:
s = "aabb"
Output:
-1

Every letter appears twice.

Example 3

Input:
s = "z"
Output:
0

Constraints

  • 1 ≤ s.length ≤ 10^5
  • s contains only lowercase English letters.

Hint

Show the first hint

When you are at index i, can you tell whether s[i] appears again later or appeared earlier?

Walkthrough

How to approach it

01Clarify before coding

  • What should I return if no character is unique? -1.
  • Do I return the character or its index? The index of its first (and only) occurrence.
  • Is the alphabet limited? Lowercase a–z, so the count table has a fixed size.

02Brute force

For each index i, scan the whole string to count how many times s[i] occurs; return the first i whose count is 1.

Cost: O(n²) time, O(1) space: 10^10 steps for n = 10^5.

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.