387. First Unique Character in a String
easyFind the index of the first non-repeating character in a string, or return -1. Two passes through a 26-entry counter — easy problem, but a great test of whether the candidate naturally reaches for the right counter structure.
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^5s consists of only lowercase English letters.
Examples
Example 1
s = 'leetcode'0Example 2
s = 'loveleetcode'2Example 3
s = 'aabb'-1Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
First pass: count each character's frequency.
Hint 2
Second pass: walk the string in order; the first char with count 1 is the answer.
Hint 3
For lowercase-only input, a length-26 array beats a hash map on constant-factor performance — both are O(n).
Solution approach
Reveal approach
Two linear passes. Pass 1: count character frequencies into a 26-entry int array (s[i] - 'a' as the index). Pass 2: walk s in order; the first index where count[s[i] - 'a'] == 1 is the answer. Return -1 if no such index. Both passes are O(n); the count array is O(1) for the lowercase-only constraint (length 26). For Unicode input substitute a hash map and the bound becomes O(distinct-chars). The two-pass structure is the clean shape — single-pass attempts get tangled in 'is this still unique?' bookkeeping.
Complexity
- Time
- O(n)
- Space
- O(1)
Related patterns
- hash-table
- counting
- string
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Microsoft
- Bloomberg
- Goldman Sachs
Practice these live with InterviewChamp.AI
Drill First Unique Character in a String and Hash Tables problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →