working on the second algorithm