data-structures · intermediate · ~15 min

Queue length in a ring

Compute occupancy in a circular buffer.

Challenge

Compute how many items a ring buffer currently holds.

Task

Implement int ring_count(int head, int tail, int cap) that returns the number of items stored between head (the front of the queue) and tail (the next free slot) in a ring buffer, accounting for wrap-around.

Input

  • head: index of the front item, 0 <= head < cap.
  • tail: index of the next free slot, 0 <= tail < cap.
  • cap: the buffer capacity.

Output

int: the number of stored items. In this convention head == tail means the queue is empty.

Example

ring_count(2, 5, 8)   ->   3
ring_count(4, 4, 8)   ->   0    (empty)
ring_count(6, 2, 8)   ->   4    (wraps around)

Edge cases

  • Equal head and tail means empty (returns 0).
  • When tail < head the count wraps around the end of the buffer.

Input format

head, tail (both in [0, cap)), and cap.

Output format

int: number of items between head and tail; equal indices mean empty.

Constraints

Add cap before the modulo so the result stays non-negative.

Starter code

int ring_count(int head, int tail, int cap) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.