EASY NC#41 Blind #41 Linked List
141. Linked List Cycle
๐ Problem
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 (0-indexed). Note that pos is not passed as a parameter. Return true if there is a cycle in the linked list. Otherwise, return false.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
๐ก Approach
- โ Use Floyd's Tortoise and Hare algorithm
- โ Slow pointer moves one step, fast pointer moves two steps
- โ If they meet, there's a cycle; if fast reaches null, no cycle
- โ Time: O(n), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse Floyd's Tortoise and Hare algorithm
- โขSlow pointer moves one step, fast pointer moves two steps
- โขIf they meet, there's a cycle; if fast reaches null, no cycle
Common Pitfalls
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
hasCycle(arrayToListWithCycle([3,2,0,-4], 1)); Expected:
true Test Case 2
Not run Input:
hasCycle(arrayToListWithCycle([1,2], 0)); Expected:
true Test Case 3
Not run Input:
hasCycle(arrayToListWithCycle([1], -1)); Expected:
false ๐ Code Editor
๐ค Output