Skip to content

Commit 2b0fd3a

Browse files
committed
Add solution #1258
1 parent 0f23fd6 commit 2b0fd3a

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1167,6 +1167,7 @@
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|
11691169
1257|[Smallest Common Region](./solutions/1257-smallest-common-region.js)|Medium|
1170+
1258|[Synonymous Sentences](./solutions/1258-synonymous-sentences.js)|Medium|
11701171
1260|[Shift 2D Grid](./solutions/1260-shift-2d-grid.js)|Easy|
11711172
1261|[Find Elements in a Contaminated Binary Tree](./solutions/1261-find-elements-in-a-contaminated-binary-tree.js)|Medium|
11721173
1262|[Greatest Sum Divisible by Three](./solutions/1262-greatest-sum-divisible-by-three.js)|Medium|
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/**
2+
* 1258. Synonymous Sentences
3+
* https://leetcode.com/problems/synonymous-sentences/
4+
* Difficulty: Medium
5+
*
6+
* You are given a list of equivalent string pairs synonyms where synonyms[i] = [si, ti]
7+
* indicates that si and ti are equivalent strings. You are also given a sentence text.
8+
*
9+
* Return all possible synonymous sentences sorted lexicographically.
10+
*/
11+
12+
/**
13+
* @param {string[][]} synonyms
14+
* @param {string} text
15+
* @return {string[]}
16+
*/
17+
var generateSentences = function(synonyms, text) {
18+
const graph = new Map();
19+
20+
for (const [word1, word2] of synonyms) {
21+
if (!graph.has(word1)) graph.set(word1, []);
22+
if (!graph.has(word2)) graph.set(word2, []);
23+
graph.get(word1).push(word2);
24+
graph.get(word2).push(word1);
25+
}
26+
27+
const words = text.split(' ');
28+
const allCombinations = [];
29+
backtrack(0, []);
30+
return allCombinations.sort();
31+
32+
function findSynonyms(word) {
33+
if (!graph.has(word)) return [word];
34+
35+
const visited = new Set();
36+
const queue = [word];
37+
const synonymGroup = [];
38+
39+
while (queue.length > 0) {
40+
const current = queue.shift();
41+
if (visited.has(current)) continue;
42+
43+
visited.add(current);
44+
synonymGroup.push(current);
45+
46+
for (const neighbor of graph.get(current)) {
47+
if (!visited.has(neighbor)) {
48+
queue.push(neighbor);
49+
}
50+
}
51+
}
52+
53+
return synonymGroup.sort();
54+
}
55+
56+
function backtrack(index, currentSentence) {
57+
if (index === words.length) {
58+
allCombinations.push(currentSentence.join(' '));
59+
return;
60+
}
61+
62+
const synonyms = findSynonyms(words[index]);
63+
for (const synonym of synonyms) {
64+
currentSentence.push(synonym);
65+
backtrack(index + 1, currentSentence);
66+
currentSentence.pop();
67+
}
68+
}
69+
};

0 commit comments

Comments
 (0)