Monday, July 12, 2021

Algorithm practice: I need to get back to work on coding again

 July 12, 2021

Introduction

I like to work on a short and quick research. Why I should work on Leetcode coding every day? 

Life is challenge | Take more risk

I should think about more carefully what I should work on. I should start to work on Leetcode algorithms again. 

Once I build a good habit to code every day, I will start to build some new skills, and I should be more happy, and be a better problem solver in other areas of my life. 

Do not get frustrated. Go back to practice again.

It is not too difficult to get back on practice. I have solve over 600 algorithm, this year I only solved less than 50 algorithms, less than 10 algorithms for every month. 

Facts to review

I used to play hackerrank contest, and then I played leetcode weekly contest. I also work on Leetcode algorithms as well. 


3 days preparation | 10 algorithms to practice | Failed phone screen

 July 12, 2021

Introduction

Hard work beats talent. I have to prepare and practice over 100 algorithms, at least I should fail 10 times in my practice first so that my spirit will go high and be ready to face whatever challenge it is. I like to write a short blog to remind myself, do not waste the opportunity again. 

3 day preparation | 10 algorithms to practice | Failed phone screen

I just could not believe that I should learn how to work hard and prepare better next time for phone screen. 

  1. First I should try to practice continuously at least 3 days, 3 * 8 hours a day; 
  2. Next I should think about how to make the task simple, and work on naive test case and make sure that code works for simplest case, like a tree with only one node, and then two nodes;
  3. Do not be afraid. Always be confident. I should be responsible. I should be flexible, and focus on current situation;
  4. One thing I can do is to try to solve the problem, and make simple test case works first;
  5. When I test the code, I should run the code with the simple test case; Communicate better as well. 
  6. Do not feel frustrated. Next time if I prepare bring-home assignment, I should start to prepare for phone screen. 
  7. One week for bring-home assignment, one week for phone screen. 
  8. I should have time to review algorithms. Just take some breaks once or twice a day. Study the algorithm, and work on coding.
  9. I do believe that coding is so important, if I stop working on coding and run code against Leetcode, then I become totally a different person. I do not think and plan things carefully. 
  10. Remember, I need Leetcode as a tool to help me train myself. Think more efficiently as a programmer. 
  11. No one is perfect. Always practice. And stay positive all the time. I can be so close to make the code work.
  12. Try to make things work. Talk less. Act fast. Come out ideas to save myself if I am in trouble. 


Sunday, July 11, 2021

Leetcode | Hard level | tree algorithm |1483. Kth Ancestor of a Tree Node

July 11, 2021

I like to take some time to write the code for the algorithm. 

SPCE stock: Virgin Galactic

 Virgin Galactic is a British-American spaceflight company that operates in the United States. It was founded by Richard Branson and his Virgin Group retains a 24% stake.[1] It is developing commercial spacecraft and aims to provide suborbital spaceflights to space tourists. Virgin Galactic's suborbital spacecraft are air launched from beneath a carrier airplane known as White Knight Two.

Virgin Galactic's founder, Richard Branson, had originally hoped to see a maiden flight by the end of 2009,[2] but the date was delayed for several years, most seriously by the October 2014 crash of VSS Enterprise. As of 2020, the first passenger flight was planned for no earlier than May 2021.[3]

The company did the early work on the satellite launch development of LauncherOne before this was hived off to a separate company Virgin Orbit in 2017. The company also has aspirations for suborbital transport and in 2017, Branson has said that Virgin Galactic was "in the best position in the world" to provide rocket-powered, point-to-point 3,000 mph (4,800 km/h) air travel.[4][5][6][7][8]

