First Unique Character in a String (LeetCode 387): Solution and Explanation

Easy
Hash Table
String
Queue
Counting

Given a lowercase string, return the index of the first character that appears exactly once. If every character repeats, return -1.

Intuition

You cannot tell whether a character is unique the moment you see it. The 'v' in "loveleetcode" looks unique at index 2, but so does the first 'l' at index 0, and that one turns out to repeat at index 4.

So the decision needs information about the whole string. The cheapest way to get it is a frequency count: one pass that records how many times each letter appears.

Once the counts are known, uniqueness is a lookup. Walk the string again from the left and stop at the first letter whose count is exactly 1. Scanning the string, rather than the 26 counters, is what guarantees you return the earliest index.

Because the input only has lowercase letters, 26 counters are enough, so the extra space stays constant.

Approach: Two-pass frequency count

  1. Create count, an array of 26 zeros.
  2. Pass 1: for each character, increment count[ch - 'a'].
  3. Pass 2: for each index i from left to right, if count[s[i] - 'a'] == 1, return i.
  4. If pass 2 finishes, no letter is unique. Return -1.

Step-by-step example

s = "leetcode"
  1. Pass 1 counts the letters: l=1, e=3, t=1, c=1, o=1, d=1.
  2. Pass 2 starts at index 0. The letter is 'l' and its count is 1.
  3. Nothing before index 0 needed to be rejected, so 'l' is the first unique character.
  4. The function returns 0.

Code: Python, Java, C++

1class Solution:
2    def firstUniqChar(self, s: str) -> int:
3        count = [0] * 26
4        for ch in s:
5            count[ord(ch) - ord('a')] += 1
6        for i, ch in enumerate(s):
7            if count[ord(ch) - ord('a')] == 1:
8                return i
9        return -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

The string is read once to count and at most once more to scan. Each step is a constant-time array access.

Space

O(1)

The counter array has 26 slots regardless of the string's length.

Other approaches

Hash map counter (time O(n), space O(k) for k distinct characters)

Use a dictionary or Counter for the counts. It reads the same and also handles characters outside a-z.

First and last index per letter (time O(n), space O(1))

For each of the 26 letters, record its first index and whether it was seen again. The answer is the smallest first index among letters seen once. The final scan is over 26 letters instead of n characters.

Brute force (time O(n^2), space O(1))

For each index, scan the whole string to see whether its character appears anywhere else. Easy to write but quadratic.

Common mistakes

  • Deciding uniqueness during the first pass. A character seen once so far may still repeat later in the string.
  • Scanning the counter array in alphabetical order instead of the string. That returns the alphabetically smallest unique letter, not the leftmost one.
  • Returning the character instead of its index.
  • Forgetting the -1 case when every letter repeats.

Frequently asked questions

Why do I need two passes?

Uniqueness depends on the whole string. Until you have read every character you cannot know whether a letter shows up again later, so the counting pass has to finish before the answer can be chosen.

Can this be done in one pass?

You can do one pass over the string plus a pass over the 26 letters by storing each letter's first index and a repeated flag. That is still O(n) overall; it only shortens the second pass.

Is a queue solution better?

A queue of candidates that pops repeated letters from the front is useful for a stream, where characters keep arriving. For a fixed string the two-pass count is simpler and just as fast.

What is the time complexity of First Unique Character in a String?

O(n) time and O(1) extra space, since only 26 counters are kept.