↓Skip to main content
  1. LeetCode/

LeetCode 1627: Graph Connectivity With Threshold

·2 mins· ·
LeetCode Hard Math Number-Theory Union-Find Array
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: hard First Attempt: 2026-09-05

  • Submissions: Time Limit Exceeded → Accepted

Approach
#

x and y are connected ⇔ some z > threshold divides both.

Turned around: for each z > threshold, all of z, 2z, 3z, ... are connected (z divides them all). So union every multiple of z with z.

  • The number of unions is Σ n / z, a harmonic series, O(n log n).
  • With threshold == 0, z = 1 divides everything, so all are connected.
  • For z > n / 2, z has no other multiple in range, so skip it.

A query asks whether two cities share a root.

My Attempts
#

Attempt 1 computed GCDs for every pair of cities, O(n^2 log n), a TLE at n = 10^4. “Each z connects its multiples” passed in 44ms.

Solution
#

class Solution:
    def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:
        parent = list(range(n + 1))

        def find(a: int) -> int:
            while parent[a] != a:
                parent[a] = parent[parent[a]]
                a = parent[a]
            return a

        for z in range(threshold + 1, n // 2 + 1):
            for multiple in range(2 * z, n + 1, z):  # all multiples of z are connected
                parent[find(multiple)] = find(z)

        return [find(a) == find(b) for a, b in queries]

With threshold == 0, z starts at 1, whose multiples are everything, so the loop connects all cities with no special case.

Complexity
#

Time O(n log n · α(n) + q), space O(n).

Mistakes to Avoid
#

  • Pairwise GCDs: O(n^2).
  • z must be strictly greater than threshold.

Interview Explanation
#

Instead of pairwise GCDs I flip it: for each z above the threshold, all its multiples are connected, so I union them with z in Union-Find. The unions total a harmonic series, O(n log n), and each query compares two roots.

Related

LeetCode 2709: Greatest Common Divisor Traversal
·3 mins
LeetCode Hard Math Number-Theory Union-Find Sieve Gcd Array
LeetCode 2709 note: every pair of indices connects ⇔ one component; factor with SPF and union each number with its prime factors in Union-Find, treating 1 specially
LeetCode 952: Largest Component Size by Common Factor
·2 mins
LeetCode Hard Math Number-Theory Union-Find Hash-Table Array
LeetCode 952 note: sharing a factor ⇔ sharing a prime factor; factor each number and union indices with the same prime factor using Union-Find, with no pairwise GCDs
LeetCode 3873: Maximum Points Activated with One Addition
·2 mins
LeetCode Hard Union-Find Hash-Table Array
LeetCode 3873 note: merge points sharing an x or y into components; a new point joins at most two of them, so the answer is the two largest plus 1
LeetCode 2382: Maximum Segment Sum After Removals
·2 mins
LeetCode Hard Union-Find Prefix-Sum Ordered-Set Array
LeetCode 2382 note: work backward so removals become additions; the Union-Find root stores the segment sum, and the maximum only grows
LeetCode 927: Three Equal Parts
·3 mins
LeetCode Hard Math Array
LeetCode 927 note: every part has the same number of 1s, so count them; the third part always runs to the end of the array, fixing what each part must match, then check the parts do not overlap
LeetCode 204: Count Primes
·2 mins
LeetCode Medium Array Math Enumeration Number-Theory
LeetCode 204 note: the sieve of Eratosthenes, crossing out multiples of each prime p starting at p², with the outer loop only up to √n