Longest Subarray of 1's After Deleting One Element
Longest Subarray of 1's After Deleting One Element is a medium arrays & hashing problem solved with the sliding window · variable pattern.
The best approach, optimal (sliding window with at most one zero), runs in O(n) time and O(1) space.
Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (try every deletion) up.
Problem
You are given a binary array nums (every element is 0 or 1).
You must delete exactly one element from it. After the deletion, return the length of the longest non-empty subarray that contains only 1’s. If no such subarray exists, return 0.
Examples
Example 1
- Input
nums = [1,1,0,1,1,1,0,1]- Output
5- Why
- Delete the 0 at index 2. The array becomes [1,1,1,1,1,0,1], whose longest block of 1's has length 5.
Example 2
- Input
nums = [1,1,1,1]- Output
3- Why
- There is no 0 to remove, but one element must still be deleted. Deleting any 1 leaves a block of three 1's.
Example 3
- Input
nums = [0,0,0]- Output
0- Why
- Whatever is deleted, only 0's remain, so no non-empty subarray contains only 1's.
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 26 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (try every deletion) | O(n²) | O(1) |
| Runs to the left and right of each index | O(n) | O(n) |
| Optimal (sliding window with at most one zero) | O(n) | O(1) |
1Brute force (try every deletion)
O(n²)n choices of the deleted index, each followed by a full scan of n elements.O(1)Only the counters run and best.Try deleting each index in turn. For each choice, scan the rest of the array, skipping the deleted index, and track the longest run of consecutive 1's. The answer is the best run over all choices.
- Set best = 0.
- For each index del: set run = 0 and scan i = 0 to n - 1, skipping i == del.
- On a 1, add one to run and update best; on a 0, reset run to 0.
- Return best.
class Solution {
public int longestSubarray(int[] nums) {
int n = nums.length, best = 0;
for (int del = 0; del < n; del++) {
int run = 0;
for (int i = 0; i < n; i++) {
if (i == del) continue;
if (nums[i] == 1) {
run++;
best = Math.max(best, run);
} else {
run = 0;
}
}
}
return best;
}
}class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
best = 0
for dl in range(n):
run = 0
for i in range(n):
if i == dl:
continue
if nums[i] == 1:
run += 1
best = max(best, run)
else:
run = 0
return bestclass Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size(), best = 0;
for (int del = 0; del < n; del++) {
int run = 0;
for (int i = 0; i < n; i++) {
if (i == del) continue;
if (nums[i] == 1) {
run++;
best = max(best, run);
} else {
run = 0;
}
}
}
return best;
}
};function longestSubarray(nums) {
const n = nums.length;
let best = 0;
for (let del = 0; del < n; del++) {
let run = 0;
for (let i = 0; i < n; i++) {
if (i === del) continue;
if (nums[i] === 1) {
run++;
best = Math.max(best, run);
} else {
run = 0;
}
}
}
return best;
}2Runs to the left and right of each index
O(n)Three passes over the array, each doing constant work per index.O(n)The two run arrays have n entries each.Precompute two arrays. left[i] is the length of the run of 1's that ends at index i (0 when nums[i] is 0), and right[i] is the length of the run that starts at index i. If we delete index i, the block of 1's through the gap is left[i - 1] + right[i + 1], treating positions outside the array as 0. Taking the maximum over every i covers deleting a 0 (two runs join) and deleting a 1 (one run loses an element), so the all-ones case gives n - 1 on its own.
- Fill left from the left: left[i] = left[i - 1] + 1 when nums[i] is 1, otherwise 0.
- Fill right from the right: right[i] = right[i + 1] + 1 when nums[i] is 1, otherwise 0.
- For every i, best = max(best, left[i - 1] + right[i + 1]), using 0 beyond the ends.
- Return best.
class Solution {
public int longestSubarray(int[] nums) {
int n = nums.length;
int[] left = new int[n], right = new int[n];
for (int i = 0; i < n; i++) {
if (nums[i] == 1) left[i] = (i > 0 ? left[i - 1] : 0) + 1;
}
for (int i = n - 1; i >= 0; i--) {
if (nums[i] == 1) right[i] = (i < n - 1 ? right[i + 1] : 0) + 1;
}
int best = 0;
for (int i = 0; i < n; i++) {
int before = i > 0 ? left[i - 1] : 0;
int after = i < n - 1 ? right[i + 1] : 0;
best = Math.max(best, before + after);
}
return best;
}
}class Solution:
def longestSubarray(self, nums: List[int]) -> int:
n = len(nums)
left = [0] * n
right = [0] * n
for i in range(n):
if nums[i] == 1:
left[i] = (left[i - 1] if i > 0 else 0) + 1
for i in range(n - 1, -1, -1):
if nums[i] == 1:
right[i] = (right[i + 1] if i < n - 1 else 0) + 1
best = 0
for i in range(n):
before = left[i - 1] if i > 0 else 0
after = right[i + 1] if i < n - 1 else 0
best = max(best, before + after)
return bestclass Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size();
vector<int> left(n, 0), right(n, 0);
for (int i = 0; i < n; i++) {
if (nums[i] == 1) left[i] = (i > 0 ? left[i - 1] : 0) + 1;
}
for (int i = n - 1; i >= 0; i--) {
if (nums[i] == 1) right[i] = (i < n - 1 ? right[i + 1] : 0) + 1;
}
int best = 0;
for (int i = 0; i < n; i++) {
int before = i > 0 ? left[i - 1] : 0;
int after = i < n - 1 ? right[i + 1] : 0;
best = max(best, before + after);
}
return best;
}
};function longestSubarray(nums) {
const n = nums.length;
const left = new Array(n).fill(0), right = new Array(n).fill(0);
for (let i = 0; i < n; i++) {
if (nums[i] === 1) left[i] = (i > 0 ? left[i - 1] : 0) + 1;
}
for (let i = n - 1; i >= 0; i--) {
if (nums[i] === 1) right[i] = (i < n - 1 ? right[i + 1] : 0) + 1;
}
let best = 0;
for (let i = 0; i < n; i++) {
const before = i > 0 ? left[i - 1] : 0;
const after = i < n - 1 ? right[i + 1] : 0;
best = Math.max(best, before + after);
}
return best;
}3Optimal (sliding window with at most one zero)
O(n)right moves forward n times and left moves forward at most n times in total.O(1)Only the two pointers and two counters.After the deletion, the block of 1's comes from a window of the original array that contains at most one 0: the deleted element is that 0, or any 1 if the window has no 0. So find the longest window with at most one 0 and subtract one for the deleted element. Grow the window by moving right forward and counting zeros; while it holds two zeros, move left forward until one zero leaves. The window [left, right] then has right - left + 1 elements, so the candidate answer is right - left.
- Set left = 0, zeros = 0 and best = 0.
- For right = 0 to n - 1: if nums[right] is 0, add one to zeros.
- While zeros > 1: if nums[left] is 0, subtract one from zeros; then move left forward.
- Update best = max(best, right - left), the window length minus the one deleted element.
- Return best.
class Solution {
public int longestSubarray(int[] nums) {
int left = 0, zeros = 0, best = 0;
for (int right = 0; right < nums.length; right++) {
if (nums[right] == 0) zeros++;
while (zeros > 1) {
if (nums[left] == 0) zeros--;
left++;
}
best = Math.max(best, right - left);
}
return best;
}
}class Solution:
def longestSubarray(self, nums: List[int]) -> int:
left = zeros = best = 0
for right in range(len(nums)):
if nums[right] == 0:
zeros += 1
while zeros > 1:
if nums[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left)
return bestclass Solution {
public:
int longestSubarray(vector<int>& nums) {
int left = 0, zeros = 0, best = 0;
for (int right = 0; right < (int) nums.size(); right++) {
if (nums[right] == 0) zeros++;
while (zeros > 1) {
if (nums[left] == 0) zeros--;
left++;
}
best = max(best, right - left);
}
return best;
}
};function longestSubarray(nums) {
let left = 0, zeros = 0, best = 0;
for (let right = 0; right < nums.length; right++) {
if (nums[right] === 0) zeros++;
while (zeros > 1) {
if (nums[left] === 0) zeros--;
left++;
}
best = Math.max(best, right - left);
}
return best;
}Edge cases to test
- All 1's: exactly one element must still be deleted, so the answer is n - 1, not n
- All 0's: the answer is 0
- A single element: after deleting it the array is empty, so the answer is 0
- Two blocks of 1's separated by a single 0 join into one; two 0's in a row never let blocks join
- The best block may touch either end of the array, or the deleted 0 may be at an end
Hints
Hint 1
Deleting a 1 never helps more than deleting a 0 next to it, except when there is no 0 at all.
Hint 2
If you delete position i, the best block that uses the gap is (run of 1's ending at i - 1) + (run of 1's starting at i + 1).
Hint 3
Equivalently, find the longest window that contains at most one 0. Its length minus one is the answer, because one element of the window is deleted.
FAQ
What is the best time complexity for Longest Subarray of 1's After Deleting One Element?
Optimal (sliding window with at most one zero) runs in O(n) time and O(1) extra space. right moves forward n times and left moves forward at most n times in total.
Which pattern does Longest Subarray of 1's After Deleting One Element use?
It is a arrays & hashing problem that uses the sliding window · variable pattern. Other problems with the same pattern: Minimum Size Subarray Sum, Count of Subarrays with Product Less Than K, Longest Repeating Character Replacement.
Is there a brute force solution for Longest Subarray of 1's After Deleting One Element?
Yes. Brute force (try every deletion) takes O(n²) time and O(1) space. Try deleting each index in turn.
Which edge cases should I test for Longest Subarray of 1's After Deleting One Element?
All 1's: exactly one element must still be deleted, so the answer is n - 1, not n; All 0's: the answer is 0; A single element: after deleting it the array is empty, so the answer is 0; Two blocks of 1's separated by a single 0 join into one; two 0's in a row never let blocks join; The best block may touch either end of the array, or the deleted 0 may be at an end.