Skip to content

Commit 5f45465

Browse files
authored
Create minimum-number-of-swaps-to-make-the-binary-string-alternating.py
1 parent e0da1f4 commit 5f45465

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
class Solution(object):
5+
def minSwaps(self, s):
6+
"""
7+
:type s: str
8+
:rtype: int
9+
"""
10+
def cost(s, x):
11+
diff = 0
12+
for c in s:
13+
diff += int(c) != x
14+
x ^= 1
15+
return diff//2
16+
17+
ones = s.count('1')
18+
zeros = len(s)-ones
19+
if abs(ones-zeros) > 1:
20+
return -1
21+
if ones > zeros:
22+
return cost(s, 1)
23+
if ones < zeros:
24+
return cost(s, 0)
25+
return min(cost(s, 1), cost(s, 0))

0 commit comments

Comments
 (0)