Showing posts sorted by relevance for query longest univalue path. Sort by date Show all posts
Showing posts sorted by relevance for query longest univalue path. Sort by date Show all posts

Wednesday, May 1, 2019

Case study: 687. Longest Univalue Path discussion post

May 1, 2019

Introduction


It is so interesting to write a short research blog to talk about my learning experience from 687 longest univalue path. I like to make it simple and talk about discussion posts I shared.

Discussion posts


I wrote a few discussion post. Here is the snapshot taken on May 1, 2019.


687. Longest univalue path optimal solution
687. Longest univalue path with design flaw, pass 43 out of 68 test cases
687. Longest univalue path copy the idea from most popular post
687. Longest univalue path learn from a mock interview
687. Longest univalue path C# post order - check with parent value with step by step illustration


I worked on the algorithm with over 20 interviews on interviewing.io from August 2018 to May 2019. I learn that there are so many solutions and it is hard for me to be an interviewer. The algorithm definitely is not an easy level. 

However, I still do not get any upvote from my sharing. One thing I can do is to revisit last post, and then put all diagrams into one diagram to illustrate the steps. 


Time lines


August 11, 2018
I took my ex-coach's advice, worked on easy level algorithms on leetcode.com. This is the first time I learn the algorithm and how hard it is for me to solve it.

I failed to submit a working solution. I wrote the code and also shared the solution. Just by luck, there is no down vote on this one.

August 11, 2018


Tuesday, January 22, 2019

Case study: longest univalue path

Jan. 22, 2019

Introduction 


It is another 60 minutes discussion about algorithm longest univalue path. I was an interviewer on interviewing.io and the algorithm is longest univalue path.


Case study


Here is the example we worked on together.


Here is my feedback:


I work on the algorithm with over 20 interviewee right now. I learn one way to approach the problem and it should take me less than 15 minutes to solve it right now.

The fact I learned is the following:

I failed to solve the similar problem in weekly contest 120 distribute coins in binary tree, and I spent over 36 minutes in Jan. 19 2019.

Steps to shorten the time to 15 minutes

Using post order traversal, bottom up. It is a good idea to mark the path using number next to each node, and the number can be solved using recursively.

First step is to work on straight path, not cross path. From any node as a root node to the leaf node longest univalue path.

Second step is to calculate the cross node path.

Feedbacks


Here is the interviewee's feedback:


It took us more than 60 minutes to reach a final solution, and the code is still under investigation. One of ideas to improve for me as an interviewer is to bring the interviewee into discussion how to hack solution in quick and easy way.

The interviewee tried a few ideas but none of them worked. Even though the code passed a few test cases. I ask why it is plus one in one statement, I ask where is the statement to add two path together in the code.


code review: longest univalue path

Jan. 22, 2019

Introduction


It is a good idea for me to train myself hard. One thing I can do is to study very good written solution, and try to improve it, or simplify the code.

Code review

Here is the algorithm written in a coding blog called  a casual coder.
Here is C# solution I like to review for longest univalue path.

I also write down my thought process as well.

Thank you for sharing longest univalue path. I played with your solution in the above a few times, it is hard for me to come out the good review, but I did something to share with you. 

The variable maxThruLeft is declared and calculated but it is no use in your code. Same as maxThruRight variable. 

If we use maxThruCurrent variable and apply it to every node in the tree using post order, then we can get longest univalue path. No need to use third variable called maxGlobal. 

The following is the code I rewrote and just provide you a second opinion. The code passes online judge. 

Here is C# solution I rewrite to simplify the code.


Wednesday, December 23, 2020

Leetcode discuss: 687. Longest Univalue Path | 10 upvotes | 474 views

 Here is the link. 

C# post order - check with parent value with step by step illustration

Added on Feb. 2019

The idea to solve the problem is to avoid using root node to compare with left and right child, two user cases; Every node works with its parent node instead.

It is very challenge to explain and prove the code written is correct based on counting the edge from node to it's parent node.

What I like to suggest is to go over a few steps based on an example to test manually before writing the code. First step is to number every node in the tree using a, b, c, d,..; And then work on edge value calculation following the order of nodes in traversal, specify each edge using node id; third step is to calculate cross path and explain how it works for the maximum value.

I like to show the steps to work on an example, how to explain the idea and come out the design. Since there are so many ways to approach the problems, it is important to make the approach easy to understand.

Added on June 2019
Case study a binary tree

To understand the approach, let us work on simple test case, a binary tree with three nodes, root node with value 5, and left and right child both with value 5 as well:

Here is the overview to display, after that, I will go over one step a time.
Here are hightlights:

  1. Traversal the tree using post order traversal, mark with a, b, c in the order of traversal for each node;
  2. Add edge value to each node, every node will check its parent and see its value equal to parent value;
  3. Add cross path value next to the node from 5a, 5b, 5c. Only 5c has cross path value 2.

image

Quick overview for each step

Three steps, each step is illustrated one diagram:
step 1: Post order traversal the tree, mark the order using a, b, c next to the node.

image

step 2: Calculate edge value, and add value next to the node.
image

step 3: Calculate the cross path value, add value next to the node
image

The following tree with node value 5 is very helpful to illustrate the process.
image

The longest univalue path is 2, and the edge count is 2, including one edge from root node to its left child, and one edge from root node to its right child.

There are so many ways to approach the problem, to check with parent value is different from the above counting. The edge is counted from left child to it's parent, likewise the right child to its parent. The node is counting the edges toward itself from direct children nodes first, and also includes it's child's count if need.

How to approach the problem in detail?

A few steps will be explained in the following. using postorder traversal
image

First, we work on recursive function. Every node is to check with its parent node's path value. Post order traversal, bottom up, three steps, left child 5a, right child 5b, root node 5c, all nodes in the tree have value 5, using a, b c to mark them with unique id, and also alphabetic order is the order of post order traversal.

step 1:
image

The first node visited is 5a, and its value is equal to it's parent node 5c. 1 edge is added next to 5a. The edge is from node 5a to node 5c.
step 2:
image

The second node visted is 5b, and its value is equal to it's parent node 5c. One edge is added next to 5b.

step 3:
image

The third visited node is 5c, and the value does not equal to it's parent node's value. 0 is added next to 5c.

Combination of step 1, 2, 3:

The above tree left child with node value 5, 1 counts for the edge of the node 5 to its parent, in other words, edge from node 5a to 5c;

likewise the right child.
Now the calucation of cross path, bottom up, post order, in the order of 5a, 5b, 5c

Step 1: work on 5a-1-?, cross path value
image

Step 2: work on 5b-1
image

Step 3: work on 5c-1
Cross path should be two edges, 5a->5c, 5b->5c
image

The node 5c's cross path value is 2, since two edges, one is 5a to 5c, and the other is 5b to 5c.

I think that it is definitely good idea in general to go over an example first, and then write the code based on the idea to check with parent value.

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

namespace longest_univalue_path___compare_to_root
{
    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)
        {
        }

        int maxCrossPath = 0; // global variable
        public int LongestUnivaluePath(TreeNode root)
        {
            if (root == null)
            {
                return 0;
            }

            maxCrossPath = 0;
            postOrderTraversal(root, root.val);

            return maxCrossPath;
        }

        private int postOrderTraversal(TreeNode node, int parentValue)
        {
            if (node == null)
            {
                return 0;
            }

            var current = node.val;

            int left  = postOrderTraversal(node.left,  current);
            int right = postOrderTraversal(node.right, current);

            maxCrossPath = Math.Max(maxCrossPath, left + right); // longest univalue path crossing the root

            if (parentValue == node.val)
            {
                return Math.Max(left, right) + 1;
            }

            return 0;
        }
    }
}

Saturday, January 19, 2019

Case study: Longest univalue path mock interview

Jan. 19, 2019

Introduction


It is my mock interview again in Nov. 18, 2019 as an interviewer. I asked the interviewee to solve the longest univalue path. I like to do a case study on the interview.

Case study


I like to push myself to learn how to be a good interviewer. This time the interviewee wrote a solution with a bug, but I did not find the bug in the mock interview.

The interview was on Jan. 18, 2019.

Now it is Jan. 19, 9:54 AM. I put the idea into C# code and run Leetcode online judge. The code failed.

Here is the gist.

Uncover the problem


The problem is on the recursive to solve the cross path.

Line 35 return 2 + LongestUnivaluePath(root.left) + LongestUnivaluePath(root.right);

The counter example is the following:

Line 1:         3
Line 2:      /       \
Line 3      3        3
Line 4:   /   \
Line 5:  3    3

The above tree's longest univalue path is 3, not 4.

Actionable Item


I wrote an email to sam@interviewing.io and ask how I can modify my feedback.



Friday, June 7, 2019

Leetcode 687: longest univalue path - C# various topics covered in practice from 2018 to 2019

Here is my post on leetcode.com.

June 2019
It is an easy level tree algorithm. I got advice to work on easy level algorithm on Leetcode.com first in June 2018. So I started to work on all easy level tree algorithms on Leetcode.com in August 2018, I found out that my first practice was hard, and my idea did not lead to a working solution. After that, I asked the algorithm on interviewing.io as an interviewer, I continued to learn from every interviewee, and I like to put together a list of topics I learn through the experience. Here are the blogs I wrote based on my mock interview experience using this algorithm from August 2018 to June 2019. I will add some of practices here for me to master the tree algorithm.
August, 2018
My failed first practice, here is the link.
Recursive function design: return longest path from root to leaf instead
My first recursive solution, here is the link.
Case study two examples
Sept. 2018
Longest path cross the root, two case studies on example trees, the link is here.
Recursive function design: return cross root longest univalue path directly
Nov., 2018
One recursive function to solve the problem, here is the link.
Feb. 2019
check with parent node's value instead of check child's node - inverse check
C# post order - check with parent value with step by step illustration, here is the link.
Common mistakes in mock interviews:
  1. Make sure that every node is traversed, bottom up, post order traversal is most commonly used;
  2. Common mistake - visit left or right only if the root value equals to its left(right) child's value
    So the whole tree will not be traversed properly.
  3. Make sure that there is a place to increment one, otherwise the value will always be zero; explain to the interviewer, that one is related to which edge or node in example tree.
An experienced interviewer will check you a few things:
  1. post order traversal or preorder, bottom up or top down, what is your choice?
  2. How do you design recursive function, return directly asked or return indirectly?
  3. Count node or count edge?
  4. Do you check children node with two cases to discuss, or compare to parent node only one case?
  5. Argue the code will be correct.
    A. Increment one check, relate to example tree edge or node clearly.
    B. Make sure that all nodes will be traversed. Do not put conditional check for left or right child node's value to apply traverse;
  6. Can you explain the algorithm very well? At least you warm up the traversal with an example, and then explain every node what will happen. Do not jump to coding for only solution you memorize. Click here to see how I explain the algorithm in case study.

Show case


I like to share my experience how I master a tree algorithm to work with over 50 most talent people in the world, every time 45 minutes discussion, and a lot of follow-up practice after mock interview as an interviewer. I do believe that it is possible for me to master a tree algorithm. I took time from August 2018 to June 2019 after my first failure practice dated on August 11, 2018.

Right now, I move on another tree algorithm called lowest common ancestor and ask the algorithm in mock interview on interviewing.io almost every time.



Tuesday, November 26, 2019

124. Binary Tree Maximum Path Sum

Here is the link.

C# mock interview practice on Nov 24, 2019 with insights

Nov 25, 2019
It is one of my mock interview algorithms. I solved the algorithm but I also experienced the nervousness since I could not remember if I solved the algorithm before. It is a hard level algorithm, and I like to write down how to approach the algorithm in the contest or mock interview or onsite.
I solved all tree algorithms on Leetcode six months ago. But my generic approach is to solve all easy level algorithms on Leetcode.com first, and then move to medium level. So it is important for me to explain how to approach this hard level algorithm since I solved similar easy level tree algorithm called longest univalue path, my discussion post is here. I am still in the accumulation stage to solve as many algorithms as possible. Be greedy, solve easy one, solve one with less time first, solve ones to help me build confidence, increase curiosity, and expand my comfortable zone.
Case study
I like to go over the example and explain to myself how to approach the problem. Let me show some diagram with my thought process in my mock interview.
image
I like to go over the example, and explain how I ask question what to do based on example 2.
image
After the work out on example 2, I learned that I need to work on an extra task to calculate the path cross the root node. The whole process from example 1 and example 2 took me around 10 to 15 minutes.
If you cannot follow the process, then I can advice you to review the post I have about longest univalue path. Here is the link.
I spent two months to interview people on interiviewing.io using a few binary tree algorithms almost every weekday, I learn and work every day on tree algorithms. Those interviewees are best teachers in the world and they brought all their education and industry experience to demonstrate how good thinkers are, I learn to build up my curiousity and be a real problem solver, open to all ideas as an interviewer and determin to make the idea work, remove bias and avoid memorization of a solution, ask good questions to follow the idea and understand the question.
References:
image
public class Solution {
    public int MaxPathSum(TreeNode root) {
        if (root == null)
                return 0;
            var maxPathSum = Int32.MinValue;
            postorderTraversal(root, ref maxPathSum);

            return maxPathSum; 
        }

        /// <summary>
        /// return max value of path from root node to one of node downward to leaf node
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        private static int postorderTraversal(TreeNode root, ref int maxPathSum)
        {
            if (root == null)
            {
                return 0;
            }

            var maxLeft = postorderTraversal(root.left, ref maxPathSum);
            var maxRight = postorderTraversal(root.right, ref maxPathSum);

            var sumLeft  = Math.Max(0,maxLeft);
            var sumRight = Math.Max(0, maxRight);

            var currentMax = root.val + Math.Max(sumLeft, sumRight);
            var currentPath = root.val + sumLeft + sumRight; 
            maxPathSum = Math.Max(maxPathSum, currentPath);
            return currentMax;
        }
}