Bug-free O(n) serial code