On 13 December 2018, VSS Unity achieved the project's first suborbital space flight, VSS Unity VP-03, with two pilots, reaching an altitude of 82.7 kilometres (51.4 mi), and officially entering outer space by US standards.[9][10] In February 2019, the project carried three people, including a passenger, on VSS Unity VF-01, with a member of the team floating within the cabin during a spaceflight that reached 89.9 kilometres (55.9 mi). On July 11, 2021 Virgin Galactic became the first spaceflight company to independently launch a paying civilian into outer space using the 50 mile high definition of outer space, having flown Virgin Galactic founder, Richard Branson above the 50 mile mark.

How Jeff Bezos and Richard Branson’s Space Flights Will Differ | WSJ

 July 11, 2021

Here is the link. 

Jeff Bezos, the founder of Blue Origin, and Richard Branson, the founder of Virgin Galactic, are in a head-to-head race to get into space The billionaire founders of Blue Origin and Virgin Galactic will both be on board as the companies send their vessels to the edge of space. But their spacecraft, flight logistics and altitudes have some differences. Photo illustration: Laura Kammermann More from the Wall Street Journal: Visit WSJ.com: http://www.wsj.com Visit the WSJ Video Center: https://wsj.com/video


Saturday, July 10, 2021

Instagram: trainwithjoan | I just could not believe that I cannot beat a 70 year old in weight training

July 10, 2021

Introduction

I came cross this 70 year old instagram, and then I learn that I should work on my own instagram as well. I started to walk 9 KM every weekday more than two months ago, I like to document my experience on instagram. 

70 year old | Weight loss from close to 200 lb to 160 lb | Million followers

Here is the link.  


Why did I choose not to actively look for a software engineer job?

July 10, 2021

Introduction

It is my short research topic. I like to write down some ideas and work on this research more if I have time. 

Love the technology

I do think that it is so enjoyable to read books written for large distributed system. I like to spend time reading and learn better compared to writing code. I do think that it is the best time for me to learn better about life. If I had a choice, then I would like to learn more and read more. I like the job to provide the challenge for me, and always let me try new things. 

Love the stock market and equity research

I also love to work on equity research. There are so many businesses I would like to learn more about it. It is so important for me to learn how not to trade my time with salary by hour. I am 55-year-old, so I will be healthier and happier, and enjoy my life another 20 to 30 years. 

Coding is hard | Crafting skills are not easy to acquire 

I do think that in the last five years I spent over 10,000 hours on coding, but I should have read more about large distributed systems and learned more about business and worked on more on equity research. 

Coding is a challenge. I do not have time to code daily, so I should think carefully how to improve my efficiency at work, after work and weekends. 

Follow up 

Oct. 20, 2023

It takes a lot of time to apply for jobs. I think that it is better to invest on things I enjoy most, live happier and healthier instead. 

Learn to live frugal, and also make a living by living under my means. 


Leetcode tree algorithms: My idea is to go over hard level algorithms, study and copy idea using C#

July 10, 2021

Introduction

It is so important for me to learn from others, specially on tree algorithms. I only have less than two days to prepare for one phone screen, I like to get more hands-on experience. 

My idea | Go over hard level tree algorithms | study one idea | write my own C# code

The goal is to learn from best. I need to push myself to compete with best programmers in the world. One of ideas is to read most upvoted discussion post, and then write my own C# code quickly. 

I plan to work and solve 10 algorithms if I can. 


Leetcode discuss: 124. Binary Tree Maximum Path Sum

July 10, 2021

Here is the link. 

C# | Post order traversal | Bottom up | One visit each node | Optimal time and space

July 10, 2021
Introduction
It takes time for me to finish all tree algorithms, easy medium and hard level. I did complete the project in 2020. Now there are another 50 tree algorithms, and I like to spend time to work on. But I learned better through onsite interview, specially when I made mistake not to provide optimal time complexity this May, 2021.

Bottom up | Post order traversal | Each node has 4 values
Most of important is to make it simple. One visit of each node in the tree using bottom- up post order traversal is good enough to solve all calculation need.

Cross root maximum path | root to leaf node path maximum sum
There are four cases for cross root maximum path sum, left subtree take it or leave it, same as right subtree.

