← Back to DSA Animator
Longest Common Prefix LC #14 Easy Horizontal Scan
Problem

Write a function to find the longest common prefix string among an array of strings. If there is no common prefix, return an empty string "".

Example 1
Input: strs = ["flower","flow","flight"]
Output: "fl"
Explanation: f and l match across all strings, but "flo" fails on "flight".
Example 2
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: No common prefix — first chars d, r, c are all different.
Constraints: 1 ≤ strs.length ≤ 200 | 0 ≤ strs[i].length ≤ 200 | strs[i] consists of lowercase English letters
Try Examples
Custom:
Approach
Horizontal scan: trim prefix until it matches each string
Start with prefix = strs[0]. For each next string, shrink prefix from right until it matches. O(S) total characters.
String Grid
Current Prefix
""
Scanning…
Variables
i
prefix
compare
starts?
len
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Set prefix = strs[0] (candidate starts as the first string)
2
For i = 1 to n−1: check strs[i].startsWith(prefix)
3
While strs[i] does not start with prefix: trim one char from the right
4
If prefix becomes empty → return "" immediately
5
Once all strings match the prefix → return prefix
Time
O(S)
Space
O(1)
Why This Works

Horizontal scanning treats strs[0] as the candidate prefix. The prefix can only shrink — it is trimmed from the right until it matches each subsequent string. Once trimmed to match all strings, it is the longest possible common prefix. S = total characters across all strings.