Evaluate Division Coding Problem Solution
Source: Dev.to
Evaluate Division Overview
Evaluate Division is a graph problem disguised as algebra. You are given a list of equations such as:
a / b = 2.0
b / c = 3.0
and queries like:
a / c = ?
c / a = ?
x / x = ?
Your task is to compute each query’s result using the relationships implied by the equations. If a query cannot be answered with the given information, return -1.0.
The key insight is to treat variables as nodes in a weighted graph. Each equation provides a direct conversion rate between two variables, turning the problem into finding a path between nodes and multiplying the edge weights along that path.
What Makes It Tricky
- Unordered equations – The equations may appear in any order, requiring multiple hops to answer a query.
- Disconnected components – Some variables may never be connected to others.
- Missing variables – Queries can involve variables that never appear in any equation; these must immediately return
-1.0.
Solution Idea Expected by Interviewers
Model the Equations as a Weighted Graph
- Treat each variable as a node.
- For an equation
u / v = k, add two directed edges:u → vwith weightkv → uwith weight1 / k
The reciprocal edge is essential because division relationships are reversible.
Answer Queries Using Graph Traversal
For each query x / y:
- Check existence – If either
xoryis absent from the graph, return-1.0. - Search for a path – Perform a depth‑first search (DFS) or breadth‑first search (BFS) from
xtoy.- Carry a running product initialized to
1.0. - Multiply the product by the edge weight each time you traverse an edge.
- When
yis reached, the running product is the answer.
- Carry a running product initialized to
- Avoid cycles – Maintain a
visitedset for the current search to prevent infinite loops.
Special Cases
- Self‑division (
x / x)- If
xexists in the graph, the result is1.0. - If
xdoes not exist, return-1.0.
- If
Why This Approach Is Efficient in Interviews
- Graph construction – Linear time
O(E)whereEis the number of equations. - Query processing – Each query costs
O(V + E)in the worst case for the connected component explored, which is acceptable for typical interview constraints. - Scalability – For many queries, you can cache results or use a weighted union‑find (disjoint set) structure to reduce repeated searches, though most interviewers are satisfied with the straightforward traversal solution.
Common Mistakes to Avoid
- Omitting the reciprocal edge – This breaks reverse‑direction queries.
- Not using a per‑query visited set – Can cause infinite recursion or redundant work on cyclic graphs.
- Returning
1.0forx / xwhenxis unknown – The correct response is-1.0in that case.