Implement Queue using Arrays

Pattern: Implementation

easy

Keep head and size in an array used as a ring. The front is data[head]; the next free slot is (head + size) mod capacity. Removing moves head forward with wrap-around, so nothing is ever shifted. When full, copy into a doubled array front first.

The problem

Build a class ArrayQueue with push(x) (add at the back), pop() (remove and return the front), peek() (return the front) and isEmpty(), storing items in an array. After push(5), push(10): peek() is 5 and pop() is 5.

On an empty structure, pop, top and peek return -1. This is this guide's own rule; the linked page does not say what happens.

Think first

  • Which end do you add at, and which do you remove from?
  • What goes wrong if removing shifts every item left?
  • How can the front move without shifting?

Hints

    Brute force, and why it fails

    Remove at index 0 and shift everything left: O(n) per pop.

    The key insight

    Let the front move instead of the items. Treating the array as a ring reuses the slots the front has left behind.

    Dry run

    50head
    101 
    2 
    3 
    size2

    Capacity 4, head 0, size 0. push(5), push(10).

    Step 1 of 4

    The plan

    push(x): if size == capacity: copy items in order (front first) into a doubled array; head = 0
             data[(head + size) mod capacity] = x; size += 1
    pop():   if size == 0: return -1
             x = data[head]; head = (head + 1) mod capacity; size -= 1; return x
    peek():  return -1 if size == 0 else data[head]
    

    Complexity

    Time
    O(1) per operation (amortised for push)
    Space
    O(n)

    Each operation reads or writes one slot and does a little arithmetic. Growing copies each item once per doubling.

    Edge cases

    • Pop on an empty queue: -1.
    • Many pushes and pops in turn: head wraps round many times.
    • Growing while head is not 0: the copy must start at head, not at 0.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class ArrayQueue {
        private int[] data = new int[4];
        private int head = 0, size = 0;             // items are data[head], data[head + 1], ... wrapping round
    
        public void push(int x) {
            if (size == data.length) {              // full: copy into a doubled array, front first
                int[] bigger = new int[size * 2];
                for (int i = 0; i < size; i++) bigger[i] = data[(head + i) % data.length];
                data = bigger;
                head = 0;
            }
            data[(head + size) % data.length] = x;
            size++;
        }
    
        public int pop() {
            if (size == 0) return -1;               // this guide's rule for an empty queue
            int x = data[head];
            head = (head + 1) % data.length;
            size--;
            return x;
        }
    
        public int peek() {
            return size == 0 ? -1 : data[head];
        }
    
        public boolean isEmpty() {
            return size == 0;
        }
    }

    C++

    class ArrayQueue {
    public:
        vector<int> data = vector<int>(4);
        int head = 0, size = 0;                     // items are data[head], data[head + 1], ... wrapping round
    
        void push(int x) {
            int cap = static_cast<int>(data.size());
            if (size == cap) {                      // full: copy into a doubled array, front first
                vector<int> bigger(cap * 2);
                for (int i = 0; i < size; i++) bigger[i] = data[(head + i) % cap];
                data = bigger;
                head = 0;
                cap *= 2;
            }
            data[(head + size) % cap] = x;
            size++;
        }
    
        int pop() {
            if (size == 0) return -1;               // this guide's rule for an empty queue
            int x = data[head];
            head = (head + 1) % static_cast<int>(data.size());
            size--;
            return x;
        }
    
        int peek() {
            return size == 0 ? -1 : data[head];
        }
    
        bool isEmpty() {
            return size == 0;
        }
    };

    Python

    class ArrayQueue:
        def __init__(self):
            self.data = [0] * 4
            self.head = 0                           # items are data[head], data[head + 1], ... wrapping round
            self.size = 0
    
        def push(self, x: int) -> None:
            cap = len(self.data)
            if self.size == cap:                    # full: copy into a doubled array, front first
                self.data = [self.data[(self.head + i) % cap] for i in range(self.size)] + [0] * cap
                self.head = 0
                cap *= 2
            self.data[(self.head + self.size) % cap] = x
            self.size += 1
    
        def pop(self) -> int:
            if self.size == 0:
                return -1                           # this guide's rule for an empty queue
            x = self.data[self.head]
            self.head = (self.head + 1) % len(self.data)
            self.size -= 1
            return x
    
        def peek(self) -> int:
            return -1 if self.size == 0 else self.data[self.head]
    
        def isEmpty(self) -> bool:
            return self.size == 0

    Common mistakes

    • Copying the old array in index order when growing, which mixes the order up after a wrap.
    • Computing the back as head + size without the modulo.
    • Telling full from empty with head == tail alone; keeping size avoids it.

    Similar problems