Created
March 7, 2026 16:14
-
-
Save tatsuyax25/b2d690c40ffc7d7ed40662fe580567f5 to your computer and use it in GitHub Desktop.
You are given a binary string s. You are allowed to perform two types of operations on the string in any sequence: Type-1: Remove the character at the start of the string s and append it to the end of the string.
Type-2: Pick any character in s and
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 minFlips = function(s) { | |
| const n = s.length; | |
| const s2 = s + s; | |
| // Build alternating patterns of length 2n | |
| let alt0 = "", alt1 = ""; | |
| for (let i = 0; i < 2 * n; i++) { | |
| alt0 += i % 2 === 0 ? "0" : "1"; | |
| alt1 += i % 2 === 0 ? "1" : "0"; | |
| } | |
| let diff0 = 0, diff1 = 0; | |
| let res = Infinity; | |
| let left = 0; | |
| for (let right = 0; right < 2 * n; right++) { | |
| if (s2[right] !== alt0[right]) diff0++; | |
| if (s2[right] !== alt1[right]) diff1++; | |
| // Once window size exceeds n, shrink from left | |
| if (right - left + 1 > n) { | |
| if (s2[left] !== alt0[left]) diff0--; | |
| if (s2[left] !== alt1[left]) diff1--; | |
| left++; | |
| } | |
| // When window size is exactly n, update result | |
| if (right - left + 1 === n) { | |
| res = Math.min(res, diff0, diff1); | |
| } | |
| } | |
| return res; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment