Improving time complexity to O(N+M) in solution 3.2