the time complexity of second method should be O(m+n)