Write code to find the longest common substring among the input list ['flower', 'floor', 'flow'].
💡 Model Answer
The longest common substring that appears in all three strings is "flo". A simple approach is to generate all substrings of the first string and check whether each appears in the other two strings. Start with the longest substrings to stop early. Complexity is O(n^3) in the worst case, where n is the length of the longest string. A more efficient solution uses suffix trees or dynamic programming to achieve O(n^2) time. Below is a straightforward Python implementation:
strings = ['flower', 'floor', 'flow']
first = strings[0]
max_sub = ''
for i in range(len(first)):
for j in range(i+1, len(first)+1):
sub = first[i:j]
if all(sub in s for s in strings[1:]):
if len(sub) > len(max_sub):
max_sub = sub
print(max_sub) # outputs 'flo'This code checks each substring of the first string against the others and keeps the longest match.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500