Understanding zip(*strs) for Longest Common Prefix in Python
Problem Statement
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
Input: strs = ["flower", "flow", "flight"]
Output: "fl"
Input: strs = ["dog", "racecar", "car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lowercase English letters if non-empty
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: prefix = "" for chars in zip(*strs): if len(set(chars)) == 1: prefix += chars[0] else: break return prefix
How It Works
zip(*strs)
Transposes the list of strings by grouping characters from the same index in each string.
Example:
strs = ["flower", "flow", "flight"]
list(zip(*strs))
Output: [('f','f','f'), ('l','l','l'), ('o','o','i'), ...]
set(chars)
Used to check if all characters in the same position across the strings are the same.
If all match, the character is added to the prefix.
If not, the loop breaks.
Step-by-step Example
Given:
strs = ["cat", "car", "cap"]
Position Word 1 Word 2 Word 3
0 c c c
1 a a a
2 t r p
Transposed with zip(*strs):
[('c', 'c', 'c'), ('a', 'a', 'a'), ('t', 'r', 'p')]
We loop through these tuples and compare:
('c', 'c', 'c') → all same → add 'c'
('a', 'a', 'a') → all same → add 'a'
('t', 'r', 'p') → not all same → stop
Final prefix: "ca"
What is zip() in Python?
The zip() function combines elements from multiple iterables (lists, tuples, etc.) by index.
Basic Example
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for pair in zip(names, ages):
print(pair)
Output:
('Alice', 25)
('Bob', 30)
('Charlie', 35)
What does zip(*strs) do?
It transposes the input, grouping characters by their positions.
strs = ["dog", "doll", "door"]
list(zip(*strs))
Output: [('d', 'd', 'd'), ('o', 'o', 'o'), ('g', 'l', 'o')]
This allows column-wise comparison of characters.
Why Use zip(*strs)?
- Clean and concise
- Automatically stops at the shortest string
- Easier than looping with indices
- Ideal for comparing strings character by character
Use Cases for zip()
Processing multiple sequences in parallel
`students = ['Alice', 'Bob']
scores = [90, 95]
for name, score in zip(students, scores):
print(name, score)
`
Transpose a matrix
matrix = [
[1, 2, 3],
[4, 5, 6]
]
transposed = list(zip(*matrix))
Output: [(1, 4), (2, 5), (3, 6)]
Compare strings by character positions
words = ["flow", "flower", "flight"]
for letters in zip(*words):
print(letters)
When Not to Use zip()
When working with a single list
When lists are of unequal length and you need the remaining elements
When element position doesn’t matter
Practice Scenarios
Scenario 1: Combine three lists into tuples
a = [1, 2]
b = ['x', 'y']
c = ['apple', 'banana']
list(zip(a, b, c))
Output: [(1, 'x', 'apple'), (2, 'y', 'banana')]
Scenario 2: Check if two lists differ element-wise
`a = [10, 20, 30]
b = [10, 25, 30]
for x, y in zip(a, b):
if x != y:
print(f"Mismatch: {x} ≠ {y}")`
Scenario 3: Longest Common Prefix (Interview Example)
products = ["macbook", "macpro", "macmini", "imac"]
prefix = ""
for chars in zip(*products):
if len(set(chars)) == 1:
prefix += chars[0]
else:
break
print(prefix) # Output: "mac"
Time and Space Complexity
Time Complexity: O(S) where S is the sum of all characters across all strings.
Space Complexity: O(1) (excluding the result), since we only use a few extra variables.
Summary
Use zip(*strs) to align strings character-wise.
It’s one of the most Pythonic ways to solve the longest common prefix problem.
Helps simplify logic, reduce index errors, and improve readability.
Top comments (0)