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

 

Example

Given:

a / b = 2

b / c = 3

 

We can calculate:

a / c = 2 × 3 = 6

 

and:

c / a = 1 / 6

 

Main Idea

Represent the equations as a weighted graph.

For:

a / b = 2

 

create:

a → b : 2

b → a : 0.5

 

For:

b / c = 3

 

create:

b → c : 3

c → b : 1/3

 

Then use DFS/BFS to find a path between the variables.

For:

a / c

 

the path is:

a → b → c

 

so:

2 × 3 = 6

Example 1

Input

2
a b 2
b c 3
4
a c
b a
a e
a a

Output

6 0.5 -1 1

Explanation

Given:

a / b = 2

b / c = 3

 

Therefore:

a / c = 2 × 3 = 6

 

For:

b / a

 

we reverse:

b / a = 1 / 2 = 0.5

 

There is no connection between a and e, so:

a / e = -1

 

And:

a / a = 1

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.5 0.666667 -1 2.5 0.4

Explanation

From:

a / b = 1.5

 

we get:

b / a = 1 / 1.5

      ≈ 0.666667

 

There is no path from a to c, so:

a / c = -1

 

Similarly:

c / d = 2.5

d / c = 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.

Hints:

Hint 1

Think of every variable as a graph node.

Hint 2

For:

a / b = 2

 

create:

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 17, 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