Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. Internally, pos is the index the tail's next points to (-1 means no cycle). Do not modify the list, and use O(1) extra memory.
head = [3,2,0,-4], pos = 1node at index 1head = [1,2], pos = 0node at index 0head = [1], pos = -1null (no cycle)headnull (no cycle)head; keep ๐ at the meeting pointWhen they meet, ๐ข has walked a + b and ๐ has walked 2(a + b), which is also a + b + kยทL (it lapped the loop k times). So a + b = kยทL, i.e. a = kยทL โ b = (k โ 1)ยทL + c. Walking a steps from the meeting point lands on the start. That's exactly what walking a steps from head does.
Empty list or one node without a loop โ return null. Cycle starts at head (pos = 0) โ they meet, and after the reset both are already on the answer. Self-loop at the tail works the same way. A HashSet solution is simpler but uses O(n) memory; interviewers expect this O(1) version.