[ADS-FINAL-PREP] 5. Deque
A Deque (Double-Ended Queue) is a generalized data structure that allows adding and removing elements from both the front and the end of the queue. It combines the capabilities of both a stack and a queue.
Core Deque Operations
- push_front(x) — Adds element
xto the front of the queue.
- push_back(x) — Adds element
xto the end of the queue.
- pop_front() — Removes and returns the element from the front of the queue.
- pop_back() — Removes and returns the element from the end of the queue.
- front() — Views the first element without removing it.
- back() — Views the last element without removing it.
- is_empty() — Checks whether the queue is empty.
- size() — Returns the number of elements in the queue.
Use Cases
- Bidirectional Data Processing: Used in problems where data needs to be processed from both directions.
- Stack and Queue Implementation: A deque can serve as a direct replacement for a standard stack or queue.
- Sliding Window: Efficiently solves algorithms that find the minimum or maximum value in a subarray of a given size.
Advantages of a Deque
- Flexibility: Supports insertions and deletions at both ends.
- High Speed: Executes insertion and deletion operations at both ends in O(1) time complexity (when implemented via linked lists or using Python's
collections.deque).
Disadvantages of a Deque
- Memory Overhead: May consume more memory than required, especially if implemented using dynamic arrays.
- Restricted Access: Elements between the first and last cannot be directly accessed.
If you noticed a mistake or copyright issues, please contact: lebroskiofficial@proton.me