AlgoTales · Roadmap

Longest common prefix

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

The longest common prefix of many words is the part they all start with. In a trie it is simply the stretch of road you can walk before the path splits or a word ends, so it is found without comparing words pair by pair.

Practical use cases

  • Web app: Shell-style tab completion in a web terminal. An online code playground has a file tree and a command box. When the user presses Tab after typing "src/comp", the app fills in the shared start of all matching paths, like "src/components/". It walks the single road in the path trie until it first branches. The user saves keystrokes, and the page never has to compare each path with every other path.
  • Web app: Grouping URLs in an analytics report. A dashboard has thousands of page URLs and the manager wants to see them grouped by a common start, such as "/shop/men/shirts/". Finding where the URLs first split shows the natural group names without sorting and comparing every pair. The manager gets sensible group names automatically instead of an unreadable list of ten thousand links.
  • System: DNA analysis and file systems. Biologists look for the shared starting stretch among many gene reads, and operating systems find the shared folder of many file paths. Both are the same walk down until the first fork.

The story: The Wedding Cards That Start the Same

Kabir's uncle was printing wedding invitations in three languages for different relatives. To save ink he wanted the part of the heading that was the same on every card, so it could be printed once in gold and only the rest varied.

Kabir compared card 1 with card 2, then the result with card 3, letter by letter. It worked, but with hundreds of cards it took the whole afternoon, and every card was read many times.

Mira said, "Put all the headings on one lane board. Then walk down from the start. As long as the lane has one road only, everybody agrees. The moment the road splits (or a heading simply ends), you have found the end of what is common."

This is the longest common prefix with a trie: insert every string, then follow the single-child chain from the root, stopping at the first box with more than one child or a word-end flag. Each letter is touched once.

How to spot this problem, and where you need it

You have many strings such as paths, URLs or codes and need the part they all begin with, but comparing each string to every other one is clumsy and slow.

Signs you need it

  • A feature should "fill in as much as possible" when several options share the same beginning.
  • The problem says "common prefix" of an array of strings.
  • You are grouping URLs, file paths or product codes by how they start.
  • Your code compares string pairs in nested loops to find where they differ.

Where to use it in a project

  • Tab-completion in web terminals, file pickers and command palettes.
  • Report pages that group routes, categories or SKU codes by their shared start.

The solution

Insert all strings into a trie. Start at the root and keep stepping down as long as the current node has exactly one child and is not the end of a word. The letters you pass are the longest common prefix. The moment the road forks or a word ends, you have reached where the strings stop being alike.

Payoff: Before: comparing each pair of 10,000 paths. After: one walk of a few dozen steps down the shared road.

Explain it like I am 8

Draw all the words as one road map. Start at the front gate and keep walking while there is only one road to take. The place where the road first splits is where the words stop being alike. The letters you walked are the shared beginning.

How it works, step by step

  1. Insert every word into one trie.
  2. Start at the root with an empty answer.
  3. While the current box has exactly one child and no word ends here, append that child's letter to the answer and move to it.
  4. Stop at a box with zero or several children, or one that ends a word.
  5. Return the answer (empty if the very first box already forks, e.g. "dog" and "racecar").

The code in four languages

PHP

<?php
class TrieNode {
    public array $kids = [];
    public bool $end = false;
}

function longestCommonPrefix(array $words): string {
    $root = new TrieNode();
    foreach ($words as $w) {                         // 1) build the trie
        $n = $root;
        foreach (str_split($w) as $ch) { $n->kids[$ch] ??= new TrieNode(); $n = $n->kids[$ch]; }
        $n->end = true;
    }
    $prefix = '';
    $n = $root;
    // 2) walk while there is a single road and no word stops here
    while (count($n->kids) === 1 && !$n->end) {
        $ch = array_key_first($n->kids);
        $prefix .= $ch;
        $n = $n->kids[$ch];
    }
    return $prefix;
}

echo '[' . longestCommonPrefix(['chair', 'chain', 'chat']) . ']' . PHP_EOL;   // cha
echo '[' . longestCommonPrefix(['dog', 'racecar']) . ']' . PHP_EOL;           // empty
echo '[' . longestCommonPrefix(['do', 'dog', 'door']) . ']' . PHP_EOL;        // do
echo '[' . longestCommonPrefix(['solo']) . ']' . PHP_EOL;                     // solo

JavaScript

