xamples
epeat
ode
pproach
ptimize
est
Goal: Find the longest substring that contains only 2 unique characters.
Ex. Given a string 'abbaaZZaa', return 'aaZZaa'.
Understanding Goals: Understand how to keep track of pointers better. Familiarity with slice/splice/indexOf. Logic isn't too complex, but keeping track is.
Aim to have the candidate clearly state the if/else logic and then write code.
Talk about approach on the whiteboard. Use repl.it to write the code.
Examples:
"abbaaZZaa" //should return "aaZZaa"
"aabbccc" //should return "bbccc"
1. I need to use at least 1 for loop.
2. I will use 2 pointers to track the possible substrings beginnings.
3. As I move through the loop, I need to look at each character and make sure it is within my 2 allowable characters => charArr.indexOf(currentLetter) each time
4. What happens if it is a "new" character? (Z)
5. I need to check my current start and end points are bigger than some maxString.length and if so get the new maxString by slicing(start,end).
Examples:
"abbaaZZaa" //should return "aaZZaa"
"aabbccc" //should return "bbccc"
5. When I get to Z, I have to know somehow where "a", begins. Then I have to remove "b" from my 2-character storage and replace it with Z.
6. How will I know when to set my pointer to "a"? What is unique about a's position? What "event" should I be looking for as I move from left to right?
Example: "abbaaZZaa" //should return "aaZZaa"
7. I will keep track of whenever a character changes. This will take 1 variable. This way I can jump back to the last change.
8. Then I can make a new character array that contains the character at the change, and the one I am on.
"abbAaZzaa"
charArr = [ string[changePoint],string[i] ]
9. Ok now let's try and code it.
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"));
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?