Faster version. O(n) time.