|
| 1 | +# [Loop Detector](https://www.codewars.com/kata/loop-detector "https://www.codewars.com/kata/68851563123e161332d2a84b") |
| 2 | + |
| 3 | +In this kata, you'll simulate traversing a one-way pointer chain, similar to a singly linked list. Each element in the input list represents |
| 4 | +the index of the next element to move to. |
| 5 | + |
| 6 | +Your task is to determine whether this chain eventually enters a loop, or whether it terminates by stepping out of bounds. |
| 7 | + |
| 8 | +## Function Signature |
| 9 | + |
| 10 | +* ```arr``` is a list or array of non-negative integers. |
| 11 | + |
| 12 | +* Return ```True``` (or your language's equivalent) if the traversal enters a loop. |
| 13 | + |
| 14 | +* Return ```False``` (or your language's equivalent) if the traversal terminates. |
| 15 | + |
| 16 | +## How Traversal Works |
| 17 | + |
| 18 | +* Begin at index ```0```. |
| 19 | + |
| 20 | +* Read the value at the current index to get the next index. |
| 21 | + |
| 22 | +* Continue stepping through the array. |
| 23 | + |
| 24 | +* If you encounter an index you've already visited, you've found a loop — return ```True``` (or your language's equivalent). |
| 25 | + |
| 26 | +* If a step takes you to an index outside the array, the traversal ends — return ```False``` (or your language's equivalent). |
| 27 | + |
| 28 | +## Examples |
| 29 | + |
| 30 | +``` |
| 31 | +Input: 1, 2, 3, 4, 2 ➞ True |
| 32 | +Path: 0 -> 1 -> 2 -> 3 -> 4 -> 2 -> ... (loop detected) |
| 33 | +
|
| 34 | +Input: 1, 2, 3, 4, 5 ➞ False |
| 35 | +Path: 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> (out of bounds) |
| 36 | +
|
| 37 | +Input: 0 ➞ True |
| 38 | +Path: 0 -> 0 -> 0 -> ... (self-loop) |
| 39 | +
|
| 40 | +Input: 3, 2, 1, 6 ➞ False |
| 41 | +Path: 0 -> 3 -> 6 -> (out of bounds) |
| 42 | +
|
| 43 | +Input: 1, 0 ➞ True |
| 44 | +Path: 0 -> 1 -> 0 -> 1 -> ... (cycle of two) |
| 45 | +``` |
| 46 | + |
| 47 | +## Notes |
| 48 | + |
| 49 | +* The input may be empty. In that case, return ```False``` (or your language's equivalent). |
| 50 | + |
| 51 | +* All elements are guaranteed to be non-negative integers. |
| 52 | + |
| 53 | +* You must detect any kind of loop, whether it be a: |
| 54 | + |
| 55 | +LICENSE build.gradle.kts docs gradle gradle.properties gradlew gradlew.bat kata settings.gradle.kts Self-loop (e.g., ```[0]```) |
| 56 | + |
| 57 | +LICENSE build.gradle.kts docs gradle gradle.properties gradlew gradlew.bat kata settings.gradle.kts Two-node loop (e.g., ```[1, 0]```) |
| 58 | + |
| 59 | +LICENSE build.gradle.kts docs gradle gradle.properties gradlew gradlew.bat kata settings.gradle.kts Larger cycle (e.g., ```[1, 2, 0]```) |
| 60 | + |
| 61 | +* An index is considered out of bounds if it is greater than or equal to ```len(arr)```. |
0 commit comments