Fewest Panel Flips

HardSliding Window

Problem

A row of display panels is described by panels: 1 means the panel shows its lit side and 0 its dark side. A maintenance tool flips exactly `k` consecutive panels at once, turning every 0 into 1 and every 1 into 0 in that block.

Return the minimum number of tool uses needed to make every panel show 1, or -1 if it is impossible.

Example 1

Input:
panels = [0, 0, 1, 0, 0, 1, 1], k = 3
Output:
2

Flip positions 0–2 → [1, 1, 0, 0, 0, 1, 1], then flip 2–4 → all ones.

Example 2

Input:
panels = [1, 0, 1], k = 2
Output:
-1

Each flip changes two adjacent panels, so the lone 0 can never be fixed without breaking a neighbour.

Constraints

  • 1 ≤ k ≤ panels.length ≤ 10^5
  • panels[i] is 0 or 1

Hint

Show the first hint

Look at the leftmost panel. Which flips can ever change it, and do you have a choice?

Walkthrough

How to approach it

01Clarify before coding

  • Must the block be fully inside the row? Yes, exactly k panels, no wrapping.
  • Does the order of flips matter? No: flipping is XOR, so only how many times each start is used matters, and using one twice cancels out.
  • Return -1 when impossible? Yes.

02Brute force

Greedy with literal flipping: scan left to right and, at every 0, flip the next k panels in the array.

Cost: O(n·k) time; at n = 10^5 and k = 5·10^4 this is 2.5·10^9 writes. (Trying all subsets of starts is O(2^n).)

The rest of the walkthrough is in the app

The full walkthrough (key insight, step-by-step, dry run, complexity, edge cases, pitfalls, follow-ups) and solutions in Python and JavaScript are in the app, next to an editor and a terminal that runs your code against the tests.

This problem is part of Pro.