Showing posts sorted by relevance for query recursive function. Sort by date Show all posts
Showing posts sorted by relevance for query recursive function. Sort by date Show all posts

Wednesday, May 27, 2020

Leetcode discussion: 236. Lowest Common Ancestor of a Binary Tree

Here is the discussion post.

C# Recursive function design collections from 2019 to 2020

May 27, 2020
It is most challenging task to build good learning material for software engineers. How to design recursive function to solve lowest common ancestor? I like to put together a collection of solutions with the following list of recursive function return:
  1. Return bool
  2. Return void
  3. Return TreeNode
  4. Return Stack
  5. Return Tuple<TreeNode, int>
  6. Good ones vs bad ones - mix returns - break single-responsibility principle SRP
  7. More will be added later
Recursive function is fun to play
Return Tuple<TreeNode, int> or ArrayList? Always strong typing
C# Postorder traversal and count nodes found practice in 2020 Learn from ex-facebook engineer, super performance, April 30, 2020
My advice
Please kindly consider carefully to choose good recursive function to solve the problem in mock interview or onsite interview. Most of important is to focus on quality, not quantity to solve Leetcode algorithms.
Good one to showcase talent
Return Tuple<TreeNode, int> or ArrayList? Always strong typing
C# Postorder traversal and count nodes found practice in 2020 Learn from ex-facebook engineer, super performance, April 30, 2020
Not so good one, memorize a solution - Need hardwork in practice
recursive function - mix returns, final one is lowest common ancestor (May 29, 2019)
recursive function designsrp principlec# strong type tuple

Sunday, November 20, 2016

HackerRank stone division - recursive design study (series 4 of 5)

Nov. 23, 2016

Introduction

It is time to get some training on recursive function. Learn a few terms related to recursive function first, Julia can describe what problems she had in the contest. She had problem to come out a simple recursive function, after so many years hard working as a scholar and full time programming experience.

She missed the important part to work on, recursive step, build a recurrence formula.  
C# solution - copy the code from editorial notes: score 50 - maximum score, pass all test cases

In the above C# solution, line 80:
ans = Math.Max(ans, 1 + ( (pile/runner) * rec(runner) ) );

Study Recursive Function
Julia googles searched the recursive function, and then she found 3 things to work on. And then, she noticed that her study lacks depth of industry experience. She found an engineer on stackoverflow.com, and then she spent a few hours to read his blog. Great teaching about recursive.
 

Google Search: recursive function common mistakes

Choose some content to read:
  1. university lecture notes - umd.edu
  2. IBM article
  3. lecture notes - MIT
  4. recursive function blogs
Here are the details. 

1. university lecture notes - umd.edu:


Write down keywords:

c - core dump 
c - compact code - recursive solution 
h - How to think recursively?
s - stack space - recursive vs iterative 
     O(n)  vs  O(1)
    stack size - several megabytes - 1000 recursive calls 
t - tail-recursive function 

Google those keywords, and get more readings.


Notes:
Inductive definition 
inductively-defined 

Bug source: state changes
Ideas to avoid bugs:
    No variable does double-duty
    Be certain that all variables hit the state they are supposed to be in when the loop restarts. 

One rule: 
Assign a value to a variable only once and NEVER MODIFY IT!

1. Reusing a variable 
2. Conditional modification of a variable 
3. Loop variables

Base case proof. 
Inductive step proof. 

Two common mistakes:
1.     The base case is missing entirely. or the problem needs more than one base case but not all the base cases are covered. 
2.     The recursive step doesn't reduce to a smaller subproblem, so the recursion doesn't converge. 

base cases
recursive steps

decompose a recursive problem into recursive steps and base cases
when and how to use helper methods in recursion
understand the advantages and disadvantages of recursion vs. iteration 

Structure of recursive implementations
- base case
- recursive step

A direct recursive implementation 

Don't expose the helper method to your clients

Temporary state 
Evolution of the computation

Recurrence relation 
Helper methods
Choose the right recursive subproblem


4. Eric Lippert's blog about recursive function



