Showing posts sorted by date for query Leetcode 212. Sort by relevance Show all posts
Showing posts sorted by date for query Leetcode 212. Sort by relevance Show all posts

Sunday, October 25, 2020

Leetcode discuss: 1631. Path With Minimum Effort

Here is the link on youtube.com. 



Here is my Leetcode discuss post.

First practice - C# copy idea and copy code to learn quickly

Oct. 25, 2020
Introduction
It is the third algorithm in weekly contest 212. I started the contest late and only had 10 minutes left, I thought about the problem and it was hard. I could not find a working idea.

After the contest
I just quickly went over the discussion post, and then I like to study the code and then figure out the following:

  1. Start from top left node in the matrix, define C# Tuple<int, int,int>(int Height, int row, int col);
  2. Try to start from top left node to visit all nodes in the matrix, but choose the order to get minimum distance. How to do that? Design a minimum heap.
  3. Define a minimum heap with distance, and always remove the minimum node from the heap, and then visit it's unvisited neighbors, and add all those neighbors to the heap.
  4. Make sure that visit all nodes in the order based on minimum distance until bottom right node is reached.
  5. Define a node with distance based on consideration of previous node's distance in minimum heap process and current one.

Case study
I think that the code is pretty standard minimum heap practice once I understand the idea and learn how to reason it.

I need to look into C# SortedSet default comparer for this Tuple<int, int, int>. It is surprising that the code can be simplified using short hand expression, and no need to write any code related to IComparer as well. I did look up Google.

It is much better to work on a small case study, then I can quickly understand the algorithm and how to design it next time.

Example:
Matrix
1, 2, 3
3, 8, 2
5, 3, 5
Using A, B, C, D, E to mark those first five nodes in matrix.
1A, 2B, 3C
3D, 8E, 2
5, 3, 5
Add A node in matrix into minimum heap, (0,0,0), remove minimum one in the heap, and then visit A's neighbor nodes B and D, and then add B and D into minimum heap.
Next step is to remove minimum node in the heap, which is B. The distance is 1, and add C and E into the heap.

Step by step
Let me work on a more simple example,
Example:
Matrix
1, 2
3, 8
Add A, B, C, D marks to simplify the explanation.
1A, 2B
3C, 8D
1A is added to minimum heap, the minimum effort is 0;
remove 1A from minimum heap, and visit two neighbors, 2B and 3C.
1A -> 2B has minimum effort 1, and 1A to 3C has minimum effort 2.

Add 2B and 3C to minimum heap. The smallest one is 2B.

Next is to remove 3B from minimum heap, visit 2B's neighbor 8D, so 8D has minimum effort 6. Add (6, 1, 1) to minimum heap.

Next is to remove 3C from minimum heap, visit 3C's neighbor 8D, so 8D has minimum effort 5. Add (5, 1, 1) to minimum heap.

The tip is to mark visit only after the node is popped from minimum heap. In our simple example case, 8D has chance to be added into minimum heap more than once, first one is with height 6, second one is with height 5.

Since minimum heap is sorted, the path from 1A->3C->8D is removed from minimum heap first before 1A->2B->8D, the answer is 5 not 6.

In summary, the first tip is enforce order using minimum heap, and the second tip is to mark visit after the node is removed from minimum heap, so one node 8D has two chance to be considered and added to minimum heap. It is kind of clever. But it took me over 30 minutes to figure out, I had to debug the code using Visual studo first, and then figure out step by step.

Go over again, the minimum heap step by step:

  1. 1A, (0, 0, 0)
  2. remove 1A from heap, add 2B and 3C, sort them.
    (1, 0, 1)
    (2, 1, 0)
  3. remove 2B from minimum heap, add 8D into minimum heap.
    (2, 1, 0)
    (6, 1, 1)
  4. remove 3C from minimum heap, add 8D into minimum heap.
    (6, 1, 1)
    (5, 1, 1)
    sort them
    (5, 1, 1)
    (6, 1, 1)
    Remove 8D from minimum heap, which is bottom right, minimum effort is 5, not 6. The path is from 1A -> 3C -> 8D.

I do believe if I can read this short case study, then I can write the code in the contest or phone screen in 10 minutes. But I have to go over step by step to understand competition of two 8D entries in minimum heap in order to get minimum effort.

public class Solution {
        // (0,1),(1,0),(0,-1), (-1,0) four directions, simplified version
        private int[] directions = new int[] { 0, 1, 0, -1, 0 };
    
        /// Oct. 25, 2020
        /// study code: 
        public int MinimumEffortPath(int[][] heights)
        {
            int r = heights.Length;
            int c = heights[0].Length;
            bool[,] visited = new bool[r,c];
            
            // declare Tuple data type
            // https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/types
            // new Tuple<int,int,int>( int H, int X, int Y) -> short hand -> (int H, int X, int Y)
            // default comparer ? 
            var sorted = new SortedSet<(int H, int X, int Y)>();
            
            sorted.Add((0, 0, 0)); 
            while (sorted.Count > 0)
            {
                // find smallest one in Height, if the same, then compare X, then compare Y
                // ask why? What is strategy? Find smallest one - greedy 
                // 
                var cur = sorted.Min;
                
                if (cur.X == r - 1 && cur.Y == c - 1)
                {
                    return cur.H;
                }
                
                visited[cur.X, cur.Y] = true;
                
                // Look up C# SortedSet source code - Remove API
                // very complicated - red black tree - find node and remove node
                // https://referencesource.microsoft.com/#system/compmod/system/collections/generic/sortedset.cs
                sorted.Remove(cur);
                
                for (int d = 0; d < 4; d++)
                {
                    int nx = cur.X + directions[d];
                    int ny = cur.Y + directions[d + 1];
                    
                    if(nx < 0 || nx == r || ny < 0 || ny == c || visited[nx,ny]) 
                    {
						continue;
                    }
                   
                    // all nodes in smallest path - smallest distance should be maximum one
                    var next = Math.Max(cur.H, Math.Abs(heights[cur.X][cur.Y] - heights[nx][ny]));
                    
                    sorted.Add((next,nx,ny));
                }
            }

            return 0;
        }
}

After mock interview
10/25/2020 3:58 PM 

I could not make it work in my mock interview as an interviewer, then I debugged the code using visual studio, and learned the detail the competition case in minimum heap. 

I recorded another video. 

Wednesday, June 24, 2020

Leetcode discuss: 208. Implement Trie (Prefix Tree)

Here is the post.

C# Trie algorithm practice in June 2020

June 24, 2020
Introduction
It is the second algorithm of my mock interview. I did not start to work on until 20 minutes left. So I did successfully submit the answer, since I just worked on Trie algorithm hard level 212 Word search. I also wrote in detail how to design a Trie. The link will be provided here as well.
Here are my practice:
  1. Understand Trie recursive data structure of Tree;
  2. Think about Trie as a binary tree when I implement, and then understand "new Trie()" for child node assignment;
  3. Do not get confused with statement "root.word != null", another one is "word != null"
public class Trie {

    
    private Trie[] Children = new Trie[26];
    private string word; 
    
    /** Initialize your data structure here. */
    public Trie() {
        //Children = new Trie[26];
        
    }
    
    /** Inserts a word into the trie. */
    public void Insert(string word) {
        if(word == null || word.Length == 0)
            return;
        
        var root = this; 
        
        foreach(var item in word)
        {
            if(root.Children[item - 'a'] == null)
            {
                root.Children[item - 'a'] = new Trie();
            }
            
            root = root.Children[item - 'a'];
        }
        
        root.word = word;  
    }
    
