Showing posts sorted by relevance for query Leetcode 72: edit distance. Sort by date Show all posts
Showing posts sorted by relevance for query Leetcode 72: edit distance. Sort by date Show all posts

Tuesday, December 10, 2019

Leetcode 72: Edit distance

Dec. 10, 2019

Introduction


It is hard for me to correct my own behavior. I used to watch a lot of personal finance video, but I should spend time to review algorithm instead last few days. This morning I rushed to spend one hour to review algorithms. I chose to review pramp.com mock interview algorithms, I only had time to review algorithm Edit distance.

My past practices


I just could not believe that I started to write down so many practice blogs related to Leetcode 72: Edit distance. I did find some issues, so I quickly added source code into the blog.

Learning Edit distance algorithm was such amazing experience. I worked with 10 rounds mock interview, 10 times I was an interviewer, 10 times I was an interviewee on the algorithm.

I did work hard to write down some practice notes. It is easy for me to review my progress through those practice.

Those people helped me to learn how to write good code, and also reminded me to understand the importance of dynamic programming algorithm.

I just could not believe that those experience in 2017 is already more than two years ago. I am growing old but those blogs are written so clear and very good reading material.

Here is the link to access those practice searched by "Leetcode 72: Edit distance".

My timeline


I got up around 9:30 am.
Took a walk 20 minutes - 10:00 PM
10:00 PM - 10:50 PM study Leetcode 72 Edit distance
Mock interview github page is here.

I just could not believe that that is the way I prepared for the phone screen on Dec. 10, 2019.


Sunday, September 4, 2016

Leetcode 72: Edit distance - code study

Sept. 4, 2016

First thing in the morning, this Sunday, labor long weekend, Julia read the book about "competitive programming. She read the book -
page 112,
6.3 String Processing with Dynamic Programming
6.3.1 string alignment - edit distance

Using Dynamic Programming, she was amazed that how good the solution is provided in the book. She read aloud the analysis and solution word by word, sentence by sentence, a few times. So enjoyable experience.

The book is detailed in the previous blog:
http://juliachencoding.blogspot.ca/2016/09/book-reading-competitive-programming.html

So, she looked up google and found the similar algorithm: Leetcode 72 - edit distance
Problem statement: (Hard)
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Blog reading:
1. Machine learning - 
http://www.hpl.hp.com/news/2011/jul-sep/luluhe.html

Sunday, July 30, 2017

Leetcode 72: Edit Distance

July 30, 2017

Introduction


It is such great mocking experience for Julia to work on edit distance algorithm again in 30 minutes this afternoon around 4:00 pm. Since Julia was tired and kind of sleepy, she could not hear the peer because of her speaker was turned off. It took her 5 minutes to find out, both tried to login again. The fact is that if you are tired, your will have some issues to work on the small thing.

It is good to observe that when you are tired, the thing can go out of control once a while. Julia remembered last time that she was very tired and then she worked on week of code 34 over 5 hours and did not score anything. Always get ready for the mocking!

The algorithm is hard to write. Even though it is not the first time to write it. Her last practice is documented here.

Design of Memoization


The peer helped Julia to come out the idea to design the key for memoization. Julia worked on design by going through the simple case, "heat" to "hit",  how to express distance("eat","it") using the key? Julia thought about loud, one way is to concatenate two keys like this "eat it", and she said that "it eat" should be the same as "eat it". Because Julia was too tired, she did not have a good idea. She was given a hint to use the array, use index of string, then she asked the idea using int[2] and define the comparer function.

The peer gave her hint to use jagged array memo[i][j], whereas i and j are the index of start position of substring.

Algorithm practice 



C# practice code is here. The code runs with a test case and the result is correct. The peer reminded Julia line 71 and 72 having an issue. Julia forgot to increment one to the distance. At the end with a test case, the peer applaused  Julia, and it was unbelievable 71 lines of code no bug.


Editorial Notes:

9/22/2017
I practiced again this algorithm through mocking interview, I met a senior developer who has very good managing experience. He asked me the time complexity about brute force solution, I stumbled on the question.

Based on the above experience, I did not learn the algorithm very well in theory. The dynamic programming is not easy to figure out. I need to relate to a simple life experience for this algorithm. I did one later on. Here is the blog link.

