Problem 995

Abstract / Summary

Given a binary array and an integer k, find the least flips needed to turn all zeros to ones by flipping exactly k consecutive bits each time.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0995.cpp

class Solution {
public:
    int minKBitFlips(vector<int>& nums, int k) {
        // track active flips
        deque<int> flips;
        int good = 1;

        // flips after that point lead to impossible configurations
        int threshold = nums.size() - k;

        int result = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            // expired
            if (!flips.empty() && flips.front() == i)
            {
                flips.pop_front();
                good = 1 - good;
            }

            // no flip ?
            if (nums[i] == good)
                continue;

            // too late, impossible
            if (i > threshold)
                return -1;

            // flip
            result++;

            good = 1 - good;
            flips.push_back(i + k);
        }

        return result;
    }
};
38 lines | 886 bytes | submitted August 9, 2023 | GitHub   24% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Prefix Sum
  • Queue
  • Sliding Window
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “minimum K-bit flips” problem. It processes the input array nums from left to right, maintaining a sliding window of active flip operations. The algorithm decides at each position whether a new flip is required, updates the state that represents the current logical value of the bits, and records when each flip expires. The result is the smallest number of flips needed to make every element equal to 1; if this cannot be achieved, the function returns -1.

Core Logic

Tracking active flips

A double-ended queue (deque<int> flips) stores the indices at which each flip operation stops influencing the array. The front of the deque always holds the earliest expiration index.

deque<int> flips;
int good = 1;

good represents the logical value that a bit should have after applying all active flips. Initially it is 1 because the goal is to turn all bits to 1.

Determining the last feasible start position

The variable threshold marks the last index where a new flip of length k can start without exceeding the array bounds.

int threshold = nums.size() - k;

If the current index exceeds this threshold and the bit is still incorrect, the algorithm concludes that the target configuration is impossible.

Main iteration

The loop iterates over every index i of nums.

for (int i = 0; i < nums.size(); i++)
{
    // expired
    if (!flips.empty() && flips.front() == i)
    {
        flips.pop_front();
        good = 1 - good;
    }

    // no flip ?
    if (nums[i] == good)
        continue;

    // too late, impossible
    if (i > threshold)
        return -1;

    // flip
    result++;

    good = 1 - good;
    flips.push_back(i + k);
}

Expiration handling

When the current index matches the expiration index at the front of flips, that flip no longer affects subsequent positions. The code removes it and toggles good to reflect the removal of its effect.

Decision to flip

If the current element already matches good, the algorithm proceeds without action. Otherwise, if the index is beyond threshold, it returns -1 because a new flip would overrun the array. If a flip is possible, result is incremented, good is toggled to account for the new flip, and the expiration index i + k is pushed to the back of the deque.

Final result

After processing all elements, the accumulated result holds the minimum number of flips required.

return result;

Edge Cases Handled

When the input array is empty, the loop body never executes and result remains 0, correctly indicating that no flips are needed.

If k equals 1, each mismatched bit triggers an immediate flip; the expiration index becomes i + 1, so the flip expires on the next iteration, and the algorithm still functions correctly.

When k is larger than the array length, threshold becomes negative. The condition i > threshold is true for the first index, causing an early return of -1 unless the array already satisfies the target (nums[i] == good for all i). This correctly captures the impossibility of performing any flip.

The deque automatically discards expired flips, ensuring that overlapping flips are accounted for without double counting.

Performance Optimizations

The use of a deque provides O(1) amortized insertion at the back and removal from the front, enabling constant-time management of flip expirations. By toggling a single boolean variable good instead of recomputing the parity of active flips at each step, the algorithm avoids repeated scanning of the deque, keeping the per-iteration work minimal.

The early termination check (i > threshold) prevents unnecessary processing once it is known that a solution cannot exist, saving cycles for inputs where the required flips would extend beyond the array bounds.

Overall, the algorithm processes each element exactly once, with constant-time operations per element, leading to an efficient solution for large inputs.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of light switches that can be either on or off. The goal is to make sure every single switch is turned to the on position. To do this, a special tool is used that flips a group of switches all at once. Because the tool is a certain size, it always flips a fixed number of switches in a row.

The code walks down the line of switches one by one to check their state. A list is kept to remember where the tool was used previously. This is important because flipping a switch twice is the same as not flipping it at all. The variable called good keeps track of whether the current switch needs to be changed based on how many times it has been flipped by the tool.

When the code sees a switch that is in the wrong position, it decides to use the tool. If the current spot is too close to the end of the line, it becomes impossible to finish the job because the tool is too wide to fit. Every time the tool is used, the count of moves goes up by one, and the memory list is updated to know when that specific flip will no longer affect the upcoming switches. Once every switch is checked and fixed, the total number of times the tool was used is revealed.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.74 | σ = 1.20

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Go Rust TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JS
shreymehul C#
suxrobGM C#
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
Garvit244 Python
halfrost Go
JoshCrozier JavaScript
shreymehul C#
suxrobGM C#
wisdompeak C++
29 links | 15 authors | 8 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

4 similar problems

Solved On The Same Day

10 easy 2 medium 15 hard
28 solutions   August 9, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality