Tweaked algorithm so that sets aren't updated while iterating