July 6 2023
I am working on Meta phone screen in two months, so I have chance to review Edit distance. 

Thursday, September 14, 2017

July 18, 2017 algorithm review

Sept. 14, 2017


Introduction


It is two months ago, I did spend 3 to 4 hours to review my own practice before 8:00 pm. I went over around 30 algorithms, print one by one on the paper, and then read one by one. I really learned from the preparation, and I like to open a folder on my own github, and list all those algorithms I chose to study on July 18, 2017.

It is so interested to know that once I am busy with the study, the nervousness is kind of going away. I did very good one on preparation, and I had great performance later on the evening to complete code in limited time.

Algorithms


Algorithm 1. In order successor
Algorithm 2. Flatten the dictionary
Algorithm 3: HTree
Algorithm 4: Reverse words
Algorithm 5. Find distance binary tree
Algorithm 6. Leetcode 23 Merge K Sorted List
Algorithm 7: Leetcode 37 Sudoku
Algorithm 8: Leetcode 49 Group anagrams
Algorithm 9: Leetcode54 SpiralMatrix
Algorithm 10: Leetcode 72 Edit distance
Algorithm 11: Leetcode 114 Flatten Binary Tee to Linked List
Algorithm 12: Leetcode 212 Word Search II
Algorithm 13: Leetcode 295 Find median for path stream
Algorithm 14: Leetcode 295 median of stream
Algorithm 15. Leetcode 300 Longest Increasing Subsequence
Algorithm 16. Leetcode 416 Partition equal subset sum
Algorithm 17: Leetcode 516 Longest palindrome subsequence
Algorithm 18: Leetcode 605 Can place flowers
Algorithm 19: Binary tree two path same value
Algorithm 20: Leetcode 239 Sliding window maximum
Algorithm 21: Leetcode 57   Insert interval
Algorithm 22: Leetcode 10   Regular expression matching
Algorithm 23: Leetcode 547 Find Circle
Algorithm 24: Leetcode 130 Surrouned region
Algorithm 25: Maze Project
Algorithm 26: Short Job First using Icomparer
Algorithm 27: Leetcode 554 Brick wall



Wednesday, June 17, 2015

Leetcode 72: edit distance

June 16, 2015

Problem statement:

72. Edit Distance 

Code study: 

One solution in Chinese, blog is here written by FightForYouDream. 

Stanford lecture note about edit distance, the pdf file is here. 

Write down the feeling after the practice:

It is a two dimension dynamic programming. It took me a few hours to understand the algorithm. After a few month, I may totally forget the algorithm.
这个算法是2 dimensional dynamic programming. 读了好几个小时, 练习了代码, 理解了算法; 可能过几个月全忘了. 代码有一段容易出错,

Share the C# code, code is here. 

Follow up 


May 5, 2017

Review the algorithm after mocking experience on this algorithm in May 4, 2017. 



Saturday, December 30, 2017

Leetcode 72: Edit Distance

Dec. 30, 2017

Plan to study the blog related to Leetcode 72: Edit Distance.

Here is the blog link.

Wednesday, June 21, 2017

Leetcode 72: Edit Distance

June 21, 2017

Introduction



Plan to work on Leetcode 72: Edit Distance again. The problem statement is here.

Algorithm study 



Julia's C# practice is here. 

Follow up

Dec. 10, 2019 10:49 PM

It is better to add code to the blog. Also I spent 10 minutes to review the code, there are three cases involved to build next iteration in dynamic programming, left, top, and left and top, first two the increment is 1, last one may be one or zero, depending on last char in two strings are the same or not.

This definitely is a good practice question for dynamic programming.

Saturday, December 30, 2017

Leetcode 72: Edit Distance

Dec. 30, 2017

Introduction


It is the Saturday morning, I like to go out to play tennis, and it is the first day of week we have a sunny day. Also I like to review the algorithm Leetcode 72: Edit distance.

Here is the blog I like to review today, I found it through my 2015 blog.

I also created a gist for the code written by the author. Here is the link.




Discussion Panel of Leetcode 72 - Edit Distance

Dec. 30, 2017

Plan to study the discussion panel of Leetcode 72 - Edit Distance.

