#3532

Path Existence Queries in a Graph I

Medium
ArrayHash TableBinary SearchUnion-FindGraph TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n + q * α(n))
Space
O(1)
O(n)
💡

Intuition

Time O(n + q * α(n))Space O(n)

Utilize Union-Find to group connected nodes based on the maxDiff condition. Preprocess the nodes into connected components for efficient query resolution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a Union-Find structure to group nodes based on the maxDiff condition.
  2. 2Step 2: Iterate through the sorted nums array, connecting nodes that satisfy the maxDiff condition.
  3. 3Step 3: For each query, check if the two nodes belong to the same connected component.
solution.py16 lines
1class UnionFind:
2    def __init__(self, size):
3        self.parent = list(range(size))
4    def find(self, x):
5        if self.parent[x] != x:
6            self.parent[x] = self.find(self.parent[x])
7        return self.parent[x]
8    def union(self, x, y):
9        self.parent[self.find(x)] = self.find(y)
10
11def pathExist(n, nums, maxDiff, queries):
12    uf = UnionFind(n)
13    for i in range(n - 1):
14        if nums[i + 1] - nums[i] <= maxDiff:
15            uf.union(i, i + 1)
16    return [uf.find(u) == uf.find(v) for u, v in queries]

Complexity note: Union-Find operations are nearly constant time, making it efficient for multiple queries.

  • 1Connected components can be efficiently managed with Union-Find.
  • 2Sorting helps in grouping nodes with similar values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.