Leetcode Same Tree Iterative Solution - javascript

Question at hand: https://leetcode.com/problems/same-tree/
Can someone point out why my JavaScript solution can pass the test cases but fails during the actual submission?
var isSameTree = function(p, q) {
let queue = [];
queue.push(p);
queue.push(q);
while (!queue.length) {
let p = queue.shift();
let q = queue.shift();
if (p == null && q == null) {
continue;
} else if (p == null || q == null || p.val != q.val) {
return false;
} else {
queue.push(p.left);
queue.push(q.left);
queue.push(p.right);
queue.push(q.right);
}
}
return true;
};

#trincot mentioned it in the comments.
Just update the comparison inside the while loop to get into that loop.
var isSameTree = function(p, q) {
let queue = [];
queue.push(p);
queue.push(q);
while (queue.length != 0) {
let p = queue.shift();
let q = queue.shift();
if (p == null && q == null) {
continue;
} else if (p == null || q == null || p.val != q.val) {
return false;
} else {
queue.push(p.left);
queue.push(q.left);
queue.push(p.right);
queue.push(q.right);
}
}
console.log(queue);
return true;
};
This will pass all the test cases.

Related

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

Optimization for Binary Search Tree 'remove' function

I just finished my first binary search tree remove function and it is in major need of optimization. I have spent a lot of time on this and this was the best I could manage. Is there a easier way to do this? Does anyone have any suggestions for optimization? To me, it just seems like it will necessarily be massive code.
For starters...
My Binary Search Tree...
function BST() {
this.root = null;
}
My 'remove' function...
BST.prototype.remove = function(data) {
if(this.root.data === data){
var curr = this.root.left;
while(true){
if(curr.right.left === null && curr.right.right === null){
this.root.data = curr.right.data;
curr.right = null;
break;
}
curr = curr.right;
}
}
var curr = this.root;
var found_data = this.find(data);
if(found_data.left !== null && found_data.right !== null){
var runner = found_data.right;
var runner_prev = found_data;
while(true){
if(runner.left === null && runner.right === null){
found_data.data = runner.data;
if(runner_prev.left === runner){
runner_prev.left = null;
}else{
runner_prev.right = null;
}
break;
}
runner_prev = runner;
runner = runner.left;
}
}else if(found_data.left === null || found_data.right === null){
var prev = this.prev(found_data.data);
if(prev.right === found_data){
if(found_data.left){
prev.right = found_data.left;
}else{
prev.right = found_data.right;
}
}else{
if(found_data.left){
prev.left = found_data.left;
}else{
prev.left = found_data.right;
}
}
}else{
var prev = this.prev(found_data.data);
if(prev.left === found_data){
prev.left = null;
}else{
prev.right = null;
}
}
};
You will notice that I use supporting functions within my remove() function, such as prev() and find() They are apart of my overarching BST() function and can be used anywhere within is by prefacing it using this..
Supporting functions I use within remove() (prev() and find())
BST.prototype.find = function(data) {
if(this.root === null){
return 'wrong';
}
var curr = this.root;
while(true){
if(data > curr.data){
curr = curr.right;
}else if(data < curr.data){
curr = curr.left;
}else{
if(curr.data enter code here=== data){
return curr;
}else{
return 'not here player'
}
}
}
}
BST.prototype.prev = function(data){
if(this.root === null){
return false;
}
var prev = this.root;
var curr = this.root;
while(true){
if(curr.left === null && curr.right === null){
return prev;
}
if(data < curr.data){
prev = curr;
curr = curr.left;
}else if(data > curr.data){
prev = curr;
curr = curr.right;
}else{
return prev;
}
}
}
This algorithm absolutely works, but as you can imagine, this is not the type of monster you would want to be answering a whiteboard interview question with.
It would be more efficient if you either:
Combine prev() and find() by returning both the previous node and the found node from find()
Give each node a parent pointer, and just follow it to find prev

Faster Evaluating IF Condition of JavaScript

Back to the basics of JavaScript. This is a question I am coming with is based on computation time speed of JavaScript If condition.
I have a logic which includes usage of if condition. The question is computing equal to value is faster OR not equal to value is faster?
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
{
vm.isReminderSectionVisible = true;
} else
{
vm.isReminderSectionVisible = false;
}
The above one computes not equal to
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
{
vm.isReminderSectionVisible = false;
} else
{
vm.isReminderSectionVisible = true;
}
The above one computes equal to value
which of both these is faster in execution?
Why don't you try it out? Write to your console this:
function notequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag !== '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn !== null)
vm.isReminderSectionVisible = true;
}
else {
vm.isReminderSectionVisible = false;
}
}
function yesequal() {
if(vm.currentFeedbackObject.sendReminderLists[0].sendReminderFlag === '' && vm.currentFeedbackObject.sendReminderLists[0].sendReminderedOn === null)
vm.isReminderSectionVisible = false;
}
else {
vm.isReminderSectionVisible = true;
}
}
var iterations = 1000000;
console.time('Notequal #1');
for(var i = 0; i < iterations; i++ ){
notequal();
};
console.timeEnd('Notequal #1')
console.time('Yesequal #2');
for(var i = 0; i < iterations; i++ ){
yesequal();
};
console.timeEnd('Yesequal #2')

creating a javascript recursive filter function

Is there any way of making this function recursive so that I do not need to create a switch for each length of filter criteria ?
var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]
function select(data,where){
return data.filter(function(e){
var k = Object.keys(where);
switch(k.length){
case 1: return (e[k[0]] == where[k[0]]);
case 2: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]]);
case 3: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]]);
case 4: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]]);
case 5: return (e[k[0]] == where[k[0]] && e[k[1]] == where[k[1]] && e[k[2]] == where[k[2]] && e[k[3]] == where[k[3]] && e[k[4]] == where[k[4]]);
}
})
}
var where = {a:'aaa',b:'bbb'}
console.log(select(data,where));
It doesn't need to be recursive (I'm not sure you understand what that means), you just need to loop on the elements in where:
function select(data, where) {
return data.filter(function(e) {
var k = Object.keys(where);
return k.every(function(key) {
return e[key] == where[key];
});
})
}
var data = [
{a:'aaa',b:'bbb',c:'ccc',d:'ddd',e:'eee'},
{a:'aaa',b:'bbb',c:'ccc',d:'eee',e:'fff'},
{a:'xxx',b:'bbb',c:'ccc',d:'ddd',e:'fff'}
]
var where = {a:'aaa',b:'bbb'}
console.log(select(data,where));
Try this code:
function select(data, where) {
return data.filter(function (e) {
for (var key in where) {
if (where.hasOwnProperty(key)) {
if (e.hasOwnProperty(key)) {
if (e[key] != where[key]) {
return false;
}
}
else {
return false
}
}
}
return true;
})
}

Recursion Function to search

How would I go about creating a recursive function that can search through a list for a node where x = 10?
I do not have any javascript experience so I am not sure where to start so would appreciate and input
I have come across the following code and tried to adapt it but I am not sure if I am on the right track:
function search(_for, _in) {
var r;
for (var p in _in) {
if ( p === 10 ) {
return _in[p];
}
if ( typeof _in[p] === 'object' ) {
if ( (r = search(_for, _in[p])) !== null ) {
return r;
}
}
}
return null;
}
Thank you in advance
Try this
var finder = function(needle, haystack) {
if (haystack.length == 0)
return false
if (haystack[0] == needle)
return true
return finder(pin, haystack.slice(1))
}
Or
var finder = function(pin, haystack) {
return (haystack[0] == pin) || (haystack.length != 0) && finder(pin, haystack.slice(1))
}
Recursion FTW

Categories

Resources