Longest Common Prefix in DSA Python - Time & Space Complexity
We want to know how the time needed to find the longest common prefix grows as we add more words or longer words.
How does the work increase when the input list or word length grows?
Analyze the time complexity of the following code snippet.
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
This code finds the longest common prefix string among a list of strings by comparing and shortening the prefix as needed.
- Primary operation: Checking if each string starts with the current prefix and shortening the prefix.
- How many times: For each string, the prefix may be shortened multiple times, up to the length of the prefix.
As the number of strings (n) or the length of the prefix (m) grows, the work increases roughly by n times m.
| Input Size (n strings, m length) | Approx. Operations |
|---|---|
| 10 strings, prefix length 5 | About 50 checks |
| 100 strings, prefix length 10 | About 1000 checks |
| 1000 strings, prefix length 20 | About 20,000 checks |
Pattern observation: The operations grow roughly by multiplying the number of strings by the prefix length.
Time Complexity: O(n * m)
This means the time grows proportionally with the number of strings and the length of the prefix we check.
[X] Wrong: "The time is just O(n) because we only loop through the list once."
[OK] Correct: Each string comparison can take up to the length of the prefix, so the inner work depends on prefix length too.
Understanding this helps you explain how nested checks affect performance and shows you can analyze combined factors, a key skill in interviews.
"What if we sorted the strings first and only compared the first and last strings? How would the time complexity change?"
Practice
Solution
Step 1: Understand the problem definition
The Longest Common Prefix means the longest substring at the start of all strings that is the same.Step 2: Compare options with the definition
Only The longest starting substring common to all strings matches this definition exactly.Final Answer:
The longest starting substring common to all strings -> Option BQuick Check:
Longest Common Prefix = longest starting substring [OK]
- Confusing prefix with suffix
- Thinking about any substring instead of prefix
- Counting total strings instead of prefix length
Solution
Step 1: Identify the correct data type for prefix storage
The longest common prefix is a string, so it should be initialized as an empty string.Step 2: Match initialization with data type
lcp = '' initializes lcp as an empty string, which is correct.Final Answer:
lcp = '' -> Option CQuick Check:
Prefix is a string, so empty string initialization [OK]
- Using list [] instead of string
- Using None which is not a string
- Using 0 which is a number, not string
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']))Solution
Step 1: Initialize prefix and iterate over strings
Prefix starts as 'flower'. Check 'flow': 'flow' does not start with 'flower', so remove last char to 'flowe', then 'flow', which matches.Step 2: Check next string 'flight'
'flight' does not start with 'flow', remove last char to 'flo', no match; then 'fl', which matches.Final Answer:
fl -> Option AQuick Check:
Common start of all strings = 'fl' [OK]
- Returning first string without checking others
- Not shrinking prefix correctly
- Confusing substring anywhere with prefix
def longest_common_prefix(strs):
prefix = strs[0]
for s in strs:
while not s.startswith(prefix):
prefix = prefix[:-1]
return prefix
print(longest_common_prefix(['dog', 'racecar', 'car']))Solution
Step 1: Analyze loop and prefix shrinking
The code shrinks prefix until s starts with prefix, but does not check if prefix becomes empty.Step 2: Identify infinite loop risk
If no common prefix exists, prefix will shrink to empty string, then prefix[:-1] stays empty, causing infinite loop.Final Answer:
Missing check for empty prefix causing infinite loop -> Option DQuick Check:
Empty prefix check needed to stop loop [OK]
- Not checking prefix empty condition
- Looping over all strings including first
- Confusing startswith arguments
Solution
Step 1: Understand vertical scanning
Vertical scanning means checking each character position across all strings one by one.Step 2: Identify stopping condition
Stop when a mismatch or end of any string is found at that position.Final Answer:
Compare characters column by column across all strings until a mismatch is found -> Option AQuick Check:
Vertical scanning = column-wise character comparison [OK]
- Confusing vertical scanning with sorting
- Using hash maps unnecessarily
- Concatenating strings instead of comparing
Ready to prove it?
Pass the test and this pattern moves unknown
