Word Break II
LeetCode 140 · कठिन · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Backtracking over prefix words; a full path is one sentence.
मैंने Word Break II (LeetCode 140) ऐसे हल किया — String DP / Word Break पैटर्न का एक कठिन प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
We need every sentence, not just a yes/no, so explore: try each dictionary word that starts at the current position, add it to the path, recurse on the rest, and undo. Reaching the end of the string records one sentence.
Approach
- 1
Dictionary in a set.
- 2
backtrack(start, path): if start == len(s), join the path into a sentence.
- 3
For each end after start, if s[start:end] is a word, append it, recurse from end, then pop.
- 4
Return all collected sentences.
मैंने कैसे हल किया
BacktrackingPythonexponential in the worst case
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
#if prefix exists in dict we should move forward to find the rest
#if cat exists - check if sanddog - sand->dog
#backrack - if cats exists - anddog - and->dog
res=[]
words_set = set(wordDict)
def backtrack(start, path):
if start == len(s):
res.append(" ".join(path))
return
for end in range(start+1,len(s)+1):
prefix = s[start:end]
if prefix in words_set:
path.append(prefix)
backtrack(end,path)
path.pop()
backtrack(0,[])
return res
Word Break II — अक्सर पूछे जाने वाले प्रश्न
Word Break II के पीछे intuition क्या है?
We need every sentence, not just a yes/no, so explore: try each dictionary word that starts at the current position, add it to the path, recurse on the rest, and undo. Reaching the end of the string records one sentence.
Word Break II (LeetCode 140) कैसे हल करें?
1. Dictionary in a set. 2. backtrack(start, path): if start == len(s), join the path into a sentence. 3. For each end after start, if s[start:end] is a word, append it, recurse from end, then pop. 4. Return all collected sentences.
Word Break II की time और space complexity क्या है?
Time: O(2ⁿ) worst case (output can be exponential)। Space: O(n) recursion। (Accepted approach: Backtracking।)
Word Break II में आम गलतियाँ क्या हैं?
Pop after recursing or later sentences inherit stale words. For heavy inputs, memoising sentences per start index avoids rework.