There are three cases for root to leaf node path maximum sum, root value itself, + left subtree's max, + right subtree's max.

The following code passes online judge.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    
    /// <summary>
    /// July 10, 2021
    /// Apply post order traversal once, bottom up, each node
    /// is visited only once, and each node will calculate root node
    /// to leaf node's max path, cross root node maximum path. 
    /// Space optimal: O(1)
    /// Time complexity: O(N)
    /// Each node has four values:
    /// 1. Node value itself
    /// 2. Node + left subtree
    /// 3. Node + right subtree
    /// 4. Cross root node max path
    /// </summary>
    /// <param name="root"></param>
    /// <returns></returns>
    public int MaxPathSum(TreeNode root)
    {
        if(root == null)
        {
            return 0; 
        }

        var maxCrossRoot = Int32.MinValue;

        applyPostOrderTraversal(root, ref maxCrossRoot);
        
        return maxCrossRoot; 
    }

    /// <summary>
    /// post order - L, R, Root
    /// Calculate root node to leaf node max path sum - return value
    /// Each node has four values to compare
    /// </summary>
    /// <param name="root"></param>
    /// <param name="maxCrossRoot"></param>
    /// <returns></returns>
    private int applyPostOrderTraversal(TreeNode root, ref int maxCrossRoot)
    {
        if(root == null)
        {
            return 0; 
        }

        var left = applyPostOrderTraversal(root.left, ref maxCrossRoot);
        var right = applyPostOrderTraversal(root.right, ref maxCrossRoot);

        var value = root.val;
        var current = value; 
        if(left > 0)
        {
            current += left;
        }

        if (right > 0)
        {
            current += right; 
        }

        maxCrossRoot = Math.Max(maxCrossRoot, current);

        var toLeaf = new int[] { value, value + left, value + right };
        return toLeaf.Max(); 
    }
}

What defines a good programmer | My coding skills | My favorite thing | What I should learn

July 10, 2021

Introduction

It was a busy week. I noticed this past Thursday morning the website was not working, and I like to write down something and later will come back to review. 

Lessons learned | What I should should learn

I learned that my old computer at work could not power up. I was able to open the box and found out that there is SSD card with 512 GB storage, and I need to install Microsoft visual studio 2012 professional on my new computer. 

I noticed that I did not save a few project into github, and I did not fully back up all projects in github. I have to wait until next Monday to get an adapter, the source code can be transferred from my old hard disk. 

Read more books | System design

I need to read more books about system design. I just could not believe that it is best and efficient way to read books, besides going through youtube videos and Linkedin premium courses. I need to find time to read and learn by reading well-written technical books, but I have to figure out how to squeeze time. I need 2 hours a day to walk 9 KM from office to home as well. 

Right now I cut my working hours from 8 to 6 hours/day sometimes in summer time. I also like to think about more carefully on this issue. Missing hours will reduce my time to learn things at work. 

Good programmer | Code once a while 

I just could not believe that I need to be more responsible once I code something on Leetcode.com. I need to make it work, force myself to think carefully and be patient to learn lessons. 

I just could not believe that last three weeks I did not code very often. 



 


Leetcode discuss: 737. Sentence Similarity II

July 10, 2021

Here is the link. 

C# | Graph using adjacent list | DFS | Warmup

July 10, 2021
Introduction
It is my warmup practice to prepare for a phone screen on July 12, 2021. I like to work on a few algorithms, graph, tree, dynamic programming and go over all hard level algorithms I studied to prepare for Google onsite in Dec. 2020. I just started to work on algorithm on my discussion post here called 600 beyond.

Graph | Undirected graph | use Hashmap | Common exception
I wrote C# code and then ran into exception. I did not think carefully, instead I copied the test case and then ran it in visual studio. The error is clear inside visual studio. The word may not in graph at all, null pointer exception.

