#139

Word Break

MediumDPHas vizHash TableStringDynamic Programming
Related studio

Problem

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

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Example 1

Input: s = "leetcode", wordDict = ["leet","code"]

Output: true

Segment as "leet code".

Example 2

Input: s = "applepenapple", wordDict = ["apple","pen"]

Output: true

Reuse apple.

Example 3

Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]

Output: false

Cannot segment fully.

Constraints

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • s and wordDict[i] consist of only lowercase English letters.
  • All the strings of wordDict are unique.
Loading visualization…

Explanation

Word Break is a Medium interview problem tagged [Hash Table, String, Dynamic Programming]. The winning approach is typically **DP**.

Intuition

Overlapping subproblems are solved once and reused.

Approach

Define dp state → write transition → fill base cases → iterate in dependency order.

  1. Sentence-define dp[i] (or dp[i][j]).
  2. Relate to smaller states.
  3. Initialize bases.
  4. Loop correctly.
  5. Return the goal state.

Solution

Pattern-level skeleton only — not this problem’s exact answer. Adapt it to the statement.

Pattern templateDP

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (DP), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #139 Word Break as understood when the pattern clicks.