Changed algorithm a bit to use the Set more efficiently.