Sliding Window · Medium

Longest Subarray of 1s After Flipping At Most K Zeros

Solve it on DeVert Campus - free code runner

Problem

You are given a binary array (containing only 0s and 1s) of length n and an integer k. You may flip at most k of the 0s in the array to 1s. Find the length of the longest contiguous subarray that consists entirely of 1s after performing the best possible choice of flips.

Input and output

Input: The first line contains two space-separated integers n and k. The second line contains n space-separated integers (each 0 or 1) representing the array. Output: Print a single integer: the length of the longest subarray of 1s obtainable after flipping at most k zeros.

Example

Input:
11 2
1 1 1 0 0 0 1 1 1 1 0
Output:
6

Constraints

1 <= n <= 10^5 0 <= k <= n arr[i] is either 0 or 1.

Key observation

This is a great illustration of simplifying a general sliding-window technique (tracking a full frequency map) down to just a single counter, when the underlying problem's constraint (binary values only) makes that simplification valid and sufficient.

Intuition

Find the longest run of 1s achievable by flipping at most k zeros within a binary array. Brute force: Check every possible subarray directly, counting its zeros and verifying it's within the k-flip budget - this costs O(n²), too slow for large arrays. Optimised: Since all values are either 0 or 1 (a simplified case of the general 'at most k distinct/violating elements' pattern), tracking just a ZERO COUNT (rather than a full frequency map) is sufficient - expanding and shrinking the window in a single combined linear pass finds the longest valid window in O(n).

Step by step

1. Slide a window over the array while counting how many ZEROS it currently contains. 2. Whenever the zero count inside the window EXCEEDS k, shrink the window from the left until it contains at most k zeros again. 3. The answer is the maximum window length observed; each zero inside the final window represents one of the flips used.

Complexity

Time: O(n) - each element enters and leaves the window at most once. Space: O(1) - just a running zero count, no full frequency map needed since there are only two possible values.

Edge cases

Handle k = 0 (no flips allowed, so the answer is the longest existing run of 1s) and k = n (every zero may be flipped, so the whole array can become the answer).

Interview tip

Be ready to connect this directly to the more general 'longest substring with at most k distinct characters' pattern - this is a simplified special case where the 'violating' condition is specifically 'too many zeros', rather than 'too many distinct characters'.

All DSA problems