Problem Description
Given two strings s and goal, determine if you can swap exactly two letters in s so that the resulting string is equal to goal.
Key Insights
- The strings must be of the same length; otherwise, the swap can never form goal.
- If s is identical to goal, a valid swap is possible only if there is a duplicate character (allowing a swap that doesn't change the string).
- When s and goal are different, there must be exactly two indices i and j such that s[i] != goal[i] and s[j] != goal[j]. Additionally, swapping these two characters must produce goal.
- Early termination is possible if more than two mismatches are found.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string, since we iterate through the strings once. Space Complexity: O(n) in the worst case for storing mismatches (or O(1) if the number of differences is bounded by 2).
Solution
We check the length of s and goal. If they differ, return false. If s equals goal, we need to verify that s contains at least one duplicate character which can be swapped without affecting the string. Otherwise, we collect all indices where s and goal differ. If there are exactly two differences, we then check if swapping these characters in s gives goal. This approach uses simple iteration and, optionally, a set to check for duplicates.