implemented iterative way with index moving