Show problems as
Classic problem #14EasyArrayStringTrie

Longest Common Prefix

Real-world version: Shared Crate Code
Tracked in this browser only
Read Longest Common Prefix on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A depot stencils a lowercase code onto every crate in a shipment. codes lists one code per crate, in the order the crates were loaded, and a crate whose stencil ran dry carries an empty code.

Return the longest opening run of characters that all of the codes begin with. The run is matched front to back and position by position: its first character must be the first character of every code, its second character must be the second character of every code, and so on for as far as the agreement holds.

When the codes already part ways at their opening character, or when any crate in the shipment carries an empty code, the answer is the empty string "".

A shipment can consist of one crate, and then that crate's own code is the whole answer.

Examples

Example 1

Input
codes = ["shipment", "shipping", "ship"]
Output
"ship"

All three begin with s, h, i, p. The fifth position holds m, p and nothing at all, so the run stops after four characters, exactly the length of the shortest code.

Example 2

Input
codes = ["crate", "box", "pallet"]
Output
""

The opening characters are c, b and p, so the agreement is empty before it starts.

Example 3

Input
codes = ["solo"]
Output
"solo"

A lone crate agrees with itself over its full code.

Constraints

  • 1 <= codes.length <= 200
  • 0 <= codes[i].length <= 200
  • codes[i] is made of lowercase English letters when it is not empty

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def shared_crate_code(codes: list[str]) -> str:
Java
public String sharedCrateCode(String[] codes)