Add solution 2 with O(n) space.