sol with O(MNlg(M))
add comments