updated algorithm no longer 0(n!)