Skip to main content

Edit Distance

Calculate minimum edits (insert, delete, replace) to convert word1 to word2 Example: word1 = "horse", word2 = "ros" => 3 horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')

Given two strings word1 and word2, return the minimum number of single-character insertions, deletions, and replacements needed to turn word1 into word2. Each operation costs one edit. Both strings contain lowercase English letters and may be empty, with lengths up to 2000; converting an empty string to a non-empty one requires one insertion per character. For example, word1 = "horse" and word2 = "ros" require 3 edits.

Examples

You write

min_distance(word1: str, word2: str)

  1. Example 1

    Input
    word1 = "horse", word2 = "ros"
    returns
    3
  2. Example 2

    Input
    word1 = "intention", word2 = "execution"
    returns
    5

The pattern behind it

Dynamic Programming

I reach for it when

  • Brute force repeats the same subproblem.
  • You are asked for a count, a minimum or a maximum.

Say this before you type. Say the state in one sentence, then say which smaller states it reads from.

All 37 Dynamic Programming problems

Strings

I reach for it when

  • The input is text and the answer is a count, a substring or a new string.
  • You need to compare, reverse or rebuild characters.

Say this before you type. Say which array pattern the string is hiding before you touch a character.

All 51 Strings problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Minimum Edit Distancemedium