Design Circular Deque

Implement a fixed-size double-ended queue on a ring buffer: values can be added or removed at both the front and the rear. Support insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty and isFull, each in O(1) without a built-in deque.

30:00

Design Circular Deque
medium
Free written solution
Topics
Companies

Implement a fixed-size double-ended queue on a ring buffer: values can be added or removed at both the front and the rear. Support insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty and isFull, each in O(1) without a built-in deque.

Example 1:
Input: {"commands":["MyCircularDeque","insertLast","insertLast","insertFront","insertFront","getRear","isFull","deleteLast","insertFront","getFront"],"values":[[3],[1],[2],[3],[4],[],[],[],[4],[]]}
Output: [null,true,true,true,false,2,true,true,true,4]
Constraints:
  • 1≤k≤10001 \leq k \leq 1000

  • 0≤value≤10000 \leq \text{value} \leq 1000

  • At most 20002000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["MyCircularDeque","insertLast","insertLast","insertFront","insertFront","getRear","isFull","deleteLast","insertFront","getFront"],"values":[[3],[1],[2],[3],[4],[],[],[],[4],[]]}

9 calls on a ring of 3 slots. front marks the first value and the rear is (front + count - 1) % k, so both ends can move in O(1).

Ring of 3 slots

count 0/3

012frontsize0/3

What the caller sees

front
(empty)
rear

Ready

output: []
Variables
VariableValue
call
front0
count0
rear-
DepthFunction Call
Stack empty
0/13