Leetcode 141: Linked List Cycle

grid47
grid47
Exploring patterns and algorithms
Oct 23, 2024 5 min read

A circular linked list glowing in a cycle, with the loop softly visible.
Solution to LeetCode 141: Linked List Cycle Problem

Given the head of a linked list, determine if there is a cycle. A cycle occurs if a node can be revisited by following the ’next’ pointers. The ‘pos’ parameter denotes where the last node connects to. If ‘pos’ is -1, there is no cycle.
Problem
Approach
Steps
Complexity
Input: The input consists of a linked list head and a position, 'pos', indicating where the tail node connects.
Example: Input: head = [4, 3, 2, 1], pos = 2
Constraints:
• The number of nodes in the list is between 0 and 10^4.
• Node values range between -10^5 and 10^5.
• 'pos' is either -1 or a valid index within the list.
Output: The output is a boolean value indicating whether a cycle exists in the linked list.
Example: Output: true
Constraints:
• The output is true if a cycle exists, otherwise false.
Goal: The goal is to detect if there is a cycle in the linked list using efficient memory usage.
Steps:
• 1. Use two pointers, 'slow' and 'fast', where 'slow' moves one step and 'fast' moves two steps at a time.
• 2. If there is a cycle, the two pointers will meet; otherwise, the fast pointer will reach the end of the list.
Goal: The solution should be optimized for both time and space complexity.
Steps:
• Ensure the solution runs efficiently for lists with up to 10^4 nodes.
• The space complexity must be constant, O(1).
Assumptions:
• The linked list can have a cycle, or it can be a simple acyclic list.
• All nodes contain integer values.
Input: Input: head = [4, 3, 2, 1], pos = 2
Explanation: In this example, the tail node points to the 2nd node, forming a cycle.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus