Implement Stack using Array

easy

Implement a stack (last-in, first-out) backed by an array, supporting two operations:

  • push(x) — add x to the top of the stack.
  • pop() — remove and return the top element; if the stack is empty, return -1.

You'll be given a sequence of operations; the first names the class (its constructor). Each pop reports its result; push and the constructor report nothing.

Hints

Which end of an array supports O(1) add and remove?
Treat the last element as the top: push appends, pop removes from the end.
Guard pop against an empty stack by returning -1.

Common doubts

Appending and removing at the end are amortized O(1). Removing from the front would shift every element, costing O(n).
By this problem's convention, it returns -1 instead of raising an error — check the size before removing.

Interview follow-ups

Preallocate an array and keep a top index; push writes at top and increments, pop reads and decrements. You handle overflow yourself.
A linked list pushes/pops at the head with guaranteed O(1) (no resizing), at the cost of a node allocation and pointer per element.

Fun facts

  • The call stack your program runs on is exactly this structure — push a frame on call, pop it on return.
  • 'Stack' is one of the oldest data structures, formalized alongside the first compilers to evaluate expressions.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: push(5), push(10), pop(), pop(), pop()
Output: 10, 5, -1
Two pushes, then three pops return 10, 5, and -1 (empty).
Example 2
Input: push(7), pop()
Output: 7
Push 7, then pop returns 7.
Constraints

- 1 <= number of operations <= 100 - 1 <= x <= 10^5 - pop() returns -1 if the stack is empty.

Solve this problem →