ExamAdda Logo

Longest Common Prefix

Medium

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

3
flower
flow
flight

Output

fl

Explanation

All three strings begin with "fl", and no longer common prefix exists.

Constraints

1 ≤ strs.length ≤ 200
0 ≤ strs[i].length ≤ 200
strs[i] consists of lowercase English letters.

Hints:

Hint 1

Assume the first string is the common prefix initially.

Hint 2

Compare the current prefix with each remaining string. Shorten the prefix until it matches the beginning of the current string.

Author & Technical Reviewer

Chatla Jithin Sri Surya

Technically reviewed by: Chatla Jithin Sri Surya

Content Writer

<p>IIEST Shibpur | SDE | AI, ML &amp; Gen AI | DSA | Building Intelligent, Scalable Software</p>

Published

Sep 30, 2026

Last updated

Sep 30, 2026

Last technically reviewed

Sep 30, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output