Length of loop in LL

Linked-List FAQs (Medium) Medium
  • This problem underpins many real-world applications particularly in system software and web development fields
  • It is commonly used in debugging or troubleshooting memory leaks and infinite loops
  • For example, in garbage collection frameworks used in languages like Java and
  • NET, understanding the cycle detection in linked lists is crucial to manage memory efficiently and ensure that objects involved in a cycle are not prematurely deallocated
  • Additionally, in web crawling or network routing algorithms, it's important to prevent infinite loops by understanding and identifying cycles within networks

Given the head of a singly linked list, find the length of the loop in the linked list if it exists. Return the length of the loop if it exists; otherwise, return 0.


A loop exists in a linked list if some node in the list can be reached again by continuously following the next pointer. Internally, pos is used to denote the index (0-based) of the node from where the loop starts.


Note that pos is not passed as a parameter.

Examples:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5, pos = 1

Output: 4

Explanation: 2 -> 3 -> 4 -> 5 - >2, length of loop = 4.

Input: head -> 1 -> 3 -> 7 -> 4, pos = -1

Output: 0

Explanation: No loop is present in the linked list.


Input: head -> 6 -> 3 -> 7, pos = 0

Constraints

  • 0 <= number of nodes in the cycle <= 105
  • 0 <= ListNode.val <= 104
  • pos is -1 or a valid index in the linked list

Hints

  • A brute-force approach uses a HashSet (O(n) space) to track visited nodes. However, a more efficient O(1) space solution exists using Floyd’s Cycle Detection Algorithm.
  • Use Two Pointers (slow and fast) to detect a cycle. If they meet inside the cycle, initialize a counter and traverse the loop to count its length.

Company Tags

Etsy Broadcom DoorDash Dropbox Boston Consulting Group Databricks Epic Games Qualcomm Zomato Wayfair eBay Cerner Micron Technology Rockstar Games Activision Blizzard Zynga KPMG Oracle Riot Games Bloomberg AMD Western Digital ARM GE Healthcare Flipkart Google Microsoft Amazon Meta Apple Netflix Adobe