Problem · Union Find

Sentence Equivalence with Synonyms

Learn this problem
MediumRead AI logoRead AIFULLTIMEPHONE SCREEN

Problem statement

You are given two sentences, firstSentence and secondSentence, represented as ordered arrays of words, together with an array of synonym pairs.

Each synonym pair is undirected, and synonym relationships are transitive. For example, if rapid is a synonym of fast and fast is a synonym of quick, then rapid and quick are also equivalent.

Return true exactly when the sentences have equal length and every pair of words at the same position is either identical or belongs to the same synonym component. A word absent from the synonym graph matches only itself.

Function

areSentencesEquivalent(firstSentence: String[], secondSentence: String[], synonymPairs: String[][]) → boolean

Examples

Example 1

firstSentence = ["flat","is","useful"]secondSentence = ["flatting","is","useful"]synonymPairs = [["flat","flatting"]]return = true

The first aligned words are directly connected by a synonym pair, and the remaining aligned words are identical.

Example 2

firstSentence = ["hit","the","ball"]secondSentence = ["hits","a","ball"]synonymPairs = [["hit","hits"]]return = false

Although hit and hits are connected, the and a are neither identical nor synonyms.

Example 3

firstSentence = ["rapid","meeting"]secondSentence = ["quick","session"]synonymPairs = [["rapid","fast"],["fast","quick"],["meeting","session"]]return = true

rapid reaches quick transitively through fast, while meeting and session are directly connected.

Constraints

  • 0 <= firstSentence.length, secondSentence.length <= 100000.
  • 0 <= synonymPairs.length <= 100000.
  • Every synonym pair contains exactly two words.
  • Every word is a nonempty lowercase English token.
  • The total number of sentence words plus synonym-pair endpoints is at most 200000.
drafts saved locally
public boolean areSentencesEquivalent(String[] firstSentence, String[] secondSentence, String[][] synonymPairs) {
  // write your code here
}
firstSentence["flat","is","useful"]
secondSentence["flatting","is","useful"]
synonymPairs[["flat","flatting"]]
expectedtrue
checking account