Microsoft interview question

Q: Write a function to detect loop in a linked list.

Interview Answer

Anonymous

23 July 2022

First I told him the brute solution that is to compare every node with each other and if two nodes are equal, loop is detect else return false. Then I told better solution, that is two pointer approach. Make a fast and slow pointer, fast pointer traverse the linked list skipping one node while slow traverse each node. Now when fast == slow, return true i.e. loop is detected. If fast reaches null pointer return false i.e. no loop is detected.