Sunday, June 9, 2019

5087. Letter Tile Possibilities - My first practice after weekly contest

Here is the discussion post I shared.

It is the algorithm in weekly contest, I came out the idea to permutate all possible strings. After the contest, I learned to write my first C# practice in the following.
Here are highlights:
  1. The result is stored in HashSet, so duplicated one will be ignored.
  2. Based on step 1, the depth first search no need worry about duplicate checking.
  3. For any given length, start from leftmost, every index should be considered as next char.
public class Solution {
    /// <summary>
        /// Leetcode 5087
        /// study code
        /// https://leetcode.com/problems/letter-tile-possibilities/discuss/308377/C-DFS-Readable-Solution
        /// 
        /// Brute force solution 
        /// Try all combination of different length from 1 to 7
        /// </summary>
        /// <param name="tiles"></param>
        /// <returns></returns>
        public int NumTilePossibilities(string tiles)
        {
            var set = new HashSet<string>();
            var list = tiles.ToList();

            // brute force all lengths
            // length options: 1, 2, 3, 4, 5, 6, 7
            for (int i = 1; i <= tiles.Length; i++)
            {
                NumTilePossibilitiesHelper(new StringBuilder(), set, list, i);
            }

            return set.Count;
        }

        /// <summary>
        /// backtracking, depth first search
        /// List class API List.Insert(index, value)
        /// Stringbuilder class API StringBilder(start, length)
        /// </summary>
        /// <param name="sequence"></param>
        /// <param name="set"></param>
        /// <param name="tiles"></param>
        /// <param name="length"></param>
        private static void NumTilePossibilitiesHelper(
            StringBuilder sequence, 
            HashSet<string> set, 
            List<char> tiles, 
            int length)
        {
            // base case 
            if (sequence.Length == length)
            {
                set.Add(sequence.ToString());
                return;
            }

            // please consider the next char for all possible chars
            int backtrackingLength = sequence.Length;

            for (int i = 0; i < tiles.Count; i++)
            {
                var current = tiles[i];

                sequence.Append(current);
                // remove current char from the list
                tiles.RemoveAt(i);

                NumTilePossibilitiesHelper(sequence, set, tiles, length);

                // insert current char to the list
                // List.Insert()
                tiles.Insert(i, current);

                // StringBuilder.Remove(start, length)
                sequence.Remove(backtrackingLength, sequence.Length - backtrackingLength);
            }
        }
}


5087. Letter Tile Possibilities

June 9, 2019

Introduction


It is the algorithm I like to learn as many solutions as I can. I also think about how to use this algorithm in mock interview for me to explore the algorithm as much as I can in future interviews on interviewing.io as a mock interviewer.

Case study


Here is one elegant solution I like to explore, learn and write one.
I wrote C# code based on the above post. Here is the link.

I also copy and paste the content here.

It is challenging job to understand the code and solution without a case stduy "AAB". I like to share C# code first with a solution. And then there is a post written with a case study to help to understand how to design, and what is "sum++" statement which refers to a substring in detail.
The solution code
Here is the elegant solution without tiles.
public class Solution {
    /// <summary>
        /// June 9, 2019
        /// study code:
        /// https://leetcode.com/problems/letter-tile-possibilities/discuss/308284/Concise-java-solution
        /// </summary>
        /// <param name="tiles"></param>
        /// <returns></returns>
        public int NumTilePossibilities(string tiles)
        {
            int[] count = new int[26];
            foreach (var item in tiles)
            {
                count[item - 'A']++;
            }

            return depthFirstSearch(count);
        }

        /// <summary>
        /// case study: "AAB"
        /// count: A -> 2, B->1
        /// length 1: "A", "B"
        /// length 2: 
        /// For "A":
        ///   count:  A->1, B->1
        ///   We can still pick either A, or B
        ///   So we have "AA,"AB"
        /// For "B":
        ///   count: A->2, B->0
        ///   We can only pick A
        ///   So we have "BA"
        /// </summary>
        /// <param name="numbers"></param>
        /// <returns></returns>
        private static int depthFirstSearch(int[] numbers)
        {
            int sum = 0; 
            for(int i = 0; i < 26; i++)
            {
                if(numbers[i] == 0)
                {
                    continue;
                }

                sum++; // 
                numbers[i]--;
                sum += depthFirstSearch(numbers);
                numbers[i]++;
            }

            return sum; 
        }
}


Bad Investing Habits You NEED to Break | Phil Town

June 9, 2019

Here is the link.

Bad investing habits to break
  • Try to get rich overnight
  • Giving your money to someone else to invest
  • Over-diversifying your money
  • Panic selling
  • Impatience

Try to get rich overnight

1:25/ 14:09
"If you aren't thinking about owning a stock for 10 years, don't even think about owning it for 10 minutes."  - Warren Buffet

Really good investment is about long-term.

Giving your money to someone else to invest


Simple fact:
Nobody cares about the money as you do. They get percentage. They even do not try to beat stock market. They churn to get bigger commissions.

You do not do your favor to let others do your own work.
You learn how to manage your own funds. Make your own decisions.

Over-diversifying your money

Due diligence

Honest management
Is the price attract?
Are you familiar enough ...
Moat ...

You truly do not understand what you own. You just hope that it goes up.

Impatience


Something just takes time.



ROBO-ADVISORS: Should You Invest with Them for Financial Independence? | Our Warning

Here is the link.


Weekly contest 140

June 9, 2019

Introduction


It is my favorite weekly contest. I started 10 minutes later, first I worked on tree algorithm, and then I worked on the first easy level algorithm. It is best learning experience after the contest.

Case study


I like to study my performance.

Here is the snapshot what I did in the contest.


Learning experience in the contest and after the contest 


June 8 - 10, 2019 
1079. Letter Tile Possibilities C# various topics covered in my practice in 2019
1079. Letter Tile Possibilities C# learn to write a solution after the weekly contest on June 8, 2019
1079. Letter Tile Possibilities C# counting sort and depth first search to count unique substrings practice in 2019 
1079. Letter Tile Possibilities C# case study "AAB" to figure out the solution in 2019 
1081. Smallest Subsequence of Distinct Characters C# using stack and also counting sort
1080. Insufficient Nodes in Root to Leaf Paths C# code could not pass large test case in weekly contest
1078. Occurrences After Bigram C# One iteration of parsed words

Saturday, June 8, 2019

4 Top Large-Cap Value ETFs

Here is the link.


Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - Summary

June 8, 2019
Here is the article.

Summary
The benefits of this strategy are easy to see. Over 44 years it would have increased annualized return by 19% — and more than doubled the cumulative total return — with no additional risk. As far as I have been able to determine, this strategy is the best that an investor is likely to do. That's why I think it's worthy of the descriptive term "ultimate."
Putting this strategy to work
The trickiest part of this strategy is achieving the right level of risk for each investor — how, in other words, to divide your investments between stocks and bonds. Though I've used the industry standard of 60% stocks and 40% bonds, that mix may not be right for you. In my next column I'll show you how to find the right combination.
Before you put this strategy to work, you may want to learn more of what's behind it. Here are three easy ways to do that:
  • For more details and important disclosure about how I arrived at the numbers cited above, I encourage you to check out my longer article.
  • If you'd like to listen to a discussion of this strategy, check out my recent podcast.
  • You can also find my specific and my for implanting this strategy.

Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - step six

June 8, 2019

Here is the article.

Step Six takes us beyond the borders of the U.S. to invest in international stocks. Like U.S. stocks, they have a long-term upward bias. Over shorter periods, the trends in U.S. and international stock markets often offset each other, giving the combination less volatility.
Step Six slices the stock portion equally 10 ways, adding international large, international large value, international small, international small value and emerging markets stocks, which have become an increasingly important part of the world's total market capital — and which have outperformed the S&P 500 over long periods.
With this final step, the 44-year return of the portfolio jumped to 10.5% and had a standard deviation of 11.2%. Recall the industry standard we described in Step One; it had a return of 8.8% and a standard deviation of 11.3%. And for the record, during this same period the S&P 500 returned 10.4% with a standard deviation of 15.5%.

Over 44 years, this portfolio would have grown to almost $8.2 million, twice as much as the traditional pension model we introduced in Step One.


Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - step five

June 8, 2019

Here is the article.

Growth stock investors look for companies with rising sales and profits, enterprises that dominate their markets or aspire to do so. These companies are typical of those in the S&P 500 index.


Value investors, on the other hand, look for stocks that may be temporary bargains, out of favor for reasons that might include poor management, weak finances, new competition or problems with unions, government agencies and defective products — or sometimes perfectly good companies that are in struggling industries.
One by one, these stocks usually make lousy investments. But when they are bundled by the hundreds or even thousands in mutual funds, they have historically outperformed growth stocks. The best value funds use a systematic, mechanical approach to identifying value companies based on financial ratios.
Over the past 87 years, a large-cap value index outperformed the large-cap growth index by nearly three percentage points a year; a small-cap value index outperformed a small-cap growth index by nearly five percentage points.
With additional slices of large-cap value stocks and small-cap value stocks, our portfolio's historic return would have risen to 9.9%, with a slightly lower standard deviation as compared with Step One. And notice how much this would have added to the 44-year cumulative return: More than $2.3 million, 23 times the original $100,000 investment


Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - step four

June 8, 2019

Here is the article.

The standard pension fund's equity portfolio consists mostly of the stocks of the largest U.S. companies. Each of today's giants such as Apple, Google, General Electric and Procter & Gamble was once a small company going through rapid growth that paid off in a big way for early investors.
Because small companies can grow much faster than large ones, including small-cap stocks is an excellent way to enhance long-term returns. The "ultimate" portfolio we're building includes a 12% slice of small-cap stocks, representing the smallest 10% of U.S. companies.
This four-slice pie, from 1970 through 2013, would have produced an annualized return of 8.9%, with a standard deviation of 10.8%.

Actionable Items


I need to look into small cap index fund and compare to S&P index ETF performance last 10 years. 


Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - step three

June 8, 2019

Here is the article.

Step Three: Add real-estate investment trusts

Professionally managed commercial real estate, in the form of real-estate investment trusts (REITs), can reduce risk and increase return. From 1972 through 2013, REITs compounded at 10.4%, almost the same as the S&P 500 (10.5%). As you can see from the pie chart, if REITs made up 12% of this portfolio (20% of the equity slice), the annual return would have been 8.8%, but with less risk: A standard deviation of 10.4%.


Treasury Inflation-Protected Securities – TIPS Definition - Investopedia

Here is the article for me to read.


Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - step two

June 8, 2019

Here is the article.

Step Two: Get bonds right
Whether your portfolio is heavy or light on bonds, the kind of bonds you own makes a huge difference to your risk and your return. I'm in favor of taking carefully calculated risks with stocks, but I believe in being very conservative with the bond part of this portfolio. Therefore it doesn't include long-term bonds or corporate bonds.
My recommended tax-deferred bond portfolio is exclusively in government bond funds: 50% intermediate-term, 30% short-term and 20% in TIPS funds for inflation protection. This is more stable than the standard mix I described above, yet it provides a very similar return.
With this change, the portfolio would have had an annualized return of 8.7% from 1970 through 2013. The industry standard I described in Step One had a standard deviation (a measure of risk) of 11.3%. This change reduces it to 10.9%.
The best is yet to come when we tweak the equity side of the portfolio.

Home RetireMentors Investing 6 steps to the ultimate retirement portfolio - step one

Here is the article.

To be described as "ultimate," a retirement portfolio strategy had better be mighty good. This one is. It has a long historical record of "beating the market" by outperforming the Standard & Poor's 500 Index SPX, +1.05%  — with less risk the 15.5% standard deviation of the index.

