Consider a binary heap used to implement a priority queue. Which statement best describes how it maintains the priority queue property?
Think about how the root element relates to its children in a heap.
A binary heap maintains the priority queue property by ensuring the root node is always the smallest (min-heap) or largest (max-heap) element. Each parent node respects this order relative to its children, but the elements are not fully sorted.
When inserting a new element into a binary heap used as a priority queue, what is the time complexity of this operation?
Consider how the heap property is restored after adding a new element.
Insertion adds the element at the bottom and then 'bubbles up' to restore the heap property. This bubbling up takes at most the height of the heap, which is log n for a binary heap.
Given the min-heap represented as an array: [3, 5, 8, 10, 15, 12], what is the array after removing the root element?
Initial heap array: [3, 5, 8, 10, 15, 12] Operation: Remove root (minimum element)
After removing the root, replace it with the last element and then 'bubble down' to restore the heap.
Remove 3 (root). Replace root with last element 12: [12, 5, 8, 10, 15]. Bubble down 12: swap with 5 → [5, 12, 8, 10, 15]. Then swap 12 with 10 → [5, 10, 8, 12, 15].
Compare a binary heap and a sorted array for implementing a priority queue. Which statement is true about their efficiency?
Think about how insertion and removal work in both data structures.
Binary heap inserts in O(log n) by bubbling up and removes root in O(log n) by bubbling down. Sorted array requires O(n) to insert (to keep sorted) but removal of highest priority (first element) is O(1).
Both binary heaps and balanced binary search trees (BSTs) can implement priority queues. Why is a binary heap often preferred?
Consider the complexity and structure simplicity of both data structures.
Binary heaps are simpler to implement and provide O(log n) insertion and removal with less overhead than balanced BSTs, which maintain full order but have more complex balancing operations.