Search⌘ K
AI Features

ArrayQueue: An Array-Based Queue

Explore the ArrayQueue data structure that efficiently implements a FIFO queue using modular arithmetic to simulate an infinite array. Understand how to add and remove elements with constant time complexity, manage array resizing, and implement a circular buffer for optimized storage and retrieval.

ArrayQueue operations

In this lesson, we present the ArrayQueue data structure, which implements a FIFO (first-in-first-out) queue; elements are removed (using the remove() operation) from the queue in the same order they are added (using the add(x) operation).

Notice that an ArrayStack is not a good choice for an implementation of a FIFO queue because we must choose one end of the list upon which to add elements and then remove elements from the other end. One of the two operations must work on the head of the list, which involves calling add(i, x) or remove(i) with a value of i = 0. This gives a running time proportional to nn.

To obtain an efficient array-based implementation of a queue, we first notice that the problem would be easy if we had an infinite array aa. We could maintain one index j that keeps track of the next element to remove and an integer n that counts the number of elements in the queue. The queue elements would always be stored in

a[j],a[j+1],...,a[j+n1]a[j],a[j+1],...,a[j+n−1] ...