Problem Statement
You are given n nodes and a list of edges where each edge has a weight. Two nodes are in the same component if they are connected.
Design a data structure that supports:
- union(u, v, weight) — Merge the components containing
uandv. The weight represents the ratio relationshipvalue[u] / value[v] = weight. - query(u, v) — If
uandvare in the same component, return the ratiovalue[u] / value[v]. Otherwise return-1.0.
This is essentially a weighted Union-Find where edges store multiplicative relationships between nodes.
Constraints
1 <= n <= 10^51 <= edges.length <= 2 * 10^50.0 < weight <= 100.0- Queries can be interleaved with union operations
Example
union(0, 1, 2.0) // value[0] / value[1] = 2.0
union(1, 2, 3.0) // value[1] / value[2] = 3.0
query(0, 2) → 6.0 // value[0]/value[2] = (value[0]/value[1]) * (value[1]/value[2]) = 2*3 = 6
query(2, 0) → 0.167 // value[2]/value[0] = 1/6
query(0, 3) → -1.0 // not connected
Follow-ups
- How do you handle path compression while maintaining correct weight calculations?
- What happens when a union creates a contradiction (conflicting ratio)? How would you detect it?
- Can you support a
delete(u, v)operation? What are the challenges? - What's the amortized time complexity with both path compression and union by rank?