    /** Returns if the word is in the trie. */
    public bool Search(string word) {
        if(word == null || word.Length == 0)
            return false;
        
        var root = this; 
        
        foreach(var item in word)
        {
            if(root.Children[item - 'a'] == null)
            {
                return false;
            }
            
            root = root.Children[item - 'a'];
        }
        
        return root.word != null; 
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public bool StartsWith(string prefix) {
        if(prefix == null || prefix.Length == 0)
            return false;
        
        var root = this; 
        
        foreach(var item in prefix)
        {
            if(root.Children[item - 'a'] == null)
            {
                return false;
            }
            
            root = root.Children[item - 'a'];
        }
        
        return true; 
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.Insert(word);
 * bool param_2 = obj.Search(word);
 * bool param_3 = obj.StartsWith(prefix);
 */


Tuesday, June 16, 2020

Leetcode discuss: 212. Word Search II

Here is the link. 

C# Trie design challenge and DFS algorithm practice in June 2018

June 16, 2020
It is challenge task to write the depth first search algorithm using Trie data structure. It took me several hours to make it work. I failed three test cases, and then I like to write down my lessons here.

First it is the design of depth first search. The checking of our-of-index-range of the matrix, visited node, child node is not in Trie data structure object are those three important checkings for a complete test.

Second one is to understand Trie data structure. Trie is a recursive data structure, so it is important to identify current node matrix[row][col] with function argument TrieNode parentNode relationship. The design is to pass parentNode which is not null, so the child node may not be in Trie data structure object.

Third one is to write TrieNode Build function to construct a Trie tree object. It is not easy task, so please work on "a", one char word, and it should be two level, parent node is dummy head, and dummy head's child is 'a' instead.

What else can I write down to make this TrieNode class crafting more error-prone?

  1. I change for(int i = 0; i < words.Length; i++) to foreach loop to make code clean, no need to use i to do any checking.
  2. Dummy head is important, and also understand that the call is passed using parent node;
  3. Statement: public TrieNode[] nodes = new TrieNode[26]; each nodes[i] is still null pointer.
  4. Remove "iterate.word = word;" outside statement "foreach (char c in word)" in TrieNode class API defintion.
  5. GetByIndex API of TrieNode should check pointer null first.

Template of DFS

  1. Design a DFS function to search a matrix, please understand DFS and also backtracking.
  2. Function name runDFS is good enough, TrieNode parentNode argument should be clearly defined, since current char may not be in Trie object.
  3. Put all edge cases in one statement, do not define explanation variable "var visit = board[row][col]" before checking index range and also board's content has not been visited yet.
  4. One word in dictionary can be a prefix in another word in dictionary, so it should continue to search. Termination should not put after the word is added to found string.
  5. Think about time complexity using Trie compared to HashSet, and practice more often Trie to solve problems.
  6. Discuss termination of DFS with interviewer or think about more test cases. It is safe to continue to search if a word is found, let it fall through the checking of index-out-range or char is not in the tree.

Template of TrieNode definition of Build

  1. Trie is a recursive data structure, tree data structure;
  2. Trie should start from a dummy hand for easy reference;
  3. Child node is one of element of TrieNode[26] array
  4. Child node is still null pointer even TrieNode[26] is called using statement " ... = new TrieNode();"
  5. Clean up TrieNode Build API

Special case: binary tree
To expedite the process to craft a TrieNode class Build API, treat special case a binary tree and see how to make it work; left and right child map to index 0 and 1. If left child exist, then do nothing except going to left child for next iteration. If left child does not exist, then create one first. Go over each word in dictionary, build a binary tree to include all words, assuming that all chars are 'a' or 'b' in those words. Try to go over the following test case 3, build a trie by hand first, and then talk about how to write a trie version with size of 26 array.

For each word in dictionary, go through char by char, and then start from dummy head of Trie object, and then if child node is created then continue, otherwise create the tree object.

Test case Trie
I failed the test case 3, so I like to share this test case.

image

One word in dictionary can be a prefix in another word in dictionary, so it should continue to search. Depth first search algorithm's termination should not put after the word is added to found string.
In the above test case, "aaa" is the prefix of "aaaa".

Practice talk
I could not perform very well on Amazon code screen this March. The reason is that debugger is disabled, and my design is not relax to allow mistake happen. I write something to remind myself, focus on design when debugging, think about modifying design to make it more robust.

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

namespace _212_word_search_warmup_June_16_20
{
    class Program
    {
        static void Main(string[] args)
        {
            //RunTestcase1();
            //RunTestcase2();
            RunTestcase3(); 
        }

        public static void RunTestcase1()
        {
            var board = new char[4][];

            board[0] = "oaan".ToCharArray();
            board[1] = "etae".ToCharArray();
            board[2] = "ihkr".ToCharArray();
            board[3] = "iflv".ToCharArray();

            var found = FindWords(board, new string[] { "oath", "pea", "eat", "rain" }); 
        }

        public static void RunTestcase2()
        {
            var board = new char[1][];

            board[0] = "a".ToCharArray();            

            var found = FindWords(board, new string[] { "b"}); 
        }


        public static void RunTestcase3()
        {
            //[["a","b"],["a","a"]]
            // ["aba","baa","bab","aaab","aaa","aaaa","aaba"]
            var board = new char[2][];

            board[0] = "ab".ToCharArray();
            board[1] = "aa".ToCharArray();

            var found = FindWords(board, new string[] { "aba", "baa", "bab", "aaab", "aaa", "aaaa", "aaba" });

            // ["aba","aaa","baa","aaba"]
            // ["aaa","aaab","aaba","aba","baa"]  expected - mine is missing: "aaab"
        }

        /// <summary>
        /// design Trie class 
        /// </summary>
        class TrieNode
        {
            public TrieNode[] nodes = new TrieNode[26];
            private string word;

            /// <summary>
            /// Design Trie class
            /// Please use the following test cases:
            /// ["a"]
            /// </summary>
            /// <param name="words"></param>
            /// <returns></returns>
            public TrieNode Build(string[] words)
            {
                if (words == null)
                {
                    return new TrieNode(); 
                }

                var original = new TrieNode(); // dummy head                
                
                var length = words.Length;   // ["oath",""]
                foreach (var word in words)
                {
                    var iterate = original;  // start from root char again                    

                    foreach (char c in word)
                    {                                                                       
                        int index = c - 'a';
                        if (iterate.nodes[index] == null)  // caught by online judge
                        {
                            iterate.nodes[index] = new TrieNode();
                        }

                        // go to next trie node  
                        iterate = iterate.nodes[index];                        
                    }

                    iterate.word = word;
                }

                return original; 
            }

            public bool IsWord()
            {
                return word != null;
            }

            public string GetWord()
            {
                return word; 
            }

            public bool IsUnitialized()
            {
                return nodes == null; 
            }

            public void Initialize()
            {
                nodes = new TrieNode[26];
            }

            public TrieNode GetByIndex(int index)
            {
                if (nodes[index] == null)
                    return null;

                return nodes[index];
            }
        }

        /// <summary>
        /// Code review on June 16, 2020
        /// warmup practice
        /// 1. Design backtracking, walk through the example "oath" to explain to myself 
        /// how 'o','a','t','h' is marked as '#', after the word "oath" is added to the hashset, 
        /// all matrix's positions have original chars back. 
        /// 2. I did not fully understand how to apply backtracking back in June 2019, so I wrote my experience
        /// on Lowest common ancestor showcase on Leetocode discuss
        /// 3. This is perfect time for me to master the backtracking in DFS. 
        /// Facts:
        /// Sometimes one word is another word's prefix in dictionary. 
        /// So do not stop search if the word is added to found hashset. 
        /// </summary>
        /// <param name="board"></param>
        /// <param name="words"></param>
        /// <returns></returns>
        public static IList<string> FindWords(char[][] board, string[] words)
        {
            if (board == null || words == null)
            {
                return new List<string>(); 
            }

            // build a trie
            var trie = new TrieNode(); 
            trie = trie.Build(words);  // caught by debugger            

            var rows = board.Length;
            var columns = board[0].Length;

            var set = new HashSet<string>(); 

            for (int row = 0; row < rows; row++)
            {
                for (int col = 0; col < columns; col++)
                {
                    runDFS(board, row, col, trie, set);
                }
            }

            return set.ToList(); 
        }

        /// <summary>
        /// Design requirement: 
        /// TrieNode
        /// Make sure that parentNode is not null all the time
        /// current node is one of parentNode's child
        /// </summary>
        /// <param name="board"></param>
        /// <param name="words"></param>
        /// <param name="found"></param>
        private static void runDFS(char[][] board, int row, int col, TrieNode parentNode, HashSet<string> found)
        {
            var rows = board.Length;
            var columns = board[0].Length;
            var visitedChar = '#';            

            // out of range or visited already
            // or current node trie[visit - 'a'] is not in Trie
            if (row < 0 || row >= rows || col < 0 || col >= columns || 
                board[row][col] == visitedChar ||
                parentNode.GetByIndex(board[row][col]-'a') == null
                )  
            {
                return; 
            }

            var visit = board[row][col];
            var child = parentNode.GetByIndex(board[row][col] - 'a');

            // work on trie
            if (child.IsWord())
            {
                found.Add(child.GetWord());
                //return;  // June 16, 2020 case 3: sometimes a word is another word's prefix in dictionary. So continue to search. 
            }

            // Design DFS with backtracking 
            var current = board[row][col];
           
            // mark visited
            board[row][col] = visitedChar;            
            
            // Four directions - clockwise, top, right, down, left
            runDFS(board, row - 1, col, child, found);
            runDFS(board, row, col + 1, child, found);
            runDFS(board, row + 1, col, child, found);
            runDFS(board, row, col - 1, child, found);

            //backtracking
            board[row][col] = current; 
        }
    }
}

Comment

Monday, June 15, 2020

Leetcode discuss: Trie data structure showcase

Here is the link.

C# Trie showcase starting from 2018

C# Trie showcase practice starting from 2017
  1. Word Search II
    C# First practice using Trie in 2017
    C# Trie data structure DFS algorithm practice in June 2020
More practice:
139 word break I
I plan to write a solution using Trie to expedite the search of dictionary.
Tsinghua coach - my practice in 2018
Suggest a char based on prefix occurrence