optimize the algorithm to have a linear time comlexity