class TrieNode {
  constructor() { this.kids = {}; this.end = false; }
}

function longestCommonPrefix(words) {
  const root = new TrieNode();
  for (const w of words) {                       // 1) build the trie
    let n = root;
    for (const ch of w) { if (!n.kids[ch]) n.kids[ch] = new TrieNode(); n = n.kids[ch]; }
    n.end = true;
  }
  let prefix = '';
  let n = root;
  // 2) walk while there is a single road and no word stops here
  while (Object.keys(n.kids).length === 1 && !n.end) {
    const ch = Object.keys(n.kids)[0];
    prefix += ch;
    n = n.kids[ch];
  }
  return prefix;
}

console.log('[' + longestCommonPrefix(['chair', 'chain', 'chat']) + ']');   // cha
console.log('[' + longestCommonPrefix(['dog', 'racecar']) + ']');           // empty
console.log('[' + longestCommonPrefix(['do', 'dog', 'door']) + ']');        // do
console.log('[' + longestCommonPrefix(['solo']) + ']');                     // solo

Java

import java.util.*;

public class Main {
    static class TrieNode {
        Map<Character, TrieNode> kids = new HashMap<>();
        boolean end = false;
    }

    static String longestCommonPrefix(String[] words) {
        TrieNode root = new TrieNode();
        for (String w : words) {                         // 1) build the trie
            TrieNode n = root;
            for (char ch : w.toCharArray()) {
                n.kids.putIfAbsent(ch, new TrieNode());
                n = n.kids.get(ch);
            }
            n.end = true;
        }
        StringBuilder prefix = new StringBuilder();
        TrieNode n = root;
        // 2) walk while there is a single road and no word stops here
        while (n.kids.size() == 1 && !n.end) {
            char ch = n.kids.keySet().iterator().next();
            prefix.append(ch);
            n = n.kids.get(ch);
        }
        return prefix.toString();
    }

    public static void main(String[] args) {
        System.out.println("[" + longestCommonPrefix(new String[]{"chair", "chain", "chat"}) + "]");   // cha
        System.out.println("[" + longestCommonPrefix(new String[]{"dog", "racecar"}) + "]");           // empty
        System.out.println("[" + longestCommonPrefix(new String[]{"do", "dog", "door"}) + "]");        // do
        System.out.println("[" + longestCommonPrefix(new String[]{"solo"}) + "]");                     // solo
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type TrieNode struct {
	kids map[rune]*TrieNode
	end  bool
}

func newTrieNode() *TrieNode { return &TrieNode{kids: map[rune]*TrieNode{}} }

func longestCommonPrefix(words []string) string {
	root := newTrieNode()
	for _, w := range words { // 1) build the trie
		n := root
		for _, ch := range w {
			if n.kids[ch] == nil {
				n.kids[ch] = newTrieNode()
			}
			n = n.kids[ch]
		}
		n.end = true
	}
	var prefix strings.Builder
	n := root
	// 2) walk while there is a single road and no word stops here
	for len(n.kids) == 1 && !n.end {
		for ch, kid := range n.kids { // the only entry
			prefix.WriteRune(ch)
			n = kid
		}
	}
	return prefix.String()
}

func main() {
	fmt.Println("[" + longestCommonPrefix([]string{"chair", "chain", "chat"}) + "]") // cha
	fmt.Println("[" + longestCommonPrefix([]string{"dog", "racecar"}) + "]")         // empty
	fmt.Println("[" + longestCommonPrefix([]string{"do", "dog", "door"}) + "]")      // do
	fmt.Println("[" + longestCommonPrefix([]string{"solo"}) + "]")                   // solo
}

Time: O(total letters) · Extra space: O(total letters). Building the trie reads every letter once; the final walk is at most as long as the shortest word.

Watch out for

  • Not stopping at a word-end flag: for "do" and "dog" the answer is "do", not "dog".
  • Forgetting the empty list or a single word as special cases.
  • Stopping when the first word ends instead of using the fork/flag rule on the trie.

Quick check

  1. You walk down the trie. When do you stop?
    • At the first box with more than one child or a word end
    • At the last letter of the longest word
    • Never, you walk to a leaf
  2. Words: "dog", "racecar". What is the LCP?
    • "d"
    • An empty string
    • "r"
  3. Words: "do", "dog". The LCP is...
    • "do"
    • "dog"
    • ""