Wednesday, January 6, 2021

Leetcode discuss: 158. Read N Characters Given Read4 II - Call multiple times

 Here is the link. 

First practice - C# - Failed - Test case

Dec. 31, 2020
Introduction
I spent over 30 minutes to work on the algorithm in my mock interview. I could not figure out how to solve failed test case in limited time constraint. I will follow up with ideas how to fix it later.

Failed test case
63/81
Input:
"abc"
[1,2,1]
Output:
["a","b","c"]
Expected:
["a","bc",""]

Follow up
Jan. 5, 2020

  1. Trouble shooting, Read function, first if statement should be a while loop.
  2. In Read function, do not change variable n's value, make a copy of n and work on while loop.
  3. It is important to be patient, actually I wrote a simulation for me to debug the code. I learned a few things through this Facebook mock onsite interview algorithm.
/**
 * The Read4 API is defined in the parent class Reader4.
 *     int Read4(char[] buf4);
 */

public class Solution : Reader4 {
    private List<char> buffer = new List<char>(); 
    
    /**
     * @param buf Destination buffer
     * @param n   Number of characters to read
     * @return    The number of actual characters read
     */
    public int Read(char[] buf, int n) {
        // read 5, twice, first one 4, second one
        // read 5, twice, first one 4, second 4 - but only save 5        
        
        var index = 0; 
        
        // read from buffer <- leave n unchange, declare a copy variable: copy = n; work on copy
        if(buffer.Count > 0 && n > 0) // <- this should be while statement - added on Jan. 5, 2020
        {
            buf[index++] = buffer[0];
            buffer.RemoveAt(0);
            n--; 
        }
        
        var totalTimes = (n + 3)/ 4; 
        
        for(int i = 0; i < totalTimes; i++)
        {
            var tmp = new char[4];
            var actual = Read4(tmp);            
           
            for(int j = 0; j < actual; j++)    
            {
                if(index < n)  // <- this requires that n should not be changed. Added on Jan. 5, 2020
                {
                    buf[index++] = tmp[j];    
                }
                else
                {
                    buffer.Add(tmp[j]);
                }
            }
            
            if(actual != 4)
            {
                break; 
            }            
        }
        
        return index; 
    }
}

Sven Carlin: 10 Things To Know Before Buying Undervalued Oil Stocks in 2020

 Here is the link. 

Oil stocks are down, but before investing in oil stocks or buying the cheap oil stocks with high dividend, there are 10 factors you should consider including: oil price analysis, oil production costs, oil stocks volatility, structural headwinds, growth in production, Saudi Aramco, Shell etc.


Leetcode discuss: 1305. All Elements in Two Binary Search Trees

 Here is the link. 

Jan. 6, 2020
It is my mock interview perform. My goal is to take some risk. It should not have TLE concern. What I did is to apply inorder traversal for two trees separately, and then call C# List.AddRange to merge two lists, and then call Sort API.

It is a good practice. It should take me less than 15 minutes.

/**
 * 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 {
    public IList<int> GetAllElements(TreeNode root1, TreeNode root2) {
        var list = new List<int>();         
        traverseInOrder(root1, list);
        
        var list2 = new List<int>(); 
        traverseInOrder(root2, list2);
        
        list.AddRange(list2);
        list.Sort(); 
        
        return list; 
    }
    
    private void traverseInOrder(TreeNode root1, IList<int> list)
    {
        if(root1 == null)
            return; 
        
        traverseInOrder(root1.left, list); 
        
        list.Add(root1.val);
        
        traverseInOrder(root1.right, list);         
    }
}

Leetcode discuss: 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

 Here is the link. 

Second practice - C# - copy idea - Time complexity - Each row maximum cost - Sorting

January 5, 2020
Introduction
It is so quick to learn a new idea and code is so easy to write. I really enjoyed the learning.

Copy idea - C# - changes
I made a few changes to make it work and fit into my style.

It is localize optimization algorithms as well. Do not worry about kth element smallest for given number of columns. Focus on each row, keep kth small numbers of prefix sums.

First row, just start from left to right, and keep kth smallest number. It is smart and easy to do.
Next row, brute force all comibination of two rows, first row has at most kth numbers, second row has size of columns numbers. So combination is easy, k * columns variations.

The time complexity is upper bounded by sorting those k * columns numbers, O(k * columns * log(k * columns)).

Time complexity
O(rows * k * columns * log(k * columns))
Each row upper bound of time complexity is related to sorting algorithm.

My first one hour
I spent one hour in mock interview, but I could not figure out a working solution.

Here are lesson learned:

  1. Work on time complexity analysis - brute force, how to lower the the time compleixty
  2. Brute force, find all sequence in which one number is selected for each row, the combinations are columns^rows. It will time out.
  3. Next, work on exactly how to get next smallest sum for sequence - it is too hard to search - beyond a hard level
  4. Next, relax the condition, each row, find kth smallest numbers. Easy task;
  5. Start from second row, consider sequence of two numbers, keep kth smallest sequence as well. Time complexity, sorting, total upper bound of number - k * columns.
  6. What did I miss in mock interview? Will add later.
  7. Take a row by row solution, work on one row at a time. Next work on combination of two rows, sum of two number sequence, find kth smallest one.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1439_kth_element_II
{
    class Program
    {
        static void Main(string[] args)
        {
            var mat = new int[2][];

            mat[0] = new int[] { 1, 3, 11 };
            mat[1] = new int[] { 2, 4, 6 };

            var result = KthSmallest(mat, 5);
            Debug.Assert(result == 7); 
        }

        /// <summary>
        /// study code and copy idea 
        /// https://leetcode.com/problems/find-the-kth-smallest-sum-of-a-matrix-with-sorted-rows/discuss/609961/C-Without-Priority-Queue
        /// </summary>
        /// <param name="mat"></param>
        /// <param name="k"></param>
        /// <returns></returns>
        public static int KthSmallest(int[][] mat, int k)
        {
            var rows = mat.Length; 
            var columns = mat[0].Length; 

            var currentSum = new List<int>();

            for (int i = 0; i < columns && i < k; i++)
            {
                currentSum.Add(mat[0][i]);
            }            

            // start from second row 
            for (int row = 1; row < rows; row++)
            {
                var nextSum = new List<int>();

                for (int col = 0; col < columns; col++)
                {
                    var current = mat[row][col];

                    foreach (var sum in currentSum)
                    {
                        nextSum.Add(sum + current);
                    }

                    nextSum.Sort(); 

                    // remove those beyond k 
                    while (nextSum.Count > k) 
                    {
                        nextSum.RemoveAt(nextSum.Count - 1);
                    }
                }

                currentSum = nextSum;
            }

            currentSum.Sort();

            return currentSum[k - 1];
        }
    }
}

Leetcode discuss: 1439. Find the Kth Smallest Sum of a Matrix With Sorted Rows

 Here is the link. 

First practice - C# - TLE 35/71 - DFS

Jan. 5, 2020
Introduction
It is the last algorithm in one of mock onsite on Leetcode premium. I spent over one hour but I could not figure out working solution - not brute force. It is hard to figure out next smaller. After the mock session, I wrote a DFS solution and then ran into TLE error.

Test case 35/ 71
Timeout - I will quickly figure out how to fix this issue. I believe that I should apply some pruning so it will be able to avoid TLE.

Time compleixty
DFS algorithm will exhaust all options, upper bound will be related to columns^ rows, which is the number of sequence, in which one for each row.

The working solution will take less than 20 minutes to write, and time complexity can be low as O(rows * k * columns * log(k * columns)).
Here is my working solution.

My first one hour
I spent one hour in mock interview, but I could not figure out a working solution.

Here are lesson learned:

  1. Work on time complexity analysis - brute force, how to lower the the time compleixty
  2. Brute force, find all sequence in which one number is selected for each row, the combinations are columns^rows. It will time out.
  3. Next, work on exactly get next smallest sum for sequence - it is too hard to search - beyond a hard level
  4. Next, relax the condition, each row, find kth smallest numbers. Easy task;
  5. Start from second row, consider sequence of two numbers, keep kth smallest sequence as well. Time complexity, sorting, total upper bound of number - k * columns.
  6. What did I miss in mock interview? Will add later.
  7. Take a row by row solution, work on one row at a time. Next work on combination of two rows, sum of two number sequence, find kth smallest one.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _1439_kth_element
{
    class Program
    {
        static void Main(string[] args)
        {
            var mat = new int[2][];

            mat[0] = new int[] { 1, 3, 11};
            mat[1] = new int[] { 2, 4,  6};

            var result = KthSmallest(mat, 5);
            Debug.Assert(result == 7); 
        }

        public static int KthSmallest(int[][] mat, int k)
        {
            if (mat == null || mat.Length == 0 || mat[0].Length == 0)
            {
                return -1;
            }

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

            var sorted = new SortedSet<Tuple<int, int>>();
            var list  = new List<int>();
            var index = 0; 

            runDFS(mat, k, sorted, 0, list, ref index);

            return sorted.Last().Item1; 
        }

        private static void runDFS(int[][] mat, int k, SortedSet<Tuple<int, int>> sorted, int row, List<int> list, ref int index)
        {
            if (row >= mat.Length)
            {
                var total = list.Sum(); 

                if (sorted.Count < k)
                {
                    sorted.Add(new Tuple<int, int>(total, index++));
                }
                else if (sorted.Count == k && sorted.Last().Item1 > total)
                {
                    sorted.Remove(sorted.Last());
                    sorted.Add(new Tuple<int,int>(total, index++));
                }

                return;
            }

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

            for (int col = 0; col < columns; col++)
            {
                var current = mat[row][col];

                // check the sum so far - compare to sorted
                if (sorted.Count == k && sorted.Last().Item1 < list.Sum() + current)
                {                    
                    break;                    
                }

                list.Add(mat[row][col]);

                runDFS(mat, k, sorted, row + 1, list, ref index);

                list.RemoveAt(list.Count - 1);
            }
        }
    }
}

Leetcode discuss: 123. Best Time to Buy and Sell Stock III

 Here is the link. 

C# - mock interview - performance - design issue

Jan. 6, 2020
It is challenge for me to analyze this written solution in mock onsite interview, how to quickly modify the design to make it work, fix TLE error.

The TLE problem
The function I designed called MaxProfitOneTrade takes O(N) time for each start variable.
It should be simplifyed using dynamic programming to make it O(1).

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

namespace stockTradeII
{
    class Program
    {
        static void Main(string[] args)
        {
            var result = MaxProfit(new int[]{1, 2});
        }

        public static int MaxProfit(int[] prices)
        {
            if (prices == null || prices.Length < 4)
            {
                return 0;
            }

            var length = prices.Length;
            var twoOrderProfit = 0;

            // at most 2 
            for (int i = 0; i + 1 < length; i++)
            {
                var first = MaxProfitOneTrade(prices, 0, i);
                var second = MaxProfitOneTrade(prices, i, length - i);
                var current = first + second;
                twoOrderProfit = current > twoOrderProfit ? current : twoOrderProfit;
            }

            return twoOrderProfit;
        }

        /// <summary>
        /// the problem of the design is time complexity
        /// O(N), it can be O(1), using extra space, save all profit for each position
        /// </summary>
        /// <param name="prices"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private static int MaxProfitOneTrade(int[] prices, int start, int length)
        {
            if (prices == null || length == 0)
            {
                return 0;
            }

            var minPrice = prices[start];
            var maxProfit = 0;

            for (int i = start + 1; i < start + length; i++)
            {
                var current = prices[i];
                var isSmaller = current < minPrice;
                if (isSmaller)
                {
                    minPrice = current;
                }
                else
                {
                    var profit = current - minPrice;
                    maxProfit = profit > maxProfit ? profit : maxProfit;
                }
            }

            return maxProfit;
        }
    }
}

Leetcode discuss: 123. Best Time to Buy and Sell Stock III

Here is the link. 

C# - dynamic programming - case study - choose DP first always

Jan. 6, 2020

This solution is based on the Best Time to Buy and Sell Stock (Easy level) where you track the global minimum price and maximum profit. At most two trades are considered, so the important task is to divide the array into two areas.

Go left to right, and store the best profit for each day individually in left.
left[i] shows the max profit for days [1, i]

Go right to left, store best profit in right
right[i] shows the max profit for days [i + 1, n]

The maximum profit is the maximum of left[i] + right[i] for i = 0 to n - 1.

Case study
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6

The idea is to find at most two trades to make maximum profit. The array interval can be divided into two intervals. There are at most n ways to divide.

It is to think about dynamic programming way to use exisitng calculated solution.
[3, 3, 5], how to calculate the maximum profit for one trade in the interval, last index is 2, value 5, only need to find minimum value in previous interval.
left[2] = Math.Max(left[1], 5 - minPrice[i - 1]).

Just consider current price 5 to calculate it's maximum profit value.

[0,0,3,1,4]
this one is to work from right to left iteration order. Index position is 4, value 0, the maximum profit to purchast at index = 4 is to find maximum profit in right side of the index = 4.

public class Solution {
    // at most two trades - maximum profit
        // dynamic programming solution
        // 
        public int MaxProfit(int[] prices) 
        {
            var n = prices.Length;

            var minLeft = Int32.MaxValue;
            var maxRight = 0;
            var maxProfit = 0;

            var left  = new int[n + 1]; 
            var right = new int[n + 1];

            // interval from [0, i]
            for (int i = 0; i < n; ++i) 
            {
                var price  = prices[i];                

                minLeft     = Math.Min(minLeft, price);                
                left[i + 1] = Math.Max(left[i], price - minLeft);                
            }

            // interval from [n - i - 1, n)
            for (int i = 0; i < n; ++i)
            {                
                var price = prices[n - i - 1];
                
                maxRight = Math.Max(maxRight, price);               
                right[n - i - 1] = Math.Max(right[n - i], maxRight - price);
            }

            // at most two trades
            for (int i = 0; i < n; i++ )
            {
                maxProfit = Math.Max(maxProfit, left[i] + right[i]);
            }
            
            return maxProfit;            
        }
}

 

Leetcode discuss: 839. Similar String Groups

 Here is the link. 

Second practice - C# - Union Find - Union API lesson learned

Jan. 6, 2020

I wrote the working solution after the bug fix - Union API functionality. Since the code I wrote in mock interview failed on one test case, I learned the lesson. The failed practice is here.

Importance
It took me more than a hour to learn to fix the problem after the mock interview. I need to be humble and stay cautious on wrong answer to apply Union Find algorithm.

public class Solution {
    // union find algorithm    
        public int NumSimilarGroups(string[] strs)
        {
            if (strs == null || strs.Length <= 1)
                return 0;

            var length = strs.Length;
            var parents = new int[length];

            for (int i = 0; i < length; i++)
            {
                parents[i] = i;
            }            

            for (int i = 0; i < length - 1; i++)
            {
                var first = strs[i];

                for (int j = i + 1; j < length; j++)
                {
                    var second = strs[j];
                    
                    if (runSimilarCheck(first, second))
                    {
                        parents[FindParent(j, parents)] = FindParent(i, parents);
                    }                    
                }
            }

            // run again 
            for (int i = 0; i < length; i++)
            {
                parents[i] = FindParent(i, parents);
            }

            var count = 0;
            for (int i = 0; i < length; i++)
            {
                if (i == parents[i])
                {
                    count++;
                }
            }

            return count;
        }

        private static bool runSimilarCheck(string s1, string s2)
        {
            var length = s1.Length;
           
            var count = 0;

            for (int i = 0; i < length; i++)
            {
                if (s1[i] != s2[i])
                {
                    count++;                    
                }
            }            

            // since s1 and s2 are anagram, there is no need to compare chars between s1 and s2. 
            return count <= 2 ;
        }

        private static int FindParent(int start, int[] parents)
        {
            if (start != parents[start])
            {
                parents[start] = FindParent(parents[start], parents);
            }

            return parents[start];
        }
}