Java String Program · S68
Word Break II in Java
Instead of asking whether a string can be split into words, list every possible split. Memoising the sentences for each start position avoids recomputing shared suffixes.
Problem Statement
Given a string and a dictionary of words, return every sentence that can be formed by splitting the string into dictionary words, with words separated by single spaces.
Words may be reused. Return the sentences in alphabetical order; if no split exists, return an empty list.
Input/Output Examples
"javabytechie", [java, by, tech, techie, ie]Output[java by tech ie, java by techie]Explanation: the end can be split as techie or as tech + ie."icecreamcone", [ice, cream, icecream, cone]Output[ice cream cone, icecream cone]Explanation: icecream can be one word or two."bookshelf", [book, shelves, self]Output[]Explanation: shelf is not in the dictionary.Visual Explanation
- Start 0wordsjavaonly java matches
- Start 4wordsbyonly by matches
- Start 6wordstechtechietwo choices
- Start 10wordsieafter tech sentences(12) = [""]
- Done2 sentences
"javabytechie": from each start position, every matching dictionary word leads to a later start. Position 6 has two choices (amber), which produce the two sentences.The sentences for a start position depend only on that position, not on how you got there. Caching them means each position is expanded once, even when many earlier splits lead to it.
Approaches
Both approaches list every sentence. The first caches sentences per position; the second first checks which positions can reach the end, then backtracks only through those.
Approach 1: Memoised DFS (Recommended)
Idea: solve(start) returns all sentences for s[start..]: for each word that matches at start, prepend it to every sentence of solve(start + word.length()).
- At the end of the string, return a list with one empty sentence.
- Return the cached list if this start was solved before.
- For each matching word, combine it with every sentence from the next position.
- Cache and return the list; sort the final result.
Time: O(n² + S) · Space: O(n + S). S is the total size of all sentences.
Approach 2: Backtracking Pruned by DP
Idea: compute canFinish[i] (can s[i..] be split at all?) from right to left, then backtrack only into positions where it is true.
- Fill
canFinishfrom the end of the string to the start. - If
canFinish[0]is false, return an empty list immediately. - Backtrack from 0, choosing words that lead to a position with
canFinishtrue. - Join the path into a sentence at the end of the string.
Time: O(n² + S) · Space: O(n). Plus the output.
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Memoised DFS (Recommended)
Shared suffixes are computed once and reused, which matters for strings with many overlapping words.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class WordBreakAllMemo {
// sentences(start) = every way to split s[start..]; cached so each start is solved once
static List<String> wordBreak(String s, List<String> dictionary) {
List<String> result = new ArrayList<>(solve(s, 0, Set.copyOf(dictionary), new HashMap<>()));
Collections.sort(result);
return result;
}
private static List<String> solve(String s, int start, Set<String> words, Map<Integer, List<String>> memo) {
if (memo.containsKey(start)) {
return memo.get(start);
}
List<String> sentences = new ArrayList<>();
if (start == s.length()) {
sentences.add("");
}
for (String w : words) {
if (s.startsWith(w, start)) {
for (String rest : solve(s, start + w.length(), words, memo)) {
sentences.add(rest.isEmpty() ? w : w + " " + rest);
}
}
}
memo.put(start, sentences);
return sentences;
}
public static void main(String[] args) {
Object[][] cases = {
{"javabytechie", List.of("java", "by", "tech", "techie", "ie")},
{"icecreamcone", List.of("ice", "cream", "icecream", "cone")},
{"bookshelf", List.of("book", "shelves", "self")}};
for (Object[] c : cases) {
@SuppressWarnings("unchecked")
List<String> dict = (List<String>) c[1];
System.out.println("\"" + c[0] + "\" -> " + wordBreak((String) c[0], dict));
}
}
}
"javabytechie" -> [java by tech ie, java by techie] "icecreamcone" -> [ice cream cone, icecream cone] "bookshelf" -> []
Time complexity: O(n² + S) · Space complexity: O(n + S).
Approach 2: Backtracking Pruned by DP
The DP pass guarantees that every branch the backtracking enters leads to at least one sentence.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class WordBreakAllPruned {
// canFinish[i] says whether s[i..] can be split at all; backtracking never enters a dead end
static List<String> wordBreak(String s, List<String> dictionary) {
Set<String> words = Set.copyOf(dictionary);
int n = s.length();
boolean[] canFinish = new boolean[n + 1];
canFinish[n] = true;
for (int i = n - 1; i >= 0; i--) {
for (String w : words) {
if (s.startsWith(w, i) && canFinish[i + w.length()]) {
canFinish[i] = true;
break;
}
}
}
List<String> result = new ArrayList<>();
if (canFinish[0]) {
build(s, 0, words, canFinish, new ArrayList<>(), result);
}
Collections.sort(result);
return result;
}
private static void build(String s, int start, Set<String> words, boolean[] canFinish,
List<String> path, List<String> result) {
if (start == s.length()) {
result.add(String.join(" ", path));
return;
}
for (String w : words) {
int end = start + w.length();
if (s.startsWith(w, start) && canFinish[end]) {
path.add(w);
build(s, end, words, canFinish, path, result);
path.remove(path.size() - 1);
}
}
}
public static void main(String[] args) {
Object[][] cases = {
{"javabytechie", List.of("java", "by", "tech", "techie", "ie")},
{"icecreamcone", List.of("ice", "cream", "icecream", "cone")},
{"bookshelf", List.of("book", "shelves", "self")}};
for (Object[] c : cases) {
@SuppressWarnings("unchecked")
List<String> dict = (List<String>) c[1];
System.out.println("\"" + c[0] + "\" -> " + wordBreak((String) c[0], dict));
}
}
}
"javabytechie" -> [java by tech ie, java by techie] "icecreamcone" -> [ice cream cone, icecream cone] "bookshelf" -> []
Time complexity: O(n² + S) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Memoised DFS | O(n² + S) | O(n + S) |
| Backtracking Pruned by DP | O(n² + S) | O(n) |
Here n is the length of the string and S the total length of all output sentences. The number of sentences can be exponential, so the running time is bounded by the size of the answer.
Interview Tips and Recommended Approach
- Warn about the output size. A string like
"aaaa…"with wordsa,aa,aaahas exponentially many sentences. - Check feasibility first. Running the yes/no Word Break DP avoids exploring hopeless branches.
- Cache by position. The remaining sentences depend only on where you are in the string.
- Sort if the order matters. Iterating over a
Setgives no fixed order.
Recommended Approach: Memoised DFS
Why: it computes the sentences for each position once and reuses them, which is the key to handling strings with many overlapping words efficiently.