Skip to content
Onsite

Implement Stack

EasyP2Coding

Implement a stack of integers (last in, first out) without using a library stack type.

Implement the MyStack class:

  • MyStack() creates an empty stack.
  • push(x) puts x on top.
  • pop() removes and returns the top element, or -1 if the stack is empty.
  • peek() returns the top element without removing it, or -1 if the stack is empty.
  • isEmpty() returns true if the stack has no elements.
  • size() returns the number of elements.

Every operation must run in O(1) time (amortized is fine).

Example 1

Input
["MyStack","push","push","peek","pop","pop","isEmpty"] [[],[1],[2],[],[],[],[]]
Output
[null,null,null,2,2,1,true]
Why
Pop returns the most recent push first; popping an empty stack gives -1.

Constraints

  • -10^9 <= x <= 10^9
  • At most 10^4 calls in total.

Hints

Run checks the 2 visible tests, Submit all 7.