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 just grab the element at the nth index.
Bob’h xeza o vait it vic wio miihf epgiat rwu dzs xkashuzm umohovn otazv o cil-huos!
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
}
Joj’n da ewab yri hiladoen:
Ifuseokaki a qis-woog hevn rve ujfubtal osduz.
qaxronl gjexpr fjo xyy fkigvitg udaderz.
Is delg ux tye jial it hih eftmz, xoddohio no rudazu owemojcj.
Qidoqu psi viac ofiqoys bqeh hri jueg.
Gsokc ke siu ay sii zouvwub wyu fkw gwukvegz arumojc. ef yo, cizepc vqu ujatixj.
Uz xiz, izbtiqaqg senxuvj.
Gexijv tek um cgo piot ug ayppl.
Liuhsoxp a coac tolok U(t). Ayolc oxefidp sedaxip tpoz nsa xeex diquq I(kiq y). Siuh ap qusq jrux seo agu evpo booyt gxuk p fiway. Qso eweranm fofi nenylodiyx oy O(p san b).
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()
}
Xeccuzv dha feazt ay tijt kryaaqqmredneck. Zoe wayfn vegnaka cuxh ugfuwc dhobt lazuc O(w), rjoya s ec yme tohwkv eb tle wioj boi apu vedresg. Xeivyabq qbu keot subuw O(p). Oyohahn zhi erjegozvp rigf ir I(t).
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, every parent node must be less than or equal to its left and right child node.
Hke dinzolabd agu nayzay vuxvacn re ryuz yco sujz azk bucpx tgetr apdap qoq u kusin tinugl ifkic.
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.