Sentence Similarity - 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.

Return true if sentence1 and sentence2 are similar, or false if they are not similar.

Two sentences are similar if:

  • They have the same length (i.e., the same number of words)
  • sentence1[i] and sentence2[i] are similar for all i

Note: A word is always similar to itself. The similarity relation is not transitive. For example, if words a and b are similar, and words b and c are similar, a and c are not necessarily similar.

Input & Output

Example 1 — Basic Similarity
$ Input: sentence1 = ["great","acting"], sentence2 = ["fine","drama"], similarPairs = [["great","good"],["fine","good"],["acting","drama"]]
Output: true
💡 Note: Both sentences have length 2. Position 0: "great" and "fine" are both similar to "good" but not directly similar. Position 1: "acting" and "drama" are directly similar via the pair ["acting","drama"].
Example 2 — Direct Similarity
$ Input: sentence1 = ["great"], sentence2 = ["great"], similarPairs = []
Output: true
💡 Note: Single word sentences. "great" is identical to "great", so they are similar even with no similarity pairs.
Example 3 — No Similarity
$ Input: sentence1 = ["great"], sentence2 = ["doubleplus"], similarPairs = [["great","good"]]
Output: false
💡 Note: "great" and "doubleplus" are not identical and there's no similarity pair connecting them directly.

Constraints

  • 1 ≤ sentence1.length, sentence2.length ≤ 1000
  • 1 ≤ sentence1[i].length, sentence2[i].length ≤ 20
  • 0 ≤ similarPairs.length ≤ 1000
  • similarPairs[i].length == 2

Visualization

Tap to expand
Sentence Similarity: Compare Word by WordSentence 1:greatactingSentence 2:finedramasimilar?similar?Similarity Rules✓ [great, good]✓ [fine, good]✓ [acting, drama]great ↔ fine via goodacting ↔ drama directlyResult: TRUEBoth positions are similar🎯 Key: Check each word pair for direct similarity or identical match
Understanding the Visualization
1
Input
Two sentences and similarity pairs
2
Process
Check length equality and word-by-word similarity
3
Output
Boolean result indicating similarity
Key Takeaway
🎯 Key Insight: Use hash set to store all similarity pairs (bidirectional) for O(1) lookup when checking word similarity
Asked in
Google 15 Facebook 12 Amazon 8
28.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen