optimize add and remove algorithm