Chaturmind
LearnDSASystem DesignDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.

DSA›Dynamic Programming›Word Break
MediumDynamic Programming

Word Break

dynamic-programmingstringtrie

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.

Examples

Example 1

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

Output: true

Explanation: "leet code"

Example 2

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

Output: true

Explanation: "apple pen apple"

Example 3

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

Output: false

Constraints

  • •1 <= s.length <= 300
  • •1 <= wordDict.length <= 1000

Hints

Hint 1

The brute-force recursive idea: at each position, try every possible next word from the dictionary and recurse — correct, but the same suffix of the string gets re-examined across many different branches.

Hint 2

dp[i] = true if s[0..i] can be segmented — built bottom-up so each prefix length is resolved exactly once, not recomputed per branch.

Hint 3

For each i, dp[i] is true if some earlier dp[j] is true AND s[j..i] is itself a dictionary word — trying every valid split point j.

Solutions

public boolean wordBreakBruteForce(String s, List<String> wordDict) {
    Set<String> dict = new HashSet<>(wordDict);
    return helper(s, 0, dict);
}
private boolean helper(String s, int start, Set<String> dict) {
    if (start == s.length()) return true;
    for (int end = start + 1; end <= s.length(); end++) {
        if (dict.contains(s.substring(start, end)) && helper(s, end, dict)) {
            return true;
        }
    }
    return false;
}

Time: O(2^n) worst case · Space: O(n) recursion depth