Leetcode Problem 1864. Minimum Number of Swaps to Make the Binary String Alternating

1864. Minimum Number of Swaps to Make the Binary String Alternating

Leetcode Solutions

Counting Swaps for Alternating Binary String

  1. Count the number of '0's and '1's in the string.
  2. If the absolute difference between the counts is greater than 1, return -1.
  3. If the counts are equal, calculate the number of swaps needed to alternate starting with '0' and starting with '1', and return the minimum of the two.
  4. If the counts are not equal, calculate the number of swaps needed based on which character is in excess.
  5. To calculate the number of swaps, iterate through the string and count the number of characters that are out of place for the expected alternating pattern.
  6. The number of swaps is half the number of characters out of place since each swap corrects two positions.
UML Thumbnail

Brute Force Swap Simulation

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...