garfield the cat
garfield the cat

Reputation: 71

MinStack LeetCode - implementing pop()

For this LC problem, we're supposed to implement a stack that supports pop() (and other methods) in constant time. For pop(), the solution is just

class MinStack {
    stack = [];

    pop() {
        this.stack.pop();
    }
}

I don't understand why this works. How does this.stack.pop() call the native pop() method instead of calling the MinStack implementation of pop() (which would result in a loop)?

Disclaimer: I'm a self taught engineer who studied on my own well enough to get into FAANG - but there's still a lot I don't know. Please be nice :)

Upvotes: 0

Views: 131

Answers (1)

Abhinav Mathur
Abhinav Mathur

Reputation: 8101

  • If you call this.pop() inside pop(), it will result in an infinite recursion.
  • this.stack.pop() will call the pop() function for the array, not the pop() function defined in class MinStack (there is no "native" pop function). The object for which you call object.function() decides the function definition that is actually evoked. So this will not be infinitely recursive.

Upvotes: 1

Related Questions