There is a solution given by amit. The problem is that you either know it or not, but you won’t be able to figure it out in an interview. Since I never had to find a loop in a linked list, knowing that this was pointless to me, except for transmitting the interview. Therefore, for the interviewer, stating this as an interview question, and waiting for the amir’s response (which is nice because it has linear time and zero extra space), is pretty stupid.
So, your solution is mostly fine, except that you have to use a hash table, and you have to make sure that the hash table hashes links to nodes, not nodes. Let's say you have a node containing the string and the “next” pointer, and the hash function hashes the string and compares the nodes as equal if the lines are equal. In this case, you will find the first node with a repeating line, and not node at the beginning of the loop, if you are not careful.
(the amir solution has a very similar problem in languages where == compares objects, not links. For example, in Swift you have to use === (compares links) rather than == (compares objects)).
gnasher729
source share