Problem 218916 · easy · Level 02 Linear Data Structures

Fixed-Size Ring Buffer

queues · circular buffer · class design

Design a class RingBuffer: a first-in-first-out queue of integers with a fixed capacity, backed by a fixed-size list (do not use collections.deque or list pop(0)).

  • RingBuffer(capacity): create an empty buffer that can hold capacity items.
  • enqueue(x): add x at the back; return True on success, False if the buffer is full.
  • dequeue(): remove the front item and return True, or return False if the buffer is empty.
  • front(): return the front item, or -1 if empty.
  • rear(): return the back item, or -1 if empty.
  • is_empty(), is_full(): return booleans.

Examples

Input:  ops  = ["RingBuffer", "enqueue", "enqueue", "enqueue", "front", "dequeue", "enqueue", "rear", "front", "is_full", "dequeue", "dequeue", "dequeue", "is_empty", "rear"]
        args = [[2], [5], [6], [7], [], [], [7], [], [], [], [], [], [], [], []]
Output: [None, True, True, False, 5, True, True, 7, 6, True, True, True, False, True, -1]
Explanation: the third enqueue fails because the buffer holds 2; after removing 5 there is room for 7.
Two dequeues empty the buffer, so the third returns False and rear() returns -1.

Constraints

  • 1 <= capacity <= 1000
  • At most 10**4 operations
  • Target: O(1) per operation

Goals

  • Implement a queue on top of a fixed-size list using head index and count
  • Wrap indices around with modulo
  • Distinguish the full and empty states
Starting Python…