I was recently tasked with finding a way to calculate SCCs in a directed graph by a teacher expecting me to reach Tarjan's or Kosaraju's algorithm, but I reached a completely different and new solution (the novelty Im not fully sure).
It's arguably a bit worse in both simplicity and complexity, but I decided to write a blog about it anyway since I think I used some cool ideas, and who knows, maybe somebody else can utilize this either to find a useful variant or in some completely unrelated problem.
My teacher named it KS-SCC, hinting at the fact that it's dumb/useless (in Farsi), lmao.
I think it's funny, so I will stick with it.
DSU: Simple understanding of keeping and merging components will suffice
DFS: Needs more than a base-level understanding, needs full understanding of qualities and different types of edges in the DFS tree
Since I couldn't find a good resource for a more advanced DFS, I asked Claude to write an explanation of DFS on directed graphs and difference array on the DFS tree
DFS states. Every vertex is in one of three states, stored in mark[u]:
- $$$mark[u] = 0$$$: undiscovered
- $$$mark[u] = 1$$$: discovered & unfinished (**active**)
- $$$mark[u] = 2$$$: finished
DFS gives a forest of tree edges (the edge $$$u \to v$$$ that first discovers $$$v$$$). Write $$$sub(x)$$$ for the set of descendants of $$$x$$$ (including $$$x$$$), and $$$h(x)$$$ for its depth in the forest.
Classifying an edge $$$u \to v$$$ at the moment $$$u$$$ examines it:
- $$$mark[v] = 0$$$: tree edge, $$$v$$$ becomes a child of $$$u$$$.
- $$$mark[v] = 1$$$: back edge, $$$v$$$ is an ancestor of $$$u$$$ (or $$$v = u$$$, a self-loop).
- $$$mark[v] = 2$$$: forward edge if $$$v \in sub(u)$$$ (a finished descendant that isn't a child), otherwise cross edge ($$$v$$$ is in a branch that was fully explored earlier, or in an earlier tree of the forest).
markalone can't tell these two apart, you'd need discovery times.
There are four types, not three.
Facts that everything else is built on:
- Active vertices are exactly the recursion stack. They form a single chain: the tree path from a root to the vertex $$$u$$$ currently executing. So any two active vertices are in an ancestor/descendant relation, and every ancestor of an active vertex is active.
- $$$sub(c)$$$ is exactly the set of vertices discovered while $$$c$$$ is active. In particular, descendants finish before their ancestors.
- When $$$v$$$ finishes, everything reachable from $$$v$$$ has been discovered. (If a reachable $$$w$$$ were still undiscovered, DFS would have reached it from $$$v$$$ before $$$v$$$ could finish.)
- Consequence of 1 and 3: if a finished vertex $$$v$$$ can reach an active vertex $$$w$$$, then $$$w$$$ was discovered before $$$v$$$ and is still active, so $$$w$$$ is an ancestor of $$$v$$$.
- Cross edges only point "backwards in time": from a later-discovered vertex to an earlier-discovered, already finished one. An edge to a later-discovered vertex would make that vertex a descendant.
What each edge tells you about reachability:
- Tree path: an ancestor reaches all of its descendants.
- Back edge $$$u \to v$$$: $$$u$$$ reaches its ancestor $$$v$$$, and $$$v$$$ reaches $$$u$$$ along the tree path, so the tree path $$$v \leadsto u$$$ plus the edge is a cycle.
- Forward/cross edges give a path to a finished vertex, which says nothing by itself about getting back up. What matters is whether that finished vertex can reach an active vertex (fact 4).
The whole traversal is $$$O(|V|+|E|)$$$. The recursion depth can be $$$|V|$$$, so on judges with small stacks you may need an iterative version.
The problem. You have a rooted tree and a set of vertical paths $$$(a, b)$$$, where $$$b$$$ is an ancestor-or-equal of $$$a$$$ and the path goes up from $$$a$$$ to $$$b$$$. For every tree edge $$$(p(x), x)$$$, you want to know how many paths cover it.
The trick. For each path $$$(a, b)$$$ do
Then the number of paths covering the edge $$$(p(x), x)$$$ is the subtree sum
Why it works. A path contributes $$$+1$$$ at $$$a$$$ and $$$-1$$$ at $$$b$$$, so it contributes to $$$S(x)$$$ as follows:
- both $$$a, b \in sub(x)$$$: $$$+1-1 = 0$$$, so the path never leaves the subtree and doesn't cover the edge above $$$x$$$.
- $$$a \in sub(x)$$$, $$$b \notin sub(x)$$$: $$$+1$$$. Since $$$b$$$ is an ancestor of $$$a$$$, $$$b$$$ must be a proper ancestor of $$$x$$$, so the path really does pass through $$$(p(x), x)$$$.
- $$$a \notin sub(x)$$$ and $$$b \in sub(x)$$$: impossible, because $$$b$$$ is an ancestor of $$$a$$$ so $$$a \in sub(b) \subseteq sub(x)$$$.
So $$$S(x) \gt 0$$$ if and only if some path goes from inside $$$sub(x)$$$ to strictly above $$$x$$$.
The only requirement is that the target of each pair is an ancestor-or-equal of its source. That is exactly what a back edge satisfies.
Computing it during the DFS. You don't need a separate pass. After a child returns, add its value into the parent:
dfs(u):
mark[u] = 1
for v in adj[u]:
if mark[v] == 0:
dfs(v)
cnt[u] += cnt[v] // now cnt[v] = S(v), final
else if mark[v] == 1: // back edge: vertical path (u, v)
cnt[u]++, cnt[v]--
mark[u] = 2
When $$$dfs(v)$$$ returns, $$$cnt[v] = S(v)$$$ is final, because every update involving $$$sub(v)$$$ (a $$$+1$$$ at a source, or a $$$-1$$$ at a target) happens while $$$v$$$ is active (fact 2). So at that moment $$$cnt[v] \gt 0$$$ tells you "the tree edge $$$(p(v), v)$$$ is covered by a non-tree edge that goes from $$$sub(v)$$$ to a proper ancestor of $$$v$$$". In a directed graph that means the edge lies on a cycle, because the back edge returns to the ancestor and the tree path leads down again.
Things to keep in mind:
- $$$cnt[x]$$$ counts the recorded pairs, not necessarily original edges. Any non-tree edge can be recorded as a pair $$$(a, b)$$$ as long as $$$b$$$ is an active ancestor-or-equal of $$$a$$$ and you know $$$a \leadsto b$$$. For example, a cross edge $$$u \to v$$$ can be recorded with a substitute target $$$b$$$ if $$$v$$$ is known to reach $$$b$$$ and $$$b$$$ is active (fact 4).
- A back edge to $$$u$$$ itself cancels out in $$$cnt[u]$$$ ($$$+1-1$$$), so it doesn't count as covering anything above $$$u$$$.
- The same trick on an undirected graph gives bridges: a tree edge is a bridge if and only if no back edge covers it, i.e. $$$S(x) = 0$$$.
I will provide a hand-written explanation of KS-SCC by me, which is intuitive and informal, and I won't prove anything.
I will also provide a formal proof of KS-SCC by Claude (based on my explanation).
The Procedure itself is explained in both my explanation and the full proof by claude.
I'm terribly sorry for leaving the formal proof to artificial intelligence. I tried proving the algo myself, but with respect to the fact that I'm still a student and have zero experience with this, I couldn't write well and kept leaving gaps in my proof, so I left it to Claude.
To find the SCCs, we do the following recursive depth-first traversal:
Procedure
Definition of arrays used
mark[u]represents the state of $$$u$$$ in DFS- $$$mark[u] = 0$$$: undiscovered
- $$$mark[u] = 1$$$: discovered & unfinished (active)
- $$$mark[u] = 2$$$: finished
cnt[u]represents the number of cycle-closing edges in $$$u$$$'s subtree such that the cycle includes at least one vertex that is an ancestor of $$$u$$$up[u]represents the node with the lowest distance to the root of the DFS (i.e., height) in $$$u$$$'s SCC
**SCC_DFS(u):**
1. set mark[u] = 1.
2. go through all nodes v, connected by an edge to u:
if mark[v] == 0 (tree edge)
call SCC_DFS(v)
if cnt[v] > 0
merge the components of u & v
add cnt[v] to cnt[u]
else if mark[v] == 1 (back edge)
cnt[u]++, cnt[v]--
else if mark[v] == 2 (cross edge)
if (mark[up[v]] == 1)
cnt[u]++, cnt[up[v]]--
3. set mark[u] = 2
Intuition of why the procedure works
The core of the procedure is built on the following two claims:
Claim 1: a set $$$S$$$ of nodes is strongly connected if and only if there exists a directed closed walk that goes through every vertex of $$$S$$$, and an SCC is a maximal strongly connected set.
Claim 2: two nodes $$$u$$$ & $$$v$$$ are in the same SCC if and only if there exists a directed path from $$$v$$$ to $$$u$$$ and a directed path from $$$u$$$ to $$$v$$$.
[As said, I won't be proving anything here.]
Step 2 of procedure
In SCC_DFS, after discovering a vertex $$$u$$$ and while visiting the list of edges $$$e = (u \to v)$$$ adjacent to $$$u$$$ during DFS, there are three types you encounter:
That means that $$$v$$$ is an undiscovered vertex, so we still don't know anything about $$$v$$$'s relation to $$$u$$$, so first call its SCC_DFS.
Claim 3: if node $$$u$$$ is part of a closed walk $$$W$$$ with one of its ancestors $$$a$$$, there exists a closed walk $$$W'$$$ where $$$par[u], u \in W'$$$.
So by Claims 1 & 3, if $$$cnt[v] \gt 0$$$ then we can merge the $$$u$$$ & $$$v$$$ components. Then we update $$$cnt[u]$$$ based on $$$cnt[v]$$$.
It closes a cycle: $$$C = [P = {\text{path from } v \text{ to } u \text{ using tree edges}}] + e$$$, so we update the difference array.
By Claim 2, we should merge $$$u$$$ and $$$v$$$ if there exists a path from $$$v$$$ to $$$u$$$.
Since $$$v$$$'s subtree is finished (i.e., mark[v] = 2), there needs to be a $$$w$$$ such that $$$v$$$ has a directed path to $$$w$$$ and mark[w] == 1.
Claim 4: such $$$w$$$ exists if and only if the minimum depth node in $$$v$$$'s current SCC fits $$$w$$$'s criteria.
This needs a bit of explanation.
The list of nodes that can satisfy $$$w$$$ are all $$$v$$$'s ancestors, proof by contradiction if they were not,
since $$$v$$$ is finished and $$$v$$$ has a directed path to $$$w$$$, this means that $$$w$$$ has to be discovered by $$$v$$$,
but this can't be because $$$mark[w] = 1$$$ and $$$mark[v] = 2$$$.
By similar reasoning, all $$$w$$$'s are on the same path and form a chain where each is an ancestor of rest, then we know if $$$mark[x] = 1$$$ then for all ancestor's $$$a$$$ of $$$x$$$ we have $$$mark[a] = 1$$$,
so we can look at the earliest ancestor, i.e., the one with minimum height.
Basically, candidate $$$w$$$'s are like a chain of nodes going up from $$$lca(u, v)$$$ to the highest node on the path from $$$lca(u, v)$$$ to root which $$$v$$$ has directed path to.
By Claim 4, we can check if $$$mark[up[v]] == 1$$$; then we can treat this cross edge like a back edge from $$$u$$$ to $$$up[v]$$$, so we update the difference array accordingly.
Updating up[v]
We can update $$$up[v]$$$ in DSU: when merging the two components with roots $$$u$$$ & $$$v$$$ to a merged component with root $$$u$$$, we do:
if h[up[v]] < h[up[u]]
up[u] = up[v]
Note we update $$$up$$$ only for the component's root, so when looking for $$$up[u]$$$ we should do up[component_root(u)] instead.
Then the SCC for each node $$$u$$$ is: component_root(u).
Why this finds all SCCs (intuitively)
In my explanation it's obvious that every merge happening is needed.
Imagine a certain SCC like $$$C$$$, and imagine the first node of $$$C$$$ discovered in the DFS is $$$u$$$. Then since every node of $$$C$$$ is reachable from $$$u$$$, so it's like $$$C$$$ is a hanging piece of the DFS tree from $$$u$$$, and each boundary of this piece is increased when reaching a back edge or a cross edge which links that piece and up to $$$u$$$.
Correctness of the KS-SCC algorithm for strongly connected components
0. Setting, notation and the algorithm
Let $$$G=(V,E)$$$ be a finite directed multigraph (parallel edges and self-loops are allowed). Write $$$x \rightsquigarrow y$$$ if there is a directed walk from $$$x$$$ to $$$y$$$ in $$$G$$$ (every vertex reaches itself). Write $$$x \sim y$$$ if $$$x \rightsquigarrow y$$$ and $$$y \rightsquigarrow x$$$.
The relation $$$\sim$$$ is an equivalence relation (reflexive, symmetric by definition, transitive because walks can be concatenated). Its equivalence classes are the SCCs. This is the definition used in the proof, so nothing from claims 1–4 of the informal explanation is assumed. What those claims say is re-proved below as Lemmas 5, 6 and 7.
The driver and the initialization. All vertices start with $$$\texttt{mark}=0$$$, $$$\texttt{cnt}=0$$$, $$$\texttt{up}[x]=x$$$, and every vertex is its own DSU class. The driver does: for every vertex $$$r$$$ with $$$\texttt{mark}[r]=0$$$, call $$$\texttt{SCC_DFS}(r)$$$.
SCC_DFS(u):
1. mark[u] = 1
2. for each edge (u -> v):
if mark[v] == 0: // tree edge
SCC_DFS(v)
if cnt[v] > 0: Merge(u, v)
cnt[u] += cnt[v]
else if mark[v] == 1: // back edge (incl. self-loop)
cnt[u]++ ; cnt[v]--
else: // mark[v] == 2 : cross/forward edge
if mark[ up[find(v)] ] == 1:
cnt[u]++ ; cnt[ up[find(v)] ]--
3. mark[u] = 2
Merge(a, b):
A = find(a), B = find(b)
union the classes A, B, and store at the new representative R the value
up[R] = up[B] if h[up[B]] < h[up[A]], else up[A]
(The informal explanation writes $$$\texttt{up}[v]$$$ for $$$\texttt{up}[\texttt{find}(v)]$$$. Below I write $$$U(x)=\texttt{up}[\texttt{find}(x)]$$$.)
Notation about the DFS forest. The tree edges form a rooted forest $$$T$$$.
- $$$p(x)$$$ is the parent of $$$x$$$ in $$$T$$$.
- $$$h(x)$$$ is the depth of $$$x$$$ in its tree (this is the "height" of the explanation).
- $$$\operatorname{sub}(x)$$$ is the set of descendants of $$$x$$$, including $$$x$$$ itself.
- "Ancestor-or-equal" of $$$x$$$ means a vertex on the tree path from the root to $$$x$$$, including $$$x$$$.
- The activation interval of $$$c$$$ is the stretch of execution from step 1 to the end of step 3 of the call $$$\texttt{SCC_DFS}(c)$$$. A vertex is active during its activation interval, which is exactly when $$$\texttt{mark}=1$$$.
Records. Every time the algorithm executes a pair "$$$\texttt{cnt}[a]\text{++}$$$ and $$$\texttt{cnt}[b]\text{--}$$$" it makes a record $$$(a,b)$$$. In the back-edge case the record is $$$(u,v)$$$. In the cross-edge case it is $$$(u,U(v))$$$. Let $$$\mathcal R$$$ be the set of records made over the whole run.
The merged edges. Let $$$M$$$ be the set of tree edges $$$(p(v),v)$$$ for which $$$\texttt{Merge}(p(v),v)$$$ has been called. Because $$$\texttt{Merge}$$$ is only ever called on the endpoints of a tree edge, the DSU classes at any moment are exactly the connected components of the graph $$$(V,M)$$$. Write $$$K(x)$$$ for the class of $$$x$$$.
1. Basic facts about the recursion
Lemma 1 (recursion structure).
- At any moment the active vertices are exactly the vertices on the call stack. They form the tree path from a DFS root to the vertex $$$x$$$ that is currently executing. In particular, when $$$x$$$ is executing, every ancestor-or-equal of $$$x$$$ is active.
- A vertex $$$w$$$ lies in $$$\operatorname{sub}(c)$$$ if and only if $$$w$$$ is discovered during the activation interval of $$$c$$$. Moreover, a vertex of $$$\operatorname{sub}(c)$$$ executes only during that interval.
- When the edge $$$(u\to v)$$$ is examined and $$$\texttt{mark}[v]=0$$$, then $$$v$$$ becomes a child of $$$u$$$. If $$$\texttt{mark}[v]=1$$$, then $$$v$$$ is an ancestor-or-equal of $$$u$$$.
- When $$$\texttt{SCC_DFS}(v)$$$ returns to $$$p(v)$$$, the test "$$$\texttt{cnt}[v] \gt 0$$$" and the possible $$$\texttt{Merge}$$$ are executed immediately, before any other vertex executes any step.
Part 1 holds because each frame on the stack was called by the frame below it, so each vertex is the parent of the vertex above it, and a vertex is active exactly while its frame is on the stack.
For part 2, a call made while $$$c$$$'s frame is on the stack is made by a frame above (or equal to) $$$c$$$'s frame. By induction on the stack height, all such vertices are descendants of $$$c$$$. Conversely, a descendant of $$$c$$$ is called, by definition of $$$T$$$, from its parent's frame, which is above $$$c$$$'s frame or is $$$c$$$'s frame. The same argument shows that a descendant executes only while its frame is on the stack, and this happens inside $$$c$$$'s interval.
Part 3 is by definition of the tree edge (a call is made and $$$u$$$ is its caller), and by part 1 for $$$\texttt{mark}[v]=1$$$.
Part 4 is read off from the pseudocode.
Lemma 2 (shape of records).
For every record $$$(a,b)$$$, at the moment it is made, $$$b$$$ is active and is an ancestor-or-equal of $$$a$$$. In particular $$$a\in\operatorname{sub}(b)$$$.
The record is made while $$$a=u$$$ is executing. In the back-edge case $$$b=v$$$ has $$$\texttt{mark}=1$$$, so Lemma 1(3) applies. In the cross-edge case the condition $$$\texttt{mark}[b]=1$$$ is tested, so $$$b$$$ is active, and Lemma 1(1) shows that every active vertex is an ancestor-or-equal of the executing vertex $$$u$$$.
2. What $$$\texttt{cnt}$$$ counts
Lemma 3 (value of cnt).
Consider the moment when $$$\texttt{SCC_DFS}(v)$$$ is about to return (just after step 3, before the parent reads $$$\texttt{cnt}[v]$$$). Then
and every such $$$b$$$ is a proper ancestor of $$$v$$$. Thus $$$\texttt{cnt}[v] \gt 0$$$ if and only if some record has its source in $$$\operatorname{sub}(v)$$$ and its target a proper ancestor of $$$v$$$.
Fix a vertex $$$z$$$ and call $$$d(z)=#{\text{records with source } z}-#{\text{records with target } z}$$$, counted over the whole run.
Which events change $$$\texttt{cnt}[z]$$$.
- Records with source $$$z$$$ are made only while $$$z$$$ is executing, hence inside its activation interval.
- Records with target $$$z$$$ are made only while $$$z$$$ is active (Lemma 2), hence inside its activation interval.
- The addition "$$$\texttt{cnt}[z]\mathrel{+}=\texttt{cnt}[\text{child}]$$$" occurs once for each child, inside the activation interval of $$$z$$$.
No other statement touches $$$\texttt{cnt}[z]$$$. Hence at the moment $$$z$$$ is about to return,
Induction on the height of $$$\operatorname{sub}(v)$$$. Suppose that, for every child $$$w$$$ of $$$v$$$, $$$\texttt{cnt}[w]$$$ at its return equals $$$\sum_{z\in\operatorname{sub}(w)}d(z)$$$ (the base case, a leaf, is the displayed formula with no children). Then $$$\texttt{cnt}[v]=\sum_{z\in\operatorname{sub}(v)}d(z)$$$ at the return of $$$v$$$. Here $$$d(z)$$$ is the final value over the whole run. This is legitimate because every record whose source or target lies in $$$\operatorname{sub}(v)$$$ is made inside the activation interval of $$$v$$$ (by the event list above, since all vertices of $$$\operatorname{sub}(v)$$$ are active or executing only inside that interval, Lemma 1(2)). So at the moment $$$v$$$ returns, all of those records have already been made.
Evaluating the sum. With $$$S=\operatorname{sub}(v)$$$,
If $$$b\in S$$$ then $$$a\in\operatorname{sub}(b)\subseteq S$$$ by Lemma 2. Therefore every record counted in the second set is also counted in the first, and the difference is the number of records with $$$a\in S$$$ and $$$b\notin S$$$.
Proper ancestors. For such a record, $$$b$$$ is an ancestor-or-equal of $$$a$$$ (Lemma 2), so $$$b$$$ lies on the tree path from the root to $$$a$$$. That path passes through $$$v$$$ because $$$a\in\operatorname{sub}(v)$$$. Since $$$b\notin\operatorname{sub}(v)$$$, $$$b$$$ lies strictly before $$$v$$$ on this path, i.e., $$$b$$$ is a proper ancestor of $$$v$$$.
3. Structure of the DSU classes and of $$$\texttt{up}$$$
Lemma 4 (classes are tree-connected, and up is the top).
At every moment, every class $$$K$$$ has a unique vertex $$$\operatorname{top}(K)\in K$$$ of minimum depth. It is an ancestor-or-equal of every vertex of $$$K$$$ (so $$$K\subseteq\operatorname{sub}(\operatorname{top}K)$$$), and $$$U(x)=\operatorname{top}(K(x))$$$ for every $$$x$$$.
Existence and ancestor property. $$$K$$$ is a connected component of $$$(V,M)$$$ and $$$M\subseteq T$$$. For $$$x,y\in K$$$ there is a path from $$$x$$$ to $$$y$$$ using edges of $$$M$$$. It is a path in the tree $$$T$$$, hence it is the unique tree path from $$$x$$$ to $$$y$$$, and that path contains $$$\operatorname{lca}(x,y)$$$. So $$$\operatorname{lca}(x,y)\in K$$$. Taking the lca of all vertices of $$$K$$$ (repeatedly applying the above to pairs) gives a vertex $$$t\in K$$$ that is an ancestor-or-equal of all vertices of $$$K$$$. It is the unique vertex of minimum depth: any other vertex of $$$K$$$ is a proper descendant of $$$t$$$ and is deeper.
The identity $$$U=\operatorname{top}$$$. Induction over the moments at which classes change. Initially every class is a singleton $$${x}$$$ with $$$\texttt{up}[x]=x$$$. When classes $$$A=K(a)$$$ and $$$B=K(b)$$$ are merged, the union has top $$$t\in A\cup B$$$. Say $$$t\in A$$$. Since $$$t$$$ is an ancestor-or-equal of $$$\operatorname{top}(A)\in A$$$, and $$$\operatorname{top}(A)$$$ is an ancestor-or-equal of $$$t$$$, we get $$$t=\operatorname{top}(A)$$$. The same holds if $$$t\in B$$$. So $$$t\in{\operatorname{top}(A),\operatorname{top}(B)}$$$ and it is the shallower of the two. The two tops have different depths: if they had equal depth, the ancestor-or-equal relation between $$$t$$$ and the other top would force them to be equal, which is impossible for disjoint classes. By the induction hypothesis $$$\texttt{up}[\texttt{find}(a)]=\operatorname{top}(A)$$$ and $$$\texttt{up}[\texttt{find}(b)]=\operatorname{top}(B)$$$, and $$$\texttt{Merge}$$$ stores the shallower of the two (strict comparison $$$h[\text{up}[B]] \lt h[\text{up}[A]]$$$, otherwise the value of $$$A$$$).
Remark (not used later). At the moment $$$\texttt{SCC_DFS}(v)$$$ returns, the only edge of $$$T$$$ between $$$\operatorname{sub}(v)$$$ and the rest of the tree is $$$(p(v),v)$$$, and it is not yet in $$$M$$$. Hence $$$K(v)\subseteq\operatorname{sub}(v)$$$ and $$$\operatorname{top}K(v)=v$$$, which is deeper than $$$\operatorname{top}K(p(v))$$$. So the condition $$$h[\texttt{up}[B]] \lt h[\texttt{up}[A]]$$$ never holds, and $$$\texttt{up}$$$ of the merged class always keeps the value of the parent's class. The update rule is therefore harmless but redundant. The proof does not depend on this.
4. Soundness: classes never contain two different SCCs
Lemma 5 (soundness).
At every moment:
- (I1) any two vertices in the same DSU class satisfy $$$x\sim y$$$;
- (I2) every record $$$(a,b)$$$ made so far satisfies $$$a\rightsquigarrow b$$$.
We prove (I1) and (I2) together by induction over the sequence of steps of the algorithm. Initially there are no records and all classes are singletons.
Records. Suppose a record $$$(a,b)$$$ is made, and (I1) holds just before.
- Back-edge case: $$$(a\to b)$$$ is an edge of $$$G$$$, so $$$a\rightsquigarrow b$$$.
- Cross-edge case: $$$b=U(v)$$$ where $$$(a\to v)$$$ is an edge. By Lemma 4, $$$b=\operatorname{top}(K(v))\in K(v)$$$, so by (I1) $$$v\sim b$$$. Hence $$$a\to v\rightsquigarrow b$$$.
Merges. Suppose $$$\texttt{Merge}(u,v)$$$ is executed with $$$u=p(v)$$$, right after $$$\texttt{SCC_DFS}(v)$$$ returned with $$$\texttt{cnt}[v] \gt 0$$$ (Lemma 1(4): nothing else happened in between). By Lemma 3 there is a record $$$(a,b)$$$ with $$$a\in\operatorname{sub}(v)$$$ and $$$b$$$ a proper ancestor of $$$v$$$. We have:
- $$$v\rightsquigarrow a$$$, along the tree path from $$$v$$$ down to $$$a$$$;
- $$$a\rightsquigarrow b$$$ by (I2) for this record;
- $$$b\rightsquigarrow u$$$, along the tree path down from $$$b$$$ to $$$u=p(v)$$$ ($$$b$$$ is an ancestor-or-equal of $$$p(v)$$$);
- $$$u\to v$$$ is a tree edge.
So $$$v\rightsquigarrow u$$$ and $$$u\rightsquigarrow v$$$, i.e., $$$u\sim v$$$. Now take any $$$x\in K(u)$$$ and $$$y\in K(v)$$$. By (I1), $$$x\sim u$$$ and $$$v\sim y$$$, and by transitivity $$$x\sim y$$$. Therefore the merged class again satisfies (I1). Pairs inside $$$K(u)$$$ or inside $$$K(v)$$$ are unaffected.
5. Completeness: every SCC ends up inside a single class
Throughout this section fix an SCC $$$C$$$, and let $$$r$$$ be the vertex of $$$C$$$ that is discovered first (every vertex is discovered exactly once, so "first" is well-defined).
Lemma 6 (an SCC is a connected hanging piece of the tree).
- $$$C\subseteq\operatorname{sub}(r)$$$.
- For every $$$c\in C\setminus{r}$$$, the whole tree path from $$$r$$$ to $$$c$$$ lies in $$$C$$$. In particular $$$p(c)\in C$$$, and $$$r$$$ is a proper ancestor of $$$c$$$.
(1) Let $$$w\in C\setminus{r}$$$ and take a simple path $$$r=z_0\to z_1\to\dots\to z_k=w$$$ in $$$G$$$. Every $$$z_i$$$ satisfies $$$r\rightsquigarrow z_i\rightsquigarrow w\rightsquigarrow r$$$, so $$$z_i\in C$$$. In particular no $$$z_i$$$ is discovered before $$$r$$$. Suppose not all $$$z_i$$$ are in $$$\operatorname{sub}(r)$$$ and let $$$i\ge1$$$ be the smallest index with $$$z_i\notin\operatorname{sub}(r)$$$. Then $$$z_{i-1}\in\operatorname{sub}(r)$$$. When $$$z_{i-1}$$$ examines the edge $$$(z_{i-1}\to z_i)$$$, the vertex $$$r$$$ is active (Lemma 1(1),(2)), and:
- If $$$\texttt{mark}[z_i]=0$$$: $$$z_i$$$ becomes a child of $$$z_{i-1}$$$, hence lies in $$$\operatorname{sub}(r)$$$. Contradiction.
- If $$$\texttt{mark}[z_i]=1$$$: $$$z_i$$$ is an ancestor-or-equal of $$$z_{i-1}$$$, so it lies on the path from the root through $$$r$$$ to $$$z_{i-1}$$$. As $$$z_i\notin\operatorname{sub}(r)$$$, it is a proper ancestor of $$$r$$$ and was discovered before $$$r$$$, although $$$z_i\in C$$$. Contradiction.
- If $$$\texttt{mark}[z_i]=2$$$: $$$z_i$$$ was discovered after $$$r$$$ (it is in $$$C$$$ and $$$z_i\ne r$$$ since the path is simple) and has already finished while $$$r$$$ is still active. So it was discovered during the activation interval of $$$r$$$, and by Lemma 1(2) it lies in $$$\operatorname{sub}(r)$$$. Contradiction.
(2) Let $$$c\in C\setminus{r}$$$. By (1), $$$c\in\operatorname{sub}(r)$$$ and $$$c\neq r$$$, so $$$r$$$ is a proper ancestor of $$$c$$$. Every vertex $$$z$$$ on the tree path from $$$r$$$ to $$$c$$$ satisfies $$$r\rightsquigarrow z\rightsquigarrow c\rightsquigarrow r$$$ (tree edges are edges of $$$G$$$), so $$$z\in C$$$.
Lemma 7 (every non-first vertex of an SCC merges with its parent).
For every vertex $$$c\in C\setminus{r}$$$, at the moment $$$\texttt{SCC_DFS}(c)$$$ is about to return we have $$$\texttt{cnt}[c]\ge1$$$. Consequently $$$(p(c),c)\in M$$$ right after the return.
Strong induction on the finishing order of the vertices. Assume the statement holds for all vertices of $$$C\setminus{r}$$$ that finish before $$$c$$$ finishes.
Choosing an exit edge. Since $$$c\rightsquigarrow r$$$, choose a simple path $$$c=z_0\to\dots\to z_k=r$$$ in $$$G$$$. Every $$$z_i$$$ lies in $$$C$$$ (same argument as in Lemma 6(1)). The vertex $$$r$$$ is a proper ancestor of $$$c$$$ by Lemma 6(2), so $$$r\notin\operatorname{sub}(c)$$$. Let $$$i$$$ be the smallest index with $$$z_{i+1}\notin\operatorname{sub}(c)$$$, and set $$$x=z_i\in\operatorname{sub}(c)$$$, $$$y=z_{i+1}\in C\setminus\operatorname{sub}(c)$$$. The edge $$$e=(x\to y)$$$ is examined at some moment $$$\tau$$$ during the execution of $$$x$$$. At $$$\tau$$$, $$$c$$$ is active (Lemma 1(1)), and so is $$$r$$$, being an ancestor of $$$c$$$.
Case $$$\texttt{mark}[y]=0$$$ at $$$\tau$$$. Then $$$y$$$ becomes a child of $$$x$$$, so $$$y\in\operatorname{sub}(x)\subseteq\operatorname{sub}(c)$$$. Impossible.
Case $$$\texttt{mark}[y]=1$$$ at $$$\tau$$$. Then $$$y$$$ is an ancestor-or-equal of $$$x$$$ (Lemma 1(3)), and $$$y\notin\operatorname{sub}(c)$$$. The record $$$(x,y)$$$ is made, with $$$x\in\operatorname{sub}(c)$$$ and $$$y\notin\operatorname{sub}(c)$$$.
Case $$$\texttt{mark}[y]=2$$$ at $$$\tau$$$. Let $$$t=U(y)=\operatorname{top}(K(y))$$$ at moment $$$\tau$$$ (Lemma 4). We claim that $$$\texttt{mark}[t]=1$$$ at $$$\tau$$$.
- Since $$$y\in C$$$ and by (I1) of Lemma 5 all vertices of $$$K(y)$$$ are equivalent to $$$y$$$, we have $$$K(y)\subseteq C$$$ and in particular $$$t\in C$$$.
- $$$t$$$ is an ancestor-or-equal of $$$y$$$ (Lemma 4), so $$$t$$$ has been discovered: $$$\texttt{mark}[t]\in{1,2}$$$.
- Suppose, for contradiction, that $$$\texttt{mark}[t]=2$$$. Since $$$r$$$ is active at $$$\tau$$$, $$$t\ne r$$$, so $$$t\in C\setminus{r}$$$. The vertex $$$t$$$ finished before $$$\tau$$$, hence before $$$c$$$ finishes. By the induction hypothesis, $$$\texttt{cnt}[t]\ge1$$$ when $$$t$$$ returned, so by Lemma 1(4) the edge $$$(p(t),t)$$$ was put in $$$M$$$ immediately, before $$$\tau$$$. Hence $$$p(t)\in K(t)=K(y)$$$ at $$$\tau$$$ (classes only grow). But $$$h(p(t)) \lt h(t)$$$, which contradicts $$$t$$$ being the unique vertex of minimum depth in $$$K(y)$$$.
So $$$\texttt{mark}[t]=1$$$, the test succeeds, and the record $$$(x,t)$$$ is made. It remains to see that $$$t\notin\operatorname{sub}(c)$$$. If $$$t\in\operatorname{sub}(c)$$$, then $$$y\in\operatorname{sub}(t)\subseteq\operatorname{sub}(c)$$$ (Lemma 4: $$$t$$$ is an ancestor-or-equal of $$$y$$$), contradicting $$$y\notin\operatorname{sub}(c)$$$.
Conclusion. In both possible cases a record $$$(x,b)$$$ was made with $$$x\in\operatorname{sub}(c)$$$ and $$$b\notin\operatorname{sub}(c)$$$. Lemma 3 then gives $$$\texttt{cnt}[c]\ge1$$$ when $$$c$$$ returns. Note that $$$c$$$ has a parent, since $$$c\in\operatorname{sub}(r)\setminus{r}$$$. By Lemma 1(4), $$$\texttt{Merge}(p(c),c)$$$ is executed at once, so $$$(p(c),c)\in M$$$.
6. The theorem
Theorem
When the driver terminates, for all $$$x,y\in V$$$: $$$\texttt{find}(x)=\texttt{find}(y)$$$ if and only if $$$x\sim y$$$. So the DSU representative $$$\texttt{find}(x)$$$ identifies the SCC of $$$x$$$.
($$$\Rightarrow$$$) This is (I1) of Lemma 5 applied at the end of the run.
($$$\Leftarrow$$$) Let $$$x\sim y$$$ and let $$$C$$$ be their SCC with first-discovered vertex $$$r$$$. We show that every $$$c\in C$$$ lies in $$$K(r)$$$, by induction on $$$h(c)-h(r)$$$, which is $$$\ge0$$$ by Lemma 6(1). For $$$c=r$$$ this is trivial. If $$$c\ne r$$$, then $$$p(c)\in C$$$ (Lemma 6(2)) and $$$h(p(c))-h(r) \lt h(c)-h(r)$$$, so by the induction hypothesis $$$p(c)\in K(r)$$$. By Lemma 7, $$$(p(c),c)\in M$$$, so $$$c\in K(p(c))=K(r)$$$. Thus $$$C\subseteq K(r)$$$, and in particular $$$x,y\in K(r)$$$, i.e., $$$\texttt{find}(x)=\texttt{find}(y)$$$.
7. Remarks
- Cross edges include forward edges. The branch "$$$\texttt{mark}[v]=2$$$" is also taken when $$$v$$$ is a finished descendant of $$$u$$$. The proof never assumed otherwise. Lemma 5 only needs $$$u\to v\rightsquigarrow U(v)$$$, and Lemma 2 only needs $$$U(v)$$$ to be active. If $$$U(v)=u$$$, the record is $$$(u,u)$$$, which changes nothing, and $$$u\in K(v)$$$ already.
- Self-loops and parallel edges are covered by the back-edge case. A record $$$(u,u)$$$ adds $$$+1-1$$$ to the same counter. Parallel edges are counted with multiplicity, which is harmless since only "$$$\ge1$$$" matters.
- Where each informal claim went. Claims 1–2 are replaced by the definition of SCC as a class of $$$\sim$$$. Claim 3 is Lemma 5 (merge step). Claim 4 is Lemma 7 together with Lemma 4: it shows that checking only the single vertex $$$U(v)$$$, the top of $$$v$$$'s current class, is enough, because if $$$v$$$ can reach any active vertex of its SCC then its class top is active. The "hanging piece" intuition is Lemma 6.
- Complexity (not part of correctness). Each edge causes $$$O(1)$$$ $$$\texttt{find}$$$ operations and each tree edge causes at most one union, so the total is $$$O((|V|+|E|)\,\alpha(|V|))$$$ with union by size/rank and path compression.
The following is my implementation of the algorithm
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define fi first
#define se second
#define pb push_back
#define Fast ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr)
#define Tests int tt; cin >> tt; while(tt--) input(), solve(), output()
#define Single input(), solve(), output()
// 0 1 2 3 4 5 6 7 8 9 | n = 10
const int N = 1e5 + 5;
vector<int> adj[N];
int n, m, par[N], cnt[N], h[N], up[N], mark[N];
int get_par(int u) {
return par[u] < 0 ? u : par[u] = get_par(par[u]);
}
bool merge(int u, int v) {
if ((u = get_par(u)) == (v = get_par(v)))
return false;
if (par[v] < par[u])
swap(u, v);
up[u] = h[up[u]] < h[up[v]] ? up[u] : up[v];
par[u] += par[v], par[v] = u;
return true;
}
void dfs(int u) {
mark[u] = 1;
for (int v : adj[u])
if (!mark[v]) {
h[v] = h[u] + 1, dfs(v);
if (cnt[v])
merge(u, v);
cnt[u] += cnt[v];
}
else if (mark[up[get_par(v)]] == 1)
cnt[u]++, cnt[up[get_par(v)]]--;
mark[u] = 2;
}
void input() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
u--, v--;
adj[u].pb(v);
}
}
void solve() {
memset(par, -1, sizeof par);
iota(up, up + n, 0);
for (int u = 0; u < n; u++)
if (!mark[u])
dfs(u);
}
void output() {
for (int u = 0; u < n; u++)
cout << get_par(u) << ' ';
cout << '\n';
}
int main() {
Fast;
Single;
}
Note: I've abbreviated and merged the cross-edge and back-edge branch since,
if mark[v] == 1 then, by earlier explanation also mark[up[get_par(v)]] == 1.
The rest of the changes are obvious after a bit of thought.
I used ChatGPT to test KS-SCC, independently to test correctness, and on $$$10^5$$$ node graphs to see difference in runtime against Tarjan & Kosaraju.
KS-SCC — Testing and Performance Report
1. Environment and Testing Overview
KS-SCC was evaluated using GCC 14.2.0, C++23, and -O2 optimization on a 64-bit Linux environment running on an AMD EPYC 9V74 CPU.
The testing focused on three properties:
- Correctness: Comparing SCC partitions against an independent Kosaraju implementation.
- Performance: Measuring execution time across different graph structures and densities.
- Robustness: Testing edge cases, large inputs, recursion depth, and memory safety.
The test space includes exhaustive small graphs, randomized directed multigraphs, specifically constructed graph families, and large stress tests.
The complete testing methodology and environment details are provided in Section 5.
2. Complexity Analysis
Let:
- $$$V$$$ denote the number of vertices.
- $$$E$$$ denote the number of directed edges.
- $$$\alpha(V)$$$ denote the inverse Ackermann function.
2.1 Time Complexity
Every vertex is visited exactly once by DFS.
Every directed edge is examined exactly once.
DSU operations use path compression and union by size, giving an amortized complexity of $$$O(\alpha(V))$$$ per operation.
Consequently:
Since $$$\alpha(V)$$$ grows extremely slowly, the practical complexity is effectively linear.
2.2 Space Complexity
The implementation maintains five global integer arrays:
par[]cnt[]h[]up[]mark[]
Their combined storage is:
For $$$V=100,000$$$:
Approximately 1.91 MiB.
Additional memory is required for:
- Adjacency lists: $$$O(V+E)$$$.
- Recursive DFS stack: $$$O(V)$$$.
Therefore:
3. Testing Results
3.1 Exhaustive Testing
66,066 / 66,066 graphs passed.
Every possible simple directed graph was generated for $$$1\leq V\leq4$$$, including self-loops.
| Vertices | Graphs generated | Passed |
|---|---|---|
| 1 | 2 | 2 |
| 2 | 16 | 16 |
| 3 | 512 | 512 |
| 4 | 65,536 | 65,536 |
| Total | 66,066 | 66,066 |
No incorrect SCC partitions were reported.
3.2 Randomized Testing
50,000 / 50,000 graphs passed.
Generator specifications:
- $$$1\leq V\leq30$$$
- $$$0\leq E\leq2V^2$$$
- Both endpoints of every edge selected independently and uniformly.
- Self-loops allowed.
- Parallel edges allowed.
- Multiple identical directed edges allowed.
| Statistic | Result |
|---|---|
| Generated graphs | 50,000 |
| Generated edges | 15,792,586 |
| Graphs containing self-loops | 47,047 |
| Graphs containing parallel edges | 45,539 |
| Incorrect partitions | 0 |
The generator used a fixed seed (0xA17A2026) for reproducibility.
3.3 Structural Testing
The following graph families were included:
| Graph structure | Expected SCC structure |
|---|---|
| Empty graph | Every vertex is a singleton |
| Self-loops only | Every vertex is a singleton |
| Directed chain | Every vertex is a singleton |
| Directed cycle | One SCC |
| Bidirectional chain | One SCC |
| Disconnected cycles | One SCC per cycle |
| Multiple SCCs connected in a DAG | Original SCCs remain separate |
| Cross-component edges | No incorrect merging |
| Parallel edges | No change in SCC membership |
3.4 Large Stress Testing
All large structural tests used 100,000 vertices.
| Graph | Vertices | Edges | Expected SCCs |
|---|---|---|---|
| Empty graph | 100,000 | 0 | 100,000 |
| Self-loops only | 100,000 | 100,000 | 100,000 |
| Directed chain | 100,000 | 99,999 | 100,000 |
| Directed cycle | 100,000 | 100,000 | 1 |
| Bidirectional chain | 100,000 | 199,998 | 1 |
| 50,000 connected pairs | 100,000 | 149,999 | 50,000 |
| Random directed graph | 100,000 | 400,000 | Reference-dependent |
| Random directed graph | 100,000 | 1,000,000 | Reference-dependent |
Random graph cases were evaluated against reference partitions rather than assuming a particular SCC count.
3.5 Recursion Depth
A directed chain was used to maximize DFS depth.
| Vertices | Expected DFS depth | Result |
|---|---|---|
| 10,000 | 10,000 | PASS |
| 20,000 | 20,000 | PASS |
| 30,000 | 30,000 | PASS |
| 40,000 | 40,000 | PASS |
| 50,000 | 50,000 | PASS |
| 60,000 | 60,000 | PASS |
| 70,000 | 70,000 | PASS |
| 80,000 | 80,000 | PASS |
| 90,000 | 90,000 | PASS |
| 100,000 | 100,000 | PASS |
The 100,000-vertex test required a 64 MiB stack limit. It should not be assumed to pass with the default 8 MiB stack limit.
3.6 Sanitizer Testing
Compilation configuration:
g++ -std=c++23 -O1 -g \
-fsanitize=address,undefined \
-fno-omit-frame-pointer
| Test category | Graphs | Result |
|---|---|---|
| Exhaustive | 66,066 | PASS |
| Randomized | 50,000 | PASS |
| AddressSanitizer errors | 0 | PASS |
| UndefinedBehaviorSanitizer errors | 0 | PASS |
The sanitizer results should be interpreted separately from optimized runtime measurements.
4. Comparison Against Tarjan and Kosaraju
All three implementations were evaluated using the same graph instances.
4.1 Time Complexity
| Property | KS-SCC | Tarjan | Kosaraju |
|---|---|---|---|
| Time complexity | $$$O((V+E)\alpha(V))$$$ | $$$O(V+E)$$$ | $$$O(V+E)$$$ |
| DFS passes | 1 | 1 | 2 |
| DSU operations | Yes | No | No |
| Reverse graph required | No | No | Yes |
4.2 Space Complexity
| Property | KS-SCC | Tarjan | Kosaraju |
|---|---|---|---|
| Overall space | $$$O(V+E)$$$ | $$$O(V+E)$$$ | $$$O(V+E)$$$ |
| Forward adjacency | Yes | Yes | Yes |
| Reverse adjacency | No | No | Yes |
| Auxiliary arrays | 5 integer arrays | Implementation-dependent | Implementation-dependent |
| Recursive stack | $$$O(V)$$$ | $$$O(V)$$$ | $$$O(V)$$$ |
4.3 Runtime Comparison
Benchmark configuration:
- 100,000 vertices per graph.
- GCC 14.2.0.
- C++23.
-O2.- AMD EPYC 9V74.
- 15 executions per algorithm.
- Median runtime reported.
- 64 MiB stack limit.
- Graph generation and input/output excluded.
All times are in milliseconds.
| Graph | Vertices | Edges | KS-SCC | Tarjan | Kosaraju |
|---|---|---|---|---|---|
| Directed chain | 100,000 | 99,999 | 0.964 | 2.230 | 5.331 |
| Directed cycle | 100,000 | 100,000 | 2.386 | 2.587 | 6.820 |
| Bidirectional chain | 100,000 | 199,998 | 2.009 | 2.514 | 7.520 |
| Paired SCC DAG | 100,000 | 149,999 | 1.954 | 2.258 | 6.418 |
| Random graph | 100,000 | 400,000 | 21.761 | 22.367 | 63.347 |
| Random graph | 100,000 | 1,000,000 | 36.566 | 23.853 | 86.891 |
4.4 Runtime Summary
| Algorithm | Directed chain | Directed cycle | Paired SCC DAG | Random 400K | Random 1M |
|---|---|---|---|---|---|
| KS-SCC | 0.964 | 2.386 | 1.954 | 21.761 | 36.566 |
| Tarjan | 2.230 | 2.587 | 2.258 | 22.367 | 23.853 |
| Kosaraju | 5.331 | 6.820 | 6.418 | 63.347 | 86.891 |
Times are in milliseconds.
KS-SCC recorded the lowest runtime on five of the six tested graph families.
On the 1,000,000-edge random graph, Tarjan was faster.
The measured results are specific to the stated environment and graph instances.
5. Testing Facility and Methodology
5.1 Environment
| Parameter | Configuration |
|---|---|
| CPU | AMD EPYC 9V74 |
| Architecture | x86-64 |
| OS | Linux |
| Compiler | GCC 14.2.0 |
| Language standard | C++23 |
| Optimized build | -O2 |
| Sanitizer build | -O1 -g |
| Benchmark stack limit | 64 MiB |
| Maximum tested vertices | 100,000 |
| Maximum tested edges | 1,000,000 |
5.2 Reference Implementation
An independent Kosaraju implementation was used as the correctness reference.
For each graph, both implementations generated an SCC assignment.
The assignments were normalized before comparison.
Two vertices $$$u$$$ and $$$v$$$ must satisfy:
This verifies the complete SCC partition rather than component numbering.
Different algorithms can assign different component IDs or DSU representatives to identical SCCs, so direct numerical comparison would be incorrect.
5.3 Exhaustive Graph Generator
For a graph with $$$V$$$ vertices, there are $$$V^2$$$ possible directed edges when self-loops are included.
Every possible subset of these edges was enumerated.
The total number of generated graphs is:
For $$$V=4$$$:
This provides complete coverage of simple directed graphs up to four vertices.
5.4 Random Graph Generator
Random directed multigraphs were generated by independently selecting both endpoints of every edge.
This allows:
- Self-loops.
- Parallel edges.
- Repeated edges.
- Disconnected components.
- Arbitrary directed cycles.
A fixed random seed ensures reproducibility.
5.5 Structural Generators
Dedicated generators construct graph families with known SCC partitions.
These include:
- Directed chains.
- Directed cycles.
- Bidirectional chains.
- Disconnected cycles.
- Collections of small SCCs connected by directed edges.
- Large strongly connected graphs.
These tests verify specific graph structures independently of the reference algorithm.
5.6 Stress Testing
Large graphs were generated directly in memory.
The objectives were:
- Verify behavior at maximum vertex counts.
- Evaluate performance at different edge densities.
- Exercise long DFS paths.
- Exercise large SCCs.
- Exercise large numbers of independent SCCs.
- Detect stack exhaustion.
- Evaluate memory consumption.
5.7 Performance Measurement
Each algorithm was executed on identical graph instances.
The measured execution time includes:
- Algorithm-specific initialization.
- Required preprocessing.
- SCC computation.
- Component extraction.
It excludes:
- Graph generation.
- File input.
- Console output.
Each configuration was executed 15 times, and the median execution time was recorded.
std::chrono::steady_clock is the appropriate monotonic clock for measuring these intervals.
Kosaraju's reverse adjacency construction was included in its timing.
5.8 Memory Measurement
Memory requirements were evaluated using the implementation's data structures and asymptotic storage requirements.
A complete empirical comparison requires peak resident set size (RSS) measurements in separate processes.
The measurement should include:
- Adjacency storage.
- Auxiliary arrays.
- DSU storage.
- Recursion stack.
- Dynamic allocation overhead.
Theoretical array sizes should not be confused with total process memory.
6. Conclusion
KS-SCC has the following theoretical characteristics:
- Time complexity: $$$O((V+E)\alpha(V))$$$.
- Space complexity: $$$O(V+E)$$$.
- One DFS traversal.
- One forward adjacency list.
- DSU-based component management.
The reported correctness test suite covers 66,066 exhaustive graphs, 50,000 randomized multigraphs, and large structural cases up to 100,000 vertices.
In the runtime comparison, KS-SCC recorded the lowest execution time on five of six tested graph families.
Tarjan was faster on the 1,000,000-edge random graph.
The implementation therefore demonstrates competitive measured performance, effectively linear practical complexity, and successful handling of a broad range of graph structures.
I might have made a bigger deal out of this than it is but it was really fun for me to write this blog so I hope it was worthwhile.
I did not find anything similar by doing a quick search online but if anybody found an earlier discovery of the same solution they can share in the comments.
I checked everything I said multiple times to make sure whatever I said is correct, but I'm relatively in the beginning of my CP journey(8 months in) so if a more experienced coder can check what I said, I would truly appreciate it.
Also, I'm not technical enough and don't even think I have the required specs to run my own tests so I used ChatGPT for testing KS-SCC, and was overjoyed to see it outperformed Tarjan and Kosaraju at least for $$$n, m \lt = 10^5$$$ but I am not sure how trustworthy it is so if anybody is willing to test my code I will be eternally grateful.
This is the first version of KS-SCC and I did not spend much time on optimizing it, for instance I think the up[] array can be fully eliminated.
So I'm open to any and all suggestions for edits & optimization.
UPD1:
Im examining it along with DFS Tree to come up with a simpler explanation, In the meantime if anybody is struggling on grasping the concept i will be happy to answer any questions they have in my messages.
Im also attempting to write the full proof myself but take this with a grain of salt since I doubt I would be able to come up with and adequate proof.
And btw does anybody know what are the requirements on making it into Catalog? Is it even possible for me given that im a specialist?
If anybody has any info on this i would be extremely thankful if they could help me.









Auto comment: topic has been updated by Tabriz-Talayi (previous revision, new revision, compare).
Auto comment: topic has been updated by Tabriz-Talayi (previous revision, new revision, compare).
Auto comment: topic has been updated by Tabriz-Talayi (previous revision, new revision, compare).
next target to reach : Find the Chromatic number of a graph
And congratulations on finding a new algorithm . its really admirable. be gold
Thank you pouya!
Auto comment: topic has been updated by Tabriz-Talayi (previous revision, new revision, compare).
Auto comment: topic has been updated by Tabriz-Talayi (previous revision, new revision, compare).
idk why this is being downvoted
OP, you should read about DFS trees, they'll give you more insight here
Thank you, i will look into it
Auto comment: topic has been updated by Tabriz-Talayi (previous revision, new revision, compare).
mashala shir
ماشاالله آقا تبریز
Benazam bi nazir bood
I am so proud of you
eshghi tabriz jooonam
mashala agha tabriz