This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Solution Notebook

Problem: Find the start of a linked list loop.

Constraints

  • Is this a singly linked list?
    • Yes
  • Can we assume we are always passed a circular linked list?
    • No
  • Can we assume we already have a linked list class that can be used for this problem?
    • Yes

Test Cases

  • Empty list -> None
  • Not a circular linked list -> None
    • One element
    • Two or more elements
  • Circular linked list general case

Algorithm

  • Use two pointers i, j, initialized to the head
  • Increment i and j until they meet
    • j is incremented twice as fast as i
      • If j's next is None, we do not have a circular list
  • When i and j meet, move j to the head
  • Increment i and j one node at a time until they meet
  • Where they meet is the start of the loop

Complexity:

  • Time: O(n)
  • Space: O(1)

Code


In [1]:
%run ../linked_list/linked_list.py

In [2]:
class MyLinkedList(LinkedList):

    def find_loop_start(self):
        if self.head is None or self.head.next is None:
            return
        i = self.head
        j = self.head
        i = i.next
        j = j.next.next

        # Increment i and j until they meet
        # j is incremented twice as fast as i
        while j != i:
            i = i.next
            if j is None or j.next is None:
                return
            j = j.next.next

        # When i and j meet, move j to the head
        j = self.head

        # Increment i and j one node at a time until
        # they meet, which is the start of the loop
        while j != i:
            i = i.next
            j = j.next
        return i.data

Unit Test


In [3]:
%%writefile test_find_loop_start.py
from nose.tools import assert_equal


class TestFindLoopStart(object):

    def test_find_loop_start(self):
        print('Test: Empty list')
        linked_list = MyLinkedList()
        assert_equal(linked_list.find_loop_start(), None)

        print('Test: Not a circular linked list: One element')
        head = Node(1)
        linked_list = MyLinkedList(head)
        assert_equal(linked_list.find_loop_start(), None)

        print('Test: Not a circular linked list: Two elements')
        linked_list.append(2)
        assert_equal(linked_list.find_loop_start(), None)

        print('Test: Not a circular linked list: Three or more elements')
        linked_list.append(3)
        assert_equal(linked_list.find_loop_start(), None)

        print('Test: General case: Circular linked list')
        node10 = Node(10)
        node9 = Node(9, node10)
        node8 = Node(8, node9)
        node7 = Node(7, node8)
        node6 = Node(6, node7)
        node5 = Node(5, node6)
        node4 = Node(4, node5)
        node3 = Node(3, node4)
        node2 = Node(2, node3)
        node1 = Node(1, node2)
        node0 = Node(0, node1)
        node10.next = node3
        linked_list = MyLinkedList(node0)
        assert_equal(linked_list.find_loop_start(), 3)

        print('Success: test_find_loop_start')


def main():
    test = TestFindLoopStart()
    test.test_find_loop_start()


if __name__ == '__main__':
    main()


Overwriting test_find_loop_start.py

In [4]:
%run -i test_find_loop_start.py


Test: Empty list
Test: Not a circular linked list: One element
Test: Not a circular linked list: Two elements
Test: Not a circular linked list: Three or more elements
Test: General case: Circular linked list
Success: test_find_loop_start