Here is the image of top ranked discussion readings:


Sunday, July 7, 2019

72. Edit Distance - 2015 practice

July 7, 2019

Introduction


It is my best favorite thing to do. What it is ?  Read my own code back in 2015. I was shy and also very close a person. Hard working, but I still like to explore more things. At that time, I remember that I ask my retired friend Rick if he likes to purchase a condo in the city of Seattle. I like to go out and drove my Ford Explorer SUV and cross border to shop clothes, hand bags. A lonely person likes to do things and enjoy road trip.  Certainly I do not know that there is a product feature called Discuss, I can share my practice over there, and also learn from other people as well.

My practice 


Today I like to review my practice. For me it is surprise and surprise. I need to review more often, since I learn the dynamic programming solution very well back in 2017 and 2018.

Here is my discussion post I write today.

It is so sweet to read my own code back in 2015. At that time, I started to work on leetcode algorithm, most of times I still google and found blogs written in Chinese, and then read the content I like most; at that time, I did not know there is a product feature called discuss on Leetcode.com. I did not know that there are over hundreds of sharing. I just could not believe that I was the person so close mind; not curious enough to press all possible links on Leetcode.com for a few hours, explore all possible resourceful places.
Lesson No. 1:
Good software programmer should be very curious person.
Another thing is that I should learn that Google search misses a lot of things, all Leetcode discuss will not find in any Google search as well.
All comments are in Chinese, but I will write down the tips for me to score all points in my writing next time.
Here are highlights:
  1. Understand subproblems, there are only three subproblems, from three possible direction, up, left, and cross up left;
  2. Greedy algorithm idea is to find the minimum value in all subproblems, go ahead to calculate three subproblems;
  3. More about step 2, the difficult part is left top cross one. How to determine the minimum value based on the corner? Just replace one char with another one is second string if last char in both string are different;
  4. Ask myself what is maxmimum difference between the current problem and subproblem, since add, delete and replace three choice, the difference is one.
  5. If there is no choice to replace a char, then answer of step 4 question will be 2 for cross corner subprobelm case.
public class Solution {
    public int MinDistance(string word1, string word2) {
        int l1 = word1.Length; 
            int l2 = word2.Length; 

            int[][] distance = new int[l1+1][];
  
            for(int i = 0; i<l1+1;i++)
                distance[i] = new int[l2+1]; 
          
            // 边界情况:当其中一个string为空时,只要一直添加或删除就可以  
            for(int i=0; i< l1+1; i++){  
                distance[i][0] = i;  
            } 
 
            for(int j=1; j< l2+1; j++){  
                distance[0][j] = j;  
            }  
          
            // 递推,[i][j]处可以由左,上,左上3种情况而来  
            for(int i=1; i<l1+1; i++){  
                for(int j=1; j< l2+1; j++){  
                     int tmp = Math.Min(distance[i-1][j]+1,   // 从上演变  
                                        distance[i][j-1]+1); // 从左演变  
                 
                     // 从左上演变,考虑是否需要替换 
                     // avoid word1, word2 index out of range bug - how?
                     // word1: index range from 0->l1-1
                     // word2: index range from 0->l2-1
                     // but distance[i][j] is between word1's substring from 0 to i-1 and word2's substring from i to j-1
                     // there is one difference! 
                     distance[i][j] = Math.Min(tmp, distance[i-1][j-1]+((word1[i-1]==word2[j-1]) ? 0 : 1));                  
                }  
            }  

            // 返回右下角
            return distance[l1][l2];  
    }
}






Monday, September 11, 2017

Leetcode 72: Edit Distance

Sept. 11, 2017


Introduction



It is one of classical algorithms related to recursive function and also memoization. I have practiced a few times and I am still learning the algorithm. My last practice is documented here, and all past practices are available through the search by Leetcode 72.

It was such great experience to be interviewed using the algorithm again. This is my third algorithm practice, my last practice was more than one month ago. I still remembered the mistake I had and the advice I got from the peer.

Algorithm practice 


Here is my C# code written in 30 minutes. I had a mocking experience starting from 10:00 pm.

I knew that I have to work hard to be an interviewer in order to get unlimited credit. I just started my new round of mocking practice. I could not memorize the algorithms, there are a lot of new issues coming out on this algorithm. I failed to do analysis of brute force solution, it should be 2(max(str1.Length, str2.Length)), because every time there is at most 2 choices. I was given the hint and then I took the hint to go from n * m to power of 2 analysis. In other words, the time complexity is lowered from polynomial time to quadratic time.

Assume that the worst case happens. In other words, the comparison of two chars are not equal, so one of them has to be deleted. There are two choices to do deletion, the minimum value of two choices will be recorded. For example, two strings are "abc" and "edfg". The total choices are at most 27. In mathematical term, the upper bound is 27 = 512. The dynamic programming using memoization will lower time complexity using jagged array memo[3][4], time complexity 3 * 4 = 12.

I also was told to make correction on the first line of the function, line 8. The checking is for the case of both strings are null or empty. Not at least one of them. I wrote || by the mistake.


Related to a simple life choice



9/12/2016

It is always good idea to write down the practice experience, what did I actually learn from the mocking? This time, 30 minutes coding passes all test cases, with one of corrections from the peer. But I was surprised to know that I need to grasp the basic algorithm analysis, as I shared my knowledge of Monte Carlo algorithm to a young graduate from a linguistic major, I have to explain the algorithm to myself. The most important is to know how to analyze instead of guessing.


If I have two choices to calculate distance, how should I make a decision? I have to go for the minimum one from the two choices. If I have a series of choices to make, then the combinations of choices will be 2n. To summarize, Leetcode 72 is the algorithm for me to teach myself how to understand the brute force solution with polynomial time complexity, know how to solve the problem first, and then apply dynamic programming, lower the time complexity to m * n using memoization, dynamic programming using bottom up solution.

It is interesting to know the memoization design, the best choice I know is to use jagged array, memo[][], the size of jagged array is str1.Length * str2.Length, that is how many intermediate result we have to hold. Assume that each of them is calculated to use a few simple steps which are O(1) time complexity. 

Saturday, December 30, 2017

Leetcode 72: Edit the distance

Dec. 30, 2017

Introduction


Plan to watch the video about edit distance, it is titled "How to Calculate Edit Distance Between Two Strings". The video is about one hour long. Here is the link.


Leetcode 72: Edit Distance

Dec. 30, 2017

Plan to study the blog Edit Distance. Here is the link.

Saturday, August 22, 2015

Leetcode questions: 70 - 80

August 22, 2015


70 climbing stairs

71 Simplify Path

72 Edit Distance

http://juliachencoding.blogspot.ca/2015/06/leetcode-edit-distance.html

73 Set Matrix Zeroes

74 Search a 2D Matrix

75 Sort Colors

76 Minimum Window Substring

77 Combinations

78 Subsets


79 Word Search

http://juliachencoding.blogspot.ca/2015/07/leetcode-word-search.html

Thursday, May 4, 2017

Algorithm learning small talk

May 4, 2017

Introduction


It is very interesting to read the article called "when pressure and off-court life overcome talent and results". The article link is here.

It is more exciting to practice coding and attend contest in the weekends. Julia enjoys the contest and also likes to push herself to join the community and share what she can do. Here is the blog to show her ask code review on a hard level algorithm in Hackerrank world codesprint 10 recently.

Julia had a mocking experience tonight, she had a big surprise about learning a dynamic programming algorithm.

The problem is a very ordinary solution using dynamic programming, recursive solution.

The deletion distance of two strings is the minimum number of characters you need to delete in the two strings in order to get the same string. For instance, the deletion distance between "meat" and "mit" is 3:
  • By deleting 'e' and 'a' in "meat", and 'i' in "mit", we get the string "mt" in both cases.
  • We cannot get the same string from both strings by deleting 2 letters or fewer.

Less means more 


How to analyse the above algorithm? 

Use frog and dog as an example, we have two words, we like to linear scan two strings from left to right, all starts from the beginning. First chars of two strings are 'f' and 'd'. If they are equal, then both pointers go to next one. Otherwise, we have to move one of pointers. Both cases should be counted. In other words, 'd' is deleted, then continue to work on two strings: "og" and "frog"; or 'f' is deleted, then continue to work on two string: "dog" and "rog". 

