LeetCode: Minimum Number Of Swaps To Make The Binary String Alternating Solution
1/**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) <= 11011 if (!valid) {12 return -113 }1415 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 }2526 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}
Comments
Loading comments...
Tags
leetcode
greedy
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.