Polski

Split a hashtag into words

Can a string without spaces (e.g. a hashtag) be split into dictionary words? Dynamic programming instead of exponential backtracking.

medium · typescript · javascript · python · csharp · java · go · 20 XP

An analytics module splits hashtags into words to index them: #cleancodematters → "clean code matters". The first step is deciding whether a split exists at all: can the string be built entirely from consecutive dictionary words (words may repeat)?

Task

The function gets a string text (lowercase letters, no spaces) and a list of words words. Return true if text can be split into a sequence of words from words, otherwise false. An empty string can always be split (into zero words).

Signatures: wordBreak(text, words) (JS/TS), word_break(text, words) (Python), Solution.WordBreak (C#), Solution.wordBreak (Java), WordBreak (Go).

Examples

textwordsResult
"cleancode"["clean", "code"]true
"applepenapple"["apple", "pen"]true – words may repeat
"goalspecial"["go", "goal", "goals", "special"]true – "goal" + "special"
"catsandog"["cats", "dog", "sand", "and", "cat"]false

Constraints

  • 0 ≤ text.length ≤ 5,000, up to 1,000 words, each 1–20 characters long.

Expected complexity

O(n · L) set lookups (L – length of the longest word; each lookup costs O(L) to cut the fragment), O(n + dictionary size) memory.