Which structure gives O(1) append and pop at both ends?
Options
- list
- collections.deque (Correct option)
- tuple
- heapq
Answer
collections.deque
Why
A Python list is an array: inserting or removing at the FRONT shifts every other element, which is O(n).
collections.deque (double-ended queue) is built for fast adds and removes at both ends: O(1).
Use it for queues (first in, first out) and sliding windows.
Remember
Need a queue in Python? Use collections.deque.