algoritmauzmanı
Sign in
TREN
5.7Exam Practice
Lesson 5.7.1

Queue: exam questions and answers

This page is the exam practice for the queue section. University exams ask about queues in a few recurring ways: comparing linear and circular queues, tracing front and rear after a series of operations, telling a full queue from an empty one, coding enqueue and dequeue, building a queue from two stacks, and tracing a priority queue. Here you get original questions of each kind with step-by-step answers.

What you will learn
  • How to trace front, rear and count in linear and circular arrays with a table
  • How to code enqueue and dequeue with an array, a linked list and a circular linked list
  • How to compare priority queues, the two-stack queue and the cost of each operation
25 min

1Conceptual questions

The questions are original, but their types were picked from the kinds that often appear in published midterm and final exams of universities in Turkey and abroad. Solve each question yourself first, then open the box and compare your answer. Write a queue with the front on the left and the rear on the right: in the queue [4, 7, 1], 4 is at the front. The function names in the code match those in the lessons on the array queue, the circular queue and the linked-list queue.

1What principle does a queue follow? At which ends are elements added and removed? Name three places where computers use a queue.Midterm · concept

A queue follows the principle: first in, first out. adds an element at the rear (), and removes one from the front (). The two operations work at two different ends.

  • Print queues: documents are printed in the order they were sent.
  • Process scheduling in an operating system: runs processes in turn from a queue.
  • Network and keyboard buffers: incoming packets and keys are handled in the order they arrive.

Breadth-first search in a graph also uses a queue: near nodes are visited first, then the ones farther away. See What is a queue?.

2What is the difference between a linear array queue and a circular queue? What is the advantage of the circular queue?Midterm · concept

In a linear queue front and rear only move forward. Dequeue frees cells at the front, but they are never used again. When rear reaches the end of the array, the queue counts as full even if the front cells are empty. In a circular queue the index goes back to the start with mod when it reaches the end, so freed cells are used again.

Linear queueCircular queue
Moving an indexrear++, front++(rear + 1) % CAPACITY
Empty cells at the frontWastedUsed again
Counts as full whenrear == CAPACITY - 1count == CAPACITY
ShiftingNone (or O(n) on every dequeue)None

One way to fix the linear queue is to shift the elements left on every dequeue, but that makes dequeue O(n). A circular queue wastes no space and keeps every operation . See Wasted cells.

3If a circular queue keeps only front and rear (no count), why can a full queue not be told apart from an empty one? How is this solved?Midterm · concept

Let rear point at the last element. In an empty queue front is the cell after rear: (rear + 1) % n == front. Fill the queue with n elements and rear comes around to the cell just before front again; the condition is the same. The two indexes have the same values, yet one queue is empty and the other is full.

  1. Keep the element count: count == 0 means empty, count == n means full. The code on this site does this.
  2. Always leave one cell empty: at most n - 1 elements are stored. In this method rear usually points at the first free cell; front == rear means empty and (rear + 1) % n == front means full.
  3. Keep a flag for whether the last operation was an enqueue or a dequeue: when the indexes meet, the queue is full if it was an enqueue and empty if it was a dequeue.

All three keep the operations O(1). Leaving a cell empty costs one element of space; count updates one more number on each operation. See Full or empty?.

4Compare a stack and a queue. What is a deque (double-ended queue), and how can a stack and a queue be defined in terms of it?Final · concept

A stack works and a queue works . In a stack adding and removing happen at the same end; in a queue adding is at the rear and removing at the front. A allows all four operations: push at the front or back, pop from the front or back.

StructureAddRemoveAs a deque
StackTopToppushBack + popBack
QueueRearFrontpushBack + popFront
DequeBoth endsBoth endsAll four operations

So a stack and a queue are each a deque with restricted operations. That is why Java's java.util.ArrayDeque class is used both as a stack and as a queue. See Deque: double-ended queue.

2Tracing questions

5A linear array queue with capacity 5 is empty (front = 0, rear = -1). You run enqueue 10, enqueue 20, enqueue 30, dequeue, dequeue, enqueue 40, enqueue 50, enqueue 60. Write front and rear after each operation. Which operation fails, and how many elements are in the queue at that moment?Midterm · trace

enqueue 60 fails because rear has reached 4, which is CAPACITY - 1. At that moment the queue holds only 3 elements (30, 40, 50); cells 0 and 1 are empty, but a linear queue cannot use them.

