Member-only story

LeetCode Word Break II Explained

Saloni Kaur
3 min readJul 16, 2019

--

This is another one from LeetCode: https://leetcode.com/problems/word-break-ii/

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

  • The same word in the dictionary may be reused multiple times in the segmentation.
  • You may assume the dictionary does not contain duplicate words.
Input:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
Output:
[
"cats and dog",
"cat sand dog"
]

Please give this question a try before reading further.

“catsanddog” → “catsand” + “dog”

“catsand”“cats” + “and” or “cat” + “sand”

Do you see the pattern? Let’s try another example.

Input:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
Output:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]

“pineapplepenapple” → “pineapplepen” + “apple”

pineapplepen” → pineapple + “pen” or “pine” + applepen

--

--

Saloni Kaur
Saloni Kaur

No responses yet