Optimize to O(n).