refine the algorithm using Map