Debug Queues and Solve Arrays
LinkedInSoftware Engineer · OnsiteLast 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
numswhere each element is either0or1. - Output: An integer representing the maximum length of consecutive
1s after at most one flip.
Constraints
1 <= len(nums) <= 10^5nums[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 only0s. - A single-element array (
[0]or[1]). - Arrays where the longest sequence strictly spans across the boundary between index
n - 1and index0. - Ensuring the window size never exceeds
len(nums)even if no additional0s 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?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.