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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit