Minimum Number of Swaps to Make the Binary String Alternating — LeetCode 1864 Python Solution
- Problem
- #1864
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a binary string s, return the minimum number of character swaps to make it alternating, or -1 if it is impossible. The string is called alternating if no two adjacent characters are equal.
Example
- Input
- s = "111000"
- Output
- 1
- Explanation
- Swap positions 1 and 4: "111000" -> "101010"
Python solution
class Solution:
def minSwaps(self, s: str) -> int:
def calc(c: int) -> int:
return sum((c ^ i & 1) != x for i, x in enumerate(map(int, s))) // 2
n0 = s.count("0")
n1 = len(s) - n0
if abs(n0 - n1) > 1:
return -1
if n0 == n1:
return min(calc(0), calc(1))
return calc(0 if n0 > n1 else 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string \textit{s} |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating?
- LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating?
- The Python solution on this page runs in O(n), where n is the length of the string \textit{s}.
- What is the space complexity of LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating cover?
- LeetCode 1864. Minimum Number of Swaps to Make the Binary String Alternating is tagged Greedy and String on LeetCode.