Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    Find where a linked list loops back

    MediumAbout 25 minFull AccessLearn it: Linked Lists in C#: Reversal, Fast and Slow Pointers, Merging and an LRU Cache

    The task

    A job scheduler keeps its tasks in a singly linked list. A bug can point a task's Next back to an earlier task, and then following Next never ends. The scheduler needs the task where the loop starts, to cut it there.

    Complete CycleStart(ListNode? head). Return the node where the loop begins: the first node, counting from the head, that following Next reaches a second time. Return null if the list ends. Compare nodes, not values: different nodes can hold the same value. Use O(1) extra memory and do not change the list. The ListNode class is given; do not change it.

    Signature

    public static ListNode? CycleStart(ListNode? head)

    Examples

    • list 1 → 2 → 3 → 4 → back to the node 2 → the node 2. Following Next from 4 goes back to 2, and 2 is the first node reached twice.
    • list 1 → 2 → 3 → null. The list ends, so there is no loop.

    Limits: Up to 5,000 nodes.

    The tests check: an empty list, one node with and without a loop, a loop back to the first node, nodes with equal values, equal values without a loop, that your method leaves the list unchanged, and a long list with a loop starting in the middle.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      // A node of a singly linked list. Do not change this class: the tests build lists with it.
      public sealed class ListNode
      {
          public int Val;
          public ListNode? Next;
      
          public ListNode(int val, ListNode? next = null)
          {
              Val = val;
              Next = next;
          }
      }
      
      public static class Solution
      {
          // Returns the node where the list's loop begins, or null if the list ends.
          public static ListNode? CycleStart(ListNode? head)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.