Data Structures & Algorithms Dynamic Programming — 1D
💡
Exercise 128

Word Break 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

Given a string and a dictionary of words, determine if the string can be segmented into dictionary words.

s = "leetcode" wordDict = ["leet", "code"] # "leet" + "code" = "leetcode" → True

dp[i] = True if s[:i] can be segmented. For each position i, check all words that could END at position i.

💡 Pro tip: Understand this problem deeply — don't just memorize the code. Try explaining the approach out loud as if teaching a friend. If you can explain it simply, you truly understand it!

📋 Instructions
Check if the string can be segmented into dictionary words.
dp[0] = True. For i in range(1, len(s)+1), for each word, if dp[i-len(word)] and s[i-len(word):i] == word, dp[i] = True.
🧪 Test Cases
Input
wordBreak('leetcode', ['leet', 'code'])
Expected
True
Boolean check
Input
wordBreak('catsandog', ['cats', 'dog', 'sand', 'and', 'cat'])
Expected
False
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.