Longest Common Prefix
Programming Interview
Medium
4 views
Problem Description
Given {x}, Output their longest common prefix. If no common prefix, output EMPTY.
Input Format
First line n. Next n lines strings.
Output Format
One line prefix or EMPTY.
Sample Test Case
Input:
3
flower
flow
flight
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
arr=[(lines[i] if i<len(lines) else '') for i in range(1,1+n)]
if not arr:
sys.stdout.write('EMPTY')
else:
pref=arr[0]
for s in arr[1:]:
j=0
L=min(len(pref),len(s))
while j<L and pref[j]==s[j]:
j+=1
pref=pref[:j]
if pref=='':
break
sys.stdout.write(pref if pref!='' else 'EMPTY')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!