Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Home
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets

Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
Jobs
Learning
Career Tools
Talentd Logo
Talentd#1 Freshers Platform
DSA Corner
DashboardQuestionsTopicsCompaniesSheets
Back to Problems

72. Edit Distance

Medium57.7% Acceptance
StringDynamic Programming
Asked by:
A
Amazon
LinkedIn
ProblemSolutions (5)VideosCompanies (8)Notes

Problem Statement

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

  • Insert a character
  • Delete a character
  • Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

Constraints:

  • 0 <= word1.length, word2.length <= 500
  • word1 and word2 consist of lowercase English letters.
Talentd Logo
Talentd

Your trusted platform to ace any job interviews, craft the perfect resumes, and land your dream jobs.

P
Featured on
Product Hunt
▲455
All services are online

Products

  • Resume Review
  • Company Prep Pack
  • DSA Corner
  • Jobs
  • Internships
  • Fresher Jobs
  • Roadmaps
  • Tax Calculator

Resources

  • Articles
  • DRDO Internships

Support

  • Contact Us

DSA & Interview Prep

  • DSA Questions
  • DSA Sheets
  • Company Questions
  • Topics

Company

  • Companies Hiring
  • About
  • Contact
  • Advertisement

Legal

  • Privacy Policy
  • Terms & Conditions
  • Refund Policy
  • Delivery Policy

Popular Skills

Browse All Skills →

Popular Tags

Browse All Tags →

© 2025 Talentd.in - All rights reserved

Privacy PolicyTerms & Conditions
L
M
Microsoft
G
Google
A
Apple
+3

Approach

The Edit Distance problem asks for the minimum number of operations required to convert one string into another. Allowed operations typically include insert, delete, and replace. Because many subproblems repeat when comparing prefixes of the two strings, this problem is best approached using Dynamic Programming.

A common strategy is to build a dp table where dp[i][j] represents the minimum operations required to convert the first i characters of one string into the first j characters of the other. By comparing characters and considering the three possible operations, you iteratively fill the table from smaller prefixes to larger ones. Base cases handle transformations involving empty prefixes.

This approach efficiently reuses previously computed results, leading to a time complexity of O(m × n), where m and n are the lengths of the two strings. Space can also be optimized using rolling arrays.

Complexity

ApproachTime ComplexitySpace Complexity
Dynamic Programming (2D DP table)O(m × n)O(m × n)
Space Optimized DPO(m × n)O(min(m, n))

Video Solution Available

Tushar Roy - Coding Made Simple

View all video solutions

Solutions (5)

Dynamic Programming Approach

This approach uses a 2D array to store the edit distances between all prefixes of both strings. By building solutions for smaller subproblems, we can efficiently calculate the solution for the entire problem.

We define dp[i][j] as the edit distance between the first i characters of word1 and the first j characters of word2. The recursion is based on comparing the last characters of the current substrings. If they are the same, the edit distance is the same as dp[i-1][j-1], otherwise, we add 1 (to account for an edit operation) and consider the minimum edit distance found after each possible operation: insertion, deletion, or replacement.

Time Complexity: O(m * n) where m and n are the lengths of word1 and word2 respectively, as we compute values for each combination of indices.

Space Complexity: O(m * n) for storing the dp table.

PythonJavaScriptC
1def minDistance(word1, word2):
2    m, n = len(word1), len(word2)
3    dp = [[0] * (n + 1) for _ in range(m + 1)]
4
5    for i in range(m + 1):
6        dp[i][0] = i
7    for j in range(n + 1):
8        dp[0][j] = j
9
10    for i in range(1, m + 1):
11        for j in range(1, n + 1):
12            if word1[i - 1] == word2[j - 1]:
13                dp[i][j] = dp[i - 1][j - 1]
14            else:
15                dp[i][j] = 1 + min(
16                    dp[i - 1][j],      # Deletion
17                    dp[i][j - 1],      # Insertion
18                    dp[i - 1][j - 1]   # Replacement
19                )
20
21    return dp[m][n]
22

Explanation

This Python implementation uses dynamic programming. We start with initializing a table where each cell dp[i][j] represents the edit distance between the first i characters of word1 and the first j characters of word2.

The base cases are filled as follows: dp[i][0] = i (deleting all i characters of word1 to match an empty word2) and dp[0][j] = j (inserting all j characters of word2 into an empty word1).

