Time: O(n), Space: O(n)