Skip to content
DeepForgeby svx
All problems
EasyData Structuresds-086

Ring Buffer with Overwrite

Problem

Simulate a circular ring buffer that overwrites its oldest element when full.

operations contains "write" (values[i] is the value), "read" (returns the oldest value or None when empty), or "to_list" (records the contents from oldest to newest). Once capacity elements are present, each new write replaces the oldest element and advances the read pointer.

Return the list of recorded results.

Hint

Track a start index and a count; the next write position is (start + count) % capacity.

Test cases

case 1
in: [3,["write","write","write","to_list","write","to_list"],[1,2,3,0,4,0]]
expected: [null,null,null,[1,2,3],null,[2,3,4]]
case 2
in: [2,["write","write","write","read","read","read"],[1,2,3,0,0,0]]
expected: [null,null,null,2,3,null]
case 3
in: [1,["write","write","to_list","read"],[5,6,0,0]]
expected: [null,null,[6],6]
case 4
in: [2,["read","to_list"],[0,0]]
expected: [null,[]]
Starter codePython
def ring_buffer_overwrite(capacity, operations, values):
    # Your code here
    pass

4 test cases · run your code against them in the editor