sol of q073 with worst case of space O(MN)