File: check-if-one-string-swap-can-make-strings-equal/solution.py

Date: 2026-06-06

Time: 15:42

Purpose

This file implements LeetCode 1790: Check if One String Swap Can Make Strings Equal. It owns the complete solution and its test suite in a single module — the standard structure across this repository where each problem directory contains solution.py with both implementation and unit tests.

Key Components

arealmostequal(s1: str, s2: str) -> bool

The sole public function. Returns True if s1 can be made equal to s2 by performing at most one swap of two characters within one of the strings.

Contract:

TestAreAlmostEqual

Nine test cases covering:

Flow

1. Scan for mismatches: Iterate through both strings index-by-index, collecting indices where s1[i] != s2[i] into diffs.

2. Early exit: If len(diffs) > 2, return False immediately — more than two mismatches means no single swap can fix it. This is an O(n) worst-case optimization that avoids scanning the rest of the string.

3. Decision by mismatch count:

Patterns

Dependencies

Imports: only unittest from the standard library — no external dependencies.

Imported by: the testsolution.py in this same directory, plus the massive list of testsolution.py files across 400+ other problem directories. That "imported by" list is likely an artifact of the test harness or code-expert tooling rather than actual import relationships — those other test files wouldn't import this problem's solution.

Invariants

Error Handling

None — the function trusts its inputs per LeetCode conventions. No length validation, no type checking. An IndexError would surface naturally if s2 were shorter than s1.

Topics to Explore

Beliefs