1. Dictionary set
Set lookup makes word checks fast.
const words = new Set(wordDict)Typorithm · medium
Step 1 of 8 · intro card
Dynamic Programming
Word Break checks whether each prefix can be segmented into dictionary words.
The state says whether a prefix is segmentable.
For each end, try every earlier split point.
A hash set gives fast dictionary lookup.
State: dp[end] means prefix s[0:end] works.
Base: empty prefix is true.
Transition: dp[start] and word suffix.
Time O(n^2) substring checks.
function wordBreak(s, wordDict) {
const words = new Set(wordDict);
const dp = Array(s.length + 1).fill(false);
dp[0] = true;
for (let end = 1; end <= s.length; end++) {
for (let start = 0; start < end; start++) {
if (dp[start] && words.has(s.slice(start, end))) {
dp[end] = true;
break;
}
}
}
return dp[s.length];
}Connect each part of the code to the concept before you type.
Set lookup makes word checks fast.
const words = new Set(wordDict)The empty prefix can always be segmented.
dp[0] = trueA prefix is valid if an earlier prefix is valid and the suffix is a word.
if (dp[start] && words.has(s.slice(start, end)))Once dp[end] is true, no more starts are needed.
breakRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputText leetcode · dictionary leet, code, apple, pen, cats, dog, sand, and, cat
Follow temporary values, local state and supporting structures at this step.
↗ The 9-cell working table above is itself auxiliary memory. Input values are shown separately.
Input · not auxiliary memory
Text8 entries
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state