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