Linked List

How does one find a loop in a singly linked list in O(n) time using constant memory? You cannot modify the list in any way (and constant memory means the amount of memory required for the solution cannot be a function of n.).


Solution

I first figured this out when I was asked the question in a Microsoft interview, so there’s verification that one question in the book was from a real interview. The best part of this problem is that I actually needed to write the code out for it a little while ago to detect a bug.

One way to detect a loop is to iterate over the list with 2 pointers at the same time where one is iterating at double speed. If the 2 pointers are ever equal after they iterate once and before they both reach an end, there’s a loop.

Now for another puzzle.. I think the next question I had to answer was something along the lines of “OK, How do you remove a loop in a linked list with the same constraints?” The latter question definitely seems harder, but in the sequence of questions I’d already answered for the interviewer, the solution was pretty obvious. I’ll leave that solution to someone else today.

Hm. I think I should pick up that book. I’ve always wondered where people got their juicy interview riddles.. I’ve always just repeated ones I’ve heard before or made up new ones along the same lines.

💡Strategies for Solving This Problem

Linked List Operations

This is a general linked list problem that usually asks you to implement common operations. Let me cover the most frequently asked ones.

Common Operations

1. Insertion: Beginning, end, at position

2. Deletion: By value, at position

3. Search: Find node by value

4. Reverse: Covered in other problems

5. Find middle: Slow/fast pointer

6. Detect cycle: Covered separately

The Dummy Node Trick

Use a dummy node at the start to simplify edge cases. Makes insertion/deletion code cleaner because you never need to update head pointer directly.

The Two-Pointer Patterns

Find middle: Slow moves 1 step, fast moves 2. When fast reaches end, slow is at middle.

Nth from end: Move fast n steps ahead, then move both until fast reaches end.

Cycle detection: If fast ever equals slow, there's a cycle.

What Interviewers Look For

  • Handling null/empty lists
  • Not losing references (causing memory leaks)
  • Edge cases: single node, two nodes
  • Clean code without lots of special cases

At Various Companies

Every company asks linked list questions. They're fundamental. The key is knowing the patterns (dummy node, two pointers, recursion) and applying them cleanly.

Most common: "Remove nth node from end" (fast/slow pointers), "Merge two sorted lists" (like merge sort), "Find intersection of two lists" (length difference trick).

Scroll to Top