# TLE in "Stacks": Problem Code: STACKS

``````var arr = '';
process.stdin.on('data',function(chunk){
arr += chunk;
});
process.stdin.on('end',function(){
arr = arr.split('\n');
while(i<=t){
n = parseInt(arr[line++]);
stack = [];
for(j=0;j<len;j++){
else{
else{
for(k=0;k<stack.length;k++){
break;
}
}
}
}
}
console.log(stack.length+" "+stack.join(' '));
i++;
}
});
``````

I wrote the program of “Stack” in node.js but the output is coming “time limit exceeded”. The same program when I am writing in C then it is getting executed successfully. Where the time complexity in both the case is O(n3). Anyone have any idea to do it in javascript?

Here we go, i did it in Javascript. I change my logic and implemented binary search for getting the index to put the disk.
All i want to know how come the time complexity reduces for binary search. If you notice the time complexity for my above solution is O(n3) and for binary search it is O(n3logn). So where is the reduction of the time complexity?
Below is my AC solution with binary search:-

``````var arr = '',stack;
process.stdin.on('data',function(chunk){
arr += chunk;
});
process.stdin.on('end',function(){
arr = arr.split('\n');
while(i<=t){
n = parseInt(arr[line++]);
stack = [];
for(j=0;j<len;j++){
else{
else{
if(index == -1) stack[0] = parseInt(radii[j]);
}
}
}
console.log(stack.length+" "+stack.join(' '));
i++;
}
});

function binarySearch(l,h,key){
while(l<h){
let mid = Math.floor((l+h)/2);
if(stack[mid]<=key && stack[mid+1]>key) return mid+1;
else if(stack[mid]>key) h = mid;
else l = mid+1;
}
return -1;
}``````