You get a list of words. Find the longest prefix that every word starts with. If there is none, return an empty string.
DSA Animator › DSA Revision › Strings › Longest Common Prefix
Remember: compare column by column, and stop at the first mismatch. The prefix is never longer than the shortest word. The video solves Longest Common Prefix (LeetCode 14, Easy) with the Vertical Scan pattern from the Strings topic, and you can replay every step in the interactive Longest Common Prefix animation.
You get a list of words. Find the longest prefix that every word starts with. If there is none, return an empty string.
Take flower, flow and flight. All three start with f l, so the answer is f l.
Building every possible prefix and checking it against every word is slow. And remember, the prefix can never be longer than the shortest word.
Line the words up, one under another, and read them column by column. Take the letter from the first word, and check that every other word has the same letter in that column. Stop at the first mismatch, or as soon as a word runs out.
In column 0, all three words have f. The prefix is now f. In column 1, all three have l. The prefix is now f l. In column 2, flower and flow have o, but flight has i. The letters differ, so we stop here. The answer is f l.
In code, loop over each index of the first word. For every other word, if the word has ended or the letter differs, return the part before this index. If the whole loop finishes, the first word itself is the answer. Time is O of S, where S is the total number of characters, and space is O of 1.
Remember: compare column by column, and stop at the first mismatch. The prefix is never longer than the shortest word.