graphs · Problem 1 of 2

Count Connected Components

medium
Amazon logoAmazon
Google logoGoogle

graph maps each node to its neighbours. Return how many connected components it has.

countComponents({ "a": ["b"], "b": ["a"], "c": [] }) -> 2

Your solution

Runs your code and animates it without grading anything. Change the input to see what it does on a case the tests do not cover.

Running is free — Submit is what records it. Or press ⌘↩

Tests

4 cases, 1 hidden
calltypeexpectedresult
countComponents({"a":["b"],"b":["a"],"c":[]})two components2
countComponents({"a":["b"],"b":["a","c"],"c":["b"]})one component1
countComponents({})empty graph0
withheldhiddenwithheld

Hidden cases run too — their inputs aren't listed here, so aim for a general solution rather than one fitted to the cases above.

Complexity

target time
O(V + E)
target space
O(V)

Every node and edge is examined once. The visited set is what makes that true — without it a cycle never terminates.

Hints

Stuck? Hints open one at a time, each giving a little more away.

3 hints left