InferenceAI

Enter at least two characters to search.

Start free

Clone a Graph

mediumGraphs25 min25 XP

An undirected graph with nodes 1..n is given as adj, where adj[i] lists the neighbours of node i + 1. Deep-copy it by traversing from node 1, and return the copy's adjacency list in the same format, with each neighbour list sorted. Nodes not reachable from node 1 get an empty list.

Examples

EXAMPLE WALKTHROUGHsquare

A guided view of the published example, not a trace of your code.

INPUT[[[2,4],[1,3],[2,4],[1,3]]]
TASKclone_graph_edges()
EXPECTED OUTPUT[[2,4],[1,3],[2,4],[1,3]]

Start with the input values shown in this example.

Example 1 of 3

Input: adj = [[2,4],[1,3],[2,4],[1,3]]

Output: [[2,4],[1,3],[2,4],[1,3]]

Explanation: square

Input: adj = [[]]

Output: [[]]

Explanation: single node

Input: adj = []

Output: []

Explanation: empty graph

Hint 1

Traverse with BFS or DFS, keeping a map from original node to its copy so each node is cloned once.

Topics

DSAGraphsPython