from collections import deque d = deque() d.append(1) d.appendleft(2) d.append(3) d.pop() d.appendleft(4) print(list(d))
The operations modify the deque as follows:
- append(1): deque is [1]
- appendleft(2): deque is [2, 1]
- append(3): deque is [2, 1, 3]
- pop(): removes 3, deque is [2, 1]
- appendleft(4): deque is [4, 2, 1]
A deque allows insertion and deletion at both ends, front and rear, making option C correct.
Option C is false because operations are allowed at both ends.
Option C is false because deque supports both FIFO and LIFO behaviors.
Option C is false because deque can grow dynamically.
from collections import deque d = deque([1, 2, 3]) d.pop() d.pop() d.pop() d.pop()
The deque initially has 3 elements. Popping 4 times tries to remove an element from an empty deque on the last pop, causing an IndexError.
from collections import deque d = deque([10, 20, 30, 40, 50]) d.rotate(2) print(list(d))
Rotating by 2 moves the last two elements (40, 50) to the front, resulting in [40, 50, 10, 20, 30].
The sliding window maximum algorithm requires adding and removing elements from both ends efficiently to maintain candidates for maximum values.
Deque supports O(1) insertion and deletion at both ends, which is crucial.
It does not sort elements automatically, nor does it provide O(1) random access.