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
apply-operations-to-make-all-array-elements-equal-to-zero
[Python3] prefix sum
python3-prefix-sum-by-ye15-j7ty
\n\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n for i, x in enumerate(nums): \n if i >= k: nums[i] += nums[i
ye15
NORMAL
2023-07-09T04:07:06.096203+00:00
2023-07-09T04:07:06.096221+00:00
3,157
false
\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n for i, x in enumerate(nums): \n if i >= k: nums[i] += nums[i-k]\n if i and nums[i-1] > nums[i]: return False \n return all(nums[~i] == nums[-1] for i in range(k))\n```
10
3
['C', 'Java', 'Python3']
3
apply-operations-to-make-all-array-elements-equal-to-zero
✌️2 Approaches || 1.Prefix Sum Range Update || 2.Segment Tree ||
2-approaches-1prefix-sum-range-update-2s-fe3i
DO UPVOTE if you find it useful!!\n\n# Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your spac
JainWinn
NORMAL
2023-07-09T09:11:30.616140+00:00
2023-07-09T09:11:30.616163+00:00
608
false
### DO UPVOTE if you find it useful!!\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code : Prefix Sum\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k){\n int n=nums.size();\n vector<int> d(n+1,0);\n for(int i=0 ; i<n ; i++){\n if(i>0){\n d[i]+=d[i-1];\n }\n int diff=nums[i]-d[i];\n if(diff<0){\n return false;\n }\n if(i+k>n){\n if(diff!=0){\n return false;\n }\n else{\n continue;\n }\n }\n d[i]+=diff;\n d[i+k]-=diff;\n }\n return true;\n }\n};\n```\n------------------------\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code : Segment Tree\n```\nclass SGTree_lazy{\n vector<long long> seg;\n vector<long long> lazy;\n public : \n SGTree_lazy(int n){\n seg.resize(4*n+1,0);\n lazy.resize(4*n+1,0);\n }\n\n void build(long long idx,long long low,long long high,vector<int> &arr){\n if(low==high){\n seg[idx]=arr[low];\n return;\n }\n\n int mid=low+((high-low)/2);\n build(2*idx+1,low,mid,arr);\n build(2*idx+2,mid+1,high,arr);\n seg[idx]=(seg[2*idx+1]+seg[2*idx+2]);\n }\n\n void update(long long idx,long long low,long long high,int l,int r,long long val){\n //lazy propagation\n if(lazy[idx]!=0){\n seg[idx]+=(high-low+1)*lazy[idx];\n if(low!=high){\n lazy[2*idx+1]+=lazy[idx];\n lazy[2*idx+2]+=lazy[idx];\n }\n lazy[idx]=0;\n }\n\n //no overlap\n if(l>high || r<low){\n return;\n }\n\n\n //complete overlap\n if(low>=l && high<=r){\n seg[idx]+=(high-low+1)*val;\n if(low!=high){\n lazy[2*idx+1]+=val;\n lazy[2*idx+2]+=val;\n }\n return ;\n }\n\n //partial overlap\n long long mid=low+((high-low)/2);\n update(2*idx+1,low,mid,l,r,val);\n update(2*idx+2,mid+1,high,l,r,val);\n seg[idx]=(seg[2*idx+1]+seg[2*idx+2]);\n }\n\n long long query(long long idx,long long low,long long high , int l,int r){\n //lazy propagation\n if(lazy[idx]!=0){\n seg[idx]+=(high-low+1)*lazy[idx];\n if(low!=high){\n lazy[2*idx+1]+=lazy[idx];\n lazy[2*idx+2]+=lazy[idx];\n }\n lazy[idx]=0;\n }\n\n // no overlap\n if(high<l || low>r){\n return 0;\n }\n\n //complete overlap\n if(low>=l && high<=r){\n return seg[idx];\n }\n\n //partial overlap\n long long mid=low+((high-low)/2);\n long long left=query(2*idx+1,low,mid,l,r);\n long long right=query(2*idx+2,mid+1,high,l,r);\n\n return (left+right);\n }\n};\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k){\n int n=nums.size();\n SGTree_lazy sg(n);\n sg.build(0,0,n-1,nums);\n long long sum=sg.query(0,0,(n-1),0,n-1);\n if((sum%k)!=0){\n return false;\n }\n for(int i=0 ; i<n ; i++){\n int curr=sg.query(0,0,n-1,i,i);\n if(curr<0){\n return false;\n }\n if(curr==0){\n continue;\n }\n if((i+k-1)<=n-1){\n sg.update(0,0,n-1,i,i+k-1,(-1)*curr);\n }\n else{\n if(curr!=0){\n return false;\n }\n }\n }\n return true;\n }\n};\n```
6
0
['Segment Tree', 'Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
using queue | simple c++ | O(n)
using-queue-simple-c-on-by-satenderrkuma-pq5m
Intuition\nmaking all element 0 while moving from left(from 0 to n-k) because there is only one way to make leftmost element zero which is decrement the first w
satenderrkumar11
NORMAL
2023-07-09T04:09:56.178959+00:00
2023-07-09T17:12:54.292808+00:00
1,776
false
# Intuition\nmaking all element 0 while moving from left`(from 0 to n-k)` because there is only one way to make leftmost element zero which is decrement the first window.\n\n# Approach\n- we will use a queue of size `k` and var `d` to keep track `no of decrements` on index `i` from previous windows. \n- where `q.front()` will give the `no of decrements` performed at window starting from `i-k`.\n- `d` - total no of decrements performed in all prev k windows starting from `i-k,i-k+1.. ,i-1`.\n- `d = d - q.front()` - no of decrements on index `i` from previous windows. \n\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n \n queue<int> q;\n \n for(int i=0;i<k;i++)\n q.push(0);\n\n \n int d = 0;\n \n for(int i=0;i<nums.size();i++){\n d = d - q.front();\n q.pop();\n if(nums[i]-d <0)return false;\n \n if(i>nums.size()-k){\n if(nums[i]-d != 0)return false;\n continue;\n }\n q.push(nums[i]-d);\n d += nums[i]-d;\n\n \n }\n \n \n \n \n return true;\n \n }\n};\n```
6
0
['Queue', 'C++']
2
apply-operations-to-make-all-array-elements-equal-to-zero
[Python3] Sweep Line (Range Addition), Clean & Concise
python3-sweep-line-range-addition-clean-fbi8x
Approach\nThink about the problem reversely.\n\n1. We start from an array arr with a same length as nums and all elements being 0.\n2. Now, we scan each element
xil899
NORMAL
2023-07-09T04:03:34.726837+00:00
2023-07-09T04:12:22.029418+00:00
660
false
# Approach\nThink about the problem **reversely**.\n\n1. We start from an array `arr` with a same length as `nums` and all elements being 0.\n2. Now, we scan each element from left to right, using the "Range Addition" way ([LC 370. Range Addition](https://leetcode.com/problems/range-addition/)).\n3. If the value of current element (i.e. `arr[i]`) is greater than `nums[i]`, we can already return `False`.\n4. Otherwise, if the value of current element (i.e. `arr[i]`) is less than `nums[i]`, we then add the difference `diff` between the two elements to `arr[i]`, and subtract `diff` at `arr[i + k]`.\n5. One caveat is that in Step 4, if the remaining subarray length starting from index `i` to the end of array (i.e. index `n - 1`) is strictly less than `k`, meaning that we cannot fulfill the condition. In this case, we also need to return `False`.\n6. Return `True` if we arrive at the end of the array.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n n = len(nums)\n arr = [0] * n\n for i in range(n):\n if i > 0:\n arr[i] += arr[i - 1]\n if arr[i] == nums[i]:\n continue\n elif arr[i] > nums[i]:\n return False\n elif n - i < k:\n return False\n diff = nums[i] - arr[i]\n arr[i] += diff\n if i + k < n:\n arr[i + k] -= diff\n return True\n```
6
0
['Python3']
1
apply-operations-to-make-all-array-elements-equal-to-zero
C++ SLIDING WINDOW SOLUTION
c-sliding-window-solution-by-arpiii_7474-mybb
Code\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n int sum=0;\n if(k==1) return true
arpiii_7474
NORMAL
2023-07-10T04:36:32.555431+00:00
2023-07-10T04:36:32.555463+00:00
354
false
# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n int sum=0;\n if(k==1) return true;\n for(int i=0;i<n;i++){\n if(i>=k) sum-=nums[i-k];\n nums[i]-=sum;\n sum+=nums[i];\n if(nums[i]<0) return false;\n }\n return nums[n-1]==0;\n }\n};\n```
5
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
[Python3] +1/-1 trick
python3-1-1-trick-by-awice-o4iu
We can encode subarrays [w, w, ..., w] of length K via two events: an event at position i of weight +w, and an event at position i + K of weight -w.\n\nMaintain
awice
NORMAL
2023-07-09T06:12:45.240395+00:00
2023-07-09T06:12:45.240418+00:00
765
false
We can encode subarrays `[w, w, ..., w]` of length `K` via two events: an event at position `i` of weight `+w`, and an event at position `i + K` of weight `-w`.\n\nMaintain a `brush` weight that will paint infinitely to the right, eg. `brush = 2` will write `[2, 2, 2, ...]` forever.\n\nNow for example, when `brush = 2` and `A[i] = 5`, it means that we must place a new subarray `[3, 3, ...]`, so `brush += 3` and `events[i + K] -= 3`.\n\n# Code\n```\nclass Solution:\n def checkArray(self, A: List[int], K: int) -> bool:\n N = len(A)\n events = [0] * (N + K) # events[i] tells us how much to adjust brush\n \n brush = 0\n for i in range(N):\n brush += events[i] # adjust the brush\n A[i] -= brush # A[i] got painted by brush\n if A[i] < 0: # painted too much\n return False\n if A[i] and i > N - K: # new subarrays must be K length\n return False\n brush += A[i] # add new brush stroke of weight A[i]\n events[i + K] -= A[i] # record event to downweight brush by A[i] later\n \n return True\n```
5
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Difference Array | O(n) TC and SC | Simple Approach
difference-array-on-tc-and-sc-simple-app-97e3
Code\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> diff(n+1, 0);\n \n
roboto7o32oo3
NORMAL
2023-07-09T04:06:52.900335+00:00
2023-07-09T04:06:52.900362+00:00
1,109
false
# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> diff(n+1, 0);\n \n diff[0] += nums[0];\n diff[k] -= nums[0];\n \n for(int i=1; i<n; i++) {\n diff[i] += diff[i-1];\n \n if(diff[i] == nums[i]) continue;\n \n if(diff[i] > nums[i] or i+k-1 >= n) return false;\n \n int d = nums[i] - diff[i];\n \n diff[i] += d;\n diff[i+k] -= d;\n }\n \n return true;\n }\n};\n```
5
0
['C++']
1
apply-operations-to-make-all-array-elements-equal-to-zero
✅Simple C++ Solution🔥|| Sliding Window
simple-c-solution-sliding-window-by-i_an-9cvv
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
i_anurag_mishra
NORMAL
2023-07-09T04:04:17.936034+00:00
2023-07-09T04:05:48.603220+00:00
1,531
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 bool checkArray(vector<int>& nums, int k) \n {\n int n = nums.size();\n int sum = 0;\n vector<pair<int, int>> v;\n int j = 0;\n for(int i=0; i<n; i++) \n {\n while(j<v.size() && i-v[j].first>=k) \n {\n sum -= v[j].second;\n j++;\n }\n if(nums[i]<sum) \n {\n return false;\n }\n nums[i] -= sum;\n if(nums[i]>0) \n {\n v.push_back({i, nums[i]});\n int temp = nums[i];\n nums[i] = 0;\n sum += temp;\n }\n }\n while (j<v.size() && n-v[j].first>=k) \n {\n j++;\n }\n int mx=-1e9;\n for(int x: nums) mx=max(mx, x);\n return mx==0 && j==v.size();\n }\n};\n```
5
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Easiest solution | Intuition explained | O(N) Faster than 100% | C++ | Java
easiest-solution-intuition-explained-on-6wabr
Intuition\n Describe your first thoughts on how to solve this problem. \nDon\'t think that you want to do something on the range, think that you just want to ma
budhirajamadhav
NORMAL
2023-07-10T02:33:09.052189+00:00
2023-07-10T02:33:09.052212+00:00
445
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDon\'t think that you want to do something on the range, think that you just want to make the current element 0. Ofcourse it will take `nums[i]` operations to make `nums[i] = 0`. But is your current `nums[i]` same as the original `nums[i]`? No. It must have been edited by the previous k - 1 elements. When you were trying to make them 0, they must have changed the current element. But changed by how much? Decreased by how much?\n\nA single element(in the previous `k - 1` elements) would decrease the current element by the amount - the changed value you encountered when you visited that element. The number of operations it took you to make that `element = 0` when you were standing at that element. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nFrom the above intuition, we can develop a solution:\n1. Get the latest changed value of the current element. It should be the `sum` of previous `k - 1` elements (not the original, the changed values that you encountered).\n2. If the new value comes out to be less than `0`, that means previous `k - 1` elements changed the current element more than they should have.\n3. Now for the next number, add the current new value to `cursum` and delete the `(k - 1)th` element from the `cursum`.\n4. That\'s all. Think of the edge case yourself. \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 bool checkArray(vector<int>& nums, int k) {\n\n if (k == 1) return true;\n\n int curSum = 0;\n int n = nums.size();\n\n for (int i = 0; i < n; i++) {\n nums[i] -= curSum; // get the latest value of the current element \n if (nums[i] < 0) return false; // previous k - 1 elements decreased the current element more than they should\n // update the cursum by adding the current element, and deleting the k - 1 th element\n curSum += nums[i];\n if (i - (k - 1) >= 0) curSum -= nums[i - (k - 1)];\n }\n\n return nums[n - 1] == 0;\n }\n};\n```\n```java []\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n if (k == 1) return true;\n\n int curSum = 0;\n int n = nums.length;\n\n for (int i = 0; i < n; i++) {\n nums[i] -= curSum; // get the latest value of the current element \n if (nums[i] < 0) return false; // previous k - 1 elements decreased the current element more than they should\n // update the cursum by adding the current element, and deleting the k - 1 th element\n curSum += nums[i];\n if (i - (k - 1) >= 0) curSum -= nums[i - (k - 1)];\n }\n\n return nums[n - 1] == 0;\n }\n}\n```
4
0
['Prefix Sum', 'C++', 'Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Explained using - vector & priority queue || Simple & easy to understand solution
explained-using-vector-priority-queue-si-39b5
\n# Approach\nBasically, here the catch is - that we consider that it possible to do this operation. So first elements need to be subtracted from first k elemen
kreakEmp
NORMAL
2023-07-09T08:47:49.911522+00:00
2023-07-09T08:47:49.911545+00:00
2,265
false
\n# Approach\nBasically, here the catch is - that we consider that it possible to do this operation. So first elements need to be subtracted from first k elements, while doing so when ever then element is not zero then add it to your subtraction value and keep subtracting. After k elements the subtraction need to reduce by num[i-k] vlues as we don\'t hv to subtract any more.\n\nInitially thought to do this using priority queue and later realised that the removal after kth element is sequential can be achieved using simple vector.\n\nFurther when checked out the solutions, found that the same input array can be used to and no extra vector required. Here is solution to this : \nhttps://leetcode.com/problems/apply-operations-to-make-all-array-elements-equal-to-zero/solutions/3739101/java-c-python-greedy-sliding-window/\n\n\n# Solution 1:\n```\nbool checkArray(vector<int>& nums, int k) {\n auto comp = [](const pair<int, int>& a, const pair<int,int>& b){\n return a.first > b.first; \n };\n priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(comp)> pq(comp);\n int sub = 0;\n for(int i = 0; i < nums.size(); ++i){\n while(!pq.empty() && pq.top().first <= i) { sub -= pq.top().second; pq.pop(); }\n nums[i] -= sub;\n sub += nums[i];\n pq.push({i+k, nums[i]});\n if(nums[i] < 0) return false;\n }\n if(!pq.empty()) { sub -= pq.top().second; }\n if(sub) return false;\n return true;\n}\n```\n\n# Solution 2:\n\n```\nbool checkArray(vector<int>& nums, int k) {\n vector<pair<int,int>> store;\n int sub = 0, ind = 0;\n for(int i = 0; i < nums.size(); ++i){\n while(ind < store.size() && store[ind].first <= i) { sub -= store[ind].second; ind++; }\n nums[i] -= sub;\n sub += nums[i];\n store.push_back({i+k, nums[i]});\n if(nums[i] < 0) return false;\n }\n if(ind < store.size()) { sub -= store[ind].second; }\n if(sub) return false;\n return true;\n}\n```\n\n<b>Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted
4
2
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C++ || Easy Solution || Best Approach || 🔥🔥
c-easy-solution-best-approach-by-abhi_pa-8u9v
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
abhi_pandit_18
NORMAL
2023-07-09T04:05:34.267696+00:00
2023-07-09T04:05:34.267716+00:00
679
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 bool checkArray(vector<int>& nums, int k) \n {\n int n = nums.size();\n int sum = 0;\n vector<pair<int, int>> v; // idx, val\n int j = 0;\n for(int i=0; i<n; i++) \n {\n while(j<v.size() && i-v[j].first>=k) \n {\n sum -= v[j].second;\n j++;\n }\n if(nums[i]<sum) \n {\n return false;\n }\n nums[i] -= sum;\n if(nums[i]>0) \n {\n v.push_back({i, nums[i]});\n int val = nums[i];\n nums[i] = 0;\n sum += val;\n }\n }\n while (j<v.size() && n-v[j].first>=k) \n {\n j++;\n }\n if(j!=v.size()) return false;\n int mx=-1e9;\n for(int x: nums) mx=max(mx, x);\n return mx==0;\n }\n};\n```
4
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Java | O(n) | beats 100% | Sliding window | visual model
java-on-beats-100-sliding-window-visual-k6dc3
Intuition\n Describe your first thoughts on how to solve this problem. \nThis question reminds me of this visual model\n\n\nA certain number of lego bars (lengt
slayzzzzz
NORMAL
2023-07-10T04:35:39.088183+00:00
2023-07-10T15:31:28.851685+00:00
474
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis question reminds me of this visual model\n![Screenshot 2023-07-09 at 8.50.09 PM.png](https://assets.leetcode.com/users/images/bdb18ebc-676d-495a-9d0f-ec8d264e21cc_1688961035.5830061.png)\n\nA certain number of lego bars (length of `k`, here `k = 4`) stacking up, and `nums[i]` is their thickness at `i`. So the goal is to validate `nums` indicates the correct values.\n \n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s assume `increment[i]` is the number of bars added at index `i`, `increment[i]` will only last till `i + k - 1`, which is the right end of the bars that are added at `i`. `increment[i]` will no longer contribute to the next iteration, so we\'ll have to deduct `increment[i]` when we reach the bars\' right ends.\n\nBefore index `0`, `increment = 0`\n\nLet\'s reuse `nums[i]` to store `increment[i]`: that\'s why we have `nums[i] -= increment`, and then add the difference to `increment` and carry it over to the next iteration. In the meantime, deduct `increment[i - k + 1]` because it won\'t contribute to the next iteration.\n\nAt the end of the array, we should reach the right end of all the remaining bars. So `increment` has to fall back to `0` after all the iterations are done. \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\n# Code\n```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int increment = 0;\n for(int i = 0; i < nums.length; i++) {\n if(increment > nums[i])\n return false;\n nums[i] -= increment; // calculate increment[i]\n increment += nums[i];\n if(i - k + 1 >= 0) {\n increment -= nums[i - k + 1]; // remove increment[i - k + 1]\n }\n }\n return increment == 0;\n }\n}\n```
3
0
['Java']
1
apply-operations-to-make-all-array-elements-equal-to-zero
C++ BruteForce Solution Got Accepted 🤯
c-bruteforce-solution-got-accepted-by-ka-ii1v
\nclass Solution {\npublic:\n bool checkArray(vector<int>& arr, int k) {\n if (arr.back() > arr.front()) {\n reverse(arr.begin(), arr.end()
kamalkish0r
NORMAL
2023-07-09T08:57:55.371218+00:00
2023-07-09T09:48:16.606634+00:00
1,212
false
```\nclass Solution {\npublic:\n bool checkArray(vector<int>& arr, int k) {\n if (arr.back() > arr.front()) {\n reverse(arr.begin(), arr.end());\n }\n int n = arr.size();\n for (int i = 0; i + k <= n; ) {\n int mn = INT_MAX;\n for (int j = i; j - i + 1 <= k; j++) {\n mn = min(arr[j], mn);\n }\n \n for (int j = i; j - i + 1 <= k; j++) {\n arr[j] -= mn;\n }\n\n int l = i;\n for (int j = i; j - i + 1 <= k; j++) {\n if (arr[j] == 0) {\n l++;\n }\n else {\n break;\n }\n }\n \n if (l == i) {\n return false;\n }\n i = l;\n }\n \n int ok = 1;\n for (int i : arr) {\n ok &= i == 0;\n }\n return ok;\n }\n};\n```\n\n![image](https://assets.leetcode.com/users/images/7ed436c5-6b5a-4210-bf9d-c00a21ad02bb_1688896086.8668668.png)\n\n\nTest cases couldn\'t have been more weak!!
3
0
['C']
1
apply-operations-to-make-all-array-elements-equal-to-zero
Zero the Array in O(n) Efficiently
zero-the-array-in-on-efficiently-by-snig-y9ec
IntuitionThe problem requires us to determine if we can make all elements in the arraynumsequal to zero by repeatedly selecting a contiguous subarray of sizekan
Nyx_owl
NORMAL
2025-02-23T06:59:16.502506+00:00
2025-02-23T07:01:39.495604+00:00
289
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The problem requires us to determine if we can make all elements in the array `nums` equal to zero by repeatedly selecting a contiguous subarray of size `k` and decrementing all its elements by 1. A **brute-force** approach where we decrement elements directly would be too slow (**O(n*k)**), so we need a more **efficient** way to track decrements. # Approach <!-- Describe your approach to solving the problem. --> We iterate through `nums` while maintaining: - `prefix_sum`: The cumulative effect of past operations. - `operation[i]`: A difference array that marks where decrement operations end. For each `nums[i]`, we: 1. **Update `prefix_sum`** by adding `operation[i]` (cumulative decrements applied so far). 2. **Compute `current = nums[i] - prefix_sum`**, the number of decrements still required. - If `current < 0`, return False (we over-decremented an element). - If `current > 0`, we must apply `current` decrement operations over the next `k` elements. - If `i + k > n`, return False (not enough space to apply operation). 3. Mark end of operation by updating `operation[i + k] -= current`. 4. **Update `prefix_sum`** to reflect the applied decrements. If we complete the loop without contradiction, return **True**. --- ## **Step-by-Step Example** ### **Example 1** #### **Input**: `nums = [2,2,3,1,1,0]`, `k = 3` #### **Processing Steps** We initialize: `operation = [0,0,0,0,0,0,0]` `prefix_sum = 0` | `i` | `nums[i]` | `prefix_sum`+=`operation[i]` | `current = nums[i] - prefix_sum` | `operation` Changes | Result | |------|----|---------|-------------|--------------------------------------------------|--------| | 0 | `2` | `0+0=0` | `2-0=2` | `operation[3] -= 2` `[0,0,0,-2,0,0,0]` | `prefix_sum+=current=2` Continue | | 1 | `2` | `2+0=2` | `2-2=0` | `[0,0,0,-2,0,0,0]` | `prefix_sum+=current=2` Continue | | 2 | `3` | `2+0=2` | `3-2=1` | `operation[5] -= 1` `[0,0,0,-2,0,-1,0]` | `prefix_sum+=current=3` Continue | | 3 | `1` | `3-2=1` | `1-1=0` | `[0,0,0,-2,0,-1,0]` | `prefix_sum+=current=1` Continue | | 4 | `1` | `1+0=1` | `1-1=0` | `[0,0,0,-2,0,-1,0]` | `prefix_sum+=current=1` Continue | | 5 | `0` | `1-1=0` | `0-0=0` | `[0,0,0,-2,0,-1,0]` | `prefix_sum+=current=0` endloop; return True | --- ### **Example 2** #### **Input:** `nums = [1,3,1,1]`, `k = 2` #### **Processing Steps** We initialize: `operation = [0, 0, 0, 0, 0]` `prefix_sum = 0` | `i` | `nums[i]` | `prefix_sum += operation[i]` | `current = nums[i] - prefix_sum` | `operation` Changes | Result | |------|----------|----------------------------|--------------------------------|----------------------------------|-----------------------------| | 0 | `1` | `0 + 0 = 0` | `1 - 0 = 1` | `operation[2] -= 1` → `[0, 0, -1, 0, 0]` | `prefix_sum += 1` and Continue | | 1 | `3` | `1 + 0 = 1` | `3 - 1 = 2` | `operation[3] -= 2` → `[0, 0, -1, -2, 0]` | `prefix_sum += 2` and Continue | | 2 | `1` | `3 - 1 = 2` | `1 - 2 = -1` | **(Negative! Return False)** | **Exit Immediately** 🚨 | # Complexity - **Time Complexity**: **O(n)** - We iterate through `nums` once, updating `operation` and `prefix_sum` in constant time. - **Space Complexity**: **O(n)** - We use an auxiliary `operation` array. # Code ```python3 [] class Solution: def checkArray(self, nums: List[int], k: int) -> bool: n = len(nums) operation = [0] * (n + 1) # Difference array prefix_sum = 0 for i in range(n): prefix_sum += operation[i] # Apply effect of previous operations current = nums[i] - prefix_sum # Remaining decrements needed if current < 0: return False # Over-decremented, impossible case if current > 0: if i + k > n: return False # Cannot apply operation beyond array bounds operation[i + k] -= current # Mark end of effect prefix_sum += current # Apply current decrements return True ``` # Alternative Approach (In-Place Modification) Instead of using an operation array, we modify nums directly. # Code ```python3 [] class Solution: def checkArray(self, nums: List[int], k: int) -> bool: for i in range(len(nums)): if i >= k: nums[i] += nums[i - k] # Propagate past decrements if i > 0 and nums[i - 1] > nums[i]: return False # If any element is increasing, it's invalid return all(nums[-i] == nums[-1] for i in range(k)) # Check last k elements ``` 🔹 Pros: Saves space. 🔹 Cons: Modifies input array, which may not always be desirable. ### Key Takeaways 1. Difference Array (operation) allows efficient range updates. 2. Prefix Sum helps track cumulative decrements. 3. Processing left-to-right ensures correctness. 4. Handles edge cases like over-decrementing or exceeding array bounds.
2
0
['Prefix Sum', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C++ || EASY || Beats 99% || Simple Solution ||
c-easy-beats-99-simple-solution-by-vansh-07to
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
vanshsuneja_
NORMAL
2023-07-15T16:16:01.835906+00:00
2023-07-15T16:16:01.835948+00:00
223
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 bool checkArray(vector<int>& nums, int k) {\n auto const n = static_cast<int>(std::size(nums));\n\n\t\tauto current = 0;\n\t\tfor (auto i = 0; i != n; ++i)\n\t\t{\n\t\t\tif (current > nums[i]) { return false; }\n\n\t\t\tnums[i] -= current;\n\t\t\tcurrent += nums[i];\n\t\t\tif (i >= k - 1) { current -= nums[i - k + 1]; }\n\t\t}\n\n\t\treturn current == 0;\n }\n};\n```
2
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Python (Simple Maths)
python-simple-maths-by-rnotappl-70dm
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
rnotappl
NORMAL
2023-07-09T19:34:53.373302+00:00
2023-07-09T19:34:53.373321+00:00
171
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:\n def checkArray(self, nums, k):\n n, val, ans = len(nums), True, [0]*k\n\n for i in range(n):\n ans[i%k] += nums[i]\n\n for i in range(1,k):\n if ans[i] != ans[0]:\n val = False\n break\n\n return val\n```
2
0
['Python3']
1
apply-operations-to-make-all-array-elements-equal-to-zero
Python3 Solution
python3-solution-by-motaharozzaman1996-55k4
\n\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n curr=0\n for i,a in enumerate(nums):\n if curr>a:\n
Motaharozzaman1996
NORMAL
2023-07-09T19:29:09.413203+00:00
2023-07-09T19:29:09.413223+00:00
282
false
\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n curr=0\n for i,a in enumerate(nums):\n if curr>a:\n return False\n\n nums[i],curr=a-curr,a\n if i>=k-1:\n curr-=nums[i-k+1]\n\n return curr==0 \n```
2
0
['Python', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
[Python3] Solve System of Equations
python3-solve-system-of-equations-by-awi-qtgp
Let\'s say we add a subarray of weight B_i at positions [i, i+1, ..., i+K-1]. This means:\n\n\nA_0 = B_0\\\nA_1 = B_0 + B_1\\\n...,\\\nA_{K-1} = B_0 + ... + B_
awice
NORMAL
2023-07-09T06:25:29.430389+00:00
2023-07-09T06:27:08.176248+00:00
1,001
false
Let\'s say we add a subarray of weight $$B_i$$ at positions $$[i, i+1, ..., i+K-1]$$. This means:\n\n$$\nA_0 = B_0\\\\\nA_1 = B_0 + B_1\\\\\n...,\\\\\nA_{K-1} = B_0 + ... + B_{K-1}\\\\\nA_K = B_1 + ... + B_K\\\\\nA_{K+1} = B_2 + ... + B_{K+1}\\\\\n...\n$$\n\nWe can solve these equations for B. Let P be the prefix sum of B (`P[i] = sum(B[:i])`). Then $$A_i = B_i - (B_{i-1} + ... + B_{i-(K-1)}) = B_i - (P_i - P_{i-(K-1)})$$, where $$B_{-1}$$, $$B_{-2}$$ etc. are regarded as zero.\n\nAt the end, $$B_i \\geq 0$$ [all subarrays must have non-negative weight] and $$B_j = 0$$ (for $$j > N - K$$) [subarrays can\'t start after position `N - K`] correspond to the legal choices.\n\n# Code\n```\nclass Solution:\n def checkArray(self, A: List[int], K: int) -> bool:\n N = len(A)\n B = []\n P = [0]\n for i, x in enumerate(A):\n b = x - (P[i] - P[max(0, i - K + 1)])\n B.append(b)\n P.append(P[-1] + b)\n\n return all(b >= 0 for b in B) and not any(B[~i] for i in range(K - 1))\n```
2
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Prefix Sum
prefix-sum-by-littlehobo-wpog
Intuition\n Describe your first thoughts on how to solve this problem. \nEach element at ith index can update elements till i+k-1 index elements ahead(as at eac
littlehobo
NORMAL
2023-07-09T04:57:29.627214+00:00
2023-07-09T05:00:53.084102+00:00
632
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEach element at ith index can update elements till i+k-1 index elements ahead(as at each index i we make its element 0, so don\'t need to worry about previous elements) of it so we can use prefix sum.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nJust Apply prefix sum on range (i+0,i+1,...,i+k-1) taking care of edge cases and check whether all elements become 0 or not. Check out code for better understanding.\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n vector<long long> pre(n+2,0);\n for(int i=1;i<=n;i++){\n pre[i]+=pre[i-1];\n int val=nums[i-1];\n val+=pre[i];\n // as negative val(means element<0) can\'t update elements ahead\n if(i<=(n-k+1)&&val>0){\n pre[i]-=val;\n pre[i+k]+=val;\n }\n }\n \n for(int i=0;i<n;++i){\n nums[i]+=pre[i+1];\n if(nums[i]!=0) return false;\n }\n return true;\n }\n};\n```
2
0
['C++']
1
apply-operations-to-make-all-array-elements-equal-to-zero
Python || greedy || O(n)
python-greedy-on-by-hanna9221-v5rr
h = the least number we need so far..\narr[i] = the number needed to subtract from h at index i.\n2. At index i, first we subtract arr[i] from h, then compare n
hanna9221
NORMAL
2023-07-09T04:43:58.137032+00:00
2023-07-09T04:43:58.137055+00:00
1,211
false
1. `h` = the least number we need so far..\n`arr[i]` = the number needed to subtract from `h` at index `i`.\n2. At index `i`, first we subtract `arr[i]` from `h`, then compare `n=nums[i]` with `h`.\nIf `n > h`, save `n-h` in `arr[i+k]` and raise `h` to `n`;\nIf `n < h`, contradiction occurs, so we return `False`.\nIf `n == h`, just continue.\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n arr = [0]*(len(nums)+1)\n h = 0\n for i, n in enumerate(nums):\n h -= arr[i]\n if n > h:\n if i+k > len(nums):\n return False\n arr[i+k] = n-h\n h = n\n elif n < h:\n return False\n return True
2
0
['Python3']
1
apply-operations-to-make-all-array-elements-equal-to-zero
Video Explanation (2 Approaches - Range Query and Prefix sum)
video-explanation-2-approaches-range-que-9qd8
Explanation\n\nClick here for the video\n\n# Code\n\ntypedef long long int ll;\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n
codingmohan
NORMAL
2023-07-09T04:29:08.392012+00:00
2023-07-09T04:29:08.392029+00:00
274
false
# Explanation\n\n[Click here for the video](https://youtu.be/uPNVi4IG7NI)\n\n# Code\n```\ntypedef long long int ll;\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n \n vector<ll> arr(n, 0);\n ll prefix_sum = 0;\n \n for (int j = 0; j < n; j ++) {\n prefix_sum += arr[j];\n nums[j] += prefix_sum;\n \n if (nums[j] < 0) return false;\n if (nums[j] == 0) continue;\n if ((j + k) > n) return false;\n \n prefix_sum -= nums[j];\n if (j+k < n) arr[j+k] += nums[j];\n }\n return true;\n }\n};\n```
2
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Apply Operations to Make All Array Elements Equal to Zero
apply-operations-to-make-all-array-eleme-y6u9
Intuition\nThe code aims to determine whether it is possible to make all elements of the array nums equal to 0 by repeatedly applying the operation of reducing
shashankiitm27
NORMAL
2024-08-30T02:13:01.166578+00:00
2024-08-30T02:13:01.166612+00:00
24
false
# Intuition\nThe code aims to determine whether it is possible to make all elements of the array nums equal to 0 by repeatedly applying the operation of reducing all elements of a subarray of size k by 1.\n\nThe main idea behind this approach is to simulate the effect of the operations using a temp array. This array helps in tracking the cumulative effect of operations applied so far. Instead of directly modifying nums, the algorithm tracks how much reduction has been applied to each element and ensures it doesn\'t exceed what is possible.\n\n# Approach\n**1 Initialization:**\nThe algorithm starts by initializing a temp array of the same size as nums and fills it with zeros. This array will store the cumulative operations applied to each index.\nIf n == 1, the algorithm immediately returns true because a single element can always be reduced to zero by choosing a subarray of size \n\n**2.First Element Handling:**\nThe first element nums[0] is directly assigned to temp[0], meaning it will require this many operations to reduce to zero.\nIf k < n, it sets temp[k] to -nums[0] to cancel the effect of the operation after k elements, maintaining the effect within the subarray of size k.\n\n**3 Main Loop:**\nThe loop iterates over the array starting from the second element (i = 1) up to n-k.\nFor each index i, it adds the cumulative operations from the previous index (temp[i] += temp[i-1]).\nIf the cumulative operations so far exceed the value of nums[i], it means it\'s impossible to reduce nums[i] to zero, so the function returns false.\nOtherwise, the algorithm calculates the necessary operations (x = nums[i] - temp[i]) and applies them. It then adjusts the temp array to mark the end of the operation\'s effect after k elements.\n\n**4 Handling the Last Window:**\nIf the loop exits early, it indicates that the last segment of the array is smaller than k. The algorithm then checks if this last segment matches the expected values (i.e., they should all be zero after applying all operations).\nIf the values in temp don\'t match nums in this final segment, the function returns false.\n\n# **Final Check:**\n\nIf all checks pass, the function returns true, indicating that it is possible to reduce all elements in the array to zero.\n\n# Complexity\n- **Time complexity :** The time complexity is O(n), where n is the size of the nums array. The algorithm iterates through the array once, with constant time operations for each element.\n\n- **Space complexity :** The space complexity is O(n) due to the additional temp array used to track the cumulative operations applied.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1) return true;\n \n vector<int> temp(n,0);\n int i=0;\n temp[i]=nums[i];\n if(k<n) temp[k]=-nums[i];\n\n // i will be 1 even if first condition is false\n for(i=1;i<n-k+1;i++) { \n temp[i]+=temp[i-1];\n \n if(temp[i]>nums[i]) return false;\n\n int x = nums[i]-temp[i];\n temp[i]+=x;\n if(i+k<n) temp[i+k]-=x;\n else { i++; break; } // Last Window\n }\n // Checking if Last Window element is equals to our temp array element or not\n while(i<n) {\n temp[i]+=temp[i-1];\n if(temp[i]!=nums[i]) return false;\n i++;\n }\n return true;\n }\n};\n```
1
0
['Array', 'Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
O(n) Time Beats 100%
on-time-beats-100-by-hakkiot-t4y8
Proof\n\n\n# Approach\n Describe your approach to solving the problem. \nFor first element , you have to apply operations a[0] times and next k-1 elements will
hakkiot
NORMAL
2024-01-22T10:51:36.558538+00:00
2024-01-23T03:41:41.298925+00:00
358
false
# Proof\n![Screenshot from 2024-01-22 15-50-19.png](https://assets.leetcode.com/users/images/d8cf4340-ce55-4194-b72a-1b27372b2724_1705920678.1404316.png)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor first element , you have to apply operations $$a[0]$$ times and next $$k-1$$ elements will also decrease by $$a[0]$$. So continue this idea.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. -->\n$$O(n)$$\n# Code\n```\n//~~~~~~~~~~~~~MJ\xAE\u2122~~~~~~~~~~~~~\n#include <bits/stdc++.h>\n#pragma GCC optimize("Ofast")\n#pragma GCC optimize("unroll-loops")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")\n#define Code ios_base::sync_with_stdio(0);\n#define by cin.tie(NULL);\n#define Hayan cout.tie(NULL);\n#define append push_back\n#define all(x) (x).begin(),(x).end()\n#define allr(x) (x).rbegin(),(x).rend()\n#define vi vector<int>\n#define yes cout<<"YES";\n#define no cout<<"NO";\n#define vb vector<bool\n#define vv vector<vector<int>>\n#define ul unordered_map<int,vi>\n#define ub unordered_map<int,bool>\n#define ui unordered_map<int,int>\n#define sum(a) accumulate(all(a),0)\n#define add insert\n#define endl \'\\n\'\n#define pi pair<int,int>\n#define ff first\n#define ss second\nclass Solution {\npublic:\n bool checkArray(vector<int>& a, int k) {\n Code by Hayan\n int n=a.size();\n vector<int>mp(n+1,0);\n int curr=0;\n for(int i=0;i<n;i++)\n {\n curr-=mp[i];\n a[i]-=curr;\n if (a[i]<0)\n {\n return false;\n }\n else if (a[i]>0)\n {\n if (i+k>n)\n {\n return false; \n }\n mp[i+k]+=a[i];\n \n curr+=a[i];\n }\n }\n return true;\n }\n};\n```
1
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Apply Operations to Make All Array Elements Equal to Zero | Java | Easy to Understand | O(n*k)
apply-operations-to-make-all-array-eleme-mvg3
\n\n# Code\n\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int n=nums.length;\n for(int i=0;i<n;i++){\n if(i>
Paridhicodes
NORMAL
2023-08-10T20:21:30.253599+00:00
2023-08-10T20:21:30.253642+00:00
210
false
\n\n# Code\n```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int n=nums.length;\n for(int i=0;i<n;i++){\n if(i>n-k && nums[i]!=0){\n return false;\n }\n\n if(nums[i]==0)continue;\n\n int dec=nums[i];\n\n for(int j=0;j<k;j++){\n nums[i+j]-=dec;\n\n if(nums[i+j]<0){\n return false;\n }\n }\n\n // System.out.println(Arrays.toString(nums));\n }\n\n return true;\n }\n}\n```
1
0
['Array', 'Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C++ Prefix sum
c-prefix-sum-by-ankit_6776-4x9k
Approach\nPefix sum. \n\n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(N)\n Add your space complexi
ankit_6776
NORMAL
2023-07-22T04:52:45.644696+00:00
2023-07-22T04:52:45.644713+00:00
60
false
# Approach\nPefix sum. \n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n int i=0;\n int j=1;\n vector<int> arr(n+2);\n while(i<nums.size()) {\n if(i!=0)arr[i]+=arr[i-1];\n if(nums[i]<arr[i])return false;\n if(nums[i]==arr[i]) {i++; continue;}\n int p = nums[i]-arr[i];\n if(i+k>n)return false;\n arr[i]+=p;\n arr[i+k]-=p;\n i++;\n }\n return true;\n }\n};\n```
1
0
['Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
[Python] Keep tracking the operation count that makes each element zero
python-keep-tracking-the-operation-count-0v4d
The problem asks to make the entrie array zero. However, every operation is apply on a subarray with length k.\n\nAn intuitive way is substract each element in
wangw1025
NORMAL
2023-07-19T21:22:57.852355+00:00
2023-07-19T21:22:57.852386+00:00
74
false
The problem asks to make the entrie array zero. However, every operation is apply on a subarray with length k.\n\nAn intuitive way is substract each element in a subarray with the value that makes the first element zero. Next, we move to the second element, if the value of the second element is still possitive, we apply the same operations to the next k elements. In the case that there is an element with value less than zero after the process, we know that we cannot make the entire array to be zero.\n\nHowever, the above process requires O(n^2) time. What we can do to improve the algorithm is use one array to keep tracking the value we need to substract for each window k, so that we can use O(1) to find the value that need to be substracted for each element.\n\nsee the details below:\n\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n # 1 <= k <= nums.length <= 10^5\n # 0 <= nums[i] <= 10^6\n len_n = len(nums)\n\n if k == 1:\n return True\n\n # recording the running diff that applied to make the first element of\n # each subarray starting at index i to be zero\n running_diff = [0] * len_n\n current_diff = 0\n\n idx = 0\n while idx <= len_n - k:\n if idx - k >= 0:\n current_diff -= running_diff[idx - k]\n if current_diff > nums[idx]:\n return False\n else:\n running_diff[idx] = nums[idx] - current_diff\n current_diff += running_diff[idx]\n #print(idx, current_diff, running_diff)\n idx += 1\n\n # for the last subarray ending at len_n - 1\n while idx < len_n:\n current_diff -= running_diff[idx - k]\n print(idx, current_diff)\n if current_diff != nums[idx]:\n return False\n idx += 1\n\n return True\n```
1
0
['Array', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Operations Solution
operations-solution-by-dair68-cdby
Approach 1 - Double Loops\n Describe your approach to solving the problem. \n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nNote t
dair68
NORMAL
2023-07-15T09:10:21.495251+00:00
2023-07-15T09:10:21.495280+00:00
41
false
# Approach 1 - Double Loops\n<!-- Describe your approach to solving the problem. -->\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nNote that the order in which subarrays receive operations does not matter. All that matters is which subarrays are chosen and how many times they receive the decrement operation. With order not affecting the solution, it makes sense to process the subarrays from left to the right for convenience.\n\nThe idea is to turn the elements into zero from left to right. Have `i` iterate over range `0 <= i < nums.length`. When `i <= nums.length-k`, it is the leftmost element of subarray `nums[i:i+k-1]`. Examine `nums[i]`: \n- If `nums[i] = 0`, visit the next subarray\n- If `nums[i] > 0`, apply the operation to the subarray `nums[i]` times. This can be done by using a second loop to subtract `nums[i]` from elements `i` to `i+k-1`.\n- If `nums[i] < 0`, return false. It is not possible to make elements to the left of `i` zero without making `nums[i]` negative.\n\nWhen `i > nums.length-k`, it is not the the leftmost element of a `k` length subarray which means no more operations should be made. For those `i`, simply check if `nums[i] = 0`. If `nums[i]` is nonzero return false. If all values `i` finish processing, it means the operations transformed the elements into zero without a hitch. Return true at the end of the code! \n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, const int& k) {\n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] == 0) {\n continue;\n }\n if (nums[i] < 0) {\n return false;\n }\n if (i > nums.size() - k && nums[i] != 0) {\n return false;\n }\n\n const int operations = nums[i];\n\n for (int j = i; j < i+k; j++) {\n nums[j] -= operations;\n }\n }\n\n return true;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == 0) {\n continue;\n }\n if (nums[i] < 0) {\n return false;\n }\n if (i > nums.length - k && nums[i] != 0) {\n return false;\n }\n\n final int operations = nums[i];\n\n for (int j = i; j < i+k; j++) {\n nums[j] -= operations;\n }\n }\n\n return true;\n }\n}\n```\n```Python3 []\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n for i in range(len(nums)):\n if nums[i] == 0:\n continue\n if nums[i] < 0:\n return False\n if i > len(nums) - k and nums[i] != 0:\n return False\n\n operations = nums[i]\n\n for j in range(i, i+k):\n nums[j] -= operations\n \n return True\n```\n\n# Complexity\n\nLet $$n$$ be the length of `nums`\n- Time complexity: $$O(n\\cdot{k})$$\n - All $$n$$ elements of `nums` are visited\n - For each `i`, up to $$k$$ subarray elements undergo subtraction\n - Total time is $$n\\cdot{O(k)=O(n\\cdot{k})}$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n - All the primitive variables take up constant space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Approach 2 - Queue\n<!-- Describe your approach to solving the problem. -->\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nInsteading of subtracting from `nums` in chunks of `k`, it is possible to subtract once per element. This can be done using a queue.\n\nLet `opQueue` be a queue that stores the number of operations used in each of the previous `k-1` subarrays. Let\'s look at Example 1 for an idea of what the queue should look like:\n```\nnums = [2,2,3,1,1,0], k = 3\nopQueue = {} nums = [(2),2,3,1,1,0]\nopQueue = {2} nums = [0,(0),1,1,1,0] \nopQueue = {2,0} nums = [0,0,(1),1,1,0]\nopQueue = {0,1} nums = [0,0,0,(0),0,0]\nopQueue = {1,0} nums = [0,0,0,0,(0),0]\nopQueue = {0,0} nums = [0,0,0,0,0,(0)]\n```` \nThe queue keeps track of subtractions to the current element contributed by previous subarrays. Let `operations` be the sum of the elements of `opQueue`. Through smart use of `opQueue` and `operations`, it becomes possible to quickly update an element to incorporate previous subtractions. When visiting element `i` for the first time, simply subtract `operations` from `nums[i]`. From there compare `nums[i]` to `0` like in the previous approach. Update `opQueue` and `operations` by appending and adding `nums[i]` respectively. Remove data no longer relevant to the current index by popping it from the queue and subtracting it from `operations`.\n\n# Algorithm\n1. Set `operations = 0` and `opQueue` to empty queue\n2. For `i` in range `0 <= i < nums.length`:\n - If `i >= k`, subtract head of `opQueue` from `operations`, then pop element from queue\n - Subtract `operations` from `nums[i]`\n - If `nums[i] < 0` return false\n - if `i > nums.length - k` AND `nums[i] != 0` return false\n - Push `nums[i]` into `opQueue` and add `nums[i]` to `operations`\n3. Once loop finishes return true\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, const int& k) {\n int operations = 0;\n queue<int> opQueue;\n \n for (int i = 0; i < nums.size(); i++) {\n if (i >= k) {\n operations -= opQueue.front();\n opQueue.pop();\n }\n\n nums[i] -= operations;\n \n if (nums[i] < 0) {\n return false;\n }\n if (i > nums.size() - k && nums[i] != 0) {\n return false;\n }\n \n opQueue.push(nums[i]);\n operations += nums[i];\n nums[i] = 0;\n }\n \n return true;\n }\n};\n```\n```Java []\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int operations = 0;\n final Queue<Integer> opQueue = new LinkedList<Integer> ();\n \n for (int i = 0; i < nums.length; i++) {\n if (i >= k) {\n operations -= opQueue.remove();\n }\n\n nums[i] -= operations;\n \n if (nums[i] < 0) {\n return false;\n }\n if (i > nums.length - k && nums[i] != 0) {\n return false;\n }\n \n opQueue.add(nums[i]);\n operations += nums[i];\n nums[i] = 0;\n }\n \n return true;\n }\n}\n```\n```Python3 []\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n operations = 0\n opQueue = deque()\n \n for i in range(len(nums)):\n if i >= k:\n operations -= opQueue.popleft()\n\n nums[i] -= operations\n \n if nums[i] < 0:\n return False\n if i > len(nums) - k and nums[i] != 0:\n return False\n \n opQueue.append(nums[i])\n operations += nums[i]\n nums[i] = 0\n \n return True\n```\n\n# Complexity\n\nLet $$n$$ be the length of `nums`\n- Time complexity: $$O(n)$$\n - All $$n$$ elements of `nums` are visited once\n - Add, remove, and peek operations for a queue occur in $$O(1)$$ time\n - Total time is $$O(n)\\cdot{O(1)}=O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(k)$$\n - The queue stores $$O(k-1)$$ elements at most\n - Total space is $$O(k-1)=O(k)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
1
0
['Queue', 'C++', 'Java', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Greedy Using sliding window and deque
greedy-using-sliding-window-and-deque-by-w42e
Intuition\n Describe your first thoughts on how to solve this problem. \nFor each window of size k ,the minimum element in that window should be greater than th
user3220K
NORMAL
2023-07-10T17:19:12.807194+00:00
2023-07-10T17:20:35.079193+00:00
112
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor each window of size k ,the minimum element in that window should be greater than the first element. Also in the last element of next window add first element of current window.\nInstead of substracting in current window I am changing next window.\nAt last all elements should be equal of last window.\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(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n if(k==1) return 1;\n\n int n = nums.size();\n deque<pair<int,int>> dq;\n int i=0;\n for(;i<k;i++){\n dq.push_back({nums[i],i});\n while(dq.front().first>nums[i]) dq.pop_front();\n }\n if(dq.front().first<nums[0]) return 0;\n\n for(;i<n;i++){\n nums[i]+=nums[i-k];\n dq.push_back({nums[i],i});\n if(dq.front().second==i-k) dq.pop_front();\n while(dq.front().first>nums[i]) dq.pop_front();\n if(dq.front().first<nums[i-k+1]) return 0;\n }\n\n for(int i=0;i<k-1;i++){\n if(nums[n-1-i]!=nums[n-2-i]) return 0;\n }\n return 1;\n\n \n }\n};\n```
1
0
['Greedy', 'Sliding Window', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Easy C++ Solution
easy-c-solution-by-lakshya_12-nj07
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
lakshya_12
NORMAL
2023-07-10T08:45:06.269899+00:00
2023-07-10T08:45:06.269923+00:00
127
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 bool checkArray(vector<int>& nums, int k) {\n int n= nums.size();\n int a=0,b=0;\n vector<pair<int,int>>vec;\n for(int i=0;i<n;i++){\n while(b<vec.size() && i-vec[b].first>=k){\n a-=vec[b].second; \n b++;\n }\n if(nums[i]<a) return false;\n \n nums[i]-=a;\n if(nums[i]){\n vec.push_back({i,nums[i]});\n int temp= nums[i];\n nums[i]=0;\n a+=temp;\n }\n }\n \n while(vec.size() && b<vec.size() && n-vec[b].first>=k){\n b++;\n }\n return *max_element(nums.begin(),nums.end())==0 && b==vec.size();\n }\n};\n```
1
0
['Sliding Window', 'C++']
1
apply-operations-to-make-all-array-elements-equal-to-zero
Rust Prefix Sum
rust-prefix-sum-by-xiaoping3418-lp7t
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
xiaoping3418
NORMAL
2023-07-09T19:50:39.931486+00:00
2023-07-09T19:50:39.931514+00:00
24
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)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nimpl Solution {\n pub fn check_array(nums: Vec<i32>, k: i32) -> bool {\n let mut nums = nums;\n let (n, k) = (nums.len(), k as usize);\n let mut update = vec![0; n];\n let mut sum = 0;\n \n for i in 0 .. n {\n sum += update[i];\n let d = nums[i] + sum;\n if d < 0 { return false }\n if d > 0 {\n if i + k > n { return false }\n update[i] -= d;\n sum -= d;\n if i + k < n { update[i + k] += d; }\n }\n }\n \n true\n }\n}\n```
1
0
['Rust']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Sweep line
sweep-line-by-darv-mx80
Code\n\nclass Solution {\n bool checkArray(List<int> nums, int k) {\n final sweep = List.filled(nums.length, 0);\n int prev_sweep_sum = 0;\n for (int
darv
NORMAL
2023-07-09T19:19:39.663999+00:00
2023-07-09T19:19:39.664018+00:00
67
false
# Code\n```\nclass Solution {\n bool checkArray(List<int> nums, int k) {\n final sweep = List.filled(nums.length, 0);\n int prev_sweep_sum = 0;\n for (int i = 0; i < nums.length; i++) {\n sweep[i] += prev_sweep_sum;\n\n if (nums[i] + sweep[i] != 0) {\n if (nums.length - i < k) return false;\n\n if (nums[i] + sweep[i] < 0) return false;\n final int change = nums[i] + sweep[i];\n sweep[i] -= change;\n if (i + k < nums.length)\n sweep[i + k] += change;\n }\n\n prev_sweep_sum = sweep[i];\n }\n return true;\n }\n}\n```
1
0
['Dart']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Simple Answer | Good for Beginners | C++ | Java | ♥🚀
simple-answer-good-for-beginners-c-java-7xup2
C++\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size(), s = 0,j = 0;\n deque<pair<int, int>> q;\n
adityabahl
NORMAL
2023-07-09T15:27:21.966795+00:00
2023-07-09T15:27:21.966824+00:00
464
false
C++\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size(), s = 0,j = 0;\n deque<pair<int, int>> q;\n for (int i = 0; i < n; ++i) {\n while (!q.empty() && i - q.front().first >= k) {\n s -= q.front().second;\n q.pop_front();\n }\n if (nums[i] < s)\n return false;\n nums[i] -= s;\n if (nums[i]) {\n int v = nums[i];\n nums[i] = 0;\n s += v;\n q.push_back({ i, v });\n }\n while (!q.empty() && i - q.back().first >= k - 1) {\n s -= q.back().second;\n q.pop_back();\n }\n }\n return q.empty();\n }\n};\n```\nJava\n```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int n = nums.length;\n int s = 0;\n int j = 0;\n Deque<Pair<Integer, Integer>> q = new ArrayDeque<>();\n for (int i = 0; i < n; ++i) {\n while (!q.isEmpty() && i - q.peekFirst().getKey() >= k) {\n s -= q.peekFirst().getValue();\n q.pollFirst();\n }\n if (nums[i] < s) \n return false;\n nums[i] -= s;\n if (nums[i] != 0) {\n int v = nums[i];\n nums[i] = 0;\n s += v;\n q.offerLast(new Pair<>(i, v));\n }\n while (!q.isEmpty() && i - q.peekLast().getKey() >= k - 1) {\n s -= q.peekLast().getValue();\n q.pollLast();\n }\n }\n return q.isEmpty();\n }\n}\n```
1
0
['C', 'Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Swift | Sliding window approach explained
swift-sliding-window-approach-explained-nheat
Intuition\n- If there is a winning set of operations, then the order in which these operations are performed does not matter.\n- The first and last numbers have
VladimirTheLeet
NORMAL
2023-07-09T06:12:30.440441+00:00
2023-07-09T07:19:44.684715+00:00
145
false
# Intuition\n- If there is a winning set of operations, then the order in which these operations are performed does not matter.\n- The first and last numbers have only one variant of valid subarray that affects them.\n- More generally, the same can be said for the first and last non-zero nums.\n- We can reduce nums to zero one-by-one by going from left to right and performing `num[i]` decrease operations on subarray starting at `i`. By virtue of our first statement, if there is a winning set of operations, it can be arranged this way.\n- If any number will drop below zero due to decrease operation initiated by some of the previous nums, the goal is unachievable.\n\n# Approach\n\nWe will not straightforwardly perform the \'decrease by num[i]\' operation on the whole $k$ nums after each index `i`. Instead, we note that the decrement for a number is only affected by the previous $k-1$ numbs, or, more precisely, accumulated decrement for `num[i]` is $\\sum$`num[j]`, where $max(0, i-k) \\le j \\lt i$, and `num[j]` is the current value at `j` index when we reached `j` in the process, applied its own decrement, and then considered the subarray starting from `j`.\nWe\'ll denote this decrement value as `slidingSum` and update it in a sliding window manner, by adding next num value and subtracting the last, $(k+1)$th from head since it drops out of the affecting range. Simply saying, we mantain $k$ size sliding window, keeping track of its sum. This way we know how much to subtract from the each next number.\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(1)$\n\n# Code\n```\nclass Solution {\n func checkArray(_ nums: [Int], _ k: Int) -> Bool\n {\n let n = nums.count\n if k == 1 { return true }\n if k == n { return nums.allSatisfy { $0 == nums[0] } }\n \n var nums = nums, slidingSum = 0\n for i in 0..<n\n {\n // remove exceeding\n if i >= k { slidingSum -= nums[i-k] }\n\n // bringing previous nums to zero causes this num to become negative\n if nums[i] < slidingSum { return false }\n\n // apply the accumulated decrement\n nums[i] -= slidingSum\n\n // advance, taking into account that for the next k-1 elements, the\n // decrement will be increased by the value remained in that num\n if i <= n-k { slidingSum += nums[i] }\n\n // our window bumped into right border and now shrinks\n // no more operations possible, we just check whether the\n // previously arranged ones will bring all the remaining nums to zero\n else if nums[i] != 0 { return false }\n }\n return true\n }\n}\n```
1
0
['Swift', 'Sliding Window']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C++ Simple Greedy Two pointers
c-simple-greedy-two-pointers-by-harshils-m57c
Code\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n int i=0, j=n-1;\n while(i <= j){\
HarshilSad007
NORMAL
2023-07-09T04:44:49.184307+00:00
2023-07-09T04:44:49.184336+00:00
543
false
# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n int i=0, j=n-1;\n while(i <= j){\n while(i<=j && nums[i]==0) i++;\n while(i<=j && nums[j]==0) j--;\n if(i>j) return true;\n if(j-i < k-1) return false;\n if(nums[i] >= nums[j]){\n for(int x=i+1; x<i+k; x++){\n if(nums[x] < nums[i]) return false;\n nums[x] -= nums[i];\n }\n nums[i] = 0;\n } else {\n for(int x=j-1; x>j-k; x--){\n if(nums[x] < nums[j]) return false;\n nums[x] -= nums[j];\n }\n nums[j] = 0;\n }\n }\n return true;\n }\n};\n```
1
0
['Two Pointers', 'Greedy', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Using queue approach | C++ solution
using-queue-approach-c-solution-by-gl01-vhs0
Intuition\nThe very first & simple intuition is to store the position up to which deletions are being made and update the delete sum with nums array to ensure t
gl01
NORMAL
2023-07-09T04:35:40.313967+00:00
2023-07-09T04:35:40.313985+00:00
403
false
# Intuition\nThe very first & simple intuition is to store the position up to which deletions are being made and update the delete sum with `nums` array to ensure the elements become zero.\n\n# Approach\nI used a `queue` to store deleted elements and a vector `del` to keep track of their positions. Starting from index `0`, I push elements greater than 0 into the queue, since we need to delete them to make those 0. I update the delete sum `sum` by adding the element, and I also update the `del` array with the last delete mark, which is `(i+k-1)`. This process is repeated iteratively. If subtraction from `nums` is not possible during the iteration, the loop is exited.\n\nIn the end, we will check whether it is possible to make all elements zero or not.\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n if (k == 1)\n return true;\n\n int n = nums.size(), sum = nums[0];\n \n vector<int> del(n + 1, 0); \n queue<int> q;\n \n q.push(nums[0]);\n nums[0] = 0;\n del[k - 1] = 1;\n \n for (int i = 1; i < n; ++i) {\n if (sum >= 0)\n nums[i] -= sum;\n else\n break;\n\n if (nums[i] > 0 && i <= n - k) {\n q.push(nums[i]);\n sum += nums[i];\n nums[i] = 0;\n del[i + k - 1] = 1;\n }\n \n if (del[i] == 1) {\n sum -= q.front();\n q.pop();\n }\n }\n \n for (auto i : nums) {\n if (i != 0)\n return false;\n }\n \n return true;\n }\n};\n```
1
0
['Queue', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Exactly same q from codeforces
exactly-same-q-from-codeforces-by-heho12-j68z
\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int n = nums.length;\n for (int i = 0; i < n - k + 1; i++) {\n
heho123
NORMAL
2023-07-09T04:07:32.935590+00:00
2023-07-09T04:07:32.935615+00:00
493
false
```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int n = nums.length;\n for (int i = 0; i < n - k + 1; i++) {\n if (nums[i] > 0) {\n int min = nums[i];\n for (int j = i; j < i + k; j++) {\n nums[j] -= min;\n if (nums[j] < 0) {\n return false;\n }\n }\n }\n }\n for (int i = n - k + 1; i < n; i++) {\n if (nums[i] != 0) {\n return false;\n }\n }\n return true;\n }\n}\n```
1
1
[]
2
apply-operations-to-make-all-array-elements-equal-to-zero
Prefix Sum
prefix-sum-by-awakenx-s6nf
Code
AwakenX
NORMAL
2025-04-09T12:59:40.053472+00:00
2025-04-09T12:59:40.053472+00:00
2
false
# Code ```cpp [] class Solution { public: bool checkArray(vector<int>& nums, int k) { int n = nums.size(); vector<int> prefix(n + 1); prefix[0] = -1 * nums[0]; prefix[k] = nums[0]; for(int i = 1; i < n; i++) { prefix[i] += prefix[i - 1]; int rest = nums[i] + prefix[i]; if(rest < 0) return false; prefix[i] -= rest; if(i + k <= n) prefix[i + k] += rest; else if(rest > 0) return false; } return true; } }; ```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Running Difference Array Technique | Java Code
running-difference-array-technique-java-cds55
CodeComplexity Analysis Time complexity: O(n) Space complexity: O(n) Do Upvote ⬆️⬆️⬆️.Keep Hustling,Keep Coding!!!
Rahul_Me_Gupta
NORMAL
2025-03-18T15:16:48.320011+00:00
2025-03-18T15:16:48.320011+00:00
10
false
# Code ```java [] class Solution { public static boolean check(int[] nums,int start,int end) { for(int i=start;i<=end;i++){ if(nums[i]!=0){ return false; } } return true; } public static void print(int[] nums){ for(int it:nums){ System.out.print(it+" "); } System.out.println(""); } public boolean checkArray(int[] nums, int k) { int n=nums.length; int[] diff=new int[n+1]; int currsum = 0; for(int i=0;i<n;i++){ currsum+=diff[i]; nums[i]+=currsum; if(nums[i]<0){ return false; } if(nums[i]>0){ if (i+k>n){ return false; } currsum-=nums[i]; diff[i+k]+=nums[i]; nums[i]=0; } } //print(nums); return check(nums,0,n-1); } } ``` # Complexity Analysis - Time complexity: $$O(n)$$ - Space complexity: $$O(n)$$ # Do Upvote ⬆️⬆️⬆️. # Keep Hustling,Keep Coding!!!
0
0
['Array', 'Hash Table', 'Math', 'Prefix Sum', 'C++', 'Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Reverse of Line Sweep
reverse-of-line-sweep-by-lilongxue-rbhw
IntuitionIt can be solved by using the reverse of line sweep.ApproachSee code.Complexity Time complexity: O(n) Space complexity: O(n) Code
lilongxue
NORMAL
2025-03-18T04:21:20.620793+00:00
2025-03-18T04:21:20.620793+00:00
3
false
# Intuition It can be solved by using the reverse of line sweep. # Approach See code. # Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```javascript [] /** * @param {number[]} nums * @param {number} k * @return {boolean} */ var checkArray = function(nums, k) { const len = nums.length const index2end = new Array(1 + len).fill(0) let subtractMe = 0 for (const [i, val] of nums.entries()) { const end = index2end[i] if (end !== undefined) { subtractMe -= end index2end[i] = 0 } if (i === len) break const val = nums[i] const height = val - subtractMe if (height < 0) return false if (height > 0) { subtractMe += height index2end[i + k] = height } } index2end[len] = 0 if (index2end.some(val => val !== 0)) return false return true }; ```
0
0
['JavaScript']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Greedy + Sliding Window || C++|| O(N) Time Complexity
greedy-sliding-window-c-on-time-complexi-vs4w
IntuitionTo make the entire array zero using the given operation, we need to apply a greedy approach while keeping track of the accumulated decrement effect. Si
Shiva1906
NORMAL
2025-03-07T17:08:00.219079+00:00
2025-03-07T17:08:00.219079+00:00
6
false
# Intuition To make the entire array zero using the given operation, we need to apply a **greedy** approach while keeping track of the accumulated decrement effect. Since we can only modify `k` consecutive elements at a time, we must ensure that at every index `i`, the remaining value in `nums[i]` is sufficient to be reduced to zero without violating constraints. # Approach 1. **Use a running sum `cur`** to keep track of the net decrement applied so far. 2. **Iterate through the array**: - If `cur > nums[i]`, it means we have over-decremented before reaching `i`, making it impossible to reach zero → return `false`. - Otherwise, subtract `cur` from `nums[i]` to reflect previous decrements. - **Increase `cur` by `nums[i]`**, meaning we start a new operation affecting the next `k` elements. - If `i >= k - 1`, we **remove the effect** of the operation that started `k` steps earlier by decrementing `cur` with `nums[i - k + 1]`. 3. After iterating through the array, check if `cur == 0` to ensure all elements are zero. # Complexity - **Time complexity:** - $$O(N)$$ since we iterate through `nums` once. - **Space complexity:** - $$O(1)$$ as we modify `nums` in place and use only a few extra variables. # Code ```cpp class Solution { public: bool checkArray(vector<int>& nums, int k) { int cur = 0; int n = nums.size(); for (int i = 0; i < n; i++) { if (cur > nums[i]) return false; // Impossible to make nums[i] zero nums[i] -= cur; cur += nums[i]; // Apply operation starting at i if (i >= k - 1) cur -= nums[i - k + 1]; // Remove effect of past operation } return cur == 0; } };
0
0
['Array', 'Greedy', 'Sliding Window', 'Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
python
python-by-mykono-g1w9
Code
Mykono
NORMAL
2025-03-07T08:52:24.705891+00:00
2025-03-07T08:52:24.705891+00:00
3
false
# Code ```python3 [] class Solution: def checkArray(self, nums: List[int], k: int) -> bool: cur = 0 for i, num in enumerate(nums): if cur > num: return False # num - cur is ops required after cur ops # and i's contribution to cur nums[i], cur = num - cur, num if i >= k - 1: cur -= nums[i - k + 1] return cur == 0 ```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Easy Python Solution
easy-python-solution-by-vidhyarthisunav-rnoz
Code
vidhyarthisunav
NORMAL
2025-02-10T21:48:47.788312+00:00
2025-02-10T21:48:47.788312+00:00
22
false
# Code ```python3 [] class Solution: def checkArray(self, nums: List[int], k: int) -> bool: n = len(nums) diff = [0] * (n + 1) curr = 0 for i in range(n): curr += diff[i] nums[i] += curr if nums[i] < 0: return False if nums[i] > 0: if i + k > n: return False res = nums[i] nums[i] -= res curr -= res diff[i + k] += res return True ```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Java difference array + sliding window beats 63%
java-difference-array-sliding-window-bea-ci27
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
siyang_yin
NORMAL
2025-02-06T22:11:10.130138+00:00
2025-02-06T22:11:10.130138+00:00
13
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: $$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(n)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public boolean checkArray(int[] a, int k) { int n = a.length; int[] d = new int[n]; d[0] = a[0]; for (int i = 1; i < k; i++) { d[i] = a[i] - a[i - 1]; if (d[i] < 0) return false; if (n == k && d[i] > 0) return false; } for (int i = k; i < n; i++) { d[i] = a[i] - a[i - 1] + d[i - k]; d[i - k] = 0; if (d[i] < 0) return false; if (i > n - k && d[i] > 0) return false; } return true; } } ```
0
0
['Sliding Window', 'Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Py Solution Leverage Prefix Sums Linear Pass O(N) T,S Solution
py-solution-leverage-prefix-sums-linear-in99t
Intuition and ApproachSee problem titleComplexityN=len(input) Time complexity: O(N) Space complexity: O(N) ( Explicit ) O(1) ( Implicit ) Code
2018hsridhar
NORMAL
2025-01-09T20:29:58.335825+00:00
2025-01-09T20:29:58.335825+00:00
27
false
# Intuition and Approach See problem title # Complexity $$N = len(input)$$ - Time complexity: $$O(N)$$ - Space complexity: $$O(N)$$ ( Explicit ) $$O(1)$$ ( Implicit ) # Code ```python3 [] ''' URL := https://leetcode.com/problems/apply-operations-to-make-all-array-elements-equal-to-zero/description/ 2772. Apply Operations to Make All Array Elements Equal to Zero Target complexity analysis Let N := length(input list) Time = O(N) Space = O(1) (E) O(1) ( I ) Intuition and Approach : 1. We must traverse the array left to right. If we have an element > 0 in the first index ( 0 ), we must decrement it by exactly it's value 2. Apply those decrements rightbound ( by size of k ) 3. If a condition breaks for a given element, then bail out Can we think in terms of sliding windows as well ( for incr/decr operations )? ''' class Solution: def checkArray(self, nums: List[int], k: int) -> bool: canMakeAllZero = True n = len(nums) posDeltas = [0 for idx in range(n)] runSum = 0 index = 0 leftBound = len(nums) - k while(index <= leftBound): num = nums[index] runSum -= posDeltas[index] valDiff = num - runSum if(valDiff >= 0): if(index + k < n): posDeltas[index + k] = valDiff runSum += valDiff elif(valDiff < 0): canMakeAllZero = False break index += 1 # check rest can go to zero ( special case here ) # evolve run Sum here? while(index < len(nums)): runSum -= posDeltas[index] curNum = nums[index] if(curNum - runSum != 0): canMakeAllZero = False index += 1 return canMakeAllZero ```
0
0
['Array', 'Prefix Sum', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Detailed Explanation - Prefix Sum + Sliding Window 🔥
detailed-explanation-prefix-sum-sliding-rnk8a
IntuitionInspired by the post:https://leetcode.com/problems/apply-operations-to-make-all-array-elements-equal-to-zero/solutions/3743200/easiest-solution-intuiti
saiphaniram98
NORMAL
2024-12-14T03:58:24.139123+00:00
2024-12-14T03:59:25.242627+00:00
36
false
# Intuition\n\nInspired by the post:\n\nhttps://leetcode.com/problems/apply-operations-to-make-all-array-elements-equal-to-zero/solutions/3743200/easiest-solution-intuition-explained-o-n-faster-than-100-c-java/\n\nEvery element is impacted by deletions on previous `(k-1)` elements which when put together forms the window.\n\nLet us say, we have an array: `[a, b, c, d, e]` and `k = 3` (window size)\n\nDeletions performed on `[a, b]` will impact `c`\nDeletions performed on `[b, c]` will impact `d`\nDeletions performed on `[c, d]` will impact `e`\n\nFor the first element, we must perform `a` deletions. Because, it has no prior elements which can zero its value.\n\n\n# Approach\n\nConsider the test case, `[3, 2, 2, 4, 4]` and `k = 2`\n\nWe will start with `3` deletions at first.\n\n2 is the element at `idx = 1`\nIt will be impacted by previous `(k-1)` elements => `[3]`\n\nAfter we zero the first element, result will be: `[0, -1, 2, 4, 4]`\n\nThis means, element `2` gets deleted more than needed.\n\nOBSERVATION:\n\nTo zero out the given array, it is mandatory for the first `k` elements to be in increasing order.\n\n### Lets dive into given test case:\n \n`arr = [2, 2, 3, 1, 1, 0]` and `k = 3`\n\nInitial deletions = `2`, the value at index 0.\n\nStart iterating from index 1:\n\n`Window 1:`\n\nInitial State of Window 1: `[2, 2, 3]`\n\n- It is influenced by deletions from prev `(k-1)` elements.\n\n Initial Window: `[2, 2, 3]`\n\n- Since there are 2 deletions, updated value at index 1 become `0`. No new deletions needed.\n\nSame goes with element at index 2. However, we need one more deletion to zero out `3`\n\nTherefore, Deletions in Window 1: `2 + 1 = 3`\n\nIt is time to update the window: (Sliding Window)\n\n- But before that we need to eliminate the impact of the first element of current window on to the next window.\n\nUpdated deletions: `Current deletions - nums[i - (k-1)]` = `3 - 2 = 1`\n\nWhich means, the only deletion from index `2` impacts the next window.\n\n\n`Window 2:`\n \nAfter impacted by arr[0], Initial State of Window 2: `[0, 0, 1]`\n\nWe are at index `3` with number of deletions as `1`.\n\nThe value at index 3 as well zeroes out just by the impact of deletion at index 2. No extra deletions needed.\n\nIt is time to update the window: (Sliding Window)\n\n- But before that we need to eliminate the impact of the first element of current window on to the next window.\n\nUpdated deletions: `Current deletions - nums[i - (k-1)]` = `1 - 0 = 1`\n\n\n`Window 3:`\n\nInitial State of Window 3: `[0, 0, 1]`\n\nWe are at index `4` with number of deletions as `1`.\n\nThe value at index 4 as well zeroes out just by the impact of deletion at index 2. No extra deletions needed.\n\nIt is time to update the window: (Sliding Window)\n\n- But before that we need to eliminate the impact of the first element of current window on to the next window.\n\nUpdated deletions: `Current deletions - nums[i - (k-1)]` = `1 - 0 = 1`\n\n\n`Window 4:`\n\nInitial State of Window 4: `[0, 0, 0]`\n\nWe have finished iterating the loop. Just check, by the time we cross the last element we must have the last element as zero.\n\nKIND OF A DYNAMO EFFECT WITHIN A WINDOW.\n\nReturn \'True\' if that\'s the case. Else \'False\'\n\n\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```python3 []\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n \n \'\'\'\n Very Good Problem.\n \n Pattern: Prefix Sum\n TC = O(n)\n SC = O(1)\n \'\'\'\n n = len(nums)\n if n == 1 or k == 1:\n return True\n \n # First element must be decremented nums[0] times. No other option\n decrements = nums[0]\n\n for i in range(1, n):\n # Latest value - Impact of previous decrements\n nums[i] = nums[i] - decrements\n\n # Previous (i-1) elements decreased nums[i] more than they should\n if nums[i] < 0:\n return False\n \n # If the val > 0, need few more decrements to make this 0\n # decrements + latest value\n decrements = decrements + nums[i]\n\n # Last element of Window? Reset decrements for next window\n if i - (k-1) >= 0:\n decrements = decrements - nums[i - (k-1)]\n \n return nums[n-1] == 0\n```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Sliding window with hashtable
sliding-window-with-hashtable-by-shayank-2k31
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
shayankhan1156
NORMAL
2024-12-01T05:14:38.675016+00:00
2024-12-01T05:14:38.675043+00:00
11
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(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n unordered_map<int,int> mp;\n int start=0;\n int cnt=0;\n int i=0;\n if(k==1)return true;\n int sub=0;\n bool flag=0;\n while(i<nums.size()){\n sub-=mp[i];\n if(i==start){\n if(nums[i]==0){\n i+=1;\n start=i;\n continue;\n }\n flag=1;\n sub+=nums[i];\n mp[i+k]+=nums[i];\n i+=1;\n continue;\n }\n if(nums[i]-sub<0)return false;\n if(nums[i]-sub==0){\n if(i-start+1==k){\n start=i+1;\n flag=0;\n i+=1;\n }else{\n i+=1;\n continue;\n }\n }else{\n int ab=abs(nums[i]-sub);\n mp[i+k]=ab;\n sub+=ab;\n start=i;\n i+=1;\n continue;\n }\n }\n return flag==false;\n }\n};\n```
0
0
['Hash Table', 'Sliding Window', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
[Python] Inverted line sweep (2-liner)
python-inverted-line-sweep-2-liner-by-ds-ihj9
Approach\nWe may use the line sweep technique in reverse:\n\n1. Restore the array of value deltas\n2. Check that this array is valid:\n 2.a First k elements
dsapelnikov
NORMAL
2024-11-09T22:38:12.169844+00:00
2024-11-09T22:49:34.326468+00:00
12
false
# Approach\nWe may use the line sweep technique in reverse:\n\n1. Restore the array of value deltas\n2. Check that this array is valid:\n 2.a First k elements of this array >= 0\n 2.b The sum of every k-spaced subarray == 0\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```python3 []\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n deltas = [b - a for a, b in zip([0] + nums, nums + [0])]\n return all(deltas[i] >= 0 and sum(deltas[i::k]) == 0 for i in range(k))\n```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
[C++] Beats 100% | EASY TO UNDERSTAND INTUITIVE SOLUTION
c-beats-100-easy-to-understand-intuitive-3uja
Intuition\nThe first element in nums needs exactly nums[i] operations and it can appear in only one window i.e. the window starting with itself so all the eleme
ahbar
NORMAL
2024-10-19T13:53:44.749386+00:00
2024-10-19T13:53:44.749421+00:00
4
false
# Intuition\nThe first element in nums needs exactly nums[i] operations and it can appear in only one window i.e. the window starting with itself so all the elements after it within the windows will also get reduced by nums[0], use the same logic for nums[1] and so on..\n\n# Approach\nkeep track of number of operations at each index\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n =nums.size();\n vector<int> ops(n + 1, 0);\n\n for (int i =0; i < n; i++) {\n ops[i] += ops[max(0, i - 1)];\n nums[i] += ops[i];\n\n if (nums[i] >= 0 && i + k <= n) { \n ops[i] -= nums[i]; // remaining operations just for nums[i]\n ops[i + k] += nums[i];\n nums[i] = 0;\n }\n \n if (nums[i] < 0 || (i + k > n && nums[i] != 0)) return false;\n }\n\n return true; \n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Easy C++ Solution
easy-c-solution-by-himanshuackerman-j7fv
Code\ncpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n for(int i = 0; i < nums.size() -
himanshuackerman
NORMAL
2024-09-06T17:46:24.057405+00:00
2024-09-06T17:46:24.057433+00:00
9
false
# Code\n```cpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n for(int i = 0; i < nums.size() - k + 1; i++){\n if(nums[i] > 0){\n int mini = nums[i];\n for(int j = i; j < i + k; j++){\n nums[j] -= mini;\n if(nums[j] < 0){\n return false;\n }\n }\n }\n }\n for(int i = 0; i < n; i++){\n if(nums[i] != 0){\n return false;\n }\n }\n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
halwa || aao aur kha lo ||
halwa-aao-aur-kha-lo-by-rajan_singh5639-7f5i
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
rajan_singh5639
NORMAL
2024-08-30T21:59:50.695775+00:00
2024-08-30T21:59:50.695813+00:00
6
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```cpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n for(int i = 0; i<=nums.size()-k; i++)\n {\n if(nums[i] ==0) continue;\n if(nums[i] <0) return false;\n int no = nums[i];\n for(int j=i; j<i+k; j++)\n {\n nums[j] = nums[j] - no;\n\n }\n\n\n }\n\n\n for(int i =0; i<nums.size(); i++)\n {\n if(nums[i] >0 || nums[i] <0) return false;\n \n }\n\n\nreturn true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
halwa || aao aur kha lo ||
halwa-aao-aur-kha-lo-by-rajan_singh5639-ms2p
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
rajan_singh5639
NORMAL
2024-08-30T21:59:48.308815+00:00
2024-08-30T21:59:48.308839+00:00
1
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```cpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n for(int i = 0; i<=nums.size()-k; i++)\n {\n if(nums[i] ==0) continue;\n if(nums[i] <0) return false;\n int no = nums[i];\n for(int j=i; j<i+k; j++)\n {\n nums[j] = nums[j] - no;\n\n }\n\n\n }\n\n\n for(int i =0; i<nums.size(); i++)\n {\n if(nums[i] >0 || nums[i] <0) return false;\n \n }\n\n\nreturn true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
khud samz sakte ho aram sss
khud-samz-sakte-ho-aram-sss-by-rajan_sin-6ht0
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
rajan_singh5639
NORMAL
2024-08-30T21:07:54.300951+00:00
2024-08-30T21:07:54.300979+00:00
4
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```cpp []\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n for(int i = 0; i<=nums.size()-k; i++)\n {\n if(nums[i] ==0) continue;\n if(nums[i] <0) return false;\n int no = nums[i];\n for(int j=i; j<i+k; j++)\n {\n nums[j] = nums[j] - no;\n\n }\n\n\n }\n\n\n for(int i =0; i<nums.size(); i++)\n {\n if(nums[i] >0 || nums[i] <0) return false;\n \n }\n\n\nreturn true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Simple Prefix Sum C++✅✅|Easy Solution
simple-prefix-sum-ceasy-solution-by-jaye-g45r
\n\n# Code\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> pre(n, 0);\n\n
Jayesh_06
NORMAL
2024-08-16T08:21:34.446245+00:00
2024-08-16T08:21:34.446269+00:00
7
false
\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> pre(n, 0);\n\n for (int i = 0; i < n; i++) {\n (i > 0) ? pre[i] += pre[i - 1] : 0;\n nums[i] -= pre[i];\n if (nums[i] < 0) {\n return false;\n }\n if (i < n - k + 1) {\n pre[i] += nums[i];\n if (i + k < n) {\n pre[i + k] -= nums[i];\n }\n nums[i] = 0;\n }\n }\n\n for (int i = 0; i < n; i++) {\n if (i > 0 && nums[i] != 0) {\n return false;\n }\n }\n return true;\n }\n};\n```
0
0
['Array', 'Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Sliding window with subtraction.
sliding-window-with-subtraction-by-sav20-t6q6
Approach\nIn the loop, I look for the first non-"0" first.\nThis value is used as the "subtractor" in a loop of length "k".\nIf there is a number smaller than t
sav20011962
NORMAL
2024-07-15T08:25:01.923392+00:00
2024-07-15T08:25:01.923427+00:00
2
false
# Approach\nIn the loop, I look for the first non-"0" first.\nThis value is used as the "subtractor" in a loop of length "k".\nIf there is a number smaller than the "subtractor" in this loop, no conversion is possible.\n# Complexity\nimage.\n![image.png](https://assets.leetcode.com/users/images/3cc3f905-0079-46dd-b780-12223b1b2c14_1721031828.1012306.png)\n```\nclass Solution {\n fun checkArray(nums: IntArray, k: Int): Boolean {\n val len = nums.size\n var pos = 0\n while (pos<len) {\n while (pos<len && nums[pos] == 0) {\n pos++\n }\n if (pos==len) return true\n if (pos+k>len) return false\n val delta = nums[pos]\n for (i in 0 until k) {\n if (nums[pos+i]>=delta) nums[pos+i] -=delta\n else return false\n }\n }\n return true\n }\n}\n```
0
0
['Kotlin']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Simple Approach but can be optimized more
simple-approach-but-can-be-optimized-mor-rn3c
Intuition\n1)Trying out 5-6 test cases you will find out the pattern that we need to decrement a particular value nums[i], nums[i] times then only that will bec
Hardy1
NORMAL
2024-07-03T14:18:23.007132+00:00
2024-07-03T14:18:23.007172+00:00
14
false
# Intuition\n1)Trying out 5-6 test cases you will find out the pattern that we need to decrement a particular value nums[i], nums[i] times then only that will become zero.\n\n# Approach\n1) Approach is similar to prefix sum.\n2) First we need to check how many times we need to decrement a particular element.\n3) We need to decrement each value from that particular element till k elements by number of times we need to decrement a particular value.\n\n4) We also need to check if the element is getting negative , in that case return false.\n# Complexity\n- Time complexity:\nO(n*k)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n //checking first left k elements in the subarray apart from 0 like from [0,1,3,4] choose 1,3,4\n /* int n=nums.size();\n if(n<k){\n return false;\n }\n if(k>1 && ((nums[0]>nums[1]) || (nums[n-1]>nums[n-2]))){ //This I need to check for every window or subarray of size k\n return false;\n }\n if(k==1){\n return true;\n } */\n //Take first k elements and decrease their values by 1 which are starting with non-zero element.\n //Take last k elements and decrease their values by 1 which are starting with non-zero element.\n //These both should be done one after the other and for both these cases need to check this (nums[0]>nums[1]) || (nums[n-1]>nums[n-2])).\n \n // If the array length is less than k, we can\'t perform any operations\n int n=nums.size();\n if (n < k) {\n return false;\n }\n\n // Iterate through the array and try to make all elements zero\n for (int i = 0; i <= n - k; i++) {\n if (nums[i] < 0) {\n return false; // If any element becomes negative, it\'s not possible to make all elements zero\n }\n if (nums[i] > 0) {\n int decrement = nums[i]; // Number of times we need to apply the operation to make nums[i] zero\n for (int j = 0; j < k; j++) {\n nums[i + j] -= decrement; // Apply the decrement operation to the subarray\n }\n }\n }\n\n // Check the remaining elements after the last subarray operation\n for (int i = n - k + 1; i < n; i++) {\n if (nums[i] != 0) {\n return false; // If any element is not zero, return false\n }\n }\n\n return true; // If we reach here, it means we successfully made all elements zero\n\n }\n};\n```
0
0
['Array', 'Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
O(nLogk) using segment tree and lazy propogation
onlogk-using-segment-tree-and-lazy-propo-cowv
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
leethard
NORMAL
2024-06-25T13:27:40.371209+00:00
2024-06-25T13:27:40.371232+00:00
10
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 SegTree:\n def __init__(self, data):\n self.data = data\n self.tree = [0] * (4 * len(self.data))\n self.lazy = [0] * (4 * len(self.data))\n self._init(1, 0, len(self.data) - 1)\n\n def _init(self, i, tl, tr):\n if tl == tr:\n self.tree[i] = self.data[tl]\n return self.tree[i]\n self.tree[i] = self._init(i * 2, tl, (tl + tr) // 2) + self._init(\n i * 2 + 1, (tl + tr) // 2 + 1, tr\n )\n return self.tree[i]\n\n def _update(self, i, ql, qr, add, tl, tr):\n if qr < tl or tr < ql: # [ql, qr] and [tl, tr] don\'t intersect.\n return\n if ql <= tl and tr <= qr: # [ql, qr] includes [tl, tr].\n self.lazy[i] += add\n return\n self.lazy[i * 2] += self.lazy[i]\n self.lazy[i * 2 + 1] += self.lazy[i]\n self.tree[i] += (self.lazy[i] + add) * (min(qr, tr) - max(ql, tl) + 1)\n self.lazy[i] = 0\n self._update(i * 2, ql, qr, add, tl, (tl + tr) // 2)\n self._update(i * 2 + 1, ql, qr, add, (tl + tr) // 2 + 1, tr)\n\n def _query(self, i, ql, qr, tl, tr):\n if qr < tl or tr < ql: # [ql, qr] and [tl, tr] don\'t intersect.\n return 0\n if ql <= tl and tr <= qr: # [ql, qr] includes [tl, tr].\n return self.tree[i] + self.lazy[i] * (tr - tl + 1)\n self.lazy[i * 2] += self.lazy[i]\n self.lazy[i * 2 + 1] += self.lazy[i]\n self.tree[i] += self.lazy[i]\n self.lazy[i] = 0\n return self._query(i * 2, ql, qr, tl, (tl + tr) // 2) + self._query(\n i * 2 + 1, ql, qr, (tl + tr) // 2 + 1, tr\n )\n\n def update(self, left, right, add):\n self._update(1, left, right, add, 0, len(self.data) - 1)\n\n def query(self, left, right):\n return self._query(1, left, right, 0, len(self.data) - 1)\n\n\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n s = SegTree([0] * len(nums))\n for i in range(len(nums) - k + 1):\n if nums[i] == 0 and s.query(i, i) == 0:\n continue\n nums[i] -= s.query(i, i)\n if nums[i] < 0:\n return False\n if nums[i] > 0:\n s.update(i + 1, i + k - 1, nums[i])\n\n for i in range(len(nums) - k + 1,len(nums)):\n if nums[i]-s.query(i,i)!=0:\n return False\n return True\n```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Simple python3 solution | Prefix Sum + Hash Table
simple-python3-solution-prefix-sum-hash-os8e7
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
tigprog
NORMAL
2024-06-24T20:31:27.037568+00:00
2024-06-24T20:33:54.915150+00:00
45
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n n = len(nums)\n\n deltas = Counter()\n current_delta = 0\n\n for i, elem in enumerate(nums):\n current_delta += deltas.pop(i, 0)\n elem -= current_delta\n\n if elem == 0:\n continue\n if elem < 0:\n return False\n \n if i + k > n:\n return False\n current_delta += elem\n deltas[i + k] -= elem\n\n return True\n```
0
0
['Hash Table', 'Greedy', 'Sliding Window', 'Prefix Sum', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Java brute force
java-brute-force-by-ihatealgothrim-60t0
Intuition\n- Do the actual decrease operation over nums start from beginning with length of k, say indices (i, j) inclusive, repeat this process until the end o
IHateAlgothrim
NORMAL
2024-06-13T13:32:13.579410+00:00
2024-06-13T13:32:13.579442+00:00
20
false
# Intuition\n- Do the actual decrease operation over ```nums``` start from beginning with length of ```k```, say indices ```(i, j)``` inclusive, repeat this process until the end of ```nums```\n- Each time when decreasing, ```nums[i]``` MUST always less or equals to the one on the right i.e. ```nums[i+1], nums[i+2], nums[i+3], ... , nums[j]``` (You can play this on paper to prove it)\n- At the end, check ```nums``` emptiness\n\n# Code\n```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n for (int i = 0; i < nums.length - k + 1; i++) {\n if (nums[i] == 0) continue;\n int start = nums[i];\n for (int j = i; j < i + k; j++) {\n if (nums[j] < start) return false;\n nums[j] -= start;\n }\n }\n return Arrays.stream(nums).allMatch(num -> num == 0);\n }\n}\n```
0
0
['Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
scala ugly nonFP solution. cleaner nonFP or FP produce MLE
scala-ugly-nonfp-solution-cleaner-nonfp-q30il
scala\nobject Solution {\n import collection.immutable.Queue\n def checkArray(nums: Array[Int], k: Int): Boolean =\n def forall(lo:Int, hi:Int): Boolean =\
vititov
NORMAL
2024-06-08T16:11:53.097986+00:00
2024-06-08T16:14:17.688778+00:00
1
false
```scala\nobject Solution {\n import collection.immutable.Queue\n def checkArray(nums: Array[Int], k: Int): Boolean =\n def forall(lo:Int, hi:Int): Boolean =\n if(hi<=lo) true else nums(hi)==nums(lo) && forall(lo,hi-1)\n def dec(lo:Int, hi:Int): Unit = if(hi>=lo) { nums(hi)-=nums(lo); dec(lo,hi-1) }\n def f(i: Int): Boolean =\n if(nums(i)<0) false\n else if(i+k>=nums.size) forall(i,i+k-1)\n else { dec(i,i+k-1); f(i+1) }\n f(0)\n\n def checkArray_Non_FP_MLE(nums: Array[Int], k: Int): Boolean =\n def f(i: Int): Boolean =\n lazy val j=i+k\n lazy val h = nums(i)\n if(h<0) false\n else if(j>=nums.size) ((i+1) until j).forall{x => nums(x) == h }\n else {(j-1 to i by -1).foreach(i2 => nums(i2)-=h); f(i+1)}\n f(0)\n\n def checkArrayFP_MLE(nums: Array[Int], k: Int): Boolean =\n def f(seq: Seq[Int], q:Queue[Int]): Boolean =\n if(q.head<0) false \n else if(seq.isEmpty) q.tail.forall(_ == q.head)\n else f(seq.tail, (q.tail).map(_ - q.head) :+ seq.head)\n f(nums.iterator.drop(k).to(List), nums.iterator.take(k).to(Queue))\n}\n```
0
0
['Scala']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Greedy 10 lines code c++
greedy-10-lines-code-c-by-vishal_reddy_k-bk25
Intuition\n Describe your first thoughts on how to solve this problem. \nGreedy and simple. go from first element and check the conditions\n\n# Approach\n Descr
VISHAL_REDDY_K
NORMAL
2024-06-08T11:57:50.905902+00:00
2024-06-08T11:57:50.905932+00:00
6
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreedy and simple. go from first element and check the conditions\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> dec(n + 1, 0); // +1 to handle the edge case cleanly\n int curr = 0;\n \n for (int i = 0; i < n; ++i) {\n curr += dec[i]; // Apply the accumulated decrement at index i\n if (nums[i] + curr < 0) return false; // If it goes negative, impossible to continue\n if (nums[i] + curr > 0) {\n if (i + k > n) return false; // If we can\'t apply the operation to a full subarray\n int decrement = nums[i] + curr; // Amount to decrement\n curr -= decrement; // Apply the decrement starting from current index\n dec[i + k] += decrement; // Undo the decrement effect after k elements\n }\n }\n \n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Cpp code||Brute method||traversing all the possible subarrays from left to right and making them 0.
cpp-codebrute-methodtraversing-all-the-p-uliz
Intuition\nwe have to make all the possible k element subarrays to 0;\nso starting from the very left of nums we\'ll try to turn each of the subarray into 0 whi
yashashvi-J
NORMAL
2024-06-08T09:57:19.921767+00:00
2024-06-08T09:57:19.921797+00:00
9
false
# Intuition\nwe have to make all the possible k element subarrays to 0;\nso starting from the very left of nums we\'ll try to turn each of the subarray into 0 while moving right \nfor instance,if a[0]>0 then we have to subtract a certain number(temp=a[0]) from all k elements following it.\n\n\neg.[2,2,3,1,1,0] and k=3\na[0]>0 so temp=2;\ni=0->2 we\'ll sub 2 from k elements so,\nnums=[0,0,1,1,0];\na[1]-> skip\na[2]>0 so,\ntemp=nums[2]=1;\ni=2->4 we\'ll sub 1 from k elements so,\nnums=[0,0,0,0,0,0];\na[3]->skip\na[4]->skip\na[5]->skip\nreturn true;\n\n1.while subtracting if an element becomes 0 then return false;\n2.if we are left with an element a[i]>0 then we\'ll subratct a[i] from all k elements following it but if there are not k elements then it is not possible to change it to 0 hence return false;\n\n\n# Complexity\n- Time complexity:\nO(n*k) \n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n=nums.size();\n for(int i=0;i<n;i++){\n if(nums[i]==0) continue; // if number is already 0 just skip it\n if(i+k>n) return false;\n else if(nums[i]<0) return false; // if a number becomes negative \n //while subtracting from a subarray then false\n else if(nums[i]>0){//if number is greater than 0 we\'ll make it 0\n //and also subtract that value from all following k elements\n int temp=nums[i];\n for(int j=i;j<k+i;j++){\n nums[j]=nums[j]-temp;\n }\n }\n \n }\n return true;\n }\n};\n```
0
0
['Array', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Beats 100% 97%. In-place prefix sum.
beats-100-97-in-place-prefix-sum-by-tyle-imjz
Approach\nKeep prefix sum of how much we have currently decreased an element. If it is negative then return False. Decrease element to 0, and store how much we
tyler__
NORMAL
2024-06-06T04:12:43.671272+00:00
2024-06-06T04:12:43.671307+00:00
17
false
# Approach\nKeep prefix sum of how much we have currently decreased an element. If it is negative then return False. Decrease element to 0, and store how much we decreased the element. \n\nWe can\'t decrease the last k-1 elements any farther.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1) extra space\n\n# Code\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n n = len(nums)\n ct = 0\n for i in range(n):\n if i>=k:\n ct -= nums[i-k]\n v = nums[i]-ct\n if v<0: return False\n nums[i] = v\n if i<=n-k:\n ct+=v\n else:\n if v!=0: return False\n return True\n```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
O(n) solution using a single pass on the array
on-solution-using-a-single-pass-on-the-a-2ygu
Intuition\nWe start from the left hand side of the array, and we know that for every extrimity, we have no choice but to remove a[0] times the array, that will
magic_yoni
NORMAL
2024-06-04T07:52:23.387184+00:00
2024-06-04T07:52:23.387215+00:00
13
false
# Intuition\nWe start from the left hand side of the array, and we know that for every extrimity, we have no choice but to remove a[0] times the array, that will impact the next k elements. We keep track of the next k elements to know what has been removed already. \n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution(object):\n def checkArray(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: bool\n """\n if k == 1:\n return True\n curr_s = 0\n arr = [0]*(k + len(nums))\n for i, n in enumerate(nums):\n curr_s -= arr[i]\n if n - curr_s < 0 or (i > len(nums) - k and n - curr_s != 0):\n return False\n arr[i+k] = n - curr_s\n curr_s = n\n \n return True\n```
0
0
['Python']
0
apply-operations-to-make-all-array-elements-equal-to-zero
One of the best solution
one-of-the-best-solution-by-risabhuchiha-4vk7
\n\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n if(k==1)return true;\n Deque<Integer>dq=new ArrayDeque<>();\n int nd=0;\n
risabhuchiha
NORMAL
2024-06-01T20:11:11.457524+00:00
2024-06-01T20:11:11.457545+00:00
22
false
\n```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n if(k==1)return true;\n Deque<Integer>dq=new ArrayDeque<>();\n int nd=0;\n for(int i=0;i<nums.length;i++){\n if(i>=k){\n nd-=dq.pollFirst();\n }\n if(nums[i]<nd)return false;\n int nx=nums[i]-nd;\n dq.offerLast(nx);\n nd+=nx;\n }\n return dq.getLast()==0;\n }\n}\n```
0
0
['Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Hard Intution and observation | | C++
hard-intution-and-observation-c-by-arbaz-bmyp
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
Arbaz_nitp
NORMAL
2024-05-20T10:13:17.995010+00:00
2024-05-20T10:13:17.995041+00:00
14
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 bool checkArray(vector<int>& nums, int k) {\n int n=nums.size(),sum=0;\n for(int i=0;i<n;i++){ \n if(sum>nums[i])\n return false;\n nums[i]-=sum;\n sum+=nums[i]; \n if(i-k>=-1)\n sum-=nums[i-k+1];\n }\n return sum==0;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
c++ most easiest approach
c-most-easiest-approach-by-bhavanabadava-ockt
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
bhavanabadavath29
NORMAL
2024-05-17T06:07:52.457884+00:00
2024-05-17T06:07:52.457918+00:00
12
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 bool checkArray(vector<int>& nums, int k) {\n \n \n int n=nums.size(),sum=0;\n \n for(int i=0;i<n;i++)\n {\n if(sum>nums[i])\n return 0;\n \n nums[i]-=sum;\n sum+=nums[i];\n \n if(i>=k-1)\n sum-=nums[i-k+1];\n }\n return (sum==0);\n }\n\n \n \n\n \n \n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Ruby O(N) time and O(k) space with explanation
ruby-on-time-and-ok-space-with-explanati-d749
Intuition\n\nBy going from left to right, the leftmost element (a0) always has to be reduced to 0. That means the leftmost element and its group have to be redu
rmuntani
NORMAL
2024-04-26T18:21:51.509717+00:00
2024-04-26T18:21:51.509736+00:00
2
false
# Intuition\n\nBy going from left to right, the leftmost element (a0) always has to be reduced to 0. That means the leftmost element and its group have to be reduced by the remaining leftmost (a0). Example:\n\n[7,9,10,11,14] with k = 2 - after reducing the leftmost element and its group, we will get [0,2,10,11,14].\n\nWe can apply that until we get to the end of the last group of the array.\n\nGROUP [7,9] (-7) | GROUP [2, 10] (-2) | GROUP [8,11] (-8)\n[7,9,10,11,14] -> [0,2,10,11,14] -> [0,0,8,11,14] -> [0,0,0,3,14]\n\nBecause of that, we\'ll consider it\'s impossible to reduce all elements to 0 if the accumulated reduction makes the curr element be less than 0. (e.g. [10,3,7] with k = 2 cannot be reduce to 0 because the reduction for the leftmost element and its group would result in [0,-7,7]).\n\nWhen you get to the last group, you cannot change the value that gets subtracted from all of the elements of thaat group. So we get the value that gets subtracted from the leftmost element and subtract it from the remaining elements.\n\nGROUP [3,14] (-3)\n[0,0,0,3,14] -> [0,0,0,0,11] \n\nIn the example above, we don\'t get an array full of zeros, so it\'s impossible to get one for k = 2.\n\nAs we would subtract the remaining leftmost element from its k-sized group for each element the array has, that would result in an algorithm with O(n*k) time-complexity. We can improve that by storing the accumulated subtracted value. When the size of the group used for the subtracting value is greater than k, we update the subtracted value to not consider it.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n) - numbers are seen once\n\n- Space complexity:\nO(k) - the queue stores at most k elements\n\n# Code\n```\n# @param {Integer[]} nums\n# @param {Integer} k\n# @return {Boolean}\ndef check_array(nums, k)\n reduce_in = 0\n queue = []\n\n nums.each.with_index do |n, i|\n delta_reduction = if i <= nums.length - k \n n - reduce_in\n else\n # don\'t update delta_reduction or reduce_in if we\'re in the last group\n 0\n end\n reduce_in += delta_reduction\n queue.push(delta_reduction)\n\n return false if delta_reduction < 0 || n - reduce_in != 0\n\n reduce_in -= queue.shift if queue.length >= k\n end\n\n true\nend\n```
0
0
['Ruby']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Deque
deque-by-macrohard-o5gn
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
macrohard
NORMAL
2024-02-15T07:05:58.329337+00:00
2024-02-15T07:05:58.329385+00:00
7
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 {\n public boolean checkArray(int[] nums, int k) {\n int n = nums.length;\n var q = new ArrayDeque<Integer>();\n for(int i = 0; i < n; i++) {\n int a = nums[i];\n int prevSum = i == 0 ? 0 : nums[i-1];\n if(q.size() == k) prevSum -= q.removeFirst();\n if(prevSum > a) return false;\n if(i >= n - k + 1 && prevSum < a) return false;\n q.addLast(a - prevSum);\n }\n return true;\n }\n}\n```
0
0
['Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
An anology of a stack of pancakes
an-anology-of-a-stack-of-pancakes-by-alc-e132
Intuition\n Describe your first thoughts on how to solve this problem. \nImagine the nums as a stack of even pancakes of length k, say, [1, 2, 2, 1] (k=3).\nWhe
alchenerd
NORMAL
2024-02-11T07:27:35.159371+00:00
2024-02-11T07:27:35.159404+00:00
10
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nImagine the `nums` as a stack of even pancakes of length `k`, say, [1, 2, 2, 1] (k=3).\nWhen we nudge the rightmost pancake to its left, `nums` becomes [2, 2, 2, 0].\nThis is same as taking `nums[3]` and adding it to `nums[0]`.\nIf `nums` is really made of evenly cooked pancakes, then it can eventually be arranged to become [x, x, x, x, ... x, 0, 0, 0, 0, ..., 0], where there are `k` elements of value `x`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe loop through `nums` and add it to `tally[i%k]`. Since we\'re assuming that `nums` is a stack of evenly cooked pancakes, the newly added tally column must be grater then or equal to the previous tally column. If the edge is thicker than the center, then the presumption of `nums` being made of evenly cooked pancakes is false.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nScan once and check for the tally array, thus O(n+k) and k <= n, so O(n).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(k) and in a sense, O(n).\n\n# Code\n```\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n tally = [0] * k\n for i, num in enumerate(nums):\n tally[i%k] += num\n if tally[i%k] < tally[(i-1)%k]:\n return False\n return len(set(tally)) == 1\n\n \n```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Prefix Sum approach~~C++~~Cpp~~O(n) time~~Beats 90%+
prefix-sum-approachccppon-timebeats-90-b-3gwt
Intuition\nAt first it looks like that we have to check a sorted list but it was almost similar to that.\n\n# Approach\nwe have to check a sorted list but wiht
Abdullah-Ishfaq
NORMAL
2024-01-26T13:30:49.854118+00:00
2024-01-26T14:34:41.773269+00:00
14
false
## Intuition\nAt first it looks like that we have to check a sorted list but it was almost similar to that.\n\n# Approach\nwe have to check a sorted list but wiht some ristrictions,\nin case we want list with 0 elements we should take first k elements than i+1 till k+1 and so on but we have to substract difference between two consecutive elemts of first array because they are no longer in use.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n if(k==1){\n return true;\n }\n int s=0,n=nums.size();\n vector<int>pre(n);\n for(int i=0;i<n;i++){\n s+=pre[i];\n int d=nums[i]-s;\n if(d<0 or (d>0 and i+k>n)){\n return false;\n }\n s=nums[i];\n if(i+k<n){\n pre[i+k]-=d;\n }\n }\n return true;\n\n \n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
91.26% Beats | No special algo - just a single loop 🔥🔥🔥
9126-beats-no-special-algo-just-a-single-gerb
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
SyedSohaib
NORMAL
2024-01-23T01:40:43.483368+00:00
2024-01-23T01:40:43.483391+00:00
17
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```\n#define print(ls) for(auto i:ls){cout<<i<<\' \';}cout<<endl; \nclass Solution {\npublic:\n bool checkArray(vector<int>& ls, int k) {\n int n=ls.size();\n long long sum=0;\n for(auto i:ls){sum+=i;}\n if (sum%k){return false;}\n if (k==1){return true;}\n for(int i=0;i<k;i++){\n if (ls[i]<ls[0] or ls[n-1]>ls[n-i-1]){return false;}\n }\n for(int i=1;i<n-1;i++){\n if (ls[i]>ls[i+1]+ls[i-1]){return false;}\n }\n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Python Explained Sliding Window
python-explained-sliding-window-by-dinar-wy4b
Python\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n if k == 1:\n return True\n q = deque([0] * k)\n
dinar
NORMAL
2024-01-10T19:33:01.244564+00:00
2024-01-10T19:33:01.244597+00:00
11
false
```Python\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n if k == 1:\n return True\n q = deque([0] * k)\n s = 0\n for n in nums:\n left = q.popleft()\n s -= left\n if n < s:\n return False\n n -= s\n s += n\n q.append(n)\n return q[-1] == 0\n```\n\n**Explanation**:\n\n1. **Special Case for k = 1**: \n - If `k` is 1, any subarray of size 1 is just a single element. Since you can decrease any element individually, it\'s always possible to make all elements 0, hence return `True`.\n\n2. **Deque Initialization**:\n - A deque (double-ended queue) named `q` of length `k` is initialized with zeros. This deque will be used to keep track of the decreases made to the elements in the array.\n\n3. **Sliding Window Mechanism**:\n - The algorithm employs a sliding window of size `k` to iterate through the array. As it slides, it maintains the sum `s` of the last `k` elements (or fewer at the start) that have been modified.\n\n4. **Iterating Through the Array**:\n - For each element `n` in `nums`, the algorithm does the following:\n - Pops the leftmost element from the deque (`left`). This value represents the decrease made to an element `k` steps behind in the array. Som it has no influence any more.\n - Subtracts this value from the sum `s`, effectively removing its impact as the window slides forward.\n - Compares the current element `n` with the sum `s`. If `n` is less than `s`, it implies that `n` has already been reduced to a negative number by previous operations, which is not allowed. Therefore, it returns `False`.\n - Otherwise, adjusts the current element `n` by subtracting `s` from it, which accounts for the cumulative decrease applied to it from previous elements in the window.\n - Adds the adjusted `n` to the sum `s` and appends it to the deque. This addition represents the decrease that this element will contribute to the next `k` elements in the array.\n\n5. **Final Check**:\n - Finally, the algorithm checks whether the last element in the deque is 0. This is crucial because if the algorithm managed to reduce every element in the array to 0, the final `k` elements (or fewer if the array\'s length is less than `k`) should also be reduced to 0. This last element in the deque represents the cumulative decrease applied to the last element of the array.\n\nIn summary, this solution uses a sliding window approach with a deque to track the decreases applied to each element in the array. It ensures that no element is reduced below 0 and that the final state of the array has all elements equal to 0. If these conditions are met, the function returns `True`; otherwise, it returns `False`.
0
0
['Python']
0
apply-operations-to-make-all-array-elements-equal-to-zero
similar to line sweep tc:O(N) space:O(1)
similar-to-line-sweep-tcon-spaceo1-by-ut-d7ev
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
cute_utkarshi
NORMAL
2024-01-09T17:13:34.818771+00:00
2024-01-09T17:13:34.818801+00:00
4
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 {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int sum=0;\n int n=nums.size();\n nums.push_back(0);\n for(int i=0;i<n;i++)\n {\n if(abs(sum)>nums[i])\n return false;\n else if(abs(sum)==nums[i])\n {\n if(i+k<=n)\n nums[i+k]=nums[i+k]+nums[i];\n\n }\n else\n {\n if(i+k>n)\n return false;\n else\n nums[i+k]=nums[i+k]+nums[i];\n sum=-nums[i];\n }\n }\n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
O(n) time, O(k) mem
on-time-ok-mem-by-harkness-w8x8
Intuition\nThe first elememt needs to become 0, so at some point we need to pick first k elements and subtract nums[0] from all of them. Assume this operation h
harkness
NORMAL
2024-01-05T00:01:31.276780+00:00
2024-01-05T00:01:31.276812+00:00
10
false
# Intuition\nThe first elememt needs to become 0, so at some point we need to pick first k elements and subtract nums[0] from all of them. Assume this operation happens after another operation on another window of k. Then these 2 operations can be swapped in order, and resulting array is the same. So we can perform the reduction on first k elements in the begining. Then we process the next k elements, and so on. Eventually all numbers should be 0.\n\nNaive implementation would take O(n*k), as follows:\n```\ne.g. input = [2,3,5,4,4,3].\neach iteration: subtract first non-0 from first k elements\n2,3,5,4,4,3\n0,1,3,4,4,3\n0,0,2,3,4,3\n0,0,0,1,2,3\n0,0,0,0,1,2\n```\nTo reduce to O(n) time, instead of subtracting all elements in current window by the first element, we keep track of a `base`, where each number in the window minus the base is the real value. Whenever we add new element to the window, we add base on top of it. This new number should be bigger than the last element in the window, otherwise return false. Eventually we check if all elements in the last iteration of the window are equal.\n\n# Code\n```\nfrom collections import deque\n\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n if k == 1:\n return True\n \n n = len(nums)\n C = deque()\n for i in range(k):\n if C and nums[i] < C[-1]:\n return False\n C.append(nums[i])\n base = 0\n for i in range(k, n):\n base = C.popleft()\n if nums[i] < C[-1] - base:\n return False\n C.append(nums[i] + base)\n \n base = C.popleft()\n while C:\n if base != C.popleft():\n return False\n return True\n \n```
0
0
['Queue', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
java solution very important question
java-solution-very-important-question-by-unq5
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
trivedi_cs1
NORMAL
2023-12-24T13:54:44.156962+00:00
2023-12-24T13:54:44.156992+00:00
31
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 {\n public boolean checkArray(int[] nums, int k) {\n int n=nums.length;\n for(int i=0;i<n;i++)\n {\n if(nums[i]==0)\n {\n continue;\n }\n if(nums[i]<0)\n {\n return false;\n }\n int val=nums[i];\n if(i+k-1>=n)\n {\n return false;\n }\n for(int j=i;j<Math.min(n,i+k);j++)\n {\n nums[j]=nums[j]-val;\n }\n // System.out.println(Arrays.toString(nums));\n }\n return true;\n }\n}\n```
0
0
['Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C++, O(n) time, very beginner friendly, with comments
c-on-time-very-beginner-friendly-with-co-wyb5
Intuition\nIf I organized the data such that I had, for each element, only the influence from the previous k - 1 elements; then this problem would be easily sol
adamcesco
NORMAL
2023-11-20T00:42:35.163102+00:00
2023-11-20T00:42:35.163124+00:00
11
false
# Intuition\nIf I organized the data such that I had, for each element, only the influence from the previous k - 1 elements; then this problem would be easily solved.\n\n# Approach\n1. Have a queue, where the front element always holds the influence of the element at i - (k - 1). This queue represents our influence window, and it will only ever be of size k - 1, because any element in nums will over ever be influenced by the previous k - 1 elements.\n2. Have a variable that holds the sum of this influence window.\n3. Use that influence-sum variable to decrement the ith element in num.\n4. Get the left overs from this decrementation and use it as influence on the next k - 1 elements by adding it to influence-sum variable.\n5. Subtract the influence of the element at i - (k - 1) from the influence-sum variable. The element at i - (k - 1) is the front of this window (queue), and now we are shifting this window one element to the right.\n6. Pop for the queue (window)\n7. Push the left over value to the queue so that we can easily remove it from the influence-sum variable when needed.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(k)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n if(k == 1){\n return true;\n }\n\n queue<int> influence_window;\n influence_window.push(0); // nothing influences the first element in nums\n for (int i = 1; i < k - 1; ++i) {\n influence_window.push(nums[0]); // the first element in nums will influence the following k - 1 items\n }\n\n int n = nums.size();\n int sum_of_influence_window = 0; // holds the influence from the previous k - 1 numbers in nums\n // this is because for any element in nums, only the previous k - 1 items have influence over it\n \n for (int i = 0; i < n; ++i) {\n int leftover = nums[i] - sum_of_influence_window;\n if(leftover < 0) { // if the leftover is negative, that means the a number in the previous k - 1 numbers is larger than nums[i]\n return false;\n }\n\n // the influence variable holds the influence from the number at nums[max(0, i - (k - 1))]\n int influence = influence_window.front();\n influence_window.pop();\n\n // this leftover value will now be used as influence on the number at nums[i + (k - 1)]\n influence_window.push(leftover);\n\n // we always add the leftover value from nums[i] to be influence on the next k - 1 numbers\n sum_of_influence_window += leftover;\n if(i - (k - 1) >= 0){\n // but we only remove the influence from the element at the beginning of the influence window if the size of the window is larger than k - 1\n sum_of_influence_window -= influence;\n }\n }\n\n return (sum_of_influence_window == 0); // if sum_of_influence_window is not 0 at this point, then one of the last k numbers was not properly accounted for\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Intuitive solution
intuitive-solution-by-crusher95574-b1xh
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
Crusher95574
NORMAL
2023-10-28T17:19:51.560684+00:00
2023-10-28T17:19:51.560702+00:00
14
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 {\n public boolean checkArray(int[] nums, int k) {\n int ptr=0;\n for(int i=0;i<=nums.length-k;i++){\n if(nums[i]==0)continue;\n if(nums[i]<0)return false;\n if(nums[i]>0)ptr=nums[i];\n \n for(int j=i;j<i+k;j++){\n nums[j]-=ptr; \n }\n }\n for(int j=nums.length-k;j<nums.length;j++){\n if(nums[j]!=0)return false;\n }\n\n return true;\n }\n}\n```
0
0
['Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C# O(n)
c-on-by-tt_nk-ae9a
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
tt_nk
NORMAL
2023-10-15T10:17:28.150000+00:00
2023-10-15T10:17:28.150026+00:00
9
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```\npublic class Solution {\n public bool CheckArray(int[] nums, int k) {\n if(k==1){\n return true;\n }\n int currentSum=0;\n for(int i=0;i<nums.Length;i++){\n nums[i] -= currentSum;\n if(nums[i]<0){\n return false;\n }\n currentSum += nums[i];\n if(i-(k-1)>=0){\n currentSum -= nums[i-(k-1)];\n }\n }\n return nums[nums.Length-1]==0;\n }\n}\n```
0
0
['C#']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Prefix Sum Approach, optiminal Solution
prefix-sum-approach-optiminal-solution-b-1blf
Intuition\n Describe your first thoughts on how to solve this problem. \nFor the first A[i] > 0,\nwe need to select the array A[i],A[i+1]..A[i+k-1]\nand decreas
Shree_Govind_Jee
NORMAL
2023-10-12T16:01:33.651846+00:00
2023-10-12T16:01:33.651868+00:00
66
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor the first `A[i] > 0`,\nwe need to select the array `A[i],A[i+1]..A[i+k-1]`\nand decrease all these elements by `A[i]`.\n\n\n# Approach\nThe subarray deleted starting at `A[i]`,\nwill affect the `A[i+1], A[i+2], ...A[i+k-1]`.\n\nSo we can use cur to record the sum of previous `k - 1` elements,\nwhere `cur = A[i - 1] + A[i - 2] + A[i - k + 1]`.\n\nSo there is a sense of sliding window here,\nwith window size of `k`.\n\nNow to solve this problem,\nwe iterate `A[i]`,\nand compare `A[i]` with cur.\n\nIf `cur > A[i]`,\nit means `A[i]` will be over-decreased to negative,\nreturn false.\n\nFor example,\n`A = [2,1] `and` k = 2` will return false.\n\nIf `cur <= A[i]`,\nA[i] will be decresed cur times,\nso `A[i] -= cur`,\nthen still need to decrese A[i] times,\nso `cur += A[i]`.\n\nWe continue doing this for all `A[i]`,\nand finally we check if `cur == 0`.\nFor example,\n`A = [0,0,1]` and` k = 2` will return 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```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n/*\n for(int i=0; i<nums.length-k && k>0; i++){\n if(nums[i]==0){\n continue;\n } else{\n int min = Math.min(Math.min(nums[i], nums[i+1]), nums[i+2]);\n nums[i]-=min;\n nums[i+1]-=min;\n nums[i+2]-=min;\n k-=min;\n }\n }\n\n for(int num:nums){\n if(num!=0) return false;\n }\n return true;\n*/\n\n int cur = 0;\n for(int i=0; i<nums.length; i++){\n if(cur > nums[i]){\n return false;\n }\n nums[i]-=cur;\n cur += nums[i];\n if(i>=k-1){\n cur -= nums[i-k+1];\n }\n }\n return cur==0;\n }\n}\n```
0
0
['Array', 'Prefix Sum', 'Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Python Line Sweep/Greedy O(n)
python-line-sweepgreedy-on-by-tannerr12-2dng
Greedily remove from the leftmost element which should than make a new leftmost element. for example [2,2,3,1,1,0] k = 3 the only way to get to at postion 0 is
Tannerr12
NORMAL
2023-09-27T23:00:57.252370+00:00
2023-09-27T23:00:57.252389+00:00
4
false
Greedily remove from the leftmost element which should than make a new leftmost element. for example [2,2,3,1,1,0] k = 3 the only way to get to at postion 0 is to subtract 2,2,3 and we can greedily subtract 2 from this whole array making [0,0,1,1,1,0] since we dont want to manually go through and update these elements we keep a range running total in this case -2 and add it back after our k range at position 3. When we reach position 2 we take 3 - 2 = 1 than subtract 1 from our range of 3 elements = [0,0,0,0,0,0]. If we ever go below 0 or run out of space to increase the running total we return False.\n\n```py\nclass Solution:\n def checkArray(self, nums: List[int], k: int) -> bool:\n \n ls = deque([[k,nums[0]]])\n run = -nums[0]\n \n for i in range(len(nums)):\n if ls and ls[0][0] == i:\n run += ls.popleft()[1]\n \n newnum = nums[i] + run\n if newnum < 0 or (newnum > 0 and i + k > len(nums)):\n return False\n else:\n if newnum > 0:\n ls.append([i + k, newnum])\n run -= newnum\n \n return True\n
0
0
['Greedy']
0
apply-operations-to-make-all-array-elements-equal-to-zero
O(n) solution
on-solution-by-user9062q-3s9m
Intuition\n Describe your first thoughts on how to solve this problem. \nFirst, instead of trying to make the array zero. try to build the array from all zeros.
user9062q
NORMAL
2023-09-17T07:36:10.101667+00:00
2023-09-17T07:36:10.101686+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst, instead of trying to make the array zero. try to build the array from all zeros. \n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nbase cases are trivial.\nfor this we are gonna take a index i and every k-length subarray which starts from i is going to be increased by some value. We find this value from the original array and check if it is valid or not.\nExplained in the code with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n if(k==1){\n return true;\n }\n if(n==k){\n for(int i=0;i<n-1;i++){\n if(nums[i]!=nums[i+1]){\n return false;\n }\n }\n return true;\n }\n vector<int> v1(n,0); \n // starting at i to i+k-1. all elements in that\n // k-length window are increased by v1[i];\n // nums[i] = sum(v[j]) for j=i;j>i-k;j--;\n int m1 = n-k+1; // total length of k subarrays possible.\n // for i >= m1 v1[i] =0; this isn\'t possible.\n int m2 = min(m1,k); \n // number of k-subarrays which include the first \n // element. for this we can get the raise by difference \n // between i and i-1th element. \n v1[0] = nums[0];\n for(int i=1;i<m2;i++){\n v1[i] = nums[i] - nums[i-1];\n // cout << i << " " << v1[i] << endl;\n if(v1[i] < 0) return false;\n }\n if(m1>k){\n for(int i=k;i<n-k+1;i++){\n v1[i] = nums[i] - nums[i-1] + v1[i-k]; \n // increase what\'s been subtracted extra.\n // cout << i << " " << v1[i] << endl;\n if(v1[i] < 0) return false;\n }\n }\n int tmp = 0,tmp2;\n for(int i=max(0,n-2*k+2);i<=n-k+1;i++){\n tmp += v1[i];\n }\n // cout << tmp << endl;\n // for the tail elements, which cannot have k-subarray starting from the \n // current element. check whether the sums add up based on from previous \n // increments.\n for(int i=n-k+1;i<n;i++){\n // cout<< i << " - " << tmp << endl;\n if(tmp != nums[i]){\n return false;\n }\n tmp2 = ((i-k+1)<0)?0:v1[i-k+1];\n tmp -= tmp2;\n }\n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
not easy solution
not-easy-solution-by-tharunbandi007-9za3
Intuition\n Describe your first thoughts on how to solve this problem. \nno explanation , not easy solution \n\n# Approach\n Describe your approach to solving t
tharunbandi007
NORMAL
2023-09-15T12:53:25.132370+00:00
2023-09-15T12:53:25.132421+00:00
14
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nno explanation , not easy solution \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nprefix sum \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> v(n+1,0);\n for(int i=0;i<n;i++){\n if(i==0){\n if(nums[i]==0) continue;\n v[i] = -1*nums[i];\n if(i+k<=n){\n v[i+k] = nums[i];\n }\n }else{\n v[i] = v[i]+v[i-1];\n }\n int x = nums[i]+v[i];\n if(x<0) return false;\n else if(x>0){\n v[i] = v[i] + (-1*x);\n if(i+k<=n){\n v[i+k] = v[i+k]+x;\n }\n }\n }\n if(v[n]+v[n-1]<0) return false;\n return true;\n }\n};\n```
0
0
['Greedy', 'Prefix Sum', 'C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Sliding Window | Array | Java | O(N) | Video Tutorial
sliding-window-array-java-on-video-tutor-n1pi
Approach\n Describe your approach to solving the problem. \n Apply Operation from one end (here from start) \n At ith index , choose K size subarray and decreas
21stCenturyLegend
NORMAL
2023-09-01T13:20:06.143482+00:00
2023-09-01T13:20:06.143509+00:00
20
false
# Approach\n<!-- Describe your approach to solving the problem. -->\n* Apply Operation from one end (here from start) \n* At ith index , choose K size subarray and decrease the all elements by ith index value. \n\n# Video Tutorial (For all)\nhttps://youtu.be/uAqmYIwCudY\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n public boolean checkArray(int[] nums, int k) {\n int last = 0;\n int n = nums.length;\n int[] updateValue = new int[n];\n\n for (int i=0; i<n; ++i) {\n int curr = nums[i] + last + updateValue[i];\n if (curr < 0) {\n return false;\n }\n if (i+k < n) {\n updateValue[i+k] += curr;\n } else if (i+k > n && curr > 0) {\n return false;\n }\n last += updateValue[i] - curr;\n }\n\n return true;\n }\n}\n```
0
0
['Java']
0
apply-operations-to-make-all-array-elements-equal-to-zero
simple one iteration solution without sliding window Python 3
simple-one-iteration-solution-without-sl-sdgb
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
throwawayleetcoder19843
NORMAL
2023-08-17T03:36:47.687697+00:00
2023-08-17T03:36:47.687716+00:00
24
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:\n def checkArray(self, nums: List[int], k: int) -> bool:\n for i in range(0, len(nums)-k):\n nums[i+k] += nums[i]\n for i in range(0, len(nums)-1):\n if nums[i]>nums[i+1]:\n return False\n if i>= len(nums)-k and nums[i] != nums[i+1]:\n return False\n return True\n \n\n```
0
0
['Python3']
1
apply-operations-to-make-all-array-elements-equal-to-zero
simple one iteration solution without sliding window Python 3
simple-one-iteration-solution-without-sl-g4gi
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
throwawayleetcoder19843
NORMAL
2023-08-17T03:36:46.965109+00:00
2023-08-17T03:36:46.965126+00:00
23
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:\n def checkArray(self, nums: List[int], k: int) -> bool:\n for i in range(0, len(nums)-k):\n nums[i+k] += nums[i]\n for i in range(0, len(nums)-1):\n if nums[i]>nums[i+1]:\n return False\n if i>= len(nums)-k and nums[i] != nums[i+1]:\n return False\n return True\n \n\n```
0
0
['Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
[C++] O(n) space, O(k) time. Beats 99.93%
c-on-space-ok-time-beats-9993-by-luizcor-d5fc
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
LuizCordeiro
NORMAL
2023-07-31T19:18:46.170902+00:00
2023-07-31T19:18:46.170926+00:00
16
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 bool checkArray(vector<int>& nums, int k) {\n if (k==1) return true;\n\n auto n = nums.size();\n vector<int> removed(k); // Stores the amount which was already removed\n \n int l = 0;\n removed[0] = -nums[0];\n for (auto l=1 ; l<n ; l++) {\n removed[l%k] += nums[l-1];\n if (nums[l]<removed[l%k]) {\n return false;\n }\n removed[l%k] -= nums[l];\n }\n removed[n%k] += nums[n-1];\n\n for (auto i=0 ; i<k ; i++) {\n if (removed[i]!=0) return false;\n }\n\n return true;\n }\n};\n```\n\n# Results\n\n![image.png](https://assets.leetcode.com/users/images/899ecaf7-e47e-4377-b93b-aec497dc79d2_1690831100.9140112.png)\n
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
JavaScript brute force spaghetti O(kn) time
javascript-brute-force-spaghetti-okn-tim-5fm2
\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nvar checkArray = function(nums, k) {\n const len = nums.length;\n if (len =
el_rookie
NORMAL
2023-07-29T23:59:57.603600+00:00
2023-07-29T23:59:57.603619+00:00
24
false
```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {boolean}\n */\nvar checkArray = function(nums, k) {\n const len = nums.length;\n if (len === 1) return true;\n let max = -Infinity;\n for (let i = 0; i < len; i++) {\n if (i <= len - k) {\n if (nums[i] === 0) continue;\n const currentMin = min(nums, i, i + k);\n if (currentMin) {\n for (let j = i; j < i+k; j++) {\n nums[j] -= currentMin;\n }\n }\n }\n max = Math.max(max, nums[i]);\n }\n return max === 0;\n};\n\nfunction min(arr, start, end) {\n if (arr[end - 1] === undefined) return 0;\n let result = Infinity;\n for (let i = start; i < end; i++) {\n if (arr[i] < result) result = arr[i];\n }\n return result;\n}\n```
0
0
['JavaScript']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Simple C++ Solution
simple-c-solution-by-asrawat2001-gse9
Code\n\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int curr=0;\n if(k==1){\n return true;\n }\n
asrawat2001
NORMAL
2023-07-29T07:05:18.545958+00:00
2023-07-29T07:05:18.545977+00:00
11
false
# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int curr=0;\n if(k==1){\n return true;\n }\n int n=nums.size();\n for(int i=0;i<k;i++){\n if(nums[i]<nums[0]){\n return false;\n }\n }\n for(int i=0;i<n;i++){\n \n if(i-k>=0){\n curr-=nums[i-k];\n }\n if(nums[i]<curr){\n return false;\n }\n if(i==(n-1)){\n if(nums[i]!=curr){\n return false;\n }\n }\n nums[i]-=curr;\n curr+=nums[i];\n\n \n }\n \n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
C++ time: O(N) space: O(1) with explanation
c-time-on-space-o1-with-explanation-by-s-v6vu
Intuition\n1) Slide the window from left to right, keeping track of the accumulated decrease value of the k - 1 previous windows (dec).\n2) i is the left side o
skoparov
NORMAL
2023-07-22T09:44:46.572639+00:00
2023-07-22T09:44:46.572661+00:00
21
false
# Intuition\n1) Slide the window from left to right, keeping track of the accumulated decrease value of the k - 1 previous windows (`dec`).\n2) `i` is the *left* side of the window, hense this is the last chance of decrease the current element to 0 (since all other windows containing `nums[i]` have already been processed). The proof would be nums[0], which only partakes in 1 window => we start from it and work our way to the right so:\n* if `nums[i] - dec < 0`, we cannot fulfill the requirement, as any value < dec will leave some of the previous elements positive\n* if `nums[i] - dec > 0` in the RIGHTMOST window, we also return false, as we can no longer accumulate `dec` due to lack of windows to the right, and we `dec` to decrease all elements in the rightmost windows to 0.\n\n# Complexity\n- Time complexity: O(N)\n- Space complexity: O(1)\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) \n {\n int dec{ 0 };\n for (size_t i{ 0 }; i < nums.size(); ++i)\n {\n if (i >= k)\n dec -= nums[i - k];\n\n nums[i] -= dec;\n if (nums[i] < 0)\n return false;\n\n if (i + k <= nums.size())\n dec += nums[i];\n else if (nums[i] != 0)\n return false;\n }\n\n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
EASY Solution
easy-solution-by-mishra__ji20-rm3y
\n\nclass Solution {\npublic:\n bool check(vector<int> &nums,int k)\n {\n if(nums.size()==1 || k==1)\n return 1;\n queue<int>q;\n
mishra__ji20
NORMAL
2023-07-21T19:30:40.295856+00:00
2023-07-21T19:30:40.295879+00:00
13
false
\n```\nclass Solution {\npublic:\n bool check(vector<int> &nums,int k)\n {\n if(nums.size()==1 || k==1)\n return 1;\n queue<int>q;\n int sum=0;\n for(int i=0;i<nums.size();i++)\n {\n if(nums.size()-1==i)\n {\n if(sum!=nums[i])\n return 0;\n \n }\n if(sum>nums[i])\n return 0;\n else\n nums[i]-=sum;\n q.push(nums[i]);\n sum+=nums[i];\n if(q.size()==k)\n {\n sum-=q.front();\n q.pop();\n }\n }\n return 1;\n }\n bool checkArray(vector<int>& nums, int k) {\n int a=check(nums,k);\n return a;\n \n \n \n }\n};\n```
0
0
['Queue']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Best explanation so far
best-explanation-so-far-by-sk_games-xs2q
If you on my level of IQ, you probably find this helpful. All solutions for this problems which people mention (Prefix Sub/Queue, Backtrack tracking) are based
sk_games
NORMAL
2023-07-20T22:22:53.844612+00:00
2023-08-05T06:43:20.374671+00:00
63
false
If you on my level of IQ, you probably find this helpful. All solutions for this problems which people mention (Prefix Sub/Queue, Backtrack tracking) are based on the next idea. \n\n\nStarting at some index and moving to the right: \n- When you see any number(let\'s say N) greater than 0, **the only one way where solution exist is to decrese this number to 0** (by subtracting N). \n- When subtracting by N, you need to ensure that all rightmost element in window can be subtracted by N as well (not leading to negative number)\n\n\n*It\'s natural to think that order, where you start decreseasing the window - matters (Example 3 below). However solution for the problems is based on different intuition.*\n\n```\n[2,2,3,1,1,0] k=3\n\tIndex 0. From this index subtract Number 2 from all numbers from the Index till Index + Window\n\t\tResult: [0,0,1,1,1,0]\n\tIndex 1 (No Changes) \n\t\tResult: [0,0,1,1,1,0]\n\tIndex 2 From this index subtract Number 1 from all numbers from the Index till Index + Window\n\t\tResult [0,0,0,0,0,0]\n\t....\n\n[1,2,3,2,1,0] k=3\n\tIndex 0: From this index subtract Number 1 from all numbers from the Index till Index + Window\n\t\tResult: [0,1,2,2,1,0]\n\tIndex 1: From this index subtract Number 1 from all numbers from the Index till Index + Window\n\t\tResult: [0,0,1,1,1,0]\n\tIndex 2: From this index subtract Number 1 from all numbers from the Index till Index + Window\n\t\tResult [0,0,0,0,0,0]\n\t....\n\n\n[1,1,3,3,3,1]\n\tIndex 0: From this index subtract Number 1 from all numbers from the Index till Index + Window\n\t\tResult: [0,0,2,3,3,1]\n\tIndex 1: (No Changes)\n\tIndex 2: From this index subtract Number 2 from all numbers from the Index till Index + Window\n\t\tResult: [0,0,0,1,1,1]\n\t....\n```\n\n
0
0
['C++', 'Java', 'Python3']
0
apply-operations-to-make-all-array-elements-equal-to-zero
NEW CONCEPT | SLIDING WINDOW + IMPACT PRESERVE | LEARN NEW TODAY❤️‍🔥
new-concept-sliding-window-impact-preser-yhpi
Intuition # Approach\n// used the approach to start from each window of size k and then subtracting each element from the starting element of each window \n// i
MihirKathpal
NORMAL
2023-07-19T06:16:08.618069+00:00
2023-07-19T06:16:08.618088+00:00
21
false
# Intuition # Approach\n// used the approach to start from each window of size k and then subtracting each element from the starting element of each window \n// if any element is negative then return false\n// but this O(n*k-1) times and this create time limit excedded\n// to make it optimal ---> I tried this approach\n\n// very well expalained in detail\n// imagine you are standing in the middle of the array \n// and we are decreasing each elememt of window k with starting element of window ---> starting from left and approaching you [2,2,3,1,1,0] \n// so sum = impact ****** \n// so the impact on the element i am standing is the sum of all k-1 previous elements\n// so to bear that impact \n// element must be greater than that impact first of all----> ( first if condition )\n// if it is greater so element becomes now ---> (nums[i]) - impact(sum) \n// now create your own imapact which is equal to your own value \n// and adding that impact in sum\n// if an case that the impact of previous k element is loosed so decrease that impact from sum \n // sum -=nums[i-k+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# Code\n```\nclass Solution {\npublic:\n bool checkArray(vector<int>& nums, int k) {\n int sum = 0; // impact\n for(int i = 0;i<nums.size();++i)\n {\n if(sum > nums[i])\n return false;\n \n nums[i] -= sum;\n sum += nums[i];\n\n if(i >= k-1)\n sum -= nums[i-k+1];\n }\n return sum == 0;\n \n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Sliding Window Protocol + Prefix Sum || Commented Code
sliding-window-protocol-prefix-sum-comme-xyky
Code\n\nclass Solution {\npublic:\n\n // prefix sum + sliding window\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n\n
om_golhani
NORMAL
2023-07-19T05:50:01.658012+00:00
2023-07-19T05:50:01.658040+00:00
18
false
# Code\n```\nclass Solution {\npublic:\n\n // prefix sum + sliding window\n bool checkArray(vector<int>& nums, int k) {\n int n = nums.size();\n\n // temp = value that is to be decreased from the current element and next k-1 elements to make \n // current element 0.\n int temp = 0;\n for(int i=0 ; i<n ; i++){\n // if temp > nums[i] that means nums[i] will get descreased to negative, hence return fasle.\n if(nums[i] < temp){\n return false;\n }\n // else nums[i] will get decreased by temp.\n nums[i] -= temp;\n // still nums[i]!=0 then add it to temp for future.\n if(nums[i]!=0){\n temp += nums[i];\n }\n // slide the window to next k elements.\n if(i+1>=k){\n temp-=nums[i+1-k];\n }\n }\n // if temp == 0 , that means there is no element left to be decreased to 0\n if(temp!=0){\n return false;\n }\n return true;\n }\n};\n```
0
0
['C++']
0
apply-operations-to-make-all-array-elements-equal-to-zero
Array | prefixsum
array-prefixsum-by-rahulkumarhavitmsi-ziha
\n# Code\n\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int len = nums.length;\n long[] arr = new long[len];\n l
rahulkumarhavitmsi
NORMAL
2023-07-17T17:39:50.529872+00:00
2023-07-17T17:39:50.529892+00:00
40
false
\n# Code\n```\nclass Solution {\n public boolean checkArray(int[] nums, int k) {\n int len = nums.length;\n long[] arr = new long[len];\n long prefixSum = 0;\n for (int j = 0; j < len; j++) {\n prefixSum += arr[j];\n nums[j] += prefixSum;\n if (nums[j] < 0) return false;\n if (nums[j] == 0) continue;\n if ((j + k) > len) return false;\n prefixSum -= nums[j];\n if (j + k < len) arr[j + k] += nums[j];\n }\n return true;\n\n }\n}\n```
0
0
['Java']
0
find-target-indices-after-sorting-array
Java O(N) single-loop count
java-on-single-loop-count-by-singyeh-hby5
One iteration to count less than target, and equal target. Build output based on the first index at lessthan.\n\n\nclass Solution {\n public List<Integer> ta
singyeh
NORMAL
2021-11-28T04:14:24.059568+00:00
2021-11-28T04:14:24.059599+00:00
13,339
false
One iteration to count less than `target`, and equal `target`. Build output based on the first index at `lessthan`.\n\n```\nclass Solution {\n public List<Integer> targetIndices(int[] nums, int target) {\n int count = 0, lessthan = 0;\n for (int n : nums) {\n if (n == target) count++;\n if (n < target) lessthan++;\n }\n \n List<Integer> result = new ArrayList<>();\n for (int i = 0; i < count; i++) {\n result.add(lessthan++);\n }\n return result;\n }\n}\n```
312
1
[]
28
find-target-indices-after-sorting-array
Python O(N) Easy and Fast
python-on-easy-and-fast-by-true-detectiv-tv2y
Just count the number of elements that are less than and equal to target and create a list out of those.\n\n\nclass Solution:\n def targetIndices(self, nums,
true-detective
NORMAL
2021-11-29T20:14:42.915520+00:00
2022-10-29T04:41:41.179571+00:00
5,777
false
Just count the number of elements that are less than and equal to target and create a list out of those.\n\n```\nclass Solution:\n def targetIndices(self, nums, target):\n lt_count = eq_count = 0\n for n in nums:\n if n < target:\n lt_count += 1\n elif n == target:\n eq_count += 1\n \n return list(range(lt_count, lt_count+eq_count))\n```
108
1
[]
14
find-target-indices-after-sorting-array
C++ O(N) Time Counting Sort
c-on-time-counting-sort-by-lzl124631x-0gu2
\n\nSee my latest update in repo LeetCode\n\n## Solution 1. Sorting\n\ncpp\n// OJ: https://leetcode.com/contest/weekly-contest-269/problems/find-target-indices-
lzl124631x
NORMAL
2021-11-28T04:00:45.402909+00:00
2021-11-28T04:00:45.402941+00:00
9,078
false
\n\nSee my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Sorting\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-269/problems/find-target-indices-after-sorting-array/\n// Author: github.com/lzl124631x\n// Time: O(NlogN)\n// Space: O(1) extra space\nclass Solution {\npublic:\n vector<int> targetIndices(vector<int>& A, int target) {\n sort(begin(A), end(A));\n vector<int> ans;\n for (int i = 0; i < A.size(); ++i) {\n if (A[i] == target) ans.push_back(i);\n }\n return ans;\n }\n};\n```\n\n## Solution 2. Counting Sort\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-269/problems/find-target-indices-after-sorting-array/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n vector<int> targetIndices(vector<int>& A, int target) {\n int cnt = 0, rank = 0; // `cnt` is the frequency of `target`, `rank` is the sum of frequencies of all numbers < target\n for (int n : A) {\n cnt += n == target;\n rank += n < target;\n }\n vector<int> ans;\n while (cnt--) ans.push_back(rank++);\n return ans;\n }\n};\n```
97
1
[]
13
find-target-indices-after-sorting-array
✅Concise/Simple | Beats 100% | Explained Both O(n) & O(nlogn)
concisesimple-beats-100-explained-both-o-4070
1st Method [Sorting]:\nCode:\n\npublic List<Integer> targetIndices(int[] nums, int target) { \n Arrays.sort(nums);\n\t ArrayList<Integer> ans =
rohan_21s
NORMAL
2021-11-28T13:23:22.507070+00:00
2022-01-21T19:17:13.828677+00:00
6,745
false
# **1st Method [Sorting]:**\n**Code:**\n```\npublic List<Integer> targetIndices(int[] nums, int target) { \n Arrays.sort(nums);\n\t ArrayList<Integer> ans = new ArrayList<Integer>();\n\t\t \n for(int i=0;i<nums.length;i++){\n if(nums[i] == target) ans.add(i);\n }\n return ans; \n\t\t}\n```\n**Complexity Analysis:**\nTime Complexity: O(nlogn) *[As the array is being sorted]*\nSpace Complexity: O(1) *[No extra space used]*\n\n**Explanation:**\n* The array ```nums``` is sorted using ```Array.sort()``` method.\n* Then while traversing ```nums```, if any element equals the ```target``` its index is added in the ArrayList ```ans```.\n* List ```ans``` is then returned as answer.\n\n# **2nd Method [Without Sorting/Optimal]:**\n**Code:**\n```\n public List<Integer> targetIndices(int[] nums, int target) {\n int belowTCount=0, tCount=0; \n for(int n : nums){\n if(n<target)\n belowTCount++;\n else if(n==target)\n tCount++;\n }\n List<Integer> ans = new ArrayList<>();\n for(int t=0;t<tCount;t++)\n ans.add(belowTCount++);\n \n return ans;\n }\n```\n**Complexity Analysis:**\nTime Complexity: O(n) *[As no sorting is done]*\nSpace Complexity: O(1) *[No extra space used]*\n\n**Explanation:**\n* While traversing ```nums```, these variable are used:\n ``` belowTCount```: To maintain the count of elements having lesser value than ```target```.\n\t ```tCount```: To maintain the count of elements having value equal to ```target```.\n\t \n* \tNow, as you can see in the ```for-loop```, we are adding ```belowtCount```\'s value(increased after every iteration) to our list, as it lets us ignore the indexes which have lesser value than the ```target``` and only add indexes of elements equal to ```target```.\n* \tThis is the same thing we would have done if the array was sorted.\n* \tList ```ans``` is then returned as answer.\n\n**The above process mimics answer given after sorting without actually sorting.**\n\n\nDo Upvote,if it helps you \uD83D\uDE00\nComment your doubts, if any \u270C\n\n
85
3
['Counting Sort', 'Java']
9
find-target-indices-after-sorting-array
4 different Ways | Binary Search | Counting Sort | Time Complexities Explained
4-different-ways-binary-search-counting-zgxwf
Approach 1: This approach is naive as it\'s the one that comes to mind at first. Sort the array. Traverse it and find the valid indexes,such that nums[index] ==
deadline_savvy
NORMAL
2021-12-01T18:28:35.452825+00:00
2021-12-01T18:32:01.918270+00:00
6,437
false
**Approach 1**: This approach is naive as it\'s the one that comes to mind at first. Sort the array. Traverse it and find the valid indexes,such that `nums[index] == target`. \nTime Complexity: `O(Nlog N + N) ~ O(NLogN)`\n```\nclass Solution {\npublic:\n vector<int> targetIndices(vector<int>& nums, int target) {\n sort(nums.begin(),nums.end());\n print(nums);\n vector<int> res;\n int i =0;\n for(auto e: nums){\n if(e == target) res.push_back(i);\n ++i;\n }\n return res;\n }\n};\n```\n**Next two approaches are based on Binary Search technique**\n**Approach 2**: Sort the array. Find the minimum index (say `lb`) such that` nums[lb] == target`. Similarly find maximum index (say `ub`) such that `nums[ub] == target`. At last push indexes between `lb` and `ub` to result vector(automatically its going to be in sorted order).\nTime Complexity : `O(NlogN)` for Sort + finding `lb` and `ub` will take` O(log N)` time each + `O(ub-lb)` for traversal\nthat sums up to `O(NlogN + 2*LogN + N) ~ O(Nlog N)`\n```\nclass Solution {\npublic:\n int LB(vector<int> nums, int x){\n int l = 0;\n int r = nums.size()-1;\n int lb = nums.size();\n while(l <= r){\n int m = l + (r-l)/2;\n if(nums[m] == x){\n lb = m;\n r = m - 1; \n }\n else if(nums[m] < x){\n l = m + 1;\n }\n else r = m - 1;\n }\n return lb;\n }\n int UB(vector<int> nums, int x){\n int l = 0;\n int r = nums.size() - 1;\n int ub = -1;\n while(l <= r){\n int m = l + (r-l)/2;\n if(nums[m] == x){\n ub = m;\n l = m + 1;\n }\n else if(nums[m] > x){\n r = m - 1;\n }\n else l = m + 1;\n }\n return ub;\n }\n vector<int> targetIndices(vector<int>& nums, int target) {\n sort(nums.begin(),nums.end());\n int lb = LB(nums,target);\n int ub = UB(nums,target);\n //cout<<lb<<" "<<ub<<endl;\n vector<int> res;\n for(int i=lb;i<=ub;++i) res.push_back(i);\n return res;\n }\n};\n```\n**Approach 3**: Similar to second one. Sort the array. Binary Search to find an index such that `nums[index] == target`. Traverse from `index-1 to 0` to find out left valid indexes and `index+1 to nums.size()-1` to find right valid indexes. In this context, valid specifies the index, where `nums[index] == target` Push those to the result array. And return sorted result array(`say res.size() comes out to be M(obviously M<=N`)).\nTime Complexity: `O(NlogN + log N + N + MlogM) ~ O(Nlog N)`\n```\nclass Solution {\npublic:\n int bsearch(vector<int> &a, int x){\n int l = 0;\n int r = a.size()-1;\n while(l<=r){\n int m = l + (r-l)/2;\n if(a[m] == x) \n return m;\n else if(a[m] < x)\n l = m + 1;\n else r = m - 1;\n }\n return -1;\n }\n vector<int> targetIndices(vector<int>& nums, int target) {\n sort(nums.begin(),nums.end());\n int index = bsearch(nums,target);\n vector<int> res;\n if(index == -1) return {};\n int i = index-1;\n while(i >= 0){\n if(nums[i] == target) res.push_back(i);\n else break;\n i--;\n }\n res.push_back(index);\n i = index + 1;\n while(i < nums.size()){\n if(nums[i] == target) res.push_back(i);\n else break;\n \n i++;\n }\n sort(res.begin(),res.end());\n return res;\n }\n};\n```\n**Approach 4:**` Counting Sort Approach(Best approach for this problem)`. In this approach we keep a count of numbers that are smallest than our target(`say rank`) and second we keep a count how many times does this target appears in given array(`say cnt`). Now that we have a count for both the things, we can just loop `cnt `varialble. Keep on pushing rank into result array and incrementing rank for next iteration.\nTime Complexity: `O(N)`\n```\nclass Solution {\npublic:\n vector<int> targetIndices(vector<int>& nums, int target) {\n int cnt = 0, rank = 0;\n for(auto e: nums){\n cnt += e == target;\n rank += e < target;\n }\n vector<int> res;\n while(cnt--){\n res.push_back(rank++);\n }\n return res;\n }\n};\n```\n**Hope it make sense!**
71
1
['Sorting', 'Binary Tree', 'Counting Sort']
4
find-target-indices-after-sorting-array
Count Smaller and Equal
count-smaller-and-equal-by-votrubac-9fd8
We do not need to sort the array - we can just count elements smaller than the target.\n\nThe first index of the target (in the sorted array) will be smaller, t
votrubac
NORMAL
2021-11-28T22:29:01.036776+00:00
2021-11-29T01:27:48.462238+00:00
4,966
false
We do not need to sort the array - we can just count elements `smaller` than the target.\n\nThe first index of the target (in the sorted array) will be `smaller`, then `smaller + 1`, and so on - depending on how many times the target appears in the array.\n\n**C++**\n```cpp\nvector<int> targetIndices(vector<int>& nums, int target) {\n int smaller = count_if(begin(nums), end(nums), [&](int n){ return n < target; });\n int equal = count(begin(nums), end(nums), target);\n vector<int> res(equal);\n iota(begin(res), end(res), smaller);\n return res;\n}\n```
58
3
['C']
9