2nd solution with O(m+n) space