Skip to content

Commit 3c3ed98

Browse files
committed
Add solution #1257
1 parent 60f1489 commit 3c3ed98

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1166,6 +1166,7 @@
11661166
1254|[Number of Closed Islands](./solutions/1254-number-of-closed-islands.js)|Medium|
11671167
1255|[Maximum Score Words Formed by Letters](./solutions/1255-maximum-score-words-formed-by-letters.js)|Hard|
11681168
1256|[Encode Number](./solutions/1256-encode-number.js)|Medium|
1169+
1257|[Smallest Common Region](./solutions/1257-smallest-common-region.js)|Medium|
11691170
1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy|
11701171
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
11711172
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* 1257. Smallest Common Region
3+
* https://leetcode.com/problems/smallest-common-region/
4+
* Difficulty: Medium
5+
*
6+
* You are given some lists of regions where the first region of each list directly contains
7+
* all other regions in that list.
8+
*
9+
* If a region x contains a region y directly, and region y contains region z directly, then
10+
* region x is said to contain region z indirectly. Note that region x also indirectly contains
11+
* all regions indirectly containd in y.
12+
*
13+
* Naturally, if a region x contains (either directly or indirectly) another region y, then x
14+
* is bigger than or equal to y in size. Also, by definition, a region x contains itself.
15+
*
16+
* Given two regions: region1 and region2, return the smallest region that contains both of them.
17+
*
18+
* It is guaranteed the smallest region exists.
19+
*/
20+
21+
/**
22+
* @param {string[][]} regions
23+
* @param {string} region1
24+
* @param {string} region2
25+
* @return {string}
26+
*/
27+
var findSmallestRegion = function(regions, region1, region2) {
28+
const map = new Map();
29+
30+
for (const region of regions) {
31+
const parent = region[0];
32+
for (let i = 1; i < region.length; i++) {
33+
map.set(region[i], parent);
34+
}
35+
}
36+
37+
const path1 = getPath(region1);
38+
const path2 = getPath(region2);
39+
const set = new Set(path1);
40+
41+
for (const ancestor of path2) {
42+
if (set.has(ancestor)) {
43+
return ancestor;
44+
}
45+
}
46+
47+
function getPath(region) {
48+
const path = [];
49+
let current = region;
50+
while (current) {
51+
path.push(current);
52+
current = map.get(current);
53+
}
54+
return path;
55+
}
56+
};

0 commit comments

Comments
 (0)