KatInterview

399. Evaluate Division

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Graph Traversal (BFS)

This problem can be elegantly solved by modeling it as a graph problem. The variables are nodes in the graph, and the division equations represent weighted, directed edges between them.

Solution

Evaluate Division in Python

from collections import defaultdict, deque

class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        # Step 1: Build the graph using a defaultdict for convenience
        graph = defaultdict(dict)
        for (u, v), val in zip(equations, values):
            graph[u][v] = val
            graph[v][u] = 1.0 / val

        # Function to handle a single query using BFS
        def bfs(start_node, end_node):
            # Case 1: A node is not in the graph
            if start_node not in graph or end_node not in graph:
                return -1.0
            
            # Case 2: Start and end are the same
            if start_node == end_node:
                return 1.0
            
            # BFS setup
            queue = deque([(start_node, 1.0)])  # (node, current_product)
            visited = {start_node}

            while queue:
                node, product = queue.popleft()
                
                for neighbor, value in graph[node].items():
                    if neighbor == end_node:
                        return product * value
                    
                    if neighbor not in visited:
                        visited.add(neighbor)
                        queue.append((neighbor, product * value))
            
            # If end_node is not reached
            return -1.0

        # Step 2: Process each query
        return [bfs(c, d) for c, d in queries]

Evaluate Division in Java

class Solution {
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        // Step 1: Build the graph
        Map<String, Map<String, Double>> graph = new HashMap<>();
        for (int i = 0; i < equations.size(); i++) {
            String u = equations.get(i).get(0);
            String v = equations.get(i).get(1);
            double val = values[i];
            graph.computeIfAbsent(u, k -> new HashMap<>()).put(v, val);
            graph.computeIfAbsent(v, k -> new HashMap<>()).put(u, 1.0 / val);
        }

        double[] results = new double[queries.size()];
        // Step 2: Process each query
        for (int i = 0; i < queries.size(); i++) {
            String startNode = queries.get(i).get(0);
            String endNode = queries.get(i).get(1);

            // Case 1: Either node does not exist in the graph
            if (!graph.containsKey(startNode) || !graph.containsKey(endNode)) {
                results[i] = -1.0;
                continue;
            }

            // Case 2: startNode and endNode are the same
            if (startNode.equals(endNode)) {
                results[i] = 1.0;
                continue;
            }

            // Step 3: Find path using BFS
            Queue<Pair<String, Double>> queue = new LinkedList<>();
            queue.offer(new Pair<>(startNode, 1.0)); // Pair(node, current product)

            Set<String> visited = new HashSet<>();
            visited.add(startNode);

            boolean found = false;
            while (!queue.isEmpty()) {
                Pair<String, Double> current = queue.poll();
                String node = current.getKey();
                double product = current.getValue();

                if (node.equals(endNode)) {
                    results[i] = product;
                    found = true;
                    break;
                }

                for (Map.Entry<String, Double> entry : graph.get(node).entrySet()) {
                    String neighbor = entry.getKey();
                    if (!visited.contains(neighbor)) {
                        visited.add(neighbor);
                        queue.offer(new Pair<>(neighbor, product * entry.getValue()));
                    }
                }
            }

            if (!found) {
                results[i] = -1.0;
            }
        }

        return results;
    }

    // LeetCode's Java environment does not have javafx.util.Pair by default, 
    // so we can use a simple custom Pair class or another structure. 
    // Here, for completeness, let's assume a Pair class is available or defined. 
    // For a self-contained solution without defining a class, one could use two parallel queues.
    private static class Pair<K, V> {
        private final K key;
        private final V value;

        public Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }
    }
}

Evaluate Division in C++

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

        vector<double> results;
        // Step 2: Process each query
        for (const auto& query : queries) {
            const string& start_node = query[0];
            const string& end_node = query[1];

            // Case 1: Either node is not in the graph
            if (graph.find(start_node) == graph.end() || graph.find(end_node) == graph.end()) {
                results.push_back(-1.0);
                continue;
            }
            
            // Case 2: Start and end nodes are the same
            if (start_node == end_node) {
                results.push_back(1.0);
                continue;
            }
            
            // Step 3: Find path using BFS for each query
            queue<pair<string, double>> q;
            q.push({start_node, 1.0}); // {node, current_product}
            
            unordered_set<string> visited;
            visited.insert(start_node);
            
            bool found = false;
            while (!q.empty()) {
                auto current = q.front();
                q.pop();
                string node = current.first;
                double product = current.second;
                
                if (node == end_node) {
                    results.push_back(product);
                    found = true;
                    break;
                }
                
                for (const auto& edge : graph[node]) {
                    const string& neighbor = edge.first;
                    if (visited.find(neighbor) == visited.end()) {
                        visited.insert(neighbor);
                        q.push({neighbor, product * edge.second});
                    }
                }
            }
            
            if (!found) {
                results.push_back(-1.0);
            }
        }
        return results;
    }
};

Evaluate Division in TypeScript

function calcEquation(equations: string[][], values: number[], queries: string[][]): number[] {
    // Step 1: Build the graph using a Map
    const graph = new Map<string, Map<string, number>>();
    for (let i = 0; i < equations.length; i++) {
        const [u, v] = equations[i];
        const val = values[i];
        
        if (!graph.has(u)) {
            graph.set(u, new Map<string, number>());
        }
        if (!graph.has(v)) {
            graph.set(v, new Map<string, number>());
        }
        
        graph.get(u)!.set(v, val);
        graph.get(v)!.set(u, 1.0 / val);
    }

    const results: number[] = [];
    // Step 2: Process each query
    for (const [startNode, endNode] of queries) {
        // Case 1: Either node does not exist in the graph
        if (!graph.has(startNode) || !graph.has(endNode)) {
            results.push(-1.0);
            continue;
        }
        
        // Case 2: Start and end nodes are the same
        if (startNode === endNode) {
            results.push(1.0);
            continue;
        }

        // Step 3: Find path using BFS
        // The queue will store tuples of [node, current_product]
        const queue: [string, number][] = [[startNode, 1.0]];
        const visited = new Set<string>([startNode]);
        
        let found = false;
        while (queue.length > 0) {
            // Using shift() for a queue-like behavior.
            // For very large inputs, a more efficient queue might be needed.
            const [node, product] = queue.shift()!;
            
            if (node === endNode) {
                results.push(product);
                found = true;
                break;
            }
            
            const neighbors = graph.get(node);
            if (neighbors) {
                for (const [neighbor, val] of neighbors.entries()) {
                    if (!visited.has(neighbor)) {
                        visited.add(neighbor);
                        queue.push([neighbor, product * val]);
                    }
                }
            }
        }
        
        if (!found) {
            results.push(-1.0);
        }
    }
    return results;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.