Wednesday, March 16, 2016

Mock interview (4th practice): Matrix Spiral Print

March 16, 2016

Problem statement

Given a 2D array (matrix) named M, print all items of M in a spiral order, clockwise.
For example:

M  =  1    2    3    4   5
         6    7    8    9  10
       11  12  13  14  15
       16  17  18  19  20

The clockwise spiral print is:  1 2 3 4 5 10 15 20 19 18 17 16 11 6 7 8 9 14 13 12

Mock interview practice


I had a mock interview recently and my algorithm is Spiral matrix. The code I wrote in mock interview using C# is here.

Let us take a look at evaluation from the mock interviewer, as a matter of fact the peer gave me the honest feedback, I have to figure out how to work on the improvement:



Code review


After the mock interview, I thought about more how to improve the solution. I do not have good idea to solve the problem. Based on my mathematics background and I tried to define how many variables in the problem.


Let us look at one variable, let us call it layer, using variable name row, value is from 0 to (N+1) / 2, where N is how many columns in the matrix. So, the spiral matrix output is to follow the order of clockwise starting from (0,0). 

N - how many columns
M - how many rows

Four corners are left-top, right-top, bottom-right, bottom-left, abbreviation using four variables: LT, RT, BR, BL


   LT     coordinates:   ( row,             row )    
   RT    coordinates:   ( row,             N - 1 - row)  
   BR    coordinates:   ( M - 1 - row,  N -1 - row)
   BL     coordinates:   ( M - 1 - row,  row)


private static void leftToRight(Coordinate[] A)

TopToDown, RightToLeft, and DownToUp 
  
           row

            0     1       2
            -------------->
           1    2     3   4   5
            6    7     8   9  10
           11  12  13  14  15
           16  17  18  19  20

The above case, LT = (0, 0), RT = (0, 4), BR = (3, 4), BL = (3, 0)

C# practice code based on the above idea is here.  

Continue to improve the idea. 

LT, BR those two pointers should be checked on the conditions, M – 1 - row >= row, N – 1 - row >= row; in other words, left top pointer is above the bottom right pointer, therefore it should be row <= Math.Min((M - 1)/ 2, (N - 1)/ 2).


It is true that the idea I came out just after the mock interview was not so good. But the hard work spirit is good, and also it is very good to write down the idea and review later on.

Issues found in mock interview


I like to write down a few issues in my practice. 

1. Jagged array initialization
Julia spent more than 5 minutes to look up the internet. 

2. Try another idea. Use one variable instead of two variables. 
Assuming that N rows and M columns, how many layers of spiral? Use the variable i to denote the number. 

It should be from 0 to (N+1)/2, but it is hard to figure out correct answer first time, it should be 0 to 
Math.Min((M-1)/2, (N-1)/2). 

Julia spent more than 20 minutes to debug in the practice. 

Spiral matrix practice in 2015



I practice once in 2015 on Leetcode 54 Spiral matrix algorithm. I found the blog and it is very interesting to read the code I wrote back in 2015 June. Here is the blog about the practice. 


Follow up 


May 23, 2017

It is such great experience to compare the current practice to the one in 2016. Julia learned that she made such great improvement on coding readability, and she starts to know how important it is to document and track the progress. 

After considering a few of options, it is much easy to write a while loop to track the total visited nodes in the original array. 

Instead of using i, j, use variable row and col because it is more meaningful. 

Do not run the code and depend on the compiler; 

Test the code by yourself. 

C# practice is here

In order to make sure that the code is working, Julia used the same idea to write a solution for Leetcode 54. The solution failed to pass one row test case [1, 2, 3]. 

The C# code is fixed to add one row and one column checking. The code is here



Sunday, March 13, 2016

HackerRank: string algorithm - Anagram

March 13, 2016

Anagram

Julia's C# implementation:
https://gist.github.com/jianminchen/f3c48ed9f3b16e8c5928

Julia made a few tries before she noticed that she needs to figure out the formula:

