KatInterview

Longest All-Ones Window After Limited Bit Flips

Arrays & HashingAuto-graded · 24 test cases
MediumAuto-gradedArrays & Hashingsliding-windowtwo-pointersarrays

Last updated

Tests the ability to reframe a flip problem as a sliding-window search and reason about amortized complexity.

You are given a list nums consisting only of 0s and 1s, along with an integer k that represents the maximum number of 0-to-1 flips you may perform.

Find the length of the longest contiguous segment of the array that can be turned into all 1s by flipping at most k of its elements from 0 to 1.

Return a single integer: the maximum possible length of such a segment.

Constraints:

  • 0 <= len(nums) <= 10^5
  • Each element of nums is either 0 or 1.
  • 0 <= k <= len(nums)

Edge-case rules:

  • If the array is empty, return 0.
  • If k is 0, the answer is the length of the longest existing run of consecutive 1s.
  • If k is greater than or equal to the total number of 0s in the array, the answer is len(nums).
  • If every element is 0, the answer is min(k, len(nums)).
  • If every element is 1, the answer is len(nums).

Examples

Example 1

Input: longest_ones_after_flips([1, 0, 0, 1, 0, 1, 0, 0], 2)

Output: 4

Example 2

Input: longest_ones_after_flips([0, 0, 1, 1, 0, 0, 1, 1, 1, 0], 3)

Output: 8

Example 3

Input: longest_ones_after_flips([1, 1, 1, 1], 0)

Output: 4

Example 4

Input: longest_ones_after_flips([0, 0, 0], 5)

Output: 3

Hints

Hint 1

Reframe the problem: instead of tracking flips, find the longest contiguous segment that contains at most k zeros.

Hint 2

Use a variable-size sliding window with two pointers, keeping a count of zeros currently inside the window.

Hint 3

When the zero count exceeds k, advance the left pointer until the window is valid again. Each element is visited at most twice, giving O(n) time.