On this page
Longest Common Prefix
TIP101 Unit 3 Session 2 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What is the input?
- A list of strings,
strings.
- A list of strings,
- What should the function return?
- The longest string that every string in the list starts with.
- What if the strings share no common prefix?
- Return an empty string
"".
- Return an empty string
- What if the list is empty?
- Return an empty string
"", as the first step of the plan below says.
- Return an empty string
- Is the comparison case-sensitive?
- Yes. Characters are compared exactly, so
"A"and"a"do not match.
- Yes. Characters are compared exactly, so
HAPPY CASE
Input: strings = ["flower", "flow", "flight"]
Output: "fl"
Explanation: The shortest string is "flow". Its first two characters match every string, but at index 2 "flight" has "i" instead of "o".
EDGE CASE
Input: strings = ["dog", "racecar", "car"]
Output: ""
Explanation: "racecar" does not start with "d", so there is no common prefix.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: First, find the shortest string in the list. Then check each character of that string, and if something does not match the other strings, return everything before that.
1) If the strings list is empty, return an empty string `""`
2) Find the smallest of the strings by comparing their lengths
3) Loop through the index and value of each char in smallest
a) Loop through each other string
i) If the other[index] does not match smallest[index],
return smallest from 0 to index-1
4) If everything matched, return smallest
⚠️ Common Mistakes
- Looping through the “index and value of each char” may seem tricky, but using
enumeratein Python makes it much easier.
I-mplement
def longest_common_prefix(strings):
if not strings:
return ""
shortest_str = strings[0]
for s in strings:
if len(s) < len(shortest_str):
shortest_str = s
for i, char in enumerate(shortest_str):
for other in strings:
if other[i] != char:
return shortest_str[:i]
return shortest_str