First Unique Character
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.
Algorithm Flow

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