MinDistance (1st task) n*logn implementation