Maintained by Vikas Dulgunde, software engineer
You are handed a string `s` and a list of allowed words called `wordDict`. The task is to determine if you can slice `s` into back-to-back chunks so that each chunk is one of the allowed words and the chunks together cover the whole string with nothing left over.
Every character of `s` has to belong to exactly one chunk, and the chunks must appear in order with no gaps or overlaps. You are not asked for the actual breakdown, only whether at least one valid breakdown exists.
A word from the dictionary can be used as many times as you like, or not at all. So if `s` is "aaaa" and the dictionary holds "a", you can reuse "a" four times and the answer is yes.
Return `true` when some valid segmentation exists and `false` when no arrangement of dictionary words spells out `s` exactly.
Splitting after position 4 gives "leet" then "code", and both are in the dictionary, so the whole string is covered.
The split is "apple" + "pen" + "apple". The word "apple" is reused, which is allowed.
Every prefix path stalls. "cats" leaves "andog", "cat" leaves "sandog"; neither remainder can be finished with dictionary words, so no full segmentation exists.
Visible test cases
Think about prefixes. If you already know the first `start` characters can be segmented, you only need to check whether the slice from `start` to some later index is a dictionary word.
Define a boolean per position: can the prefix ending at this index be split fully? Position 0 (empty prefix) is reachable by definition.
Build positions left to right. An index is reachable if some earlier reachable index is followed by a substring that exists in the word set. Put the dictionary in a hash set so each substring check is fast.
From the current position, try every dictionary word that matches the upcoming characters, consume it, and recurse on the rest. Succeed when you consume the entire string.
Track which prefix lengths are segmentable. A prefix of length `end` is segmentable if some shorter segmentable prefix of length `start` is followed by a dictionary word spanning start to end.