All problems
EasyStrings

Longest Common Prefix

googleamazonappleadobemicrosoft

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"
Explanation: "fl" is the longest common prefix shared by all three strings.

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

Example 3:

Input: strs = ["interspecies","interstellar","interstate"]
Output: "inters"
Explanation: "inters" is the longest prefix common to all three strings.

Examples

Example 1

Input: strs = ["flower","flow","flight"]

Output: "fl"

Explanation: All three strings start with "fl". The third string diverges at index 2 ('i' vs 'o'), so the longest common prefix is "fl".

Example 2

Input: strs = ["dog","racecar","car"]

Output: ""

Explanation: There is no character that all three strings share at index 0 ('d' vs 'r' vs 'c'), so the common prefix is empty.

Constraints

  • -1 <= strs.length <= 200
  • -0 <= strs[i].length <= 200
  • -strs[i] consists of only lowercase English letters.

Optimal Complexity

Time

O(n * m)

Space

O(1)

Practice this problem with an AI interviewer

TechInView conducts a full voice mock interview — the AI asks clarifying questions, evaluates your approach, watches you code, and scores you on 5 dimensions. Just like a real FAANG interview.

Start a free interview