time O(log(n*m)) space O(1)