# Wormhole Traversal

I've seen a few specific problems from USACO as well as Leetcode that uses this idea.

## Concepts

***Whenever the value of an array element is used as the index for accessing another element, it is a wormhole...***

If we have a 1D array of size `n`, and every element has a **unique** value between `[0,n-1]` (so guarantees no index out of bounds) or similar (sometimes problem context varies), we should be sensitive that a Wormhole Traversal may be used on this array.

Essentially we treat the value of each element of this array as the index of the next element to go to, and turn the array traversal into a linkedlist traversal. This linked list is guaranteed to contain cycles (again, may vary). Any further cycle detections/manipulations can be potentially connected to [Floyd's Cycle Detection](/cp-notes/advanced/graph-theory/floyds-cycle-detection.md)

## Notes

* This is a very insightful choice especially when numbers are unique in an array, which established the constraints that the `in-degree` and `out-degree` of every element is strictly 1.

## Problems

{% embed url="<https://leetcode.com/problems/find-the-duplicate-number/description/>" %}

{% embed url="<https://leetcode.com/problems/find-all-duplicates-in-an-array/description/>" %}


---

# 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://welchj.gitbook.io/cp-notes/foundementals/wormhole-traversal.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.
