Word Break — LeetCode 139 Python Solution

MediumTrieMemoizationArrayHash TableStringDynamic Programming
Problem
#139
Pattern
Trie
Reading time
2 min

The 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. Note that the same word in the dictionary may be reused multiple times in the segmentation.

Example

Input
s = "leetcode", wordDict = ["leet","code"]
Output
true
Explanation
Return true because "leetcode" can be segmented as "leet code".

Python solution

Python
class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        words = set(wordDict)
        n = len(s)
        f = [True] + [False] * n
        for i in range(1, n + 1):
            f[i] = any(f[j] and s[j:i] in words for j in range(i))
        return f[n]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Trie

Store a set of words by their shared prefixes so lookups cost the length of the word. LeetCode 139. Word Break is filed here because LeetCode tags it Trie, which is the vocabulary this hub collects.

The trie guide has the Python template for the pattern and the 49 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 139. Word Break?
LeetCode 139. Word Break is rated Medium on LeetCode.
What is the time complexity of LeetCode 139. Word Break?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 139. Word Break?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 139. Word Break cover?
LeetCode 139. Word Break is tagged Trie, Memoization, Array, Hash Table, String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview