Code Logo

First Unique Character

Published at16 Mar 2026
Easy 19 views
Like1

You are given a string and need to find the index of the first character that appears exactly once.

The word first matters here. A character might be unique, but if an earlier unique character exists, you must return the earlier index. If every character repeats, return -1.

For example, in s = "leetcode", the answer is 0 because 'l' appears only once and it is already at the front. In s = "loveleetcode", both 'l' and 'o' repeat, so the first unique character is 'v' at index 2.

So the task is to scan the string for the earliest position whose character has frequency 1.

Example Input & Output

Example 1
Input
s = "leetcode"
Output
0
Explanation

The character 'l' at index 0 appears only once.

Example 2
Input
s = "loveleetcode"
Output
2
Explanation

'l' and 'o' repeat, so the first unique is 'v' at index 2.

Example 3
Input
s = "aabb"
Output
-1
Explanation

Every character appears more than once.

Algorithm Flow

Recommendation Algorithm Flow for First Unique Character
Recommendation Algorithm Flow for First Unique Character

Solution Approach

The usual approach is two passes with a frequency map.

First count how many times each character appears in the string. Then scan the string from left to right a second time and return the first index whose character has count 1.

If you finish the second pass without finding one, return -1. This stays at O(n) time with O(k) space, where k is the number of distinct characters.

Best Answers

java
import java.util.*;
class Solution {
    public int first_unique_character(String s) {
        Map<Character, Integer> count = new LinkedHashMap<>();
        for (char c : s.toCharArray()) count.merge(c, 1, Integer::sum);
        for (int i = 0; i < s.length(); i++) {
            if (count.get(s.charAt(i)) == 1) return i;
        }
        return -1;
    }
}