OperationReturnsfrontrearQueue (front → rear)
enqueue 100010
enqueue 200110, 20
enqueue 300210, 20, 30
dequeue101220, 30
dequeue202230
enqueue 402330, 40
enqueue 502430, 40, 50
enqueue 60full2430, 40, 50

In a linear queue the element count is rear - front + 1: 4 - 2 + 1 = 3. This question shows why a circular queue is needed. See Wasted cells.

6A circular queue with capacity 5 is empty (front = 0, rear = -1, count = 0). You run enqueue 1, 2, 3, 4; dequeue, dequeue; enqueue 5, 6, 7, 8; dequeue. Write front, rear and count at each step. What is in the items array at the end, and what is the order of the queue?Midterm · trace

enqueue 8 fails because count is 5 at that moment. At the end front = 3, rear = 1 and count = 4. The items array holds 6, 7, 3, 4, 5 from left to right, but the queue is read starting at front: 4, 5, 6, 7. The 3 in cell 2 is no longer part of the queue.

OperationReturnsfrontrearcount
enqueue 1, 2, 3, 4034
dequeue1133
dequeue2232
enqueue 5243
enqueue 620 (wrapped)4
enqueue 7215
enqueue 8full215
dequeue3314

rear went from 4 to 0 with (4 + 1) % 5 = 0. That is why it is hard to say full or empty by looking at front and rear; count settles it with one comparison.

7Some textbooks let rear in a circular queue point at the cell after the last element, the first free cell, and always leave one cell empty. How do you compute the element count then? For n = 8, how many elements are there when (a) front = 2, rear = 6; (b) front = 6, rear = 2; (c) front = rear = 5? How many elements can the queue hold at most?Midterm · trace

The element count is (rear - front + n) % n. The + n keeps the difference from going negative when rear has wrapped around to the left of front.

CaseCalculationElementsUsed cells
(a) front 2, rear 6(6 - 2 + 8) % 842, 3, 4, 5
(b) front 6, rear 2(2 - 6 + 8) % 846, 7, 0, 1
(c) front 5, rear 5(5 - 5 + 8) % 80none, the queue is empty

Since one cell always stays empty, the queue holds at most n - 1 = 7 elements. It is full when (rear + 1) % n == front. In this site's code rear points at the last element; there the formula is (rear - front + 1 + n) % n, but it gives 0 for a full queue too, so count is kept as well.

8A queue built from two stacks (inbox and outbox) runs enqueue 1, enqueue 2, dequeue, enqueue 3, enqueue 4, dequeue, dequeue, enqueue 5, dequeue. What does each dequeue return, what is left in the two stacks, and how many pushes and pops happen in total?Final · trace

The dequeues return 1, 2, 3 and 4 in that order. At the end inbox holds 5 and outbox is empty. 17 stack operations happen in total. Elements are moved only when outbox is empty, and each moved element costs one pop and one push.

OperationReturnsinbox (top on the right)outbox (top on the right)Stack operations
enqueue 1, enqueue 21 2empty2
dequeue1empty2move 4 + pop 1 = 5
enqueue 3, enqueue 43 422
dequeue23 4empty1
dequeue3empty4move 4 + pop 1 = 5
enqueue 5541
dequeue45empty1

Each element goes through at most four stack operations: push onto inbox, pop from inbox, push onto outbox, pop from outbox. For 5 elements the limit is 20; we stopped at 17 because 5 has not left yet. That is why each operation costs O(1). See Queue with two stacks.

9A linked-list queue is empty. You run enqueue 7, enqueue 4, dequeue, dequeue, enqueue 9. Write the node front and rear point at after each step. What happens if dequeue does not set rear to NULL when it removes the last node?Midterm · trace

At the end the queue has one node: front and rear both point at 9. The real trap is the fourth step: when 4 leaves, the list is empty, and rear must become NULL along with front.

OperationReturnsfrontrear
enqueue 777
enqueue 474
dequeue744
dequeue4NULLNULL
enqueue 999

If rear is not set to NULL, it points at the freed node 4. The next enqueue does not see an empty queue, writes into freed memory with rear->next = node, and front stays NULL. The new element never shows up in the queue. See Linked-list dequeue.

3Code reading questions

Code for the next question (Python, circular queue with front, rear and count fields):

q = CircularQueue(5)for x in (3, 8, 5, 2):    q.enqueue(x)for _ in range(3):    x = q.dequeue()    if x % 2 == 1:        q.enqueue(x * 2)print(q.peek(), q.count, q.front, q.rear)while not q.is_empty():    print(q.dequeue(), end=" ")
10What does the code above print? Why do front and rear have these values on the first print line?Midterm · code reading

The first line is 2 3 3 0 and the second is 2 6 10. The loop doubles odd numbers and puts them back at the rear, and drops even numbers. rear looks smaller than front because it wrapped from 4 to 0.

StepQueue (front → rear)frontrearcount
Four enqueues3, 8, 5, 2034
x = 3, odd: enqueue 68, 5, 2, 6144
x = 8, even5, 2, 6243
x = 5, odd: enqueue 102, 6, 10303

peek gives the 2 at the front without removing it. The last loop empties the queue and prints 2, 6, 10.

Code for the next question (C, circular queue):

bool enqueue(struct Queue* q, int value) {    if (q->count == CAPACITY) return false;    q->rear = q->rear + 1 % CAPACITY;    q->items[q->rear] = value;    q->count++;    return true;}
11This enqueue function has a bug. What is it, and when does it show up? Fix it.Midterm · code reading

The bug is operator precedence. % is applied before +, so the line runs as q->rear + (1 % CAPACITY), which is q->rear + 1. rear never wraps.

It shows up when elements have left the front before the queue fills. For example, with capacity 5, after 5 enqueues and 1 dequeue count is 4 and rear is 4. The next enqueue sets rear to 5 and writes to items[5], outside the array. The fix is parentheses:

q->rear = (q->rear + 1) % CAPACITY;

Code for the next question (Python, the library queue collections.deque):

from collections import deque def mystery(n, k):    q = deque(range(1, n + 1))    removed = []    while len(q) > 1:        for _ in range(k - 1):            q.append(q.popleft())        removed.append(q.popleft())    return removed, q[0]
12What does mystery(7, 3) return? What does the function do?Final · code reading

It returns ([3, 6, 2, 7, 5, 1], 4). The numbers 1 to n sit in the queue like a circle. In each round k - 1 people are taken from the front and put at the rear, and the k-th person is removed. The last one left is returned. This is known as the Josephus problem.

RoundQueue after rotatingRemovedQueue left
13, 4, 5, 6, 7, 1, 234, 5, 6, 7, 1, 2
26, 7, 1, 2, 4, 567, 1, 2, 4, 5
32, 4, 5, 7, 124, 5, 7, 1
47, 1, 4, 571, 4, 5
55, 1, 451, 4
61, 414

Each removal takes k - 1 rotations and one dequeue; n - 1 people leave, so the time is O(n · k).

4Code writing questions

13Write enqueue and dequeue in C for a circular array queue. The struct is struct Queue { int items[CAPACITY]; int front; int rear; int count; }, and an empty queue has front = 0, rear = -1, count = 0.Midterm · code writing

Enqueue first checks for a full queue, moves rear forward with mod, writes, and increases count. Dequeue first checks for an empty queue, reads the value at front, moves front forward with mod, and decreases count.

bool enqueue(struct Queue* q, int value) {    if (q->count == CAPACITY) return false;   // queue is full    q->rear = (q->rear + 1) % CAPACITY;       // wrap to the start at the end    q->items[q->rear] = value;    q->count++;    return true;} bool dequeue(struct Queue* q, int* value) {    if (q->count == 0) return false;          // queue is empty    *value = q->items[q->front];    q->front = (q->front + 1) % CAPACITY;    q->count--;    return true;}

A common mistake is mixing up the order in dequeue: if front moves first, the element after the front one is read. Both operations take . See Circular queue enqueue and dequeue.

14Write enqueue and dequeue in C for a linked-list queue. The struct is struct Queue { struct Node* front; struct Node* rear; }.Midterm · code writing

Enqueue links the new node after rear; if the queue is empty, front points at the new node too. Dequeue removes front; if the list becomes empty, rear is set to NULL as well.

bool enqueue(struct Queue* q, int value) {    struct Node* node = malloc(sizeof(struct Node));    if (node == NULL) return false;   // out of memory    node->data = value;    node->next = NULL;    if (q->rear == NULL)              // empty queue        q->front = node;    else        q->rear->next = node;         // link after the last node    q->rear = node;    return true;} bool dequeue(struct Queue* q, int* value) {    if (q->front == NULL) return false;   // queue is empty    struct Node* temp = q->front;    *value = temp->data;    q->front = temp->next;    if (q->front == NULL)             // the last node left        q->rear = NULL;    free(temp);    return true;}

Since the two ends are held in separate pointers, both operations take O(1). Without rear, enqueue would walk to the end every time and take O(n). There is no capacity; enqueue returns false only if malloc fails.

15Write a queue on a circular linked list with a single pointer: the struct holds only rear. How are enqueue and dequeue written in C?Final · code writing

In a circular list the last node points at the first; the front node is rear->next. So one pointer reaches both ends in O(1). Enqueue puts the new node between rear and rear->next and makes it rear. Dequeue removes rear->next.

bool enqueue(struct Queue* q, int value) {    struct Node* node = malloc(sizeof(struct Node));    if (node == NULL) return false;    node->data = value;    if (q->rear == NULL) {        node->next = node;             // a single node points to itself    } else {        node->next = q->rear->next;    // the new node points to the front        q->rear->next = node;    }    q->rear = node;    return true;} bool dequeue(struct Queue* q, int* value) {    if (q->rear == NULL) return false;  // queue is empty    struct Node* head = q->rear->next;  // the front node    *value = head->data;    if (head == q->rear)                // there was a single node        q->rear = NULL;    else        q->rear->next = head->next;    free(head);    return true;}

There are two special cases: the first element in an empty queue points at itself, and when the only node leaves, rear becomes NULL. See Queue with one pointer.

16Using only queue operations (enqueue, dequeue, is empty) and one stack, write a function that reverses a queue.Midterm · code writing

Until the queue is empty, elements are taken from the front and onto the stack. Then, until the stack is empty, they are and added back to the queue. Since the stack is , the last one in, the last element of the queue, comes back first.

def reverse(q):    s = []                       # helper stack    while not q.is_empty():        s.append(q.dequeue())    # the front element goes onto the stack    while s:        q.enqueue(s.pop())       # last in comes back first

If the queue is [1, 2, 3, 4], the stack (bottom → top) becomes [1, 2, 3, 4], and after moving back the queue is [4, 3, 2, 1]. Each element sees one dequeue, one push, one pop and one enqueue; time and extra memory are O(n).

17Write a queue class using two stacks (Java). Explain the worst-case and amortized cost of dequeue.Final · code writing

Enqueue always pushes onto inbox. Dequeue pops from outbox; if outbox is empty, every element in inbox is moved over first. The move reverses the order, so the oldest element ends up on top of outbox.

class TwoStackQueue {    java.util.ArrayDeque<Integer> inbox = new java.util.ArrayDeque<>();    java.util.ArrayDeque<Integer> outbox = new java.util.ArrayDeque<>();     void enqueue(int value) {        inbox.push(value);    }     int dequeue() {        if (outbox.isEmpty()) {            if (inbox.isEmpty()) throw new IllegalStateException("queue is empty");            while (!inbox.isEmpty())                outbox.push(inbox.pop());   // the order flips        }        return outbox.pop();    }}

A single dequeue takes O(n) if inbox holds n elements. But each element is moved at most once, so n operations take O(n) in total and each costs O(1). Moving while outbox still holds elements breaks the order.

5Priority queue questions

18A priority queue built on a linked list sorted from small to large is empty (a smaller value has higher priority; among equals, the earlier one leaves first). You run insert 5, insert 2, insert 8, insert 2, insert 1, removeMin, removeMin. Write the list after each step.Midterm · priority queue

Insert walks the list until it finds the first node larger than the new value and puts the new node before it. The new node goes behind equal values, so the 2 that came first stays in front. Removal is from the head. To tell the two 2s apart, call the second one 2'.

OperationList (head → tail)ReturnsNote
insert 55into the empty list
insert 22, 5at the head
insert 82, 5, 8at the tail
insert 2'2, 2', 5, 8behind the equal one
insert 11, 2, 2', 5, 8at the head
removeMin2, 2', 5, 81from the head
removeMin2', 5, 82the 2 that came first

In the worst case insert walks the whole list, O(n). Removal is O(1). See Linked-list insert.

19A priority queue can be built with four structures: an unsorted array, a sorted array, a sorted linked list and a heap. Compare the cost of insert, removing the highest priority element, and looking at it.Final · priority queue

With sorted structures the work falls on insert; with an unsorted one it falls on removal. A heap balances both at O(log n).

StructureInsertRemoveLook (peek)
Unsorted arrayO(1), add at the endO(n), search and close the gapO(n)
Sorted array (large to small)O(n), shiftingO(1), from the endO(1)
Sorted linked listO(n), find the placeO(1), from the headO(1)
HeapO(log n)O(log n)O(1)

With few elements and frequent removals a sorted structure is enough. With many elements and mixed operations a heap is chosen; n operations then take O(n log n) instead of O(n²). See Which structure?.

20Write insert and removeMin in C for a priority queue on an array sorted from large to small. Among equal priorities, the earlier one must leave first.Final · priority queue

The highest priority (smallest) element is at the end of the array; removal only decreases size. Insert walks from the end toward the start, shifts the values smaller than or equal to the new one a cell to the right, then writes into the opened cell.

bool insert(struct PQ* pq, int value) {    if (pq->size == CAPACITY) return false;      // queue is full    int i = pq->size - 1;    while (i >= 0 && pq->items[i] <= value) {    // higher priority and equal ones move right        pq->items[i + 1] = pq->items[i];        i--;    }    pq->items[i + 1] = value;    pq->size++;    return true;} bool removeMin(struct PQ* pq, int* value) {    if (pq->size == 0) return false;             // queue is empty    *value = pq->items[--pq->size];              // the highest priority is at the end    return true;}

Shifting the equal values matters: with < instead of <=, the new element lands to the right of its equals, closer to the end, and leaves before them. Insert is O(n) and removal O(1). See Array insert.

21An emergency room sorts patients into three priority groups: red (0), yellow (1), green (2). Within a group, patients are seen in order of arrival. Write this using one queue per group. If the arrivals are P1 green, P2 yellow, P3 green, P4 red, P5 yellow, in what order are the patients seen?Final · priority queue

The order is P4, P2, P5, P1, P3. Each group is a queue of its own. Removal starts at the highest priority group and takes the front of the first queue that is not empty.

from collections import deque class GroupedQueue:    def __init__(self, levels):        self.queues = [deque() for _ in range(levels)]   # 0 is the highest priority     def insert(self, name, priority):        self.queues[priority].append(name)      # to the rear of its own group     def remove_min(self):        for q in self.queues:                   # start from the highest priority group            if q:                return q.popleft()        raise IndexError("queue is empty")

With g groups, insert takes O(1) and removal O(g); since g is fixed, both count as O(1). When there are few fixed priority values, this structure beats both a sorted list and a heap, and it keeps arrival order among equals by itself.

6Complexity and comparison questions

22Compare queues built on a linear array, a circular array, a linked list, a circular linked list with one pointer, and two stacks, in terms of enqueue, dequeue and memory.Midterm · complexity

Except for the two-stack queue, every structure does enqueue and dequeue in ; the differences are in memory and limits.

StructureenqueuedequeueMemory and limit
Linear arrayO(1)O(1)Cells at the front are wasted
Circular arrayO(1)O(1)Fixed , no wasted space
Linked list (front, rear)O(1)O(1)No limit, one pointer per node
Circular linked list (rear)O(1)O(1)No limit, one pointer in the struct
Two stacksO(1)Amortized O(1), worst O(n)The total of the two stacks

In a linear array "full" means less than it says: the queue counts as full when rear reaches the end, even with few elements inside. See Array or linked list?.

23If a linked-list queue keeps only front, what do enqueue and dequeue cost? And if the list is built the other way round, with the front at the tail?Final · complexity

With only front, dequeue removes the head, O(1). But enqueue walks the whole list to add at the end, O(n).

Keptenqueuedequeue
Only front (head)O(n)O(1)
front (head) + rear (tail)O(1)O(1)
Front at the tail, rear at the headO(1), add at the headO(n), remove from the tail

Built the other way round, the problem moves: in a singly linked list, removing from the tail means walking from the head to find the node before the last. That is why the front is kept at the head, the rear at the tail, and both pointers are stored.

24You want to write a deque on a singly linked list (keeping head and tail). Which operation will not be O(1)? How do you fix it?Final · comparison

Popping from the back will not be O(1). tail points at the last node, but there is no link from the last node to the one before it; finding that one means walking from the head, O(n).

OperationSingly linked listDoubly linked listCircular array
Push frontO(1)O(1)O(1)
Push backO(1)O(1)O(1)
Pop frontO(1)O(1)O(1)
Pop backO(n)O(1)O(1)

The fix is a doubly linked list: each node also points at the one before it, so tail = tail.prev removes the last node in O(1). Or the deque is written on a circular array. See Deque.

7Try it

A circular queue with capacity 6 has front = 4 and count = 3. At which index is the last element?

Show the answer

The answer is A. The elements are in cells 4, 5 and 0: (4 + 3 - 1) % 6 = 0.

What must happen when dequeue removes the last node of a linked-list queue?

Show the answer

The answer is B. Once the list is empty, rear must not point at the freed node. Otherwise the next enqueue writes into it.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.