Tag Archives: graphs

Copy List with Random Pointer

[tabby title=”Task”]

 

A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null.

Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list.

For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y.

Return the head of the copied linked list.

The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:

  • val: an integer representing Node.val
  • random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.

Your code will only be given the head of the original linked list.

 

Example 1:

Input:

 head = [[7,null],[13,0],[11,4],[10,2],[1,0]]

Output:

 [[7,null],[13,0],[11,4],[10,2],[1,0]]

Example 2:

Input:

 head = [[1,1],[2,1]]

Output:

 [[1,1],[2,1]]

Example 3:

Input:

 head = [[3,null],[3,0],[3,null]]

Output:

 [[3,null],[3,0],[3,null]]

 

Constraints:

  • 0 <= n <= 1000
  • -104 <= Node.val <= 104
  • Node.random is null or is pointing to some node in the linked list.

This problem was taken from https://leetcode.com/problems/copy-list-with-random-pointer/

[tabby title=”Solution”]

 

Brute force using tree traversal

 

/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

/**
 * @param {Node} head
 * @return {Node}
 */
var copyRandomList = function(head) {


    function dfsTraverse(node, visited={}) {
        if(!node) {
            return null;
        }
        
        // if a new node is created, return it. Otherwise you will fall into circular loops
        if(node?.clone) {
            return node?.clone;    
        }
        
        var newNode = new Node(node?.val, null, null);
        node.clone = newNode;
        var next = dfsTraverse(node?.next);
        var random = dfsTraverse(node?.random);

        newNode.next = next;
        newNode.random = random;
        return newNode;
    }

    var result = dfsTraverse(head);
    return result;
};

function Node(val, next, random) {
    this.val = val;
    this.next = next;
    this.random = random;
}
;// [1,null],[2,0],[3,1]

var nodes = {};
nodes['1'] = new Node(1,null,null);
nodes['2'] = new Node(2,null,null);
nodes['3'] = new Node(3,null,null);

nodes['1'].next = nodes['2'];
nodes['1'].random = null;

nodes['2'].next = nodes['3'];
nodes['2'].random = nodes['1'];

nodes['3'].next = null;
nodes['3'].random = nodes['2'];

//console.log("root");
//console.log(nodes['7']);
var result = copyRandomList(nodes['1']);
console.log(result);

 

 

More elegant solution

 

/**
 * // Definition for a Node.
 * function Node(val, next, random) {
 *    this.val = val;
 *    this.next = next;
 *    this.random = random;
 * };
 */

/**
 * @param {Node} head
 * @return {Node}
 */
var copyRandomList = function(head) {
  let cur = head;
  const copy = new Map();

  // add all new nodes and values for now
  while (cur) {
    copy.set(cur, new Node(cur.val));
    cur = cur.next;
  }
  
  cur = head;

  // iterate again and point curent node to the newly created nodes using the key 
  while (cur) {
    copy.get(cur).next = copy.get(cur.next) || null;
    copy.get(cur).random = copy.get(cur.random) || null;
    cur = cur.next;
  }
  
  return copy.get(head);
}


function Node(val, next, random) {
    this.val = val;
    this.next = next;
    this.random = random;
};


// [1,null],[2,0],[3,1]

var nodes = {};
nodes['1'] = new Node(1,null,null);
nodes['2'] = new Node(2,null,null);
nodes['3'] = new Node(3,null,null);

nodes['1'].next = nodes['2'];
nodes['1'].random = null;

nodes['2'].next = nodes['3'];
nodes['2'].random = nodes['1'];

nodes['3'].next = null;
nodes['3'].random = nodes['2'];


var result = copyRandomList(nodes['1']);
console.log(result);

 

 

[tabbyending]

Graph traversal

The graph

The graph represent connections between airports. Nodes (vertices)  represent airports, and  edges represent flights.

BFS search (Breadth First Search)

Breadth-first Search (BFS) starts by pushing all of the direct children to a queue (first-in, first-out). It then visits each item in queue and adds the next layer of children to the back of the queue. Since one node could be visited multiple times causing infinite loop, we have to keep track of all visited nodes.

Using JavaScript Map

// DATA
const airports = 'PHX BKK OKC JFK LAX MEX EZE HEL LOS LAP LIM'.split(' ');

const routes = [
    ['PHX', 'LAX'],
    ['PHX', 'JFK'],
    ['JFK', 'OKC'],
    ['JFK', 'HEL'],
    ['JFK', 'LOS'],
    ['MEX', 'LAX'],
    ['MEX', 'BKK'],
    ['MEX', 'LIM'],
    ['MEX', 'EZE'],
    ['LIM', 'BKK'],
];


// The graph
const adjacencyList = new Map();

// Add node
function addNode(airport) {
    adjacencyList.set(airport, []);
}

// Add edge, undirected
function addEdge(origin, destination) {
    adjacencyList.get(origin).push(destination);
    adjacencyList.get(destination).push(origin);
}

// Create the Graph
airports.forEach(addNode);
routes.forEach(route => addEdge(route[0], route[1]));

console.log(adjacencyList);


function bfs(start, searchItem) {

    const visited = new Set();
    const queue = [start];


    while (queue.length > 0) {

        const airport = queue.shift(); // mutates the queue
        const destinations = adjacencyList.get(airport);


        for (const destination of destinations) {
            if (destination === searchItem)  {
                console.log(`BFS found a route to`, searchItem)
            }

            if (!visited.has(destination)) {
                visited.add(destination);
                queue.push(destination);
            }           
        }        
    }

}

bfs('PHX', 'BKK');

 

Using JavaScript object

// Data
var airports = {
    'PHX': ['LAX', 'JFK'],
    'BKK': ['MEX', 'LIM'],
    'OKC': ['JFK'],
    'JFK': ['LAX', 'PHX', 'OKC', 'HEL', 'LOS', 'EZE'],
    'LAX': ['PHX', 'JFK', 'MEX'],
    'MEX': ['LAX', 'EZE', 'BKK', 'LIM'],
    'EZE': ['JFK', 'MEX'],
    'HEL': ['JFK'],
    'LOS': ['JFK'],
    'LAP': [],
    'LIM': ['MEX', 'BKK']
};


function bfs(start, endDest) {
    var queue = [start];
    var visited = {};

    while(queue.length > 0) {
        var curentNodeVal = queue.shift();
        var childNodes = airports[curentNodeVal];
        for(const childNode of childNodes) {
            if(childNode === endDest) {
                console.log("BFS found a route to :", endDest);
            }            

            if(!visited[childNode]) {
                console.log(childNode);
                visited[childNode] = true;
                queue.push( childNode);          
            }
        }
    }
}


bfs('PHX', 'BKK');

 

DFS (Depth First Search)

Depth-first Search (DFS) will go as far into the graph as possible until it reaches a node without any children, at which point it backtracks and continues the process. The algorithm can be implemented with a recursive function that keeps track of previously visited nodes. If a node has not been visited, we call the function recursively.

Using JavaScript Map

// DATA
const airports = 'PHX BKK OKC JFK LAX MEX EZE HEL LOS LAP LIM'.split(' ');

const routes = [
    ['PHX', 'LAX'],
    ['PHX', 'JFK'],
    ['JFK', 'OKC'],
    ['JFK', 'HEL'],
    ['JFK', 'LOS'],
    ['MEX', 'LAX'],
    ['MEX', 'BKK'],
    ['MEX', 'LIM'],
    ['MEX', 'EZE'],
    ['LIM', 'BKK'],
];

// The graph
const adjacencyList = new Map();

// Add node
function addNode(airport) {
    adjacencyList.set(airport, []);
}

// Add edge, undirected
function addEdge(origin, destination) {
    adjacencyList.get(origin).push(destination);
    adjacencyList.get(destination).push(origin);
}

// Create the Graph
airports.forEach(addNode);
routes.forEach(route => addEdge(route[0], route[1]));

console.log(adjacencyList);



function dfs(start, visited = new Set()) {

    console.log(start)
    
    visited.add(start);

    const destinations = adjacencyList.get(start);

    for (const destination of destinations) {

        if (destination === 'BKK') { 
            console.log(`DFS found Bangkok`)
            return;
        }
        
        if (!visited.has(destination)) {
            dfs(destination, visited);
        }

    }

}

dfs('PHX');

Using JavaScript object

// Data
var airports = {
    'PHX': ['LAX', 'JFK'],
    'BKK': ['MEX', 'LIM'],
    'OKC': ['JFK'],
    'JFK': ['LAX', 'PHX', 'OKC', 'HEL', 'LOS', 'EZE'],
    'LAX': ['PHX', 'JFK', 'MEX'],
    'MEX': ['LAX', 'EZE', 'BKK', 'LIM'],
    'EZE': ['JFK', 'MEX'],
    'HEL': ['JFK'],
    'LOS': ['JFK'],
    'LAP': [],
    'LIM': ['MEX', 'BKK']
};


function dfs(start, endDest, visited = {}) {
        
    visited[start] = true;
    console.log(start);

    const destinations = airports[start];

    for(const destination of  destinations) {
        if (destination === endDest) { 
            console.log(`DFS found route to`, endDest);
        }

        if(!visited[destination]) {
            dfs(destination, endDest, visited);
        }
        
    }
}


dfs('PHX', 'BKK');