00:00

Problem Statement

Input/Output Examples

Visual Explanation

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.

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.

Complexity Analysis

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 words a, aa, aaa has 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 Set gives 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.