Sign Shop Letter Blocks

MediumgreedyAlso known as Greedy Longest-Match Tokenizer

A sign shop builds lettering from pre-cut wooden blocks: single letters, plus blocks for common groups like th, ing and bake, since one block mounts faster than four. The workbench rule is that, reading left to right, you always take the longest block that fits the next letters exactly, or a single letter if none does.

Some language-model tokenizers use the same longest-match-first rule to cut text into pieces from a fixed vocabulary. That is why a common word is often one token while a rare word breaks into several.

Your task

Write tokenize(text, pieces). Start at the first letter. At each position, find the longest string in pieces that appears in text starting exactly there. Add it to the result and move past it. If no piece matches, add the single letter at that position and move one step.

Return the list of tokens in order. Joined together they must spell text. An empty text gives an empty list.

tokenize(text: string, pieces: string[]) → string[]

Examples

Example 1
Input
text = "bakery"
pieces = ["ba", "bake", "ry", "er", "y"]
Output
["bake", "ry"]
Why

At position 0 both "ba" and "bake" fit, and the longer one, "bake", is taken. At position 4 the piece "ry" fits, while "er" does not start there. The result is ["bake", "ry"].

Example 2
Input
text = "thinking"
pieces = ["th", "in", "ink", "ing", "king"]
Output
["th", "ink", "ing"]
Why

At position 0 the piece "th" fits. At position 2 both "in" and "ink" fit, and the longer one, "ink", is taken. At position 5 the piece "ing" fits. The result is ["th", "ink", "ing"]. The greedy rule does not look ahead, so it never considers "in" followed by "king", even though that split would also cover the text.

Example 3
Input
text = "zoo"
pieces = ["oo", "bake"]
Output
["z", "oo"]
Why

No piece starts with "z", so it becomes a single-letter token. Then "oo" fits, so the result is ["z", "oo"].

Constraints

  • 0 ≤ text.length ≤ 10,000
  • 0 ≤ pieces.length ≤ 1,000
  • 1 ≤ pieces[i].length ≤ 20
  • text and pieces use lowercase letters a to z only. pieces may contain repeats.
Start with brute force

At every position, check every piece and keep the longest that starts there. With 10,000 letters and 1,000 pieces of up to 20 letters, that is up to 200 million character comparisons.

Only about 20 lengths are possible at any position, and a set says whether a chunk is a piece in roughly one step, so you can check those few lengths instead of checking every piece.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code