https://leetcode.com/problems/word-break/
I wrote this O(n^2) dp solution in the interview as the following (bug free). The interviewer was quite unhappy. I got rejected for this. He mentioned that he expected a solution better than O(n^2) while I did not know how. I searched online and couldn't find one so far.
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
wordDict = set(wordDict)
n = len(s)
dp = [0] * (n + 1)
dp[0] = 1
for i, _ in enumerate(s):
for j in range(i, -1, -1):
if s[j: i + 1] in wordDict and dp[j] == 1:
dp[i+1] = 1
break
return dp[n]Result: Rejected.