Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 19 of 19 · 8 min read

Data structures and algorithms with Dart

Dart data structures notes: Big-O, linear and binary search, bubble, selection and insertion sort, recursion, stack, queue, linked list and hashing.

What is an algorithm?

An algorithm is a step-by-step method for solving a problem, like a recipe. A data structure is a way of organising data so those steps are efficient. Choosing well can make a program thousands of times faster on large data.

Measuring speed: the Big-O idea

Big-O describes how the work grows as the input size n grows:

Big-ONameExampleSteps for n = 1,000,000
O(1)constantread list[i], look up a map key1
O(log n)logarithmicbinary searchabout 20
O(n)linearlinear search, sum a list1,000,000
O(n log n)linearithmicDart's sortabout 20,000,000
O(n²)quadraticbubble sort, two nested loops1,000,000,000,000

Interviews and exams ask for the Big-O of loops: one loop over n items is O(n); a loop inside a loop is O(n²); halving the problem each step is O(log n).

Check each item in turn. Works on any list; O(n).

int linearSearch(List<int> xs, int target) {
  for (int i = 0; i < xs.length; i++) {
    if (xs[i] == target) return i;
  }
  return -1;
}

void main() {
  var rolls = [14, 3, 27, 8, 19];
  print(linearSearch(rolls, 8));
  print(linearSearch(rolls, 5));
}
3
-1

On a sorted list, look at the middle; if the target is smaller, search the left half, otherwise the right half. Each step halves the list, so it is O(log n).

int binarySearch(List<int> xs, int target) {
  int lo = 0, hi = xs.length - 1;
  while (lo <= hi) {
    int mid = (lo + hi) ~/ 2;
    if (xs[mid] == target) return mid;
    if (xs[mid] < target) {
      lo = mid + 1;
    } else {
      hi = mid - 1;
    }
  }
  return -1;
}

void main() {
  var sorted = [3, 8, 14, 19, 27, 35, 42];
  print(binarySearch(sorted, 27));
  print(binarySearch(sorted, 10));
}
4
-1

Three simple sorts

All three are O(n²). Learn them to understand sorting; in real code use list.sort(), which is O(n log n).

Bubble sort repeatedly swaps neighbours that are in the wrong order, so the biggest value "bubbles" to the end on each pass:

void bubbleSort(List<int> a) {
  for (int pass = 0; pass < a.length - 1; pass++) {
    bool swapped = false;
    for (int i = 0; i < a.length - 1 - pass; i++) {
      if (a[i] > a[i + 1]) {
        final t = a[i];
        a[i] = a[i + 1];
        a[i + 1] = t;
        swapped = true;
      }
    }
    if (!swapped) break;   // already sorted
  }
}

void selectionSort(List<int> a) {
  for (int i = 0; i < a.length - 1; i++) {
    int min = i;
    for (int j = i + 1; j < a.length; j++) {
      if (a[j] < a[min]) min = j;
    }
    final t = a[i];
    a[i] = a[min];
    a[min] = t;
  }
}

void insertionSort(List<int> a) {
  for (int i = 1; i < a.length; i++) {
    int key = a[i];
    int j = i - 1;
    while (j >= 0 && a[j] > key) {
      a[j + 1] = a[j];
      j--;
    }
    a[j + 1] = key;
  }
}

void main() {
  var a = [29, 10, 14, 37, 13];
  var b = [...a], c = [...a];
  bubbleSort(a);
  selectionSort(b);
  insertionSort(c);
  print(a);
  print(b);
  print(c);
}
[10, 13, 14, 29, 37]
[10, 13, 14, 29, 37]
[10, 13, 14, 29, 37]
  • Selection sort finds the smallest remaining value and puts it next.
  • Insertion sort takes each value and slides it into place among the sorted ones before it, like sorting playing cards in your hand. It is fast on nearly sorted lists.

Recursion: factorial, Fibonacci and Tower of Hanoi

int factorial(int n) => n <= 1 ? 1 : n * factorial(n - 1);

int fib(int n, [Map<int, int>? memo]) {
  memo ??= {};
  if (n < 2) return n;
  return memo[n] ??= fib(n - 1, memo) + fib(n - 2, memo);
}

void hanoi(int n, String from, String to, String via) {
  if (n == 0) return;
  hanoi(n - 1, from, via, to);
  print('Move disc $n from $from to $to');
  hanoi(n - 1, via, to, from);
}

void main() {
  print(factorial(6));
  print(fib(40));
  hanoi(2, 'A', 'C', 'B');
}
720
102334155
Move disc 1 from A to B
Move disc 2 from A to C
Move disc 1 from B to C

The plain recursive Fibonacci is O(2ⁿ) because it repeats work; the memo map stores answers already found, making it O(n). Tower of Hanoi with n discs needs 2ⁿ − 1 moves.

