• Time:O(n)
• Space:O(1)

C++

``````class Solution {
public:
int minSwaps(string s) {
const int ones = count(begin(s), end(s), '1');
const int zeros = s.length() - ones;
if (abs(ones - zeros) > 1)
return -1;
if (ones > zeros)
return countSwaps(s, '1');
if (zeros > ones)
return countSwaps(s, '0');
return min(countSwaps(s, '1'), countSwaps(s, '0'));
}

private:
int countSwaps(const string& s, char curr) {
int swaps = 0;
for (const char c : s) {
if (c != curr)
++swaps;
curr ^= 1;
}
return swaps / 2;
}
};
``````

JAVA

``````class Solution {
public int minSwaps(String s) {
final int ones = (int) s.chars().filter(c -> c == '1').count();
final int zeros = s.length() - ones;
if (Math.abs(ones - zeros) > 1)
return -1;
if (ones > zeros)
return countSwaps(s, '1');
if (zeros > ones)
return countSwaps(s, '0');
return Math.min(countSwaps(s, '1'), countSwaps(s, '0'));
}

private int countSwaps(final String s, char curr) {
int swaps = 0;
for (final char c : s.toCharArray()) {
if (c != curr)
++swaps;
curr ^= 1;
}
return swaps / 2;
}
}
``````

Python

``````class Solution:
def minSwaps(self, s: str) -> int:
ones = s.count('1')
zeros = len(s) - ones
if abs(ones - zeros) > 1:
return -1

def countSwaps(curr: chr) -> int:
swaps = 0
for c in s:
if c != curr:
swaps += 1
curr = chr(ord(curr) ^ 1)
return swaps // 2

if ones > zeros:
return countSwaps('1')
if zeros > ones:
return countSwaps('0')
return min(countSwaps('1'), countSwaps('0'))
``````