737. Sentence Similarity II
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to determine if two sentences are similar, given a set of similar word pairs. The core conditions are that the sentences must have the same number of words, and each pair of corresponding words must be similar. The crucial part of the definition of similarity is that it is transitive: if word a is similar to b, and b is similar to c, then a is also similar to c. This property, along with the implied reflexivity (a word is similar to itself) and symmetry (if a is similar to b, b is similar to a), defines an equivalence relation. This relation partitions all related words into disjoint sets (or groups). Two words are considered similar if and only if they belong to the same group.
Solution
Sentence Similarity II in Python
class Solution:
def areSentencesSimilarTwo(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
if len(sentence1) != len(sentence2):
return False
# DSU data structure using a dictionary for parent pointers.
# This allows handling strings directly without mapping to integers.
parent = {}
# find function with path compression
def find(word):
if word not in parent:
parent[word] = word
if parent[word] == word:
return word
parent[word] = find(parent[word])
return parent[word]
# union function to merge two sets
def union(w1, w2):
root1 = find(w1)
root2 = find(w2)
if root1 != root2:
parent[root1] = root2
# Build the disjoint sets from the similar pairs
for w1, w2 in similarPairs:
union(w1, w2)
# Check if corresponding words in sentences are similar
for i in range(len(sentence1)):
w1 = sentence1[i]
w2 = sentence2[i]
# Words are similar if they are in the same set (have the same root).
# The find function will create entries for words not in similarPairs,
# treating them as their own separate components.
if find(w1) != find(w2):
return False
return True
Sentence Similarity II in Java
class Solution {
public boolean areSentencesSimilarTwo(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
if (sentence1.length != sentence2.length) {
return false;
}
// Using an integer-based DSU is more idiomatic and performant in Java.
// First, map all unique words to integer IDs.
Map<String, Integer> wordToId = new HashMap<>();
int idCounter = 0;
for (List<String> pair : similarPairs) {
for (String word : pair) {
if (!wordToId.containsKey(word)) {
wordToId.put(word, idCounter++);
}
}
}
DSU dsu = new DSU(idCounter);
// Perform union operations on the IDs of similar words.
for (List<String> pair : similarPairs) {
int id1 = wordToId.get(pair.get(0));
int id2 = wordToId.get(pair.get(1));
dsu.union(id1, id2);
}
// Compare words in the sentences.
for (int i = 0; i < sentence1.length; i++) {
String w1 = sentence1[i];
String w2 = sentence2[i];
if (w1.equals(w2)) {
continue;
}
Integer id1 = wordToId.get(w1);
Integer id2 = wordToId.get(w2);
// If a word is not in any similar pair, it cannot be similar to any other word.
if (id1 == null || id2 == null) {
return false;
}
// Check if they belong to the same component.
if (dsu.find(id1) != dsu.find(id2)) {
return false;
}
}
return true;
}
// Disjoint Set Union (DSU) helper class
private class DSU {
private int[] parent;
public DSU(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
// find with path compression
public int find(int i) {
if (parent[i] == i) {
return i;
}
parent[i] = find(parent[i]);
return parent[i];
}
// union of two sets
public void union(int i, int j) {
int rootI = find(i);
int rootJ = find(j);
if (rootI != rootJ) {
parent[rootI] = rootJ;
}
}
}
}
Sentence Similarity II in C++
class Solution {
public:
bool areSentencesSimilarTwo(vector<string>& sentence1, vector<string>& sentence2, vector<vector<string>>& similarPairs) {
if (sentence1.size() != sentence2.size()) {
return false;
}
unordered_map<string, string> parent;
// Find function with path compression
function<string(const string&)> find =
[&](const string& s) -> string {
if (parent.find(s) == parent.end()) {
parent[s] = s;
return s;
}
if (parent[s] == s) {
return s;
}
return parent[s] = find(parent[s]);
};
// Union function to merge two sets
auto unite = [&](const string& s1, const string& s2) {
string root1 = find(s1);
string root2 = find(s2);
if (root1 != root2) {
parent[root1] = root2;
}
};
// Build the disjoint sets from similar pairs
for (const auto& pair : similarPairs) {
unite(pair[0], pair[1]);
}
// Check if corresponding words in sentences are similar
for (int i = 0; i < sentence1.size(); ++i) {
// Words are similar if they are in the same set (have the same root)
if (find(sentence1[i]) != find(sentence2[i])) {
return false;
}
}
return true;
}
};
Sentence Similarity II in TypeScript
function areSentencesSimilarTwo(sentence1: string[], sentence2: string[], similarPairs: string[][]): boolean {
if (sentence1.length !== sentence2.length) {
return false;
}
// DSU data structure using a Map for parent pointers.
// This allows handling strings directly without mapping to integers.
const parent = new Map<string, string>();
// find function with path compression
const find = (word: string): string => {
if (!parent.has(word)) {
parent.set(word, word);
}
if (parent.get(word) === word) {
return word;
}
const root = find(parent.get(word)!);
parent.set(word, root);
return root;
};
// union function to merge two sets
const union = (w1: string, w2: string): void => {
const root1 = find(w1);
const root2 = find(w2);
if (root1 !== root2) {
parent.set(root1, root2);
}
};
// Build the disjoint sets from the similar pairs
for (const [w1, w2] of similarPairs) {
union(w1, w2);
}
// Check if corresponding words in sentences are similar
for (let i = 0; i < sentence1.length; i++) {
const w1 = sentence1[i];
const w2 = sentence2[i];
// Words are similar if they are in the same set (have the same root).
// The find function will create entries for words not in similarPairs,
// treating them as their own separate components.
if (find(w1) !== find(w2)) {
return false;
}
}
return true;
}
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.