Stack and queue

A stack is last in, first out (LIFO): the undo history, the back button, matching brackets. A Dart List works as a stack with add and removeLast.

A queue is first in, first out (FIFO): a print queue, a ticket counter. Queue from dart:collection adds and removes at both ends in O(1).

import 'dart:collection';

bool balanced(String s) {
  final stack = <String>[];
  const pairs = {')': '(', ']': '[', '}': '{'};
  for (var ch in s.split('')) {
    if ('([{'.contains(ch)) {
      stack.add(ch);
    } else if (pairs.containsKey(ch)) {
      if (stack.isEmpty || stack.removeLast() != pairs[ch]) return false;
    }
  }
  return stack.isEmpty;
}

void main() {
  print(balanced('{[a + b] * (c)}'));
  print(balanced('(a + b]'));

  final tokens = Queue<String>()..addAll(['T1', 'T2', 'T3']);
  tokens.addLast('T4');
  print('Serving ${tokens.removeFirst()}');
  print('Waiting: $tokens');
}
true
false
Serving T1
Waiting: {T2, T3, T4}

Avoid list.removeAt(0) as a queue: it shifts every item, so it is O(n).

A linked list

A linked list stores each value in a node that points to the next node. Inserting at the front is O(1); reaching the i-th item is O(n).

class Node<T> {
  T value;
  Node<T>? next;
  Node(this.value, [this.next]);
}

class SimpleLinkedList<T> {
  Node<T>? head;
  int length = 0;

  void addFirst(T v) {
    head = Node(v, head);
    length++;
  }

  @override
  String toString() {
    final parts = <String>[];
    for (var n = head; n != null; n = n.next) {
      parts.add('${n.value}');
    }
    return parts.join(' -> ');
  }
}

void main() {
  final list = SimpleLinkedList<int>();
  list.addFirst(30);
  list.addFirst(20);
  list.addFirst(10);
  print(list);
  print(list.length);
}
10 -> 20 -> 30
3

Hashing with maps: counting, grouping and two-sum

A Map (a hash table) finds a key in O(1) on average. Many O(n²) problems become O(n) with a map.

List<int>? twoSum(List<int> xs, int target) {
  final seen = <int, int>{};               // value -> index
  for (int i = 0; i < xs.length; i++) {
    final need = target - xs[i];
    if (seen.containsKey(need)) return [seen[need]!, i];
    seen[xs[i]] = i;
  }
  return null;
}

void main() {
  print(twoSum([2, 7, 11, 15], 9));

  final words = ['apple', 'avocado', 'banana', 'blueberry', 'cherry'];
  final byLetter = <String, List<String>>{};
  for (var w in words) {
    byLetter.putIfAbsent(w[0], () => []).add(w);
  }
  print(byLetter);
}
[0, 1]
{a: [apple, avocado], b: [banana, blueberry], c: [cherry]}

Common mistakes

  • Using binary search on an unsorted list: it returns wrong answers without any error.
  • Computing mid and then not moving lo or hi past it, which loops forever.
  • Recursion without a base case, or plain recursive Fibonacci for large n.
  • Using a List with contains inside a loop (O(n²)) where a Set would be O(n).
  • Using removeAt(0) for queues on large data.

Key points

  • Big-O describes how work grows: O(1), O(log n), O(n), O(n log n), O(n²).
  • Linear search is O(n) on any list; binary search is O(log n) on a sorted list.
  • Bubble, selection and insertion sort are O(n²); built-in sort is O(n log n).
  • Recursion needs a base case; memoisation removes repeated work.
  • Stacks are LIFO, queues FIFO, linked lists chain nodes; maps give O(1) lookups.

Practice questions

1. What is the Big-O of a loop over n items that contains another loop over n items?

O(n²): the inner loop runs n times for each of the n outer rounds.

2. Write a function that reverses a string using a stack.
String reverse(String s) {
  final stack = <String>[];
  for (var ch in s.split('')) {
    stack.add(ch);
  }
  final sb = StringBuffer();
  while (stack.isNotEmpty) {
    sb.write(stack.removeLast());
  }
  return sb.toString();
}

void main() {
  print(reverse('Dart'));   // traD
}
3. How many steps does binary search need at most for a sorted list of 1,024 items?

About 10 (or 11 checks counting the last), because 2¹⁰ = 1,024 and each step halves the list.

4. Find the first repeated number in [4, 1, 7, 1, 4] in O(n) using a set.
void main() {
  final seen = <int>{};
  for (var n in [4, 1, 7, 1, 4]) {
    if (!seen.add(n)) {
      print(n);   // 1
      break;
    }
  }
}

Set.add returns false when the value was already there.

5. Why is insertion sort a good choice for a list that is already almost sorted?

Each value moves only a short way, so the inner loop does very little work and the sort runs in close to O(n) time.