Practice Problem

Longest Common Prefix

Difficulty: Easy

Find the longest common prefix string among an array of strings.

Longest Common Prefix

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 "".

Examples

Example 1:

Input: strs = ["flower", "flow", "flight"]
Output: "fl"
Explanation: "fl" is the longest 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 = ["interview", "internet", "internal"]
Output: "inter"

Constraints

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

Expected Complexity

  • Time: O(S) where S is the sum of all characters in all strings
  • Space: O(1)
EASY
Arrays
Strings
Beginner

0 views

Solution

Hints

Hint 1
Hint 2
Premium
Hint 3
Premium