ExamAdda Logo

Evaluate Division

Easy

You are given a list of equations where:

a / b = value

 

You are also given queries asking for the value of:

c / d

 

Return the answer for every query.

If the answer cannot be determined, return:

-1.0

 

Important Idea

Treat the equations as a weighted graph.

For:

a / b = 2

 

create:

a → b = 2

b → a = 1/2

 

Then a query can be solved by finding a path between the two variables.

Example Graph

Given:

a / b = 2

b / c = 3

 

The graph becomes:

a --2--> b --3--> c

a <--1/2-- b <--1/3-- c

 

Therefore:

a / c = 2 × 3 = 6

 

and:

c / a = 1/3 × 1/2 = 1/6

 

Main Logic

Use:

HashMap + DFS

 

For each equation:

a / b = k

 

store:

a → b : k

b → a : 1/k

 

For a query:

a / c

 

perform DFS from a to c.

Multiply the edge weights along the path.

If no path exists:

return -1.0

 

If:

a == c

 

and a exists, the answer is:

1.0

Example 1

Input

2
a b 2.0
b c 3.0
4
a c
b a
a e
a a

Output

6.000000 0.500000 -1.000000 1.000000

Explanation

Given:

a / b = 2

b / c = 3

 

For:

a / c

 

we have:

a / c = (a / b) × (b / c)

      = 2 × 3

      = 6

 

For:

b / a

 

we reverse the first equation:

b / a = 1 / 2

      = 0.5

 

For:

a / e

 

there is no connection between a and e.

Therefore:

-1.0

 

For:

a / a

 

the answer is:

1.0

 

Example 2

Input

2
a b 1.5
c d 2.5
5
a b
b a
a c
c d
d c

Output

1.500000 0.666667 -1.000000 2.500000 0.400000

Explanation

From:

a / b = 1.5

 

we get:

b / a = 1 / 1.5

      ≈ 0.666667

 

There is no connection between a and c, so:

a / c = -1

 

From:

c / d = 2.5

 

we get:

d / c = 1 / 2.5

      = 0.4

Constraints

1 <= equations.length <= 20
equations[i].length == 2
1 <= queries.length <= 20
1.0 <= values[i] <= 20.0
Variables consist of lowercase English letters.
All variables appearing in queries are either present in the equations or unknown.

Hints:

Hint 1

Think of every variable as a graph node.

Hint 2

For:

a / b = 2

 

create two directed edges:

a → b : 2

b → a : 0.5

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 16, 2026

Last updated

Aug 16, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output