# LeetCode: Minimum Number Of Swaps To Make The Binary String Alternating Solution

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {string} s3 * @return {number}4 */5var minSwaps = function (s) {6  const N = s.length7  const count = (s, c) => s.split("").filter(_c => _c === c).length8  const [count1, count0] = [count(s, "1"), count(s, "0")]9  const valid = Math.abs(count1 - count0) <= 110
11  if (!valid) {12    return -113  }14
15  const calculateSwaps = (s, nextMatch) => {16    let swaps = 017    for (const c of s) {18      if (c !== nextMatch) {19        swaps++20      }21      nextMatch = nextMatch === "1" ? "0" : "1"22    }23    return swaps >> 124  }25
26  if (count1 > count0) {27    return calculateSwaps(s, "1")28  } else if (count0 > count1) {29    return calculateSwaps(s, "0")30  } else {31    return Math.min(calculateSwaps(s, "1"), calculateSwaps(s, "0"))32  }33}```

leetcode

greedy

## Next Post

LeetCode: Binary Tree Cameras

May 18, 2021

Search Posts