Saturday, July 16, 2016

Reverse unsigned 32 bit integer - facebook code lab - 5+ practice

July 16, 2016

Problem statement:

REVBITS

Reverse bits of an 32 bit unsigned integer
Example 1:
x = 0,
          00000000000000000000000000000000  
=>        00000000000000000000000000000000
return 0
Example 2:
x = 3,
          00000000000000000000000000000011 
=>        11000000000000000000000000000000
return 3221225472

Practice:

Java Practice:
1st practice: 
code is working, but Java code is using Math.pow(2, index).
https://gist.github.com/jianminchen/395ccf0277250e5d3d68498e0d2238f1

2nd practice: not working, error on 32 bit integer, left most significant bit 1 means negative number. 
https://gist.github.com/jianminchen/7bfdcd0c1643bf01c2bf6ba7acea6f70

Sorry, wrong answer. Your program's output doesn't match the expected output. You can try testing your code with custom input and try putting debug statements in your code.
Your submission failed for the following input:
A : 3
Your function returned the following :
-1073741824
The expected returned value :
3221225472
line 11:  ret += 1 << power;
1 is int with 32 bit.
http://stackoverflow.com/questions/1032982/is-a-java-int-always-32-bits

should be: ret += ((long)1) << power;

3rd practice: fail to fix the issue. 
https://gist.github.com/jianminchen/2b753978ffe983600a031a0fcda7b3a6

4th practice: Use bit manipulation - left shift to get 2^n value - code is working

https://gist.github.com/jianminchen/6a5c1ab71b01414f008b22386000ee59

5th practice:

First, study the solution provided by lab, great idea:
Reversing bits could be done by swapping the n/2 least significant bits with its most significant bits.
The trick is to implement a function called swapBits(i, j), which swaps the ‘i’th bit with the ‘j’th bit.
If you still remember how XOR operation works:

here
0 ^ 0 == 0, 
1 ^ 1 == 0, 
0 ^ 1 == 1, and 
1 ^ 0 == 1.

We only need to perform the swap when the ‘i’th bit and the ‘j’th bit are different.
To test if two bits are different, we could use the XOR operation. Then, we need to toggle both ‘i’th and ‘j’th bits.
We could apply the XOR operation again.
By XOR-ing the ‘i’th and ‘j’th bit with 1, both bits are toggled.
Bonus approach (The divide and conquer approach):
Remember how merge sort works? Let us use an example of n == 8 (one byte) to see how this works:
Remember how merge sort works? Let us use an example of n == 8 (one byte) to see how this works:

              01101001

             /        \

           0110       1001

          /   \       /   \

         01    10    10    01

        /\     /\    /\     /\

       0  1   1  0  1  0   0  1
The first step is to swap all odd and even bits. After that swap consecutive pairs of bits, and so on …
Therefore, only a total of log(n) operations are necessary.
Example:
For the first step, you would do:
    x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
Julia's comment:  5 minutes workout - how to swap odd bit and even bits?
  5 = 101
How to swap odd bit and even bits?
In other words, odd bit becomes even bit; even bit goes to odd bit

First, odd bit shifts to left; even bit shifts to right.

32 bits: 0101 0101 0101 0101 0101 0101 0101 0101
  all odd bit number in x:
    x & 0x55555555
 left shift 1 bit: 
 (x & 0x55555555) << 1)

So, even bits shift to right; 
  A in bits presentation: 1010 
all even bit number in x:
  x & 0xAAAAAAAA

After the swap, the new value is 
   x = ((x & 0x55555555) << 1) | ((x & 0xAAAAAAAA) >> 1);
-- end of Julia's comment --

study the code in C++:
https://gist.github.com/jianminchen/3526dd68e72ae97563cdd61580052016

Flatten - facebook code lab - 2 practices

July 16, 2016

Given a binary tree, flatten it to a linked list in-place.
Example :
Given

         1
        / \
       2   5
      / \   \
     3   4   6
The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
Note that the left child of all nodes should be NULL.

First practice:  Run time error
https://gist.github.com/jianminchen/5cad1bd01525e58da40bff23ab541fc7

