Find the starting point in LL

Linked-List FAQs (Medium) Medium
  • One real-world application of this problem is in detecting memory leaks in computer software
  • Memory leaks occur when a computer program incorrectly manages memory allocations, leading to a decrease in available memory and causing the system to slow down or crash
  • By using a linked list and understanding where a 'loop' or cycle starts, programmers can trace back and identify where memory is not being freed properly, leading to efficient bug fixing and enhanced software performance

Given the head of a singly linked list, the task is to find the starting point of a loop in the linked list if it exists. Return the starting node if a loop exists; otherwise, return null.


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 denotes 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(value of the returned node is displayed): 2

Explanation: The tail of the linked list connects to the node at 1st index.

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

Output(value of the returned node is displayed): null

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, reset slow to head and move both pointers one step at a time. The meeting point is the cycle’s start node.

Company Tags

Nutanix Red Hat Reddit Epic Systems Instacart Zoho Ernst & Young MongoDB Square NVIDIA Robinhood OYO Rooms Rockstar Games Zynga Cloudflare Salesforce Airbnb Roblox Databricks Boston Consulting Group Cerner Oracle Visa Bain & Company Bloomberg Google Microsoft Amazon Meta Apple Netflix Adobe