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;
}
};
Difficulty
and has an acceptance rate of about 62% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Prefix Sum
- Queue
- Sliding Window
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 319: Bulb Switcher
- problem 2167: Minimum Time to Remove All Cars Containing Illegal Goods
- problem 2450: Number of Distinct Binary Strings After Applying Operations
- problem 3191: Minimum Operations to Make Binary Array Elements Equal to One I
Solved On The Same Day
- problem 125: Valid Palindrome
- problem 191: Number of 1 Bits
- problem 202: Happy Number
- problem 217: Contains Duplicate
- problem 219: Contains Duplicate II
- problem 290: Word Pattern
- problem 383: Ransom Note
- problem 392: Is Subsequence
- problem 1047: Remove All Adjacent Duplicates In String
- problem 1089: Duplicate Zeros
- problem 151: Reverse Words in a String
- problem 187: Repeated DNA Sequences
- problem 51: N-Queens
- problem 52: N-Queens II
- problem 60: Permutation Sequence
- problem 68: Text Justification
- problem 76: Minimum Window Substring
- problem 135: Candy
- problem 140: Word Break II
- problem 220: Contains Duplicate III
- problem 239: Sliding Window Maximum
- problem 352: Data Stream as Disjoint Intervals
- problem 502: IPO
- problem 895: Maximum Frequency Stack
- problem 982: Triples with Bitwise AND Equal To Zero
- problem 996: Number of Squareful Arrays
- problem 2136: Earliest Possible Day of Full Bloom
Extra
- 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