Minimum Edge Weight Equilibrium Queries in a Tree
Time O(r * (n + q)) · Space O(r * n + q) · Official statement on LeetCode
Solutions
// Time: O(r * (n + q)), r = max(w for _, _, w in edges)
// Space: O(r * n + q)
// Tarjan's Offline LCA Algorithm
class Solution {
private:
static const int MAX_W = 26;
public:
vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {
vector<vector<pair<int, int>>> adj(n);
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1], e[2] - 1), adj[e[1]].emplace_back(e[0], e[2] - 1);
}
unordered_map<int, unordered_set<int>> pairs;
for (const auto& q : queries) {
pairs[q[0]].emplace(q[1]), pairs[q[1]].emplace(q[0]);
}
TreeInfos tree_infos(adj, pairs);
vector<int> result(size(queries));
for (int i = 0; i < size(queries); ++i) {
const auto& a = queries[i][0], &b = queries[i][1];
const auto& lca = tree_infos.lca(a, b);
int mx = 0;
for (int w = 0; w < MAX_W; ++w) {
mx = max(mx, tree_infos.count(a, w) + tree_infos.count(b, w) - 2 * tree_infos.count(lca, w));
}
result[i] = (tree_infos.depth(a) + tree_infos.depth(b) - 2 * tree_infos.depth(lca)) - mx;
}
return result;
}
private:
class UnionFind {
public:
UnionFind(int n)
: set_(n)
, rank_(n)
, ancestor_(n) {
iota(set_.begin(), set_.end(), 0);
iota(ancestor_.begin(), ancestor_.end(), 0); // added
}
int find_set(int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
bool union_set(int x, int y) {
x = find_set(x), y = find_set(y);
if (x == y) {
return false;
}
if (rank_[x] > rank_[y]) {
swap(x, y);
}
set_[x] = y; // Union by rank.
if (rank_[x] == rank_[y]) {
++rank_[y];
}
return true;
}
int find_ancestor_of_set(int x) { // added
return ancestor_[find_set(x)];
}
void update_ancestor_of_set(int x) { // added
ancestor_[find_set(x)] = x;
}
private:
vector<int> set_;
vector<int> rank_;
vector<int> ancestor_; // added
};
class TreeInfos {
public:
TreeInfos(const vector<vector<pair<int, int>>>& adj, const unordered_map<int, unordered_set<int>>& pairs)
: D_(size(adj))
, uf_(size(adj))
, lookup_(size(adj))
, CNT_(size(adj)) // added
, cnt_(MAX_W) { // added
dfs(adj, pairs, 0, -1);
}
int lca(int a, int b) const {
if (a > b) {
swap(a, b);
}
return lca_.at(a).at(b);
}
int depth(int a) const {
return D_[a];
}
int count(int a, int w) const { // added
return CNT_[a][w];
}
private:
void dfs(const vector<vector<pair<int, int>>>& adj,
const unordered_map<int, unordered_set<int>>& pairs,
int u, int p) {
D_[u] = (p == -1) ? 1 : D_[p] + 1;
CNT_[u] = cnt_; // added
for (const auto& [v, w] : adj[u]) {
if (v == p) {
continue;
}
++cnt_[w]; // added
dfs(adj, pairs, v, u);
--cnt_[w]; // added
uf_.union_set(v, u);
uf_.update_ancestor_of_set(u);
}
lookup_[u] = true;
if (!pairs.count(u)) {
return;
}
for (const auto& v : pairs.at(u)) {
if (!lookup_[v]) {
continue;
}
lca_[min(u, v)][max(u, v)] = uf_.find_ancestor_of_set(v);
}
}
vector<int> D_;
UnionFind uf_;
unordered_map<int, unordered_map<int, int>> lca_;
vector<bool> lookup_;
vector<vector<int>> CNT_; // added
vector<int> cnt_; // added
};
};
// Time: O(r * (n + q) + nlogn + qlogn), r = max(w for _, _, w in edges)
// Space: O(r * n + nlogn)
// binary lifting (online lca algorithm)
class Solution2 {
private:
static const int MAX_W = 26;
public:
vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) {
vector<vector<pair<int, int>>> adj(n);
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1], e[2] - 1), adj[e[1]].emplace_back(e[0], e[2] - 1);
}
TreeInfos tree_infos(adj);
vector<int> result(size(queries));
for (int i = 0; i < size(queries); ++i) {
const auto& a = queries[i][0], &b = queries[i][1];
const auto& lca = tree_infos.lca(a, b);
int mx = 0;
for (int w = 0; w < MAX_W; ++w) {
mx = max(mx, tree_infos.count(a, w) + tree_infos.count(b, w) - 2 * tree_infos.count(lca, w));
}
result[i] = (tree_infos.depth(a) + tree_infos.depth(b) - 2 * tree_infos.depth(lca)) - mx;
}
return result;
}
private:
class TreeInfos {
public:
TreeInfos(const vector<vector<pair<int, int>>>& adj)
: L_(size(adj))
, R_(size(adj))
, D_(size(adj))
, P_(size(adj))
, C_(-1)
, CNT_(size(adj)) // added
, cnt_(MAX_W) { // added
dfs(adj, 0, -1);
}
bool is_ancestor(int a, int b) const {
return L_[a] <= L_[b] && R_[b] <= R_[a];
}
int lca(int a, int b) const {
if (D_[a] > D_[b]) {
swap(a, b);
}
if (is_ancestor(a, b)) {
return a;
}
for (int i = size(P_[a]) - 1; i >= 0; --i) { // O(logN)
if (i < size(P_[a]) && !is_ancestor(P_[a][i], b)) {
a = P_[a][i];
}
}
return P_[a][0];
}
int depth(int a) const {
return D_[a];
}
int count(int a, int w) const { // added
return CNT_[a][w];
}
private:
void dfs(const vector<vector<pair<int, int>>>& adj, int u, int p) {
D_[u] = (p == -1) ? 1 : D_[p] + 1;
if (p != -1) {
P_[u].emplace_back(p); // ancestors of the node i
}
for (int i = 0; i < size(P_[u]); ++i) {
if (i >= size(P_[P_[u][i]])) {
break;
}
P_[u].emplace_back(P_[P_[u][i]][i]);
}
L_[u] = ++C_;
CNT_[u] = cnt_; // added
for (const auto& [v, w] : adj[u]) {
if (v == p) {
continue;
}
++cnt_[w]; // added
dfs(adj, v, u);
--cnt_[w]; // added
}
R_[u] = C_;
}
vector<int> L_;
vector<int> R_;
vector<int> D_;
vector<vector<int>> P_;
int C_;
vector<vector<int>> CNT_; // added
vector<int> cnt_; // added
};
};
Beginner Explanation
What is Minimum Edge Weight Equilibrium Queries in a Tree?
Minimum Edge Weight Equilibrium Queries in a Tree (LeetCode #2846) is a Hard problem that primarily trains tree.
How to think about it
- Restate the goal in your own words before coding.
- Work a tiny example by hand so the invariant becomes obvious.
- Identify the pattern — this problem aligns with tree and tarjans offline lca algorithm.
- Only then translate the idea into code.
Why this problem matters
Hard problems force you to combine patterns and prove complexity carefully — interview gold. Official solution notes mention: Tree, Binary Lifting, Tarjan's Offline LCA Algorithm.
AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.
Interview Walkthrough
Interview approach for Minimum Edge Weight Equilibrium Queries in a Tree
Opening (30–60 seconds)
- Clarify inputs/outputs and edge cases (empty input, single element, duplicates, overflow).
- State a brute force so the interviewer knows you can solve it naively.
- Propose the optimal direction tied to tree and tarjans offline lca algorithm.
Core solution narrative
- Define the state you track (pointers, DP cell, set membership, stack top, etc.).
- Explain the transition when you process the next element.
- Call out time (O(r * (n + q))) and space (O(r * n + q)) before coding.
- Code cleanly; narrate variable names.
What interviewers listen for
- Correctness on edge cases
- Complexity honesty
- Ability to discuss trade-offs (e.g., hash map space vs. sort + two pointers)
Follow-up questions they may ask
- Can you solve it with less memory?
- What if the input stream is infinite / doesn't fit in RAM?
- How would tests look for adversarial inputs?
Optimized Approach
Optimized solution notes
The reference solutions on AlgoForge target O(r * (n + q)) time and O(r * n + q) space.
Pattern focus: tree and tarjans offline lca algorithm
Use the pattern as a checklist:
- tree — confirm the invariant holds after each step
- tarjans offline lca algorithm — confirm the invariant holds after each step
Multiple methods appear in the source solutions — compare them and explain when each is preferable.
Implementation tips
- Prefer readable names over micro-optimizations in interviews.
- Extract helpers only when they clarify (e.g., expand-around-center, DFS visit).
- After AC-level logic, re-scan for off-by-one and null checks.
Complexity Analysis
Complexity
| Measure | Bound |
|---|---|
| Time | O(r * (n + q)) |
| Space | O(r * n + q) |
How to justify this in an interview
- Time: count loops, map/set operations, and recursive branching; state average vs worst case if relevant.
- Space: include hash maps, recursion stack, and output allocation when the problem asks for it.
If your implementation differs from the reference, re-derive big-O from your code — never memorize a complexity you cannot defend.
Common Mistakes
Common mistakes on Minimum Edge Weight Equilibrium Queries in a Tree
- Skipping edge cases — empty collections, single-element inputs, max constraints.
- Wrong invariant for tree and tarjans offline lca algorithm — updating state too early or too late.
- Mutating input unexpectedly when the problem forbids it.
- Off-by-one in windows, ranges, or binary search bounds.
- Ignoring overflow / precision for integer arithmetic problems.
- Overengineering — jumping to an advanced structure when a simpler approach works.
Alternative Approaches
Alternatives
The source file includes more than one method. Compare:
- Primary optimized path — best complexity for typical interviews.
- Secondary approach — often brute force, sorting-based, or space-optimized variant.
Practice articulating when you would pick each (constraints, readability, follow-ups).
Edge Cases
Edge cases checklist
- Minimum input size
- Maximum input size / time limits
- Duplicates and already-sorted input
- Negative numbers / zeros (if applicable)
- Disconnected structures (graphs/trees)
- Single path vs branching recursion depth
Pattern Recognition
Spotting this pattern
Signal phrases that point to tree and tarjans offline lca algorithm:
- Sorted input or ability to sort without changing the answer class
- Need for contiguous subarray / substring → consider sliding window
- Need for O(1) membership → hash set/map
- Optimal substructure + overlapping subproblems → DP
- Connectivity / components → graph DFS/BFS or Union-Find
Primary topics: tree.
Follow-up Interview Questions
Follow-ups
- How does the solution change if the input is a stream?
- Can you solve it in-place?
- What if duplicates must be handled differently?
- How would you parallelize the approach?
- Design tests that would break a buggy implementation.
Practice Recommendations
What to practice next
- Re-solve Minimum Edge Weight Equilibrium Queries in a Tree in a second language (cpp, python).
- Drill 3–5 more problems tagged tree.
- Teach the solution out loud in under 5 minutes.
- Add this problem to your revision calendar in 3 days and 14 days.
Visualization
Study checklist
- Read the official problem statement on LeetCode
- Solve on paper / whiteboard first
- Implement the tree and tarjans offline lca algorithm approach
- Verify edge cases from the checklist
- State time and space complexity aloud
- Compare with the AlgoForge reference solution
- Schedule a revision session
Revision notes
Minimum Edge Weight Equilibrium Queries in a Tree (#2846) — Hard. Pattern: tree and tarjans offline lca algorithm. Complexity: O(r * (n + q)) time / O(r * n + q) space. Re-derive the invariant before coding.
FAQs
What is the time complexity of Minimum Edge Weight Equilibrium Queries in a Tree?+
The reference solutions aim for O(r * (n + q)) time and O(r * n + q) space. Always re-derive complexity from the code you write in the interview.
What pattern does Minimum Edge Weight Equilibrium Queries in a Tree use?+
It primarily maps to tree and tarjans offline lca algorithm, within the broader topic of tree.
Is Minimum Edge Weight Equilibrium Queries in a Tree good for interviews?+
Yes — as a Hard problem it is a solid practice target. Pair it with related problems in the same pattern family for spaced repetition.
Where can I read the official statement?+
Open the official LeetCode page for constraints and examples: https://leetcode.com/problems/minimum-edge-weight-equilibrium-queries-in-a-tree/