Shared Starting Sequence in String Array
StringsAuto-graded · 22 test casesLast updated
Determine the longest initial substring shared across every word in a given list.
Given a collection of strings strs, determine the longest prefix that is shared by every string in the list.
If the input collection has no shared prefix among all strings, or if the list is empty, return an empty string "".
Constraints
0 <= len(strs) <= 2000 <= len(strs[i]) <= 200strs[i]consists only of lowercase English letters ('a'through'z').
Examples
Example 1
Input: longest_common_prefix(['flower', 'flow', 'flight'])
Output: 'fl'
Example 2
Input: longest_common_prefix(['dog', 'racecar', 'car'])
Output: ''
Hints
Hint 1
Start by assuming the first string is the common prefix candidate.
Hint 2
Compare the candidate character-by-character against each remaining string, trimming it whenever a mismatch occurs.
Hint 3
If your candidate prefix becomes empty at any point, you can immediately return an empty string.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach: Sequential Substring Trimming
We can find the longest common prefix by processing the strings sequentially:
- Handle edge cases: If
strsis empty, return""immediately. - Initialize our running common prefix
prefixas the very first string in the array (strs[0]). - Iterate through each subsequent string
sinstrs[1:]. - Compare
prefixwithscharacter by character up to the length of the shorter string. - Trim
prefixto match only the prefix segment where characters equal those ofs. - If
prefixreduces to an empty string""at any point, return""early as no non-empty prefix can exist across all strings. - Return
prefixafter inspecting all strings.
Correctness
The prefix of a set of strings is associative: $$\text{LCP}(S_1, S_2, \dots, S_n) = \text{LCP}(\text{LCP}(S_1, S_2), S_3, \dots, S_n)$$
At step $k$, prefix stores the exact longest common prefix for strs[0...k]. Trimming it against strs[k+1] maintains this invariant.
Complexity
- Time Complexity: $O(S)$, where $S$ is the total number of characters across all strings in
strs. In the worst case (all identical strings), every character of every string is inspected. Under the given constraints, $S \le 200 \times 200 = 40,000$, executing almost instantaneously. - Space Complexity: $O(m)$ auxiliary space, where $m$ is the length of the initial string, used to construct sliced substring copies during trimming.
from typing import List
def longest_common_prefix(strs: List[str]) -> str:
if not strs:
return ""
prefix = strs[0]
for s in strs[1:]:
limit = min(len(prefix), len(s))
match_len = 0
while match_len < limit and prefix[match_len] == s[match_len]:
match_len += 1
prefix = prefix[:match_len]
if not prefix:
return ""
return prefix