Skip to main content
Back to problems
#734
Easy Algorithms

Sentence similarity

Array Hash Table String
44.8% acceptance
Mar 31, 2026
68
72
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. Notice that a word is always similar to itself, also notice that the similarity relation is not transitive. For example, if the words a and b are similar, and the words b and c are similar, a and c are not necessarily similar.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn are_sentences_similar(sentence1: Vec<String>, sentence2: Vec<String>, similar_pairs: Vec<Vec<String>>) -> bool {
    if sentence1.len() != sentence2.len() { return false; }
    use std::collections::HashSet;
    let pairs: HashSet<(&str, &str)> = similar_pairs.iter()
      .flat_map(|p| vec![(&p[0] as &str, &p[1] as &str), (&p[1] as &str, &p[0] as &str)])
      .collect();
    sentence1.iter().zip(sentence2.iter()).all(|(a, b)| {
      a == b || pairs.contains(&(a.as_str(), b.as_str()))
    })
  }
}