← Daily Logs
Algorithms

Largest Component (Graph)

EasyJul 5, 2026graphdfsconnected-components

One line away from `connectedComponentsCount`: instead of `exploreGraph` returning a flat `1` for 'found a component', it returns the component's actual size, and the outer loop swaps `+=` for `Math.max`. Same shared `visited` set, same reason a component is never measured twice — only what gets returned per call changes.

The problem

Implement `largestComponent(graph)` returning the size (node count) of the biggest connected component in an adjacency-list graph. The two-cluster graph (`0`/`1`/`5`/`8` vs. `2`/`3`/`4`) should return `4`, since the first cluster has one more node than the second.

Single-node components all return `1`, not `0` — `largestComponent({a: [], b: [], c: []})` is `1`, because every isolated node is still a component of size one; only the fully empty graph (`{}`) returns `0`, since the outer loop never runs and `maxSize` never leaves its initial value.

The approach

`exploreGraph` gains a local counter, `sizeOfComponent`, seeded at `1` for the source node itself and incremented every time an unvisited neighbour gets pushed onto the stack. Because that increment happens at the same place a node is marked `visited`, it counts each node in the component exactly once, regardless of how many edges point back to it.

The outer loop no longer sums — `connectedComponentsCount` wanted 'how many components exist' (add one per component found), but here the question is 'how big is the biggest one', so `Math.max(maxSize, ...)` replaces `+=`. Nodes already in a counted component still return `0` from the `visited.has(source)` guard, and `0` never wins a `Math.max` against a real component's size, so revisits are harmless rather than needing a separate check.

Nothing about the traversal changed — same stack, same `visited` set passed by reference so a component already walked doesn't get walked (or measured) again. The only edits versus `connectedComponentsCount` are the counter inside `exploreGraph` and the reduction operator in the outer loop.

The solution

js
export function largestComponent(graph) {
    const visited = new Set()
    let maxSize = 0
    for (let node in graph) {
        maxSize = Math.max(maxSize, exploreGraph(graph, node, visited))
    }
    return maxSize
}

export function exploreGraph(graph, source, visited) {
    if (visited.has(source)) return 0
    visited.add(source)
    let sizeOfComponent = 1
    const stack = [source]
    while (stack.length) {
        const node = stack.pop()
        for (let neighbour of graph[node]) {
            if (!visited.has(neighbour)) {
                visited.add(neighbour)
                stack.push(neighbour)
                sizeOfComponent++
            }

        }
    }
    return sizeOfComponent
}

Time O(V + E)Space O(V)

All entries