Double Linked List Connected Components

You are given a doubly linked list and an array of references to nodes on the linked list. How many "blocks" are there present in the linked list?

A "block" is defined as a group of nodes on the list with references directed at them and adjacent to each other.

For example

[node #0] -><-[node#1] -><-[node#2] -><-[node#3] 
node[] nodes = {ref_to_node#0, ref_to_node#2, ref_to_node#3};

Is two blocks because the first block is at node #0.

Node #1 has no incoming reference. Node #2 and Node #3 have references are are adjacent so it's just one block.

The Idea: Iterate through the references. If the either the left or right node has been visited, that means our current reference will belong to an already existing connected component. If this is not true, then we've introduced a new connected component.

Complexity: O(n) time and space.

def dll_n_connected(refs):
    visited = set()
    blocks = 0

    # references assumed to be unique
    for ref in refs:
        if (not ref.left and not ref.right in visited)
            blocks += 1
        elif (not ref.right and not ref.left in visited)
            blocks += 1
        elif not (ref.left in visited or ref.right in visited)
            blocks += 1
    return blocks

Last updated