Back

Lists, Stacks & Queues (Medium) / 211. Implement Stack using Array

00:00
1/6

211. Implement Stack using Array

Medium

Implement a basic Stack data structure using an array (or list in Python). Support the following operations:

  • push(x): Add x to stack.
  • pop(): Remove and return top element.
  • top(): Return top element without removing.
  • isEmpty(): Return true if stack is empty.

Example:

stack = MyStack()
stack.push(10)
stack.push(20)
stack.top() → 20
stack.pop() → 20
stack.isEmpty() → False
  • 1

    Underlying Structure: Use a dynamic array (Python List).

  • 2

    Operations:

  • 3

    push: list.append(x) (O(1)).

  • 4

    pop: list.pop() (O(1)).

  • 5

    top: list[-1] (O(1)).

  • 6

    isEmpty: len(list) == 0 (O(1)).

PYTHON PLAYGROUND
PYTHON PLAYGROUND
⏳ Loading editor…