Longest Common Prefix
Vertical Scanning
Asked at 12 companies
10 recent
- CME Group
- opentext
- Bloomberg
- Apple
- Amazon
- tcs
- Microsoft
- Meta
- IBM
+2 moreShow fewer
- Revolut
- USAA
Community-reported · source · updated 2026-11-18. ● asked in the last 6 months.
Go step by step: try it yourself before the video and the visual. Progress saves on this device.
0 / 110 pointsSolved (Easy) 0/20Reviews 0/50Mastered 0/25Practice steps 0/15
Step 1
Know these before you start
Practise each one here, or tick what you already know
Builds on: Counting subarrays with a map of totals
Step 2
Try it on paper
5–10 minutes, no code yet
In the wild · Caches and duplicate detection: A hash map answers “have I seen this before?” in one step. It's how apps cache results, and how a photo app spots the same picture uploaded twice.
ProblemProblem statementWrite a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".ReadHide
Problem Statement
Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".
Added 2026-10-30 from Srujan's LeetCode solved list (photo) — not previously in the repo.
Input / Output
Input: strs = ["flower","flow","flight"]
Output: "fl"
Input: strs = ["dog","racecar","car"]
Output: ""
Input: strs = ["a"]
Output: "a"
Code it here
Tab / Shift+Tab indent · ⌘/Ctrl+/ comments · ⌘/Ctrl+Enter runs · Esc leaves the editor
Step 6
Get it accepted
All test cases pass
Step 7
Review it so it sticks
Re-solve from memory after
The step that matters most: without reviews most of a solved problem fades within weeks. Three short re-solves, each just as you start to forget, are what make it yours.
Your notes
Three lines in your own words. They come back with this problem's reviews, so you can check yourself after recalling the solution.
Solve it yourself before you look
Reading the solution first feels like progress, but it makes the next similar problem — and the interview version — much harder, because you skipped the part where you figure it out. Give it an honest 20–30 minutes. Stuck? Re-read the pattern, watch the concept video, or try the brute force first.
Hidden: approach · solution code · optimal solution
Approach
Pattern Recognition
Vertical Scanning — read one column (same index in every word) at a time. The first column where any word differs — or any word runs out — ends the prefix. The answer can never be longer than the shortest word.
Approach
Brute Force — Try Every Prefix, O(n · m²)
for length from len(shortest) down to 0:
prefix = shortest[:length]
if every word starts with prefix: return prefix
return ""
Optimized — Vertical Scanning, O(S)
for i in range(len(strs[0])):
c = strs[0][i]
for w in strs[1:]:
if i >= len(w) or w[i] != c:
return strs[0][:i] # first mismatch ends it
return strs[0]
(S = total characters in all strings.)
Complexity
| Approach | Time | Space | Notes |
|---|---|---|---|
| Try every prefix | O(n · m²) | O(m) | Re-checks whole prefixes |
| Vertical scan | O(S) | O(1) extra | Stops at first mismatch |
Solution code
from typing import List
class SolutionBruteForce:
"""O(n * m^2) time — try every prefix of the shortest word, longest first."""
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
shortest = min(strs, key=len)
for length in range(len(shortest), -1, -1):
prefix = shortest[:length]
if all(w.startswith(prefix) for w in strs):
return prefix
return ""
class Solution:
"""O(S) time | O(1) extra space — vertical scan, stop at first mismatch."""
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
for i in range(len(strs[0])):
c = strs[0][i]
for w in strs[1:]:
if i >= len(w) or w[i] != c:
return strs[0][:i]
return strs[0]Other ways to solve it
- Thought of another approach (slower, or cleverer)? Code it here: the same tests check any approach.
- Community solutions on LeetCode ↗ for many more versions, in many languages. Read them after you've solved it.
Revising this one?
- →Solve it from memory before peeking
- →Say the pattern out loud, not just the code
- →Explain it like you would to a friend
- →Try it again in a different language