Hi, I was trying to solve this standard problem on complement graph traversal. Following are 2 almost similar solutions where one TLE's and the other passes, I'm not able to see where is the inefficiency coming in for the TLE solution, is it the complexity or just poor implementation.
TLE SOLUTION
AC SOLUTION
I understand the complexity of the second solution is $$$\mathcal{O}((N+M)\log N)$$$ as the number of times we check if an edge is present or not is $$$\mathcal{O}(M)$$$, but I'd be grateful if someone can outline the issue/complexity with/of the TLE solution.








Consider a graph with $$$0$$$ edges. Obviously everything is connected in such a graph. In the TLE version, when you first enter the
dfsfunction,nxcontains all other nodes. Then, when you loop through everything innx, youdfsto each of those individually. Now in the next call ofdfs, everything is in the unvisited set, excluding the first node that was visited. Nownxcontains every node other than the first node. Continuing with this logic, in the first call of dfsnxis of size $$$n$$$, then $$$n-1$$$, then $$$n-2$$$, until it's of size $$$1$$$. In total, this is $$$\mathcal{O}(n^2)$$$. The AC version fixes this by ensuring that you never add some node tonxif you've already done so, preserving the $$$\mathcal{O}((N+M)\log{}N))$$$ complexity you mentioned.That makes a lot of sense, thanks a lot for addressing it!!