When Everything Feels Urgent
When Everything Feels Urgent — Learning Priority Queues in the Burning Bazaar
A fire breaks out in the royal bazaar, and Arjun discovers that not all emergencies are equal — some must be handled now, others can wait. Guru Bodhi uses the chaos to teach him the idea behind priority queues and heaps: always pull the most important task first.
Characters: Arjun, Guru Bodhi · Arc: Intermediate · Pattern: Priority Queues, Heaps, Bubble Up, Extract Max
🔥 Sutra of the Firestorm — When Everything Feels Important
The sun hung high above the Grand Bazaar of Chintan when the first scream tore through the air.
One stall’s roof had caught fire. Then another oil lamp fell. A spice cart overturned. Somewhere, a child cried. Pots rolled, cloth burned, people shouted — each voice claiming, “Mine is urgent! Help here first!”
Arjun stood in the middle of the market, robe whipping in the heat, brain melting faster than the wax candles around him.
Everything is on fire. How do I choose?”
This wasn’t just a physical problem. It was the same feeling he had in code and in life: a dozen tasks screaming “ASAP”, no clear order, and a brain trying to juggle too much at once.
🧊 Sutra of Frozen Sparks — Ordering Chaos
As Arjun spun in circles, a staff struck the stone floor with a ringing clang. The sparks from a falling lamp slowed, then stopped in mid-air.
Guru Bodhi stood at the edge of the fireline, palm raised. All around them, flaming debris, smoke, and people’s movements hung like a painting.
What you need is a way to always know: who or what needs you next.”
With a gesture, glowing symbols appeared above different stalls: a blazing 🔥 above the oil depot, a 🧒 above the trapped children, a dimmer 💰 above a burning moneylender’s sign.
“Each symbol,” Guru said, “is a priority. Some flames can burn a little longer. Some will destroy the whole bazaar if ignored even for a breath.”
📜 Sutra of the Queue — But With Priorities
Guru Bodhi drew in the air, and a glowing line of tasks appeared like spirits waiting their turn:
- 🔥 “Oil storage about to explode.”
- 🧒 “Child trapped near spice stall.”
- 💰 “Merchant’s money box on fire.”
- 🧵 “Cloth stall smoldering.”
“If you use a normal queue,” Guru said, “you help in the order they arrived. First in, first out. But in a crisis, time must bend around importance.”
“We need a structure that always gives you the most important task next. Whether it arrived five minutes ago or just now.”
“That structure is called a priority queue.”
🧠 The Bazaar Queue — Coding Priorities
In code, a priority queue is usually implemented with a heap. In Python, that’s the
heapq module.
Let’s model Arjun’s emergency list. Higher priority means more dangerous.
import heapq
# In Python, heapq is a *min*-heap, so we store negative priorities
# so that larger priority values come out first.
class EmergencyQueue:
def __init__(self):
self._heap = [] # each item: (-priority, description)
def add(self, priority, description):
heapq.heappush(self._heap, (-priority, description))
def next_task(self):
if not self._heap:
return None
priority, description = heapq.heappop(self._heap)
return -priority, description
queue = EmergencyQueue()
queue.add(priority=100, description="Oil storage about to explode")
queue.add(priority=90, description="Child trapped near stall")
queue.add(priority=20, description="Cloth stall burning")
print(queue.next_task()) # (> 100, "Oil storage about to explode")
print(queue.next_task()) # (> 90, "Child trapped near stall")
Internally, the heap keeps the most important item at the top. We never sort the whole list. Instead, the structure reorganizes itself just enough to preserve the “highest priority first” rule.
🏛️ Real-World Scroll — The Royal Priority Desk
In the palace, petitions from citizens arrived in thick scrolls. If the king read them in arrival order, he’d waste mornings on disputes about goats while wars burned at the border.
So a royal clerk had a priority desk: petitions marked with glowing seals — royal emergency, city emergency, village matter, personal complaint. The clerk always placed the highest seal at the top of the stack.
That’s exactly what a priority queue does for your tasks, threads, background jobs, or alarms: it makes sure the right thing reaches the king (or CPU) next.
⚙️ Heap Mechanics — Bubble Up & Extract Max
A heap keeps its pyramid shape using two simple rituals:
- Bubble Up (heapify-up): when a new emergency arrives, it’s added at the bottom and then “bubbles up” if its priority is higher than its parent.
- Extract Max (or Min): when you handle the most urgent task, you remove the root, move the last element to the top, and let it “sink down” to its proper place.
That’s how we preserve the rule: the top is always the current most important thing we know about.
class MaxHeap:
def __init__(self):
self.data = [] # store (priority, description)
def push(self, priority, description):
self.data.append((priority, description))
self._bubble_up(len(self.data) - 1)
def pop_max(self):
if not self.data:
return None
self._swap(0, len(self.data) - 1)
item = self.data.pop()
self._sink_down(0)
return item
def _bubble_up(self, idx):
while idx > 0:
parent = (idx - 1) // 2
if self.data[idx][0] <= self.data[parent][0]:
break
self._swap(idx, parent)
idx = parent
def _sink_down(self, idx):
n = len(self.data)
while True:
left = 2 * idx + 1
right = 2 * idx + 2
largest = idx
if left < n and self.data[left][0] > self.data[largest][0]:
largest = left
if right < n and self.data[right][0] > self.data[largest][0]:
largest = right
if largest == idx:
break
self._swap(idx, largest)
idx = largest
def _swap(self, i, j):
self.data[i], self.data[j] = self.data[j], self.data[i]
Arjun imagined each new emergency as a glowing orb added to a pyramid. If it was more dangerous than the orb above it, they swapped places until the pyramid reflected reality again.
📜 Sutra of Action — How Arjun Now Faces “Urgent” Days
When time flowed again, Arjun did not run randomly. He moved like a cursor through a heap:
- He listed all fires and problems he knew about.
- He gave each one a clear priority score — based on danger, people, and spread.
- He always acted on the current highest-priority task.
- As new fires appeared, he inserted them into the structure instead of panicking.
The bazaar still burned. But now it burned according to a plan — and piece by piece, the worst disasters were averted first.