Longest Common Prefix
Real-world version: Shared Crate CodeThe 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.
def shared_crate_code(codes: list[str]) -> str:public String sharedCrateCode(String[] codes)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Word BreakReal-world version: Label Splits Into CodesMedium
- Top K Frequent WordsReal-world version: Most Drawn Part CodesMedium
- Find the Length of the Longest Common PrefixReal-world version: Longest Shared Route LeadMedium
- Shortest Uncommon Substring in an ArrayReal-world version: Unique Fragment Per CodeMedium