Twenty-Five Days · day 23 · both parts
Day 23: LAN Party
A graph day. Part 1 counts triangles, and the trick is to start from the links rather than from every set of three. Part 2 asks for the largest clique, a problem with no known fast algorithm for every graph, and the interesting part is which method you can trust.
The puzzle, in my words
Each line of the input links two computers with two-letter names, like
kh-tc, and links work both ways. Count the groups of three computers that
are all linked to each other, keeping only the groups where at least one name
starts with t.
The example has 16 computers and 32 links. They form 12 such triangles, and
7 of them have a t computer, for example co,de,ta and qp,td,wh.
Part 1: triangles with a t in them
Step 1: the first version
Build each computer’s set of neighbours, then try every group of three and keep the ones where all three links exist:
from collections import defaultdict
from itertools import combinations
def graph(text: str) -> dict[str, set[str]]:
adj = defaultdict(set)
for line in text.split():
a, b = line.split("-")
adj[a].add(b)
adj[b].add(a)
return adj
def part1(text: str) -> int:
adj = graph(text)
count = 0
for a, b, c in combinations(sorted(adj), 3):
linked = b in adj[a] and c in adj[a] and c in adj[b]
if linked and (a[0] == "t" or b[0] == "t" or c[0] == "t"):
count += 1
return count
combinations on a sorted list yields each group once, in order, so no
triangle is counted twice. It is correct and it is slow: n computers make
about n³/6 groups. Write-ups report that real inputs give every computer
exactly 13 links; with a guessed 520 computers that’s about 23 million groups,
almost none of them triangles. On a generated input of that shape this takes
about 0.9 s.
Step 2: start from the links
A triangle is a link a-b plus a computer linked to both ends, and the
computers linked to both are exactly adj[a] & adj[b]. So walk the links and
intersect. Asking for a < b < c finds each triangle once, from its
alphabetically first name, so there’s no set of seen triangles to keep:
def part1(text: str) -> int:
adj = graph(text)
count = 0
for a in adj:
for b in adj[a]:
if b > a:
for c in adj[a] & adj[b]:
if c > b and "t" in (a[0], b[0], c[0]):
count += 1
return count
Each link costs one intersection of two 13-element sets. On the same
generated input this takes about 2.4 ms. You could go further and start only
from the t computers, but then a triangle with two ts is found twice and
needs deduplicating; that came out at 1.4 ms, not worth a step.
The test checks “starts with t”, not “contains t”: at, bt and ct in a
triangle count for nothing.
Part 2: the largest group
Now find the largest set of computers that are all linked to each other, a
maximum clique. The password is their names, sorted and joined with commas.
In the example it is co,de,ka,ta: four computers, six links.
Step 1: keep growing
Part 1 grew links into triangles; keep going. Hold each clique as a sorted tuple and extend it by every computer that is linked to all its members and sorts after its last name, so each clique is built exactly once. When a round makes nothing bigger, the previous round’s cliques are the largest:
def part2(text: str) -> str:
adj = graph(text)
cliques = [(a,) for a in sorted(adj)]
while True:
bigger = [
c + (n,)
for c in cliques
for n in sorted(set.intersection(*(adj[v] for v in c)))
if n > c[-1]
]
if not bigger:
return ",".join(cliques[0])
cliques = bigger
set.intersection(*sets) takes any number of sets, which saves a loop.
This is exact, and it’s fine on the generated input: 27 ms. The catch is that it builds every sub-clique of the answer on the way, and a clique of k computers has 2^k of them. Write-ups report the real answer has 13 names, so that’s 8,192. Plant a 20-clique instead (each computer with 20 links) and this step takes 7.7 s.
Step 2: greedy
From each computer, walk its neighbours and keep each one that is linked to everyone kept so far. That’s one pass per computer, no 2^k:
def part2(text: str) -> str:
adj = graph(text)
best = []
for a in sorted(adj):
clique = [a]
for n in sorted(adj[a]):
if all(n in adj[m] for m in clique):
clique.append(n)
if len(clique) > len(best):
best = clique
return ",".join(sorted(best))
It gets co,de,ka,ta on the example, 3.6 ms on the generated input, and
4 ms even with the planted 20-clique. But it can be wrong. If an early
neighbour isn’t part of the big clique, taking it shuts the clique’s members
out. The tests have a 4-clique ma, mb, mc, md where each member also has a
decoy neighbour whose name sorts first (aa, ab, …) and has no other
link: greedy takes the decoy every time and answers with two names.
Write-ups report that greedy works on the real inputs, because of how they’re built: every computer has 13 links and the answer has 13 members, so from a member of the clique all but one of its neighbours are in it. I couldn’t check that here. It also worked on the three generated inputs I timed (planted cliques of 13, 16 and 20), which says nothing about the real ones, since I built those.
The sorted calls matter more than they look. String hashes are randomised
per run in Python, so iterating over a set of strings can give a different
order each time, and greedy’s answer depends on the order. Sorting makes it
repeatable.
Step 3: Bron-Kerbosch with pivoting
Bron-Kerbosch lists every maximal clique (one that no computer can be added
to) and is exact on any graph. It carries three sets: r, the clique so far;
p, the computers that could still join it; x, the ones already tried from
here. Adding v to r narrows both p and x to v’s neighbours. When p
and x are both empty, r is maximal; when only p is empty, every way to
extend r was already covered by an earlier branch.
The pivot is the speed-up. Take any computer u from p or x: a maximal
clique here either contains u or a computer that isn’t u’s neighbour
(otherwise u could join it). So only u and its non-neighbours need trying,
and choosing the u with the most neighbours in p skips the most.
def part2(text: str) -> str:
adj = graph(text)
best = set()
def expand(r, p, x):
nonlocal best
if not p and not x:
if len(r) > len(best):
best = r
return
pivot = max(sorted(p | x), key=lambda v: len(adj[v] & p))
for v in sorted(p - adj[pivot]):
expand(r | {v}, p & adj[v], x & adj[v])
p.remove(v)
x.add(v)
expand(set(), set(adj), set())
return ",".join(sorted(best))
On the example it makes 40 calls and finds 15 maximal cliques; the clip plays all of them. On the generated input it takes 7.5 ms, a bit slower than greedy, and 10.6 ms with the planted 20-clique. Finding a maximum clique is NP-hard in general, and no known method is fast on every graph, but this one is never wrong, and on graphs like these it is fast too. That’s the version I’d keep. The tests run it and step 1 against a brute force over all subsets on 200 random graphs and check the size of the answer (random graphs often have several largest cliques, so the names can differ).
All of this was checked on the puzzle’s example and on generated inputs, not on a puzzle input of my own.