This approach is still far from ideal, but at least it has linear complexity in the common case instead of quadratic.