Bloomberg interview question

How do we find if a linked list has a loop..

Interview Answers

Anonymous

3 Aug 2015

You could make a hashmap of all the nodes and youll know when you have run across a node for a second time...its O(n) space and time though... if you want O(n) time and O(1) space: 1. record the first node somewhere (Node first = current) 2. for every node you visit (from the beginning) ...a. take a note of what the next node is (Node nextNode = current.next) ...b. for the node you are currently on, have it point to the previous node (this will be null in the beginning) (current.next = previous) ...c. keep note of the current node before you move onto the next node (previous = current) ...d. move onto the next node (current = next) ...e. if you are pointing to null, then check to see if previous==first...if it does, then you have a loop..otherwise, there is no loop

Anonymous

3 Aug 2015

You could make a hashmap of all the nodes and youll know when you have run across a node for a second time...its O(n) space and time though... if you want O(n) time and O(1) space: 1. record the first node somewhere (Node first = current) 2. for every node you visit (from the beginning) ...a. take a note of what the next node is (Node nextNode = current.next) ...b. for the node you are currently on, have it point to the previous node (this will be null in the beginning) (current.next = previous) ...c. keep note of the current node before you move onto the next node (previous = current) ...d. move onto the next node (current = next) ...e. if you are pointing to null, then check to see if previous==first...if it does, then you have a loop..otherwise, there is no loop

Anonymous

1 Mar 2016

Use two pointers: slowPtr=slowPtr.next, fastPtr=fastPtr.next.next. If there is loop in linked list, slowPtr and fastPtr will definitely meet somewhere in the middle.