Linked List Cycle

Try to solve the Linked List Cycle problem.

Statement#

Check whether or not a linked list contains a cycle. If a cycle exists, return TRUE. Otherwise, return FALSE. The cycle means that at least one node can be reached again by traversing the next pointer.

Constraints:

Let n be the number of nodes in a linked list.

  • 00\leq n 500\leq500
  • 105-10^5 \leq Node.data 105\leq 10^5

Examples#

Created with Fabric.js 3.6.6 Sample example 1 head 2 4 6 8 10 TRUE

1 of 3

Created with Fabric.js 3.6.6 Sample example 2 head 1 3 5 7 9 NULL FALSE

2 of 3

Created with Fabric.js 3.6.6 Sample example 3 head 1 2 3 4 5 6 TRUE

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Linked List Cycle

1

What is the output if the following linked list is given as input?

A)

TRUE

B)

FALSE

Question 1 of 30 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Initialize both fast and slow pointers to the head of the linked list.

Move the slow pointer one node ahead and the fast pointer two nodes ahead.

Check if both pointers point to the same node at any point. If yes, then return TRUE.

Else, if the fast pointer reaches the end of the linked list, return FALSE.


Try it yourself#

Implement your solution in detect_cycle.py in the following coding playground. You’ll need the provided supporting code to implement your solution.

Note: The first input of the test case includes an array representing the contents of a linked list. The second input represents the index of the node to which the tail pointer is pointing. It will be 1-1, in case it is pointing to NULL. The second input is not passed as a parameter in the function because it is just to represent the cycle in the linked list.

Python
detect_cycle.py
linked_list_node.py
linked_list.py
Input #1
Input #2
Linked List Cycle

Solution: Happy Number

Solution: Linked List Cycle