Here's the shortest description I can give you: In a nutshell, 60% of this portfolio is a sophisticated combination of equity funds with massive world-wide diversification that includes value stocks, small-company stocks and real-estate funds added to a traditional large-cap growth stock portfolio. The other 40% is made up of short-term to intermediate-term government bonds.


Step One: The basics
The first chart has only two slices, 60% in for stocks (S&P 500 500 index) and 40% in bonds (Barclay's Government Credit Index). This is a traditional industry standard, approximating the way that pension funds, insurance companies and other large institutional investors allocate their assets. The stocks provide long-term growth, while the bonds add stability and income.
Let's use this as our benchmark. For 44 years, from January 1970 through December 2013, this portfolio would have produced a compound annual return of 8.8%. Not bad, especially considering this period included four of the most severe bear markets of the past 100 years.
Allocated this way, an initial investment of $100,000 in 1970 grew to over $4 million by the end of 2013.

Most of the details of this strategy involve the 60% stock side of the pie, and that's the main focus of this article. But the bond part is very important.


Actionable Items


It is challenge part to prepare $100,000 dollars to start a portfolio. I am working on my Canada portfolio Victoria using three ETFs, $37,000 dollars portfolio, using equity 60%, bond 40%, similar idea. 

Deviation is something I have to learn more carefully. When I make decision, I have to learn deviation is normal, and bear market is normal as well. 


Opinion: A half a percent that can change your retirement

Here is the link.


Richo takes on Ash Barty

Here is the video I like to watch a few times.


Being a tennis fan - French open Roland Garros Champion Ashleigh Barty

June 8, 2019

Introduction


It is my small task to post one thing on Facebook.com. I like to show how good I am as a tennis fan of French open champion Ashleigh Barty. I was busy and I did not post anything, last two posts one of them is being a fan of Miami Open March 2019 - Ashleigh Barty.

Being a tennis fan


It is tough to be a tennis fan, since I have to spend time to learn new champion each time. I look up height, how to train, where those coaches help her.

Here is the video I like to watch.


Ashleigh Barty | My Story

Here is 10 minutes interview.

2:00

No matter how good you are, you always can get up to level...?


Friday, June 7, 2019

Looking for action? Try large-cap value stocks

Here is the link.


10 Things You Should Know About Large Cap Value

Here is the podcast link page.


Is one of Wall Street's biggest bulls getting bearish on market?

Here is the link.


Case study: I missed the work today since I thought it is Saturday

June 7, 2019


Introduction


It is the first time I mistakely think that today is Saturday, I did not call the office since I thought that it is Saturday. Until 5:00 PM, my roommate came home and told me that I came home early. She told me it is Friday.

Case study


I like to write down how many facts contributes this mistake in my judgement on this Friday not Saturday instance.

It was too busy a day yesterday. I was too busy to handle and then the mistake happened.

Time line:

Thursday
1. 7:00 AM - 8:00 PM place orders on Questrade.com, and then place two more orders on Ameritrade.com
2. 9:00 AM - 6:30 PM go to work at 9:00 AM, get home around 6:20
3. 6:20 PM - 6:40 PM surf internet and read news on facebook.com
7. 7:00 PM - 7:40 PM Scotia bank appointment with mutual fund manager
8. 8:00 PM - 8:40 PM Tennis court on Burnaby central park
9. 9:00 PM - 9:50 PM Talked to ex-landlord Chinese, a mother about her son and math tutor
10. 10:00 PM - 11:00 PM mock interview on interviewing.io
11. Donate money on GoFundMe.com, share the update on wechat.com sibling group

Friday
1. 7:00 PM - get up, reply wechat message,  at least 20 minutes
2. It is Saturday, somehow I made wrong judgement

1. Get up 7:00 am Thursday

Before I went to work yesterday, I chose the market price and bought $30,000 Canada dollar for my portfolio on questrade.com, and also purchased over $10,000 for my IRA portfolio on Ameritrade.com.

2. I had an appointment with Scotia bank mutual fund manager yesterday, 7:00 PM. I left office around 5:20 PM. I planned to purchase Scotia Canada dollar index fund, $3,000 dollars, every month $120 dollars;

3. I saw goFundMe on facebook.com, my friend in Florida and her husband's heart surgery and diabetic disease before 7:00 PM;

4. I went to play tennis after Scotia bank appointment. I talked to friends on the court in central park about investing and health;

5. I talked to my friend over the phone over 30 minutes from 9:10 PM to 9:50 PM;

6. I had a mock interview from 10:00 PM - 11:00 PM;

7. After 11:00 PM, I was busy with donation to the friend on GoFundMe.com; I shared the story on wechat sibling wechat group;

8. I got up too early around 7:00 AM, I saw two responses from wechat sibling groups. I spend more than 20 minutes to respond.

Actionable Item


I decided to quit my Sibling wechat group, so that I can stay away from relatives, and focus on the life and work in Vancouver area.

One top strategist warns a correction could be coming if no US-China trade deal is reached

Here is the link.


Here are the big losers traders are still buying after earnings

Here is the link.


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.



Wednesday, June 5, 2019

Savita Subramanian

I like to watch all videos and watch the presentation by Savita Subramanian.

Here is Google search result.

Tuesday, June 4, 2019

10 things every investor should know about asset classes

Here is the link.


Case study: First portfolio in questrade.com - Victoria

June 4, 2019

Introduction


It is time for me to set up a portfolio on questrade.com. I have to push myself to learn and also take some risk to build my own portfolio.

Case study


The portfolio I like to set up is the following:

In Canadian dollars
1. $5000 VBAL - ETF, balanced fund, 0.22% MER

$39000 Canadian dollars, 30% VFV, 30% VDU, 40% VAB
2. VFV   $11700, 30%
3. VDU  $11700, 30%
4. VAB   $15600, 40%

I also need to set up orders, and I like to get into the market as soon as possible.

Here are snapshot of two order I placed tonight.



Next order is here:

I like to name this portfolio a beautiful name using one of Vancouver island names. I like to call it Victoria portfolio.

Follow up 



June 6, 2019

I had to pay extra amount in order to get into the market, 600 share pay extra 0.50 cents each share, 140 share pay extra 1 dollar each share. Those two I paid extra few hundred dollars to get into market.

Here are my purchases.


I need to purchase VDU ETF in short future. So I can build a portfolio balanced 60% stock, 40% bond.

Scotia Canadian Index Fund - Series A

Here is the link.

I like to make a purchase plan for my RRSP, initial deposit $3000 dollars, and then $100 every month.

I like to contribute Canada economy. I also notice that MER fee is also lower compared to other Scotia mutual fund.





Scotia Canadian Equity Fund - Series A

Here is the link.


Why Rebalancing Could Be a Huge Mistake

Here is the article to read. Here is the link of podcast.


This lets you set an overall risk profile for your portfolio—for example 60% equities and 40% bonds—and maintain that profile through the ups and downs of the stock market. You know the drill: After a big decline in stocks, buy more (by selling bonds) at low prices; after a big run-up in prices, sell some stocks (when prices are high) and buy bonds.
This is a good strategy. If you didn’t do this, over time you would most likely wind up with a portfolio that’s increasingly heavy on stocks—perhaps 70% when you wanted 60%. That would leave you with a higher risk profile.

So here’s my advice, in three parts.
First, all investors should continue to rebalance between stocks and bonds. This is a legitimate tactic for controlling risk.
Second, young investors probably will do better over the long haul if they don’t rebalance among equity asset classes. Remember the $6.6 million (no rebalancing) versus $4.2 million (annual rebalancing) over the past 50 calendar years.

Third, older investors, certainly including retirees, should be more conservative and not let any single asset class get too far away from its target percentage. For these investors, rebalancing is probably a good idea. It doesn’t have to happen every year, but it should happen at least every four or five years.