Word Break
MediumThis is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.
Question
You're given a strip of text and a supply list of reusable text fragments.
Return whether you can rebuild the whole strip by placing fragments from the supply list one after another. There can't be any gaps or extra characters left over. You can reuse any fragment as many times as you like.
Input: s = "redbluered", words = ["red", "blue"]
Output: True
Place "red", then "blue", then "red" again. That lines up exactly with the strip. Notice that we used "red" twice.
Input: s = "aaaab", words = ["aa", "aaa"]
Output: False
Every fragment is made only of the letter "a". So you can never end the strip on a "b", however you combine them.
Input: s = "xyz", words = ["xy", "yz"]
Output: False
If you place "xy" first, you're left with just "z". Neither fragment matches "z" on its own. And "yz" doesn't match the start of the strip. So you can't place it first.
Input: s = "", words = ["a", "b"]
Output: True
An empty strip is already complete before you place a single fragment.
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Remember to understand the problem and plan your approach before you start coding.