Menu
Coddy logo textTech

Practice #3

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

challenge icon

Challenge

Easy

Write a function kthSmallest that gets an integer array arr and a positive integer k, and returns the k-th smallest value (1-indexed). So k = 1 returns the smallest value, k = 2 returns the second-smallest, and so on.

If k is out of bounds (less than 1 or greater than the array length), return -1.

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];
    char tline[64];
    if (!fgets(line, sizeof(line), stdin)) line[0] = '\0';
    if (!fgets(tline, sizeof(tline), stdin)) tline[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"); }
    int k = atoi(tline);
    int r = kthSmallest(arr, n, k);
    printf("%d\n", r);
    return 0;
}

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