Skip to main content

Longest Subarray of 1's After Deleting One Element - Solution & Explanation

MediumArrayDynamic ProgrammingSliding Window29 min readAsked at: Amazon, Microsoft, Meta +5
Practice this problem

Problem Statement

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

 

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.

Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].

Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.

 

Constraints:

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

Approach Overview

Problem Overview: You receive a binary array and must delete exactly one element. After the deletion, return the length of the longest contiguous subarray containing only 1s. The challenge is maximizing the length while handling the single allowed deletion efficiently.

Approach 1: Sliding Window with Variables (O(n) time, O(1) space)

This approach uses the classic sliding window technique. Maintain two pointers left and right and track how many zeros exist inside the window. Expand the window by moving right. When more than one zero appears, shrink the window by moving left until only one zero remains. Since deleting one element effectively allows one zero inside the window, the maximum valid window length minus one represents the answer. The array is scanned once, making this approach linear and memory efficient.

Approach 2: Prefix Sum and Single Pass (O(n) time, O(n) space)

This method precomputes consecutive runs of ones using prefix-style arrays. One array stores the number of consecutive 1s ending at each index from the left, while another stores consecutive 1s starting from each index from the right. When a 0 appears, you simulate deleting it by combining the left and right counts: left[i-1] + right[i+1]. This effectively merges two blocks of ones separated by a zero. The algorithm performs a single pass to build the arrays and another to compute the best merge. It uses extra memory but clearly demonstrates the structure of the problem using ideas similar to dynamic programming over an array.

Recommended for interviews: The sliding window solution is what interviewers typically expect. It shows you understand how to maintain constraints dynamically while scanning the array once. The prefix approach demonstrates solid reasoning about prefix states and segment merging, but the sliding window version is simpler, uses constant space, and is easier to implement under interview pressure.

Approach 1: Sliding Window with Variables

This approach uses a sliding window technique with variables to keep track of the count of consecutive 1's before and after a zero. The main idea is to iterate through the array, and whenever you encounter more than one zero, calculate the length of 1's that can be formed by deleting the previous zero, update maximum length as needed, and reset counts.

The C solution iterates through the array and calculates the length of subarrays of 1's using counters. It uses variables to keep track of the length before and after a zero, and updates the maximum length as needed. Edge cases are handled by checking if the current maximum length equals the size of the array, indicating every element is 1 and one must be deleted.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), as we iterate through the array once.
Space Complexity: O(1), as no additional space is used proportional to input size.

Try this approach in the editor →

Approach 2: Prefix Sum and Single Pass

This approach utilizes prefix sums to keep a cumulative count of 1's encountered and calculates lengths avoiding excessive recalculations. Two arrays store the prefix sum of 1's up to the current element and from the current element to the end, respectively. A single pass is then made to compute the maximum length by checking possible deletions at each zero.

This C solution efficiently constructs a prefix and suffix table with cumulative counts of consecutive 1's. With these, every possible 0 is evaluated by checking adjacent blocks, optimizing overall calculations.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), each element is processed three independent times.
Space Complexity: O(n), proportional to input due to prefix and suffix arrays.

Try this approach in the editor →

Approach 3: Enumeration

We can enumerate each position i to be deleted, then calculate the number of consecutive 1s on the left and right, and finally take the maximum value.

Specifically, we use two arrays left and right of length n+1, where left[i] represents the number of consecutive 1s ending with nums[i-1], and right[i] represents the number of consecutive 1s starting with nums[i].

The final answer is max_{0 leq i < n} {left[i] + right[i+1]}.

The time complexity is O(n), and the space complexity is O(n). Where n is the length of the array nums.

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Approach 4: Two Pointers

The problem is actually asking us to find the longest subarray that contains at most one 0. The remaining length after deleting one element from this subarray is the answer.

Therefore, we can use two pointers j and i to point to the left and right boundaries of the subarray, initially j = 0, i = 0. In addition, we use a variable cnt to record the number of 0s in the subarray.

Next, we move the right pointer i. If nums[i] = 0, then cnt is incremented by 1. When cnt > 1, we need to move the left pointer j until cnt leq 1. Then, we update the answer, i.e., ans = max(ans, i - j). Continue to move the right pointer i until i reaches the end of the array.

The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Approach 5: Two Pointers (Optimization)

In Solution 2, we move the left pointer in a loop until cnt leq 1. Since the problem asks for the longest subarray, it means we don't need to reduce the length of the subarray. Therefore, if cnt \gt 1, we only move the left pointer once, and the right pointer continues to move to the right. This ensures that the length of the subarray does not decrease.

Finally, the answer we return is n - l - 1, where l is the position of the left pointer.

The time complexity is O(n), where n is the length of the array nums. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Rust

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Sliding Window with Variables

Time Complexity: O(n), as we iterate through the array once.
Space Complexity: O(1), as no additional space is used proportional to input size.

Prefix Sum and Single Pass

Time Complexity: O(n), each element is processed three independent times.
Space Complexity: O(n), proportional to input due to prefix and suffix arrays.

Enumeration—
Two Pointers—
Two Pointers (Optimization)—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Sliding Window with VariablesO(n)O(1)Best general solution. Optimal for interviews and large arrays due to constant space.
Prefix Sum and Single PassO(n)O(n)Useful when analyzing contiguous segments or when prefix information simplifies reasoning.

Video Solution

Longest Subarray of 1's After Deleting One Element- Leetcode 1493 - Python • TechError • 8,139 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Longest Subarray of 1's After Deleting One Element easy or hard?
This problem is rated Medium on LeetCode because it requires recognizing the sliding window pattern and handling the single-deletion constraint correctly. Once the idea of allowing at most one zero in the window is understood, the implementation becomes straightforward.
Longest Subarray of 1's After Deleting One Element Python/Java solution
Python and Java implementations typically use the same sliding window logic with two pointers and a zero counter. Iterate through the array, update the window boundaries when more than one zero appears, and keep track of the maximum length. The algorithm runs in O(n) time and constant space in both languages.
How to solve Longest Subarray of 1's After Deleting One Element in O(n)?
Use a sliding window that allows at most one zero in the current range. Move the right pointer through the array while counting zeros. If more than one zero appears, move the left pointer forward until the window becomes valid again. Track the maximum window length and subtract one to account for the mandatory deletion.
What is the best approach for Longest Subarray of 1's After Deleting One Element?
The sliding window approach is the most efficient and commonly expected solution. Maintain a window that contains at most one zero and expand it using two pointers. When the window contains more than one zero, move the left pointer until the constraint is satisfied again. This produces the longest valid window in O(n) time and O(1) space.
Is Longest Subarray of 1's After Deleting One Element asked at Google/Amazon/Meta?
Variants of this problem appear in interviews at companies like Amazon, Google, and Meta because it tests sliding window reasoning on binary arrays. Interviewers use it to evaluate whether candidates can manage window constraints and compute optimal subarray lengths efficiently.
What data structure is used in Longest Subarray of 1's After Deleting One Element?
The core solution uses a two-pointer sliding window over an array. Only integer counters and indices are required, so no additional data structures such as hash maps or stacks are necessary for the optimal implementation.
What is the time complexity of Longest Subarray of 1's After Deleting One Element?
The optimal solution runs in O(n) time because the array is scanned once using two pointers. Each element enters and leaves the sliding window at most one time. The space complexity is O(1) since only a few variables are used to track pointers and zero counts.

Ready to solve this problem?

Practice Longest Subarray of 1's After Deleting One Element with our built-in code editor and test cases.

Practice on FleetCode