Memory and Recursion
- Understand Stack and Heap in Java: https://www.youtube.com/watch?v=450maTzSIvA
 
Heap: Used for dynamic allocation of memory. Once done, variables are available in Garbage Collection.Stack: Functions waiting to execute are stored here, once executed, they are popped out of stack. (FIFO) Each function in the stack will create a frame to store local variablesStatic Area: Store machine code, global static variables1
2
3
4
5
6
7
8------------
| Heap |
|----------|
| Stack |
|----------|
|Static Var|
| Code |
|__________|
[Recursion]
- Introduction: https://www.youtube.com/watch?v=neuDuf_i8Sg
 - A method that calls itself
 - With each method call the problem becomes simpler
 - Must have a condition that leads to the method no longer making another method call on itself
 
Tail & Non-Tail Recursion
Understand Tail Recursion: http://www.ruanyifeng.com/blog/2015/04/tail-call.html
[Recursion]
The general recursion solution for fibonacci problem will have exponential memory usage. 2^(n-1)
1  | int factorial(int n) {  | 
[Tail Recursion]
Call function itself at the last step of the function.
- No pending computation
 - Reuse existing stack frames
 - Use constant memory space, avoid stack overflow
 
To transform a non-tail recursion, we can add all the local variables as arguments to the function.
1  | int factorial(int n) {  |