#1864
Minimum Number of Swaps to Make the Binary String Alternating
specialist · 960 · lc medium +32 · verified · 43.9% accepted · 624 likes · top 26%
Description
Given a binary string s, find the minimum number of character swaps (any two positions, not just adjacent) required to make s alternating (no two adjacent characters equal), or return -1 if impossible.
Example 1:
Input: s = "111000"
Output: 1
Explanation: Swap positions 1 and 4: "111000" -> "101010"
The string is now alternating.
Example 2:
Input: s = "010"
Output: 0
Explanation: The string is already alternating, no swaps are needed.
Example 3:
Input: s = "1110"
Output: -1
Code
1
2
3