← Capgemini bank

Capgemini · Question 59 · Graphs

Clone Graph

GraphsC++code⏱ O(n+e)💾 O(n)
Service-based

Problem

You are given reference of node in connected undirected graph. Return deep copy.

Approach

DFS-clone each node once, memoizing copies in a hashmap.

Time O(n+e)Space O(n)

How it works

  1. 1Clone nodes on first DFS visit.
  2. 2Memoize to preserve sharing and cycles; driver sorts for stability.

Sample input / output

Input:
adjList = [[2, 4], [1, 3], [2, 4], [1, 3]]
Output:
[[1, [2, 4]], [2, [1, 3]], [3, [2, 4]], [4, [1, 3]]]

Constraints

0 <= nodes <= 100; connected undirected graph.

Solution — read it, then walk it

Time O(n+e)Space O(n)Loops 7Branches 3Returns 1source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <unordered_map>include <algorithm>include <set>using namespace stdCLASS NodeDEFINE valvector<Node*> neighborsNode(int v) : val(v) {}Node* cloneGraph(Node*node, unordered_map<Node*,Node*>& visited)Node* cloneGraph(Node*node)DEFINE main()vector<Node*> nodesfor (int i = 1; i <=4; ++i)nodes.push_back(ne…vector<vector<int>> links ={{2, 4}, {1, 3}, {2, 4},{1, 3}}for (size_t i = 0; i <nodes.size(); ++i)for (int v : links[i])nodes[i]->neighbors.push_back(nodes[v- 1])Node* clone =cloneGraph(nodes[0])set<Node*> seenvector<Node*> stack ={clone}vector<pair<int,vector<int>>> outwhile (!stack.empty())Node* cur = stack.back()stack.pop_back()if (seen.count(cur))continueseen.insert(cur)vector<int> adjfor (Node* nb :cur->neighbors)adj.push_back(nb->val)stack.push_back(nb)sort(adj.begin(),adj.end())out.push_back({cur->val,adj})sort(out.begin(),out.end())cout << "["for (size_t i = 0; i <out.size(); ++i)if (i) cout << ", "cout << "[" << out[i].first<< ", ["for (size_t j = 0; j <out[i].second.size();++j)if (j) cout << ", "cout << out[i].second[j]cout << "]]"cout << "]" << endlRETURN 0END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/45

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits