#14

Longest Common Prefix

Easy Vertical scan

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the longest prefix shared by every string in the array, or "" if there is none.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest start shared by all the words.

Why this works: compare column by column; stop at the first column where any word differs or ends.

Example: ["flower", "flow", "flight"]

col 0: f f f ✓, col 1: l l l ✓col 2: o o i ✗ → "fl"

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting that a shorter string can end before a mismatch — check the length first.

Solve on LeetCode ↗
Complexity
  • Time: O(total characters).
  • Space: O(1) besides the output.
Topic: Strings
🎬 Episodes 16–20: video coming soon