HomeInterview QuestionsFind the longest common prefix among the strings […

Find the longest common prefix among the strings ['flow', 'flower', 'floor'].

🟢 Easy Coding Fresher level
1Times asked
May 2026Last seen
May 2026First seen

💡 Model Answer

The longest common prefix of the three strings is "flo". A common technique is to sort the list of strings; the common prefix of the entire list must be a prefix of both the first and the last string in the sorted order. Then compare characters of these two strings until a mismatch occurs.

Python implementation:

python
strings = ['flow', 'flower', 'floor']
strings.sort()
first, last = strings[0], strings[-1]
prefix = ''
for c1, c2 in zip(first, last):
    if c1 == c2:
        prefix += c1
    else:
        break
print(prefix)  # outputs 'flo'

Time complexity is O(n * m), where n is the number of strings and m is the length of the shortest string. Space complexity is O(1) aside from the input list.

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