Algo-Sim › Advanced Graphs

Evaluate Division

Medium · Advanced Graphs · step through it in Java, Python and C++ on your own input

Each equation a / b = v is a weighted edge both ways; a query x / y is the product of the weights along any path from x to y.

Problem

You are given equations a / b = v between variables, and queries x / y. Answer each query from the equations, or with -1.0 when it cannot be determined (a variable never appears, or nothing links the two). The equations never contradict each other and no value is 0.

Constraints

Edge cases to test

Follow-up questions

How does weighted union-find help?
Each node stores its ratio to its root, so a query is two finds and one division: near O(1) per query after unions.
What if there are many queries?
Precompute all pairs with Floyd–Warshall over ratios (O(V³)) or answer each with union-find.

Solution

Java

public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
    Map<String, Map<String, Double>> graph = new HashMap<>();
    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(graph, x, y, new HashSet<>());
    }
    return answers;
}

// The product of the weights along a path from x to target, or -1 if there is none.
private double dfs(Map<String, Map<String, Double>> graph, String x, String target, Set<String> seen) {
    if (x.equals(target)) return 1.0;
    seen.add(x);
    for (Map.Entry<String, Double> e : graph.get(x).entrySet()) {
        if (seen.contains(e.getKey())) continue;
        double rest = dfs(graph, e.getKey(), target, seen);
        if (rest != -1.0) return e.getValue() * rest;
    }
    return -1.0;
}

Python

from collections import defaultdict


def calc_equation(equations, values, queries):
    graph = defaultdict(dict)
    for (a, b), v in zip(equations, values):
        graph[a][b] = v
        graph[b][a] = 1 / v
    answers = []
    for x, y in queries:
        if x not in graph or y not in graph:
            answers.append(-1.0)
        else:
            answers.append(dfs(graph, x, y, set()))
    return answers


# The product of the weights along a path from x to target, or -1 if there is none.
def dfs(graph, x, target, seen):
    if x == target:
        return 1.0
    seen.add(x)
    for nxt, w in graph[x].items():
        if nxt in seen:
            continue
        rest = dfs(graph, nxt, target, seen)
        if rest != -1.0:
            return w * rest
    return -1.0

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values, vector<vector<string>> &queries) {
        // Neighbours in insertion order, like Java's LinkedHashMap.
        unordered_map<string, vector<pair<string, double>>> graph;
        for (int i = 0; i < int(values.size()); i++) {
            const string &a = equations[i][0], &b = equations[i][1];
            graph[a].push_back({b, values[i]});
            graph[b].push_back({a, 1 / values[i]});
        }
        vector<double> answers;
        for (vector<string> &q : queries) {
            const string &x = q[0], &y = q[1];
            if (!graph.count(x) || !graph.count(y))
                answers.push_back(-1.0);
            else {
                unordered_set<string> seen;
                answers.push_back(dfs(graph, x, y, seen));
            }
        }
        return answers;
    }

  private:
    // The product of the weights along a path from x to target, or -1 if there is none.
    double dfs(unordered_map<string, vector<pair<string, double>>> &graph, const string &x, const string &target, unordered_set<string> &seen) {
        if (x == target)
            return 1.0;
        seen.insert(x);
        for (auto &[next, w] : graph[x]) {
            if (seen.count(next))
                continue;
            double rest = dfs(graph, next, target, seen);
            if (rest != -1.0)
                return w * rest;
        }
        return -1.0;
    }
};

More Advanced Graphs problems