nlgn but both loops run logn times