← All coding problems
Longest Common Prefix
easyStrings+10 XPTime limit 2s
Find the longest string that is a prefix of every word in the list.
Input:
- line 1:
n - next
nlines: one word each (lowercase letters)
Output: the longest common prefix, or - if the words share no prefix at all.
Constraints: 1 ≤ n ≤ 10⁴, 1 ≤ word length ≤ 200.
Think about it: compare character by character across all words ("vertical scanning"). Neat trick: after sorting, you only need to compare the first and the last word.
Sample input 1
3 flower flow flight
Sample output 1
fl
Sample input 2
3 dog racecar car
Sample output 2
-
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).