Second practice:   Pass all test cases!
https://gist.github.com/jianminchen/8388016355c3e3a393c71b17d508e79b

         1
        / \
       2   3
          /    
         4       

The above tree is serialized by level order traversal, 1 2 3 -1 -1 4 -1 -1 -1

So, that is the reason in the second practice, line ..., line 12, line 34, line 35, discussion of -1 value.

3. Study the iterative solution - editorial solution in C++:

https://gist.github.com/jianminchen/082118552020666ec5c794d1383b6ae8

4. Study the Java solution -

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



Bulbs - facebook code lab - five practices

July 16, 2016

 Work on facebook code lab - bulbs

N light bulbs are connected by a wire. Each bulb has a switch associated with it, however due to faulty wiring, a switch also changes the state of all the bulbs to the right of current bulb. Given an initial state of all bulbs, find the minimum number of switches you have to press to turn on all the bulbs. You can press the same switch multiple times.
Note : 0 represents the bulb is off and 1 represents the bulb is on.
Example:
Input : [0 1 0 1]
Return : 4

Explanation :
 press switch 0 : [1 0 1 0]
 press switch 1 : [1 1 0 1]
 press switch 2 : [1 1 1 0]
 press switch 3 : [1 1 1 1]

1. First practice:
Recursive solution - stack overflow issue:

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

2. Second practice:  Partial correct - work on time complexity

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

Here is the error message:

  • Time Complexity
    Almost there. Your solution is not well optimized for runtime. Focus your effort in solving the problem in shorter time frame.
  • Partially Correct Answer. Make your solution more efficient
3. Third practice:
https://gist.github.com/jianminchen/7093c5dcd52dd72f1ecd06e1d969e648
    Same message, almost there!

4. Fourth practice:  Correct answer
https://gist.github.com/jianminchen/7e934805e2bfa9fe4ce79f3991a4b570

  Highlights of change:
  1. No change on input argument List<Integer>, no List.remove call, no function call of getOpposite

5. Standard answer provided by author - C++

https://gist.github.com/jianminchen/7857bba5138d6c72067eddf40f0f5d5b

Actually, just use one variable - state, and only two states: 0 or 1.

Actionable Items:

1. Go over Java List Interface, and list all APIs here. Try to memorize all APIs.

2. Go over Java Integer class, and list all APIs here.

Entertainment notes:

Julia's favorite practice, first, she forced herself to write Java code in the facebook code lab, no C# support; she started to read more about Java List API, and got some coding experience on basic List coding.

And then, she started to challenge herself to figure out step by step to elegant solution. One step a time.

The practices were quite entertaining, Julia likes the big surprise at the end.

Coding practice talk

