changing iteration direction fixed the duplicates bug