The Circular Array for a Deque
The questions in this section are about storing a deque in a backing array arr.
Solution
First end at index 0: addLast is amortized and removeLast is , but addFirst and removeFirst are , because all the other items shift one slot. Last end at index 0: addFirst is amortized and removeFirst is , but addLast and removeLast are . Either way, the two operations at one end cost .
Solution
front, which is 6.(front + size - 1) % arr.length, which is(6 + 2) % 8, that is, 0.(front + size) % arr.length, which is(6 + 3) % 8, that is, 1.(front + arr.length - 1) % arr.length, which is(6 + 7) % 8, that is, 5.
Solution
It fails when front is 0. Java’s % keeps the sign of the left operand, so -1 % arr.length is -1, which is not a valid index. The fix is to add arr.length before taking the remainder: (front + arr.length - 1) % arr.length, which gives arr.length - 1 when front is 0.
Solution
0 1 2 3 4
┌───┬───┬───┬───┬───┐
│ W │ _ │ _ │ K │ M │
└───┴───┴───┴───┴───┘
↑ ↑ ↑
│ │ front
│ addFirst
addLast
K is at index 3, M at index 4, and W wraps to index 0. The next addFirst writes at index 2, and the next addLast writes at index 1.