Linked-List Cycle LeetCode 141

Honey
2 min readJun 13, 2022

Problem Statement

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

Test Cases

Example 1 :

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2 :

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Approach — 1

FLOYD’S TORTOISE & HARE

In this approach we will use two pointers, i.e. slow and fast and we will iterate through the entire linked-list with these pointers. The position of the slow pointer will be incremented by 1 after each loop i.e. it will point to its next element(->next). Whereas, the fast pointer will be incremented by 2, i.e. it will point to the next’s next element (->next->next)

For detailed explanation, you can refer this video here.

Code

Time Complexity — O(n) (since the loop is traversed once)

Auxiliary Space — O(1), (only two pointers are used)

Approach — 2

Using Unordered Set

We create an unordered_set of type pointer. Then we find the value of our current node in the set, if found, it returns the true, otherwise it inserts that element in the set.

Code

--

--

Honey

Tech or non-tech 'll post all my crazy cool stuff here!