← Back to challenges

Minimum Swaps to Alternate a Binary String

JavaScriptHardstringsloops

Instructions

Create a function that returns the minimum number of swaps it takes to transform a binary string into a string of alternating 0s and 1s. A swap is switching from a 0 to a 1 or vice versa.

Examples

minSwaps("010010111") ➞ 4

// Two possible conversions:
//   1. "101010101" (4 swaps)
//   2. "010101010" (5 swaps)

minSwaps("10101010") ➞ 0

minSwaps("10010") ➞ 2

Notes

N/A

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.