So far, the analysis is perfect. We cannot sort the string, because the order is important and has to be kept. The count of char does not help much. The brute force solution is not good since it will be O(n2), actually it is hard to find a brute force solution.

In other words, recursive function can be written in the following recurrence formula:

CalculateDeletionDistance(s1, s2) = CalculateDeletionDistance(s1.substring(1, length1 - 1), s2.substring(1, length2 - 1)) if s1[0] == s2[0];

Make it short, CalculateDeletionDistance is shorted as CDD, s11 is the substring of s1, s21 is the substring of s2.

CDD(s1, s2) = CDD(s11, s21) if s1[0] == s2[0],
CDD(s1, s2) = 1 + Math.Min(CDD(s1, s21), CDD(s11, s2)) if s1[0] != s2[0]

Basically the recursive function is depth first search, base case should be calculated the deletion distance. And then in order to save time, it is better using bottom-up solution, called dynamic programming method.

Edit Distance Algorithm


Previous practice on Leetcode 72 is here. Spend 20 minutes to review lecture note from standford again. Also plan to spend 30 minutes to review Leetcode discussion, link is here.

Julia was wondering if the dynamic programming is also solvable using DFS algorithm.

Actionable Items


Plan to read the article on topcoder: Dynamic Programming - From novice to expert, the link is here.

Read the facebook engineering manager - Yi Huang's linkedin profile.

Take some notes from the recommendation:

Understand to build a hobby - writing code, solve problems on topcoders:

"Numerous times we turn to each other to discuss algorithm and optimization problems and every time I am impressed how insightful Yi can be. Yi has won countless programming awards and takes coding as a serious hobby. Yi has great enthusiasm in algorithm optimization. His hobby is to log into topcoder and attack one problem after another. He also has the great ability to apply research knowledge to actual programming. He is one of the few guys that will always think of how to turn research results into reality."



Sunday, September 18, 2016

HackerRank Stryker Code Sprint Grind (V) - The Hidden Message - 70%

Sept. 18, 2016

Problem statement

Julia's C# solution is here.

Here is the timeline Julia worked on the problem solving:

Section 1:
 /* 7:08pm - start to read the problem statement
     *
     * 7:47pm start to write down her approach
     * start position is increasing
     * How to find word match?
     *
     * Time complexity -
     * Data structure
     * Space complexity:
     *
     * 7:55pm start to code
     *
     * 10:04pm start to conduct testing
     */

 Section 2: 
Copy the code from previous practice - substring search, using Boyer algorithm to speed up, avoid timeout issues. 
/*
         * 8:24pm
         * copy code from blog:
         * http://juliachencoding.blogspot.ca/2016/04/hackerrank-string-function-calculation_10.html
         *
         * 8:36 prepare to exit the function
         */
        private static bool findUsingBoyerAlgo(string substring, string s, ref int start)

Section 3:
/*
         * 9:02pm - start to code
         * 9:43pm - still work on the calculation of cost
         * - try to think about how many chars to be removed - second step
         * 9:57pm use brute force solution first
         */
        public static string calculateCost(IList<Match> data,
            string message
            )

Section 4:
 /*
     * 10:19pm
     * Summary of submission:
     * 40.80/60
     * Wrong answer for test case: 11, 15
     * Try to fix the bug
     */

Summary:
1. 40 minutes to read the problem statement
2. 2 hours coding - including eating a dinner - 20 minutes

55 minutes to work on calculation of cost, looked into interval algorithm, and then, figured out using brute force solution instead.

2. 10:04pm testing

Score 40.80/ 60 

Decided to give up bug fix, and then, moved on next question.

Study C# submission - 60 out of 60
1. Use Trie

2. C#: use dynamic programming.

Related to Leetcode 72: "Edit Distance"

3. Study the blog: Levenshtein Distance wiki

4. Study Java 8 solution - use Rabin Karp algorithm search class, DP

5. C++ code - Learn from the best, competitive programmer

6. C++ - KMP algorithm, DP

7. The programmer - 5 Gold - rank 32/1700
a Googler, a blog.

Talk about Google code review - in Chinese, link is here.

Wednesday, August 5, 2015

Leetcode questions and web link

August 5, 2015

  Here is the table about leetcode questions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
179
186
187
188
189
190
191
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251