Magicsheet logo

Minimum Number of Swaps to Make the Binary String Alternating

Medium
100%
Updated 6/1/2025

Asked by 2 Companies

Minimum Number of Swaps to Make the Binary String Alternating

1. What is this problem about?

You are given a binary string consisting of '0's and '1's. You want to transform it into an "alternating" string (like "0101..." or "1010...") using the minimum number of swaps. A swap involves picking any two indices and exchanging their characters. Note that swaps are only possible if the number of '0's and '1's in the original string matches the requirements of an alternating string.

2. Why is this asked in interviews?

Amazon and Societe Generale use this "Minimum Number of Swaps to Make the Binary String Alternating coding problem" to test a candidate's ability to evaluate multiple targets. Since there are only two possible alternating patterns, the problem requires checking both and determining which one is achievable and cheaper. It also tests the understanding of parity and character counts.

3. Algorithmic pattern used

The pattern is Greedy and Parity Checking.

  1. Count the number of '0's and '1's. If the difference is greater than 1, it's impossible (return -1).
  2. Calculate the number of "misplaced" characters for the "0101..." pattern.
  3. Calculate the number of "misplaced" characters for the "1010..." pattern.
  4. Each swap fixes two misplaced characters, so the answer is misplaced / 2.

4. Example explanation

String: "111000"

  • Count 1s: 3, Count 0s: 3. (Possible)
  • Pattern A: "010101" -> Misplaced at index 0, 1, 2, 3, 4, 5. Total 6. Swaps = 3.
  • Pattern B: "101010" -> Misplaced at index 0, 1, 2, 3, 4, 5. Total 6. Swaps = 3. Minimum swaps = 3. If the string was "11100", only "10101" is possible. You must check character counts before calculating swaps for a pattern.

5. Common mistakes candidates make

Failing to check the "impossible" condition is a major error. If you have three '1's and one '0', you can never form an alternating string. Another mistake is forgetting that a single swap fixes two positions. If you find 4 characters are in the wrong place, you only need 2 swaps to fix them.

6. Interview preparation tip

When a problem has a very limited number of "target" states (like two alternating patterns), don't try to find a complex path to the best one. Simply calculate the cost for all possible targets and pick the minimum. This is a common strategy in string and array modification problems.

Similar Questions