The problem. Build a queue on top of an array. Support enqueue(x) (add x at the back), dequeue() (remove and return the front item, or -1 if the queue is empty), front() (return the front item, or -1 if empty), isEmpty() and size(). The queue must keep working however many items pass through it.
enqueue(10) enqueue(20) front() -> 10
dequeue() -> 10 size() -> 1
dequeue() -> 20 dequeue() -> -1 (empty)Enqueue is easy on any array: append at the end. The whole problem is the front. Items leave from the start of the array, and the start is exactly where an array is slow to change.
Members only · free account
The rest of this lesson, with 6 more sections, 4 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++, opens with a free account.
Not ready yet? The Arrays course is free to read, no account needed.
In the rest of this lesson