Emmanuel Akinfulubi

JavaScriptString

Longest common prefix in JavaScript

Advanced · 4 min read

Given ['flower', 'flow', 'flight'], what start do all three share? fl. That shared start is the longest common prefix. It is a classic interview question, and it is useful too: autocomplete uses it to fill in the part every match agrees on, and file tools use it to find the folder a set of paths share.

In this tutorial you will write longestCommonPrefix by starting with a guess and shortening it until it fits every word. Then you will write a second version that sorts the list and compares only two words. You should know slice, startsWith, sort and while loops.

The idea: shrink a candidate

Every word in the list must start with the answer. So the answer can't be longer than the first word. Start by guessing that the whole first word is the prefix, then check it against each other word:

  • If the word starts with the guess, keep it.
  • If not, chop the last character off the guess and try again.

The guess only ever gets shorter, and once it is the empty string '' you can stop: nothing is shared.

What startsWith does

'flower'.startsWith('flo') is true: it checks whether a string begins with another string. It saves you comparing characters one by one. And slice(0, -1) returns a string without its last character.

JavaScript

console.log('flower'.startsWith('flo')); // true
console.log('flower'.slice(0, -1));      // 'flowe'

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

53 Longest common prefix

hard

Given a list of strings, find the longest prefix they all share. ['flower', 'flow', 'flight'] gives 'fl'.

Stuck? Three hints, smallest first
  1. 1. Start with the first word as a candidate and shorten it until every word starts with it.
  2. 2. startsWith saves you comparing character by character.
  3. 3. Sorting the list means only the first and last entries need comparing.

Step 1: shrink against one word

Step 1

let prefix = 'flower';
const word = 'flow';
while (prefix !== '' && !word.startsWith(prefix)) prefix = prefix.slice(0, -1);
console.log(prefix); // 'flow'

flow doesn't start with flower or flowe, so the loop chops twice and stops at flow. The prefix !== '' part makes sure the loop ends even when nothing matches.

Step 2: go through every word

Step 2

function longestCommonPrefix(words) {
  if (words.length === 0) return '';
  let prefix = words[0];
  for (const word of words.slice(1)) {
    while (prefix !== '' && !word.startsWith(prefix)) prefix = prefix.slice(0, -1);
    if (prefix === '') return '';
  }
  return prefix;
}
console.log(longestCommonPrefix(['flower', 'flow', 'flight'])); // 'fl'
console.log(JSON.stringify(longestCommonPrefix(['dog', 'racecar', 'car']))); // ""

words.slice(1) is every word after the first. Against flow the guess shrinks to flow; against flight it shrinks to fl. In the second list racecar doesn't start with any piece of dog, so the guess shrinks to '' and the function returns early without looking at car.

Step 3: the edge cases

Step 3

function longestCommonPrefix(words) {
  if (words.length === 0) return '';
  let prefix = words[0];
  for (const word of words.slice(1)) {
    while (prefix !== '' && !word.startsWith(prefix)) prefix = prefix.slice(0, -1);
    if (prefix === '') return '';
  }
  return prefix;
}
console.log(longestCommonPrefix(['single']));         // 'single'
console.log(JSON.stringify(longestCommonPrefix([]))); // ""
console.log(JSON.stringify(longestCommonPrefix(['abc', '']))); // ""
console.log(longestCommonPrefix(['abc', 'abc']));     // 'abc'
console.log(JSON.stringify(longestCommonPrefix(['Flow', 'flower']))); // ""

One word is its own prefix. An empty list has no first word to guess from, which is why the function checks for it first: words[0] would be undefined. An empty word forces an empty answer. And capitals matter: F and f are different characters.

Step 4: a string prefix is not a folder

Step 4

function longestCommonPrefix(words) {
  if (words.length === 0) return '';
  let prefix = words[0];
  for (const word of words.slice(1)) {
    while (prefix !== '' && !word.startsWith(prefix)) prefix = prefix.slice(0, -1);
    if (prefix === '') return '';
  }
  return prefix;
}
console.log(longestCommonPrefix(['/usr/local/bin', '/usr/local/lib', '/usr/lib'])); // '/usr/l'

The answer is correct for strings, but /usr/l is not a real folder. If you want the shared folder, split each path on / and compare the pieces instead of the characters.

Step 5: a second way, by sorting

Sort the words alphabetically. The first and last words are then the two most different ones, so whatever they share, every word in between shares too. That means you only need to compare two words:

Step 5

