Leetcode[141] Linked List Cycle

Bryan W.
1 min readFeb 3, 2021

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.

Difficulty

  • Level: Easy
  • Acceptance: 42.6%

Solution

Time Complexity: O(n), Space Complexity: O(n)

Analysis

I used a set in my solution as sets are great with dealing with large amounts of data in comparison to an array, good for searching, and great for unique values.

While the head is not null, the algorithm will check if the set has a reference to the node. If not, it will be added to the set and the reference for the head will point to the next node. If so, it will return true. If we have reached the end of the linked list and there are still no matches with the set, we shall return false.

--

--

Bryan W.

I have a passion for coding | Salesforce Developer