</>

399. Evaluate Division

Medium
Graphs Time O(Q*(V+E) Space O(V+E)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
Graphs
Time
O(Q*(V+E)
Space
O(V+E)

Standard Solution (C++)

SummaryGiven a list of variable-ratio equations (e.g., a/b = 2.0) and a list of queries, compute the result of each queried division by chaining known ratios, returning -1.0 for any query that cannot be resolved.

Approach
  • Model variables as nodes in a weighted directed graph: for each equation a/b = v, add edges a→b with weight v and b→a with weight 1/v.
  • For each query (src, dst), run BFS from src, multiplying edge weights along the path to accumulate the ratio product.
  • Return -1.0 if either variable is unknown (not in the graph) or no path exists between them.
  • BFS guarantees correctness because every valid path through the graph yields the same numerical result (ratios are consistent by problem guarantee).
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;

class Solution {
public:
    vector<double> calcEquation(vector<vector<string>>& equations,
                                vector<double>& values,
                                vector<vector<string>>& queries) {
        // Build adjacency list: graph[u][v] = u/v
        unordered_map<string, unordered_map<string, double>> graph;
        for (int i = 0; i < (int)equations.size(); ++i) {
            const string& a = equations[i][0];
            const string& b = equations[i][1];
            double v = values[i];
            graph[a][b] = v;
            graph[b][a] = 1.0 / v;
        }

        // BFS helper: returns product of edge weights along path src->dst, or -1
        auto bfs = [&](const string& src, const string& dst) -> double {
            if (!graph.count(src) || !graph.count(dst)) return -1.0;

            // {current node, accumulated product}
            queue<pair<string, double>> q;
            unordered_set<string> visited;
            q.push({src, 1.0});
            visited.insert(src);

            while (!q.empty()) {
                auto [node, prod] = q.front();
                q.pop();

                if (node == dst) return prod;

                for (const auto& [neighbor, weight] : graph[node]) {
                    if (!visited.count(neighbor)) {
                        visited.insert(neighbor);
                        q.push({neighbor, prod * weight});
                    }
                }
            }
            return -1.0; // no path found
        };

        vector<double> results;
        results.reserve(queries.size());
        for (const auto& query : queries)
            results.push_back(bfs(query[0], query[1]));

        return results;
    }
};
Time O(Q * (V + E)) where Q = number of queries, V = number of distinct variables, E = number of equations Space O(V + E) for the graph plus O(V) per BFS call for the visited set

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

#include <unordered_map>
#include <unordered_set>
#include <queue>
using namespace std;

class Solution {
public:
    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
        unordered_map<string, unordered_map<string, double>> g;
        // build the graph
        int n=equations.size();
        for(int i=0; i<n; ++i){
            string a=equations[i][0];
            string b=equations[i][1];
            double val=values[i];
            g[a][b]=val;
            g[b][a]=1/val;
        }

        // do bfs
        vector<double> res;
        for(const auto& query: queries){
            string a=query[0];
            string b=query[1];
            if(!g.count(a) || !g.count(b)){
                res.push_back(-1.0);
                continue;
            }
            // find a path from a to b
            unordered_set<string> visited;
            queue<pair<string, double>> q;
            q.push({a, 1.0});
            visited.insert(a);
            bool found=false;
            double ans=-1.0;
            
            while(!q.empty()){
                auto [u, prod]=q.front();
                q.pop();
                if(u==b){
                    found=true;
                    ans=prod;
                }
                for(const auto& [node, weight]: g[u]){
                    if(!visited.count(node)){
                        q.push({node, weight*prod});
                        visited.insert(u);
                    }
                }
            }

            res.push_back(ans);
        }

        return res;
    }
};

// Time Complexity: O(Q*(V+E)), where Q is the number of queries, V is the number of variables, and E is the number of equations.
// Space Complexity: O(V+E) for the graph, O(V) for the visited set, and O(Q) for the result vector.
Time O(Q*(V+E) Space O(V+E)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern