Edit Distance

Given two strings str1 and str2 and below operations that can performed on str1. Find minimum number of edits (operations) required to convert ‘str1’ into ‘str2’.

 

Insert

Remove

Replace

All of the above operations are of equal cost.

Input:   str1 = "geek", str2 = "gesek"

Output:  1

We can convert str1 into str2 by inserting a 's'.

 

Input:   str1 = "cat", str2 = "cut"

Output:  1

We can convert str1 into str2 by replacing 'a' with 'u'.

 

Input:   str1 = "sunday", str2 = "saturday"

Output:  3

Last three and first characters are same.  We basically

need to convert "un" to "atur".  This can be done using

below three operations.  

Replace 'n' with 'r', insert t, insert a.

 

CodingNinjas
author
2y
  • Firstly I gave the interviewer, a recursive solution then he asked me to reduce complexity as it was exponential of recursive solution so I gave him a top-down DP solution.
CodingNinjas
author
2y
Recursive Approach
  • We will write a recursive approach.
  • The base case would be if the length of the first string is 0 then we need to add all the characters of the second string to the first string hence...read more
CodingNinjas
author
2y
Memoization
  • We will write a recursive approach and memoize it. So first make a 2D array of size (N + 1) x (M + 1) where N and M are lengths of the two strings and fill it with -1. -1 means that we don’...read more
CodingNinjas
author
2y
Iterative DP

We will use the dynamic programming approach here and will have a 2-dimensional array, dp where

dp[i][j] stores the edit distance of the (i+1)th length substring of str1 and (j+1)th length ...read more

Add answer anonymously...
Goldman Sachs Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter