Sunday, June 9, 2019

1079. Letter Tile Possibilities - C# various topics covered in my practice in 2019

Here is the link.

It is the algorithm I learned after weekly contest 140. I was surprised that I have difficulty to come out the solution in the weekly contest, I like to push myself to master the algorithm in next three to six months. One idea is to ask the algorithm in mock interview on interviewing.io as an interviewer, and also practice various ideas using C#.
I also like to put together all kinds of ideas in this post, and then push myself to learn depth first search algorithm better through the practice.
June 8, 2019
Use hashSet to remove duplicate and help to count the total number
C# learn to write a solution after the weekly contest on June 8, 2019
June 9, 2019
Only put unique substring into consideration
C# counting sort and depth first search to count unique substrings practice in 2019
Understand each tile using prefix string
C# case study "AAB" to figure out the solution in 2019


How McKinsey Became One Of The Most Powerful Companies In The World

Here is the link.


If you hold the stock market, you will grow with America, says Jack Bogle

Here is the link.

Grow with America. GDP, annual correlation with GDP.

Question:

Buy and hold is dead?

Answer:

Buy and hold US stock is different. If you hold the stock market, you will grow with America. The stock market is ...

Short way bet is not good way to go. Long way bet is way to go.

Question:

10 Years after the crisis
What's the next crisis?

Mechanic buyers, marketing structure? Liquidity crunch?

If there is panic over there, then there is anywhere.

Which ETF? High yield?




5087/ 1079. Letter Tile Possibilities - case study "AAB"

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. Also, I did case study on "AAB", and then I wrote a solution to show all tiles as well. Here is the link.

I also copy and paste the content here.

It is challenging job to write a case study, and then figure out how to interpret the code written in such an elegant solution, the solution post is here. I like to share the solution with case study "AAB" and extra output to show depth first search all result with "AAB" study case.
Case study "AAB"
I like to write down some explanation based on case study "AAB". I am just a learner with some curiousity. Follow me and let me know if I miss the important things in my analysis.
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"
The answer is 8. How to ensure uniqueness?
set prefix = ""
dfs("AAB") -> two distinct chars, 'A', 'B', each one sum variable increment one; related to tile: prefix + "A", prefix + "B".
For 'A' case, next step is to calculate dfs("AB"), what ever it has, the string should be prefixed with "A".
For 'B' case, next step is to calculate dfs("AA"), what ever it has, the string should be prefixed with "B".
So the output of search result is the following:
"A"
"AA"
"AAB"
"AB"
"ABA"
"B"
"BA"
"BAA"
Next step
Since the algorithm is to ask the total number of tile possibilities, we do not need to know all tiles. I mark those lines of code added just to be easily followed.
The code with debugging info
I made a few changes based on study code, so that it is easy to tell statement "sum++", what is the tile content.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _5087_Letter_tile_possibilities
{
    class Program
    {
        static void Main(string[] args)
        {
            NumTilePossibilities("AAB");
        }

        /// <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 static int NumTilePossibilities(string tiles)
        {
            int[] count = new int[26];
            foreach (var item in tiles)
            {
                count[item - 'A']++;
            }

            var all = new List<string>();
            return depthFirstSearch(count, "", all);
        }

        /// <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"
        /// Questions:
        /// 1. uniqueness - not duplicated one, how to ensure uniqueness
        /// 2. 
        /// </summary>
        /// <param name="numbers"></param>
        /// <returns></returns>
        private static int depthFirstSearch(int[] numbers, string prefix, List<string> tiles)
        {
            int sum = 0; 
            for(int i = 0; i < 26; i++)
            {
                if(numbers[i] == 0)
                {
                    continue;
                }

                sum++; 
                /* determine what is tile to be added*/
                char toChar = Convert.ToChar('A' + i);
                var nextPrefix = prefix + toChar.ToString();
                tiles.Add(nextPrefix);
                /**/

                numbers[i]--;
                sum += depthFirstSearch(numbers, nextPrefix, tiles);

                numbers[i]++;
            }

            return sum; 
        }
    }
}

William Lee economist

Here is the link.


top strategist Dan Suzuki

Here is the link.

BofA's Suzuki: Stocks go lower before higher in 6-12 months, here is the link. 

Yana Barton, Eaton Vance equity portfolio manager

Here is the link to watch all videos from Yana Barton.

Nancy Davis, Quadratic Capital CIO

Here is the link to spend time watch videos searched by Google.




Stocks just had their best week of the year as Wall Street bets Jerome Powell will save rally

Here is the link.


State of the Market 2019 | Phil Town

Here is the link.

State of the market 2019


  • America has a strong economy
  • Keep your money in cash
  • Search for wonderful companies
  • Build up your watch list

5:09 - 5:52/ 8:41
Market valuation vs GDP - 20%, the age of Warren Buffet invested more than a few decades ago as a young man.

20% - compared to GDP when Warren Buffet invested

Right now, related to GDP, the price is higher than memory, 175% of GDP.

6:20
Build a watch list of wonderful business - how to do it?

Every 10 years or so, economic storm ...

The moat company will take market share ...

7:34
Most of companies are not selling right now, the price is high.

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.