Live Batches
Masterclasses
Menu
Free Courses
Account
Login / Sign Up

Detect Loop in linked list

Medium Acceptance 43.49% Points 30.00

Given the head of a singly linked list, determine if the list contains a loop, where a loop exists if a node’s next pointer points back to a previous node, creating a circular structure; otherwise, the list ends with a null pointer.

The input includes the linked list and a 1-based position (pos) indicating the node to which the last node connects, forming a loop (if pos = 0, there is no loop). Return true if a loop is detected, otherwise return false.

Examples
Example 1

Example 1

Input: LinkedList: 2 -> 4 -> 6 -> 8 -> 4

Output: true

Explanation: The last node connects back to the second node, forming a loop.

Example 2

Example 2

Input: LinkedList: 1 -> 2 -> 3 -> 4

Output: false

Explanation: The last node points to null, indicating there is no loop.

Hints
Hint 1
Expected Time Complexity: O(n)
Hint 2
Expected Space Complexity: O(1)
Constraints
  • 1 <= number of nodes <= 10^4
  • 1 <= node->data <= 10^3
Companies
Amazon Samsung Adobe Qualcomm Paytm
Topics
Linked List
Solution.cs C#JavaPythonC++Javascript

Unlock the code editor

Sign in to write, run, and submit your solution against the full test suite.

  • Run code against sample & hidden test cases
  • Save submissions and track your streak
  • Compare with editorial & community solutions