Implement Queue using Array

easy

Implement a queue (first-in, first-out) backed by an array, supporting:

  • push(x) — add x to the back of the queue.
  • pop() — remove and return the front element; if the queue is empty, return -1.

The first operation names the class (its constructor). Each pop reports its result; push and the constructor report nothing.

Hints

Push adds at the back — where should pop remove from for FIFO order?
Removing from the front by shifting is O(n); can you avoid moving elements?
Keep a front index that advances on each pop; return -1 once it passes the end.

Common doubts

That shifts every remaining element left, costing O(n). A front index advances in O(1) and leaves the elements in place.
In this simple version, yes — the popped prefix isn't reclaimed. A production queue uses a circular buffer (or a linked list) to reuse space.

Interview follow-ups

Wrap the front and back indices modulo the capacity, reusing freed slots; resize when the buffer is full.
Two stacks give amortized O(1) FIFO by moving elements from an input stack to an output stack only when the output is empty.

Fun facts

  • Ring buffers — circular-array queues — are everywhere in systems: network packet queues, audio buffers, and OS scheduler run-queues.
  • The 'advance an index instead of shifting' idea is the same trick behind the two-pointer sliding window.

Asked at

AmazonMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: push(5), push(10), pop(), pop(), pop()
Output: 5, 10, -1
FIFO: the first pushed (5) is the first popped, then 10, then -1 (empty).
Example 2
Input: push(7), pop()
Output: 7
Push 7, then pop returns 7.
Constraints

- 1 <= number of operations <= 100 - 1 <= x <= 10^5 - pop() returns -1 if the queue is empty.

Solve this problem →