Skip to content
StackDecode
StringsAnimated

Longest Common Prefix

Compare strings column by column until a mismatch.

Time

O(n · m)

Extra space

O(1)

Use it for

Autocomplete, file path handling.

How it works

  1. Take the first word as the candidate prefix.
  2. Compare it with the next word character by character.
  3. Cut the candidate down to the part both words share.
  4. Repeat for every word. What is left is the longest common prefix.

Watch it run

Loading animation…