Browse curriculum

Evaluate Division (LeetCode 399)

Evaluate Division (LeetCode 399): given equations like a / b = 2, answer queries like a / c. Build a graph with an edge a → b weighted a / b, and answer each query by DFS, multiplying the weights along the path.

Problem Understanding

Evaluate Division (LeetCode 399): you are given equations equations[i] = [a, b] with values[i], meaning a / b = values[i], and queries [x, y] asking for x / y. Return the answer to every query, or -1.0 if it cannot be determined. The equations never contradict each other and no value is 0.

Example: a / b = 2, b / c = 3; queries a/c, b/a, a/e, a/a, x/x → [6.0, 0.5, -1.0, 1.0, -1.0].

The Intuition: Multiply Along a Path

Ratios chain: knowing a / b and b / c gives a / c by multiplying. So turn the equations into a weighted graph and look for a path.

  1. Build the graph. For a / b = v, add a → b with weight v and b → a with weight 1 / v.
  2. Reject unknown variables. If x or y is not a node, the answer is -1.
  3. DFS from x, carrying the product of the weights walked. Reaching y returns the product; running out of unvisited neighbours returns -1.

It is a DFS on a graph like Keys and Rooms, with a value carried along the path, the way Path Sum carries a running sum down a tree.

Evaluate Division Visualization

a → b LABELLED v MEANS a / b = v · BACKWARDS IS × 1 / v

BUILD THE GRAPH

query

:

product

:

answers

a/c = ?
b/a = ?
a/e = ?
a/a = ?
x/x = ?

 

Each a / b = v becomes a → b with weight v and b → a with weight 1 / v

Next

Query a / c: DFS from a looking for c

Free preview: the first 4 of 13 steps

equations

queries

Each arrow a → b labelled v is one equation; walking it backwards multiplies by 1 / v. During a query the DFS path is outlined with the running product under each node, the target turns green when reached, and dead ends turn red. The answers fill in on the right. Try Two groups, where a query has to give up, and Long chain.

Evaluate Division Dry Run

Input: a / b = 2, b / c = 3; queries a/c, b/a, a/e, a/a, x/x.

Query What happens Product Answer
a / c a → b → c 2 × 3 6
b / a b → a, walking a → b backwards 1 / 2 0.5
a / e e is in no equation -1
a / a a is the target already 1 1
x / x x is in no equation -1

Answer: [6.0, 0.5, -1.0, 1.0, -1.0].

Evaluate Division LeetCode Solution

An adjacency map with weights both ways, then a DFS per query. The C version maps names to numbers and keeps the weights in a matrix.

Evaluate Division Code
1var calcEquation = function(equations, values, queries) {
2 const graph = new Map();
3 equations.forEach(([a, b], i) => {
4 if (!graph.has(a)) graph.set(a, new Map());
5 if (!graph.has(b)) graph.set(b, new Map());
6 graph.get(a).set(b, values[i]);
7 graph.get(b).set(a, 1 / values[i]);
8 });
9 const dfs = (node, target, product, seen) => {
10 if (node === target) {
11 return product;
12 }
13 seen.add(node);
14 for (const [next, w] of graph.get(node)) {
15 if (!seen.has(next)) {
16 const found = dfs(next, target, product * w, seen);
17 if (found !== -1) {
18 return found;
19 }
20 }
21 }
22 return -1;
23 };
24 return queries.map(([x, y]) => {
25 if (!graph.has(x) || !graph.has(y)) {
26 return -1;
27 }
28 return dfs(x, y, 1, new Set());
29 });
30};

Evaluate Division in Python, Java, C++, TypeScript and C

Evaluate Division in Python
class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        graph = defaultdict(dict)
        for (a, b), v in zip(equations, values):
            graph[a][b] = v
            graph[b][a] = 1 / v

        def dfs(node, target, product, seen):
            if node == target:
                return product
            seen.add(node)
            for nxt, w in graph[node].items():
                if nxt not in seen:
                    found = dfs(nxt, target, product * w, seen)
                    if found != -1:
                        return found
            return -1.0

        answers = []
        for x, y in queries:
            if x not in graph or y not in graph:
                answers.append(-1.0)
            else:
                answers.append(dfs(x, y, 1.0, set()))
        return answers
Evaluate Division in Java
class Solution {
    private final Map<String, Map<String, Double>> graph = new HashMap<>();

    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        for (int i = 0; i < values.length; i++) {
            String a = equations.get(i).get(0), b = equations.get(i).get(1);
            graph.computeIfAbsent(a, k -> new LinkedHashMap<>()).put(b, values[i]);
            graph.computeIfAbsent(b, k -> new LinkedHashMap<>()).put(a, 1 / values[i]);
        }
        double[] answers = new double[queries.size()];
        for (int i = 0; i < answers.length; i++) {
            String x = queries.get(i).get(0), y = queries.get(i).get(1);
            if (!graph.containsKey(x) || !graph.containsKey(y)) {
                answers[i] = -1.0;
            } else {
                answers[i] = dfs(x, y, 1.0, new HashSet<>());
            }
        }
        return answers;
    }

    private double dfs(String node, String target, double product, Set<String> seen) {
        if (node.equals(target)) {
            return product;
        }
        seen.add(node);
        for (Map.Entry<String, Double> edge : graph.get(node).entrySet()) {
            if (!seen.contains(edge.getKey())) {
                double found = dfs(edge.getKey(), target, product * edge.getValue(), seen);
                if (found != -1.0) {
                    return found;
                }
            }
        }
        return -1.0;
    }
}
Evaluate Division in C++
class Solution {
    unordered_map<string, vector<pair<string, double>>> graph;

