#3887
Incremental Even-Weighted Cycle Queries
HardUnion-FindGraph TheoryUnion-FindGraph Traversal
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n α(n)) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n α(n))Space O(n)
Use Union-Find to manage connected components and track parity. Each node can represent a bit, ensuring cycles maintain even weights.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a Union-Find structure to manage components and their parities.
- 2Step 2: For each edge, check if it can be added without creating an odd-weight cycle using the Union-Find structure.
- 3Step 3: If it can be added, union the nodes and update their parities accordingly.
solution.py33 lines
1class UnionFind:
2 def __init__(self, n):
3 self.parent = list(range(n))
4 self.rank = [0] * n
5 self.parity = [0] * n
6 def find(self, x):
7 if self.parent[x] != x:
8 orig_parent = self.parent[x]
9 self.parent[x] = self.find(self.parent[x])
10 self.parity[x] ^= self.parity[orig_parent]
11 return self.parent[x]
12 def union(self, x, y, weight):
13 rootX = self.find(x)
14 rootY = self.find(y)
15 if rootX != rootY:
16 if self.rank[rootX] > self.rank[rootY]:
17 self.parent[rootY] = rootX
18 self.parity[rootY] = self.parity[x] ^ self.parity[y] ^ weight
19 else:
20 self.parent[rootX] = rootY
21 self.parity[rootX] = self.parity[x] ^ self.parity[y] ^ weight
22 if self.rank[rootX] == self.rank[rootY]:
23 self.rank[rootY] += 1
24 def add_edges_optimal(n, edges):
25 uf = UnionFind(n)
26 count = 0
27 for u, v, w in edges:
28 if uf.find(u) != uf.find(v):
29 uf.union(u, v, w)
30 count += 1
31 elif (uf.parity[u] ^ uf.parity[v] ^ w) != 0:
32 continue
33 return countℹ
Complexity note: Union-Find operations are nearly constant time, leading to efficient edge processing.
- 1Cycles must maintain even weight sums.
- 2Union-Find helps manage components and parity efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.