File: sentence-similarity/solution.py

Date: 2026-06-06

Time: 19:02

sentence-similarity/solution.py

Purpose

This file implements LeetCode problem 734 - Sentence Similarity. It determines whether two sentences (represented as word lists) are "similar" given a set of explicitly defined word pairs. Similarity is checked word-by-word at matching positions — it is not transitive (if A~B and B~C, that does not imply A~C).

Key Components

areSentencesSimilar(sentence1, sentence2, similarPairs) -> bool — The sole public function. Contract:

Patterns

Set-of-tuples for O(1) lookup — The similarity pairs are pre-processed into a set of 2-tuples rather than left as a list of lists. This converts each pair-check from O(P) to O(1), making the overall algorithm O(N + P) where N is sentence length and P is the number of pairs.

Early exit on length mismatch — The length check at the top short-circuits before doing any pair processing.

Generator expression with all() — The final check uses all() with a generator, which short-circuits on the first mismatch rather than evaluating every position.

Self-contained test file — Tests are co-located via unittest in the same module, runnable with python -m unittest or if _name == "main_".

Dependencies

Imports: Only unittest (stdlib). No external dependencies.

Imported by: The testsolution.py files listed in the "Imported By" section are an artifact of the repo's shared test infrastructure — they likely import a common test runner or share a pattern, not this specific solution. The direct consumer is sentence-similarity/testsolution.py.

Flow

1. Length guard — If len(sentence1) != len(sentence2), return False immediately.

2. Build lookup set — Iterate similarPairs, inserting both (x, y) and (y, x) into similar_set. This ensures symmetric lookup without needing to check both orderings later.

3. Pairwise comparisonzip the two sentences and for each (w1, w2) pair, accept if w1 == w2 (identity) or (w1, w2) in similar_set (explicit similarity).

Invariants

Error Handling

None. The function assumes valid inputs per the LeetCode contract — no None checks, no type validation. Empty sentences and empty pair lists are handled naturally by the iteration (both produce True via vacuous truth from all() over an empty zip).

Topics to Explore

Beliefs