← Home

1247. Minimum Swaps to Make Strings Equal

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
124

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 1247. Minimum Swaps to Make Strings Equal, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. 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 minimumSwap.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • 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:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

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

solution.cpp
01//Runtime: 4 ms, faster than 53.72% of C++ online submissions for Minimum Swaps to Make Strings Equal.
02//Memory Usage: 6.5 MB, less than 100.00% of C++ online submissions for Minimum Swaps to Make Strings Equal.
03
04class Solution {
05public:
06    int minimumSwap(string s1, string s2) {
07        int N = s1.size();
08        int i = N-1;
09        while(i >= 0){
10            if(s1[i] == s2[i]){
11                s1.erase(i,1);
12                s2.erase(i,1);
13            }
14            i--;
15        }
16        
17        int xcount = count(s1.begin(), s1.end(), 'x');
18        int ycount = count(s1.begin(), s1.end(), 'y');
19        int ans = 0;
20        
21        //("xx", "yy") => 1 swap
22        ans += xcount/2 + ycount/2;
23        xcount %= 2; ycount %= 2;
24        
25        //("xy", "yx") => 2 swaps
26        if(xcount == 1 && ycount == 1){
27            ans += 2;
28            xcount--; ycount--;
29        }
30        
31        return (xcount == 0 && ycount == 0) ? ans : -1;
32    }
33};
34
35//optimized
36//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Minimum Swaps to Make Strings Equal.
37//Memory Usage: 6.5 MB, less than 100.00% of C++ online submissions for Minimum Swaps to Make Strings Equal.
38class Solution {
39public:
40    int minimumSwap(string s1, string s2) {
41        int N = s1.size();
42        int xcount = 0, ycount = 0;
43        int ans = 0;
44        
45        for(int i = 0; i < N; i++){
46            if(s1[i] == s2[i]) continue;
47            
48            if(s1[i] == 'x'){
49                xcount++;
50            }else{
51                ycount++;
52            }
53        }
54        
55        //("xx", "yy") => 1 swap
56        ans += xcount/2 + ycount/2;
57        xcount %= 2; ycount %= 2;
58        
59        //("xy", "yx") => 2 swaps
60        if(xcount == 1 && ycount == 1){
61            ans += 2;
62            xcount--; ycount--;
63        }
64        
65        return (xcount == 0 && ycount == 0) ? ans : -1;
66    }
67};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.