{ "data": { "question": { "questionId": "133", "questionFrontendId": "133", "boundTopicId": null, "title": "Clone Graph", "titleSlug": "clone-graph", "content": "

Given a reference of a node in a connected undirected graph.

\n\n

Return a deep copy (clone) of the graph.

\n\n

Each node in the graph contains a value (int) and a list (List[Node]) of its neighbors.

\n\n
\nclass Node {\n    public int val;\n    public List<Node> neighbors;\n}\n
\n\n

 

\n\n

Test case format:

\n\n

For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.

\n\n

An adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.

\n\n

The given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.

\n\n

 

\n

Example 1:

\n\"\"\n
\nInput: adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput: [[2,4],[1,3],[2,4],[1,3]]\nExplanation: There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n
\n\n

Example 2:

\n\"\"\n
\nInput: adjList = [[]]\nOutput: [[]]\nExplanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.\n
\n\n

Example 3:

\n\n
\nInput: adjList = []\nOutput: []\nExplanation: This an empty graph, it does not have any nodes.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 9002, "dislikes": 3594, "isLiked": null, "similarQuestions": "[{\"title\": \"Copy List with Random Pointer\", \"titleSlug\": \"copy-list-with-random-pointer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone Binary Tree With Random Pointer\", \"titleSlug\": \"clone-binary-tree-with-random-pointer\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Clone N-ary Tree\", \"titleSlug\": \"clone-n-ary-tree\", \"difficulty\": \"Medium\", \"translatedTitle\": null}]", "exampleTestcases": "[[2,4],[1,3],[2,4],[1,3]]\n[[]]\n[]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Hash Table", "slug": "hash-table", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Depth-First Search", "slug": "depth-first-search", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Breadth-First Search", "slug": "breadth-first-search", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Graph", "slug": "graph", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "/*\n// Definition for a Node.\nclass Node {\npublic:\n int val;\n vector neighbors;\n Node() {\n val = 0;\n neighbors = vector();\n }\n Node(int _val) {\n val = _val;\n neighbors = vector();\n }\n Node(int _val, vector _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n};\n*/\n\nclass Solution {\npublic:\n Node* cloneGraph(Node* node) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "/*\n// Definition for a Node.\nclass Node {\n public int val;\n public List neighbors;\n public Node() {\n val = 0;\n neighbors = new ArrayList();\n }\n public Node(int _val) {\n val = _val;\n neighbors = new ArrayList();\n }\n public Node(int _val, ArrayList _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\nclass Solution {\n public Node cloneGraph(Node node) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "\"\"\"\n# Definition for a Node.\nclass Node(object):\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n\"\"\"\n\nclass Solution(object):\n def cloneGraph(self, node):\n \"\"\"\n :type node: Node\n :rtype: Node\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n\"\"\"\n\nfrom typing import Optional\nclass Solution:\n def cloneGraph(self, node: Optional['Node']) -> Optional['Node']:\n ", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "/**\n * Definition for a Node.\n * struct Node {\n * int val;\n * int numNeighbors;\n * struct Node** neighbors;\n * };\n */\n\nstruct Node *cloneGraph(struct Node *s) {\n\t\n}", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "/*\n// Definition for a Node.\npublic class Node {\n public int val;\n public IList neighbors;\n\n public Node() {\n val = 0;\n neighbors = new List();\n }\n\n public Node(int _val) {\n val = _val;\n neighbors = new List();\n }\n\n public Node(int _val, List _neighbors) {\n val = _val;\n neighbors = _neighbors;\n }\n}\n*/\n\npublic class Solution {\n public Node CloneGraph(Node node) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * // Definition for a Node.\n * function Node(val, neighbors) {\n * this.val = val === undefined ? 0 : val;\n * this.neighbors = neighbors === undefined ? [] : neighbors;\n * };\n */\n\n/**\n * @param {Node} node\n * @return {Node}\n */\nvar cloneGraph = function(node) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "/**\n * Definition for Node.\n * class Node {\n * val: number\n * neighbors: Node[]\n * constructor(val?: number, neighbors?: Node[]) {\n * this.val = (val===undefined ? 0 : val)\n * this.neighbors = (neighbors===undefined ? [] : neighbors)\n * }\n * }\n */\n\nfunction cloneGraph(node: Node | null): Node | null {\n\t\n};", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "/**\n * Definition for a Node.\n * class Node {\n * public $val = null;\n * public $neighbors = null;\n * function __construct($val = 0) {\n * $this->val = $val;\n * $this->neighbors = array();\n * }\n * }\n */\n\nclass Solution {\n /**\n * @param Node $node\n * @return Node\n */\n function cloneGraph($node) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "/**\n * Definition for a Node.\n * public class Node {\n * public var val: Int\n * public var neighbors: [Node?]\n * public init(_ val: Int) {\n * self.val = val\n * self.neighbors = []\n * }\n * }\n */\n\nclass Solution {\n func cloneGraph(_ node: Node?) -> Node? {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "/**\n * Definition for a Node.\n * class Node(var `val`: Int) {\n * var neighbors: ArrayList = ArrayList()\n * }\n */\n\nclass Solution {\n fun cloneGraph(node: Node?): Node? {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "/**\n * Definition for a Node.\n * type Node struct {\n * Val int\n * Neighbors []*Node\n * }\n */\n\nfunc cloneGraph(node *Node) *Node {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# Definition for a Node.\n# class Node\n# attr_accessor :val, :neighbors\n# def initialize(val = 0, neighbors = nil)\n#\t\t @val = val\n#\t\t neighbors = [] if neighbors.nil?\n# @neighbors = neighbors\n# end\n# end\n\n# @param {Node} node\n# @return {Node}\ndef cloneGraph(node)\n \nend", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "/**\n * Definition for a Node.\n * class Node(var _value: Int) {\n * var value: Int = _value\n * var neighbors: List[Node] = List()\n * }\n */\n\nobject Solution {\n def cloneGraph(graph: Node): Node = {\n \n }\n}", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"1.1M\", \"totalSubmission\": \"2M\", \"totalAcceptedRaw\": 1114974, \"totalSubmissionRaw\": 2005665, \"acRate\": \"55.6%\"}", "hints": [], "solution": { "id": "814", "canSeeDetail": false, "paidOnly": true, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "[[2,4],[1,3],[2,4],[1,3]]", "metaData": "{\n \"name\": \"cloneGraph\",\n \"params\": [\n {\n \"name\": \"edges\",\n \"type\": \"integer[][]\"\n }\n ],\n \"return\": {\n \"type\": \"boolean\"\n },\n \"languages\": [\n \"cpp\",\n \"java\",\n \"python\",\n \"csharp\",\n \"javascript\",\n \"python3\",\n \"golang\",\n \"swift\",\n \"kotlin\",\n \"ruby\",\n \"c\",\n \"scala\",\n \"php\",\n \"typescript\"\n ],\n \"manual\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 20 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17. Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 8.2 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O1). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.21

\\r\\n

Support https://godoc.org/github.com/emirpasic/gods@v1.18.1 library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.9.0.

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 5.1.6, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": { "id": "1296", "date": "2023-04-08", "incompleteChallengeCount": 0, "streakCount": 0, "type": "DAILY", "__typename": "ChallengeQuestionNode" }, "__typename": "QuestionNode" } } }