First Unique Character
Ever been in a crowded room where every person is part of a couple, except for one? That "lonely" person is the First Unique Character! You’re given a string, and your mission is to find the very first character that does not repeat anywhere else in that string. If everyone has a twin, return a signal like null or -1.
The "secret sauce" here is a two-step process using a Frequency Map. First, you walk through the string and count how many times each character appears. Once you have your "people count," you walk through the string a second time and ask: "Is this the person with a count of exactly 1?" The first one you hit is your winner! This approach provides a linear O(n) solution, which is much faster than checking every character against every other character manually.
This is a classic problem because it teaches you how to use a Map to solve "first-time" discovery problems efficiently. It’s a gold standard pattern for data deduplication and deep text analysis!
Examples
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

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 problem.
