## Data Structures & Algorithms in Dart

Second Edition · Flutter · Dart 3.0 · VS Code 1.78

#### Before You Begin

Section 0: 6 chapters

#### Section I: Introduction

Section 1: 3 chapters

#### Section II: Elementary Data Structures

Section 2: 3 chapters

#### Section IV: Sorting Algorithms

Section 4: 5 chapters

#### Section V: Graphs

Section 5: 5 chapters

# 14. Chapter 14 Solutions Written by Jonathan Sande

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... 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.

Unlock now

## Solution to Challenge 1

There are many ways to solve for the nth smallest number in an unsorted list. This chapter is about heaps, so the solution here will use a min-heap.

``````num? getNthSmallestElement(int n, List<num> elements) {
var heap = Heap<num>(
elements: elements,
priority: Priority.min,
);
num? value;
for (int i = 0; i < n; i++) {
value = heap.remove();
}
return value;
}
``````

Since `heap.remove` always returns the smallest element, you just loop through n times to get the nth smallest number.

## Solution to Challenge 2

Given the following unsorted list:

``````[21, 10, 18, 5, 3, 100, 1]
``````

## Solution to Challenge 3

To combine two heaps, add the following method to `Heap`:

``````void merge(List<E> list) {
_buildHeap();
}
``````

## Solution to Challenge 4

To satisfy the min-heap requirement, every parent node must be less than or equal to its left and right child nodes.

``````bool isMinHeap<E extends Comparable<E>>(List<E> elements) {
// 1
if (elements.isEmpty) return true;
// 2
final start = elements.length ~/ 2 - 1;
for (var i = start; i >= 0; i--) {
// 3
final left = 2 * i + 1;
final right = 2 * i + 2;
// 4
if (elements[left].compareTo(elements[i]) < 0) {
return false;
}
// 5
if (right < elements.length &&
elements[right].compareTo(elements[i]) < 0) {
return false;
}
}
// 6
return true;
}
``````
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

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.

Unlock now