MEDIUM NC#108 Blind #20 Dynamic Programming 1D

139. Word Break

šŸ“– Problem

Given a string s and a dictionary of strings wordDict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

🧠 Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • •Array methods (`push`, `pop`, `shift`, `slice`)
  • •Object/Map/Set usage patterns
  • •Function parameter and return typing
  • •Array DP table updates
  • •State transition thinking
  • •Base case initialization

Logical Thinking Concepts

  • •Define invariants before coding
  • •Check edge cases first (`[]`, single element, duplicates)
  • •Estimate time/space before implementation
  • •Apply Dynamic Programming reasoning pattern
  • •Apply DFS reasoning pattern
  • •Apply Recursion reasoning pattern

šŸ’” Approach

  • → dp[i] = true if s[0:i] can be segmented
  • → For each position i, check all substrings ending at i
  • → dp[0] = true (empty string is valid)
  • → Time: O(n² * m) where n = s.length, m = avg word length, Space: O(n)

🧭 Prerequisites

šŸ› ļø Hints & Pitfalls

Hints

  • •dp[i] = true if s[0:i] can be segmented
  • •For each position i, check all substrings ending at i
  • •dp[0] = true (empty string is valid)

Common Pitfalls

  • •Time: O(n² * m) where n = s.length, m = avg word length, Space: O(n)

🧪 Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
wordBreak('leetcode', ['leet','code']);
Expected:
true
Test Case 2
Not run
Input:
wordBreak('applepenapple', ['apple','pen']);
Expected:
true
Test Case 3
Not run
Input:
wordBreak('catsandog', ['cats','dog','sand','and','cat']);
Expected:
false

šŸ“ Code Editor

šŸ“š Reference Solution

ā–¼
⌘K Search āŒ˜ā†© Run ⌘S Submit