Data Structures · Visualization
Priority Queue: Insert
Priority Queue
Inserting into a priority queue adds a new item along with its priority, then relies on the underlying heap to place it correctly so the highest (or lowest) priority item stays accessible at the top. Time: O(log n). Space: O(1) extra.
Big-O: Insert/serve O(log n).
Priority Queue: Insert
Priority QueueInserting into a priority queue adds a new item along with its priority, then relies on the underlying heap to place it correctly so the highest (or lowest) priority item stays accessible at the top. This is exactly the same as inserting into a heap: add at the end, then bubble it up into position.
How Insert Works
- Add the new item to the end of the underlying heap array.
- Compare its priority with its parent's priority.
- Swap upward as long as it has higher priority than its parent (for a max-priority queue).
- Stop once it settles into a valid position.
Insert Worked Example
Input: Insert task D(7) into max-priority queue with heap [C(5), A(3), B(1)]
- Add D(7) to the end: [C(5), A(3), B(1), D(7)]
- D's parent is A(3): 7 > 3, swap → [C(5), D(7), B(1), A(3)]
- D's new parent is C(5): 7 > 5, swap → [D(7), C(5), B(1), A(3)]
Output: [D(7), C(5), B(1), A(3)]
Press ▶ Run to watch it step by step.
import heapq
# heapq is a MIN-heap by default
tasks = []
heapq.heappush(tasks, (3, "low"))
heapq.heappush(tasks, (1, "urgent"))
heapq.heappush(tasks, (2, "normal"))
while tasks:
priority, name = heapq.heappop(tasks)
print(priority, name) # highest priority first
# For max-priority: push (-p, item)
# example: priority queueBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Insert Time & Space Complexity
When to Use Insert
- Adding a new process to an OS scheduler's ready queue
- Adding a new edge/node option while running Dijkstra's algorithm
- Registering a new event at a given simulation time
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.