added efficient, single-pass O(n) implementation