We then populate the table by computing the cost of each edit operation and choosing the one with the minimum cost.

Recursive Approach with Memoization

This approach uses recursive calls with memoization to effectively reduce the factors of redundant subproblem calculations. We use a hash map or an array to store results of previously encountered subproblems to avoid recalculating them, subsequently turning the recursive depth-first search into a memoized search.

Time Complexity: O(m * n) where m and n are lengths of word1 and word2. Each subproblem is computed once.

Space Complexity: O(m * n) for memoization storage plus recursion call stack space.

JavaC#
1import java.util.HashMap;
2
3






Video Solutions

Watch expert explanations and walkthroughs

Minimum Edit Distance Dynamic Programming

Tushar Roy - Coding Made Simple
9:47571,776 views

Asked By Companies

8 companies
A
Amazon
L
LinkedIn
M
Microsoft
G
Google
A
Apple
B
Bloomberg
F
Facebook
R
Rubrik

Prepare for Interviews

Practice problems asked by these companies to ace your technical interviews.

Explore More Problems

Notes

Personal Notes

Jot down your thoughts, approach, and key learnings

0 characters

Similar Problems

Longest Palindromic SubstringMedium
Regular Expression MatchingHard
Generate ParenthesesMedium
Longest Valid ParenthesesHard
More similar problems

Related Topics

StringDynamic Programming

Problem Stats

Acceptance Rate57.7%
DifficultyMedium
Companies8

Practice on LeetCode

Solve with full IDE support and test cases

Solve Now

Frequently Asked Questions

Is Edit Distance asked in FAANG interviews?

Yes, Edit Distance is a classic dynamic programming problem frequently discussed in technical interviews, including FAANG-level companies. It tests understanding of DP transitions, string manipulation, and optimization techniques.

What is the optimal approach for Edit Distance?

The optimal approach uses dynamic programming. A 2D DP table stores the minimum operations needed to convert prefixes of one string into prefixes of another, avoiding repeated computation and ensuring efficient processing.

Why is dynamic programming suitable for Edit Distance?

The problem has overlapping subproblems and optimal substructure. Converting larger prefixes depends on results from smaller prefixes, which makes storing intermediate results with dynamic programming very effective.

What data structure is used in the Edit Distance solution?

Most solutions use a 2D array (DP table) where each cell represents the minimum edit operations for specific prefix lengths. Some optimized solutions reduce memory by using two 1D arrays instead of the full matrix.

Previous Problem

Simplify Path

Next Problem

Minimum Window Substring

public
class
Solution
{
4
private
HashMap
<
String
,
Integer
>
memo
=
new
HashMap
<
>
(
)
;
5
6
public
int
minDistance
(
String
word1
,
String
word2
)
{
7
return
helper
(
word1
,
word2
,
word1
.
length
(
)
,
word2
.
length
(
)
)
;
8
}
9
10
private
int
helper
(
String
word1
,
String
word2
,
int
m
,
int
n
)
{
11
String
key
=
m
+
"-"
+
n
;
12
if
(
memo
.
containsKey
(
key
)
)
{
13
return
memo
.
get
(
key
)
;
14
}
15
16
if
(
m
==
0
)
return
n
;
17
if
(
n
==
0
)
return
m
;
18
19
if
(
word1
.
charAt
(
m
-
1
)
==
word2
.
charAt
(
n
-
1
)
)
{
20
int
result
=
helper
(
word1
,
word2
,
m
-
1
,
n
-
1
)
;
21
memo
.
put
(
key
,
result
)
;
22
return
result
;
23
}
24
25
int
insert
=
helper
(
word1
,
word2
,
m
,
n
-
1
)
;
26
int
delete
=
helper
(
word1
,
word2
,
m
-
1
,
n
)
;
27
int
replace
=
helper
(
word1
,
word2
,
m
-
1
,
n
-
1
)
;
28
29
int
result
=
1
+
Math
.
min
(
insert
,
Math
.
min
(
delete
,
replace
)
)
;
30
memo
.
put
(
key
,
result
)
;
31
32
return
result
;
33
}
34
}

Explanation

This Java solution implements a top-down recursion with memoization. The primary operation function 'helper' recursively solves the edit distance problem by considering character matches and operations separately.

Memoization is achieved by storing results of subproblems in a HashMap, uniquely keyed by the indices of remaining substrings.