Longest Common Prefix easy
Description
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
> Case 1:
Input: strs = ["flower", "flow", "flight"]
Output: "fl"
> Case 2:
Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: There is no common prefix among the input strings.Constraints
1 <= strs.length <= 2000 <= strs[i].length <= 200strs[i]consists of only lowercase English letters
Approach 1: Vertical Scanning
Compare characters column by column across all strings. Stop when any string ends or characters disagree.
Finding common prefix of ["flower", "flow", "flight"]
Step 1 of 3
f
[0]l
[1]o
[2]w
[3]e
[4]r
[5]Column 0: 'f' in flower, 'f' in flow, 'f' in flight. All match! Prefix: 'f'.
Approach 2: Sort and Compare First/Last (Clever)
After sorting, the first and last strings in lexicographic order will have the least in common. Their common prefix is the answer.
Explanation
Vertical Scanning:
- Use the first string as reference
- For each character position, compare that character across all strings
- As soon as any string is too short or has a different character, we have found our prefix
Sort and Compare:
- After sorting lexicographically, strings with common prefixes are adjacent
- The first and last strings have the minimum overlap
- Only need to compare these two strings
The zip(*strs) trick in Python transposes the list of strings into columns.
zip("flower", "flow", "flight") yields ('f','f','f'), ('l','l','l'), ('o','o','i'), ....
If all characters in a column are the same, they are part of the common prefix.
Analysis
Vertical Scanning:
- Time Complexity:
O(S)where S is the total number of characters across all strings - Space Complexity:
O(1)
Sort and Compare:
- Time Complexity:
O(n * m * log n)where n = number of strings, m = average length - Space Complexity:
O(1)extra (ignoring sort space)