
Problem
Solution
Submissions
Circular Buffer (Circular Queue)
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a Python program to implement a Circular Buffer (also known as a Circular Queue). A circular buffer is a fixed-size buffer that works as if the memory is contiguous and circular in nature, allowing for efficient memory usage.
Algorithm for MyCircularBuffer class
- Initialize a fixed-size array and front/rear pointers.
- For enqueue operations, update the rear pointer and add elements.
- For dequeue operations, update the front pointer and remove elements.
- Implement methods to check if the buffer is empty or full.
- Use modulo arithmetic to handle wraparound of indices.
Example 1
- Input: ["MyCircularBuffer", "enqueue", "enqueue", "enqueue", "enqueue", "Rear", "isFull", "dequeue", "enqueue", "Rear"] [[3], [1], [2], [3], [4], [], [], [], [4], []]
- Output: [null, true, true, true, false, 3, true, true, true, 4]
- Explanation:
- MyCircularBuffer myCircularBuffer = new MyCircularBuffer(3);
- myCircularBuffer.enqueue(1); // return True
- myCircularBuffer.enqueue(2); // return True
- myCircularBuffer.enqueue(3); // return True
- myCircularBuffer.enqueue(4); // return False, the buffer is full
- myCircularBuffer.Rear(); // return 3
- myCircularBuffer.isFull(); // return True
- myCircularBuffer.dequeue(); // return True
- myCircularBuffer.enqueue(4); // return True
- myCircularBuffer.Rear(); // return 4
Example 2
- Input: ["MyCircularBuffer", "enqueue", "dequeue", "Front", "Rear", "isEmpty", "isFull"] [[5], [10], [], [], [], [], []]
- Output: [null, true, true, -1, -1, true, false]
- Explanation:
- MyCircularBuffer myCircularBuffer = new MyCircularBuffer(5);
- myCircularBuffer.enqueue(10); // return True
- myCircularBuffer.dequeue(); // return True
- myCircularBuffer.Front(); // return -1, buffer is empty
- myCircularBuffer.Rear(); // return -1, buffer is empty
- myCircularBuffer.isEmpty(); // return True
- myCircularBuffer.isFull(); // return False
Constraints
- 1 ≤ capacity ≤ 1000
- 0 ≤ value ≤ 10^4
- At most 3000 calls will be made to enqueue, dequeue, Front, Rear, isEmpty, and isFull.
- Time Complexity: O(1) for all operations
- Space Complexity: O(n) where n is the capacity
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a fixed-size array to store the elements.
- Keep track of front and rear pointers.
- When removing an element, move the front pointer forward.
- When adding an element, move the rear pointer forward.
- Use modulo arithmetic to wrap around the buffer indices.