Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Thread-Safe Circular Buffer Operations

MediumPython00:00
I
Practice interviewer
Your interviewer
In session
I
Interviewer

Welcome to the Python screen.

The question is on your right: Thread-Safe Circular Buffer Operations. Read through the requirements first.

Run and submit your code as often as you need. You also have five interviewer messages this session - want to talk through your approach, or are you ready to start coding?

You need to log in / sign up to run or submit.

Problem

In Meta embedded systems, components such as sensor pipelines or device telemetry often use a fixed-size circular buffer to pass data between producers and consumers. Implement the core buffer operations for a bounded circular buffer and return the results of a sequence of commands.

Task

Write a function that simulates a circular buffer of capacity capacity. The buffer stores integers and supports these commands in order:

  • "push", value — insert value at the tail if the buffer is not full; otherwise return false for that command.
  • "pop" — remove and return the oldest value if the buffer is not empty; otherwise return -1.
  • "peek" — return the oldest value without removing it; return -1 if empty.
  • "size" — return the current number of elements.

Use a fixed-size array with wraparound indexing. The goal is to model the core logic that a thread-safe C circular buffer would protect with a mutex, while keeping this interview problem focused on correct buffer behavior.

Constraints

  • 1 <= capacity <= 10^5
  • 1 <= len(operations) <= 2 * 10^5
  • -10^9 <= value <= 10^9
  • Each operation is one of ["push", value], ["pop"], ["peek"], or ["size"]
  • All operations should run in O(1) time

Function Signature

def circular_buffer_results(capacity, operations):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output