question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
longest-subarray-of-1s-after-deleting-one-element | Sliding Window approach | Python / JS Solution | sliding-window-approach-python-js-soluti-cxxy | Hello Tenno Leetcoders, \n\nFor this problem, we are given a binary array nums, you should delete one element from it.\n\nReturn the size of the longest non-emp | TFDLeeter | NORMAL | 2023-07-05T01:43:30.575362+00:00 | 2023-07-05T01:43:30.575388+00:00 | 805 | false | Hello **Tenno Leetcoders**, \n\nFor this problem, we are given a binary array nums, you should delete one element from it.\n\nReturn the size of the longest non-empty subarray containing only 1\'s in the resulting array. Return 0 if there is no such subarray.\n\n#### Explanation\n\nThis problem, We are given a binary array nums, where each element can be either 0 or 1. Our main goal is to `delete exactly one element` from the array in order to obtain the longest possible subarray consisting only of 1\'s. We need to determine the size (length) of this longest subarray.\n\nSince the problem has asked us to remove at most one element from the subarray, we can set `k = 1` to ensure that when using `sliding window` approach, we are only removing at most one element while finding the longest subarray consisting only of `1\'s`. This will allow us to handle the scenario where we need to delete a single element to maximize the length of the subarray.\n\nThus, the main idea behind this solution is to use a sliding window approach to find the longest subarray consisting of only 1s while considering the removal of at most one element. When `k` becomes negative, this represents that we have encountered more `0s` than allowed. Therefore, we shrink the window from the left side by moving `left` pointer by 1\n\nAfter each movement right pointer, we will update max length to keep track of the maximum length of the subarray found so far.\n\n- Initialize:\n\n 1) left = 0 to represent the start of the sliding window\n \n 2) k = 1 to represents we can only remove at most one element from the subarray\n \n 3) max length = 0 to help store the length of the longest subarray found\n \n- Traverse through nums till the end of the nums array\n\n 1) If we encounter a 0 at our current element, we decrement k by 1 \n \n 2) Once k becomes negative, this means we have encountered more 0s than allowed (k=1) \n \n - If `nums[left]` is 0, we increment k by 1 to remove a zero from the current window\n \n - We then shrink the window by moving left pointer to the right until k becomes a non negative\n \n \n \n 3) Update max length if the current subarray length is greater than the previous max length\n \n \n 4) return max length as this represents the longest subarray consisting only of 1s after removing at most one element\n\n# Code\n**Python**\n\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n\n left = 0\n k = 1\n max_length = 0\n\n for right in range(len(nums)):\n if nums[right] == 0: k -=1\n\n while k < 0:\n if nums[left] == 0: k+=1\n left += 1\n max_length = max(max_length, right - left)\n \n return max_length\n```\n\n**JavaScript**\n\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n let left = 0\n let k = 1\n let maxLength = 0\n\n for(let right = 0 ; right < nums.length; right++){\n if (nums[right] === 0) k-=1\n\n while(k < 0){\n if (nums[left] === 0) k+=1\n left += 1\n }\n\n maxLength = Math.max(maxLength, right - left)\n }\n return maxLength\n};\n```\n \n### Time Complexity: O(n)\n### Space Complexity: O(1)\n\n \n***Warframe\'s Darvo wants you to upvote this post \uD83D\uDE4F\uD83C\uDFFB \u2764\uFE0F\u200D\uD83D\uDD25***\n\n | 11 | 0 | ['Sliding Window', 'Python3', 'JavaScript'] | 3 |
longest-subarray-of-1s-after-deleting-one-element | Dynamic Programming Approach O(n) time, O(1) space with Explanation (C++) | dynamic-programming-approach-on-time-o1-v292z | Most of the solutions provided in discussion seems to be using sliding window approach.\nHere I povided a simple DP approach with same time/space complexity. Th | szzzwno123 | NORMAL | 2020-06-27T17:59:05.013013+00:00 | 2020-06-27T18:01:24.201427+00:00 | 876 | false | Most of the solutions provided in discussion seems to be using sliding window approach.\nHere I povided a simple DP approach with same time/space complexity. This is very close to LC 196 - House Robber\n\nDefine: \nD[i] := longest subarray ends at nums[i] with all ones, with one deletion used\nN[i] := longest subarray ends at nums[i] with all ones, with no deletion used\n\nThen we can easily see the transisition as:\n1). when nums[i] == 0:\n\tD[i] = N[i-1];\n\tN[i] = 0;\n2). when nums[i] == 1\n D[i] = max(D[i-1] + 1, N[i-1]);\n N[i] = N[i-1] + 1;\n \nWith simple rolling method, space complexity can be reduced to O(1). \nExample code:\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int D = 0;\n int N = nums[0] == 1 ? 1 : 0;\n \n int res = INT_MIN;\n for (int i = 1; i < nums.size(); i++){\n if (nums[i] == 0){\n D = N;\n N = 0;\n }else{\n D = max(D + 1, N);\n N = N + 1;\n }\n \n res = max(res, D);\n }\n \n return res == INT_MIN ? 0 : res;\n }\n};\n``` | 11 | 0 | [] | 4 |
longest-subarray-of-1s-after-deleting-one-element | ✅ C++ || Beginner [Easy To Understand] || Sliding Window | c-beginner-easy-to-understand-sliding-wi-tcmz | Logic Simplified\n\n while(window exists)\n {\n if(current is 1)\n Add 1 to window\n else // means current is 0[bcoz array is bin | 99NotOut_half_dead | NORMAL | 2021-09-17T15:15:24.216119+00:00 | 2021-09-17T15:21:17.754663+00:00 | 1,006 | false | # ***Logic Simplified***\n```\n while(window exists)\n {\n if(current is 1)\n Add 1 to window\n else // means current is 0[bcoz array is binary]\n {\n Making space for adding 0 element if required : \n this while loop may or may not run depending upon frequency of 0 in current window\n\n while(frequency of 0 in window is 1)\n shrink window from front\n\n add (current = 0) to window\n }\n\n // here current window size is taken as (right - left) instead of (right - left + 1) because we have to delete a element as mentioned in statement\n max_len = max(max_len , right - left);\n }\n return max_len;\n\t\nTime : O(N)\nSpace : O(1)\n```\n# ***Code***\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int> &nums) {\n vector<int> map(2);\n // map[0] holds count for 0\n // map[1] holds count for 1\n \n int left = 0 , right = 0;\n int max_len = 0;\n \n while(right != nums.size())\n {\n if(nums[right] == 1)\n map[1]++;\n else\n {\n // Making space for addition of 0 in window if required\n while(map[0])\n {\n // shrinking from front\n map[nums[left]]--;\n left++;\n }\n \n map[0]++;\n }\n // window size : (righ - left) instead of (right - left + 1)\n // because we have to delete one element as mentioned in problem statment\n max_len = max(max_len , right - left);\n ++right;\n }\n return max_len;\n }\n};\n```\n# ***If you liked the solution , Please Upvote :)*** | 10 | 0 | ['C'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | O(n) Solution | on-solution-by-malikdinar-30e9 | Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n let co | malikdinar | NORMAL | 2023-07-05T07:22:36.697868+00:00 | 2023-07-05T07:24:17.184582+00:00 | 948 | false | # Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n let count = 0;\n let array = []\n for(let i = 0;i<nums.length;i++){\n if(nums[i]==1){\n count++\n }else {\n array.push(count)\n count = 0\n }\n }\n if(count>0){\n array.push(count)\n }\n if(nums.length === count) return count-1\n\n let result = array[0]+array[1]\n for(let j=1;j<array.length-1;j++){\n if(array[j]+array[j+1] > result){\n result = array[j]+array[j+1] \n }\n }\n\n return result\n};\n``` | 9 | 0 | ['Array', 'JavaScript'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Sliding Window | Easy to understand | C++ | sliding-window-easy-to-understand-c-by-w-2zt1 | Intuition\nMaintain the longest subarray window with at most 1 "0" in it.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThis is a | warrior0331 | NORMAL | 2023-07-05T05:17:41.442937+00:00 | 2023-07-05T05:17:41.442970+00:00 | 1,840 | false | # Intuition\nMaintain the longest subarray window with at most 1 "0" in it.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis is a variable sized sliding window problem in which the window size depends on the number of "0" in the window. If we find the maximum sized window with at most one "0" then it would be our window which could contain the answer.\n\nNormal sliding window algorithm in which we first make the window with given constraint and then after we slide and find answer. \n\nMake variables i->frontend, j->rearend, count0->number of "0" currently, ans->our answer with maximum window size.\n\nTo make the initial window check if count0 is still 0 if yes we check if the number at rear end is 0 if yes then count0 is increased.\nNow if count0 is not 0, that means we have achieved the window with one "0" so now, if at rear end there is "1" we can still increase the window size otherwise we have to slide the window, so first we find the answer as the maximum of previous answer and current window size-2 then we slide, also for sliding if the number at front end is "0" then we decrase the count0 value and then slide.\n\nAt last after the loop is over, we again find the answer as maximum of previous answer and current window size, this is for the case when none of the time window was slided.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n=nums.size();\n if(n==0 or n==1) return 0;\n int i=0,j=0,count0=0,ans=0;\n while(j<n){\n if(count0==0){\n if(nums[j]==0) count0++;\n j++;\n }\n else{\n if(nums[j]==1) j++;\n else{\n ans=max(ans,j-i-1);\n if(nums[i]==0) count0--;\n i++;\n }\n }\n }\n ans=max(ans,j-i-1); \n return ans;\n }\n};\n``` | 9 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | ✅ One Line Solution | one-line-solution-by-mikposp-xqkt | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)Code #1.1 - One LineTime complexity: O(n). Space com | MikPosp | NORMAL | 2025-02-17T17:02:55.175734+00:00 | 2025-02-17T17:02:55.175734+00:00 | 878 | false | (Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)
# Code #1.1 - One Line
Time complexity: $$O(n)$$. Space complexity: $$O(n)$$.
```python3
class Solution:
def longestSubarray(self, a: List[int]) -> int:
return max(map(add,(f:=lambda a:[0,*accumulate(a,lambda q,v:(q+1)*v)])(a),f(a[::-1])[-2::-1]))
```
# Code #1.2 - Unwrapped
```python3
class Solution:
def longestSubarray(self, a: List[int]) -> int:
f = lambda a:[0,*accumulate(a,lambda q,v:(q+1)*v)]
l, r = f(a), f(a[::-1])[::-1]
return max(map(add, l, r[1:]))
```
(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better) | 8 | 2 | ['Array', 'Prefix Sum', 'Python', 'Python3'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Beats 💯; Sliding Window Aproach ; ✅ Easy to Understand✅ | beats-sliding-window-aproach-easy-to-und-3m48 | Code | 20250409.hema260706 | NORMAL | 2025-01-09T07:34:38.024955+00:00 | 2025-01-09T07:34:38.024955+00:00 | 1,466 | false | 
# Code
```cpp []
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int left = 0, maxLength = 0, zeroCount = 0;
for (int right = 0; right < nums.size(); ++right) {
if (nums[right] == 0) {
zeroCount++;
}
while (zeroCount > 1) {
if (nums[left] == 0) {
zeroCount--;
}
left++;
}
maxLength = max(maxLength, right - left);
}
return maxLength;
}
};
```
```python []
class Solution:
def longestSubarray(self, nums):
left, zeroCount, maxLength = 0, 0, 0
for right in range(len(nums)):
if nums[right] == 0:
zeroCount += 1
while zeroCount > 1:
if nums[left] == 0:
zeroCount -= 1
left += 1
maxLength = max(maxLength, right - left)
return maxLength
```
```Java []
class Solution {
public int longestSubarray(int[] nums) {
int left = 0, zeroCount = 0, maxLength = 0;
for (int right = 0; right < nums.length; ++right) {
if (nums[right] == 0) {
zeroCount++;
}
while (zeroCount > 1) {
if (nums[left] == 0) {
zeroCount--;
}
left++;
}
maxLength = Math.max(maxLength, right - left);
}
return maxLength;
}
}
```

| 8 | 1 | ['Sliding Window', 'C++', 'Java', 'Python3'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | very simple easy implementation only 1 loop with no extra space, best solution | very-simple-easy-implementation-only-1-l-5e6l | Intuition\nThe problem requires finding the length of the longest subarray containing only 1s after flipping at most one 0 to 1. One approach could be to utiliz | Have-To-Do-Every-Thing | NORMAL | 2024-04-08T14:06:42.478836+00:00 | 2024-04-08T17:15:36.018942+00:00 | 1,440 | false | # Intuition\nThe problem requires finding the length of the longest subarray containing only 1s after flipping at most one 0 to 1. One approach could be to utilize a sliding window technique to keep track of the longest subarray with only one zero. Once the zero occur the track that we made till now we compare with previous window and current last window.\n\n# Approach\n1. Initialize variables `prevWindow`, `currWindow`, and `max_length` to 0.\n2. Iterate through the elements of the `nums` vector.\n3. If the current element is 0, it marks the end of the current subarray. Update `max_length` with the maximum length found so far (`prevWindow + currWindow`).\n4. Update `prevWindow` to `currWindow`, and reset `currWindow` to 0 to start counting the length of the next subarray.\n5. If the current element is 1, increment `currWindow` to count the length of the current subarray.\n6. After the loop, if `currWindow` equals the size of the `nums` vector, return `currWindow - 1`.\n7. Update `max_length` with the maximum length found so far (`prevWindow + currWindow`) and return `max_length`.\n\n# Complexity\n- Time complexity: O(n), where n is the size of the `nums` vector. We iterate through the array once.\n- Space complexity: O(1), as we use only a constant amount of extra space regardless of the input size.\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int prevWindow = 0;\n int currWindow = 0;\n int max_length = 0;\n \n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] == 0) {\n max_length = max(max_length, prevWindow + currWindow);\n prevWindow = currWindow;\n currWindow = 0;\n } else {\n currWindow++;\n }\n }\n\n if (currWindow == nums.size()) {\n return currWindow - 1;\n }\n\n max_length = max(max_length, prevWindow + currWindow);\n return max_length;\n }\n};\n\n```\n``` Python []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n prevWindow = 0\n currWindow = 0\n max_length = 0\n\n for num in nums:\n if num == 0:\n max_length = max(max_length, prevWindow + currWindow)\n prevWindow = currWindow\n currWindow = 0\n else:\n currWindow += 1\n\n if currWindow == len(nums):\n return currWindow - 1\n\n max_length = max(max_length, prevWindow + currWindow)\n return max_length\n```\n``` Java []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int prevWindow = 0;\n int currWindow = 0;\n int max_length = 0;\n \n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0) {\n max_length = Math.max(max_length, prevWindow + currWindow);\n prevWindow = currWindow;\n currWindow = 0;\n } else {\n currWindow++;\n }\n }\n\n if (currWindow == nums.length) {\n return currWindow - 1;\n }\n\n max_length = Math.max(max_length, prevWindow + currWindow);\n return max_length;\n }\n};\n```\n``` C []\n#include <stdio.h>\n\nint longestSubarray(int* nums, int numsSize) {\n int prevWindow = 0;\n int currWindow = 0;\n int max_length = 0;\n \n for (int i = 0; i < numsSize; i++) {\n if (nums[i] == 0) {\n if (prevWindow + currWindow > max_length) {\n max_length = prevWindow + currWindow;\n }\n prevWindow = currWindow;\n currWindow = 0;\n } else {\n currWindow++;\n }\n }\n\n if (currWindow == numsSize) {\n return currWindow - 1;\n }\n\n if (prevWindow + currWindow > max_length) {\n max_length = prevWindow + currWindow;\n }\n\n return max_length;\n}\n```\n``` JavaScript []\nvar longestSubarray = function(nums) {\n let prevWindow = 0;\n let currWindow = 0;\n let max_length = 0;\n\n for (let i = 0; i < nums.length; i++) {\n if (nums[i] === 0) {\n max_length = Math.max(max_length, prevWindow + currWindow);\n prevWindow = currWindow;\n currWindow = 0;\n } else {\n currWindow++;\n }\n }\n\n if (currWindow === nums.length) {\n return currWindow - 1;\n }\n\n max_length = Math.max(max_length, prevWindow + currWindow);\n return max_length;\n};\n``` \n``` C# []\nusing System;\n\npublic class Solution {\n public int LongestSubarray(int[] nums) {\n int prevWindow = 0;\n int currWindow = 0;\n int max_length = 0;\n \n for (int i = 0; i < nums.Length; i++) {\n if (nums[i] == 0) {\n max_length = Math.Max(max_length, prevWindow + currWindow);\n prevWindow = currWindow;\n currWindow = 0;\n } else {\n currWindow++;\n }\n }\n\n if (currWindow == nums.Length) {\n return currWindow - 1;\n }\n\n max_length = Math.Max(max_length, prevWindow + currWindow);\n return max_length;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n prevWindow = 0\n currWindow = 0\n max_length = 0\n\n for num in nums:\n if num == 0:\n max_length = max(max_length, prevWindow + currWindow)\n prevWindow = currWindow\n currWindow = 0\n else:\n currWindow += 1\n\n if currWindow == len(nums):\n return currWindow - 1\n\n max_length = max(max_length, prevWindow + currWindow)\n return max_length\n``` | 8 | 0 | ['Array', 'Math', 'Sliding Window', 'Counting', 'Prefix Sum', 'Python', 'C++', 'Java', 'JavaScript', 'C#'] | 3 |
longest-subarray-of-1s-after-deleting-one-element | Python 3 || 6 lines, w/ explanation || T/S: 99% / 72% | python-3-6-lines-w-explanation-ts-99-72-otfr6 | Here\'s how the code works:\n\n\n1. We check whether there are are either only 1s or only 0s innums. If either case is true, we are done.\n\n1. We use groupby | Spaulding_ | NORMAL | 2023-07-05T06:44:13.361835+00:00 | 2024-06-04T20:33:14.105650+00:00 | 610 | false | Here\'s how the code works:\n\n\n1. We check whether there are are either only 1s or only 0s in`nums`. If either case is true, we are done.\n\n1. We use `groupby` to parse `nums` into groups of like-digit groups. For example:\n```\n [1,1,0,0,1,1,1,0,1] --> [[1,1],[0,0],[1,1,1],[0],[1]]\n```\n 3. We eliminate all *single-zero* groups, and map the remaining groups to their respective sums:\n```\n [[1,1],[0,0],[1,1,1],[0],[1]] --> [2, 0, 3, 1]\n```\n4. We use `pairwise` to find our answer:\n```\n [2, 0, 3, 1] --> [(2, 0), (0, 3), (3, 1)]\n --> max(2+0, 0+3, 3+1)\n --> answer is 4\n```\n```\n```\nHere\'s the code:\n```\nfrom itertools import groupby\n\nclass Solution:\n def longestSubarray(self, nums: list[int]) -> int:\n\n if 1 not in nums: return 0 # 1)\n if 0 not in nums: return len(nums)-1\n\n arr = [list(g) for k, g in groupby(nums)] # 2)\n\n arr = [sum(x) for x in arr if x!= [0]] # 3)\n if len(arr) == 1: return arr[0]\n \n return max(map(sum,pairwise(arr))) # 4)\n```\n[https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/submissions/1277816064/](https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/submissions/1277816064/)\n\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~`len(nums)`. | 8 | 0 | ['Python3'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Easiest Java Solution with 2 pointers | easiest-java-solution-with-2-pointers-by-lmjy | \nclass Solution {\n public int longestSubarray(int[] nums) {\n int prev = 0;\n int curr = 0;\n int max = 0;\n for(int i = 0; i < | pulkit269 | NORMAL | 2020-10-11T07:00:24.506847+00:00 | 2020-10-11T07:00:24.506897+00:00 | 754 | false | ```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int prev = 0;\n int curr = 0;\n int max = 0;\n for(int i = 0; i < nums.length; ++i){\n if(nums[i] == 1){\n curr++;\n if(curr + prev > max) max = curr + prev;\n }\n else if(nums[i] == 0){\n prev = curr;\n curr = 0;\n }\n }\n if(max == nums.length) return max - 1;\n else return max;\n }\n}\n``` | 8 | 1 | ['Java'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Clean Python 3, O(N)/O(1) time/space | clean-python-3-ono1-timespace-by-lenchen-nv7y | Use two states to maintain consecutive 1\'s after meeting a 0\nnew for a new consecutive 1s.\nold for making that 0 to be deleted.\nThen just find the maximum i | lenchen1112 | NORMAL | 2020-06-27T16:01:46.043742+00:00 | 2021-02-09T07:53:30.862293+00:00 | 659 | false | Use two states to maintain consecutive 1\'s after meeting a 0\n`new` for a new consecutive 1s.\n`old` for making that 0 to be deleted.\nThen just find the maximum in `old`.\nTime: `O(N)`\nSpace: `O(1)`\n```\n```python\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n new, old, m = 0, 0, 0\n for num in nums:\n if num == 1:\n old, new = old + 1, new + 1\n else:\n old, new = new, 0\n m = max(m, old)\n return min(m, len(nums) - 1)\n```\n``` | 8 | 1 | [] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Best Solution for Arrays, DP 🚀 in C++, Python and Java || 100% working | best-solution-for-arrays-dp-in-c-python-u1tqn | Intuition💡 The problem asks for the longest subarray where at most one zero is removed. My first thought is to use the sliding window technique to keep track of | BladeRunner150 | NORMAL | 2025-01-08T07:15:47.843287+00:00 | 2025-01-08T07:15:47.843287+00:00 | 640 | false | # Intuition
💡 The problem asks for the longest subarray where at most one zero is removed. My first thought is to use the **sliding window technique** to keep track of valid subarrays.
# Approach
1. 🪟 Use two pointers (`l` and `r`) to represent a sliding window.
2. 🧮 Keep a count of zeros in the current window.
3. 🚨 If there are more than one zero, move the left pointer (`l`) to shrink the window until it's valid again.
4. 📏 Track the maximum window size as the result.
# Complexity
- **Time complexity:** $$O(n)$$, where $$n$$ is the size of the array.
- **Space complexity:** $$O(1)$$.
# Code
```cpp []
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int l = 0, max1 = 0, zero = 0;
for (int r = 0; r < nums.size(); r++) {
if (nums[r] == 0) zero++;
while (zero > 1) {
if (nums[l] == 0) zero--;
l++;
}
max1 = max(max1, r - l);
}
return max1;
}
};
```
```python []
class Solution:
def longestSubarray(self, nums):
l, max1, zero = 0, 0, 0
for r in range(len(nums)):
if nums[r] == 0:
zero += 1
while zero > 1:
if nums[l] == 0:
zero -= 1
l += 1
max1 = max(max1, r - l)
return max1
```
```java []
class Solution {
public int longestSubarray(int[] nums) {
int l = 0, max1 = 0, zero = 0;
for (int r = 0; r < nums.length; r++) {
if (nums[r] == 0) zero++;
while (zero > 1) {
if (nums[l] == 0) zero--;
l++;
}
max1 = Math.max(max1, r - l);
}
return max1;
}
}
```
<img src="https://assets.leetcode.com/users/images/7b864aef-f8a2-4d0b-a376-37cdcc64e38c_1735298989.3319144.jpeg" alt="upvote" width="150px">
# Connect with me on LinkedIn for more insights! 🌟 Link in bio | 7 | 0 | ['Array', 'Dynamic Programming', 'Python', 'C++', 'Java', 'Python3'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Optimal solution without sliding window | optimal-solution-without-sliding-window-5z4ph | Complexity\n- Time complexity:\nO(n) time\n\n- Space complexity:\nO(1) space\n\n# Code\n\n// O(n) time\n// O(1) space\nfunction longestSubarray(nums: number[]): | kazinov | NORMAL | 2023-05-24T08:12:38.175914+00:00 | 2023-05-24T08:12:38.175951+00:00 | 523 | false | # Complexity\n- Time complexity:\nO(n) time\n\n- Space complexity:\nO(1) space\n\n# Code\n```\n// O(n) time\n// O(1) space\nfunction longestSubarray(nums: number[]): number {\n let maxLength = 0;\n let count = 0;\n let onesBefore = 0;\n for(const num of nums) {\n if(num) {\n count++;\n maxLength = Math.max(maxLength, count + onesBefore);\n } else {\n onesBefore = count;\n count = 0;\n }\n }\n return Math.min(maxLength, nums.length - 1);\n};\n``` | 7 | 0 | ['TypeScript'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | C++ Sliding Window (+ Cheat Sheet) | c-sliding-window-cheat-sheet-by-lzl12463-he1v | See my latest update in repo LeetCode\n## Solution 1.\n\nprev2 and prev are the indexes of the non-one values we\'ve seen most recently during scanning.\n\n\npr | lzl124631x | NORMAL | 2021-10-05T07:58:21.665441+00:00 | 2021-10-05T07:58:21.665469+00:00 | 3,247 | false | See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1.\n\n`prev2` and `prev` are the indexes of the non-one values we\'ve seen most recently during scanning.\n\n```\nprev2 prev i\n 0 1 1 1 0 1 1 1 0 \n```\n\nIf the array only contains 1, then return `N - 1`.\nOtherwise, the answer is the maximum of `i - prev2 - 2`.\n\n```cpp\n// OJ: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int longestSubarray(vector<int>& A) {\n int N = A.size(), prev2 = -1, prev = -1, ans = 0;\n for (int i = 0; i <= N; ++i) {\n if (i < N && A[i] == 1) continue;\n if (i == N && prev == -1) return N - 1;\n if (prev != -1) ans = max(ans, i - prev2 - 2);\n prev2 = prev;\n prev = i;\n }\n return ans;\n }\n};\n```\n\n## Solution 2. Sliding Window\n\nCheck out "[C++ Maximum Sliding Window Cheatsheet Template!](https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/1175088/C%2B%2B-Maximum-Sliding-Window-Cheatsheet-Template!)"\n\nShrinkable Sliding Window:\n\n```cpp\n// OJ: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int longestSubarray(vector<int>& A) {\n int i = 0, j = 0, N = A.size(), cnt = 0, ans = 0;\n for (; j < N; ++j) {\n cnt += A[j] == 0;\n while (cnt > 1) cnt -= A[i++] == 0;\n ans = max(ans, j - i);\n }\n return ans;\n }\n};\n```\n\nNon-shrinkable Sliding Window:\n\n```cpp\n// OJ: https://leetcode.com/problems/longest-subarray-of-1s-after-deleting-one-element/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int longestSubarray(vector<int>& A) {\n int i = 0, j = 0, N = A.size(), cnt = 0;\n for (; j < N; ++j) {\n cnt += A[j] == 0;\n if (cnt > 1) cnt -= A[i++] == 0;\n }\n return j - i - 1;\n }\n};\n```\n\n | 7 | 0 | [] | 2 |
longest-subarray-of-1s-after-deleting-one-element | [Java] O(n) time, O(1) space with explanation. | java-on-time-o1-space-with-explanation-b-ogl9 | Maintain 2 variables a and c .c- number of continous ones till the current index.\na - number of continous ones with a single zero in between.\nWhenever a one i | hemanthsrinivas | NORMAL | 2020-06-28T08:18:49.700756+00:00 | 2020-07-01T16:33:50.141046+00:00 | 311 | false | Maintain 2 variables a and c .c- number of continous ones till the current index.\na - number of continous ones with a single zero in between.\nWhenever a one is encountered, a and c both are incremented.\nWhenever a zero is encountered, copy the value of c to a and make c = 0.\nEx : 1 0 0 1 1 0 1\t\t\nintially a = 0 , c = 0\n1 - a =1 ,c =1\n0 - a = 1 , c=0\n0 - a = 0 , c = 0\n1 - a = 1 , c = 1\n1 - a = 2 , c = 2\n0 - a = 2 , c = 0\n1 - a = 3, c = 1\nreturn the maximum value of a. \nIf array is all ones, return max - 1.\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int c = 0 ,max = Integer.MIN_VALUE , a = 0;\n boolean check = false;\n for(int i = 0; i<nums.length ;i++)\n {\n if(nums[i] == 1)\n {\n c++;\n a++;\n }\n else \n { \n check = true;\n a = c;\n c = 0;\n }\n max = Math.max(max,a);\n }\n if(!check)\n return max -1;\n return max;\n }\n}\n```\n | 7 | 1 | [] | 0 |
longest-subarray-of-1s-after-deleting-one-element | JavaScript + comments | DP | javascript-comments-dp-by-zhang1pr-g342 | This solution uses dynamic programming to keep track of non-deleted and deleted states.\n\nWe use an array of 2 for each position i for non-deleted state and de | zhang1pr | NORMAL | 2020-06-27T18:32:17.546614+00:00 | 2023-07-11T01:17:58.855669+00:00 | 1,039 | false | This solution uses dynamic programming to keep track of non-deleted and deleted states.\n\nWe use an array of 2 for each position `i` for non-deleted state and deleted state.\n`dp[i][0]` means the longest contiguous 1 to `nums[i]` if we haven\'t deleted one element.\n`dp[i][1]` means the longest contiguous 1 to `nums[i]` if we have deleted one element.\n\nFor example:\nnums[i] - [1, 1, 0, 1, 1, 1, 0]\ndp[i][0] - [1, 2, 0, 1, 2, 3, 0]\ndp[i][1] - [0, 1, 2, 3, 4, 5, 3]\nmax is 5 when we delete 0 at position 2.\n\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n const dp = [...new Array(nums.length)].map(() => new Array(2));\n // Initalize dp[0][0] and max to nums[0]\n // Initalize dp[0][1] to 0 because we have to delete the first element to reach the deleted state\n dp[0] = [nums[0], 0];\n let max = 0;\n \n for (let i = 1; i < nums.length; i++) {\n if (nums[i] == 0) {\n\t // In the case of 0 \n\t // For dp[i][1], delete element 0 and set deleted state to not deleted state of dp[i-1]\n\t // For dp[i][0], set deleted state to 0 because we can\'t delete any more and the longest contigous 1 to element 0 is none\n dp[i][1] = dp[i - 1][0];\n dp[i][0] = 0;\n } else {\n\t // In the case of 1, increment both states by 1 because we don\'t need to worry about deletion\n dp[i][0] = dp[i - 1][0] + 1;\n dp[i][1] = dp[i - 1][1] + 1;\n }\n \n\t// Since we have to delete one element, we only care about max of deleted states\n max = Math.max(dp[i][1], max);\n }\n \n return max;\n};\n```\n\nSince each pair of states only depends on the last pair, we can reduce space complexity from O(n) to O(1) by using only 2 variables for states as well as simplify the logic.\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n let notDeletedState = 0;\n let deletedState = 0;\n let max = 0;\n \n for (const num of nums) {\n if (num == 0) {\n deletedState = notDeletedState;\n notDeletedState = 0;\n } else {\n notDeletedState++; \n deletedState++;\n }\n \n max = Math.max(deletedState, max);\n }\n\n // Max can be the number of elements in this case but we have to delete one element\n // e.g. nums = [1, 1, 1]\n return max == nums.length ? max - 1 : max;\n}; | 7 | 1 | ['Dynamic Programming', 'JavaScript'] | 3 |
longest-subarray-of-1s-after-deleting-one-element | Simple Solution | 3ms | Two Pointer | Java | simple-solution-3ms-two-pointer-java-by-2ziok | \n# Code\njava []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int zeroes = 0;\n int left = 0;\n int result = 0;\n | eshwaraprasad | NORMAL | 2024-09-24T11:46:25.544843+00:00 | 2024-09-24T11:46:25.544875+00:00 | 1,102 | false | \n# Code\n```java []\nclass Solution {\n public int longestSubarray(int[] nums) {\n int zeroes = 0;\n int left = 0;\n int result = 0;\n for(int right = 0; right < nums.length; right++) {\n if(nums[right] == 0) zeroes++;\n\n while(zeroes == 2) {\n int val = nums[left++];\n if(val == 0) zeroes--;\n }\n\n result = Math.max(result, right - left);\n }\n return result;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Binary search on answers | binary-search-on-answers-by-algo_maniac-t2sq | Intuition\n Describe your first thoughts on how to solve this problem. \nWe are given an array of N length which contains only 1\'s and 0\'s. We can observe tha | algo_maniac | NORMAL | 2023-07-06T07:19:08.662632+00:00 | 2023-07-06T07:19:08.662671+00:00 | 234 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe are given an array of N length which contains only 1\'s and 0\'s. We can observe that if we can form a subarray of length k(by deleting 1 or no zeros), then we can also form subarrays of length less than k.\nThis shows that we have a monotonic search space. Hence, we can apply binary search on lengths of subarrays. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe take lo=1 and hi=n and apply binary search on lengths of subarrays. If we find that a solution of subarray exists for length mid(mid=(lo+hi)/2), then we can check for a higher length(as we have to maximize the answer)\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe binary search takes O(log n) time and for checking if there exists answer for a particular length, it takes O(n) time. \n\nSo overall Time Complexity : O(n*log(n))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nNo extra space used.\n\nAuxiliary Space : O(1) \n\n# Code\n```\nclass Solution {\npublic:\n bool check(vector<int>& nums, int n, int len){\n int zero=0;\n for(int i=0; i<len; i++){\n if(nums[i]==0) zero++;\n }\n int f=0;\n if(zero<=1) f=1;\n for(int i=len; i<n; i++){\n if(nums[i]==0) zero++;\n if(nums[i-len]==0) zero--;\n if(zero<=1){\n f=1;\n break;\n }\n }\n return f==1;\n }\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n int lo=1, hi=n;\n int ans=0;\n while(lo<=hi){\n int mid=(lo+hi)/2;\n if(check(nums, n, mid)){\n lo=mid+1;\n ans=mid;\n // cout<<ans<<endl;\n }\n else{\n hi=mid-1;\n }\n }\n return ans-1;\n }\n};\n```\n | 6 | 0 | ['Binary Search', 'C++'] | 2 |
longest-subarray-of-1s-after-deleting-one-element | C++ || SLIDING WINDOW || WITH EXPLANATION | c-sliding-window-with-explanation-by-neh-hn19 | Simple logic of sliding window there are two pointers left and right. We always include the right element and try to get maximum element from left. So while inc | neha0312 | NORMAL | 2023-07-05T03:34:29.618323+00:00 | 2023-07-05T03:34:29.618342+00:00 | 781 | false | Simple logic of sliding window there are two pointers left and right. We always include the right element and try to get maximum element from left. So while including we check if count of zeros in our current window is <=1 . if it is so the length of the window will be (right-left+1) but we will perform 1 deletion if one zero is present then of zero otherwise delete 1. So our curr ans will be (right-left). If the count is greater than 1 we will try to remove left elements so that count becomes 1.\n\n\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int ans=0;\n int n=nums.size();\n int count=0;\n int left=0;\n int right=0;\n while(right<n){\n if(nums[right]==0) count++;\n if(count<=1){\n ans= max(ans,right-left);\n right++;\n }\n else{\n while(count>1){\n if(nums[left]==0) count--;\n left++;\n }\n ans= max(ans,left-right);\n right++;\n }\n \n }\n return ans;\n \n }\n};\n | 6 | 0 | ['C', 'Sliding Window'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | [C++] Solution W/ Explanation | Sliding Window | Two Pointer | c-solution-w-explanation-sliding-window-2v953 | APPROACH :\n\n We need to find the longest subarray with all 1\'s after deleting any one zero.\n The question can be re-phrased as : Find the longest subarray w | Mythri_Kaulwar | NORMAL | 2022-02-14T16:09:58.370564+00:00 | 2022-02-14T16:10:14.415309+00:00 | 692 | false | **APPROACH :**\n\n* We need to find the longest subarray with all 1\'s after deleting any one zero.\n* The question can be re-phrased as : Find the longest subarray with **atmost 1** zero.\n* So we traverse the array with 2 pointers, at any point there\'s only atmost 1 zero in the window.\n* We count the number of zeros encountered after the last zero, if the ```count``` exceeds the ```limit``` (1) (We keep moving the left pointer until we make it less than the ```limit``` and count the longest subarray until then).\n\n**Time Complexity :** O(n)\n\n**Code :**\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n if(n==1) return 0;\n int count = 0, l=0, r=0, limit = 1, maxLen = 0;\n while(r < n){\n if(nums[r] == 0) count++;\n while(count > limit){\n if(nums[l]==0) count--;\n l++;\n }\n maxLen = max(maxLen, r-l);\n r++;\n }\n return maxLen;\n }\n};\n```\n\n**Do upvote if you\'ve found it helpful :)** | 6 | 0 | ['C', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | [Java] Single pass solution, w/ diagram and explanation | java-single-pass-solution-w-diagram-and-c91hu | For every position of 0 in the array we need to find:\n length of the subarray consisting of only 1s, ending just before the current position.\n length of the s | SonicBoomer | NORMAL | 2021-02-23T20:49:27.706103+00:00 | 2021-02-23T20:58:29.397940+00:00 | 415 | false | For every position of `0` in the array we need to find:\n* length of the subarray consisting of only `1`s, ending just before the current position.\n* length of the subarray consisting of only `1`s, starting just after the current position.\n\nThe sum of these lengths is the length of the subarray of `1`s that will be formed if the `0` was removed.\n\nThe required answer is the maximum such length possible. So we\'ll have to figure out such lengths for each position of `0`.\n\nOne key observation is that the right subarray of `1`s for a certain position of `0` will be the left subarray for the *next* position of `0` in the array. With this, we can get the answer in a single pass.\n\nExample:\n\n```text\n0 1 1 1 0 1 1 0 1\n | | | | | |\n ----------- ------ ---\n 3 2 1 <-- lengths of the subarrays of 1s.\n\t\n 0 1 1 1 0 1 1 0 1\n | | |\n (0+3) (3+2) (2+1) <-- sum of left and right subarray lengths (consisting of only 1s) for each position of 0.\n```\n\n```java\nclass Solution {\n public int longestSubarray(int[] nums) {\n int leftLen = 0, rightLen = 0, pos = 0, max = 0;\n \n while (pos < nums.length) {\n //Left subarray increases\n if (nums[pos] == 1) {\n ++pos;\n ++leftLen;\n }\n //0 means we are at the center of a potential answer. Need to find size of the right subarray.\n else if (nums[pos] == 0) {\n rightLen = 0;\n ++pos;\n \n //Find out size of right subarray.\n while (pos < nums.length && nums[pos] == 1) {\n ++pos;\n ++rightLen;\n }\n max = Math.max(max, leftLen + rightLen);\n \n //Position has advanced to the next available \'0\' in array. \n //The previous \'right\' subarray becomes the \'left\' subarray of this new position.\n leftLen = rightLen;\n }\n }\n \n //This means there were only 1s in the array.\n if (leftLen == nums.length)\n max = nums.length - 1;\n \n return max;\n }\n}\n```\n\n**Time Complexity**\n\n`O(N)`. Single pass through the input.\n\n**Space Complexity**\n\n`O(1)`. | 6 | 0 | ['Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Python 3 Faster than 100% Explanation | python-3-faster-than-100-explanation-by-veq55 | \n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n l=len(nums)\n ar=[]\n\t\t\n c=0 # it will count 1\'s\n | anurag_tiwari | NORMAL | 2020-06-27T20:31:25.428595+00:00 | 2020-06-27T20:31:25.428628+00:00 | 1,094 | false | \n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n l=len(nums)\n ar=[]\n\t\t\n c=0 # it will count 1\'s\n su=sum(nums)\n\t\t# if all element are 1\n if su==l:\n return l-1\n\t\t#if all element are 0\n if su==0:\n return su\n\t\t\t\n for i in nums:\n\t\t\t# if 1 increment c\n if i==1:\n c+=1\n else:\n if c==0:\n\t\t\t\t\t# if list is empty or previous element is not 0\n\t\t\t\t\t# if two or more consecutive avoid that condition by pass\n if ar==[] or ar[-1]==0:\n pass\n\t\t\t\t\t# else append c to ar\n else:\n ar.append(c)\n else:\n ar.append(c)\n c=0\n\t\t# if last element of nums is 1 then append c to ar as in the above for loop we can not append \n\t\t#c to ar when i==1 and we have to add the last value of c in ar to get ans \n if nums[-1]==1:\n ar.append(c) \n m=ar[0]\n la=len(ar)\n for i in range(la-1):\n m=max(m,ar[i]+ar[i+1])\n return m | 6 | 0 | ['Python', 'Python3'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | [Swift, C++, Python3] Simple solution with diagram and explanation 0ms 100% faster | swift-c-python3-simple-solution-with-dia-gjrm | Intuition\nCan we use Dynamic Programming to calculate all subarrays lengths? \nLike [1,1,1,1,1,0,1,1] = [1,2,3,4,5,0,1,2].\nBut how can we optimize this and no | evkobak | NORMAL | 2024-12-03T05:51:22.127808+00:00 | 2024-12-03T06:31:09.620716+00:00 | 264 | false | # Intuition\nCan we use Dynamic Programming to calculate all subarrays lengths? \nLike `[1,1,1,1,1,0,1,1]` = `[1,2,3,4,5,0,1,2]`.\nBut how can we optimize this and not check every subarray\'s number from the start before we find `0` and it ends? Can we check from backward? Sure :)\n\n# Approach\n\n\n# Complexity\n- Time complexity: O(N)\n- Space complexity: O(N)\n\n\n\n# Swift Code\n```swift []\nclass Solution {\n func longestSubarray(_ nums: [Int]) -> Int {\n var dp = [0]\n var maximum = 0\n\n for i in 0 ..< nums.count {\n if nums[i] == 1 {\n dp.append(dp[i] + 1)\n } else {\n dp.append(0)\n }\n }\n\n guard dp.last! + 1 != dp.count else { return dp.last! - 1 }\n\n var i = dp.count-1\n while i >= 1 {\n if dp[i] != 0 {\n if (i - dp[i] - 1 >= 0) {\n maximum = max(maximum, dp[i] + dp[i - dp[i] - 1])\n } else {\n maximum = max(maximum, dp[i])\n }\n i -= dp[i]\n }\n i -= 1;\n }\n\n return maximum\n }\n}\n```\n\n# C++ Code\n```cpp []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n vector<int> dp = {0};\n int maximum = 0;\n\n for (int i = 0; i < nums.size(); ++i)\n {\n if (nums[i] == 1)\n dp.push_back(dp[i] + 1);\n else\n dp.push_back(0);\n }\n\n if (dp.back() + 1 == dp.size())\n return dp.back() - 1;\n\n for (int i = dp.size()-1; i >= 0; --i)\n {\n if (dp[i] != 0)\n {\n if (i - dp[i] - 1 >= 0)\n maximum = max(maximum, dp[i] + dp[i - dp[i] - 1]);\n else\n maximum = max(maximum, dp[i]);\n i -= dp[i];\n }\n }\n\n return maximum;\n }\n};\n```\n\n# Python3 Code\n```python3 []\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n dp = [0]\n maximum = 0\n\n for i in range(len(nums)):\n if nums[i] == 1:\n dp.append(dp[i] + 1)\n else:\n dp.append(0)\n\n if dp[-1] + 1 == len(dp):\n return dp[-2]\n\n i = len(dp)-1\n while i >= 1:\n if dp[i] != 0:\n if i - dp[i] - 1 >= 0:\n maximum = max(maximum, dp[i] + dp[i - dp[i] - 1])\n else:\n maximum = max(maximum, dp[i])\n i -= dp[i]\n i -= 1\n\n return maximum\n```\n\nIf you like it, please upvote it :) | 5 | 0 | ['Array', 'Dynamic Programming', 'Swift', 'C++', 'Python3'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Beats 99.99%🚀 Constant Space O (1) 💡 Sliding window 🪟 Beginner Friendly 💯 | beats-9999-with-proof-solution-using-sli-n5ij | Proof:Approach
Variables:
left: This is the left pointer for the sliding window.
max_length: This will store the maximum length of the subarray of 1's found so | harsh9265 | NORMAL | 2024-10-18T05:22:30.125146+00:00 | 2024-12-20T19:43:21.784669+00:00 | 393 | false | # Proof:

# Approach
<!-- Describe your approach to solving the problem. -->
1) Variables:
**left**: This is the left pointer for the sliding window.
**max_length**: This will store the maximum length of the subarray of 1's found so far.
**curr_length**: This will store the current length of the subarray as the window slides.
**k**: This variable represents how many zeros you are allowed to "flip" (in this case, you can flip only one zero).
**flips**: This keeps track of how many zeros you've encountered so far in the current window.
2) Sliding Window Approach:
You use the variable right as the right pointer to expand the window. For each element in nums, you check if it's a **0**. If it is, you **increment** the **flips** counter.
3) Shrinking the Window:
When the number of **flips exceeds k (which is 1 here, meaning more than one zero)**, you start shrinking the window from the left side by moving the left pointer. If the element at the left pointer is a 0, you decrement flips since you're moving past that zero.
4) Adjusting the Current Window:
**curr_length is calculated as the size of the current window, which is right - left + 1 - 1. You subtract 1 because the problem asks you to delete one element**, meaning the window should exclude one element (ideally a zero).
5) Updating Maximum Length:
After calculating curr_length, the code updates max_length to keep track of the largest window found so far.
6) Edge Condition for Exact Array End:
There's a check:
```
if right == len(nums) and flips==0:
curr_length-=1
```
This condition aims to handle the case where the loop reaches the end of the array and no flip (or zero) has occurred.
# Complexity
- Time complexity: $$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def longestSubarray(self, nums: List[int]) -> int:
left=0
max_length=0
curr_length=0
k=1
flips=0
for right in range(len(nums)):
if nums[right] == 0:
flips+=1
while flips >k:
if nums[left]==0:
flips-=1
left+=1
if right == len(nums) and flips==0:
curr_length-=1
curr_length = ((right-left)+1)-1
max_length = max(curr_length,max_length)
return max_length
```

| 5 | 0 | ['Array', 'Dynamic Programming', 'Sliding Window', 'Python', 'Python3'] | 2 |
longest-subarray-of-1s-after-deleting-one-element | This makes Your Life easy | this-makes-your-life-easy-by-anand_shukl-kj8g | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n$1):$ Initialization:\n\n=> n is the length of the input list nums.\n=> m | anand_shukla1312 | NORMAL | 2024-06-19T17:44:31.189193+00:00 | 2024-06-19T17:44:31.189217+00:00 | 269 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n$1):$ Initialization:\n\n=> n is the length of the input list nums.\n=> max_len keeps track of the maximum length of the subarray found so far.\n=> zero_count keeps track of the number of zeros in the current window.\n=> left is the left boundary of the current window.\n\n\n$2):$ Sliding Window:\n\n=> We iterate over the array using right as the right boundary of the window.\n=> If nums[right] is 0, we increment the zero_count.\n=> If zero_count exceeds 1, it means we have more than one zero in the current window, so we need to shrink the window from the left until we have at most one zero.\n=> Update max_len with the size of the current valid window (which is right - left).\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nTime Complexity:\nThe main part of the algorithm is a single loop that iterates over the elements of the array exactly once. Inside this loop, there is a while loop that advances the left pointer. However, each element is processed at most twice: once when the right pointer includes it in the window, and once when the left pointer excludes it from the window. Therefore, the overall time complexity is O(n), where n is the length of the input array nums.\n\nSpace Complexity:\nThe algorithm uses a constant amount of extra space. The variables n, max_len, zero_count, left, and right are all scalars and do not depend on the size of the input. Therefore, the space complexity is O(1).\n\n\n# Code\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n max_len = 0\n zero_count = 0\n left = 0\n \n for right in range(n):\n if nums[right] == 0:\n zero_count += 1\n \n while zero_count > 1:\n if nums[left] == 0:\n zero_count -= 1\n left += 1\n \n max_len = max(max_len, right - left)\n \n return max_len\n\n\n```\n \n\n\n---\n\n>Thank you!\n\n | 5 | 0 | ['Array', 'Two Pointers', 'Sliding Window', 'Iterator', 'Python3'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | ✅ BEST C++ SOLUTION ☑️ | best-c-solution-by-2005115-vove | PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand | 2005115 | NORMAL | 2024-02-18T15:12:15.603338+00:00 | 2024-02-18T15:12:15.603371+00:00 | 180 | false | # **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/_pratay_nandy_/]()**\n\n# Approach\nTo approach this problem, we can utilize a sliding window technique with two pointers `i` and `j` to traverse the array while maintaining the following conditions:\n\n1. **Maintain a Count of Zeros**: \n - We keep track of the number of zeros encountered within the current window using the variable `zerocnt`.\n \n2. **Move the Left Pointer When Necessary**:\n - If the number of zeros within the window exceeds one, we move the left pointer `i` towards right until `zerocnt` becomes one again. This operation ensures that we maintain the condition of deleting only one element.\n \n3. **Update the Maximum Length**:\n - We continuously update the maximum length of a subarray containing only ones (`ans`) as `j - i`, where `j` is the right pointer and `i` is the left pointer.\n \n4. **Return the Maximum Length**:\n - After traversing the entire array, we return the maximum length (`ans`) as the result.\n\n\nThis approach efficiently finds the size of the longest non-empty subarray containing only ones after deleting one element from the input array.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**0()**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**0(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n int ans = 0;\n int i = 0;\n int j = 0;\n int zerocnt = 0;\n for(int j = 0 ;j < n;j++) \n {\n if(nums[j] == 0)\n {\n zerocnt++;\n }\n if(zerocnt > 1)\n {\n while(zerocnt > 1)\n {\n if(nums[i] == 0)\n {\n zerocnt--;\n }\n i++;\n } \n }\n else\n {\n ans = max(j-i,ans);\n }\n }\n return ans ;\n }\n};\n``` | 5 | 0 | ['Array', 'C', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | [C++] Recursion? I hardly know her. | c-recursion-i-hardly-know-her-by-jaintle-5jnc | \n\n# Code\n\nclass Solution {\npublic:\n int longest(vector<int>& nums, int index, int maxi, int curr, int flag){\n if(index>=nums.size()){\n | jaintle | NORMAL | 2023-07-05T09:23:35.747415+00:00 | 2023-07-05T09:23:35.747440+00:00 | 228 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int longest(vector<int>& nums, int index, int maxi, int curr, int flag){\n if(index>=nums.size()){\n return maxi;\n }\n int ans = 0;\n if(flag==1){\n if(nums[index]==1){\n ans = longest(nums,index+1,max(maxi,curr+1),curr+1,1);\n }\n else{\n ans = longest(nums,index+1,maxi,0,1);\n }\n }\n else{\n if(nums[index]==1){\n ans = longest(nums,index+1,max(maxi,curr+1),curr+1,0);\n }\n else{\n ans = max(longest(nums,index+1,maxi,0,0),longest(nums,index+1,maxi,curr,1));\n }\n }\n return ans;\n }\n int longestSubarray(vector<int>& nums) {\n if(*min_element(nums.begin(),nums.end())==1){\n return nums.size()-1;\n }\n return longest(nums,0,0,0,0);\n }\n};\n```\n\n\n```\n int int if if if set set OOO for for for EEEEE \n int int if if set set O O for E \n int int if if if set set O O for EEE \n int int if set set O O for E \n int int if set OOO for EEEEE \n``` | 5 | 0 | ['Recursion', 'C++'] | 2 |
longest-subarray-of-1s-after-deleting-one-element | Simple iteration problem solved in O(n) time complexity | simple-iteration-problem-solved-in-on-ti-czoc | Intuition\nSimple iteration problem , can solove in O(n) time complexity \n\n\n# Approach\ncount the number of 1s together with no zero between among them.count | mairothiya | NORMAL | 2023-07-05T08:31:38.557082+00:00 | 2023-07-05T08:31:38.557109+00:00 | 23 | false | # Intuition\nSimple iteration problem , can solove in O(n) time complexity \n\n\n# Approach\ncount the number of 1s together with no zero between among them.count for every set of 1s, then check if we del the zero between them how many 1s we can get. for example...\nlet array be- 0 1 1 1 0 0 1 1 0 1 1 1 1 0\nthen we get the number of one together is\n- 0 3 0 2 4 \nnow we only count the max pair sum which is 6,\nThere is only 1 catch - if there is no zero in the given array then the answer will be : ans-1(see the code) , because we have to delete 1 element from the array.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int a=0,b=0,ans=0;\n bool f=0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]==0){\n ans=max(ans,a+b);\n b=a;\n a=0;\n f=true;\n }\n else a++;\n }\n ans=max(ans,a+b);\n if(!f)ans--;\n return ans;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | 🏆Beats 99%🔥Java/C++🔥concise Solution + Explanation🔥 | beats-99javacconcise-solution-explanatio-zetw | Intuition\n\n\n Describe your first thoughts on how to solve this problem. \nThe main concept behind this question is to mantain a single 0 in your window.\n# A | Sanchit_Jain | NORMAL | 2023-07-05T07:20:38.193176+00:00 | 2023-07-05T07:30:24.924510+00:00 | 406 | false | Intuition\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe main concept behind this question is to mantain a single 0 in your window.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nMain approach behind this solution is to start a valid window which only contain one zero and take the maxm of the window at the end.\nWhenever we encounter a zero this means that we need to update our starting point of window that is the last occurence of the zero +1 and we also need to update the zeroIdx to current 0 so that in next iteration we can start the valid window directly from the current last occurence of zero\n\n\n \n\n\nj is used for iterating the array\ni is used from where we can start our valid window\nzeroIdx is used for mantaining the last occurence of zero so that we can start our new window directly from zeroIdx+1\n\n\nLastly if maxLen is equal to the length of nums, this means we have all one in nums, so we need to return length-1 because it is mandatory to delete one integer from the nums.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\n\n# Code Java\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int zeroIdx = -1;\n int i=-1;\n int j=0;\n int n = nums.length;\n int maxLen = 0;\n while(j<n){\n if(nums[j]==0){ //updating our starting point\n i=zeroIdx+1;\n zeroIdx=j;\n }\n maxLen = Math.max(maxLen,j-i);\n j++;\n }\n return maxLen==nums.length?maxLen-1:maxLen;\n }\n}\n```\n# Code C++\n``` \nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int zeroIdx = -1;\n int i=-1;\n int j=0;\n int n = nums.size();\n int maxLen = 0;\n while(j<n){\n if(nums[j]==0){\n i=zeroIdx+1;\n zeroIdx=j;\n }\n maxLen =max(maxLen,j-i);\n j++;\n }\n return maxLen==nums.size()?maxLen-1:maxLen;\n }\n};\n\n```\n | 5 | 0 | ['Array', 'Sliding Window', 'C++', 'Java'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | C++ Solution using Two Pointers | c-solution-using-two-pointers-by-krishan-uqrq | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | KrishanBrar | NORMAL | 2023-07-05T05:56:44.182763+00:00 | 2023-07-05T05:56:44.182796+00:00 | 820 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n int left = 0, right, zeros = 0, ans = 0;\n\n for (right = 0; right < n; right++) {\n if (nums[right] == 0){\n zeros++;\n }\n if (zeros > 1 && nums[left++] == 0){\n zeros--;\n }\n ans = max(ans, right - left);\n }\n return ans; \n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | C# Solution for Longest Subarray of 1s after deleting one Element Problem | c-solution-for-longest-subarray-of-1s-af-k15a | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind the solution is to use the sliding window technique to find the lo | Aman_Raj_Sinha | NORMAL | 2023-07-05T04:06:07.055970+00:00 | 2023-07-05T04:06:07.056001+00:00 | 507 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind the solution is to use the sliding window technique to find the longest subarray containing only ones after deleting one element.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach is to iterate through the array using two pointers, start and i, where start represents the left end of the window and i represents the current position. We also keep track of the count of zeros within the window using the zeroCount variable.\n\nAt each iteration, we update the zeroCount by incrementing it when encountering a zero. If the zeroCount exceeds 1, we shrink the window by moving the start pointer and decrementing the zeroCount until it becomes 1 again.\n\nDuring each step, we calculate the length of the current window (i - start) and update the longestWindow variable with the maximum length encountered so far.\n\nFinally, we return the longestWindow, which represents the size of the longest non-empty subarray containing only ones after deleting one element.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of the solution is O(n), where n is the length of the input array. This is because we iterate through the array once using a single loop.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of the solution is O(1) because we only use a constant amount of additional space to store the variables zeroCount, longestWindow, and start. The space required does not depend on the size of the input array.\n\n# Code\n```\npublic class Solution {\n public int LongestSubarray(int[] nums) {\n int zeroCount = 0;\n int longestWindow = 0;\n int start = 0;\n\n for (int i = 0; i < nums.Length; i++)\n {\n zeroCount += (nums[i] == 0 ? 1 : 0);\n\n while (zeroCount > 1)\n {\n zeroCount -= (nums[start] == 0 ? 1 : 0);\n start++;\n }\n\n longestWindow = Math.Max(longestWindow, i - start);\n }\n\n return longestWindow;\n }\n}\n``` | 5 | 0 | ['C#'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | SIMPLE JAVA O(N) SOLUTION || FASTER THAN 99% || | simple-java-on-solution-faster-than-99-b-dyvu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | deepak_kumar_m | NORMAL | 2023-07-05T03:38:59.948559+00:00 | 2023-07-05T03:42:08.274721+00:00 | 973 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int c1=0,c2=0,ans=0;\n for(int i:nums)\n {\n if(i==0)\n {\n //c1 is number of one after last 0\n //c2 is number of one before last 0\n ans=Math.max(ans,c1+c2);\n c2=c1;\n c1=0;\n }\n else c1++;\n }\n if(c1+c2==nums.length) return nums.length-1; //if there is no 0\'s in array , then one 1 should be deleted\n return Math.max(ans,c1+c2);\n }\n}\n``` | 5 | 0 | ['Two Pointers', 'Java'] | 4 |
longest-subarray-of-1s-after-deleting-one-element | Java Solution 5ms Sliding Window | java-solution-5ms-sliding-window-by-aadi-bc3q | \nclass Solution {\n public int longestSubarray(int[] nums) {\n int n=nums.length,o=0,z=0;\n for(int i=0;i<n;i++)\n { \n\t\t// Calcula | aadishjain__ | NORMAL | 2021-11-22T08:21:56.608215+00:00 | 2021-11-22T08:24:37.205264+00:00 | 126 | false | ```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int n=nums.length,o=0,z=0;\n for(int i=0;i<n;i++)\n { \n\t\t// Calculating One\n if(nums[i]==1)\n {\n o++;\n }\n\t\t\t//Calculating zero\n else\n {\n z++;\n }\n }\n\t\t//If all array is one we have to return n-1\n if(o==n)\n {\n return n-1;\n }\n\t\t//If all array is zero we have to return n-1\n else if(z==n)\n {\n return 0;\n }\n int i=0,j=0,count=0,m=0;\n for(i=0;i<n;i++)\n {\n if(nums[i]==0)\n {\n count++;\n }\n while(count>1)\n {\n if(nums[j]==0)\n {\n count--;\n }\n j++;\n }\n\t\t\t// this will count longest length of subarray having only 1 zero\n m=Math.max(m,i-j+1);\n \n }\n\t\t//we have to return m-1 becz we have to del 0 and have to count rest 1\n return m-1; \n }\n}\n``` | 5 | 1 | [] | 0 |
longest-subarray-of-1s-after-deleting-one-element | easy solution using sliding window, O(n) time complexity | easy-solution-using-sliding-window-on-ti-2y93 | \n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n | ujjuengineer | NORMAL | 2024-09-28T06:10:41.718916+00:00 | 2024-09-28T06:10:41.718949+00:00 | 25 | false | \n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n // we can solve this problem just like the problem number \n int n = nums.size();\n int del = 1;\n \n int len = INT_MIN, maxLen = INT_MIN;\n int i = 0, j = 0;\n bool flag = 0;\n while(j<n){\n if(nums[j]==1) j++;\n else{\n if(del==1) {\n j++, del--;\n flag = 1;\n }\n\n else {\n len = j-i;\n maxLen = max(len, maxLen);\n\n // shifting i infront of first 0\n while(nums[i]==1) i++;\n i++;\n del = 1;\n }\n \n }\n }\n len = j-i;\n maxLen = max(len, maxLen);\n return maxLen-1; \n // we returned maxlen - 1, as we had to delete the one zero, but we have included it by flipping it\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Easy Solution | Java | better than 98% | easy-solution-java-better-than-98-by-chh-m6ye | Intuition\nCalculating no of zero\'s before 1 and after 1 \n\n# Approach\nMaths \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Cod | chhavigupta095 | NORMAL | 2024-02-05T18:28:56.655225+00:00 | 2024-02-05T18:28:56.655280+00:00 | 251 | false | # Intuition\nCalculating no of zero\'s before 1 and after 1 \n\n# Approach\nMaths \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int back =0, count=0,max =0;\n for(int i : nums){\n if(i==1) count++;\n else {\n max= Math.max(max, back + count);\n back=count;\n count=0;\n }\n }\n max= Math.max(max, back + count);\n if(max == nums.length) return nums.length-1;\n return max; \n }\n}\n``` | 4 | 0 | ['Math', 'Java'] | 3 |
longest-subarray-of-1s-after-deleting-one-element | ✅Beats 98% | Easy to Understand | C++ | Sliding Window Algorithm | | beats-98-easy-to-understand-c-sliding-wi-nqu5 | \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe approach employs a sliding window technique to find the longest subarray with | sri_mayur | NORMAL | 2024-01-19T00:11:39.774215+00:00 | 2024-01-19T00:11:39.774232+00:00 | 7 | false | \n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe approach employs a sliding window technique to find the longest subarray with at most one zero. It uses two pointers, i and j, to maintain a window. Also, we have used a counter named "zero" to track the number of zeroes in the window.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We have initialized two pointers i and j at the zeroth index. Also, we have initialized a counter "zero" to check the occurrence of zeroes in the window and "ans" to store the answer.\n2. We have initialized a while loop which will run until the value of j is less than the size of the nums.\n3. Inside the while loop, we have checked if the value of nums[j] == 0. If this is true, we will increase the counter "zero".\n4. The moment we get 2 zeroes in our window, we have to slide it. So, we have used another while loop in which we are sliding the window to the right side.\n(It can be observed from the test case that only 1 zero is allowed inside the window.)\n5. At the end, we are storing the one less size of the window (j-i) because we have to delete at least one element.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n\n int i = 0, j = 0, zero = 0, ans = 0;\n int n = nums.size();\n\n while(j < n){\n\n if(nums[j] == 0){\n zero++;\n }\n\n while(zero == 2){\n if(nums[i] == 0){\n zero--;\n }\n i++;\n }\n ans = max(ans, j - i);\n j++;\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | INTUITIVE || Easy to understand || No sliding window || No dp | intuitive-easy-to-understand-no-sliding-m2vum | Intuition\n Describe your first thoughts on how to solve this problem. \nIf we somehow manage to know the count of 1\'s before and after a particular occurence | nexgphoenix | NORMAL | 2023-07-05T19:35:19.867775+00:00 | 2023-07-05T19:35:19.867801+00:00 | 279 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf we somehow manage to know the count of 1\'s **before** and **after** a particular occurence of 0 and the number of 0\'s in the subarray we are considering **must be one** because we are allowed to delete only one element. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nDeclaring a vector "cal" which will store the count of ones at the i-th index such that **nums[i] == 0**.\n\nDeclaring a variable "cnt" which will tell us the **count of 1\'s** before encountering a 0.\n\n\nNow we will traverse in the nums vector from the **front** and keep updating our cnt variable whenever we encounter 1. And if we encounter 0 at i-th index then we update our cal[i] to the cnt and make our cnt = 0 again because we want only 1\'s in the subarray and we are assuming that we are going to delete this 0 element **(for more clarity refer to the dry run of a sample test case given below)**.\n\nSo far our cal vector only tells us the count of 1\'s **before** 0 and now we have to calculate the number of 1\'s **after** that 0 without encountering 0 again.\n\nSo we will traverse from back and update our cnt variable as earlier and whenever we get to 0 we add cnt to cal[i] (assuming ith element is 0). And at the end we will **return maximum element** in cal vector.\n\n\n**Dry run on sample test case**\nsample test case : 0 1 1 1 1 0 1 1 1 1 0 \ncnt value update : 0 1 2 3 4 0 1 2 3 4 0 \ncal[i] front traverse : 0 0 0 0 0 4 0 0 0 0 4 \ncal[i] back traverse : 4 0 0 0 0 4 0 0 0 0 0\ncal[i] overall (f + b) : 4 0 0 0 0 8 0 0 0 0 4\nmaximum element : 8 .\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n**O(2 * n) or O(n)** As we are traversing in nums vector **twice**.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**O(n)** As we are declaring cal vector of **size n**\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size() ;\n vector<int> cal(n , 0) ;\n int cnt = 0 ;\n for(int i = 0 ; i < nums.size() ; i++){\n if(nums[i] == 1){\n cnt++ ;\n }\n else{\n cal[i] = cnt ;\n cnt = 0 ;\n }\n }\n if(cnt == n){\n return n - 1 ;\n }\n cnt = 0 ;\n for(int i = nums.size() - 1 ; i >= 0 ; i--){\n if(nums[i] == 1){\n cnt++ ;\n }\n else{\n cal[i] += cnt ;\n cnt = 0 ;\n }\n }\n return *max_element(cal.begin() , cal.end()) ;\n }\n};\n``` | 4 | 0 | ['C++'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | VERY EASY||100% FAST||SLIDING WINDOW|| C++ | very-easy100-fastsliding-window-c-by-vai-ou90 | Very simple use of sliding window\n1. initailize i and j=0 \n2. maintain a counter and max counter\n3. set flag when counter with zero and store position after | VaidyaPS | NORMAL | 2023-07-05T10:18:34.262649+00:00 | 2023-07-05T10:24:22.777421+00:00 | 20 | false | Very simple use of sliding window\n1. initailize i and j=0 \n2. maintain a counter and max counter\n3. set flag when counter with zero and store position after zero.\n4. if we counter again 0 when our flag is set then set i and j both to stored position and reset counter and flag.\n5. manage to keep track of maxium count and return it.\n \n int longestSubarray(vector<int>& num) {\n int i=0;\n int j=0;\n int flag=0;\n int count=0;\n int n= num.size();\n int k=0;\n int ans=0;\n while(i<n&&j<n){\n if(num[j]==0 && flag==1){\n i=k;\n j=k;\n ans = max(ans,count);\n count=0;\n flag=0;\n // j++;\n continue;\n }\n if(num[j]==0 &&flag==0){\n flag=1;\n k= j+1;\n }\n \n if(num[j]==1)\n count++;\n \n j++;\n cout<<count<<" ";\n \n }\n cout<<endl;\n ans = max(ans,count);\n if(ans==n)\n ans=ans-1;\n return ans;\n }\n\t\n\t\n\tTIME COMPLEXITY O(N)\n\tSPACE COMPLEXITY O(1)\n\t\n\t\n\t**Please Upvote** | 4 | 0 | ['C', 'Sliding Window'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | JAVA SIMPLE APPROUCH🔥🔥Easy to understand💯💯 | java-simple-approucheasy-to-understand-b-qwpl | Intuition\nInitialize three variables: cur (current count of consecutive 1s), prev (previous count of consecutive 1s), and ans (maximum length of the subarray f | Aisu-08 | NORMAL | 2023-07-05T09:33:11.465422+00:00 | 2023-07-05T09:33:11.465446+00:00 | 350 | false | # Intuition\nInitialize three variables: cur (current count of consecutive 1s), prev (previous count of consecutive 1s), and ans (maximum length of the subarray found so far).\n\nIterate through each element i in the nums array.\n\nIf the current element i is equal to 1, increment the cur variable to count consecutive 1s.\n\nIf the current element i is equal to 0, update the ans by taking the maximum between the current ans and the sum of cur and prev (representing the length of the subarray with at most one 0). Then, update prev to hold the value of cur and reset cur to 0 since the current sequence of 1s is interrupted.\n\nAfter the loop, update ans by taking the maximum between the current ans and the sum of cur and prev again to handle the case when the longest subarray ends at the last element of the input array.\n\nFinally, check if ans is equal to the length of the nums array. If it is, decrement ans by 1. This is done to handle the edge case when the input array consists only of 1s.\n\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int cur = 0 , prev = 0;\n int ans = 0;\n for(int i : nums){\n if(i == 1) cur++;\n else{\n ans = Math.max(ans , cur+prev);\n prev = cur;\n cur = 0;\n }\n }\n ans = Math.max(ans , cur+prev);\n\n return ans == nums.length?ans-1:ans;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Simple 2-Step Java Solution | simple-2-step-java-solution-by-iamc0der-32sf | Intuition\nAs we need to allow only one zero in the subarray, the simplest way to track zeroes is to memorise the last zero position in the given array.\n\n# Ap | iamc0der | NORMAL | 2023-07-05T08:56:12.587008+00:00 | 2023-07-05T08:56:12.587040+00:00 | 299 | false | # Intuition\nAs we need to allow **only one zero in the subarray**, the simplest way to track zeroes is to memorise the last zero position in the given array.\n\n# Approach\nTo remember the last zero position we will use the variable `lastZeroIndex` with an initial value of `-1`.\nAdditionally, we will use 2 pointers to mark the subarray\'s borders: `from` and `current` variables.\n\n**Algorithm:**\nIterate over the array and check whether `arr[current] == 0`.\n1. If the current element equals zero move the `from` pointer to the right:\n`from = lastZeroIndex + 1`.\nBy default, `lastZeroIndex = -1`, and if the given array starts with `0`, it will also be considered. \nThis action allows us to exclude an extra zero element if the subarray contains more than one zero element.\n2. Calculate `maxLen` - the maximum subarray length.\n\n# Complexity\n- Time complexity:\n$$O(n)$$ as the algorithm iterates the whole array in a `for`-loop.\n\n- Space complexity:\n$$O(1)$$ as the solution doesn\'t require any additional space except integer variables of fixed size.\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] arr) {\n // input check\n if (arr == null || arr.length == 0) {\n return -1;\n }\n\n // memorise the last zero array element via \'lastZeroIndex\' variable\n int from = 0, maxLen = 0, lastZeroIndex = -1;\n for (int current = 0; current < arr.length; current++) {\n // move \'from\' pointer if needed\n if (arr[current] == 0) {\n from = lastZeroIndex + 1;\n lastZeroIndex = current;\n }\n // track maximum subarray length\n maxLen = Math.max(maxLen, current - from);\n }\n return maxLen;\n }\n}\n``` | 4 | 0 | ['Java'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Simple and Fast C++ Code || Beats 99% in speed and 99% in memory | simple-and-fast-c-code-beats-99-in-speed-sgl7 | Intuition\nMaintain the count of 1\'s Before Zero and after Zero and the max sum of Before and after is our answer.\n\n# Approach\nMaintain the count of 1\'s Be | NNikhil_Nik | NORMAL | 2023-07-05T08:14:50.710121+00:00 | 2023-07-05T08:20:02.845711+00:00 | 496 | false | # Intuition\nMaintain the count of 1\'s Before Zero and after Zero and the max sum of Before and after is our answer.\n\n# Approach\nMaintain the count of 1\'s Before Zero and after Zero.\n->0 1 1 1 0 1 1 0 1\nIn the above example\nFirst element is zero,Make fz=1 and we will only increase After counter.\n->At Index 4 second zero is encountered.Here we will transfer after elements in Before counter. Meaning we are only taking one zero in our subarray hence Before value will be 3 (number of zeroes before index 4)and after (counter) will start again from 0 untill it encounters second zero again.\n\n# Complexity\n- Time complexity:\n**O(n)**\n\n- Space complexity:\n**O(1)**\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int after=0;\n int before=0;\n int fz=0;\n int sz=0;\n int ans=0;\n for(int i=0;i<nums.size();++i){\n if(nums[i]==0&&!fz)\n {\n fz=1;\n }\n else if(nums[i]==0&&fz&&!sz)\n {\n before=after;\n after=0;\n }\n if(nums[i]==1&&!fz&&!sz)\n before++;\n else if(nums[i]==1&&fz)\n after++;\n ans=max(ans,before+after);\n\n }\n if(ans==nums.size())\n return ans-1;\n return ans; \n \n }\n};\n``` | 4 | 0 | ['Two Pointers', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Concise Intuitive Approach with Counters | concise-intuitive-approach-with-counters-xawg | Complexity\n- Time complexity: O(n).\n\n- Space complexity: O(1).\n\n# Code\n\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n | MikPosp | NORMAL | 2023-07-05T07:34:57.782974+00:00 | 2023-07-05T07:34:57.783006+00:00 | 273 | false | # Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(1)$$.\n\n# Code\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n maxLen = 0\n prevOnesCntr = zero = curOnesCntr = 0\n for num in nums:\n if num == 1:\n curOnesCntr += 1\n elif num == 0:\n prevOnesCntr, zero, curOnesCntr = curOnesCntr, 1, 0\n \n maxLen = max(maxLen, prevOnesCntr + curOnesCntr)\n \n return maxLen if zero else (maxLen - 1)\n``` | 4 | 0 | ['Array', 'Counting', 'Python3'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Longest Subarray of 1's After Deleting One Element || sliding window || O(N) | longest-subarray-of-1s-after-deleting-on-1a4n | \n# Approach\nwe can atlmost remove one 0 from the given array. selecting that 0 is the main task here. we will be counting the number of number of 0\'s in any | AD23315 | NORMAL | 2023-07-05T05:53:58.992912+00:00 | 2023-07-05T05:53:58.992946+00:00 | 350 | false | \n# Approach\nwe can atlmost remove one 0 from the given array. selecting that 0 is the main task here. we will be counting the number of number of 0\'s in any subarray. till the count of 0\'s is in our range we know we can remove that much 0\'s, but if the count goes out of bound the given subarray cannot be continued and hence we will starting forming new subarray. the above thing can be implemented easily using sliding window.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n \n int longestSubarray(vector<int>& nums) {\n int j = 0;\n int len = 0;\n int count = 0; // it will keep account of number of times 0 has occured till ith index\n for(int i = 0 ; i < nums.size() ;){\n if(!nums[i])count++;\n while(count>1){\n if(!nums[j]){\n count-=1;\n }\n j++;\n }\n len = max(len,i-j);\n i++;\n }\n return len;\n }\n};\n```\n\n\nSimilar list of questions to the above problem :- \nhttps://leetcode.com/problems/max-consecutive-ones-iii/\nhttps://leetcode.com/problems/max-consecutive-ones-ii/\nhttps://leetcode.com/problems/max-consecutive-ones/\n\nIf you like this solution, I\'m happy if you give this post a vote.\nHappy coding! <3\n | 4 | 0 | ['Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | 🏆 Image Explanation | C++ | Sliding Window | Optimised | Clean Code | Template | image-explanation-c-sliding-window-optim-vmp1 | Intuition\n Describe your first thoughts on how to solve this problem. \nWhen I read this problem statement, it had words like longest, subarray, exactly k. And | patelshubh694 | NORMAL | 2023-07-05T04:25:16.924434+00:00 | 2023-07-05T04:25:16.924468+00:00 | 430 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWhen I read this problem statement, it had words like longest, subarray, exactly k. And I know that, if problem statement contains -> \n\n1) Longest, Shortest\n2) subarray, substring\n3) Exactly, at most k\n4) Required to solve in O(n) time\n\nHigher chances that it can be solved using sliding window.\n\nPS : It can be solved using dynamic programming in O(n) time and O(1) space.\n For that, follow -> recursion -> memoization -> iteration -> optimization\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n int i = 0, maxi = 0, zeroes = 0;\n\n for(int j = 0; j < n; j++){\n if(nums[j] == 0) zeroes++;\n\n while(zeroes >= 2){\n if(nums[i] == 0) zeroes--;\n i++;\n }\n\n maxi = max(maxi, j - i);\n }\n return maxi;\n }\n};\n``` | 4 | 0 | ['Array', 'Dynamic Programming', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Easy C++/Python using 2 pointers||Beats 95.29% | easy-cpython-using-2-pointersbeats-9529-jgkv6 | Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe code finds the length of the longest subarray in a given array, allowing at most | anwendeng | NORMAL | 2023-07-05T00:06:16.436938+00:00 | 2023-07-05T01:44:05.627194+00:00 | 921 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe code finds the length of the longest subarray in a given array, allowing at most one zero. It uses two pointers and a count of zeros to iterate through the array and update the answer by finding the maximum subarray length.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(1)$$\n# Code Runtime 35 ms Beats 95.29%\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n=nums.size();\n int left=0 , right, zeros=0, ans=0;\n for(right=0; right<n; right++){\n if(nums[right]==0) zeros++;\n if(zeros>1 && nums[left++]==0) zeros--;\n ans=max(ans, right-left);\n }\n return ans; \n }\n};\n```\n# Code with Explanation in comments\n\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n int left = 0, right, zeros = 0, ans = 0;\n \n // Iterate over the array using the right pointer\n for (right = 0; right < n; right++) {\n // Check if the current element is 0\n if (nums[right] == 0)\n zeros++;\n \n // If the number of zeros exceeds 1, move the left pointer to the right\n // until the number of zeros becomes valid (at most 1 zero)\n if (zeros > 1 && nums[left++] == 0)\n zeros--;\n \n // Update the answer by finding the maximum length of subarray\n ans = max(ans, right - left);\n }\n \n return ans; \n }\n};\n\n```\n# Python code\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n = len(nums)\n left = 0\n zeros = 0\n ans = 0\n for right in range(n):\n if nums[right] == 0:\n zeros += 1\n while zeros > 1:\n if nums[left] == 0:\n zeros -= 1\n left += 1\n ans = max(ans, right - left)\n return ans\n\n``` | 4 | 0 | ['Two Pointers', 'C++'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | ✅Easy sliding window implementation | time: O(n), space: O(1) | easy-sliding-window-implementation-time-iq5ep | \n# Code\n\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i=0,j=0,count=0,mx=0;\n bool flag=true;\n while(j | underground_coder | NORMAL | 2023-01-05T17:00:38.751131+00:00 | 2023-01-05T17:00:38.751184+00:00 | 1,760 | false | \n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i=0,j=0,count=0,mx=0;\n bool flag=true;\n while(j<nums.size()){\n if(nums[j] == 0){\n flag = false;\n count++;\n }\n \n if(count < 1){\n j++;\n }else if(count == 1){\n mx = max(mx,(j-i+1));\n j++;\n }else{\n if(nums[i] == 0)\n count--;\n i++;\n j++;\n }\n }\n if(flag)\n return nums.size()-1;\n return mx-1;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | C++ | Explanation | Sliding Window | Easy | c-explanation-sliding-window-easy-by-gjh-qt5h | Simple Solution using Sliding Window\nWe maintain the count of zero and one\nWhile count of zero is 1 we will keep the track of window size in mx\nIf count of z | gjha133 | NORMAL | 2022-08-15T00:51:03.213406+00:00 | 2022-08-15T00:51:03.213449+00:00 | 687 | false | Simple Solution using Sliding Window\nWe maintain the ```count of zero and one```\nWhile ```count of zero is 1``` we will keep the track of **window size** in ```mx```\nIf ```count of zero is 2```, we will **decrease** the window from left until ```count of zero is 1```.\n\nDo Upvote if it helped!\n\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int zero = 0, one = 0, mx = INT_MIN, i = 0, j = 0, n = nums.size();\n \n while(j < n)\n {\n if(nums[j] == 0) zero++;\n else one++;\n if(zero == 1)\n {\n mx = max(mx, j - i + 1 - zero); // Can also use max(mx, j - i)\n }\n \n while(zero == 2)\n {\n if(nums[i] == 0) zero--;\n i++;\n }\n \n j++;\n }\n \n \n return mx == INT_MIN ? one - 1 : mx;\n }\n};\n``` | 4 | 0 | ['C', 'Sliding Window'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Simple || Intutive || Java Soln with explanation | simple-intutive-java-soln-with-explanati-slfh | Well as y\'all know that this is\'nt your normal sliding window question, because the size here could vary according the requirement of the question for eg:- [1 | kageyama09 | NORMAL | 2022-01-16T09:38:59.150053+00:00 | 2022-01-16T09:38:59.150088+00:00 | 132 | false | Well as y\'all know that this is\'nt your normal sliding window question, because the size here could vary according the requirement of the question for eg:- [1,1,1,0,1] this could be your possible answer and [1,0,1] too could be your possible answer. The only catch is that we have consider the maximum subarray in our answer, for eg if above two subarrays would have been our options to choose from then we would\'ve gone with the first subarray of size 5, and hence the answer would\'ve been 4 after deleting one element from it.\n\n**Now, what intutive approach can you come up with**\nWell as for a beginner, you wouldn\'t need answers that are most optimized but those that a noob like me would think of.\nMy approach was simple:-\n**1.** I thought that the maximum subarray after deleting 1 element would be the one which will be the longest subarray to have only **1 Zero**. So that you could remove that zero and have your answer.\n**2.** Some of you may think that what about the 3rd example given in the description, it contains no zero and still have an answer. So as for now lets not focus about that, it\'s a corner case which we will try to follow up after we have finished our general code.\n**3.** The basic idea is to have two pointers i and j at the start of the array, onw would help us to traverse the array ( i in our case ) and another one will help us to jump over the **zeros** to enter into the new subarray ( j in our case ).\n**4.** We will have a variable called **zeroct** which will have a count of zeroes in the subarray j to i, and a **max** variable to have the value of the maximum subarray, which will obviously be our answer.\n\n\n```\npublic int longestSubarray(int[] nums) {\n int zeroct=0,max=0,i,j;\n for(i=0,j=0;i<nums.length;i++){\n if(nums[i]==0)zeroct++; //We are counting the no. of zeroes seen so far\n if(zeroct==2){ //We will check for our answer at any point when zero count becomes 2\n max=Math.max(max,i-j-1); //Update max if it less than i-j-1 (we are subracting one from i-j because 1 element must be deleted.)\n while(nums[j]!=0) //Now our subarray contains two zeroes, so find the index of the first zero\n j++;\n j++; //Move to the next index in order to remove the first zero\n zeroct--; //Decrease the zero count by 1 so that if(zeroct==2) can be checked again\n }\n }\n return Math.max(max,i-j-1);\n }\n```\n\n\nIn the end, we will just return the maximum of **max** or **i-j-1** to counter the condition which will occur when the **zeroct won\'t reach 2** in the last feasible subarray.\n\t\n**Sayonara :)**\n\t\n | 4 | 0 | ['Array', 'Sliding Window'] | 2 |
longest-subarray-of-1s-after-deleting-one-element | C++ Sliding Window with explanation | c-sliding-window-with-explanation-by-sau-mj1h | Logic : At any point in time our current window must only contains 1\'s and at most one 0 . So if we encounter another zero in our path we must slide our left | saumitrakumar | NORMAL | 2021-08-10T11:39:48.013141+00:00 | 2021-08-10T11:39:48.013186+00:00 | 187 | false | Logic : At any point in time our current window must only contains 1\'s and at most one 0 . So if we encounter another zero in our path we must slide our left end of the window to `lastZeroIndex + 1` to remove a zero from our current window and accomodate the upcoming zero.\n ```\nint longestSubarray(vector<int>& nums) {\n int left=0 , right=0 ,res=0;\n int n=nums.size() , lastZeroIdx=-1;\n \n while(right<n){\n if(nums[right]==0)\n {\n if(lastZeroIdx==-1)\n {\n lastZeroIdx=right;\n }\n else\n {\n left=lastZeroIdx+1;\n lastZeroIdx=right;\n }\n }\n \n res = max(res, right-left+1);\n right++;\n }\n \n return res-1; // -1 because we have to delete 1 element mandatory\n }\n``` | 4 | 0 | [] | 0 |
longest-subarray-of-1s-after-deleting-one-element | C++ | Time Complexity - O(n) | Space Complexity - O(1) | c-time-complexity-on-space-complexity-o1-h9fa | \nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int ones=0, zero=0;\n int n=nums.size(), i=0, j=0, res=0;\n \n | manas02 | NORMAL | 2021-07-12T16:36:49.846490+00:00 | 2021-07-12T16:36:49.846530+00:00 | 268 | false | ```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int ones=0, zero=0;\n int n=nums.size(), i=0, j=0, res=0;\n \n while(j<n){\n if(nums[j]==0) zero++;\n else ones++;\n \n if(zero<2) res=max(res, ones);\n else{\n while(zero>1){\n if(nums[i]==0) zero--;\n else ones--;\n i++;\n }\n }\n j++;\n }\n if(zero==0) return res-1;\n return res;\n }\n};\n``` | 4 | 0 | ['Sliding Window'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Java, sliding window, linear, O(n), explained | java-sliding-window-linear-on-explained-3kckx | If problem statement flipped than it can be equvivalent of finding longest array of all 1s if we allow to replace one 0 to 1. At the end we just do answer - 1 l | gthor10 | NORMAL | 2020-07-05T23:19:55.736430+00:00 | 2020-07-05T23:19:55.736464+00:00 | 458 | false | If problem statement flipped than it can be equvivalent of finding longest array of all 1s if we allow to replace one 0 to 1. At the end we just do answer - 1 like the 0 is deleted.\nSuch problem solved by sliding window approach in linear time. We have left and right pointers, advance right by 1 and check if number of 0 we met is 0 or 1. If not - advance left pointer to the right until number of 0 is 0 or 1 again. \n\nO(n) time - each element checked at most twice (one by right pointer and possible once by left). \nO(1) space - few vars to keep state.\n\n```\n public int longestSubarray(int[] nums) {\n\t\t//initial position of left pointer\n int l = 0;\n\t\t//ma length of sequence so far\n int max = 0;\n\t\t//count of 0s we met so far\n int count0 = 0;\n\t\t\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0) {\n ++count0;\n }\n\t\t\t//we we met 2 0s - need to move left pointer unless number of 0s is 0 or 1\n while(count0 > 1) {\n if (nums[l] == 0)\n --count0;\n ++l;\n }\n\t\t\t//update max length of sequence we\'ve found so far\n max = Math.max(max, i - l + 1);\n }\n\t\t//max will have length including 0, need to adjust it by 1\n return max - 1;\n }\n``` | 4 | 0 | ['Sliding Window', 'Java'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Simple DP solution, Easy to Understand | simple-dp-solution-easy-to-understand-by-hyau | Runtime: 3 ms, faster than 50.00% of Java online submissions for Longest Subarray of 1\'s After Deleting One Element.\nMemory Usage: 47.2 MB, less than 100.00% | aroraharsh010 | NORMAL | 2020-06-28T08:42:54.751554+00:00 | 2020-06-28T08:42:54.751585+00:00 | 369 | false | Runtime: 3 ms, faster than 50.00% of Java online submissions for Longest Subarray of 1\'s After Deleting One Element.\nMemory Usage: 47.2 MB, less than 100.00% of Java online submissions for Longest Subarray of 1\'s After Deleting One Element.\n\n```\nint[] dp=new int[nums.length];\n if(nums.length==0)return 0;\n dp[0]=nums[0];\n int cnt=0;\n int max=0;\n if(nums[0]==1){max++;cnt++;}\n ArrayList<Integer> list=new ArrayList<>();\n for(int i=1;i<nums.length;i++){\n if(nums[i]==1){\n dp[i]=dp[i-1]+1;\n cnt++;\n max=Math.max(max,cnt);\n \n }\n else{\n dp[i]=0;\n cnt=0;\n list.add(i);\n }\n }\n if(list.size()==0)\n return nums.length-1;\n for(int i:list){// Loop on all indices where there is zero\n if(i==0)continue;// Already handled\n int k=i+1;\n while(k<dp.length&&dp[k]!=0){\n max=Math.max(max,dp[i-1]+dp[k]);\n k++;\n }\n }\n \n return max;\n``` | 4 | 2 | ['Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Very concise and intuitive solution | very-concise-and-intuitive-solution-by-z-svw2 | Intuition\nFirst, check if there are any zeros in the array. If not, it doens\'t make sence to iterate over the array.\n\n\nIterate until the right pointer is e | zhav1k | NORMAL | 2024-07-24T14:20:09.380521+00:00 | 2024-07-24T14:20:09.380546+00:00 | 155 | false | # Intuition\nFirst, check if there are any zeros in the array. If not, it doens\'t make sence to iterate over the array.\n\n\nIterate until the right pointer is equal to the size of the array. \n\nIf we didn\'t encounter zero, update the max length with the current max length and a new one (R-L)\nIf we encounter zero, we check if it\'s the first zero we have encountered and if not, move the left index on the right side of that zero. Update the current zero index with R and continue updating the maximum value.\n\nEnjoy!\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n if sum(nums) == len(nums):\n return len(nums) - 1\n \n L, R = 0, 0\n max_len = 0\n zero_index = -1\n\n while R < len(nums):\n if nums[R] == 0:\n if zero_index != -1:\n L = zero_index + 1\n zero_index = R\n max_len = max(max_len, R - L)\n R += 1\n\n return max_len\n \n``` | 3 | 0 | ['Python3'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Easy Java Solution for Beginners|| O(N) Solution....... | easy-java-solution-for-beginners-on-solu-d9jp | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Bugs_Bunny15 | NORMAL | 2024-07-12T10:08:32.387113+00:00 | 2024-07-12T10:08:32.387134+00:00 | 120 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n\n- Space complexity:O(1)\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int i=0;int j=0;int k=1;int max=Integer.MIN_VALUE;\n while(j<nums.length){\n if(nums[j]==0){\n k--;\n \n }\n if(k>=0){\n j++;\n }else if(k<0){\n \n if(nums[i]==0){\n k++;\n\n }\n i++;j++;\n }\n }\n \n return j-(i+1);\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Easiest Optimal Solutions for Longest Subarray After Deleting One Element | easiest-optimal-solutions-for-longest-su-w6fe | Approach 1 Complexity\n- Time complexity:O(N)\n\n- Space complexity: O(1)\n\n# Approach 1\n\nclass Solution(object):\n def longestSubarray(self, nums):\n | Sachinonly__ | NORMAL | 2024-06-28T15:30:47.001687+00:00 | 2024-06-28T15:30:47.001727+00:00 | 299 | false | # Approach 1 Complexity\n- Time complexity:O(N)\n\n- Space complexity: O(1)\n\n# Approach 1\n```\nclass Solution(object):\n def longestSubarray(self, nums):\n ans = 0\n deleted = False\n prev = 0\n count = 0\n for x in nums:\n if x == 0:\n if ans < count:\n ans = count\n deleted = True\n prev = count - prev\n count = prev\n else:\n count += 1\n if ans < count:\n ans = count\n \n if deleted:\n return ans\n return ans - 1\n```\n\n# Result\n\n\n\n# Approach 2 Complexity\n- Time complexity:O(N)\n\n- Space complexity: O(N)\n\n# Approach 2\n```\nclass Solution(object):\n def longestSubarray(self, nums):\n arr = []\n count = 0\n n = len(nums)\n for i in range(n):\n if nums[i] == 1:\n count += 1\n else:\n arr.append(count)\n count = 0\n if i > 0:\n arr.append(0)\n if count > 0:\n arr.append(count)\n \n if len(arr) == 1 and arr[0] > 0:\n return arr[0] - 1\n elif len(arr) == 2:\n return sum(arr)\n else:\n ans = 0\n for i in range(1, len(arr) - 1):\n x = arr[i - 1] + arr[i + 1]\n if arr[i] == 0 and x > ans:\n ans = x\n else:\n if arr[i] > ans: # to handle when [0, 1, 0]\n ans = arr[i]\n return ans\n```\n# Result\n\n\n\n\n | 3 | 0 | ['Array', 'Dynamic Programming', 'Sliding Window', 'Python'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Greedy linear solution without additional memory | greedy-linear-solution-without-additiona-2ulf | \n# Approach\n Describe your approach to solving the problem. \nIf two sequences of ones with lengths $k_1$ and $k_2$ are separated by a single zero, i.e., $\un | drgavrikov | NORMAL | 2024-04-17T09:06:06.183122+00:00 | 2024-06-04T20:39:14.507556+00:00 | 70 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nIf two sequences of ones with lengths $k_1$ and $k_2$ are separated by a single zero, i.e., $\\underbrace{11..1}_{k_1}0\\underbrace{11..1}_{k_2}$, then by deleting $0$ with $1$, we can obtain a sequence of length $k_1 + k_2$.\n\nTo account for these cases, we store the lengths of the last two subsequences of ones and reset the length of the previous one if they are separated by more than one zero. This can be implemented in a single iteration through the array without using additional memory.\n\nSpecial case: we output its length minus $1$ when all elements in the array are ones.\n\n---\n\n\u0415\u0441\u043B\u0438 \u0434\u0432\u0435 \u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0438 \u0435\u0434\u0438\u043D\u0438\u0446 \u0434\u043B\u0438\u043D\u043E\u0439 $k1$ \u0438 $k2$ \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u044B \u043E\u0434\u043D\u0438\u043C \u043D\u0443\u043B\u0435\u043C, \u0442. e. $\\underbrace{11..1}_{k_1}0\\underbrace{11..1}_{k_2}$, \u0442\u043E \u0443\u0434\u0430\u043B\u0435\u043D\u0438\u0435\u043C $0 -> 1$ \u043C\u043E\u0436\u043D\u043E \u043F\u043E\u043B\u0443\u0447\u0438\u0442\u044C \u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C $k_1 + k_2$.\n\n\u0414\u043B\u044F \u0443\u0447\u0435\u0442\u0430 \u044D\u0442\u043E\u0433\u043E \u0441\u043B\u0443\u0447\u0430\u044F\u0445 \u0445\u0440\u0430\u043D\u0438\u043C \u0434\u043B\u0438\u043D\u044B \u0434\u0432\u0443\u0445 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0438\u0445 \u043F\u043E\u0434\u043F\u043E\u0441\u043B\u0435\u0434\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u0435\u0439 \u0435\u0434\u0438\u043D\u0438\u0446 \u0438 \u043E\u0431\u043D\u0443\u043B\u044F\u0435\u043C \u0434\u043B\u0438\u043D\u0443 \u043F\u0440\u0435\u0434\u044B\u0434\u0443\u0449\u0435\u0439 \u0435\u0441\u043B\u0438 \u043E\u043D\u0438 \u0440\u0430\u0437\u0434\u0435\u043B\u0435\u043D\u044B \u0431\u043E\u043B\u044C\u0448\u0435 \u0447\u0435\u043C \u043E\u0434\u043D\u0438\u043C \u043D\u0443\u043B\u0435\u043C. \n\u042D\u0442\u043E \u043C\u043E\u0436\u043D\u043E \u0440\u0435\u0430\u043B\u0438\u0437\u043E\u0432\u0430\u0442\u044C \u043E\u0434\u043D\u0438\u043C \u043F\u0440\u043E\u0445\u043E\u0434\u043E\u043C \u043F\u043E \u043C\u0430\u0441\u0441\u0438\u0432\u0443 \u0431\u0435\u0437 \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0439 \u043F\u0430\u043C\u044F\u0442\u0438.\n\n\u0427\u0430\u0441\u0442\u043D\u044B\u0439 \u0441\u043B\u0443\u0447\u0430\u0439: \u043A\u043E\u0433\u0434\u0430 \u0432\u0441\u0435 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B \u0432 \u043C\u0430\u0441\u0441\u0438\u0432\u0435 \u0435\u0434\u0438\u043D\u0438\u0446\u044B, \u0432\u044B\u0432\u043E\u0434\u0438\u043C \u0435\u0433\u043E \u0434\u043B\u0438\u043D\u0443 \u043C\u0438\u043D\u0443\u0441 $1$.\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n```C++ []\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int result = 0;\n \n int currentCount = 0;\n int prevCount = 0;\n bool isZeros = false;\n for (auto num: nums) {\n if (num == 0) {\n result = max(result, currentCount + prevCount);\n prevCount = currentCount;\n currentCount = 0;\n isZeros = true;\n } else {\n currentCount++; \n }\n }\n result = max(result, currentCount + prevCount);\n if (!isZeros) return nums.size() - 1;\n return result;\n }\n};\n```\n```Kotlin []\nclass Solution {\n fun longestSubarray(nums: IntArray): Int {\n var result = 0\n\n var count = 0\n var countPrev = 0\n\n var isZeros = false\n\n for (index in 0 until nums.size) {\n if (nums[index] == 1) {\n count++\n result = max(countPrev + count, result)\n } else {\n countPrev = count\n count = 0\n isZeros = true\n }\n }\n if (!isZeros) return nums.size - 1\n return result\n }\n}\n```\n\nMost of my solutions are in\xA0[C++](https://github.com/drgavrikov/leetcode-cpp)\xA0and\xA0[Kotlin](https://github.com/drgavrikov/leetcode-jvm)\xA0on my\xA0Github.\n | 3 | 0 | ['Greedy', 'C++', 'Kotlin'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Detailed Explanation - Beats 96% Runtime, 85% Space | detailed-explanation-beats-96-runtime-85-s3bb | Intuition\nMy first thought was that we\'d need to track which zero we "dropped" within the sliding window. Then of course we\'d need the starting and end point | mckamike | NORMAL | 2024-02-09T21:47:24.096194+00:00 | 2024-03-20T23:50:49.115807+00:00 | 186 | false | # Intuition\nMy first thought was that we\'d need to track which zero we "dropped" within the sliding window. Then of course we\'d need the starting and end pointers of the window.\n\n# Approach\nIts fairly simple. \n1. We expand the window rightward (so, increment the `end` pointer)\n2. When `end` runs into the first zero, we track that in `indexOfDroppedZero`. We will refer to this later\n3. Keep incrementing `end` until you reach the second zero. We can only afford to drop one zero, so lets record the size of the window\n4. **Important!** We move the start index to be one index past the zero that\'s inside the window. We can only have one zero in our window, and we just ran into another zero, so we don\'t care about the one inside our window anymore! So move the start to be one index past it.\n\n# Complexity\n- Time complexity:\nO(n), we are looping through the nums array once.\n\n- Space complexity:\nO(1) We are only using additional constant time helper variables.\n\n# Code\n```\nclass Solution {\n func longestSubarray(_ nums: [Int]) -> Int {\n var start = 0\n var end = 0\n var maxSize = 0\n \n // if an index has a zero, we need to move nums[start] to the spot after the zero to slide the window.\n var indexOfDroppedZero = -1\n\n while end < nums.count {\n if nums[end] == 0 {\n if indexOfDroppedZero != -1 {\n maxSize = max(maxSize, end - start - 1)\n start = indexOfDroppedZero + 1\n indexOfDroppedZero = -1\n } else {\n // record the location of the zero in our window\n indexOfDroppedZero = end\n end += 1\n }\n } else {\n end += 1\n }\n }\n\n return max(maxSize, end - start - 1)\n }\n}\n``` | 3 | 0 | ['Swift'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | JavaScript Solution | javascript-solution-by-sahil3554-0iu7 | \n\n# Code\n\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n let leftPtr = 0;\n let result = 0;\n l | sahil3554 | NORMAL | 2023-11-29T03:23:27.631699+00:00 | 2023-11-29T03:23:27.631726+00:00 | 326 | false | \n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar longestSubarray = function(nums) {\n let leftPtr = 0;\n let result = 0;\n let zeroCount = 0;\n for(let rightPtr=0;rightPtr<nums.length;rightPtr++){\n \n if(nums[rightPtr]===0){\n zeroCount++\n }\n\n if(zeroCount>1){\n if(nums[leftPtr]===0){\n zeroCount--;\n }\n leftPtr++;\n }\n if(zeroCount<=1){\n result = Math.max(result,rightPtr-leftPtr);\n }\n }\n return result;\n};\n``` | 3 | 0 | ['JavaScript'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Simple Sliding Window | simple-sliding-window-by-pndev0404-ij4m | Intuition\nMaximum substring with atmost K deletions\n\n# Approach\nIncrease the sliding window until we have only one zero in it, once encountered another zero | pndev0404 | NORMAL | 2023-10-14T18:12:26.833483+00:00 | 2023-10-14T18:12:26.833502+00:00 | 75 | false | # Intuition\nMaximum substring with atmost K deletions\n\n# Approach\nIncrease the sliding window until we have only one zero in it, once encountered another zero, shrink the window until previous zero goes out of window scope and continue.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\n fun longestSubarray(nums: IntArray): Int {\n var result = 0\n var start = 0\n var k = 1\n for(end in nums.indices){\n if(nums[end] == 0){\n //if k==0, it means we already have one zero\n //in the window, so shrink it\n while(k == 0){\n if(nums[start] == 0) k++\n start++\n }\n k--\n }\n val window = end - start\n result = maxOf(result, window)\n }\n return result\n }\n}\n``` | 3 | 0 | ['Sliding Window', 'Kotlin'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Longest Subarray of 1's After Deleting One Element C++ Solution | longest-subarray-of-1s-after-deleting-on-xmyj | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rissabh361 | NORMAL | 2023-09-12T17:47:23.782154+00:00 | 2023-09-12T17:47:23.782188+00:00 | 119 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size();\n int left = 0, right, zeros = 0, ans = 0;\n\n for (right = 0; right < n; right++) {\n if (nums[right] == 0){\n zeros++;\n }\n if (zeros > 1 && nums[left++] == 0){\n zeros--;\n }\n ans = max(ans, right - left);\n }\n return ans; \n }\n};\n``` | 3 | 0 | ['Array', 'Dynamic Programming', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Python short and clean. Functional programming. | python-short-and-clean-functional-progra-cndj | Approach\n1. For every element x in nums, calculate the length of streaks of 1s upto x excluding itself.\n\n2. Select the streaks corresponding to x == 0, lets | darshan-as | NORMAL | 2023-07-05T19:41:20.746323+00:00 | 2023-07-05T20:09:11.978539+00:00 | 856 | false | # Approach\n1. For every element `x` in `nums`, calculate the length of streaks of `1s` upto `x` excluding itself.\n\n2. Select the streaks corresponding to `x == 0`, lets call it `streaks_at_0`. This acts as deleting the corresponding `x` and selecting the streaks of `1s` to the left of it.\n\n3. The longest possible `streak` of `1s` after removing a `0` is the maximum `pairwise` sum of `steaks_at_0`. This corresponds to merging 2 adjacent streaks of `1s` to form a longer streak.\n\n\nFor ex:\n```python\nnums = [1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1] 0 // Extra 0 at the end\nstreaks_of_1s = [0, 1, 0, 0, 1, 2, 3, 0, 1, 2, 0, 1]\nstreaks_at_0 = [ 1, 0, 3, 2, 1]\n\npairwise(...) = [(1, 0), (0, 3), (3, 2), (2, 1)]\npairwise_sum = [1, 3, 5, 3]\nmax_sum = 5 // Answer\n\n```\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```python\nclass Solution:\n def longestSubarray(self, nums: list[int]) -> int:\n streaks_of_1s = accumulate(nums, lambda a, x: (a + 1) * (x != 0), initial=0)\n streaks_at_0 = compress(streaks_of_1s, map(not_, chain(nums, (0,))))\n return max(starmap(add, pairwise(streaks_at_0)), default=len(nums) - 1)\n\n\n``` | 3 | 0 | ['Array', 'Dynamic Programming', 'Sliding Window', 'Python', 'Python3'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Ez Pz | Singe Loop | Zero Logic | ez-pz-singe-loop-zero-logic-by-lourdessa-1r8m | \n\n# Code\n\nclass Solution {\n public int longestSubarray(int[] nums) {\n int prev = 0, cur = 0, max = 0;\n\n for(int num : nums) {\n | LourdesSanthosh | NORMAL | 2023-07-05T16:45:24.710936+00:00 | 2023-07-05T16:45:24.710970+00:00 | 178 | false | \n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int prev = 0, cur = 0, max = 0;\n\n for(int num : nums) {\n if(num == 1) cur++;\n else {\n max = (max > prev+cur) ? max : prev+cur;\n prev = cur;\n cur = 0;\n }\n }\n if(nums[nums.length-1] == 1) {\n max = (max > prev+cur) ? max : prev+cur;\n }\n if(max == nums.length) max--; //cuz we MUST delete one element even if all are elements are 1\n\n return max;\n }\n}\n``` | 3 | 0 | ['Brainteaser', 'Sliding Window', 'Prefix Sum', 'Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Easy Sliding Window Approach || C++ | easy-sliding-window-approach-c-by-rahul2-27g4 | Intuition\nLooks similar to sliding window pattern.\n\n# Approach\nStart with a sliding window. Keep a zero-count to track the number of zeroes in the current w | rahul2001dogra | NORMAL | 2023-07-05T14:09:08.742563+00:00 | 2023-07-05T14:09:08.742593+00:00 | 112 | false | # Intuition\nLooks similar to sliding window pattern.\n\n# Approach\nStart with a sliding window. Keep a zero-count to track the number of zeroes in the current window.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int zero_count = 0;\n int len = 0;\n int start = 0;\n\n for(int i=0; i<nums.size(); i++){\n if(nums[i] == 0) zero_count++;\n\n if(zero_count > 1){\n zero_count -= (nums[start] == 0);\n start++;\n }\n\n len = max(len, i- start);\n }\n\n return len;\n }\n};\n``` | 3 | 0 | ['Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | EASY AND BEST C++ SOLUTION WITH NO EXTRA SPACE AND O(N)TIME COMPLEXITY | easy-and-best-c-solution-with-no-extra-s-a0z1 | Intuition\n Describe your first thoughts on how to solve this problem. \n#BEST SOLUTION WITH NO EXTRA SPACE AND O(N)TIME COMPLEXITY\n\n# Approach\n Describe you | its_arunra0 | NORMAL | 2023-07-05T11:04:22.187534+00:00 | 2023-07-05T11:04:22.187554+00:00 | 930 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n#BEST SOLUTION WITH NO EXTRA SPACE AND O(N)TIME COMPLEXITY\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. FIRST CHECK IF ALL ELEMENTS ARE 1 OR NOT BY CHECK POINTER;\n2. USE COUNT2 POINTER TO COUNT NO. OF 1 EVERY TIME \n3. THERE ARE 2 CASE FOR 0:-\nONLY 1 ZERO PRESENT(THEN TRANSFER VALUE OF COUNT2 IN COUNT1)\nMORE THEN 1 ZERO PRESENT(MAKE BOTH VARIBLE ZERO (COUNT 1 AND COUNT 2))\n4. VARIBLE SUM IS CREATE TO CEHCK EVERYTIME NO. OF 1 AFTER REMOVING 0\n5. FOR i=0(i-1 is not accessible ) and i=N (i+1 is not accessible ) SO FOR THIS ONE IF CONDITION IS MADE INSIDE FOR LOOP;\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(N)\nLINEAR TIME COMPLEXITY\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(1)\nUSING NO EXTRA SPACE \n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int count1=0;\n int count2=0;\n int sum=0;\n int check=0;\n for(int j=0;j<nums.size();j++){\n if(nums[j]==0){\n check=1;\n }\n }\n if(check==0){\n return nums.size()-1;\n }\n for(int i=0;i<nums.size();i++){\n if(i==0 && nums[i]==0 || i==nums.size()-1 && nums[i]==0){\n continue;\n }\n if(count1+count2>sum){\n sum=count1+count2;\n }\n if(nums[i]==1){\n count2++;\n }\n else if (nums[i-1]==1 && nums[i+1]==1){\n count1=count2;\n count2=0;\n }\n else {\n count1=0;\n count2=0;\n }\n \n }\n if(count1+count2>sum){\n sum=count1+count2;\n }\n return sum;\n }\n};\n```\n#PLEASE UPVOTE MY SOLUTION IF U LIKE IT# | 3 | 0 | ['Two Pointers', 'C++'] | 3 |
longest-subarray-of-1s-after-deleting-one-element | ✅C++ | ✅Efficient & Easy solution | c-efficient-easy-solution-by-yash2arma-xm88 | Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution \n{\npublic:\n int longestSubarray(vector<int>& nums) \n {\n | Yash2arma | NORMAL | 2023-07-05T10:32:59.972806+00:00 | 2023-07-05T10:40:57.554531+00:00 | 240 | false | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution \n{\npublic:\n int longestSubarray(vector<int>& nums) \n {\n int lastzero=-1, i=0, j, ans=0, n=nums.size();\n for(j=0; j<n; j++)\n {\n if(nums[j]==0)\n {\n ans = max(ans, j-i-1);\n i = lastzero+1;\n lastzero = j; \n }\n }\n ans = max(ans, j-i-1);\n\n return ans;\n \n }\n};\n```\n## For better understanding dry run this code... | 3 | 0 | ['Array', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Easy cpp solution with detailed step wise explanation||Sliding Window Approach | easy-cpp-solution-with-detailed-step-wis-gho9 | Intuition\nFirst thought was to relate somehow with zeroes,as it requires maximum numbers of 1.\n\n# Approach\n1. Initialize variables: Initialize n as the size | Harsh_Balwani | NORMAL | 2023-07-05T10:28:58.422071+00:00 | 2023-07-05T10:28:58.422088+00:00 | 160 | false | # Intuition\nFirst thought was to relate somehow with zeroes,as it requires maximum numbers of 1.\n\n# Approach\n1. Initialize variables: Initialize `n` as the size of the `nums` vector, `start` as 0 (indicating the start index of the current subarray), `longwind` as 0 (representing the length of the longest subarray with at most one zero), `answer` as -1 (to keep track of the maximum length), and `zerocount` as 0 (to count the number of zeros encountered).\n\n2. Iterate through the `nums` vector: Start a `for` loop from `i = 0` to `i < n`.\n\n3. Check for zero: If the current element `nums[i]` is 0, increment the `zerocount` by 1.\n\n4. Check if `zerocount` is equal to 1: If `zerocount` is equal to 1, it means we have encountered the first zero in the subarray. Set `longwind` to the difference between the current index `i` and `start` (indicating the length of the current subarray without considering the first zero).\n\n5. Check if `zerocount` is greater than 1: If `zerocount` is greater than 1, it means we have encountered more than one zero in the current subarray. Enter a `while` loop to handle this case.\n\n6. Update the answer: If the current `longwind` is greater than the previous `answer`, update the `answer` to the value of `longwind`.\n\n7. Handle zeros: Check if the element at `start` index is 0. If it is, decrement `zerocount` by 1.\n\n8. Move the `start` pointer: Increment the `start` index by 1 to move the sliding window.\n\n9. Check if `zerocount` is equal to 1 and `i` is at the last index: If `zerocount` is equal to 1 and `i` is at the last index, it means we have reached the end of the array. Check if the `answer` is greater than the current `longwind`. If it is, return `answer`; otherwise, return `longwind`.\n\n10. Check if `zerocount` is equal to 0 and `i` is at the last index: If `zerocount` is equal to 0 and `i` is at the last index, it means there are no zeros in the array. Return `n-1`, indicating the length of the entire array as the longest subarray.\n\n11. Return the `answer`: After the loop, return the final value of `answer`, which represents the length of the longest subarray with at most one zero.\n\n# Complexity\n- Time complexity:\n - O(n*m)\n\n- Space complexity:\n - O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n=nums.size();\n int start=0;\n int longwind=0;\n int answer=-1;\n int zerocount=0;\n for(int i=0;i<n;i++)\n {\n if(nums[i]==0) zerocount++;\n if(zerocount==1)\n {\n longwind=i-start;\n \n }\n while(zerocount>1)\n {\n if(longwind>answer) answer=longwind;\n if(nums[start]==0) zerocount--;\n start++;\n } \n if(zerocount==1 && i==n-1)\n {\n if(answer>longwind) return answer;\n return longwind;\n }\n if(zerocount==0 && i==n-1) return n-1; \n } \n return answer;\n }\n};\n```\n# Please upvote and feel free to ask doubts. | 3 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | ✅ O(n) solution | 86 % faster 🚀 | Easy Understanding with Images 🏙️ | on-solution-86-faster-easy-understanding-cnlx | Intuition\n Describe your first thoughts on how to solve this problem. \n- If we want to remove one element, most probably a zero from the array then we need to | codingWith_aman | NORMAL | 2023-07-05T07:02:30.847136+00:00 | 2023-07-05T07:02:30.847169+00:00 | 139 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- If we want to remove one element, most probably a zero from the array then we need to count the number of 1\'s that is place around every zero.\n- Simply find the count of 1\'s on left and right side of a zero and return the max value that can be found.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Take any of the data structure to store the count of 1 on left and right side of a zero.\n- Sum the count and store the maximum value in a variable.\n- If the size of data-structure to store the count is 0, i.e. there are no zeroes in the array then simply return size of array-1 as we need to delete one element.\n\n\n\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: $$O(m)$$ : m = number of zeroes in array\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n\n List<Integer> store = new ArrayList<>();\n int n = nums.length, count = 0, max = 0;\n\n // to store the prefix sum\n for(int i = 0; i < n; i++) {\n\n if(nums[i] == 0) {\n store.add(count);\n count = 0;\n }\n else \n count++;\n }\n\n int k = store.size()-1;\n count = 0;\n\n // to store the postfix sum\n for(int i = n-1; i >= 0; i--) {\n\n if(nums[i] == 0) {\n int val = store.get(k)+count;\n store.set(k, val);\n max = val > max ? val : max;\n k--;\n count = 0;\n }\n else \n count++;\n }\n\n if(store.size() == 0) return n-1;\n else return max; \n }\n}\n```\n\nCan be done in one pass as well. | 3 | 0 | ['Array', 'Prefix Sum', 'Java'] | 1 |
longest-subarray-of-1s-after-deleting-one-element | Simple Memoization approach | simple-memoization-approach-by-akashtoma-n8zg | Intuition\nTry all possiblilty and add memoization.\n\n# Approach\n Since \n Only in the case where all elements are one we will have to delete one (resul | akashtomar19 | NORMAL | 2023-07-05T05:53:44.726247+00:00 | 2023-07-07T16:50:39.119418+00:00 | 2,038 | false | # Intuition\nTry all possiblilty and add memoization.\n\n# Approach\n Since \n Only in the case where all elements are one we will have to delete one (result will be totalSum - 1)\n Otherwise we can always delete zero and in case of deletion we can have two possibilites\n 1) Affect our result that is might increase the length of 1 (for ex del 0 in 11011)\n 2) Does not affect our result (for ex 1111000) \n So whenever we encounter zero \n .) if it is the first zero encountered from right then try deleting which might increase the length of 1s (for example zero b/w 1\'s in 0011011)\n or skip it \n .) if it is the second zero encountered then return 0 we are not allowed deleting this.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n * 2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * 2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n int ans = 0;\n vector<vector<int>>dp;\n int solve(vector<int>& nums, int n, int del){\n if(n < 0)return 0;\n if(dp[n][del] != -1)return dp[n][del];\n if(del){ // if zero is already deleted \n int cur = 0;\n if(nums[n]){\n cur = 1 + solve(nums, n - 1, del);\n ans = max(ans, cur);\n return dp[n][del] = cur;\n }\n return dp[n][del] = 0; // if zero is deleted and again we encountered zero we cannot consider subarray starting from here\n } else {\n int cur = 0;\n if(nums[n]){ // if not encountered zero then keep expanding the length of array with 1\'s\n cur = 1 + solve(nums, n - 1, del);\n ans = max(ans, cur);\n return dp[n][del] = cur;\n }\n // if first zero encountered\n int nodelete = solve(nums, n - 1, 0); // try not deleting it that means completely skip it \n int deleted = solve(nums, n - 1, 1); // try deleting it\n ans = max({ans, deleted, nodelete});\n return dp[n][del] = deleted; // return the result of deleting one because in previous states we have not deleted zero so this needs to be considered for expansion of length\n }\n return 0;\n }\n int longestSubarray(vector<int>& nums) {\n dp.resize(nums.size(), vector<int>(2, -1));\n int sum = 0;\n sum = accumulate(nums.begin(), nums.end(), 0);\n if(sum == nums.size())return sum - 1;\n solve(nums, (int)nums.size() - 1, 0);\n return ans;\n }\n};\n``` | 3 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 2 |
longest-subarray-of-1s-after-deleting-one-element | ✅✅C++ || Easy Solution || Sliding Window | c-easy-solution-sliding-window-by-raz3r-dzn2 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | raz3r | NORMAL | 2023-07-05T05:44:58.291394+00:00 | 2023-07-05T05:44:58.291413+00:00 | 1,295 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i=0, j=0, ct0=0, total=0, mx=0;\n while(j<nums.size()){\n if(nums[j]==0){\n ct0++;\n while(ct0>1){\n if(nums[i]==0) ct0--;\n else total--;\n i++;\n }\n }\n else{\n total++;\n mx=max(mx, total);\n }\n j++;\n }\n if(mx==nums.size()) return --mx;\n return mx;\n }\n};\n``` | 3 | 0 | ['Array', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Optimised solution using sliding windows and single pass | optimised-solution-using-sliding-windows-bbt5 | Approach\nTo solve this problem, we can use a sliding window approach. We\'ll maintain two pointers, left and right, that define the current subarray we\'re con | priyanshu11_ | NORMAL | 2023-07-05T05:37:14.680080+00:00 | 2023-07-05T05:37:14.680119+00:00 | 254 | false | # Approach\nTo solve this problem, we can use a sliding window approach. We\'ll maintain two pointers, left and right, that define the current subarray we\'re considering. We\'ll initialize both pointers to the start of the array.\n\nThe idea is to iterate through the array and expand the window by moving the right pointer to the right. If the window still contains only one zero element, we continue expanding it. If we encounter a second zero element, we need to shrink the window by moving the left pointer to the right until we remove one zero element.\n\nWhile expanding the window, we\'ll keep track of the maximum length of a subarray containing only ones. After each expansion, we\'ll update the maximum length if necessary.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# C++ Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int left = 0; // left pointer\n int zeros = 0; // number of zeros in the current window\n int maxLen = 0; // maximum length of a subarray containing only ones\n \n int n = nums.size();\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0)\n zeros++;\n \n // Shrink the window if there are more than one zeros\n while (zeros > 1) {\n if (nums[left] == 0)\n zeros--;\n left++;\n }\n \n // Update the maximum length\n maxLen = max(maxLen, right - left);\n }\n \n return maxLen;\n }\n};\n\n```\n# Java Code\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int left = 0; // left pointer\n int zeros = 0; // number of zeros in the current window\n int maxLen = 0; // maximum length of a subarray containing only ones\n\n int n = nums.length;\n for (int right = 0; right < n; right++) {\n if (nums[right] == 0)\n zeros++;\n\n // Shrink the window if there are more than one zeros\n while (zeros > 1) {\n if (nums[left] == 0)\n zeros--;\n left++;\n }\n\n // Update the maximum length\n maxLen = Math.max(maxLen, right - left);\n }\n\n return maxLen;\n }\n}\n``` | 3 | 0 | ['Array', 'Dynamic Programming', 'Sliding Window', 'C++', 'Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Simple C++ solution | simple-c-solution-by-samarpan27-8ssn | Intuition\n Describe your first thoughts on how to solve this problem. \nBased on counting number of 1 and 2 in nums\n# Approach\n Describe your approach to sol | Samarpan27 | NORMAL | 2023-07-05T05:07:22.490917+00:00 | 2023-07-05T05:08:07.787057+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBased on counting number of 1 and 2 in nums\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWhile traversing nums we keep track of number of 1 and 2. If nums[i] is 1 we simply increment n_one by 1 and calculate ans based on no of zero present till now. If nums[i] is 0, then we check if curretly we don\'t have any zero previously, we calculate answer by not considering this zero (ie by deleting this zero), if previosly we have a zero, then we can\'t delete 2 zeroes, so we traverse j till we get no of zeroes again=1 and we calculate answer.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n if(nums.size()==1)\n return 0;\n int i=0,j=0,n_zero=0,n_one=0,ans=0;\n while(i<nums.size() && j<nums.size())\n {\n if(nums[i]==1)\n {\n n_one++;\n if(n_zero==0)\n ans = max(ans,n_one - 1);\n else\n ans=max(ans,n_one);\n }\n else\n {\n n_zero++;\n if(n_zero==1)\n ans=max(ans,n_one);\n else\n {\n while(j<nums.size() && n_zero>1)\n {\n if(nums[j]==1)\n n_one--;\n else\n n_zero--;\n\n j++;\n }\n ans=max(ans,n_one);\n }\n }\n\n i++;\n }\n \n return ans;\n }\n};\n```\n\nPlease Upvote if you liked this solution!! | 3 | 0 | ['Two Pointers', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | SUPER EASY SOLUTION | super-easy-solution-by-himanshu__mehra-cg01 | Code\n\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i=0;\n int j=0;\n int n=nums.size();\n int c0= | himanshu__mehra__ | NORMAL | 2023-07-05T04:51:24.466880+00:00 | 2023-07-05T04:51:24.466911+00:00 | 283 | false | # Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i=0;\n int j=0;\n int n=nums.size();\n int c0=0;\n int mx=0;\n while(j<n){\n if(nums[j]==0){\n c0++;\n }\n while(i<n&&c0==2){\n if(nums[i]==0){\n c0--;\n }\n i++;\n }\n mx=max(j-i,mx);\n j++;\n }\n return mx;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | 🔥💯Best Explanation [C++,JAVA]💯|| 🌟NO DP || Sliding Window✅ | best-explanation-cjava-no-dp-sliding-win-5y6z | Connect with me on LinkedIn : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n# Approach\n## 1. Initialize variables:\n- n stores the size of the in | aDish_21 | NORMAL | 2023-07-05T02:55:53.193127+00:00 | 2023-07-05T03:34:47.771427+00:00 | 236 | false | ### Connect with me on LinkedIn : https://www.linkedin.com/in/aditya-jhunjhunwala-51b586195/\n# Approach\n## 1. Initialize variables:\n- n stores the size of the input vector nums.\n- i and j are indices used for iterating through the vector.\n- count_before_0 and count_after_0 are counters to keep track of the lengths of the subarrays before and after the zero.\n- maxi stores the maximum length found so far.\n- is_0_present is a boolean flag indicating whether a zero has been encountered.\n\n## 2. Iterate through the vector:\n- While j is less than the size of nums, perform the following steps:\n\n## 3. Check if the current element is zero:\n\n- If nums[j] is equal to 0, it means a zero has been encountered.\n- Check if is_0_present is false:\n- If it\'s false, set is_0_present to true, indicating that the first zero has been found.\n- If it\'s true, it means there is already a zero present in the subarray.\n- Update maxi with the maximum of the current count before and after zero.\n- Set count_before_0 to count_after_0 (the count after the previous zero).\n- Reset count_after_0 to 0 to start counting again from the next element.\n\n## 4. Count elements before and after zero:\n- If is_0_present is false, it means no zero has been encountered yet & so increment count_before_0 to count the length of the subarray before a zero.\n- If is_0_present is true, it means a zero has been encountered & so increment count_after_0 to count the length of the subarray after the last zero.\n\n## 5. Move to the next element:\n- Increment j to move to the next element in the vector.\n\n## 6. Finalize the maximum length:\n- After the loop, update maxi with the maximum of the current count before and after the last zero encountered.\n\n## 7. Return the result:\n- If is_0_present is true, return maxi as the length of the longest subarray.\n- If is_0_present is false, subtract 1 from maxi and return the result (since there is no zero present).\n\n# Complexity\n```\n- Time complexity:\nO(n)\n\n```\n```\n- Space complexity:\nO(1)\n```\n### NOTE : Here no need to take (is_0_present variable) as u can also do it like whenever nums[j] == 1 then always only increment count_after_0 & when nums[j] == 0 then simply store maxi = max(maxi,count_before_0 + count_after_0) & initialize count_before_0 = count_after_0 & count_after_0 = 0 (P.S : I have only used this xtra variable in order to make u understand & make my code readable).\n## I have also provided this code using name "Short Version"\n# Code\n## Please Upvote if u found it useful\uD83E\uDD17\n# C++\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n // Initialize variables\n int n = nums.size(); // Size of the input vector\n int i = 0, j = 0; // Indices for iterating through the vector\n int count_before_0 = 0, count_after_0 = 0; // Counters for lengths of subarrays\n int maxi = 0; // Maximum length found so far\n bool is_0_present = false; // Flag indicating if a zero has been encountered\n\n // Iterate through the vector\n while (j < n) {\n // Check if the current element is zero\n if (nums[j] == 0) {\n // If zero is encountered for the first time\n if (!is_0_present) {\n is_0_present = true;\n }\n // If there is already a zero present in the subarray\n else {\n // Update maxi with the maximum of count_before_0 + count_after_0\n maxi = max(maxi, count_before_0 + count_after_0);\n // Update count_before_0 with count_after_0\n count_before_0 = count_after_0;\n // Reset count_after_0 to 0\n count_after_0 = 0;\n }\n }\n // If the current element is not zero\n else {\n // If no zero has been encountered yet, increment count_before_0\n if (!is_0_present) {\n count_before_0++;\n }\n // If a zero has been encountered, increment count_after_0\n if (is_0_present) {\n count_after_0++;\n }\n }\n // Move to the next element\n j++;\n }\n\n // Update maxi with the maximum of count_before_0 + count_after_0\n maxi = max(maxi, count_before_0 + count_after_0);\n\n // Return the result\n // If a zero is present, return maxi as the length of the longest subarray\n // If no zero is present, subtract 1 from maxi and return the result\n return is_0_present ? maxi : maxi - 1;\n }\n};\n```\n# Short version :-\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n = nums.size(),i = 0,j = 0,count_before_0 = 0,count_after_0 = 0,maxi = 0;\n while(j < n){\n if(nums[j] == 0){\n maxi = max(maxi,count_before_0 + count_after_0);\n count_before_0 = count_after_0;\n count_after_0 = 0;\n }\n else\n count_after_0 ++;\n j++;\n }\n maxi = max(maxi,count_before_0 + count_after_0);\n return maxi != n ? maxi : maxi - 1;\n }\n};\n```\n# JAVA\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int n = nums.length;\n int i = 0, j = 0, count_before_0 = 0, count_after_0 = 0, maxi = 0;\n boolean is_0_present = false;\n\n while (j < n) {\n if (nums[j] == 0) {\n if (!is_0_present) {\n is_0_present = true;\n } else {\n maxi = Math.max(maxi, count_before_0 + count_after_0);\n count_before_0 = count_after_0;\n count_after_0 = 0;\n }\n } else {\n if (!is_0_present) {\n count_before_0++;\n }\n if (is_0_present) {\n count_after_0++;\n }\n }\n j++;\n }\n maxi = Math.max(maxi, count_before_0 + count_after_0);\n return is_0_present ? maxi : maxi - 1;\n }\n}\n```\n\n | 3 | 0 | ['Array', 'Sliding Window', 'C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Sliding Window - MAX 1 zero inside. [C++/Python] | sliding-window-max-1-zero-inside-cpython-g91y | \n\n# Code\n\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i = 0, j = 0, ans = 0, cnt = 1, n = nums.size();\n whi | tryingall | NORMAL | 2023-07-05T02:48:28.441114+00:00 | 2023-07-05T02:48:28.441138+00:00 | 618 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int i = 0, j = 0, ans = 0, cnt = 1, n = nums.size();\n while(j < n)\n {\n if(nums[j] == 0) {\n --cnt;\n }\n while(cnt < 0)\n {\n if(nums[i] == 0) {\n ++cnt;\n }\n \n ++i;\n }\n ans = max(ans, j-i);\n ++j;\n }\n return ans;\n }\n};\n```\n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n i, j = 0, 0\n ans = 0\n cnt = 1\n n = len(nums)\n\n while j < n:\n if nums[j] == 0:\n cnt -= 1\n while cnt < 0:\n if nums[i] == 0:\n cnt += 1\n i += 1\n ans = max(ans, j-i)\n j += 1\n\n return ans\n``` | 3 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | [ C++ ] [ Left and Right Counting ] | c-left-and-right-counting-by-sosuke23-z353 | Code\n\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n=(int)nums.size();\n \n if(n==1){\n retur | Sosuke23 | NORMAL | 2023-07-05T02:41:02.975119+00:00 | 2023-07-05T02:41:02.975148+00:00 | 956 | false | # Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& nums) {\n int n=(int)nums.size();\n \n if(n==1){\n return 0;\n }\n if(count(nums.begin(),nums.end(),0)==0){\n return n-1;\n }\n \n int cnt=0;\n vector<int> tot;\n for(int i=0;i<n;i++){\n if(nums[i]==0){\n tot.push_back(cnt);\n tot.push_back(0);\n cnt=0;\n }\n else{\n cnt++;\n }\n }\n if(cnt){\n tot.push_back(cnt);\n }\n int res=0;\n for(int i=0;i<(int)tot.size();i++){\n if(i-1>=0 and i+1<(int)tot.size() and tot[i]==0 and tot[i-1]>0 and tot[i+1]>0){\n res=max(res,tot[i-1]+tot[i+1]);\n }\n else if(i-1>=0 and i+1<(int)tot.size()){\n if(tot[i]==0 and tot[i-1]>0){\n res=max(res,tot[i-1]);\n }\n if(tot[i+1]>0 and tot[i]==0){\n res=max(res,tot[i+1]);\n }\n }\n }\n return res;\n }\n};\n``` | 3 | 0 | ['C++'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Java Easy Solution Sliding Window | java-easy-solution-sliding-window-by-sai-k89f | #upvote if you like the solution\n\n\n\nclass Solution {\n public int longestSubarray(int[] nums) {\n int ans = 0;\n int z = 0, si = 0 , cur | Saitama_2727 | NORMAL | 2023-07-05T02:24:14.482900+00:00 | 2023-07-05T02:24:14.482923+00:00 | 297 | false | # #upvote *if you like the solution*\n\n\n```\nclass Solution {\n public int longestSubarray(int[] nums) {\n int ans = 0;\n int z = 0, si = 0 , cur = 0, ei = nums.length-1;\n while(cur<=ei){ \n \n // growing the window size\n if(nums[cur] == 0){\n z++;\n }\n \n // shrinking the window size and move the position of\n // start from old to new position\n while(si<=cur && z>1 ){\n if(nums[si]==0){\n z--;\n }\n si++;\n }\n \n // taking answer max window size\n ans = Math.max(ans, cur - si);\n cur++;\n }\n return ans;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Python3 Solution | python3-solution-by-motaharozzaman1996-clm5 | \n\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n=len(nums)\n best=0\n left=0\n right=0\n curr= | Motaharozzaman1996 | NORMAL | 2023-07-05T02:22:04.591643+00:00 | 2023-07-05T02:22:04.591674+00:00 | 292 | false | \n```\nclass Solution:\n def longestSubarray(self, nums: List[int]) -> int:\n n=len(nums)\n best=0\n left=0\n right=0\n curr=0\n while right<n:\n if nums[right]==0:\n curr+=1\n while curr>1:\n if nums[left]==0:\n curr-=1\n left+=1\n\n right+=1\n best=max(best,right-left-1)\n\n return best\n``` | 3 | 0 | ['Python', 'Python3'] | 0 |
longest-subarray-of-1s-after-deleting-one-element | Sliding Window , C++ Beats 100% ✅✅ | sliding-window-c-beats-100-by-deepak_591-a7di | if it Helps You. Please Upvote Me.....\uD83E\uDDE1\uD83E\uDD0D\uD83D\uDC9A\n# Approach\n Describe your approach to solving the problem. \nUsing Sliding Window a | Deepak_5910 | NORMAL | 2023-07-05T01:36:11.305459+00:00 | 2023-07-05T01:36:11.305481+00:00 | 470 | false | # if it Helps You. Please Upvote Me.....\uD83E\uDDE1\uD83E\uDD0D\uD83D\uDC9A\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Using Sliding Window approach, Find the largest subarray in which zero occurs exactly once.**\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int longestSubarray(vector<int>& arr) {\n \n int n = arr.size(),ans = 0,i = 0,j = 0,count = 0;\n while(j<n)\n {\n if(arr[j]==0) count++;\n while(i<j && count>1)\n {\n if(arr[i]==0) count--;\n i++;\n }\n ans = max(ans,j-i);\n j++;\n }\n return ans;\n }\n};\n```\n\n | 3 | 0 | ['Sliding Window', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | ✅Recursion✅ || Brute Force || C++ || Java | recursion-brute-force-c-java-by-anishkrs-h9ii | Intuition \nSince the constraints are very less we can apply recursion here.\n# Approach\nEach time we encounter a cell with grid[i][j] == 0 then we can take 1 | AnishKrSingh | NORMAL | 2023-09-10T04:01:27.917447+00:00 | 2024-10-12T09:00:46.803259+00:00 | 11,046 | false | # Intuition \n**``` Since the constraints are very less we can apply recursion here.```**\n# Approach\n**```Each time we encounter a cell with grid[i][j] == 0 then we can take 1 from any of the other 8 cells which have a value > 1```**\n\n# Complexity\n**- Time complexity:**\n**```The maximum depth of recursion is O(n^2).\nThe maximum depth of recursion is O(n\xB2). For each recursive call, there are up to 8 possible moves for each empty cell. Therefore, the overall time complexity is O(8^(n\xB2)) in the worst case. ```**\n\n**Therefore, the overall time complexity is O(8^(n\xB2)).**\n\n**- Space complexity:**\n**```The space complexity is O(D), where D is the maximum depth of the recursion ```**\n\n# Code (C++)\n```\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n // Base Case\n int t = 0;\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (grid[i][j] == 0)\n t++;\n if (t == 0)\n return 0;\n \n int ans = INT_MAX;\n for (int i = 0; i < 3; ++i)\n {\n for (int j = 0; j < 3; ++j)\n {\n if (grid[i][j] == 0)\n {\n for (int ni = 0; ni < 3; ++ni)\n {\n for (int nj = 0; nj < 3; ++nj)\n {\n int d = abs(ni - i) + abs(nj - j);\n if (grid[ni][nj] > 1)\n {\n grid[ni][nj]--;\n grid[i][j]++;\n ans = min(ans, d + minimumMoves(grid));\n grid[ni][nj]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n};\n\n```\n# Code (Java)\n```\nimport java.util.*;\npublic class Solution {\n public int minimumMoves(int[][] grid) {\n // Base Case\n int t = 0;\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (grid[i][j] == 0)\n t++;\n if (t == 0)\n return 0;\n\n int ans = Integer.MAX_VALUE;\n for (int i = 0; i < 3; ++i) {\n for (int j = 0; j < 3; ++j) {\n if (grid[i][j] == 0) {\n for (int ni = 0; ni < 3; ++ni) {\n for (int nj = 0; nj < 3; ++nj) {\n int d = Math.abs(ni - i) + Math.abs(nj - j);\n if (grid[ni][nj] > 1) {\n grid[ni][nj]--;\n grid[i][j]++;\n ans = Math.min(ans, d + minimumMoves(grid));\n grid[ni][nj]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n}\n\n```\n``` Please Upvote if it was helpful ``` | 91 | 0 | ['Backtracking', 'Recursion', 'C++', 'Java'] | 17 |
minimum-moves-to-spread-stones-over-grid | 🔥✅ Java BFS Easy Solution 🔥✅ | java-bfs-easy-solution-by-vishesht27-sl6b | Intuition\nGiven the setup of the problem, it is reminiscent of sliding tile puzzles where you aim to get from one configuration to another using a series of sl | vishesht27 | NORMAL | 2023-09-10T04:04:03.740354+00:00 | 2023-09-10T04:05:58.121140+00:00 | 6,144 | false | # Intuition\nGiven the setup of the problem, it is reminiscent of sliding tile puzzles where you aim to get from one configuration to another using a series of slides. In this case, you\'re trying to shift the stones around to get from one grid configuration to the target configuration. Naturally, this leads to thinking about a Breadth-First Search (BFS) approach, where each step or "slide" would correspond to a move.\n\n# Approach\n\n1. Initial State: Convert the 2D grid into a 1D representation. This simplification makes it easier to iterate and manipulate the state of the grid.\n2. Target State: The final configuration that we desire is a grid with a single stone in every cell. So, the target is represented as a 1D array of nines.\n3. BFS: Start BFS with the initial state. At each step, for every cell that has more than one stone, try to move one stone to its adjacent cell. Keep track of the visited states using a HashSet to avoid unnecessary repetition.\n4. Generating Adjacent Cells: For any given cell index, its adjacent cells can be deduced based on its position (whether it\'s on an edge or not). This is done using the helper function getAdjacent.\n5. End Condition: The BFS continues until the current state matches the target state or the BFS completes without finding a solution.\nComplexity\n\n# Complexity\n- Time complexity: O(9!)\n\n- Space complexity: O(9!)\n\n# Code\n```\nimport java.util.*;\n\nclass Solution {\n public int minimumMoves(int[][] grid) {\n int[] start = new int[9];\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n start[i * 3 + j] = grid[i][j];\n }\n }\n \n int[] target = {1, 1, 1, 1, 1, 1, 1, 1, 1};\n \n Queue<int[]> queue = new LinkedList<>();\n Set<String> visited = new HashSet<>();\n \n queue.offer(start);\n visited.add(Arrays.toString(start));\n \n int moves = 0;\n \n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int[] curr = queue.poll();\n \n if (Arrays.equals(curr, target)) {\n return moves;\n }\n \n for (int j = 0; j < 9; j++) {\n if (curr[j] > 1) {\n // Try to move to adjacent cells\n for (int next : getAdjacent(j)) {\n int[] newState = curr.clone();\n newState[j]--;\n newState[next]++;\n if (!visited.contains(Arrays.toString(newState))) {\n visited.add(Arrays.toString(newState));\n queue.offer(newState);\n }\n }\n }\n }\n }\n moves++;\n }\n \n return -1;\n }\n \n private List<Integer> getAdjacent(int index) {\n List<Integer> adjacent = new ArrayList<>();\n \n if (index % 3 != 0) adjacent.add(index - 1);\n if (index % 3 != 2) adjacent.add(index + 1);\n if (index / 3 != 0) adjacent.add(index - 3);\n if (index / 3 != 2) adjacent.add(index + 3);\n \n return adjacent;\n }\n}\n\n```\n\n\n\n | 60 | 1 | ['Array', 'Hash Table', 'Breadth-First Search', 'Queue', 'Matrix', 'Hash Function', 'Java'] | 13 |
minimum-moves-to-spread-stones-over-grid | Python: Hungarian assignment. 10 Lines. O(n^3) beats 100% | python-hungarian-assignment-10-lines-on3-yarl | Intuition\nThe problem is a standard Hungarian algorithm\n\nIterate over all elements in the matrix and check where you have 0 and where you have values > 1.\n\ | salvadordali | NORMAL | 2023-09-10T04:12:03.669013+00:00 | 2023-09-10T04:14:44.771620+00:00 | 3,621 | false | # Intuition\nThe problem is a standard [Hungarian algorithm](https://en.wikipedia.org/wiki/Hungarian_algorithm)\n\nIterate over all elements in the matrix and check where you have 0 and where you have values > 1.\n\nValues above 1 will be values from which you are moving, values with 0, where are you moving.\n\nThen build a matrix of cost where cost is the distance between two points. You can do this easily with [cdist](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist) module where metric is manhathan distance (called cityblock there)\n\nAnd just use [linear assignment](https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.linear_sum_assignment.html)\n\n# Complexity\n- Time complexity: $O(n^3)$\n- Space complexity: $O(n^2)$\n\n# Code\n```\nfrom scipy.optimize import linear_sum_assignment\nimport numpy as np\n\n\nclass Solution:\n def minimumMoves(self, M: List[List[int]]) -> int:\n data_from, data_to = [], []\n for i in range(3):\n for j in range(3):\n if M[i][j] == 0:\n data_to.append((i, j))\n elif M[i][j] > 1:\n data_from.extend([(i, j)] * (M[i][j] - 1))\n\n cost = cdist(data_from, data_to, metric=\'cityblock\')\n row_ind, col_ind = linear_sum_assignment(cost)\n return int(cost[row_ind, col_ind].sum())\n``` | 28 | 1 | ['Python3'] | 8 |
minimum-moves-to-spread-stones-over-grid | Python 3 || 6 lines, permutation, w/ explanation || T/S: 65% / 71% | python-3-6-lines-permutation-w-explanati-ma40 | Here\'s the plan:\n1. We compile the coordinates (i, j) of (a) zeros in zero and (b) spare stones in spare.\n\n1. We construct a set of permutations of spare a | Spaulding_ | NORMAL | 2023-09-10T19:03:05.518610+00:00 | 2024-06-18T00:52:29.482866+00:00 | 1,823 | false | Here\'s the plan:\n1. We compile the coordinates (i, j) of (a) zeros in `zero` and (b) *spare* stones in `spare`.\n\n1. We construct a set of permutations of `spare` and match each permutation with `zero`.\n1. We compute the sum of moves for each pairing and return the minimum.\n\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n\n dist = lambda x,y: abs(x[0]-y[0])+ abs(x[1]-y[1]) \n zeros, spare = [], []\n\n for i,j in product(range(3),range(3)):\n\n stone = grid[i][j]\n if stone == 0: zeros.append((i,j)) # <-- 1a)\n if stone > 1: spare.extend([(i,j)]*(stone-1)) # <-- 1b)\n\n return min((sum(map(dist, zeros, per))) for per in # <-- 2) and 3) \n set(permutations(spare)))\n```\n[https://leetcode.com/problems/minimum-moves-to-spread-stones-over-grid/submissions/1201933456/](https://leetcode.com/problems/minimum-moves-to-spread-stones-over-grid/submissions/1201933456/)\n\nI could be wrong, but I think that time complexity is *O*(*M* !) and space complexity is *O*(*M*), in which *M* ~ the number of spare stones.. | 24 | 0 | ['Python3'] | 5 |
minimum-moves-to-spread-stones-over-grid | Java || DFS + Backtrack || Easy to Undertand | java-dfs-backtrack-easy-to-undertand-by-r2xlj | Idea\n\nLet\'s call empty cells consumers. Suppliers for rich cells.\n\n> Please \u2B06\uFE0F upvote if you like my diagrams :)\n\nFor each consumer, DFS on ea | cooper-- | NORMAL | 2023-09-10T04:01:49.706836+00:00 | 2023-09-10T04:17:33.403941+00:00 | 1,306 | false | ### Idea\n\nLet\'s call empty cells `consumers`. `Suppliers` for rich cells.\n\n> Please \u2B06\uFE0F upvote if you like my diagrams :)\n\nFor each `consumer`, DFS on each available `supplier`. Use `flag` to mark avaliability instead of pop and add.\n(DFS is accepted since only 3 * 3)\n\n\n---\n\nBesides, greedy does not work. Don\'t ask me why. Here is a case when greedy failed to solve.\nNote: for each consumer, find cloesest supplier.\n\n\n\n### Code\n```java\nclass Solution {\n\n public int minimumMoves(int[][] grid) {\n List<int[]> consumers = new ArrayList<>();\n List<int[]> suppliers = new ArrayList<>();\n \n for (int r = 0; r < 3; r++) {\n for (int c = 0; c < 3; c++) {\n if (grid[r][c] == 0)\n consumers.add(new int[]{r, c});\n else if (grid[r][c] > 1) \n suppliers.add(new int[]{r, c, 1});\n }\n }\n\n return dfs(0, consumers, suppliers, grid);\n }\n \n private int dfs(int pos, List<int[]> consumers, List<int[]> suppliers, int[][] grid) {\n if (pos == consumers.size()) \n return 0;\n\n int min = Integer.MAX_VALUE;\n for (int i = 0; i < suppliers.size(); i++) {\n int[] s = suppliers.get(i);\n if (s[2] == 0) continue;\n grid[s[0]][s[1]]--;\n if (grid[s[0]][s[1]] == 1) {\n s[2] = 0;\n }\n min = Math.min(min, dfs(pos + 1, consumers, suppliers, grid) + getDis(consumers.get(pos), s));\n grid[s[0]][s[1]]++;\n s[2] = 1;\n }\n return min;\n }\n \n private int getDis(int[] a, int[] b) {\n return Math.abs(a[0] - b[0]) + Math.abs(a[1] - b[1]);\n }\n \n\n// greedy failed case\n /**\n Input:\n [[3,2,0],\n [0,1,0],\n [0,3,0]]\n 9\n 7\n **\n */\n}\n``` | 20 | 0 | ['Backtracking', 'Depth-First Search', 'Java'] | 3 |
minimum-moves-to-spread-stones-over-grid | Video Solution 🔥(C++,JAVA,PYTHON) || Brute Force✅ || Recursion 🔥 || Back Tracking ✅ | video-solution-cjavapython-brute-force-r-0gq3 | Intuition\n Describe your first thoughts on how to solve this problem. \nIf you observe the Constraints they are very minimum 33=9. So we can solve using Brute | ayushnemmaniwar12 | NORMAL | 2023-09-10T04:48:33.387722+00:00 | 2023-09-10T04:53:56.982106+00:00 | 3,396 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you observe the Constraints they are very minimum 3*3=9. So we can solve using Brute Force methods\n\n# ***Detailed and easy Video Solution***\nhttps://youtu.be/soC2B658iFY\n\n# Summary\n<!-- Describe your approach to solving the problem. -->\nhe code uses a depth-first search approach, recursively exploring possible moves. For each move, it calculates the Manhattan distance between the current position and the target position for each number. The algorithm minimizes the total distance by exploring all possible arrangements. The code converts the problem into a graph traversal problem and keeps track of visited cells. The final result is the minimum number of moves needed to reach the target state.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n The code uses a depth-first search (DFS) approach to explore all possible configurations of the puzzle.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O((3*3)!)->O(9!)->O((N*N)!)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(9)->O(N*N)\n\n```C++ []\nclass Solution {\npublic:\n int ans;\n void solve(int i,vector<vector<int>>&a,vector<vector<int>>&b,vector<int>&vis,int c,int s)\n { \n if(c==b.size())\n { \n ans=min(ans,s);\n return;\n }\n for(int j=0;j<b.size();j++)\n { \n if(vis[j]==1)\n continue;\n vis[j]=1;\n int x=abs(a[i][0]-b[j][0])+abs(a[i][1]-b[j][1]);\n solve(i+1,a,b,vis,c+1,s+x);\n vis[j]=0;\n }\n }\n int minimumMoves(vector<vector<int>>& v) {\n vector<vector<int>>a;//stones\n vector<vector<int>>b;//empty\n for(int i=0;i<3;i++)\n {\n for(int j=0;j<3;j++)\n {\n if(v[i][j]==0)\n {\n vector<int>t{i,j};\n b.push_back(t);\n }\n else\n {\n int x=v[i][j]-1;\n vector<int>t{i,j};\n while(x--)\n {\n a.push_back(t);\n }\n }\n }\n }\n int x=b.size();\n vector<int>vis(x,0);\n ans=INT_MAX;\n solve(0,a,b,vis,0,0);\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def __init__(self):\n self.ans = float(\'inf\')\n\n def solve(self, i, a, b, vis, c, s):\n if c == len(b):\n self.ans = min(self.ans, s)\n return\n for j in range(len(b)):\n if vis[j] == 1:\n continue\n vis[j] = 1\n x = abs(a[i][0] - b[j][0]) + abs(a[i][1] - b[j][1])\n self.solve(i + 1, a, b, vis, c + 1, s + x)\n vis[j] = 0\n\n def minimumMoves(self, v):\n a = []\n b = []\n for i in range(3):\n for j in range(3):\n if v[i][j] == 0:\n b.append([i, j])\n else:\n x = v[i][j] - 1\n t = [i, j]\n while x > 0:\n a.append(t.copy())\n x -= 1\n x = len(b)\n vis = [0] * x\n self.ans = float(\'inf\')\n self.solve(0, a, b, vis, 0, 0)\n return self.ans\n\n```\n```JAVA []\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Solution {\n private int ans;\n\n private void solve(int i, List<List<Integer>> a, List<List<Integer>> b, List<Integer> vis, int c, int s) {\n if (c == b.size()) {\n ans = Math.min(ans, s);\n return;\n }\n for (int j = 0; j < b.size(); j++) {\n if (vis.get(j) == 1)\n continue;\n vis.set(j, 1);\n int x = Math.abs(a.get(i).get(0) - b.get(j).get(0)) + Math.abs(a.get(i).get(1) - b.get(j).get(1));\n solve(i + 1, a, b, vis, c + 1, s + x);\n vis.set(j, 0);\n }\n }\n\n public int minimumMoves(List<List<Integer>> v) {\n List<List<Integer>> a = new ArrayList<>();\n List<List<Integer>> b = new ArrayList<>();\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (v.get(i).get(j) == 0) {\n List<Integer> t = new ArrayList<>();\n t.add(i);\n t.add(j);\n b.add(t);\n } else {\n int x = v.get(i).get(j) - 1;\n List<Integer> t = new ArrayList<>();\n t.add(i);\n t.add(j);\n while (x-- > 0) {\n a.add(t);\n }\n }\n }\n }\n int x = b.size();\n List<Integer> vis = new ArrayList<>(x);\n for (int i = 0; i < x; i++) {\n vis.add(0);\n }\n ans = Integer.MAX_VALUE;\n solve(0, a, b, vis, 0, 0);\n return ans;\n }\n}\n```\n\n# ***If you like the solution Please Upvote and subscribe to my youtube channel***\n***It Motivates me to record more videos\nThank you*** | 18 | 1 | ['Backtracking', 'Recursion', 'C++', 'Java', 'Python3'] | 2 |
minimum-moves-to-spread-stones-over-grid | 🔥Python two different methods: DFS & BFS🔥 | python-two-different-methods-dfs-bfs-by-c183e | \n\n# DFS Code \u2705\nThe state of DFS is the current grid, and one branch represents moving 1 stone from a cell with more than 1 stones to an empty cell. Opti | Michael-Yang | NORMAL | 2023-09-17T23:05:14.409742+00:00 | 2023-09-17T23:18:18.901923+00:00 | 1,881 | false | \n\n# DFS Code \u2705\nThe state of DFS is the current grid, and one branch represents moving 1 stone from a cell with more than 1 stones to an empty cell. Optimized with memorization.\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n memo = {}\n def compute_string(g):\n res = ""\n for i in range(3):\n for j in range(3):\n res += str(g[i][j])\n return res\n def dfs(grid):\n nonlocal memo\n grid_s = compute_string(grid)\n if grid_s in memo: return memo[grid_s]\n\n non_zero = True\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n non_zero = False\n if non_zero:\n memo[grid_s] = 0\n return 0\n res = float("inf")\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n for x in range(3):\n for y in range(3):\n if grid[x][y] > 1:\n dist = abs(i-x) + abs(j-y)\n grid[i][j] += 1\n grid[x][y] -= 1\n res = min(res, dist + dfs(grid))\n grid[i][j] -= 1\n grid[x][y] += 1\n memo[grid_s] = res\n return res\n return dfs(grid)\n```\n\n# BFS Code (TLE)\nThis is my initial intuition to solve the problem, but got TLE. I think it has the same idea as [this one](https://leetcode.com/problems/minimum-moves-to-spread-stones-over-grid/solutions/4024683/java-bfs-easy-solution/) and has TC $$O(9!)$$ since there are at most $$9!$$ states. For the given example 2, I have printed the size of visited set when the target state is reached: my visited set has a size of 66 while the Java method\'s visited set has a size of 157. Not sure why my solution gets TLE, is it because of the difference between Python and Java???\n\n```\nimport copy\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n def compute_string(g):\n res = ""\n for i in range(3):\n for j in range(3):\n res += str(g[i][j])\n return res\n target = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n queue = deque()\n queue.append(grid)\n step = 0\n visited = set()\n while queue:\n for _ in range(len(queue)):\n cur_grid = queue.popleft()\n if cur_grid == target: return step\n visited.add(compute_string(cur_grid))\n for i in range(3):\n for j in range(3):\n if cur_grid[i][j] > 1:\n if i+1 < 3:\n temp = copy.deepcopy(cur_grid)\n temp[i+1][j] += 1\n temp[i][j] -= 1\n if compute_string(temp) not in visited:\n queue.append(temp)\n if j+1 < 3:\n temp = copy.deepcopy(cur_grid)\n temp[i][j+1] += 1\n temp[i][j] -= 1\n if compute_string(temp) not in visited:\n queue.append(temp)\n if i > 0:\n temp = copy.deepcopy(cur_grid)\n temp[i-1][j] += 1\n temp[i][j] -= 1\n if compute_string(temp) not in visited:\n queue.append(temp)\n if j > 0:\n temp = copy.deepcopy(cur_grid)\n temp[i][j-1] += 1\n temp[i][j] -= 1\n if compute_string(temp) not in visited:\n queue.append(temp)\n step += 1\n``` | 15 | 0 | ['Python3'] | 0 |
minimum-moves-to-spread-stones-over-grid | Why Greedy won't Work ? || Backtracking || C++ | why-greedy-wont-work-backtracking-c-by-i-j8ng | Intuition\nWhy Greedy won\'t work\nIf we fill all the cells having value as zero with the closest cell having value greater than 1 line by line.\nTestcase for w | isht_1542 | NORMAL | 2023-09-10T04:53:15.739627+00:00 | 2023-09-11T17:12:11.989940+00:00 | 1,178 | false | # Intuition\n**Why Greedy won\'t work**\nIf we fill all the cells having value as zero with the closest cell having value greater than 1 line by line.\nTestcase for which it won\'t work: \n[[3,2,0] \n[0,1,0] \n[0,3,0]]\n**0 indexed**\n**-** Fill [0,3] from [0,2] steps = 1\n**-** Fill [1,0] from [0,0] steps = 1\n**-** Fill [1,3] from [2,2] steps = 2\n**-** Fill [2,0] from [2,2] steps = 1\n**- Fill [2,3] from [0,0] steps = 4**\n**The main Edge case is: When u take 1 from your nearest neighbor, then in future we may need to go way longer because of previous step.**\nAns using greedy = 9\n**Correct ans = 7**\n\n# Approach\n**- Using Map for storing all cells having value > 1 will give TLE**;\n**-Use normal Backtracking**\n-We are checking every possible combination as constraints are less.\n-For every cell having value 0 we will go to every cell having value greater than 1 and check if taking value from it will minimize the no of steps\n# Complexity\n- Time complexity:\nThe overall time complexity is O(3^(n^2))\n\n- Space complexity:\nO(D), where D is the maximum depth of the recursion\n\n# Code\n```\nclass Solution {\npublic:\n \n int solve(vector<vector<int>>& grid){\n //We can take any value greater than 18 as ans\n int ans = 50;\n bool check = true;\n for(int i=0;i<3;i++){\n for(int j=0;j<3;j++){\n if(grid[i][j]==0){\n //To check if there is any cell still having 0 value\n check = false;\n //To go to every cell having value greater than 1 and \n //check if taking value from it will minimize the no of steps\n for(int k=0;k<3;k++){\n for(int l=0;l<3;l++){\n if(grid[k][l]>1){\n grid[k][l]--;\n grid[i][j] = 1;\n ans = min(ans, (abs(i-k)+abs(j-l)) + solve(grid));\n //Making values same as before - Backtracking\n grid[i][j] = 0;\n grid[k][l]++;\n }\n }\n }\n }\n }\n }\n //If no cell having value 0 is left then return 0\n if(check) return 0;\n return ans;\n }\n \n int minimumMoves(vector<vector<int>>& grid){\n return solve(grid);\n }\n};\n``` | 14 | 0 | ['Backtracking', 'Greedy', 'Recursion', 'C++'] | 5 |
minimum-moves-to-spread-stones-over-grid | 🤣😂 Permutation solution!!!🔄💡 GIGA EAZZ LOL!!! DONT FEEL❤️🔥 | permutation-solution-giga-eazz-lol-dont-5iu5i | Intuition\n Describe your first thoughts on how to solve this problem. \nLets build all possible combinations and choose the best from them\n# Approach\n Descri | LTDigor | NORMAL | 2023-09-10T04:11:44.735713+00:00 | 2023-09-10T04:27:52.986579+00:00 | 1,355 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nLets build all possible combinations and choose the best from them\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe need to construct arrays target with empty cells and stones with cells with free stones. If we have more than one free stone in the cell, each one will be in the array separately\nNow we need to match each stone from the array with a cell from the second\nJust going through all the combinations, since the grid is 3 by 3, there will be no more than 20 of them\n# Complexity\n- Time complexity: $$O(n!)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n targets = [(x, y) for x in range(3) for y in range(3) if grid[x][y] == 0]\n stones = []\n for x in range(3):\n for y in range(3):\n if grid[x][y] > 1:\n stones.extend([(x, y)] * (grid[x][y] - 1))\n \n ways = []\n for targets_perm in permutations(targets):\n ways.append(list(zip(targets_perm, stones)))\n \n res = 100000\n for way in ways:\n cur = 0\n for cell1, cell2 in way:\n cur += abs(cell1[0] - cell2[0]) + abs(cell1[1] - cell2[1])\n res = min(res, cur)\n \n return res\n \n \n``` | 9 | 2 | ['Python3'] | 6 |
minimum-moves-to-spread-stones-over-grid | JAVA || BACKTRACKING || EXPLAINED | java-backtracking-explained-by-minnikesw-qd3n | \n\n# Approach\nBacktracking and selecting an overfilled cell(grid[i][j] > 1) to fill an empty cell (grid[i][j] == 0)\n\nThe cost of each filling will be the Ma | Minnikeswar | NORMAL | 2023-09-10T04:25:26.817354+00:00 | 2023-09-11T12:48:18.767819+00:00 | 659 | false | \n\n# Approach\nBacktracking and selecting an overfilled cell(grid[i][j] > 1) to fill an empty cell (grid[i][j] == 0)\n\nThe cost of each filling will be the [Manhattan distance](https://www.quora.com/What-is-Manhattan-Distance) between the empty cell and overfilled cell\n\n\n\n# Code\n```\nclass Solution {\n int solve(int emptyCells , int grid[][]){\n // base case (no moves needed)\n if(emptyCells == 0) return 0;\n\n // intializing answer to infinty\n int ans = Integer.MAX_VALUE;\n\n // checking for empty cell\n for(int row1 = 0 ; row1 < 3 ; row1++){\n for(int col1 = 0 ; col1 < 3 ; col1++){\n if(grid[row1][col1] == 0){\n\n // filling the empty cell with an overfilled cell\n for(int row2 = 0 ; row2 < 3 ; row2++){\n for(int col2 = 0 ; col2 < 3 ; col2++){\n\n //checking if the cell is overfilled\n //backtracking move\n if(grid[row2][col2] > 1){\n grid[row2][col2]--;\n grid[row1][col1] = 1;\n\n //Manhattan distance\n int currMoves = Math.abs(row1 - row2) + Math.abs(col1 - col2);\n \n ans = Math.min(ans , currMoves + solve(emptyCells - 1 , grid));\n grid[row1][col1] = 0;\n grid[row2][col2]++;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n public int minimumMoves(int[][] grid) {\n int emptyCells = 0;\n // counting the number of empty cells\n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){\n if(grid[i][j] == 0){\n emptyCells++;\n }\n }\n }\n return solve(emptyCells , grid);\n }\n}\n```\n\n\n\n# UPVOTE IF YOU FIND THIS HELPFUL !!! | 8 | 0 | ['Backtracking', 'Greedy', 'Java'] | 2 |
minimum-moves-to-spread-stones-over-grid | Video Explanation (Both N! & 2^N solution) | video-explanation-both-n-2n-solution-by-4g3ap | Explanation\n\nClick here for the video\n\n# Code\n\n#define pii pair<int, int>\n#define F first\n#define S second\n\n/*\nclass Solution {\n vector<pii> zero | codingmohan | NORMAL | 2023-09-10T05:34:22.871934+00:00 | 2023-09-10T05:34:22.871954+00:00 | 310 | false | # Explanation\n\n[Click here for the video](https://youtu.be/KTSBf8sJm5s)\n\n# Code\n```\n#define pii pair<int, int>\n#define F first\n#define S second\n\n/*\nclass Solution {\n vector<pii> zero;\n vector<pii> non_zero;\n int result;\n \n int Distance (pii x, pii y) {\n return abs(x.F - y.F) + abs(x.S - y.S);\n }\n \n void Arrange (vector<bool>& taken, vector<int>& order) {\n if (order.size() == zero.size()) {\n int val = 0;\n for (int j = 0; j < zero.size(); j ++)\n val += Distance(non_zero[order[j]], zero[j]);\n \n result = min (result, val);\n }\n \n for (int i = 0; i < zero.size(); i ++) {\n if (taken[i]) continue;\n \n taken[i] = true;\n order.push_back(i);\n \n Arrange (taken, order);\n \n order.pop_back();\n taken[i] = false;\n }\n }\n \npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n result = 1e9;\n zero.clear();\n non_zero.clear();\n \n for (int j = 0; j < 3; j ++) {\n for (int k = 0; k < 3; k ++) {\n if (grid[j][k] != 0) {\n for (int i = 0; i < grid[j][k]-1; i ++)\n non_zero.push_back({j, k});\n }\n else zero.push_back({j, k});\n }\n }\n \n vector<bool> taken(zero.size(), false);\n vector<int> order;\n Arrange(taken, order);\n \n return result;\n }\n};\n*/\n\n\nconst int N = 9;\nint dp[1 << N];\n\nvector<pii> pos(N+1);\nvector<int> val(N+1);\n\nclass Solution {\n vector<pii> zero;\n vector<pii> non_zero;\n \n int Distance (pii x, pii y) {\n return abs(x.F - y.F) + abs(x.S - y.S);\n }\n \n int MinMoves (int mask) {\n int n = non_zero.size();\n \n if (mask+1 == (1 << n)) return 0;\n \n int &ans = dp[mask];\n if (ans != -1) return ans;\n \n int ind = 0;\n for (int i = 0; i < n; i ++)\n if (mask&(1 << i)) ind ++;\n \n ans = 1e9;\n for (int i = 0; i < n; i ++) {\n if (mask & (1 << i)) continue;\n \n ans = min (ans, Distance(zero[ind], non_zero[i]) + MinMoves(mask|(1 << i)));\n }\n return ans;\n }\n \npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n memset(dp, -1, sizeof(dp));\n zero.clear();\n non_zero.clear();\n \n for (int j = 0; j < 3; j ++) {\n for (int k = 0; k < 3; k ++) {\n if (grid[j][k] != 0) {\n for (int i = 0; i < grid[j][k]-1; i ++)\n non_zero.push_back({j, k});\n }\n else zero.push_back({j, k});\n }\n }\n \n return MinMoves(0);\n }\n};\n``` | 7 | 0 | ['C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | Naive backtrack to try all possible movements. I thought it was BFS | naive-backtrack-to-try-all-possible-move-yy1e | Intuition\n Describe your first thoughts on how to solve this problem. \nTry to move any exceed stone in one cell to any other empty cell.\nIn the contest, I th | Hayleyy | NORMAL | 2023-09-10T04:39:33.622862+00:00 | 2023-09-10T04:39:33.622883+00:00 | 375 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to move any exceed stone in one cell to any other empty cell.\nIn the contest, I thought it is BFS/ multi source BFS, BFS from stones or BFS from empty cells. But it will not give the optimal solution.\n\n# Code\n```\nclass Solution {\n public int minimumMoves(int[][] grid) {\n int minMoves = Integer.MAX_VALUE;\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (grid[i][j] > 1) {\n //try to move the exceeded stones\n for (int k = 0; k < 3; k++) {\n for (int l = 0; l < 3; l++) {\n int curMove = 0;\n if (grid[k][l] == 0) {\n grid[k][l] = 1;\n curMove += Math.abs(k - i) + Math.abs(l - j);\n grid[i][j]--;\n curMove += minimumMoves(grid);\n grid[i][j]++;\n grid[k][l] = 0;\n minMoves = Math.min(minMoves, curMove);\n }\n }\n }\n }\n }\n }\n\n return minMoves == Integer.MAX_VALUE ? 0 : minMoves;\n }\n}\n``` | 7 | 0 | ['Backtracking', 'Depth-First Search', 'Java'] | 2 |
minimum-moves-to-spread-stones-over-grid | Handwritten | Why Greedy FAILS ? | Backtracking | handwritten-why-greedy-fails-backtrackin-6j71 | Intuition\n## Why Backtracking?\n\n\n Describe your first thoughts on how to solve this problem. \n- Extreme Brute Force with backtracking solution\n- See the i | bala_000 | NORMAL | 2023-09-10T04:09:55.109907+00:00 | 2023-09-10T04:34:48.786514+00:00 | 370 | false | # Intuition\n## Why Backtracking?\n\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Extreme Brute Force with backtracking solution\n- See the issue actually kicked in this testcase [3 2 0] [0 1 0] [0 3 0]. Where Greedy or BFS didn\'t work\n- As we can go to multiple places to get the value, sometimes when we locally take those values from nearby leads to the issue\n- Like Here [3 2 0] [0 1 0] [0 3 0] \n- grid[2][0] = 0 and grid[1][2] = 0, when both 0s takes from nearby 3 grid[2][1].\n- The last grid[2][2] = 0, cannot take it from grid[2][1] with 1 move.\n- Instead it needs to go to the 1st cell grid[0][0] to get it. Which is 4 moves.\n- Instead grid[2][0] = 0, this 0 could have taken from there, to get a overall minimum value.\n- **The main Edge case was: when u take that 1 from your nearest neighbor, there can be in future someone who needs to go way longer because of ur step.**\n- It\'s more or less like the N Queen problem\n\n\n# Code\n```\nclass Solution {\nprivate:\n \n int f(vector<vector<int>>& grid){\n \n int N = 3;\n \n //IF NONE is 0 = BASE COND\n int fg = 1;\n for(int i=0; i<N; i++){\n for(int j=0; j<N; j++){\n if(grid[i][j] == 0){ \n fg = 0;\n break;\n }\n }\n }\n if(fg == 1) return 0;\n \n int tot = 1e8;\n for(int i=0; i<N; i++){\n for(int j=0; j<N; j++){\n for(int k=0; k<N; k++){\n for(int l=0; l<N; l++){\n if(grid[i][j] == 0 && grid[k][l] > 1){\n grid[k][l]--;\n grid[i][j]++;\n int d = abs(k-i) + abs(j-l);\n tot = min(tot, d + f(grid));\n grid[k][l]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n return tot;\n }\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n return f(grid);\n }\n};\n``` | 7 | 0 | ['Backtracking', 'Greedy', 'C++'] | 2 |
minimum-moves-to-spread-stones-over-grid | [C++] Brute Force || but Couldn't solved in Time | c-brute-force-but-couldnt-solved-in-time-5402 | Couldn\'t solved in contest!Very disappointed\n# Intuition\nBrute Force\nTry all possiblities\n# Approach\njust using Brute Force\n\nThis code is an implementat | Pathak_Ankit | NORMAL | 2023-09-10T04:09:36.483384+00:00 | 2023-09-10T11:36:00.657092+00:00 | 920 | false | Couldn\'t solved in contest!Very disappointed\n# Intuition\nBrute Force\nTry all possiblities\n# Approach\njust using Brute Force\n\nThis code is an implementation of a recursive algorithm to find the minimum number of moves required to place one stone in each cell of a 3x3 grid, where each cell can have multiple stones.\n\n\n1. The `Solution` class defines a 2D vector called `ref`, which represents the ideal configuration of the grid where each cell has one stone. `ref` is initialized to a 3x3 matrix filled with ones.\n\n2. The `help` function is a recursive function that takes a `grid` as input and returns the minimum number of moves required to reach the ideal configuration (represented by `ref`).\n\n3. Inside the `help` function:\n - If the current `grid` is the same as the ideal configuration (`grid == ref`), it means we have achieved the desired state, so the function returns 0.\n\n - `ans` is initialized to a large value (30) to keep track of the minimum number of moves needed.\n\n - The code uses four nested loops (i, j, k, l) to iterate through all possible pairs of cells in the grid.\n\n - It checks if `grid[i][j]` is empty (contains 0 stones) and `grid[k][l]` has more than one stone (`grid[k][l] > 1`). If this condition is met, it means we can move a stone from `grid[k][l]` to `grid[i][j]`.\n\n - The code simulates this move by incrementing `grid[i][j]` and decrementing `grid[k][l]`. It then recursively calls the `help` function with the updated `grid` to continue searching for the minimum number of moves.\n\n - After the recursive call, it calculates the total moves required for this move and stores it in `ans`.\n\n - Finally, it undoes the move by decrementing `grid[i][j]` and incrementing `grid[k][l]` to explore other possible moves.\n\n4. The `minimumMoves` function simply calls the `help` function with the input `grid` and returns the result.\n\nIn essence, this code explores all possible moves in a recursive manner, keeping track of the minimum number of moves required to reach the ideal configuration. It backtracks after each move to explore other possibilities until it finds the minimum number of moves needed to solve the problem.\n```\nclass Solution {\n \npublic:\n vector<vector<int>> ref = {{1,1,1},{1,1,1},{1,1,1}};\n int help(vector<vector<int>>& grid)\n {\n if(grid==ref)\n return 0;\n int ans = 30;\n for(int i = 0;i<3;i++)\n {\n for(int j = 0; j<3;j++)\n {\n for(int k = 0 ; k<3;k++)\n {\n for(int l = 0;l<3;l++)\n {\n if(grid[i][j]==0 && grid[k][l]>1)\n {\n grid[i][j]++;\n grid[k][l]--;\n ans = min(ans,abs(i-k)+abs(j-l)+help(grid));\n grid[i][j]--;\n grid[k][l]++;\n }\n }\n }\n }\n }\n return ans; \n }\n int minimumMoves(vector<vector<int>>& grid) {\n return help(grid);\n }\n};\n``` | 7 | 1 | ['Backtracking', 'C'] | 2 |
minimum-moves-to-spread-stones-over-grid | Backtracking Solution | backtracking-solution-by-hong_zhao-cmmu | Since n is 9, we can brute force the minimum with backtracking\npython []\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n n | hong_zhao | NORMAL | 2023-09-10T04:07:58.112084+00:00 | 2023-12-19T00:34:10.625787+00:00 | 650 | false | Since n is 9, we can brute force the minimum with backtracking\n```python []\nclass Solution:\n def minimumMoves(self, grid: List[List[int]]) -> int:\n need, has = [], {}\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n need.append((i, j))\n if grid[i][j] > 1:\n has[(i, j)] = grid[i][j]\n \n def go():\n if len(need) == 0: return 0\n best = inf\n i1, j1 = need.pop()\n for (i2, j2) in has.keys():\n if has[(i2, j2)] == 1:\n continue\n has[(i2, j2)] -= 1\n cost = abs(i2 - i1) + abs(j2 - j1)\n best = min(best, go() + cost)\n has[(i2, j2)] += 1\n need.append((i1, j1))\n return best\n\n return go()\n``` | 7 | 0 | ['Python3'] | 1 |
minimum-moves-to-spread-stones-over-grid | Simple Recursion || Brute Force || Memoization || C++ || JAVA || Python | simple-recursion-brute-force-memoization-paxh | Intuition\n Describe your first thoughts on how to solve this problem. \nI am mapping every 0 with every possible index. Will fail for 8^8, for handled it separ | amannimcet2021 | NORMAL | 2023-09-10T06:06:48.454418+00:00 | 2023-09-10T06:51:17.140627+00:00 | 1,240 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI am mapping every 0 with every possible index. Will fail for 8^8, for handled it separately. Else to avoid the 8^8 condition Memoize it.\n\n\n# Complexity\n- Time complexity: n^n (n<=7)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nRecursion || 983 ms\n```C++ []\nclass Solution {\n \n int f(vector<pair<int,int>>&z,vector<pair<int,int>>&o, int ind ){\n int n = z.size();\n if(ind==n) { \n return 0;\n } \n \n int ans = 1e8; \n for(int j=0 ; j<o.size() ; j++){\n int cur = abs(z[ind].first - o[j].first) + abs(z[ind].second - o[j].second);\n auto it = o[j];\n o[j] = {-1e8,-1e8};\n \n ans = min(ans , cur += f(z,o,ind+1));\n o[j]=it;\n }\n \n return ans;\n }\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n \n if(grid[0][0]==9||grid[0][2]==9||grid[2][0]==9||grid[2][2]==9) return 18;\n \n if(grid[0][1]==9||grid[1][0]==9||grid[1][2]==9||grid[2][1]==9) return 15;\n if(grid[1][1]==9) return 12;\n \n vector<pair<int,int>>z,o;\n for(int i=0 ; i<3 ; i++){\n for(int j=0 ; j<3 ; j++){\n if(grid[i][j] == 0) z.push_back({i,j});\n \n while(grid[i][j]>1) grid[i][j]-- , o.push_back({i,j});\n }\n }\n \n // cout<<z.size()<<o.size()<<" | ";\n return f(z,o,0);\n }\n};\n```\nMemoization || 353ms\n```C++ Memoization []\nclass Solution {\n map<pair<vector<pair<int,int>>,int>,int>mp;\n int f(vector<pair<int,int>>&z,vector<pair<int,int>>&o, int ind ){\n int n = z.size();\n if(ind==n) { \n return 0;\n } \n if(mp[{o,ind}]) return mp[{o,ind}];\n int ans = 1e8; \n for(int j=0 ; j<o.size() ; j++){\n int cur = abs(z[ind].first - o[j].first) + abs(z[ind].second - o[j].second);\n auto it = o[j];\n o[j] = {-1e8,-1e8};\n \n ans = min(ans , cur += f(z,o,ind+1));\n o[j]=it;\n }\n return mp[{o,ind}]=ans;\n }\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n \n \n vector<pair<int,int>>z,o;\n for(int i=0 ; i<3 ; i++){\n for(int j=0 ; j<3 ; j++){\n if(grid[i][j] == 0) z.push_back({i,j});\n \n while(grid[i][j]>1) grid[i][j]-- , o.push_back({i,j});\n }\n }\n \n return f(z,o,0);\n }\n};\n\n```\n```python []\nclass Solution(object):\n def minimumMoves(self, grid):\n def f(z, o, ind):\n n = len(z)\n if ind == n:\n return 0\n\n ans = float(\'inf\')\n for j in range(len(o)):\n curZ = z[ind]\n curO = o[j]\n\n cur = abs(curZ[0] - curO[0]) + abs(curZ[1] - curO[1])\n o[j] = (-1, -1)\n\n ans = min(ans, cur + f(z, o, ind + 1))\n o[j] = curO\n\n return ans\n\n if grid[0][0] == 9 or grid[0][2] == 9 or grid[2][0] == 9 or grid[2][2] == 9:\n return 18\n if grid[0][1] == 9 or grid[1][0] == 9 or grid[1][2] == 9 or grid[2][1] == 9:\n return 15\n if grid[1][1] == 9:\n return 12\n\n z = []\n o = []\n\n for i in range(3):\n for j in range(3):\n if grid[i][j] == 0:\n z.append((i, j))\n while grid[i][j] > 1:\n grid[i][j] -= 1\n o.append((i, j))\n\n return f(z, o, 0)\npy\n```\n```java []\nimport java.util.ArrayList;\nimport java.util.List;\n\nclass Solution {\n private int minimumMoves(int[][] grid) {\n if (grid[0][0] == 9 || grid[0][2] == 9 || grid[2][0] == 9 || grid[2][2] == 9)\n return 18;\n if (grid[0][1] == 9 || grid[1][0] == 9 || grid[1][2] == 9 || grid[2][1] == 9)\n return 15;\n if (grid[1][1] == 9)\n return 12;\n\n List<int[]> z = new ArrayList<>();\n List<int[]> o = new ArrayList<>();\n\n for (int i = 0; i < 3; i++) {\n for (int j = 0; j < 3; j++) {\n if (grid[i][j] == 0) {\n z.add(new int[]{i, j});\n }\n while (grid[i][j] > 1) {\n grid[i][j]--;\n o.add(new int[]{i, j});\n }\n }\n }\n\n return f(z, o, 0);\n }\n\n private int f(List<int[]> z, List<int[]> o, int ind) {\n int n = z.size();\n if (ind == n) {\n return 0;\n }\n\n int ans = Integer.MAX_VALUE;\n for (int j = 0; j < o.size(); j++) {\n int[] curZ = z.get(ind);\n int[] curO = o.get(j);\n\n int cur = Math.abs(curZ[0] - curO[0]) + Math.abs(curZ[1] - curO[1]);\n o.set(j, new int[]{-1, -1});\n\n ans = Math.min(ans, cur + f(z, o, ind + 1));\n o.set(j, curO);\n }\n\n return ans;\n }\n}\n\n```\n\n\n | 6 | 0 | ['Recursion', 'Python', 'C++', 'Java'] | 1 |
minimum-moves-to-spread-stones-over-grid | TIME 100% BEATS || BRUTE FORCE || RECURSION || C++ | time-100-beats-brute-force-recursion-c-b-h275 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | coding_night | NORMAL | 2023-09-10T09:06:46.703668+00:00 | 2023-09-10T09:06:46.703691+00:00 | 621 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n vector<vector<int>> tmp = {{-1,0},{0,-1},{1,0},{0,1},{-1,-1},{-1,1},{1,-1},{1,1},{-2,0},{0,-2},{2,0},{0,2},{-2,1},{-2,-1},{2,1},{2,-1},{1,-2},{1,2},{-1,2},{-1,-2},{-2,-2},{-2,2},{2,-2},{2,2}};\n int solve(int k,vector<vector<int>> &g){\n if(k>=9){\n return 0;\n }\n int ans = 100;\n int x = k/3,y = (k%3);\n if(g[x][y]==0){\n for(auto &i: tmp){\n if(x+i[0]>=0&&x+i[0]<3&&y+i[1]>=0&&y+i[1]<3 && g[x+i[0]][y+i[1]]>1){\n g[x+i[0]][y+i[1]]--;\n ans = min(ans,abs(i[0])+abs(i[1])+solve(k+1,g));\n g[x+i[0]][y+i[1]]++;\n }\n }\n return ans;\n }else{\n return solve(k+1,g);\n }\n return 0;\n }\n int minimumMoves(vector<vector<int>>& grid) {\n return solve(0,grid);\n }\n};\n``` | 5 | 0 | ['Recursion', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | ✅☑[C++] || 2 Best Approaches || Rescursion 🔥 | c-2-best-approaches-rescursion-by-marksp-zl4o | \n\n# Approach\nEach time we encounter a cell with grid[i][j] == 0 then we can take 1 from any of the other 8 cells which have a value > 1\n\n\n# Code\n\n\n---- | MarkSPhilip31 | NORMAL | 2023-09-10T04:56:18.782281+00:00 | 2023-09-10T04:56:18.782304+00:00 | 1,033 | false | \n\n# Approach\nEach time we encounter a cell with grid[i][j] == 0 then we can take 1 from any of the other 8 cells which have a value > 1\n\n\n# Code\n```\n\n------------------Approach 1--------------------\nclass Solution {\nprivate:\n bool check(vector<vector<int>> &grid){\n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){\n if(grid[i][j] != 1) return false;\n }\n }\n return true;\n }\n \n int helper(vector<vector<int>> &grid){\n if(check(grid)){\n return 0;\n }\n \n int answer = INT_MAX;\n \n for(int i = 0 ; i < 3 ; i++){\n for(int j = 0 ; j < 3 ; j++){\n if(grid[i][j] == 0){\n grid[i][j] = 1;\n \n for(int ii = 0 ; ii < 3 ; ii++){\n for(int jj = 0 ; jj < 3 ; jj++){\n if(grid[ii][jj] > 1){\n grid[ii][jj] -= 1;\n answer = min(answer, abs(ii - i) + abs(jj - j) + helper(grid));\n grid[ii][jj] += 1;\n }\n }\n }\n \n grid[i][j] = 0;\n }\n }\n }\n \n return answer;\n \n }\n \npublic:\n \n int minimumMoves(vector<vector<int>>& grid) {\n return helper(grid);\n }\n};\n\n----------------Approach 2----------------\n\nclass Solution {\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n // Base Case\n int t = 0;\n for (int i = 0; i < 3; ++i)\n for (int j = 0; j < 3; ++j)\n if (grid[i][j] == 0)\n t++;\n if (t == 0)\n return 0;\n \n int ans = INT_MAX;\n for (int i = 0; i < 3; ++i)\n {\n for (int j = 0; j < 3; ++j)\n {\n if (grid[i][j] == 0)\n {\n for (int ni = 0; ni < 3; ++ni)\n {\n for (int nj = 0; nj < 3; ++nj)\n {\n int d = abs(ni - i) + abs(nj - j);\n if (grid[ni][nj] > 1)\n {\n grid[ni][nj]--;\n grid[i][j]++;\n ans = min(ans, d + minimumMoves(grid));\n grid[ni][nj]++;\n grid[i][j]--;\n }\n }\n }\n }\n }\n }\n return ans;\n }\n};\n``` | 5 | 0 | ['Recursion', 'C++'] | 1 |
minimum-moves-to-spread-stones-over-grid | Simplest Backtracking solution beats 100% with explanation | simplest-backtracking-solution-beats-100-rymg | Intuition\n Describe your first thoughts on how to solve this problem. \nThe given code is an implementation of a solution to find the minimum number of moves r | noob0408 | NORMAL | 2023-09-10T04:15:20.605738+00:00 | 2023-09-10T04:15:20.605764+00:00 | 444 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe given code is an implementation of a solution to find the minimum number of moves required to transform a given grid into a state where all cells contain the value 1. The grid contains cells with values 0 and values greater than 1. The goal is to move the cells with values greater than 1 to empty cells (denoted by 0) in the fewest number of moves. You can think of it as moving objects in a grid where each move costs one unit.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code first checks if the grid is already in the target state where all cells have the value 1. If it is, the function returns 0 because no moves are needed.\n\nIt then iterates through the grid to find the positions of all cells with values greater than 1 and the position of the empty cell (0).\n\nIt initializes a variable mini to store the minimum number of moves needed and uses a recursive approach to explore all possible moves for each object with a value greater than 1.\n\nFor each object, it calculates the Manhattan distance (the sum of horizontal and vertical distances) between the object and the empty cell. It then temporarily updates the grid to simulate a move by decrementing the object\'s value and incrementing the empty cell\'s value.\n\nIt recursively calls minimumMoves on the updated grid to explore the next move.\n\nAfter exploring all possible moves for a particular object, it reverts the grid back to its original state.\n\nIt keeps track of the minimum number of moves required to reach the target state by updating the mini variable.\n\nFinally, it returns the minimum number of moves (mini) needed to transform the grid into the target state.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is exponential because it explores all possible moves by recursion. For each cell with a value greater than 1, it considers all possible moves. Therefore, the time complexity can be expressed as O(3^n), where n is the number of cells with values greater than 1. This is because, for each cell, it can move up, left, or right, resulting in three possibilities.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n), where n is the number of cells with values greater than 1.\n\n# Code\n```\n\nclass Solution {\npublic:\n int minimumMoves(std::vector<std::vector<int>>& grid) {\n if (all_of(grid.begin(), grid.end(), [](vector<int>& row) {\n return all_of(row.begin(), row.end(), [](int val) {\n return val == 1;\n });\n })) {\n return 0;\n }\n \n vector<pair<int, int>> all;\n pair<int, int> empty = make_pair(0, 0);\n for (int i = 0; i < grid.size(); i++) {\n for (int j = 0; j < grid[i].size(); j++) {\n if (grid[i][j] > 1) {\n all.push_back(make_pair(i, j));\n }\n if (grid[i][j] == 0) {\n empty = make_pair(i, j);\n }\n }\n }\n \n int mini = INT_MAX;\n for (const auto& p : all) {\n int dist = abs(p.first - empty.first) + abs(p.second - empty.second);\n grid[empty.first][empty.second]++;\n grid[p.first][p.second]--;\n mini = min(mini, minimumMoves(grid) + dist);\n grid[p.first][p.second]++;\n grid[empty.first][empty.second]--;\n }\n \n return mini;\n }\n};\n```\n\n\n | 5 | 0 | ['Dynamic Programming', 'Backtracking', 'Recursion', 'C++', 'Java'] | 0 |
minimum-moves-to-spread-stones-over-grid | Easy C++ Backtracking Solution 🔥🔥 | easy-c-backtracking-solution-by-kingsman-byjm | Intuition\nFor every zero, use backtracking and try to fill it with values from cells with extra numbers and try out all possible such combinations using backtr | kingsman007 | NORMAL | 2023-09-10T04:04:09.336810+00:00 | 2023-09-10T04:04:09.336827+00:00 | 1,064 | false | # Intuition\nFor every zero, use backtracking and try to fill it with values from cells with extra numbers and try out all possible such combinations using backtracking.\n# Code\n```\nclass Solution {\nprivate:\n vector<vector<int>> xtra, zero;\n int ret;\n void solve(int i, int count) {\n // base case\n if(i >= zero.size()) {\n ret = min(ret, count);\n return;\n }\n // calling recursion\n // trying out all remaining possibilities\n for(int k = 0; k < xtra.size(); k++) {\n if(xtra[k][2] == 0) continue;\n xtra[k][2]--;\n solve(i + 1, abs(xtra[k][0] - zero[i][0]) + abs(xtra[k][1] - zero[i][1]) + count);\n xtra[k][2]++;\n }\n }\npublic:\n int minimumMoves(vector<vector<int>>& grid) {\n // taking all zero coordinates\n // taking all extra values coordinates with extra value\n for(int i = 0; i < 3; i++) {\n for(int j = 0; j < 3; j++) {\n if(grid[i][j] == 0)\n zero.push_back({i, j});\n else if(grid[i][j] > 1)\n xtra.push_back({i, j, grid[i][j] - 1});\n }\n }\n if(zero.size() == 0) return 0;\n ret = INT_MAX;\n solve(0, 0);\n return ret;\n }\n};\n``` | 5 | 0 | ['Backtracking', 'Recursion', 'C++'] | 2 |
minimum-moves-to-spread-stones-over-grid | 🔥BackTracting It Is || C++ | backtracting-it-is-c-by-jainwinn-fct4 | Code\n\nclass Solution {\npublic:\n //for each position having zero stones, we try putting stone from each position which has excess stones at a particular i | JainWinn | NORMAL | 2023-09-10T04:03:23.403414+00:00 | 2023-09-10T04:04:24.854546+00:00 | 442 | false | # Code\n```\nclass Solution {\npublic:\n //for each position having zero stones, we try putting stone from each position which has excess stones at a particular instant.\n \n //Recursion/Backtracking\n int solve(int idx,vector<pair<int,int>> &more,vector<pair<int,int>> &zero,vector<vector<int>>& grid){\n if(idx==zero.size()){\n return 0;\n }\n int curr=1e9;\n for(auto v : more){\n if(grid[v.first][v.second]>1){\n grid[v.first][v.second]--;\n curr=min(curr,abs(zero[idx].first-v.first)+abs(zero[idx].second-v.second)+solve(idx+1,more,zero,grid));\n grid[v.first][v.second]++;\n }\n }\n return curr;\n }\n \n int minimumMoves(vector<vector<int>>& grid) {\n //excess stone positions\n vector<pair<int,int>> more;\n \n //zero stone positions\n vector<pair<int,int>> zero;\n \n for(int i=0 ; i<3 ; i++){\n for(int j=0 ; j<3 ; j++){\n if(grid[i][j]>1){\n more.push_back(make_pair(i,j));\n }\n if(grid[i][j]==0){\n zero.push_back(make_pair(i,j));\n }\n }\n }\n \n return solve(0,more,zero,grid);\n }\n};\n``` | 5 | 0 | ['Backtracking', 'C++'] | 0 |
minimum-moves-to-spread-stones-over-grid | ☑️✅Easy Java Solution || Beats 99.7% users✅☑️ | easy-java-solution-beats-997-users-by-vr-28u5 | PLEASE UPVOTE IF IT HELPED\n\n---\n\n# Intuition\nThis question can not be solved with the help of a greedy approach.\nBut Why? Because we have try to all ways | vritant-goyal | NORMAL | 2024-02-24T12:19:14.400147+00:00 | 2024-02-24T12:19:14.400182+00:00 | 248 | false | # **PLEASE UPVOTE IF IT HELPED**\n\n---\n\n# Intuition\nThis question can not be solved with the help of a greedy approach.\nBut Why? Because we have try to all ways to find the minimum among all of them.\nI wasted a lot of my time on solving this question with greedy appoaches,but failed every time.\nBut i have came up with the best and easiest solution for you all.\nWe will create two 2-D arrays to store the cells with stones more than 1 and another to store the cells with stones equal to 0.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1)We will create two 2-D arrays and then iterate over the grid to find the cells with 0 stones and more than 1 stones.\n2)Then we will give call to the helper function.\n3)We will iterate over the entire array with more than 1 stones and find the minimum among them. \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int helper(ArrayList<ArrayList<Integer>>ones,ArrayList<ArrayList<Integer>>zeros,int i){\n int n=zeros.size();\n if(i==n)return 0;\n int ans=(int)(1e9);\n for(int a=0;a<ones.size();a++){\n if(ones.get(a).get(2)>1){\n ones.get(a).set(2,ones.get(a).get(2)-1);\n int val=Math.abs(zeros.get(i).get(0)-ones.get(a).get(0))+Math.abs(zeros.get(i).get(1)-ones.get(a).get(1));\n ans=Math.min(ans,val+helper(ones,zeros,i+1));\n ones.get(a).set(2,ones.get(a).get(2)+1);\n }\n }\n return ans;\n }\n public int minimumMoves(int[][] grid) {\n int n=grid.length;\n ArrayList<ArrayList<Integer>>ones=new ArrayList<>();\n ArrayList<ArrayList<Integer>>zeros=new ArrayList<>();\n for(int i=0;i<n;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]>1){\n ones.add(new ArrayList<>());\n ones.get(ones.size()-1).add(i);\n ones.get(ones.size()-1).add(j);\n ones.get(ones.size()-1).add(grid[i][j]);\n\n }\n else if(grid[i][j]==0){\n zeros.add(new ArrayList<>());\n zeros.get(zeros.size()-1).add(i);\n zeros.get(zeros.size()-1).add(j);\n }\n }\n }\n return helper(ones,zeros,0);\n }\n}\n```\n# **PLEASE UPVOTE IF IT HELPED**\n\n---\n | 4 | 0 | ['Array', 'Recursion', 'Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.