Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Longest Common Prefix in Python
Finding the longest common prefix among a set of strings is a common programming problem. The longest common prefix is the initial substring that appears at the beginning of all strings in the array. If no common prefix exists, we return an empty string.
For example, given the array ["school", "schedule", "scotland"], the longest common prefix is "sc" since it appears at the start of all three strings.
Algorithm Approach
We start by taking the first string as our reference. Then we iterate through each remaining string, comparing characters one by one. When we find a mismatch, we update our current prefix and continue with the next string.
Implementation
class Solution:
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ""
current = strs[0]
for i in range(1, len(strs)):
temp = ""
if len(current) == 0:
break
for j in range(len(strs[i])):
if j < len(current) and current[j] == strs[i][j]:
temp += current[j]
else:
break
current = temp
return current
# Test the solution
input_list = ["school", "schedule", "scotland"]
solution = Solution()
result = solution.longestCommonPrefix(input_list)
print(f"Longest common prefix: '{result}'")
Longest common prefix: 'sc'
Alternative Approach Using Built-in Functions
Python provides a more concise way to find the longest common prefix using the zip function and set:
def longest_common_prefix(strs):
if not strs:
return ""
# Zip characters from all strings and check if all are same
prefix = ""
for chars in zip(*strs):
if len(set(chars)) == 1: # All characters are the same
prefix += chars[0]
else:
break
return prefix
# Test the function
strings = ["school", "schedule", "scotland"]
result = longest_common_prefix(strings)
print(f"Longest common prefix: '{result}'")
# Test with no common prefix
strings2 = ["hello", "world", "python"]
result2 = longest_common_prefix(strings2)
print(f"No common prefix: '{result2}'")
Longest common prefix: 'sc' No common prefix: ''
How It Works
The algorithm works by:
- Step 1: Handle edge case of empty input
- Step 2: Use first string as initial reference
- Step 3: Compare each subsequent string character by character
- Step 4: Stop at first mismatch and update the current prefix
- Step 5: Continue until all strings are processed
Time and Space Complexity
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Iterative | O(S) where S is sum of all characters | O(1) |
| Using zip() | O(M × N) where M is length of shortest string | O(M) |
Conclusion
The longest common prefix problem can be solved efficiently by comparing strings character by character. The iterative approach is memory-efficient, while the zip() approach offers cleaner, more Pythonic code for shorter inputs.
