All problems
0019EasyArrayStringTrie

Shared Crate Code

Tracked in this browser only
Write code

Trains the technique from

LeetCode 14Longest Common Prefix

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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