Prepin
Log in

Identify a loop or cycle within a linked list.

Approach / Explanation

The task requires you to develop an algorithm that determines whether a linked list contains a loop or cycle. In linked lists, a loop or cycle is formed when traversing the list causes you to revisit the same node multiple times. This results in an infinite loop as you continuously cycle through these 'looped' nodes. Here are some important considerations for your solution: Loop detection : To identify a loop, implement two pointers that traverse the linked list at different speeds (one slow pointer and one fast pointer). If the fast pointer encounters the slow pointer at any point, it indicates the presence of a loop. Clarify assumptions : It is essential to ask the interviewer whether the linked list will always terminate with a null pointer in the absence of a loop, as this assumption will influence your algorithm.

Suggested Answer

One of the most frequently utilized algorithms for this issue is Floyd's Cycle-Finding Algorithm, commonly referred to as the Tortoise and the Hare method. This algorithm begins with two pointers positioned at the start of the list: a slow pointer that advances one node at a time, and a fast pointer that advances two nodes at a time. If a loop exists, the fast pointer will eventually catch up to the slow pointer within the loop. Below is an example of a Python implementation of this algorithm: def has_cycle ( head ) : slow = head fast = head while fast is not None and fast . next is not None : slow = slow . next fast = fast . next . next if slow == fast : # both pointers meet, indicating a loop exists return True return False If a loop is present in the linked list, the code will return True ; otherwise, it will return False .

Alternative Answer

If the linked list is changeable and we can alter the existing nodes, an alternative method involves marking nodes as visited while we navigate through the list. When we come across a node that has already been marked as visited, it indicates the presence of a loop. Below is a possible implementation in Python: class Node : def __init__ ( self , x ) : self . val = x self . next = None self . visited = False def has_cycle ( head ) : current = head while current : if current . visited : return True current . visited = True current = current . next return False In this method, we introduce an additional visited attribute to each node. As we move through the list, we mark each node as visited. If we detect a node that is already marked as visited, it indicates that a loop exists.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Apple

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.