Sub topic 11
Deques and Restricted Queues
This chapter assumes you know the queue ADT and the circular queue from the previous chapters, including front and size bookkeeping and modulo wrap-around. It also assumes you are comfortable with doubly linked lists. A deque generalizes the queue by allowing both ends to be used. Restricted variants then take one capability away, and GATE tests which output orders each variant can produce.
What a deque is
A deque (double-ended queue, pronounced "deck") is a sequence that supports insertion and deletion at both ends. It has four core operations:
add_front(x)inserts x before the current first element.add_rear(x)inserts x after the current last element.remove_front()deletes and returns the first element.remove_rear()deletes and returns the last element.
Most implementations also offer peek_front() and peek_rear(), which read an end without removing it, plus is_empty() and is_full() for bounded versions.
A deque contains both other structures as special cases. If you only use add_rear and remove_front, it is a queue. If you only use add_rear and remove_rear, it is a stack. Nothing in the middle is directly accessible, so the abstract interface does not allow random access.
Restricted queues
Restricting a deque means disabling one of its operations at one end. There are two standard restrictions:
| Variant | Insertion allowed at | Deletion allowed at |
|---|---|---|
| Input-restricted deque | Rear only | Front and rear |
| Output-restricted deque | Front and rear | Front only |
The names refer to which side is limited. In an input-restricted deque, input is limited to one end. In an output-restricted deque, output is limited to one end.
The diagram shows that each restricted deque can act as a queue or a stack. An input-restricted deque becomes a stack if you delete only from the rear. An output-restricted deque becomes a stack if you insert only at the front.
Implementing a deque
Circular array
The circular queue from the previous chapter extends naturally. Keep front and size. The rear element sits at (front + size - 1) % capacity. Adding at the front moves front one step backward.
class Deque:
def __init__(self, capacity):
self.a = [None] * capacity
self.front = 0
self.size = 0
def add_rear(self, x):
if self.size == len(self.a):
raise OverflowError('deque full')
self.a[(self.front + self.size) % len(self.a)] = x
self.size += 1
def add_front(self, x):
if self.size == len(self.a):
raise OverflowError('deque full')
self.front = (self.front - 1 + len(self.a)) % len(self.a)
self.a[self.front] = x
self.size += 1
def remove_front(self):
if self.size == 0:
raise IndexError('deque empty')
x = self.a[self.front]
self.a[self.front] = None
self.front = (self.front + 1) % len(self.a)
self.size -= 1
return x
def remove_rear(self):
if self.size == 0:
raise IndexError('deque empty')
i = (self.front + self.size - 1) % len(self.a)
x = self.a[i]
self.a[i] = None
self.size -= 1
return x
d = Deque(4)
d.add_rear(10)
d.add_rear(20)
d.add_front(5)
print(d.remove_rear(), d.remove_front())The program prints 20 5. After add_front(5), front has wrapped from 0 to 3, so the elements 5, 10, 20 occupy indices 3, 0, 1.
Doubly linked list
A doubly linked list with head and tail pointers supports all four operations in O(1) time. Deleting the rear of a singly linked list would take O(n) time, because you must walk to the second-to-last node. Each node therefore needs both prev and next pointers. With a singly linked list, three of the four operations are O(1), and only remove_rear is O(n).
| Representation | add_front | add_rear | remove_front | remove_rear | Notes |
|---|---|---|---|---|---|
| Circular array | O(1) | O(1) | O(1) | O(1) | Fixed capacity, overflow possible |
| Doubly linked list | O(1) | O(1) | O(1) | O(1) | Extra pointer per node, no fixed capacity |
| Singly linked list with tail | O(1) | O(1) | O(1) | O(n) | Cannot step back from tail |
A plain non-circular array with front at index 0 makes add_front cost O(n), because every element must shift one position. This is why the circular layout matters.
Deque in Python
Python's standard library provides collections.deque, which has appendleft, append, popleft, and pop. All four are O(1). Indexing into the middle is O(n), which matches the abstract interface. Calling pop or popleft on an empty deque raises IndexError.
Which output orders are possible
A GATE-style question gives an input sequence 1, 2, 3, ... n, fed in order, and asks which output sequences a restricted deque can produce. Reason from which elements are reachable at the ends.
Take an input-restricted deque with input 1, 2, 3, 4. Elements enter only at the rear, so the contents always stay in input order. Only the two ends can leave. To output 4 first, all four elements must already be inside, so the contents are 1, 2, 3, 4. After removing 4, the contents are 1, 2, 3. The next output must be 1 or 3, never 2. Therefore the sequence 4, 2, 1, 3 is impossible.
The brute-force program below enumerates every reachable output.
def input_restricted_outputs(n):
results = set()
def explore(next_in, dq, out):
if len(out) == n:
results.add(out)
return
if next_in <= n:
explore(next_in + 1, dq + (next_in,), out)
if dq:
explore(next_in, dq[1:], out + (dq[0],))
explore(next_in, dq[:-1], out + (dq[-1],))
explore(1, (), ())
return results
r = input_restricted_outputs(4)
print(len(r))
print((4, 2, 1, 3) in r)It prints 22 and False. Of the 24 permutations of four elements, the two that start with 4, 2 (namely 4, 2, 1, 3 and 4, 2, 3, 1) are unreachable. Counting by first output confirms this: 6 permutations start with 1, 6 with 2, 6 with 3, and only 4 of the 6 that start with 4.
For an output-restricted deque, the mirror argument applies. Insertions at both ends build an arrangement, and only the front leaves. The set of reachable permutations has the same size, since reversing the roles of input and output turns one structure into the other.
Common mistakes
- Confusing the names. "Input-restricted" means insertion is limited, not deletion.
- Using a singly linked list for a deque and assuming
remove_rearis O(1). - Testing full and empty with
front == rearon a circular array. Keeping asizecounter, as in the code above, avoids that ambiguity. - Forgetting the single-element case. When one element remains,
remove_frontandremove_rearreturn the same value. In a linked list, both head and tail must become null. - Treating a deque as a random-access structure. Only the ends are accessible.
Exercise
An input-restricted deque receives the input 1, 2, 3, 4 in that order. Can it produce the output 3, 1, 4, 2? If so, give the sequence of operations.
Show answer
Yes. Insert 1, 2, 3 at the rear (contents 1, 2, 3). Delete from the rear to get 3 (contents 1, 2). Delete from the front to get 1 (contents 2). Insert 4 at the rear (contents 2, 4). Delete from the rear to get 4, then delete the last element, 2. The output is 3, 1, 4, 2.
Exercise
A deque is stored in a circular array of capacity 6 with front = 0 and size = 2. After one addfront and then one removerear, what are front and size, and which indices hold the elements?
Show answer
addfront sets front to (0 - 1 + 6) % 6 = 5 and size to 3. The elements sit at indices 5, 0, 1. removerear removes the element at (5 + 3 - 1) % 6 = 1 and sets size to 2. The final state is front = 5, size = 2, with the elements at indices 5 and 0.