function byExtremes(words) {
  if (words.length === 0) return '';
  const sorted = [...words].sort();
  const first = sorted[0];
  const last = sorted.at(-1);
  let i = 0;
  while (i < first.length && first[i] === last[i]) i++;
  return first.slice(0, i);
}
console.log([...['flower', 'flow', 'flight']].sort()); // [ 'flight', 'flow', 'flower' ]
console.log(byExtremes(['flower', 'flow', 'flight']));  // 'fl'

After sorting, flight is first and flower is last. at(-1) gets the last item. The loop walks forward while the two words agree; it stops at index 2, where i meets o. slice(0, 2) is fl.

Which to use

The shrinking version can stop early as soon as one word shares nothing. The sorting version does more work up front, then a single walk. Both give the same answers. The sorting trick only works with plain sort(), though: a different order, such as one that ignores case, would break the argument.

The full solution

The panel has both versions and prints three example lists, including the paths. Press Run, then read the checks underneath, including the one that proves the two versions always agree.

The answer

function longestCommonPrefix(words) {
  if (words.length === 0) return '';
  let prefix = words[0];
  for (const word of words.slice(1)) {
    while (prefix !== '' && !word.startsWith(prefix)) prefix = prefix.slice(0, -1);
    if (prefix === '') return '';
  }
  return prefix;
}

// Sorted lexically, the two most different strings are the first and the last,
// so comparing only those two is enough.
function byExtremes(words) {
  if (words.length === 0) return '';
  const sorted = [...words].sort();
  const first = sorted[0];
  const last = sorted.at(-1);
  let i = 0;
  while (i < first.length && first[i] === last[i]) i++;
  return first.slice(0, i);
}

console.log("['flower', 'flow', 'flight'] ->", longestCommonPrefix(['flower', 'flow', 'flight']));
console.log("['dog', 'racecar', 'car']    ->", JSON.stringify(longestCommonPrefix(['dog', 'racecar', 'car'])));
console.log('paths                        ->', longestCommonPrefix(['/usr/local/bin', '/usr/local/lib', '/usr/lib']));

Output


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

10 checks

test('the classic example', longestCommonPrefix(['flower', 'flow', 'flight']), 'fl');
test('no shared start gives an empty string', longestCommonPrefix(['dog', 'racecar', 'car']), '');
test('one word is its own prefix', longestCommonPrefix(['single']), 'single');
test('an empty list has no prefix', longestCommonPrefix([]), '');
test('an empty word in the list forces an empty prefix', longestCommonPrefix(['abc', '']), '');
test('identical words give the whole word', longestCommonPrefix(['abc', 'abc']), 'abc');
test('the comparison is case sensitive', longestCommonPrefix(['Flow', 'flower']), '');
test('a shared path prefix, which is what this is usually for', longestCommonPrefix(['/usr/local/bin', '/usr/local/lib', '/usr/lib']), '/usr/l');
test('the sorted two-extremes version gives the same answer', byExtremes(['flower', 'flow', 'flight']), 'fl');
test('and agrees on every case above', [['flower', 'flow', 'flight'], ['dog', 'racecar', 'car'], ['abc', 'abc'], ['abc', ''], ['single'], []].every((list) => byExtremes(list) === longestCommonPrefix(list)), true);

Both versions are worth having in your head. The first shortens a candidate and stops early on the first word that shares nothing — good when a mismatch is likely. The second sorts, which costs more up front, and then does a single character walk.

The insight behind byExtremes is that lexical order puts the two least similar strings at the ends, so their common prefix is the common prefix of the whole set. It is a neat argument and it generalises badly — it depends on the order being lexical, so a collator would break it.

Note what '/usr/l' means: this is a string prefix, not a path prefix. If you want the common directory, split on / and compare segments, or you will produce paths that do not exist.

Common mistakes

  • Forgetting the empty list. words[0] is undefined, so the function returns undefined instead of a string. Return '' first.
  • Sorting the caller's array. words.sort() reorders the list that was passed in. Sort a copy, [...words].sort().
  • Treating the result as a folder. /usr/l is a string prefix. Compare path segments if you need a directory.

Try it yourself

  1. Write commonFolder(paths) that splits on / and returns '/usr' for the three paths in Step 4.
  2. Make the function ignore case, so ['Flow', 'flower'] gives 'flow'.
  3. Write longestCommonSuffix, so ['walking', 'talking', 'king'] gives 'king'.

Keep practising

Newsletter

New writing, when it lands.

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