The following code passes online judge.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _737_sentence_similarity
{
    class Program
    {
        static void Main(string[] args)
        {
            RunTestcase2(); 
        }

        public static void RunTestcase1()
        {
            var sentence1 = new string[] { "great", "acting", "skills" };
            var sentence2 = new string[] { "fine", "drama", "talent" };

            var pairs = new List<IList<string>>();
            pairs.Add(new string[] { "great", "good" }.ToList());
            pairs.Add(new string[] { "fine", "good" }.ToList());
            pairs.Add(new string[] { "drama", "acting" }.ToList());
            pairs.Add(new string[] { "skills", "talent" }.ToList());

            var result = AreSentencesSimilarTwo(sentence1, sentence2, pairs); 
        }

        /// failed test case - 14/119 - investigate the issue 
        public static void RunTestcase2()
        {            
            var sentence1 = new string[]{"a","very","delicious","meal"};
            var sentence2 = new string[]{"one","really","good","dinner"};

            var pairs = new List<IList<string>>();
            pairs.Add(new string[]{"great","good"}.ToList());
            pairs.Add(new string[]{"extraordinary","good"}.ToList());
            pairs.Add(new string[]{"well","good"}.ToList());
            pairs.Add(new string[]{"wonderful","good"}.ToList());
            pairs.Add(new string[]{"excellent","good"}.ToList());            

            var items = new string[][]{
            new string[]{"fine","good"},new string[]{"nice","good"},new string[]{"any","one"},new string[]{"some","one"},new string[]{"unique","one"},new string[]{"the","one"},
            new string[]{"an","one"},new string[]{"single","one"},new string[]{"a","one"},new string[]{"truck","car"},new string[]{"wagon","car"},new string[]{"automobile","car"},
            new string[]{"auto","car"},new string[]{"vehicle","car"},new string[]{"entertain","have"},new string[]{"drink","have"},new string[]{"eat","have"},
            new string[]{"take","have"},new string[]{"fruits","meal"},new string[]{"brunch","meal"},new string[]{"breakfast","meal"},new string[]{"food","meal"},
            new string[]{"dinner","meal"},new string[]{"super","meal"},new string[]{"lunch","meal"},new string[]{"possess","own"},new string[]{"keep","own"},
            new string[]{"have","own"},new string[]{"extremely","very"},new string[]{"actually","very"},new string[]{"really","very"},new string[]{"super","very"}};

            foreach (var item in items)
            {
                pairs.Add(item.ToList());
            }

            AreSentencesSimilarTwo(sentence1, sentence2, pairs);             
        }

        /// <summary>
        /// Graph - how to build an undirected graph using adjacent list. 
        /// How to search a graph using BFS/ DFS and avoid deadloop - mark visit
        /// Transitive
        /// ["great", "good"], ["fine","good"], so "great","good" and "fine" are all connected. 
        /// Brute force solution
        /// Search graph for connected words, check if there is a match
        /// </summary>
        /// <param name="sentence1"></param>
        /// <param name="sentence2"></param>
        /// <param name="similarPairs"></param>
        /// <returns></returns>
        public static bool AreSentencesSimilarTwo(string[] sentence1, string[] sentence2, IList<IList<string>> similarPairs)
        {
            if(sentence1 == null || sentence2 ==  null || sentence1.Length != sentence2.Length)
            {
                return false; 
            }

            // build a graph
            var graph = new Dictionary<string, List<string>>(); 
            foreach(var pair in similarPairs)
            {
                if (pair.Count() < 2)
                {
                    continue; 
                }

                var node1 = pair[0];
                var node2 = pair[1]; 
                if(!graph.ContainsKey(node1))
                {
                    graph.Add(node1, new List<string>());
                }
                
                if(!graph.ContainsKey(node2))
                {
                    graph.Add(node2, new List<string>());
                }

                graph[node1].Add(node2);
                graph[node2].Add(node1);
            }

            // search the graph
            var length = sentence1.Length;
            for (var index = 0; index < length; index++)
            {
                var word1 = sentence1[index];
                var word2 = sentence2[index];

                // DFS - search word1 connected graph
                var seenWords = new HashSet<string>();
                var stack = new Stack<string>();
                stack.Push(word1);
                var found = false; 

                while(stack.Count > 0)
                {
                    var visit = stack.Pop();
                    seenWords.Add(visit);

                    if (visit.CompareTo(word2) == 0)
                    {
                        found = true;
                        break; 
                    }

                    // caught by online judge - failed test case - 14/119
                    if(!graph.ContainsKey(visit))
                    {
                        continue; 
                    }

                    foreach(var word in graph[visit])
                    {
                        if (seenWords.Contains(word))
                        {
                            continue; 
                        }

                        stack.Push(word);
                    }
                }

                if(!found)
                {
                    return false; 
                }            
            }

            return true; 
        }
    }
}

