medium Longest Subarray of 1's After Deleting One Element
Problem Statement
Given a binary array nums, return the length of the longest non-empty subarray containing only 1's after removing 1 element from the array. Return 0 if there is no such subarray.
Examples
Example 1
- Input:
[1, 1, 0, 0, 1, 1] - Expected Output:
2 - Justification: By removing the first 0, you get
[1, 1, 0, 1, 1]and the longest sequence of 1s is[1, 1].
Example 2
- Input:
[1, 1, 0, 1, 1, 1] - Expected Output:
5 - Justification: By removing the first 0, you get
[1, 1, 1, 1, 1]which is the longest sequence of 1s .
Example 3
- Input:
[1, 0, 1, 1, 0, 1] - Expected Output:
3 - Justification: By removing the 0 between the first and third 1, you get
[1, 1, 1, 0, 1], which has a length of 3.
Pattern cue: variable window with at most one 0 (same family as Max Consecutive Ones III with k = 1); answer is window length minus 1 because one deletion is mandatory.
Try it yourself
Try solving this question here:
🎯 STRICT STANDOUT — Longest 1s After Deleting One Element
1. Why / judgment
You must delete exactly one element. Equivalent: longest window with at most one 0, then answer windowLength − 1 (the deletion). Same family as Max Consecutive Ones III with k=1, with the mandatory-delete twist (all-ones array cannot return n).
2. Hand-run + complexity (K11)
nums=[1,1,0,1,1,1]
Find max R−L+1 with ≤1 zero, then ans = that − 1
R advances over [1,1,0,1,1,1] zeros=1; size=6; ans=5 ✓
[1,1,0,0,1,1]: max window with ≤1 zero is length 3 (e.g. indices 0..2 or 3..5) → ans=2 ✓
Each index enters/leaves once → Θ(n) time, Θ(1) space.
Brute delete each index then scan → Θ(n²).
3. Pattern — VARIABLE WINDOW, AT MOST k ZEROS (k=1) (K12)
Name: Max consecutive ones with one deletion.
Recognition: binary array; delete one; longest 1-run after delete.
When-NOT: k flips allowed (general k) → same window, zeros≤k, answer length not length−1 if flips optional; non-binary → different constraint; must return subarray itself → keep bounds.
4. Edge hand-run (K13)
[1,1,1] → must delete one → answer 2 (not 3)
[0,0,0] → after delete still zeros → 0
[1,0,1] → delete 0 → 2
[0] → delete the only element → empty → 0
5. Interviewer follow-ups
Q1. Why subtract 1 from window length?
A: One element is deleted from the window; remaining 1s form the answer length.
Q2. All ones special case?
A: Window can be whole array with 0 zeros; still delete one → n−1.
Q3. Complexity?
A: Θ(n) time two pointers, Θ(1) space.
✅ Solution Longest Subarray of 1's After Deleting One Element
Problem Statement
Given a binary array nums, return the length of the longest non-empty subarray containing only 1's after removing 1 element from the array. Return 0 if there is no such subarray.
Examples
Example 1
- Input:
[1, 1, 0, 0, 1, 1] - Expected Output:
2 - Justification: By removing the first 0, you get
[1, 1, 0, 1, 1]and the longest sequence of 1s is[1, 1].
Example 2
- Input:
[1, 1, 0, 1, 1, 1] - Expected Output:
5 - Justification: By removing the first 0, you get
[1, 1, 1, 1, 1]which is the longest sequence of 1s .
Example 3
- Input:
[1, 0, 1, 1, 0, 1] - Expected Output:
3 - Justification: By removing the 0 between the first and third 1, you get
[1, 1, 1, 0, 1], which has a length of 3.
Constraints:
- 1 <= nums.length <= 105
- nums[i] is either 0 or 1.
Pattern
Variable window with must-delete-one. This is Max Consecutive Ones III with flip budget k = 1, but the problem requires deleting exactly one element, so the answer is window length minus 1: track maxLen = max(maxLen, right - left) (not + 1). Recognition: "longest 1s after deleting one element" / "at most one zero inside the window."
Edge: all ones → you still delete one, return n - 1. All zeros → after delete, empty of 1s → 0. Single element → 0.
Why right - left not right - left + 1: the window always "pays" for one deletion slot (the one zero allowed, or one 1 if there is no zero). Dropping the +1 encodes that forced deletion without a separate branch.
Solution
Maintain a window that contains at most one 0. Expand right; when a second 0 enters, advance left until only one 0 remains. Update the best length as right - left (window size minus the deleted element). One pass, O(n) time, O(1) space.
Step-by-Step Algorithm
-
Initialize Pointers and Variables:
- Set two pointers,
leftandright, at the start of the list. - Create a variable
zeroCountto count zeros in the current window. - Create a variable
maxLento store the maximum length of 1s found.
- Set two pointers,
-
Iterate through the List:
- Move the
rightpointer across the list. - If
nums[right]is 0, incrementzeroCount.
- Move the
-
Adjust the Window:
- If
zeroCountexceeds 1, move theleftpointer to the right untilzeroCountis at most 1 again. - Adjust
zeroCountaccordingly by checking the value atnums[left].
- If
-
Update Maximum Length:
- Calculate the length of the current window (i.e.,
right - left). - Update
maxLenif the current window length is greater.
- Calculate the length of the current window (i.e.,
-
Return Result:
- Return
maxLen, which is the maximum length of a subarray containing only 1s after removing one element.
- Return
Algorithm Walkthrough
Using the example input [1, 0, 1, 1, 0, 1]:
-
Initial State:
left = 0,right = 0,zeroCount = 0,maxLen = 0- Array:
[1, 0, 1, 1, 0, 1]
-
Step 1:
- Move
rightto 0. nums[right]is 1, sozeroCountremains 0.- Current window:
[1] maxLen = max(0, 0 - 0) = 0rightmoves to 1.
- Move
-
Step 2:
rightat 1.nums[right]is 0, sozeroCountincrements to 1.- Current window:
[1, 0] maxLen = max(0, 1 - 0) = 1rightmoves to 2.
-
Step 3:
rightat 2.nums[right]is 1, sozeroCountremains 1.- Current window:
[1, 0, 1] maxLen = max(1, 2 - 0) = 2rightmoves to 3.
-
Step 4:
rightat 3.nums[right]is 1, sozeroCountremains 1.- Current window:
[1, 0, 1, 1] maxLen = max(2, 3 - 0) = 3rightmoves to 4.
-
Step 5:
rightat 4.nums[right]is 0, sozeroCountincrements to 2.- Since
zeroCount> 1, adjustleft.nums[left]is 1, sozeroCountremains 2.leftmoves to 1.nums[left]is 0, sozeroCountdecrements to 1.leftmoves to 2.
- Current window:
[1, 1, 0, 1] maxLen = max(3, 4 - 2) = 3rightmoves to 5.
-
Step 6:
rightat 5.nums[right]is 1, sozeroCountremains 1.- Current window:
[1, 1, 0, 1] maxLen = max(3, 5 - 2) = 3rightmoves to 6 (end of array).
-
Final State:
- The maximum length of a subarray containing only 1s after removing one element is
3.
- The maximum length of a subarray containing only 1s after removing one element is
Code
class Solution {
public int longestSubarray(int[] nums) {
int left = 0, right = 0, zeroCount = 0, maxLen = 0;
// Iterate through the array with right pointer
while (right < nums.length) {
if (nums[right] == 0) zeroCount++;
// If more than one zero in the window, adjust left pointer
while (zeroCount > 1) {
if (nums[left] == 0) zeroCount--;
left++;
}
// Update max length
maxLen = Math.max(maxLen, right - left);
right++;
}
return maxLen;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.longestSubarray(new int[] { 1, 1, 0, 0, 1, 1 })); // Output: 2
System.out.println(sol.longestSubarray(new int[] { 1, 1, 0, 1, 1, 1 })); // Output: 5
System.out.println(sol.longestSubarray(new int[] { 1, 0, 1, 1, 0, 1 })); // Output: 3
}
}
Complexity Analysis
Time Complexity
The time complexity of the solution is n is the length of the input array nums. This is because we iterate through the array only once with the right pointer, and the left pointer also moves at most n times. Each element is processed a constant number of times, resulting in linear time complexity.
Space Complexity
The space complexity of the solution is
🎯 STRICT STANDOUT: Why / complexity derivation / pattern+when-not / edges / drills — Solution Longest Subarray of 1's After Deleting One Element
Why this exists (judgment layer)
Must-delete-one is Max Consecutive Ones III with k=1 plus a forced removal — the subtlety is encoding the delete as right−left (not +1) so all-ones still returns n−1.
Worked example & complexity derivation
nums=[1,0,1,1,0,1], k_zeros_allowed=1, must delete one element
Window may contain ≤1 zero; score = right-left (= len-1)
Trace ends with best covering one zero + ones → score 3
All ones [1,1,1]: window full n, score n-1 (must delete a 1)
All zeros: after delete still no 1-run → 0
Time O(n) two pointers; space O(1)
Pattern transfer & when-NOT
Pattern: VARIABLE WINDOW, k=1 zero, answer = len−1. When-NOT: optional delete (then pure Ones III with k=1 keeps +1); delete up to k → Ones III; non-binary arrays → different constraint. Not fixed window.
Edge cases (hand-run)
Single element → 0. All ones → n−1. All zeros → 0. Two zeros only → longest ones after removing one zero may be short runs of ones.
Hostile-panel drills (defend the decision)
Q1. Why right−left not right−left+1?
Model answer: Problem forces deleting one element from the subarray/window; dropping +1 encodes that tax without a special case for 'zero vs one deleted'.
Q2. Hand-run [1,1,0,1,1,1] → 5.
Model answer: Window spanning the single zero has length 6; delete the zero → 5 ones.
Q3. Map to Ones III.
Model answer: Identical expand/shrink with k=1; answer transformation is −1 for mandatory delete.
Recognize it: Best/longest/count over a contiguous subarray or substring → grow the window, shrink it when a constraint breaks.
▶ Visualize this problem (step it, predict each fork)
🤖 Don't fully get this? Learn it with Claude
Stuck on Longest Subarray of 1's After Deleting One Element? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Longest Subarray of 1's After Deleting One Element** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Longest Subarray of 1's After Deleting One Element** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Longest Subarray of 1's After Deleting One Element**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Longest Subarray of 1's After Deleting One Element**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.