JavaMediumStrings20 min

Find the longest common prefix

Print the longest prefix shared by all words, or an empty line if n=0 or no prefix exists. Follow the stated ordering and edge-case conventions exactly. Interviewers use this task to probe boundary handling and collection selection.

Input

n followed by n nonempty lowercase words separated by whitespace.

Output

Print the longest prefix shared by all words, or an empty line if n=0 or no prefix exists.

Constraints

0 <= n <= 10000; total word length <= 100000.

Example

Input

3 flower flow flight

Output

fl

Example 2 input

2 a ab

Output

a

This example exercises a further boundary or ordering case.

Public test cases (2)

  • Input

    3 flower flow flight

    Expected output

    fl
  • Input

    3 dog racecar car

    Expected output

    —
Hints (2)
  1. Identify the state needed to avoid recomputing work for each element.
  2. Maintain a prefix length and shorten it only when a later word disagrees.

Target complexity: time O(total input length) · space O(maximum word length)

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All Java programs