Squashed Hashtag

Mediumdynamic programmingAlso known as Word Break

A screen reader reads posts aloud. A hashtag like #lemoncakerecipe is one long run of letters, so the reader tries to cut it into words from a known list and say "lemon cake recipe".

Before it can read the hashtag, it first needs to know whether any clean cut exists.

Your task

Write canSplit(tag, words). Return true if tag can be cut into pieces that are all in words, and false otherwise.

Every letter belongs to exactly one piece, and pieces keep their order. A word can be used any number of times. The tag has no # and is all lowercase.

canSplit(tag: string, words: string[]) → bool

Examples

Example 1
Input
tag = "lemoncakerecipe"
words = ["cake", "lemon", "recipe", "rec", "ipe"]
Output
true
Why

Cut it as lemon | cake | recipe. The cut lemon | cake | rec | ipe also works, but one clean cut is enough.

Example 2
Input
tag = "startupweek"
words = ["star", "start", "up", "week"]
Output
true
Why

The cut start | up | week works. If you grab the shortest matching word first, you take "star" and are left with "tupweek", which cannot be cut into words. So you must be ready to try a different first word.

Example 3
Input
tag = "nightowls"
words = ["night", "owl", "nigh", "towel"]
Output
false
Why

The cut night | owl leaves a lone "s" at the end. Starting with nigh leaves "towls", and "towel" does not match it. No cut covers every letter.

Constraints

  • 1 ≤ tag.length ≤ 300
  • 1 ≤ words.length ≤ 1,000
  • 1 ≤ words[i].length ≤ 20, all words different
  • tag and words contain only lowercase letters a to z.
Start with brute force

Try every word that matches the start of the tag, recurse on the rest, and backtrack when stuck.

On forty as followed by a b, with words a, aa, aaa, it tries billions of splits of the as before learning the b can never be covered. It asks "can the rest from position 20 be cut?" over and over, and the answer is always the same.

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