Find Interview Questions for Top Companies
Allied testing Interview Questions and Answers
Ques:- Write a function to copy a graph
Right Answer:
```python
class Node:
def __init__(self, val):
self.val = val
self.neighbors = []

def cloneGraph(node):
if not node:
return None

# Dictionary to hold the mapping from original node to its clone
clone_map = {}

def dfs(n):
if n in clone_map:
return clone_map[n]

# Create a clone for the current node
clone = Node(n.val)
clone_map[n] = clone

# Recursively clone the neighbors
for neighbor in n.neighbors:
clone.neighbors.append(dfs(neighbor))

return clone

return dfs(node)
```
AmbitionBox Logo

What makes Takluu valuable for interview preparation?

1 Lakh+
Companies
6 Lakh+
Interview Questions
50K+
Job Profiles
20K+
Users