Implement a Circular Buffer
Company: Jane Street
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of data structures and buffer management, specifically FIFO semantics, fixed-capacity storage, wraparound indexing, and careful edge-case handling.
Constraints
- 1 <= capacity <= 10^5
- 0 <= len(operations) <= 2 * 10^5
- Values used in `enqueue` are integers in the range [-10^9, 10^9]
- Each operation should be processed in O(1) time
Examples
Input: (3, [('enqueue', 10), ('enqueue', 20), ('peek',), ('dequeue',), ('size',), ('isEmpty',), ('isFull',)])
Expected Output: [True, True, 10, 10, 1, False, False]
Explanation: After inserting 10 and 20, the oldest value is 10. Dequeue removes 10, leaving one element. The buffer is neither empty nor full.
Input: (3, [('enqueue', 1), ('enqueue', 2), ('enqueue', 3), ('isFull',), ('dequeue',), ('enqueue', 4), ('peek',), ('dequeue',), ('dequeue',), ('dequeue',), ('isEmpty',)])
Expected Output: [True, True, True, True, 1, True, 2, 2, 3, 4, True]
Explanation: This tests wraparound. After removing 1, inserting 4 reuses the freed slot at the front of the underlying array.
Input: (2, [('enqueue', 5), ('enqueue', 6), ('enqueue', 7), ('peek',), ('size',), ('dequeue',), ('enqueue', 7), ('isFull',)])
Expected Output: [True, True, False, 5, 2, 5, True, True]
Explanation: The third enqueue fails because the buffer is full. After one dequeue, 7 can be inserted successfully.
Input: (1, [('isEmpty',), ('enqueue', 9), ('isFull',), ('peek',), ('enqueue', 10), ('dequeue',), ('dequeue',), ('isEmpty',)])
Expected Output: [True, True, True, 9, False, 9, None, True]
Explanation: With capacity one, the buffer becomes full after a single enqueue. A second enqueue fails, and dequeue empties the buffer again.
Input: (4, [])
Expected Output: []
Explanation: No operations means no results.
Input: (3, [('enqueue', -1), ('enqueue', -1), ('dequeue',), ('peek',), ('size',)])
Expected Output: [True, True, -1, -1, 1]
Explanation: This shows that negative numbers and duplicate values should be handled correctly.
Hints
- Track the index of the oldest element and the current number of elements. You do not need to shift elements after a dequeue.
- When moving to the next slot, use modulo arithmetic so indices wrap back to the beginning of the array.