oneby7

1-D Dynamic Programming Take it or skip it

519. Word Break

Medium 147 DSA Sheet

You are given a string s and a list of words, wordDict. Return true if s can be cut into pieces so that every piece is a word from the list. Otherwise return false.

Every letter of s belongs to exactly one piece, and the pieces keep their order. A word can be used any number of times, and some words may not be used at all.

Example 1

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

Output: true

Explanation: ice cream cone works, and so does icecream cone. One way is enough.

Example 2

Input: s = "bedroomlamp" wordDict = ["bed", "room", "bedroom", "lam", "lamps"]

Output: false

Explanation: Both bed room and bedroom reach lamp, and lamp cannot be cut. lam leaves a lone p, and lamps is longer than what is left.

Example 3

Input: s = "hahaha", wordDict = ["ha"]

Output: true

Explanation: A word can be used again and again: ha ha ha.

Check your understanding

Work out the answer for this input before you write any code.

s = "notable", wordDict = ["not", "nota", "able"]

Constraints

  • 1 ≤ s.length ≤ 105
  • 1 ≤ wordDict.length ≤ 104
  • 1 ≤ wordDict[i].length ≤ 20
  • s and every word hold only lowercase English letters
  • The words in wordDict are all different.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.