When Everything Feels Urgent

A crowded bazaar in warm golden light, a swirling vortex of fire at its center, with Arjun in orange robes standing in the foreground facing the chaos.
The Burning Bazaar of Chintan — when every stall is screaming for help, the real skill is knowing which flame to put out first.
When Everything Feels Urgent — Learning Priority Queues in the Burning Bazaar
Gurukul Tale XI

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.

Arjun: “If I save the cloth merchant, the oil seller’s stall explodes. If I run to the storage house, the children might get hurt.
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.

Young Arjun walking through a burning bazaar, surrounded by panicking people and falling pottery, looking overwhelmed by the chaos
Too many emergencies, one small human — the classic problem of limited attention and unlimited panic.

🧊 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.

Guru: “You are trying to save everyone at once, Shishya. That is not strategy. That is panic.
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.”

Guru Bodhi standing in a burning street, golden priority symbols floating frozen above different fires as people look on
Guru Bodhi freezes the chaos and tags each problem with a glowing symbol — not every fire has the same priority.

📜 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.”

Glowing golden pyramid of interconnected nodes, brightest at the top, floating in a dim temple-like space
A heap: a pyramid of priorities, where the brightest, most important task always lives at the top.

🧠 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.

Python - Simple Emergency Priority Queue
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.

Elegant wooden desk with scrolls and tablets neatly arranged, some glowing red and gold to indicate higher priority
The royal priority desk — scrolls are not read in arrival order, but in the order that matters most to the kingdom.

⚙️ Heap Mechanics — Bubble Up & Extract Max

A heap keeps its pyramid shape using two simple rituals:

  1. 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.
  2. 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.

Python - Max-Heap with Bubble-Up and Sink-Down
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.

Golden spheres arranged in a pyramid in space, with one bright sphere rising upward from lower levels toward the top
Bubble Up & Extract Max — new emergencies climb to their true importance, and the most urgent one is always taken from the top.

📜 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:

  1. He listed all fires and problems he knew about.
  2. He gave each one a clear priority score — based on danger, people, and spread.
  3. He always acted on the current highest-priority task.
  4. 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.