Data Structures & Algorithms / Module 1: Linear data structures
Topic 1.6
Deque
A line with two doors: in and out at both ends, able to act as a stack or a queue.
Watch: items can be added and removed at both ends, left or right, without shifting what's in the middle.
- moving now
Like a train
Carriages can be coupled or uncoupled at the front or the back of a train, but not in the middle. A deque works the same way. There are four moves: pushFront and pushBack to add, popFront and popBack to take. Press Step in the figure to see all four.
- Use only the back: the deque is a stack.
- Join at the back, leave at the front: the deque is a queue.
Its signature use: a sliding window
A deque is handy when you walk through data while keeping "the last few". For example, tracking the highest temperature of the past 7 days, every day: new readings join at the back, readings older than 7 days drop off the front. You will meet this pattern again in the sliding-window topic.
Code, for programmersA 'recently viewed' history capped at 3
const recent = []; // a deque: the back is the newest
function view(item) {
recent.push(item); // pushBack
if (recent.length > 3) recent.shift(); // popFront the oldest
}
// For big deques use a circular buffer instead of shift, which is O(n).Quiz
A deque holds [5, 7]. After pushFront(1) then popBack(), what is left?
A deque that only uses pushBack and popBack behaves like…
To keep 'the last seven days' as time moves on, the best fit is…
0 of 3 answered.
Built on
Used in
No follow-up topics yet.