Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.
Move from brute-force thinking to an efficient approach using greedy strategy.
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. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
Any two characters may be swapped, even if they are not adjacent.
Example 1:
Input: s = "111000" Output: 1 Explanation: Swap positions 1 and 4: "111000" -> "101010" The string is now alternating.
Example 2:
Input: s = "010" Output: 0 Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110" Output: -1
Constraints:
1 <= s.length <= 1000s[i] is either '0' or '1'.Problem summary: 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. For example, the strings "010" and "1010" are alternating, while the string "0100" is not. Any two characters may be swapped, even if they are not adjacent.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Greedy
"111000"
"010"
"1110"
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1864: Minimum Number of Swaps to Make the Binary String Alternating
class Solution {
private char[] s;
public int minSwaps(String s) {
this.s = s.toCharArray();
int n1 = 0;
for (char c : this.s) {
n1 += (c - '0');
}
int n0 = this.s.length - n1;
if (Math.abs(n0 - n1) > 1) {
return -1;
}
if (n0 == n1) {
return Math.min(calc(0), calc(1));
}
return calc(n0 > n1 ? 0 : 1);
}
private int calc(int c) {
int cnt = 0;
for (int i = 0; i < s.length; ++i) {
int x = s[i] - '0';
if ((i & 1 ^ c) != x) {
++cnt;
}
}
return cnt / 2;
}
}
// Accepted solution for LeetCode #1864: Minimum Number of Swaps to Make the Binary String Alternating
func minSwaps(s string) int {
n0 := strings.Count(s, "0")
n1 := len(s) - n0
if abs(n0-n1) > 1 {
return -1
}
calc := func(c int) int {
cnt := 0
for i, ch := range s {
x := int(ch - '0')
if i&1^c != x {
cnt++
}
}
return cnt / 2
}
if n0 == n1 {
return min(calc(0), calc(1))
}
if n0 > n1 {
return calc(0)
}
return calc(1)
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
# Accepted solution for LeetCode #1864: Minimum Number of Swaps to Make the Binary String Alternating
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)
// Accepted solution for LeetCode #1864: Minimum Number of Swaps to Make the Binary String Alternating
/**
* [1864] Minimum Number of Swaps to Make the Binary String Alternating
*
* 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. For example, the strings "010" and "1010" are alternating, while the string "0100" is not.
* Any two characters may be swapped, even if they are not adjacent.
*
* Example 1:
*
* Input: s = "111000"
* Output: 1
* Explanation: Swap positions 1 and 4: "1<u>1</u>10<u>0</u>0" -> "1<u>0</u>10<u>1</u>0"
* The string is now alternating.
*
* Example 2:
*
* Input: s = "010"
* Output: 0
* Explanation: The string is already alternating, no swaps are needed.
*
* Example 3:
*
* Input: s = "1110"
* Output: -1
*
*
* Constraints:
*
* 1 <= s.length <= 1000
* s[i] is either '0' or '1'.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/
// discuss: https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-binary-string-alternating/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn min_swaps(s: String) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1864_example_1() {
let s = "111000".to_string();
let result = 1;
assert_eq!(Solution::min_swaps(s), result);
}
#[test]
#[ignore]
fn test_1864_example_2() {
let s = "010".to_string();
let result = 0;
assert_eq!(Solution::min_swaps(s), result);
}
#[test]
#[ignore]
fn test_1864_example_3() {
let s = "1110".to_string();
let result = -1;
assert_eq!(Solution::min_swaps(s), result);
}
}
// Accepted solution for LeetCode #1864: Minimum Number of Swaps to Make the Binary String Alternating
function minSwaps(s: string): number {
const n0 = (s.match(/0/g) || []).length;
const n1 = s.length - n0;
if (Math.abs(n0 - n1) > 1) {
return -1;
}
const calc = (c: number): number => {
let cnt = 0;
for (let i = 0; i < s.length; i++) {
const x = +s[i];
if (((i & 1) ^ c) !== x) {
cnt++;
}
}
return Math.floor(cnt / 2);
};
if (n0 === n1) {
return Math.min(calc(0), calc(1));
}
return calc(n0 > n1 ? 0 : 1);
}
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.