Last active
March 5, 2026 20:53
-
-
Save tatsuyax25/d594c1cf52d3bf8a250ba3748eb90b88 to your computer and use it in GitHub Desktop.
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 alterna
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {string} s | |
| * @return {number} | |
| */ | |
| var minOperations = function(s) { | |
| // cost0 = number of flips needed if we force pattern "010101..." | |
| // cost1 = number of flips needed if we force pattern "101010..." | |
| let cost0 = 0; | |
| let cost1 = 0; | |
| for (let i = 0; i < s.length; i++) { | |
| // For pattern starting with '0': | |
| // even index → '0', odd index → '1' | |
| const expected0 = (i % 2 === 0) ? '0' : '1'; | |
| // For pattern starting with '1': | |
| // even index → '1', odd index → '0' | |
| const expected1 = (i % 2 === 0) ? '1' : '0'; | |
| // Count mismatches for each pattern | |
| if (s[i] !== expected0) cost0++; | |
| if (s[i] !== expected1) cost1++; | |
| } | |
| // The minimum flips needed to match either valid alternating pattern | |
| return Math.min(cost0, cost1); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment