Skip to contentKEEP THE CRAFTTHE SANCTUARY

Simulate a Circular Buffer

Run a fixed-size queue in a list with a head index, a count and wraparound.

The problem

Implement simulate_circular_buffer(capacity, actions). Simulate a queue that holds at most capacity values in a fixed list of capacity slots. Each action is either ["put", value], which adds value at the back, or ["get"], which removes the oldest value. A put on a full buffer is ignored. For every get, append the removed value to the output list, or None if the buffer is empty. Return the output list. For example, with capacity 2 the actions put "a", put "b", put "c", get, get return ["a", "b"]: "c" was ignored because the buffer was full. capacity is at least 1.

Starter code

def simulate_circular_buffer(capacity, actions):
    pass

Public examples

  1. capacity = 3, actions = [["put", 1], ["put", 2], ["get"], ["put", 3], ["put", 4], ["get"], ["get"], ["get"]]gives[1, 2, 3, 4]
  2. capacity = 2, actions = [["put", "a"], ["put", "b"], ["put", "c"], ["get"], ["get"]]gives["a", "b"]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.