exp5 reduce time complexity to logn