DSA
Longest Subarray of 1's After Deleting One Element
Sliding Window approach. Optimal — Time O(n), Space O(1).
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.
Sliding Window#
Because we must delete exactly one element, the best we can do is keep a window that contains at most one zero — that zero is the element we "delete". Use two pointers (start, end) to maintain this window: expand end freely, and whenever the window accumulates more than one zero, shrink from the left by advancing start until only one zero remains. The length of the window minus 1 (to account for the mandatory deletion) gives the count of 1s; tracking the maximum across all valid windows gives the answer. Note that end - start (not end - start + 1) already accounts for the deletion since we never count the deleted zero.
- One zero is allowed in window, since we can delete it.
- As soon as you discover second zero, shift the zero
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int n = nums.size();
int start = 0;
int zeroCount = 0;
int maxLen = INT_MIN;
for(int end = 0; end < n; end++){
if(nums[end] == 0){
zeroCount++;
}
while(zeroCount > 1){
if(nums[start]==0)
zeroCount--;
start++;
}
maxLen = max(maxLen, end-start);
}
if(maxLen == INT_MIN)
return 0;
return maxLen;
}
};
Time Complexity: O(n)
Space Complexity: O(1)