Emmanuel Akinfulubi

JavaScriptFunction

Function to find the first unique character in JavaScript

Intermediate · 4 min read

In the string 'abacddbec', which character shows up only once, and comes first? Most letters repeat. The first one that doesn't is 'e'. Finding the first unique item is a classic coding interview question, and it has everyday uses too: the first customer who ordered only once, the first word in a text that never comes back.

In this tutorial you will write firstNonRepeated(text). You will also see a shorter version that looks right and isn't, and learn why the correct one has to read the string twice. You need to know loops, strings and functions. The Map it uses is explained below.

Counting with a Map

A Map stores pairs: a key and its value. Here the key is a character and the value is how many times it has appeared.

JavaScript

const counts = new Map();
counts.set('a', 1);
console.log(counts.get('a')); // 1
console.log(counts.get('z')); // undefined: never set

To add one to a count that may not exist yet, write (counts.get(c) ?? 0) + 1. The ?? operator means "use the right side if the left side is null or undefined". So a new character starts from 0.

JavaScript

console.log(undefined ?? 0); // 0
console.log(3 ?? 0);         // 3

Here is the exercise. Try it on your own first if you like, or read on and we will build it together.

23 The first non-repeated character

fair

'abacddbec' should give 'e'. Find the first character that appears exactly once.

Stuck? Three hints, smallest first
  1. 1. Two passes: count everything, then walk the string again looking for a count of 1.
  2. 2. One pass cannot work, because a character early on may repeat later.
  3. 3. Return something definite when every character repeats.

Step 1: count every character

The first pass walks the whole string and fills in the counts:

Step 1

function countAll(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  return counts;
}
const totals = countAll('abacddbec');
console.log(totals.get('a')); // 2
console.log(totals.get('e')); // 1
console.log(totals.get('c')); // 2

After this loop you know every character's total. That matters for the next step.

Step 2: walk again and stop at the first count of 1

The second pass reads the string from the start again. The first character whose count is exactly 1 is the answer. If the loop finishes without finding one, every character repeats, so return null to say "there isn't one".

Step 2

function firstNonRepeated(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  for (const c of text) if (counts.get(c) === 1) return c;
  return null;
}
console.log(firstNonRepeated('abacddbec')); // 'e'
console.log(firstNonRepeated('swiss'));     // 'w'
console.log(firstNonRepeated('aabbcc'));    // null
console.log(firstNonRepeated(''));          // null

return c inside the loop stops the function the moment it finds the answer. Returning null is a clear choice: the caller can check for it, which is better than getting undefined by accident.

Step 3: why one pass is not enough

Two loops can feel wasteful. Here is a one-pass version that tries to be clever by remembering which characters it has already seen:

Step 3

function brokenOnePass(text) {
  const seen = new Set();
  for (const c of text) {
    if (!seen.has(c)) return c;
    seen.add(c);
  }
  return null;
}
console.log(brokenOnePass('aab'));    // 'a'
console.log(firstNonRepeated('aab')); // 'b'

A Set is a list of values with no repeats, and has asks whether a value is in it. The broken version answers a different question: "the first character not seen so far". The very first character is always new, so it returns 'a'. But 'a' repeats later, and the loop can't know that yet. The real answer is 'b'. Only after counting the whole string can you tell which characters are truly unique.

Step 4: use the Map's own order

A Map remembers the order its keys were first added. So instead of walking the string again, you can walk the counts:

Step 4

const byMapOrder = (text) => {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  for (const [c, n] of counts) if (n === 1) return c;
  return null;
};
console.log(byMapOrder('abacddbec')); // 'e'
console.log([...new Map([['b', 1], ['a', 1]]).keys()]); // ['b', 'a']

Each key was added when its character first appeared, so the order is the same as in the string. for (const [c, n] of counts) gives each key and its count together.

A plain object could hold the counts too, but it moves number-like keys to the front:

JavaScript

console.log(Object.keys({ b: 1, 2: 1, 1: 1 })); // ['1', '2', 'b']

With a string of digits, that reordering would give the wrong "first" character. A Map keeps the order you added things.

The full solution

