# Levenshtein Distance

![](/files/MXCYjSelFGqnch2imMxl)

* n x m, n x m

```jsx
function levenshteinDistance(str1, str2) {
  const edits = new Array(str1.length + 1);
  edits[0] = new Array(str2.length + 1).fill(1).map((v, idx) => idx)
  for (let i = 1; i < str1.length + 1; i++ ) {
    edits[i] = new Array(str2.length + 1).fill(0);
    edits[i][0] = i;
  }

  for (let i = 1; i < str1.length + 1; i++) {
    for (let j = 1; j < str2.length + 1; j++) {
      const c1 = str1[i - 1];
      const c2 = str2[j - 1];

      if (c1 === c2) {
        edits[i][j] = edits[i - 1][j - 1];
        continue;
      }

      edits[i][j] = Math.min(edits[i - 1][j], edits[i][j - 1], edits[i - 1][j - 1]) + 1;
    }
  }
  console.log(edits)

  return edits[str1.length][str2.length];
}

// Do not edit the line below.
exports.levenshteinDistance = levenshteinDistance;
```

* n x m, min(m, n)

```jsx
function levenshteinDistance(str1, str2) {
  let small = str1;
  let big = str2;
  if (small.length > big.length) {
    const temp = small;
    small = big;
    big = temp;
  }

  // set up two arrays 
  const evenEdits = new Array(small.length + 1);
  for (let i = 0; i < evenEdits.length; i++) {
    evenEdits[i] = i;
  }
  const oddEdits = new Array(small.length + 1).fill(0);

  let previousEdits = [0]; // when empty
  let currentEdits = [0]; // when empty
  
  for (let i = 1; i < big.length + 1; i++) {
    // swap edits array
    if (i % 2 === 1) {
      previousEdits = evenEdits;
      currentEdits = oddEdits;
    } else {
      previousEdits = oddEdits;
      currentEdits = evenEdits;
    }

    currentEdits[0] = i;
    
    for (let j = 1; j < small.length + 1; ++j) {
      if (big[i - 1] === small[j - 1]) {
        currentEdits[j] = previousEdits[j - 1];
      } else {
        currentEdits[j] = 1 + Math.min(currentEdits[j - 1], previousEdits[j], previousEdits[j - 1])
      }
    }
    
  }
  
  return currentEdits[small.length];
}

// Do not edit the line below.
exports.levenshteinDistance = levenshteinDistance;
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/levenshtein-distance.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
