Back to problems Sign in to unlock
Leetcode
Easy
Strings
Arrays
Longest Common Prefix
Find the longest prefix shared by every string in an array.
Acceptance 88%
Problem Statement
Problem
Given an array of strings, return the longest prefix that appears at the start of every string.
If there is no common prefix, return an empty string.
A prefix is a substring that starts at the beginning of a string.
Notes
- Compare the strings character by character from left to right.
- The answer must be common to all strings, not just some of them.
Input Format
- An array of strings
strs. strs[i]contains lowercase or mixed-case text depending on the platform variant.
Output Format
- Return a single string: the longest common prefix across all strings in
strs.
Constraints
1 <= strs.length- Strings may be empty in some variants.
- The answer length is at most the length of the shortest string.
Examples
Sample cases returned by the problem API.
Example 1
Input
strs = ["flower", "flow", "flight"]
Output
"fl"
Explanation
All three strings start with fl, but the next character differs.
Example 2
Input
strs = ["dog", "racecar", "car"]
Output
""
Explanation
There is no character sequence that appears at the start of every string.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.