BudiBadu Logo

First Unique Character

Hash Table Easy 12 views
Like1

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

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 - Budibadu
Recommendation Algorithm Flow for First Unique Character - Budibadu

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;
    }
}