Squashed Hashtag

Mediumdynamic programmingAlso known as Word Break

A screen reader reads posts aloud for people who cannot see the screen. Hashtags are a problem: #lemoncakerecipe is one long run of letters, and reading it letter by letter is useless. The reader has a list of known words and tries to cut each hashtag into them, so it can say "lemon cake recipe".

Before trying to say anything, it needs to know whether a clean cut exists at all.

Your task

Write canSplit(tag, words). Return true if tag can be cut into pieces so that every piece is in words, and false otherwise.

Every letter must belong 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. (lemon | cake | rec | ipe also works; one clean cut is enough.)

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

start | up | week works. Grabbing the shortest word first takes "star" and leaves "tupweek", which nothing fits. So you must be ready to try a different first word.

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

night | owl leaves a lone "s". 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, then recursively do the same on what is left. Backtrack when you get stuck.

On a tag like forty as followed by a b, with words a, aa, aaa, every split of the as is tried before the recursion learns that the b can never be covered. That is billions of splits. The recursion keeps asking "can the rest from position 20 be cut?" again and again, and the answer never changes.

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