    double dfs(const string& node, const string& target, double product, unordered_set<string>& seen) {
        if (node == target) {
            return product;
        }
        seen.insert(node);
        for (auto& [next, w] : graph[node]) {
            if (!seen.count(next)) {
                double found = dfs(next, target, product * w, seen);
                if (found != -1.0) {
                    return found;
                }
            }
        }
        return -1.0;
    }

public:
    vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
        for (int i = 0; i < (int)values.size(); i++) {
            graph[equations[i][0]].push_back({equations[i][1], values[i]});
            graph[equations[i][1]].push_back({equations[i][0], 1 / values[i]});
        }
        vector<double> answers;
        for (auto& q : queries) {
            if (!graph.count(q[0]) || !graph.count(q[1])) {
                answers.push_back(-1.0);
            } else {
                unordered_set<string> seen;
                answers.push_back(dfs(q[0], q[1], 1.0, seen));
            }
        }
        return answers;
    }
};
Evaluate Division in TypeScript
function calcEquation(equations: string[][], values: number[], queries: string[][]): number[] {
    const graph = new Map<string, Map<string, number>>();
    equations.forEach(([a, b], i) => {
        if (!graph.has(a)) graph.set(a, new Map());
        if (!graph.has(b)) graph.set(b, new Map());
        graph.get(a)!.set(b, values[i]);
        graph.get(b)!.set(a, 1 / values[i]);
    });
    const dfs = (node: string, target: string, product: number, seen: Set<string>): number => {
        if (node === target) {
            return product;
        }
        seen.add(node);
        for (const [next, w] of graph.get(node)!) {
            if (!seen.has(next)) {
                const found = dfs(next, target, product * w, seen);
                if (found !== -1) {
                    return found;
                }
            }
        }
        return -1;
    };
    return queries.map(([x, y]) => {
        if (!graph.has(x) || !graph.has(y)) {
            return -1;
        }
        return dfs(x, y, 1, new Set<string>());
    });
}
Evaluate Division in C
static char* names[40];
static int count;
static double weight[40][40];
static bool seen[40];

static int idOf(char* s, bool add) {
    for (int i = 0; i < count; i++) {
        if (strcmp(names[i], s) == 0) {
            return i;
        }
    }
    if (!add) {
        return -1;
    }
    names[count] = s;
    return count++;
}

static double dfs(int node, int target, double product) {
    if (node == target) {
        return product;
    }
    seen[node] = true;
    for (int next = 0; next < count; next++) {
        if (weight[node][next] > 0 && !seen[next]) {
            double found = dfs(next, target, product * weight[node][next]);
            if (found != -1.0) {
                return found;
            }
        }
    }
    return -1.0;
}

double* calcEquation(char*** equations, int equationsSize, int* equationsColSize, double* values, int valuesSize,
                     char*** queries, int queriesSize, int* queriesColSize, int* returnSize) {
    count = 0;
    memset(weight, 0, sizeof(weight));
    for (int i = 0; i < equationsSize; i++) {
        int a = idOf(equations[i][0], true), b = idOf(equations[i][1], true);
        weight[a][b] = values[i];
        weight[b][a] = 1.0 / values[i];
    }
    double* answers = malloc(queriesSize * sizeof(double));
    *returnSize = queriesSize;
    for (int i = 0; i < queriesSize; i++) {
        int x = idOf(queries[i][0], false), y = idOf(queries[i][1], false);
        if (x == -1 || y == -1) {
            answers[i] = -1.0;
        } else {
            memset(seen, 0, sizeof(seen));
            answers[i] = dfs(x, y, 1.0);
        }
    }
    return answers;
}

Edge Cases & Common Mistakes

  • x / x for an unknown x: the answer is -1, not 1, because x never appears in an equation.
  • x / x for a known x: 1, found immediately without walking any edge.
  • Only adding a → b: queries that need b / a then fail; add the reverse edge with weight 1 / v.
  • Variables in separate groups: both are known, but no path joins them, so the DFS returns -1.
  • Reusing the visited set across queries: start a fresh one for every query.

Summary

Each equation a / b = v is an edge a → b with weight v and b → a with weight 1 / v. A query x / y is the product of the weights on any path from x to y, found by DFS, or -1 when there is none. O(q · (V + E)) time, O(V + E) space.

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Build the graph

    For each a / b = v, add an edge a → b with weight v and b → a with weight 1 / v.

  2. Check the variables

    If x or y appears in no equation, the answer is -1.

  3. DFS with a product

    From x, carry the product of the weights; return it on reaching y, or -1 if y cannot be reached.

Frequently asked questions

Why is Evaluate Division a graph problem?

a / b = 2 and b / c = 3 chain together: a / c = (a / b) × (b / c) = 6. Make each variable a node and each equation a pair of edges, a → b with weight 2 and b → a with weight 1/2. Then any path from x to y multiplies out to x / y.


Why does any path give the same answer?

LeetCode guarantees the equations do not contradict each other. Along any path the intermediate variables cancel, (x / p) × (p / q) × (q / y) = x / y, so two different paths between the same pair must give the same product.


When is the answer -1?

When x or y never appears in any equation, including x / x for an unknown x, or when y is not reachable from x, which means the equations never relate the two. A known variable divided by itself is 1, even though there is no edge from it to itself.


Is there a faster approach for many queries?

Weighted union-find stores each variable’s ratio to its group’s root, so a query is two finds and a division, nearly O(1). Floyd–Warshall precomputes every ratio in O(V³). With at most 20 equations and 20 queries, a DFS per query is simplest.

New to the technique behind this problem? Watch it run step by step:

Topological Sort Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description