Monday, September 7, 2020

Leetcode discuss: 1028. Recover a Tree From Preorder Traversal

 Here is the link. 

C# Using stack and also mark visited left node

Sept. 7, 2020
1028. Recover a Tree From Preorder Traversal

Introduction
It is my practice for Microsoft phone screen from Vancouver on Sept. 11, 2020. My plan is to go over all tree algorithms and then learn from those tree algorithms.

Case study
Test case 1: A tree with 1-2--3
The tree starts from root node with value 1, and then it's left child with value 2, and then left child with value 3.

Preorder traversal is to start from root node, and the left child, and then right child.
A tree can be constructed from root node, and then if next node has depth with increment 1, then assume that it is left child. In the same time, push node into stack until a node is no longer the child node in the top of stack.

Test case 2: 1-2--3--4
The challenge part is to set node with value 4 as node with 2's right child, not left child.
The idea is to use marked visited HashSet, and then if the top of stack is not parent node of current visited node, then pop up the node.

Node 1 is pushed into stack, and then node with value 2 is pushed into stack, then node with value 3 is pushed into stack; node with value 4 has depth 2, same as node with 3 on top of stack, so pop up stack. In other words, node 3 is popped out, the top of stack is node with value 2, hashSet contains node with value 2, so node with value 2 already has left child, so node with value 4 is right child instead.

The bug I came cross in my first writing is to fall back outside while loop, the current visited node is skipped and then go to next one. I used Microsoft visual studio debugger and then catched the bug. I added nested while loop to continue to check stack if it is not empty.

Hard level algorithm
It is hard level algorithm. But I do think that it is easy to figure out since I worked on medium level algorithm related to preorder traversal. The algorithm is to construct binary tree using preorder and postorder traversal.

I wrote a solution using recursive function, 889. Construct Binary Tree from Preorder and Postorder Traversal is the discussion post.

Time complexity:
O(N) - N is total number of nodes in the tree

space complexity:
average O(logN), height of tree, worst case is O(N)
hashset is also to remove the node once it is visited second time.

/**
 * 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 TreeNode RecoverFromPreorder(string S) {
        // the idea is to push those nodes into stack, and then backtrack based on level comparison
            if (S == null || S.Length == 0)
                return null;

            // parse string 
            // var list = parseNodes(S); // List<int[]> - value, level

            var stack = new Stack<Tuple<TreeNode, int[]>>();

            int index = 0;
            var length = S.Length;

            var rootValue = 0;
            //while(index < length && S[index] >= '0' && S[index] <='9')
            while (index < length && S[index] != '-')
            {
                rootValue = rootValue * 10 + (S[index] - '0');
                index++;
            }

            var rootDepth = 0;
            var root = new TreeNode(rootValue);

            var hashSet = new HashSet<TreeNode>(); // has left child already

            stack.Push(new Tuple<TreeNode, int[]>(root, new int[] { rootValue, rootDepth }));

            // two nodes   - one is left child
            // three nodes - one is left, third one is left's left
            // three nodes - one is left child, one is right child
            while (stack.Count > 0 && index < length)
            {
                var currentDepth = 0;
                while (index < length && S[index] == '-')
                {
                    index++;
                    currentDepth++;
                }

                var currentValue = 0;
                //while(index < length && S[index] >= '0' && S[index] <='9')
                while (index < length && S[index] != '-')
                {
                    currentValue = currentValue * 10 + (S[index] - '0');
                    index++;
                }

                while (stack.Count > 0)
                {
                    var peek = stack.Peek();
                    var peekNode = peek.Item1;
                    var peekDepth = peek.Item2[1];
                    var isChild = currentDepth > peekDepth;

                    // push the current node to the stack
                    if (isChild)
                    {
                        var node = new TreeNode(currentValue);
                        if (!hashSet.Contains(peekNode))
                        {
                            peekNode.left = node; // go to left node as first choice
                            hashSet.Add(peekNode);
                        }
                        else
                        {
                            peekNode.right = node;

                            // to save space - it is also ok to remove node from hashSet
                            hashSet.Remove(peekNode);
                        }

                        stack.Push(new Tuple<TreeNode, int[]>(node, new int[] { currentValue, currentDepth }));
                        break;
                    }
                    else
                    {
                        // or node in the top of stack is a leaf node, pop up, 
                        // push current node into the stack
                        stack.Pop();
                    }
                }
            }

            return root;
    }
}


Stop Losses: How to Use Trailing Stops Part 4

 Here is the link. 



How To Set A Stop Loss Based on Price Part 1

 Here is the link. 

Stop losses

1. Premise based

2. Time based

3. Volatility based 

4. Trailing stop 



How to Use Stops and Limit Orders to Exit or Get into Trades

 Here is the link.


Sunday, September 6, 2020

Leetcode discuss: 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

 Here is the link. 

C# preorder traversal the original tree and find target

August 31, 2020
1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree

It is an easy problem to find target node using preorder traversal, and only extra task is to visit cloned tree as well in the same time.
Time complexity:
O(N), N is number of total nodes in the tree.

/**
 * 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 TreeNode GetTargetCopy(TreeNode original, TreeNode cloned, TreeNode target)
        {
            if (original == null)
                return null;

            TreeNode found = null;

            preorderTraversal(original, cloned, target, ref found);
            return found; 
        }

        private void preorderTraversal(TreeNode original, TreeNode cloned, TreeNode target, ref TreeNode found)
        {
            if (found != null || original == null)
                return;

            if (original == target)
            {
                found = cloned;
                return;
            }

            preorderTraversal(original.left,  cloned.left,  target, ref found);
            preorderTraversal(original.right, cloned.right, target, ref found);
        }
}


Leetcode discuss: 1302. Deepest Leaves Sum

 Here is the link. 

C# Apply level order traversal and calculate sum of each level nodes

August 31, 2020
1302. Deepest Leaves Sum

Introduction
It is easy to apply level order traversal and also calculate sum of all nodes in the same level.
Last level is easy to determine by checking queue's size.

/**
 * 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 {
    /// <summary>
        /// August 31, 2020
        /// using level order traversal, and then calculate the sum of all nodes in the same level
        /// If the level is last level, then sum is the answer
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public int DeepestLeavesSum(TreeNode root)
        {
            if (root == null)
            {
                return 0; 
            }

            var queue = new Queue<TreeNode>();
            queue.Enqueue(root);
            var lastLevel = 0; 

            while (queue.Count > 0)
            {
                var levelSize = queue.Count;
                var sum = 0; 
                for (int i = 0; i < levelSize; i++)
                {
                    var node = queue.Dequeue();
                    sum += node.val;

                    if (node.left != null)
                    {
                        queue.Enqueue(node.left);
                    }

                    if (node.right != null)
                    {
                        queue.Enqueue(node.right);
                    }
                }

                if (queue.Count == 0)
                {
                    lastLevel = sum; 
                }
            }

            return lastLevel; 
        }
}

Leetcode discuss: 1315. Sum of Nodes with Even-Valued Grandparent

 Here is the link. 

C# Apply level order traversal and also enqueue a node and it's parent and grandparent

August 31, 2020
1315. Sum of Nodes with Even-Valued Grandparent

The algorithm can easily be solved by using level order traversal and also enqueuing node and it's parent and grandparent node.

/**
 * 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 {
    /// <summary>
        /// August 31, 2020
        /// apply level order traversal, and also pass parent and grandparent nodes in the queue
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public int SumEvenGrandparent(TreeNode root)
        {
            if (root == null)
            {
                return 0; 
            }

            var queue = new Queue<TreeNode[]>();

            queue.Enqueue(new TreeNode[]{root, null, null});
            var sum = 0; 

            while (queue.Count > 0)
            {
                var levelSize = queue.Count;

                for (int i = 0; i < levelSize; i++)
                {
                    var node = queue.Dequeue();
                    var grandParent = node[2];
                    var isEven = grandParent != null && grandParent.val %2 == 0;

                    if (isEven)
                    {
                        sum += node[0].val;
                    }

                    var current = node[0];
                    if (current.left != null)
                    {
                        queue.Enqueue(new TreeNode[]{current.left, current, node[1]});
                    }

                    if (current.right != null)
                    {
                        queue.Enqueue(new TreeNode[] { current.right, current, node[1] });
                    }
                }
            }

            return sum; 
        }
}


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

 Here is the link. 

C# preorder traversal of binary search tree and then merge two sorted list

August 31, 2020
1305. All Elements in Two Binary Search Trees

I tried to think about using O(1) space to solve the problem, but I could not figure out the solution. The naive solution is to preorder traverse two binary searach tree first, and then merge two sorted lists.

/**
 * 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 list1 = new List<int>();
            var list2 = new List<int>(); 

            inorderTraversal(root1, list1);
            inorderTraversal(root2, list2); 
                       
            return mergeTwoSortedLists(list1, list2);            
        }

        private static void inorderTraversal(TreeNode root, List<int> list)
        {
            if(root == null)
            {
                return; 
            }

            inorderTraversal(root.left, list);

            list.Add(root.val);

            inorderTraversal(root.right, list);
        }

        private static List<int> mergeTwoSortedLists(List<int> list1, List<int> list2)
        {
            var merged = new List<int>(); 

            if (list1 == null || list1.Count == 0)
            {
                merged = new List<int>(list2);
                return merged; 
            }

            if (list2 == null || list2.Count == 0)
            {
                merged = new List<int>(list1);
                return merged;
            }

            var length1 = list1.Count;
            var length2 = list2.Count;

            int index1 = 0;
            int index2 = 0;

            while (index1 < length1 || index2 < length2)
            {
                if (index1 == length1)
                {
                    merged.Add(list2[index2]);
                    index2++;
                }
                else if (index2 == length2)
                {
                    merged.Add(list1[index1]);
                    index1++;
                }
                else
                {
                    var current1 = list1[index1];
                    var current2 = list2[index2];
                    if (current1 <= current2)
                    {
                        merged.Add(current1);
                        index1++;
                    }
                    else
                    {
                        merged.Add(current2);
                        index2++;
                    }
                }
            }

            return merged; 
        }
}


Leetcode discuss: 1261. Find Elements in a Contaminated Binary Tree

 Here is the link. 

C# Using HashSet<int> to get O(1) time complexity to lookup

August 31, 2020
1261. Find Elements in a Contaminated Binary Tree

It is easy for me to think about using HashSet to store all node's values in the tree. So it is easy to write API Find(int target) using O(1) time complexity.

/**
 * 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 FindElements {

    private HashSet<int> nodes = new HashSet<int>(); 

            public FindElements(TreeNode root)
            {
                nodes.Clear();
                if (root.val == 0)
                {
                    return; 
                }

                preorderTraversal(root, 0);
            }

            private void preorderTraversal(TreeNode root, int value)
            {
                if (root == null)
                {
                    return;
                }

                nodes.Add(value);
                preorderTraversal(root.left,  value * 2 + 1);
                preorderTraversal(root.right, value * 2 + 2);
            }

            public bool Find(int target)
            {
                return nodes.Contains(target);
            }
}

/**
 * Your FindElements object will be instantiated and called as such:
 * FindElements obj = new FindElements(root);
 * bool param_1 = obj.Find(target);
 */


Why Most Traders Lose Money

 Here is the link. 

One of the Most important Video Lessons on Why Most Traders Lose Money. Despite being good at charts and pattern recognition, They still end up not making any money as a Trader, Common issues and Pitfalls traders go through with their Mindset and Psychology and How to Overcome the Inner Demons.


1) No plan 2) No stop loss 3) No backtested strategy 4) No education 5) No patience 6) No time 7) No discipline 8) No willingness to learn 9) No mindset work 10) No mentor

How To Get Started as a Day Trader & Learning Market Cycles

 Here is the link. 

Curious what you need to be a trader? This video will walk you through it. As well as how to read market cycles so you can take advantage of all market environments!

37:00 - 47:00 - 50:00 Very good explanation using 4 stages

stage 1: Accumulation

Health phase

Awareness phase

mania phase

blow off phase

volume -

The Science Behind Why Day Traders Fail... (Dunning-Kruger Effect)

 Here is the link. 

Let's talk some science. Not just any old science, but literally award winning science in the field of psychology and human behavior. I have been guiding and helping traders since 2013 and I've seen some very common traits pop up time and time again. Until now, I've never really had an exact explanation of why beginner traders who are just getting started behave the way they do, but... now I do! I want to share with you what is known as the Dunning-Kruger Effect. When you understand even just the broad idea of the effect, you can quickly see how it explains why so many day traders fail. The stock market and being a day trader is already hard enough; however, when you introduce in this award winning psychology, you can see why it becomes that much more difficult leading day trader to ultimately fail. I realize that these kinds of videos can come across as "being a hater" or "being negative", but please watch this will full self awareness and an open mind. Per the research, if you are honest with yourself, you will probably begin to understand why and how this psychology is affecting your trading. Let's learn not with opinions, but some award winning science.

