What if there's duplicate?

  • 0

    Different node with same value (label).

    For example, the below solution requires no duplications?

    public class Solution {
    private HashMap<Integer, UndirectedGraphNode> map = new HashMap<>();
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    return clone(node);

    private UndirectedGraphNode clone(UndirectedGraphNode node) {
        if (node == null) return null;
        if (map.containsKey(node.label)) {
            return map.get(node.label);
        UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
        map.put(clone.label, clone);
        for (UndirectedGraphNode neighbor : node.neighbors) {
        return clone;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.