for (int i = 0; i < SIZE; i++)
            {
                if (sumA[i] > 0)
                    // add count of chars in array sumA but not in sumB
                    // axxbbbxx, 
                    // axxb -> bbxx, change a to b, that is it!
                    // axxb  a 1, b 1, x 2
                    // bbxx, a 0, b 2, x 2
                    // formula -> 
                    count += (sumA[i] >= sumB[i]) ? (sumA[i] - sumB[i]) : 0;   
            }

Another approach is to add all the differences, and then, divided by 2

C# submission code to study:

1. String class contains, Split functions etc. 
Split function - return array length to get the count of any char in the string. 
https://gist.github.com/jianminchen/adbfc2d809fb5b2bac78

2. add all the difference between two strings, and then divide it by 2
https://gist.github.com/jianminchen/7bbe86bbb83787d6b98b

3. Using Dictionary, KeyValuePair class
https://gist.github.com/jianminchen/78346475b6a7ce5d1681

4. Read more Lambda expression code in C#
https://gist.github.com/jianminchen/9d121bd95266db41dfa8

5. using StringBuilder, C# code
https://gist.github.com/jianminchen/d972656068fa8088ae70

6. use string.Remove function
https://gist.github.com/jianminchen/65687cefd2b107ec5e23


Java Code:
1. https://gist.github.com/jianminchen/794ffee7726df6062a1f

2. Maybe not smart idea, but it works - declare a string
String alph = "abcdefghijklmnopqrstuvwxyz";

https://gist.github.com/jianminchen/0cfa60bac880f2bba10f


Julia likes to read code, any language in submission. She could 
not stop reading, she has read more than 50 solutions, totally opened to so many creative ideas. 

HackerRank: string algorithm - Make it anagram

March 13, 2016


Make it anagram

Julia's practice:
C# language

https://gist.github.com/jianminchen/050b64f483c9a251d472

Read other's submission:

1. C#, using Dictionary, HashSet - Speically helpful, when you are not sure what Latin chars are. You just declare in general Dictionary, HashSet.

https://gist.github.com/jianminchen/5c6f6a70a1be4f71a98a

2. C#, using List class, remove method:

https://gist.github.com/jianminchen/a2258616e596c0328660

3. C#, kind of functional programming, new style to Julia - like JavaScript programming style

https://gist.github.com/jianminchen/2909916d9435f69c036b

4. using one array, first string each char - add to the array, second string each char - take away from the array, sum of abs value of each item.
https://gist.github.com/jianminchen/fbf8e9049d3a1539ee87

5. Using IList interface, distinct method, and functional programming - Lambda Expression <- Julia, you should try this code by yourself. It should be quickly picked up.

https://gist.github.com/jianminchen/fc8b4309efe00d67a640

read this webpage to refresh Lambda expression:
https://msdn.microsoft.com/en-CA/library/bb397687.aspx

6. Sort two strings first, and then, using two pointers - sliding forward

https://gist.github.com/jianminchen/41e6cbd30228e9ba7204

7. using string operation, remove a char from a string - for any char in both two strings
https://gist.github.com/jianminchen/0138e2425592638dcf7a









Sunday study time: Good advice how to have good work ethnics

March 13, 2016

Know one billionaire story, how he gives out advice how to do thing better. Self-made billionaire. Amazed that he likes to ride bicycle 60 miles a day and then keep fit.

Alan Michael Sugar Top 10 Rules For Success

https://www.youtube.com/watch?v=J7ZXs5Lrs_0

1. Your destiny is in your hands
When he was young, his family lived in a council flat.

2. Recognize failure 
After leaving school at 16, he worked as a statistician at the Ministry of Education.

3. Seize opportunities
He started selling electrical goods out of a van which he had bought with his savings of £50.

4. Have a good work ethic

5. Stick to what you know

6. Appreciate your team

7. Have discipline

8. Track your progress

9. Analyze your marketplace
He is a fan of and the former owner of Tottenham Hotspur.

10. Let your product do the talking

