Edit Distance
LeetCode 72 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
dist(i, j) = dist(i-1, j-1) if chars match else 1 + min(insert, delete, replace).
ನಾನು Edit Distance (LeetCode 72) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — String DP / Word Break ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Compare the last characters of the two prefixes. If they match, no edit is needed for them. If not, the last operation was an insert, a delete or a replace — each shrinks the problem by one character in one or both words. Take the cheapest and add one.
Approach
- 1
State: dfs(i, j) = edits to turn word1[:i] into word2[:j].
- 2
If one prefix is empty, the answer is the other's length.
- 3
Matching last characters: recurse on (i-1, j-1).
- 4
Otherwise: insert → (i, j-1), delete → (i-1, j), replace → (i-1, j-1); 1 + the min.
- 5
lru_cache makes it O(m·n).
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Recursion + memoPythonO(m·n) time · O(m·n) space
from functools import lru_cache
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
@lru_cache(maxsize=None)
def dfs(word1index,word2index):
if word1index==0:
return word2index
if word2index==0:
return word1index
if word1[word1index-1]==word2[word2index-1]:
return dfs(word1index-1,word2index-1)
else:
insertOps = dfs(word1index,word2index-1)
deleteOps = dfs(word1index-1,word2index)
replaceOps = dfs(word1index-1,word2index-1)
return 1+min(insertOps,deleteOps,replaceOps)
return dfs(len(word1),len(word2))
Edit Distance — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Edit Distance ಹಿಂದಿನ intuition ಏನು?
Compare the last characters of the two prefixes. If they match, no edit is needed for them. If not, the last operation was an insert, a delete or a replace — each shrinks the problem by one character in one or both words. Take the cheapest and add one.
Edit Distance (LeetCode 72) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. State: dfs(i, j) = edits to turn word1[:i] into word2[:j]. 2. If one prefix is empty, the answer is the other's length. 3. Matching last characters: recurse on (i-1, j-1). 4. Otherwise: insert → (i, j-1), delete → (i-1, j), replace → (i-1, j-1); 1 + the min. 5. lru_cache makes it O(m·n).
Edit Distance ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(m · n). Space: O(m · n). (Accepted approach: Recursion + memo.)
Edit Distance ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Using lengths (1-based) as indices keeps the empty-string base cases simple — remember to read word[i-1].