20/39
Part 4 of 7 · Cycles and meeting pointsLearn and do

Level the lengths, then step both pointers together

The set version comes first. Put every node of a in a set, then walk b until a node is in it:

def shared_by_set(a, b):
    seen = set()
    while a is not None:
        seen.add(a)
        a = a.next
    while b is not None:
        if b in seen:
            return b
        b = b.next
    return None


print(shared_by_set(a, b).val)
7

That's O(m + n) time for lists of m and n nodes, and O(m) memory for the set.

To drop the set, look at where the lengths differ. Past the shared node both lists are the same nodes, so the whole difference in length is in the part before it.

Count both lengths, and move the longer list's pointer ahead by the difference. Now both pointers are the same distance from the end. Step both together until they're the same node:

b has 6 nodes and a has 5, so b's pointer starts 1 node in
b
5
→
1pb
→
9step 1
→
7step 2
→
3
→
6
→None
a
2pa
→
9step 1
→
7step 2
→
3
→
6
→None

Step 1 puts pa and pb on two 9s: equal values, two nodes, so go on. Step 2 puts them on the same 7: return it.

If the lists never meet, both pointers reach None on the same step, and None is None ends the loop with the right answer. That's O(m + n) time and O(1) memory.

In the editor, finish first_shared(a, b) by leveling the lengths. It finds the first shared node of the two lists, both ways round.