For example, AAL stock went down 10%, went up 13%

100 shares of AAL, something is wrong. You should do a stop loss order. 

What if the person places 500 shares of order...


Position size: Determining Proper Position Size When Day Trading Stock

 Here is the article. 


4 Ways Your Mind Is Tricking You Into Being a Losing Trader

 Here is the article. 

Availability Bias

For a strategy, that means trading it for a couple of months or taking at least 100 trades. At least with 100 trades, you have some idea of how it actually performs.

Loss Aversion

All these reasons stem from not taking a loss when you should. Don't fear losses—even with lots of them, you can still be profitable. Instead, plan your exits before trading and stick to your plan.

Lottery Syndrome

Trading with the hope of hitting it big on a few trades is a fool's errand. Practice trading common market tendencies. It's in those moves that money resides, not in the elusive unicorn trade.

Knowing Vs. Doing

Instead of following these core concepts, they go on another information binge. But more information is useless if you don't apply it. Eventually, you need to stop searching and start applying what you know.

Major Behavioural Traits of Successful Traders - Respect for Risk and Uncertainty

Here is the article about the topic. 


Trait 7) Respect for Risk and Uncertainty.

Successful traders have a huge respect for risk, and an appreciation for the dangers of uncertainty. They also acknowledge and work with the subtle difference between the two. Risk is only a small part of uncertainty: if one of my positions is stopped out, then I lose $x being my ‘risk’. Every time I trade, something is ‘at risk’. As a concept, it’s much more self-evident than ‘uncertainty’. Uncertainty itself is much wider: it is impossible to put a value on exactly how the market will behave tomorrow. Some people try and price uncertainty, which they mistake for risk, however, it is hard to truly put a price on uncertainty. This point is admittedly contentious and some may debate the simplistic definitions, however I do believe that attempts to price uncertainty typically end in disaster. People thought they had valued uncertainty correctly at LTCM, and the lessons of this were quickly forgotten as people also thought they had correctly priced uncertainty ahead of the Global Financial Crisis. Top traders embrace risk, and respect uncertainty. They know crucially that they do not know what comes next, and are at best making educated guesses. Successful traders are not gamblers. The only casino game successful traders usually play is poker, and they usually do not see poker as gambling since they have the ability to shift the odds in their favour. In all other casino games, the odds are too heavily stacked against them. There has to be positive expectation of a favourable outcome, not merely an assessment of market direction. Helpful behaviours to support development of this trait:

  • Develop a rule base for risk, and assessing it vs reward.
  • Plan trades and include risk in trade evaluation.
  • Ensure you are consistent in applying the tactics needed to enforce the strategy.
  • Evaluate and monitor your performance in risk assessment.

Major Behavioural Traits of Successful Traders - Planning, Preparation, Patience and Discipline

 Here is the article about the topic. 

Trait 6) Planning, Preparation, Patience and Discipline.

It is hard to find a book on trading that does not stress these virtues. Yet actually following through and exercising these virtues within one’s trading is one of the hardest things to achieve on a regular basis. All the hard work and preparation that goes into one’s work can be lost in a few moments of ill-discipline. Successful traders place significant emphasis on these aspects of trading, they think through what they do thoroughly. Their planning and preparation provide a solid foundation that allows them to exercise the necessary patience and discipline; it also helps facilitate a reduction in uncertainty and thus helps reduce anxiety and stress levels. Let us not however imagine that successful traders are anything like perfect in this area, they aren’t, however many of them will display higher propensities to display these skills than the majority of traders. It is nonetheless this propensity to perform these skills and attributes that places a trader in the right position to do well in the long-term. As the great South African golfer Gary Player once famously said, ‘Luck is what happens when preparation meets opportunity’. Helpful behaviours to support development of this trait:

  • Invest time to developing and implementing appropriate behaviours.
  • Review your progress towards achieving your development goals.
  • Develop a structure and strategic perspective around your trading. Then, use the right tactics.

Common traits of successful traders

  1. Loss cutting
  2. Consistency
  3. Can differentiate Hype and Reality
  4. Patience
  5. Inquisitiveness
  6. Ability to learn new things quickly
  7. Practice discipline
  8. Simple and clear planning
  9. Maintains records
  10. Attention to detail
  11. Always learn from the markets
  12. Find balance 

Three practice trailing stop: Trailing Stop Definition and Uses

Sept. 6, 2020

Introduction

