Skip to main content

387. First Unique Character in a String

easy

Find the index of the first non-repeating character in a string, or -1 if every character repeats. A clean two-pass hash-map problem.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of only lowercase English letters.

Examples

Example 1

Input
s = "leetcode"
Output
0

Example 2

Input
s = "loveleetcode"
Output
2

Example 3

Input
s = "aabb"
Output
-1

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Hints

Progressive — try the first before opening the next.

Hint 1

Single-pass approaches usually fail — you can't tell a char is unique until you've seen the whole string.

Hint 2

Two passes is fine: first pass counts characters, second pass finds the first with count == 1.

Hint 3

For lowercase ASCII, a 26-element int array is faster than a hash map.

Solution approach

Reveal approach

Two passes. First pass: build a frequency map of every character. Second pass: walk the string again and return the index of the first character whose count is 1. If the second pass finishes, return -1. For lowercase-English input, the frequency 'map' is a 26-element int array — O(1) extra space by alphabet size.

Complexity

Time
O(n)
Space
O(1)

Related patterns

  • hash-map

Related problems

Asked at

Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).

  • Amazon
  • Microsoft
  • Bloomberg

Practice these live with InterviewChamp.AI

Drill First Unique Character in a String and Strings problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →