Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Thread-Safe Circular Buffer Operations

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Thread-Safe Circular Buffer Operations. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

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