Easy

Len Chen
1 min readSep 16, 2018

Problem

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: ["flower","flow","flight"]
Output: "fl"

Example 2:

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

Note:

All given inputs are in lowercase letters a-z.

Solution

Take the first str from strs list and iterate all its character and comparing with corresponding position character of other strs. If there is a character not matched, return current LCP immediately. Otherwise, first is the LCP.

Complexity

Obviously it takes O(nk) time if n denotes to length of strs and k denotes to length of LCP because it will be terminated if one unmatched character is detected.

There is a list for saving current LCP so the space complexity is O(k).

--

--

Len Chen
Len Chen

No responses yet