improved problem 8 to O(n) solution