LINK-P5

Where the loop starts

Practice 5 of 6Linked lists9 tests

The problem

A linked list may have a loop: its last node points back to an earlier node instead of None. If it does, return the first node of the loop. If it does not, return None.

5 -> 1 -> 8 -> 3 -> 7 -> 2 -> 6 -> 4
               ^                   |
               +-------------------+
loop_start(head)   # the node holding 3

Return the node itself, not its value: the tests check which node you return by its position. Use O(1) extra space. To make that fair, the nodes in the tests cannot be put in a set or used as dictionary keys: trying raises TypeError: unhashable type.

Limits

  • Up to 100,000 nodes.
  • Values can repeat, so you cannot find the loop by looking at values.

Builds on LINK-5 Fast and slow pointers.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1The figure's listNot run
2No loopNot run
3EmptyNot run
4One node, pointing to itselfNot run
5One node, no loopNot run
6Whole list is the loopNot run
7Last node points to itselfNot run
8Same values everywhereNot run
9100,000 nodesNot run