How Do You Implement a Heap Using an Array

πŸ’‘ Concept Name

Heap using Array – A binary heap is efficiently represented as an array by leveraging the predictable parent-child index relationships inherent in a complete binary tree.

πŸ“˜ Quick Intro

A heap is a complete binary tree where every node satisfies the heap property (either min-heap or max-heap). Due to its completeness, the heap nodes can be stored sequentially in an array without using explicit pointers.

🧠 Analogy / Short Story

Imagine stacking oranges in a pyramid inside a flat crate row by row. You don't need strings to connect them; their position in the crate tells you exactly where each orange sits in relation to others. This is how heaps can be stored in arrays.

πŸ”§ Technical Explanation

  • πŸ‘¨β€πŸ‘§β€πŸ‘¦ For a node at index i in the array:
    • Left child index = 2 * i + 1
    • Right child index = 2 * i + 2
    • Parent index = (i - 1) / 2 (integer division)
  • πŸ—οΈ Insertion: Add the new element at the end and bubble it up to maintain the heap property (heapify up).
  • ❌ Removal: Remove the root by replacing it with the last element, then heapify down to restore order.
  • πŸ“¦ Arrays provide a compact and efficient storage model without pointers, leveraging simple index arithmetic.

🎯 Purpose & Use Case

  • βœ… Implementing priority queues efficiently
  • βœ… Scheduling tasks based on priority
  • βœ… In-place sorting algorithms such as heapsort
  • βœ… Calculating running medians or maintaining k-largest elements dynamically

πŸ’» Real Code Example

public class MaxHeap
{
    private List<int> heap = new List<int>();

    public void Insert(int value)
    {
        heap.Add(value);
        int i = heap.Count - 1;
        while (i > 0 && heap[i] > heap[(i - 1) / 2])
        {
            (heap[i], heap[(i - 1) / 2]) = (heap[(i - 1) / 2], heap[i]);
            i = (i - 1) / 2;
        }
    }

    public int ExtractMax()
    {
        if (heap.Count == 0) throw new InvalidOperationException("Heap is empty.");
        int max = heap[0];
        heap[0] = heap[^1];
        heap.RemoveAt(heap.Count - 1);
        Heapify(0);
        return max;
    }

    private void Heapify(int i)
    {
        int largest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;

        if (left < heap.Count && heap[left] > heap[largest]) largest = left;
        if (right < heap.Count && heap[right] > heap[largest]) largest = right;

        if (largest != i)
        {
            (heap[i], heap[largest]) = (heap[largest], heap[i]);
            Heapify(largest);
        }
    }
}

❓ Interview Q&A

Q1: How is a heap represented using an array?
A: The heap elements are stored sequentially in an array, where the parent-child relationship is determined by index calculations.

Q2: How do you find the parent of a node at index i?
A: Parent index = (i - 1) / 2 (integer division).

Q3: How do you find the left child of a node at index i?
A: Left child index = 2 * i + 1.

Q4: How do you find the right child of a node at index i?
A: Right child index = 2 * i + 2.

Q5: Why use an array to represent a heap instead of pointers?
A: Arrays offer cache-friendly memory layout and simple index calculations, improving performance.

Q6: What is the advantage of storing heaps in arrays?
A: No need for explicit pointers; parent and child relationships are implicit via indices.

Q7: How is insertion handled in an array-based heap?
A: Insert the new element at the end and heapify-up to maintain heap property.

Q8: How is removal of the root handled in an array-based heap?
A: Replace root with last element, reduce heap size, and heapify-down.

Q9: What is the time complexity of heap operations using arrays?
A: O(log n) for insertion and deletion.

Q10: Can heaps using arrays be easily resized?
A: Yes, dynamic arrays or array resizing techniques can be applied.

πŸ“ MCQs

Q1. How do you find the parent index in an array-based heap?

  • (i - 1) / 2
  • 2 * i + 1
  • 2 * i + 2
  • i / 2

Q2. What is the left child index in an array heap?

  • 2 * i + 1
  • (i - 1) / 2
  • 2 * i + 2
  • i - 1

Q3. What is the right child index in an array heap?

  • 2 * i + 2
  • 2 * i + 1
  • (i - 1) / 2
  • i + 1

