AniUI Academy

A stack you can look into without disturbing it

easyData Structures+150 XPPractice

A stack is the first structure most frontend work reaches for: the router history you pop back through, the modal layers you close in reverse order, the parser that matches your JSX tags. It is a list where the only item you can touch is the most recent one.

Implement a Stack class. It is constructed with no arguments and starts empty. push(value) adds a value on top and returns the new size as a number. pop() removes the top value and returns it, or returns undefined when the stack is empty. peek() returns the top value without removing it, or undefined when the stack is empty. size() returns how many values are currently held. isEmpty() returns true when nothing is held and false otherwise.

Examples

const s = new Stack();
s.push("a"); // 1
s.push("b"); // 2
s.peek();    // "b"
s.pop();     // "b"
s.size();    // 1

push returns the new size; pop and peek work on the top.

const s = new Stack();
s.pop();     // undefined
s.peek();    // undefined
s.isEmpty(); // true

An empty stack returns undefined rather than throwing.

What it has to do

  • push returns the size of the stack after the value was added.
  • pop returns values in last-in-first-out order.
  • pop and peek return undefined on an empty stack rather than throwing.
  • peek leaves the stack unchanged.
  • isEmpty() is true only when size() is 0.

Notes

  • Every operation is O(1) when the stack is backed by an array that only touches the end.
  • Reaching for .shift() instead of .pop() turns the stack into a queue and makes every operation O(n) — be deliberate about which end you work from.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.