Taro Logo

Max Consecutive Ones III

#39 Most AskedMedium
0 views
Topics:
ArraysTwo PointersSliding Windows

Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.

Example 1:

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.

Example 2:

Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.
  • 0 <= k <= nums.length

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the size of the array `nums` and the integer `k`?
  2. Can `k` be greater than the total number of zeros in the array, or even larger than the length of the array itself?
  3. What should be returned if the array is empty or if `k` is 0 and the array contains only zeros?
  4. Are we guaranteed that the input array will only contain binary values (specifically 0s and 1s), or could there be invalid inputs?
  5. Should I return the maximum length of the consecutive ones, or do you need the starting and ending indices of the window as well?

Brute Force Solution

Approach

Imagine you have a long row of alternating light and dark tiles, and you are allowed to flip a few dark tiles to light ones to make the longest possible continuous stretch of light tiles. The brute force approach involves testing every single possible starting point and ending point in the row, and counting how many dark tiles would need to be flipped in between.

Here's how the algorithm would work step-by-step:

  1. Begin by looking at the very first tile in the row.
  2. Pretend this tile is the start of your continuous stretch and trace forward step by step to see how long of a stretch you can make.
  3. Count every dark tile you encounter along the way, keeping track of how many you are allowed to flip.
  4. Once you run out of allowed flips, note the total length of the continuous stretch of tiles you just covered.
  5. Next, move your starting point to the second tile in the row and repeat the entire process of tracing forward and counting flips.
  6. Continue this exhaustive process for every possible starting point from the beginning of the row to the very end.
  7. Compare the lengths of all the stretches you measured during this process and pick the absolute longest one as your final answer.

Code Implementation

def longest_ones(binary_array, maximum_flips):
    maximum_length = 0

    # Iterate through every possible starting position to test all subarrays
    for start_index in range(len(binary_array)):
        flipped_count = 0

        for end_index in range(start_index, len(binary_array)):
            if binary_array[end_index] == 0:
                flipped_count += 1

            # Stop expanding this subarray if we exceed our allowed flips
            if flipped_count > maximum_flips:
                break

            current_length = (end_index - start_index) + 1

            # Keep track of the longest valid stretch we encounter
            if current_length > maximum_length:
                maximum_length = current_length

    return maximum_length

Big(O) Analysis

Time Complexity
O(n²) – For each of the n elements in the array acting as a starting point, we trace forward through the remaining elements to test the length of the continuous stretch. For the first starting point we check up to n elements, for the second we check up to (n-1) elements, and so on. This exhaustive evaluation of every possible starting and ending point leads to approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on a few primitive integer variables to track the current starting point, the ending point, and a count of flipped tiles. These variables occupy a constant amount of memory regardless of how long the row of tiles is. Because no auxiliary data structures, temporary lists, or recursion stacks are created that scale with the input, the extra memory usage remains completely fixed. Therefore, the auxiliary space complexity is constant, which simplifies to Big O of 1 in terms of the input size N.

Optimal Solution

Approach

Instead of checking every single possible stretch of zeros and ones, we can use a clever sliding window strategy. This approach expands our view to capture as many matching items as possible, and smoothly slides forward whenever we run out of our allowed swaps.

Here's how the algorithm would work step-by-step:

  1. Start at the very beginning of the row of items and imagine holding a flexible framing tool that looks at a growing stretch.
  2. Extend the right side of your frame outward, welcoming every item you encounter into your current view.
  3. Keep a mental count of any zeros you capture inside your frame, since those represent the items you will need to flip.
  4. If the number of zeros you have collected ever exceeds your limit, gently slide the left side of your frame forward to drop the oldest item and lower your zero count.
  5. As you slide, constantly measure the total distance between the left and right sides of your frame to see how many items you have successfully gathered.
  6. Continue expanding to the right whenever possible, ensuring your frame always represents the longest valid stretch you have seen so far.
  7. Once you reach the very end of the row, the maximum size your frame ever achieved will be your final answer.

Code Implementation

def longest_ones(binary_array, allowed_flips):
    window_start = 0
    zero_count = 0
    max_sequence_len = 0

    for window_end in range(len(binary_array)):
        if binary_array[window_end] == 0:
            zero_count += 1

        # We shrink the window from the left when zero count exceeds our allowed limit.
        if zero_count > allowed_flips:
            if binary_array[window_start] == 0:
                zero_count -= 1
            window_start += 1

        # Track the maximum valid window size found so far during our scan.
        current_window_size = window_end - window_start + 1
        if current_window_size > max_sequence_len:
            max_sequence_len = current_window_size

    return max_sequence_len

Big(O) Analysis

Time Complexity
O(n) – As the right pointer iterates through the n elements of the array from start to finish, the left pointer only moves forward and never backtracks. Each element is visited at most once by the right pointer and at most once by the left pointer. This means the total operations scale linearly as roughly 2n steps, which simplifies to O(n).
Space Complexity
O(1) – The algorithm tracks the sliding window using only a few primitive variables for the left and right boundaries, the zero count, and the maximum length. These variables require a constant amount of memory regardless of the input array size. No auxiliary data structures, temporary lists, or recursive call stacks are utilized during execution. Therefore, the extra memory used remains entirely independent of N, resulting in constant auxiliary space complexity.

Edge Cases

Empty input array where nums is null or has length zero
How to Handle:
The sliding window loop will not execute, returning the correct max length of zero.
Array size of one with k equals zero or one
How to Handle:
The pointer logic correctly evaluates the single element and returns its value.
All zeros in the array and k equals zero
How to Handle:
The window will collapse to a size of zero and return the correct maximum length of zero.
All zeros in the array and k is greater than or equal to the array length
How to Handle:
The right pointer will traverse the entire array and return the total array length as the result.
All ones in the array regardless of the value of k
How to Handle:
No zeros need to be flipped, and the sliding window expands to encompass the entire array returning its length.
k is greater than the total number of zeros in the array
How to Handle:
The window expands to the end of the array without violating the zero count constraint, returning the full array length.
Maximum possible array length with up to one hundred thousand elements
How to Handle:
The linear time sliding window approach processes the array efficiently in O(n) time avoiding time limit errors.
Alternating ones and zeros with a small k value
How to Handle:
The left pointer contracts efficiently whenever the zero count exceeds k maintaining an accurate maximum window size.
0/257 completed