Skip to content
LEETFLIX

Longest Common Prefix

Solve on LeetCode

Easy · shrink the prefix. Real solution for this problem — same player as the hand-authored deep-dives.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 14. Longest Common Prefix. The copyrighted prompt is on LeetCode. This page is a working shrink the prefix for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

strs =
flower flow flight

Output

fl

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Start with the first word, shrink

Assume the first string is the prefix. For every later word, cut the prefix down until it is a prefix of that word.

The answer can only get shorter. The moment it becomes empty, stop.

Algorithm

  1. Seed pref with strs[0].
  2. While the current word does not start with pref, drop the last character of pref.
  3. Return pref.
Time
O(n k)
Space
O(k)
Solution.py
class Solution:    def longestCommonPrefix(self, strs: list[str]) -> str:        if not strs:            return ""        pref = strs[0]        for w in strs[1:]:            while not w.startswith(pref):                pref = pref[:-1]                if not pref:                    return ""        return pref
Watch this run

03

Interactive walkthrough

Playing “Start with the first word, shrink”. Edit the input, hit Run, then scrub.

Approach: Start with the first word, shrink

Loading animation…