PPractick

DSA interview question

Implement a Queue Using an Array (Circular Buffer)

Easy · Data structures · Topics: queue, array

The problem

A logging agent buffers outgoing log lines in a fixed-size array before shipping them, and it needs a first-in, first-out queue: enqueue at the back, dequeue from the front, both O(1). The naive design (dequeue by shifting everything left) is O(n), and "just advance a front index" wastes the freed slots at the start forever. A circular buffer fixes both: keep a head index and a count, and wrap positions around with modulo so freed slots are reused.

Example: enqueue(2), enqueue(3), dequeue() → 2, enqueue(4), dequeue() → 3.

Function signature

class ArrayQueue {
public:
    explicit ArrayQueue(int capacity);
    bool enqueue(int x);   // false if full
    int dequeue();         // -1 if empty
    int front() const;     // -1 if empty
    bool isEmpty() const;
    int size() const;
};

Test cases

OperationsOutputExplanation
enqueue(2) enqueue(3) dequeue() enqueue(4) dequeue()2 3First in, first out
dequeue() on an empty queue-1
capacity 2: enqueue(1) enqueue(2) enqueue(3)true true falseFull
capacity 3: enqueue 1, 2, 3; dequeue; enqueue 4; dequeue ×31 2 3 44 wraps into the freed slot 0
enqueue(9) front() size()9 1

(Confirm: all operations O(1); capacity is fixed; −1 signals "empty".)

How interviewers phrase it

Clarifying questions to ask

  1. Fixed capacity? What should happen when it's full?
  2. What should dequeue return when the queue is empty?
  3. Is O(1) required for every operation? (Yes, which rules out shifting.)

Follow-ups to expect

  1. "Why not shift elements on dequeue?"
  2. "Why a count instead of just front and rear?"
  3. "Where does the next element go?"
  4. "How would you grow it?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in