MediumNo. 0139

Word Break — LeetCode 139 Python Solution

Pattern
Trie
Topics
Trie, Memoization, Array, Hash Table, String, Dynamic Programming
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

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.

Free to download. Check it runs on your machine, then pick a plan.