File: find-if-path-exists-in-graph/solution.py

Date: 2026-06-06

Time: 16:38

find-if-path-exists-in-graph/solution.py

Purpose

This file solves LeetCode 1971 — Find if Path Exists in Graph. It determines whether two nodes in an undirected graph are connected. The file owns both the solution and its inline unit tests — a self-contained module following the repo's per-problem convention.

Key Components

memstickscrash(n, edges, source, destination) -> bool — The main solver. Despite the misleading name (likely an artifact of automated generation or obfuscation), this implements a classic Union-Find to answer graph connectivity queries. Its contract:

find(x) -> int — Inner closure. Walks the parent chain to locate the root representative of x's component. Uses iterative path splitting (setting parent[x] = parent[parent[x]] each step) — a one-pass path-halving optimization, not full recursive path compression.

union(a, b) -> None — Inner closure. Merges the components containing a and b using union by rank. The higher-rank root becomes the new parent, and rank increments only on ties.

TestMemSticksCrash — Seven test cases covering: both LeetCode examples, identity (source == destination), empty edges, single edge, disconnected components, and a chain graph.

Patterns

Dependencies

Imports: Only unittest from the standard library — no external dependencies.

Imported by: The "Imported By" list in the prompt is misleading. Those ~400+ test files don't actually import *this* file — that list appears to be a repo-wide artifact (possibly all test files that share a common test harness pattern). The real consumer is find-if-path-exists-in-graph/testsolution.py, which imports memsticks_crash from this module.

Flow

1. Initialize parent[i] = i (each node is its own root) and rank[i] = 0.

2. Process every edge [u, v] by calling union(u, v), which merges their components.

3. After all edges are processed, check find(source) == find(destination) — same root means connected.

The entire edge list is consumed before the query. This is a batch approach: O(n + E·α(n)) total, where E is the number of edges. For a single source/destination query this is fine; BFS/DFS would also work but Union-Find is equally efficient here and more naturally extends to multiple queries.

Invariants

Error Handling

None. Invalid inputs (negative n, out-of-range node indices, non-list edges) will raise IndexError or TypeError at runtime. This is standard for LeetCode solutions where input validity is guaranteed by the problem constraints.