Code Logo

First Unique Character in a String

Published at23 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
"leetcode"
Output
0
Explanation

l first at index 0.

Example 2
Input
"loveleetcode"
Output
2
Explanation

v first at index 2.

Example 3
Input
"aabb"
Output
-1
Explanation

No unique character.

Algorithm Flow

Recommendation Algorithm Flow for First Unique Character in a String
Recommendation Algorithm Flow for First Unique Character in a String

Solution Approach

Count character frequencies with a hash map. Iterate again and return the index of the first character whose count is 1.

function solution(s) {
  var counts = {};
  for (var i = 0; i < s.length; i++) counts[s[i]] = (counts[s[i]] || 0) + 1;
  for (var i = 0; i < s.length; i++) { if (counts[s[i]] === 1) return i; }
  return -1;
}

Time O(n), Space O(1).

Best Answers

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