Dynamic programming · Exercise 71 of 100
Longest common prefix
A prefix starts at the first letter and has no gaps. For a nonempty list of words, compare the letters in the same position across all the words, moving from left to right. Stop when a word ends or the letters differ, because a shared prefix cannot extend past that point.
Try it yourself
What is the longest common prefix of planted, planter, and plank?
One-step hint
Align the three words at their first letters. Compare one column at a time and stop just before the first column with a mismatch.
Worked solution
- Read one position at a time across all three words. The first four letters agree in order, giving p, l, a, and n.
- The fifth letters are t, t, and k, so the shared prefix ends at plan.