First Unique Character
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
The character 'l' at index 0 appears only once.
'l' and 'o' repeat, so the first unique is 'v' at index 2.
Every character appears more than once.
Algorithm Flow

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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
