#1493
Longest Subarray of 1's After Deleting One Element
MediumArrayDynamic ProgrammingSliding WindowSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal approach uses a sliding window technique to maintain a window that contains at most one zero. This way, we can efficiently find the longest subarray of 1's after deleting one element.
⚙️
Algorithm
5 steps- 1Step 1: Initialize two pointers (left and right) and a variable to count zeros.
- 2Step 2: Expand the right pointer to include elements in the window until we encounter more than one zero.
- 3Step 3: If the count of zeros exceeds one, move the left pointer to shrink the window until we have at most one zero.
- 4Step 4: Calculate the length of the current valid window and update the maximum length.
- 5Step 5: Return the maximum length found.
solution.py13 lines
1def longestSubarray(nums):
2 left = 0
3 max_length = 0
4 zero_count = 0
5 for right in range(len(nums)):
6 if nums[right] == 0:
7 zero_count += 1
8 while zero_count > 1:
9 if nums[left] == 0:
10 zero_count -= 1
11 left += 1
12 max_length = max(max_length, right - left)
13 return max_lengthℹ
Complexity note: The time complexity is O(n) because we traverse the array with two pointers, each moving at most n times, leading to a linear scan.
- 1Using a sliding window allows us to efficiently manage the count of zeros.
- 2We can find the longest subarray by adjusting the window size dynamically.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.