Thursday, April 21, 2016

Insert value into a circle linked list

April 21, 2016

Work on an algorithm called "Insert value into a circle linked list"


http://www.geeksforgeeks.org/sorted-insert-for-circular-linked-list/

another problem:

Insert into a cyclic sorted list:

http://articles.leetcode.com/insert-into-a-cyclic-sorted-list/

Question and Answer:
1. Three cases:
  1. prev→val ≤ x ≤ current→val:
  2. Insert between prev and current.
  3. x is the maximum or minimum value in the list:
    Insert before the head. (ie, the head has the smallest value and its prev→val > head→val.
  4. Traverses back to the starting point:
    Insert before the starting point.
2. Let us walk through the code, and put some comment:

void insert(Node *& aNode, int x) {
  if (!aNode) { // Julia: if the node is empty, then, create one, link to itself to form a loop
    aNode = new Node(x);
    aNode->next = aNode;
    return;
  }
  Node *p = aNode; // Julia: two pointers, one is current, one is previous, get into a loop
  Node *prev = NULL;
  do {
    prev = p;
    p = p->next;

int[] arr = new int[2]{prev->data, p->data}; // Julia: add some explanation variable

    if (x >= arr[0] && x <= arr[1] ) break;   // For case 1)
    if ((arr[0] > arr[1]) && (x > arr[0] || x < arr[1] )) break; // For case 2)
  } while (p != aNode);   // when back to starting point, then stop. For case 3)
  Node *newNode = new Node(x);
  newNode->next = p;
  prev->next = newNode;
}

Two rectangles to see if they overlap

April 21, 2016

Work on algorithm called Two rectangle to see if they overlap.
http://www.geeksforgeeks.org/find-two-rectangles-overlap/

http://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other



Find optimal weight

April 21, 2016

Find optimal weight - an algorithm to study

Matrix shortest distance set - get its Maximum value

April 21, 2016

Try to work on this algorithm, including problem statement, algorithm involved, and then, get similar question on HackerRank, and do some practice.

矩阵路径最小值的最大值:
 给一个int[][]的matirx,对于一条从左上到右下的path p_i,p_i中的最小值是m_i,求所有m_i中的最大值。只能往下或右




Window minimum

April 21, 2016

Try to get some algorithm reading and then find a similar algorithm in HackerRank, and get some workout on coding.

It is called Window minimum.

Problem statement from the geeksforgeeks website


Given an array of size N, a window of size W slides over it by increment of slide S. If the window reaches to the end, we should stop there. Find a formula in form of N, S, W so that we can find the number of valid windows. Write a program to find minimum in every window and print it. Optimize it.
e.g. {1,2,3,4,5}, W=2, S=1
first window: {1,2} min=1
second window(increment by S=1): {2,3}, min=2
last window: {4,5}, min=4
The array might not be sorted. I have taken sorted array for simplicity.

or in Chinese, 
滑动窗口求最小:
 给了一个ArrayList:4, 2, 12, 11, -5,窗口size为2,返回的ArrayList为:2, 2, 11, -5。这里窗口size是一个参数。

Leetcode 239: Sliding window maximum

Read one of solutions using Java:
Java solution 

K nearest point

April 21, 2016

Try to find similar algorithm in HackerRank about K nearest point, and get some workout on coding.

Read the blog:

https://www.glassdoor.co.in/Interview/Given-a-list-of-points-in-2D-and-a-single-reference-point-find-k-nearest-neighbors-No-code-required-iirc-QTN_296848.htm


https://www.careercup.com/question?id=4751976126480384

https://www.quora.com/What-are-the-some-of-the-problems-on-the-heap-priority-queue-on-SPOJ-HackerRank-CodeChef-Codeforces-or-HackerEarth

Julia, try to work on one of 4 questions using priority queue/ heap:

https://www.hackerearth.com/code-monk-heaps-and-priority-queues/judge/

Read the tutorial: (Excellent reading time - 1 hour)

https://www.hackerearth.com/notes/heaps-and-priority-queues/

Take some notes:
Heapify process, using array to store the heap, amortized heapify analysis - O(N) instead of O(nlogN)

Many ways to implement the priority queue.

Naive approach to build priority queue:
1. a list, sorted them, so O(NlogN) time

Efficient approach:
using heaps to implement the priority queue. It will take O(logN)to insert and delete each element in the priority queue.


C# tutorial - reading first, coding follows

April 21, 2016

Julia found something she likes - C# tutorial
read it every day when you have 20 minutes in the morning.

https://msdn.microsoft.com/en-us/library/aa288436(v=vs.71).aspx


Julia likes to make C# her professional language - 35% of programmer are using C#, 40% of programmer are using C++, 40% are using Java; Some of them use more than 1 programming language.

Get more tips to help C# learning, help fast coding.



Tuesday, April 19, 2016

HackerRank: facts to share

April 19, 2016

Read one more blog:
http://blog.hackerrank.com/dreams-silicon-valley/

Notes:
HackerRank is a great platform — the challenges are approachable and related to real-world problems. The best part about it, though, is that there are some great coders who compete on HackerRank, so you can evaluate how you’re compared with e.g. top 1% of hackers. It’s very motivating and inspiring — in my case it was enough to make me solve a majority of problems listed there initially.

Some people might be drawn to Silicon Valley to chase their dreams of money and fame. But for me, my dream was as simple as making it there, to be surrounded by the best talent in the industry.

More reading:
http://goo.gl/m6jcFE

video: How to Keep Calm at Crunch Time - Ask Ian #31

April 19, 2016

To write code for a competition/ assessment is to like to play a sports match. Julia still has to work on mental toughness, and improve her probability to pass any code assessment. How to keep calm in crucial moment?

Spend a lot of hours to work on techniques, practice; but in the crucial moment, allow the pressure take control, and cannot execute as normal.

How to do your best?  practice, continue to improve and be in present. It takes a lot of discipline. A lot of experience under the situation. Be in present, problem solving.

Take notes from the talk in the video:

Key #1:
1. Be present. Do not think about past, do not think about future;

Do not allow yourself travel time line; What if you lose, do not take it too seriously; do not focus on the future outcome. Second guess themselves, it is not good.

Focus on present, problem needs to be solved.

2. Learn to embrace your nerves and anxieties. Everybody gets nervous, does not matter how good you are, how long you play. Every one has anxiety, every one has fears over winning or losing. It is natural response if you are put in the competition.

As a matter of fact, it is a great thing to feel nervous and anxiety. This shows that you care about outcome. Use it to sharpen your focus, sharpen your perform.

Do not put yourself in a downward spiral.

video link:
https://www.youtube.com/watch?v=t8KjshrxS48

Arguments:

Amazon hiring bar: better coding than 50% existing employees. Code assessment is just a basic skills indicator. Learn from the experience.

https://goo.gl/HkHyFV

Always memorize a bible verse to calm down:

How precious to me are Your thoughts, O God! How vast is the sum of them! Were I to count them, they would outnumber the grains of sand.

Psalm139: 17 -18 NIV

June 14, 2016
Study 2 hours on the blog:
https://www.quora.com/How-can-I-get-over-my-failed-interview-at-Amazon


Study the article - July 4, 2016

http://firstround.com/review/Mechanize-Your-Hiring-Process-to-Make-Better-Decisions/

Monday, April 18, 2016

HackerRank: Matrix Rotation (Series 3 of 5) - using extra space - an array

April 18, 2016 
Rotate array - HackerRank

problem statement:
https://www.hackerrank.com/challenges/matrix-rotation-algo


Study other's code:

https://gist.github.com/jianminchen/9005cbbbbbd60e307759747856e3a35a

Write a solution using the same idea. Try to practice 20 - 30 minutes.

Just be simple; Read other people's code, like it; and then, write exactly same idea, and see if you can make it work as well.

Write same algorithm again and again, use various ideas; same idea, write again and again, see if you can improve the performance, more concentration - write the program from hours to 30 minutes, less than 10 minutes. Practice makes perfect.

To be continued:
Action item:

Will write my own version of implementation.






HackerRank: Matrix Rotation (Series 2 of 5)

April 18, 2016 
Rotate array - HackerRank

problem statement:
https://www.hackerrank.com/challenges/matrix-rotation-algo


Study other's code:

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

So, do not swap two nodes value, just save first node's value in a variable, and then, shift array kind operation.

Write C# solution:


another practice: (more than 1 hour, still having bugs, score 8.89/ wrong answer)
https://gist.github.com/jianminchen/57572227dafe939060f7cc81b193cd9b

Time spent:

More than 2 hours 

K index - Algorithm (II) using Queue

April 18, 2016

More code writing. Try to use Queue to solve the problem. Write more than one solution using Queue.

Julia practiced twice, first one hour she failed some test cases using HackerRank. And then, she tried again.

Practice #2:
https://gist.github.com/jianminchen/ce7ccfa5db5b57c36d6742b622e9153e

First blog about this algorithm - K index:

http://juliachencoding.blogspot.ca/2016/04/k-index-algorithm.html

Julia wrote C# implementation using Queue,
https://gist.github.com/jianminchen/63c0bccec2ab476d71abbe43c8837566

Test cases:
1. Input
4
1     2   3     4
5     6   7     8
9   10 11   12
10 14 15   16
2
Yes, 10 is found at arr[3,0], 2 steps away from arr[2,1]


Time spent:
More than 30 minutes

Learned from mistakes:
1. Two dimension array arr[,], use getLength(0) and getLength(1) for first and second dimension length; But, jagged array - arr[][], getLength(1) will throw exception, use arr.Length, arrp[0].Length to check the size.
 
The first practice using queue, Julia created a run-time exception - index out of range; the error is so late to catch, not in compile time. So, take it seriously. Array, two dimensional array, jagged array are very basics.

https://gist.github.com/jianminchen/93f963043c47649a496a2fccc862d801

change search array to use two dimensional array:
https://gist.github.com/jianminchen/9346c2d2cb2e611ec2db3519dc7a879a

Read blog:
http://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays
http://stackoverflow.com/questions/12567329/multidimensional-array-vs?lq=1

https://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

April 21, 2016
Julia found something she likes - C# tutorial
read it every day when you have 20 minutes in the morning.

https://msdn.microsoft.com/en-us/library/aa288436(v=vs.71).aspx

Sunday, April 17, 2016

HackerRank: Connected Cells in a grid (V) - C++ solution

April 17, 2016

problem statement:

https://www.hackerrank.com/challenges/connected-cell-in-a-grid


C++ solution:
spent time: 40 minutes

1. use pair<int, int>, make_pair, and queue; very short code - excellent!

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

pair, make_pair, understand the standard library function template - make_pair:
http://www.cplusplus.com/reference/utility/make_pair/

2. Another solution:
https://gist.github.com/jianminchen/93839295fb15ab1a7d2226213f15dcd0

3. use vector
https://gist.github.com/jianminchen/3e489592beaa267c10540302bf08745b

4. interesting solution, no queue, no recursive calls; just store the values:
4
4
1 1 0 0
0 1 1 0
0 0 1 0
1 0 0 0

{-5, 0, -1, -1, -1, 0, 0, -1, -1, -1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, ...}           int[111]

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

HackerRank: Connected Cells in a grid (IV) - JavaScript code

April 16, 2016

problem statement: Connected cells in a grid



JavaScript submission:
Time spent: 30 minutes

Read 5 - 10 submissions, write down good tips:

All Javascript submissions


1. Favorite JavaScript implementation:

Javascript connected cells in a grid

2. Very structured JavaScript code, using prototype, ===, neighbor nodes - an array - [], define function acting like class Node.

https://gist.github.com/jianminchen/8f17d6582ce6335af33e952450d255a3


Small talk - muscle memory from 100 hours to 500 hours

April 17, 2016

Julia is still a beginner to write answers for questions on Quora, so she tried to practice on her own blog first.

Answer the question on Quora:

How to perform at work? 

http://qr.ae/8NYfUf

Julia's thoughts based on her sports experience - muscle memory based on practice, from 100 hours to 500 hours, a few mistakes and then reward experience:

Finally, I found some article to read, and then, try to express my ideas and concerns, relieve some stress.

First take notes from the talk:
1. Constant learning is everything in our line of work and the perpetual hunger for knowledge will keep you sharp throughout your years.

2. Like tennis sports, find a good tennis coach, maybe, it is also a solution to find a therapist that can guide your along the path of improvement of your self-esteem and self-evaluation.

3. If you are dealing with serious companies who will value you for your strong CS fundamentals and the ability to think in math and algorithms, they really don't give a damn if you don't speak their lingo yet, because they will see in you an innate ability to learn, even quicker than others and know that you'll ultimately be able to chew whatever they throw at you.

Julia's thoughts:

Confidence, and play nice, always be calm under stress at work. It takes a lot of practice, and learn through the experience. At work, you cannot play like sports; In sports, you make mistakes, and then, you try to fix them. Learn from sports activities's mistakes is much cheaper.

Still remembered that first day showing up in Burnaby central park tennis court in summer of 2012, I told a Chinese that I played tennis over 10 year from 2001 - 2010, one hour every 2 weeks; After 10 minutes to rally with him, he told me that I have to go to the wall and then practice against the wall. I found out that people over the park may have play hundreds of hour tennis.

Later, people ask me how many hour I put on tennis sports already. 100 hours, 200 hours, 300 hours. I started to measure my hours spent, I did spend summer time every day 2 hours after work, 7:00pm - 10:00pm; the whole summer, over 100 hours, what it means, I lost at least 20 lb, first time, I built muscle around my stomach.

Mistakes made in tennis sports:

1. Hurt my wrist, wrist pain <- put a lot of hours on practice, do not have muscle memory to protect wrist; In my first 100 hours practice.

2. Hurt my back, fall on the ground in a double match <- could not walk after standing up at office after falling accident. In my first 200 - 300 hours practice, do not have muscle memory, knowledge of balance. To maintain body balanced is most important, it does not worth to fall in order to save a point.

3. Swing forehand, racket hitting my head, my legs/ arms a few times. <- after 200 - 300 hours practice


But I learned from tennis sports, how important it is to love the sports; build up relationship to your hitting partners, help each other to practice, and get improved; How important it is to find new players, help them improve, and then, you have a new hitting partner on the court.

So, people will feed me tennis balls; And invite me to play matches.

Certainly, I also learn to play for fun, not too cheap; give people some decency, not cheating on points when playing games, give people credit when in doubt. Show respect and encourage people to play more sports through the game activity.

Right now, I am totally going to extreme;  To play social games, when the team I am in to win 2 sets in double games, my partner and I will let the opponent to win 3rd game.

Summarize what I say, in tennis sports, I learn a lot of people skills from my practice. People can help you achieve more on sports activities as well. You learn quickly how to read people, and get workout done.

So, too far away from topic - how work is related to sports?

When in trouble at work, sometimes, it is ok to be panic, get frustrated; but, tell the boss that "I am still learning". Ask for fair chance to learn, catch up, recover.

Recently, I found out that I broke the principles when I wrote code, If I have followed "Do not repeat yourself" principle closely, or "Single Responsibility Principle", I should be less stressful to maintain products. I can exhaust all the test cases for a simple function/ class quickly, but I could not handle a function with more than 200 lines of code, just by human eye, not using debugging. If you play good on design principles, you find yourself in better situation.

Stop complaining. Just work hard. It takes more than 1 year to figure out how to excel at a job. My case, I think that it takes more than 5 years.

Blog reading:

1. Read this blog about C++ study.


2. sports programmer - Gennady Korotkevich



HackerRank: Connected Cell in a Grid (III) - C# solution (III) - using recursive function

April 17, 2016

problem statement:

https://www.hackerrank.com/challenges/connected-cell-in-a-grid

Here is the code studied using DFS function with return value.

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

Julia likes to practice using same idea, write her own implementation.

Practice #1: 

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

Time spent:

Copy main function from previous implementation, and write recursive function - it takes less than 15 minutes.

First time write, no bug!

April 18, 2018

Here is another writing over 30 minutes:
Practice #2: 
https://gist.github.com/jianminchen/d434bcc59ebc8eb7c2cbb20c6f48ac06

The practice goal is to see if I can shorten the time to 10 minutes in writing. How good I can write.

But, surprisingly, the practice takes 30 minutes; and I found out the several issues:
1. Timeout - recursive calls, if/ while checking
2. Array.GetLength api

First, time out issue; read a row of '0' or '1', should be if, I put a while. <- it takes more than 10 minutes to find out. I pinpoint recursive call, because I have doubt, not 100% sure.

And then, I tried to avoid the recursive call to itself, and then, (dr, dc), mistakely I put (dr, dr); HackerRank shows wrong answers for 2 test cases.

Make one change a time, and see if I can shorten the time to 10 minutes.

Study Array.getLength()
https://msdn.microsoft.com/en-us/library/system.array.getlength(v=vs.110).aspx

Another version, it takes 14 minutes to write, without a bug:
Practice #3: 
https://gist.github.com/jianminchen/bd155e574b32ebb163455dad02fa76b1

Julia's performance is up and down, from 15 minutes to 30 minutes.
Again, all practices links:
#1
https://gist.github.com/jianminchen/fd909c3545e2081cf2dd2b6daea5900f
#2
https://gist.github.com/jianminchen/d434bcc59ebc8eb7c2cbb20c6f48ac06
#3
https://gist.github.com/jianminchen/bd155e574b32ebb163455dad02fa76b1

Work on speed and accuracy. Practice, more concentrated on writing. More alert on bug code. More knowledge about api, and basic things.

Learn Jagged Array -
http://stackoverflow.com/questions/597720/what-are-the-differences-between-a-multidimensional-array-and-an-array-of-arrays

HackerRank - Connected Cell In A Grid (II) - C# solution (II) using Queue

April 17, 2:50 - 3:25

Problem statement


First practice using C#,  solution written by Julia:

C# practice by Julia


Study the code: 
1. Use Queue, instead of using recursive calls, using 2 dimension array, excellent code to study:

Study code 

So, Julia did one more practice, and just wrote second implementation using idea in the above blog. 

Write C# code again using idea - 2 dimension array, queue, and also, mark the visited node using '2'. 
C# solution 1

Second Practice

It takes 30 minutes to write and fix bug, log interesting things happening in the practice:

1. First, fix the issue to read a row to a string, and then go over one char a time to get each node for the row.

   use Console.ReadKey()  first <- fatal error

2. use wrong local variable about key

3. Count should be 5 but 11 for one test case, count same thing more than once! - > add extra checking before counting. Or, set node is visited just before adding to the queue. 

Compare to the solution #1, two dimension array uses integer 1 or 0, my copy is using char '1', '0';
And also, the solution #1, every node sets visited true before adding to queue.
And my design, do not set, which causes problem. Same node is added to the queue more than once.

It is better to add unvisited node to the queue once.

Julia, you have to make sure that no bug in the code, it does not matter what idea you use. 

Third practice:

Write in 20 minutes, no bug:

3rd practice using C#


Again, 3 practices:

No. 1 - C# code

No. 2 - C# code

No. 3 - C# code




Saturday, April 16, 2016

HackerRank: Connected Cell in a Grid - C# solution - using DFS

April 16, 2016

Practice one DFS algorithm this Saturday.

problem statement: connected cell in a grid


C# solution written by Julia:


Time spent:  4:48pm - 5:41pm 
20 minutes to think about design, 
30 minutes to write the code
Feeling: nervous when thinking about solution - DFS, it took more than 15 minutes
Study other submissions, and see if I can learn something, also figure out how to cut time to write the code. 

C# solution: 
Time spent: 60 minutes

1. Use Queue, intead of using recurisve calls, using 2 dimension array, excellent code to study.

Tips to learn: 
1. use integer as key: i*10+j
2. mark the visited node using value 2

2. Design the function to return a value 

Julia, people are smart, no need for extra bool array[row][col], just mark the visited node using a new value:

1. mark visited node using 'X'

3. use C# Tuple class, declare a shift array to get more organized. 8 neighbors nodes - go through array twice.


4. study the code


5. declare offset array for x and y - Julia likes the idea.

https://gist.github.com/jianminchen/737138aeb946961aded556181c06502e

Statistics:

1. 10 submissions, there are at least 2 of them using queue - Julia, you have to catch up this using queue!  <- write queue version, practice it 20 minutes, post your version down here!
2. 10 submission, 2-3 DFS algorithm return count <- easy way to track the count
3. Different ways to mark the node is visited.

Reviewed the algorithm on Nov. 16, 2016
- some one found the page through yahoo.com search.

Thursday, April 14, 2016

HackerRank: Matrix Rotation (Series 1 of 5)

April 14, 2016

Rotate array - HackerRank

problem statement:
https://www.hackerrank.com/challenges/matrix-rotation-algo

Spent hours to work on the solution, passed 4 basic test case, but still score 0 out of 80 points:

https://gist.github.com/jianminchen/4d719488e378aeb498d4cb363cbd1f7d

Just be patient. Study other's code:

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

So, do not swap two nodes value, just save first node's value in a variable, and then, shift array kind operation.

Corner case is very simple. Julia wasted hours to work on poor design, try to avoid overwrite the value of arr[1][0]. Just use a variable to save it.

https://www.hackerrank.com/rest/contests/master/challenges/matrix-rotation-algo/hackers/Relentless/download_solution

So, changed my own code, with bugs to fix:  Int16 should be int, check Int16 max value 32767, whereas Int32 max value 2,147,484,647, less than 3 *10^9
https://gist.github.com/jianminchen/6e3ca88e8633ad8bace8387f154904df

only pass one case:
https://gist.github.com/jianminchen/12b58729c59e44a0d71d9f9c47bc937c

another practice: (more than 1 hour, still having bugs, score 8.89/ wrong answer)
https://gist.github.com/jianminchen/57572227dafe939060f7cc81b193cd9b

study the code here:
https://gist.github.com/jianminchen/6e2ca0ac395913646ed012c40c283e7f

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

study forum:
https://www.hackerrank.com/challenges/matrix-rotation-algo/forum







Wednesday, April 13, 2016

HackerRank: String Calculate function (III) - LCP array

April 13, 2016

Still work on the problem:

Problem statement:

https://www.hackerrank.com/challenges/string-function-calcula


Put together 2-3 hours on LCP array study first, and then, work out a solution for this advanced algorithm.


The LCP-LR array helps improve this to O(m+logN)O(m+logN), in the following way


LCP array reading
https://www.hackerrank.com/challenges/pseudo-isomorphic-substrings/topics/lcp-array

https://en.wikipedia.org/wiki/LCP_array

Question and Answer:

Before you write LCP implementation, tell me what you learn about LCP, give me an example you work on? 

Tuesday, April 12, 2016

Advice for practice on coding question - easy, medium to hard questions

April 12, 2016

Good Sharing from the following blog:
Know new people and their success story:

Easy, medium questions, just for coding, not much algorithm. Practice coding questions. And then, move to hard questions. And come back to easy, medium questions again, to improve speed.

https://www.quora.com/How-does-Ahmed-Aly-practice-for-competitive-programming

Very good story:

https://www.quora.com/Whom-do-you-respect-the-most-in-the-world-living-Why/answer/Ahmed-Aly?srid=o3vR

How to improve? Solve a lot of problems, easy problems.

http://qr.ae/81vRga

Julia's thought:

No time to write your own solutions. Then, read a lot of solution, over 100 solution for one problem. Easy problem, string, on HackerRank, read all kinds of solutions, more than 20 of them; and try to understand them first.

Coach gave tips how to improve quickly?
http://qr.ae/81vc1V

Talk about bugs: 
http://qr.ae/81rRyj

Julia's thought:
Debug takes time.

Relax and read more coding blog:
From MSFT, and
https://www.quora.com/profile/Duncan-Smith-23

http://www.redgreencode.com/

weekly bolog about TopCoder competitive algorithms:
http://petr-mitrichev.blogspot.com/2016/04/a-doubles-week.html

rotate array

April 12, 2016

Rotate array one element to right or down, clockwise.

For example:
1 2 3
8 9 4
7 6 5

After rotation, the matrix is the following:
8 1 2
7 9 3
6 5 4

Practice: (Time spent: 1 hour)
https://gist.github.com/jianminchen/24d77970e9a58a7850f2add10dfe7c4f

Failed test case:
1 2
4 3

output should be:
4 1
3 2

but my result:
3 2
4 1

Bug fix: (Time spent: 20+ minutes)
https://gist.github.com/jianminchen/6eb6244fbb1912e3a06e672f604f87e0

        /*
         * Do it in place
         */
        public static bool rotateArray(int[][] arr, int k)
        {
            if (arr == null) return false;
            int n = arr.Length;  // row
            int m = arr[0].Length; // column

            if (n != m) return false;
            if (n != k) return false;

            int start = 0;
            int end = k - 1;

            while (start <= end && start < k / 2)
            {
                // for left column
                swap(arr, start, start, start, start + 1, k);
                for (int i = start + 1; i <= end; i++)
                {
                    swap(arr, i, start, i - 1, start, k);
                }

                // for down row - swap
                for (int i = start; i < end; i++)
                {
                    swap(arr, end, i, end, i + 1, k);
                }
                // for right column
               // for (int i = end; i > start; i--)  // bug 001  if there are only two rows, exception
                for (int i = end; i > start && (end-start) > 1; i--)  // bug001 fix - do not swap if there are two rows
                {
                    swap(arr, i, end, i - 1, end, k);
                }
                // for up row              
                for (int i = end; i > start + 2; i--)
                {
                    swap(arr, start, i, start, i - 1, k);
                }
                start++;
                end--;
            }
            return true;
        }

Action item:
Base case 1x1,  2x2, and then 3X3, you cannot skip 2x2. It doesn't t matter what test case is given. Think about basics.

Also, think about how many swaps are needed for
1 2
4 3
only 3 swaps:
First one,
1 and 2
1 2
second one:
2 and 4
2
4
third one:
2 and 3
2 3

<- and then, need to filter out last 2 swaps in the while loop.

Relax, take more practice:
Smart to use debugger:
https://www.quora.com/Does-using-debugger-help-a-lot-in-competitive-programming

https://www.quora.com/What-are-the-best-competitive-programming-debugging-tips

April 15, 2016
Better design is to save arr[0][0] value, and then shift array value to left on top row. Make corner case much easy to handle.
So, good ritual is to come out more than 1 idea, and then, compare which one is better. Ask why!

Swap value cannot beat the array shift, much simpler the later one.

K Index algorithm

April 12, 2016

An array, to search if there is duplicate in k steps distance

First practice, two bugs (Time spent: 1 hour):
https://gist.github.com/jianminchen/1fec656b154a70acb30b5f6d7ad509ab

 private static bool DFS(int[][] arr, int oriX, int oriY, int row, int col, int kIndex, int search, int MaxRow, bool[][] searchedA)
        {
            if (!isValid(row, MaxRow) || !isValid(col, MaxRow) || kIndex < 0)
                return false;

            if (Math.Abs(oriX - row) + Math.Abs(oriY - col) > 0 && !searchedA[row][col])
            {
                if (arr[oriX][oriY] == arr[row][col])
                    return true;
                //bug 001 - Julia, you need to continue do DFS here
            }
            else
            {
                searchedA[row][col] = true;

                // bug 002 - all those DFS search, you need to check search result! 
                DFS(arr, oriX, oriY, row - 1, col, kIndex - 1, search, MaxRow, searchedA);
                DFS(arr, oriX, oriY, row + 1, col, kIndex - 1, search, MaxRow, searchedA);
                DFS(arr, oriX, oriY, row, col + 1, kIndex - 1, search, MaxRow, searchedA);
                DFS(arr, oriX, oriY, row, col - 1, kIndex - 1, search, MaxRow, searchedA);

            }

            return false;
        }

Fix two bugs (Time spent: 20+ minutes):

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

function after bugs are fixed:
 private static bool DFS(int[][] arr, int oriX, int oriY, int row, int col, int kIndex, int search, int MaxRow, bool[][] searchedA)
        {
            if (!isValid(row, MaxRow) || !isValid(col, MaxRow) || kIndex < 0)
                return false;
         
            if (Math.Abs(oriX - row) + Math.Abs(oriY - col) > 0 &&  !searchedA[row][col] )
            {
                if (arr[oriX][oriY] == arr[row][col])
                    return true;                            
            }
         
            searchedA[row][col] = true;  // Bug001 - check condition is wrong 

            if (DFS(arr, oriX, oriY, row - 1, col, kIndex - 1, search, MaxRow, searchedA) ||
            DFS(arr, oriX, oriY, row + 1, col, kIndex - 1, search, MaxRow, searchedA) ||
            DFS(arr, oriX, oriY, row, col + 1, kIndex - 1, search, MaxRow, searchedA) ||
            DFS(arr, oriX, oriY, row, col - 1, kIndex - 1, search, MaxRow, searchedA))
                return true; // bug002 - any of conditions are ok, then, return true

            return false;
        }

Actionable item:
1. Julia, you have to build up skills to do code static analysis. Debugging takes time, you should check your logic, run your code through yourself by thinking, criticize your code by thinking about the test case, go through virtually first.

April 18, 2016
Julia, you should have more than 1 idea to solve this kind of problem - thinking about using Queue to solve it.