Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Heap Insert (sift up)

Heapsmedium

Implement `heapInsert(arr, val)` returning a new min-heap array after adding `val` and sifting it up to its correct position.

Sample tests

Input: heapInsert([1,3,5], 2)
Output: [1,2,5,3]
Input: heapInsert([], 5)
Output: [5]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Sifting down instead of up after appending.

Learning resources

  • Wikipedia: Binary heap
Approach & explanation (try first)

Appending then sifting up restores the heap in O(log n).

Loading...
⌘/Ctrl + Enter

Run your code to see results.