Word Break II

Hard · Dynamic Programming · String · Dynamic Programming · Backtracking · Memoization · Hash Table

Problem

You are given a string s and a list wordDict of distinct words. Add spaces to s so that every piece is a word from wordDict.

Return every sentence that can be made this way, in any order. A word may be used any number of times.

Examples

Input: s = "icecreamcone", wordDict = ["ice","cream","icecream","cone","creamcone"]
Output: ["ice cream cone","ice creamcone","icecream cone"]

ice + cream + cone, ice + creamcone, and icecream + cone.

Input: s = "abcd", wordDict = ["ab","c"]
Output: []

The final d is not part of any word, so there is no sentence.

Input: s = "gogo", wordDict = ["go","gog","o"]
Output: ["go go","gog o"]

Either go + go, or gog + o. The word go is used twice in the first sentence.

Constraints

Approaches

Follow-up

If you only need to know whether a split exists, or how many there are, a boolean or a count per suffix is enough and the work becomes polynomial; the use cases below ask both. Listing every sentence cannot beat the size of the output, which can grow exponentially with the length of s, which is why s is kept short here.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…