Thursday, August 31, 2017

Leetcode 18: 4 sum

August 31, 2017

Introduction



Plan to continue to work on 4 sum solution, using hashtable to store all possible two sum, and then look for 4 elements with the given sum. I chose to write the solution instead of using a two for loop for the first two elements, and then two pointer technique to find a sum value. This is the first time I wrote the idea and I like the adventure.

30 minutes practice code is here.

In the mocking practice, I explained to the peer that I have to write a function to determine that 4 indexes are unique. In other words, assume that 4 indexes are a, b, c, d, then at least 4 comparisons are needed, a != c, a != d, b != c, b != d. Actually there are a lot of duplicated pairs for a < b < c < d four numbers to a given sum, (a, b) and (c, d) are two pairs with sum a + b + c + d, or (a, c) and (b, d)  with the same sum, etc., to simplify, we can enforce that the pairs to look for are (a, b) and (c, d) only.

I thought that it will take a few minutes to write the logic, and gave up the writing in the mocking. Since in the mocking interview, I was not sure that I should simplify the search, enforce the rule to apply a < b < c < d, therefore the checking will be very simple as b < c, in other words, the second element in the first pair is smaller than the first element in the second pair.

9/1/2018

The C# code passes all test case, I did fix the grammar error, and also simplify the search. I try to search two pairs in the ascending order. First sort the array, and then iterate any pair less and equal half the given value, find another pair with index of array (start, end), the start index is bigger than the pair's second argument's index.

C# code is here. Last practice is on April, 2017, the blog is here.

A very competitive peer 


A few things I learned from the peer. If I am the interviewer, I should explain the problem to the interviewee, and then let interviewee ask questions to clarify the problem. I do not explain the algorithm to the peer when I am the interviewer, but this time the peer asked me to explain the algorithm at the very beginning, and I was told that I should explain the problem as the normal interviewer does.

The fact is that only two or three peers out of 80 mocking experience did explain the algorithm to me at the beginning. Now I knew that it should be always the case.

Do not just let the interviewee to read the problem statement and then figure out the algorithm.


Try to simplify the algorithm, otherwise I cannot finish it in 30 minutes. The peer thought that it is better to have a working solution instead of having a solution not completed.


Write test cases by yourself first, instead of using "Run tests" feature embedded in the browser.


Feedback






No comments:

Post a Comment