OOP Fundamentals · Coding problem

A Bounded Stack Built by Composition

A free coding problem from the OOP Pillars & Composition skill. Read it here, then solve it in the app in Java or Python.

  • Easy
  • Coding problem
  • Free
  • Java and Python

The problem

java.util.Stack extends Vector, so every stack also exposes add(index, element) and other list methods that break last-in-first-out. Build a better one by composition: BoundedStack has a Deque and exposes only these operations:

  • push(item) - adds to the top; if the stack already holds capacity items, throw IllegalStateException("stack is full")
  • pop() - removes and returns the top item; if empty, throw IllegalStateException("stack is empty")
  • peek() - returns the top item without removing it; if empty, throw IllegalStateException("stack is empty")
  • size() - the number of items

In Python: BoundedStack has a list - subclassing list would hand every caller insert, sort and slicing, the same mistake as Stack extends Vector - and the errors are RuntimeError("stack is full") and RuntimeError("stack is empty"), which the command handler catches where Java's catches IllegalStateException.

Commands: NEW <capacity> (always first), PUSH <item>, POP, PEEK, SIZE.

Example

Input:
6
NEW 2
PUSH a
PUSH b
PUSH c
POP
PEEK

Output:
capacity 2
pushed a
pushed b
ERROR stack is full
popped b
top a

Constraints

  • At most 1000 commands; 1 <= capacity <= 1000.

How it's graded

  • Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their 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 OOP Pillars & Composition

Solve it A Bounded Stack Built by Composition free

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

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