iterative solution
bug free