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
minimum-difference-between-highest-and-lowest-of-k-scores
C++ | Sliding Window and Recursive-backtracking solution
c-sliding-window-and-recursive-backtrack-yzoq
Intuition\nI first tried to solve using recursive-backtracking approach, which obviously gave me TLE. But still my code was working for smaller inputs. \nThe be
anandvaibhav
NORMAL
2023-07-29T13:01:32.763759+00:00
2023-07-29T13:01:32.763780+00:00
24
false
# Intuition\nI first tried to solve using recursive-backtracking approach, which obviously gave me TLE. But still my code was working for smaller inputs. \nThe better approach I found was first sorting and updating our ans for given window size.\n\n# Approach\nStart with sorting an array, defining two pointers i and j and res variable which will get updated once we hit window size.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nSliding Window Solution -\n\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n sort(nums.begin(), nums.end());\n int i=0, j=0;\n int res = INT_MAX;\n \n for (;j<nums.size(); j++){\n // Reached window size\n if(j-i+1==k){\n res = min(res, nums[j]-nums[i]);\n i++;\n }\n }\n return res;\n }\n};\n\nRecursive-backtracking solution -\nclass Solution {\npublic:\n int solve(int idx, int n, vector<int>& nums, vector<int>& tm, int k, int low, int high, int res){\n if (k==0){\n res = min(res, high-low);\n return res;\n }\n int curr_low = low, curr_high=high;\n for (int i=idx; i<n; i++){\n // ADDING ELEMENT TO TEMP VECTOR\n tm.push_back(nums[i]);\n // FIND high and low for elements added till now\n low = min(low, nums[i]);\n high = max(high, nums[i]);\n // cout<<low<<" "<<high<<endl;\n // NOW SOLVE FOR REMAINING ELEMENTS\n res = min(res, solve(i+1, n, nums, tm, k-1, low, high, res));\n // cout<<res<<endl;\n // REMOVE ADDED ELEMENT\n tm.pop_back();\n low = curr_low, high=curr_high;\n }\n return res;\n }\n\n int minimumDifference(vector<int>& nums, int k) {\n int n=nums.size();\n vector<int>tm;\n int low=INT_MAX, high=INT_MIN;\n int ans = solve(0, n, nums, tm, k, low, high, INT_MAX);\n return ans;\n }\n};\n```
2
0
['Backtracking', 'Recursion', 'Sliding Window', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
90% Runtime, 85% Memory with Simple Code
90-runtime-85-memory-with-simple-code-by-bshh
\n\n# Approach\nres = nums[k-1] - nums[0]\nSince nums is sorted, nums[k-1] - nums[0] returns max dif.\n\nres = min(res, nums[i] - nums[i - k + 1])\nFrom window
yw1033
NORMAL
2023-06-30T13:16:23.968786+00:00
2023-06-30T13:16:23.968819+00:00
623
false
\n\n# Approach\n`res = nums[k-1] - nums[0]`\nSince nums is sorted, `nums[k-1] - nums[0]` returns max dif.\n\n`res = min(res, nums[i] - nums[i - k + 1])`\nFrom window of size k, the far left is the minimum \nand far right is the maximum value in the window since nums is sorted. \n`nums[i]` : Far right\n`nums[i - k + 1])` : Far left\nSo "far right" - "far left" returns min dif.\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n if len(nums) <= 1:\n return 0\n\n nums.sort()\n res = nums[k-1] - nums[0]\n\n for i in range(k, len(nums)):\n res = min(res, nums[i] - nums[i - k + 1])\n\n return res\n\n \n```
2
0
['Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python 2 line + CPP Soln With Explanation
python-2-line-cpp-soln-with-explanation-860jf
\nThis Q is asking what is the minimum difference between nums[i] and nums[i+(k-1)] for all.\n k-1 beacuse Total K Values = from nums[i] to nums[i+k-1]\n
speedyy
NORMAL
2023-05-23T15:46:09.052054+00:00
2023-05-23T15:55:16.527093+00:00
800
false
```\nThis Q is asking what is the minimum difference between nums[i] and nums[i+(k-1)] for all.\n k-1 beacuse Total K Values = from nums[i] to nums[i+k-1]\n ------- -----------\n 1 value k-1 values\n = 1 + k-1\n = k values\n```\n```\nnums = [7, 1, 9, 3] , k = 2\n\nfor the value nums[1] = 1, ONLY 3 - 1 = 2 WHICH IS THE MINIMUM AMONG 7 - 1 = 6 and 9 - 1 = 8.\nBecause the closest MINIMUM value of 1 is 3. 7 and 9 are far away from 1.\n" So the far they are, the more difference it is. " \n```\n```\nSo sort and compare the minimum for every i by creating a "sliding window" at first\nlike : minDiff = nums[k-1]-nums[0] \nNow move this window till the i for which k exist means for nums[i] there exists a nums[k]\n```\n```Python []\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min( nums[i+k-1]-nums[i] for i in range(len(nums)-k+1) )\n```\n```CPP []\nclass Solution \n{\npublic:\n int minimumDifference(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());\n int minDiff = nums[k-1]-nums[0], n = nums.size()-k+1;\n for(int i=1;i<n;i++)\n minDiff = min(minDiff,nums[i+k-1]-nums[i]);\n return minDiff;\n }\n};\n```\n```\nTime complexity : O(nlogn)\nSpace complexity : O(1)\n```
2
0
['C++', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
🔥 🔥🔥 JavaScript, easy to understand, faster than 94% Sliding Window 🔥 🔥🔥
javascript-easy-to-understand-faster-tha-jfx0
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
azamatval75
NORMAL
2023-04-15T14:18:05.774711+00:00
2023-04-15T19:16:50.396705+00:00
428
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(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(logn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar minimumDifference = function(nums, k) {\n if(nums.length === 1) return 0\n\n let difference = Infinity\n nums.sort((a,b) => a - b)\n\n let start = 0\n let end = k - 1\n while(end < nums.length) {\n difference = Math.min(difference, nums[end] - nums[start])\n start++\n end++\n }\n\n return difference\n};\n```
2
0
['Sliding Window', 'JavaScript']
1
minimum-difference-between-highest-and-lowest-of-k-scores
✅ С | Sorted and compare
s-sorted-and-compare-by-kosant-g36s
Complexity\n- Time complexity: O(N * logN)\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) \
kosant
NORMAL
2023-03-25T07:59:24.366194+00:00
2023-03-25T07:59:24.366231+00:00
2,440
false
# Complexity\n- Time complexity: O(N * logN)\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```\nint min(int a, int b) {\n if (a < b) return a;\n else return b;\n}\n\nint cmp(const void *a, const void *b) {\n return *(int*)a - *(int*)b;\n}\n\nint minimumDifference(int* nums, int numsSize, int k){\n if (k == 1) return 0;\n\n qsort(nums, numsSize, sizeof(int), cmp);\n\n int result = 1000000;\n for (int i = 0; i <= numsSize - k; i++) {\n result = min(nums[i + k - 1] - nums[i], result);\n }\n \n return result;\n}\n```
2
0
['C', 'Sorting', 'C++']
1
minimum-difference-between-highest-and-lowest-of-k-scores
simple cpp solution
simple-cpp-solution-by-prithviraj26-jlpw
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
prithviraj26
NORMAL
2023-02-02T13:41:52.519046+00:00
2023-02-02T13:41:52.519080+00:00
846
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n if(nums.size()==1)return 0;\n int ans=INT_MAX;\n for(int i=0;i<=nums.size()-k;i++)\n {\n ans=min(nums[i+k-1]-nums[i],ans);\n }\n return ans;\n }\n};\n```
2
0
['Array', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Java Easy Solution || 100% working
java-easy-solution-100-working-by-himans-lnmb
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
himanshu_gupta_
NORMAL
2023-01-23T16:23:55.395325+00:00
2023-01-23T16:23:55.395368+00:00
1,262
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 int minimumDifference(int[] nums, int k) {\n if(k==1) return 0;\n Arrays.sort(nums);\n k--;\n int n = nums.length-k;\n int ans = 999999;\n for(int i=0; i<n; i++){\n int temp = nums[k++]-nums[i];\n if (ans>temp) ans = temp;\n }\n return ans;\n }\n}\n```
2
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python Solution
python-solution-by-marcmourning-wa90
Intuition\nThe hardest issue was trying to figure out how to calculate the difference, based on the number of k students, no matter the size of the list. And th
marcmourning
NORMAL
2022-12-30T04:59:51.760110+00:00
2022-12-30T04:59:51.760172+00:00
1,064
false
# Intuition\nThe hardest issue was trying to figure out how to calculate the difference, based on the number of k students, no matter the size of the list. And then check each difference and compare it to the minimum difference, and then return the lowest possible difference. \n\n# Approach\nSimple usage of python built in functions for sorting nums and calculating the min diff, and then return the min diff after comparing it to each possible difference calcultion\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums = sorted(nums)\n return_diff = float(\'inf\')\n for num in range(len(nums)-k + 1):\n current_diff = nums[num+k-1] - nums[num]\n if current_diff < return_diff:\n return_diff = current_diff\n\n return return_diff\n\n\n```
2
0
['Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
C++ || sliding window approach
c-sliding-window-approach-by-als_venky-r7iz
\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n if(k>nums.size()) return 0;\n sort(nums.begin(),nums.end());\
ALS_Venky
NORMAL
2022-09-17T06:13:11.799649+00:00
2022-09-17T06:13:11.799693+00:00
313
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n if(k>nums.size()) return 0;\n sort(nums.begin(),nums.end());\n int mini=nums[k-1]-nums[0];\n for(int i=k;i<nums.size();i++){\n mini=min(nums[i]-nums[i-k+1],mini);\n }\n return mini;\n }\n};\n```
2
0
['C', 'Sorting', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
JAVA easy solution 100% fast
java-easy-solution-100-fast-by-21arka200-eanq
\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n Arrays.sort(nums);\n int min=Integer.MAX_VALUE;\n int i=k;\n
21Arka2002
NORMAL
2022-09-11T06:41:38.477656+00:00
2022-09-11T06:41:38.477742+00:00
1,027
false
```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n Arrays.sort(nums);\n int min=Integer.MAX_VALUE;\n int i=k;\n while(i<=nums.length)\n {\n int h=nums[i-1];\n int l=nums[i-k];\n if(h-l<min)min=h-l;\n i+=1;\n }\n return min;\n }\n}\n```
2
0
['Sliding Window', 'Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python Easy to Understand Beats 92% With Explanation
python-easy-to-understand-beats-92-with-o8pwo
Idea\nWe take a greedy approach to this problem. The greedy property is as follows:\n> There exists an optimal solution where the selected students form a subar
jflow2
NORMAL
2022-08-25T22:35:44.550537+00:00
2022-08-25T22:35:44.550577+00:00
544
false
# Idea\nWe take a greedy approach to this problem. The greedy property is as follows:\n> There exists an optimal solution where the selected students form a subarray of the sorted scores.\n\nTo rephrase, we are claiming that an optimal solution may be selected from the subarrays of the array of sorted scores. To see that this claim is true, consider any arbitrary optimal solution. We may consider this solution as a subset of the sorted scores array. \n\nConsider the subarray of length `k` of the sorted scores array ending at the maximum element of this subset. It has the same maximum as the maximum of the subset, since the sorted scores array is sorted. But, its minimum is at least the minimum of the subset, since it must occur on or after it in the sorted array. Since the original subset was assumed to be optimal, we must conclude that this subarray is also optimal. That is, if an optimal solution exists, then there must exist an optimal solution using a subarray of the sorted scores. Given that an optimal solution must clearly exist, we are done.\n\nThis motivates the following algorithm:\n1. Sort `nums`\n2. Iterate through the `len(nums) - k + 1` subarrays of `nums` of size `k`, and find the one with minimum difference between its maximum and minimum element\n# Code\n```\ndef minimumDifference(nums: List[int], k: int) -> int:\n\tnums.sort()\n\tbest = float(\'inf\')\n\tfor i in range(len(nums) - k + 1):\n\t\tbest = min(best, nums[i+k - 1] - nums[i])\n\treturn best\n```\n Note that we initialize `best` to `float(\'inf\')` to ensure that it will not be selected in the `min` function call.\n # Runtime Analysis\n Let `n = len(nums)`. The sorting step takes `O(n log n)` time, and the iteration takes `O(n - k)` time, for a total runtime of `O(n log n)`. The memory used depends on the sorting methon. Python\'s default sorting method is [Timsort](https://en.wikipedia.org/wiki/Timsort), which uses `O(n)` memory, but with [Heapsort](https://en.wikipedia.org/wiki/Heapsort), this may be done with `O(1)` memory.\n \n This solution ran in 115ms, beating 92.14%, and used 14.1MB of memory, beating 92.51%.
2
0
['Greedy', 'Sliding Window', 'Python']
0
minimum-difference-between-highest-and-lowest-of-k-scores
✔️Java solution | Sliding window | O(n) time complexity | Easy to understand
java-solution-sliding-window-on-time-com-42lb
Here\'s my code with O(n) complexity :\n```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if(nums.length==1){\n retu
Lord_Ambar
NORMAL
2022-06-22T07:21:26.694325+00:00
2022-06-22T07:21:26.694355+00:00
865
false
Here\'s my code with O(n) complexity :\n```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if(nums.length==1){\n return 0; \n }\n Arrays.sort(nums);\n int min = Integer.MAX_VALUE;\n int diff = 0;\n for(int e = k-1;e<nums.length;e++){\n diff = nums[e] - nums[e-(k-1)];\n min = Math.min(min,diff);\n }\n return min;\n }\n}
2
1
['Sliding Window', 'Sorting', 'Java']
3
minimum-difference-between-highest-and-lowest-of-k-scores
C++ Sort ( m=min(m,nums[i+k-1]-nums[i]))
c-sort-mminmnumsik-1-numsi-by-mensenvau-bd1w
\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n int m=INT_MAX;\n
mensenvau
NORMAL
2021-11-01T14:47:52.008963+00:00
2021-11-01T14:47:52.008994+00:00
66
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end());\n int m=INT_MAX;\n for(int i=0;i<=nums.size()-k;i++){\n m=min(m,nums[i+k-1]-nums[i]);\n }\n return m;\n }\n};\n```
2
0
[]
1
minimum-difference-between-highest-and-lowest-of-k-scores
Easy to understand JavaScript solution
easy-to-understand-javascript-solution-b-vau8
\tvar minimumDifference = function(nums, k) {\n\t\tif (k === 1) return 0;\n\n\t\tlet minimum = Infinity;\n\t\tnums.sort((a, b) => b - a);\n\n\t\tfor (let index
tzuyi0817
NORMAL
2021-10-10T05:59:08.232465+00:00
2021-10-10T05:59:08.232499+00:00
269
false
\tvar minimumDifference = function(nums, k) {\n\t\tif (k === 1) return 0;\n\n\t\tlet minimum = Infinity;\n\t\tnums.sort((a, b) => b - a);\n\n\t\tfor (let index = 0; index <= nums.length - k; index++) {\n\t\t\tconst max = nums[index];\n\t\t\tconst min = nums[index + k - 1];\n\n\t\t\tminimum = Math.min(minimum, max - min);\n\t\t}\n\n\t\treturn minimum;\n\t};
2
0
['JavaScript']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python O(nlogn) solution || sort first
python-onlogn-solution-sort-first-by-byu-wgp5
\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n \n n = len(nums)\n nums.sort()\n minv = nums[-1]-
byuns9334
NORMAL
2021-10-10T01:52:21.398592+00:00
2021-10-10T01:52:21.398624+00:00
256
false
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n \n n = len(nums)\n nums.sort()\n minv = nums[-1]-nums[0]\n for i in range(n-k+1):\n minv = min(minv, nums[i+k-1]-nums[i])\n return minv\n```
2
1
['Sorting', 'Python', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Simplest C++ solution. Easy to understand.
simplest-c-solution-easy-to-understand-b-kyq0
\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k)\n {\n int ans = INT_MAX;\n sort(nums.begin(),nums.end());\n
kfaisal-se
NORMAL
2021-09-03T05:24:31.478662+00:00
2021-09-03T05:24:31.478716+00:00
265
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k)\n {\n int ans = INT_MAX;\n sort(nums.begin(),nums.end());\n \n for(int i=0;i<=nums.size()-k;i++)\n {\n ans = min(ans,nums[i+(k-1)] - nums[i]);\n }\n return ans;\n }\n};\n```\n**Like the solution?\nPlease upvote \u30C4**\n\nIf you can\'t understand any step/point, feel free to comment.\nHappy to help
2
1
['C']
1
minimum-difference-between-highest-and-lowest-of-k-scores
Runtime: 92 ms, faster than 100.00% of JavaScript online submissions
runtime-92-ms-faster-than-10000-of-javas-t9m3
\nvar minimumDifference = function(nums, k) {\n if (nums.length===1) return 0;\n \n nums.sort((a,b)=>a-b);\n \n let left = 0;\n let right = k-
masha-nv
NORMAL
2021-08-29T16:57:19.215113+00:00
2021-08-29T16:58:21.717643+00:00
270
false
```\nvar minimumDifference = function(nums, k) {\n if (nums.length===1) return 0;\n \n nums.sort((a,b)=>a-b);\n \n let left = 0;\n let right = k-1;\n \n let min = Infinity;\n \n while (right<nums.length){\n min = Math.min(min, nums[right]-nums[left]);\n right++;\n left++;\n }\n return min;\n};\n```\n![image](https://assets.leetcode.com/users/images/ea3a80e2-83fe-4a9f-9985-ef14bdac8b7e_1630256224.933265.png)\n
2
0
['JavaScript']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python | Sort | 2 Lines
python-sort-2-lines-by-leeteatsleep-in8u
\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min(nums[i+k-1] - nums[i] for i in ran
leeteatsleep
NORMAL
2021-08-29T04:50:37.874525+00:00
2021-08-29T04:50:37.874553+00:00
285
false
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min(nums[i+k-1] - nums[i] for i in range(len(nums) - k + 1))\n```\n\nMore readable 5 liner:\n\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n min_diff = float(\'inf\')\n for i in range(len(nums) - k + 1):\n min_diff = min(min_diff, nums[i+k-1] - nums[i])\n return min_diff\n```
2
1
['Sorting', 'Python', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python 3, two lines - sort and sliding window
python-3-two-lines-sort-and-sliding-wind-waxb
\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min(nums[i+k-1]-nums[i] for i in range(
silvia42
NORMAL
2021-08-29T04:06:21.601224+00:00
2021-08-29T04:06:21.601261+00:00
211
false
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n return min(nums[i+k-1]-nums[i] for i in range(len(nums)-k+1))\n```
2
0
[]
0
minimum-difference-between-highest-and-lowest-of-k-scores
[Java] Sort & Sliding Window || Easy to understand
java-sort-sliding-window-easy-to-underst-ersm
\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if(k == 1)return 0;\n int i = 0,j = k-1,res = Integer.MAX_VALUE;\n\t\t
abhijeetmallick29
NORMAL
2021-08-29T04:00:50.096091+00:00
2021-08-29T04:02:10.897745+00:00
585
false
```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if(k == 1)return 0;\n int i = 0,j = k-1,res = Integer.MAX_VALUE;\n\t\t\n Arrays.sort(nums);\n while(j < nums.length){\n res = Math.min(res,nums[j] - nums[i]);\n j++;\n i++;\n }\n\t\t\n return res;\n }\n}\n```
2
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Simple python solution | sliding window ✅
simple-python-solution-sliding-window-by-07g2
IntuitionTo solve with sliding windowComplexity Time complexity: O(N Log N) Space complexity: O(1) Code
vaishnav_dinesh
NORMAL
2025-03-17T09:26:44.239636+00:00
2025-03-17T09:26:44.239636+00:00
222
false
# Intuition To solve with sliding window # Complexity - Time complexity: O(N Log N) - Space complexity: O(1) # Code ```python3 [] class Solution: def minimumDifference(self, nums: list[int], k: int) -> int: L,R,min_v=0,k-1,float('inf') nums.sort() while R < len(nums): min_v = min(min_v, abs(nums[L] - nums[R])) R += 1 L += 1 return min_v ```
1
0
['Array', 'Sliding Window', 'Sorting', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
[Java] Easy 100% solution
java-easy-100-solution-by-ytchouar-pcvv
null
YTchouar
NORMAL
2025-03-04T04:42:06.267307+00:00
2025-03-04T04:42:06.267307+00:00
377
false
```java [] class Solution { public int minimumDifference(final int[] nums, final int k) { final int n = nums.length; Arrays.sort(nums); int min = Integer.MAX_VALUE; for(int i = 0; i < n - k + 1; ++i) min = Math.min(min, nums[i + k - 1] - nums[i]); return min; } } ```
1
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
🔥 Minimize Score Difference 🎯 | Sorting + Sliding Window 🚀 | But EASIEST Code
minimize-score-difference-sorting-slidin-5v5d
Intuition "Please make an ✨UPVOTE✨, Guys, if you like my approach and explanation... 👍 This will motivate me further in solving problems!"ApproachThe code follo
Sarad_Agarwal__MANG
NORMAL
2025-01-30T18:50:31.834108+00:00
2025-01-30T18:50:31.834108+00:00
376
false
# Intuition "Please make an ✨UPVOTE✨, Guys, if you like my approach and explanation... 👍 This will motivate me further in solving problems!" <!-- Describe your first thoughts on how to solve this problem. --> # Approach The code follows the Sorting + Sliding Window approach. Step-by-Step Explanation: Edge Case Handling: If nums.length < k, return 0 (since it's impossible to pick k elements). If k == nums.length, sort nums and return nums[nums.length - 1] - nums[0] (max - min of the entire array). Sorting: The array is sorted in ascending order to make it easier to pick k consecutive elements with the smallest difference. Sliding Window (Fixed-size Window of k elements): Iterate through the array, picking k consecutive elements. Track the minimum difference between the first and last element of each selected window. Return the Minimum Difference Found. <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(NlogN) -(dominated by sorting) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) -(Sorting is in-place, and only a few extra variables are used) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] import java.util.*; class Solution { public int minimumDifference(int[] nums, int k) { if(nums.length<k) { return 0; }else if(k==nums.length){ Arrays.sort(nums);//ascending order sorting return nums[nums.length-1]-nums[0]; }else{ Arrays.sort(nums);//ascending order sorting int min=Integer.MAX_VALUE; for(int i=0;i<=nums.length-k;i++) { int first=nums[i]; int last=nums[(i+k)-1]; min=Math.min(min,last-first); } return min; } } } ```
1
0
['Array', 'Sliding Window', 'Sorting', 'Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
🔥Minimize the Gap: Smallest Difference Between Scores🔥
minimize-the-gap-smallest-difference-bet-0wv1
IntuitionThe essence of the problem lies in minimizing the difference between the highest and lowest scores in a subset of size ( k ). To achieve this, we need
ghost030705
NORMAL
2024-12-27T05:26:27.860362+00:00
2024-12-27T05:26:27.860362+00:00
263
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> The essence of the problem lies in minimizing the difference between the highest and lowest scores in a subset of size \( k \). To achieve this, we need to evaluate subsets where the scores are closely packed together, as such subsets are more likely to yield smaller differences. When the scores are sorted, subsets of consecutive elements inherently have the smallest range since the elements are arranged in increasing order. This allows us to efficiently find the subset with the minimum difference without the need to evaluate all possible combinations, making the solution both logical and computationally efficient. # Approach <!-- Describe your approach to solving the problem. --> 1. **Sort the Array**: Begin by sorting the array. Sorting ensures that the scores are in ascending order, which allows us to consider subsets of \( k \) consecutive elements to minimize the difference. 2. **Initialize Pointers**: Use two pointers, \( i \) (start of the subset) and \( j \) (end of the subset), to represent a window of size \( k \). Initially, set \( i = 0 \) and \( j = k - 1 \). 3. **Sliding Window to Evaluate Differences**: Slide the window across the sorted array: - Calculate the difference between the element at \( j \) (maximum in the window) and \( i \) (minimum in the window). - Update the minimum difference if the current difference is smaller. 4. **Continue Sliding**: Increment both \( i \) and \( j \) until \( j \) reaches the end of the array. This ensures all subsets of size \( k \) are considered. 5. **Return the Result**: Once the loop is complete, the smallest difference calculated is the answer. # Complexity - Time complexity:**O(NLogN)** <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:**O(1).** <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimumDifference(vector<int>& nums, int k) { sort(nums.begin(),nums.end()); int i=0 , j=k-1; int mini=INT_MAX; while(j<=nums.size()-1) { mini=min(mini,(nums[j]-nums[i])); i++,j++; } return mini; } }; ```
1
0
['C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Java | simple approach
java-simple-approach-by-siyadhri-0ljo
\n\n# Code\njava []\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n Arrays.sort(nums);\n int min=Integer.MAX_VALUE;\n
siyadhri
NORMAL
2024-10-30T04:30:50.131737+00:00
2024-10-30T04:30:50.131763+00:00
269
false
\n\n# Code\n```java []\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n Arrays.sort(nums);\n int min=Integer.MAX_VALUE;\n for(int i=0;i<nums.length-k+1;i++){\n int j=i+k-1;\n int temp=nums[j]-nums[i];\n min=Math.min(min,temp);\n }\n return min;\n }\n}\n```
1
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Good Job Bro,Now Let Me Help You!!
good-job-bronow-let-me-help-you-by-yedug-spa9
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
yeduganisaketh
NORMAL
2024-04-12T02:36:47.371800+00:00
2024-04-12T02:36:47.371828+00:00
178
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 minimumDifference(self, nums: List[int], k: int) -> int:\n final=[]\n nums.sort()\n for i in range(len(nums)-(k-1)):\n help=nums[i:i+k]\n score=max(help)-min(help)\n final.append(score)\n #print(help)\n #print(final)\n return min(final)\n```
1
0
['Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
[Java] Sorting, O(NlogN) , O(1)
java-sorting-onlogn-o1-by-20481a5432-4zdk
# Intuition\nDescribe your first thoughts on how to solve this problem. \n\n# Approach\n\nWe can sort the array and then compare every element at index i with
20481A5432
NORMAL
2024-02-19T09:07:42.022158+00:00
2024-02-19T09:07:42.022213+00:00
478
false
<!-- # Intuition\nDescribe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can sort the array and then compare every element at index i with the element at index **i+k-1**. Take the minimum difference of all such pairs.\n\n# Complexity\n<!-- - Time complexity: -->\nTime Complexity - **O(NlogN)**\nSpace Complexity - **O(1)**\n<!-- - Space complexity: -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n Arrays.sort(nums);\n int res = Integer.MAX_VALUE;\n for(int i=0; i<nums.length; i++){\n if(i+k-1 >= nums.length) break;\n res = Math.min(res, nums[i+k-1] - nums[i]);\n }\n return res;\n }\n}\n```
1
1
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Simple java code 5 ms beats 91 %
simple-java-code-5-ms-beats-91-by-arobh-ks6s
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int minimumDifference(int[] arr, int k) {\n if(k==1){\n return 0;\n }\n
Arobh
NORMAL
2023-12-27T02:53:55.715479+00:00
2023-12-27T02:53:55.715502+00:00
237
false
\n# Complexity\n- \n![image.png](https://assets.leetcode.com/users/images/ca9395c7-3838-4a87-bab4-e042a6e20425_1703645631.4038453.png)\n# Code\n```\nclass Solution {\n public int minimumDifference(int[] arr, int k) {\n if(k==1){\n return 0;\n }\n int n=arr.length;\n Arrays.sort(arr);\n int min=11111111;\n for(int i=0;i<n-k+1;i++){\n min=Math.min(min,arr[i+k-1]-arr[i]);\n }\n return min;\n }\n}\n```
1
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
mysol
mysol-by-samhitha_peddireddy-ydwa
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
samhitha_peddireddy
NORMAL
2023-11-21T01:31:08.329715+00:00
2023-11-21T01:31:08.329740+00:00
71
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 int MinimumDifference(int[] nums, int k) {\n if(nums.Length== 1 || k==1)\n return 0;\n int i=0;\n int j=1;\n int mindiff=1222344550;\n Array.Sort(nums);\n while(j<nums.Length)\n {\n if(j-i+1<k)\n j++;\n else\n {\n if((nums[j]-nums[i])<mindiff)\n {\n mindiff= nums[j]-nums[i];\n }\n i++;\n j++;\n }\n\n }\n\n return mindiff;\n }\n}\n```
1
0
['C#']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Sliding Window solution in C++
sliding-window-solution-in-c-by-wx231-yhib
Complexity\n- Time complexity: O(nlogn)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k)
Wx231
NORMAL
2023-07-24T09:03:56.310747+00:00
2023-07-24T09:03:56.310766+00:00
44
false
# Complexity\n- Time complexity: $$O(nlogn)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n if(nums.size()==1) return 0;\n sort(nums.begin(), nums.end());\n int i=0, j=k-1, result=INT_MAX;\n while(j<nums.size())\n {\n result= min(result, nums[j]-nums[i]);\n i++; j++;\n }\n return result;\n }\n};\n```
1
0
['Array', 'Two Pointers', 'Sliding Window', 'Sorting', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
sliding window
sliding-window-by-dosadarsh-uvf4
Intuition\nusing the concept of the sliding window to solve this problem\n\n# Approach\nin the approach we have take two index pointer head , tail\nhead used to
dosadarsh
NORMAL
2023-07-14T05:44:35.392097+00:00
2023-07-14T05:44:35.392130+00:00
54
false
# Intuition\nusing the concept of the sliding window to solve this problem\n\n# Approach\nin the approach we have take two index pointer head , tail\nhead used to decribe the current window last element and tail decribe the last window element\n\n# Complexity\n- Time complexity:\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n\n int head=0,tail=0,ans=INT_MAX;\n int n=nums.size();\n\n sort(nums.begin(),nums.end());\n\n for(head=0;head<n;head++){\n\n if((head-tail+1)==k){\n\n//with the head-tail+1 we can calculate the size of curr window\n //iska means tail par small wala hoga and head of large wala bcoz array is sorted\n ans = min(ans,nums[head]-nums[tail]);\n tail++;\n\n }\n \n\n\n\n }\n return ans;\n \n }\n};\n```
1
0
['C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
nlogn
nlogn-by-pathaksanjeev38-h1n0
\n\n# Code\n\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort() # we sort the element\n l,r = 0,k-1\
pathaksanjeev38
NORMAL
2023-06-26T06:14:29.105139+00:00
2023-06-26T06:14:29.105175+00:00
18
false
\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort() # we sort the element\n l,r = 0,k-1\n res = float("inf")\n\n while r < len(nums):\n res = min(res,nums[r]-nums[l])\n l,r = l+1,r+1\n return res\n\n# time complexity -- O(Nlogn)\n```
1
0
['Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
one liner, sort + sliding window
one-liner-sort-sliding-window-by-7ffffff-rol0
Code\n\n# @param {Integer[]} nums\n# @param {Integer} k\n# @return {Integer}\ndef minimum_difference(nums, k)\n return nums.sort.each_cons(k).map{|s| s.last-s.
7fffffff
NORMAL
2023-05-29T07:36:41.382985+00:00
2023-05-29T07:37:06.522751+00:00
13
false
# Code\n```\n# @param {Integer[]} nums\n# @param {Integer} k\n# @return {Integer}\ndef minimum_difference(nums, k)\n return nums.sort.each_cons(k).map{|s| s.last-s.first}.min\nend\n\n```
1
0
['Sliding Window', 'Ruby']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Java easy solution 100% faster || beats 100%.
java-easy-solution-100-faster-beats-100-yj5bb
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
tausif_02
NORMAL
2023-05-07T17:46:03.332952+00:00
2023-05-07T17:46:03.333070+00:00
88
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 int minimumDifference(int[] nums, int k) {\n Arrays.sort(nums);\n int diff=nums[k-1]-nums[0];\n int n=nums.length-k+1;\n int s=0;\n for(int i=0;i<n;i++)\n {\n s=nums[i+k-1] - nums[i];\n if(diff>s)diff=s;\n }\n return diff;\n }\n}\n```
1
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
It's my fu**ing code... Beat 100 % .... Wanna learn something New Today ?????
its-my-fuing-code-beat-100-wanna-learn-s-vp1p
Intuition\n:: Sorting and pointers\n\n# Approach\n\ni.e for {1,3,4,6,7,8},and k=3 ;\ncompae difference of :: (1,4),(3,6),(4,7),(6,8).. just this is enough\n// s
Eun_ha
NORMAL
2023-04-07T18:35:19.464487+00:00
2023-04-07T18:35:19.464537+00:00
24
false
# Intuition\n**:: Sorting and pointers**\n\n# Approach\n<first sort and than compare the difference of the boundary elements for the window of k consecutive elements >\ni.e for {1,3,4,6,7,8},and k=3 ;\ncompae difference of :: (1,4),(3,6),(4,7),(6,8).. just this is enough\n// so our ans will min of(ans , diff(right bound - left bound ));;\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& v, int k) {\n std::sort(v.begin(),v.end()); \n // first sort ,, Why ???\n // Ans :: So that all term inside window excluding the boundary\n // all are inside the boundary of window ..\n\n k--; // K-1 will be used many time so i did it --;\n\n int ans=v[k] - v[0]; \n // U can also assign ans with INT MAX but no need ...\n\n int i=v.size()-k;\n while(i--){ // My window is moving from end \n // U can start from first ,.. no big deal .. \n\n ans=min(ans,(v[i+k]-v[i])); // Updatng ans.\n }\n return ans;\n }\n};\n```
1
0
['Sorting', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Minimum Difference Between Highest and Lowest of K Scores
minimum-difference-between-highest-and-l-1qz0
Intuition\n Describe your first thoughts on how to solve this problem. \nusing list append method and two pointer algorithm\n\n# Approach\n Describe your approa
vengateshk18
NORMAL
2023-03-31T08:26:04.773346+00:00
2023-03-31T08:26:04.773381+00:00
179
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing list append method and two pointer algorithm\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\ntwo pointer algorithm\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nn\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n a=[]\n i=0\n j=k-1\n nums=sorted(nums)\n if(len(nums)!=1):\n while(j<=len(nums)-1):\n a.append(nums[j]-nums[i])\n i=i+1\n j=j+1\n else:\n return(0)\n return min(a)\n```
1
0
['Two Pointers', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
C Solution
c-solution-by-ychencs-r0hn
Intuition\n- Sort\n- Compare i and i + k - 1, which is the Difference Between Highest and Lowest of K Scores\n Describe your first thoughts on how to solve this
ychencs
NORMAL
2023-02-21T14:32:17.429697+00:00
2023-02-21T14:32:17.429748+00:00
48
false
# Intuition\n- Sort\n- Compare `i` and `i + k - 1`, which is the Difference Between Highest and Lowest of K Scores\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Quick sort\n2. For loop:\nCompare `i` and `i + k - 1`, choose the minimum one\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)`, does recursion stack space count? `O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nvoid swap(int *a, int *b)\n{\n int t = *a;\n *a = *b;\n *b = t;\n}\n\nint partition(int *a, int x, int y)\n{\n int i = x - 1, pk = a[y];\n for (int j = x; j < y; j++)\n {\n if (a[j] <= a[y])\n {\n i++;\n swap(&a[i], &a[j]);\n }\n }\n swap(&a[i + 1], &a[y]);\n return i + 1;\n}\n\nvoid quickSort(int *a, int x, int y)\n{\n if (x < y)\n {\n int q = partition(a, x, y);\n quickSort(a, x, q - 1);\n quickSort(a, q + 1, y);\n }\n}\n\nint minimumDifference(int* nums, int numsSize, int k){\n if(numsSize == 1)\n return 0;\n quickSort(nums, 0, numsSize - 1);\n int returnValue = nums[k - 1] - nums[0];\n for (size_t i = 1; i < numsSize - k + 1; i++)\n {\n if(returnValue > nums[i + k - 1] - nums[i])\n returnValue = nums[i + k - 1] - nums[i];\n }\n return returnValue;\n}\n```
1
0
['C']
1
minimum-difference-between-highest-and-lowest-of-k-scores
Easy Sliding Window C++
easy-sliding-window-c-by-divyansh_mishra-ezzv
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
Divyansh_Mishra10
NORMAL
2023-02-12T15:19:58.869005+00:00
2023-02-12T15:19:58.869031+00:00
827
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.log(n))\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n int n=nums.size();\n sort(nums.begin(), nums.end());\n\n int left=0, right=k-1;\n int diff=INT_MAX;\n int ans=INT_MAX;\n while(right<n){\n diff=nums[right]-nums[left];\n ans=min(ans, diff);\n left++;\n right++;\n }\n\n return ans;\n }\n};\n```
1
0
['Sliding Window', 'Python', 'C++', 'Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
[Accepted] Swift
accepted-swift-by-vasilisiniak-zt5o
\nclass Solution {\n func minimumDifference(_ nums: [Int], _ k: Int) -> Int {\n \n let nu = nums.sorted()\n var mi = Int.max\n \n
vasilisiniak
NORMAL
2023-01-13T09:03:26.806991+00:00
2023-01-13T09:03:26.807025+00:00
61
false
```\nclass Solution {\n func minimumDifference(_ nums: [Int], _ k: Int) -> Int {\n \n let nu = nums.sorted()\n var mi = Int.max\n \n for i in 0...(nu.count - k) {\n mi = min(mi, nu[i + k - 1] - nu[i])\n }\n \n return mi\n }\n}\n```
1
0
['Swift']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Sorting followed by Sliding Window Approach
sorting-followed-by-sliding-window-appro-qeyl
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
dev_007_fun
NORMAL
2022-12-29T07:36:05.933746+00:00
2022-12-29T07:36:05.933775+00:00
21
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 int minimumDifference(int[] nums, int k) {\n if(nums.length <= 1) return 0;\n \n Arrays.sort(nums);\n int minDifference = Integer.MAX_VALUE;\n int left = 0;\n for(int right = 0; right < nums.length; right++) {\n\n if(right < k - 1) continue;\n\n minDifference= Math.min(minDifference, nums[right] - nums[left]);\n left++;\n }\n return minDifference;\n }\n}\n```
1
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python 99.70% time solution (beginner friendly)
python-9970-time-solution-beginner-frien-5nh4
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nSort the input array first so it is easier to work with, then implement sliding w
Bread0307
NORMAL
2022-12-27T06:09:47.866882+00:00
2022-12-27T06:09:47.866927+00:00
581
false
![Screenshot 2022-12-26 at 10.06.37 PM.png](https://assets.leetcode.com/users/images/d2266660-7868-44d6-9070-0820cc451cbe_1672121376.6683125.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSort the input array first so it is easier to work with, then implement sliding window approach\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSort the input array so we can know what the lowest and highest number in the sliding window is easily; then use a loop to go through the array with a sliding window of length k, then the result will be the minimum of what it is currently and nums[right] - nums[left]\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(NlogN)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N) from sorting\n# Code\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n result = float(\'inf\')\n left = 0\n for right in range(k - 1, len(nums)):\n result = min(result, nums[right] - nums[left])\n left += 1\n return result\n```
1
0
['Sliding Window', 'Sorting', 'Python3']
1
minimum-difference-between-highest-and-lowest-of-k-scores
Python 3 || C++ || O(nlogn) || Easy Solution
python-3-c-onlogn-easy-solution-by-sagar-k8me
Python 3:\n\tclass Solution:\n\t\tdef minimumDifference(self, nums: List[int], k: int) -> int:\n\t\t\tnums.sort()\n\t\t\tl, r = 0, k-1\n\t\t\tres = float("inf")
sagarhasan273
NORMAL
2022-11-11T15:23:45.324145+00:00
2022-11-11T15:23:45.324186+00:00
77
false
## Python 3:\n\tclass Solution:\n\t\tdef minimumDifference(self, nums: List[int], k: int) -> int:\n\t\t\tnums.sort()\n\t\t\tl, r = 0, k-1\n\t\t\tres = float("inf")\n\n\t\t\twhile r < len(nums):\n\t\t\t\tres = min(res, nums[r] - nums[l])\n\t\t\t\tl, r = l+1, r+1\n\n\t\t\treturn res\n\n## C++:\n\n\tclass Solution {\n\tpublic:\n\t\tint minimumDifference(vector<int>& nums, int k) {\n\t\t\tsort(nums.begin(), nums.end());\n\n\t\t\tint l = 0, r = k-1, res=INT_MAX;\n\n\t\t\twhile (r < nums.size()){\n\t\t\t\tres = min(res, nums[r] - nums[l]);\n\t\t\t\tl++; r++;\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t};
1
0
['C', 'Python']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Best Easy approach || 96.84% Beat || Python
best-easy-approach-9684-beat-python-by-k-3aj4
Intuition\nSorting\n\n# Approach\nSliding Window\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(K)\n\n# Code\n\nimport math\nclass Solu
k_shark_ocean
NORMAL
2022-11-08T06:37:53.526430+00:00
2022-11-08T06:37:53.526476+00:00
155
false
# Intuition\nSorting\n\n# Approach\nSliding Window\n\n# Complexity\n- Time complexity:\nO(NlogN)\n\n- Space complexity:\nO(K)\n\n# Code\n```\nimport math\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n lst=[]\n res=math.inf\n nums.sort()\n for i in range(len(nums)-k+1):\n lst=nums[i:i+k]\n res=min(res,lst[-1]-lst[0])\n return res\n```
1
0
['Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
🎊 Python | O(n log(n) ) | Sort and traverse 🎊
python-on-logn-sort-and-traverse-by-neos-ximh
Solution \nPlease upvote if you liked it :)\n1. Here, we sort the array first : O(nlogn)\n2. Then we just look compare difference between: [i-(k-1)] and [i] :
neosh11
NORMAL
2022-10-09T04:28:56.663048+00:00
2022-10-09T04:28:56.663085+00:00
14
false
# Solution \n**Please upvote if you liked it :)**\n1. Here, we sort the array first : O(nlogn)\n2. Then we just look compare difference between: [i-(k-1)] and [i] : O(n)\n\nTotal complexity is O( n log(n) ) \n\n```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n \n if k == 1:\n return 0\n \n nums.sort(reverse=True)\n minDiff = inf\n \n for i in range(k-1, len(nums)):\n d = nums[i-(k-1)] - nums[i]\n if d < minDiff:\n minDiff = d\n \n return minDiff\n \n```
1
0
[]
0
minimum-difference-between-highest-and-lowest-of-k-scores
java 4ms
java-4ms-by-anujrohitkumar3010-qcmh
Here is my code \n\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n int n=nums.length;\n if(k>n ) return -1;\n Ar
anujrohitkumar3010
NORMAL
2022-09-08T20:37:38.336237+00:00
2022-09-08T20:39:06.688102+00:00
219
false
Here is my code \n```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n int n=nums.length;\n if(k>n ) return -1;\n Arrays.sort(nums);\n int min =nums[k-1]-nums[0];\n for(int i=1;i+k-1<n;i++)\n min=Math.min(min,nums[i+k-1]-nums[i]);\n \n return min;\n \n }\n}\n```
1
0
['Java']
1
minimum-difference-between-highest-and-lowest-of-k-scores
✅✅Faster || Easy To Understand || C++ Code
faster-easy-to-understand-c-code-by-__kr-38ww
Approach 1 :- Using Sorting\n\n Time Complexity :- O(NlogN)\n\n Space Complexity :- O(1)\n\n\nclass Solution {\npublic:\n \n int minimumDifference(vector<
__KR_SHANU_IITG
NORMAL
2022-09-02T11:01:45.849207+00:00
2022-09-02T11:01:45.849257+00:00
674
false
* ***Approach 1 :- Using Sorting***\n\n* ***Time Complexity :- O(NlogN)***\n\n* ***Space Complexity :- O(1)***\n\n```\nclass Solution {\npublic:\n \n int minimumDifference(vector<int>& nums, int k) {\n \n // sort the array\n \n sort(nums.begin(), nums.end());\n \n int mini = INT_MAX;\n \n // take the k elements in a group\n \n for(int i = 0; i < nums.size(); i++)\n {\n if(i + k - 1 < nums.size())\n {\n int diff = nums[i + k - 1] - nums[i];\n \n mini = min(mini, diff);\n }\n else\n {\n break;\n }\n }\n \n return mini;\n }\n};\n```
1
0
['C', 'Sorting', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
C++ | Easy | Simple
c-easy-simple-by-akshat0610-rvtj
\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end(),greater<int>()); //sort\n \n
akshat0610
NORMAL
2022-08-31T11:34:22.967486+00:00
2022-08-31T11:34:22.967534+00:00
715
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end(),greater<int>()); //sort\n \n int ans=INT_MAX;\n\n for(int i=0;i<nums.size();i++)\n {\n if(i<k)\n {\n if(i==(k-1)) //first actula size of the window\n {\n ans=min(ans,nums[0]-nums[i]);\t\n }\n }\n else\n {\n ans=min(ans,nums[i-k+1]-nums[i]);\n }\n }\n return ans; \n }\n};\n```
1
0
['C', 'Sliding Window', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
short | easy python code
short-easy-python-code-by-ayushigupta240-pcca
\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n n=len(nums)\n if n==1 or k==1:\n return 0\n nums=sorted(nums)\n
ayushigupta2409
NORMAL
2022-08-29T12:51:29.178172+00:00
2022-08-29T12:51:29.178211+00:00
114
false
```\ndef minimumDifference(self, nums: List[int], k: int) -> int:\n n=len(nums)\n if n==1 or k==1:\n return 0\n nums=sorted(nums)\n least=nums[k-1]-nums[0]\n for j in range(1,n-k+1):\n least=min(least,nums[j+k-1]-nums[j])\n return least\n```
1
0
['Python', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python | Sliding Window | O(nlogn)
python-sliding-window-onlogn-by-aryonbe-8zg6
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n cur = float(\'inf\')\n for i in rang
aryonbe
NORMAL
2022-07-27T12:36:05.551538+00:00
2022-07-27T12:36:05.551571+00:00
277
false
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n cur = float(\'inf\')\n for i in range(len(nums)-k+1):\n cur = min(cur, nums[i+k-1]-nums[i])\n
1
0
['Python']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Faster than 89.9% java submission easy understandable java code
faster-than-899-java-submission-easy-und-0fz9
class Solution {\n public int minimumDifference(int[] nums, int k) {\n if(k==0)\n return 0;\n Arrays.sort(nums);\n int n = nums.leng
chirag_0401
NORMAL
2022-07-07T04:13:20.736981+00:00
2022-07-07T04:13:20.737033+00:00
230
false
class Solution {\n public int minimumDifference(int[] nums, int k) {\n if(k==0)\n return 0;\n Arrays.sort(nums);\n int n = nums.length,i=0,mn=Integer.MAX_VALUE;\n \n for(i=0;i<=n-k;i++)\n {\n mn = Math.min(mn,nums[i+k-1]-nums[i]);\n \n }\n \n return mn;\n }\n}\n/////**** If You like the solution please hit up the like button ****////\nfeel free to ask any question or send any another approach
1
0
['Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Simple sliding window || easy to understand || c++
simple-sliding-window-easy-to-understand-olbj
\n int minimumDifference(vector& nums, int k) {\n sort(nums.begin(),nums.end()) ;\n int i=0,j=0;\n int mini=INT_MAX;\n while(j<nums
Akshay1054
NORMAL
2022-05-23T15:01:31.982119+00:00
2022-05-23T15:01:31.982160+00:00
91
false
\n int minimumDifference(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end()) ;\n int i=0,j=0;\n int mini=INT_MAX;\n while(j<nums.size()){\n if(j-i+1<k) j++;\n else if(j-i+1==k){\n int val=nums[j]-nums[i];\n if(val<mini) mini=val;\n i++;\n j++;\n }\n }\n return mini;\n }\n};
1
0
['C', 'Sliding Window']
0
minimum-difference-between-highest-and-lowest-of-k-scores
C++|Sort and Sliding Window|O(nlogn) Time Complexity
csort-and-sliding-windowonlogn-time-comp-in68
\nint minimumDifference(vector<int>& nums, int k) {\n if(k == 1)\n return 0;\n sort(nums.begin(),nums.end());\n int max1 = nums[
aniket212
NORMAL
2022-05-09T12:06:55.844250+00:00
2022-05-14T04:37:31.221389+00:00
136
false
```\nint minimumDifference(vector<int>& nums, int k) {\n if(k == 1)\n return 0;\n sort(nums.begin(),nums.end());\n int max1 = nums[k - 1] , min1 = nums[0];\n int ans = max1 - min1;\n for(int i = k ; i < nums.size() ; i++){\n max1 = nums[i];\n min1 = nums[i - k + 1];\n int diff = max1 - min1;\n if(ans > diff)\n ans = diff;\n }\n return ans;\n }\n```
1
0
['Array', 'Sliding Window']
1
minimum-difference-between-highest-and-lowest-of-k-scores
C++ | O(nlogn) time O(1) space | 14ms faster than 90% | 13.6MB less than 96%
c-onlogn-time-o1-space-14ms-faster-than-u4h51
Runtime: 14 ms, faster than 90.53% of C++ online submissions for Minimum Difference Between Highest and Lowest of K Scores.\nMemory Usage: 13.6 MB, less than 96
nguyenchiemminhvu
NORMAL
2022-04-27T16:21:49.380174+00:00
2022-04-27T16:22:12.030134+00:00
45
false
Runtime: 14 ms, faster than 90.53% of C++ online submissions for Minimum Difference Between Highest and Lowest of K Scores.\nMemory Usage: 13.6 MB, less than 96.30% of C++ online submissions for Minimum Difference Between Highest and Lowest of K Scores.\n\n```\nclass Solution \n{\npublic:\n int minimumDifference(vector<int>& nums, int k) \n {\n std::sort(nums.begin(), nums.end());\n \n int mi = INT_MAX;\n for (int i = 0; i <= nums.size() - k; i++)\n {\n mi = std::min(mi, nums[i + k - 1] - nums[i]);\n }\n return mi;\n }\n};\n```
1
0
[]
0
minimum-difference-between-highest-and-lowest-of-k-scores
☕ Java - 8ms - Sliding Wndow - Explanation - O(NLogN)
java-8ms-sliding-wndow-explanation-onlog-l8ok
The trick to solving this problem is realizing that we don\'t actually need to find the difference of every number within a subset of numbers of size k. Given a
rar349
NORMAL
2022-04-24T19:01:49.507630+00:00
2022-04-24T19:02:58.814356+00:00
273
false
The trick to solving this problem is realizing that we don\'t actually need to find the difference of every number within a subset of numbers of size k. Given a subset of size k, we only need to find the difference of the highest and lowest number.\n\nWith the above logic, it makes the most sense to start by **sorting the array.** This is because when the array is sorted, we do not have to find the largest and smallest elements in a given subarray. The largest and smallest elements will always be the last and first element in the subarray respectively.\n\nThen, we simply need to iterate over the sorted input and subtract the element at position **i (highest element in subsequence)** from the element at **position (i - k + 1)** which is the **lowest element** in the subsequence. We need to add the one because we want to include that element K positions back. As long as we continuously do this for every element in the array, we can be sure to find the minimum difference.\n\n**Runtime Complexity - O(NlogN)**\n**Memory Complexity - O(1)**\nwhere N is the size of the input array.\n```\n public int minimumDifference(int[] nums, int k) {\n if(k == 1) return 0;\n \n Arrays.sort(nums);\n \n int zeroIndexedK = k - 1;\n \n int toReturn = Integer.MAX_VALUE;\n for(int i = zeroIndexedK; i < nums.length; i++) {\n int highest = nums[i];\n int lowest = nums[i - zeroIndexedK];\n \n int difference = highest - lowest;\n toReturn = Math.min(toReturn, difference);\n }\n \n return toReturn;\n }\n```
1
0
['Sliding Window', 'Sorting', 'Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python Easiest Solution | 96.98 % Faster | Sliding Window | Beg To adv
python-easiest-solution-9698-faster-slid-b4j8
python\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n l, r = 0, k-1\n \n min_dif
rlakshay14
NORMAL
2022-04-15T20:41:51.631140+00:00
2022-04-15T20:41:51.631180+00:00
385
false
```python\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n l, r = 0, k-1\n \n min_diff = float(\'inf\') # max out possible value\n \n while r < len(nums):\n min_diff = min(min_diff, nums[r] - nums[l])\n l, r = l+1, r+1\n \n return min_diff \n```\nTo read more about "float("inf")". \nhttps://stackoverflow.com/questions/34264710/what-is-the-point-of-floatinf-in-python\n\n***Found helpful, Do upvote !!***
1
0
['Sliding Window', 'Python', 'Python3']
0
minimum-difference-between-highest-and-lowest-of-k-scores
c++ sliding window
c-sliding-window-by-me_abhi_2511-mf82
class Solution {\npublic:\n\n int minimumDifference(vector& nums, int k) {\n sort(nums.begin(),nums.end());\n int mx=INT_MAX;\n int i=0,
me_abhi_2511
NORMAL
2022-04-11T16:14:04.771799+00:00
2022-04-11T16:14:04.771830+00:00
130
false
class Solution {\npublic:\n\n int minimumDifference(vector<int>& nums, int k) {\n sort(nums.begin(),nums.end());\n int mx=INT_MAX;\n int i=0,j=0;\n while(j<nums.size())\n {\n if(j-i+1<k)\n j++;\n if(j-i+1==k)\n {\n mx=min(mx,nums[j]-nums[i]);\n i++;\n j++;\n }\n }\n return mx;\n \n \n }\n};
1
0
['C', 'Sliding Window']
0
minimum-difference-between-highest-and-lowest-of-k-scores
python easy fast solution
python-easy-fast-solution-by-akash795515-qi5g
class Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n i=0\n j=k-1\n l=[]\n while
akash795515
NORMAL
2022-04-11T06:13:07.321285+00:00
2022-04-11T06:13:07.321317+00:00
59
false
class Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n nums.sort()\n i=0\n j=k-1\n l=[]\n while j<len(nums):\n b=nums[j]-nums[i]\n l.append(b)\n i+=1\n j=k-1+i\n return min(l)\n \n
1
0
['Sliding Window']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Java
java-by-irock8929-pdpo
\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if (k <= 1)\n return 0;\n \n Arrays.sort(nums);\n
irock8929
NORMAL
2022-04-06T23:10:26.147157+00:00
2022-04-06T23:10:26.147190+00:00
43
false
```\nclass Solution {\n public int minimumDifference(int[] nums, int k) {\n if (k <= 1)\n return 0;\n \n Arrays.sort(nums);\n int ans = Integer.MAX_VALUE;\n \n for (int i = 0; i < nums.length - k + 1; i++)\n ans = min(ans, nums[i + k - 1] - nums[i]);\n return ans;\n }\n \n private int min(int n1, int n2) {\n return n1 < n2 ? n1 : n2;\n }\n}\n```
1
0
[]
0
minimum-difference-between-highest-and-lowest-of-k-scores
Easy solution || O(N) || Beats 50% of submissions
easy-solution-on-beats-50-of-submissions-3ck1
```\nclass Solution {\npublic:\n int minimumDifference(vector& nums, int k) {\n if(k==1)\n return 0;\n sort(nums.begin(),nums.end())
Shristha
NORMAL
2022-03-30T14:21:28.030916+00:00
2022-03-30T14:21:28.030953+00:00
193
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n if(k==1)\n return 0;\n sort(nums.begin(),nums.end());\n int res;\n res=(nums[k-1]-nums[0]);\n for(int i=k;i<nums.size();i++){\n res=min(res,(nums[i]-nums[i-(k-1)]));\n }\n return res;\n }\n};
1
0
['C', 'C++']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Java | 0ms | Efficient Solution | Using Sliding Window
java-0ms-efficient-solution-using-slidin-ksqp
class Solution {\n public int minimumDifference(int[] nums, int k) {\n \n \n //Sliding Window\n \n if(nums.length == 1)\n
ishashank
NORMAL
2022-03-22T14:38:14.236240+00:00
2022-03-22T14:38:14.236292+00:00
141
false
class Solution {\n public int minimumDifference(int[] nums, int k) {\n \n \n //Sliding Window\n \n if(nums.length == 1)\n return 0;\n \n Arrays.sort(nums);\n \n int diff = Integer.MAX_VALUE;\n \n for(int i = k - 1; i < nums.length; ++i){\n \n diff = Math.min(diff, nums[i] - nums[i - k + 1]);\n \n }\n \n \n return diff;\n \n }\n}
1
0
['Sliding Window', 'Java']
0
minimum-difference-between-highest-and-lowest-of-k-scores
Python3
python3-by-excellentprogrammer-kftb
\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n a=float(\'inf\')\n s=[]\n b=sorted(nums)\n for
ExcellentProgrammer
NORMAL
2022-03-20T10:12:44.360375+00:00
2022-03-20T10:12:44.360415+00:00
45
false
```\nclass Solution:\n def minimumDifference(self, nums: List[int], k: int) -> int:\n a=float(\'inf\')\n s=[]\n b=sorted(nums)\n for i in range(k-1,len(b)):\n if b[i]-b[i-k+1]<a:\n s.append(b[i]-b[i-k+1])\n return min(s)\n```
1
0
[]
0
minimum-difference-between-highest-and-lowest-of-k-scores
C++ | Simple solution
c-simple-solution-by-riteshkhan-vdhp
\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n int l = nums.size();\n if(l==1) return 0;\n sort(nums.
RiteshKhan
NORMAL
2022-03-15T05:57:35.096170+00:00
2022-03-15T05:57:35.096220+00:00
99
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n int l = nums.size();\n if(l==1) return 0;\n sort(nums.begin(), nums.end());\n int i=0, m = INT_MAX,p;\n while((i<l)&&(i+k-1 <l)){\n p = nums[i+k-1]-nums[i];\n m = min(m,p);\n i++;\n }\n return m;\n }\n};\n```
1
0
['C']
0
minimum-difference-between-highest-and-lowest-of-k-scores
C++ beginner friendly
c-beginner-friendly-by-richach10-aez1
\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end(), greater<int>());\n \n
Richach10
NORMAL
2022-03-08T17:47:25.939415+00:00
2022-03-08T17:47:25.939450+00:00
151
false
```\nclass Solution {\npublic:\n int minimumDifference(vector<int>& nums, int k) {\n \n sort(nums.begin(),nums.end(), greater<int>());\n \n int i=0,j=k-1;\n int mini=INT_MAX;\n int res=0;\n while(j<nums.size())\n {\n mini=min(mini,nums[i]-nums[j]);\n \n j++;\n i++;\n }\n return mini;\n }\n};\n```
1
0
['C', 'C++']
0
set-matrix-zeroes
Any shorter O(1) space solution?
any-shorter-o1-space-solution-by-mzchen-45mk
My idea is simple: store states of each row in the first of that row, and store states of each column in the first of that column. Because the state of row0 and
mzchen
NORMAL
2014-11-13T06:03:08+00:00
2024-02-14T07:40:17.985101+00:00
200,983
false
My idea is simple: store states of each row in the first of that row, and store states of each column in the first of that column. Because the state of row0 and the state of column0 would occupy the same cell, I let it be the state of row0, and use another variable `col0` for column0. In the first phase, use matrix elements to set states in a top-down way. In the second phase, use states to set matrix elements in a bottom-up way.\n\n```cpp []\nvoid setZeroes(vector<vector<int>>& matrix) {\n int col0 = 1, rows = matrix.size(), cols = matrix[0].size();\n\n for (int i = 0; i < rows; i++) {\n if (matrix[i][0] == 0) col0 = 0;\n for (int j = 1; j < cols; j++)\n if (matrix[i][j] == 0)\n matrix[i][0] = matrix[0][j] = 0;\n }\n\n for (int i = rows - 1; i >= 0; i--) {\n for (int j = cols - 1; j >= 1; j--)\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n if (col0 == 0) matrix[i][0] = 0;\n }\n}\n```
1,936
17
['C++']
133
set-matrix-zeroes
✅☑️ Best C++ 4 solution || Hash Table || Matrix || Brute Force -> Optimize || One Stop Solution.
best-c-4-solution-hash-table-matrix-brut-xwgo
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can solve this problem using Four approaches. (Here I have explained all the possibl
its_vishal_7575
NORMAL
2023-02-11T17:44:27.247935+00:00
2023-02-11T17:44:27.247964+00:00
109,662
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can solve this problem using Four approaches. (Here I have explained all the possible solutions of this problem).\n\n1. Solved using Matrix with Extra space. TC : O((N*M)*(N+M)), SC : O(N*M).\n2. Solved using Matrix with Constant space. TC : O((N*M)*(N+M)), SC : O(1).\n3. Solved using Array + Hash Table (Unordered set). TC : O(N*M), SC : O(N+M).\n4. Solved using Matrix with Constant space. Optimized Approaches. TC : O(N*M), SC : O(1).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe can easily understand the All the approaches by seeing the code which is easy to understand with comments.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nTime complexity is given in code comment.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nSpace complexity is given in code comment.\n\n# Code\n```\n/*\n\n Time Complexity : O((N*M)*(N+M)), Where N is the number of row and M is number of column of matrix. Here\n nested loops creates the time complexity. O(N*M) for traversing through each element and (N+M) for traversing\n to row and column of elements having value 0.\n\n Space Complexity : O(N*M), visited matrix space.\n\n Solved using Matrix with Extra space.\n\n*/\n\n\n/***************************************** Approach 1 Code *****************************************/\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int n = matrix.size();\n int m = matrix[0].size();\n vector<vector<int>> visited = matrix;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(matrix[i][j] == 0){\n for(int k=0; k<m; k++){\n visited[i][k] = 0;\n }\n }\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(matrix[i][j] == 0){\n for(int k=0; k<n; k++){\n visited[k][j] = 0;\n }\n }\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n matrix[i][j] = visited[i][j];\n }\n }\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O((N*M)*(N+M)), Where N is the number of row and M is number of column of matrix. Here\n nested loops creates the time complexity. O(N*M) for traversing through each element and (N+M)for traversing\n to row and column of elements having value 0.\n\n Space Complexity : O(1), Constant space.\n\n Solved using Matrix.\n\n*/\n\n\n/***************************************** Approach 2 Code *****************************************/\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int n = matrix.size();\n int m = matrix[0].size();\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(matrix[i][j] == 0){\n for(int k=0; k<m; k++){\n if(matrix[i][k] != 0){\n matrix[i][k] = -9999;\n }\n }\n }\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(matrix[i][j] == 0){\n for(int k=0; k<n; k++){\n if(matrix[k][j] != 0){\n matrix[k][j] = -9999;\n }\n }\n }\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(matrix[i][j] == -9999){\n matrix[i][j] = 0;\n }\n }\n }\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N*M), Where N is the number of row and M is number of column of matrix. Here two nested \n loops creates the time complexity.\n\n Space Complexity : O(N+M), Here Unordered set(setRows and setColumn) creates the space complexity. O(N) for\n storing the row indexs and O(M) for storing the column indexs.\n\n Solved using Matrix + Hash Table.\n\n*/\n\n\n/***************************************** Approach 3 Code *****************************************/\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int n = matrix.size();\n int m = matrix[0].size();\n unordered_set<int> setRows; \n unordered_set<int> setColumns; \n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(matrix[i][j] == 0){\n setRows.insert(i);\n setColumns.insert(j);\n }\n }\n }\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(setRows.count(i) > 0 || setColumns.count(j) > 0){\n matrix[i][j] = 0;\n }\n }\n }\n }\n};\n\n\n\n\n\n\n/*\n\n Time Complexity : O(N*M), Where N is the number of row and M is number of column of matrix. Here two nested \n loops creates the time complexity.\n\n Space Complexity : O(1), Constant space.\n\n Solved using Matrix.\n\n*/\n\n\n/***************************************** Approach 4 Code *****************************************/\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int n = matrix.size();\n int m = matrix[0].size();\n bool flag1 = false, flag2 = false;\n for(int i=0; i<n; i++){\n if(matrix[i][0] == 0){\n flag1 = true;\n }\n }\n for(int j=0; j<m; j++){\n if(matrix[0][j] == 0){\n flag2 = true;\n }\n }\n for(int i=1; i<n; i++){\n for(int j=1; j<m; j++){\n if(matrix[i][j] == 0){\n matrix[i][0] = matrix[0][j] = 0;\n }\n }\n }\n for(int i=1; i<n; i++){\n for(int j=1; j<m; j++){\n if(matrix[i][0] == 0 || matrix[0][j] == 0){\n matrix[i][j] = 0;\n }\n }\n }\n if(flag1 == true){\n for(int i=0; i<n; i++){\n matrix[i][0] = 0;\n }\n }\n if(flag2 == true){\n for(int j=0; j<m; j++){\n matrix[0][j] = 0;\n }\n }\n }\n};\n\n\n```\n\n***IF YOU LIKE THE SOLUTION THEN PLEASE UPVOTE MY SOLUTION BECAUSE IT GIVES ME MOTIVATION TO REGULARLY POST THE SOLUTION.***\n\n![WhatsApp Image 2023-02-10 at 19.01.02.jpeg](https://assets.leetcode.com/users/images/0a95fea4-64f4-4502-82aa-41db6d77c05c_1676054939.8270252.jpeg)
1,005
2
['Array', 'Hash Table', 'Matrix', 'C++']
27
set-matrix-zeroes
My AC java O(1) solution (easy to read)
my-ac-java-o1-solution-easy-to-read-by-l-scc7
public class Solution {\n public void setZeroes(int[][] matrix) {\n boolean fr = false,fc = false;\n for(int i = 0; i < matrix.length; i++) {\n
lz2343
NORMAL
2015-06-01T09:05:32+00:00
2018-10-25T19:58:56.410965+00:00
83,238
false
public class Solution {\n public void setZeroes(int[][] matrix) {\n boolean fr = false,fc = false;\n for(int i = 0; i < matrix.length; i++) {\n for(int j = 0; j < matrix[0].length; j++) {\n if(matrix[i][j] == 0) {\n if(i == 0) fr = true;\n if(j == 0) fc = true;\n matrix[0][j] = 0;\n matrix[i][0] = 0;\n }\n }\n }\n for(int i = 1; i < matrix.length; i++) {\n for(int j = 1; j < matrix[0].length; j++) {\n if(matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n if(fr) {\n for(int j = 0; j < matrix[0].length; j++) {\n matrix[0][j] = 0;\n }\n }\n if(fc) {\n for(int i = 0; i < matrix.length; i++) {\n matrix[i][0] = 0;\n }\n }\n \n }\n}
560
6
[]
30
set-matrix-zeroes
Full Explanation || Super easy || constant space
full-explanation-super-easy-constant-spa-teim
Intuition\nIn this approach, we can just improve the space complexity. So, instead of using two extra matrices row and col, we will use the 1st row and 1st colu
raunakkodwani
NORMAL
2023-05-01T06:59:26.835480+00:00
2023-05-01T06:59:26.835515+00:00
53,816
false
# Intuition\nIn this approach, we can just improve the space complexity. So, instead of using two extra matrices row and col, we will use the 1st row and 1st column of the given matrix to keep a track of the cells that need to be marked with 0. But here comes a problem. If we try to use the 1st row and 1st column to serve the purpose, the cell matrix[0][0] is taken twice. To solve this problem we will take an extra variable col0 initialized with 1. Now the entire 1st row of the matrix will serve the purpose of the row array. And the 1st column from (0,1) to (0,m-1) with the col0 variable will serve the purpose of the col array\n\n![image.png](https://assets.leetcode.com/users/images/5e4c94b5-ea1e-4ca5-a166-9a014d49e001_1682924194.5173662.png)\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe steps are as follows:\n\nFirst, we will traverse the matrix and mark the proper cells of 1st row and 1st column with 0 accordingly. The marking will be like this: if cell(i, j) contains 0, we will mark the i-th row i.e. matrix[i][0] with 0 and we will mark j-th column i.e. matrix[0][j] with 0.\nIf i is 0, we will mark matrix[0][0] with 0 but if j is 0, we will mark the col0 variable with 0 instead of marking matrix[0][0] again.\n\nAfter step 1 is completed, we will modify the cells from (1,1) to (n-1, m-1) using the values from the 1st row, 1st column, and col0 variable.\n\nWe will not modify the 1st row and 1st column of the matrix here as the modification of the rest of the matrix(i.e. From (1,1) to (n-1, m-1)) is dependent on that row and column.\n\nFinally, we will change the 1st row and column using the values from matrix[0][0] and col0 variable. Here also we will change the row first and then the column.\n\nIf matrix[0][0] = 0, we will change all the elements from the cell (0,1) to (0, m-1), to 0.\nIf col0 = 0, we will change all the elements from the cell (0,0) to (n-1, 0), to 0. Note that the above approach is provided by Striver on youtube.\n<!-- Describe your approach to solving the problem. -->\n![image.png](https://assets.leetcode.com/users/images/e3a4d44d-7ade-4acb-8e2e-6cdc257505f3_1682924171.8253722.png)\n\n# Complexity\n- Time complexity:O(n^2)\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```\npublic class Solution {\npublic void setZeroes(int[][] matrix) {\n boolean fr = false,fc = false;\n for(int i = 0; i < matrix.length; i++) {\n for(int j = 0; j < matrix[0].length; j++) {\n if(matrix[i][j] == 0) {\n if(i == 0) fr = true;\n if(j == 0) fc = true;\n matrix[0][j] = 0;\n matrix[i][0] = 0;\n }\n }\n }\n for(int i = 1; i < matrix.length; i++) {\n for(int j = 1; j < matrix[0].length; j++) {\n if(matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }}\n }\n if(fr) {\n for(int j = 0; j < matrix[0].length; j++) {\n matrix[0][j] = 0;\n }\n }\n if(fc) {\n for(int i = 0; i < matrix.length; i++) {\n matrix[i][0] = 0;\n }\n }\n}} \n\n```\n![images.jpeg](https://assets.leetcode.com/users/images/43fc6382-7684-43ad-91e9-cea1908663b6_1682924250.7315671.jpeg)\n\n\n
491
0
['Java']
16
set-matrix-zeroes
All approaches from brute force to optimal with easy explanation
all-approaches-from-brute-force-to-optim-t9mb
Method 1: (Brute force)\n-using another matrix (let\'s say it matrix2)\n1. we can copy all the elements of given matrix to matrix2\n2. while traversing given ma
pranjulagrawal9
NORMAL
2022-09-03T17:04:22.574240+00:00
2023-08-02T06:46:54.957971+00:00
37,073
false
**Method 1:** (Brute force)\n-using another matrix (let\'s say it matrix2)\n1. we can copy all the elements of given matrix to matrix2\n2. while traversing given matrix whenever we encounter 0, we will make the entire row and column of the matrix2 to 0\n3. finally we can again copy all the elements of matrix2 to given matrix\n-**Time:** $$O((mn)*(m+n))$$, **Space:** $$O(mn)$$\n\n![image](https://assets.leetcode.com/users/images/edb17693-61dd-424b-88e7-f37b79c602f1_1662224098.764936.png)\n\n\n```\npublic void setZeroes(int[][] matrix){\n\n\t\tint m= matrix.length, n= matrix[0].length;\n int matrix2[][]= new int[m][n];\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++)\n matrix2[i][j]=matrix[i][j];\n }\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]==0){\n for(int k=0;k<n;k++)\n matrix2[i][k]=0;\n\n for(int k=0;k<m;k++)\n matrix2[k][j]=0;\n }\n }\n }\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++)\n matrix[i][j]=matrix2[i][j];\n }\n }\n```\n\n\n**Method 2:** (Better)\n1. we can use two separate arrays one for rows (rowsArray) and one for columns (colsArray) and initialize them to 1\n2. while traversing the given matrix whenever we encounter 0 at (i,j), we will set rowsArray[i]=0 and colsArray[j]=0\n3. After completion of step 2, again iterate through the matrix and for any (i,j), if rowsArray[i] or colsArray[j] is 0 then update matrix[i][j] to 0.\n-**Time:** $$O(mn)$$, **Space:** $$O(m+n)$$\n\n![image](https://assets.leetcode.com/users/images/985c05ee-ba5b-43ec-a7c2-41983d8bdae1_1662224319.5420349.png)\n\n```\npublic void setZeroes(int[][] matrix){\n\n\t\tint m=matrix.length, n=matrix[0].length;\n int rowsArray[]= new int[m];\n int colsArray[]= new int[n];\n \n Arrays.fill(rowsArray,1);\n Arrays.fill(colsArray,1);\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]==0){\n rowsArray[i]=0;\n colsArray[j]=0;\n }\n }\n }\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(rowsArray[i]==0 || colsArray[j]==0)\n matrix[i][j]=0;\n }\n }\n }\n```\n\n**Method 3:** (Optimal)\n-we can use the 0th row and 0th column of the given matrix itself instead of using two separate arrays\n1. first we will traverse the 0th row and 0th column of the given matrix and if we encounter any 0 then we will set the isRow0/isCol0 variable to true which indicates that the 0th row/0th column of the given matrix will become 0\n2. next we will traverse the remaining matrix except 0th row and 0th column and if we encounter any 0, we will make the corresponding row no. and column no. equal to 0 in the 0th column and 0th row respectively\n3. Now we will update the values of the matrix except first row and first column to 0 if matrix[i][0]=0 or matrix[0][j]=0 for any (i,j).\n4. finally we will traverse the 0th row and 0th column and if we find any 0, we will make the whole row and whole column equal to 0\n-**Time:** $$O(mn)$$, **Space:** $$O(1)$$\n\n![image](https://assets.leetcode.com/users/images/75193089-d14a-4cf9-aacf-5f97cc935f02_1662224420.9994516.png)\n\n```\npublic void setZeroes(int[][] matrix){\n\n\t\tint m=matrix.length, n=matrix[0].length;\n boolean isRow0=false, isCol0=false;\n \n for(int j=0;j<n;j++){\n if(matrix[0][j]==0)\n isRow0=true;\n }\n \n for(int i=0;i<m;i++){\n if(matrix[i][0]==0)\n isCol0=true;\n }\n \n for(int i=1;i<m;i++){\n for(int j=1;j<n;j++){\n if(matrix[i][j]==0){\n matrix[i][0]=0;\n matrix[0][j]=0;\n }\n }\n }\n \n for(int i=1;i<m;i++){\n for(int j=1;j<n;j++){\n if(matrix[0][j]==0 || matrix[i][0]==0)\n matrix[i][j]=0;\n }\n }\n \n if(isRow0){\n for(int j=0;j<n;j++)\n matrix[0][j]=0;\n }\n \n if(isCol0){\n for(int i=0;i<m;i++)\n matrix[i][0]=0;\n }\n }\n```\n\nDon\'t forget to upvote if you find it helpful! \uD83D\uDC4D
465
1
['Array', 'Matrix', 'C++', 'Java']
16
set-matrix-zeroes
【Video】O(1) space - Use the first row and column as a note.
video-o1-space-use-the-first-row-and-col-1kr7
Intuition\nUse the first row and column as a note.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/24Q1BR7gL2g\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to s
niits
NORMAL
2024-12-07T01:16:38.881143+00:00
2024-12-07T01:16:38.881168+00:00
27,003
false
# Intuition\nUse the first row and column as a note.\n\n---\n\n# Solution Video\n\nhttps://youtu.be/24Q1BR7gL2g\n\n### \u2B50\uFE0F\u2B50\uFE0F Don\'t forget to subscribe to my channel! \u2B50\uFE0F\u2B50\uFE0F\n\n**\u25A0 Subscribe URL**\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\nSubscribers: 10,154\nThank you for your support!\n\n---\n\n# Approach\n\nWe will solve this question with $$O(1)$$ space. We can\'t use extra data structure, so we use input array to keep something.\n\n```\nmatrix = \n[1,1,1]\n[1,0,1]\n[0,1,1]\n```\nMy strategy is to use the first row and first column as a note. More precisely, if we find `0`, update the same row and column at the first row and at the first column with `0`.\n\nBefore that, we have to check if we have `0` at index `0` of row and column, I\'ll explain why we need this check later.\n\nIn this case, we have `0` at `[0][2]`. Let\'s say we have flags for row and column.\n\n```\nfirst_row_has_zero = false\nfirst_col_has_zero = true\n```\nNext we iterate through except the first row and column. In the end, we find `0` at `[1][1]`, so update `[1][0]` and `[0][1]`.\n\n```\n[1,0,1]\n[0,0,1]\n[0,1,1]\n```\nThen update `row 1`, `row 2` and, `column 1`.\n```\n[1,0,1]\n[0,0,0]\n[0,0,0]\n```\n\nAt last, we check the flags we created in the first step. If the flags are `true`, we will update corresponding row or column. In the end,\n\n```\nreturn [[0,0,1],[0,0,0],[0,0,0]]\n\n[0,0,1]\n[0,0,0]\n[0,0,0]\n```\n\n- Why do we have the flags?\n\nLook at the matrix before we check flags.\n```\n[1,0,1]\n[0,0,0]\n[0,0,0]\n```\nNext step is to update the first row and the first column if needed. But **can you tell if a 0 was originally at the first row or the first column without using flags?** It\'s almost impossible.\n\n```\n note 0\n \u2193\n [1,0,1]\n note 0 \u2192 [0,0,0]\noriginal 0 \u2192 [0,0,0]\n```\nThat\'s why we use the flags.\n\n---\n\nhttps://youtu.be/bU_dXCOWHls\n\n---\n\n# Complexity\n\nBased on Python. Other language might be different.\n\n- Time complexity: $$O(m * 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```python []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n rows = len(matrix)\n cols = len(matrix[0])\n\n first_row_has_zero = False \n first_col_has_zero = False\n\n # check if the first row contains zero\n for c in range(cols):\n if matrix[0][c] == 0:\n first_row_has_zero = True\n break\n\n # check if the first column contains zero\n for r in range(rows):\n if matrix[r][0] == 0:\n first_col_has_zero = True\n break\n \n # use the first row and column as a note\n for r in range(1, rows):\n for c in range(1, cols):\n if matrix[r][c] == 0:\n matrix[r][0] = 0\n matrix[0][c] = 0\n \n # set the marked rows to zero\n for r in range(1, rows):\n if matrix[r][0] == 0:\n for c in range(1, cols):\n matrix[r][c] = 0\n\n # set the marked columns to zero\n for c in range(1, cols):\n if matrix[0][c] == 0:\n for r in range(1, rows):\n matrix[r][c] = 0\n \n # set the first row to zero if needed\n if first_row_has_zero:\n for c in range(cols):\n matrix[0][c] = 0\n\n # set the first column to zero if needed\n if first_col_has_zero:\n for r in range(rows):\n matrix[r][0] = 0\n \n return matrix\n```\n```javascript []\nvar setZeroes = function(matrix) {\n const rows = matrix.length;\n const cols = matrix[0].length;\n\n let first_row_has_zero = false;\n let first_col_has_zero = false;\n\n // Check if the first row contains zero\n for (let c = 0; c < cols; c++) {\n if (matrix[0][c] === 0) {\n first_row_has_zero = true;\n break;\n }\n }\n\n // Check if the first column contains zero\n for (let r = 0; r < rows; r++) {\n if (matrix[r][0] === 0) {\n first_col_has_zero = true;\n break;\n }\n }\n\n // Use the first row and column as markers\n for (let r = 1; r < rows; r++) {\n for (let c = 1; c < cols; c++) {\n if (matrix[r][c] === 0) {\n matrix[r][0] = 0;\n matrix[0][c] = 0;\n }\n }\n }\n\n // Set the marked rows to zero\n for (let r = 1; r < rows; r++) {\n if (matrix[r][0] === 0) {\n for (let c = 1; c < cols; c++) {\n matrix[r][c] = 0;\n }\n }\n }\n\n // Set the marked columns to zero\n for (let c = 1; c < cols; c++) {\n if (matrix[0][c] === 0) {\n for (let r = 1; r < rows; r++) {\n matrix[r][c] = 0;\n }\n }\n }\n\n // Set the first row to zero if needed\n if (first_row_has_zero) {\n for (let c = 0; c < cols; c++) {\n matrix[0][c] = 0;\n }\n }\n\n // Set the first column to zero if needed\n if (first_col_has_zero) {\n for (let r = 0; r < rows; r++) {\n matrix[r][0] = 0;\n }\n }\n\n return matrix; \n};\n```\n```java []\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int rows = matrix.length;\n int cols = matrix[0].length;\n\n boolean firstRowHasZero = false;\n boolean firstColHasZero = false;\n\n // Check if the first row contains zero\n for (int c = 0; c < cols; c++) {\n if (matrix[0][c] == 0) {\n firstRowHasZero = true;\n break;\n }\n }\n\n // Check if the first column contains zero\n for (int r = 0; r < rows; r++) {\n if (matrix[r][0] == 0) {\n firstColHasZero = true;\n break;\n }\n }\n\n // Use the first row and column as markers\n for (int r = 1; r < rows; r++) {\n for (int c = 1; c < cols; c++) {\n if (matrix[r][c] == 0) {\n matrix[r][0] = 0;\n matrix[0][c] = 0;\n }\n }\n }\n\n // Set the marked rows to zero\n for (int r = 1; r < rows; r++) {\n if (matrix[r][0] == 0) {\n for (int c = 1; c < cols; c++) {\n matrix[r][c] = 0;\n }\n }\n }\n\n // Set the marked columns to zero\n for (int c = 1; c < cols; c++) {\n if (matrix[0][c] == 0) {\n for (int r = 1; r < rows; r++) {\n matrix[r][c] = 0;\n }\n }\n }\n\n // Set the first row to zero if needed\n if (firstRowHasZero) {\n for (int c = 0; c < cols; c++) {\n matrix[0][c] = 0;\n }\n }\n\n // Set the first column to zero if needed\n if (firstColHasZero) {\n for (int r = 0; r < rows; r++) {\n matrix[r][0] = 0;\n }\n } \n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int rows = matrix.size();\n int cols = matrix[0].size();\n\n bool firstRowHasZero = false;\n bool firstColHasZero = false;\n\n // Check if the first row contains zero\n for (int c = 0; c < cols; c++) {\n if (matrix[0][c] == 0) {\n firstRowHasZero = true;\n break;\n }\n }\n\n // Check if the first column contains zero\n for (int r = 0; r < rows; r++) {\n if (matrix[r][0] == 0) {\n firstColHasZero = true;\n break;\n }\n }\n\n // Use the first row and column as markers\n for (int r = 1; r < rows; r++) {\n for (int c = 1; c < cols; c++) {\n if (matrix[r][c] == 0) {\n matrix[r][0] = 0;\n matrix[0][c] = 0;\n }\n }\n }\n\n // Set the marked rows to zero\n for (int r = 1; r < rows; r++) {\n if (matrix[r][0] == 0) {\n for (int c = 1; c < cols; c++) {\n matrix[r][c] = 0;\n }\n }\n }\n\n // Set the marked columns to zero\n for (int c = 1; c < cols; c++) {\n if (matrix[0][c] == 0) {\n for (int r = 1; r < rows; r++) {\n matrix[r][c] = 0;\n }\n }\n }\n\n // Set the first row to zero if needed\n if (firstRowHasZero) {\n for (int c = 0; c < cols; c++) {\n matrix[0][c] = 0;\n }\n }\n\n // Set the first column to zero if needed\n if (firstColHasZero) {\n for (int r = 0; r < rows; r++) {\n matrix[r][0] = 0;\n }\n } \n }\n};\n```\n\n\n---\n\nThank you for reading my post.\n\n## \u2B50\uFE0F Subscribe URL\nhttp://www.youtube.com/channel/UC9RMNwYTL3SXCP6ShLWVFww?sub_confirmation=1\n\n## \u2B50\uFE0F Twitter\nhttps://twitter.com/CodingNinjaAZ\n\n## \u2B50\uFE0F My previous video - Valid Parentheses #274\n\nhttps://youtu.be/UCPTkQSvTTY\n\n
244
0
['Array', 'Matrix', 'C++', 'Java', 'Python3']
1
set-matrix-zeroes
Python Solution w/ approach explanation & readable with space progression from: O(m+n) & O(1)
python-solution-w-approach-explanation-r-vh4j
Note: m = number of rows, n = number of cols\n\nBrute force using O(m*n) space: The initial approach is to start with creating another matrix to store the resul
cmeow
NORMAL
2020-05-28T19:11:19.813141+00:00
2020-05-28T19:13:17.820082+00:00
33,671
false
Note: m = number of rows, n = number of cols\n\n**Brute force using O(m*n) space:** The initial approach is to start with creating another matrix to store the result. From doing that, you\'ll notice that we want a way to know when each row and col should be changed to zero. We don\'t want to prematurely change the values in the matrix to zero because as we go through it, we might change a row to 0 because of the new value. \n\n**More optimized using O(m + n) space:** To do better, we want O(m + n). How do we go about that? Well, we really just need a way to track if any row or any col has a zero, because then that means the entire row or col has to be zero. Ok, well, then we can use an array to track the zeroes for the row and zeros for the col. Whenever we see a zero, just set that row or col to be True.\n\nSpace: O(m + n) for the zeroes_row and zeroes_col array \n``` Python\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # input validation\n if not matrix:\n return []\n\n m = len(matrix)\n n = len(matrix[0])\n\n zeroes_row = [False] * m\n zeroes_col = [False] * n\n for row in range(m):\n for col in range(n):\n if matrix[row][col] == 0:\n zeroes_row[row] = True\n zeroes_col[col] = True\n\n for row in range(m):\n for col in range(n):\n if zeroes_row[row] or zeroes_col[col]:\n matrix[row][col] = 0\n```\n\n**Most optimized using O(1) space:** But, we can do even better, O(1) - initial ask of the problem. What if instead of having a separate array to track the zeroes, we simply use the first row or col to track them and then go back to update the first row and col with zeroes after we\'re done replacing it? The approach to get constant space is to use first row and first col of the matrix as a tracker. \n* At each row or col, if you see a zero, then mark the first row or first col as zero with the current row and col. \n* Then iterate through the array again to see where the first row and col were marked as zero and then set that row/col as 0. \n* After doing that, you\'ll need to traverse through the first row and/or first col if there were any zeroes there to begin with and set everything to be equal to 0 in the first row and/or first col. \n\nTime complexity for all three progression is O(m * n).\n\n\n\n**Space:** O(1) for modification in place and using the first row and first col to keep track of zeros instead of zeroes_row and zeroes_col\n```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n\n m = len(matrix)\n n = len(matrix[0])\n\t\t\n first_row_has_zero = False\n first_col_has_zero = False\n \n # iterate through matrix to mark the zero row and cols\n for row in range(m):\n for col in range(n):\n if matrix[row][col] == 0:\n if row == 0:\n first_row_has_zero = True\n if col == 0:\n first_col_has_zero = True\n matrix[row][0] = matrix[0][col] = 0\n \n # iterate through matrix to update the cell to be zero if it\'s in a zero row or col\n for row in range(1, m):\n for col in range(1, n):\n matrix[row][col] = 0 if matrix[0][col] == 0 or matrix[row][0] == 0 else matrix[row][col]\n \n # update the first row and col if they\'re zero\n if first_row_has_zero:\n for col in range(n):\n matrix[0][col] = 0\n \n if first_col_has_zero:\n for row in range(m):\n matrix[row][0] = 0\n \n```
244
2
['Python', 'Python3']
17
set-matrix-zeroes
21 lines concise and easy understand C++ solution, O(1) space, three steps
21-lines-concise-and-easy-understand-c-s-nhqj
class Solution {\n public:\n void setZeroes(vector<vector<int>>& matrix) {\n bool row = false, col = false;\n for(int i = 0; i <
allen231x
NORMAL
2016-01-28T14:46:57+00:00
2018-10-23T02:21:00.261787+00:00
22,083
false
class Solution {\n public:\n void setZeroes(vector<vector<int>>& matrix) {\n bool row = false, col = false;\n for(int i = 0; i < matrix.size(); i++){\n for(int j = 0; j < matrix[0].size(); j++){\n if(matrix[i][j] == 0) {\n if(i == 0) row = true;\n if(j == 0) col = true;\n matrix[0][j] = matrix[i][0] = 0;\n }\n }\n }\n for(int i = 1; i < matrix.size(); i++){\n for(int j = 1; j < matrix[0].size(); j++){\n if(matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0;\n }\n }\n if(col){\n for(int i = 0; i < matrix.size(); i++) matrix[i][0] = 0;\n }\n if(row){\n for(int j = 0; j < matrix[0].size(); j++) matrix[0][j] = 0;\n }\n }\n };
156
2
[]
8
set-matrix-zeroes
✅Set Matrix Zeroes || 2 Approach w/ Explanation || C++ | Python | Java
set-matrix-zeroes-2-approach-w-explanati-hfd6
OBSERVATION:\nThe time complexity of this problem remains O(M*N), the only improvement we can do is of the space complexity. So we will have 2 approaches here\n
Maango16
NORMAL
2021-08-13T07:38:57.933600+00:00
2021-08-13T07:38:57.933661+00:00
9,989
false
**OBSERVATION:**\nThe time complexity of this problem remains `O(M*N)`, the only improvement we can do is of the space complexity. So we will have 2 approaches here\n\n# **APPROACH I:**\n*Additional Memory Approach-*\nIf any cell of the matrix has a zero we can record its row and column number. All the cells of this recorded row and column can be marked zero in the next iteration.\n\n**Algorithm**\n* We iterate over the original array and look for zero entries.\n* If we find that an entry at `[i, j]` is `0`, then we need to record somewhere the row `i` and column `j`.\n* So, we use two sets, one for the rows and one for the columns.\n```\n if cell[i][j] == 0 \n {\n row.insert(i) \n column.insert(j)\n }\n ```\n* We iterate over the array once again, and check each cell.\n\t* If the row **Or** column is marked, we set the value of the cell as 0.\n\n**Solution**\n`In C++`\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int R = matrix.size();\n int C = matrix[0].size();\n set<int> rows ;\n set<int> cols ;\n // We mark the rows and columns that are to be made zero\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (matrix[i][j] == 0) \n {\n rows.insert(i);\n cols.insert(j);\n }\n }\n }\n // Iterate over the array once again and using the rows and cols sets, update the elements.\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (rows.count(i) || cols.count(j)) \n {\n matrix[i][j] = 0;\n }\n }\n }\n }\n};\n```\n`In JAVA`\n```\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int R = matrix.length;\n int C = matrix[0].length;\n Set<Integer> rows = new HashSet<Integer>();\n Set<Integer> cols = new HashSet<Integer>();\n\n // We mark the rows and columns that are to be made zero\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (matrix[i][j] == 0) \n {\n rows.add(i);\n cols.add(j);\n }\n }\n }\n\n // Iterate over the array once again and using the rows and cols sets, update the elements.\n for (int i = 0; i < R; i++) \n {\n for (int j = 0; j < C; j++) \n {\n if (rows.contains(i) || cols.contains(j)) \n {\n matrix[i][j] = 0;\n }\n }\n }\n }\n}\n```\n`In Python`\n```\nclass Solution(object):\n def setZeroes(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: None Do not return anything, modify matrix in-place instead.\n """\n R = len(matrix)\n C = len(matrix[0])\n rows, cols = set(), set()\n\n # We mark the rows and columns that are to be made zero\n for i in range(R):\n for j in range(C):\n if matrix[i][j] == 0:\n rows.add(i)\n cols.add(j)\n\n # Iterate over the array once again and using the rows and cols sets, update the elements\n for i in range(R):\n for j in range(C):\n if i in rows or j in cols:\n matrix[i][j] = 0\n```\n**TIME COMPLEXITY- O(M*N)** where M and N are the number of rows and columns respectively.\n**SPACE COMPLEXITY- O(M+N)**\n\n# **APPROACH II**\nWe handle cases seperately. \n* Check the first row and column for pre-existing `0`. \n\t* If found we mark that row or column as true\n* Now we work upon the remaining matrix.\n\t* First we look for the cell that has `0` in it.\n\t* Then proceed with the working i.e. marking the cell as 0. \n* Now work upon the checked first row and column and update their values.\n\t* Note: Updating before hand gives WA\n \n**Solution**\n`In C++`\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n bool RowZero = false;\n bool ColZero = false;\n for (int i = 0; i < matrix[0].size(); i++) //check the first row\n { \n if (matrix[0][i] == 0) \n {\n RowZero = true;\n break;\n } \n }\n for (int i = 0; i < matrix.size(); i++) //check the first column\n { \n if (matrix[i][0] == 0) \n {\n ColZero = true;\n break;\n } \n }\n for (int i = 1; i < matrix.size(); i++) //check except the first row and column\n { \n for (int j = 1; j < matrix[0].size(); j++) \n { \n if (matrix[i][j] == 0) \n {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n } \n }\n }\n for (int i = 1; i < matrix.size(); i++) //process except the first row and column \n {\n for (int j = 1; j < matrix[0].size(); j++)\n {\n if (matrix[i][0] == 0 || matrix[0][j] == 0)\n {\n matrix[i][j] = 0;\n \n }\n }\n }\n if(RowZero) //handle the first row\n { \n for (int i = 0; i < matrix[0].size(); i++) \n {\n matrix[0][i] = 0;\n }\n }\n if (ColZero) //handle the first column\n { \n for (int i = 0; i < matrix.size(); i++)\n {\n matrix[i][0] = 0;\n }\n }\n }\n};\n```\n**TIME COMPLEXITY- O(M*N)** where M and N are the number of rows and columns respectively.\n**SPACE COMPLEXITY- O(1)**
139
2
[]
8
set-matrix-zeroes
CPP||C++||99.23%||Google||Amazon
cppc9923googleamazon-by-rupakpro107-wnvz
Approach-First of all create two vectors rowmarker and columnmarker to store the positions of column and row where the element is zero. \nIf element in either r
rupakpro107
NORMAL
2020-07-03T08:31:58.849547+00:00
2020-07-03T18:52:15.649752+00:00
10,587
false
Approach-First of all create two vectors rowmarker and columnmarker to store the positions of column and row where the element is zero. \nIf element in either row marker or columnmarker is 0.Then make the element in the whole matrix 0. \n```\n void setZeroes(vector<vector<int>>& matrix) { \n int rowsize=matrix.size(); \n int columnsize=matrix[0].size(); \n vector<int>rowmarker(rowsize,1);\n vector<int>columnmarker(columnsize,1); \n for(int i=0;i<rowsize;i++)\n {\n for(int j=0;j<columnsize;j++)\n {\n if(matrix[i][j]==0)\n {\n rowmarker[i]=0; \n columnmarker[j]=0;\n }\n }\n } \n for(int i=0;i<rowsize;i++)\n {\n for(int j=0;j<columnsize;j++)\n {\n if(rowmarker[i]==0 or columnmarker[j]==0)\n matrix[i][j]=0;\n }\n }\n \n }\n\t```\n\t Please Upvote if you like my solution.Jai Hind.
101
23
['C', 'C++']
6
set-matrix-zeroes
C++ | Simple | 99% Faster | O(1) Space | Upvote
c-simple-99-faster-o1-space-upvote-by-v4-7o4x
\n void setZeroes(vector<vector<int>>& a) {\n int n = a.size();\n int m = a[0].size();\n bool firstRow = false; // do we need to set fi
v4vijay
NORMAL
2021-06-16T09:52:38.299354+00:00
2021-06-16T09:52:38.299386+00:00
12,635
false
```\n void setZeroes(vector<vector<int>>& a) {\n int n = a.size();\n int m = a[0].size();\n bool firstRow = false; // do we need to set first row zero\n bool firstCol = false; // do we need to ser first col zero\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n\t\t\t\t\tif(a[i][j] == 0){ // store rows and cols state in first row and col\n if(i==0) firstRow = true;\n if(j==0) firstCol = true;\n a[i][0] = 0;\n a[0][j] = 0;\n }\n }\n }\n // cout<<firstRow<<" "<<firstCol<<endl;\n for(int i=1; i<n; i++){\n for(int j=1; j<m; j++){\n if(a[i][0] == 0 || a[0][j] == 0){\n a[i][j] = 0;\n }\n }\n }\n \n if(firstRow){\n for(int i=0;i<m;i++) a[0][i] = 0;\n }\n \n if(firstCol){\n for(int i=0;i<n;i++) a[i][0] = 0;\n }\n }\n```
96
1
['C']
8
set-matrix-zeroes
My C++ O(1) yoooooo
my-c-o1-yoooooo-by-lugiavn-t3qo
I find the last row which has 0, and use it to store the 0-collumns.\nThen go row by row set them to 0.\nThen go column by column set them to 0.\nFinally set th
lugiavn
NORMAL
2015-01-10T18:47:20+00:00
2018-09-30T02:27:50.611484+00:00
32,639
false
I find the last row which has 0, and use it to store the 0-collumns.\nThen go row by row set them to 0.\nThen go column by column set them to 0.\nFinally set the last row which has 0. It's long but hey it's O(1) \n\n\n class Solution {\n public:\n void setZeroes(vector<vector<int> > &matrix) {\n \n int H = matrix.size();\n int W = matrix[0].size();\n \n // find the last 0 row\n int last_0_row = -1;\n for (int y = H - 1; y >= 0 && last_0_row == -1; y--)\n for (int x = 0; x < W; x++)\n if (matrix[y][x] == 0)\n {\n last_0_row = y;\n break;\n }\n if (last_0_row == -1)\n return;\n \n // go row by row\n for (int y = 0; y < last_0_row; y++)\n {\n bool this_is_a_0_row = false;\n \n for (int x = 0; x < W; x++)\n {\n if (matrix[y][x] == 0)\n {\n this_is_a_0_row = true;\n matrix[last_0_row][x] = 0;\n }\n }\n \n if (this_is_a_0_row)\n for (int x = 0; x < W; x++)\n {\n matrix[y][x] = 0;\n }\n }\n \n // set collums to 0\n for (int y = 0; y < H; y++)\n for (int x = 0; x < W; x++)\n {\n if (matrix[last_0_row][x] == 0)\n matrix[y][x] = 0;\n }\n \n // set the last 0 row \n for (int x = 0; x < W; x++)\n {\n matrix[last_0_row][x] = 0;\n }\n }\n };
70
2
[]
11
set-matrix-zeroes
O(1) space solution in Python
o1-space-solution-in-python-by-autekwing-50gx
class Solution:\n # @param {integer[][]} matrix\n # @return {void} Do not return anything, modify matrix in-place instead.\n def setZeroes(self, matrix
autekwing
NORMAL
2015-07-30T03:38:25+00:00
2018-10-10T19:19:08.682070+00:00
22,026
false
class Solution:\n # @param {integer[][]} matrix\n # @return {void} Do not return anything, modify matrix in-place instead.\n def setZeroes(self, matrix):\n m = len(matrix)\n if m == 0:\n return\n n = len(matrix[0])\n \n row_zero = False\n for i in range(m):\n if matrix[i][0] == 0:\n row_zero = True\n col_zero = False\n for j in range(n):\n if matrix[0][j] == 0:\n col_zero = True\n \n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == 0:\n matrix[i][0] = 0\n matrix[0][j] = 0\n \n for i in range(1, m):\n if matrix[i][0] == 0:\n for j in range(1, n):\n matrix[i][j] = 0\n \n for j in range(1, n):\n if matrix[0][j] == 0:\n for i in range(1, m):\n matrix[i][j] = 0\n \n if col_zero:\n for j in range(n):\n matrix[0][j] = 0\n if row_zero:\n for i in range(m):\n matrix[i][0] = 0
63
0
[]
13
set-matrix-zeroes
[Python] O(mn)/O(1) time/space solution, explained
python-omno1-timespace-solution-explaine-a5sy
The idea is to use first row and first column as indicator, if we need to set the whole corresponding column or row to zeros. We also keep r1 andc1variables: do
dbabichev
NORMAL
2021-08-13T07:44:07.179415+00:00
2021-08-13T08:33:03.946460+00:00
4,189
false
The idea is to use first row and first column as indicator, if we need to set the whole corresponding column or row to zeros. We also keep `r1 and `c1` variables: do we need to update first column and/or first row in the end. So, we have the following steps:\n\n1. Create `r1` and `c1`.\n2. Iterate through our matrix and if we see that for if element `M[i][j]` is equal to `0`, we put both elements `M[i][0]` and `M[0][j]` to `0`.\n3. Now, we updated all elements in first row and column, so we iterate our matrix once again: and if we see that one of elements `M[i][0]` or `M[0][j]` equal to `0`, we make `M[i][j] equal to `0`.\n4. Finally, we need to update first row and column, so we make them `0`, if we have indicator `r1` for row and `c1` for column.\n\n#### Complexity\nTime complexity is `O(mn)`, space is `O(1)`.\n\n#### Code\n```python\nclass Solution:\n def setZeroes(self, M):\n m, n = len(M[0]), len(M)\n r1 = any(M[0][j] == 0 for j in range(m))\n c1 = any(M[i][0] == 0 for i in range(n))\n for i in range(1, n):\n for j in range(1, m):\n if M[i][j] == 0: M[i][0] = M[0][j] = 0\n \n for i in range(1, n):\n for j in range(1, m):\n if M[i][0] * M[0][j] == 0: M[i][j] = 0\n \n if r1:\n for i in range(m): M[0][i] = 0\n \n if c1:\n for j in range(n): M[j][0] = 0\n```\n\t\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
61
2
['Math']
6
set-matrix-zeroes
Java/Python O(1) space 11 lines solution
javapython-o1-space-11-lines-solution-by-7u82
Java\n\n public void setZeroes(int[][] matrix) {\n int m = matrix.length, n = matrix[0].length, k = 0;\n // First row has zero?\n while
dietpepsi
NORMAL
2015-11-19T18:06:40+00:00
2018-08-09T19:07:21.958197+00:00
21,131
false
**Java**\n\n public void setZeroes(int[][] matrix) {\n int m = matrix.length, n = matrix[0].length, k = 0;\n // First row has zero?\n while (k < n && matrix[0][k] != 0) ++k;\n // Use first row/column as marker, scan the matrix\n for (int i = 1; i < m; ++i)\n for (int j = 0; j < n; ++j)\n if (matrix[i][j] == 0)\n matrix[0][j] = matrix[i][0] = 0;\n // Set the zeros\n for (int i = 1; i < m; ++i)\n for (int j = n - 1; j >= 0; --j)\n if (matrix[0][j] == 0 || matrix[i][0] == 0)\n matrix[i][j] = 0;\n // Set the zeros for the first row\n if (k < n) Arrays.fill(matrix[0], 0);\n }\n\n**Python**\n\n def setZeroes(self, matrix):\n # First row has zero?\n m, n, firstRowHasZero = len(matrix), len(matrix[0]), not all(matrix[0])\n # Use first row/column as marker, scan the matrix\n for i in xrange(1, m):\n for j in xrange(n):\n if matrix[i][j] == 0:\n matrix[0][j] = matrix[i][0] = 0\n # Set the zeros\n for i in xrange(1, m):\n for j in xrange(n - 1, -1, -1):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n # Set the zeros for the first row\n if firstRowHasZero:\n matrix[0] = [0] * n
51
2
['Python', 'Java']
12
set-matrix-zeroes
[Python] From O(M+N) space to O(1) space - with Picture - Clean & Concise
python-from-omn-space-to-o1-space-with-p-8jnv
Solution 1: Additional Memory Space\n- Let zeroRow[r] = True denote all the cells in row r must have value 0.\n- Let zeroCol[c] = True denote all the cells in c
hiepit
NORMAL
2021-09-17T15:55:52.526541+00:00
2021-09-17T17:15:23.668938+00:00
1,756
false
**Solution 1: Additional Memory Space**\n- Let `zeroRow[r] = True` denote all the cells in row `r` must have value 0.\n- Let `zeroCol[c] = True` denote all the cells in column `c` must have value 0.\n```python\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m, n = len(matrix), len(matrix[0])\n zeroRow = [False] * m\n zeroCol = [False] * n\n for r in range(m):\n for c in range(n):\n if matrix[r][c] == 0:\n zeroRow[r] = zeroCol[c] = True\n\n for r in range(m):\n for c in range(n):\n if zeroRow[r] or zeroCol[c]:\n matrix[r][c] = 0\n```\nComplexity:\n- Time: `O(M * N)`, where `M <= 200` is number of rows, `N <= 200` is number of columns.\n- Space: `O(M + N)`\n\n---\n**Solution 2: In-space Solution**\n- We re-use the first row as the meaning of `zeroCol`. It means `matrix[r][0] = 0` is the same meaning with `zeroRow[r] = True`. \n- We re-use the first column as the meaning of `zeroRow`. It means `matrix[0][c] = 0` is the same meaning with `zeroCol[c] = True`.\n- While processing to set `matrix[r][0] = 0` or `matrix[0][c] = 0`, we iterate cells with `r` in `[1...m-1]`, `c` in `[1..n-1]`. \n\t- We skip cells in the first row `r = 0` and cells in the first column `c = 0`. \n\t- Otherwise, we will get WRONG ANSWER, can check following example:\n\t![image](https://assets.leetcode.com/users/images/dc1a5e2f-615e-409c-bdb5-a153fe66c955_1631898869.821589.png)\n- Before, we need to use 2 additional flag:\n\t- `zeroFirstRow`: To check if all elements in the first row should be set into zero\n\t- `zeroFirstCol`: To check if all elements in the first column should be set into zero.\n```python\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m, n = len(matrix), len(matrix[0])\n \n zeroFirstRow = any(matrix[0][c] == 0 for c in range(n))\n zeroFirstCol = any(matrix[r][0] == 0 for r in range(m))\n \n for r in range(1, m):\n for c in range(1, n):\n if matrix[r][c] == 0: matrix[0][c] = matrix[r][0] = 0\n\n for r in range(1, m):\n for c in range(1, n):\n if matrix[r][0] == 0 or matrix[0][c] == 0: matrix[r][c] = 0\n \n if zeroFirstRow:\n for c in range(n): matrix[0][c] = 0\n \n if zeroFirstCol:\n for r in range(m): matrix[r][0] = 0\n```\nComplexity:\n- Time: `O(M * N)`, where `M <= 200` is number of rows, `N <= 200` is number of columns.\n- Space: `O(1)`\n
48
0
[]
4
set-matrix-zeroes
My JAVA solution, easy to understand
my-java-solution-easy-to-understand-by-k-au4f
public void setZeroes(int[][] matrix) {\n int m=matrix.length;\n int n=matrix[0].length;\n int[] row = new int[m];\n int[] col = new
knighty
NORMAL
2015-09-01T20:36:12+00:00
2015-09-01T20:36:12+00:00
5,214
false
public void setZeroes(int[][] matrix) {\n int m=matrix.length;\n int n=matrix[0].length;\n int[] row = new int[m];\n int[] col = new int[n];\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(matrix[i][j]==0){\n row[i]=1;\n col[j]=1;\n }\n }\n }\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(row[i]==1||col[j]==1){\n matrix[i][j]=0;\n }\n }\n }\n }
43
6
['Java']
7
set-matrix-zeroes
O(1) JAVA, straightforward idea
o1-java-straightforward-idea-by-januarui-1c1l
Use the first column and the first row as marker:\n1. first scan through the whole matrix, and if one row i has zero, label matrix[i][0] = 0, if column j has ze
januarui
NORMAL
2015-10-16T06:06:26+00:00
2015-10-16T06:06:26+00:00
14,711
false
Use the first column and the first row as marker:\n1. first scan through the whole matrix, and if one row i has zero, label matrix[i][0] = 0, if column j has zero, then label matrix[0][j] = 0.\nif we find the first row has zero, then mark a boolean row = true, if the first column has zeros, mark a boolean col = true;\n\n2. By the markers on the first row and first col, set the other columns and rows to zeros. (first row and first column already contain zeros)\n\n3. According to booleans row and col, decide whether to set first row and column to zeros.\n\n public class Solution {\n public void setZeroes(int[][] matrix) {\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return;\n int m = matrix.length, n = matrix[0].length;\n boolean row = false, col = false;\n for (int i = 0; i < m; i++)\n for (int j = 0; j < n; j++){\n if (matrix[i][j] == 0) {\n matrix[0][j] = 0;\n matrix[i][0] = 0;\n if (i == 0) row = true;\n if (j == 0) col = true;\n }\n }\n for (int i = 1; i < m; i++){\n if (matrix[i][0] == 0){\n for (int j = 1; j < n;j++)\n matrix[i][j] = 0;\n }\n }\n for (int j = 1; j < n; j++){\n if (matrix[0][j] == 0){\n for (int i = 1; i < m; i++)\n matrix[i][j] = 0;\n }\n }\n if (row){\n for (int j = 0; j < n; j++)\n matrix[0][j] = 0;\n }\n if (col){\n for(int i = 0; i < m; i++)\n matrix[i][0] = 0;\n }\n }\n}
40
1
[]
4
set-matrix-zeroes
✅ 🔥 0 ms Runtime Beats 100% User🔥|| Code Idea ✅ || Algorithm & Solving Step ✅ ||
0-ms-runtime-beats-100-user-code-idea-al-ul63
\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n\n\n### Key Idea :\n1. Marking Rows and Columns:\n - Use the first row and the fir
Letssoumen
NORMAL
2024-11-30T08:14:17.796414+00:00
2024-11-30T08:14:17.796475+00:00
5,535
false
![Screenshot 2024-11-30 at 1.39.16\u202FPM.png](https://assets.leetcode.com/users/images/1b49d033-d7d7-4aa2-8194-3eee8ea4cf5a_1732954316.8230045.png)\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n\n\n### **Key Idea** :\n1. **Marking Rows and Columns**:\n - Use the first row and the first column of the matrix as markers:\n - If `matrix[i][j] == 0`, mark `matrix[i][0]` and `matrix[0][j]` as 0.\n - This avoids the need for extra space while still keeping track of which rows and columns should be zeroed out.\n\n2. **Handle Zeroes in Place**:\n - First, traverse the matrix (excluding the first row and column) and use the markers to set appropriate elements to zero.\n - Then, handle the first row and first column separately.\n\n3. **Edge Case**:\n - To prevent overwriting the markers prematurely, keep track of whether the first row and first column themselves need to be zeroed out.\n\n---\n\n### **Steps** :\n\n1. Traverse the matrix to identify zero elements.\n - Mark the corresponding row and column in the first row and column.\n\n2. Traverse the matrix again (excluding the first row and column) to zero out cells based on the markers.\n\n3. Zero out the first row and first column if necessary.\n\n---\n\n### **Code Implementation** :\n\n#### **C++** :\n```cpp\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int m = matrix.size(), n = matrix[0].size();\n bool firstRowZero = false, firstColZero = false;\n\n // Check if the first row and first column need to be zero\n for (int i = 0; i < m; i++) {\n if (matrix[i][0] == 0) firstColZero = true;\n }\n for (int j = 0; j < n; j++) {\n if (matrix[0][j] == 0) firstRowZero = true;\n }\n\n // Mark zeros in the first row and column\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Set matrix cells to zero based on markers\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Zero out the first row if needed\n if (firstRowZero) {\n for (int j = 0; j < n; j++) {\n matrix[0][j] = 0;\n }\n }\n\n // Zero out the first column if needed\n if (firstColZero) {\n for (int i = 0; i < m; i++) {\n matrix[i][0] = 0;\n }\n }\n }\n};\n```\n\n---\n\n#### **Java** :\n```java\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int m = matrix.length, n = matrix[0].length;\n boolean firstRowZero = false, firstColZero = false;\n\n // Check if the first row and first column need to be zero\n for (int i = 0; i < m; i++) {\n if (matrix[i][0] == 0) firstColZero = true;\n }\n for (int j = 0; j < n; j++) {\n if (matrix[0][j] == 0) firstRowZero = true;\n }\n\n // Mark zeros in the first row and column\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n // Set matrix cells to zero based on markers\n for (int i = 1; i < m; i++) {\n for (int j = 1; j < n; j++) {\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n\n // Zero out the first row if needed\n if (firstRowZero) {\n for (int j = 0; j < n; j++) {\n matrix[0][j] = 0;\n }\n }\n\n // Zero out the first column if needed\n if (firstColZero) {\n for (int i = 0; i < m; i++) {\n matrix[i][0] = 0;\n }\n }\n }\n}\n```\n\n---\n\n#### **Python** :\n```python\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n m, n = len(matrix), len(matrix[0])\n firstRowZero = any(matrix[0][j] == 0 for j in range(n))\n firstColZero = any(matrix[i][0] == 0 for i in range(m))\n\n # Mark zeros in the first row and column\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][j] == 0:\n matrix[i][0] = 0\n matrix[0][j] = 0\n\n # Set matrix cells to zero based on markers\n for i in range(1, m):\n for j in range(1, n):\n if matrix[i][0] == 0 or matrix[0][j] == 0:\n matrix[i][j] = 0\n\n # Zero out the first row if needed\n if firstRowZero:\n for j in range(n):\n matrix[0][j] = 0\n\n # Zero out the first column if needed\n if firstColZero:\n for i in range(m):\n matrix[i][0] = 0\n```\n\n---\n\n### **Complexity** :\n\n- **Time Complexity**: O(m \xD7 n) \n - Traverse the matrix twice: once to mark rows/columns and once to zero out cells.\n- **Space Complexity**: O(1) \n - No additional space is used apart from the input matrix itself.\n\n---\n\n![image.png](https://assets.leetcode.com/users/images/2d7c2498-cf20-407f-8b94-1a0b6a1c0e5a_1732954446.8487918.png)\n
39
1
['Array', 'Hash Table', 'Matrix', 'C++', 'Java', 'Python3']
1
set-matrix-zeroes
My java O(1) solution (easy to understand)
my-java-o1-solution-easy-to-understand-b-80nl
public class Solution {\n public void setZeroes(int[][] matrix) {\n if(matrix==null){\n return;\n }\n \n
xiangru_wang
NORMAL
2015-02-13T00:27:48+00:00
2018-09-25T02:23:37.815620+00:00
18,187
false
public class Solution {\n public void setZeroes(int[][] matrix) {\n if(matrix==null){\n return;\n }\n \n int m = matrix.length;\n int n = matrix[0].length;\n \n boolean rowHasZero = false;\n boolean colHasZero = false;\n \n for(int i=0; i<n; i++){\n if(matrix[0][i]==0){\n rowHasZero = true;\n break;\n }\n }\n \n for(int i=0; i<m; i++){\n if(matrix[i][0]==0){\n colHasZero = true;\n break;\n }\n }\n \n for(int i=1; i<m; i++){\n for(int j=1; j<n; j++){\n if(matrix[i][j]==0){\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n \n \n \n for(int j=1;j<n; j++){\n if(matrix[0][j]==0){\n nullifyCol(matrix, j, m, n);\n }\n }\n \n for(int i=1; i<m; i++){\n if(matrix[i][0]==0){\n nullifyRow(matrix, i, m, n);\n }\n }\n \n if(rowHasZero){\n nullifyRow(matrix, 0, m, n);\n }\n if(colHasZero){\n nullifyCol(matrix, 0, m, n);\n }\n \n }\n \n public void nullifyRow(int[][] matrix, int i, int m, int n){\n for(int col=0; col<n; col++){\n matrix[i][col] = 0;\n }\n }\n \n public void nullifyCol(int[][] matrix, int j, int m, int n){\n for(int row=0; row<m; row++){\n matrix[row][j] = 0;\n }\n }\n }
39
7
[]
4
set-matrix-zeroes
Python solution using set | beats 100%
python-solution-using-set-beats-100-by-r-ba2w
\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n
rougef4ak
NORMAL
2020-04-20T12:37:18.575694+00:00
2020-04-20T12:37:18.575726+00:00
4,877
false
```\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n """\n Do not return anything, modify matrix in-place instead.\n """\n row = set()\n column = set()\n \n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n if matrix[i][j] == 0:\n row.add(i)\n column.add(j) \n for i in row:\n for j in range(len(matrix[0])):\n matrix[i][j] = 0\n for i in column:\n for j in range(len(matrix)):\n matrix[j][i] = 0 \n```
36
3
['Ordered Set', 'Python', 'Python3']
9
set-matrix-zeroes
Java easy to understand O(1) space solution with 2 passes
java-easy-to-understand-o1-space-solutio-8qlp
public class Solution {\n \n public void setZeroes(int[][] matrix) {\n if(matrix==null || matrix.length==0){\n return;\n }\n
krzykid
NORMAL
2016-02-17T04:55:48+00:00
2018-08-14T04:38:15.208627+00:00
7,692
false
public class Solution {\n \n public void setZeroes(int[][] matrix) {\n if(matrix==null || matrix.length==0){\n return;\n }\n \n boolean setFirstRowToZeroes = false;\n boolean setFirstColumnToZeroes = false;\n \n //check if first column needs to be set to zero\n for(int row=0;row<matrix.length;row++){\n if(matrix[row][0] == 0){\n setFirstColumnToZeroes=true;\n break;\n }\n }\n \n //check if first row needs to be set to zero\n for(int col=0;col<matrix[0].length;col++){\n if(matrix[0][col] == 0){\n setFirstRowToZeroes=true;\n break;\n }\n }\n \n //mark columns and rows to be set to zero\n for(int row=1;row<matrix.length;row++){\n for(int col=1;col<matrix[0].length;col++){\n if(matrix[row][col]==0){\n matrix[row][0]=0;\n matrix[0][col]=0;\n }\n }\n }\n \n // make rows zero\n for(int row=1;row<matrix.length;row++){\n if(matrix[row][0]==0){\n for(int col=1;col<matrix[0].length;col++){\n matrix[row][col]=0;\n }\n }\n }\n \n // make columns zero\n for(int col=1;col<matrix[0].length;col++){\n if(matrix[0][col]==0){\n for(int row=1;row<matrix.length;row++){\n matrix[row][col]=0;\n }\n }\n }\n \n // zero out first row (if needed)\n if(setFirstRowToZeroes){\n for(int col=0;col<matrix[0].length;col++){\n matrix[0][col]=0;\n }\n }\n \n // zero out first column (if needed)\n if(setFirstColumnToZeroes){\n for(int row=0;row<matrix.length;row++){\n matrix[row][0]=0;\n }\n }\n \n }\n}
34
3
['Java']
6
set-matrix-zeroes
✅ Easiest | 4 approaches | Video | Line by line explanation | Beginner Friendly
easiest-4-approaches-video-line-by-line-82747
Mastering LeetCode 73: Set Matrix Zeroes\n\nWelcome to our deep dive into LeetCode problem 73: Set Matrix Zeroes. This problem is an excellent exercise in matri
hackcode62
NORMAL
2024-09-11T01:52:03.365421+00:00
2024-09-11T01:54:22.936644+00:00
2,590
false
# Mastering LeetCode 73: Set Matrix Zeroes\n\nWelcome to our deep dive into LeetCode problem 73: Set Matrix Zeroes. This problem is an excellent exercise in matrix manipulation and optimization. We\'ll explore four different approaches, starting with a brute force solution and gradually optimizing to achieve the most efficient O(1) space complexity solution.\n\n---\n\n## Problem Statement\n\nGiven an m x n integer matrix, if an element is 0, set its entire row and column to 0\'s, and do it in-place.\n\n---\n\n## Video Solution\nhttps://youtu.be/fXrAW5UFTeo\n\n---\n\n\n## Approach 1: Brute Force with Deep Copy\n\nOur first approach uses a deep copy of the matrix to avoid modifying the original during iteration.\n\n```python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # Step 1: Handle edge case for an empty matrix\n if not matrix:\n return\n \n # Step 2: Get the dimensions of the matrix\n rows, cols = len(matrix), len(matrix[0])\n \n # Step 3: Create a deep copy of the original matrix\n copy_matrix = [row[:] for row in matrix]\n \n # Step 4: Traverse the original matrix to find zeros\n for row in range(rows):\n for col in range(cols):\n if matrix[row][col] == 0:\n # Step 5: Mark the entire row with zeros in the copied matrix\n for k in range(cols):\n copy_matrix[row][k] = 0\n # Step 6: Mark the entire column with zeros in the copied matrix\n for k in range(rows):\n copy_matrix[k][col] = 0\n \n # Step 7: Copy the updated values back to the original matrix\n for row in range(rows):\n for col in range(cols):\n matrix[row][col] = copy_matrix[row][col]\n\n # Why deep copy?\n # Using a deep copy prevents discrepancies that could occur\n # if we modified the original matrix during iteration.\n```\n### Complexities\n- Time Complexity: O(M * N * (M + N)) \n- Space Complexity: O(M * N)\n\nThis approach is straightforward but inefficient in both time and space.\n\n---\n\n## Approach 2: Using Sets\nWe can optimize by using sets to track rows and columns that need to be zeroed.\n\n```python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # Step 1: Handle edge case for an empty matrix\n if not matrix:\n return []\n \n # Step 2: Initialize sets to track rows and columns that need to be zeroed\n zero_rows, zero_cols = set(), set()\n rows, cols = len(matrix), len(matrix[0])\n\n # Step 3: Traverse the matrix to identify cells with zero and mark the corresponding rows and columns\n for row in range(rows):\n for col in range(cols):\n if matrix[row][col] == 0:\n zero_rows.add(row) # Mark the row to be zeroed\n zero_cols.add(col) # Mark the column to be zeroed\n\n # Step 4: Update the matrix by setting cells to zero based on the marked rows and columns\n for row in range(rows):\n for col in range(cols):\n if row in zero_rows or col in zero_cols:\n matrix[row][col] = 0\n\n # Why use sets?\n # Sets provide efficient lookup and eliminate duplicates,\n # making this approach more time and space-efficient than the brute force method.\n```\n### Complexities\n- Time Complexity: O(M * N) \n- Space Complexity: O(M + N)\n\n---\n\n## Approach 3: Using Lists\nA slight variation using boolean lists instead of sets:\n```python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # Step 1: Input validation to handle edge cases (e.g., empty matrix)\n if not matrix:\n return []\n\n rows, cols = len(matrix), len(matrix[0])\n\n # Step 2: Initialize two boolean arrays to track which rows and columns need to be zeroed\n zero_row = [False] * rows\n zero_col = [False] * cols\n\n # Step 3: Iterate through the matrix to mark rows and columns that contain zero\n for row in range(rows):\n for col in range(cols):\n if matrix[row][col] == 0:\n zero_row[row] = True # Mark the entire row to be zeroed\n zero_col[col] = True # Mark the entire column to be zeroed\n\n # Step 4: Iterate through the matrix again to set the appropriate cells to zero\n for row in range(rows):\n for col in range(cols):\n # If the row or column is marked, set the cell to zero\n if zero_row[row] or zero_col[col]:\n matrix[row][col] = 0\n\n # Why use lists?\n # Lists can be more memory-efficient than sets for larger matrices,\n # while still providing O(1) lookup time.\n```\n\n### Complexities\n- Time Complexity: O(M * N) \n- Space Complexity: O(M + N)\n\n---\n\n## Approach 4: O(1) Space Solution\nThe most optimized solution uses the first row and column as markers:\n```python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n # Step 1: Initialize variables\n rows, cols = len(matrix), len(matrix[0])\n first_row_has_zero = False\n first_col_has_zero = False\n \n # Step 2: Mark zeros on the first row and column\n for row in range(rows):\n for col in range(cols):\n if matrix[row][col] == 0:\n # Mark if zero is in the first row\n if row == 0:\n first_row_has_zero = True\n # Mark if zero is in the first column\n if col == 0:\n first_col_has_zero = True\n # Use first row and column as markers\n matrix[row][0] = matrix[0][col] = 0\n\n # Step 3: Use markers to set zeros in the matrix\n for row in range(1, rows):\n for col in range(1, cols):\n if matrix[0][col] == 0 or matrix[row][0] == 0:\n matrix[row][col] = 0\n \n # Step 4: Set zeros for the first row if needed\n if first_row_has_zero:\n for col in range(cols):\n matrix[0][col] = 0\n \n # Step 5: Set zeros for the first column if needed\n if first_col_has_zero:\n for row in range(rows):\n matrix[row][0] = 0\n\n # Why use this approach?\n # This method achieves O(1) space complexity by using\n # the first row and column as markers, eliminating\n # the need for additional data structures.\n\n```\n---\n\n## Conclusion\nWe\'ve explored four different approaches to solve the Set Matrix Zeroes problem, each with its own trade-offs between simplicity, time efficiency, and space usage. The O(1) space solution is the most optimized, but it\'s also the most complex to implement and understand. When solving such problems, it\'s crucial to consider the specific requirements and constraints of your use case to choose the most appropriate solution.\n\n\n---\n\n\nI hope you found this solution to the Minimum Window Substring problem helpful! \nIf this solution helps you out in any way then don\'t forget to upvote, for such detailed solutions!\n\n![image.png](https://assets.leetcode.com/users/images/c23a8c20-5e27-4335-8cd5-fccc07f07033_1723978308.44916.png)\n\n\n\nIf you have any questions or suggestions, feel free to leave a comment below. And don\u2019t forget to check out our Blind 75 playlist [(link)](https://youtube.com/playlist?list=PLJjAsZiSomUmTfAG_zhkFTDokWoKFL4Rj&si=3Pca2h3uRfRYeGJx) for more such problem-solving techniques.\nPlaylist \n\nDSA Sheet by HackCode: [link](https://docs.google.com/spreadsheets/d/1ohxk2Hw3O9ySKvLhxMjy3mOmOxnUWMB8MV4gZELaakM/edit?usp=sharing)\n\nHappy coding! \uD83D\uDE0A
32
0
['Array', 'Hash Table', 'Matrix', 'Python3']
1
set-matrix-zeroes
[Python3] O(1) with reverse traversal
python3-o1-with-reverse-traversal-by-you-tr9y
Use the first cell of every row and column as a flag if all row or col values should be set to zeros.\nColumn with index 0 => matrix[0][j] are using like flag f
yourick
NORMAL
2023-05-11T20:13:39.248577+00:00
2024-01-23T21:29:06.461564+00:00
5,563
false
Use the first cell of every row and column as a flag if all row or col values should be set to zeros.\nColumn with index `0 => matrix[0][j]` are using like flag for `rows`.\nRow with index `0 => matrix[i][0]` are using like flag for columns.\nBut because the cell `matrix[0][0]` already are using like flag for `0` row we need to use additional flag variable `firstRowVal` to save flag for the first row.\n```python3 []\nclass Solution:\n def setZeroes(self, matrix: List[List[int]]) -> None:\n firstRowVal, R, C = 1, len(matrix), len(matrix[0])\n\n for i in range(R):\n for j in range(C):\n if matrix[i][j] == 0:\n matrix[0][j] = 0 # mark column\n if i != 0: \n matrix[i][0] = 0\n else:\n firstRowVal = 0\n \n for i in reversed(range(R)):\n for j in reversed(range(C)):\n if i == 0:\n matrix[i][j] *= firstRowVal\n elif matrix[0][j] == 0 or matrix[i][0] == 0:\n matrix[i][j] = 0\n```
27
0
['Matrix', 'Python', 'Python3']
4
set-matrix-zeroes
Javascript Fast and Simple
javascript-fast-and-simple-by-galberto80-fwtm
\nvar setZeroes = function(matrix) {\n\n var track = []\n \n // find zeros\n for(var i = 0; i < matrix.length; i++){\n for(var j = 0; j < matri
galberto807
NORMAL
2020-01-31T22:18:34.179985+00:00
2020-01-31T22:18:34.180019+00:00
3,923
false
```\nvar setZeroes = function(matrix) {\n\n var track = []\n \n // find zeros\n for(var i = 0; i < matrix.length; i++){\n for(var j = 0; j < matrix[0].length; j++){\n if(matrix[i][j] === 0) track.push([i, j]) \n }\n }\n\n for(var i = 0; i < track.length; i++){\n var [x, y] = track[i]\n \n // update row\n for(var j = 0; j < matrix[0].length; j++){\n matrix[x][j] = 0\n }\n \n // udpate column\n for(var j = 0; j < matrix.length; j++){\n matrix[j][y] = 0\n }\n\n }\n};\n```
23
0
['JavaScript']
3
set-matrix-zeroes
4 APPROACHES
4-approaches-by-pranayharishchandra-4vf4
BRUTE FORCE\n- traverse over matrix and when you find 0\n- traverse over it\'s row and col, if you encounter 1 then change it to -1\n- after traversing over who
pranayharishchandra
NORMAL
2024-05-23T08:31:14.927213+00:00
2024-05-25T04:38:40.290613+00:00
4,314
false
# BRUTE FORCE\n- traverse over matrix and when you find 0\n- traverse over it\'s row and col, if you encounter 1 then change it to -1\n- after traversing over whole matrix and finding all 0, now replace the -1 with 0\n![image.png](https://assets.leetcode.com/users/images/3a8d4c37-5edb-408c-a416-8ff5b9152ab1_1716451022.4589996.png)\n\nNOTE:\nin LeetCode this solution will fail, as -1 can be also be an element of matrix, -231 <= matrix[i][j] <= 231 - 1\nthank for correcting me **@muktadirkhan889**\n\n![image.png](https://assets.leetcode.com/users/images/ade28dbe-d5c8-4e55-af77-4fc4c49132bb_1716611698.657892.png)\n\n\n# BETTER \n- make 2 arrays to mark 0s row and col\n- this will take mxn time complexity\n- now traverse over matix and replace the 1 to 0, using row and col matrix (row[i][j] || col[i][j])\n![image.png](https://assets.leetcode.com/users/images/046f7fe8-a160-40f9-9d92-87f7d9ad6f6b_1716451169.1382115.png)\n\n# BETTER 2\n- make only 1 array of size = max(n, m)\n- as either one of row or col is true means 0 present\n- then you have to mark it in row and col both\n- so no use tracking both row and col individually\n\n# OPTIMAL \n- this solution is space optimaization of the "Better" approach.\n- this use no extra space since we are storing in the matrix itself.\n(in first row and first col of the matrix, as shown in figure)\n- just make one extra variable "col0", as matrix[0][0] can only represent either a row or a col. \n- catch with this approach is you must know the sequence to mark 1 to 0\n- the correct sequence will be:-\n - mark using : matrix[0][j], j: 1 to m\n - then mark using: matrix[i][0], i: 0 to n\n - then mark using: col0\n - in this way no information that you haven\'t used will be changed\n![image.png](https://assets.leetcode.com/users/images/27eb8741-c9e0-4dc1-b228-f4fd322a6f9c_1716452379.9213622.png)\n\n\n# Code of better\n```\n\nclass Solution\n{\npublic:\n void setZeroes(vector<vector<int>> &matrix)\n {\n\n int n = matrix.size();\n int m = matrix[0].size();\n\n vector<int> row(n, 0);\n vector<int> col(m, 0);\n\n // if we have to mark entire col to zero\n // in that case we will store 1 in the row, col \n \n // Traverse the matrix:\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n if (matrix[i][j] == 0)\n {\n // mark ith index of row wih 1:\n row[i] = 1;\n\n // mark jth index of col wih 1:\n col[j] = 1;\n }\n }\n }\n\n // Finally, mark all (i, j) as 0\n // if row[i] or col[j] is marked with 1.\n for (int i = 0; i < n; i++)\n {\n for (int j = 0; j < m; j++)\n {\n if (row[i] || col[j])\n {\n matrix[i][j] = 0;\n }\n }\n }\n }\n};\n```\n# Code for OPTIMAL\n```\nvector<vector<int>> zeroMatrix(vector<vector<int>> &matrix, int n, int m) {\n\n // int row[n] = {0}; --> matrix[..][0]\n // int col[m] = {0}; --> matrix[0][..]\n\n int col0 = 1;\n // step 1: Traverse the matrix and\n // mark 1st row & col accordingly:\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (matrix[i][j] == 0) {\n // mark i-th row:\n matrix[i][0] = 0;\n\n // mark j-th column:\n if (j != 0)\n matrix[0][j] = 0;\n else\n col0 = 0;\n }\n }\n }\n\n // Step 2: Mark with 0 from (1,1) to (n-1, m-1):\n for (int i = 1; i < n; i++) {\n for (int j = 1; j < m; j++) {\n if (matrix[i][j] != 0) {\n // check for col & row:\n if (matrix[i][0] == 0 || matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n }\n }\n\n //step 3: Finally mark the 1st col & then 1st row:\n if (matrix[0][0] == 0) {\n for (int j = 0; j < m; j++) {\n matrix[0][j] = 0;\n }\n }\n if (col0 == 0) {\n for (int i = 0; i < n; i++) {\n matrix[i][0] = 0;\n }\n }\n\n return matrix;\n}\n```\n\n## If you found my answer helpful, please consider upvoting it \u2B06\uFE0F to show your appreciation for my effort!
22
0
['C++']
4
set-matrix-zeroes
C++/Java/Python/JavaScript || ✅🚀Using Matrix and Array || ✔️🔥With Full Explanation
cjavapythonjavascript-using-matrix-and-a-vjmn
Intuition:\nWe need to modify the matrix in-place, so we can\'t use an auxiliary matrix or hash table. We can instead use the first row and first column of the
devanshupatel
NORMAL
2023-05-13T14:17:00.148959+00:00
2023-05-13T14:17:00.149004+00:00
7,722
false
# Intuition:\nWe need to modify the matrix in-place, so we can\'t use an auxiliary matrix or hash table. We can instead use the first row and first column of the original matrix as a replacement for the auxiliary array. This way, we can save the extra space required for the auxiliary arrays and also set the values in the first row and column to zero if any element in the corresponding row or column is zero.\n\n# Approach:\n1. First, the code initializes two dummy vectors, `dummyRow` and `dummyCol`, with initial values of -1. These vectors will be used to mark the rows and columns that need to be set to zero.\n2. The code then iterates through each element of the matrix and checks if it is zero. If an element is zero, it updates the corresponding indices in `dummyRow` and `dummyCol` to 0.\n3. After marking the rows and columns, the code iterates through the matrix again. For each element, it checks if the corresponding row index or column index in `dummyRow` or `dummyCol` is zero. If either of them is zero, it sets the current element to zero.\n4. Finally, the matrix will have rows and columns set to zero based on the values in `dummyRow` and `dummyCol`.\n\n# Complexity:\n- Time complexity: O(mn), where m and n are the number of rows and columns in the matrix, respectively. We have to traverse the matrix twice.\n- Space complexity: O(m+n), where m and n are the number of rows and columns in the matrix, respectively. We are using two auxiliary vectors of size m and n to keep track of the rows and columns that contain zero elements.\n\n---\n# C++\n```cpp\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int row = matrix.size();\n int col = matrix[0].size();\n vector <int> dummyRow(row,-1);\n vector<int> dummyCol(col,-1);\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(matrix[i][j]==0){\n dummyRow[i] = 0;\n dummyCol[j] = 0;\n }\n }\n }\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(dummyRow[i] == 0 || dummyCol[j] == 0 ){\n matrix[i][j]=0;\n }\n }\n }\n }\n};\n```\n\n---\n# Java\n```java\nclass Solution {\n public void setZeroes(int[][] matrix) {\n int row = matrix.length;\n int col = matrix[0].length;\n int[] dummyRow = new int[row];\n int[] dummyCol = new int[col];\n Arrays.fill(dummyRow, -1);\n Arrays.fill(dummyCol, -1);\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(matrix[i][j]==0){\n dummyRow[i] = 0;\n dummyCol[j] = 0;\n }\n }\n }\n for(int i=0;i<row;i++){\n for(int j=0;j<col;j++){\n if(dummyRow[i] == 0 || dummyCol[j] == 0 ){\n matrix[i][j]=0;\n }\n }\n }\n }\n}\n\n```\n\n---\n# Python\n```py\nclass Solution(object):\n def setZeroes(self, matrix):\n row = len(matrix)\n col = len(matrix[0])\n dummyRow = [-1] * row\n dummyCol = [-1] * col\n for i in range(row):\n for j in range(col):\n if matrix[i][j] == 0:\n dummyRow[i] = 0\n dummyCol[j] = 0\n for i in range(row):\n for j in range(col):\n if dummyRow[i] == 0 or dummyCol[j] == 0:\n matrix[i][j] = 0\n\n```\n---\n# JavaScript\n```js\nvar setZeroes = function(matrix) {\n const row = matrix.length;\n const col = matrix[0].length;\n const dummyRow = new Array(row).fill(-1);\n const dummyCol = new Array(col).fill(-1);\n for(let i=0;i<row;i++){\n for(let j=0;j<col;j++){\n if(matrix[i][j]==0){\n dummyRow[i] = 0;\n dummyCol[j] = 0;\n }\n }\n }\n for(let i=0;i<row;i++){\n for(let j=0;j<col;j++){\n if(dummyRow[i] == 0 || dummyCol[j] == 0 ){\n matrix[i][j]=0;\n }\n }\n }\n};\n\n```
21
0
['Python', 'C++', 'Java', 'JavaScript']
2
set-matrix-zeroes
Java | TC: O(R*C) | SC: O(1) | Optimized In-Place solution
java-tc-orc-sc-o1-optimized-in-place-sol-qqo9
java\n/**\n * Optimized In-Place solution\n *\n * We can use the first cell of every row and column as a flag. This flag will\n * determine whether a row or a c
NarutoBaryonMode
NORMAL
2021-10-11T03:41:37.161473+00:00
2021-10-11T03:42:33.272776+00:00
1,465
false
```java\n/**\n * Optimized In-Place solution\n *\n * We can use the first cell of every row and column as a flag. This flag will\n * determine whether a row or a column has to be set to zero.\n *\n * Time Complexity: O(2 * R * C)\n *\n * Space Complexity: O(1)\n *\n * R = Number of rows. C = Number of columns.\n */\nclass Solution {\n public void setZeroes(int[][] matrix) {\n if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {\n return;\n }\n\n int rows = matrix.length;\n int cols = matrix[0].length;\n if (rows == 1 && cols == 1) {\n return;\n }\n\n boolean isFirstColZero = false;\n for (int i = 0; i < rows; i++) {\n if (matrix[i][0] == 0) {\n isFirstColZero = true;\n }\n for (int j = 1; j < cols; j++) {\n if (matrix[i][j] == 0) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n }\n }\n }\n\n for (int i = rows - 1; i >= 0; i--) {\n for (int j = cols - 1; j >= 1; j--) {\n if (matrix[i][0] == 0 | matrix[0][j] == 0) {\n matrix[i][j] = 0;\n }\n }\n if (isFirstColZero) {\n matrix[i][0] = 0;\n }\n }\n }\n}\n```
21
0
['Array', 'Matrix', 'Java']
1
set-matrix-zeroes
Simple C++ solution|| Using extra space
simple-c-solution-using-extra-space-by-a-xgq0
If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries
anubhavbaner7
NORMAL
2021-08-04T17:56:51.875418+00:00
2021-08-04T17:56:51.875463+00:00
2,070
false
**If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n```\n void setZeroes(vector<vector<int>>& matrix) {\n int m=matrix.size();\n int n=matrix[0].size();\n vector<pair<int,int>> cor;\n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(matrix[i][j]==0)\n {\n cor.push_back({i,j});\n }\n }\n }\n for(int i=0;i<cor.size();i++)\n {\n int x=cor[i].first;\n int y=cor[i].second;\n int row=0;\n int col=0;\n while(row<m)\n {\n matrix[row][y]=0;\n row++;\n }\n while(col<n)\n {\n matrix[x][col]=0;\n col++;\n }\n }\n }\n```
21
1
['C', 'C++']
3
set-matrix-zeroes
3 sweet and simple approach. BRUTE-FORCE || OPTIMAL || PRO-OPTIMAL.
3-sweet-and-simple-approach-brute-force-tnenv
```\nclass Solution {\npublic:\n void setZeroes(vector>& v) {\n int x,y;\n \n /-------------BRUTE FORCE APPROACH-----------------/\n/
lazyfool_008
NORMAL
2021-06-18T09:06:03.408195+00:00
2021-06-18T09:06:03.408239+00:00
2,414
false
```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& v) {\n int x,y;\n \n /*-------------BRUTE FORCE APPROACH-----------------*/\n/* \n \n int m=v.size();\n int n=v[0].size();\n int temp[m][n];\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n temp[i][j]=1;\n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(v[i][j]==0)\n {\n for(int k=0;k<m;k++)\n temp[k][j]=0;\n \n for(int k=0;k<n;k++)\n temp[i][k]=0;\n }\n \n }\n \n \n }\n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(temp[i][j]==0)\n v[i][j]=temp[i][j];\n else\n v[i][j]=v[i][j];\n }\n }\n T.C =O(M*N*(M+N)) S.C=O(MN)\n */ \n \n /*-----------OPTIMAL APPROACH MAKE DUMMY ROW AND COLUMN---------*/\n \n \n /* \n int m=v.size();\n int n=v[0].size();\n int row[m];\n int col[n];\n \n for(int i=0;i<m;i++)\n row[i]=false;\n \n \n for(int i=0;i<n;i++)\n col[i]=false;\n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(v[i][j]==0)\n {\n row[i]=true;\n col[j]=true;\n }\n }\n }\n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if( row[i]==true || col[j]==true)\n {\n v[i][j]=0;\n }\n }\n }\n \n time complexity = O(N*M)\n\nSpace Complexity: O(M + N), for storing hash tables.\n\n*/\n \n /*--------------------- PRO -OPTIMAL APPROACH-----------------------*/\n int col0 = 1, rows = v.size(), cols = v[0].size();\n\n for (int i = 0; i < rows; i++) {\n if (v[i][0] == 0) col0 = 0;\n for (int j = 1; j < cols; j++)\n if (v[i][j] == 0)\n v[i][0] = v[0][j] = 0;\n }\n\n for (int i = rows - 1; i >= 0; i--) {\n for (int j = cols - 1; j >= 1; j--)\n if (v[i][0] == 0 || v[0][j] == 0)\n v[i][j] = 0;\n if (col0 == 0) v[i][0] = 0;\n \n }\n }\n};
21
1
['C']
2
set-matrix-zeroes
✅C++ Easy Solution Optimized
c-easy-solution-optimized-by-ayushsenapa-9dsx
\n\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int col0 = true;\n // int rows = sizeof(matrix)/sizeof(matrix[0
ayushsenapati123
NORMAL
2022-06-19T13:50:08.530700+00:00
2022-06-19T13:50:08.530741+00:00
1,680
false
\n```\nclass Solution {\npublic:\n void setZeroes(vector<vector<int>>& matrix) {\n int col0 = true;\n // int rows = sizeof(matrix)/sizeof(matrix[0]);\n int rows = matrix.size();\n // int cols = sizeof(matrix[0]/sizeof(matrix[0][0]));\n int cols = matrix[0].size();\n \n \n // iterate from forward\n for(int i = 0; i < rows; i++)\n {\n if(matrix[i][0]==0) col0 = false;\n for(int j = 1; j < cols; j++)\n if(matrix[i][j]==0)\n matrix[i][0] = matrix[0][j] = 0;\n }\n // iterate from backward\n for(int i = rows-1; i >= 0; i--){\n for(int j = cols-1; j >= 1; j--)\n if(matrix[i][0] == 0 || matrix[0][j] == 0)\n matrix[i][j] = 0;\n if(col0 == 0) matrix[i][0] = 0;\n }\n }\n};\n```\n**Please upvote if you find the solution useful, means a lot.**
18
0
['C', 'Matrix']
2
set-matrix-zeroes
JavaScript - Three Solutions. One is Suggested Transcribed to JS. 100%
javascript-three-solutions-one-is-sugges-hfx8
\n\n\nDoing the Blind 75 and posting all solutions.\n\nHere is the \'Suggested Solution\' transcribed to JS. Cool solution if you Have to keep constant space.
casmith1987
NORMAL
2021-09-22T00:37:05.028845+00:00
2022-03-01T20:31:29.275838+00:00
2,914
false
![image](https://assets.leetcode.com/users/images/45384296-f1fe-4288-9759-058e94dde2c9_1632272059.2179272.png)\n\n\nDoing the Blind 75 and posting all solutions.\n\nHere is the \'Suggested Solution\' transcribed to JS. Cool solution if you Have to keep constant space. A little convoluted otherwise imo.\n```\nvar setZeroes = function(matrix) {\n let isCol = false, r = matrix.length, c = matrix[0].length;\n for (let i = 0; i < r; i++) {\n if (!matrix[i][0]) isCol = true;\n for (let j = 1; j < c; j++) {\n if (!matrix[i][j]) {\n matrix[i][0] = 0;\n matrix[0][j] = 0;\n };\n }\n }\n for (let i = 1; i < r; i++) {\n for (let j = 1; j < c; j++) {\n if (!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0;\n }\n }\n if (!matrix[0][0]) {\n for (let j = 0; j < c; j++) matrix[0][j] = 0;\n }\n if (isCol) {\n for (let i = 0; i < r; i++) {\n matrix[i][0] = 0;\n }\n }\n};\n```\n\nHere is a version where we use Sets to track 0\'s. A little extra space, but not a ton. Won\'t work if interviewer challenges you to constant space though.\n```\nvar setZeroes = function(matrix) {\n const rowSet = new Set(), colSet = new Set()\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (!matrix[i][j]) {\n rowSet.add(i);\n colSet.add(j);\n };\n }\n }\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (rowSet.has(i) || colSet.has(j)) matrix[i][j] = 0\n }\n }\n};\n```\n\nHere is a version where we just deep copy the array and go to town. This is the easiest imo and gets solid time complexity (Maybe slight redoing of the recursive calls if 0\'s overwrite cells more than once.). It Is the worst on space complexity though. Just depends what they\'re looking for and if Constant Space is make or break.\n```\nvar setZeroes = function(matrix) {\n const copy = JSON.parse(JSON.stringify(matrix));\n for (let i = 0; i < matrix.length; i++) {\n for (let j = 0; j < matrix[i].length; j++) {\n if (!copy[i][j]) traverse(i, j);\n }\n }\n \n function traverse(row, col, dir = \'all\') {\n matrix[row][col] = 0;\n if (row - 1 >= 0 && (dir === \'all\' || dir === \'up\')) traverse(row - 1, col, \'up\');\n if (row + 1 <= matrix.length - 1 && (dir === \'all\' || dir === \'down\')) traverse(row + 1, col, \'down\');\n if (col - 1 >= 0 && (dir === \'all\' || dir === \'left\')) traverse(row, col - 1, \'left\');\n if (col + 1 <= matrix[row].length - 1 && (dir === \'all\' || dir === \'right\')) traverse(row, col + 1, \'right\');\n }\n};\n\n```
18
0
['JavaScript']
3
set-matrix-zeroes
Is there a better constant space solution?
is-there-a-better-constant-space-solutio-r01a
My solution is kind of hackish - accpeted. So, I want to know if there is a better constant space solution?\n\nI traverse the matrix and if I find a zero, I rep
gpraveenkumar
NORMAL
2013-12-28T00:31:44+00:00
2013-12-28T00:31:44+00:00
10,700
false
My solution is kind of hackish - accpeted. So, I want to know if there is a better constant space solution?\n\nI traverse the matrix and if I find a zero, I replace all the elements, except the 0 elements, of the corresponding row and column with -1. Finally I make all the -1 to 0.\n\nThis algorithm would fail if the matrix has -1s. \n\n void setZeroes(vector<vector<int> > &matrix) {\n \n int i,j,k,m,n;\n \n m = matrix.size();\n n = matrix[0].size();\n \n for(i=0;i<m;i++)\n for(j=0;j<n;j++)\n if(matrix[i][j]==0)\n {\n for(k=0;k<n;k++)\n if(matrix[i][k]!=0)\n matrix[i][k] = -1;\n for(k=0;k<m;k++)\n if(matrix[k][j]!=0)\n matrix[k][j] = -1;\n }\n \n for(i=0;i<m;i++)\n for(j=0;j<n;j++)\n if(matrix[i][j]==-1)\n matrix[i][j]=0; \n }
17
4
[]
10
set-matrix-zeroes
Constant Space Java solution
constant-space-java-solution-by-siyang2-ki1r
a b b \n\n b c c\n\n b c c\n\nStep1: Determine row1 and col1. Need to go through the first col and first row. Use two vars to store that information.\nStep2
siyang2
NORMAL
2014-10-29T18:03:27+00:00
2014-10-29T18:03:27+00:00
4,392
false
a b b \n\n b c c\n\n b c c\n\nStep1: Determine row1 and col1. Need to go through the first col and first row. Use two vars to store that information.\nStep2: Use "c" to determine "b". Need to go through the entire matrix. Once "c" is zero, set its corresponding two "b"s to zero.\nStep3: Use "b" to set "c". If "b" is zero, its corresponding row or col are set to all zero.\nStep4: Use previous row1 and col1 information to set col1 and row1.\n\n public class Solution {\n public void setZeroes(int[][] matrix) {\n boolean firstColZero = false, firstRowZero = false;\n for(int i = 0;i < matrix.length;i++)\n if(matrix[i][0] == 0)\n firstColZero = true;\n for(int j = 0;j < matrix[0].length;j++)\n if(matrix[0][j] == 0)\n firstRowZero = true;\n for(int i = 1;i < matrix.length;i++)\n for(int j = 1;j < matrix[0].length;j++)\n if(matrix[i][j] == 0)\n matrix[i][0] = matrix[0][j] = 0;\n for(int i = 1;i < matrix.length;i++)\n if(matrix[i][0] == 0)\n for(int j = 0;j < matrix[0].length;j++)\n matrix[i][j] = 0;\n for(int j = 1;j < matrix[0].length;j++)\n if(matrix[0][j] == 0)\n for(int i = 0;i < matrix.length;i++)\n matrix[i][j] = 0;\n if(firstColZero)\n for(int i = 0;i < matrix.length;i++)\n matrix[i][0] = 0;\n if(firstRowZero)\n for(int j = 0;j < matrix[0].length;j++)\n matrix[0][j] = 0;\n \n }\n }
17
2
['Java']
3
set-matrix-zeroes
Very Short Python Solution with O(1) Space Complexity. 13 Lines of Code.
very-short-python-solution-with-o1-space-9ii8
Idea is as follow:\nIts only necessary to find out which row and column contains 0. After this step, change all elements in certain row and column to 0. If no 0
sktgater
NORMAL
2017-02-02T18:51:16.353000+00:00
2018-09-18T20:12:44.305593+00:00
2,431
false
Idea is as follow:\nIts only necessary to find out which row and column contains 0. After this step, change all elements in certain row and column to 0. If no 0 exists, do nothing.\n\n```\n# Two sets that record which row and column has 0\nrowSet = set()\ncolSet = set()\n# Iterate each element. \n# If it is 0, record row and column number\nfor r in range(len(matrix)):\n for c in range(len(matrix[0])):\n if matrix[r][c] == 0:\n rowSet.add(r)\n colSet.add(c)\n# Change all rows containing 0 to 0\nfor r in rowSet:\n for c in range(len(matrix[0])):\n matrix[r][c] = 0\n# Change all columns containing 0 to 0\nfor c in colSet:\n for r in range(len(matrix)):\n matrix[r][c] = 0\n```
17
10
[]
5
set-matrix-zeroes
Quiet simple answer, \u2018hacking\u2019 with javascript
quiet-simple-answer-u2018hackingu2019-wi-84pb
var setZeroes = function(matrix) {\n\n var r = matrix.length;\n var l = matrix[0].length;\n for (var i = 0; i < r; i++) {\n for (var j = 0; j <
handsomeone
NORMAL
2016-04-06T07:46:06+00:00
2016-04-06T07:46:06+00:00
2,165
false
var setZeroes = function(matrix) {\n\n var r = matrix.length;\n var l = matrix[0].length;\n for (var i = 0; i < r; i++) {\n for (var j = 0; j < l; j++) {\n if (matrix[i][j] === 0 && 1 / matrix[i][j] === Infinity) {\n for (var x = 0; x < r; x++) {\n matrix[x][j] = matrix[x][j] && -0;\n }\n for (var y = 0; y < l; y++) {\n matrix[i][y] = matrix[i][y] && -0;\n }\n }\n }\n }\n\n};
16
2
[]
6
set-matrix-zeroes
PYTHON || OPTIMAL SOLUTION 🔥 || EASY TO UNDERSTAND ||
python-optimal-solution-easy-to-understa-3k7a
if it\'s help, please up \u2B06vote!\u2764\uFE0F and comment\uD83D\uDD25\n# Intuition\n Describe your first thoughts on how to solve this problem. \n- When we e
Adit_gaur
NORMAL
2024-06-30T14:54:45.824272+00:00
2024-06-30T14:54:45.824306+00:00
1,447
false
# if it\'s help, please up \u2B06vote!\u2764\uFE0F and comment\uD83D\uDD25\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- When we encounter a zero in the matrix, the entire row and column containing that zero need to be set to zero. This can be efficiently tracked using two sets, one for rows and one for columns. By recording the rows and columns that should be zeroed in the first pass, we can then set the respective rows and columns to zero in the second and third passes.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Initialization:\n - Create two sets, zero_rows and zero_cols, to store the indices of rows and columns that contain zeros.\n- First Pass:\n - Traverse the matrix to identify all elements that are zero.\nAdd the row index to zero_rows and the column index to zero_cols whenever a zero is encountered.\n- Second Pass:\n - For each row in zero_rows, set all elements in that row to zero.\n- Third Pass:\n - For each column in zero_cols, set all elements in that column to zero.\n- This ensures that all rows and columns that should be zeroed are correctly updated.\n# Complexity\n- Time complexity: O(n\xD7m), where \uD835\uDC5B is the number of rows and \uD835\uDC5A is the number of columns. This is because we traverse the entire matrix once to find zeros and then make another pass to set the rows and columns to zero.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n+m), due to the additional space used by the zero_rows and zero_cols sets to store the indices of rows and columns that need to be zeroed.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def setZeroes(self, matrix):\n """\n :type matrix: List[List[int]]\n :rtype: None Do not return anything, modify matrix in-place instead.\n """\n rows, cols = len(matrix), len(matrix[0])\n zero_rows, zero_cols = set(), set()\n\n # First pass: record the rows and columns that are to be zeroed\n for i in range(rows):\n for j in range(cols):\n if matrix[i][j] == 0:\n zero_rows.add(i)\n zero_cols.add(j)\n\n # Second pass: set the rows to zero\n for row in zero_rows:\n for j in range(cols):\n matrix[row][j] = 0\n\n # Third pass: set the columns to zero\n for col in zero_cols:\n for i in range(rows):\n matrix[i][col] = 0\n```\n![7c17f983-3b8b-4738-b722-c1c1466f9510_1682940288.2823734.jpeg](https://assets.leetcode.com/users/images/fdd4b3ca-1523-4645-84fd-83c4d986faec_1719759119.0720453.jpeg)\n
14
0
['Array', 'Hash Table', 'Matrix', 'Python', 'Python3']
3