Simulate a Ring Buffer Queue from a Command Log
Data Structure DesignAuto-graded · 14 test casesLast updated
Replay a list of queue commands against a bounded ring buffer, returning each command's result while handling wrap-around, full and empty states correctly.
Simulate a Ring Buffer Queue from a Command Log
You are given the capacity of a bounded first-in-first-out queue and a log of commands to run against it. The queue starts empty and can never hold more than k items. Process the commands in order and report the outcome of each one.
Your queue should be backed by a fixed-size array whose positions are reused cyclically, so each command takes constant time.
Function
Implement ring_queue_replay(capacity, commands, params), where:
capacityis the maximum number of items the queue may hold (k).commandsis a list of command names.params[i]is the argument list forcommands[i]: it is[x](one integer) for"enQueue"and[]for every other command.
Return a list with exactly one result per command, in the same order.
Commands
| Command | Behavior | Result |
|---|---|---|
"enQueue" | Append x at the back if there is room. Never overwrite existing items. | True if added, False if the queue was full |
"deQueue" | Remove the oldest item if there is one. | True if an item was removed, False if the queue was empty |
"Front" | Look at the oldest item without removing it. | The item, or -1 if the queue is empty |
"Rear" | Look at the newest item without removing it. | The item, or -1 if the queue is empty |
"isEmpty" | Check whether the queue holds no items. | True or False |
"isFull" | Check whether the queue holds exactly capacity items. | True or False |
A command that fails (an enQueue on a full queue or a deQueue on an empty queue) must leave the queue unchanged.
If a command name is not one of the six above, raise a ValueError.
Notes on edge cases
- When
capacityis0, everyenQueuefails,FrontandRearreturn-1, and bothisEmptyandisFullreturnTrue. - Returned
-1values fromFrontandRearare just a sentinel for an empty queue. - Slots freed by
deQueuemust be reusable by laterenQueuecalls, including after the write position wraps past the end of the array.
Constraints
0 <= capacitylen(commands) == len(params)- Each command name is a string; the valid names are
enQueue,deQueue,Front,Rear,isEmpty,isFull. - For
enQueue,params[i]holds exactly one integer; for all other commands it is empty. - Each command must run in O(1) time, so the whole log is processed in O(n) for n commands.
Examples
Example 1
Input: ring_queue_replay(3, ['enQueue', 'enQueue', 'enQueue', 'enQueue', 'Rear', 'isFull', 'deQueue', 'enQueue', 'Rear'], [[1], [2], [3], [4], [], [], [], [4], []])
Output: [True, True, True, False, 3, True, True, True, 4]
Example 2
Input: ring_queue_replay(1, ['enQueue', 'deQueue', 'Front', 'Rear', 'isEmpty', 'isFull'], [[9], [], [], [], [], []])
Output: [True, True, -1, -1, True, False]
Hints
Hint 1
A plain pair of head and tail indices cannot tell an empty buffer from a full one, because both look like head == tail. Think about what extra piece of state removes the ambiguity.
Hint 2
Store only the index of the oldest item and a count of how many items are held. The slot for the next write is (head + count) % capacity, and the newest item sits at (head + count - 1) % capacity.
Hint 3
Check for empty or full before doing any index arithmetic. This avoids stale reads for Rear on an empty queue and a modulo by zero when capacity is 0.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Allocate one array of length capacity and treat it as a ring: any index that would run past the end wraps back to 0 using % capacity.
Keep just two integers:
head: the index of the oldest item (the next one to remove).count: how many items are currently stored.
The tail is never stored, because it can be derived:
- The next free slot to write is
(head + count) % capacity. - The newest item lives at
(head + count - 1) % capacity.
Each command then becomes a few lines:
- enQueue(x): if
count == capacity, returnFalse. Otherwise writexat(head + count) % capacity, incrementcount, returnTrue. - deQueue(): if
count == 0, returnFalse. Otherwise advancehead = (head + 1) % capacity, decrementcount, returnTrue. Clearing the old slot is optional housekeeping. - Front / Rear: return
-1when empty; otherwise readbuf[head]orbuf[(head + count - 1) % capacity]. - isEmpty / isFull: compare
countwith0andcapacity. - Any other command name raises
ValueError.
Empty versus full
With only head and tail pointers, head == tail happens both when the buffer is empty and when it is full. Common ways out are:
- Keep a count of stored items (used here). It needs no wasted slot and gives the tail for free.
- Allocate
capacity + 1slots and sacrifice one, so full means(tail + 1) % (capacity + 1) == head. - Maintain a separate boolean
fullflag.
Why it is correct
The invariant is that the queue contents in FIFO order are exactly buf[head], buf[(head+1) % capacity], ..., buf[(head+count-1) % capacity], with 0 <= count <= capacity.
- Initially
count = 0, so the sequence is empty. - A successful enqueue writes just past the last element. Since
count < capacity, that slot is not occupied by any live item. Incrementingcountextends the sequence by one. - A successful dequeue moves
headforward by one and decreasescount, dropping exactly the oldest element and preserving the order of the rest. - Front and Rear read the first and last positions of the sequence.
- Rejected commands change nothing, so the invariant holds.
Because count <= capacity, no two logical positions map to the same physical slot.
All index arithmetic is guarded by a count check, so with capacity = 0 no modulo by zero is ever executed (enQueue is rejected because count == capacity, and the others see an empty queue). The guard on Rear also prevents reading a stale slot from an empty queue.
Complexity
- Time: O(1) per command, O(n) for n commands.
- Space: O(capacity) for the array, plus O(n) for the output list.
Reference solution
from typing import List, Optional
def ring_queue_replay(capacity: int, commands: List[str], params: List[List[int]]) -> List[Optional[int]]:
buf = [None] * capacity
head = 0
count = 0
out = []
for cmd, args in zip(commands, params):
if cmd == "enQueue":
if count == capacity:
out.append(False)
else:
buf[(head + count) % capacity] = args[0]
count += 1
out.append(True)
elif cmd == "deQueue":
if count == 0:
out.append(False)
else:
buf[head] = None
head = (head + 1) % capacity
count -= 1
out.append(True)
elif cmd == "Front":
out.append(-1 if count == 0 else buf[head])
elif cmd == "Rear":
out.append(-1 if count == 0 else buf[(head + count - 1) % capacity])
elif cmd == "isEmpty":
out.append(count == 0)
elif cmd == "isFull":
out.append(count == capacity)
else:
raise ValueError("Unknown operation")
return out