Bird
0
0

Identify the bug in this Levenshtein distance initialization code snippet:

medium📝 Debug Q6 of 15
NLP - Text Similarity and Search
Identify the bug in this Levenshtein distance initialization code snippet:
def lev_dist(s, t):
    dp = [[0]*(len(t)) for _ in range(len(s))]
    for i in range(len(s)):
        dp[i][0] = i
    for j in range(len(t)):
        dp[0][j] = j
    # rest omitted
AThe dp matrix size should be (len(s)+1) x (len(t)+1) to include empty prefixes
BThe loops initializing dp should start from 1 instead of 0
CThe dp matrix should be initialized with ones instead of zeros
DThe code incorrectly assigns dp[0][0] twice
Step-by-Step Solution
Solution:
  1. Step 1: Check dp matrix size

    It is initialized as len(s) x len(t), but it must be (len(s)+1) x (len(t)+1) to handle empty string cases.
  2. Step 2: Understand initialization loops

    Loops correctly assign first row and column, but indices go out of range if matrix is smaller.
  3. Step 3: Analyze options

    The dp matrix size should be (len(s)+1) x (len(t)+1) to include empty prefixes correctly identifies the size bug. Others are incorrect or irrelevant.
  4. Final Answer:

    Option A -> Option A
  5. Quick Check:

    Matrix must include empty string row/column. [OK]
Quick Trick: Matrix size must be lengths + 1 for empty prefixes [OK]
Common Mistakes:
MISTAKES
  • Not adding +1 to matrix dimensions
  • Starting loops at wrong indices

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NLP Quizzes