Skip to content

Commit f8ae9e1

Browse files
Leetcode 1493 answer
1 parent f481bd3 commit f8ae9e1

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Leetcode/Leetcode_1493.py

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
"""
2+
Problem: Longest Subarray of 1's After Deleting One Element
3+
4+
Approach: Sliding Window
5+
6+
We maintain a window that contains at most ONE zero.
7+
Why? Because we are allowed to delete one element.
8+
9+
So if the window has:
10+
- 0 zeros → all 1's → we must delete one → length = window_size - 1
11+
- 1 zero → delete that zero → remaining all 1's
12+
13+
Hence, answer = r - l
14+
"""
15+
16+
class Solution:
17+
# ----------------------------------------
18+
# VERSION 1: Using WHILE loop
19+
# ----------------------------------------
20+
def longestSubarray_while(self, nums):
21+
l = 0
22+
r = 0
23+
count_0 = 0 # count of zeros in window
24+
ans = 0
25+
26+
while r < len(nums):
27+
# Step 1: Expand window
28+
if nums[r] == 0:
29+
count_0 += 1
30+
31+
# Step 2: Shrink window if more than 1 zero
32+
while count_0 > 1:
33+
if nums[l] == 0:
34+
count_0 -= 1
35+
l += 1
36+
37+
# Step 3: Update answer
38+
# r - l instead of (r - l + 1) because we must delete one element
39+
ans = max(ans, r - l)
40+
41+
r += 1
42+
43+
return ans
44+
45+
# ----------------------------------------
46+
# VERSION 2: Using FOR loop (Recommended)
47+
# ----------------------------------------
48+
def longestSubarray_for(self, nums):
49+
l = 0
50+
count_0 = 0
51+
ans = 0
52+
53+
for r in range(len(nums)):
54+
# Step 1: Expand window
55+
if nums[r] == 0:
56+
count_0 += 1
57+
58+
# Step 2: Shrink window if more than 1 zero
59+
while count_0 > 1:
60+
if nums[l] == 0:
61+
count_0 -= 1
62+
l += 1
63+
64+
# Step 3: Update answer
65+
ans = max(ans, r - l)
66+
67+
return ans
68+
69+
70+
# ----------------------------------------
71+
# 🔍 Example Usage (for testing locally)
72+
# ----------------------------------------
73+
if __name__ == "__main__":
74+
sol = Solution()
75+
76+
nums = [1, 1, 0, 1]
77+
78+
print("While Loop Version:", sol.longestSubarray_while(nums))
79+
print("For Loop Version:", sol.longestSubarray_for(nums))

0 commit comments

Comments
 (0)