improved time complexity

at the cost of minor space complexity.