Linked List Cycle

Python data engineering interview problem. Difficulty: intermediate. Pattern: Linked Lists. About 14 minutes. Part of the Pro drill bank.

Detect a cycle using values and a cycle start index. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.

A linked-list consumer can hang forever when the last node points back to an earlier node. The input describes that link with a cycle start index. Build the list conceptually from values, connect the last node to index pos when pos is non-negative, and detect whether following next links can continue forever. Write has_cycle(values: list, pos: int) -> bool. [3, 2, 0, -4] with pos = 1 loops from -4 back to 2, so it returns True. The starter file already has the function name and harness print lines. Keep them and fill only the function body.

Requirements

  • Return true when a cycle exists.
  • Treat pos -1 as no cycle.
  • Use the node links, not duplicate value checks.

Constraints

  • pos is an index or -1 and values can repeat.
  • Return a boolean; Floyd's slow and fast pointers are the intended method.

Examples

Input: has_cycle([3, 2, 0, -4], 1) Output: True Tail links to index 1.

Topics: lakebench, python, floyd, cycle.

More Python interview questions · All interview problems · Learn data engineering

intermediate

Linked List Cycle

Interview-style drill: Detect a cycle using values and a cycle start index.

Implement `has_cycle(values: list, pos: int) -> bool`. Build a singly linked list from `values`. If `pos >= 0`, connect the last node to the node at index `pos`. Use Floyd's algorithm. Example: `[3, 2, 0, -4], 1` → `True`. Keep the harness.