An AI-powered platform that generates unique coding challenges daily, helping developers enhance their problem-solving skills through consistent practice.
- 🤖 AI-Powered: Challenges are generated using advanced AI to ensure uniqueness and relevance
- 🕒 Daily Updates: New challenges are automatically generated and committed at 12 AM EST
- ⭐ Difficulty Ratings: Each challenge includes a difficulty rating from 1-5
- 💡 Complete Solutions: Every challenge comes with a detailed Python solution
- 🔥 React + Vite: For a fast and modern development experience
- 🔷 TypeScript: For type-safe code
- 🛠️ Shadcn/UI: For pre-built, customizable components
- 🔌 Supabase: For backend functionality and database
- 🤖 Perplexity API: For AI-powered challenge generation
Difficulty: ⭐⭐⭐ (3/5)
Linked List Cycle Detection
Given a singly linked list, determine if the list contains a cycle (i.e., if any node points back to a previous node). Implement a method to detect such a cycle and return True if one exists, otherwise return False.
Input: A singly linked list with nodes [1, 2, 3, 4] where node 3 points back to node 1.
Output: True
Input: A singly linked list with nodes [1, 2, 3, 4] where no nodes point back.
Output: False
- The list may or may not contain a cycle.
- Nodes in the list contain only integer data.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def hasCycle(head):
if head is None:
return False
slow = head
fast = head
while fast is not None and fast.next is not None:
slow = slow.next # Move one step at a time
fast = fast.next.next # Move two steps at a time
if slow == fast:
return True
return FalseThe solution uses Floyd's Tortoise and Hare algorithm to detect the cycle in the linked list. This algorithm leverages two pointers, slow and fast, which move at different speeds through the linked list.
-
Initialization:
- If the head is
None, it means there are no nodes, so we returnFalse.
- If the head is
-
Main Loop:
- Set both pointers (
slowandfast) to the head of the linked list. - While
fastand its next node are notNone, moveslowone step at a time andfasttwo steps at a time. - If
slowandfastever meet, it indicates that there is a cycle in the linked list, so we returnTrue.
- Set both pointers (
-
Termination:
- If
fastbecomesNoneor its next node becomesNone, it means there are no more nodes or no more adjacent nodes left, so we returnFalse.
- If
This algorithm has a time complexity of O(n), where n is the number of nodes in the linked list because each node is visited at most twice (once by slow and once by fast). The space complexity is O(1) since only a constant amount of space is used.
- Time Complexity: O(n)
- Space Complexity: O(1)
Floyd's Tortoise and Hare algorithm is optimal for detecting cycles in linked lists because it takes advantage of the fact that if there is a cycle, eventually the faster pointer will caught up with the slower one. This approach ensures that every node is visited at most twice, making it highly efficient.