AniUI Academy

A deque you can push and pop from both ends

mediumData Structures+250 XPPractice

Some queues are entered from both ends: a carousel you can scroll either way, a chat that prepends older messages while appending new ones, a sliding window that grows at the front and shrinks at the back.

Implement a Deque class (double-ended queue). It is constructed with no arguments and starts empty. pushFront(value) and pushBack(value) add a value at that end and each return the new size. popFront() and popBack() remove and return the value at that end, or return undefined when the deque is empty. peekFront() and peekBack() return the value at that end without removing it, or undefined when empty. size() returns how many values are held. toArray() returns the values as a plain array ordered front to back, and [] when empty.

Examples

const d = new Deque();
d.pushBack("b");
d.pushBack("c");
d.pushFront("a");
d.toArray();   // ["a", "b", "c"]
d.peekFront(); // "a"
d.peekBack();  // "c"
const d = new Deque();
[1, 2, 3, 4].forEach((v) => d.pushBack(v));
d.popFront();  // 1
d.popBack();   // 4
d.toArray();   // [2, 3]

You can drain from either end in any order.

What it has to do

  • pushFront and pushBack each return the new size.
  • toArray() lists values from front to back.
  • All four pop and peek methods return undefined on an empty deque.
  • Values pushed to the front come out of popFront in reverse push order.
  • The deque stays consistent when drained from both ends.

Notes

  • A plain-array deque has O(1) back ops but O(n) front ops because unshift and shift have to slide the rest of the array.
  • For a truly O(1) deque at any size, back it with a doubly linked list or a circular ring buffer that grows on demand.

Stuck? The javascript course covers everything this challenge needs.

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

Discussion

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

No comments yet. Be the first to say something.