Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Build Heap from Array Heapify in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Build Heap from Array Heapify
What is it?
Building a heap from an array means rearranging the array elements to satisfy the heap property, where each parent node is ordered with respect to its children. Heapify is the process used to fix the heap property starting from a node down to its children. This process transforms any array into a valid heap efficiently.
Why it matters
Without heapify, building a heap would be slow and inefficient, making many algorithms like priority queues and heap sort impractical. Heapify allows us to build a heap in linear time, which is crucial for performance in real-world applications like scheduling tasks or managing resources.
Where it fits
Before learning heapify, you should understand arrays and the basic heap data structure concept. After mastering heapify, you can learn heap operations like insert and extract, and then apply heaps in algorithms like heap sort and priority queues.
Mental Model
Core Idea
Heapify fixes the heap property by pushing a node down the tree until it is in the correct position relative to its children.
Think of it like...
Imagine a family tree where parents must be taller than their children. If a parent is shorter, you swap heights with the tallest child until the rule is true everywhere.
Array: [16, 14, 10, 8, 7, 9, 3, 2, 4, 1]

Heap tree:
        16
      /    \
    14      10
   /  \    /  \
  8    7  9    3
 / \  /
2  4 1

Heapify starts from bottom non-leaf nodes and moves upward fixing each subtree.
Build-Up - 7 Steps
1
FoundationUnderstanding Heap Property Basics
🤔
Concept: Learn what the heap property means for a binary heap and how it relates to array representation.
A max-heap requires each parent node to be greater than or equal to its children. In an array, for a node at index i, its children are at indices 2i+1 and 2i+2. The heap property ensures the largest element is always at the root (index 0).
Result
You can identify if an array satisfies the heap property by checking parent-child relationships.
Understanding the heap property is essential because heapify's goal is to enforce this property throughout the array.
2
FoundationArray Representation of Binary Heap
🤔
Concept: Learn how a binary heap is stored in an array and how to find parent and child indices.
In a zero-based array: - Parent of node at i is at (i-1)//2 - Left child is at 2i+1 - Right child is at 2i+2 This allows efficient navigation without pointers.
Result
You can traverse the heap structure using simple arithmetic on indices.
Knowing this mapping lets you implement heapify directly on arrays without extra data structures.
3
IntermediateHeapify Operation on a Single Node
🤔Before reading on: do you think heapify swaps a node with both children at once or only one child at a time? Commit to your answer.
Concept: Heapify compares a node with its children and swaps it with the largest child if needed, then continues down recursively.
Heapify(nodeIndex): 1. Find left and right child indices. 2. Compare node with children to find largest. 3. If largest is not node, swap and heapify at largest child index. 4. Else, stop. This fixes the subtree rooted at nodeIndex.
Result
The subtree rooted at nodeIndex satisfies the heap property after heapify.
Understanding that heapify works top-down and swaps only one child at a time clarifies why it efficiently restores heap order.
4
IntermediateBuilding Heap Using Bottom-Up Heapify
🤔Before reading on: do you think building a heap by heapifying from the start or from the end of the array is faster? Commit to your answer.
Concept: Build heap by heapifying all non-leaf nodes from bottom to top, ensuring each subtree is a heap.
Start from the last parent node at index (n//2 - 1) and move backward to index 0: For each index i: Call heapify(i) This ensures all subtrees satisfy the heap property, resulting in a full heap.
Result
The entire array is rearranged into a valid max-heap in O(n) time.
Knowing that heapify from bottom-up is more efficient than inserting elements one by one explains why build heap is O(n), not O(n log n).
5
IntermediateTypeScript Implementation of Heapify
🤔
Concept: See how to implement heapify in TypeScript using array and index calculations.
function heapify(arr: number[], n: number, i: number): void { let largest = i; const left = 2 * i + 1; const right = 2 * i + 2; if (left < n && arr[left] > arr[largest]) { largest = left; } if (right < n && arr[right] > arr[largest]) { largest = right; } if (largest !== i) { [arr[i], arr[largest]] = [arr[largest], arr[i]]; heapify(arr, n, largest); } }
Result
Heapify rearranges the subtree rooted at i to satisfy max-heap property.
Seeing the code helps connect the theory of heapify with practical implementation details.
6
AdvancedComplete Build Heap Function in TypeScript
🤔Before reading on: do you think buildHeap calls heapify on leaf nodes? Commit to your answer.
Concept: Build heap by calling heapify on all non-leaf nodes from bottom to top in the array.
function buildHeap(arr: number[]): void { const n = arr.length; for (let i = Math.floor(n / 2) - 1; i >= 0; i--) { heapify(arr, n, i); } } // Example usage: const arr = [4, 10, 3, 5, 1]; buildHeap(arr); console.log(arr);
Result
Output: [10, 5, 3, 4, 1] The array is rearranged into a max-heap.
Understanding that leaf nodes don't need heapify because they have no children prevents unnecessary work and improves efficiency.
7
ExpertWhy Build Heap is O(n) Not O(n log n)
🤔Before reading on: do you think build heap takes linear or logarithmic time? Commit to your answer.
Concept: Analyze the time complexity of build heap by considering heapify cost at each tree level.
Heapify on nodes near the bottom takes less time because their subtrees are smaller. Summing heapify costs over all nodes results in O(n) time, not O(n log n). Proof sketch: - Number of nodes at height h is about n / 2^(h+1) - Heapify cost per node at height h is O(h) - Total cost = sum over h of (n / 2^(h+1)) * h = O(n)
Result
Build heap runs in linear time, making it efficient for large arrays.
Knowing the real time complexity prevents overestimating build heap cost and helps choose the right algorithm.
Under the Hood
Heapify works by comparing a node with its children and swapping with the largest child if the heap property is violated. This swap may cause the subtree rooted at the child to violate the heap property, so heapify is called recursively. The process continues until the node is larger than its children or it reaches a leaf. Internally, this uses simple index arithmetic to navigate the array representing the heap.
Why designed this way?
Heapify was designed to fix local violations of the heap property efficiently without rebuilding the entire heap. The bottom-up build heap approach leverages heapify to fix smaller subtrees first, reducing redundant work. Alternatives like inserting elements one by one are simpler but less efficient, leading to O(n log n) time instead of O(n).
Build Heap Process:

Array indices: 0  1  2  3  4  5  6
Values:       4, 10, 3, 5, 1, 2, 8

Start heapify at index 2 (last parent):
  Compare 3 with children 2 and 8 -> swap with 8

Array now: 4, 10, 8, 5, 1, 2, 3

Heapify at index 1:
  Compare 10 with children 5 and 1 -> no swap

Heapify at index 0:
  Compare 4 with children 10 and 8 -> swap with 10

Array now: 10, 4, 8, 5, 1, 2, 3

Heapify at index 1:
  Compare 4 with children 5 and 1 -> swap with 5

Array now: 10, 5, 8, 4, 1, 2, 3

Heapify at index 3:
  No children, stop

Final heap:
10, 5, 8, 4, 1, 2, 3
Myth Busters - 4 Common Misconceptions
Quick: Does heapify fix the entire heap or just a subtree? Commit to your answer.
Common Belief:Heapify fixes the entire heap at once.
Tap to reveal reality
Reality:Heapify only fixes the subtree rooted at the given node, assuming its children are already heaps.
Why it matters:Misunderstanding this leads to incorrect heap construction and inefficient repeated heapify calls.
Quick: Is building a heap by inserting elements one by one faster than heapify? Commit to your answer.
Common Belief:Inserting elements one by one to build a heap is faster or equally fast.
Tap to reveal reality
Reality:Building a heap using bottom-up heapify is faster (O(n)) than inserting elements one by one (O(n log n)).
Why it matters:Choosing the slower method can cause performance issues in large data processing.
Quick: Does heapify swap a node with both children simultaneously? Commit to your answer.
Common Belief:Heapify swaps a node with both children at the same time if needed.
Tap to reveal reality
Reality:Heapify swaps a node with only the largest child at a time, then continues recursively.
Why it matters:Incorrect swapping logic breaks the heap property and causes bugs.
Quick: Are leaf nodes heapified during build heap? Commit to your answer.
Common Belief:Leaf nodes are heapified during build heap.
Tap to reveal reality
Reality:Leaf nodes are not heapified because they have no children and already satisfy the heap property.
Why it matters:Heapifying leaf nodes wastes time and can cause confusion about algorithm efficiency.
Expert Zone
1
Heapify's efficiency comes from the fact that nodes near the bottom have smaller subtrees, so their heapify calls are cheaper, balancing the total cost.
2
In-place heap construction avoids extra memory allocation, which is critical in memory-constrained environments.
3
Heapify can be adapted for min-heaps by reversing comparison logic, showing its flexibility.
When NOT to use
Heapify is not suitable when you need to maintain a heap dynamically with frequent insertions and deletions; in such cases, incremental heap operations or balanced trees may be better.
Production Patterns
Build heap is used in priority queue initialization, heap sort implementation, and real-time scheduling systems where quick setup of a heap is required before processing.
Connections
Priority Queue
Build heap is the initialization step for priority queues implemented with heaps.
Understanding build heap helps grasp how priority queues efficiently organize elements for quick access to the highest priority.
Heap Sort Algorithm
Build heap is the first phase of heap sort, preparing the array for sorting.
Knowing build heap clarifies why heap sort can sort in O(n log n) time by first creating a heap.
Tournament Bracket Systems
Both use tree structures to determine winners by comparing pairs and advancing the best.
Recognizing heapify as a process similar to tournament rounds helps understand how local comparisons lead to a global order.
Common Pitfalls
#1Calling heapify on leaf nodes unnecessarily.
Wrong approach:for (let i = arr.length - 1; i >= 0; i--) { heapify(arr, arr.length, i); }
Correct approach:for (let i = Math.floor(arr.length / 2) - 1; i >= 0; i--) { heapify(arr, arr.length, i); }
Root cause:Misunderstanding that leaf nodes have no children and already satisfy heap property.
#2Swapping a node with both children at once during heapify.
Wrong approach:if (arr[left] > arr[i]) swap(arr[i], arr[left]); if (arr[right] > arr[i]) swap(arr[i], arr[right]);
Correct approach:let largest = i; if (arr[left] > arr[largest]) largest = left; if (arr[right] > arr[largest]) largest = right; if (largest !== i) { swap(arr[i], arr[largest]); heapify(arr, n, largest); }
Root cause:Not comparing children first to find the largest before swapping.
#3Building heap by inserting elements one by one instead of heapify.
Wrong approach:for (let i = 0; i < arr.length; i++) { insertIntoHeap(arr[i]); }
Correct approach:buildHeap(arr);
Root cause:Not knowing that bottom-up heapify is more efficient than repeated insertions.
Key Takeaways
Heapify fixes the heap property by pushing a node down to its correct position relative to its children.
Building a heap from an array is done efficiently by heapifying all non-leaf nodes from bottom to top.
The array representation of a heap allows easy navigation using simple index calculations.
Build heap runs in linear time because heapify costs less for nodes near the bottom of the tree.
Misunderstanding heapify's operation or build heap's process leads to inefficient or incorrect heap construction.

Practice

(1/5)
1. What is the main purpose of the heapify process when building a heap from an array?
easy
A. To find the maximum element in the array
B. To sort the array in ascending order
C. To reverse the array elements
D. To rearrange the array elements to satisfy the heap property

Solution

  1. Step 1: Understand heap property

    A heap is a special tree where parent nodes follow a specific order compared to children (max-heap or min-heap).
  2. Step 2: Role of heapify

    Heapify rearranges elements so that the heap property holds for every subtree, starting from the bottom.
  3. Final Answer:

    To rearrange the array elements to satisfy the heap property -> Option D
  4. Quick Check:

    Heapify = Rearrange for heap property [OK]
Hint: Heapify fixes order to build a valid heap fast [OK]
Common Mistakes:
  • Thinking heapify sorts the array
  • Confusing heapify with finding max element
  • Assuming heapify reverses the array
2. Which of the following is the correct TypeScript syntax to start heapifying from the last non-leaf node in an array arr of length n?
easy
A. for(let i = Math.floor(n / 2); i < n; i++) { heapify(arr, n, i); }
B. for(let i = Math.floor(n / 2) - 1; i >= 0; i--) { heapify(arr, n, i); }
C. for(let i = n - 1; i >= 0; i--) { heapify(arr, n, i); }
D. for(let i = 0; i < n; i++) { heapify(arr, n, i); }

Solution

  1. Step 1: Identify last non-leaf node index

    In a heap array, last non-leaf node is at index Math.floor(n/2) - 1.
  2. Step 2: Loop from last non-leaf to root

    We heapify from this index down to 0 to ensure all subtrees satisfy heap property.
  3. Final Answer:

    for(let i = Math.floor(n / 2) - 1; i >= 0; i--) { heapify(arr, n, i); } -> Option B
  4. Quick Check:

    Start heapify at last non-leaf node [OK]
Hint: Start heapify at Math.floor(n/2)-1 down to 0 [OK]
Common Mistakes:
  • Starting heapify from 0 upwards
  • Starting heapify from last element
  • Looping beyond last non-leaf node
3. Given the array arr = [3, 9, 2, 1, 4, 5], what is the array after building a max-heap using heapify?
medium
A. [9, 4, 5, 1, 3, 2]
B. [5, 4, 3, 1, 9, 2]
C. [9, 3, 5, 1, 4, 2]
D. [3, 9, 2, 1, 4, 5]

Solution

  1. Step 1: Start heapify from index 2 (Math.floor(6/2)-1)

    Heapify at index 2: children 5 (index 5), swap 2 and 5 to get [3,9,5,1,4,2].
  2. Step 2: Heapify at index 1 and 0

    Index 1: children 1 and 4, max is 9 at index 1, no swap. Index 0: children 9 and 5, swap 3 and 9. Final array: [9,4,5,1,3,2]
  3. Final Answer:

    [9, 4, 5, 1, 3, 2] -> Option A
  4. Quick Check:

    Max-heap root is 9, children smaller [OK]
Hint: Heapify bottom-up swaps to fix max-heap [OK]
Common Mistakes:
  • Not swapping correctly during heapify
  • Confusing min-heap with max-heap
  • Leaving original array unchanged
4. Consider this TypeScript code snippet to build a max heap:
function heapify(arr: number[], n: number, i: number) {
  let largest = i;
  let left = 2 * i + 1;
  let right = 2 * i + 2;

  if (left < n && arr[left] > arr[largest]) largest = left;
  if (right < n && arr[right] > arr[largest]) largest = right;

  if (largest !== i) {
    [arr[i], arr[largest]] = [arr[largest], arr[i]];
    heapify(arr, n, largest);
  }
}

function buildHeap(arr: number[]) {
  let n = arr.length;
  for (let i = 0; i <= Math.floor(n / 2); i++) {
    heapify(arr, n, i);
  }
}
What is the error in this code?
medium
A. The loop in buildHeap should run from Math.floor(n/2)-1 down to 0
B. The heapify function swaps elements incorrectly
C. The left and right child indices are calculated wrongly
D. The buildHeap function should not call heapify

Solution

  1. Step 1: Analyze buildHeap loop range

    The loop runs from 0 up to Math.floor(n/2), but heapify must start from last non-leaf node down to root.
  2. Step 2: Correct loop direction and range

    Loop should be: for(let i = Math.floor(n/2) - 1; i >= 0; i--) to ensure all subtrees heapify properly.
  3. Final Answer:

    The loop in buildHeap should run from Math.floor(n/2)-1 down to 0 -> Option A
  4. Quick Check:

    Heapify bottom-up loop direction matters [OK]
Hint: Loop heapify bottom-up from last non-leaf node [OK]
Common Mistakes:
  • Looping heapify top-down instead of bottom-up
  • Incorrect child index calculations
  • Not swapping elements during heapify
5. You have an array arr = [4, 10, 3, 5, 1, 2]. After building a min-heap using heapify, what will be the array representation?
hard
A. [1, 4, 2, 10, 5, 3]
B. [1, 3, 2, 5, 10, 4]
C. [1, 4, 2, 5, 10, 3]
D. [1, 2, 3, 4, 5, 10]

Solution

  1. Step 1: Build min-heap bottom-up

    Start heapify from index 2 (Math.floor(6/2)-1): heapify at index 2 swaps 3 and 2 to get [4,10,2,5,1,3].
  2. Step 2: Heapify at index 1 and 0

    At index 1: children 5 and 1, swap 10 and 1 -> [4,1,2,5,10,3]. At index 0: children 1 and 2, swap 4 and 1 -> [1,4,2,5,10,3].
  3. Final Answer:

    [1, 4, 2, 5, 10, 3] -> Option C
  4. Quick Check:

    Min-heap root is smallest element 1 [OK]
Hint: Min-heap root is smallest; heapify swaps bottom-up [OK]
Common Mistakes:
  • Confusing min-heap with max-heap results
  • Not swapping correctly during heapify
  • Assuming sorted array equals heap
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard