Does the Treasure Hunt Loop?

Medium · Linked Lists · about 30 min

A treasure hunt has clues numbered 0 to n - 1. Clue i sends you to clue nxt[i], or nxt[i] = -1 means the hunt ends at clue i. Everyone starts at clue 0.

If following the clues from clue 0 never ends, the hunt has a loop. Return [first, length]:

  • first is the first clue you reach that is part of the loop,
  • length is how many different clues are in the loop.

If the hunt ends, return [-1, 0]. Clues that cannot be reached from clue 0 do not matter, even if they form a loop of their own. Aim for O(1) extra memory (no visited set).

  • 1 <= len(nxt), and every nxt[i] is -1 or a valid clue number.

Example: hunt_loop([1, 2, 3, 1]) → [1, 3] (0 → 1 → 2 → 3 → back to 1)

Hints

  • Before moving the fast pointer two steps, check that neither step lands on -1. If one does, there is no loop.
  • After slow and fast meet, restart one pointer from clue 0 and move both one step at a time. Where they meet is the first clue of the loop.
  • From that clue, keep stepping and count until you come back to it: that is the loop's length.

Learn the pattern first: the Linked Lists lesson.

More Linked Lists problems