Skip to main content
Back to problems
Leetcode
Medium
Dynamic Programming
Strings
DP on Strings
Google
Microsoft
Edit Distance

Find the minimum number of single-character edits needed to transform one string into another.

Acceptance 100%
Also Available On
Other platform versions and source mappings for the same problem.
Problem Statement

Given two strings word1 and word2, compute the minimum number of operations required to change word1 into word2.

You may perform any of the following operations on a string:

  • Insert one character
  • Delete one character
  • Replace one character

Each operation costs 1. Return the smallest total cost to make the strings equal.

Input Format

  • Two strings word1 and word2.
  • Each string contains lowercase English letters in the standard formulation of the problem.

Output Format

  • Return one integer: the minimum edit distance between word1 and word2.

Constraints

  • The answer is a non-negative integer.
  • Standard interview formulation assumes strings may be empty.
  • A dynamic programming solution is expected for the general case.
Examples
Sample cases returned by the problem API.

Example 1

Input

word1 = "horse", word2 = "ros"

Output

3

Explanation

One optimal sequence is: horse -> rorse (replace 'h' with 'r') -> rose (delete 'r') -> ros (delete 'e').

Example 2

Input

word1 = "intention", word2 = "execution"

Output

5

Explanation

A minimum-cost sequence uses 5 edits to transform the first string into the second.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.