Faaez Razeen

Word Break

  • 2 min read
  • LC-Medium
  • Dynamic Programming

3 years ago

Solution

def wordBreak(self, s: str, wordDict: List[str]) -> bool: word_dict = set(wordDict) memo = {} def dfs(i, cur_word): if i in memo: return memo[i] if i == len(s): if cur_word in word_dict: return True print('bruh', cur_word) return False if cur_word in word_dict: cur_word = '' memo[i] = dfs(i + 1, cur_word + s[i]) return memo[i] return dfs(0, '')

Solution (Top-down Memoization)

TimeSpaceExplanation
O()O()
def wordBreak(self, s: str, wordDict: List[str]) -> bool: @cache def dp(i): if i >= len(s): return True for word in wordDict: if s[i : i + len(word)] == word and dp(i + len(word)): return True return False return dp(0) # Another implementation without the @cache decorator def wordBreak(self, s: str, wordDict: List[str]) -> bool: memo = {} def dfs(i): if i >= len(s): return True if i not in memo: memo[i] = False for word in wordDict: if s[i : i + len(word)] == word and dfs(i + len(word)): memo[i] = True return memo[i] return dfs(0)