Code Room
CodingMediumcod-g580
Subject Circular bufferLevel Mid–Senior~25 minCommon in Algorithms & data structures interviewsIndustries Software development, Technology

Question

Implement a fixed-capacity ring buffer that overwrites the oldest element when full. Replay operations: ["write", x] appends x (overwriting the oldest if at capacity), ["read"] removes and returns the oldest element or -1 if empty, ["snapshot"] returns -2 as a marker and the snapshot itself is appended to results as the current buffer contents oldest-to-newest. Actually, to keep results flat: on ["read"] append the returned value; on ["oldest"] append the oldest value without removing (or -1 if empty); ignore other introspection. Capacity is between 1 and 10^4. Return the list of values produced by read and oldest operations in order.

Implement
ring_buffer(capacity: int, ops: list[list]) → list[int]
Examples
in[3,[["write",1],["write",2],["write",3],["write",4],["oldest"],["read"],["oldest"],["read"],["read"],["read"]]]out[2,2,3,3,4,-1]
What a strong answer looks like

State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.

Vibe coding: describe the solution in plain language (or narrate it) and the coach grades your approach. Generating runnable code from your description is coming next.

Run or narrate your approach, then ask the coach.