#387

First Unique Character in a String

Easy Frequency count

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the index of the first character that appears exactly once in the string, or -1.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the first letter that appears exactly once.

Why this works: count all letters first, then scan in order for a count of 1.

Example: "loveleetcode"

counts: l2 o2 v1 e4 …first with count 1: 'v' at index 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Scanning the count array in alphabetical order — you need the first by position in the string.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(26).
Topic: Strings
🎬 Episodes 16–20: video coming soon