Tutorialspoint
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].
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].
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
ArraysHeapHCL TechnologiesPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Initialize heap using an array and maintain a size counter.

 Step 2: For insertion, add new element at the end of the array.
 Step 3: Perform heapifyUp to bubble the new element to its correct position.
 Step 4: For extraction, store the root (minimum) element to return.
 Step 5: Replace root with the last element and decrease size.
 Step 6: Perform heapifyDown to bubble the new root to its correct position.
 Step 7: Implement swap helper method and parent-child index calculations for heap operations.

Submitted Code :