optimize the algorithm to O(n) complexity