Concatenated Words
LeetCode 472 · ಕಠಿಣ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Word Break per word, with the prefix limited to a strict prefix so the word can't match itself.
ನಾನು Concatenated Words (LeetCode 472) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — String DP / Word Break ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಕಠಿಣ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Run Word Break on each word against the set of all words. A word counts if it can be split into at least two pieces that are themselves in the list — so its first cut must leave a proper prefix, never the whole word.
Approach
- 1
Put every word into a set.
- 2
dfs(word): try each strict prefix; succeed if the prefix is a word and the suffix is either a word or itself breakable.
- 3
lru_cache shares results across words (suffixes repeat a lot).
- 4
Collect every word for which dfs returns True.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Word Break per word + memoPythonO(N·L²) time
from functools import lru_cache
class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
words_set = set(words)
res=[]
@lru_cache(maxsize=None)
def dfs(word):
if not word:
return True
for end in range(1,len(word)):
prefix = word[:end]
suffix = word[end:]
if (prefix in words_set and suffix in words_set) or (prefix in words_set and dfs(suffix)):
return True
return False
for word in words:
if dfs(word)==True:
res.append(word)
return resConcatenated Words — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Concatenated Words ಹಿಂದಿನ intuition ಏನು?
Run Word Break on each word against the set of all words. A word counts if it can be split into at least two pieces that are themselves in the list — so its first cut must leave a proper prefix, never the whole word.
Concatenated Words (LeetCode 472) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Put every word into a set. 2. dfs(word): try each strict prefix; succeed if the prefix is a word and the suffix is either a word or itself breakable. 3. lru_cache shares results across words (suffixes repeat a lot). 4. Collect every word for which dfs returns True.
Concatenated Words ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(N · L²) roughly. Space: O(N · L) for the cache. (Accepted approach: Word Break per word + memo.)
Concatenated Words ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Using range(1, len(word)+1) would let a word match itself and return every word. An empty string in the input should not make everything concatenated.