Imagine you have tasks arriving in order and you want to process them in the same order. Why is a queue better than a simple list for this?
Think about how tasks should be handled when they come in and how order matters.
A queue follows the first-in, first-out rule, which matches how tasks should be processed in order. Lists do not efficiently support this behavior because removing from the front is slow.
Given the following Python code using a queue, what will be printed?
from collections import deque q = deque() q.append('A') q.append('B') q.append('C') print(q.popleft()) print(q.popleft()) q.append('D') print(list(q))
Remember that popleft() removes from the front of the queue.
The queue starts empty. We add 'A', 'B', 'C'. Removing twice from the front gives 'A' then 'B'. Adding 'D' puts it at the end. The queue now has 'C' and 'D'.
Consider this code snippet:
tasks = ['task1', 'task2', 'task3']
while tasks:
current = tasks.pop(0)
print(current)What is the main problem with this approach when the list is very large?
Think about what happens inside the list when you remove the first element.
Using pop(0) on a list removes the first element but shifts all other elements left, which takes time proportional to the list size. This is inefficient for large lists.
Choose the scenario where using a queue data structure is the most natural and efficient solution.
Think about the order in which people are served in a line.
A queue models the first-come, first-served order perfectly, like customers waiting in line. Other options describe different data structures or problems.
In graph traversal, why do BFS algorithms use a queue instead of a stack or list?
Think about how BFS explores nodes level by level.
BFS uses a queue to visit nodes in the order they are found, which means it explores all neighbors at the current level before going deeper, matching the first-in, first-out behavior of a queue.