DEV Community

loading...

Discussion on: Leetcode MinStack Design Problem: JavaScript Low Level Solution

Collapse
alfredosalzillo profile image
Alfredo Salzillo 🐺

Low-level javascript doesn't mean you cannot use the class sugar syntax and const or let.

And why you don't use the Array length like count?

class MinStack {
   storage = [];
   history = [];
   min = Number.MAX_SAFE_INTEGER;
   push(value) {
      this.storage.push(value);
      this.history.push({ min: this.min });
      this.min = Math.min(this.min, value);
   }
   pop() {
     const last = this.history.pop();
     if (last) {
       this.min = last.min;
     }
     return this.storage.pop();
   }
   top() {
     return this.storage[this.storage.length - 1];
   }
}
Enter fullscreen mode Exit fullscreen mode

The native popand pushshould be better than the index assignment.

Collapse
definite2 profile image
Defne Eroğlu Author • Edited

Thank you for your comments Alfredo. My point in this blog to share this particular solution I've submitted to leetcode. And I know, in the description of the problem, there is no rule that we cannot use push(), pop() or length functions and props ; but this was my solution. And I just wanted to share....
But your comment was very beneficial for me! Because I've gone more detail about these native functions, at least first just by google'ing the topic (as searching with the question that push() vs index assignment). Than I've found somethings I would like to share with you too.
The first search result I've found was from stackoverflow:
stackoverflow.com/questions/210346...
This post implies that push() is slower than array assignment. And I've found some similar discussions from old times they also say that push() is slower than array assignment. But they are very old post. I know node.js is much more better now and also the javascript engines of the browsers are increased in their performance. Than
I've made a test and my test environment is: Lenova, i7, node.js v12.18.3
Here is the test code:

var i = 0
var ar = []

i = 0
console.time("With index assignment")
while(i<=99999){
  ar[i] = i
  i++
}
console.timeEnd("With index assignment")

i = 0
ar = []
console.time("With push()")
while(i<=99999){
  ar.push(i)
  i++
}
console.timeEnd("With push()")
Enter fullscreen mode Exit fullscreen mode

And the result! push() is faster than index assignment! According to my tests you are right at the saying push(), pop() is faster than but; in the 2015 you were wrong I suppose... Anyways. As I've told at the beginning, I don't say this is the best and optimal solution, btw it was better the 75% of other commiters' submissions, my aim was to write these functions without Javascript's native related functions...And thank you again of course for your comment.

Collapse
rahxuls profile image
Rahul

Thank you for this. It seems a new post in Comments.

Amazing.