Here is the video. I like to take some notes and then spend time slowly thinking about every idea.
In the world we live in today, the richest 1% of the population controls 48% of the total wealth and the top 80 richest individuals are worth as much as half the world’s population or roughly 3.5 billion people. When considering these figures, there is no doubting the fact that there is a separation between the rich and the poor. While many people assume these wealthy individuals gained their wealth by being born into wealth or winning the lottery, that simply isn’t true. In fact, only 11 out of the 80 richest individuals were passed down their fortunes with the other 69 having made their wealth through their own hard work and determination. And one of these 69 individuals is none other than the investor mogul himself, Warren Buffett. Like the majority of these rich individuals, Warren Buffett grew up in a middle-class family but found a way to amass the knowledge and skills that would eventually lead him to accumulating a wealth of over $70 billion.
Rich John vs poo Tim, similar IQ, same city,
Tim watches show.
John work on credentials.
Rich never stops learning -> Tim complained about $100 bonus. John got $10,000 check in his name.
Difference number 2:
Rich sells value, poor sells time
Difference number 3:
The rich pays them first, poor pays them last.
TV costs $1,000 for Tim, at a cost of $500 for play station.
Difference number 4:
The rich has growth mindset, the poor has fixed mindset.
Difference number 5:
Delay gratification - the rich understands the delay gratification.
Difference number 6:
The rich build a stream of income, but the poor does not.
Difference number 7:
The rich surrounds him
Difference number 8:
1. NEVER STOP LEARNING: CONTINUE TO PUT FEW HOURS EVERY NIGHT TO WORK TOWARDS GOAL
2. RICH SELL VALUE POOR SELL TIME: Instead of saying how long you been doing the work, you must ask yourself first what value you are providing.
3. RICH PAY THEMSELVES FIRST WHILE THE POOR PAY THEMSELVES LAST: With this rich strategy you will always have some savings at the end of the month.
4. RICH HAVE A GROWTH MINDSET WHILE THE POOR HAVE A FIXED MINDSET: Instead of cursing anybody why you don’t have money, always think of how you can earn more to get what you want.
5. RICH UNDERSTAND THE POWER OF DELAYING GRATIFICATION WHEREAS THE POOR SEEK SHORT TERM PLEASURE: Delaying instant gratification beat out many of the more traditional signals including age, race, ethnicity and height
6. RICH BUILD SEVERAL STREAMS OF INCOME WHILE THE POOR RELY ON ONLY ONE: Never keep all eggs in one basket if the basket is gone then lose everything.
7. RICH SURROUND THEMSELVES WITH OTHER RICH PEOPLE WHEREAS THE POOR SURROUND THEMSELVES WITH OTHER BROKE INDIVIDUALS: You tend to get more ideas of making money from other rich individuals.
From January 2015, she started to practice leetcode questions; she trains herself to stay focus, develops "muscle" memory when she practices those questions one by one. 2015年初, Julia开始参与做Leetcode, 开通自己第一个博客. 刷Leet code的题目, 她看了很多的代码, 每个人那学一点, 也开通Github, 发表自己的代码, 尝试写自己的一些体会. She learns from her favorite sports – tennis, 10,000 serves practice builds up good memory for a great serve. Just keep going. Hard work beats talent when talent fails to work hard.
Monday, October 14, 2019
My 10th Canada thanksgiving day in the city of Vancouver
I like to choose something to watch beside stock, investment, algorithm. I chose the video to visit Nicole home in Los Angeles.
Here is the video. Now it is 10:30 AM. I am watching the video second time. I just like Nicole to be my voice teacher. I like the singer and her presentation.
I like to watch a few times. And I am dreaming of owning something in Canada as well. I like to be frugal, and then Nicole explains in the video with so touching voice, I really enjoy to watch, and learn the taste her sense of art, her choices of furniture, space, art, and also small pool and swing inside house.
I am stubborn, this morning I went to bed around 1:00 AM, and then I woke up around 4:00 AM, went to bathroom, and wrote a few words on wechat. It was so interesting day. Canada day.
I like to make a so beautiful day - my 10th Canada day in the city of Vancouver.
Here is the video. Now it is 10:30 AM. I am watching the video second time. I just like Nicole to be my voice teacher. I like the singer and her presentation.
I like to watch a few times. And I am dreaming of owning something in Canada as well. I like to be frugal, and then Nicole explains in the video with so touching voice, I really enjoy to watch, and learn the taste her sense of art, her choices of furniture, space, art, and also small pool and swing inside house.
I am stubborn, this morning I went to bed around 1:00 AM, and then I woke up around 4:00 AM, went to bathroom, and wrote a few words on wechat. It was so interesting day. Canada day.
I like to make a so beautiful day - my 10th Canada day in the city of Vancouver.
Inside Nicole Scherzinger's LA House with a Cozy Home Theater | Open Door | Architectural Digest
Here is the video I like to watch a few times. And I am dreaming of owning something in Canada as well. I like to be frugal, and then Nicole explains in the video with so touching voice, I really enjoy to watch, and learn the taste her sense of art, her choices of furniture, space, art, and also small pool and swing inside house.
I am stubborn, this morning I went to bed around 1:00 AM, and then I woke up around 4:00 AM, went to bathroom, and wrote a few words on wechat. It was so interesting day. Canada day, not Canada day. It is Canada thanksgiving day.
I like to make a so beautiful day - my 10th Canada day in the city of Vancouver.
I am stubborn, this morning I went to bed around 1:00 AM, and then I woke up around 4:00 AM, went to bathroom, and wrote a few words on wechat. It was so interesting day. Canada day, not Canada day. It is Canada thanksgiving day.
I like to make a so beautiful day - my 10th Canada day in the city of Vancouver.
Sunday, October 13, 2019
What to learn after 10th year on the same job?
Oct. 13, 2019
It is 10th year I work full time in the same factory. I started from June 15, 2010, now it is 2019, October. What I should learn after 10th year on the same job?
I spent most of time this year to learn personal finance. This year is 10 year bull market, I put all my IRA CD back to stock market, and also set up a Canadian TFSA account and start to learn to stay in market.
One idea I learn is not to time the market. The time in the market is more important. Also I need to spend time to watch videos, read articles. One idea is to watch Google talk given by those hedge fund manager or fund manager, and then I start to read more articles, and learn some basics.
Introduction
It is 10th year I work full time in the same factory. I started from June 15, 2010, now it is 2019, October. What I should learn after 10th year on the same job?
Personal finance
One idea I learn is not to time the market. The time in the market is more important. Also I need to spend time to watch videos, read articles. One idea is to watch Google talk given by those hedge fund manager or fund manager, and then I start to read more articles, and learn some basics.
Don Yacktman: A fund manager’s faith produces results
Here is the article. I like to read it quickly.
He waits to buy great companies when they’re down and rides them until they recover, which great companies almost always do. You don’t need to jump in and out of stocks, he tells them. “You just need to catch the wind enough times,” he says. “And you need to be very, very patient.”
He waits to buy great companies when they’re down and rides them until they recover, which great companies almost always do. You don’t need to jump in and out of stocks, he tells them. “You just need to catch the wind enough times,” he says. “And you need to be very, very patient.”
Donald Yacktman: "Viewing Stocks as Bonds" | Talks at Google
Here is the video I like to watch.
Drawing on his four decades of experience, Don Yacktman identifies the three key characteristics of value stocks. In this talk, he shares his investment philosophy along with the lessons he has learned from the markets and from life.
Drawing on his four decades of experience, Don Yacktman identifies the three key characteristics of value stocks. In this talk, he shares his investment philosophy along with the lessons he has learned from the markets and from life.
I am a learner - investment is my second hobby
Oct. 13, 2019
Introduction
Hard work beats talent when talent fails to work hard. I choose to continue to study investment through Google talk, and then I prepare one day I can grow myself in terms of understanding market, US economy, personal finance, and also keep myself busy learning, find love of making money in my investment.
One thing a time. I was fascinated by tennis sports last 10 years, so I worked on tennis for a few years, and later I noticed that I need to learn how to control weight, at least I should learn how to lose 20 lbs by research, sports and other techniques.
I like to keep learning investment this year even though I already set up Victoria and Key Largo portfolio. I know that behavior finance is so important for me to learn; I may not know what I do when the crisis comes.
Introduction
Hard work beats talent when talent fails to work hard. I choose to continue to study investment through Google talk, and then I prepare one day I can grow myself in terms of understanding market, US economy, personal finance, and also keep myself busy learning, find love of making money in my investment.
First hobby
One thing a time. I was fascinated by tennis sports last 10 years, so I worked on tennis for a few years, and later I noticed that I need to learn how to control weight, at least I should learn how to lose 20 lbs by research, sports and other techniques.
I like to keep learning investment this year even though I already set up Victoria and Key Largo portfolio. I know that behavior finance is so important for me to learn; I may not know what I do when the crisis comes.
How to reduce risk and learn more behavior finance?
Oct. 13, 2019
It is so important for me to learn more about behavior finance. I put all my 10 yrs saving in TFSA account and RRSP, and then I am already in the market over 4 months. I like to learn behavior finance, so every time there is crisis I already know what to do based on behavior finance.
I like to learn more about investment, stock market, behavior finance. I learn the importance of the research and pre-mortem analysis.
I know that it is better for me to spend time to work on algorithm and data structure practice. I already had one onsite from Microsoft (2008), three onsite from Amazon (2016, 2018, 2019), one onsite from Facebook (2019). I can write two algorithms in one hour, one easy, one medium based on my last weekly contest 158.
I should push myself to solve 100 to 200 algorithm on Leetcode.com, play more weekly contest, and also write most posts on Leetcode discuss. I like to learn more through practice. I just turned 53 years old, and also I have the same job over 9 years. I definitely have experience to work as a software programmer.
Introduction
It is so important for me to learn more about behavior finance. I put all my 10 yrs saving in TFSA account and RRSP, and then I am already in the market over 4 months. I like to learn behavior finance, so every time there is crisis I already know what to do based on behavior finance.
Behavior finance
I like to learn more about investment, stock market, behavior finance. I learn the importance of the research and pre-mortem analysis.
I know that it is better for me to spend time to work on algorithm and data structure practice. I already had one onsite from Microsoft (2008), three onsite from Amazon (2016, 2018, 2019), one onsite from Facebook (2019). I can write two algorithms in one hour, one easy, one medium based on my last weekly contest 158.
I should push myself to solve 100 to 200 algorithm on Leetcode.com, play more weekly contest, and also write most posts on Leetcode discuss. I like to learn more through practice. I just turned 53 years old, and also I have the same job over 9 years. I definitely have experience to work as a software programmer.
10 K walk around Stanley Park - Oct. 13, 2019
Oct. 13, 2019
It is a tough walk to walk more than 10 K around Stanley park. I have to work on my fitness, and also I need to push myself outside to meet people and learn more things about nature. I started around 11:00 AM, and it took me more than four hours to walk Stanley park. It is such great experience.
I like to document my walk and a few things I learn through the walk.
1. Be open to visitors from the world. Offer help, chat with people, walk with others if I can.
2. Stay safe, stay hydrated. I brought with me a bottle of water, and I can refill it in a few places.
3. I also spent time to chat with two young Chinese visiting students in Mount Royal university, they took 12 hours road trip from Calgary to Vancouver.
4. Talk to people on strikes working for hotels. I read the news, I thought about they are bus drivers in Vancouver.
It took me more than three hours to walk 12 KM. Here is my route.
Take more pictures.
I like to show some pictures. I like to push myself to learn the city of Vancouver.
Expenses:
1. Less than 10 dollars skytrain tickets;
2. Japanese restaurant lunch with friends met on the road trip. $15.00 dollars for Japanese noodle.
I think that it is also important for me to visit downtown more often. One day I may leave Vancouver and work somewhere in silicon valley, so I should visit down town and take skytrain once a week at least.
1. First time I tried my Google hat. I got a gift bag from Google GHC meeting in Seattle Oct. 4, 2019.
2. Learn one more cruise boat - I looked down and cruise name is blocked by me. I tried to wear as less as possible. Only two layers to keep warm.
3. Celebrity Eclipse - what a cruise name, I like the cruise. I like to track how many gray hairs I have.
One more cruise -
I like the maple leave, just after the short talk to people on strike near hotel near the beach.
Introduction
It is a tough walk to walk more than 10 K around Stanley park. I have to work on my fitness, and also I need to push myself outside to meet people and learn more things about nature. I started around 11:00 AM, and it took me more than four hours to walk Stanley park. It is such great experience.
My fitness and my walk
I like to document my walk and a few things I learn through the walk.
1. Be open to visitors from the world. Offer help, chat with people, walk with others if I can.
2. Stay safe, stay hydrated. I brought with me a bottle of water, and I can refill it in a few places.
3. I also spent time to chat with two young Chinese visiting students in Mount Royal university, they took 12 hours road trip from Calgary to Vancouver.
4. Talk to people on strikes working for hotels. I read the news, I thought about they are bus drivers in Vancouver.
My route
It took me more than three hours to walk 12 KM. Here is my route.
Take more pictures.
I like to show some pictures. I like to push myself to learn the city of Vancouver.
Expenses:
1. Less than 10 dollars skytrain tickets;
2. Japanese restaurant lunch with friends met on the road trip. $15.00 dollars for Japanese noodle.
I think that it is also important for me to visit downtown more often. One day I may leave Vancouver and work somewhere in silicon valley, so I should visit down town and take skytrain once a week at least.
1. First time I tried my Google hat. I got a gift bag from Google GHC meeting in Seattle Oct. 4, 2019.
2. Learn one more cruise boat - I looked down and cruise name is blocked by me. I tried to wear as less as possible. Only two layers to keep warm.
3. Celebrity Eclipse - what a cruise name, I like the cruise. I like to track how many gray hairs I have.
One more cruise -
I like the maple leave, just after the short talk to people on strike near hotel near the beach.
Thomas Russo: "Global Value Investing" | Talks at Google
Here is the video.
“I consider myself to be a farmer—not a hunter. And I think most people on Wall Street are hunters. They like to fell big beasts and I’m very comfortable planting a few rows and just tending to them carefully.” - Thomas Russo About the Talk Mr. Russo looks forward to describing how that in his pursuit of long-term tax-deferred investment returns that he has favored investments in businesses whose global brands are well-position companies for reinvestment of mature market free cash flow into developing and emerging markets. Mr. Russo’s businesses accordingly possess the “capacity to reinvest” and managements who have the “capacity to suffer” when investments properly intended for longest term increase in intrinsic value on a per share basis burden as they often do, reported earnings in the near term. This tradeoff between near-term pain and long-term gain is at the heart of his investments when properly executed, the benefit for taxable investors is the ability to build portfolio companies whose return are long term and tax deferred.
“I consider myself to be a farmer—not a hunter. And I think most people on Wall Street are hunters. They like to fell big beasts and I’m very comfortable planting a few rows and just tending to them carefully.” - Thomas Russo About the Talk Mr. Russo looks forward to describing how that in his pursuit of long-term tax-deferred investment returns that he has favored investments in businesses whose global brands are well-position companies for reinvestment of mature market free cash flow into developing and emerging markets. Mr. Russo’s businesses accordingly possess the “capacity to reinvest” and managements who have the “capacity to suffer” when investments properly intended for longest term increase in intrinsic value on a per share basis burden as they often do, reported earnings in the near term. This tradeoff between near-term pain and long-term gain is at the heart of his investments when properly executed, the benefit for taxable investors is the ability to build portfolio companies whose return are long term and tax deferred.
Saturday, October 12, 2019
Quora: How do I write an excellent discussion post for a hard level algorithm on leetcode.com?
Here is the question I asked, and then I also wrote an answer. I figured out if I like to share my experience of Leetcode.com, I better ask my own question and then write the answer. If I answer one of existing questions, I may be marked as a suspect of spam.
1223. Dice Roll Simulation
I like to learn the algorithm this long weekend. I already spent over 20 minutes to think about the problem in weekly contest 158.
weekly contest 158
Oct. 12, 2019
It is my favorite weekly contest. I played the contest and then I solved the first two algorithms. I spent near 30 minutes to work on the third algorithm, a medium algorithm, but I could not come out the solution. I thought about using recursive function, make it really simple.
I like to show my performance. I also have to push myself hard to solve the second medium algorithm in weekly contest.
Introduction
It is my favorite weekly contest. I played the contest and then I solved the first two algorithms. I spent near 30 minutes to work on the third algorithm, a medium algorithm, but I could not come out the solution. I thought about using recursive function, make it really simple.
Performance
I like to show my performance. I also have to push myself hard to solve the second medium algorithm in weekly contest.
Case study: What is value of my IRA portfolio based on 2001 purchase?
Oct. 12, 2019
It is time for me to evaluate my portfolio back in 2001. I already spent over 11 months to study personal finance, so I already have learned so many things in terms of investment, I like to write down my analysis, and see how much I may have gained through the portfolio.
Let me upload my portfolio based on my personal finance repository on github.
The most important is not to time the market, instead it is time to stay in the market. I sold those IRA mutual fund and stock, and then open IRA CD account in Amtrust bank instead.
What I like to research is to figure out the market value for those funds and stocks if I keep them from 2001 to 2019.
Introduction
It is time for me to evaluate my portfolio back in 2001. I already spent over 11 months to study personal finance, so I already have learned so many things in terms of investment, I like to write down my analysis, and see how much I may have gained through the portfolio.
Case study
Let me upload my portfolio based on my personal finance repository on github.
The most important is not to time the market, instead it is time to stay in the market. I sold those IRA mutual fund and stock, and then open IRA CD account in Amtrust bank instead.
What I like to research is to figure out the market value for those funds and stocks if I keep them from 2001 to 2019.
If You Had Invested Right After Cisco's IPO
Here is the article.
If you had sold your Cisco shares during the height of the dot-com bubble (2001), your initial IPO investment of $1,000 would have been worth $1.264 million, representing a CAGR of over 104%.
As the dot-com bubble began to burst, Cisco lost 80% of its value from March 2000 to March 2001. As of February 2018, the company still trades nearly 50% below its all-time high.Dividend Reinvestments
The company began paying a dividend in 2011 after pressure from shareholders. Reinvestment of dividends would not have had a significant impact on your CAGR since they have only been paid for a short period of time and missed the extremely high-growth years. In comparison, Coca-Cola has been paying a quarterly dividend since 1920, which has aided its annual growth rate by over 4.2%.
Updated Aug 6, 2018
Since the recession of 2008 the company’s stock has doubled, it initiated its quarterly dividend program, and it has made massive share repurchases.
Since the recession of 2008 the company’s stock has doubled, it initiated its quarterly dividend program, and it has made massive share repurchases.
If you invest $1000 Apple IPO stock back in 1980
A $1,000 investment in Apple on the day of its IPO on December 12, 1980, would be worth more than $425,000 today, according to CNBC calculations.
Founded in 1976, Apple went public four years later in December 1980, an event the Wall Street Journal described as “one of the most eagerly awaited in recent years.”
Apple’s 4.6 million shares went for $22 each and sold out “almost immediately,” EDN reports. The stock rose more than 30 percent that day and closed at $29 per share.
However, despite its early success, Apple struggled through much of the 1980s and 90s. In 1985, the company ousted its famously volatile co-founder Steve Jobs and began to falter in the market. It fell behind its competitors, including Microsoft, thanks to a string of failed products and turnover at the top.
By 1997, Apple was on the brink of bankruptcy and forced to lay off a third of its workers. As a last-ditch effort, it rehired Jobs and named him interim CEO. Jobs vetoed the majority of Apple’s production plans at the time and implemented a new focus on simplicity.
Under his leadership, the company released the iMac G3 in 1998, which brought Apple back to prominence. Jobs followed that with the release of the iPod in 2001 and the iPhone in 2007. The iPhone quickly became a top seller and revolutionized how customers use technology.
Today, Apple is a force to be reckoned with: In August, the technology giant became the first public U.S. company to reach a $1 trillion market cap after the stock briefly hit $207.05 per share. The surge allowed the software company to reach that milestone ahead of e-commerce giant.
Case study: MSFT stock purchase December 2001
Oct. 12, 2019
It is time for me to do a short case study on MSFT stock.
I bought Microsoft stock back in 2001, and I paid price around $60.00 dollars; and then I sold as a loss after a year or two.
Introduction
It is time for me to do a short case study on MSFT stock.
Case study
I bought Microsoft stock back in 2001, and I paid price around $60.00 dollars; and then I sold as a loss after a year or two.
Here is my personal finance log related to stock purchase.
If you invested $1,000 in Microsoft and Apple at IPO, this one would have made you 4 times as rich
A $1,000 investment in Apple on the day of its IPO on December 12, 1980, would be worth more than $425,000 today, according to CNBC calculations. However, a $1,000 investment in Microsoft on the day of its IPO on March 13, 1986, would be worth more than $1.7 million, or around four times more.
Those figures include price appreciation and dividends. Returns also account for stock splits and other corporate events.
Microsoft’s popularity began to wane in the early 2000s as it released a string of unpopular products and failed to keep up with modern trends but, when Satya Nadella took over as CEO in 2014, he oversaw a major turnaround.
Since Nadella took over, Microsoft’s share price has nearly tripled. In November, it dethroned Apple as the most valuable public company in the world, with a market cap of more than $850 billion. If Microsoft holds onto the spot through the end of the year, it will mark the first time since 2002 that the company closes out in the top position.
From 2014 to 2019, the stock of Microsoft tripled.
Since Nadella took over, Microsoft’s share price has nearly tripled. In November, it dethroned Apple as the most valuable public company in the world, with a market cap of more than $850 billion. If Microsoft holds onto the spot through the end of the year, it will mark the first time since 2002 that the company closes out in the top position.
Microsoft
Since Nadella took over, Microsoft’s share price has nearly tripled. In November, it dethroned Apple as the most valuable public company in the world, with a market cap of more than $850 billion. If Microsoft holds onto the spot through the end of the year, it will mark the first time since 2002 that the company closes out in the top position.
From 2014 to 2019, the stock of Microsoft tripled.
Since Nadella took over, Microsoft’s share price has nearly tripled. In November, it dethroned Apple as the most valuable public company in the world, with a market cap of more than $850 billion. If Microsoft holds onto the spot through the end of the year, it will mark the first time since 2002 that the company closes out in the top position.
Friday, October 11, 2019
How many hours Youtube videos I watched last 12 months?
Oct.11, 2019
I like to figure out how many hours I spent to watch on youtube.com since I decided to study personal finance.
Introduction
I like to figure out how many hours I spent to watch on youtube.com since I decided to study personal finance.
If you invested $1,000 in Microsoft in 2009, here’s how much you’d have now
Here is the article.
If you had invested in Microsoft 10 years ago, that decision would have paid off. According to CNBC calculations, a $1,000 investment made on April 25, 2009, would be worth nearly $8,000 as of midday April 25, 2019, for a total return of almost 700%.
Over the same period, the S&P 500 returned just over 300%.
And Microsoft’s stock is trending up: It ended Thursday with a gain of more than 3% after earlier in the day briefly surging 5% to a $1 trillion market cap. Revenue climbed 14% to $30.6 billion, beating the $29.84 billion estimate.
If you had invested in Microsoft 10 years ago, that decision would have paid off. According to CNBC calculations, a $1,000 investment made on April 25, 2009, would be worth nearly $8,000 as of midday April 25, 2019, for a total return of almost 700%.
Over the same period, the S&P 500 returned just over 300%.
And Microsoft’s stock is trending up: It ended Thursday with a gain of more than 3% after earlier in the day briefly surging 5% to a $1 trillion market cap. Revenue climbed 14% to $30.6 billion, beating the $29.84 billion estimate.
637. Average of Levels in Binary Tree
Here is my discussion post.
The algorithm can be solved using BFS algorithm, level by level can be implemented to track nodes in the queue first; same level nodes will be visited one by one using a while loop by tracking count of nodes.
Here are highlights:
- Learn the technique to apply BFS using Queue, and track level by level by tracking nodes in the queue;
- For each level, calculate sum of each node's value; data type of sum should be long not int, and then average value will be double, so it is better to declare as double type;
- I completed the solution using 13 minutes.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public IList<double> AverageOfLevels(TreeNode root)
{
var averages = new List<double>();
if (root == null)
return averages;
var queue = new Queue<TreeNode>();
queue.Enqueue(root);
// push into queue by level
while(queue.Count > 0)
{
var count = queue.Count;
double sum = 0;
for(int i = 0; i < count; i++)
{
var current = queue.Dequeue();
sum += current.val;
if (current.left != null)
queue.Enqueue(current.left);
if (current.right != null)
queue.Enqueue(current.right);
}
averages.Add(sum/count);
}
return averages;
}
}
966. Vowel Spellchecker
Here is my discussion post.
It is the second algorithm in one of mock interviews on Leetcode.com. I worked on the solution and it took me over one hour to fix it. Because I ran into timeout issue on test case 48/53, I had to review my code to preprocess a few hashSet and hashMap to expedite the lookup.
Here are highlights:
- First, put all words in wordList into a hashSet, so it can use O(1) time to look up; if it is found, then no spell check need;
- Next, preprocess a hashSet with lower case word, and also a hashmap to map the lower case word to its original words, for example, key string "kite", value strings {"KiTe","kite"}.
- Thirdly, preprocess a hashSet with vowel char replaced, for example, "kite" has two vowel char 'i' and 'e' which can be replaced using '*', so "k*t*" can be a key string to represent all vowel error words.
- Will continue to add more detail. Stay tuned.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace spellCheckerProject
{
class Program
{
static void Main(string[] args)
{
var wordList = new string[] { "KiTe", "kite", "hare", "Hare" };
var queries = new string[] { "kite", "Kite", "KiTe", "Hare", "HARE", "Hear", "hear", "keti", "keet", "keto" };
var result = Spellchecker(wordList, queries);
}
/// <summary>
/// spellchecker
/// Oct. 11, 2019
/// Timeout bug - need to continue to work on
/// </summary>
/// <param name="wordlist"></param>
/// <param name="queries"></param>
/// <returns></returns>
public static string[] Spellchecker(string[] wordlist, string[] queries)
{
var lengthWord = wordlist.Length;
var lengthQuery = queries.Length;
var hashset = new HashSet<string>(wordlist);
var lowerHashset = new HashSet<string>();
var map = new Dictionary<string, List<string>>();
foreach (var item in wordlist)
{
var key = item.ToLower();
lowerHashset.Add(key);
if (!map.ContainsKey(key))
{
map.Add(key, new List<string>());
}
map[key].Add(item);
}
var vowelSet = new HashSet<string>();
var vowels = new HashSet<char>("aeiou".ToCharArray());
var vowelMap = new Dictionary<string, string>();
foreach (var item in wordlist)
{
var replaced = vowelReplaced(item);
vowelSet.Add(replaced);
if(!vowelMap.ContainsKey(replaced))
{
vowelMap.Add(replaced, item);
}
}
var matchingWords = new string[lengthQuery];
for (int i = 0; i < lengthQuery; i++)
{
var current = queries[i];
var currentLower = current.ToLower();
if (hashset.Contains(current))
{
matchingWords[i] = current;
continue;
}
// Capitalization
var capitalization = false;
if (lowerHashset.Contains(currentLower))
{
matchingWords[i] = map[currentLower][0];
capitalization = true;
}
if (capitalization)
{
continue;
}
// Vowel errors
var vowelErrors = false;
var replacedKey = vowelReplaced(currentLower);
if(vowelSet.Contains(replacedKey))
{
matchingWords[i] = vowelMap[replacedKey];
vowelErrors = true;
}
// edge case - no matching
if (!vowelErrors)
{
matchingWords[i] = "";
}
}
return matchingWords;
}
/// <summary>
/// convert to lower case, and then replace vowel char
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private static string vowelReplaced(string item)
{
var vowels = new HashSet<char>("aeiou".ToCharArray());
var array = item.ToLower().ToCharArray();
for (int i = 0; i < array.Length; i++)
{
var vowelCheck = array[i];
if (vowels.Contains(vowelCheck))
{
array[i] = '*';
}
}
return new string(array);
}
private static bool isMatchingVowelError(string matching, string source)
{
if (matching.Length != source.Length)
return false;
var vowels = new HashSet<char>("aeiou".ToCharArray());
for (int i = 0; i < matching.Length; i++)
{
var current = matching[i];
var sourceChar = source[i];
if (vowels.Contains(current) != vowels.Contains(sourceChar))
{
return false;
}
if (!vowels.Contains(current) && current != sourceChar)
{
return false;
}
}
return true;
}
}
}
Thursday, October 10, 2019
48. Rotate Image
Here is my second practice in 2017.
I will write down my understanding, and highlight my solution in short future. Stay tuned.
public class Solution {
public void Rotate(int[,] matrix) {
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int index = 0;
while (2 * index < rows )
{
reverseRows(index, rows - 1 - index, matrix);
index++;
}
for (int row = 0; row < rows; ++row)
{
for (int col = row + 1; col < cols; ++col)
{
swap(row, col, matrix);
}
}
}
private void reverseRows(int row1, int row2, int[,] matrix)
{
int cols = matrix.GetLength(1);
for (int col = 0; col < cols; col++)
{
int tmp = matrix[row1, col];
matrix[row1, col] = matrix[row2, col];
matrix[row2, col] = tmp;
}
}
private void swap(int row, int col, int[,] matrix)
{
int tmp = matrix[row, col];
matrix[row, col] = matrix[col, row];
matrix[col, row] = tmp;
}
}
48. Rotate Image
Here is my post.
Oct. 10, 2019
I came cross this algorithm when I reviewed one of Microsoft onsite interview post. I found out that I wrote two solution back in 2017, so I like to review the solution I wrote.
Stay tuned. I will add some highlights.
public class Solution {
public void Rotate(int[,] matrix) {
if (matrix == null || matrix.GetLength(0) == 0 || matrix.GetLength(1) == 0)
{
return;
}
int rows = matrix.GetLength(0);
int cols = rows;
var rotate90 = new int[rows, cols];
int startRow = 0;
int startCol = 0;
int lastRow = rows - 1;
int lastCol = cols - 1;
while (startRow < rows && startCol < lastCol)
{
// put the number in the one dimension array
int width = lastRow - startRow + 1;
int circle = 4 * (width - 1);
var numbers = new int[circle];
int index = 0;
// top row
for (int col = startCol; col <= lastCol; col++)
{
numbers[index++] = matrix[startRow, col];
}
// right col
for (int row = startRow + 1; row <= lastRow; row++)
{
numbers[index++] = matrix[row, lastCol];
}
// bottom row
for (int col = lastCol - 1; col >= startCol; col--)
{
numbers[index++] = matrix[lastRow, col];
}
// left row
for (int row = lastRow - 1; row > startRow; row--)
{
numbers[index++] = matrix[row, startCol];
}
// -------------
// Need to put numbers back to matrix
// right col
int start = 0;
for (int row = startRow; row <= lastRow; row++)
{
matrix[row, lastCol] = numbers[start++];
}
// bottom row
for (int col = lastCol - 1; col >= startCol; col--)
{
matrix[lastRow, col] = numbers[start++];
}
// left col
for (int row = lastRow - 1; row >= startRow; row--)
{
matrix[row, startCol] = numbers[start++];
}
// top row
for (int col = startCol + 1; col < lastCol; col++)
{
matrix[startRow, col] = numbers[start++];
}
startRow++;
startCol++;
lastRow--;
lastCol--;
}
}
}
Subscribe to:
Posts (Atom)