More reading:
stackoverflow->
recursive question/ answer by Eric Lippert
->       Eric Lippert

Recursion series:
Part 1: 
Teach how to think about recursion 

Julia's notes
recursive way to think about a list emphasize the similarity of a fragment of the list to the whole list. 
recursively define a list as either
1. the empty list with zero items on it, or
2. an item followed by a list

appear to be a circular definition, but it is really not. 'Spiral' definition

All recursive functions follow the same basic pattern: 
Am I in the base case? If so, return the easy solution. 
Otherwise, figure out some way to make the problem closer to the base case and solve that problem. 

bottom out - base case 

A binary tree is either:
an empty tree, or 
a value associated with two binary search trees, called the left and right child trees. 

inductive hypothesis - 

1 million nodes - balanced tree - 20 recursive depth - 210 = 1024, so 1 million is around 220

"anonymous locals" - 

callee's frame   -  caller's frame  - current activation frame 

the temporary variables are spelled out 
each recursion happens on its own line

Follow up after 3 months


Feb 23, 2017

Because of this study, Julia looked into stackoverflow.com, and then she found the code review on stackexchange.com. She did great job to help herself, from a failure to solve a recursive function to study recursive function, know one person/ a blog/ code review site, she is no longer a lone coder. She asked a lot of questions and tried to answer a few questions. She tasted the success of solving problem with other's help. 

Monday, May 6, 2019

lowest common ancestor

I like to write down my practice today.

235. Lowest Common Ancestor of a Binary Tree binary search in BST
236. Lowest Common Ancestor of a Binary Tree time out using string, need help
236. Lowest Common Ancestor of a Binary Tree time out using list, need help
236. Lowest Common Ancestor of a Binary Tree optimal solution bottom up with reasoning


Follow up 


May 10, 2019


I learned one more solution, and here is the post. 

I solved my first two practice with time out problem applying the idea to find root to p or q path. Here is the solution. 

I like to make a list of things I have practiced on this algorithm:


Recursive
1. Using recursive, learn how to define recursive function, simple and clear.

BFS
I also study the code and write a C# solution using BFS to store all nodes with their parent node. 

Backtracking 
I learn to solve timeout issue in my naive solution in the first practice 2019. 

Also backtrack space complexity is much less compared to my naive approach. 

Post order traversal - bottom up 
How to define a simple and easy recursive function? I learn one solution and like it. 

The solution folder is here. 


Topics 
  1. BFS
  2. child-parent map
  3. Fix naive solution timeout with complicated function
  4. how to build a path from p or q to root
  5. how to build a path from root to p
  6. Naive solution with Timeout and Complicated function
  7. Post order traversal
  8. recursive function - Do not understand
  9. Recursive solution Easy to understand
  10. Recursive solution with backtracking
  11. Timeout challenge

Here is the folder to look up problems and solution based on topics I worked on. 


Follow up 


May 29, 2019
I continue to learn the algorithm as an interviewer on interviewing.io, I give out the algorithm to interview others more than three times, one time the interviewee is Amazon SDE II in Seattle, he showed me how to design a recursive function to return if one node is found in recursive function, in early May; And later, on May 28, 2019, one engineer showed me how to solve it using recursive function assuming that given node p and q in binary tree, and he is an engineer in Motorola. 


Topics

Naive solution with Timeout and Complicated function
Timeout challenge (May 7, 2019)
Timeout challenge - using a string to store path (May 7, 2019)
Fix naive solution timeout with complicated function (May 13, 2019)
learn elegent solution using back tracking and space efficiency, avoid timeout (May 23, 2019)


June 25, 2019
Three practice for three ideas; I like to be a master of the lowest common ancestor!
find one path first and then look up path for second given node q
C# find path from given node p to root first and then find q and lowest common ancestor
find one path first top down and then look up path for second given node q
C# Find top down path for a given node p and then find q's path and look up lowest common ancestor
backtrack to find path from root node to given node p
C# backtrack to find root node to given node p

Tuesday, September 22, 2015

Leetcode 109: convert sorted list to a binary search tree

Sept. 22, 2015

