Skip to content

Commit 4d3589b

Browse files
author
Tushar Roy
committed
Evaluate division
1 parent 7bd7992 commit 4d3589b

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package com.interview.graph;
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
6+
/**
7+
* Date 10/31/2016
8+
* @author Tushar Roy
9+
*
10+
* Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number).
11+
* Given some queries, return the answers. If the answer does not exist, return -1.0.
12+
*
13+
* Solution
14+
* Do Flyod warshall algorithm initialized as values between equations. Do Flyod Warshall to create
15+
* all possible paths b/w two strings.
16+
*
17+
* Time complexity O(n * n * n) + O(m)
18+
* where n is total number of strings in equations and m is total number of queries
19+
*
20+
* Reference
21+
* https://leetcode.com/problems/evaluate-division/
22+
*/
23+
public class EvaluateDivison {
24+
public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
25+
if (equations.length == 0) {
26+
return new double[0];
27+
}
28+
Map<String, Integer> index = new HashMap<>();
29+
int count = 0;
30+
for (int i = 0; i < equations.length; i++) {
31+
String first = equations[i][0];
32+
String second = equations[i][1];
33+
if (!index.containsKey(first)) {
34+
index.put(first, count++);
35+
}
36+
if (!index.containsKey(second)) {
37+
index.put(second, count++);
38+
}
39+
}
40+
41+
double graph[][] = new double[count][count];
42+
for (int i = 0; i < graph.length; i++) {
43+
for (int j = 0; j < graph[i].length; j++) {
44+
graph[i][j] = -1;
45+
}
46+
}
47+
48+
for (int i = 0; i < equations.length; i++) {
49+
String first = equations[i][0];
50+
String second = equations[i][1];
51+
int i1 = index.get(first);
52+
int i2 = index.get(second);
53+
graph[i1][i1] = graph[i2][i2] = 1.0;
54+
graph[i1][i2] = values[i];
55+
graph[i2][i1] = 1/values[i];
56+
}
57+
58+
for (int i = 0 ; i < graph.length; i++) {
59+
for (int j = 0; j < graph.length; j++) {
60+
if (graph[i][j] != -1) {
61+
continue;
62+
}
63+
for (int k = 0; k < graph.length; k++) {
64+
if (graph[i][k] == -1 || graph[k][j] == -1) {
65+
continue;
66+
}
67+
graph[i][j] = graph[i][k] * graph[k][j];
68+
}
69+
}
70+
}
71+
72+
double[] result = new double[queries.length];
73+
for (int i = 0; i < queries.length; i++) {
74+
String first = queries[i][0];
75+
String second = queries[i][1];
76+
if (!index.containsKey(first) || !index.containsKey(second)) {
77+
result[i] = -1;
78+
} else {
79+
int i1 = index.get(first);
80+
int i2 = index.get(second);
81+
result[i] = graph[i1][i2];
82+
}
83+
}
84+
85+
return result;
86+
}
87+
}

0 commit comments

Comments
 (0)