Billisionaire Lord Sugar's Rich lifestyle and story (1 hour video)
https://www.youtube.com/watch?v=PuuAkoxlWmA

Weight loss advice - that is much more important than how to be great at work.
http://www.express.co.uk/life-style/health/276673/Lord-Sugar-s-magic-formula-for-losing-weight

If you enjoy what you do, don't be afraid of expressing your enthusiasm. Enjoyment is infectious. - Alan Sugar



Saturday, March 12, 2016

HackerRank - strings - GemStones

March 12, 2016
GemStones:
Problem statement:
https://www.hackerrank.com/challenges/gem-stones

First practice:
Julia's C# solution:
https://gist.github.com/jianminchen/aa85318f91fbcdc8f74d

More practices:

Julia, you do not need to use jagged array to store all the string, you can use one array, and then, keep adding to the array the count.

So good to learn from other submission - Julia likes HackerRank, quickly get updated with more ideas/ implementation / more informed.

1. Improvement 1:
Here is other person's implementation - less space, beat your solution! 
https://gist.github.com/jianminchen/cb0886705d99423a321f

So, Julia, write another one - short one - 
not: int[][] countA = new int[len][];

     int[]   sumA = new int[26]; 
space improvement, code is much short. 

Julia wrote second implementation using one dimension int[26] instead of int[len][]
https://gist.github.com/jianminchen/10ece1c63d85e6ae3e12

2. Improvement 2:
Here is one of solution using bit manipulation - Great idea - try to use it as well!
Java
https://gist.github.com/jianminchen/c3d56eedcb794b0fa496

Julia uses C# to implement the bit manipulation:
https://gist.github.com/jianminchen/aba5bad049353738a520

one comment on line 39:
int x = -1; // julia, debug the code, and learn the idea to use bit manipulation 

why x = -1?
recall -1 is FFFF in bit expression; since 1+1 = 0, so
FFFF
       1
---------
0000

3 solutions - space complexity using jagged array to one dimension array to one integer.

Nov. 30, 2016
Review stackexchange code review post:
http://codereview.stackexchange.com/questions/61248/diamond-in-the-rough-finding-gems-in-the-rocks


HackerRank: String algorithm - Game Throne.

March 12, 2016

Great workout! Julia made a few mistakes, and then, fixed the issues:

https://gist.github.com/jianminchen/e7038fa7e59c96378675

Julia, your code is not short enough. Study other people's submission:

1. using Dictionary
2. declare array size of 26, not 256
3. other things - check string input etc.
4. using string manipulation, from an empty string, remove char if finding it, otherwise, append the char.

C#:
1. https://gist.github.com/jianminchen/6bf133d5c42e18260410

2. https://gist.github.com/jianminchen/bd3834da7b28ae619ee2

3. https://gist.github.com/jianminchen/16e9837b7b6b1e1a721c

Read a few of solutions using Java, C++. Great experience, relax and have some fun.



HackerRank - String algorithm - Alternating Characters

March 12, 2015

Alternating characters, Julia's practice:

https://gist.github.com/jianminchen/e4863f946534124c7229

HackerRank: String algorithm - funny string

March 12, 2016

  Julia likes to work on easy questions on HackerRank - string. So, she can develop more confident to write code.

  Funny string:

  https://gist.github.com/jianminchen/e577e9180305f0343fd5

Friday, March 11, 2016

small talk: what you can control, 3 variables from Michael Bloomberg

March 11, 2016

  Julia likes the advice from Michael Bloomberg. You cannot control how lucky you are, you may not control what you will do in next 10 years.

3 things you can control, influence, and success in your life, variables:
1. how hard you work,
2. how honest you are
3. how well you deal with others.

Cannot control how lucky you are. The harder you work, the lucky you get.

Michael Bloomberg's Top 10 Rules For Success

https://www.youtube.com/watch?v=gNnE-fQrqgA

1. Don't jump too quickly 

2. Share the credit
Really get ahead, to share the credit.

3. Delegate

4. Work hard

5. Question everything

6. Focus on people

7. Be honest with yourself

