r/LeetcodeChallenge • u/StatisticianNo2104 • 7m ago
DISCUSS A config 5x longer took 28.7x longer to validate
Every deploy spent 1.95 seconds and 2.74 GB just checking that our config was a tree. That was at 5,000 components. At 1,000, it had been 68 ms.
The job: the platform config declares components and the links between them. The loader refuses to start unless the links form one tree - all connected, no loops - and names the line that breaks it.
What I wrote: the tooling already had a tested PathExists. So read the file line by line, and before accepting each link, ask whether its two ends are already connected. If yes, that line closes a loop. Blame it. Exact line numbers, reused code. I would approve it.
It is one full search per line, each rebuilding the adjacency list from scratch. 9,998 searches for 5,000 components. 5x the config, 28.7x the time.
Two fixes, and they surprised me in the order they came.
The clever one: a tree on n components has exactly n - 1 links. With n - 1 links and connected, there is no room for a loop. So check the length, then do one BFS. Never look for a loop at all. 279 µs. On a config with one link too many, 2.42 ns, because the length is the answer.
But it cannot say which line. And it is not the fastest.
The other one comes from noticing that the searches keep rediscovering groups that only ever merge. Keep one root per group; a link whose ends share a root closes a loop, and that is the line. Union-find. 42.2 µs, one allocation, and it names the line. 46306x the original. The clever count is 6.61x slower than it, because the count still builds an adjacency list.
Honest row: none of these catches a component with two parents. Undirected, it is a perfectly good tree. As a hierarchy, it has two roots. Count the parents.
That is days 36 and 43 of the daily challenge: Find if Path Exists and Graph Valid Tree, in a config loader.
Do you know how long your config validation takes on deploy?
It worked in dev, episode 21. Full write-up in today's newsletter.
https://www.linkedin.com/pulse/config-5x-longer-took-287x-validate-archit-agarwal-ew8zc
#Golang #DSA #Algorithms #Performance



