Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created January 22, 2018 07:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/96a09da17790695324ca8e6d7e1113fa to your computer and use it in GitHub Desktop.
Save jianminchen/96a09da17790695324ca8e6d7e1113fa to your computer and use it in GitHub Desktop.
deletion distance - mock interview 1/21/2018 11:25 PM - pass all test cases, the peer approved my analysis with the correction of diagram on line 82 after mock interview.
using System;
class Solution
{
public static int DeletionDistance(string str1, string str2) // "heat", "hit"
{
if(str1 == null && str2 == null) // false
{
return 0;
}
if(str1 == null)
{
return str2.Length;
}
if(str2 == null)
{
return str1.Length;
}
var length1 = str1.Length; // 4
var length2 = str2.Length; // 3
var deletionDist = new int[length1 + 1, length2 + 1]; // 5, 4
// base case
for(int col = 0; col < length2 + 1; col++)
{
deletionDist[0, col] = col;
}
for(int row = 0; row < length1 + 1; row++)
{
deletionDist[row, 0] = row;
}
for(int row = 1; row < length1 + 1; row++)
{
for(int col = 1; col < length2 + 1; col++)
{
var first = str1[row - 1];
var second = str2[col - 1];
if(first == second)
{
deletionDist[row, col] = deletionDist[row - 1, col - 1];
}
else
{
deletionDist[row, col] = 1 + Math.Min(deletionDist[row - 1, col],
deletionDist[row, col - 1]);
}
}
}
return deletionDist[length1, length2];
}
static void Main(string[] args)
{
}
}
/*
constraints: minimum number of deletion
two strings
heat
hit
if first char is equal, then we do not need to delete, move to next iteration both, 0 + dist("eat", "it")
if 'e' != 'i', delete e or i , 1 + min(dist("at", "it"), dist("eat","t"))
Draw a diagram, dynamic problem -> (str1.Length1 + 1) * (str2.Length + 1)
dist("", "hit") = 3
dist("heat", "") = 4
5 * 4 matrix -> start from (0,0), solution will be matrix[4, 3]
My intention is to scan left to right, so it should be the following matrix.
"" "h" "he" "hea" "heat" ? first char of "heat"
---------------------------------------
"" 0 1 2 3 4
"h" 1
"hi" 2 x| y
"hit" 3 z ?
But however the scan from right to left should be same deletion distance as well.
"" "t" "at" "eat" "heat" ? last char of "heat"
---------------------------------------
"" 0 1 2 3 4
"t" 1
"it" 2 -|
"hit" 3 ?
I got the help from the peer after the mock interview to confirm the line 82 statement:
My intention is to scan left to right, so it should be the following matrix.
Time complexity:
space complexity:
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment