Taro Logo

Linked List Cycle

#3 Most AskedEasy
0 views
Topics:
Linked ListsTwo Pointers

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.

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.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Constraints:

  • The number of the nodes in the list is in the range [0, 104].
  • -105 <= Node.val <= 105
  • pos is -1 or a valid index in the linked-list.

Follow up: Can you solve it using O(1) (i.e. constant) memory?

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Could the linked list be empty (i.e., is `head` ever `null`), and how should I handle that case?
  2. Are node values guaranteed to be integers, or could they contain arbitrary data types?
  3. Can the cycle point back to the head of the list, or can it point to any arbitrary node earlier in the list?
  4. Are we allowed to modify the structure of the linked list during traversal, or must it remain strictly read-only?
  5. Can we assume that the memory addresses or node references are unique, or could there be duplicate node values within the cycle?

Brute Force Solution

Approach

Imagine you are walking along a path made of stepping stones connected one after the other, and you want to know if the path eventually loops back on itself in a circle. The brute force strategy involves keeping a written record of every single stone you step on so you can check your past visits against your current location.

Here's how the algorithm would work step-by-step:

  1. Start at the very first stone of the path.
  2. Write down the location of this starting stone on a notepad.
  3. Take a step forward to the next connected stone.
  4. Look at your notepad to see if you have already written down this new stone's location.
  5. If you find it on your notepad, you have discovered a cycle because you are revisiting a place you already stood on.
  6. If you do not see it on your notepad, add this new stone's location to your list.
  7. Repeat the process of stepping forward and checking your notepad until either you run out of stones, which means there is no cycle, or you find a repeat, which proves a cycle exists.

Code Implementation

def has_cycle(head_node):
    visited_stones_notepad = set()
    
    current_stone = head_node
    
    while current_stone is not None:
        # Check notepad to detect a loop since revisiting a stone proves a cycle exists
        if current_stone in visited_stones_notepad:
            return True
            
        # Record current stone location to ensure future visits can be identified
        visited_stones_notepad.add(current_stone)
        
        current_stone = current_stone.next
        
    # Reaching the end of the path without repeats confirms the linked list is acyclic
    return False

Big(O) Analysis

Time Complexity
O(n) – As we traverse through the linked list of n nodes, we visit each node sequentially and perform a constant time lookup and insertion in our notepad for every step. The total number of operations is directly proportional to the total number of stones n in the path, because we examine each stone at most once until we either find a repeat or run out of stones. Simplifying this linear progression of checks relative to the input size results in a final runtime complexity of O(n).
Space Complexity
O(N) – The brute force strategy requires a written record, which translates to a hash set or hash map to keep track of every visited stone. As you traverse through the linked list, you store the reference of each unique node in this data structure. In the worst-case scenario where there is no cycle, you will store all N nodes from the linked list. Therefore, the auxiliary space grows linearly with the input size N, resulting in an O(N) space complexity.

Optimal Solution

Approach

To find out if a path loops back on itself, the best strategy is to use two travelers moving at different speeds along the same path. If there is a loop, the faster traveler will eventually lap the slower one, much like runners on a circular track.

Here's how the algorithm would work step-by-step:

  1. Place two travelers at the very beginning of the path.
  2. Instruct the first traveler to take one step forward at a time, and the second traveler to take two steps forward with every turn.
  3. Watch as they move along the path; if the path eventually comes to a dead end, the faster traveler will reach the end and stop, proving there is no loop.
  4. If the path actually loops in a circle, the faster traveler will eventually catch up from behind and meet the slower traveler face-to-face.
  5. Stop and declare that a loop exists the moment the two travelers occupy the exact same spot.

Code Implementation

class Solution:
    def hasCycle(self, head_node):
        # Two pointers start at the head to traverse the list at different speeds.
        slow_traveler = head_node
        fast_traveler = head_node

        while fast_traveler is not None and fast_traveler.next is not None:
            # The fast pointer moves twice as fast to eventually lap the slow pointer if a cycle exists.
            slow_traveler = slow_traveler.next
            fast_traveler = fast_traveler.next.next

            # Meeting point confirms a cycle because the faster pointer wrapped around.
            if slow_traveler == fast_traveler:
                return True

        # Reaching the end of the list proves there is no cycle present.
        return False

Big(O) Analysis

Time Complexity
O(n) – The input size n represents the total number of nodes in the linked list. The cost is driven by the two travelers traversing the nodes, where the slow pointer advances one step and the fast pointer advances two steps per iteration. In a list without a cycle, the faster traveler reaches the end in at most n/2 steps, and in a cyclic list, the faster traveler catches the slower one within at most n steps. This yields approximately 3n/2 total operations in the worst-case scenario, which simplifies to O(n).
Space Complexity
O(1) – The algorithm exclusively utilizes two pointer variables, the slower traveler and the faster traveler, regardless of the total number of nodes in the linked list. Because no auxiliary data structures such as hash maps or recursive call stacks are created to track visited nodes, the extra memory remains constant. As the input size N grows, the memory consumed by these pointers does not increase. Therefore, the auxiliary space complexity simplifies to O(1) constant space.

Edge Cases

Null head pointer representing an empty linked list
How to Handle:
The algorithm checks if head is null or head.next is null at the start and immediately returns false.
Linked list with a single node and no cycle
How to Handle:
The fast pointer will reach null on the first step, safely terminating the loop and returning false.
Single node pointing to itself forming a self-loop cycle
How to Handle:
Both fast and slow pointers will occupy the same node after one iteration and match, correctly returning true.
Two-node list with a cycle pointing back to the head
How to Handle:
The fast pointer will traverse the loop and meet the slow pointer within the first few steps.
Extremely large linked list without a cycle
How to Handle:
The two-pointer approach runs in linear time and constant space, avoiding stack overflow and scaling efficiently.
A long linear tail followed by a very small cycle at the end
How to Handle:
The fast pointer will eventually enter the cycle and lap the slow pointer, guaranteeing detection in O(N) time.
0/8 completed