🖥️
Code Snippets
  • Introduction
  • Ami's
    • Topics
      • Arrays
      • Bits & Operators
      • Graph
      • Heap
      • Linked List
      • Maths
      • Matrix
      • Queue
      • Recursion
        • Water and Jug Problem
      • Regular Expression
      • Searching
      • Sorting
      • Stack
      • String
      • Trees
  • leetcode
    • Problems
      • 1-100
        • 1. Two Sum
        • 2. Add Two Numbers
        • 3. Longest Substring Without Repeating Characters
        • 4. Median of Two Sorted Arrays
        • 5. Longest Palindromic Substring
        • 6. ZigZag Conversion
        • 7. Reverse Integer
        • 8. String to Integer (atoi)
        • 9. Palindrome Number
        • 10. Regular Expression Matching
        • 12. Integer to Roman
        • 13. Roman to Integer
        • 15. 3Sum
        • 17. Letter Combinations of a Phone Number
        • 22. Generate Parentheses
        • 29. Divide Two Integers
        • 31. Next Permutation
        • 34. Find First and Last Position of Element in Sorted Array
        • 36. Valid Sudoku
        • 37. Sudoku Solver
        • 38. Count and Say
        • 43. Multiply Strings
        • 44. Wildcard Matching
        • 45. Jump Game II
        • 48. Rotate Image
        • 49. Group Anagrams
        • 51. N-Queens
        • 52. N-Queens II
        • 63. Unique Paths II
        • 65. Valid Number
        • 67. Add Binary
        • 68. Text Justification
        • 69. Sqrt(x)
        • 70. Climbing Stairs
        • 71. Simplify Path
        • 72. Edit Distance
        • 73. Set Matrix Zeroes
        • 74. Search a 2D Matrix
        • 75. Sort Colors
        • 76. Minimum Window Substring
        • 77. Combinations
        • 78. Subsets
        • 79. Word Search
        • 80. Remove Duplicates from Sorted Array II
        • 81. Search in Rotated Sorted Array II
        • 82. Remove Duplicates from Sorted List II
        • 83. Remove Duplicates from Sorted List
        • 84. Largest Rectangle in Histogram
        • 85. Maximal Rectangle
        • 86. Partition List
        • 87. Scramble String
        • 88. Merge Sorted Array
        • 89. Gray Code
        • 90. Subsets II
        • 91. Decode Ways
        • 92. Reverse Linked List II
        • 93. Restore IP Addresses
        • 94. Binary Tree Inorder Traversal
        • 95. Unique Binary Search Trees II
        • 96. Unique Binary Search Trees
        • 97. Interleaving String
        • 98. Validate Binary Search Tree
        • 99. Recover Binary Search Tree
        • 100. Same Tree
      • 101-200
        • 101. Symmetric Tree
        • 102. Binary Tree Level Order Traversal
        • 103. Binary Tree Zigzag Level Order Traversal
        • 104. Maximum Depth of Binary Tree
        • 105. Construct Binary Tree from Preorder and Inorder Traversal
        • 106. Construct Binary Tree from Inorder and Postorder Traversal
        • 107. Binary Tree Level Order Traversal II
        • 108. Convert Sorted Array to Binary Search Tree
        • 109. Convert Sorted List to Binary Search Tree
        • 110. Balanced Binary Tree
        • 111. Minimum Depth of Binary Tree
        • 112. Path Sum
        • 113. Path Sum II
        • 114. Flatten Binary Tree to Linked List
        • 115. Distinct Subsequences
        • 116. Populating Next Right Pointers in Each Node
        • 117. Populating Next Right Pointers in Each Node II
        • 118. Pascal's Triangle
        • 119. Pascal's Triangle II
        • 120. Triangle
        • 121. Best Time to Buy and Sell Stock
        • 122. Best Time to Buy and Sell Stock II
        • 123. Best Time to Buy and Sell Stock III
        • 124. Binary Tree Maximum Path Sum
        • 125. Valid Palindrome
        • 126. Word Ladder II
        • 127. Word Ladder
        • 128. Longest Consecutive Sequence
        • 129. Sum Root to Leaf Numbers
        • 130. Surrounded Regions
        • 131. Palindrome Partitioning
        • 132. Palindrome Partitioning II
        • 133. Clone Graph
        • 134. Gas Station
        • 135. Candy
        • 136. Single Number
        • 137. Single Number II
        • 138. Copy List with Random Pointer
        • 139. Word Break
        • 140. Word Break II
        • 141. Linked List Cycle
        • 142. Linked List Cycle II
        • 143. Reorder List
        • 144. Binary Tree Preorder Traversal
        • 145. Binary Tree Postorder Traversal
        • 146. LRU Cache
        • 147. Insertion Sort List
        • 148. Sort List
        • 149. Max Points on a Line
        • 150. Evaluate Reverse Polish Notation
        • 151. Reverse Words in a String
        • 152. Maximum Product Subarray
        • 153. Find Minimum in Rotated Sorted Array
        • 154. Find Minimum in Rotated Sorted Array II
        • 155. Min Stack
        • 156. Binary Tree Upside Down
        • 157. Read N Characters Given Read4
        • 158. Read N Characters Given Read4 II - Call multiple times
        • 159. Longest Substring with At Most Two Distinct Characters
        • 160. Intersection of Two Linked Lists
        • 161. One Edit Distance
        • 162. Find Peak Element
        • 163. Missing Ranges
        • 164. Maximum Gap
        • 165. Compare Version Numbers
        • 166. Fraction to Recurring Decimal
        • 167. Two Sum II - Input array is sorted
        • 168. Excel Sheet Column Title
        • 169. Majority Element
        • 170. Two Sum III - Data structure design
        • 171. Excel Sheet Column Number
        • 172. Factorial Trailing Zeroes
        • 173. Binary Search Tree Iterator
        • 175. Combine Two Tables
        • 176. Second Highest Salary
        • 177. Nth Highest Salary
        • 178. Rank Scores
        • 179. Largest Number
        • 180. Consecutive Numbers
        • 181. Employees Earning More Than Their Managers
        • 182. Duplicate Emails
        • 183. Customers Who Never Order
        • 184. Department Highest Salary
        • 185. Department Top Three Salaries
        • 186. Reverse Words in a String II
        • 187. Repeated DNA Sequences
        • 188. Best Time to Buy and Sell Stock IV
        • 189. Rotate Array
        • 190. Reverse Bits
        • 191. Number of 1 Bits
        • 192. Word Frequency
        • 193. Valid Phone Numbers
        • 194. Transpose File
        • 195. Tenth Line
        • 196. Delete Duplicate Emails
        • 197. Rising Temperature
        • 198. House Robber
        • 199. Binary Tree Right Side View
        • 200. Number of Islands
      • 201-300
        • 201. Bitwise AND of Numbers Range
        • 202. Happy Number
        • 203. Remove Linked List Elements
        • 204. Count Primes
        • 205. Isomorphic Strings
        • 206. Reverse Linked List
        • 207. Course Schedule
        • 208. Implement Trie (Prefix Tree)
        • 209. Minimum Size Subarray Sum
        • 210. Course Schedule II
        • 211. Design Add and Search Words Data Structure
        • 212. Word Search II
        • 213. House Robber II
        • 214. Shortest Palindrome
        • 215. Kth Largest Element in an Array
        • 216. Combination Sum III
        • 217. Contains Duplicate
        • 219. Contains Duplicate II
        • 220. Contains Duplicate III
        • 221. Maximal Square
        • 222. Count Complete Tree Nodes
        • 223. Rectangle Area
        • 224. Basic Calculator
        • 226. Invert Binary Tree
        • 234. Palindrome Linked List
        • 235. Lowest Common Ancestor of a Binary Search Tree
        • 236. Lowest Common Ancestor of a Binary Tree
        • 238. Product of Array Except Self
        • 240. Search a 2D Matrix II
        • 246. Strobogrammatic Number
        • 252. Meeting Rooms
        • 253. Meeting Rooms II
        • 257. Binary Tree Paths
        • 268. Missing Number
        • 273. Integer to English Words
        • 279. Perfect Squares
        • 285. Inorder Successor in BST
        • 289. Game of Life
        • 295. Find Median from Data Stream
        • 300. Longest Increasing Subsequence
      • 301-400
        • 304. Range Sum Query 2D - Immutable
        • 316. Remove Duplicate Letters
        • 318. Maximum Product of Word Lengths
        • 322. Coin Change
        • 323. Number of Connected Components in an Undirected Graph
        • 326. Power of Three
        • 329. Longest Increasing Path in a Matrix
        • 341. Flatten Nested List Iterator
        • 365. Water and Jug Problem
        • 376. Wiggle Subsequence
        • 377. Combination Sum IV
        • 384. Shuffle an Array
        • 387. First Unique Character in a String
      • 401-500
        • 402. Remove K Digits
        • 413. Arithmetic Slices
        • 417. Pacific Atlantic Water Flow
        • 423. Reconstruct Original Digits from English
        • 449. Serialize and Deserialize BST
        • 450. Delete Node in a BST
        • 452. Minimum Number of Arrows to Burst Balloons
        • 456. 132 Pattern
        • 462. Minimum Moves to Equal Array Elements II
        • 473. Matchsticks to Square
        • 478. Generate Random Point in a Circle
        • 482. License Key Formatting
        • 496. Next Greater Element I
      • 501-600
        • 503. Next Greater Element II
        • 509. Fibonacci Number
        • 524. Longest Word in Dictionary through Deleting
        • 535. Encode and Decode TinyURL
        • 536. Construct Binary Tree from String
        • 543. Diameter of Binary Tree
        • 545. Boundary of Binary Tree
        • 554. Brick Wall
        • 567. Permutation in String
        • 572. Subtree of Another Tree
        • 575. Distribute Candies
        • 581. Shortest Unsorted Continuous Subarray
        • 582. Kill Process
        • 583. Delete Operation for Two Strings
        • 589. N-ary Tree Preorder Traversal
      • 601-700
        • 609. Find Duplicate File in System
        • 611. Valid Triangle Number
        • 617. Merge Two Binary Trees
        • 621. Task Scheduler
        • 622. Design Circular Queue
        • 623. Add One Row to Tree
        • 630. Course Schedule III
        • 637. Average of Levels in Binary Tree
        • 645. Set Mismatch
        • 655. Print Binary Tree
        • 658. Find K Closest Elements
        • 665. Non-decreasing Array
        • 667. Beautiful Arrangement II
        • 695. Max Area of Island
      • 701-800
        • 702. Search in a Sorted Array of Unknown Size
        • 706. Design HashMap
        • 714. Best Time to Buy and Sell Stock with Transaction Fee
        • 718. Maximum Length of Repeated Subarray
        • 723. Candy Crush
        • 729. My Calendar I
        • 733. Flood Fill
        • 735. Asteroid Collision
        • 746. Min Cost Climbing Stairs
        • 759. Employee Free Time
        • 775. Global and Local Inversions
        • 784. Letter Case Permutation
        • 745. Prefix and Suffix Search
        • 791. Custom Sort String
      • 801-900
        • 814. Binary Tree Pruning
        • 816. Ambiguous Coordinates
        • 820. Short Encoding of Words
        • 821. Shortest Distance to a Character
        • 823. Binary Trees With Factors
        • 841. Keys and Rooms
        • 856. Score of Parentheses
        • 859. Buddy Strings
        • 869. Reordered Power of 2
        • 870. Advantage Shuffle
        • 871. Minimum Number of Refueling Stops
        • 887. Super Egg Drop
      • 901-1000
        • 901. Online Stock Span
        • 904. Fruit Into Baskets
        • 915. Partition Array into Disjoint Intervals
        • 916. Word Subsets
        • 923. 3Sum With Multiplicity
        • 929. Unique Email Addresses
        • 946. Validate Stack Sequences
        • 948. Bag of Tokens
        • 953. Verifying an Alien Dictionary
        • 968. Binary Tree Cameras
        • 970. Powerful Integers
        • 975. Odd Even Jump
        • 986. Interval List Intersections
        • 991. Broken Calculator
        • 994. Rotting Oranges
      • 1001-1100
        • 1007. Minimum Domino Rotations For Equal Row
        • 1026. Maximum Difference Between Node and Ancestor
        • 1048. Longest String Chain
      • 1101-1200
        • 1143. Longest Common Subsequence
        • 1151. Minimum Swaps to Group All 1's Together
        • 1165. Single-Row Keyboard
        • 1167. Minimum Cost to Connect Sticks
        • 1182. Shortest Distance to Target Color
        • 1198. Find Smallest Common Element in All Rows
      • 1201-1300
        • 1209. Remove All Adjacent Duplicates in String II
        • 1228. Missing Number In Arithmetic Progression
        • 1229. Meeting Scheduler
        • 1235. Maximum Profit in Job Scheduling
        • 1239. Maximum Length of a Concatenated String with Unique Characters
        • 1249. Minimum Remove to Make Valid Parentheses
        • 1275. Find Winner on a Tic Tac Toe Game
        • 1290. Convert Binary Number in a Linked List to Integer
      • 1301-1400
        • 1302. Deepest Leaves Sum
        • 1332. Remove Palindromic Subsequences
        • 1337. The K Weakest Rows in a Matrix
        • 1354. Construct Target Array With Multiple Sums
        • 1396. Design Underground System
      • 1401-1500
        • 1423. Maximum Points You Can Obtain from Cards
        • 1428. Leftmost Column with at Least a One
        • 1461. Check If a String Contains All Binary Codes of Size K
        • 1464. Maximum Product of Two Elements in an Array
        • 1480. Running Sum of 1d Array
        • 1492. The kth Factor of n
      • 1501-1600
        • 1551. Minimum Operations to Make Array Equal
        • 1564. Put Boxes Into the Warehouse I
      • 1601-1700
        • 1642. Furthest Building You Can Reach
        • 1644. Lowest Common Ancestor of a Binary Tree II
        • 1650. Lowest Common Ancestor of a Binary Tree III
        • 1676. Lowest Common Ancestor of a Binary Tree IV
        • 1689. Partitioning Into Minimum Number Of Deci-Binary Numbers
      • 1701-1800
        • 1704. Determine if String Halves Are Alike
        • 1721. Swapping Nodes in a Linked List
      • 1801-1900
        • 1848. Minimum Distance to the Target Element
        • 1870. Minimum Speed to Arrive on Time
      • 1901-2000
      • 2001-2100
        • 2006. Count Number of Pairs With Absolute Difference K
      • 2101-2200
  • Other
    • Template