109 Convert sorted list to binary search tree (No. 109)

8/25/2015
Read the following blogs:

C#, bottom up, time O(n), space O(log n) solution - best solution:

C#, top down, time O(n^2), space O(long n) solution - naive solution:

worked on code 2 times, first time, the calculation is kind of messy, then, worked on Leetcode question 108, get the idea to make it more simple; tips like len/2 only shows once, afterwards, use m instead. Just need to improve coding, think to make it more abstract, simple.


9/21/2015
Review the best solution, and then, totally forgot the bottom up solution idea. So, update the code with more comment.

Need to review more about bottom up/ top down solution in tree problems. Get more experience on bottom-up solution, read some articles about it. 

9/22/2015

Go over one example to build some muscle memory about this bottom up, O(1) solution to find the root node in subtree function.

Sorted List:
1->2->3->4->5->6->7,

How to convert the above sorted list to a binary search tree?
Thought process:
1.      First, get length of the list, which is 7 in the above list;
2.      Secondly, define a recursive function called
constructBST(ref  TreeNode head, int start, int end)
the above function definition, 3 arguments:
1.      First one is the reference of head node of sorted list,
2.      Start index of the list,
3.    End index of the list

In the function, first define the base case:
head is null, or start<end, return null
start==end, return head

then, call the recursive function for left subtree:
 head node is the same, start is the same, but end is len/2-1;
great tip comes in, the head node should move in the function, so that
root node can be accessed in the list using O(1), instead of starting from very beginning.
One more statement:
head = head.next;
TreeNode root = head;   // return this node as tree root node
Root.left = left subtree root node
Root.right = right subtree recursive function
       constructBST(ref  head.next, mid+1, end)

The tips to remember in the design, the recursive function should return the root node of the tree; secondly, input argument of linked list should use reference, and also head node moves in the recursive function, so it is O(1) to find the root node. 

Just cannot believe that only call .next function once in the recursive function! How to argue that the move is only once? Therefore, the total calls of .next should be length of list. Total recursive function calls is n, length of list. 

Debate why the recursive function has to return root node, and set up root node, connect its left/ right subtree root node. 

Debate why the linked list head node is moving. 

设计这个递归函数, 如何避免从链的头开始访问, 到中间点? 最关键是让链的头移动, 当需要设计树的根节点, 只要移动一步, 就是根节点. 画一个图, 帮助自己理解记忆; 看一篇文章, 开拓思路. 






The main point to understand the best solution using O(ln N) space, the left subtree has to be built first, and then, head node can be retrieved as .next method call, root node can be set up, and then, left subtree can be built. So, left subtree, then right subtree, then the tree with root node. Bottom up. 

Whereas sorted array to BST, the root node can be find right away, and then, tree can be set up top down. Julia is still confusing this top down / bottom up difference. :-) read more blogs. 

Blogs:
1. use global variable to remember the head node of linked list, great idea:

2. another implementation using two pointers. Try it using C# later. 

3. Java implementation, teach me how to use reference in Java or wrapper class. Good point!

4. Time and space complexity analysis - think about it - very clear analysis 

5. Three implementation discussions 

6. Great explanation - bottom up / top down, and in order traversal/ post order traversal

Implement the above 6 blogs using C#, and then, share the blog. After 1 month, check again and see if I can come out the bottom up solution in 5 minutes. If yes, stop; otherwise review again. 

Dec. 24, 2015
Review the solution again. 
How to recall the solution step by step?

1. Get list length <- travel the list once 

2. Design the recursive function with a list, start and end two position; use the position of start/end to boundary case checking; also the function returns the root node of the tree. 

3. Build left subtree

4. Find the middle of list as root <- how to get there? 
Cannot traverse the list again to half length if you want optimized solution, since it is in recursive function,  O(nlogn)

Every recursive call the list pointer will traverse once

5. Connect root node to left child

6. Move list pointer to next one 

7. Build right subtree
connect root node to right child as well. 

Recap the importance of function design: 
1. list with a pointer moving, starting from head
2. start, end position of linked list 
3. in the function build a tree
4. return root node of the tree