Skip to content

Priority Queue Using Heaps

Get access to track progress Get access to bookmark
Asset Pricingx / 34
Behavioral Questionsx / 7
Brain Teasersx / 77
Derivatives Theoryx / 107
Digital Assets - Cryptox / 82
Energy Tradingx / 55
Linear Algebrax / 24
Machine Learningx / 62
Math Questionsx / 49
Probability and Statisticsx / 204
Programmingx / 54
Totalx / 755
Your task is to implement a Priority Queue using a binary heap data structure. The Priority Queue should support insertion, deletion, and retrieval of the element with the highest priority. To read more about the Priority Queue, check out the Hint button.
class PriorityQueue:

def __init__(self):
pass

def insert(self, element: int) -> None:
pass

def delete(self) -> int:
pass

def peek(self) -> int:
pass

def _heapify_up(self) -> None:
pass

def _heapify_down(self) -> None:
pass

Methods
  • __init__(): Initializes the Priority Queue.
  • insert(element: int): Inserts an element into the Priority Queue while maintaining the heap property.
  • delete(): Removes and returns the element with the highest priority (maximum value for max-heap, minimum value for min-heap).
  • peek() -> int: Returns the element with the highest priority without removing it from the Priority Queue.
  • _heapify_up(): Called after an insert operation. If the max heap condition is violated due to the newly inserted element, this method adjusts the heap to restore the max heap property.
  • _heapify_down(): Called after a delete operation. If the max heap condition is violated due to the swap and removal of the root, this method adjusts the heap to restore the max heap property.
Example
pq = PriorityQueue()

pq.insert(3)
pq.insert(1)
pq.insert(4)
print(pq.peek()) # Should return 4 if max-heap, 1 if min-heap
pq.delete()
print(pq.peek()) # Should return 3 if max-heap, 1 if min-heap

Note
You can assume that the delete() and peek() methods will not be called on an empty Priority Queue.
class PriorityQueue:

def __init__(self):
self.heap = []

def insert(self, element):
self.heap.append(element)
self._heapify_up()

def delete(self):
if len(self.heap) == 0:
return None
if len(self.heap) == 1:
return self.heap.pop()

root = self.heap[0]
self.heap[0] = self.heap.pop()
self._heapify_down()
return root

def peek(self):
return self.heap[0] if self.heap else None

def _heapify_up(self):
index = len(self.heap) - 1
while index > 0:
parent_index = (index - 1) // 2
if self.heap[index] > self.heap[parent_index]:
self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index]
index = parent_index
else:
break

def _heapify_down(self):
index = 0
while index < len(self.heap):
left_child_index = 2 * index + 1
right_child_index = 2 * index + 2

# Find the maximum child index
if left_child_index < len(self.heap) and right_child_index < len(self.heap):
max_child_index = left_child_index if self.heap[left_child_index] > self.heap[right_child_index] else right_child_index
elif left_child_index < len(self.heap):
max_child_index = left_child_index
else:
break

# Swap if the child is greater than the parent
if self.heap[max_child_index] > self.heap[index]:
self.heap[max_child_index], self.heap[index] = self.heap[index], self.heap[max_child_index]
index = max_child_index
else:
break


# Test the Priority Queue implementation
pq = PriorityQueue()
pq.insert(3)
pq.insert(1)
pq.insert(4)
assert pq.peek() == 4 # Should return 4 for max-heap
assert pq.delete() == 4 # Should return 4 for max-heap
assert pq.peek() == 3 # Should return 3 for max-heap

print("Priority Queue implementation is working correctly.")
Python scratchpad
# Run Python right here in your browser
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
    return []

print(two_sum([2, 7, 11, 15], 9))  # [0, 1]
Run Python in your browser

Write and execute code — numpy, pandas & scikit-learn included — right on the question page.

Log in to start coding
Title Category Subcategory Difficulty Status
Balanced Brackets ProgrammingOtherEasy
Circular Queue Implementation ProgrammingOtherHard
Evaluate RPN ProgrammingOtherMedium
Last Node of Singly Linked List ProgrammingOtherMedium
Linked List Cycle ProgrammingOtherMedium
Reverse a Linked List ProgrammingOtherEasy
Streaming Median ProgrammingOtherHard
Validate a BST ProgrammingOtherMedium
Weather API Data Analyzer ProgrammingOtherHard

Please log in to see the discussion.