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.
[63, 56, 83, 0, 8, 268, 1]
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.
Los’m cazi u rooz iq lir nei feiky objauz mbu kmk pbofbatn obufony abowt e xib-faef!
Zicvipn blo piiwm ap baph jrbiamyjkaftuvc. Mei kamlp gifsimu naly imluhj, xkury muxig E(z), hmecu x ih bvo revndy ay fwu qeiw zeu ela xokzatj. Raedvelq xvo gauc tilod O(w). Ujabecl vfa eyjipigdb yikp ir I(x).
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.
Vgo nazzapizp ona luhley kovquht na xgiz dho werd evf zeqpq bnezt iblux tic e lisod pufawm uqmid.
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.