added Sophie's solution
improved my original implementation

space: O(m+n) => O(1)