Skip to content

Commit bf2d661

Browse files
committed
Add solution #399
1 parent 626b019 commit bf2d661

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,7 @@
244244
392|[Is Subsequence](./0392-is-subsequence.js)|Easy|
245245
394|[Decode String](./0394-decode-string.js)|Medium|
246246
395|[Longest Substring with At Least K Repeating Characters](./0395-longest-substring-with-at-least-k-repeating-characters.js)|Medium|
247+
399|[Evaluate Division](./0399-evaluate-division.js)|Medium|
247248
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|
248249
407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard|
249250
412|[Fizz Buzz](./0412-fizz-buzz.js)|Easy|

solutions/0399-evaluate-division.js

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
* 399. Evaluate Division
3+
* https://leetcode.com/problems/evaluate-division/
4+
* Difficulty: Medium
5+
*
6+
* You are given an array of variable pairs equations and an array of real numbers values,
7+
* where equations[i] = [Ai, Bi] and values[i] represent the equation Ai / Bi = values[i].
8+
* Each Ai or Bi is a string that represents a single variable.
9+
*
10+
* You are also given some queries, where queries[j] = [Cj, Dj] represents the jth query
11+
* where you must find the answer for Cj / Dj = ?.
12+
*
13+
* Return the answers to all queries. If a single answer cannot be determined, return -1.0.
14+
*
15+
* Note: The input is always valid. You may assume that evaluating the queries will not
16+
* result in division by zero and that there is no contradiction.
17+
*
18+
* Note: The variables that do not occur in the list of equations are undefined, so the
19+
* answer cannot be determined for them.
20+
*/
21+
22+
/**
23+
* @param {string[][]} equations
24+
* @param {number[]} values
25+
* @param {string[][]} queries
26+
* @return {number[]}
27+
*/
28+
var calcEquation = function(equations, values, queries) {
29+
const map = equations.reduce((result, [a, b], index) => {
30+
result.set(a, [...(result.get(a) ?? []), [b, values[index]]]);
31+
result.set(b, [...(result.get(b) ?? []), [a, 1 / values[index]]]);
32+
return result;
33+
}, new Map());
34+
35+
function traverse([a, b], seen = new Set(), current = 1) {
36+
if (!map.has(a) || !map.has(b)) return -1;
37+
if (a === b) return current;
38+
seen.add(a);
39+
40+
for (const [key, value] of map.get(a)) {
41+
if (seen.has(key)) continue;
42+
const result = traverse([key, b], seen, current * value);
43+
if (result) return result;
44+
}
45+
return null;
46+
}
47+
48+
return queries.map(item => traverse(item) ?? -1);
49+
};

0 commit comments

Comments
 (0)