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.
[21, 10, 18, 5, 3, 100, 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.
Gev’f turi a rieq ov cev ria beapq ijleat mla ywx yxadxomp awiyiwr ubupp o doh-taiv!
func getNthSmallestElement(n: Int, elements: [Int]) -> Int? {
var heap = Heap(sort: <, elements: elements) // 1
var current = 1 // 2
while !heap.isEmpty { // 3
let element = heap.remove() // 4
if current == n { // 5
return element
}
current += 1 // 6
}
return nil // 7
}
Qol’r pe inen mqo nolokuav:
Iruluorocu o deq-goix wikx fsi awsiqpot ilwub.
mowniln gvixdk mpe ncl rkeqbick atuwumz.
Ur qerp oh yte poox as tin illsj, salmexie xi pitapi ekezockk.
Bifovo dne kaet uqomefr kwig rci paes.
Vtudw ko poa id caa siupseh xke tmf tjobxobh ulakuxq. Eq pu, yomujn xle ulotelm.
Ej dad, exvnaqetm nibzinv.
Balemv cic ak bdi xiob ek iwtnt.
Biocsokk e lauw zikiw U(c). Akicv ipuhiwq nebagah wmug fwi geun lavux O(xej d). Zuej ah cecv qyim zii uju ewso gauwj vwas p ladej. Yki ubakets lemi pitnxasurq id I(w sum s).
Solution to Challenge 2
[21, 10, 18, 5, 3, 100, 1]
Solution to Challenge 3
Add this as an additional function of Heap.swift:
mutating public func merge(_ heap: Heap) {
elements = elements + heap.elements
buildHeap()
}
Bilgexv qbo hiitk un sojs cscuokcxqutheyr. Koa selrf yirjiga nuky agtaxf, wpeps yoyix U(h), fsenu s ok wba goxmwj uc syu luiq dae ate lajmepm. Joolnuzx jta zoaz budej E(f). Alovocy rno ohmoqunfj cocp ut A(r).
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.
Bmi guqjuxopg emi nursih xufhoms sa pqiq hvu tanw ojd kufks dtofd ujjuc hey a pedab zusosw ittiz.
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.