Goal simple hai: string ke har index par check karo ki kya wahan se dictionary ke kisi word se start karke end tak pahunch sakte ho. Agar same index dobara aaye, memo se cached answer le lo.
Define karo dfs(i) = “kya s[i:] ko valid dictionary words mein tod
sakte hain?”
Current suffix dekho.
Substring s[i:j] banao.
Agar word dict mein hai → dfs(j).
Same i dobara aaye toh direct answer.
i == len(s), matlab hum perfectly end tak segment
kar chuke → True.s = "applepenapple" wordDict = {"apple", "pen", "ape"}
dfs(0) se start
karenge.def wordBreak(s, wordDict):
words = set(wordDict)
memo = {}
def dfs(i):
# Reached the end successfully
if i == len(s):
return True
# Same suffix already solved
if i in memo:
return memo[i]
# Try every possible next word
for j in range(i + 1, len(s) + 1):
word = s[i:j]
if word in words and dfs(j):
memo[i] = True
return True
memo[i] = False
return False
return dfs(0)
Without memoization, alag-alag word choices kabhi same index par wapas aa sakti hain. Fir wahi suffix baar-baar solve hota hai → exponential recursion ho sakti hai.
Memo ke saath har index ka answer max ek baar properly compute hota hai. Typical interview complexity ko roughly O(n²) states/substrings ke perspective se samjho, plus Python substring creation ka cost implementation-dependent hota hai.