Data Structures & AlgorithmsModerateCognizant · Capgemini pattern

What is printed? (queue using a fixed array without wrap-around)

What is printed? (queue using a fixed array without wrap-around)
N = 4; q = [None] * N; front = rear = 0; log = []
def enq(x):
    global rear
    if rear == N: log.append("full"); return
    q[rear] = x; rear += 1
def deq():
    global front
    x = q[front]; front += 1; return x
for x in (1, 2, 3, 4): enq(x)
deq(); deq()
enq(5)
print(log, rear - front)
  1. A. [] 3
  2. B. ['full'] 3
  3. C. ['full'] 2
  4. D. [] 2

Correct answer: C. ['full'] 2

A linear array queue never reuses the slots freed at the front: after two dequeues there are only 2 items, yet rear == N, so enqueue 5 is rejected ('false overflow'). A circular queue with (rear + 1) % N fixes this.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic