Let's make this one less mysterious. For 859. Buddy Strings, the solution in this repository is mainly a straightforward implementation solution.
Guide
What?
Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: straightforward implementation.
Guide
When?
Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are buddyStrings.
Guide
Why?
The solution works because it narrows the problem until every update has a clear reason to exist.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 8 ms, faster than 79.84% of C++ online submissions for Buddy Strings.
02//Memory Usage: 7.3 MB, less than 6.68% of C++ online submissions for Buddy Strings.
03class Solution {
04public:
05 bool buddyStrings(string A, string B) {
06 if(A.size() != B.size()) return false;
07
08 int n = A.size();
09
10 int diff_count = 0;
11 unordered_map<int, int> counter;
12 vector<int> diffs;
13 bool dup = false;
14
15 for(int i = 0; i < n; ++i){
16 if(A[i] != B[i]) diffs.push_back(i);
17 ++counter[A[i]];
18 if(counter[A[i]] >= 2) dup = true;
19 }
20
21 if(diffs.empty() && dup) return true;
22
23 if(diffs.size() != 2) return false;
24
25 /*
26 for diffs.size() == 2,
27 still need to check if swap works:
28 e.g. swap not works for the case:
29 "abcaa"
30 "abcbb"
31 */
32 swap(A[diffs[0]], A[diffs[1]]);
33
34 return A == B;
35 }
36};
Cost