Code and Optimize a Circular Buffer
Filed under Amazon
Free read 3 of 3Use a fixed array of size capacity with head, tail, and count pointers to utilize all capacity slots.
The question
Implement an optimized fixed-size circular buffer (ring buffer) supporting enqueue, dequeue, isEmpty, and isFull operations in O(1) time. Compare tracking capacity via a size counter versus head/tail pointer spacing, and address concurrency implications.
Constraints
- 1 <= capacity <= 10^5
- All operations must run in O(1) time
Examples
- Input
- cb = CircularBuffer(3); cb.enqueue(1); cb.enqueue(2); cb.enqueue(3); cb.isFull()
- Output
- True
- Why
- Buffer with capacity 3 holds 3 items and is full.
Approach
Use a fixed array of size capacity with head, tail, and count pointers to utilize all capacity slots.
Enqueue writes at tail and increments tail modulo capacity. Dequeue reads from head and increments head modulo capacity.
A size counter allows full capacity usage, whereas (tail + 1) % cap == head sacrifices one slot to differentiate empty from full.
In multi-process/thread setups, count requires atomic operations or mutexes; single-producer single-consumer can use memory barriers without locks.
Tips
- What they are testing: Tests mastery of modulo arithmetic, distinguishing full vs empty states, and concurrency primitives.
- Common mistake: Wasting one buffer slot when using only head and tail pointers without a separate count variable.
Follow-ups
- Explain critical section, locks, semaphores, and mutexes.
Related Amazon questions
Collected from public candidate posts and coding forums. Updated Nov 2026.