Longest common prefix in python
We need to find the letters that are present at the beginning of every word.
strs = [“flower”, “flow”, “flight”]
Output: “fl”
flower
flow
flight
Iteration 1:
├── f ← common
├── l ← common
├── o ← common
├── w ← common
├── e ← common
└── r ← common
Interation 2:
│
├── f ← common
├── l ← common
├── o ← common
└── w ← NOT common
Interation 3:
│
├── f ← common
├── l ← common
└── i ← NOT common
Visual Representation of the code:
Python Code:
class Solution:
def longestCommonPrefix(self, strs):
# add edge case to check if the given string is empty
if not strs:
return ""
prefix = strs[0]
for word in strs:
while prefix != word[:len(prefix)]:
prefix=prefix[:-1]
#if no common prefix are found return null
if prefix == ""
return ""
return prefixMain Part of the code:
while prefix != word[:len(prefix)]:why do we need this in a LOOP??
Part 1: prefix
This is the part of the word we are currently checking.
flower
Our starting prefix
Part 2: word[:len(prefix)]
This takes the first few letters of the current word — the same number of letters as prefix.
Get Ruby’s stories in your inbox
Join Medium for free to get updates from this writer.
For example, if prefix = "flower", its length is 6. If word = "flow", this expression takes the first 6 characters available from "flow". Since the word has only 4 characters, the result is "flow".
Part 3: !=
This means “is not equal to.”
The condition checks whether prefix and the beginning of word are different.
Why we need WHILE instead of IF?
Suppose:
prefix = "flower"word = "flow"
We want to check if prefix matches the beginning of word.
Imagine that prefix is "flower" and the current word is "flight".
We need to remove several letters before finding a match:
flower →Doesn’t match flight
flowe →Doesn’t match flight
flow → Doesn’t match flight
flo → Doesn’t match flight
fl → Matches the beginning of flight
This explains -
ifchecks a condition once.whilechecks the condition repeatedly and keeps running as long as the condition is true.
Here, we need while because we might need to remove one letter, two letters, or more before finding the common prefix.








