Command Palette

Search for a command to run...

Problem 4.3 · HashingEasy

First Unique Character

What it teaches: Two passes: count everything first, then use the counts while scanning in the original order.

Practise it on judges as “First Unique Character in a String”.

The problem

Given a string s, return the index of the first character that appears exactly once. If there isn't one, return -1.

Example 1

Input: s = "leetcode"
Output: 0

Example 2

Input: s = "loveleetcode"
Output: 2

Example 3

Input: s = "aabb"
Output: -1

Constraints

  • 1 ≤ s.length ≤ 10⁵
  • Lowercase English letters

Pattern clues in the wording

  • → "Appears exactly once": needs totals before deciding
  • → "First": answer depends on original order

These clues point to Frequency Counting: Count how many times each value appears (with an int[26] or a HashMap), then answer from the counts.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        return -1;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
s = "leetcode"
0
2
s = "loveleetcode"
2
3
s = "aabb"
-1

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Optimal: count, then scan

Time O(n) Space O(1) (26 counters)

First pass: count each letter. Second pass in order: the first character with count 1 wins.

Approach 1
class Solution {
    public int firstUniqChar(String s) {
        int[] count = new int[26];
        for (int i = 0; i < s.length(); i++) count[s.charAt(i) - 'a']++;
        for (int i = 0; i < s.length(); i++) if (count[s.charAt(i) - 'a'] == 1) return i;
        return -1;
    }
}

Verdict: Two linear passes.

Before you submit

Edge cases and common mistakes

Test these inputs

  • One character → 0
  • No unique character → −1
  • The unique character is last

Mistakes people make

  • Returning the first character with count 1 in alphabet order instead of string order.

Interview

Follow-up questions

What if characters arrive as a stream and you must answer after each one?