Leetcode discuss | 552. Student Attendance Record II | My C# practice

July 10, 2021

Here is the link. 

C# | Hard level DP problem | Three states | Top down

July 10, 2021
Introduction
It is time for me to code a solution using C# and understand most important is my crafting skills. I have not submitted any code on Leetcode at least three weeks. If I choose to be consistent, then it is time for me to make corrections, and go back to code the idea for those hard level Leetcode premium algorithms with Google tag.

DP solution | Three states | Top down
I do think that it is easy to write if I can take an approach to write down detail about how to solve n = 2 with 8 possible solutions.

The detail discussion is here. I wrote down to warmup and it took me a few hours.

The following C# code passes online judge.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Leetcode552_studentAttendance
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = CheckRecord(2);
            Debug.Assert(result == 8);
        }

        /// <summary>
        /// DP solution, top down
        /// Three states: 
        /// state 1: length of sequence
        /// state 2: total A in the sequence, suffix of sequence
        /// state 3: count of continuous 'L', suffix of sequence
        /// </summary>
        /// <param name="n"></param>
        /// <returns></returns>
        public static int CheckRecord(int n)
        {
            // state 2: 'A' - 0 or 1
            // state 3: 'L' - 0 or 1 or 2
            var dp = new int[n + 1, 2, 3];
            for(int index = 0 ; index < n + 1; index++)
            {
                for(int countA = 0; countA < 2; countA++)
                {
                    for(int countL = 0; countL < 3; countL++)
                    {
                        dp[index, countA, countL] = -1; 
                    }
                }
            }

            return topDownTotalCount(n, 0, 0, dp);
        }

        /// <summary>
        /// This one is challenge, top down
        /// Memoization
        /// Subproblem | three states | suffix 
        /// Take care of those above three key things
        /// </summary>
        /// <param name="n"></param>
        /// <param name="suffixA"></param>
        /// <param name="suffixContinuousL"></param>
        /// <param name="dp"></param>
        /// <returns></returns>
        private static int topDownTotalCount(int n, int suffixA, int suffixContinuousL, int[,,] dp)
        {
            var mod = 1000 * 1000 * 1000 + 7; 
            
            // base case 
            if(n == 0)
            {
                return 1; 
            }

            if(dp[n, suffixA, suffixContinuousL] != -1)
            {
                return dp[n, suffixA, suffixContinuousL];
            }

            int count = 0; 
            if(suffixA == 0)
            {
                // add 'A', reset continuous L
                count += topDownTotalCount(n - 1, suffixA + 1, 0, dp);
                count %= mod;
            }

            if(suffixContinuousL < 2)
            {
                // add 'L', suffixContinuousL++
                // suffixA - no change
                count += topDownTotalCount(n - 1, suffixA, suffixContinuousL + 1, dp);
                count %= mod; 
            }

            // add 'P'
            // reset suffixContinuousL = 0
            count += topDownTotalCount(n - 1, suffixA, 0, dp);
            count %= mod; 

            // memoization - save the count variable
            dp[n, suffixA, suffixContinuousL] = count; 

            return count; 
        }
    }
}