time complexity improved to log(n)