From January 2015, she started to practice leetcode questions; she trains herself to stay focus, develops "muscle" memory when she practices those questions one by one. 2015年初, Julia开始参与做Leetcode, 开通自己第一个博客. 刷Leet code的题目, 她看了很多的代码, 每个人那学一点, 也开通Github, 发表自己的代码, 尝试写自己的一些体会. She learns from her favorite sports – tennis, 10,000 serves practice builds up good memory for a great serve. Just keep going. Hard work beats talent when talent fails to work hard.
Tuesday, July 21, 2020
Leetcode solved problem: From 461 to 492
Introduction
It is important for me to push myself to write code every day. I did not do that since January 2020, coronavius, running to prepare for Vancouver sun run, and then hay fever, and stock market crashes. Starting from May 28, 2020, I had to prepare for Facebook phone screen, and then I started to work on algorithms again. I only solved 32 new algorithms so far.
32 algorithms
I am so glad to learn the benefit to write code for those simple algorithms. Even the tough one, it only took me less than three or four hours to make it work.
Things I like to talk about is about Trie data structure, using stack, and other things like tree algorithms.
Facts to review
It takes 3 days nonstop practice, so that I can find out how many weakness I have in my thinking process and drafting process.
After my first break-down, it took me 40 minutes to go back to think efficiently using knightdial algorithm. I learn that I have to let my brain get used to those stress, and then I can perform better.
At my peak time, it only takes me five minutes to recall the whole thing, after six months break, the first one will take me 40 minutes. To prepare for Facebook phone screen, I need something like 2 - 3 minutes to refresh my muscle memory.
Two hours research: Oil stock 10% gain
I am studying Chevron, and deal to purchase Nobel energy in 5 billion dollars.
Inflations -> good structure company with a lot of debt - cash deal to purchase stock of Nobel
Debt-burden energy company
Energy - all sectors - analyze things - who is good credit star rating ...
Five ideas to get back to more sports life
Introduction
It is tough project to work on. I like to lose 10 lb, and also play more tennis sports as well. I like to write down five ideas to go back to more sports life.
Five ideas
- Need to learn how to balance work, algorithm practice, stock investment and sports activities;
- Put sports first after the work and in the weekends;
- Start to read more about weight control, running and tennis sports;
- Plan to finish first 20 tennis workout in one week;
- Plan to hike a few times in short future.
Five hours to relax after Facebook phone screen
Intensive study is great for preparation. After one hour phone screen, I went out to play tennis sports.
First hour - watch a double game live in central park burnaby, I knew all those players.
Second hour - watch another double game
Third hour - start to work on hitting against the wall
Fourth hour - take multiple breaks
Fifth hour - hit against the wall again.
How to give good impression to a Facebook manager through phone screen?
- Communication: Ask clarifying questions around the problem before solving
- Speed: One of our values here is moving fast
- Verification and testing: bug free as possible, talking through edge cases
- Problem-solving: Finding a working solution
Crafting skills - how many hours minimal to maintain the level?
Introduction
It is my short project to work on. I have to evaluate how many hours minimal one month in order to maintain my crafting skills to the certain level. It is hard for me to measure my own curiosity, and ability to stretch my brain muscle to think a hard level algorithm in less than five minutes.
How many hours minimal to maintain the level?
I do think that I deserve to have a good career and enjoy the life as well. In order for me to work and stay competitive, I like to push myself to improve my crafting skills.
40 hours
20 hours
10 hours
5 hours
I do think that it is important for me to practice as many hours as possible. I should think about 40 hours for the first week, and then reduce hours to less the second week. There are so many things for me to work on.
What is most important in Facebook phone screen?
Introduction
Preparation
During Facebook phone screen
In other words, I have to take less optimal solution if the time is not enough for me to analyze and think clearly for a tough algorithm.
Why should I push myself very hard three days before Facebook phone screen?
Introduction
I learn from mistakes I made through Leetcode easy level tree algorithms. I understand that it is important for me to be a responsible person, how come I can take a job if I can not produce high quality of code in less than 10 to 15 minutes, and let the fact stay true for so many years. It is my 10th year on the same job. I have enough time to learn and overcome any weakness I find.
Push myself hard
It is so interesting to learn how our brain works under stress. Also it is about 53 year old engineer, or just a programmer.
How to control risk on Facebook phone screen?
Introduction
Sending out messages on Linkedin
I did send out over 10 messages on Linkedin.com, and then started to get myself understand importance of project. I got a friend to offer me four mock interview to work on communication skills.
49 tagged blogs about 2020 Facebook phone screen
I do think that it is important for me to work on those algorithm and data structure. It is vital for a software programmer to survive, no matter it is good time or hard time. What is it? I do think that problem solving ability, and crafting skills, and also ability to learn.
Here is the link.
The risk
It is high probability for me to fail Facebook phone screen. Even though I was lucky to be selected for my first onsite from Facebook. This time it is more serious and more competitive to stay on top of candidates.
I like to make sure that I do my best as I can. Enjoy the learning. Also it is important for me to find weakness to work on.
I did start my first marathon weekend to work on algorithm non-stopped for 3 days in the row. I knew the difference this time, I do think that I have to really work on so many things in terms of Leetcode discuss post, analyze of algorithms, how to stay on track to solve a simple problem. Compared to my previous experience from 2015 to 2019, I tried to memorize the solutions for as many algorithms as I can.
May 28 - July 20 two months preparation for Facebook phone screen
It is a nice journey, and I also worked on a few small projects at work. I got motivated and push myself to write more code at work as well.
Is it possible for me to be a mediocre programmer to be a competitive one? Preparation is so important, and I have to be humble and write easy level algorithms. Stay confident, take risk to learn basic things. Crafting skills are important, but without practice, there is no skills.
Tennis sports and my sports family
I went back to tennis court after one hour phone screen. I only took less than 30 minutes walk around the community last weekend. I was busy and sit whole day to review and code algorithm nonstopped. It is important for me to go back to tennis court, and then meet my tennis family.
16 tennis courts and wall
I know more than hundred people on tennis court. Any time in summer time, I can meet people and say hi. Every one of them is potential a good friend, who can help me relax and hit tennis with me, help me quickly lose those body fat. My weight is 196 lb after so many days away from tennis court.
I did spend time to watch best tennis match on double match, and I chatted with a young chinese girl in her eight year old, her father was playing double tennis, her 10 year old brother played tennis against the wall. I mainly asked about coronavirus, school stuff. She likes drawing.
I spent over four hours on tennis court. I talked to over 20 people, and watched games, and also played against the wall.
Here are highlights:
1. Dress properly - casul shoes, tennis shoes, and tennis clothing
2. Bring water bottom, chat with people
3. Work on my big muscles, run and hit against the wall half hour; take break; half hour;
4. feel my body, and examine if any muscle, bone and joints are functioning properly.
Usually I run one hour before I play tennis. Usually it is better for me to run 5000 meters around central park two rounds. Warm up first, and then I can start to play against wall half hour. And then play some matches if I have chance.
Most of important, meet people and chat, and prepare for future opportunity to play together.
It is my Canadian family on tennis court.
Two hours review of tree algorithms on Leetcode on July 20, 2020
What is most important in a software programmer life?
Say goodbye to Facebook phone screen
Introduction
【箴二十八19】「耕种自己田地的,必得饱食;追随虚浮的,足受穷乏。」
Sunday, July 19, 2020
Leetcode discuss: 979. Distribute Coins in Binary Tree
C# Need to work on a simple case study
- Distribute Coins in Binary Tree
I know that root node has coins with val, and it should take away val - 1 coins. But I continued to think which way to go, I tried to build a table.
Root node
/ \
Left subtree Right subtree
It is totally different experience to solve tree algorithms after six month break. Recursive thinking is most challenge task.
July 19, 2020 12:17 PM
Case study
A simple tree with root node (coins = 3) left child (coins 0) left.left child (coins 0)
The root node need to move away 2, left child need move one coin to add, left.left need move one coin to add, in total, there are 2.
Case study
I need to work on a test case and see if I can figure out the coins move correctly or not.

Apply post order traversal, recursive function will return number of coins to move in direction.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _979_distribute_coins_in_binary_tree
{
public class TreeNode
{
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
class Program
{
static void Main(string[] args)
{
var node0 = new TreeNode(0);
var node0B = new TreeNode(0);
var node0C = new TreeNode(0);
var node4 = new TreeNode(4);
var node0D = new TreeNode(0);
var node3 = new TreeNode(3);
var node0E = new TreeNode(0);
node0.left = node0B;
node0.right = node0C;
node0B.left = node4;
node0B.right = node0D;
node0C.left = node3;
node0C.right = node0E;
DistributeCoins(node0);
Console.WriteLine(coinsMoved);
}
public static int coinsMoved;
public static int DistributeCoins(TreeNode root)
{
if (root == null)
return 0;
coinsMoved = 0;
postOrderTraversal(root);
return coinsMoved;
}
/// <summary>
/// https://leetcode.com/problems/distribute-coins-in-binary-tree/discuss/221939/C%2B%2B-with-picture-post-order-traversal
/// go over the example in the above discuss
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public static int postOrderTraversal(TreeNode root)
{
if (root == null)
return 0;
var left = postOrderTraversal(root.left);
var right = postOrderTraversal(root.right);
coinsMoved += Math.Abs(left) + Math.Abs(right);
return left + right + root.val - 1;
}
}
}
Leetcode discuss: 332. Reconstruct Itinerary
C# DFS algorithm with tough decisions to make
It is my preparation for phone screen from Facebook on July 20, 2020. I like to work on leetcode mock interview phone screen mock interview nonstop for two days.
- More than one ticket for same start and dest cities. For example, JFK to NRT, there are two tickets.
- I tried to use C# Dictionary<string, SortedSet>, I ran into failed test case, so duplicate allows, SortedSet cannot be used;
- I tried to use C# LinkedList, but I had problem to put it back after failed DFS search. I chose to use LinkedList RemoveFirst, AddFirst API, it does not work for back tracking.
- I tried to use HashSet to make unique ticket like "JFK"+"NRT". Because two tickets are available for same ticket, I have to use original hashMap to mark visit.
- I also spent over 15 minutes to figure out that variable found as List is empty and I have to add ref.
- List is used, and then apply Sort API; Later List.RemoveAt index position, and then List.InsertAt index position position; So all destination are sorted in lexicographically order.
- Play with base case - all tickets are used and only used once.
It should take me less than 25 minutes, but I took over 100 minutes to play with the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace airlineTickets
{
class Program
{
static void Main(string[] args)
{
RunTestcase3();
}
public static void RunTestcase1()
{
// [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
var tickets = new List<IList<string>>();
tickets.Add(new List<string>() {"MUC", "LHR" });
tickets.Add(new List<string>() {"JFK", "MUC" });
tickets.Add(new List<string>() {"SFO", "SJC" });
tickets.Add(new List<string>() {"LHR", "SFO" });
var result = FindItinerary(tickets);
}
public static void RunTestcase2()
{
var tickets = new List<IList<string>>();
tickets.Add(new List<string>() {"EZE","AXA" });
tickets.Add(new List<string>() {"TIA","ANU" });
tickets.Add(new List<string>() {"ANU","JFK" });
tickets.Add(new List<string>() {"JFK","ANU" });
tickets.Add(new List<string>() {"ANU","EZE" });
tickets.Add(new List<string>() {"TIA","ANU" });
tickets.Add(new List<string>() {"AXA","TIA" });
tickets.Add(new List<string>() {"TIA","JFK" });
tickets.Add(new List<string>() {"ANU","TIA" });
tickets.Add(new List<string>() {"JFK","TIA" });
var result = FindItinerary(tickets);
}
public static void RunTestcase3()
{
var tickets = new List<IList<string>>();
// [["JFK","KUL"],["JFK","NRT"],["NRT","JFK"]]
tickets.Add(new List<string>() { "JFK","KUL" });
tickets.Add(new List<string>() { "JFK","NRT" });
tickets.Add(new List<string>() { "NRT","JFK" });
var result = FindItinerary(tickets);
}
public static IList<string> FindItinerary(IList<IList<string>> tickets)
{
// the idea is to run a DFS search
// keep all tickets into a hashmap
// path - find first path then return
// hashMap - C# Dictionary<string, SortedSet<string>>
if (tickets == null || tickets.Count == 0)
{
return new List<string>();
}
var count = tickets.Count;
// ANU->TIA two tickets
var map = new Dictionary<string, List<string>>();
foreach (var item in tickets)
{
var start = item[0];
var dest = item[1];
if (!map.ContainsKey(start))
{
map.Add(start, new List<string>());
}
map[start].Add(dest);
}
foreach(var key in map.Keys)
{
map[key].Sort();
}
var path = new List<string>();
var found = new List<string>();
path.Add("JFK");
runDFSSearch(map, 0, count, "JFK", path, ref found);
return found;
}
/// DFS - mark visited
/// backtracking
/// check the final length
private static void runDFSSearch(
Dictionary<string, List<string>> map,
int index,
int total,
string start,
List<string> path,
ref List<string> found)
{
if (found.Count > 0)
{
return;
}
// all the tickets used once and only once
if (map.Count == 0)
{
found = path.ToList();
return;
}
if (!map.ContainsKey(start))
{
return;
}
var destCities = map[start];
var copy = new List<string>(destCities);
for (int i = 0; i < copy.Count; i++ )
{
var dest = copy.ElementAt(i);
path.Add(dest);
map[start].RemoveAt(i);
if (map[start].Count == 0)
{
map.Remove(start);
}
runDFSSearch(map, index + 1, total, dest, path, ref found);
// backtracking
path.RemoveAt(path.Count - 1);
if (!map.ContainsKey(start))
{
map.Add(start, new List<string>());
}
map[start].Insert(i,dest);
}
}
}
}
Leetcode discuss: 304. Range Sum Query 2D - Immutable
C# preprocess matrix to calculate left top corner area
July 19, 2020
Introduction
In order to get O(1) to answer the query given start left top corner and bottom right corner, it is a good idea to preprocess the left top corner area for any position in the matrix.
My practice
It took me over 20 minutes and reviewed the code since one failed test case. My first submission failed since the cross area is related to (row1 - 1, col1 - 1), not (row1, col1).
public class NumMatrix {
private int[][] rectangle; // from (0,0) to (i, j) rectangle sum
private int rows, columns;
public NumMatrix(int[][] matrix) {
if(matrix == null || matrix.Length == 0 || matrix[0].Length == 0)
return;
rows = matrix.Length;
columns = matrix[0].Length;
rectangle = new int[rows][];
for(int i = 0; i < rows; i++)
{
rectangle[i] = new int[columns];
}
for(int row = 0; row < rows; row++)
{
for(int col = 0; col < columns; col++)
{
var left = col > 0? rectangle[row][col - 1] : 0;
var upper = row > 0? rectangle[row - 1][col] : 0;
var cross = (row > 0 && col > 0)? rectangle[row -1 ][col - 1] : 0;
rectangle[row][col] = matrix[row][col] + left + upper - cross;
}
}
}
public int SumRegion(int row1, int col1, int row2, int col2) {
if(row1 < 0 || row1 >= rows ||
row2 < 0 || row2 >= rows ||
row1 > row2 ||
col1 < 0 || col1 >= columns ||
col2 < 0 || col2 >= columns ||
col1 > col2)
return -1;
// whole - left - up + cross
var area = rectangle[row2][col2]; // whole
area -= col1 == 0? 0: rectangle[row2][col1 - 1]; // left
area -= row1 == 0? 0: rectangle[row1 - 1][col2]; // up
area += col1 == 0 || row1 == 0? 0: rectangle[row1-1][col1-1]; // cross
return area;
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.SumRegion(row1,col1,row2,col2);
*/Leetcode discuss: 935. Knight Dialer
C# Need to move fast
It took me over 20 minutes and then I knew that it can be solved using DFS or BFS algorithm for N step. And I thought about there is no need for each path. All we need is the total count.
It should take me less than five minutes to spot the pattern. But it did take me 20 minutes or so.
After over 40 minutes, I started to code the solution; First I define the hashset array, and then map digit 0 - 9 to next step, cross 1x2 or 2x1, eight directions.
It is hard for me to push myself. It is interesting to learn that I gained some confidence after two hour solving a problem this afternoon. Here is the discuss post I shared. It was tough for me to be patient to solve it after failing so many times.
I like to share those four things to work on when I practice through mock interviews:
As a reminder, please keep these 4 criteria in mind during your technical interview:
- Communication: Ask clarifying questions around the problem before solving
- Speed: One of our values here is moving fast
- Verification and testing: bug free as possible, talking through edge cases
- Problem-solving: Finding a working solution
public class Solution {
public int KnightDialer(int N) {
// DFS -> only 10 digits each step - using array to represent
//
if( N <= 0 || N > 5000)
return -1;
var map = new HashSet<int>[10];
for(int i = 0; i < 10; i++)
{
map[i] = new HashSet<int>();
}
map[0] = new HashSet<int>(new int[]{4, 6});
map[1] = new HashSet<int>(new int[]{6, 8});
map[2] = new HashSet<int>(new int[]{7, 9});
map[3] = new HashSet<int>(new int[]{4, 8});
map[4] = new HashSet<int>(new int[]{0, 3, 9});
//map[5] = new HashSet<int>(new int[]{});
map[6] = new HashSet<int>(new int[]{0, 1, 7});
map[7] = new HashSet<int>(new int[]{2, 6});
map[8] = new HashSet<int>(new int[]{1, 3});
map[9] = new HashSet<int>(new int[]{2, 4});
var previous = new long[10];
var current = new long[10];
var number = 1000 * 1000 * 1000 +7;
for(int i = 0; i < N; i++)
{
if(i == 0)
{
for(int j = 0; j < 10; j++)
{
current[j] = 1;
}
}
else
{
for(int j = 0; j < 10; j++)
{
var set = map[j];
foreach(var item in set)
{
current[item] = (long)(current[item] + previous[j]) % number;
}
}
}
// reset current array
for(int j = 0; j < 10; j++)
{
previous[j] = current[j];
current[j] = 0;
}
}
return (int)(previous.Sum() % number);
}
}