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)- A. [] 3
- B. ['full'] 3
- C. ['full'] 2
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A warehouse scores a shelf by adding, over every contiguous run of boxes, the weight of the lightest box in the run. Two monotonic-stack…
- A monotonic deque reports the maximum of every window of 3 readings and counts deque removals. What is printed? python from collections…
- atmost(s, k) counts substrings with at most k distinct letters using a sliding window and a frequency map. What is printed? python def…
- A KMP prefix (failure) table and an overlapping-occurrence counter. What is printed? python def prefix(p): pi = [0] len(p) for i in…
- Z-array (z[i] = length of the longest common prefix of s and s[i:]). What is printed? python def z(s): n = len(s); z = [0] n; l = r = 0…
- Rabin–Karp over digits with base 10 and a deliberately tiny modulus 7. It returns (true matches, spurious hash hits). What is printed?…