8. Be prepared

9. Don't look over your shoulder

10. Collaborate

Thursday, March 10, 2016

Pluralsight: Angular Fundamentals

March 10, 2016

  Work on "Angular Fundamentals" 6 hours course. Julia, be patient, you will have great time to play with AngularJS, and then write a great web app in 2016.

  Hours spent on AngularJS: 3 hours.

  Take some notes, and then, follow up with some reading, play with some code using AngularJS as well.

Wednesday, March 9, 2016

CodeSchool: AngularJS Tutorial

March 9, 2016

  Spent best time in the evening from 9:00pm - 11:00pm to watch the code school video, AngularJS Tutorial tonight.

  Need to find some material to study for AngularJS, and then start to memorize some content, such as AngularJS cheat sheet. Spend 20 minutes a day to memorize the cheatsheet.

  http://www.cheatography.com/proloser/cheat-sheets/angularjs/

  http://www.opitz-consulting.com/fileadmin/redaktion/veroeffentlichungen/pdf/CheatSheet-angularJS.pdf

81 contributor - great resource for new learner like Julia.
 https://github.com/jmcunningham/AngularJS-Learning/blob/master/README.md

 http://weblogs.asp.net/dwahlin/learning-angularjs-by-example-the-customer-manager-application

March 10, 2016
12 minutes of video: AngularJS Tutorial
https://www.youtube.com/watch?v=WuiHuZq_cg4

Plan to watch the video on March 10 evening time:
AngularJS Fundamentals (Pluralsight) - 6 hours 15 minutes total (paid)

http://app.pluralsight.com/author/deborah-kurata

Read Angular short book:
http://www.angularjsbook.com/angular-basics/chapters/introduction/

March 22, 2016
http://weblogs.asp.net/dwahlin/video-tutorial-angularjs-fundamentals-in-60-ish-minutes

Tuesday, March 8, 2016

Pluralsight: Structuring JavaScript

March 8, 2016

2 hours on course: Structuring JavaScript on pluralsight, from 8:00pm - 10:00pm.

Julia is a big fan of pluralsight online courses. She spent time to read JavaScript books in 2014 over 6 months; while this time the learning is more effective with excellent teaching.

She still works on how to take courses on pluralsight. She likes to take notes, and tracks her progression.

Read technical article by the course lecturer:

1. Techniques, Strategies and Patterns for Structuring JavaScript Code

2. the prototype pattern

3. the revealing module pattern

Take learning check later.

5 out 10 incorrect questions:

Which of the following code samples demonstrate creating closure:
Answer:



Related clip: Closure Demo 2

JavaScript's "this" keyword always represents the current object instance being used.
Answer:
False

Related Clip: Using the Revealing Prototype Pattern with 'this'

Which pattern is the best one to use with JavaScript code?
Answer:
There isn't one "best solution"

What features does the Revealing Module Pattern offer?
Answer: All of above
  Define public and private members
  Can include a self-calling function
  Encapsulates code

What is a  key difference between the Prototype and Revealing Prototype patterns?

Answer:
Revealing Prototype allows public and private members to be defined.

Notes to review:
The Prototype Pattern
Pros:
Leverage JavaScript's built-in features
"Modularize" code into re-usable objects
Variables/ functions taken out of global namespace
Functions loaded into memory once
Possible to "override" functions through prototyping

Cons:
"this" can be tricky
Constructor separate from prototype definition

Actionable Item

Dec. 20, 2016
Share the blog on the stackexchange.com - Radix Sort Code Review

Monday, March 7, 2016

Pluralsight: JavaScript for C# developer

March 7, 2016

 Two hours on JavaScript for C# developer on pluralsight (9:30pm - 11:30pm). Review JavaScript quickly.

 Got 3 of 8 questions correct. <- That is the excellent teaching tool - Learning Check

1. How can you specify functions overload in JavaScript?
You cannot <- julia chose the one -
But, the correct answer is: You would interrogate the arguments object to determine what parameters were passed in.

