LeetCode Solutions

995. Minimum Number of K Consecutive Bit Flips

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int minKBitFlips(vector<int>& A, int K) {
    int ans = 0;
    int flippedTime = 0;

    for (int r = 0; r < A.size(); ++r) {
      if (r >= K && A[r - K] == 2)
        --flippedTime;
      if (flippedTime % 2 == A[r]) {
        if (r + K > A.size())
          return -1;
        ++ans;
        ++flippedTime;
        A[r] = 2;
      }
    }

    return ans;
  }
};
			

class Solution {
  public int minKBitFlips(int[] A, int K) {
    int ans = 0;
    int flippedTime = 0;

    for (int r = 0; r < A.length; ++r) {
      if (r >= K && A[r - K] == 2)
        --flippedTime;
      if (flippedTime % 2 == A[r]) {
        if (r + K > A.length)
          return -1;
        ++ans;
        ++flippedTime;
        A[r] = 2;
      }
    }

    return ans;
  }
}
			

class Solution:
  def minKBitFlips(self, A: List[int], K: int) -> int:
    ans = 0
    flippedTime = 0

    for r, a in enumerate(A):
      if r >= K and A[r - K] == 2:
        flippedTime -= 1
      if flippedTime % 2 == a:
        if r + K > len(A):
          return -1
        ans += 1
        flippedTime += 1
        A[r] = 2

    return ans