Python 0399.py
class Solution:
def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
all = defaultdict(dict)
for i in range(len(equations)):
a, b = equations[i]
c = values[i]
all[a][b] = c
all[b][a] = 1 / c
again = True
while again:
again = False
derived = defaultdict(dict)
for one in all:
for two in sorted(all[one]):
for three in sorted(all[one]):
if two < three and three not in all[two]:
x = all[one][two]
y = all[one][three]
derived[two][three] = y / x
derived[three][two] = x / y
again = True
for x in derived:
for y in derived[x]:
all[x][y] = derived[x][y]
result = []
for a, b in queries:
if a in all and b in all[a]:
result.append(all[a][b])
elif a == b and a in all:
result.append(1)
else:
result.append(-1)
return result
Difficulty
and has an acceptance rate of about 64% (1+ million submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Depth First Search
- Graph Theory
- Shortest Path
- String
- Union Find
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves a system of division equations by building a graph that captures direct and indirect relationships between variables. It first records each given equation as a bidirectional edge with a weight equal to the division factor. Then it repeatedly derives new edges by composing existing ones until no further relationships can be discovered. Finally, it answers each query by looking up the computed weight or returning a sentinel value when the relationship is undefined.
Data Structure Construction
The algorithm uses a nested dictionary (defaultdict(dict)) named all to represent the graph. Each outer key corresponds to a variable, and the inner dictionary maps neighboring variables to the known division result.
all = defaultdict(dict)
for i in range(len(equations)):
a, b = equations[i]
c = values[i]
all[a][b] = c
all[b][a] = 1 / c
In this block the code iterates over the input equations, extracts the two variables and the associated numeric value, and stores both the forward and reverse relationships. The reverse edge is computed as the reciprocal, guaranteeing that the graph is symmetric with respect to division.
Transitive Closure Loop
After the direct edges are recorded, the algorithm enters a loop that repeatedly discovers indirect relationships. The loop continues as long as new edges are added (again flag).
again = True
while again:
again = False
derived = defaultdict(dict)
for one in all:
for two in sorted(all[one]):
for three in sorted(all[one]):
if two < three and three not in all[two]:
x = all[one][two]
y = all[one][three]
derived[two][three] = y / x
derived[three][two] = x / y
again = True
Inside the nested loops the code selects a pivot variable one and examines every pair of its neighbors (two and three). When a pair satisfies the ordering condition (two < three) and the relationship between them is not already known, the algorithm computes the new division factor by dividing the two known weights (y / x). It stores both directions of the derived edge in a temporary dictionary derived. The again flag is set to True to indicate that the outer loop must iterate again because new information is now available.
After the inner loops finish, the newly derived edges are merged back into the main graph:
for x in derived:
for y in derived[x]:
all[x][y] = derived[x][y]
This step expands the graph with the freshly discovered connections, enabling further composition in subsequent iterations.
Query Evaluation
Once the graph is fully populated, the algorithm processes each query by checking the presence of the requested variables and their relationship in the graph.
result = []
for a, b in queries:
if a in all and b in all[a]:
result.append(all[a][b])
elif a == b and a in all:
result.append(1)
else:
result.append(-1)
return result
If a direct edge from a to b exists, the stored weight is appended to the result list. When the query asks for the division of a variable by itself and the variable appears anywhere in the graph, the answer is 1. For any other case-missing variables or unreachable pairs-the algorithm returns -1 to indicate an undefined result.
Edge Cases Handled
The code explicitly addresses three important edge conditions.
When a query involves two identical variables, the algorithm returns 1 provided the variable participates in at least one equation, ensuring that self-division is correctly interpreted even if no explicit self-edge exists.
If either variable in a query never appears in any equation, the condition a in all or b in all[a] fails, leading to the -1 sentinel, which correctly signals that the relationship cannot be derived.
When a direct relationship is already present in the graph, the lookup path all[a][b] yields the exact value without needing further computation, guaranteeing accurate answers for queries that match the original input.
Performance Optimizations
The implementation leverages several techniques that reduce redundant work.
Using defaultdict(dict) eliminates the need for explicit existence checks before inserting new edges, streamlining the graph construction and update phases.
The inner loops iterate over sorted neighbor lists and enforce the ordering condition two < three. This prevents the same pair of variables from being processed twice in opposite order, halving the number of candidate compositions per pivot.
Derived edges are accumulated in a separate dictionary derived before being merged back into all. This batch update avoids mutating the graph while it is being iterated, which could otherwise cause inconsistent state or repeated processing of newly added edges within the same iteration.
The again flag provides an early exit from the outer while loop as soon as an iteration produces no new edges, preventing unnecessary passes once the transitive closure is complete.
Collecting query results in a pre-allocated list (result = []) and appending values directly avoids repeated list creation, contributing to a smoother runtime for large query sets.
ELI5 - Simplified Explanation
Imagine you have a big box of special blocks. Each block has a letter on it, and you have little signs that tell you how many of one block fit into another. For example, if you know that one apple block is worth two orange blocks, you can write that down in a notebook.
The first part of the code goes through all those signs and draws lines in the notebook connecting the blocks. If one apple is two oranges, the code makes sure the notebook says how many oranges fit into one apple too.
After that, the code goes on a treasure hunt through the notebook. It looks for secrets. If it knows that an apple is worth two oranges and an apple is also worth three bananas, it can figure out exactly how many bananas are in an orange without being told directly. It keeps doing this over and over again, adding all these new secrets to the notebook until there are no new secrets left to find.
Once the notebook is full of every possible connection, the code is ready to answer questions. Someone might ask how many grapes are in a strawberry. The code looks in the finished notebook. If it finds a note about those two fruits, it gives the answer. If the fruits are the exact same thing, it knows it takes one to make one. If the notebook doesn't have any notes about those two things, it says it is impossible to know and gives a special sign for not knowing.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Rust | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | TS | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | Python | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | Python | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 1258: Synonymous Sentences
- problem 2307: Check for Contradictions in Equations
Solved On The Same Day
- problem 521: Longest Uncommon Subsequence I
- problem 557: Reverse Words in a String III
- problem 697: Degree of an Array
- problem 771: Jewels and Stones
- problem 819: Most Common Word
- problem 1700: Number of Students Unable to Eat Lunch
- problem 2073: Time Needed to Buy Tickets
- problem 435: Non-overlapping Intervals
- problem 547: Number of Provinces
- problem 841: Keys and Rooms
- problem 1466: Reorder Routes to Make All Paths Lead to the City Zero
- problem 2462: Total Cost to Hire K Workers
- problem 2542: Maximum Subsequence Score
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality