Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding
Ninjas X Naukri.com

Problem of the day

You’re given a linked list. The last node might point to null, or it might point to a node in the list, thus forming a cycle.

Find out whether the linked list has a cycle or not, and the length of the cycle if it does.

If there is no cycle, return 0, otherwise return the length of the cycle.

```
Input: Linked List: 4 -> 10 -> 3 -> 5 -> 10(at position 2)
Output: Length of cycle = 3
Explanation: The cycle is 10, 3, 5.
```

Detailed explanation

```
The first line contains an integer ‘n’, the number of elements initially in the linked list.
The next line contains ‘n’ numbers, the linked list.
The third line contains an integer ‘p’. If there is no cycle, ‘p’ = 0. Otherwise ‘p’ is the position the last node is pointing to (1 - indexed).
```

```
Return the length of the cycle, or 0 if no cycle exists.
```

```
You do not need to print anything; it has already been taken care of. Just implement the given function.
```

```
4
4 10 3 5
2
```

```
3
```

```
The cycle is 10, 3, 5.
```

```
4
4 10 3 5
0
```

```
0
```

```
Since ‘p’ = 0, the last node is pointing to null, so no cycle exists.
```

```
1 <= ‘n’ <= 100000
1 <= Data in linked list node <= 10^9
0 <= ‘p’ <= ‘n’
```