July 16, 2016

  Spend some time to work on a small research topic this weekend: "coding practice", "How to conduct rigorous training".

  Read the article about facebook coding requirement, since Julia spent over 3 hours on facebook code lab and then start to find her weakness to work on.



  • Write a working solution and iterate. It's better to have a non-optimal but working solution than random fragments of an optimal but unfinished solution. (Julia's comment: 10/10)
  • Listen for hints. If your interviewer gives you hints to improve your code, please run with them.
  • Prep questions for us in advance. You'll most likely have some time at the end for questions for your interviewer. Some people find it easier to come up with a few questions in advance rather than think of them on the spot.
  • Don't worry about memorizing tables of runtimes or API calls. It's always good to know how to figure out approximate runtimes on the fly but the code you write is more important.
  • If your solution is getting ugly, step back. Most coding interview questions are designed to have reasonably elegant solutions. If you have festoons of if-else blocks and special cases everywhere, you might be taking the wrong approach. Look for patterns and try to generalize.
     (Julia's comment: 10/10)
(Julia's thought: practice more, and also review each practice, write down the issues.)

How to Prepare:


  • Do as many coding questions as you can. Visit Glassdoor, Careercup, Project Euler, orFacebook Code Lab or another site that hosts questions. The idea isn't to see every question, but to become familiar with the pattern of interpreting a question, formulating a solution, and writing an efficient, bug-free program without a compiler.
  • Practice on a whiteboard or with pencil and paper. Practice under time pressure: coding speed is important. The more rigorous your training, the easier you'll find the interviews.
  • Go over data structures, algorithms and complexity: Be able to discuss the big-O complexity of your approaches. Don't forget to brush up on your data structures like lists, arrays, hash tables, hash maps, stacks, queues, graphs, trees, heaps. Also sorts, searches, and traversals (BFS, DFS). Also review recursion and iterative approaches.
    • Our typical coding questions aren't phrased as “implement x”; they're “solve this problem.” You can pick from a number of approaches. (No one is going to ask you “implement Knuth-Morris-Pratt” or “construct a 2-3-4 tree.”)
    • Your reasoning is important. Engineering is all tradeoffs so be able to discuss those.
  • Additional reading resources: Cracking the Coding Interview, Introduction to Algorithms,Algorithms in C.

Learn from the tennis professional player - Milos Raonic - 

http://www.milosraonicofficial.com/about/

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




Sorted Linked List duplicates removal - Facebook code lab

July 16, 2016

  Julia spent over 1 hour to work on this question. So, her first two practices using facebook code lab:

1. Use recursive function - stack overflow issue

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

2. Use iteration solution, but run time performance needs to improve (July15, 2016)/ unreachable code, showing different error messages on July 16, 2016

https://gist.github.com/jianminchen/0318844f35723d6e28d9a90092b2a85c


Then, Julia spent 20 minutes to think if she should use binary search to expedite the search not distinct node - extra array to help, but then, she checked the code lab.

Recall her previous blog on the linked list:

http://juliachencoding.blogspot.ca/2016/05/hackerrank-delete-duplicate-value-nodes.html

(Pass HackerRank test, but fail facebook code lab test? double check)
https://gist.github.com/jianminchen/9013539e71764a018f3745c514da9d91

Her favorite solution: (Pass facebook code lab test)
https://gist.github.com/jianminchen/a13738b4ab32decb8601f29777172209

Julia likes to talk about the issues of her practice on July 16, 2016:





Thursday, July 14, 2016

Leetcode 142: Linked List Cycle II - third practice

July 14, 2016

Third practice:

https://gist.github.com/jianminchen/3b7194dd0f2e3672542046bda3d95d66

Leetcode 142: Linked List Cycle II - second practice

July 14, 2016

Second practice:

https://gist.github.com/jianminchen/65796a60e7320784231bd1883af0d6f8


Transcript:

 Assuming that you have the knowledge how to find the start node in the cycle. It took 20+ minutes to figure out a solution using simple examples, two simple examples are discussed here:


 So, base case coding, line 19 - 20, if the node is null or linked list has only one node, no cycle, return null; 

 Two runners start from start node in the linked list, one moves one step at a time, the fast one moves two steps at a time. 

 Since the fast node explores the linked list in front of the slow one, only check fast node can make 2 steps move or not. 
 The while loop - iteration is to determine if the fast can move forward, if it is true, then slow one can move as well. 
Line 26, while loop, check fast node next two nodes are not empty nodes. 

 Line 27, 28: go to next iteration step, 
 Line 29: check if the slow meets the fast. if it is, find the start node in the cycle:
 Line 29 - 37. The idea is to set slow runner to the start node of linked list, and fast/ slow runners both move one step a time until they meet. 

One concern is the nested while loop from line 29 - 37, the code can be moved out from the while loop, see the practice III:




Leetcode 142: Linked List Cycle II - first practice

July 14, 2016

Continue after first blog on this problem:
http://juliachencoding.blogspot.ca/2016/07/leetcode-142-linked-list-cycle-ii.html

Java solution written in facebook code lab:

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

The code failed to pass some test cases.

Highlight problems on the first writing:




1. line 20,
normalRunner - one step a time, the variable name is too long; slow will be better.

2. line 21,
doubleRunner - the variable name is not so accurate; fast will be better.


problem 1:  base case checking:
line 17:   if(a == null)
                   return null
  if the list is null or only has 1 node, then no cycle.

problem 2: doubleRunner and normalRunner is in the same list, and doubleRunner is ahead of normalRunner if there is no cycle; and if there is a cycle, two runners will run forever. In both cases, only need to check doubleRunner != null, if it is true, then normalRunner != null will be true as well.

In short, doubleRunner != null  =>   normalRunner != null

The while checking has duplicate checking! 

problem 3:
   line 24:  doubleRunner is not null <= it is duplicated with base case checking (line 17)! 
    While loop line 24, doubleRunner != null is duplicate with base case checking.

  While loop design:
Let us check fast node can move 2 steps, next two nodes are not null;
if slow and fast node meets, then break the loop. <- make the logic checking positive, not negative (line 25)

problem 4: 
   while loop is not designed very well - easy to make bugs, hidden bugs.
   line 25: negative checking - make the code more confusing

problem 5:
   line 34: bug001 - if clause checking problem
   line 35: doubleRunner != null => normalRunner != null
   so if statement is not optimal
problem 6:
   line 35: there is a hidden bug here - still cannot figure out.

problem 7:
   line 38: extra variable - not necessary, reuse the old one, still in the scope.
   line 40: not necessary
   line 41: not necessary

Actionable item:

1. Document the mistakes made in the practice, learn from the experience.

2. Review code and figure out issues without any help.

Could not figure out bugs in the first practice
-> Failed facebook code lab test cases
-> Studied optimal solution
-> Ran optimal solution in facebook code lab
-> passed all test cases
-> then, started to find problems in the first practice
-> wrote down problems one by one






Train insane or remain the same - focus on training!

Leetcode 142: Linked List Cycle II - two examples to show the idea

July 14, 2016

 Work on facebook code lab - Linked List Cycle, same question as Leetcode 142.

 Problem statement:

 Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
Work on two simple examples, and then, figure out the solution first:
Example 1: 

Example 2:


First, find the node two pointers meets - one slow runner, one step a time; one fast runner, two steps a time. If there is a cycle, two nodes will meet. 
And then, start from meeting place, one node starts from node 0, slow node continues from meeting place, then, two nodes will meet at the beginning of cycle. 
Facts about the practice: 
1. Julia worked on this problem before. But she has to figure out the solution again. 
2. Spent over 20+ minutes and still confused about the solution. 
two distance values: 
meeting place -> cycle starting node
cycle starting node -> meeting place
Use the first one, not second one. But, Julia was trying to figure out the second one. 

Denote d1 as starting node to cycle starting node
Denote d2 as cycle length

Discuss two cases:
d1 > d2,
d1 <= d2,
and when the two pointers meet, the fast node may go through cycle more than once.

The formula is not deterministic, so it is better to go through the simple example, and then, make a guess.

3. Google the blog about the solution:
https://siddontang.gitbooks.io/leetcode-solution/content/linked_list/linked_list_cycle.html
July 15, 2016
Read more blogs:
The analysis has some issues: 
http://www.cnblogs.com/hiddenfox/p/3408931.html
http://www.cnblogs.com/wuyuegb2312/p/3183214.html
http://yucoding.blogspot.ca/2013/12/leetcode-question-linked-list-cycle-ii.html

Sunday, July 10, 2016

Data Analysis Fundamentals with Tableau - pluralsight.com

July 10, 2016

 Plan to spend 4 hours to study the course on pluralsight.com - "Data Analysis Fundamentals with Tableau".

 https://www.pluralsight.com/authors/ben-sullins

Watch first 2 hours while going through twitter account of instructor - data geek - get ideas how / what data geek is so good at presentation through social media.

 People working on BI are in general much better to do presentation.

Show Me The Data!
Demo: Mapping


CSS learning / forgetting - a better cycle

July 10, 2016

  A few days ago, Julia could not recall CSS text_decoration text-decoration rule. She likes to find underline a word using a CSS property.

  So, she tried to fail better next time when she forgets CSS - how she can do that?

  Answer: Try the following

  1. Use her memory - push herself to memorize a CSS cheat sheet in a 2 weeks/ 30 minutes a day, and then, she will read more about CSS properties as a daily routine.

2. More cheat sheet about CSS and Regular Express:
https://codingsec.net/2016/04/complete-cheatsheet-csscascading-style-sheet/

3. https://www.cheatography.com/davechild/cheat-sheets/css2/

4. Read document 30 minutes a time:
https://developer.mozilla.org/en-US/docs/Web/CSS
https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors
CSS Selectors
   Basic Selectors
        Type selectors
        Class selectors
        ID  selectors
        Universal selectors
        Attribute selectors  (July 14, 2016 30 minutes - go over ~, |, ^, $, *, i)
            ~,              |,               ^,      $,      *,        i
            one of which, value or value-, prefix, suffix, contains, case insensitive,

        Combinators
           Adjacent sibling selectors
           General sibling selectors
           Child selectors
           Descendant selectors

        Pseudo-classes  (36)
           :active
           :checked
           :default
           :disabled
           :emtpy  

           :enabled
           :first
           :first-child
           :first-of-type
           :focus

           :hover
           :indeterminate
           :in-range
           :invalid
           :lang

           :last-child
           :last-of-type
           :left
          :link
           :not()

           :nth-child
           :nth-last-child
           :nth-last-of-type
           :nth-of-type
           :only-child

          :only-of-type
           :optional
           :out-of-range
           :read-only
           :read-write

          :required
           :right
           :root
           :target
           :valid

    :valid
Julia had hard time to memorize 36 pseudo classes, get some reading:
Pseudo classes:

    https://www.smashingmagazine.com/2016/05/an-ultimate-guide-to-css-pseudo-classes-and-pseudo-elements/

     https://css-tricks.com/pseudo-class-selectors/

5. CSS courses on pluralsight.com
CSS position
Introduction website layout
http://app.pluralsight.com/author/susan-simkins

CSS in-depth  6 hour course
(July25, 30mins/ Specificity 10m)
http://app.pluralsight.com/author/estelle-weyl

-- Past Experience --
  In 2013,
  Her favorite book: Head first Html with CSS & Xhtml
  Her favorite CSS learning starting from 2013: She found out that she could not read CSS code without knowing CSS selectors.

  In 2013, Julia tried to memorize all selectors - she worked on the drills to memorize all of them, write on papers etc. Show the paper writing to celebrate over 36 months - dated on on May 9, 2013 - CSS learning handscript . Post a picture here.

  Her favorite CSS blog about CSS selector.

  http://code.tutsplus.com/tutorials/the-30-css-selectors-you-must-memorize--net-16048

-- Motivation talk -
  Share a favorite verse from Julia's favorite professional ATP player:

 http://heavy.com/sports/2015/06/stan-wawrinka-tattoo-say-mean-daughter-wife-french-open/

 https://www.theguardian.com/sport/2014/jun/09/stan-wawrinka-queens-rafael-nadal-novak-djokovic

 Stan Wawrinka is one of the most intense, hard-working players on the ATP Tour; dedicating himself to every point, giving everything in the quest for victory, no matter the cost.


And Wawrinka’s ink, unsurprisingly, reflects his tennis weltanschaung. On the inside of his left arm are the words of poet Samuel Beckett: Ever tried. Ever failed. No matter. Try Again. Fail again. Fail better.


Leetcode 56: Merge Intervals

July 10, 2016

Leetcode 56: Merge Intervals

study the code:
http://xiaoyaoworm.com/blog/2016/06/27/%E6%96%B0leetcode56-merge-intervals/
https://gist.github.com/jianminchen/a75a3ff78dbb863774b3b97da0d150f8

Write down C# code - 20 minutes workout later.

Sept. 24, 2016

The idea is the following:
1. Sort the list of intervals by start value;
2. Do iteration in the following
base = first.interval
foreach(interval in list)
{
    if base.end < interval.start
   {
      result.add(base);
      base = current;
      base
      ___________
                                current
                                _____________
    }
    else
    {
        (1)   base
              ------------------------
                          current
                      ---------------------
        (2) base
            ____________________
                     current
                  _________
          _____________________
             new base
     }
}

Have some drawing to analyze the problem.

blog reading:

http://www.canadianbusiness.com/leadership/office-space/microsoft-canada-vancouver/

http://www.canadianbusiness.com/leadership/office-space/jordan-banks-facebook-canada/image/2/

Editorial Notes:
1. Julia, could you write down your experience about this problem solving?
Answer: Julia spent 8+ hours to work on the HackerRank world code sprint #7 problem solving.

The idea is to find most simple task you can complete:

Two intervals are not overlapped, so left one should be added to result collections, and move to next one. In order to find the first one, sort the intervals using start time.