Actually, on March 7, Julia wrote a function with overloading function. English, still, is julia's second language.

2. How does JavaScript support property setters and getters for objects?
Object.defineProperty

3. What is the JavaScript alternative to using C# interfaces?
Duck Typing

4. Is casting required in JavaScript?

5. What defines a scope in JavaScript?

6. How is the C#'s var keyword different from the JavaScript var keyword.

7. Does JavaScript support classes?

8. Is C#'s for each equivalent to JavaScript's for...in syntax?

Plant to watch another JavaScript course on pluralsight: structuring JavaScript.

Sunday, March 6, 2016

HackerRank: Bear And Steady Gene - Binary Search (II)

March 6, 2016

Problem statement:

https://www.hackerrank.com/contests/hourrank-6/challenges/bear-and-steady-gene  

A gene is represented as a string of length  (where  is divisible by ), composed of the letters , and . It is considered to be steady if each of the four letters occurs exactly  times. For example,  and are both steady genes.

Study code using binary search:

cannot figure out the design - confused!
https://gist.github.com/jianminchen/d01faa03ca9b06696db3

This one is easy to follow
https://gist.github.com/jianminchen/395eb9e76fe19cc9338f

Julia's C# practice code:
https://gist.github.com/jianminchen/af1b3c064c523444463f

Algorithm talk:
Work on test case GAAATAAA, let me explain the idea using binary search.

            A1 = Math.Max(0, A1 - n / 4);  // test case: GAAATAAA, A1 = 4 
            C1 = Math.Max(0, C1 - n / 4);  // C1 = 0 
            G1 = Math.Max(0, G1 - n / 4);  // G1 = 0
            T1 = Math.Max(0, T1 - n / 4);   // T1 = 0

            if (A1 == 0 && C1 == 0 && G1 == 0 && T1 == 0)
            {
                return 0;   //
            }

            int ans = n;   // default value is maximum value - string length
            for (int i = 0; i < n; i++)  // go through a loop, start from 0 to n-1. 
            {
                if (A[n] - A[i] < A1 || C[n] - C[i] < C1 || G[n] - G[i] < G1 || T[n] - T[i] < T1) // substring position from i to n, check the count of A, C, G, T
                    break;

                int l = i + 1, r = n;  // left, right two pointer
                while (l < r)
                {
                    int mid = (l + r - 1) / 2;
                    if (A[mid] - A[i] < A1 || C[mid] - C[i] < C1 || G[mid] - G[i] < G1 || T[mid] - T[i] < T1) // not enough
                        l = mid + 1;   // set left pointer to mid + 1
                    else
                        r = mid;      
                }

                ans = Math.Min(ans, l - i);   // substring is from i to l,
            }

            return ans;

In other words, GAAATAAA,

i = 0, l = 1, r = 8,
find ans = Math.Min(ans, l-i)   <-  ans = 6, l = 6

i = 1,
find ans = Math.Min(ans, l-i)  <- ans = 5, l = 6, i=1

i = 2,
find ans = Math.Min(ans, l-i)  <- ans = 5, l = 7, i=2

i =3; 
find ans = Math.Min(ans, l-i)  <- ans = 5, l = 8, i=3

i=4
break the for loop
if (A[n] - A[i] < A1 || C[n] - C[i] < C1 || G[n] - G[i] < G1 || T[n] - T[i] < T1)

                    break;
since A[n] - A[i]  =  3 < A1 = 4, TAAA, we need the substring at least 4 of A

comment:
This algorithm uses extra space for ACGT count for each i from 0 to n-1, total space is less than 1MB. 
int[] A = new int[500500]; int[] C = new int[500500]; int[] G = new int[500500]; int[] T = new int[500500];
4 bytes for int, then 500K x 4 x 4 = 8M bytes

Sunday watching: Jamie Dimon to HBS MBA Class of 2009

March 6, 2016

Spend time to relax this Sunday, and enjoy the video from Harvard business school:

https://www.youtube.com/watch?v=9T9Kp4NE5l4

Take some notes, and enjoy the teaching.