BudiBadu Logo

First Unique Character

Hash Table Easy 9 views
Like1

Given a string s, find the index of the first character that appears exactly once in the entire string. If no such character exists, return -1.

The approach is straightforward: use a hash map to count the frequency of each character in one pass, then walk the string a second time and return the index of the first character whose count equals one. This runs in linear time with constant space regardless of string length.

Return -1 for an empty string or when every character repeats at least twice.

Example 1:

Input: s = "leetcode"
Output: 0
Explanation: 'l' appears only once and is at index 0.

Example 2:

Input: s = "loveleetcode"
Output: 2
Explanation: 'l' and 'o' both repeat. The first non-repeating character 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;
    }
}