R
E
A
C
T
O

xamples
epeat
ode
pproach
ptimize
est
{fibonacci sequence}

The Question
Write an algorithm to calculate the fibonacci sequence
This is to say, given fib(3), return 2.
Assume that the sequence starts as 1,1. Positive numbers only.
Most importantly, talk about the time and space complexity.

Naive Approach/recursion
function fib(n) {
if (n===1 || n===2) return 1;
return (fib(n-1) + fib(n-2));
}
Nice and Simple, but it duplicates a lot of work.
try it out. fib(60) will crash repl.
Exponential Time Complexity
We can draw out the steps that it's taking


A Better Way
Let's store the results of fib(n) at each step so that we don't have to calculate it again
function fib(n){
var storage = [];
storage[0] = 1;
storage[1]=1;
for (var i=2; i<n;i++){
storage[i] = storage[i-1] + storage[i-2];
}
return storage[n-1];
}
Time complexity of O(n).
Space complexity of O(n).
Do we need to store all the numbers?

Text
Even Betttttter
function fib(n){
var a=1,b=1,c;
for (var i=2; i<n;i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
Space Complexity of O(1)
Time Complexity of O(n)

Code
function uniqueSub(str){
var leftPoint=0, changePoint=0;
var charArr = [];
var maxStr = '';
for (var i=0; i < str.length; i++){
if (charArr.indexOf(str[i]) < 0){
if (charArr.length < 2){
charArr.push(str[i]); //If it's the first 2 unique chars just push
} else {
charArr = [str[changePoint],str[i]]; //Gets the two new characters
leftPoint = changePoint; //moves the start point
}
changePoint = i; //set changePoint to this new position
} else if (str[i]!==str[i-1]){
changePoint = i;
}
if (i-leftPoint > maxStr.length){ //capture the max string
maxStr = str.slice(leftPoint,i+1);
}
}
return maxStr;
}
console.log(uniqueSub("abcbbbbcccbdddadacb"));

Focus on logical concepts
REACTO is not just about solving the problem
REACTO is about learning how to solve problems even when you don't know the answer.
The point is to try and get them to logically approach the problem.
You can tell people to use 2 pointers and walk them.
1. Have them state what they think/know
2. Based on those facts how would they do it?
Dynamic Programming
By Justin Sung
Dynamic Programming
- 798