Saturday, November 4, 2017

Leetcode 18: 4 Sum

Nov. 4, 2017

Introduction


It is such a great mock interview this morning starting from 10:00 am. I had to work on the algorithm Leetcode 18: 4 sum in the time limit of 35 minutes. I did a few things to make the mock interview great learning experience. I wrote an algorithm, passed the compiling and then passed all test cases without any bug. The algorithm has optimal time complexity although extra space is needed.

Here are highlights:

 1. I chose the algorithm using time complexity O(n2). Two sum pairs are saved to the dictionary for lookup later on.

 2. Whiteboard testing was very helpful, I chose the easy one [3, 2, 1, 4, 5] and the given 4 sum is 12 = 1 + 2 + 4 + 5. Compared to the test case given in the problem statement, this one is easy to follow.

3. Through whiteboard testing, I found a bug in my design. The array may have duplicate numbers, and then I spent extra 5 minutes to change the design, in line 78, I added two extra elements in the array to save index number of the array.
newList.Add(new int[]{no1, no2, i, j})

4. Through the whiteboard testing, I modified the code to make it more easy to follow. I added var no1, no2, no3, no4, assuming that no1 <= no2 <= no3 <= no4, and the index of four numbers in sorted array is in ascending order.

5. I spent less than 3 minutes to fix all compiling errors.

6. The code runs and pass all test cases without any bug.

Code review


The code I wrote in mock interivew in C# is here to view.

Based on my last practice on Leetcode 18: 4 sum in August 2017, I worked on the feedback. I need to write a run-through code, I have to simplify the solution in order to fit in 30 - 35 minutes.

A few things I did are very helpful to expedite the process this time. The most simple test case is chosen to do whiteboard testing; the whiteboard testing is not a fake one, in the process of testing, I found a bug first, and then came out the fix, and in-between I added a few more variables to make code more easy to follow, avoid bugs.

Feedback from the peer


The peer did not choose to use the video, but her knowledge of algorithm is very helpful. I did have chance to learn the algorithm compared to two pointers techniques.



No comments:

Post a Comment