Skip to lesson

Decode ways and word break

String partitioning problems apply dynamic programming across prefix boundaries to resolve parsing ambiguities and rebuild valid sentences.

Decode Ways: Parsing numerical digit sequences

Decode Ways maps characters 'A' through 'Z' to numeric values 1 through 26. Given a string of digits, count all valid decodings. Ambiguities emerge because a digit can decode alone or group with its predecessor.

Step by step

Step 1 of 3

Array: 1, 1, 0, 0.
idx
1
ways
1
Input '226'. Base case dp[0]=1. Index 1: digit '2' is valid, dp[1]=1.

Example 1 · Decode Ways String Partitioning

DecodeWays.javaJava
public class DecodeWays {    public static int numDecodings(String s) {        if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0;        int n = s.length();        int[] dp = new int[n + 1];        dp[0] = 1;        dp[1] = 1;
        for (int i = 2; i <= n; i++) {            char one = s.charAt(i - 1);            if (one != '0') {                dp[i] += dp[i - 1];            }            int two = Integer.parseInt(s.substring(i - 2, i));            if (two >= 10 && two <= 26) {                dp[i] += dp[i - 2];            }        }        return dp[n];    }
    public static void main(String[] args) {        System.out.println("Decodings for 12: " + numDecodings("12"));        System.out.println("Decodings for 226: " + numDecodings("226"));        System.out.println("Decodings for 06: " + numDecodings("06"));    }}
Output
Decodings for 12: 2
Decodings for 226: 3
Decodings for 06: 0

What this code does

  • Single digit s[i-1] contributes dp[i-1] if it is not character '0'.
  • Two-digit slice contributes dp[i-2] if its numerical value lies between 10 and 26.
  • String '06' starts with '0' and returns 0 because leading zeros are invalid.

Define dp[i] as the number of ways to decode the prefix of length i. Base case dp[0] equals 1, representing an empty prefix. If single character s[i-1] is not '0', it forms a valid digit, so add dp[i-1]. If the two-character slice s[i-2..i-1] forms a value between 10 and 26, add dp[i-2]. Leading zeros inside multi-digit groups like '06' are strictly invalid. If a zero cannot be paired with a preceding 1 or 2, decoding terminates with 0.

Word Break: Segmenting strings with dictionary sets

Word Break determines whether a target string can segment into space-separated dictionary words. Naively testing all word combinations creates an exponential recursive branching tree. Dynamic programming resolves prefixes sequentially to eliminate redundant partition scans.

Example 2 · Word Break Dictionary Segmentation

WordBreak.javaJava
import java.util.Arrays;import java.util.HashSet;import java.util.List;import java.util.Set;
public class WordBreak {    public static boolean wordBreak(String s, List<String> wordDict) {        Set<String> dict = new HashSet<>(wordDict);        int maxLen = 0;        for (String w : wordDict) maxLen = Math.max(maxLen, w.length());
        int n = s.length();        boolean[] dp = new boolean[n + 1];        dp[0] = true;
        for (int i = 1; i <= n; i++) {            for (int j = Math.max(0, i - maxLen); j < i; j++) {                if (dp[j] && dict.contains(s.substring(j, i))) {                    dp[i] = true;                    break;                }            }        }        return dp[n];    }
    public static void main(String[] args) {        System.out.println(wordBreak("leetcode", Arrays.asList("leet", "code")));        System.out.println(wordBreak("cloudpencloud", Arrays.asList("cloud", "pen")));        System.out.println(wordBreak("catsandog", Arrays.asList("cats", "dog", "sand", "and", "cat")));    }}
Output
true
true
false

What this code does

  • State dp[i] is true if prefix of length i can be completely segmented.
  • Inner loop j checks substrings backwards, bounded by maxLen to optimize runtime.
  • Strings 'leetcode' and 'cloudpencloud' succeed, whereas 'catsandog' returns false.

Define boolean dp[i] indicating whether the prefix of length i is segmentable. Initialize dp[0] to true, representing the trivial empty prefix. To evaluate index i, iterate over all possible partition split points j before i. If dp[j] is true and dictionary set contains s.substring(j, i), mark dp[i] true. Prune the inner loop by restricting j to lengths within the maximum dictionary word length. This bounds execution to O(n * maxWordLength) rather than quadratic O(n^2).

Rebuilding answers and generating sentences

Many interview questions require producing actual segmented sentences rather than just boolean outcomes. Once the boolean table confirms a valid segmentation exists, use backtracking to rebuild words. Checking the DP table during backtracking prunes dead ends before recursive descent occurs.

Example 3 · Word Break Sentence Reconstruction

WordBreakReconstruction.javaJava
import java.util.*;
public class WordBreakReconstruction {    private static List<String> dfs(String s, Set<String> dict, Map<String, List<String>> memo) {        if (memo.containsKey(s)) return memo.get(s);        List<String> res = new ArrayList<>();        if (s.isEmpty()) {            res.add("");            return res;        }
        for (String word : dict) {            if (s.startsWith(word)) {                List<String> sub = dfs(s.substring(word.length()), dict, memo);                for (String sentence : sub) {                    res.add(word + (sentence.isEmpty() ? "" : " ") + sentence);                }            }        }        memo.put(s, res);        return res;    }
    public static List<String> wordBreak(String s, List<String> wordDict) {        Set<String> dict = new HashSet<>(wordDict);        Map<String, List<String>> memo = new HashMap<>();        List<String> ans = dfs(s, dict, memo);        Collections.sort(ans);        return ans;    }
    public static void main(String[] args) {        List<String> r1 = wordBreak("catsanddog", Arrays.asList("cat", "cats", "and", "sand", "dog"));        for (String sent : r1) System.out.println(sent);    }}
Output
cat sand dog
cats and dog

What this code does

  • Memoization caches generated sentences for each suffix string.
  • Subproblem results combine with the matching prefix word using space delimiters.
  • Outputs show both valid sentences sorted alphabetically.

Alternatively, top-down memoized depth-first search can return lists of valid sentences directly. For each suffix starting at index i, test dictionary prefixes and append subproblem sentence lists. Cache computed sentence lists in a HashMap keyed by index to prevent exponential explosion. Always verify that a valid path exists before constructing sentences on huge inputs. Running boolean Word Break first prevents memory exhaustion on strings with billions of solutions.

Next step

Check your understanding

10 quick questions