First Unique Character in a String
Given a string s, find the first non-repeating character and return its index. If none exists, return -1. A hash map provides an O(n) solution: count frequencies in the first pass, then find the first character with count 1 in the second pass.
This is a classic hash table application that appears frequently in interviews. It tests understanding of frequency counting and the ability to combine two linear passes.
The problem can also be solved using a single array of size 26 for lowercase letters, making it O(1) space. However, the hash map approach works for any character set including Unicode, making it more general and flexible for different input constraints.
Edge cases include empty strings (return -1), strings with all unique characters (return index 0), and strings where all characters repeat (return -1). The algorithm handles all these cases without special handling because the two-pass approach naturally covers them.
This problem is one of the most commonly asked warm-up questions in technical interviews. It tests whether you understand how to use a hash map for frequency counting and then scan again to find a specific value. Mastering this problem builds a strong foundation for more complex string analysis problems.
Example Input & Output
l first at index 0.
v first at index 2.
No unique character.
Algorithm Flow

Solution Approach
Count character frequencies with a hash map. Iterate again and return the index of the first character whose count is 1.
Time O(n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public int solution(String s) {
Map<Character,Integer> counts = new HashMap<>();
for (char ch : s.toCharArray()) counts.put(ch, counts.getOrDefault(ch, 0) + 1);
for (int i = 0; i < s.length(); i++) { if (counts.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.
