Python Program to Find Longest Common Prefix
zip() and set() to find the longest common prefix, like def longest_common_prefix(strs): prefix = ''; for chars in zip(*strs): if len(set(chars)) == 1: prefix += chars[0] else: break; return prefix.Examples
How to Think About It
Algorithm
Code
def longest_common_prefix(strs): if not strs: return "" prefix = "" for chars in zip(*strs): if len(set(chars)) == 1: prefix += chars[0] else: break return prefix # Example usage strings = ["flower", "flow", "flight"] print(longest_common_prefix(strings))
Dry Run
Let's trace the example ['flower', 'flow', 'flight'] through the code
Check empty list
Input list is ['flower', 'flow', 'flight'], not empty, continue.
Loop over characters by position
zip(*strs) gives tuples: ('f','f','f'), ('l','l','l'), ('o','o','i'), ...
Compare characters in each tuple
First tuple ('f','f','f') all same, add 'f' to prefix -> prefix = 'f'. Second tuple ('l','l','l') all same, add 'l' -> prefix = 'fl'. Third tuple ('o','o','i') not all same, stop loop.
Return prefix
Return 'fl' as longest common prefix.
| Iteration | Characters | All Same? | Prefix |
|---|---|---|---|
| 1 | ('f','f','f') | Yes | f |
| 2 | ('l','l','l') | Yes | fl |
| 3 | ('o','o','i') | No | fl |
Why This Works
Step 1: Check if input is empty
If the list of strings is empty, return an empty string immediately because there is no prefix.
Step 2: Compare characters at each position
Using zip(*strs) groups characters from all strings at the same index, making it easy to compare them.
Step 3: Build prefix until mismatch
If all characters in a group are the same, add that character to the prefix; stop when a difference is found.
Alternative Approaches
def longest_common_prefix(strs): if not strs: return "" prefix = strs[0] for s in strs[1:]: while not s.startswith(prefix): prefix = prefix[:-1] if not prefix: return "" return prefix print(longest_common_prefix(["flower", "flow", "flight"]))
def common_prefix(left, right): min_len = min(len(left), len(right)) for i in range(min_len): if left[i] != right[i]: return left[:i] return left[:min_len] def longest_common_prefix(strs): if not strs: return "" if len(strs) == 1: return strs[0] mid = len(strs) // 2 left = longest_common_prefix(strs[:mid]) right = longest_common_prefix(strs[mid:]) return common_prefix(left, right) print(longest_common_prefix(["flower", "flow", "flight"]))
Complexity: O(S) time, O(1) space
Time Complexity
The time depends on the total number of characters in all strings until the first mismatch. In the worst case, all strings are the same, so it checks all characters, O(S), where S is the sum of all characters.
Space Complexity
Only a few extra variables are used, so space is O(1), constant space.
Which Approach is Fastest?
The zip and set method is simple and fast for most cases. Horizontal scanning can be slower if prefix shrinks many times. Divide and conquer is good for very large lists.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Zip and set | O(S) | O(1) | Simple and short code |
| Horizontal scanning | O(S) | O(1) | When strings are few and prefix is short |
| Divide and conquer | O(S) | O(log n) | Large lists with many strings |
zip(*strs) to compare characters at the same position across all strings easily.