Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 15-edit-distance-eval-similarity.jsJavaScript

Levenshtein Edit Distance and Normalised Similarity for Eval Scoring

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

Levenshtein Edit Distance and Normalised Similarity for Eval Scoring

Problem: Evals often grade model output against a reference with a fuzzy
string score. Implement:
- `levenshtein(a, b)`: the minimum number of single-character insertions,
  deletions and substitutions that turn a into b.
- `similarity(a, b)`: 1 - distance / max(|a|, |b|), a score in [0, 1]
  (two empty strings score 1).
- `bestMatch(output, references)`: the reference with the highest
  similarity, as `{ reference, score }` (first one wins ties).

Constraints:
- 0 <= |a|, |b| <= 10^4

Example:
  levenshtein("kitten", "sitting") -> 3
  similarity("kitten", "sitting") -> 1 - 3/7 = 0.571...

Approach: Classic dynamic programming where dp[i][j] is the distance
between the first i characters of a and the first j of b:
dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (a_i != b_j)).
Only the previous row is needed, and iterating over the shorter string as
the row keeps memory small. Time O(|a| * |b|), space O(min(|a|, |b|)).
@param {string} a
@param {string} b
@returns {number}
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.