The panel has firstNonRepeated, the broken one-pass version and byMapOrder. It prints the answer for seven test strings, then shows the one-pass version getting 'aab' wrong. Press Run to see the output.

The answer

/* Two passes is not laziness, it is necessary: while walking the string the first
   time you cannot know whether an early character repeats later on. */
function firstNonRepeated(text) {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  for (const c of text) if (counts.get(c) === 1) return c;
  return null;
}

// A tempting one-pass version, to show that it is wrong.
function brokenOnePass(text) {
  const seen = new Set();
  for (const c of text) {
    if (!seen.has(c)) return c;         // "first not yet seen" is a different question
    seen.add(c);
  }
  return null;
}

// Using the Map's own order instead of walking the string again.
const byMapOrder = (text) => {
  const counts = new Map();
  for (const c of text) counts.set(c, (counts.get(c) ?? 0) + 1);
  for (const [c, n] of counts) if (n === 1) return c;
  return null;
};

const cases = ['abacddbec', 'aabbcc', 'abc', 'a', '', 'aabbc', 'swiss'];

for (const t of cases) {
  console.log(JSON.stringify(t).padEnd(13), '->', JSON.stringify(firstNonRepeated(t)));
}
console.log('--- why one pass fails ---');
console.log("brokenOnePass('aab') =", JSON.stringify(brokenOnePass('aab')), "<- 'a' repeats, so the answer should be 'b'");
console.log("firstNonRepeated('aab') =", JSON.stringify(firstNonRepeated('aab')));

Output


      
16 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 16 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

16 checks

test("the example in the question", firstNonRepeated('abacddbec'), 'e');
test('all repeated gives null', firstNonRepeated('aabbcc'), null);
test('no repeats gives the first character', firstNonRepeated('abc'), 'a');
test('a single character', firstNonRepeated('a'), 'a');
test('an empty string gives null', firstNonRepeated(''), null);
test('the last character can be the answer', firstNonRepeated('aabbc'), 'c');
test("'swiss' gives w", firstNonRepeated('swiss'), 'w');
test('the one-pass version gets it wrong', brokenOnePass('aab'), 'a');
test('where the right answer is b', firstNonRepeated('aab'), 'b');
test('so they disagree', brokenOnePass('aab') === firstNonRepeated('aab'), false);
test('the Map-order version agrees on every case', cases.every((t) => byMapOrder(t) === firstNonRepeated(t)), true);
test('because a Map keeps insertion order', [...new Map([['b', 1], ['a', 1]]).keys()], ['b', 'a']);
test('the result really appears once', (() => { const c = firstNonRepeated('abacddbec'); return [...'abacddbec'].filter((x) => x === c).length; })(), 1);
test('and nothing before it does', 'abacddbec'.slice(0, 'abacddbec'.indexOf('e')).split('').every((c) => 'abacddbec'.split(c).length - 1 > 1), true);
test('it is case-sensitive', firstNonRepeated('aA'), 'a');
test('spaces count as characters', firstNonRepeated('aa b'), ' ');

Two passes are required, and the broken one-pass version is there to show why: "the first character not seen so far" is a different question from "the first character that appears exactly once". For 'aab' the first returns 'a' and the second returns 'b', and the assertion that they disagree is the point.

A Map rather than an object gives insertion order over any key type, which is why byMapOrder can skip the second walk of the string and iterate the counts instead — it agrees on every case. A plain object would mostly work too, but its integer-like keys get reordered, so a string of digits would break it.

Common mistakes

  • Trying to do it in one pass. "Not seen yet" is not the same as "appears once". You need the full counts first.
  • Returning undefined by accident. If no character is unique, say so on purpose with return null.
  • Counting in a plain object with digit keys. Number-like keys are put in number order, so walking the object can give the wrong first character.

Try it yourself

  1. Change the function to return the position of the first unique character instead, or -1 when there is none. For 'abacddbec' that is 7.
  2. Make a version that ignores case, so 'aA' has no unique character.
  3. Write allUnique(text) that returns every character with a count of 1, in order. For 'abacddbec' that is just ['e'].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.