Big O Gym › Problem

Big O Practice: Clone Graph

Time and space complexity practice in Python and JavaScript. Concept tested: graph traversal: vertex + edge cost.

def clone_graph(node):
    if not node:
        return None
    visited = {}

    def dfs(cur):
        if cur in visited:
            return visited[cur]
        clone = Node(cur.val)
        visited[cur] = clone
        for nb in cur.neighbors:
            clone.neighbors.append(dfs(nb))
        return clone

    return dfs(node)

Variables

  • v - number of vertices (graph nodes)
  • e - number of edges

Explanation

Each vertex is cloned once and each edge is traversed once (twice in an undirected graph, still O(e)) - total time **O(V + E)**. The visited map holds one entry per vertex; the recursion stack is bounded by the longest path, also at most `V` - **O(V)** auxiliary.

More Big O practice problems · Today's daily problem