Implement a single-producer multi-consumer ring buffer
Company: Citadel
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of ring-buffer data structures, circular indexing, fixed-capacity storage, and object-oriented design for a single-producer, multi-consumer implementation in C++.
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) <= 2 * 10^5
- -10^9 <= pushed values <= 10^9
- Each operation should run in O(1) time
- Do not resize the buffer after initialization
Examples
Input: (3, [("empty",), ("push", 10), ("push", 20), ("size",), ("pop",), ("push", 30), ("push", 40), ("full",), ("pop",), ("pop",), ("pop",), ("empty",)])
Expected Output: [True, True, True, 2, (True, 10), True, True, True, (True, 20), (True, 30), (True, 40), True]
Explanation: This checks basic FIFO behavior, size tracking, and wrap-around after a pop frees space.
Input: (2, [("push", 1), ("push", 2), ("push", 3), ("full",), ("size",), ("pop",), ("push", 3), ("pop",), ("pop",), ("empty",)])
Expected Output: [True, True, False, True, 2, (True, 1), True, (True, 2), (True, 3), True]
Explanation: The third push fails because the buffer is full. After popping one item, pushing succeeds again.
Input: (1, [("pop",), ("push", -5), ("full",), ("push", 7), ("size",), ("pop",), ("empty",), ("pop",)])
Expected Output: [(False, None), True, True, False, 1, (True, -5), True, (False, None)]
Explanation: Capacity 1 is a boundary case. It also checks failed pop on empty, failed push on full, and a negative value.
Input: (4, [("push", 5), ("push", 5), ("push", -1), ("pop",), ("push", 7), ("push", 7), ("full",), ("size",), ("pop",), ("pop",), ("pop",), ("pop",)])
Expected Output: [True, True, True, (True, 5), True, True, True, 4, (True, 5), (True, -1), (True, 7), (True, 7)]
Explanation: This verifies correct FIFO order with duplicates, a negative value, and wrap-around after earlier pops.
Input: (5, [])
Expected Output: []
Explanation: No operations means no output.
Hints
- Track `head`, `tail`, and the current element count. That lets you avoid shifting elements after each pop.
- When either index reaches the end of the array, wrap it back using modulo arithmetic. A separate count helps distinguish `empty` from `full`.