Longest common prefix
Take the first word as a candidate prefix and shrink it against each following word. The prefix only ever gets shorter, so one pass settles it — O(n·m) in the worst case, and it exits early the moment the prefix is empty.
Overview
The shrinking candidate
The answer is a prefix of every string, so it is certainly a prefix of the first one. Start there and remove characters as each new word disagrees. Because it only shrinks, no backtracking is possible and one pass is enough.
Two bounds to state: the answer is at most the length of the shortest string, and the total work is O(sum of all characters) in the worst case — usually far less, because the candidate collapses quickly on real input.
Step through it
What to watch
- The prefix shrinks and never grows.
- Comparison stops at the length of the shorter of the two.
- An empty prefix ends it immediately — nothing later can help.
Say this out loud
"Start with the first string as the candidate and trim it against each of the others. It can only shrink, so one pass is enough - O(total characters), and it stops early on an empty prefix."