#14
Longest Common Prefix
EasyArrayStringTrieHash MapArrayTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Horizontal Scanning)★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n * m)Space O(1)
The optimal solution uses a horizontal scanning method where we compare the prefix with each string in the array, updating the prefix as we go. This is more efficient than the brute force method because we stop checking as soon as we find a mismatch.
⚙️
Algorithm
3 steps- 1Step 1: Initialize the prefix as the first string in the array.
- 2Step 2: Loop through each string in the array starting from the second string.
- 3Step 3: For each string, compare it with the current prefix character by character, updating the prefix whenever a mismatch is found.
solution.py15 lines
1# Full working Python code with comments
2
3def longest_common_prefix(strs):
4 if not strs:
5 return ""
6 prefix = strs[0] # Start with the first string as the prefix
7 for string in strs[1:]: # Compare with the rest of the strings
8 while string[:len(prefix)] != prefix: # Check if the current prefix matches the start of the string
9 prefix = prefix[:-1] # Truncate the last character of the prefix
10 if not prefix:
11 return "" # If prefix is empty, return ""
12 return prefix
13
14# Example usage
15print(longest_common_prefix(["flower", "flow", "flight"])) # Output: "fl"ℹ
Complexity note: The time complexity is O(n * m), where n is the number of strings and m is the length of the shortest string. This is because we may need to check each character of the shortest string against the prefix. The space complexity is O(1) since we are using a constant amount of extra space.
- 1The longest common prefix can be found by comparing characters of the strings in a systematic way, which helps in reducing unnecessary comparisons.
- 2Using the first string as a reference for the prefix allows us to quickly identify mismatches with other strings.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.