Heaps Technique in DSA

Heaps in a Nutshell

What is the Heap Technique?

The Heap Technique is a method of organizing elements in a binary tree structure where the parent node always maintains a relationship with its children based on either:

Heaps are typically implemented as arrays and are ideal for scenarios requiring repeated access to the largest or smallest element.

Types of Heaps

Common Heap Operations

Pseudocode: Inserting into a Heap

// Insert value into heap and bubble it up
function insert(heap, value):
    heap.append(value)
    index = heap.length - 1

    while index > 0:
        parent = floor((index - 1) / 2)
        if heap[parent] < heap[index]:  // Max Heap
            swap(heap[parent], heap[index])
            index = parent
        else:
            break

Pseudocode: Heapify an Array

// Heapify subtree rooted at index 'i' for Max Heap
function heapify(arr, n, i):
    largest = i
    left = 2 * i + 1
    right = 2 * i + 2

    if left < n and arr[left] > arr[largest]:
        largest = left
    if right < n and arr[right] > arr[largest]:
        largest = right

    if largest != i:
        swap(arr[i], arr[largest])
        heapify(arr, n, largest)

Pseudocode: Build Max Heap from Unordered Array

function buildMaxHeap(arr):
    n = arr.length
    for i from floor(n/2) - 1 down to 0:
        heapify(arr, n, i)

Applications of Heap Technique

Example: Find K Largest Elements

Problem: Given an array, return the K largest elements in sorted order.

Solution: Use a Min Heap of size K. Iterate through the array, and:

Pseudocode

function kLargestElements(arr, K):
    minHeap = new MinHeap()

    for num in arr:
        if minHeap.size() < K:
            minHeap.insert(num)
        else if num > minHeap.peek():
            minHeap.pop()
            minHeap.insert(num)

    return minHeap.toSortedArray()

Time and Space Complexity

When to Use Heap Technique

Advantages and Disadvantages

Advantages

Disadvantages

Conclusion

The Heap Technique is vital in DSA for building efficient solutions to problems that require order-based access. Whether you're sorting, managing priorities, or scheduling, heaps offer a structured and performant approach to maintaining maximum or minimum values dynamically.