Problem 8, O(n) solution with O(1) memory