Solving Leetcode Interviews in Seconds with AI: Word Break
Introduction
In this blog post, we will explore how to solve the LeetCode problem "139" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 1: Input: s = "leetcode", wordDict = ["leet","code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code". Example 2: Input: s = "applepenapple", wordDict = ["apple","pen"] Output: true Explanation: Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word. Example 3: Input: s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] Output: false Constraints: 1 <= s.length <= 300 1 <= wordDict.length <= 1000 1 <= wordDict[i].length <= 20 s and wordDict[i] consist of only lowercase English letters. All the strings of wordDict are unique.
Explanation
Here's the solution to the word break problem:
- Dynamic Programming: Use a boolean array
dpwheredp[i]represents whether the substrings[0:i]can be segmented. - Iteration: Iterate through the string
sand for each indexi, check if any word inwordDictcan form the suffixs[j:i]and ifdp[j]is true. Base Case:
dp[0]is initialized toTruebecause an empty string can always be segmented.Runtime Complexity: O(n*m*k) where n is the length of s, m is the number of words in wordDict, and k is the average length of a word in wordDict. Storage Complexity: O(n)
Code
def wordBreak(s: str, wordDict: list[str]) -> bool:
"""
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.
Args:
s (str): The input string.
wordDict (list[str]): The dictionary of words.
Returns:
bool: True if s can be segmented, False otherwise.
"""
n = len(s)
dp = [False] * (n + 1)
dp[0] = True
for i in range(1, n + 1):
for word in wordDict:
if i >= len(word) and s[i - len(word):i] == word:
dp[i] = dp[i] or dp[i - len(word)]
return dp[n]