File: buddy-strings/solution.py

Date: 2026-06-06

Time: 15:27

buddy-strings/solution.py

Purpose

This file solves LeetCode 859 — Buddy Strings. It determines whether you can swap exactly two characters in string s to produce string goal. It's a standalone solution module following the repo's convention of one problem per directory with a Solution class.

Key Components

Solution.buddyStrings(self, s, goal) -> bool — The only method. Takes two strings and returns whether a single swap in s can yield goal.

The method handles two fundamentally different cases:

1. s == goal (lines 14-15): If the strings are already equal, a swap can only produce the same string if there's a duplicate character. len(s) != len(set(s)) checks this — if the set is smaller than the string, some character repeats, so swapping two copies of that character is a valid no-op swap.

2. s != goal (lines 17-23): Collect indices where the strings differ. If there are exactly 2 differing positions, check that swapping those two characters in s produces goal — i.e., the characters cross-match.

Patterns

Dependencies

Imports: None — pure Python, no standard library needed.

Imported by: buddy-strings/test_solution.py directly. The "Imported By" list in the prompt is misleading — those are test files for *other* problems that happen to share a test harness pattern, not actual importers of this module.

Flow

1. Reject if lengths differ → False

2. If strings are identical, return whether any character is duplicated

3. Walk both strings in lockstep, recording indices where they differ

4. Short-circuit to False as soon as a 3rd diff is found (avoids scanning the rest)

5. After the loop, require exactly 2 diffs with a cross-match: s[i] == goal[j] and s[j] == goal[i]

Invariants

Error Handling

None. The method is a pure predicate with no exceptions, no edge-case sentinels. Invalid input (non-string, None) would raise a standard Python TypeError/AttributeError — no defensive handling is added, which is typical for LeetCode solutions where input constraints are guaranteed.

Topics to Explore

Beliefs