Powered by GitBook
On this page
  • Description
  • Constraints
  • Approach
  • Links
  • Examples
  • Solutions
  • Follow up

Was this helpful?

  1. leetcode
  2. Problems
  3. 101-200

133. Clone Graph

Previous132. Palindrome Partitioning IINext134. Gas Station

Last updated 4 years ago

Was this helpful?

Description

Given a reference of a node in a undirected graph.

Return a (clone) of the graph.

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

Test case format:

For simplicity sake, 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.

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.

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.

Constraints

  • 1 <= Node.val <= 100

  • Node.val is unique for each node.

  • Number of Nodes will not exceed 100.

  • There is no repeated edges and no self-loops in the graph.

  • The Graph is connected and all nodes can be visited starting from the given node.

Approach

Links

  • YouTube

Examples

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

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

Explanation: There are 4 nodes in the graph.

1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).

2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).

4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).

Input: adjList = [[]]

Output: [[]]

Explanation: 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.

Input: adjList = []

Output: []

Explanation: This an empty graph, it does not have any nodes.

Input: adjList = [[2], [1]]

Output: [[2], [1]]

Solutions

// Definition for a Node.
class Node {
    public int val;
    public List<Node> neighbors;
    
    public Node() {
        val = 0;
        neighbors = new ArrayList<Node>();
    }
    
    public Node(int _val) {
        val = _val;
        neighbors = new ArrayList<Node>();
    }
    
    public Node(int _val, ArrayList<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
}
/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public Node cloneGraph(Node node) {
        if(node == null) return null;
        Map<Integer, Node> nodes = new HashMap();
        return helper(node, nodes);
    }
    
    private Node helper(Node node, Map<Integer, Node> nodes) {
        if(node == null) return null;
        
        if(nodes.containsKey(node.val)) {
            return nodes.get(node.val);
        }
        
        Node newNode = new Node(node.val);
        nodes.put(node.val, newNode);
        for(Node neighbor: node.neighbors) {
            newNode.neighbors.add(helper(neighbor, nodes));
        }
        return newNode;
    }
}
/**
 * Time complexity : 
 * Space complexity : 
 */
 
class Solution {
    
    private Map<Integer, Node> nodes = new HashMap<>();
    
    public Node cloneGraph(Node node) {
        if(node == null) return null;
        
        if(nodes.containsKey(node.val)) {
            return nodes.get(node.val);
        }
        
        Node newNode = new Node(node.val);
        nodes.put(node.val, newNode);
        
        for(Node adj: node.neighbors) {
            newNode.neighbors.add(cloneGraph(adj));
        }
        
        return newNode;
    }
}

Follow up

GeeksforGeeks
Leetcode
ProgramCreek
connected
deep copy