I work on practice on stock investment after March 27, 2020. I have to practice how to set trailing stop, so that I can avoid big loss of one trade over $500 US dollars. I did purchase 200 shares of INTC stock on Sept. 3, and then in less than three day there is $500 dollars loss. I need to be a quick learner, one of ideas is to practice setting trailing stop. If I do not practice first, then I will not think about using it when market corrections come. 

Learn 20 minutes first

Here is the article. 

Plan to work on trailing stop practice on Sept. 8, 2020. 

Understanding the Trailing Stop


Trailing stops only move in one direction because they are designed to lock in profit or limit losses. If a 10% trailing stop loss is added to a long position, a sell trade will be issued if the price drops 10% from its peak price after purchase. The trailing stop only moves up once a new peak has been established. Once the trailing stop has moved up, it cannot move back down.

Trailing stops can also be used for short positions by establishing a trigger price above the current market price. 

Actionable items

I purchased 200 shares of INTC stock at price of $52.50, and also I like to set up 1% trailing stop, so that shared will be sold if the price drops 0.52 dollars, $49.75/ share. If the stock goes up 3%, then the price goes up $1.56, $54.06, 1% will be 0.54 dollars, so the stock goes down 0.54 dollars, the sell will be triggered. 


Risk Management Techniques for Trading - Optimal stop loss level- No 2 technique

 Here is the article. 

There are many different approaches that traders can utilize when deciding where to place a stop.

Traders can set stops in accordance with:

  • Moving averages – set stops above (below) the specified MA for long (short) positions. The chart below shows how traders can use the moving average as a dynamic stop loss.
  • Support and resistance – set stops below (above) support (resistance) for long (short) positions. The chart below shows the stop being placed below support in a ranging market, allowing the trade enough room to breathe while protecting against a large downward move.
  • Using the Average True Range (ATR) - ATR measures the average pip/point movement in any security over a specified period and provides traders with a minimum distance away to set their stops. The chart below adopts a cautious approach to the ATR by setting the stop distance in accordance with the maximum ATR reading from recent price action.
*Advanced Tip: Instead of using a normal stop loss, traders can use a trailing stop to mitigate risk when the market is moving in your favor. The trailing stop, as the name suggests, moves the stop loss up on winning positions while maintaining the stop distance, at all times.

Risk Management Techniques for Trading - Determine the risk/ exposure upfront - No 1 technique

 Here is the article. 

Many traders see trading as an opportunity to make money but the potential for loss is often overlooked. By implementing a risk management strategy, a trader will be able to limit the negative effects of a losing trade when the market moves in the opposite direction.

A trader who incorporates risk management into the trading strategy will be able to benefit from upside movement while minimizing downside risk. This is achieved through the use of risk management tools like stops and limits and by trading a diversified portfolio.

Five risk management tools to learn from:

  1. Determine the risk/exposure upfront
  2. Optimal stop loss level
  3. Diversify your portfolio: the lower the correlation, the better the diversification
  4. Keep your risk consistent and manage your emotions
  5. Maintaining a positive risk to reward ratio

1) Determine the risk/exposure upfront:

Risk is inherent in every trade which is why it is essential to determine your risk before entering the trade. A general rule would be to risk 1% of the account equity on a single position and no more than 5% across all open positions, at any time. For example, the 1% rule applied to $10,000 account would mean no more than $100 should be risked on a single position. Traders will then need to calculate their trade size based on how far away the stop is placed in order to risk $100 or less.

The benefit of this approach is that it helps to preserve the account equity after a run of unsuccessful trades. An additional benefit of this approach is that traders are more likely to have free margin available to take advantage of new opportunities in the market. This avoids having to forgo such opportunities due to margin being tied up in existing trades.


Actionable items

I should practice how to put trailing stop and then practice a few times. It is important for me to learn the concept of trailing stop and make it work first using Ameritrade.com.



FOMO: How to Deal with FOMO to Become a Better Trader

 Here is the article. 

Dealing with the fear of missing out – or FOMO – is a highly valuable skill for traders. Not only can FOMO have a negative emotional impact, it can cloud judgment and overshadow logic, which is problematic when making trading decisions.

So what is FOMO in trading? It’s the fear traders get when they think they might be missing out on big opportunities, or that other traders are more successful. Traders who understand FOMO, where it comes from and how they react to it are in a strong position to tackle it at its root cause: the innermost workings of their own mind.