improved time complexity of the algorithm