improved time complexity