# 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.

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

    # references assumed to be unique
    for ref in refs:
        visited.add(ref)
        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
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/linked-list/double-linked-list-connected-components.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
