Skip to main content

Data Structures · Abstract data types, representation, and invariants

A ring buffer (circular array) of fixed capacity C≥ 1 stores a sequence of at most C…

Problem

A ring buffer (circular array) of fixed capacity \(C\ge 1\) stores a sequence of at most \(C\) elements using an underlying array \(B[0..C-1]\) together with two integers `head` and `size`, where \(0\le\text{head}<C\) and \(0\le\text{size}\le C\). The sequence in logical order is \[ B[\text{head}],\ B[(\text{head}+1)\bmod C],\ \ldots,\ B[(\text{head}+\text{size}-1)\bmod C]. \] Design procedures `ENQUEUE-BACK(x)`, `DEQUEUE-FRONT()`, and `PEEK(i)` (\(0\le i<\text{size}\)) for this representation. (a) Write pseudocode for the three procedures. `ENQUEUE-BACK` must fail (and leave the structure unchanged) if \(\text{size}=C\). `DEQUEUE-FRONT` must fail if \(\text{size}=0\). `PEEK` must return the element at logical index \(i\) without mutating the buffer. (b) State the representation invariant relating \(B\), `head`, `size`, and \(C\). (c) For each procedure, give a worst-case \(\Theta\) bound in terms of \(C\) and `size`, and argue that the bound does not hide a scan of the buffer.

Hint

The live data occupy a wrap-around interval of length `size` starting at `head`; the back of that interval is determined by those two integers.

Check your work

Work the problem yourself first. Then open it in Training to check your answer and read the full worked solution.

Create a free account to check your answer and see the solution. Create a free account.

More Data Structures practice problems

Back to Data Structures

An original ProofAnvil practice problem, written for this course. ProofAnvil is a practice course, not a homework-answer service.