Sentence Similarity — LeetCode 734 Python Solution

EasyLeetCode PremiumArrayHash TableString
Problem
#734
Pattern
Hash Map
Reading time
2 min

The problem

We can represent a sentence as an array of words, for example, the sentence "I am happy with leetcode" can be represented as arr = ["I","am",happy","with","leetcode"]. Given two sentences sentence1 and sentence2 each represented as a string array and given an array of string pairs similarPairs where similarPairs[i] = [xi, yi] indicates that the two words xi and yi are similar.

Example

Input
sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]
Output
true
Explanation
The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.

Python solution

Python
class Solution:
    def areSentencesSimilar(
        self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]
    ) -> bool:
        if len(sentence1) != len(sentence2):
            return False
        s = {(x, y) for x, y in similarPairs}
        for x, y in zip(sentence1, sentence2):
            if x != y and (x, y) not in s and (y, x) not in s:
                return False
        return True

Complexity

MeasureComplexity
TimeO(L)
SpaceO(L), where L is the sum of the lengths of all strings in the problem auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 734. Sentence Similarity is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 734. Sentence Similarity?
LeetCode 734. Sentence Similarity is rated Easy on LeetCode.
What is the time complexity of LeetCode 734. Sentence Similarity?
The Python solution on this page runs in O(L).
What is the space complexity of LeetCode 734. Sentence Similarity?
The Python solution on this page uses O(L), where L is the sum of the lengths of all strings in the problem auxiliary space.
What topics does LeetCode 734. Sentence Similarity cover?
LeetCode 734. Sentence Similarity is tagged Array, Hash Table and String on LeetCode.
Is LeetCode 734. Sentence Similarity a premium problem?
Yes. LeetCode 734. Sentence Similarity is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview