Katkat

Debug Queues and Solve Arrays

LinkedInSoftware Engineer · Onsite

Last updated

Tests array traversal, sliding window techniques, and handling wrap-around logic in circular data structures with edge cases.

Problem Statement

You are given a circular binary array nums of length n. Because the array is circular, the element at index 0 follows the element at index n - 1.

You are allowed to flip at most one 0 to a 1. Return the maximum number of consecutive 1s you can achieve in the array.

Note: An element at any specific index can only be included at most once in any contiguous sequence. Therefore, the result can never exceed n.

Function Interface

def max_consecutive_ones(nums: list[int]) -> int:
    pass

Input & Output Format

  • Input: A list of integers nums where each element is either 0 or 1.
  • Output: An integer representing the maximum length of consecutive 1s after at most one flip.

Constraints

  • 1 <= len(nums) <= 10^5
  • nums[i] in (0, 1)

Examples

Example 1

Input: nums = [1, 0, 1, 1, 0, 1]
Output: 5
Explanation:
If we flip nums[1] from 0 to 1, we can form a contiguous block wrapping around the ends:
indices 5, 0, 1, 2, 3 -> [1, 1, 1, 1, 1], which has length 5.

Example 2

Input: nums = [0, 0, 0]
Output: 1
Explanation:
Flipping any single 0 yields a maximum streak of 1.

Example 3

Input: nums = [1, 1, 1]
Output: 3
Explanation:
All elements are already 1, so the maximum length is the length of the array (3).

Edge Cases to Consider

  • Arrays containing only 1s or only 0s.
  • A single-element array ([0] or [1]).
  • Arrays where the longest sequence strictly spans across the boundary between index n - 1 and index 0.
  • Ensuring the window size never exceeds len(nums) even if no additional 0s are encountered.

Hints

Hint 1

A common technique for handling circular arrays is conceptually duplicating the array (`nums + nums`) to simplify wrap-around traversal.

Hint 2

Use a sliding window (two pointers) over the virtual array of length `2 * n`, maintaining the count of zeros currently in the window.

Hint 3

Ensure your sliding window length never exceeds `n` to avoid counting the same element twice.

Follow-up questions

  • How would you generalize your solution if you are allowed to flip up to `k` zeros instead of just one?
  • Can you solve this with `O(1)` extra space without creating a concatenated copy of the array?
  • If the array is represented as a stream or a thread-safe circular bounded queue, how would you continuously track the maximum consecutive ones?