Word Break
mediumBlind 75NeetCode 150dynamic-programmingstringshashing
Problem
Given a string and a dictionary of words, decide whether the string can be segmented into a sequence of one or more dictionary words. Words may be reused.
Examples
Input: s = "leetcode", dict = ["leet", "code"]
Output: true
It splits into "leet" and "code".
Input: s = "catsandog", dict = ["cats","dog","sand","and","cat"]
Output: false
No segmentation covers the whole string.
Constraints
- • 1 <= s.length <= 300
- • 1 <= dictionary size <= 1000
- • Dictionary words are unique
Hints(tap to reveal)
- 1. A prefix is breakable if some earlier breakable cut leaves a dictionary word.
- 2. Memoize over prefix lengths.
Optimal approach(spoiler)
- Let breakable(i) mean the prefix of length i can be segmented.
- breakable(0) is true as the empty prefix.
- For each i, check every j less than i where breakable(j) and the substring j..i is in the dictionary.
- Return breakable at the full length.
- O(n^2) time, O(n) space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor