
Problem
Solution
Submissions
Binary Heap
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to implement a Binary Heap data structure that functions as a Priority Queue. The heap should support insertion of elements, extraction of the minimum element, and maintain the heap property. Implement a Min-Heap where the parent node is always smaller than its children.
Example 1
- Input: Operations = [insert(3), insert(1), insert(4), extractMin(), insert(2), extractMin()]
- Output: [1, 2]
- Explanation:
- Insert 3 into heap: [3].
- Insert 1 into heap: [1, 3] (1 bubbles up as it's smaller).
- Insert 4 into heap: [1, 3, 4].
- Extract minimum returns 1, heap becomes: [3, 4].
- Insert 2 into heap: [2, 4, 3] (2 bubbles up).
- Extract minimum returns 2, heap becomes: [3, 4].
- Insert 3 into heap: [3].
Example 2
- Input: Operations = [insert(5), insert(2), insert(8), peek(), extractMin()]
- Output: [2, 2]
- Explanation:
- Insert 5 into heap: [5].
- Insert 2 into heap: [2, 5] (2 becomes root).
- Insert 8 into heap: [2, 5, 8].
- Peek returns 2 (minimum element without removing).
- Extract minimum returns 2, heap becomes: [5, 8].
- Insert 5 into heap: [5].
Constraints
- 1 ≤ number of operations ≤ 10^4
- 1 ≤ element values ≤ 10^6
- extractMin() will only be called when heap is not empty
- Time Complexity: O(log n) for insert and extractMin, O(1) for peek
- Space Complexity: O(n) where n is number of elements
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use an array to represent the heap with parent-child relationships
- For index i: left child at 2*i+1, right child at 2*i+2, parent at (i-1)/2
- Implement heapifyUp (bubble up) for insertion to maintain heap property
- Implement heapifyDown (bubble down) for extraction to restore heap property
- For insertion: add element at end, then heapify up
- For extraction: replace root with last element, remove last, then heapify down
- Maintain size property to track number of elements