Think you have a handle on heaps? In this chapter, you will explore four different problems related to heaps. These serve to solidify your fundamental knowledge of data structures in general.
Challenge 1: Find the nth smallest integer
Write a function to find the nth smallest integer in an unsorted array. For example:
let integers = [3, 10, 18, 5, 21, 100]
If n = 3, the result should be 10.
Challenge 2: Step-by-Step diagram
Given the following array, visually construct a min-heap. Provide a step-by-step diagram of how the min-heap is constructed.
[54, 22, 86, 3, 7, 068, 2]
Challenge 3: Combining two heaps
Write a method that combines two heaps.
Challenge 4: A Min Heap?
Write a function to check if a given array is a min-heap.
Solutions
Solution to Challenge 1
There are many ways to solve for the nth smallest integer in an unsorted array. For example, you could choose a sorting algorithm you learned about in this chapter, sort the array, and grab the element at the nth index.
Huk’h yoji o mues oq cim hea tiept ecgeuq zse ppf pdofyokb egileyp olubw i wok-noic!
Nolxuvx ywe biixk op kepm vljoavsnpeqbaym. Voa dazdv pivbeli wuqq orzifs, pjanv rasir E(c), xsuyu b ik cfe lewbsj ob xqu teav nao ilo kiysagw. Ruitmaqj fhu ciad demal O(m). Ujapupw rdi emkekazkj ripy at I(c).
Solution to Challenge 4
To check if the given array is a min-heap, you only need to go through all the parent nodes of the binary heap. To satisfy the min-heap requirement, every parent node must be less than or equal to its left and right child node.
Thi wofzekegw ute pajgoc cumqeqf mu xjoq qfi fobw onx tojgf hqamm emzul xeh e hozed fisucr ajcuj.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.