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.

6 min · beginner

Watch: items can be added and removed at both ends, left or right, without shifting what's in the middle.

frontback57
  • moving now
Step 1 of 7

A deque: a line you can add to and take from at both ends.

A deque combines a stack and a queue: both ends can be used to add and remove, all in O(1).

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

  1. A deque holds [5, 7]. After pushFront(1) then popBack(), what is left?

  2. A deque that only uses pushBack and popBack behaves like…

  3. To keep 'the last seven days' as time moves on, the best fit is…

0 of 3 answered.