Show problems as
Classic problem #139MediumArrayHash TableStringDynamic ProgrammingTrieMemoizationBrute-Force Search

Word Break

Real-world version: Label Splits Into Codes
Tracked in this browser only
Read Word Break on LeetCode(opens in a new tab)

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

A firmware build stamps each module with a short lowercase code, and the label of an assembled unit is the codes of its modules written one after another with nothing in between.

You are given a label label and a catalogue codes of the codes in use, all distinct. Decide whether label could have come off the line: is there a run of catalogue codes whose concatenation is exactly label, using every character of the label and adding none?

A code may be reused as often as needed, and the catalogue may contain codes that go unused. Return true if such a run exists and false otherwise.

Examples

Example 1

Input
label = "portmapper", codes = ["port", "map", "per"]
Output
true

The label breaks into `port`, `map` and `per`, three catalogue codes in a row with nothing left over.

Example 2

Input
label = "gridlockgrid", codes = ["grid", "lock"]
Output
true

`grid` is stamped twice, once at the front and once at the back, which is allowed because codes may repeat.

Example 3

Input
label = "sunflower", codes = ["sun", "flow", "power"]
Output
false

`sun` and `flow` cover the first seven characters and leave `er`, which no code matches, and `power` never lines up anywhere in the label. No run of codes reproduces it.

Constraints

  • 1 <= label.length <= 300
  • 1 <= codes.length <= 1000
  • 1 <= codes[i].length <= 20
  • label and codes[i] consist of lowercase English letters only
  • All codes are distinct

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 label_splits(label: str, codes: list[str]) -> bool:
Java
public boolean labelSplits(String label, List<String> codes)