← DSA
MEDIUM

Word Break

PracticeNeetCode ↗LeetCode ↗

Given a string s and a dictionary wordDict, return true if s can be split into a sequence of one or more dictionary words. Words may be reused any number of times.

Example

Input s = "leetcode", wordDict = ["leet","code"]
Output true

Key Pointers

Step-by-Step Analysis

  1. Convert wordDict to a set for O(1) lookups.
  2. Create dp, a boolean array of size len(s) + 1, with dp[0] = True (the empty prefix is trivially segmented).
  3. For each end position i from 1 to len(s): for each start position j from 0 to i − 1, if dp[j] is True and s[j:i] is a dictionary word, set dp[i] = True and stop checking further j values for this i.
  4. Return dp[len(s)].

Complexity

Time: O(n²) — Space: O(n)

Code

def wordBreak(s: str, wordDict: list[str]) -> bool:
    words = set(wordDict)
    dp = [False] * (len(s) + 1)
    dp[0] = True

    for i in range(1, len(s) + 1):
        for j in range(i):
            if dp[j] and s[j:i] in words:
                dp[i] = True
                break

    return dp[len(s)]

Code Explanation

How the solution above works, piece by piece.

  1. dp[i] answers: can the first i characters be split into dictionary words? dp[0] = True (the empty prefix).
  2. For each end i, try every split point j: if s[:j] can be split (dp[j]) and s[j:i] is a word, then s[:i] can be too.
  3. break as soon as one split works.
  4. The answer is dp[len(s)].
  5. O(n²) substring checks (plus the cost of slicing), O(n) space.

Visual Walkthrough

Running it on s = "leetcode", wordDict = ["leet", "code"]:

Word break table for leetcodeleetcodeT0F1F2F3T4F5F6F7T8dp[i] = can s[:i] be split into words?"leet": dp[0] → dp[4]"code": dp[4] → dp[8]
dp[i] is true when some earlier split point j is true and s[j:i] is a dictionary word. dp[4] is true because of "leet", and dp[8] because dp[4] is true and "code" follows.
Trueleetcode

Video Explanation

NeetCode — Dynamic Programming, LeetCode 139