First Unique Character in a String
Problem Statement
You’re a string sleuth tasked with finding the first character that appears only once. Return its index, or -1 if none exists. This easy-level hashing quest is a uniqueness hunt—track those counts with a map!
Example
Input: s = "leetcode"
Output: 0 (l is first unique)
Input: s = "loveleetcode"
Output: 2 (v is first unique)
Input: s = "aabb"
Output: -1 (No unique chars)
Code
Java
Python
JavaScript
public class Solution { public int firstUniqChar(String s) { Mapcount = new HashMap<>(); for (char c : s.toCharArray()) { count.put(c, count.getOrDefault(c, 0) + 1); } for (int i = 0; i < s.length(); i++) { if (count.get(s.charAt(i)) == 1) return i; } return -1; } }
from collections import Counter def first_unique_char(s): count = Counter(s) for i, c in enumerate(s): if count[c] == 1: return i return -1
function firstUniqChar(s) { let count = new Map(); for (let c of s) { count.set(c, (count.get(c) || 0) + 1); } for (let i = 0; i < s.length; i++) { if (count.get(s[i]) === 1) return i; } return -1; }
Explanation
- Hashing Insight: Count char frequencies, then find first with count 1.
- Flow: Build freq map, scan string again for first unique.
- Example Walkthrough: "leetcode" → count={l:1,e:3,t:1,c:1,o:1,d:1}, l at 0 wins.
- Optimization: Array[26] for lowercase letters could reduce space to O(1).
- Edge Case: Empty string or all repeats return -1.
Note
Time complexity: O(n), Space complexity: O(k) where k is charset size. A hashing hunt for the lone star!