implemented 2nd algorithm