Q4. Why are heaps stored in arrays?

  • Easier to program
  • Cache-friendly and simple index math
  • Faster insertions
  • Memory efficient

Q5. How is insertion done in array-based heaps?

  • Insert at root
  • Insert at end and heapify-up
  • Insert randomly
  • Insert at middle

Q6. How is root removal done in array-based heaps?

  • Delete root directly
  • Replace root with last element and heapify-down
  • Swap root with left child
  • Remove last element

Q7. What is the time complexity of insertion and removal in heaps?

  • O(1)
  • O(n)
  • O(log n)
  • O(n log n)

Q8. Can array-based heaps be resized?

  • No
  • Yes, using dynamic arrays
  • Only fixed size
  • Depends on implementation

Q9. What does heapify do?

  • Sorts the array
  • Maintains heap property after changes
  • Deletes nodes
  • Adds nodes

Q10. What property does a max-heap maintain?

  • Parent <= children
  • Parent >= children
  • Children unordered
  • No order

πŸ’‘ Bonus Insight

Storing heaps in arrays reduces memory overhead and enables efficient in-place sorting through heapsort, which runs in O(n log n) time with minimal extra space.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

Learn More About Data Structures πŸ“š

What is a Data Structure and Why is it Important? πŸ‘‰ Learn More
Linear vs Non-linear Data Structures πŸ‘‰ Learn More
Arrays vs Linked Lists πŸ‘‰ Learn More
Advantages & Disadvantages of Arrays πŸ‘‰ Learn More
Singly Linked List Explained πŸ‘‰ Learn More
Singly vs Doubly Linked List πŸ‘‰ Learn More
Circular Linked List & Its Use Cases πŸ‘‰ Learn More
Reversing a Linked List πŸ‘‰ Learn More
Stack vs Queue πŸ‘‰ Learn More
Circular Queue Explained πŸ‘‰ Learn More
Queue Overflow & Underflow πŸ‘‰ Learn More
Applications of Stacks πŸ‘‰ Learn More
Priority Queue Explained πŸ‘‰ Learn More
Deque vs Queue πŸ‘‰ Learn More
Implement Stack Using Queues πŸ‘‰ Learn More
Implement Queue Using Stacks πŸ‘‰ Learn More
Trees in Data Structures πŸ‘‰ Learn More
Binary Trees Explained πŸ‘‰ Learn More
Binary Search Tree vs Binary Tree πŸ‘‰ Learn More
Insert & Delete in BST πŸ‘‰ Learn More
Tree Traversals (Inorder, Preorder, Postorder) πŸ‘‰ Learn More
Level Order Traversal πŸ‘‰ Learn More
Balanced Binary Tree πŸ‘‰ Learn More
AVL Trees Explained πŸ‘‰ Learn More
Red-Black Trees πŸ‘‰ Learn More
B-tree vs BST πŸ‘‰ Learn More
Heaps in Data Structures πŸ‘‰ Learn More
Min-Heap vs Max-Heap πŸ‘‰ Learn More
Implementing Heap Using Arrays πŸ‘‰ Learn More
Applications of Heaps πŸ‘‰ Learn More
Tries & Word Searching πŸ‘‰ Learn More
Graphs Explained πŸ‘‰ Learn More
Adjacency Matrix vs List πŸ‘‰ Learn More
BFS vs DFS πŸ‘‰ Learn More
Detecting Cycle in Graph πŸ‘‰ Learn More
Directed Acyclic Graph (DAG) πŸ‘‰ Learn More
Topological Sorting πŸ‘‰ Learn More
Dijkstra’s Algorithm πŸ‘‰ Learn More
Prim’s vs Kruskal’s Algorithm πŸ‘‰ Learn More
Union-Find / Disjoint Set πŸ‘‰ Learn More
Hash Tables Explained πŸ‘‰ Learn More
Hash Collision Handling πŸ‘‰ Learn More
Open Addressing vs Chaining πŸ‘‰ Learn More
Load Factor in Hashing πŸ‘‰ Learn More
Static vs Dynamic Data Structures πŸ‘‰ Learn More
Segment Trees πŸ‘‰ Learn More
Share:

Tags:


Feedback Modal Popup