Stacks and Queues · Coding problem

Implement Stack using Arrays

A free coding problem from the Array-Backed Stack and Queue skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

Implement a fixed-capacity stack backed by a plain array (in Python, a list preallocated with [0] * capacity and an index - not append/pop), supporting:

  • push(x) - push a value.
  • pop() - remove and return the top value, or -1 if empty.
  • top() - return (without removing) the top value, or -1 if empty.

Input format

Line 1: capacity. Line 2: q, the number of operations. Each of the next q lines is PUSH x, POP, or TOP. For each POP/TOP, print the result.

Example

Input:
10
6
PUSH 1
PUSH 2
TOP
POP
POP
POP

Output:
2
2
1
-1

Constraints

  • 1 <= capacity <= 2 * 10^5
  • 1 <= q <= 4 * 10^5
  • 0 <= x <= 10^9, so the empty result -1 never collides with a stored value
  • The stack never holds more than capacity elements at once

How it's graded

  • Run checks your code against the examples. Submit also runs a hidden suite in four groups - basic cases, edge cases, random inputs and performance tests at the size limit - and shows which groups pass, never the hidden inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in Array-Backed Stack and Queue

Solve it Implement Stack using Arrays free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime