528. Buddy Strings
You are given two lowercase strings s and goal. Decide whether you can turn s into goal with exactly one swap: choose two different positions i and j in s and exchange the characters s[i] and s[j].
The swap is mandatory — even if s already equals goal, you must still swap some pair of positions (swapping two copies of the same letter is allowed and leaves the string unchanged).
Return true if a single swap can make the strings equal, and false otherwise.
Example 1:
Input: s = "ab", goal = "ba"
Output: true
Explanation: Swapping positions 0 and 1 turns "ab" into "ba".
Example 2:
Input: s = "ab", goal = "ab"
Output: false
Explanation: The strings already match, but the swap is forced — and swapping the two distinct letters breaks the match.
Example 3:
Input: s = "aa", goal = "aa"
Output: true
Explanation: Swap the two a's: the string does not change, so it still equals goal.
Constraints:
- 1 ≤ s.length, goal.length ≤ 2 * 10⁴
- s and goal consist of lowercase English letters only.
Hints:
A swap changes at most two positions of s. So compare the strings position by position and collect the indices where they disagree — how many mismatches can one swap possibly repair?
Exactly two mismatches i and j work only when they mirror each other: s[i] == goal[j] and s[j] == goal[i]. Zero mismatches need some letter to appear twice (swap the copies). Any other mismatch count — or different lengths — is impossible.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: s = "ab", goal = "ba"
Expected output: true