Splitting a String into Words with a Dictionary: The Word Break Problem

How the word break problem works, what dictionary-based segmentation changes in text, where it fails, and when to keep the original string.

The word break problem asks whether a string with no spaces can be split into a sequence of words that all appear in a given dictionary. It is a standard dynamic programming exercise, often listed as Word Break I in coding practice sets, and it is also a simplified model of a real text task: recovering word boundaries in text that lacks them. This review explains what the transformation does and does not change, where its output can mislead, and when you are better off keeping the original text.

Is dictionary-based word splitting suitable for your use?

Dictionary segmentation is a good fit when you control the vocabulary and the input is drawn from it: hashtags or identifiers built from known terms, compound product codes, concatenated keywords, or learning and interview practice. Its main benefit is that it never alters the characters themselves; it only decides where boundaries go, so the original string can always be recovered by removing the inserted separators.

The decisive tradeoff is ambiguity. A dictionary can confirm that a split is possible, but it cannot tell which split the author meant. If the input contains words outside the dictionary, names, typos or mixed languages, the method either fails outright or produces a valid-looking but wrong split.

Keep plain, unsegmented text (or store it alongside the segmented version) when exact meaning matters, when the dictionary is incomplete for the domain, when the text is legal, medical or otherwise high-stakes, or when the language already uses spaces and a standard word-boundary algorithm is more appropriate.

What the word break problem actually asks

In its usual form, Word Break I takes a string s and a list of dictionary words and returns true or false: can s be segmented into one or more dictionary words, with words allowed to repeat? It does not return the split itself. A related variant, often called Word Break II, returns every possible segmentation as space-separated sentences.

Commonly used illustrative inputs show the behavior:

  • "leetcode" with the dictionary ["leet", "code"] returns true: "leet code".
  • "applepenapple" with ["apple", "pen"] returns true: "apple pen apple", reusing "apple".
  • "catsandog" with ["cats", "dog", "sand", "and", "cat"] returns false: "cats and" or "cat sand" both leave the unmatched remainder "og".
Variant | Output | Typical cost driver
Word Break I (decision) | true or false | Number of positions times candidate word lengths
One segmentation | A single split, if any exists | Same as decision, plus back-pointers to rebuild the split
Word Break II (all segmentations) | Every valid split | Size of the output, which can grow exponentially

How the standard solution works

The common approach marks which prefixes of the string can be segmented. Position 0 (the empty prefix) is segmentable by definition. Position i is segmentable if there is an earlier segmentable position j such that the substring from j to i is a dictionary word. The answer is whether the final position is segmentable. Limiting j to positions no farther back than the longest dictionary word avoids pointless checks.

def word_break(s, word_dict):
    words = set(word_dict)
    max_len = max((len(w) for w in words), default=0)
    n = len(s)
    dp = [False] * (n + 1)
    dp[0] = True
    for i in range(1, n + 1):
        for j in range(max(0, i - max_len), i):
            if dp[j] and s[j:i] in words:
                dp[i] = True
                break
    return dp[n]

With n as the string length and L as the longest word length, this performs on the order of n times L dictionary lookups, and each lookup hashes a substring of up to L characters. Memoized recursion and breadth-first search over positions reach the same result; a trie can replace the set when many words share prefixes. If you need an actual split rather than a yes/no answer, record the j that made each position true and walk back from the end.

def one_segmentation(s, word_dict):
    words = set(word_dict)
    n = len(s)
    prev = [None] * (n + 1)
    prev[0] = 0
    for i in range(1, n + 1):
        for j in range(i):
            if prev[j] is not None and s[j:i] in words:
                prev[i] = j
                break
    if prev[n] is None:
        return None
    parts, i = [], n
    while i > 0:
        parts.append(s[prev[i]:i])
        i = prev[i]
    return " ".join(reversed(parts))

Listing all segmentations is a different scale of problem. A string of repeated letters with a dictionary containing "a", "aa" and "aaa" has a number of valid splits that grows exponentially with length, so Word Break II is only practical for short inputs or when results are streamed or capped.

What the transformation changes, and what "word break" can also mean

Dictionary segmentation changes stored text only by inserting separators (usually spaces) or by producing a list of tokens. No characters are reversed, substituted or restyled. Removing the separators restores the original string exactly, provided no normalization or case folding was applied along the way.

The phrase "word break" is used for several unrelated things, and mixing them up is a common source of confusion:

  • The algorithmic word break problem: deciding whether, and how, a string splits into dictionary words. It changes the stored text if you save the result.
  • The CSS word-break property: a presentation setting that controls where a browser may wrap lines inside words. It changes only how text is displayed; the underlying characters, copy/paste output and search index are unaffected.
  • Unicode word boundaries: the rules in the Unicode text segmentation standard (UAX #29) that software uses to find word edges for selection, cursor movement and searching. These rely on character properties, not a custom dictionary, and they do not insert anything into the text.

Does the split preserve meaning?

Only partially. A dictionary can certify that a split uses real words, not that it uses the intended ones. "catsanddog" with a dictionary containing "cat", "cats", "and", "sand" and "dog" splits as both "cats and dog" and "cat sand dog". The decision version reports true without revealing that ambiguity, and the single-split version returns whichever option its loop order finds first. Neither reflects meaning.

Practical systems that segment unspaced text, such as tokenizers for languages written without spaces, usually add word frequencies or statistical models to rank competing splits. The plain word break algorithm has no such ranking, so treat its output as a candidate that may need review whenever more than one split exists.

Character-level pitfalls: normalization, combining marks and emoji

The textbook version assumes one character per index. Real text breaks that assumption in ways that affect both matching and output quality.

  • Normalization: an accented letter can be stored as one precomposed code point or as a base letter plus a combining mark. If the input and the dictionary use different forms, identical-looking words will not match. Normalize both to the same form (for example NFC) before comparing.
  • Combining marks: if the dictionary contains a bare base letter or a word ending in one, the algorithm can match it and leave a combining accent stranded at the start of the next token. Restricting split points to grapheme cluster boundaries prevents this.
  • Multi-code-point emoji: emoji built from several code points (skin-tone modifiers, joined family or flag sequences) can be cut apart by index-based splitting in the same way, producing broken or substituted symbols.
  • Index units: some languages index strings by UTF-16 code units rather than code points, so a split can land inside a surrogate pair. Check what your language's slicing operation counts.
  • Case: matching is case-sensitive unless you fold case first; if you do, keep the original string to restore the author's capitalization in the output.

Will the result stay readable and usable after copying or sharing?

Because the output is ordinary text with spaces, it copies, pastes and searches like any other plain text, and it generally reads better than the unspaced original: screen readers can announce separate words instead of attempting one long run, and search tools can match individual terms. These are general properties of space-separated plain text; no tests of specific applications or assistive technologies were available for this review, so verify behavior in the destination you care about.

The usability risks come from the segmentation itself rather than from the format. A wrong split reads fluently and can be indexed, quoted or translated as if it were correct, which makes errors harder to spot than an obviously unspaced string. Splits that leave stray combining marks or broken emoji sequences can display as empty boxes or detached accents in some fonts. Where the segmented version will be shared or reused, keep the original string available so it can be checked or re-segmented.

If your goal is only to stop long unspaced strings from overflowing a layout, a display-level setting such as CSS word-break or overflow-wrap is the lighter option: it changes how lines wrap without altering the text that gets copied or indexed.

Gaps in this review

No benchmark measurements, tool-specific feature lists or destination tests were supplied, so this article describes the algorithm and general Unicode behavior rather than the performance or accuracy of any particular segmentation tool. Results for real text depend heavily on dictionary coverage and on how a given implementation handles normalization and grapheme boundaries; confirm those details in the documentation of whatever tool or library you use.