Home
DSA Patterns
Hash Map
First Unique Character in a String
First Unique Character in a String
Find the index of the first non-repeating character with two passes: count every letter in a hash map, then return the first index with count 1.
Problem Understanding
First Unique Character in a String: given a string s of lowercase letters, return the index of the first character that does not repeat anywhere in s, or -1 if there is none.
Example: "loveleetcode" returns 2: l and o repeat, and v at index 2 appears once.
The Intuition: Count First, Decide Second
Checking each letter against the rest of the string is O(n²). Instead, use a hash map of counts:
- Pass 1: count every letter.
- Pass 2: walk
sagain in order and return the first index whose count is 1.
The second pass matters: the counts say which letters are unique, but only the original order says which comes first. The same count-then-use shape solves Valid Anagram and Ransom Note.
Interactive Walkthrough
Pass 1 fills each letter as it is counted, and the counts appear beside the figure. Pass 2 walks the string again, greying out repeated letters until it finds one with count 1. Try Late repeat, where letters that look unique early on turn out to repeat.
Dry Run Table
Input: s = "loveleetcode"
Counts after pass 1: l:2, o:2, v:1, e:4, t:1, c:1, d:1.
| Index | Letter | Count | Action |
|---|---|---|---|
| 0 | l | 2 | skip |
| 1 | o | 2 | skip |
| 2 | v | 1 | return 2 |
Answer: 2.
The Solution Template
Count, then scan. Python uses Counter; the others a 26-slot array.
First Unique Character in a String Code
1var firstUniqChar = function(s) {2 const counts = new Array(26).fill(0);3 for (const c of s) counts[c.charCodeAt(0) - 97]++;4 for (let i = 0; i < s.length; i++) {5 if (counts[s.charCodeAt(i) - 97] === 1) return i;6 }7 return -1;8};
Edge Cases & Common Mistakes
- Deciding during the first pass: a letter that looks unique so far may repeat later (
"abcab"); wait for the full count. - Scanning the count table instead of the string: finds a unique letter, but not necessarily the first one in
s. - No unique letter: return
-1, as in"aabb". - Single character: it is unique; return
0. - Returning the letter: the problem asks for its index.
Summary
Count every letter in one pass, then walk the string again and return the first index whose count is 1, or -1. O(n) time and O(1) space for a fixed alphabet.
More practice: DSA interview questions with answers · patterns cheat sheet
