KatInterview

734. Sentence Similarity

EasySolutions in Python, Java, C++, TypeScript

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, represented as arrays of strings, are "similar". The criteria for similarity are straightforward:

Solution

Sentence Similarity in Python

class Solution:
    def areSentencesSimilar(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
        # Condition 1: Sentences must have the same length.
        if len(sentence1) != len(sentence2):
            return False

        # Build a map for efficient lookup of similar words.
        # The key is a word, and the value is a set of similar words.
        similar_words_map = {}
        for w1, w2 in similarPairs:
            # setdefault is a convenient way to initialize a set for a new key.
            similar_words_map.setdefault(w1, set()).add(w2)
            similar_words_map.setdefault(w2, set()).add(w1)

        # Condition 2: Each pair of corresponding words must be similar.
        for i in range(len(sentence1)):
            word1 = sentence1[i]
            word2 = sentence2[i]

            # A word is always similar to itself.
            if word1 == word2:
                continue
            
            # Check if word2 is in the set of words similar to word1.
            # We use .get() to safely handle cases where word1 has no similar pairs,
            # returning an empty set in that case.
            if word2 not in similar_words_map.get(word1, set()):
                return False

        # If all checks pass, the sentences are similar.
        return True

Sentence Similarity in Java

class Solution {
    public boolean areSentencesSimilar(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
        // Condition 1: Sentences must have the same length.
        if (sentence1.length != sentence2.length) {
            return false;
        }

        // Build a map for efficient lookup of similar words.
        // Key: a word, Value: a set of words similar to the key.
        Map<String, Set<String>> similarMap = new HashMap<>();
        for (List<String> pair : similarPairs) {
            String word1 = pair.get(0);
            String word2 = pair.get(1);
            // The similarity is symmetric, so add both ways.
            similarMap.computeIfAbsent(word1, k -> new HashSet<>()).add(word2);
            similarMap.computeIfAbsent(word2, k -> new HashSet<>()).add(word1);
        }

        // Condition 2: Each pair of corresponding words must be similar.
        for (int i = 0; i < sentence1.length; i++) {
            String word1 = sentence1[i];
            String word2 = sentence2[i];

            // A word is always similar to itself.
            if (word1.equals(word2)) {
                continue;
            }

            // Check if the pair is in our similarity map.
            // Due to symmetric build, we only need to check one direction.
            if (!similarMap.containsKey(word1) || !similarMap.get(word1).contains(word2)) {
                return false;
            }
        }

        // If all checks pass, the sentences are similar.
        return true;
    }
}

Sentence Similarity in C++

class Solution {
public:
    bool areSentencesSimilar(vector<string>& sentence1, vector<string>& sentence2, vector<vector<string>>& similarPairs) {
        // Condition 1: Sentences must have the same length.
        if (sentence1.size() != sentence2.size()) {
            return false;
        }

        // Build a map for efficient lookup of similar words.
        // Key: a word, Value: a set of words similar to the key.
        unordered_map<string, unordered_set<string>> similarMap;
        for (const auto& pair : similarPairs) {
            // The similarity is symmetric.
            similarMap[pair[0]].insert(pair[1]);
            similarMap[pair[1]].insert(pair[0]);
        }

        // Condition 2: Each pair of corresponding words must be similar.
        for (int i = 0; i < sentence1.size(); ++i) {
            const string& word1 = sentence1[i];
            const string& word2 = sentence2[i];

            // A word is always similar to itself.
            if (word1 == word2) {
                continue;
            }

            // Check if word1 and word2 are in the similar pairs list.
            // Since the map is built symmetrically, we only need to check one way.
            // e.g., if (a,b) is a pair, we check if b is in a's similar set.
            auto it = similarMap.find(word1);
            if (it == similarMap.end() || it->second.find(word2) == it->second.end()) {
                // If word1 is not in the map, or word2 is not in word1's similar set,
                // the words are not similar.
                return false;
            }
        }

        // If all corresponding words are similar, the sentences are similar.
        return true;
    }
};

Sentence Similarity in TypeScript

function areSentencesSimilar(sentence1: string[], sentence2: string[], similarPairs: string[][]): boolean {
    // Condition 1: Sentences must have the same length.
    if (sentence1.length !== sentence2.length) {
        return false;
    }

    // Build a map for efficient lookup of similar words.
    // Key: a word, Value: a set of words similar to the key.
    const similarMap = new Map<string, Set<string>>();
    for (const [w1, w2] of similarPairs) {
        // Ensure keys exist before getting their sets.
        if (!similarMap.has(w1)) {
            similarMap.set(w1, new Set<string>());
        }
        if (!similarMap.has(w2)) {
            similarMap.set(w2, new Set<string>());
        }
        // The similarity is symmetric, so add both ways.
        similarMap.get(w1)!.add(w2);
        similarMap.get(w2)!.add(w1);
    }
    
    // Condition 2: Each pair of corresponding words must be similar.
    for (let i = 0; i < sentence1.length; i++) {
        const word1 = sentence1[i];
        const word2 = sentence2[i];

        // A word is always similar to itself.
        if (word1 === word2) {
            continue;
        }
        
        // Check if the pair is in our similarity map.
        // Due to symmetric build, we only need to check one direction.
        const similarSet = similarMap.get(word1);
        if (!similarSet || !similarSet.has(word2)) {
            return false;
        }
    }

    // If all checks pass, the sentences are similar.
    return true;
}

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.