Member-only story

Day 26 — Daily JavaScript Algorithm

Find the Longest Common Prefix

Dipak Ahirav
JavaScript in Plain English
4 min readFeb 24, 2025

--

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:

  1. Take the first string as prefix.

--

--

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Written by Dipak Ahirav

Full Stack Developer | Angular & MEAN Stack Specialist | MEAN Stack Developer | Blogger | Open to Collaboration Author of "Code & Coffee: A Developer's Journey"

No responses yet

Write a response