Find the first non-repeating character in JavaScript
Intermediate · 4 min read
In the word 'swiss', the letter s shows up three times and i once, yet the first letter that appears exactly once is w. Finding that letter is a classic interview question, and the same idea turns up in real work: spotting the first unrepeated item in a log, or the first product code that has no duplicate.
In this tutorial you will write firstUnique(text). It returns the first character that appears exactly once, or null when every character repeats. You need to know what a string, a loop and a function are. The one new tool, Map, is explained below.
The plan: count first, then look
You can't tell whether a character is unique the moment you see it. The s at the start of 'swiss' looks unique until you reach the next s. So the job splits into two passes over the text:
- Count how many times each character appears.
- Walk the text again, in order, and return the first character whose count is 1.
Counting with a Map
A Map stores pairs: a key and a value. Here the key is a character and the value is how many times you have seen it. Three methods do the work. set(key, value) stores a pair, get(key) reads it back, and get gives undefined for a key you never stored.
const counts = new Map();
counts.set('a', 1);
console.log(counts.get('a')); // 1
console.log(counts.get('z')); // undefined
To add one to a count, you need "the current count, or 0 if there isn't one yet". The ?? operator says exactly that: it uses the right side when the left side is null or undefined.
const counts = new Map();
counts.set('a', (counts.get('a') ?? 0) + 1);
counts.set('a', (counts.get('a') ?? 0) + 1);
console.log(counts.get('a')); // 2
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
42 Find the first non-repeating character
fairGiven a piece of text, find the first character that appears exactly once. Return something sensible when there is no such character.
Stuck? Three hints, smallest first
- 1. Count every character first, then walk the text again and return the first with a count of one.
- 2. Two passes is correct here. One pass cannot know a character is unique until the end.
- 3. A
Mapkeeps insertion order, so you can even skip the second pass over the text.
Step 1: count every character
A for...of loop walks a string one character at a time. For each character, add one to its count:
const text = 'swiss';
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
console.log(counts); // a Map holding 's' => 3, 'w' => 1, 'i' => 1
The map now knows that s appears three times and w and i once each.
Step 2: walk the text again
Now go back through the text in its original order and stop at the first character with a count of 1:
function firstUnique(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of text) if (counts.get(ch) === 1) return ch;
return null;
}
console.log(firstUnique('swiss')); // w
return inside the loop ends the function straight away, so you get the first match, not the last. Both w and i appear once, but w comes first in the text, so w wins.
Step 3: decide what "none" looks like
What if every character repeats? The second loop finishes without returning, and the function reaches return null. That is the "sensible answer" the exercise asks for: null clearly means "there isn't one".
function firstUnique(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const ch of text) if (counts.get(ch) === 1) return ch;
return null;
}
console.log(firstUnique('aabbcc')); // null
console.log(firstUnique('')); // null
console.log(firstUnique('aabbc')); // c
console.log(firstUnique('aAbB')); // a
Empty text has no characters, so it also gives null. The last line shows that case matters: 'a' and 'A' are different characters, so each appears only once.
Step 4: skip the second walk over the text
A Map remembers the order in which keys were first added. So the map from Step 1 already holds the characters in first-seen order: s, then w, then i. That means the second pass can loop over the map instead of the text. Looping over a map gives you [key, value] pairs:
function firstUniqueViaMap(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const [ch, n] of counts) if (n === 1) return ch;
return null;
}
console.log(firstUniqueViaMap('swiss')); // w
Both versions give the same answers. The map version is shorter to loop over when the text is long and has few different characters.
The full solution
The answer panel has both functions and prints the result for five sample texts. The checks underneath cover a repeat-only text, a single character, the last character being the answer, empty text, and case. Press Run to see the output.
function firstUnique(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
// Walk the original order, not the map, so ties resolve by position.
for (const ch of text) if (counts.get(ch) === 1) return ch;
return null;
}
// Because a Map preserves insertion order, this also works.
function firstUniqueViaMap(text) {
const counts = new Map();
for (const ch of text) counts.set(ch, (counts.get(ch) ?? 0) + 1);
for (const [ch, n] of counts) if (n === 1) return ch;
return null;
}
for (const s of ['swiss', 'aabbcc', 'x', 'aabbc', '']) {
console.log(JSON.stringify(s).padEnd(10), '->', JSON.stringify(firstUnique(s)));
}
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('w in swiss', firstUnique('swiss'), 'w');
test('none when all repeat', firstUnique('aabbcc'), null);
test('a single character is unique', firstUnique('x'), 'x');
test('the last one can be the answer', firstUnique('aabbc'), 'c');
test('empty text has none', firstUnique(''), null);
test('case matters', firstUnique('aAbB'), 'a');
test('both methods agree', ['swiss', 'aabbcc', 'x', 'aabbc', ''].every((s) => firstUnique(s) === firstUniqueViaMap(s)), true);
Two passes is not a weakness here: you cannot know whether the first character is unique until you have seen the whole string, so any correct answer reads the input twice. The Map variant is neat because insertion order means the map itself already holds the characters in first-seen order, so the second pass can be over the map rather than the text.
Common mistakes
- Trying to do it in one pass. You can't know a character is unique until you have seen the whole string, so any correct answer reads the input twice, once to count and once to choose.
- Looping over a plain object instead of a Map. Plain objects put keys that look like whole numbers first, so for text such as
'b1'the order you loop in is not the order the characters appeared. AMapkeeps insertion order for every key. - Writing
counts.get(ch) + 1without?? 0. The first time you see a character,getreturnsundefined, andundefined + 1isNaN.
Try it yourself
- Write
firstRepeated(text)that returns the first character that appears more than once. For'swiss'it should bes. - Make a version that ignores case, so
'aAbBc'givesc. (Hint: lowercase the text before counting.) - Return the position of the first unique character instead of the character, and
-1when there is none.