Member-only story
Day 26 — Daily JavaScript Algorithm
Find the Longest Common Prefix

Welcome to Day 26 of our Daily JavaScript Algorithm series! Today, we’ll solve the Longest Common Prefix problem — a common question in string manipulation and coding interviews.
Not a Member? Read for FREE here.
Problem Statement
Given an array of strings strs
, return the longest common prefix shared among all the strings. If there is no common prefix, return an empty string ""
.
Example 1:
- Input:
strs = ["flower", "flow", "flight"]
- Output:
"fl"
Example 2:
- Input:
strs = ["dog", "racecar", "car"]
- Output:
""
- Explanation: No common prefix exists.
Example 3:
- Input:
strs = ["interview", "integrate", "intelligent"]
- Output:
"int"
Approach 1: Horizontal Scanning
We take the first string as a reference and compare it with all other strings, shortening the prefix until it matches all.
Algorithm Steps:
- Take the first string as
prefix
.