Evaluate Division
Time O(e + q) · Space O(n) · Official statement on LeetCode
Solutions
// Time: O((e + q) * α(n)) ~= O(e + q), using either one of "path compression" and "union by rank" results in amortized O(logn)
// , using both results in α(n) ~= O(1)
// Space: O(n)
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
UnionFind union_find;
for (int i = 0; i < equations.size(); ++i) {
union_find.union_set(equations[i][0], equations[i][1], values[i]);
}
vector<double> result;
for (const auto& q : queries) {
result.emplace_back(union_find.query_set(q[0], q[1]));
}
return result;
}
private:
class UnionFind {
public:
UnionFind() {
}
pair<string, double> find_set(const string& x) {
if (!set_.count(x)) {
set_[x] = pair(x, 1.0);
}
const auto& [xp, xr] = set_[x];
if (x != xp) {
const auto& [pp, pr] = find_set(xp); // Path compression.
set_[x] = pair(pp, xr * pr);
}
return set_[x];
}
bool union_set(const string& x, const string& y, double r) {
const auto& [xp, xr] = find_set(x);
const auto& [yp, yr] = find_set(y);
if (xp == yp) {
return false;
}
if (rank_[xp] < rank_[yp]) { // Union by rank.
set_[xp] = pair(yp, r * yr / xr);
} else if (rank_[xp] > rank_[yp]) {
set_[yp] = pair(xp, 1.0 / r * xr / yr);
} else {
set_[yp] = pair(xp, 1.0 / r * xr / yr);
++rank_[xp];
}
return true;
}
double query_set(const string& x, const string& y) {
if (!set_.count(x) || !set_.count(y)) {
return -1.0;
}
const auto& [xp, xr] = find_set(x);
const auto& [yp, yr] = find_set(y);
return (xp == yp) ? xr / yr : -1.0;
}
private:
unordered_map<string, pair<string, double>> set_;
unordered_map<string, int> rank_;
};
class UnionFindPathCompressionOnly {
public:
UnionFindPathCompressionOnly() {
}
pair<string, double> find_set(const string& x) {
if (!set_.count(x)) {
set_[x] = pair(x, 1.0);
}
const auto& [xp, xr] = set_[x];
if (x != xp) {
const auto& [pp, pr] = find_set(xp); // Path compression.
set_[x] = pair(pp, xr * pr);
}
return set_[x];
}
bool union_set(const string& x, const string& y, double r) {
const auto& [xp, xr] = find_set(x);
const auto& [yp, yr] = find_set(y);
if (xp == yp) {
return false;
}
set_[xp] = pair(yp, r * yr / xr);
return true;
}
double query_set(const string& x, const string& y) {
if (!set_.count(x) || !set_.count(y)) {
return -1.0;
}
const auto& [xp, xr] = find_set(x);
const auto& [yp, yr] = find_set(y);
return (xp == yp) ? xr / yr : -1.0;
}
private:
unordered_map<string, pair<string, double>> set_;
};
};
// Time: O(e + q * n), at most O(n^3 + q)
// Space: O(n^2)
// bfs solution
class Solution2 {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
unordered_map<string, unordered_map<string, double>> adj;
for (int i = 0; i < equations.size(); ++i) {
const auto& a = equations[i][0], &b = equations[i][1];
adj[a][b] = values[i];
adj[b][a] = 1.0 / values[i];
}
vector<double> result;
unordered_map<string, unordered_map<string, double>> lookup;
for (const auto& q : queries) {
const auto& a = q[0], &b = q[1];
result.emplace_back(bfs(adj, a, b, &lookup));
}
return result;
}
private:
double bfs(const unordered_map<string, unordered_map<string, double>>& adj,
const string& a, const string& b,
unordered_map<string, unordered_map<string, double>> *lookup) {
if (!adj.count(a) || !adj.count(b)) {
return -1.0;
}
if (lookup->count(a) && (*lookup)[a].count(b)) {
return (*lookup)[a][b];
}
unordered_set<string> visited = {a};
queue<pair<string, double>> q({{a, 1.0}});
while (!q.empty()) {
const auto [u, val] = q.front(); q.pop();
if (u == b) {
(*lookup)[a][b] = val;
return val;
}
if (!adj.count(u)) {
continue;
}
for (const auto& [v, k] : adj.at(u)) {
if (visited.count(v)) {
continue;
}
visited.emplace(v);
q.emplace(v, val * k);
}
}
(*lookup)[a][b] = -1.0;
return -1.0;
}
};
// Time: O(n^3 + q)
// Space: O(n^2)
// variant of floyd–warshall algorithm solution
class Solution3 {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
unordered_map<string, unordered_map<string, double>> adj;
for (int i = 0; i < equations.size(); ++i) {
const auto& a = equations[i][0], &b = equations[i][1];
adj[a][a] = adj[b][b] = 1.0;
adj[a][b] = values[i];
adj[b][a] = 1.0 / values[i];
}
for (const auto& [k, _] : adj) {
for (const auto& [i, _] : adj[k]) {
for (const auto& [j, _] : adj[k]) {
adj[i][j] = adj[i][k] * adj[k][j];
}
}
}
vector<double> result;
for (const auto& q : queries) {
const auto& a = q[0], &b = q[1];
result.emplace_back(adj.count(a) && adj[a].count(b) ? adj[a][b] : -1.0);
}
return result;
}
};
// Time: O(e + q * n), at most O(n^3 + q)
// Space: O(e)
class Solution4 {
public:
vector<double> calcEquation(vector<pair<string, string>> equations,
vector<double>& values, vector<pair<string, string>> query) {
unordered_map<string, unordered_map<string, double>> lookup;
for (int i = 0; i < values.size(); ++i) {
lookup[equations[i].first].emplace(equations[i].second, values[i]);
if (values[i] != 0) {
lookup[equations[i].second].emplace(equations[i].first, 1 / values[i]);
}
}
vector<double> result;
for (const auto& i : query) {
unordered_set<string> visited;
const auto tmp = check(i.first, i.second, lookup, &visited);
if (tmp.first) {
result.emplace_back(tmp.second);
} else {
result.emplace_back(-1);
}
}
return result;
}
private:
pair<bool, double> check(string up, string down,
unordered_map<string, unordered_map<string, double>> &lookup,
unordered_set<string> *visited) {
if (lookup[up].find(down) != lookup[up].end()) {
return {true, lookup[up][down]};
}
for (const auto& q : lookup[up]) {
if (!visited->count(q.first)) {
visited->emplace(q.first);
const auto tmp = check(q.first, down, lookup, visited);
if (tmp.first) {
return {true, q.second * tmp.second};
}
}
}
return {false, 0};
}
};
Beginner Explanation
What is Evaluate Division?
Evaluate Division (LeetCode #399) is a Medium problem that primarily trains graph.
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 floyd warshall algorithm, queue bfs, and union find.
- Only then translate the idea into code.
Why this problem matters
It sits in the sweet spot of interview difficulty: multiple valid approaches, clear trade-offs. Official solution notes mention: Floyd-Warshall Algorithm, BFS, Union Find.
AlgoForge explanations are original teaching notes. Always open the official problem statement on LeetCode for constraints and examples.
Interview Walkthrough
Interview approach for Evaluate Division
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 floyd warshall algorithm, queue bfs, and union find.
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(e + q)) and space (O(n)) 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(e + q) time and O(n) space.
Pattern focus: floyd warshall algorithm, queue bfs, and union find
Use the pattern as a checklist:
- floyd warshall algorithm — confirm the invariant holds after each step
- queue bfs — confirm the invariant holds after each step
- union find — 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(e + q) |
| Space | O(n) |
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 Evaluate Division
- Skipping edge cases — empty collections, single-element inputs, max constraints.
- Wrong invariant for floyd warshall algorithm, queue bfs, and union find — 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 floyd warshall algorithm, queue bfs, and union find:
- 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: graph.
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 Evaluate Division in a second language (cpp, python).
- Drill 3–5 more problems tagged graph.
- 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 floyd warshall algorithm, queue bfs, and union find 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
Evaluate Division (#399) — Medium. Pattern: floyd warshall algorithm, queue bfs, and union find. Complexity: O(e + q) time / O(n) space. Re-derive the invariant before coding.
FAQs
What is the time complexity of Evaluate Division?+
The reference solutions aim for O(e + q) time and O(n) space. Always re-derive complexity from the code you write in the interview.
What pattern does Evaluate Division use?+
It primarily maps to floyd warshall algorithm, queue bfs, and union find, within the broader topic of graph.
Is Evaluate Division good for interviews?+
Yes — as a Medium 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/evaluate-division/