O(N+M)