Menu
Coddy logo textTech

Practice #5

Lesson 14 of 14 in Coddy's Heaps & Priority Queues - Data Structures Series #7 course.

challenge icon

Challenge

Easy

Write a function isMinHeap that gets an integer array arr and returns whether the array represents a valid min-heap.

An array is a min-heap when every parent is less than or equal to its children. Specifically, for every index i in range, arr[i] <= arr[2*i + 1] (when the left child exists) and arr[i] <= arr[2*i + 2] (when the right child exists).

Empty arrays and single-element arrays are min-heaps by definition.

You must use the MinHeap class (provided in minheap.<ext>) — do not use language built-ins like sort, slice, or stdlib heap libraries to compute the result.

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include "solution.h"

int main() {
    char line[8192];
    if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
    int arr[4096];
    int n = 0;
    char* tok = strtok(line, " \t\r\n");
    while (tok) { arr[n++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
    bool r = isMinHeap(arr, n);
    printf("%s\n", r ? "true" : "false");
    return 0;
}

All lessons in Heaps & Priority Queues - Data Structures Series #7