time O(n) space O(n)