Shortest Uncommon Substring in an Array
Real-world version: Unique Fragment Per CodeThe statement here is our own: the same inputs, outputs and technique.
A warehouse labels every bin with a lowercase part code. The picking sheet wants, for each code, a short fragment that identifies it unambiguously.
You are given codes, an array of n part codes. A fragment of a code is any contiguous run of its characters. For each index i, report the shortest fragment of codes[i] that appears in no other code of the array -- appearing anywhere inside another code disqualifies it. When several fragments tie for shortest, report the alphabetically smallest of them. When no fragment of codes[i] qualifies, report the empty string for that index.
Return an array answer where answer[i] is the fragment reported for codes[i].
Examples
Example 1
- Input
- codes = ["cab", "xyz"]
- Output
- ["a", "x"]
For "cab" the fragments "a", "b" and "c" each fail to appear in "xyz", and "a" is the alphabetically smallest of them. For "xyz" the single characters all qualify, and "x" is alphabetically smallest.
Example 2
- Input
- codes = ["ab", "ax"]
- Output
- ["b", "x"]
The fragment "a" appears in both codes, so it qualifies for neither. "b" appears only in the first code and "x" only in the second.
Example 3
- Input
- codes = ["abc", "abc"]
- Output
- ["", ""]
The two codes are identical, so every fragment of one appears in the other and both indices report the empty string.
Example 4
- Input
- codes = ["zz", "z"]
- Output
- ["zz", ""]
For the first code, "z" appears in the second code but "zz" does not. The second code has only the fragment "z", which appears in the first code.
Constraints
- n == codes.length
- 2 <= n <= 100
- 1 <= codes[i].length <= 20
- codes[i] consists of lowercase English letters only.
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 shortest_substrings(codes: list[str]) -> list[str]:public String[] shortestSubstrings(String[] codes)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 9 test cases: 9 passed
- Passed: 4 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
- Number of Matching SubsequencesReal-world version: Labels That Read Through the TapeMedium