Description
You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.
The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.
Return the minimum number of operations needed to make s alternating.
Example 1:
Input: s = "0100" Output: 1 Explanation: If you change the last character to '1', s will be "0101", which is alternating.
Example 2:
Input: s = "10" Output: 0 Explanation: s is already alternating.
Example 3:
Input: s = "1111" Output: 2 Explanation: You need two operations to reach "0101" or "1010".
Constraints:
1 <= s.length <= 104s[i]is either'0'or'1'.
Solutions
This function finds the minimum number of changes needed to make a binary string alternate between 0 and 1. It works by checking how many positions violate the alternating pattern "010101..." (where even indices should be 0 and odd indices should be 1): for each character, it counts a mismatch when the character is '1' at an even index OR '0' at an odd index, using XOR (^) to detect these violations. Then it compares this count with the opposite pattern "101010..." (where even indices should be 1 and odd indices should be 0), and returns Math.min(count, s.length - count) — whichever pattern requires fewer changes to achieve. For example, "001" needs 1 change to become "010" (or 2 changes to become "101"), so it returns 1.
/**
* @param {string} s
* @return {number}
*/
var minOperations = function(s) {
let count = 0;
for (let i = 0; i < s.length; i++) {
const isEven = i % 2 === 0;
const isOne = s[i] === '1';
if (isEven ^ isOne) {
count++;
}
}
return Math.min(count, s.length - count);
};