DSA AnimatorREVISION VIDEOS
← Back to problems
New

Longest Common Prefix — LeetCode 14 video explanation

You get a list of words. Find the longest prefix that every word starts with. If there is none, return an empty string.

Loading videos…

DSA Animator › DSA Revision › Strings › Longest Common Prefix

Key moments in the Longest Common Prefix video

0:04Problem0:11Example0:16Brute force0:25Key idea0:38Dry run0:53Code1:11Takeaway

What you will learn

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.

Longest Common Prefix video transcript

Problem

You get a list of words. Find the longest prefix that every word starts with. If there is none, return an empty string.

Example

Take flower, flow and flight. All three start with f l, so the answer is f l.

Brute force

Building every possible prefix and checking it against every word is slow. And remember, the prefix can never be longer than the shortest word.

Key idea

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.

Dry run

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.

Code

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.

Takeaway

Remember: compare column by column, and stop at the first mismatch. The prefix is never longer than the shortest word.

More Strings revision videos

← All 185 DSA revision videos