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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
count-subarrays-with-median-k | Python short solution | Counter of difference | python-short-solution-counter-of-differe-ghty | \ndef countSubarrays(self, nums: List[int], k: int) -> int:\n\tcount, idx = Counter([0]), nums.index(k)\n\tans = d = 0\n\tfor i in range(len(nums)):\n\t\td -= ( | vincent_great | NORMAL | 2022-11-27T06:24:41.538765+00:00 | 2022-11-27T06:28:03.017606+00:00 | 47 | false | ```\ndef countSubarrays(self, nums: List[int], k: int) -> int:\n\tcount, idx = Counter([0]), nums.index(k)\n\tans = d = 0\n\tfor i in range(len(nums)):\n\t\td -= (nums[i]<k)\n\t\td += (nums[i]>k)\n\t\tif i<idx:\n\t\t\tcount[d] += 1\n\t\telse:\n\t\t\tans += (count[d]+count[d-1])\n\treturn ans\n``` | 1 | 0 | [] | 0 |
count-subarrays-with-median-k | Python3 Solution With Freq Table | python3-solution-with-freq-table-by-mota-48lu | \n\n# Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(N)\n Add your space complexity here, e.g. O(n) \n\n | Motaharozzaman1996 | NORMAL | 2022-11-27T04:48:27.058774+00:00 | 2022-11-27T04:48:27.058806+00:00 | 106 | false | \n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def countSubarrays(self, nums: List[int], k: int) -> int:\n idx,freq,prefix = nums.index(k), Counter(), 0\n for i in reversed(range(idx+1)): \n prefix += int(nums[i] > k) - int(nums[i] < k)\n freq[prefix] += 1\n res= prefix = 0 \n for i in range(idx, len(nums)): \n prefix += int(nums[i] > k) - int(nums[i] < k)\n res += freq[-prefix] + freq[-prefix+1]\n return res \n``` | 1 | 0 | ['Python', 'Python3'] | 0 |
count-subarrays-with-median-k | [Java] Use Map or Array to count the number of smaller/larger items around k | java-use-map-or-array-to-count-the-numbe-325w | Intuition\nThe idea is straightforwar, we just need to find k first, and count the number of smaller/larger items around it.\n\n# Approach\n1. Find the index of | wddd | NORMAL | 2022-11-27T04:21:40.672699+00:00 | 2022-11-27T04:21:40.672739+00:00 | 372 | false | # Intuition\nThe idea is straightforwar, we just need to find k first, and count the number of smaller/larger items around it.\n\n# Approach\n1. Find the index of k\n2. Count the number of smaller/larger items on one side of k\n3. Count the number of smaller/larger items on the other side (and calculate the result at the same time)\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n\nSolution 1: use a map to maintain the counts.\n```\nclass Solution {\n\n /*\n Runtime 43 ms Beats 80%\n Memory 71.8 MB Beats 40%\n\n Use a map to maitian the counts. \n */\n public int countSubarrays(int[] nums, int k) {\n int ind = 0;\n for (ind = 0; ind < nums.length; ind++) {\n if (nums[ind] == k) {\n break;\n }\n }\n\n Map<Integer, Integer> diffCount = new HashMap<>();\n int diff = 0;\n for (int i = ind; i < nums.length; i++) {\n if (nums[i] > k) {\n diff++;\n } else if (nums[i] < k) {\n diff--;\n }\n diffCount.put(diff, diffCount.getOrDefault(diff, 0) + 1);\n }\n\n int count = diffCount.get(0) + diffCount.getOrDefault(1, 0);\n diff = 0;\n for (int i = ind - 1; i >= 0; i--) {\n if (nums[i] > k) {\n diff++;\n } else if (nums[i] < k) {\n diff--;\n }\n count += diffCount.getOrDefault(-diff, 0);\n count += diffCount.getOrDefault(1 - diff, 0);\n }\n\n return count;\n }\n}\n```\n\nSolution 2: use an array to maintain the counts. Faster but less intuitive. The idea is the same.\n```\nclass Solution {\n\n /*\n Runtime 6 ms Beats 100%\n Memory 71.8 MB Beats 40%\n */\n public int countSubarrays(int[] nums, int k) {\n int ind = 0;\n for (ind = 0; ind < nums.length; ind++) {\n if (nums[ind] == k) {\n break;\n }\n }\n\n int[] diffs = new int[nums.length + 2];\n\n int diff = 0;\n for (int i = ind; i < nums.length; i++) {\n if (nums[i] > k) {\n diff++;\n } else if (nums[i] < k) {\n diff--;\n }\n diffs[k + diff]++;\n }\n\n int count = diffs[k] + diffs[k + 1];\n diff = 0;\n for (int i = ind - 1; i >= 0; i--) {\n if (nums[i] > k) {\n diff++;\n } else if (nums[i] < k) {\n diff--;\n }\n if (k - diff >= 0 && k - diff < diffs.length) {\n count += diffs[k - diff];\n }\n if (k - diff + 1 >= 0 && k - diff + 1 < diffs.length) {\n count += diffs[k - diff + 1];\n }\n }\n\n return count;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | [C++] easy unordered Map | c-easy-unordered-map-by-mble6125-5mzk | Intuition\n1. All desired subarray should include k.\n2. For a desired subarray A:\n Let x be the number of element greater than k.\n Let y be the number of | mble6125 | NORMAL | 2022-11-27T04:01:38.141978+00:00 | 2022-11-27T04:01:38.142018+00:00 | 504 | false | # Intuition\n1. All desired subarray should include k.\n2. For a desired subarray A:\n Let x be the number of element greater than k.\n Let y be the number of element lower than k.\n x - y should be 0 or 1.\n\nThese two observations conclude following algorithm.\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int target=0, res=1;\n unordered_map<int,int> record;\n\n // k itself\n record[0]=1;\n \n // find position of k in nums\n for (; target<nums.size(); ++target)\n if (nums[target]==k) break;\n \n // left side\n for (int i=target-1, cur=0; i>=0; --i) {\n if (nums[i]>k) ++cur;\n else --cur;\n \n ++record[cur];\n if (cur==0 || cur==1) ++res;\n }\n \n // right side\n for (int i=target+1, cur=0; i<nums.size(); ++i) {\n if (nums[i]>k) ++cur;\n else --cur;\n\n res+=record[-cur]+record[-cur+1]; \n }\n \n return res;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
count-subarrays-with-median-k | [Java] Prefix Sum + HashMap | O(N) | Detailed Math Explanation | java-prefix-sum-hashmap-on-detailed-math-wslz | Define:\n- int pivot: where nums[pivot] == k\n- Prefix sum array smaller: where smaller[i+1] is the number of m so that nums[m] < k and 0 <= m <= i <= nums.leng | jjeeffff | NORMAL | 2022-11-27T04:01:37.026244+00:00 | 2022-11-27T04:31:52.662050+00:00 | 924 | false | Define:\n- int `pivot`: where `nums[pivot] == k`\n- Prefix sum array `smaller`: where `smaller[i+1]` is the number of `m` so that `nums[m] < k` and `0 <= m <= i <= nums.length`.\n\nGoal: count the number of `(i, j)` pairs where `0 <= i <= pivot <= j <= nums.length` and `smaller[j+1] - smaller[i] == (j - i) / 2`.\n\nLet\'s do some basic transposition:\n```\nsmaller[j+1] - smaller[i] == (j - i) / 2\n2 * (smaller[j+1] - smaller[i]) == (j - i) or (j - i - 1)\n2 * smaller[j+1] - j == (2 * smaller[i] - i) or (2 * smaller[i] - i - 1)\n```\n\nWe find some pattern here, so define\n```\nstatistic[i] = 2 * smaller[i] - i\n```\nthen the formula becomes\n```\nstatistic[j+1] + 1 == (statistic[i]) or (statistic[i] - 1)\n```\n\nUse a map to store the count of each `statistic[i]`, where `0 <= i <= pivot`. And for each `j` where `pivot <= j <= nums.length`, add both `map.get(statistic[j+1] + 1)` and `map.get(statistic[j+1] + 2)` to the output.\n\n``` java\nclass Solution {\n public int countSubarrays(int[] nums, int k) {\n int n = nums.length;\n int[] smaller = new int[n + 1]; // smaller[i + 1]: number of elements smaller than k in nums[0...i]\n int pivot = -1; // nums[pivot] == k\n for (int i = 0; i < n; i++) {\n smaller[i + 1] = smaller[i];\n if (nums[i] < k) {\n smaller[i + 1]++;\n } else if (nums[i] == k) {\n pivot = i;\n }\n }\n Map<Integer, Integer> map = new HashMap<>(); // statistics count map\n for (int i = 0; i <= pivot; i++) {\n int statistic = 2 * smaller[i] - i;\n map.put(statistic, map.getOrDefault(statistic, 0) + 1);\n }\n int count = 0;\n for (int j = pivot; j < n; j++) {\n int statistic = 2 * smaller[j + 1] - j;\n count += map.getOrDefault(statistic, 0);\n count += map.getOrDefault(statistic + 1, 0);\n }\n return count;\n }\n}\n``` | 1 | 0 | ['Math', 'Prefix Sum', 'Java'] | 0 |
count-subarrays-with-median-k | [c++] O(n) | c-on-by-hujc-dzju | \nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n // for the definision of median in this problem,\n // suppose su | hujc | NORMAL | 2022-11-27T04:00:48.047557+00:00 | 2022-11-27T04:02:04.632254+00:00 | 522 | false | ```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n // for the definision of median in this problem,\n // suppose subarray A meets the condition\n \n // there are two cases\n // 1. odd number length: median(A) == k --> {x > k} - {x < k} == 0\n // 2. even number length: median(A) == k --> {x > k} - {x < k} == 1\n \n // We need to find subarrays that contains k that meet the above two cases\n // How? We count the diff ({x > k} - {x < k}) from k for all index to its left and right\n // And we try to find the corresponding right part for all left part.\n int m = nums.size();\n int i = 0;\n for (int j = 0; j < m; ++j) {\n if (nums[j] == k) {\n i = j;\n break;\n }\n }\n \n // count of {x > k} - {x < k}\n unordered_map<int, int> left, right;\n left[0] = 1;\n right[0] = 1;\n \n int cnt = 0;\n for (int j = i-1; j >= 0; --j) {\n if (nums[j] < k) cnt--;\n else cnt++;\n left[cnt]++;\n }\n \n cnt = 0;\n for (int j = i+1; j < m; ++j) {\n if (nums[j] < k) cnt--;\n else cnt++;\n right[cnt]++;\n }\n \n\n int res = 0;\n for (auto &p: left) {\n // case 1\n auto it = right.find(0 - p.first);\n if (it != right.end()) res += p.second * it->second;\n \n // case 2\n it = right.find(1 - p.first);\n if (it != right.end()) res += p.second * it->second;\n }\n \n return res;\n }\n};\n``` | 1 | 0 | [] | 0 |
count-subarrays-with-median-k | c++ using map | c-using-map-by-mss2-oybz | IntuitionApproachComplexity
Time complexity:O(n)
Space complexity:O(n)
Code | MSS2 | NORMAL | 2025-02-11T20:54:40.589374+00:00 | 2025-02-11T20:54:40.589374+00:00 | 7 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:$$O(n)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:$$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int countSubarrays(vector<int>& nums, int k) {
int n=nums.size();
int index=-1;
for(int i=0;i<n;i++)
{
if(nums[i]==k)
{
index=i;
nums[i]=0;
}
else if(nums[i]<k)
{
nums[i]=-1;
}
else nums[i]=1;
}
if(index==-1) return 0;
unordered_map<int,int>prefix_sum;
int sum=0;
prefix_sum[0]=1;
for(int i=index-1;i>=0;i--)
{
sum+=nums[i];
prefix_sum[sum]++;
}
sum=0;
int count=0;
for (int i = index; i < n; i++) {
sum += nums[i];
count += prefix_sum[-sum] + prefix_sum[-sum + 1];
}
return count;
}
};
``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | O(N) Python step-by-step solution with explanation comments | on-python-step-by-step-solution-with-exp-tbsy | Complexity
Time complexity:
O(N)
Space complexity:
O(N)
Code | nikalinov | NORMAL | 2025-02-06T11:16:44.930842+00:00 | 2025-02-06T11:23:41.250972+00:00 | 10 | false | # Complexity
- Time complexity:
O(N)
- Space complexity:
O(N)
# Code
```python3 []
class Solution:
def countSubarrays(self, nums: List[int], k: int) -> int:
ind_k = nums.index(k)
# subarrays to the left of index with calculated diff between
# bigger and smaller numbers as keys
# eg [2, 5, 4 <- k] would have sub_left = {0: 2 (4 itself and [2,5,4]), 1: 1}
sub_left = defaultdict(int)
sub_left[0] = 1
sub_right = defaultdict(int)
sub_right[0] = 1
nums_bigger = nums_smaller = 0
for ind in range(ind_k - 1, -1, -1):
if nums[ind] > k:
nums_bigger += 1
else:
nums_smaller += 1
diff = nums_bigger - nums_smaller
sub_left[diff] += 1
nums_bigger = nums_smaller = 0
for ind in range(ind_k + 1, len(nums)):
if nums[ind] > k:
nums_bigger += 1
else:
nums_smaller += 1
diff = nums_bigger - nums_smaller
sub_right[diff] += 1
count = 0
# diff between sub_left and sub_right keys is the difference between
# differences of smaller and bigger numbers on both sides
# so that there will be balance between numbers bigger and smaller
# in the whole subarray. EG
# [2, 5, 4, 6], sub_left = {0: 2, 1: 1}, sub_right = {0: 1, 1: 1}
# left key 0 and count 2 means we have [*nothing*, 4] and [2, 5, 4] as left side
# subarrays with balanced number of bigger and smaller numbers.
# We can "concatenate" it only with right-side subarrays where balance is
# either the same (0) or is bigger by 1 (1).
# That means in the whole subarray, after sorting all elements
# k will stand either in the middle of the array (balance 0)
# or as the middle left (left side subarray has x bigger elements,
# right side subarray contains x + 1 bigger elements).
# for [2, 5, 4, 6]:
# left_diff = 0, target_diff is 0 or 1
# eg for [*nothing*] and [2,5,4] we have [*nothing*] and [6]
# concatenated correct subarrays: [*nothing*, 4, *nothing*],
# [*nothing*, 4, 6], [2, 5, 4, *nothing*], [2, 5, 4, 6]
# for left_diff = 1, target_diff -1 or 0.
# we dont have -1 meaning there are no subarrays to the right
# where number of smaller elements - 1 = number of bigger elements
# for target_diff = 0 [*nothing*] applies.
# correct subarray: [5, 4, *nothing*]
# finally apply multiplication rule - every left side subarray can be
# concatenated with every applicable right side part.
for left_diff, left_count in sub_left.items():
target_diff_0 = -left_diff
target_diff_1 = -left_diff + 1
diff_1 = sub_right[target_diff_1]
diff_0 = sub_right[target_diff_0]
# multiplication rule
count += left_count * diff_1 + left_count * diff_0
return count
``` | 0 | 0 | ['Python3'] | 0 |
count-subarrays-with-median-k | Hash table solution [EXPLAINED] | hash-table-solution-explained-by-r9n-och5 | IntuitionFind subarrays where the median is equal to a given value k. Instead of sorting every subarray, we use a balance approach to track the number of elemen | r9n | NORMAL | 2024-12-26T06:01:31.844302+00:00 | 2024-12-26T06:01:31.844302+00:00 | 5 | false | # Intuition
Find subarrays where the median is equal to a given value k. Instead of sorting every subarray, we use a balance approach to track the number of elements greater or smaller than k, which helps us efficiently calculate the median.
# Approach
I've traversed the array, adjust a balance value based on whether elements are greater or less than k, and store the balance frequencies in a hash map; when we reach or pass k, we count subarrays where the balance matches the condition for k to be the median.
# Complexity
- Time complexity:
O(n), where n is the number of elements in the array, since we only traverse the array once and perform constant time operations for each element.
- Space complexity:
O(n), due to the hash map storing balances and counts for each element during the traversal.
# Code
```csharp []
using System;
using System.Collections.Generic;
public class Solution
{
public int CountSubarrays(int[] nums, int k)
{
int n = nums.Length;
int count = 0;
int[] memo = new int[n];
Array.Fill(memo, -1); // Initialize memoization array
// Step 1: Use two-pointer approach and prefix sum to track the balance
Dictionary<int, int> balanceMap = new Dictionary<int, int>();
balanceMap[0] = 1; // Initial balance to count subarrays from index 0
int balance = 0;
int kIndex = Array.IndexOf(nums, k); // Find the index of k
// Step 2: Traverse the array and maintain balance
for (int i = 0; i < n; i++)
{
// Step 3: Adjust balance based on comparison with k
if (nums[i] > k)
balance++;
else if (nums[i] < k)
balance--;
// Step 4: If we have passed or reached the position of k, count subarrays
if (i >= kIndex)
{
// Calculate subarrays where balance matches, meaning k is the median
if (balanceMap.ContainsKey(balance))
count += balanceMap[balance];
if (balanceMap.ContainsKey(balance - 1))
count += balanceMap[balance - 1];
}
else
{
// Store balance counts before reaching k
if (!balanceMap.ContainsKey(balance))
balanceMap[balance] = 0;
balanceMap[balance]++;
}
}
return count;
}
}
``` | 0 | 0 | ['Array', 'Hash Table', 'Prefix Sum', 'C#'] | 0 |
count-subarrays-with-median-k | Count Subarrays With Median K | count-subarrays-with-median-k-by-naeem_a-yszf | null | Naeem_ABD | NORMAL | 2024-12-12T04:50:24.249561+00:00 | 2024-12-12T04:50:24.249561+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n# Keypoint\nAll numbers are distinct. So there is only one k in nums\nbalanced: if an array is balanced(count(moreK) - count(lessK) == 0 or 1) and contains k, it is a valid subarray.\nsplit array with k. If left side and right side combined are balanced, the array has median k\n3.1 First calculate balance of right side, record balance-count in a hashtable. Then calculate balance of left side, find count of balanced right side and add it to the result.\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```golang []\nfunc countSubarrays(nums []int, k int) int {\n n := len(nums)\n cnt := map[int]int{}\n p := -1\n for i, num := range nums {\n if num == k {\n p = i\n break\n }\n }\n bal := 0\n for i := p; i < n; i++ {\n if nums[i] == k {\n bal += 0\n } else if nums[i] < k {\n bal -= 1\n } else {\n bal += 1\n }\n if _, ok := cnt[bal]; !ok {\n cnt[bal] = 1\n } else {\n cnt[bal]++\n }\n }\n res := 0\n bal = 0\n for i := p; i >= 0; i-- {\n if nums[i] == k {\n bal += 0\n } else if nums[i] < k {\n bal -= 1\n } else {\n bal += 1\n }\n res += cnt[-bal] + cnt[-bal+1]\n }\n return res\n}\n``` | 0 | 0 | ['Go'] | 0 |
count-subarrays-with-median-k | C++ | Map + Prefix sum | c-map-prefix-sum-by-kena7-58qv | \nclass Solution {\npublic:\n #define ll long long int\n int countSubarrays(vector<int>& nums, int k) \n {\n int n=nums.size(),s=-1;\n fo | kenA7 | NORMAL | 2024-12-01T10:21:27.830993+00:00 | 2024-12-01T10:21:27.831022+00:00 | 3 | false | ```\nclass Solution {\npublic:\n #define ll long long int\n int countSubarrays(vector<int>& nums, int k) \n {\n int n=nums.size(),s=-1;\n for(int i=0;i<n;i++)\n {\n if(nums[i]==k)\n {\n nums[i]=0;\n s=i;\n }\n else if(nums[i]>k)\n nums[i]=1;\n else\n nums[i]=-1;\n }\n if(s==-1)\n return 0;\n ll rsum=0,lsum=0;\n unordered_map<ll,int>m;\n for(int i=s;i<n;i++)\n {\n rsum+=nums[i];\n m[rsum]++;\n }\n int res=0;\n for(int i=s;i>=0;i--)\n {\n lsum+=nums[i];\n res+=m[0L-lsum];\n res+=m[1L-lsum];\n }\n return res;\n }\n};\n``` | 0 | 0 | [] | 0 |
count-subarrays-with-median-k | C++ Simple Well Commented Code : O(N) | c-simple-well-commented-code-on-by-nites-66wn | Code\ncpp []\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n= nums.size();\n\n unordered_map<int,int> um;\n | niteshkumartiwari | NORMAL | 2024-12-01T04:50:05.953683+00:00 | 2024-12-01T04:50:05.953707+00:00 | 8 | false | # Code\n```cpp []\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n= nums.size();\n\n unordered_map<int,int> um;\n um[0] = 1; // zero sum happended once.\n bool found = false;\n int sum =0;\n int result=0;\n\n for(int num : nums) {\n if(num < k) {\n sum -=1;\n }else if(num > k) {\n sum +=1;\n } else {\n found = true;\n }\n\n if(found) {\n /* Median for\n 1. Odd length subarray -> #LessElement +1 = #GreaterElement\n 2. Even length subarray -> #LessElement == #GreaterElement\n */\n result += um[sum] + um[sum-1];\n }else{\n /*\n Always want k to be included and map is only used to find the left boundary\n hence only inserting into the map when element is not found.\n */\n um[sum]++;\n }\n }\n\n return result;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Java BEATS 100% | java-beats-100-by-alexander_sergeev-zsk1 | 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 | alexander_sergeev | NORMAL | 2024-10-29T17:08:00.350062+00:00 | 2024-10-29T17:08:00.350095+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int countSubarrays(int[] nums, int k) {\n int length = nums.length;\n int pos = 0;\n for (int i = 0; i < length; i++) {\n if (nums[i] == k) {\n pos = i;\n break;\n }\n }\n int[] arr = new int[length * 2 + 1];\n int answer = 1;\n int count = 0;\n for (int i = pos + 1; i < length; i++) {\n count += nums[i] > k ? 1 : -1;\n if (count >= 0 && count <= 1) {\n answer++;\n }\n arr[count + length]++;\n }\n count = 0;\n for (int i = pos - 1; i >= 0; i--) {\n count += nums[i] > k ? 1 : -1;\n if (count >= 0 && count <= 1) {\n answer++;\n }\n answer += arr[-count + length] + arr[-count + 1 + length];\n }\n return answer;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | Counting Subarrays with Median Equal to k Using Balance Map | Beats 100% ✅✅ | counting-subarrays-with-median-equal-to-xpqw4 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Balance Calculation: Traverse the array and maintain a balance variabl | Sahnawas | NORMAL | 2024-10-28T09:52:04.205408+00:00 | 2024-10-28T09:52:04.205437+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Balance Calculation: Traverse the array and maintain a balance variable:\n - Increment balance by +1 for elements greater than k.\n - Decrement balance by -1 for elements less than k.\n\n2. Tracking Prefix Balances: Use a Map to track occurrences of each balance value before reaching k.\n3. Counting Valid Subarrays: After encountering k, count valid subarrays by checking if the current balance or balance - 1 existed in the map before k.\n4. Result: Sum up counts for all valid subarrays and return the result.\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```javascript []\nfunction countSubarrays(nums, k) { // Renamed function to match the expected name\n let n = nums.length;\n let balance = 0;\n let count = 0;\n let balanceMap = new Map();\n balanceMap.set(0, 1); // Initialize with balance 0, to count subarrays starting from index 0.\n\n let kIndex = nums.indexOf(k);\n \n // Traverse the array\n for (let i = 0; i < n; i++) {\n // Adjust balance based on the current element\n if (nums[i] > k) {\n balance += 1;\n } else if (nums[i] < k) {\n balance -= 1;\n }\n \n // If we\'ve reached k, calculate potential subarrays with k as median\n if (i >= kIndex) {\n // Check counts for subarrays ending here with balances needed for k to be median\n count += (balanceMap.get(balance) || 0) + (balanceMap.get(balance - 1) || 0);\n } else {\n // Store balance count before reaching k to check in the future\n balanceMap.set(balance, (balanceMap.get(balance) || 0) + 1);\n }\n }\n\n return count;\n}\n\n\n``` | 0 | 0 | ['JavaScript'] | 0 |
count-subarrays-with-median-k | Python (Simple Hashmap) | python-simple-hashmap-by-rnotappl-bc5s | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rnotappl | NORMAL | 2024-10-27T08:22:13.476721+00:00 | 2024-10-27T08:22:13.476752+00:00 | 15 | 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```python3 []\nclass Solution:\n def countSubarrays(self, nums, k):\n n, dict1, running_sum, contains_k, count = len(nums), defaultdict(int), 0, False, 0 \n\n for i in range(n):\n if nums[i] > k:\n running_sum += 1 \n elif nums[i] < k:\n running_sum += -1 \n else:\n running_sum += 0\n contains_k = True \n\n if contains_k:\n if running_sum == 0 or running_sum == 1:\n count += 1 \n if running_sum in dict1:\n count += dict1[running_sum]\n if running_sum-1 in dict1:\n count += dict1[running_sum-1]\n else:\n dict1[running_sum] += 1 \n\n return count \n``` | 0 | 0 | ['Python3'] | 0 |
count-subarrays-with-median-k | C++, O(n) | c-on-by-samaun37-86ty | 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 | samaun37 | NORMAL | 2024-10-20T19:34:04.527415+00:00 | 2024-10-20T19:34:04.527448+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countSubarrays(vector<int>& a, int k) {\n int n = a.size();\n int pref[n+5];\n pref[0] = 0;\n map<int,int>mp;\n mp[0]++;\n int ans = 0;\n bool isKPassed = false;\n for(int i = 0;i<n;i++){\n pref[i+1] = pref[i];\n if(a[i]<k) pref[i+1]--;\n else if(a[i]>k) pref[i+1]++;\n else isKPassed = true;\n if(isKPassed){\n ans+=mp[pref[i+1]];\n ans+=mp[pref[i+1]-1];\n // cout<<i+1<<" "<<pref[i+1]<<" "<<mp[pref[i+1]]<<" "<<mp[pref[i+1]-1]<<endl;\n }\n \n if(!isKPassed)mp[pref[i+1]]++;\n }\n return ans;\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Easy Map Solution | easy-map-solution-by-kvivekcodes-ecxz | 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 | kvivekcodes | NORMAL | 2024-10-09T11:27:22.050339+00:00 | 2024-10-09T11:27:22.050366+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n int ind;\n for(int i = 0; i < n; i++){\n if(nums[i] == k){\n ind = i;\n break;\n }\n }\n int ans = 1;\n\n map<int, int> mp;\n mp[0]++;\n int smaller = 0, larger = 0;\n for(int i = ind-1; i >= 0; i--){\n if(nums[i] > k) larger++;\n else smaller++;\n\n if(smaller == larger || smaller+1 == larger) ans++;\n mp[smaller-larger]++;\n }\n\n\n smaller = 0, larger = 0;\n for(int i = ind+1; i < n; i++){\n if(nums[i] > k) larger++;\n else smaller++;\n\n ans += mp[larger-smaller];\n ans += mp[larger-smaller-1];\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Hash Table', 'C++'] | 0 |
count-subarrays-with-median-k | C++ Solution with T.C :- O(N) and S.C :- O(N). | c-solution-with-tc-on-and-sc-on-by-adity-elyb | \nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n=nums.size(),ind_k;\n for(int i=0;i<n;++i){\n if | adityarupda2002 | NORMAL | 2024-10-04T11:05:23.206855+00:00 | 2024-10-04T11:05:23.206880+00:00 | 2 | false | ```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n=nums.size(),ind_k;\n for(int i=0;i<n;++i){\n if(nums[i]==k) ind_k=i;\n }\n vector<int> a(n);\n a[ind_k]=0;\n for(int i=0;i<n;++i){\n if(i!=ind_k){\n if(nums[i]<k) a[i]=-1;\n else a[i]=1;\n }\n }\n unordered_map<int,int> mp;\n int ans=0,s=0;\n for(int ed=ind_k;ed<n;++ed){\n s+=a[ed];\n mp[s]++;\n }\n s=0;\n for(int st=ind_k;st>=0;--st){\n s+=a[st];\n ans+=mp[-1*s];\n ans+=mp[-1*s+1];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Hash Table', 'C', 'Prefix Sum'] | 0 |
count-subarrays-with-median-k | C++ | c-by-tinachien-vb0n | \nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n unordered_map<int,int>odd;\n unord | TinaChien | NORMAL | 2024-09-21T04:32:11.373919+00:00 | 2024-09-21T04:32:11.373952+00:00 | 1 | false | ```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n unordered_map<int,int>odd;\n unordered_map<int,int>even;\n even[0] = 1;\n int ret = 0;\n int presum = 0;\n for(int i = 0; i < n; i++){\n if(nums[i] == k)\n nums[i] = 0;\n else if(nums[i] > k)\n nums[i] = 1;\n else\n nums[i] = -1;\n }\n for(int i = 0; i < nums.size(); i++){\n presum += nums[i];\n //if(item is odd)\n if(i % 2 == 0){\n //len is odd\n ret += even[presum];\n ret += odd[presum-1];\n odd[presum]++;\n }\n else{\n ret += odd[presum];\n ret += even[presum-1];\n even[presum]++;\n }\n }\n return ret;\n }\n};\n``` | 0 | 0 | [] | 0 |
count-subarrays-with-median-k | Prefix sum && Hash table. O(n) Beats 100%. | prefix-sum-hash-table-on-beats-100-by-15-drfj | Intuition\n Describe your first thoughts on how to solve this problem. \n- Hint1\nFirstly, we need to tanslate the question to an easier one. \nThere are number | 1504658251 | NORMAL | 2024-08-27T00:04:56.148176+00:00 | 2024-08-27T00:41:19.864171+00:00 | 51 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Hint1\nFirstly, we need to tanslate the question to an easier one. \nThere are numbers from 1 to n, but we have a \'k\', so these numbers are in three classes which are strickly grater than k, k and strictly smaller than k.\nChange the three classes to 1, 0 ans -1.\n- Hint2\nAfter the change, the property that the subarray with median k is its sum equal to either 0 or 1.\n- Hint3 \nSo, the question is translated to count the number of subarrays of nums. And the subarray is non-empty, sum equal to 1 or 0 and must have \'k\'.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nOK, after translating, think about which data structer could finish this problem efficiently.\n\n---\n\n1. Bingo, it\'s prefix sum and hash table.\nBut we also need a tag to mark whether we have meet \'k\' or not.\n2. Before we meet \'k\', we only update the hash table which store the prefix sum count.\n3. After we meet \'k\', we do not update hash table but just update the ans by checking the hash table.\n# Complexity\nWe can update the prefix sum, hash table and ans only traverse arrays once. \n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nPrefix sum could be stored in a value because we just need the current prefix to update info. So it\'s the hash table which costs O(n) space complexity.\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size(), s = 0, ans = 0;\n bool tag = false;\n unordered_map<int, int> cnt{{0, 1}};\n for (int i = 0; i < n; ++i) {\n nums[i] > k ? ++s : (nums[i] < k ? --s : tag = true);\n if (!tag) {\n ++cnt[s];\n } else {\n cnt.contains(s) ? ans += cnt[s] : 0;\n cnt.contains(s - 1) ? ans += cnt[s - 1] : 0;\n }\n }\n return ans;\n }\n};\n```\n```python []\nclass Solution:\n def countSubarrays(self, nums: List[int], k: int) -> int:\n s = ans = 0\n tag = False\n cnt = defaultdict(int)\n cnt[0] = 1\n for x in nums:\n if x > k:\n s += 1\n elif x < k:\n s -= 1\n else:\n tag = True\n\n if tag == False:\n cnt[s] += 1\n else:\n ans += cnt[s]\n ans += cnt[s - 1]\n return ans\n```\n```Go []\nfunc countSubarrays(nums []int, k int) (ans int) {\n s, tag := 0, false\n cnt := map[int]int{0 : 1}\n for _, x := range nums {\n if x > k {\n s++\n } else if x < k {\n s--\n } else {\n tag = true\n }\n\n if (!tag) {\n cnt[s]++\n } else {\n ans += cnt[s]\n ans += cnt[s - 1]\n }\n }\n return \n}\n```\n | 0 | 0 | ['Array', 'Hash Table', 'Prefix Sum', 'C++', 'Go', 'Python3'] | 0 |
count-subarrays-with-median-k | most simple c++ solution just using the hashmap balancing diff on both the sides of median | most-simple-c-solution-just-using-the-ha-knh4 | 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 | Kronos_1066 | NORMAL | 2024-07-28T10:20:34.946222+00:00 | 2024-07-28T10:20:34.946255+00:00 | 14 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n\n int n = nums.size();\n int index = -1;\n for(int i = 0 ; i < n ; i++){\n if(nums[i] == k){\n index = i;\n }\n }\n\n if(index == -1){\n return -1;\n }\n\n unordered_map<int,int> mpp;\n int diff = 0;\n mpp[0] = 1;\n\n for(int i = index+1 ; i < n ; i++){\n if(nums[i] > k) diff++;\n else if(nums[i] < k) diff--;\n mpp[diff]++;\n }\n\n diff = 0;\n int ans = 0;\n for(int i = index ; i >= 0 ; i--){\n if(nums[i] > k) diff--;\n else if(nums[i] < k) diff++;\n ans += mpp[diff];\n ans += mpp[diff+1];\n }\n\n\n return ans;\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Java PrefixSum soln | java-prefixsum-soln-by-vharshal1994-sqco | 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 | vharshal1994 | NORMAL | 2024-07-26T15:23:08.240883+00:00 | 2024-07-26T15:23:08.240913+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n /**\n 1) For odd size subarray, for k to be median, we check if we find subarray \n such that count of elements that are less than k is equal to \n count of elements that are more than k.\n Eg: 1 5 4 with median as 4. Post sorting, it becomes 1 4 5\n\n 2) For even size subarray, for k to be median, we check if we find subarray \n such that count of elements that are less than k + 1 is equal to \n count of elements that are more than k.\n Eg: 1 5 6 4 with median as 4. Post sorting, it becomes 1 4 5 6\n \n so it doesnt matter what is the value of each element. What matters is whether\n the value is greater than k or lesser than k.\n\n So we treat value > k as 1, < k as -1 and == k as 0.\n We then have array reduced to 1s, -1s and 0\n\n for k to be median, we check if subarray contains element k and\n sum of subarray is 0. This will ensure condition 1)\n for k to be median, we check if subarray contains element k and\n sum of subarray is 1. This will ensure condition 2)\n\n Because we are looking for all subarrays which include k, we first find out\n all the subarrays starting from number k, such that suffix sum is either 0 or 1.\n We store the suffix sum in hashmap and count of its occurrences.\n\n We also need to look for subarrays that start before. In those cases, we need to \n see that sum of numbers totally comes to either 0 or 1. It will be 0 in case of\n odd subarray because of condition 1). All -1s and all 1s cancel out thereby sum is 0\n It will be 1 in case of even subarray because of condition 2). There will be 1 more 1s\n as compared to -1s, thereby sum will be 1.\n\n So We look for all the prefixes such that (0 - prefixSum) is present in hashmap\n because prefixSum + 0 + suffixSum = 0 in case of odd subarray with median k\n\n We look for all the prefixes such that (1 - prefixSum) is present in hashmap\n because prefixSum + 0 + suffixSum = 1 in case of even subarray with median k\n */\n\n public int countSubarrays(int[] nums, int k) {\n int kIndex = 0;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] == k) {\n kIndex = i;\n break;\n }\n }\n\n int suffixSum = 0;\n HashMap<Integer, Integer> suffixSumCounter = new HashMap<>();\n // count all subarrays starting from k such that sum is 0 or 1\n for (int i = kIndex; i < nums.length; i++) {\n if (nums[i] > k) {\n suffixSum += 1; \n } else if (nums[i] == k) {\n suffixSum += 0; \n } else {\n suffixSum += -1; \n }\n \n suffixSumCounter.put(suffixSum, suffixSumCounter.getOrDefault(suffixSum, 0) + 1);\n }\n // System.out.println(suffixSumCounter);\n\n int ans = 0;\n // count all subarrays starting from k such that sum is 0 for odd length subarray\n ans += suffixSumCounter.getOrDefault(0, 0);\n // count all subarrays starting from k such that sum is 1 for even length subarray\n ans += suffixSumCounter.getOrDefault(1, 0);\n\n int prefixSum = 0;\n // count all subarrays starting before k such that total sum is 0 or 1\n for (int i = kIndex - 1; i >= 0; i--) {\n if (nums[i] > k) {\n prefixSum += 1; \n } else {\n prefixSum += -1;\n }\n // System.out.println(prefixSum + " " + i);\n // count all subarrays starting before k such that sum is 0 for odd length subarray\n if (suffixSumCounter.containsKey(0 - prefixSum)) {\n ans += suffixSumCounter.get(0 - prefixSum);\n } \n // count all subarrays starting before k such that sum is 1 for even length subarray\n if (suffixSumCounter.containsKey(1 - prefixSum)) {\n ans += suffixSumCounter.get(1 - prefixSum);\n }\n }\n\n return ans;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | Python (Simple Hashmap) | python-simple-hashmap-by-rnotappl-rxlm | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | rnotappl | NORMAL | 2024-07-16T10:15:16.294259+00:00 | 2024-07-16T10:15:16.294286+00:00 | 5 | 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 countSubarrays(self, nums, k):\n running_sum, count, dict1, found = 0, 0, defaultdict(int), False\n\n for i in nums:\n if i > k:\n running_sum += 1 \n elif i < k:\n running_sum -= 1 \n else:\n found = True \n\n if found and (running_sum == 0 or running_sum == 1):\n count += 1 \n\n if found:\n count += dict1[running_sum] + dict1[running_sum-1]\n else:\n dict1[running_sum] += 1\n \n return count\n``` | 0 | 0 | ['Python3'] | 0 |
count-subarrays-with-median-k | Optimal way to find the total no. of subarray with a given median | optimal-way-to-find-the-total-no-of-suba-4m5l | Intuition\nIn this implementation, we start by locating the index of the median (k) in the array. Then, we traverse forward and backward from this index, using | tasniatahsin | NORMAL | 2024-06-22T22:50:53.169968+00:00 | 2024-06-22T22:50:53.169987+00:00 | 6 | false | # Intuition\nIn this implementation, we start by locating the index of the median (k) in the array. Then, we traverse forward and backward from this index, using a diff variable to track differences between counts of elements greater than k and less than k. We store these differences in a map.\n# Approach\nBest Approach to find the subarrays with a median.\n\n# Complexity\n- Time complexity:\no(n)\n\n- Space complexity:\no(n)\n\n# Code\n```\nvar countSubarrays = function(nums, k) {\n let right = new Map(); \n let diff = 0, idx = 0, cnt = 0;\n let n = nums.length;\n\n for (let i = 0; i < n; i++) {\n if (nums[i] === k) {\n idx = i;\n break;\n }\n }\n\n right.set(0, 1);// for median\n\n \n for (let i = idx + 1; i < n; i++) {\n if (nums[i] > k) {\n diff++;\n } else {\n diff--;\n }\n if (right.has(diff)) {\n right.set(diff, right.get(diff) + 1);\n } else {\n right.set(diff, 1);\n }\n }\n diff = 0;\n \n cnt += right.get(0 - diff) || 0; \n cnt += right.get(1 - diff) || 0; \n\n \n for (let i = idx - 1; i >= 0; i--) {\n if (nums[i] > k) {\n diff++;\n } else {\n diff--;\n }\n cnt += right.get(0 - diff) || 0; \n cnt += right.get(1 - diff) || 0; \n }\n\n return cnt;\n};\n``` | 0 | 0 | ['Array', 'Hash Table', 'JavaScript'] | 0 |
count-subarrays-with-median-k | C++ Simple || Hash Map || Commented for better understanding | c-simple-hash-map-commented-for-better-u-54t4 | 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 | rajatm17 | NORMAL | 2024-05-28T11:20:57.246758+00:00 | 2024-05-28T11:20:57.246789+00:00 | 9 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int target_index;\n int n = nums.size();\n\n // Find the index of the target element \'k\'\n for (int i = 0; i < n; i++) {\n if (nums[i] == k) {\n target_index = i;\n break; // Exit loop once we find \'k\'\n }\n }\n\n // Map to store the frequency of prefix sums on the right side of the target\n unordered_map<int, int> right;\n\n int diff = 0;\n\n // Calculate prefix sums for the subarray to the right of the target\n for (int i = target_index + 1; i < n; i++) {\n if (nums[i] > k) diff++;\n else diff--;\n\n right[diff]++;\n }\n\n // Include the case where the subarray sum is exactly zero (balanced)\n right[0]++;\n\n diff = 0;\n int cnt = 0;\n\n // Check for subarrays starting exactly at the target index\n cnt += (right.find(0 - diff) != right.end() ? right[0 - diff] : 0);\n cnt += (right.find(1 - diff) != right.end() ? right[1 - diff] : 0);\n\n // Calculate prefix sums for the subarray to the left of the target\n for (int i = target_index - 1; i >= 0; i--) {\n if (nums[i] > k) diff++;\n else diff--;\n\n // Add valid subarrays found on the right that match the current prefix sum\n cnt += right[1 - diff];\n cnt += right[-diff];\n }\n\n return cnt;\n }\n};\n\n``` | 0 | 0 | ['Hash Table', 'C++'] | 0 |
count-subarrays-with-median-k | Clear Explanation | Clean Code | O(n) | Java | clear-explanation-clean-code-on-java-by-6ohpx | Intuition\n Describe your first thoughts on how to solve this problem. \nCount the elements less than k and greater than k.\nif they are equal or only differ by | f20180991 | NORMAL | 2024-05-01T11:24:37.651952+00:00 | 2024-05-01T11:24:37.651984+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCount the elements less than k and greater than k.\nif they are equal or only differ by 1 then we can say that the median is k.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLoop through the array until you find the element k. \ninitialise a variable count to 0\nIf you find an element less than k, decrease the value of count\nIf you find an element greater than k, increase the value of count\n\nAt each step store how many times count has occured in a map.\n\nDo the above steps till we find element k.\n\nAfter findning k, continue incrementing/decrementing count based on nums[i], but you need not store the value in map.\nWe need to have value of count in target subarray to be either 0 or 1(for even case)\nSo check if the either count or count-1 is present in the map and if found add its value to ans.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countSubarrays(int[] nums, int k) {\n Map<Integer, Integer> mp = new HashMap<>();\n int i=0;\n int cnt=0;\n mp.put(0, 1);\n while(i<nums.length && nums[i]!=k)\n {\n if(nums[i]<k)cnt--;\n else cnt++;\n mp.put(cnt, mp.getOrDefault(cnt, 0)+1);\n i++;\n }\n if(i==nums.length)return 0;\n int ans=0;\n while(i<nums.length)\n {\n if(nums[i]<k)cnt--;\n else if(nums[i]>k) cnt++;\n i++;\n if(mp.get(cnt) != null)\n ans += mp.get(cnt);\n if(mp.get(cnt-1) != null)\n ans += mp.get(cnt-1);\n }\n return ans;\n\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | Simple Solution | Hash Table | Counting | C++ | simple-solution-hash-table-counting-c-by-p5e4 | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst thought that comes to mind is to find the median k, then expand the array to left | 131477097 | NORMAL | 2024-03-05T14:18:59.251955+00:00 | 2024-03-05T14:18:59.251989+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst thought that comes to mind is to find the median `k`, then expand the array to left and right from the position of `k` and count the number of subarrays based on the number of less and greater `k` elements. This way is not feasible or more complicated to code and ineffective.\n\nAnother way is to divide the array into two subarrays with `k` axis and count the number of elements on both sides then calculate the result.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nInitially, the input array always had a subarray that only has an element `k`, so declare the variable `count = 1`. Two variables `prex` to count values less than `k` and `suff` to count values greater than `k`. One variable `i` is used to specify the position of `k`.\n\nThe median of an array divides that array into two parts. The left part includes values less than the median and the right part includes values greater than the median. To be the median, for the array of even length, the number of elements in the right part is one unit greater than the number of elements in the left part and for the array with odd length, the number of elements in the left part must be equal to the right part.\n\nProvided that there must be `k` in the subarrays, start the two loops over the left and right parts from the `k` position with order `k - 1` and `k + 1` first, corresponding. For each element, compare with `k` to determine whether it is to the left or right side of the median and calculate `diff = suff - prex`.\n```\nif(num < k) ++prex; else if(num > k) ++suff;\n```\nIf `diff == 0` or `diff == 1`, `count` is increased by one. If subarrays have the same `diff`, the number of subarrays of that type is increased by one.\n\nThe `count` of arrays at this point is all subarrays located on one side of the median `k`.\n\nFor subarrays with the same `diff`, try finding the `diff` value on the other side such that the sum of `diff` equals to 1 or 0.\n\nFor example, in the right part there are subarrays with `suff = 4` and `prex = 2`, so `diff = 4 - 2 = 2`; in the left part there are subarrays with `suff = 2` and `prex = 4` so `diff = 2 - 4 = -2 `; the sum of `diff` is 2 + (-2) = 0, which also means `suff == prex`, the number of elements to the left less than `k` equals to the number of elements to the right of the median, it represents the subarrays have odd lengths. Same with `diff` sum equal to 1.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n auto countSubarrays(vector<int>& nums, int k) -> int{\n //\n int count = 1, prex = 0, suff = 0, i, diff;\n //\n std::unordered_map<int, int> left, right;\n //\n for(i = 0; i < nums.size(); i++) if(nums[i] == k) break;\n //\n for(int l = i - 1; l > -1; l--) {\n //\n if(nums[l] < k) ++prex; else if(nums[l] > k) ++suff;\n //\n diff = suff - prex;\n left[diff]++;\n //\n if(diff == 1 || diff == 0) ++count;\n }\n //\n prex = 0; suff = 0;\n //\n for(int r = i + 1; r < nums.size(); r++) {\n //\n if(nums[r] < k) ++prex; else if(nums[r] > k) ++suff;\n //\n diff = suff - prex;\n right[diff]++;\n //\n if(diff == 1 || diff == 0) ++count;\n }\n //\n for(const auto& e: left) {\n //\n if(right[1 - e.first]) count += e.second * right[1 - e.first];\n if(right[0 - e.first]) count += e.second * right[0 - e.first];\n }\n //\n return count;\n }\n};\n``` | 0 | 0 | ['Hash Table', 'Counting', 'C++'] | 0 |
count-subarrays-with-median-k | [Java] HashMap | explanation | comment | java-hashmap-explanation-comment-by-hesi-iyf8 | Intuition\nThe crucial observation is that in even-sized arrays, the median is the left middle element, not the average of the middle two. This implies that for | hesicheng20 | NORMAL | 2024-02-13T21:37:34.803750+00:00 | 2024-02-13T21:37:34.803772+00:00 | 14 | false | # Intuition\nThe crucial observation is that in even-sized arrays, the median is the left middle element, not the average of the middle two. This implies that **for a subarray to have a median of k, it must necessarily include k**. Additionally, for k to be the median, the count of elements greater than k should equal or exceed by one the count of elements less than k.\n# Approach\nThe solution begins by locating k in the array. We then track the "balance" on each side of k, where balance is defined as the number of elements greater than k minus the number of elements smaller than k. Iterating over the balance from the left side and utilizing a HashMap for the right side, we efficiently count the subarrays where the total balance is 0 or 1, indicating k is the median.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.HashMap;\n\nclass Solution {\n // Finds the first occurrence of the target element in the array, returning -1 if not found.\n private static int getIndexOf(int[] nums, int target) {\n for (int i = 0; i < nums.length; i++) {\n if (target == nums[i]) {\n return i;\n }\n }\n return -1;\n }\n\n public int countSubarrays(int[] nums, int k) {\n final int n = nums.length;\n final int indexOfK = getIndexOf(nums, k);\n\n // Arrays to track the "balance" on each side of k, where balance is defined as\n // the number of elements greater than k minus the number of elements smaller than k.\n var left = new int[indexOfK + 1]; // left[i]: nums[indexOfK-i:indexOfK]\n var right = new int[n - indexOfK]; // right[i]: nums[indexOfK+1:indexOfK+i+1]\n\n var rightMap = new HashMap<Integer, Integer>(); // Maps balance values to their frequency on the right\n\n for (int i = 1; i < indexOfK + 1; i++) {\n if (nums[indexOfK - i] < k) {\n left[i] = left[i - 1] - 1;\n } else {\n left[i] = left[i - 1] + 1;\n }\n }\n\n for (int i = 1; i < n - indexOfK; i++) {\n if (nums[indexOfK + i] < k) {\n right[i] = right[i - 1] - 1;\n } else {\n right[i] = right[i - 1] + 1;\n }\n rightMap.put(right[i], rightMap.getOrDefault(right[i], 0) + 1);\n }\n\n int ans = 0;\n\n for (int i = 0; i < indexOfK + 1; i++) {\n \n // Directly include subarrays ending at k with a balance of 0 or 1\n if (left[i] == 0 || left[i] == 1) {\n ans += 1;\n }\n\n // Find subarrays that start at indexOfK-i and have a total balance of 0 or 1\n ans += rightMap.getOrDefault(-left[i], 0);\n ans += rightMap.getOrDefault(-left[i] + 1, 0);\n }\n\n return ans;\n\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | C++ | O(N) | EASY | c-on-easy-by-goku_2022-yg67 | 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 | goku_2022 | NORMAL | 2024-01-17T11:03:56.574709+00:00 | 2024-01-17T11:03:56.574731+00:00 | 11 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n class Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n // int n=nums.size();\n // int ind=-1;\n // for(int i=0;i<n;i++)if(nums[i]==k)ind=i;\n // if(ind==-1)return -1;\n // unordered_map<int,int>map;\n // int diff=0;\n // map[0]++;\n // for(int i=ind+1;i<n;i++){\n // if(nums[i]>k)diff++;\n // else if(nums[i]<k) diff--;\n // map[diff]++;\n // }\n // diff=0;\n // int ans=0;\n // for(int i=ind;i>=0;i--){\n // if(nums[i]>k)diff++;\n // else if(nums[i]<k) diff--;\n // ans+=map[0-diff];\n // ans+=map[1-diff];\n // }\n // return ans;\n map<int,int>mp;\n int d=0,ans=0,i=-1;\n for(int ik=0;ik<nums.size();ik++)if(nums[ik]==k)i=ik;\n if(i==-1)return -1;\n for(int ik=i+1;ik<nums.size();ik++){\n if(nums[ik]<k){\n d--;\n }\n else{\n d++;\n }\n mp[d]++;\n }\n mp[0]++;\n d=0;\n\n for(int ik=i;ik>=0;ik--){\n if(nums[ik]>k)d++;\n else if(nums[ik]<k) d--;\n ans+=mp[0-d];\n ans+=mp[1-d];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Solution | solution-by-penrosecat-ze91 | Intuition\n Describe your first thoughts on how to solve this problem. \nFrom the definition in the problem, the median is always an element of the array. So an | penrosecat | NORMAL | 2024-01-12T13:21:30.281527+00:00 | 2024-01-12T13:21:30.281547+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFrom the definition in the problem, the median is always an element of the array. So any array where the median is k must always have the element k in it.\n\nSo we start from the single element k. Now we want to find all the subarrays containing this element which have k as the median.\n\nSince we have to do this in O(n) due to n = 10^5, I thought of finding all possible left ends and right ends and multiplying the compatible ends.\n\nEvery other element in the array is either < k or > k. So when we go left we find say x elements < k and y elements > k.\n\nNow for this left element we are interested in right elements that upto which exactly as many elements < k and > k such that the total elements above and below k are identical or there is one element greater than k, in both cases k is the median of the array.\n\nSo essentially for every left element only the difference x-y matters. After we know x-y, we want to find a right element such that the difference between lower and higher elements to k upto that element is exactly y-x or y-x-1. \n\nSo we save the count each difference value in a map, one each for left and right end of the subarray. Iterate over all possible difference values in left, and find matching difference values in the right map. Add the product of the count of each to the answer.\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 countSubarrays(vector<int>& nums, int k) {\n unordered_map<int,int> left;\n unordered_map<int,int> right;\n\n int k_pos = 0;\n\n for(int i = 0; i<nums.size(); i++)\n {\n if(nums[i] == k)\n {\n k_pos = i;\n break;\n }\n }\n\n int lower = 0;\n int higher = 0;\n\n for(int i = k_pos; i>=0; i--)\n {\n if(nums[i] > k)\n {\n higher++;\n }\n else if(nums[i] < k)\n {\n lower++;\n }\n\n left[lower-higher]++;\n }\n\n lower = 0;\n higher = 0;\n\n for(int i = k_pos; i<nums.size(); i++)\n {\n if(nums[i] > k)\n {\n higher++;\n }\n else if(nums[i] < k)\n {\n lower++;\n }\n\n right[lower-higher]++;\n }\n\n int subarrays = 0;\n\n for(auto ele : left)\n {\n int left_diff = ele.first;\n\n if(right.find(-left_diff) != right.end())\n {\n subarrays += ele.second * right[-left_diff];\n }\n\n if(right.find(-left_diff-1) != right.end())\n {\n subarrays += ele.second * right[-left_diff-1];\n }\n }\n\n return subarrays;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Map || Checking sum of Greater and smaller on both sides | map-checking-sum-of-greater-and-smaller-m13i4 | \n\n# Code\n\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n unordered_map<int,int> mp;\n int ind = 0;\n f | szoro | NORMAL | 2023-12-15T07:23:23.956293+00:00 | 2023-12-15T07:23:23.956311+00:00 | 5 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n unordered_map<int,int> mp;\n int ind = 0;\n for(int i=0;i<nums.size();i++){\n if(nums[i]==k)ind=i;\n }\n int gs = 0,ans=0;\n for(int i=ind;i<nums.size();i++){\n if(nums[i]>k)gs++;\n else if(nums[i]<k)gs--;\n mp[gs]++;\n }\n gs = 0;\n for(int i=ind;i>=0;i--){\n if(nums[i]>k)gs++;\n else if(nums[i]<k)gs--;\n ans+=mp[-gs]+mp[-gs+1];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Prefix and Suffix Scores to Track Numbers Greater and Smaller than k.Time: O(n), Space: O(n) | prefix-and-suffix-scores-to-track-number-fd1a | class Solution(object):\n def countSubarrays(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n | iitjsagar | NORMAL | 2023-11-10T23:43:43.734391+00:00 | 2023-11-10T23:43:43.734417+00:00 | 2 | false | class Solution(object):\n def countSubarrays(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n """\n \n prefix_dict = {0:1}\n sufix_dict = {0:1}\n n = len(nums)\n \n for i,x in enumerate(nums):\n if x == k:\n pos = i\n break\n \n cur = 0\n for i in range(pos-1,-1,-1):\n if nums[i] < k:\n cur -= 1\n else:\n cur += 1\n \n if cur not in prefix_dict:\n prefix_dict[cur] = 0\n \n prefix_dict[cur] += 1\n \n \n cur = 0\n for i in range(pos+1,n):\n if nums[i] < k:\n cur -= 1\n else:\n cur += 1\n \n if cur not in sufix_dict:\n sufix_dict[cur] = 0\n \n sufix_dict[cur] += 1\n \n \n #print prefix_dict, sufix_dict\n res = 0\n \n for key,val in prefix_dict.items():\n if -key in sufix_dict:\n res += val*sufix_dict[-key]\n \n if 1-key in sufix_dict:\n res += val*sufix_dict[1-key]\n \n #print res\n return res\n\n \n | 0 | 0 | [] | 0 |
count-subarrays-with-median-k | Prefix sum Solution , fastest than 95 % of cpp user. | prefix-sum-solution-fastest-than-95-of-c-tc8c | 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 | leminhl1412 | NORMAL | 2023-11-08T05:49:23.788307+00:00 | 2023-11-08T05:49:23.788332+00:00 | 13 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n#define ll long long\nconst ll INF = 1e18 + 7;\nconst ll MAXN = 1e5 + 7;\nint n ;\nint a[MAXN];\nll greaterCount(int m) {\n vector<int> s(2 * n + 1);\n int sum = n;\n ll result = 0;\n s[sum] = 1;\n ll add = 0;\n for(int i = 1 ; i <= n ; i ++){\n if (a[i] < m)\n sum--, add -= s[sum];\n else\n add += s[sum], sum++;\n result += add;\n s[sum]++;\n }\n return result;\n}\nclass Solution {\npublic:\n ll countSubarrays(vector<int>& nums, int k) {\n n = nums.size();\n for(int i = 1 ; i <= n ; i ++){\n a[i] = nums[i - 1];\n } \n return greaterCount(k) - greaterCount(k + 1);\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | O(n): Hash Map solution. | on-hash-map-solution-by-thisnameisorigin-tb29 | Intuition\n Describe your first thoughts on how to solve this problem. \nFor the number \'k\' to be median, the number of elements greater than \'k\' and less t | thisNameIsOriginal | NORMAL | 2023-08-24T05:05:55.362040+00:00 | 2023-08-24T05:05:55.362074+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFor the number \'k\' to be median, the number of elements greater than \'k\' and less than \'k\' should differ by either 0 or 1.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPick an index to the left of the number \'k\', and check that to how many indexes on right of \'k\' can be extend the subarray to. We will also need to include subarrays that remain entirely towards left and right of \'k\'.\n\nWe need to maintain the balance between the numbers greater and less than \'k\'. If we know that on the left the balance is \'x\', then we can extend the subarray towards right to those indexes that give us the overall balance of 0 or 1. In other words, if the balance on the right is \'-x\' or \'1-x\', then the overall balance would be 0 or 1.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\npublic class Solution {\n public int CountSubarrays(int[] nums, int k) {\n Dictionary<int,int> record = new();\n int n = nums.Length;\n // Find position of \'k\' in the array.\n int pos = Array.FindIndex(nums, (a) => a == k);\n // Balance measures the difference b/w the count of numbers greater than and less than \'k\'. \n // Balance should be either 0 or 1 for the subarray to be valid.\n int balance = 0;\n // Set count to 1 because an array with only the number \'k\' is a valid subarray.\n int count = 1;\n // The loop makes a record of all the subarrays from \'pos\' to \'i\', and how far is \'k\' from the median position.\n for(int i=pos+1;i<n;i++) {\n if (nums[i] < k) balance--;\n else balance++;\n // This records subarrays that only extend on the right of pos.\n if (balance == 0 || balance == 1) count++;\n if (!record.ContainsKey(balance)) record.Add(balance,0);\n record[balance]++;\n }\n \n\n balance = 0;\n // The loop tries to extend the subarray towards left, and checks in how many ways we can extend towards right\n // so that balance is either 0 or 1.\n for(int i=pos-1;i>=0;i--) {\n if (nums[i] < k) balance--;\n else balance++;\n // This records subarrays that only extend on the left of pos.\n if (balance == 0 || balance == 1) count++;\n // This records subarrays that only extend from left to right.\n count+= record.GetValueOrDefault(-balance) + record.GetValueOrDefault(1 - balance);\n }\n \n return count;\n }\n}\n``` | 0 | 0 | ['Hash Table', 'C#'] | 0 |
count-subarrays-with-median-k | Used vector instead of Hashmap. O(n) solution. | used-vector-instead-of-hashmap-on-soluti-h8mk | Intuition\nThe approach is same as used by many people in the solutions section. This is just a modification of that only with better complexity. So please go t | Ishita_ggn | NORMAL | 2023-08-23T17:03:20.604323+00:00 | 2023-08-23T17:03:20.604355+00:00 | 14 | false | # Intuition\nThe approach is same as used by many people in the solutions section. This is just a modification of that only with better complexity. So please go through the hashmap approach before coming here.\n\n# Approach 1 (using hashmap)\nPoint to note: For ```k``` to be the median, ```k``` must be in the subarray. Let ```medianInd=index of median```. So we will be going towards left from the median and towards right from the median. Moving towards left: ```sum``` would be storing relative value of no. of values smaller than ```k``` and no. of values greater than ```k```. ```sum++``` if ```nums[i]>k``` and ```sum--``` if ```nums[i]<k```. Store these ```sum``` values in a map. \n\nLet us say no. of values less than k = ```L``` and no. of values greater than k = ```R```. \n\nNow we will be Moving towards right: ```ans``` would be incremented if ```mp[-sum]``` (subarray size=odd) is present -> this means if R-L (assuming R>L in this case and sum(in map) = R-L) is present on the left, then we have a counter L-R on the right ```or``` map[-(sum-1)] (subarray size==even) is present.\n\nI know this is a bit complex to understand but just give it a dry run and you would surely understand.\n\n* Give a thought to why we iterated from ```medianInd``` and not only ```medianInd-1``` (on left) and ```medianInd+1``` (on right). I am leaving it on you to brainstorm.\uD83D\uDE09 \nDo comment if you got it.\n\n# Code (Using Hashmap)\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n=nums.size();\n\n int medianInd=-1;\n for(int i=0;i<n;i++){\n if(nums[i]==k){\n medianInd=i;\n }\n }\n\n map<int,int> mp;\n int sum=0;\n for(int i=medianInd;i>=0;i--){\n if(nums[i]>k){\n sum++;\n }\n if(nums[i]<k){\n sum--;\n }\n mp[sum]++;\n }\n\n int ans=0;\n sum=0;\n for(int i=medianInd;i<n;i++){\n if(nums[i]>k){\n sum++;\n }\n if(nums[i]<k){\n sum--;\n }\n\n ans+=(mp[-sum]+mp[-(sum-1)]);\n }\n \n return ans;\n }\n};\n```\n\n\n# Approach 2 (Without hashmap)\nAs we know our sum can only lie between -n to +n, i.e. ```-n<=sum<=n```.\nSo, we created a vector of size ```2*n + 1``` to store the ```sum``` occurences.\nNow every key value in map is kind of ```shifted by +n``` in vector. \nThat\'s the reason we used ```v[sum+n]``` instead of ```mp[sum]```, ```v[-sum+n]``` instead of ```mp[-sum]``` and ```v[-(sum-1)+n]``` instead of ```mp[-(sum-1)]```.\nAnd that\'s it\uD83D\uDE00.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n=nums.size();\n\n int medianInd=-1;\n for(int i=0;i<n;i++){\n if(nums[i]==k){\n medianInd=i;\n }\n }\n\n vector<int> v(2*n+1,0); // earlier map was used but as we know -n<=sum<=n, so we used a vector. Every key of i will now be at i+n.\n int sum=0;\n for(int i=medianInd;i>=0;i--){\n if(nums[i]>k){\n sum++;\n }\n if(nums[i]<k){\n sum--;\n }\n v[sum+n]++; //mp[sum]++\n }\n\n int ans=0;\n sum=0;\n for(int i=medianInd;i<n;i++){\n if(nums[i]>k){\n sum++;\n }\n if(nums[i]<k){\n sum--;\n }\n\n ans+=(v[-sum+n]+v[-(sum-1)+n]); //ans+=(mp[-sum]+mp[-(sum-1)]);\n }\n \n return ans;\n }\n};\n```\n\n**I hope I was able to clear this Leetcode question to you. Please do upvote if you understood.**\n | 0 | 0 | ['Array', 'C++'] | 0 |
count-subarrays-with-median-k | Unordered Map || C++ | unordered-map-c-by-scrapernerd-qpqv | 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 | ScraperNerd | NORMAL | 2023-07-28T14:45:43.480374+00:00 | 2023-07-28T14:45:43.480400+00:00 | 24 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& v, int k) {\n int index;\n int n=v.size();\n for(int i=0;i<n;i++){\n if(v[i]==k){\n index=i;\n break;\n }\n }\n int res=0;\n int sum=0;\n unordered_map<int,int>m;\n for(int i=index+1;i<n;i++){\n if(v[i]>k) sum++;\n else if(v[i]<k) sum--;\n m[sum]++;\n }\n m[0]++;\n sum=0;\n for(int i=index;i>=0;i--){\n if(v[i]>k) sum--;\n else if(v[i]<k) sum++;\n if(m.count(sum)) res+=m[sum];\n if(m.count(sum+1)) res+=m[sum+1]; \n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | prefix sum || variant of subarray with sum k | prefix-sum-variant-of-subarray-with-sum-bsv3y | \nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n=nums.size();\n int sum=0;\n int pivot;\n int | Arbazmalik | NORMAL | 2023-07-19T12:45:06.038515+00:00 | 2023-07-19T12:45:06.038532+00:00 | 11 | false | ```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n=nums.size();\n int sum=0;\n int pivot;\n int count=0;\n map<int,int> mpp;\n mpp[0]=1;\n vector<int> arr(n,0);\n for(int i=0;i<n;i++)\n {\n if(nums[i]<k)\n arr[i]=-1;\n if(nums[i]>k)\n arr[i]=1;\n if(nums[i]==k)\n {pivot =i;\n }\n }\n vector<int>prefix(n,0);\n for(int i=0;i<pivot;i++)\n {\n sum+=arr[i];\n mpp[sum]+=1;\n \n }\n sum-=arr[pivot];\n for(int i=pivot;i<n;i++)\n {\n sum+=arr[i];\n count += mpp[sum];\n count += mpp[sum-1];\n }\n return count;\n //finding subarray with total sum=0\n \n // subarray with total sum= -1.\n }\n};\n``` | 0 | 0 | [] | 1 |
count-subarrays-with-median-k | C++ solution based on hints | c-solution-based-on-hints-by-vvhack-2tiw | \nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n int kIdx = -1;\n for (int i = 0; i < n; ++i) {\n | vvhack | NORMAL | 2023-07-04T21:49:42.610177+00:00 | 2023-07-04T21:49:42.610194+00:00 | 5 | false | ```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n int kIdx = -1;\n for (int i = 0; i < n; ++i) {\n if (nums[i] == k) kIdx = i;\n nums[i] = (nums[i] == k) ? 0 : ((nums[i] < k) ? -1 : 1);\n }\n vector<int> cumSums;\n vector<int> cumSumFreq(n + k + 1, 0);\n int cumSum = 0;\n for (int i = 0; i < n; ++i) {\n cumSum += nums[i];\n cumSums.push_back(cumSum);\n if (i >= kIdx) {\n cumSumFreq[cumSum + k]++;\n }\n }\n int tot = 0;\n int s = 0;\n for (int i = 0; i <= kIdx; ++i) {\n tot += cumSumFreq[s + 1 + k];\n tot += cumSumFreq[s + k];\n s = cumSums[i];\n }\n return tot;\n }\n};\n``` | 0 | 0 | [] | 0 |
count-subarrays-with-median-k | 🔥Easy to Understand C++ Code✅ || PrefixSum + HashMap🌟💯 | easy-to-understand-c-code-prefixsum-hash-q8z0 | Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n\nclass Solution {\npublic:\n int coun | aDish_21 | NORMAL | 2023-07-04T12:48:58.449310+00:00 | 2023-07-04T13:02:48.447162+00:00 | 45 | false | # Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n## Please Upvote if it helps\uD83E\uDD17\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size(),k_ind = -1,prefixSum = 0,count = 0;\n unordered_map<int,int> mp;\n for(int i=0;i<n;i++){\n if(nums[i] == k){\n k_ind = i;\n break;\n }\n }\n // Its like updating nums[i] > k with 1 , nums[i] < k with -1 & nums[i] == k with 0\n // Now Count Subarrays of nums array having sum equal to 0 or 1 but subarray must also contain k(remember)\n for(int i=0;i<n;i++){\n int x = 0;\n if(nums[i] > k)\n x = 1;\n else if(nums[i] < k)\n x = -1;\n prefixSum += x;\n if(i >= k_ind){\n if(prefixSum == 0 || prefixSum == 1)\n count++;\n if(mp.find(prefixSum) != mp.end())\n count += mp[prefixSum];\n if(mp.find(prefixSum - 1) != mp.end())\n count += mp[prefixSum - 1];\n }\n if(i < k_ind)\n mp[prefixSum]++;\n }\n return count;\n }\n};\n``` | 0 | 0 | ['Array', 'Hash Table', 'Prefix Sum', 'C++'] | 0 |
count-subarrays-with-median-k | JS clean solution with logic explained. Easy to understand. | js-clean-solution-with-logic-explained-e-rj2e | Approach\nFor a subarray to have a median of k, there are three cases:\n\n- case 1: [k] itself\n- case 2: there is equal amount of numbers either bigger or smal | bowen0110 | NORMAL | 2023-07-01T22:29:53.725959+00:00 | 2023-07-01T22:29:53.725979+00:00 | 17 | false | # Approach\nFor a subarray to have a median of k, there are three cases:\n```\n- case 1: [k] itself\n- case 2: there is equal amount of numbers either bigger or smaller than k\n ex: [k-2, k-1, k, k+1, k+2]\n- case 3: the number of values bigger than k - number of values smaller than k is 1\n ex: [k-1, k, k+1, k+2]\n```\n\nSo if we start from k and count to the right side\nwe can get the **balance** of a subarray with k included.\nstart a balance count at 0, if we encounter a bigger element balance+1, else -1.\nthen when the balance is 0 or 1, the subarray is a valid.\n\nNow start at k again to count to the left side.\nStill 0 and 1s will make a valid subarray.\n**Plus**\nconsider a balance count -2 like this\n\n```\n.....i......k.......j......l\n -2 0 2 3\n```\nIf we combine the balance count -2 on the left with the right hand side 2. We have a total balance count 0 which is case 2.\nIf we combine -2 with 3, i.e. subarray from i to l. We have total balance 1 which is case 3.\nHence, when we do left side balance counting, we have to check the right hand side stored (-balance) and (-balance+1) value to update total subarray count.\n\nTo quickly check for the right hand balance frequency, use a hash map to store the count of balance.\n\n# Complexity\n- Time complexity:\nstep 1: get index of k takes max O(N) time\nstep 2: go from k to the end takes N-index(k) iterations\nstep 3: go from index(k) to begining\nstep 2 and step 3 together takes O(N)\nSo total tiem is O(N)\n\n- Space complexity:\nusing a hash map to store the right side balance frequency. the worst case could be storing all N-1 values with different balance count.\nSo space is O(N)\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar countSubarrays = function(nums, k) {\n // look for k index\n // if no k return 0\n let idx = -1;\n for (let i=0; i<nums.length; i++) {\n if (nums[i] === k) idx = i;\n }\n if (idx === -1) return 0;\n\n // go from k to the right to count 0s and 1s\n let rightBalanceFreq = new Map();\n let balance = 0;\n let count = 1;\n for (let i=idx+1; i<nums.length; i++) {\n balance += nums[i] > k ? 1:-1\n if (balance === 0 || balance === 1) count++;\n rightBalanceFreq.set(balance, (rightBalanceFreq.get(balance) || 0)+1);\n }\n\n // go from k to the left to count\n // 0 and 1 will make a valid subarray already\n // then check the complementary of current balance\n // i.e. check -balance in rightBalanceMap\n // also -balance+1 can make a valid subarray\n balance = 0;\n for (let i=idx-1; i>=0; i--) {\n balance += nums[i] > k ? 1:-1;\n if (balance === 0 || balance === 1) count++;\n count += (rightBalanceFreq.get(-balance) || 0) + (rightBalanceFreq.get(-balance+1) || 0)\n\n }\n return count;\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
count-subarrays-with-median-k | O(n) one pass easy solution | on-one-pass-easy-solution-by-iworkouther-ym17 | 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 | iworkouthere | NORMAL | 2023-06-23T05:36:06.919570+00:00 | 2023-06-23T05:36:06.919604+00:00 | 34 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countSubarrays(int[] nums, int k) {\n HashMap<Integer, Integer> map = new HashMap<>();\n map.put(0, 1);\n boolean self = false;\n int count = 0;\n int[] grt = new int[nums.length];\n int[] small = new int[nums.length];\n int p1 = 0; //previous for greater\n int p2 = 0; //previous for small\n\n for(int i = 0; i < nums.length; i++) {\n self = (self || (nums[i] == k));\n //System.out.println(self);\n if(nums[i] > k) p1++;\n else if(nums[i] < k) p2++;\n int curr = p1 - p2;\n if(self) {\n count += map.getOrDefault(curr, 0);\n count += map.getOrDefault(curr - 1, 0);\n }\n if(!self && nums[i] != k) {\n map.put(curr, map.getOrDefault(curr, 0) + 1);\n //System.out.println(curr + " = " + map.get(curr));\n }\n //System.out.println(count);\n //System.out.println();\n }\n\n return count;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | Very Easy || 97% || converted into subarray sum with equal K | very-easy-97-converted-into-subarray-sum-09bl | Intuition\nconverted into subarray sum with equal K\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:\n O(n) \n\ | OMVAGHANI18 | NORMAL | 2023-06-15T05:30:39.777214+00:00 | 2023-06-15T05:30:39.777241+00:00 | 45 | false | # Intuition\nconverted into subarray sum with equal K\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n $$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\nint fun(vector<int>& nums, int k)\n{\n int ans=0;\n int n=nums.size();\n unordered_map<int,int>mp;\n mp[0]=1;\n int sum=0,found=0;\n for(int i=0;i<n;i++)\n {\n sum+=nums[i];\n if(nums[i]==0)\n {\n found=1;\n }\n if(found==1)\n {\n if(mp.find(sum-0)!=mp.end())\n ans+=mp[sum-0];\n if(mp.find(sum-1)!=mp.end())\n ans+=mp[sum-1];\n }\n else\n mp[sum]++;\n }\n return ans;\n}\n int countSubarrays(vector<int>& nums, int k) \n {\n int n=nums.size();\n for(int i=0;i<n;i++)\n {\n if(nums[i]<k)\n {\n nums[i]=-1;\n }\n else if(nums[i]>k)\n {\n nums[i]=1;\n }\n else\n {\n nums[i]=0;\n }\n }\n return fun(nums,k);\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | [Rust] O(n) with single hashmap | rust-on-with-single-hashmap-by-tiedyedvo-7t0r | The problem uses an unusual definition of median, where the median of an even-length array is the lower middle number, not the average of the two middle numbers | tiedyedvortex | NORMAL | 2023-06-03T16:06:09.987757+00:00 | 2023-06-03T16:06:09.987781+00:00 | 6 | false | The problem uses an unusual definition of median, where the median of an even-length array is the lower middle number, not the average of the two middle numbers. \n\nAdditionally, because all array elements are distinct, there is exactly one element with value k in the array.\n\nThis means that the median of a subarray can be k **only** if it contains the single position k_pos where nums[k_pos] == k.\n\nSo, we can imagine picking an index i <= k_pos, and an index j >= k_pos, and considering the range nums[i..=j]. This range results in a median of k only if the count of numbers which are greater than k equals the count of numbers less than k, OR the count of numbers greater than k is 1 more than the count of numbers less than k.\n\nWe can split this subarray nums[i..=j] in half, considering the range nums[i..=k_pos] and nums[k_pos..=j]. If we want the net total of count(nums > k) - count(nums < k) to equal 0 or 1 overall, then that means we need the left net count + right net count to be 0 or 1.\n\nWe can scan on the left side to build up a count of how many subarrays exist for some i <= k_pos where nums[i..=k_pos] has each net count. Once we have this, we can then start from k_pos and scan rightward to get the similar count, and then sum up the number of left side only arrays which have the correct inverse net count.\n\n\n# Complexity\n- Time complexity: O(n), we do one scan of nums to find k_pos, and then two half-scans to build up the left balances and final output.\n\n- Space complexity: O(n) to store the hashmap of left balances.\n\n# Code\n```\nuse std::collections::HashMap;\nimpl Solution {\n pub fn count_subarrays(nums: Vec<i32>, k: i32) -> i32 {\n let n = nums.len();\n\n let k_pos = if let Some(pos) = nums.iter().position(|&num| num == k) { pos } else {\n return 0;\n };\n\n let mut left_balances = HashMap::<i32, i32>::new();\n\n let mut running = 0;\n\n for i in (0..=k_pos).rev() {\n if nums[i] > k {\n running += 1;\n } else if nums[i] < k{\n running -= 1;\n }\n *left_balances.entry(running).or_default() += 1;\n }\n\n running = 0;\n let mut output = 0;\n for i in (k_pos..n) {\n if nums[i] > k {\n running += 1;\n } else if nums[i] < k{\n running -= 1;\n }\n output += left_balances.get(&(-running)).cloned().unwrap_or(0);\n output += left_balances.get(&(1-running)).cloned().unwrap_or(0);\n }\n output\n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
count-subarrays-with-median-k | Java | Prefix Sum | O(N) | Unique Element so we can use prefix instead of Heap | java-prefix-sum-on-unique-element-so-we-qpvn2 | \n# Code\n\n/**\n *\n[- - - - - - - # - - - - - - - - - - ]\n\nbulk loading: \n > bulk load until #\n > use two heap to find the medium\nHow | evan-dayy | NORMAL | 2023-05-31T18:50:58.490068+00:00 | 2023-05-31T18:50:58.490093+00:00 | 28 | false | \n# Code\n```\n/**\n *\n[- - - - - - - # - - - - - - - - - - ]\n\nbulk loading: \n > bulk load until #\n > use two heap to find the medium\nHowever, it took N2Log(N) time, which is pretty ackward;\nwhat about we do a transformation on the array, to an array with -1, 0, 1\n 0, 1, 2, 3, 4\n [0, 0, 0, $, 1]\n[-, -, -, -, -, -]\n 0, 1, 2, 3, 4, 5\n */\n\nclass Solution {\n public int countSubarrays(int[] nums, int k) {\n // transfer to the binary array\n int[] binary = new int[nums.length];\n int pos = -1;\n for (int i = 0; i < nums.length; i++) {\n if (nums[i] < k) binary[i] = -1;\n else if (nums[i] > k) binary[i] = 1;\n else {\n // mark the k position\n binary[i] = 0;\n pos = i;\n }\n }\n // count the prefix sum of the binary array for future repeated computation\n int[] prefix = new int[nums.length + 1];\n for (int i = 0; i < nums.length; i++) {\n prefix[i + 1] = prefix[i] + binary[i];\n }\n // count how many of each value before the k position\n HashMap<Integer, Integer> m = new HashMap<>();\n for (int i = 0; i <= pos; i++) {\n m.put(prefix[i], m.getOrDefault(prefix[i], 0) + 1);\n }\n // starting from the k position, and then rolling out to find the subarray sum = 0 or -1\n int res = 0;\n for (int i = pos + 1; i < prefix.length; i++) {\n res += m.getOrDefault(prefix[i], 0) + m.getOrDefault(prefix[i] - 1, 0);\n }\n return res;\n }\n}\n\n\n\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | Java Solution | java-solution-by-code-pk-3k5n | 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 | code-pk | NORMAL | 2023-05-23T18:26:51.430325+00:00 | 2023-05-23T18:26:51.430361+00:00 | 44 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int countSubarrays(int[] nums, int k) {\n \n int i=0;\n\n while(i<nums.length){\n if(k == nums[i])\n break;\n i++;\n }\n\n Map<Integer,Integer> map = new HashMap<>();\n\n int diff = 0;\n\n //System.out.println(i);\n map.put(diff,map.getOrDefault(diff,0)+1);\n\n for(int end=i+1;end<nums.length;end++){\n if(nums[end] > k)\n diff++;\n else\n diff--;\n map.put(diff,map.getOrDefault(diff,0)+1);\n }\n\n diff = 0;\n\n int count = 0;\n\n if(map.containsKey(1 - diff))\n count += map.get(1 - diff);\n\n if(map.containsKey(0 - diff))\n count += map.get(0 - diff);\n\n for(int start=i-1;start>=0;start--){\n if(nums[start] > k)\n diff++;\n else\n diff--;\n\n if(map.containsKey(1 - diff))\n count += map.get(1 - diff);\n \n if(map.containsKey(0 - diff))\n count += map.get(0 - diff);\n }\n\n return count;\n\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
count-subarrays-with-median-k | [JavaScript] Track difference using Hash Table | javascript-track-difference-using-hash-t-rmc4 | Approach\n- https://leetcode.com/problems/count-subarrays-with-median-k/solutions/2851940/balance/\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexit | tmohan | NORMAL | 2023-05-23T14:14:40.411740+00:00 | 2023-05-23T14:15:18.157224+00:00 | 6 | false | # Approach\n- https://leetcode.com/problems/count-subarrays-with-median-k/solutions/2851940/balance/\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nvar countSubarrays = function(nums, k) {\n const count = { 0: 1 }, kIndex = nums.findIndex((a) => a == k);\n\n for (let i = kIndex + 1, bal = 0; i < nums.length; i++)\n bal += nums[i] > nums[kIndex] ? 1 : -1, count[bal] = 1 + (count[bal] ?? 0);\n\n let res = count[0] + (count[1] ?? 0);\n for (let i = kIndex - 1, bal = 0; i >= 0; i--)\n bal += nums[i] > nums[kIndex] ? 1 : -1,\n res += (count[-bal] ?? 0) + (count[-bal + 1] ?? 0);\n return res;\n};\n``` | 0 | 0 | ['Hash Table', 'JavaScript'] | 0 |
count-subarrays-with-median-k | Easy C++ Solution | easy-c-solution-by-klu_2000031799-ivur | Intuition\nIn summary, the code divides the array into two parts based on the index of the first occurrence of k. Then, it uses prefix sums and two unordered ma | klu_2000031799 | NORMAL | 2023-05-17T05:15:57.722576+00:00 | 2023-05-17T05:15:57.722612+00:00 | 35 | false | # Intuition\nIn summary, the code divides the array into two parts based on the index of the first occurrence of k. Then, it uses prefix sums and two unordered maps to efficiently count the subarrays on the left and right sides of the array with the desired sum.\n\n# Approach\nThe calculatePrefixSum function calculates a prefix sum vector vk based on nums and k. This vector helps in finding the sum of subarrays efficiently.\nThe findKIndex function finds the index (q) of the first occurrence of k in the nums vector. It will be used to divide the array into two parts: the left side (indices 0 to q) and the right side (indices q+1 to n-1).\nThe countSolutions function counts the number of subarrays in the left side and right side of the array that sum up to a particular value. It uses two unordered maps (mpL and mpR) to store the sums and their corresponding indices.\nIn the countSubarrays function, it calls countSolutions twice:\nThe first call is with added = 0, which counts the subarrays in the left side of the array that sum up to a specific value.\nThe second call is with added = -1, which counts the subarrays in the right side of the array that sum up to a specific value.\nFinally, it returns the sum of the results obtained from the two calls to countSolutions. This sum represents the total count of subarrays with the sum equal to k.\n\n\n# Complexity\n- Time complexity:O(N)\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n int q = findKIndex(nums, k);\n vector<int> vk = calculatePrefixSum(nums, k);\n return countSolutions(vk, q, 0) + countSolutions(vk, q, -1);\n }\n\n int countSolutions(vector<int>& vk, int q, int added) {\n int n = vk.size();\n int ans = 0;\n unordered_map<int, vector<int>> mpL, mpR;\n for (int L = 0; L <= q; L++)\n mpL[getSubarraySum(L, q, vk) + added].push_back(L);\n for (int R = q; R < n; R++)\n mpR[getSubarraySum(q, R, vk)].push_back(R);\n for (auto& [sum, idxs] : mpL)\n ans += idxs.size() * mpR[sum * -1].size();\n return ans;\n }\n\n int getSubarraySum(int L, int R, vector<int>& vk) {\n int vk_R = vk[R];\n int vk_L_1 = (L == 0) ? 0 : vk[L - 1];\n return vk_R - vk_L_1;\n }\n\n int findKIndex(vector<int>& nums, int k) {\n int n = nums.size();\n for (int i = 0; i < n; i++) {\n if (nums[i] == k) {\n return i;\n }\n }\n return -1; // If k is not found, return -1\n }\n\n vector<int> calculatePrefixSum(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> vk(n, 0);\n for (int i = 0; i < n; i++) {\n if ((nums[i] - k) != 0) {\n vk[i] = abs(nums[i] - k) / (nums[i] - k);\n }\n }\n for (int i = 1; i < n; i++) {\n vk[i] = vk[i - 1] + vk[i];\n }\n return vk;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | c++ simple prefix array | c-simple-prefix-array-by-vedantnaudiyal-p9pf | 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 | vedantnaudiyal | NORMAL | 2023-05-12T19:22:51.539344+00:00 | 2023-05-12T19:22:51.539402+00:00 | 15 | 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 countSubarrays(vector<int>& nums, int k) {\n int n=nums.size();\n vector<int> pre(n);\n unordered_map<int,int> mp;\n int k_found=-1;\n int diff=0;\n for(int i=0;i<n;i++){\n if(nums[i]<=k) diff++;\n else diff--;\n\n if(nums[i]==k){\n k_found=i;\n }\n if(k_found==-1) pre[i]=diff;\n else{\n mp[diff]++;\n }\n }\n int ans=0;\n if(mp.count(0)) ans+=mp[0];\n if(mp.count(1)) ans+=mp[1];\n for(int i=0;i<k_found;i++){\n if(mp.count(pre[i])) ans+=mp[pre[i]];\n if(mp.count(pre[i]+1)) ans+=mp[pre[i]+1];\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | C++ - Letting the Standard C++ Library do ALL the work | c-letting-the-standard-c-library-do-all-nlv69 | Inspired by Vlad\'s solution, https://leetcode.com/problems/count-subarrays-with-median-k/solutions/2851940/balance/?orderBy=most_votes.\nSee his description fo | carstenh | NORMAL | 2023-05-10T05:14:34.752253+00:00 | 2023-05-10T05:14:34.752297+00:00 | 40 | false | Inspired by Vlad\'s solution, https://leetcode.com/problems/count-subarrays-with-median-k/solutions/2851940/balance/?orderBy=most_votes.\nSee his description for the theory behind.\n\nNotice **every** statement is a call to the Standard Library.\n```\nclass Solution {\npublic:\n\tint countSubarrays(std::vector<int>& nums, int k) {\n\t\t// Numbers really only matters in terms of greater than k or less than k\n\t\t// So clamp them\n\t\tfor (auto& x : nums) { x = std::clamp(x - k, -1, 1); }\n\t\tauto iter = std::find(std::begin(nums), std::end(nums), 0);\n\n // Calculating partial sums going away from k\n\t\tstd::partial_sum(std::next(iter), std::end(nums), std::next(iter));\n\t\tstd::partial_sum(std::reverse_iterator(iter), std::rend(nums), std::reverse_iterator(iter));\n\n\t\t// Counting subarrays of odd length starting or ending with k\n\t\tauto result = static_cast<int>(std::count(std::cbegin(nums), std::cend(nums), 0));\n\t\t\n\t\t// Counting subarrays of even length starting or ending with k\n\t\tresult += static_cast<int>(std::count(std::cbegin(nums), std::cend(nums), 1));\n\n\t\tauto count = std::unordered_map<int, int>();\n\t\tstd::for_each(std::begin(nums), iter,\n\t\t\t[&count](auto sum) { ++count[sum]; });\n\n\t\t// Adding subarrays straddling k\n\t\treturn std::accumulate(std::next(iter), std::end(nums), result,\n\t\t\t[&count](auto const& accu, auto sum) { return accu + count[0 - sum] + count[1 - sum]; });\n\t}\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Golang : Prefix | Map | golang-prefix-map-by-harshawasthi90-joms | \npackage main\n\n\nfunc countSubarrays(nums []int, k int) int {\n\tdict := make(map[int]int, len(nums)/2)\n\tdict[0] = 1\n\n\tresult, sum, valid := 0, 0, false | harshawasthi90 | NORMAL | 2023-04-18T20:22:03.301704+00:00 | 2023-04-18T20:29:21.374985+00:00 | 31 | false | ```\npackage main\n\n\nfunc countSubarrays(nums []int, k int) int {\n\tdict := make(map[int]int, len(nums)/2)\n\tdict[0] = 1\n\n\tresult, sum, valid := 0, 0, false\n\n\tfor i := 0; i < len(nums); i++ {\n\t\tif nums[i] < k {\n\t\t\tsum--\n\t\t} else if nums[i] > k {\n\t\t\tsum++\n\t\t} else {\n\t\t\tvalid = true\n\t\t}\n\n\t\tif valid {\n\t\t\t// Check for matching prefix sum\'s only after K has been encountered\n\t\t\tresult += dict[sum] + dict[sum-1]\n\t\t} else {\n\t\t\t// Register the prefix till K is not encountered.\n\t\t\tdict[sum]++\n\t\t}\n\t}\n\n\treturn result\n}\n\n\n``` | 0 | 0 | ['Go'] | 0 |
count-subarrays-with-median-k | CPP | EASY | cpp-easy-by-mahipalpatel11111-m3kt | class Solution {\npublic:\n int countSubarrays(vector& nums, int k) \n {\n unordered_mapl,r;\n int i=0;\n for(;i-1)\n {\n | mahipalpatel11111 | NORMAL | 2023-03-21T08:20:05.884978+00:00 | 2023-03-21T08:20:05.885014+00:00 | 10 | false | class Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) \n {\n unordered_map<int,int>l,r;\n int i=0;\n for(;i<nums.size();++i)\n {\n if(nums[i]==k)\n break;\n }\n if(i==nums.size())\n return 0;\n int j=i-1;\n int s=0;\n while(j>-1)\n {\n if(nums[j]>k)\n s-=1;\n else\n s+=1;\n ++l[s];\n --j;\n }\n j=i+1;\n s=0;\n while(j<nums.size())\n {\n if(nums[j]>k)\n s+=1;\n else\n s-=1;\n ++r[s];\n ++j;\n }\n int c=1;\n for(auto a:l)\n {\n if(r.find(a.first)!=r.end())\n {\n c=c+a.second*r[a.first];\n }\n if(r.find(a.first+1)!=r.end())\n {\n c=c+a.second*r[a.first+1];\n }\n }\n if(r.find(1)!=r.end())\n {\n c=c+r[1];\n }\n if(r.find(0)!=r.end())\n c=c+r[0];\n if(l.find(-1)!=l.end())\n {\n c=c+l[-1];\n }\n if(l.find(0)!=l.end())\n {\n c=c+l[0];\n }\n return c;\n }\n}; | 0 | 0 | [] | 0 |
count-subarrays-with-median-k | O(n) Solution || C++ || easy explanation | on-solution-c-easy-explanation-by-sashi_-bwqh | Intuition\n Describe your first thoughts on how to solve this problem. \nIt is clear that we need to consider only those sub-array\'s which contain the given me | Sashi_sharma | NORMAL | 2023-03-18T18:01:38.169077+00:00 | 2023-03-18T18:01:38.169110+00:00 | 43 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is clear that we need to consider only those sub-array\'s which contain the given median.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use the Hash-map and PrifixSum technique to solve this problem.\nAt first we creat a hashmap of `<int,int>` to store the numbers and their frequencies which are less than or greater than the given median. Initially we make the 0th frequency 1.\nwe use a `for loop` for traversal from 0 index as we find any number which is less than the median then we reduce the `sum` by 1 and if number is greater than the median we incriment the `sum`.\nas soon as we reach the median we marke the flag as `True`.\nAs the flag is marked true we we star to adding the no. of sub array in `res`.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nClearly the Time complexity is $$O(n)$$. As we traverse the the whole Array. \n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe Space Complexity will be $$O(n)$$. Because we use a Hashmap.\n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n unordered_map<int,int>m;\n m[0]++;\n int sum=0,res=0;\n bool flag=false;\n for(int i=0;i<nums.size();i++){\n if(nums[i]<k) sum--;\n else if(nums[i]>k) sum++;\n else flag=true;\n if(flag) res+=m[sum]+m[sum-1];\n else m[sum]++;\n }\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
count-subarrays-with-median-k | Easy solution | easy-solution-by-seeki-pjz6 | 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 | Seeki | NORMAL | 2023-03-18T14:07:36.642872+00:00 | 2023-03-18T14:07:36.642911+00:00 | 67 | 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 countSubarrays(self, nums: List[int], k: int) -> int:\n n = len(nums)\n pos = nums.index(k)\n\n cnt = defaultdict(int)\n\n bal = 0\n for i in range(pos, n):\n num = nums[i]\n bal += 1 if num > k else (-1 if num < k else 0)\n cnt[bal] += 1\n \n res = 0\n bal = 0\n for i in reversed(range(pos+1)):\n num = nums[i]\n bal += 1 if num > k else (-1 if num < k else 0)\n \n res += cnt[-bal]\n res += cnt[-bal+1]\n return res\n``` | 0 | 0 | ['Python3'] | 0 |
count-subarrays-with-median-k | Go Using Map | go-using-map-by-janardhankrishnasai-g34f | 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 | JanardhanKrishnaSai | NORMAL | 2023-03-18T07:43:25.673518+00:00 | 2023-03-18T07:43:25.673565+00:00 | 26 | 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```\nfunc countSubarrays(nums []int, k int) int {\n n := len(nums)\n count := map[int]int{}\n p := -1\n for i, num := range nums {\n if num == k {\n p = i\n break\n }\n }\n bal := 0\n for i := p; i < n; i++ {\n if nums[i] == k {\n bal += 0\n } else if nums[i] < k {\n bal -= 1\n } else {\n bal += 1\n }\n if _, ok := count[bal]; !ok {\n count[bal] = 1\n } else {\n count[bal]++\n }\n }\n res := 0\n bal = 0\n for i := p; i >= 0; i-- {\n if nums[i] == k {\n bal += 0\n } else if nums[i] < k {\n bal -= 1\n } else {\n bal += 1\n }\n res += count[-bal] + count[-bal+1]\n }\n return res \n}\n``` | 0 | 0 | ['Go'] | 0 |
count-subarrays-with-median-k | Python, solution with explanation | python-solution-with-explanation-by-shun-h5qj | python\n\'\'\'\ntransform the numbers > k to 1, the numbers < k to -1, the numbers == k to 0,\nuse prefix sum to track the balance between the numbers > k and n | shun6096tw | NORMAL | 2023-03-14T12:59:46.448962+00:00 | 2023-03-14T12:59:46.449005+00:00 | 25 | false | ```python\n\'\'\'\ntransform the numbers > k to 1, the numbers < k to -1, the numbers == k to 0,\nuse prefix sum to track the balance between the numbers > k and numbers < k\nif we have found k, and we can count the number of subarray\nif subarray\'s length is odd, and #(number > k) == #(number < k) in subarray (the sum of this subarray is 0), so we can use a hash map to track the number of the current sum we have got before,\nif subarray\'s length is even, and #(number > k) - #(number < k) == 1 (the sum of this subarray is 1), so we can find the the number of the current sum - 1 we have got before.\ntc is O(n), sc is O(n)\n\'\'\'\nfrom collections import defaultdict\nclass Solution:\n def countSubarrays(self, nums: List[int], k: int) -> int:\n s = 0\n prefixsumToFreq = defaultdict(int)\n prefixsumToFreq[0] = 1\n found = False\n ans = 0\n for n in nums:\n if n < k: s -= 1\n elif n > k: s += 1\n else: found = True\n \n if found: ans = ans + prefixsumToFreq[s] + prefixsumToFreq[s-1]\n else: prefixsumToFreq[s] += 1\n return ans\n``` | 0 | 0 | ['Prefix Sum', 'Python'] | 0 |
count-subarrays-with-median-k | C++ count left and right | c-count-left-and-right-by-sanzenin_aria-y6tj | Intuition\nfor a subarray, let cnt = num of values > k - num of value < k\nto make k at medium, cnt must be 0 for odd size or 1 for even size.\nuse two map to s | sanzenin_aria | NORMAL | 2023-03-13T14:14:44.838351+00:00 | 2023-03-13T14:14:44.838395+00:00 | 58 | false | # Intuition\nfor a subarray, let cnt = num of values > k - num of value < k\nto make k at medium, cnt must be 0 for odd size or 1 for even size.\nuse two map to store the cnt of leftside and rightride subarray.\nto make k at medium, left cnt + right cnt must be 0 or 1. \n\n# Code\n```\nclass Solution {\npublic:\n int countSubarrays(vector<int>& nums, int k) {\n int res = 0, n = nums.size(), pos = find(begin(nums), end(nums), k) - nums.begin(); \n unordered_map<int,int> leftCnt = {{0,1}}, rightCnt = leftCnt;\n for(int i=pos-1, cnt=0; i>=0;i--){\n nums[i] > k? cnt++ : cnt--;\n leftCnt[cnt]++;\n }\n for(int i=pos+1, cnt=0; i<n;i++){\n nums[i] > k? cnt++ : cnt--;\n rightCnt[cnt]++;\n }\n for(auto [x, n] : leftCnt){\n res += n * rightCnt[-x]; //odd\n res += n * rightCnt[1-x]; //even\n }\n return res;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
number-of-closed-islands | Java/C++ with picture, Number of Enclaves | javac-with-picture-number-of-enclaves-by-ysxi | Intuition\nThis is similar to 1020. Number of Enclaves. \n\n#### Approach 1: Flood Fill\n\nFirst, we need to remove all land connected to the edges using flood | votrubac | NORMAL | 2019-11-10T04:08:41.301974+00:00 | 2019-11-10T18:51:13.651433+00:00 | 41,307 | false | #### Intuition\nThis is similar to [1020. Number of Enclaves](https://leetcode.com/problems/number-of-enclaves/discuss/265555/C%2B%2B-with-picture-DFS-and-BFS). \n\n#### Approach 1: Flood Fill\n\nFirst, we need to remove all land connected to the edges using flood fill.\n\nThen, we can count and flood-fill the remaining islands.\n\n\n\n**Java**\n```\nint fill(int[][] g, int i, int j) {\n if (i < 0 || j < 0 || i >= g.length || j >= g[i].length || g[i][j] != 0)\n return 0;\n return (g[i][j] = 1) + fill(g, i + 1, j) + fill(g, i, j + 1)\n + fill(g, i - 1, j) + fill(g, i, j - 1);\n}\npublic int closedIsland(int[][] g) {\n for (int i = 0; i < g.length; ++i)\n for (int j = 0; j < g[i].length; ++j)\n if (i * j * (i - g.length + 1) * (j - g[i].length + 1) == 0)\n fill(g, i, j);\n int res = 0;\n for (int i = 0; i < g.length; ++i)\n for (int j = 0; j < g[i].length; ++j)\n res += fill(g, i, j) > 0 ? 1 : 0;\n return res;\n}\n```\n**C++**\n```\nint fill(vector<vector<int>>& g, int i, int j) {\n if (i < 0 || j < 0 || i >= g.size() || j >= g[i].size() || g[i][j])\n return 0;\n return (g[i][j] = 1) + fill(g, i + 1, j) + fill(g, i, j + 1) \n + fill(g, i - 1, j) + fill(g, i, j - 1);\n}\nint closedIsland(vector<vector<int>>& g, int res = 0) {\n for (int i = 0; i < g.size(); ++i)\n for (int j = 0; j < g[i].size(); ++j)\n if (i * j == 0 || i == g.size() - 1 || j == g[i].size() - 1)\n fill(g, i, j);\n for (int i = 0; i < g.size(); ++i)\n for (int j = 0; j < g[i].size(); ++j)\n res += fill(g, i, j) > 0;\n return res;\n}\n```\n**Complexity Analysis**\n- Time: `O(n)`, where `n` is the total number of cells. We flood-fill all land cells once.\n\n- Memory: `O(n)` for the stack. Flood fill is DFS, and the maximum depth is `n`. | 381 | 12 | [] | 49 |
number-of-closed-islands | C++ easy DFS (faster than 99.81%, memory less than 100%) | c-easy-dfs-faster-than-9981-memory-less-akxnv | c++\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int res = 0;\n for (int i = 0; i < grid.size(); i++){\n | tatextry | NORMAL | 2020-03-21T22:06:19.535860+00:00 | 2020-03-21T22:06:19.535907+00:00 | 15,591 | false | ```c++\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int res = 0;\n for (int i = 0; i < grid.size(); i++){\n for (int j = 0; j < grid[0].size(); j++){\n if (grid[i][j] == 0){\n res += dfs(grid, i, j) ? 1 : 0;\n }\n }\n }\n return res;\n }\n bool dfs(vector<vector<int>>& g, int i, int j){\n if (i < 0 || j < 0 || i >= g.size() || j >= g[0].size()){\n return false;\n }\n if (g[i][j] == 1){\n return true;\n }\n g[i][j] = 1;\n /* IMPORTANT NOTE: \n WHY I CANNOT USE `return dfs(g, i+1, j) && dfs(g, i, j+1) && dfs(g, i-1, j) && dfs(g, i, j-1);`???\n BECAUSE IF ANY OF THE FIRST DFS() RETURNS FALSE, FOLLOWING ONES WILL NOT EXECUTE!!! THEN WE DON\'T\n HAVE THE CHANCE TO MARK THOSE 0s TO 1s!!!\n */\n bool d1 = dfs(g, i+1, j);\n bool d2 = dfs(g, i, j+1);\n bool d3 = dfs(g, i-1, j);\n bool d4 = dfs(g, i, j-1);\n return d1 && d2 && d3 && d4;\n }\n};\n``` | 184 | 5 | [] | 24 |
number-of-closed-islands | ✅[Python3//C++//Java]✅ Easy and understand DFS solution(Beats 100%) | python3cjava-easy-and-understand-dfs-sol-a1ts | \n\nThe DFS function takes a position (i, j) and recursively checks its neighboring cells. If the cell is out of bounds or has a value of 1, it returns True. Ot | abdullayev_akbar | NORMAL | 2023-04-06T01:47:56.791135+00:00 | 2023-04-06T02:12:45.053507+00:00 | 16,019 | false | \n\nThe DFS function takes a position (i, j) and recursively checks its neighboring cells. If the cell is out of bounds or has a value of 1, it returns True. Otherwise, it marks the cell as visited and continues to recursively check its neighbors. If any of the neighboring cells are not closed islands (i.e., not completely surrounded by 1s), it returns False. If all neighbors are closed islands, it returns True.\n\nThe main function iterates through each cell in the grid and checks if it is a 0 and a closed island. If it is, it increments the count.\n# Please Upvote \uD83D\uDE07\n# Python3\n<iframe src="https://leetcode.com/playground/LyFhxP5m/shared" frameBorder="0" width="1000" height="600"></iframe>\n\n | 154 | 2 | ['Depth-First Search', 'C++', 'Java', 'Python3'] | 4 |
number-of-closed-islands | [Java] Very Simple DFS Solution | java-very-simple-dfs-solution-by-edwin_z-0lji | \nclass Solution {\n\n int[][] dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n \n public int closedIsland(int[][] grid) {\n int res = 0;\ | edwin_z | NORMAL | 2019-11-10T04:06:22.299878+00:00 | 2019-11-10T04:10:45.965430+00:00 | 17,039 | false | ```\nclass Solution {\n\n int[][] dir = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};\n \n public int closedIsland(int[][] grid) {\n int res = 0;\n for(int i = 0; i < grid.length; i++){\n for(int j = 0; j < grid[0].length; j++){\n if(grid[i][j] == 0){\n if(dfs(grid, i, j)) res++;\n }\n }\n }\n \n return res;\n }\n \n public boolean dfs(int[][] grid, int x, int y){\n \n if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) return false;\n \n if(grid[x][y] == 1) return true;\n \n grid[x][y] = 1;\n \n boolean res = true;\n \n for(int[] d : dir){\n res = res & dfs(grid, x + d[0], y + d[1]);\n }\n \n return res;\n }\n}\n``` | 99 | 6 | ['Depth-First Search', 'Java'] | 17 |
number-of-closed-islands | Python easy understand DFS solution | python-easy-understand-dfs-solution-by-t-7267 | \nclass Solution(object):\n def closedIsland(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n if not | too-young-too-naive | NORMAL | 2019-11-10T04:03:47.123566+00:00 | 2019-11-10T04:04:25.822362+00:00 | 14,901 | false | ```\nclass Solution(object):\n def closedIsland(self, grid):\n """\n :type grid: List[List[int]]\n :rtype: int\n """\n if not grid or not grid[0]:\n return 0\n \n m, n = len(grid), len(grid[0])\n \n def dfs(i, j, val):\n if 0<=i<m and 0<=j<n and grid[i][j]==0:\n grid[i][j] = val\n dfs(i, j+1, val)\n dfs(i+1, j, val)\n dfs(i-1, j, val)\n dfs(i, j-1, val)\n \n for i in xrange(m):\n for j in xrange(n):\n if (i == 0 or j == 0 or i == m-1 or j == n-1) and grid[i][j] == 0:\n dfs(i, j, 1)\n \n res = 0\n for i in xrange(m):\n for j in xrange(n):\n if grid[i][j] == 0:\n dfs(i, j, 1)\n res += 1\n \n return res\n \n \n \n \n \n``` | 97 | 6 | [] | 17 |
number-of-closed-islands | [Java/Python 3] DFS, BFS and Union Find codes w/ brief explanation and analysis. | javapython-3-dfs-bfs-and-union-find-code-zc6q | DFS\n1. Traverse grid, for each 0, do DFS to check if it is a closed island;\n2. Within each DFS, if the current cell is out of the boundary of grid, return 0; | rock | NORMAL | 2019-11-11T07:20:26.186510+00:00 | 2019-11-17T17:04:09.169154+00:00 | 8,662 | false | **DFS**\n1. Traverse `grid`, for each `0`, do DFS to check if it is a closed island;\n2. Within each DFS, if the current cell is out of the boundary of `grid`, return `0`; if the current cell value is positive, return `1`; otherwise, it is `0`, change it to `2` then recurse to its 4 neighors and return the **multification** of them.\n\n```java\n public int closedIsland(int[][] grid) {\n int cnt = 0;\n for (int i = 0; i < grid.length; ++i)\n for (int j = 0; j < grid[0].length; ++j)\n if (grid[i][j] == 0)\n cnt += dfs(i, j, grid);\n return cnt;\n }\n \n private int dfs(int i, int j, int[][] g) {\n if (i < 0 || i >= g.length || j < 0 || j >= g[0].length)\n return 0;\n if (g[i][j] > 0)\n return 1;\n g[i][j] = 2;\n return dfs(i + 1, j, g) * dfs(i - 1, j, g) * dfs(i, j + 1, g) * dfs(i, j - 1, g);\n }\n```\n```python\n def closedIsland(self, grid: List[List[int]]) -> int:\n \n def dfs(i: int, j: int) -> int:\n if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]):\n return 0\n if grid[i][j]:\n return 1\n grid[i][j] = 2\n return dfs(i, j + 1) * dfs(i, j - 1) * dfs(i + 1, j) * dfs(i - 1, j)\n \n return sum(dfs(i, j) for i, row in enumerate(grid) for j, cell in enumerate(row) if not cell) \n```\n**Analysis:**\n\nTime & space: O(m * n), where m = grid.length, n = grid[0].length.\n\n----\n\n**BFS**\n\nFor each land never seen before, BFS to check if the land extends to boundary. If yes, return 0, if not, return 1.\n\n```java\n private static final int[] d = {0, 1, 0, -1, 0};\n private int m, n;\n \n public int closedIsland(int[][] grid) {\n int cnt = 0; \n m = grid.length; n = m == 0 ? 0 : grid[0].length;\n Set<Integer> seenLand = new HashSet<>();\n for (int i = 0; i < m; ++i) {\n for (int j = 0; j < n; ++j) {\n if (grid[i][j] == 0 && seenLand.add(i * n + j)) { // (i, j) is land never seen before.\n cnt += bfs(i, j, grid, seenLand);\n }\n }\n } \n return cnt;\n }\n \n private int bfs(int i, int j, int[][] g, Set<Integer> seenLand) {\n int ans = 1;\n Queue<Integer> q = new LinkedList<>();\n q.offer(i * n + j);\n while (!q.isEmpty()) {\n i = q.peek() / n; j = q.poll() % n;\n for (int k = 0; k < 4; ++k) { // traverse 4 neighbors of (i, j)\n int r = i + d[k], c = j + d[k + 1];\n if (r < 0 || r >= m || c < 0 || c >= n) { // out of boundary.\n ans = 0; // set 0;\n }else if (g[r][c] == 0 && seenLand.add(r * n + c)) { // (r, c) is land never seen before.\n q.offer(r * n + c);\n }\n }\n }\n return ans;\n }\n```\n\n```python\n def closedIsland(self, grid: List[List[int]]) -> int:\n seen_land = set()\n \n def bfs(i: int, j: int) -> int:\n seen_land.add((i, j))\n q, ans = [(i, j)], 1\n for i, j in q:\n for r, c in (i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1): \n if r < 0 or r >= len(grid) or c < 0 or c >= len(grid[0]):\n ans = 0\n elif not grid[r][c] and (r, c) not in seen_land:\n seen_land.add((r, c))\n q.append((r, c))\n return ans\n \n return sum(bfs(i, j) for i , row in enumerate(grid) for j, cell in enumerate(row) if not cell and (i, j) not in seen_land)\n```\n**Analysis:**\n\nTime & space: O(m * n), where m = grid.length, n = grid[0].length.\n\n----\n\n**Union Find**\n\n1. Traverse all cells not on boundary of the grid; For each land with a land neighbor, if the neighbor belongs to open island, merge it into the open island; otherwise, merge the neighbor into the island including current cell;\n2. Traverse all cells not on boundary of the grid again; Whenever encountering a land that its parent (id) is itself, then it is the root of the component (island), increase count by 1; The final value of the count is the number of closed island.\n\n```java\n private static final int[] d = {0, 1, 0, -1, 0};\n private int m, n; // numbers of rows and comlumns of grid.\n private int[] id; // parent ids. \n \n public int closedIsland(int[][] grid) {\n m = grid.length; n = m == 0 ? 0 : grid[0].length;\n id = IntStream.range(0, m * n).toArray(); // Initialized as i * n + j the parent id of cell (i, j).\n for (int i = 1; i < m - 1; ++i) // traverse non-boundary rows.\n for (int j = 1; j < n - 1; ++j) // traverse non-boundary cells within a row.\n if (grid[i][j] == 0) // (i, j) is land.\n for (int k = 0; k < 4; ++k) { // traverse the neighbors of (i, j).\n int r = i + d[k], c = j + d[k + 1];\n if (grid[r][c] == 0) // (r, c) is a land neighbor.\n union(i * n + j, r * n + c);\n }\n int cnt = 0; // number of closed islands: number of the non-boundary lands that are ids (parent) of itself.\n for (int i = 1; i < m - 1; ++i) // traverse non-boundary rows.\n for (int j = 1; j < n - 1; ++j) // traverse non-boundary cells within a row.\n if (grid[i][j] == 0 && id[i * n + j] == i * n + j) // Is (i, j) a land as well as the id (parent) of self? \n ++cnt;\n return cnt;\n }\n \n private int find(int x) {\n while (x != id[x]) \n x = id[x];\n return x;\n }\n \n private void union(int x, int y) {\n int rootX = find(x), rootY = find(y);\n if (rootX == rootY) \n return;\n if (isBoundary(rootY)) {\n id[rootX] = rootY; \n }else {\n id[rootY] = rootX;\n } \n }\n \n private boolean isBoundary(int id) {\n int i = id / n, j = id % n;\n return i == 0 || j == 0 || i == m - 1 || j == n - 1;\n }\n```\n```python\n def closedIsland(self, grid: List[List[int]]) -> int:\n \n m, n = len(grid), len(grid[0])\n id = list(range(m * n))\n \n def union(x: int, y: int) -> None:\n \n def find(x: int) -> int:\n while x != id[x]:\n x = id[x]\n return x \n \n root_x, root_y = find(x), find(y)\n if root_x != root_y:\n if root_y // n in (0, m - 1) or root_y % n in (0, n - 1):\n id[root_x] = root_y\n else:\n id[root_y] = root_x\n \n for i in range(1, m - 1):\n for j in range(1, n - 1):\n if not grid[i][j]:\n for r, c in (i, j + 1), (i + 1, j), (i, j - 1), (i - 1, j):\n if not grid[r][c]:\n union(i * n + j, r * n + c)\n return sum(not grid[i][j] and id[i * n + j] == i * n + j for i in range(1, m - 1) for j in range(1, n - 1))\n```\n | 75 | 3 | [] | 13 |
number-of-closed-islands | Image Explanation🏆- [Clean - "Generalized" Code] - C++/Java/Python | image-explanation-clean-generalized-code-1h5s | Video Solution (Aryan Mittal) - Link in LeetCode Profile\nNumber of Closed Islands by Aryan Mittal\n\n\n\n# Approach & Intution\n\n\n\n\n\n\n\n\n# Generalized C | aryan_0077 | NORMAL | 2023-04-06T01:16:37.174543+00:00 | 2023-04-06T05:23:21.398096+00:00 | 14,810 | false | # Video Solution (`Aryan Mittal`) - Link in LeetCode Profile\n`Number of Closed Islands` by `Aryan Mittal`\n\n\n\n# Approach & Intution\n\n\n\n\n\n\n\n\n# Generalized Code Template:\n```C++ []\nclass Solution {\npublic:\n void dfs(int i, int j, vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 0)\n return;\n\n grid[i][j] = 1;\n int dx[4] = {1, -1, 0, 0};\n int dy[4] = {0, 0, 1, -1};\n\n for(int k=0;k<4;k++){\n int nx = i + dx[k];\n int ny = j + dy[k];\n dfs(nx, ny, grid);\n }\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if((i*j==0 || i==m-1 || j==n-1) && (grid[i][j]==0))\n dfs(i, j, grid);\n }\n }\n \n int count = 0;\n for (int i = 1; i < m-1; i++) {\n for (int j = 1; j < n-1; j++) {\n if (grid[i][j] == 0) {\n dfs(i, j, grid);\n count++;\n }\n }\n }\n return count;\n }\n};\n```\n```Java []\nclass Solution {\n public void dfs(int i, int j, int[][] grid) {\n int m = grid.length, n = grid[0].length;\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 0)\n return;\n\n grid[i][j] = 1;\n int[] dx = {1, -1, 0, 0};\n int[] dy = {0, 0, 1, -1};\n\n for(int k=0;k<4;k++){\n int nx = i + dx[k];\n int ny = j + dy[k];\n dfs(nx, ny, grid);\n }\n }\n \n public int closedIsland(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if((i*j==0 || i==m-1 || j==n-1) && (grid[i][j]==0))\n dfs(i, j, grid);\n }\n }\n \n int count = 0;\n for (int i = 1; i < m-1; i++) {\n for (int j = 1; j < n-1; j++) {\n if (grid[i][j] == 0) {\n dfs(i, j, grid);\n count++;\n }\n }\n }\n return count;\n }\n}\n```\n```Python []\nclass Solution:\n def dfs(self, i: int, j: int, grid: List[List[int]]) -> None:\n m, n = len(grid), len(grid[0])\n if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != 0:\n return\n\n grid[i][j] = 1\n dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]\n\n for k in range(4):\n nx, ny = i + dx[k], j + dy[k]\n self.dfs(nx, ny, grid)\n\n def closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n for i in range(m):\n for j in range(n):\n if (i*j==0 or i==m-1 or j==n-1) and (grid[i][j]==0):\n self.dfs(i, j, grid)\n\n count = 0\n for i in range(1, m-1):\n for j in range(1, n-1):\n if grid[i][j] == 0:\n self.dfs(i, j, grid)\n count += 1\n return count\n```\n\n# Short Code (For this Problem Only):\n```\nclass Solution {\npublic:\n void dfs(int i, int j, vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 0)\n return;\n\n grid[i][j] = 1;\n dfs(i+1, j, grid);\n dfs(i-1, j, grid);\n dfs(i, j+1, grid);\n dfs(i, j-1, grid);\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n for (int i = 0; i < m; i++) {\n dfs(i, 0, grid);\n dfs(i, n-1, grid);\n }\n for (int j = 0; j < n; j++) {\n dfs(0, j, grid);\n dfs(m-1, j, grid);\n }\n \n int count = 0;\n for (int i = 1; i < m-1; i++) {\n for (int j = 1; j < n-1; j++) {\n if (grid[i][j] == 0) {\n dfs(i, j, grid);\n count++;\n }\n }\n }\n return count;\n }\n};\n```\n | 69 | 1 | ['Depth-First Search', 'Graph', 'C++', 'Java', 'Python3'] | 6 |
number-of-closed-islands | ✔️✔️Easy Solutions in Java ✔️✔️, Python ✔️, and C++ ✔️🧐Look at once 💻 with Exaplanation | easy-solutions-in-java-python-and-c-look-3kfi | Intuition\n Describe your first thoughts on how to solve this problem. \nTo solve the problem, we can iterate through the grid, and for each unvisited land(grid | Vikas-Pathak-123 | NORMAL | 2023-04-06T02:14:20.860881+00:00 | 2023-04-06T02:14:20.860950+00:00 | 5,974 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTo solve the problem, we can iterate through the grid, and for each unvisited land` (grid[i][j] == 0 and !visited[i][j])`, we can perform a depth-first search to check if it forms a closed island, i.e., all adjacent land is surrounded by water `(1)`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a variable `count` to keep track of the number of closed islands, and a boolean array `visited` t\nkeep track of visited land.\n2. Iterate through the grid using two nested loops, `i` and `j`, for each unvisited land (grid[i][j] == 0 and\n!visited[i][j]), perform a depth-first search to check if it forms a closed island. If it does, increment the\n`count`.\n3. In the depth-first search, we need to check if the current land is out of bounds or has already been visited\nin which case we return true. If the current land is adjacent to water, we need to recursively check its four\nneighbors (up, down, left, right) to see if they form a closed island. If any of the four neighbors is not in th\nbounds or is adjacent to water, then the current land is not a closed island, and we return false. If all four\nneighbors form a closed island, then the current land also forms a closed island, and we return true.\n4. Finally, we return the `count`.\n\n\n# Complexity\n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Time complexity: $$O(mn)$$, where `m` and `n` are the dimensions of the grid. We visit each land at and perform a constant amount of work for each land, so the total time complexity is linear in thgrid.\n\n\n- Space complexity: $$O(mn)$$, for the `visited` boolean array\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n\n# Code\n```java []\nclass Solution {\n public int closedIsland(int[][] grid) {\n int m = grid.length; // number of rows in the grid\n int n = grid[0].length; // number of columns in the grid\n int count = 0; // counter to keep track of number of closed islands\n boolean[][] visited = new boolean[m][n]; // to keep track of visited cells\n \n // loop through all cells, skipping the border cells\n for (int i = 1; i < m - 1; i++) {\n for (int j = 1; j < n - 1; j++) {\n if (grid[i][j] == 0 && !visited[i][j]) { // if this is an unvisited land cell\n boolean isClosed = dfs(grid, visited, i, j); // check if it is a closed island\n if (isClosed) {\n count++; // increment the counter if it is a closed island\n }\n }\n }\n }\n return count; // return the number of closed islands\n }\n \n private boolean dfs(int[][] grid, boolean[][] visited, int i, int j) {\n int m = grid.length; // number of rows in the grid\n int n = grid[0].length; // number of columns in the grid\n if (i < 0 || i >= m || j < 0 || j >= n) { // if out of bounds, not a closed island\n return false;\n }\n if (visited[i][j]) { // if already visited, not a closed island\n return true;\n }\n visited[i][j] = true; // mark as visited\n if (grid[i][j] == 1) { // if water, not a closed island\n return true;\n }\n boolean isClosed = true; // flag to check if all adjacent cells are water (closed island)\n isClosed &= dfs(grid, visited, i - 1, j); // check the cell to the left\n isClosed &= dfs(grid, visited, i + 1, j); // check the cell to the right\n isClosed &= dfs(grid, visited, i, j - 1); // check the cell above\n isClosed &= dfs(grid, visited, i, j + 1); // check the cell below\n return isClosed; // return whether all adjacent cells are water (closed island)\n }\n}\n\n```\n\n```C++ []\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n int count = 0;\n vector<vector<bool>> visited(m, vector<bool>(n, false));\n for (int i = 1; i < m - 1; i++) {\n for (int j = 1; j < n - 1; j++) {\n if (grid[i][j] == 0 && !visited[i][j]) {\n bool isClosed = dfs(grid, visited, i, j);\n if (isClosed) {\n count++;\n }\n }\n }\n }\n return count;\n }\n \n bool dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int i, int j) {\n int m = grid.size();\n int n = grid[0].size();\n if (i < 0 || i >= m || j < 0 || j >= n) {\n return false;\n }\n if (visited[i][j]) {\n return true;\n }\n visited[i][j] = true;\n if (grid[i][j] == 1) {\n return true;\n }\n bool isClosed = true;\n isClosed &= dfs(grid, visited, i - 1, j);\n isClosed &= dfs(grid, visited, i + 1, j);\n isClosed &= dfs(grid, visited, i, j - 1);\n isClosed &= dfs(grid, visited, i, j + 1);\n return isClosed;\n }\n};\n```\n```python []\nclass Solution(object):\n def closedIsland(self, grid):\n m, n = len(grid), len(grid[0])\n count = 0\n visited = [[False] * n for _ in range(m)]\n \n def dfs(i, j):\n if i < 0 or i >= m or j < 0 or j >= n:\n return False\n if visited[i][j]:\n return True\n visited[i][j] = True\n if grid[i][j] == 1:\n return True\n isClosed = True\n isClosed &= dfs(i - 1, j)\n isClosed &= dfs(i + 1, j)\n isClosed &= dfs(i, j - 1)\n isClosed &= dfs(i, j + 1)\n return isClosed\n \n for i in range(1, m - 1):\n for j in range(1, n - 1):\n if grid[i][j] == 0 and not visited[i][j]:\n isClosed = dfs(i, j)\n if isClosed:\n count += 1\n return count\n\n```\n\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n``` | 56 | 1 | ['Array', 'Depth-First Search', 'Python', 'C++', 'Java'] | 2 |
number-of-closed-islands | [Python3] Easy DFS one pass SHORT solution | python3-easy-dfs-one-pass-short-solution-uros | If you traverse and hit the border, this is not an island so don\'t add 1.\n\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n | localhostghost | NORMAL | 2019-11-14T15:41:48.838772+00:00 | 2019-11-14T15:51:17.634321+00:00 | 3,963 | false | If you traverse and hit the border, this is not an island so don\'t add 1.\n\n```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n res = 0\n \n def dfs(x, y):\n if x in (0, m-1) or y in (0, n-1):\n self.isIsland = False \n for i, j in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):\n if 0 <= i < m and 0 <= j < n and grid[i][j] == 0:\n grid[i][j] = -1 \n dfs(i, j)\n \n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0:\n self.isIsland = True\n dfs(i, j)\n res += self.isIsland\n \n return res \n``` | 40 | 0 | [] | 3 |
number-of-closed-islands | JAVA | Simple DFS solution | 100% Runtime | java-simple-dfs-solution-100-runtime-by-jpg2n | The goal is to count the number of time the dfs function is called, this will be the number of islands that exits.\nSimilar to this problem: https://leetcode.co | suraj008 | NORMAL | 2020-06-15T17:41:40.730664+00:00 | 2020-06-15T17:48:18.745188+00:00 | 3,711 | false | The goal is to count the number of time the dfs function is called, this will be the number of islands that exits.\nSimilar to this problem: https://leetcode.com/problems/number-of-islands/.\n\nThe catch here is that if the island of 0\'s is connected to a boundary 0. i.e i =0 || j=0 || i=length-1 || j=length-1 that island will not be considered since that would mean that this island is not completely surrounded by water i.e 1\'s on all sides.\n\n\n flag = true;\n\tpublic void dfs(int[][]grid, int i, int j) {\n \n if( i<0 || j<0 || i>=grid.length || j>=grid[0].length || grid[i][j]==1)\n return;\n \n //If other 0\'s are connected to border then dont increase ans\n if((i==0 || j==0 || i==grid.length-1 || j==grid[0].length-1) && grid[i][j]==0)\n flag = false;\n \n grid[i][j]=1;\n \n dfs(grid,i-1,j);\n dfs(grid,i+1,j);\n dfs(grid,i,j-1);\n dfs(grid,i,j+1);\n \n }\n \n public int closedIsland(int[][] grid) {\n int ans=0;\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[0].length;j++){\n \n if(grid[i][j]==0)\n {\n dfs(grid,i,j);\n \n //check if 0 isn\'t border/connected to border\n if(flag)\n ans+=1;\n flag = true;\n }\n }\n }\n return ans;\n } | 34 | 0 | ['Depth-First Search', 'Java'] | 7 |
number-of-closed-islands | clean C++ solution using DFS | clean-c-solution-using-dfs-by-sky97-ips7 | We are not considering edge connected zeroes for solution so first do DFS for those zeroes and assign the value -1 so at time of counting it would not be consid | sky97 | NORMAL | 2020-07-29T08:32:23.468143+00:00 | 2020-07-29T08:32:23.468189+00:00 | 2,733 | false | We are not considering edge connected zeroes for solution so first do DFS for those zeroes and assign the value -1 so at time of counting it would not be consider for solution.\n```\nclass Solution {\npublic:\n int r , c;\n \n void dfs(vector<vector<int>>& grid , int i , int j){\n if(i < 0 || j < 0 || j >= c || i >= r || grid[i][j] != 0) return;\n grid[i][j] = -1;\n dfs(grid , i - 1 , j);\n dfs(grid , i + 1 , j);\n dfs(grid , i , j - 1);\n dfs(grid , i , j + 1);\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n r = grid.size();\n c = grid[0].size();\n \n for(int i = 0;i < r;i++) // this is for edge conneced zeroes\n for(int j = 0;j < c;j++)\n if((j == 0 || i == 0 || j == c-1 || i == r-1) && grid[i][j] == 0)\n dfs(grid,i,j);\n \n int count = 0;\n for(int i = 0;i < r;i++) // this is for Number of Closed zeroes\n for(int j = 0;j < c;j++)\n if(grid[i][j] == 0){\n count++;\n dfs(grid,i,j);\n }\n \n return count;\n }\n};\n``` | 33 | 1 | [] | 3 |
number-of-closed-islands | Detailed Explanation using Terminal Nodes | detailed-explanation-using-terminal-node-7gw9 | Intuition\nThe idea is simple. We want to perform a DFS on the matrix to find the connected component of 0s. Call a connnected component valid if none of its e | just__a__visitor | NORMAL | 2019-11-10T04:03:35.247598+00:00 | 2019-11-11T08:20:19.424440+00:00 | 2,468 | false | # Intuition\nThe idea is simple. We want to perform a DFS on the matrix to find the connected component of `0s`. Call a connnected component valid if none of its element lies on the border of the matrix. It is clear that we need to find all the valid connected component.\n\n* We consider a cell with value `1` as a blocked cell and a cell with value `0` an empty cell. We also need to maintain a `visited` matrix, but we can just modify the input matrix, setting each `0` to `1` after we have visited it.\n\n* Now, all that remains is to start a DFS from the first unvisited `0`. This DFS call would cover all the elements of this connected component (As per the property of DFS). Now, we just need to keep track whether any element in this connected component touches the boundary of the matrix or not. If it does, this connected component becomes invalid. If none of the elements touch the boundary, it means that it is surrounded by`1s` on all the sides. Hence, we increment the counter for answer.\n\n* To check whether any element in the connected componenet is a terminal node, we can just maintain a boolean variable called `terminal` and set it to true whenver we see a terminal node during the DFS call. After the DFS, we only increment the counter if `terminal` is set to false. \n\n* How do we look out for terminal nodes? Note that if we hit a terminal node, we are also going to hit an out of bound neighbour. Hence, if we see an out of bounds index, we update the `terminal` to `True`\n\n```cpp\nclass Solution\n{\npublic:\n int row, col;\n bool terminal = false;\n void dfs(vector<vector<int>> &grid, int row, int col);\n int closedIsland(vector<vector<int>>& grid);\n};\n\nvoid Solution :: dfs(vector<vector<int>> &grid, int i, int j)\n{\n if(i < 0 or j < 0 or i >= row or j >= col)\n {\n terminal = true;\n return;\n }\n \n if(grid[i][j] == 1)\n return;\n\n // Visit this cell\n grid[i][j] = 1;\n \n dfs(grid, i, j + 1); dfs(grid, i, j - 1);\n dfs(grid, i + 1, j); dfs(grid, i - 1, j);\n}\n\nint Solution :: closedIsland(vector<vector<int>>& grid)\n{\n row = grid.size();\n col = grid[0].size();\n \n int count = 0;\n for(int i = 0; i < row; i++)\n {\n for(int j = 0; j < col; j++)\n {\n if(grid[i][j] == 0)\n {\n terminal = false;\n dfs(grid, i, j);\n \n if(!terminal)\n count++;\n }\n }\n }\n \n return count;\n}\n``` | 29 | 2 | [] | 2 |
number-of-closed-islands | ✅ [C++] Easy Intuitive Solution using DFS | Explained | c-easy-intuitive-solution-using-dfs-expl-3lak | This problem is easy. You just need to figure out the fact that any island will be "surrounded" if it can\'t reach the boundary. Let me explain. \nSo we know th | biT_Legion | NORMAL | 2022-05-18T09:16:12.625558+00:00 | 2022-05-18T09:16:12.625595+00:00 | 2,574 | false | This problem is easy. You just need to figure out the fact that any island will be "surrounded" if it can\'t reach the boundary. Let me explain. \nSo we know that once we start DFS from any cell, it will move in all four directions provided they are `unvisited` and have a `0`, and it will stop if it meets an `unvisited` or a `1`. So, if DFS call from a cell is not reaching any of the matrix\'s boundary, that means there must have been a `1` in its way. Therefore, if it can\'t reach any of the boundaries, then that states that there are `1` in its way terminating the DFS call for that connected component, and thus that connected component becomes a land which is surrounded by water from all sides. You can refer to the example image. \n\n\nHere, you can see that once you start DFS call from cell `(1,1)`, it will track down all the 0s which are in the same connected component and when it encounters `1` in its way, it halts. \nThe zeros, or the connected components that can reach to any of the four boundaries can never be fully closed by water. Therefore, in the above example, we can only have two closed islands. \n\n**NOTE** : In this problem, there is only one thing different from normal DFS. Since we need to check if any dfs call reaches any of the four corner or not, therefore we need to have a boolean return type of dfs function. That creates an issue that if we just do `return fun(move left) && fun(move right) && fun(move up) && fun(move down)`, then it could happen that `fun(move left)` return false, due to which the remaining three calls will not be done. This creates an issue because it will not cover all the cells of a connected component, since we just moved in one direction from a cell and got false, so we returned. Therefore, to tackle this, we store the result of all the four calls in four different variables and then return their combined result. This way, we will mark all the cells of a connected component as visited. \nIn case you did not get this NOTE, you can refer to the cases below the code. \n \n\n```\nclass Solution {\npublic:\n int dx[4] = {1,0,-1,0};\n int dy[4] = {0,1,0,-1};\n \n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n vector <vector <int>> visited(m, vector <int>(n,0));\n \n int count = 0;\n for(int i = 0; i<m; i++){\n for(int j = 0; j<n; j++){\n if(grid[i][j]==0 and visited[i][j]==0)\n if(dfs(i,j,grid,visited)) count++;\n }\n }\n return count;\n }\nprotected:\n bool isvalid(int x, int y, int m, int n, vector <vector <int>>&grid, vector <vector <int>>&visited){\n if(visited[x][y] or grid[x][y]) return false;\n return true;\n }\n bool dfs(int x, int y, vector <vector <int>>&grid, vector <vector <int>>&visited){\n if(!isvalid(x,y,grid.size(),grid[0].size(),grid,visited)) return true;\n \n if(x==grid.size()-1 or x==0 or y==grid[0].size()-1 or y==0) return false;\n \n visited[x][y] = 1;\n \n bool left = dfs(x,y-1,grid,visited);\n bool right = dfs(x,y+1,grid,visited);\n bool up = dfs(x-1,y,grid,visited);\n bool down = dfs(x+1,y,grid,visited);\n \n return left and right and up and down;\n }\n};\n/*\n[[0,0,1,1,0,1,0,0,1,0],[1,1,0,1,1,0,1,1,1,0],[1,0,1,1,1,0,0,1,1,0],[0,1,1,0,0,0,0,1,0,1],[0,0,0,0,0,0,1,1,1,0],[0,1,0,1,0,1,0,1,1,1],[1,0,1,0,1,1,0,0,0,1],[1,1,1,1,1,1,0,0,0,0],[1,1,1,0,0,1,0,1,0,1],[1,1,1,0,1,1,0,1,1,0]]\n[[1,1,0,1,1,1,1,1,1,1],[0,0,1,0,0,1,0,1,1,1],[1,0,1,0,0,0,1,0,1,0],[1,1,1,1,1,0,0,1,0,0],[1,0,1,0,1,1,1,1,1,0],[0,0,0,0,1,1,0,0,0,0],[1,0,1,0,0,0,0,1,1,0],[1,1,0,0,1,1,0,0,0,0],[0,0,0,1,1,0,1,1,1,0],[1,1,0,1,0,1,0,0,1,0]]\n*/\n``` | 25 | 0 | ['Depth-First Search', 'C', 'C++'] | 4 |
number-of-closed-islands | ✅✅Python🔥Java🔥C++🔥Simple Solution🔥Easy to Understand🔥 | pythonjavacsimple-solutioneasy-to-unders-8ll7 | Please UPVOTE \uD83D\uDC4D\n\n!! BIG ANNOUNCEMENT !!\nI am currently Giving away my premium content well-structured assignments and study materials to clear int | cohesk | NORMAL | 2023-04-06T00:06:24.179812+00:00 | 2023-04-06T00:06:24.179855+00:00 | 4,239 | false | # Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am currently Giving away my premium content well-structured assignments and study materials to clear interviews at top companies related to computer science and data science to my current Subscribers this week. I planned to give for next 10,000 Subscribers as well. So **DON\'T FORGET** to Subscribe\n\n**Search \uD83D\uDC49`Tech Wired leetcode` on YouTube to Subscribe**\n# OR \n**Click the Link in my Leetcode Profile to Subscribe**\n\n\n# Recursion Explained (How to think recursively)\n**Search \uD83D\uDC49`Recursion by Tech Wired` on YouTube**\n\n\n\n\nHappy Learning, Cheers Guys \uD83D\uDE0A\n\n# Approach:\n\n- The problem can be solved using depth-first search (DFS). First, we traverse the edges of the grid and mark all the connected components that touch the boundary as visited. This is because these components are not closed, and we want to count only the closed components.\n\n- Then, we traverse the interior cells of the grid that are not visited yet and count the number of closed components. For each unvisited cell that is not on the boundary and has a value of 0, we perform a DFS to mark all the cells that are connected to it. If we reach a boundary cell or a cell that has already been visited, we stop the DFS. The number of closed components is equal to the number of DFS calls we make.\n\n# Intuition:\n\nThe idea behind the approach is that a closed component is surrounded by cells that are either boundaries or cells with a value of 1. If we start from the boundary and mark all the cells that are connected to it, we can identify the cells that are not connected to the boundary and are therefore part of a closed component. We can then count the number of closed components by performing a DFS on each unvisited cell that has a value of 0 and is not on the boundary.\n\n```Python []\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n def dfs(i, j):\n if i < 0 or i >= m or j < 0 or j >= n or grid[i][j] != 0:\n return\n grid[i][j] = 1\n dfs(i+1, j)\n dfs(i-1, j)\n dfs(i, j+1)\n dfs(i, j-1)\n \n m, n = len(grid), len(grid[0])\n for i in range(m):\n dfs(i, 0)\n dfs(i, n-1)\n for j in range(n):\n dfs(0, j)\n dfs(m-1, j)\n \n count = 0\n for i in range(1, m-1):\n for j in range(1, n-1):\n if grid[i][j] == 0:\n dfs(i, j)\n count += 1\n return count\n\n```\n```Java []\nclass Solution {\n private void dfs(int i, int j, int[][] grid) {\n int m = grid.length, n = grid[0].length;\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 0) {\n return;\n }\n grid[i][j] = 1;\n dfs(i+1, j, grid);\n dfs(i-1, j, grid);\n dfs(i, j+1, grid);\n dfs(i, j-1, grid);\n }\n \n public int closedIsland(int[][] grid) {\n int m = grid.length, n = grid[0].length;\n for (int i = 0; i < m; i++) {\n dfs(i, 0, grid);\n dfs(i, n-1, grid);\n }\n for (int j = 0; j < n; j++) {\n dfs(0, j, grid);\n dfs(m-1, j, grid);\n }\n int count = 0;\n for (int i = 1; i < m-1; i++) {\n for (int j = 1; j < n-1; j++) {\n if (grid[i][j] == 0) {\n dfs(i, j, grid);\n count++;\n }\n }\n }\n return count;\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n void dfs(int i, int j, vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 0) {\n return;\n }\n grid[i][j] = 1;\n dfs(i+1, j, grid);\n dfs(i-1, j, grid);\n dfs(i, j+1, grid);\n dfs(i, j-1, grid);\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n for (int i = 0; i < m; i++) {\n dfs(i, 0, grid);\n dfs(i, n-1, grid);\n }\n for (int j = 0; j < n; j++) {\n dfs(0, j, grid);\n dfs(m-1, j, grid);\n }\n int count = 0;\n for (int i = 1; i < m-1; i++) {\n for (int j = 1; j < n-1; j++) {\n if (grid[i][j] == 0) {\n dfs(i, j, grid);\n count++;\n }\n }\n }\n return count;\n }\n};\n\n```\n\n\n# Please UPVOTE \uD83D\uDC4D\n\n | 24 | 1 | ['Array', 'Depth-First Search', 'C++', 'Java', 'Python3'] | 1 |
number-of-closed-islands | [Python] 2 solutions: DFS, BFS | python-2-solutions-dfs-bfs-by-hiepit-801u | Idea\n- The closed island is the island which doesn\'t touch the bound of grid.\n\n\u2714\uFE0F Solution 1: DFS\npython\nclass Solution:\n def closedIsland(s | hiepit | NORMAL | 2019-11-10T04:57:54.722313+00:00 | 2022-07-02T18:52:34.852022+00:00 | 1,676 | false | **Idea**\n- The closed island is the island which doesn\'t touch the bound of grid.\n\n**\u2714\uFE0F Solution 1: DFS**\n```python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n DIR = [0, 1, 0, -1, 0]\n \n def dfs(r, c):\n grid[r][c] = -1\n isClosedIsland = 1\n for i in range(4):\n nr, nc = r + DIR[i], c + DIR[i+1]\n if not (0 <= nr < m and 0 <= nc < n): # This is not the closed island anymore!\n isClosedIsland = 0\n elif grid[nr][nc] == 0: \n if dfs(nr, nc) == 0:\n isClosedIsland = 0\n return isClosedIsland\n \n nClosedIsland = 0\n for r in range(m):\n for c in range(n):\n if grid[r][c] == 0:\n nClosedIsland += dfs(r, c)\n return nClosedIsland\n```\nComplexity:\n- Time: `O(M*N)`, where `M <= 100` is number of rows, `N <= 100` is number of columns in the matrix.\n- Space: `O(M*N)`\n\n---\n**\u2714\uFE0F Solution 2: BFS**\n```python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n DIR = [0, 1, 0, -1, 0]\n \n def bfs(sr, sc):\n isClosedIsland = 1\n q = deque([(sr, sc)])\n grid[sr][sc] = -1\n while q:\n r, c = q.popleft()\n for i in range(4):\n nr, nc = r + DIR[i], c + DIR[i+1]\n if not (0 <= nr < m and 0 <= nc < n): # This is not the closed island anymore!\n isClosedIsland = 0\n elif grid[nr][nc] == 0:\n grid[nr][nc] = -1\n q.append((nr, nc))\n return isClosedIsland\n \n nClosedIsland = 0\n for r in range(m):\n for c in range(n):\n if grid[r][c] == 0:\n nClosedIsland += bfs(r, c)\n return nClosedIsland\n```\nComplexity:\n- Time: `O(M*N)`, where `M <= 100` is number of rows, `N <= 100` is number of columns in the matrix.\n- Space: `O(M*N)` | 21 | 2 | [] | 2 |
number-of-closed-islands | ✅ Fastest C++ | Python | Java Solution -Runtime: 3 ms,faster than 100% | fastest-c-python-java-solution-runtime-3-sc9i | SOLUTION\n\n\n\nEXPLANATION\n\n The function takes a 2D vector of integers as input, representing the grid.\n It initializes a counter variable c to 0.\n For ea | codermal7 | NORMAL | 2023-04-06T06:10:37.418837+00:00 | 2023-04-06T06:15:26.207890+00:00 | 1,156 | false | **SOLUTION**\n\n<iframe src="https://leetcode.com/playground/E6GNYD2g/shared" frameBorder="0" width="800" height="700"></iframe>\n\n**EXPLANATION**\n\n* The function takes a 2D vector of integers as input, representing the grid.\n* It initializes a counter variable c to 0.\n* For each element in the grid, it checks if it is a 0 (land).\n* If the element is a 0, it calls a helper function with the current element\'s position, grid dimensions, and the current and old color values.\n* The helper function performs a depth-first search to find all the connected land elements with the same color as the starting element.\n* If any of the connected land elements are on the edge of the grid, it sets a flag variable f to 1.\n* It also marks all the connected land elements as visited by changing their color to -1.\n* After the helper function returns, if the flag variable f is still 0, it means all the connected land elements are surrounded by water, so it increments the counter variable c by 1.\n* Finally, the function returns the value of the counter variable c, which represents the number of closed islands in the grid.\n\n**Time complexity:**\n\nThe algorithm visits each element in the grid once, so the time complexity is O(m * n), where m is the number of rows and n is the number of columns in the grid.\nIn the helper function, each connected component is visited once, which takes O(m * n) time in the worst case.\nTherefore, the overall time complexity of the solution is **O(m * n)**.\n\n**Space complexity:**\n\nThe algorithm modifies the input grid in place, so the space complexity is O(1), i.e., constant space complexity.\nThe recursive helper function uses the call stack to keep track of the function calls, which can take up to O(m + n) space in the worst case, where m is the number of rows and n is the number of columns in the grid.\nTherefore, the overall space complexity of the solution is **O(m + n)**.\n\n**PLEASE UPVOTE \u2B06\uFE0F**\n\n\n\n\n\n | 20 | 1 | ['Depth-First Search', 'Recursion', 'C', 'Matrix', 'Python', 'C++', 'Java'] | 3 |
number-of-closed-islands | 🐍 DFS || Well-explained || 93% faster || | dfs-well-explained-93-faster-by-abhi9rai-emb7 | IDEA :\n Till we are founding "0" we can go through dfs and check if that island is surrounded by water or not.\n Up, down, left and right if all comes True the | abhi9Rai | NORMAL | 2021-06-04T05:51:12.975676+00:00 | 2021-06-04T05:52:54.772604+00:00 | 1,979 | false | ## IDEA :\n* Till we are founding "0" we can go through dfs and check if that island is surrounded by water or not.\n* Up, down, left and right if all comes True then increment the counter by 1.\n\n\'\'\'\n\n\tclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n \n def dfs(i,j):\n if grid[i][j]==1:\n return True\n if i<=0 or i>=m-1 or j<=0 or j>=n-1:\n return False\n grid[i][j]=1\n up=dfs(i-1,j)\n down=dfs(i+1,j)\n left=dfs(i,j-1)\n right=dfs(i,j+1)\n return left and right and up and down\n \n m,n = len(grid),len(grid[0])\n c=0\n\t\t# iterate through the grid from 1 to length of grid for rows and columns.\n # the iteration starts from 1 because if a 0 is present in the 0th column, it can\'t be a closed island.\n for i in range(1,m-1):\n for j in range(1,n-1):\n\t\t\t\t# if the item in the grid is 0 and it is surrounded by\n # up, down, left, right 1\'s then increment the count.\n if grid[i][j]==0 and dfs(i,j):\n c+=1\n return c\n\nThanks !!\nIf any doubt feel free to ask......... If you got helpful **Do Upvote** \uD83E\uDD1E | 20 | 0 | ['Python', 'Python3'] | 4 |
number-of-closed-islands | ✅ [C++]Easy solution with explanation (With and Without Visited Array)✅ | ceasy-solution-with-explanation-with-and-yewn | Intuition\nThe boundaries that have 0 will never be an answer as they can\'t be surrounded. Hence 0\'s connected to these 0 will also not be answer as there wil | upadhyayabhi0107 | NORMAL | 2023-04-06T02:57:33.543803+00:00 | 2023-04-06T02:57:33.543851+00:00 | 2,751 | false | # Intuition\nThe boundaries that have 0 will never be an answer as they can\'t be surrounded. Hence 0\'s connected to these 0 will also not be answer as there will be an oppening.\n\n# Approach\nWe simply neglect the outter 0\'s and their connected parts.\n\n1. Traverse over the boundaries , if you find any 0\'s just do a dfs to all the connected 0\'s to it .\n2. Then do a simple dfs over the remaining 0\'s to get the connected components\n\n# Complexity\n- Time complexity: O(N * M)\n\n- Space complexity: O(N * M)\n\n\n# CODE - 1\n```\nclass Solution {\npublic:\n bool ok(vector<vector<int>>& grid , vector<vector<int>>& vis , int i , int j , int n , int m){\n return (i >= 0 && i < n && j >= 0 && j < m && grid[i][j] != 1 && vis[i][j] == 0);\n }\n void dfs(vector<vector<int>>& grid , vector<vector<int>>& vis , int i , int j , int n , int m){\n if(!ok(grid , vis , i , j , n , m)){\n return ;\n }\n vis[i][j] = 1;\n dfs(grid , vis , i + 1 , j , n , m);\n dfs(grid , vis , i - 1 , j , n , m);\n dfs(grid , vis , i , j + 1 , n , m);\n dfs(grid , vis , i , j - 1 , n , m);\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n vector<vector<int>> vis(n , vector<int>(m , 0));\n for(int i = 0 ; i < m ; i++){\n if(grid[0][i] == 0 && vis[0][i] == 0){\n dfs(grid , vis , 0 , i , n , m);\n }\n if(grid[n-1][i] == 0 && vis[n-1][i] == 0){\n dfs(grid , vis , n-1 , i , n , m);\n }\n }\n for(int i = 0 ; i < n ; i++){\n if(grid[i][0] == 0 && vis[i][0] == 0){\n dfs(grid , vis , i , 0 , n , m);\n }\n if(grid[i][m-1] == 0 && vis[i][m-1] == 0){\n dfs(grid , vis , i , m-1 , n , m);\n }\n }\n int cnt = 0;\n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n if(grid[i][j] == 0 && vis[i][j] == 0){\n dfs(grid , vis , i , j , n , m);\n cnt++;\n }\n }\n }\n return cnt;\n }\n};\n```\n\n# Complexity\n- Time complexity: O(N * M)\n\n- Space complexity: O(1) (as no space is used by me only the given grid is used as space)\n\n\n# CODE - 2\n```\nclass Solution {\npublic:\n bool ok(vector<vector<int>>& grid , int i , int j , int n , int m){\n return (i >= 0 && i < n && j >= 0 && j < m && grid[i][j] != 1);\n }\n void dfs(vector<vector<int>>& grid, int i , int j , int n , int m){\n if(!ok(grid , i , j , n , m)){\n return ;\n }\n grid[i][j] = 1;\n dfs(grid , i + 1 , j , n , m);\n dfs(grid , i - 1 , j , n , m);\n dfs(grid , i , j + 1 , n , m);\n dfs(grid , i , j - 1 , n , m);\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n for(int i = 0 ; i < m ; i++){\n if(grid[0][i] == 0){\n dfs(grid , 0 , i , n , m);\n }\n if(grid[n-1][i] == 0){\n dfs(grid , n-1 , i , n , m);\n }\n }\n for(int i = 0 ; i < n ; i++){\n if(grid[i][0] == 0){\n dfs(grid , i , 0 , n , m);\n }\n if(grid[i][m-1] == 0){\n dfs(grid , i , m-1 , n , m);\n }\n }\n int cnt = 0;\n for(int i = 0 ; i < n ; i++){\n for(int j = 0 ; j < m ; j++){\n if(grid[i][j] == 0){\n dfs(grid , i , j , n , m);\n cnt++;\n }\n }\n }\n return cnt;\n }\n};\n```\n | 15 | 0 | ['Depth-First Search', 'Recursion', 'C++'] | 0 |
number-of-closed-islands | [C++] Fill boundaries then count islands - Beats 100% | c-fill-boundaries-then-count-islands-bea-56q6 | \nclass Solution {\n void util(vector<vector<int>>& grid, int i, int j) {\n if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j])\n | rexagod | NORMAL | 2020-11-13T03:25:28.338274+00:00 | 2020-11-13T03:25:28.338315+00:00 | 2,031 | false | ```\nclass Solution {\n void util(vector<vector<int>>& grid, int i, int j) {\n if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j])\n return;\n grid[i][j] = 1;\n util(grid,i-1,j);\n util(grid,i,j-1);\n util(grid,i+1,j);\n util(grid,i,j+1);\n }\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int c = 0;\n int n = grid.size();\n int m = grid[0].size();\n for(int i=0; i<n; i++)\n util(grid,i,0), util(grid,i,m-1);\n for(int j=0; j<m; j++)\n util(grid,0,j), util(grid,n-1,j);\n for(int i=0; i<n; i++)\n for(int j=0; j<m; j++)\n if(!grid[i][j])\n util(grid,i,j), c++;\n return c;\n }\n};\n``` | 15 | 0 | ['Depth-First Search', 'C'] | 4 |
number-of-closed-islands | ✅C++ || EASY BFS | c-easy-bfs-by-chiikuu-ibcg | Code\n\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& g) {\n queue<pair<int,int>>q;\n int n=g.size(),m=g[0].size();\n | CHIIKUU | NORMAL | 2023-04-06T08:29:44.955826+00:00 | 2023-04-06T08:30:43.757708+00:00 | 2,193 | false | # Code\n```\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& g) {\n queue<pair<int,int>>q;\n int n=g.size(),m=g[0].size();\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(i==0 || i==n-1 || j==0 || j==m-1){\n if(g[i][j]==0){\n g[i][j]=1;\n q.push({i,j});}\n }\n }\n }\n while(q.size()){\n auto l=q.front();\n q.pop();\n int x=l.first;\n int y=l.second;\n int dx[4]={1,-1,0,0};\n int dy[4]={0,0,1,-1};\n for(int i=0;i<4;i++){\n int nx=dx[i]+x;\n int ny=dy[i]+y;\n if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==0){\n g[nx][ny]=1;\n q.push({nx,ny});\n }\n }\n }\n int ct=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!g[i][j]){\n ct++;\n q.push({i,j});\n while(q.size()){\n auto l=q.front();\n q.pop();\n int x=l.first;\n int y=l.second;\n int dx[4]={1,-1,0,0};\n int dy[4]={0,0,1,-1};\n for(int i=0;i<4;i++){\n int nx=dx[i]+x;\n int ny=dy[i]+y;\n if(nx>=0 && nx<n && ny>=0 && ny<m && g[nx][ny]==0){\n g[nx][ny]=1;\n q.push({nx,ny});\n }\n }\n }\n }\n }\n }\n return ct;\n }\n};\n```\n\n | 12 | 1 | ['Breadth-First Search', 'Matrix', 'C++'] | 0 |
number-of-closed-islands | JAVA || Easy Solution || 100% Faster Code || DFS || Detailed Explanation | java-easy-solution-100-faster-code-dfs-d-skgd | \n\n\n# Code\nPLEASE UPVOTE IF YOU LIKE.\n\nclass Solution {\n \n public int closedIsland(int[][] grid) {\n\n /*\n * Base Condition :\n | shivrastogi | NORMAL | 2023-04-06T01:03:28.349259+00:00 | 2023-04-06T01:03:28.349294+00:00 | 2,097 | false | \n\n\n# Code\nPLEASE UPVOTE IF YOU LIKE.\n```\nclass Solution {\n \n public int closedIsland(int[][] grid) {\n\n /*\n * Base Condition :\n * If row or column length is less than 3 all the values will be somehow connected to perimeter.\n * So there can\'t be a island.\n */\n if (grid.length < 3 || grid[0].length < 3) {\n return 0;\n }\n\n int numberOfClosedIsland = 0;\n\n /*\n * In the perimeter of the grid, irrespective of land(0) or water(0) it will never be a closed island.\n * So, we want to confined our search from (row - 1) to (grid.length - 2) i.e. Skipping first row and last row.\n * Same thing is applicable to columns also for column also we want to confined our search from\n * (col - 1) to (grid[0].length - 2) i.e. Skipping first col and last col.\n */\n for (int i = 1; i < grid.length - 1; i++) {\n for (int j = 1; j < grid[0].length - 1; j++) {\n // Try to explore if is a land\n if (grid[i][j] == 0) {\n if (exploreIsland(i, j, grid)) {\n numberOfClosedIsland++;\n }\n }\n }\n }\n\n return numberOfClosedIsland;\n }\n\n /*\n * Will try to explore the part with DFS\n * 0 : Land , 1 : Water & -1 : Visited Position\n */\n public boolean exploreIsland(int row, int col, int[][] grid) {\n\n\n /*\n * ***** NOTE : Keep this condition before base condition of perimeter. Other wise this method will always return false.\n *\n * If we are reaching till to a position which is water or already explored we can return true.\n * As this can lead to a probable closed island\n */\n if (grid[row][col] == 1 || grid[row][col] == -1) {\n return true;\n }\n\n /*\n * Base Condition :\n * Irrespective of land(0) or water(0) if any of the position is lying on the perimeter we want to return false.\n * Because if it is lying on the perimeter it will never be a closed island.\n *\n * So, we want to confined our search from (row - 1) to (grid.length - 2) i.e. Skipping first row and last row.\n * For column also we want to confined our search from (col - 1) to (grid[0].length - 2) i.e. Skipping first col and last col.\n *\n * So if current row is reaching to position 0 or (grid.length - 1) we can return false.\n * For column also if it is reaching to position 0 or (grid[0].length - 1) we can return false.\n */\n if (row == 0 || row == grid.length - 1 || col == 0 || col == grid[0].length - 1) {\n return false;\n }\n\n\n // To denote that this position is visited, instead of boolean[] visited array.\n grid[row][col] = -1;\n\n //Explore left side\n boolean left = exploreIsland(row, col - 1, grid);\n //Explore right side\n boolean right = exploreIsland(row, col + 1, grid);\n //Explore Up side\n boolean up = exploreIsland(row - 1, col, grid);\n //Explore down side\n boolean down = exploreIsland(row + 1, col, grid);\n\n // It will be only closed island if all the side has water in it. So, final result will be ( left && right && up && down )\n return left && right && up && down;\n }\n \n}\n``` | 11 | 0 | ['Java'] | 4 |
number-of-closed-islands | Easy Approach 🔥 Simple DFS with edge cases🔥 Recursion | easy-approach-simple-dfs-with-edge-cases-afo7 | PLEASE UPVOTE \uD83D\uDC4D\n\n# Approach\n### Simple dfs algorithm is used which determines the number of island surrounded by water but we have to take care of | ribhav_32 | NORMAL | 2023-04-06T00:21:16.256612+00:00 | 2023-04-06T00:21:16.256647+00:00 | 785 | false | # **PLEASE UPVOTE \uD83D\uDC4D**\n\n# Approach\n### *Simple dfs algorithm is used which determines the number of island surrounded by water but we have to take care of island at the edges*\n### *that\'s why we have to first use dfs over all the island at the edges*\n# Code\n```\nclass Solution {\npublic:\n int n , m;\n \n void dfs(vector<vector<int>>& a , int i , int j){\n if(i < 0 || j < 0 || j >= m || i >= n || a[i][j] != 0) return;\n a[i][j] = INT_MIN;\n dfs(a , i - 1 , j);\n dfs(a , i + 1 , j);\n dfs(a , i , j - 1);\n dfs(a , i , j + 1);\n }\n \n int closedIsland(vector<vector<int>>& a) {\n n = a.size();\n m = a[0].size();\n \n // DFS for Island at Edges\n for(int i = 0;i < n;i++)\n for(int j = 0;j < m;j++)\n if((j == 0 || i == 0 || j == m-1 || i == n-1) && a[i][j] == 0)\n dfs(a,i,j);\n \n // DFS to find all other islands\n int count = 0;\n for(int i = 0;i < n;i++)\n for(int j = 0;j < m;j++)\n if(a[i][j] == 0){\n count++;\n dfs(a,i,j);\n }\n \n return count;\n }\n};\n```\n\n\n | 11 | 1 | ['Array', 'Depth-First Search', 'Graph', 'Recursion', 'C++'] | 1 |
number-of-closed-islands | 💯C++ ✅ DFS 💥 easy solution with comment | c-dfs-easy-solution-with-comment-by-sona-gxy1 | \n\n# Code\n\nclass Solution {\npublic: int dx[4]={0,0,-1,1};\n int dy[4]={1,-1,0,0};\n/* boundry check kar rhe hai isvalid function ke through ,new x ,n | sonal91022 | NORMAL | 2023-01-23T17:23:19.411243+00:00 | 2023-02-02T17:05:34.561150+00:00 | 751 | false | \n\n# Code\n```\nclass Solution {\npublic: int dx[4]={0,0,-1,1};\n int dy[4]={1,-1,0,0};\n/* boundry check kar rhe hai isvalid function ke through ,new x ,new y grid ke andr hona chiye aur grid[newx][newy] 0 hona chiye \n bool isvalid(int i,int j,int r,int c,vector<vector<int>>& grid){\n if(i>=0 && i<r && j>=0 && j<c && grid[i][j]==0){\n return true;\n }\n else{\n return false;\n }\n }\n\n /*mujhe dfs all possible 4 location me run krna hai lekin pahle check krna padega ki kahi o out of bound to nahi hai ya phir o land hi hai na ,*/\n/* agar o land nahi hai tab v hume back aana hai aur dfs is case ke liye call nahi krenge aur durse ordinate ke liye isvalid function check krnge*/\n void dfs(int i,int j,int r,int c,vector<vector<int>>& grid){\n grid[i][j]=1;\n for(int x=0;x<4;++x){\n int newx=i+dx[x];\n int newy=j+dy[x];\n if(isvalid(newx,newy,r,c,grid)){\n dfs(newx,newy,r,c,grid);\n }\n }\n }\n int closedIsland(vector<vector<int>>& grid) {\n int r=grid.size();\n int c=grid[0].size();\n /*boundary se sate hue 0 ko paani(1) me convert kar rhe hai kuki boundry waale ka kaam nhi hai dfs ka use krke usse satte saare 0 ko 1 kr de rhe hai\n taaki uske andr waale land ko count kr ske */\n for(int i=0;i<r;++i){\n for(int j=0;j<c;++j){\n if(i*j==0 || i==r-1 || j==c-1){\n if(grid[i][j]==0){\n dfs(i,j,r,c,grid);\n }\n \n }\n }\n } int ans=0;\n /* har ek elements in row and coloumn check krna hai ki humara value 0 hai ya nahi agr ye 0 hai then dfs ko call krna hai aur usse satte hue saare \nisland ko 1 marks kar dena hai jitna baar v dfs run hoga utne disconnected island present hai given grid me */\n for(int i=0;i<r;++i){\n for(int j=0;j<c;++j){\n if(grid[i][j]==0){\n ans++;\n dfs(i,j,r,c,grid);\n }\n }\n }\n return ans;\n }\n};\n```\n\n\n | 11 | 0 | ['C++'] | 1 |
number-of-closed-islands | Very Simple Solution with FLOOD FILL | very-simple-solution-with-flood-fill-by-b2bke | \nvar closedIsland = function(grid) {\n let count = 0;\n let row = grid.length;\n let column = grid[0].length;\n for(let i = 0; i<grid.length; i++ | deleted_user | NORMAL | 2022-04-23T12:08:38.260689+00:00 | 2022-04-23T12:08:38.260733+00:00 | 771 | false | ```\nvar closedIsland = function(grid) {\n let count = 0;\n let row = grid.length;\n let column = grid[0].length;\n for(let i = 0; i<grid.length; i++){\n\n for(let j=0; j<grid[0].length; j++){\n if (grid[i][j] == 0){\n if (helper(i,j))count++;\n }\n }\n }\n\n function helper(i,j){\n if (i < 0 || j < 0 || i>=row || j>=column) return false;\n if (grid[i][j]) return true;\n grid[i][j] = true;\n\n let top = helper(i - 1, j)\n let bottom = helper(i + 1, j)\n let left = helper(i, j-1)\n let right = helper(i, j + 1);\n return top && bottom && left && right;\n\n }\n return count\n};\n```\n**PLEASE UPVOTE !** | 11 | 0 | ['Depth-First Search', 'Graph', 'JavaScript'] | 1 |
number-of-closed-islands | [python] Logic Explained, DFS solution | python-logic-explained-dfs-solution-by-1-g2cv | \nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n ## RC ##\n ## APPROACH : DFS ##\n ## LOGIC ##\n ## 1. | 101leetcode | NORMAL | 2020-06-01T22:42:49.823854+00:00 | 2020-06-01T22:42:49.823902+00:00 | 1,845 | false | ```\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n ## RC ##\n ## APPROACH : DFS ##\n ## LOGIC ##\n ## 1. Find, Islands just like normal Leetcode 200. Number of Islands problem.\n ## 2. While doing so, check if every land block, is not in the border.\n ## 3. If it is in the border, mark that Island as Invalid island and after traversal donot include in the count\n \n def dfs( i, j, visited):\n \n if( (i,j) in visited ):\n return\n \n if not self.inValidIsland and ( i== 0 or j == 0 or i == m-1 or j == n-1 ):\n self.inValidIsland = True\n \n visited.add((i,j))\n \n for x,y in directions:\n if 0 <= i+x < m and 0 <= j+y < n and grid[i+x][j+y] == 0:\n dfs( i+x, j+y, visited )\n \n if not grid: return 0\n m, n = len(grid), len(grid[0])\n count, visited = 0, set()\n directions = [(0,1),(1,0),(0,-1),(-1,0)]\n for i in range(m):\n for j in range(n):\n self.inValidIsland = False\n if (i,j) not in visited and grid[i][j] == 0:\n dfs( i, j, visited )\n count = count + (1 if( not self.inValidIsland ) else 0)\n return count\n``` | 11 | 1 | ['Depth-First Search', 'Python', 'Python3'] | 3 |
number-of-closed-islands | Python DFS | python-dfs-by-rooch-t1fd | python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n if len(grid) == 0: return 0\n def help(grid,i,j):\n | rooch | NORMAL | 2020-02-01T13:54:03.982098+00:00 | 2020-02-01T13:54:03.982131+00:00 | 1,188 | false | ```python\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n if len(grid) == 0: return 0\n def help(grid,i,j):\n if i < 0 or j < 0 or i > len(grid)-1 or j > len(grid[0]) -1: return False\n if grid[i][j] == 1: return True\n grid[i][j] = 1\n A = help(grid,i+1,j)\n B = help(grid,i-1,j)\n C = help(grid,i,j+1) \n D = help(grid,i,j-1)\n return A and B and C and D\n \n count = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 0 and help(grid,i,j):\n count += 1\n return count\n``` | 11 | 0 | [] | 4 |
number-of-closed-islands | C++ , DFS , No of islands | c-dfs-no-of-islands-by-baman9451-ofci | 12 ms\n9.5 MB\n```\nclass Solution {\n public:\n \n void dfs(vector>& grid, int i, int j) { // making everthing water , every node connected will be | baman9451 | NORMAL | 2021-05-22T09:37:45.795284+00:00 | 2021-05-22T09:37:45.795330+00:00 | 1,076 | false | 12 ms\n9.5 MB\n```\nclass Solution {\n public:\n \n void dfs(vector<vector<int>>& grid, int i, int j) { // making everthing water , every node connected will become water\n \n if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j])\n return;\n \n grid[i][j] = 1;\n \n dfs(grid,i-1,j);\n dfs(grid,i,j-1);\n dfs(grid,i+1,j);\n dfs(grid,i,j+1);\n }\n\n int closedIsland(vector<vector<int>>& grid) {\n int c = 0;\n \n int n = grid.size();\n int m = grid[0].size();\n \n for(int i=0; i<n; i++) // first and last column\n dfs(grid,i,0), dfs(grid,i,m-1);\n \n for(int j=0; j<m; j++)\n dfs(grid,0,j), dfs(grid,n-1,j); // first and last row\n \n \n // after removing the border connected cases \n // the no of times we ran dfs will give us no of discounted lands\n for(int i=0; i<n; i++)\n for(int j=0; j<m; j++)\n if(!grid[i][j]){ \n dfs(grid,i,j); \n c++;\n }\n \n return c;\n }\n}; | 10 | 1 | ['Depth-First Search', 'C'] | 2 |
number-of-closed-islands | ✔💯 DAY 371 | [JAVA/C++/PYTHON] | EXPLAINED |INTUITION | Approach | PROOF | day-371-javacpython-explained-intuition-pgcyh | \n\n\n# Please Upvote as it really motivates me\n# Intuition \n##### \u2022\tAn island is formed by connecting all of the \'0s\' in all four directions (left, t | ManojKumarPatnaik | NORMAL | 2023-04-06T04:40:19.087664+00:00 | 2023-04-06T13:39:44.178798+00:00 | 426 | false | \n\n\n# Please Upvote as it really motivates me\n# Intuition \n##### \u2022\tAn island is formed by connecting all of the \'0s\' in all four directions (left, top, right, and bottom), which leads us to model the problem as a graph.\n##### \u2022\tTreat the 2D grid as an undirected graph where a land cell corresponds to a node in the graph with an undirected edge between horizontally or vertically adjacent land cells.\n##### \u2022\tTo find an island, begin at any node and proceed to its neighbors, i.e., all nodes one edge away. From the nodes 1 edge away, move to their neighbors, i.e., all the nodes 2 edges away from the starting node, and so on. If we keep traversing until we can\'t anymore, all the nodes that are visited in this traversal together form an island.\n##### \u2022\tWhile traversing the island, look to see if any node in the graph corresponds to a cell at the grid\'s boundary. The island does not form a closed island if any node on it is on the grid\'s boundary. Otherwise, a closed island is formed if there is no node on the grid\'s boundary.\n##### \u2022\tUse a graph traversal algorithm like breadth-first search (BFS) to traverse over the islands. BFS is an algorithm for traversing or searching a graph. It traverses in a level-wise manner, i.e., all the nodes at the present level (say l) are explored before moving on to the nodes at the next level (l + 1), where a level\'s number is the distance from a starting node. BFS is implemented with a queue.\n\n\n##### \u2022\tPerform a BFS from every unvisited land cell, treating it as a node. While traversing the island, check if any node in the island is present on the grid\'s boundary. If we have such a node, the island is not a closed island. Otherwise, we have a closed island if we never visit a cell at the grid\'s edge. As a result, add one to our answer variable.\n\n\n##### \u2022\tIt is important to note that we will not stop the BFS traversal if we come across a node on the boundary. We will perform the complete BFS traversal to cover the entire island so that we can mark all the nodes of the island and not visit any of its nodes again.\n##### \u2022\tReturn the answer variable as the number of closed islands in the grid.\n\n\n\n\n# Approach\n##### \u2022\tTreat the 2D grid as an undirected graph where a land cell corresponds to a node in the graph with an undirected edge between horizontally or vertically adjacent land cells.\n##### \u2022\tBegin at any node and proceed to its neighbors, i.e., all nodes one edge away. From the nodes 1 edge away, move to their neighbors, i.e., all the nodes 2 edges away from the starting node, and so on. If we keep traversing until we can\'t anymore, all the nodes that are visited in this traversal together form an island.\n##### \u2022\tWhile traversing the island, look to see if any node in the graph corresponds to a cell at the grid\'s boundary. The island does not form a closed island if any node on it is on the grid\'s boundary. Otherwise, a closed island is formed if there is no node on the grid\'s boundary.\n##### \u2022\tUse a graph traversal algorithm like breadth-first search (BFS) to traverse over the islands. BFS is an algorithm for traversing or searching a graph. It traverses in a level-wise manner, i.e., all the nodes at the present level (say l) are explored before moving on to the nodes at the next level (l + 1), where a level\'s number is the distance from a starting node. BFS is implemented with a queue.\n##### \u2022\tPerform a BFS from every unvisited land cell, treating it as a node. While traversing the island, check if any node in the island is present on the grid\'s boundary. If we have such a node, the island is not a closed island. Otherwise, we have a closed island if we never visit a cell at the grid\'s edge. As a result, add one to our answer variable.\n##### \u2022\tIt is important to note that we will not stop the BFS traversal if we come across a node on the boundary. We will perform the complete BFS traversal to cover the entire island so that we can mark all the nodes of the island and not visit any of its nodes again.\n##### \u2022\tReturn the answer variable as the number of closed islands in the grid.\n\n\n<!-- Describe your approach to solving the problem. -->\n# ALGORITHM\n\n##### \u2022\tCreate variables m and n to store the number of columns and rows in the given grid.\n##### \u2022\tCreate an answer variable count to keep track of the number of closed islands in grid. Initialize it with 0.\n##### \u2022\tCreate a 2D array called visit to keep track of visited cells.\n##### \u2022\tIterate over all the cells of grid and for every cell (i, j) check if it is a land cell or not. If it is a land cell and it has not been visited yet, begin a BFS traversal from (i, j) cell:\n##### \u2022\tUse the bfs function to perform the traversal. For each call, pass x, y, m, n, grid, and visit as the parameters. The x and y parameters represent the row and column of the cell from which BFS should begin. We start with (i, j) cell.\n##### \u2022\tInitialize a queue q of pair of integers and push (x, y) into it. Mark (x, y) as visited.\n##### \u2022\tCreate a boolean variable isClosed that stores whether or not the current island is a closed island or not. Initialize it to true because we haven\'t found any nodes in the island that are on the grid boundary yet.\n##### \u2022\tWhile the queue is not empty, dequeue the first pair (x, y) from the queue and iterate over all its neighbors. If any neighboring cell is not in bounds of grid, it means the current (x, y) cell is present at the boundary of grid. We do not have a closed island, and we mark isClosed = false. For each neighboring cell, check if it is a land cell or not. If it is a land cell and has not been visited yet, mark it as visited and push (r, c) into the queue.\n##### \u2022\tAfter the queue is empty, return isClosed.\n##### \u2022\tIf bfs returns true, increment count by 1.\n##### \u2022\tReturn count.\n##### \u2022\tNote: It is important to note that we will not stop the BFS traversal if we come across a node on the boundary. We will perform the complete BFS traversal to cover the entire island so that we can mark all the nodes of the island and not visit any of its nodes again.\n\n\n\n# BFS\n# Code\n```python []\nfrom typing import List\nfrom queue import Queue\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n visit = [[False for _ in range(n)] for _ in range(m)]\n count = 0\n\n def bfs(x: int, y: int) -> bool:\n q = Queue()\n q.put((x, y))\n visit[x][y] = True\n isClosed = True\n dirx, diry = [0, 1, 0, -1], [-1, 0, 1, 0]\n\n while not q.empty():\n x, y = q.get()\n for i in range(4):\n r, c = x + dirx[i], y + diry[i]\n if r < 0 or r >= m or c < 0 or c >= n:\n isClosed = False\n elif grid[r][c] == 0 and not visit[r][c]:\n q.put((r, c))\n visit[r][c] = True\n\n return isClosed\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0 and not visit[i][j] and bfs(i, j):\n count += 1\n\n return count\n```\n```c++ []\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n vector<vector<bool>> visit(m, vector<bool>(n));\n int count = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0 && !visit[i][j] && bfs(i, j, m, n, grid, visit)) {\n count++;\n }\n }\n }\n return count;\n }\n\n bool bfs(int x, int y, int m, int n, vector<vector<int>>& grid, vector<vector<bool>>& visit) {\n queue<pair<int, int>> q;\n q.push({x, y});\n visit[x][y] = 2;\n bool isClosed = true;\n\n vector<int> dirx{0, 1, 0, -1};\n vector<int> diry{-1, 0, 1, 0};\n\n while (!q.empty()) {\n x = q.front().first; // row nnumber\n y = q.front().second; // column number\n q.pop();\n\n for (int i = 0; i < 4; i++) {\n int r = x + dirx[i];\n int c = y + diry[i];\n if (r < 0 || r >= m || c < 0 || c >= n) {\n // (x, y) is a boundary cell.\n isClosed = false;\n } else if (grid[r][c] == 0 && !visit[r][c]) {\n q.push({r, c});\n visit[r][c] = true;\n }\n }\n }\n\n return isClosed;\n }\n};\n```\n```java []\nclass Solution {\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n boolean[][] visit = new boolean[m][n];\n int count = 0;\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0 && !visit[i][j] && bfs(i, j, m, n, grid, visit)) {\n count++;\n }\n }\n }\n return count;\n }\n\n public boolean bfs(int x, int y, int m, int n, int[][] grid, boolean[][] visit) {\n Queue<int[]> q = new LinkedList<>();\n q.offer(new int[]{x, y});\n visit[x][y] = true;\n boolean isClosed = true;\n\n int[] dirx = {0, 1, 0, -1};\n int[] diry = {-1, 0, 1, 0};\n\n while (!q.isEmpty()) {\n int[] temp = q.poll();\n x = temp[0];\n y = temp[1];\n\n for (int i = 0; i < 4; i++) {\n int r = x +dirx[i];\n int c = y +diry[i];\n if (r < 0 || r >= m || c < 0 || c >= n) {\n // (x, y) is a boundary cell.\n isClosed = false;\n } else if (grid[r][c] == 0 && !visit[r][c]) {\n q.offer(new int[]{r, c});\n visit[r][c] = true;\n }\n }\n }\n\n return isClosed;\n }\n}\n```\n# DFS \n```PYTHON []\nfrom typing import List\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m, n = len(grid), len(grid[0])\n visit = [[False for _ in range(n)] for _ in range(m)]\n count = 0\n\n def dfs(x: int, y: int) -> bool:\n if x < 0 or x >= m or y < 0 or y >= n:\n return False\n if grid[x][y] == 1 or visit[x][y]:\n return True\n\n visit[x][y] = True\n isClosed = True\n dirx, diry = [0, 1, 0, -1], [-1, 0, 1, 0]\n\n for i in range(4):\n r, c = x + dirx[i], y + diry[i]\n if not dfs(r, c):\n isClosed = False\n\n return isClosed\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 0 and not visit[i][j] and dfs(i, j):\n count += 1\n\n return count\n```\n```C++ []\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size();\n int n = grid[0].size();\n int count = 0;\n vector<vector<bool>> visit(m, vector<bool>(n));\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0 && !visit[i][j] && dfs(i, j, m, n, grid, visit)) {\n count++;\n }\n }\n }\n return count;\n }\n\n bool dfs(int x, int y, int m, int n, vector<vector<int>>& grid, vector<vector<bool>>& visit) {\n if (x < 0 || x >= m || y < 0 || y >= n) {\n return false;\n }\n if (grid[x][y] == 1 || visit[x][y]) {\n return true;\n }\n\n visit[x][y] = true;\n bool isClosed = true;\n vector<int> dirx {0, 1, 0, -1};\n vector<int> diry {-1, 0, 1, 0};\n\n for (int i = 0; i < 4; i++) {\n int r = x + dirx[i];\n int c = y + diry[i];\n if (!dfs(r, c, m, n, grid, visit)) {\n isClosed = false;\n }\n }\n\n return isClosed;\n }\n};\n```\n```JAVA []\nclass Solution {\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n boolean[][] visit = new boolean[m][n];\n int count = 0;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 0 && !visit[i][j] && dfs(i, j, m, n, grid, visit)) {\n count++;\n }\n }\n }\n return count;\n }\n\n public boolean dfs(int x, int y, int m, int n, int[][] grid, boolean[][] visit) {\n if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) {\n return false;\n }\n if (grid[x][y] == 1 || visit[x][y]) {\n return true;\n }\n\n visit[x][y] = true;\n bool isClosed = true;\n int[] dirx = {0, 1, 0, -1};\n int[] diry = {-1, 0, 1, 0};\n\n for (int i = 0; i < 4; i++) {\n int r = x + dirx[i];\n int c = y + diry[i];\n if (!dfs(r, c, m, n, grid, visit)) {\n isClosed = false;\n }\n }\n\n return isClosed;\n }\n}\n```\n\n# UNION FIND\n```C++ []\nclass UnionFound {\n vector<int> roots;\n vector<int> ranks;\npublic:\n UnionFound(int n) {\n roots.resize(n);\n ranks.resize(n, 1);\n\n for (int i = 0; i < n; i++)\n roots[i] = i;\n }\n\n int getRoot(int x) {\n if (roots[x] != x)\n roots[x] = getRoot(roots[x]);\n \n return roots[x];\n }\n\n void join(int x, int y) {\n int rx = getRoot(x), ry = getRoot(y);\n\n if (ranks[rx] < ranks[ry])\n roots[rx] = ry;\n else if (ranks[rx] > ranks[ry]) \n roots[ry] = rx;\n else {\n roots[rx] = ry;\n ranks[rx]++;\n }\n\n return;\n }\n};\n\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int m = grid.size(), n = grid[0].size();\n UnionFound uf(m*n);\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] != 0)\n continue;\n if (i - 1 >= 0 && grid[i-1][j] == 0)\n uf.join(i * n + j, (i-1) * n +j);\n \n if (j - 1 >= 0 && grid[i][j-1] == 0)\n uf.join(i *n + j, i * n + j - 1);\n }\n }\n\n unordered_set<int> groups;\n unordered_set<int> ans;\n\n for (int i = 0; i < m*n; i++) {\n int x= i/n, y = i%n;\n if(grid[x][y] != 0)\n continue;\n int r = uf.getRoot(i);\n if (x == 0 || x == m - 1 || y == 0 || y == n - 1)\n groups.insert(r);\n }\n\n\n for (int i = 0; i < m*n; i++) {\n int x= i/n, y = i%n;\n if (grid[x][y] != 0)\n continue;\n int r = uf.getRoot(i);\n if (groups.count(r) == 0)\n ans.insert(r);\n }\n\n return ans.size();\n }\n};\n```\n```PYTHON []\nclass UnionFind:\n def __init__(self, n):\n self.parents = list(range(n))\n self.ranks = [0] * n\n \n def find(self, i):\n if self.parents[i] != i: self.parents[i] = self.find(self.parents[i])\n return self.parents[i]\n \n def merge(self, i, j):\n ri, rj = self.find(i), self.find(j)\n if ri != rj:\n if self.ranks[ri] == self.ranks[rj]:\n self.parents[ri] = rj\n self.ranks[rj] += 1\n elif self.ranks[ri] < self.ranks[rj]:\n self.parents[ri] = rj\n else:\n self.parents[rj] = ri\n\nclass Solution:\n def closedIsland(self, grid: List[List[int]]) -> int:\n m = len(grid)\n n = len(grid[0])\n def map(r, c): return r * n + c\n\n union_find = UnionFind(m * n)\n island_count = 0\n for r in range(m):\n for c in range(n):\n if grid[r][c] == 0:\n island_count += 1\n for ir, ic in [(0, 1), (1, 0), (-1, 0), (0, -1)]:\n rr, cc = r + ir, c + ic\n if 0 <= rr < m and 0 <= cc < n and grid[rr][cc] == 0:\n if union_find.find(map(r, c)) != union_find.find(map(rr, cc)):\n island_count -= 1\n union_find.merge(map(r, c), map(rr, cc))\n \n open_islands = set()\n for r in range(m):\n if grid[r][0] == 0:\n open_islands.add(union_find.find(map(r, 0)))\n if grid[r][n - 1] == 0:\n open_islands.add(union_find.find(map(r, n - 1)))\n for c in range(n):\n if grid[0][c] == 0:\n open_islands.add(union_find.find(map(0, c)))\n if grid[m - 1][c] == 0:\n open_islands.add(union_find.find(map(m - 1, c)))\n\n return island_count - len(open_islands)\n```\n\n```JAVA []\nclass Solution {\n public int closedIsland(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n\n int lands = 0;\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0) {\n lands++;\n }\n }\n }\n\n UnionFind uf = new UnionFind(m * n, lands);\n\n for (int i = 0; i < m; i++) {\n if (grid[i][0] == 0) {\n uf.initEdge(i * n);\n }\n if (grid[i][n - 1] == 0) {\n uf.initEdge(i * n + n - 1);\n }\n }\n\n for (int j = 1; j < n - 1; j++) {\n if (grid[0][j] == 0) {\n uf.initEdge(j);\n }\n if (grid[m - 1][j] == 0) {\n uf.initEdge((m - 1) * n + j);\n }\n }\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 0) {\n if (i > 0 && grid[i - 1][j] == 0) {\n uf.union(i * n + j, (i - 1) * n + j);\n }\n\n if (j > 0 && grid[i][j - 1] == 0) {\n uf.union(i * n + j, i * n + j - 1);\n }\n }\n }\n }\n\n return uf.getCount();\n }\n\n class UnionFind {\n private int[] parent;\n private int[] rank;\n private boolean[] onEdge;\n private int count;\n\n public UnionFind(int n, int count) {\n parent = new int[n];\n for (int i = 0; i < n; i++) {\n parent[i] = i;\n }\n\n rank = new int[n];\n onEdge = new boolean[n];\n this.count = count;\n }\n\n public void initEdge(int x) {\n if (!onEdge[x]) {\n parent[x] = 0;\n onEdge[x] = true;\n count--;\n }\n }\n\n public void union(int x, int y) {\n int rootx = find(x);\n int rooty = find(y);\n\n if (rootx != rooty) {\n if (rank[rootx] > rank[rooty]) {\n parent[rooty] = rootx;\n onEdge[rootx] |= onEdge[rooty];\n } else if (rank[rootx] < rank[rooty]) {\n parent[rootx] = rooty;\n onEdge[rooty] |= onEdge[rootx];\n } else {\n parent[rooty] = rootx;\n onEdge[rootx] |= onEdge[rooty];\n rank[rootx]++;\n }\n count--;\n }\n }\n\n public int find(int x) {\n if (parent[x] != x) {\n parent[x] = find(parent[x]);\n }\n return parent[x];\n }\n\n public int getCount() {\n return count;\n }\n }\n}\n```\n# SHORTER CODE\n```C++ []\n bool dfs(vector<vector<int>>& grid, int i, int j){\n if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size()) return false;\n if (grid[i][j] == 1) return true;\n grid[i][j] = 1;\n int xy[5]={0,1,0,-1,0};\n bool res=1;\n for(int it=0;it<4;it++){\n bool curr= dfs(grid,i+xy[it],j+xy[it+1]);\n res=curr && res;\n } return res;\n }\n int closedIsland(vector<vector<int>>& grid, int ans = 0) {\n for (int i = 0; i < grid.size(); i++)\n for (int j = 0; j < grid[0].size(); j++)\n if (grid[i][j] == 0)\n if(dfs(grid, i, j)) ans++;\n return ans;\n }\n```\n```python []\ndef dfs(grid, i, j):\n if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]):\n return False\n if grid[i][j] == 1:\n return True\n grid[i][j] = 1\n xy = [0, 1, 0, -1, 0]\n res = True\n for it in range(4):\n curr = dfs(grid, i + xy[it], j + xy[it+1])\n res = curr and res\n return res\n\ndef closedIsland(grid):\n ans = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 0:\n if dfs(grid, i, j):\n ans += 1\n return ans\n```\n```java []\npublic boolean dfs(int[][] grid, int i, int j) {\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[0].length)\n return false;\n if (grid[i][j] == 1)\n return true;\n grid[i][j] = 1;\n int[] xy = {0, 1, 0, -1, 0};\n boolean res = true;\n for (int it = 0; it < 4; it++) {\n boolean curr = dfs(grid, i + xy[it], j + xy[it+1]);\n res = curr && res;\n }\n return res;\n}\n\npublic int closedIsland(int[][] grid) {\n int ans = 0;\n for (int i = 0; i < grid.length; i++) {\n for (int j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == 0) {\n if (dfs(grid, i, j)) {\n ans++;\n }\n }\n }\n }\n return ans;\n}\n```\n\n# Complexity\n\n##### \u2022\tThe time complexity of this algorithm is O(Ef), where E is the number of edges and f is the maximum flow. In the worst-case scenario, the algorithm may need to iterate through all edges for each unit of flow, resulting in a time complexity of O(EV), where V is the number of vertices. \n##### \u2022\tHowever, this worst-case scenario is rare, and the algorithm typically runs much faster. \n##### \u2022\tThe space complexity of the algorithm is O(E+V), as each node is added once.\n\n# DRY RUN\n##### \u2022\tThe input matrix is represented as a 2D array of integers, where 1 represents a cell with a value and 0 represents an empty cell. The algorithm first initializes a Union-Find data structure with each cell as a separate component. It then iterates over the matrix and performs a union operation between adjacent cells that have a value of 1.\n##### \u2022\tThe union operation merges the two components to which the cells belong and updates the rank and parent arrays accordingly. If two components are already merged, the algorithm does not perform the union operation.\n##### \u2022\tFinally, the algorithm returns the count of the number of components in the Union-Find data structure, which represents the number of connected components in the input matrix.\n##### \u2022\tFor the given input matrix, the algorithm would perform the following operations:\n##### \u2022\tInitialize the Union-Find data structure with each cell as a separate component.\n##### \u2022\tIterate over the matrix and perform union operations between adjacent cells that have a value of 1.\n##### \u2022\tUnion(0,1): Merge components containing cells (0,0) and (0,1).\n##### \u2022\tUnion(0,2): Merge components containing cells (0,0), (0,1), and (0,2).\n##### \u2022\tUnion(0,3): Merge components containing cells (0,0), (0,1), (0,2), and (0,3).\n##### \u2022\tUnion(0,4): Merge components containing cells (0,0), (0,1), (0,2), (0,3), and (0,4).\n##### \u2022\tUnion(0,5): Merge components containing cells (0,0), (0,1), (0,2), (0,3), (0,4), and (0,5).\n##### \u2022\tUnion(0,6): Merge components containing cells (0,0), (0,1), (0,2), (0,3), (0,4), (0,5), and (0,6).\n##### \u2022\tUnion(1,5): Merge components containing cells (1,1) and (1,5).\n##### \u2022\tUnion(1,6): Merge components containing cells (1,1), (1,5), and (1,6).\n##### \u2022\tUnion(2,4): Merge components containing cells (2,2) and (2,4).\n##### \u2022\tUnion(2,5): Merge components containing cells (2,2), (2,4), and (2,5).\n##### \u2022\tUnion(2,6): Merge components containing cells (2,2), (2,4), (2,5), and (2,6).\n##### \u2022\tUnion(3,5): Merge components containing cells (3,5) and (3,5).\n##### \u2022\tUnion(3,6): Merge components containing cells (3,5), (3,6), and (3,6).\n##### \u2022\tUnion(4,7): Merge components containing cells (4,0) and (4,7).\n##### \u2022\tReturn the count of the number of components in the Union-Find data structure, which is 2.\n##### \u2022\tTherefore, the output of the given input matrix would be 2.\n\n\n\n\n\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n\nhttps://leetcode.com/problems/number-of-closed-islands/solutions/3385159/day-371-java-c-python-explained-intuition-approach-proof/?orderBy=hot\n | 9 | 0 | ['Union Find', 'Python', 'C++', 'Java', 'Python3'] | 0 |
number-of-closed-islands | ✅ C++ || DFS || Easy to understand | c-dfs-easy-to-understand-by-indresh149-lo0a | \nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int res = 0;\n for (int i = 0; i < grid.size(); i++){\n | indresh149 | NORMAL | 2022-09-02T11:54:29.967982+00:00 | 2022-09-02T11:54:29.968013+00:00 | 661 | false | ```\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int res = 0;\n for (int i = 0; i < grid.size(); i++){\n for (int j = 0; j < grid[0].size(); j++){\n if (grid[i][j] == 0){\n res += dfs(grid, i, j) ? 1 : 0;\n }\n }\n }\n return res;\n }\n bool dfs(vector<vector<int>>& g, int i, int j){\n if (i < 0 || j < 0 || i >= g.size() || j >= g[0].size()){\n return false;\n }\n if (g[i][j] == 1){\n return true;\n }\n g[i][j] = 1;\n /* IMPORTANT NOTE: \n WHY I CANNOT USE `return dfs(g, i+1, j) && dfs(g, i, j+1) && dfs(g, i-1, j) && dfs(g, i, j-1);`???\n BECAUSE IF ANY OF THE FIRST DFS() RETURNS FALSE, FOLLOWING ONES WILL NOT EXECUTE!!! THEN WE DON\'T\n HAVE THE CHANCE TO MARK THOSE 0s TO 1s!!!\n */\n bool d1 = dfs(g, i+1, j);\n bool d2 = dfs(g, i, j+1);\n bool d3 = dfs(g, i-1, j);\n bool d4 = dfs(g, i, j-1);\n return d1 && d2 && d3 && d4;\n }\n};\n```\n**Don\'t forget to Upvote the post, if it\'s been any help to you** | 9 | 0 | ['Depth-First Search', 'Graph', 'C'] | 2 |
number-of-closed-islands | [C++] 2 approaches | DFS | BFS | Easy to understand | c-2-approaches-dfs-bfs-easy-to-understan-hbbz | The idea is at first we traverse through the boundary of the grid and on seeing any 0 (land), we apply BFS or DFS, and visit all the unvisited 0s which we can r | sk__22 | NORMAL | 2022-01-20T09:13:56.838142+00:00 | 2022-01-20T09:32:11.595793+00:00 | 731 | false | The idea is at first we traverse through the boundary of the grid and on seeing any 0 (land), we apply BFS or DFS, and visit all the unvisited 0s which we can reach. These 0s will never be a part of any closed island. \n\nThen we traverse the cells which are not on boundary, if any cell is 0 (land) and not visited, we call BFS or DFS on it, and it visits all the unvisited 0s connected from this cell. Idea is the number of times we call a DFS or BFS, it means these number of closed islands are present and we increment ans variable by 1. \n\n\n\n**BFS Solution** \n\nTime Complexity:- O(mn), where mn is the total number of cells in the grid\nSpace Complexity:- O(mn), space occupied by visited array\n\n```\nclass Solution {\npublic:\n \n void bfs(vector<vector<int>>& grid, vector<vector<int>>& vis, int i, int j, int m, int n)\n {\n queue<pair<int,int>> q;\n q.push({i,j});\n\t\tvis[i][j]=1;\n while(q.empty()!=1)\n {\n pair<int,int> curr = q.front();\n q.pop();\n vector<int> dx{-1,1,0,0};\n vector<int> dy{0,0,1,-1};\n for(int k=0;k<4;k++)\n {\n int X = curr.first+dx[k];\n int Y = curr.second+dy[k];\n if(X>=0 && X<m && Y>=0 && Y<n && grid[X][Y]==0 && vis[X][Y]==0)\n {\n q.push({X,Y});\n vis[X][Y]=1;\n }\n }\n }\n }\n\n \n int closedIsland(vector<vector<int>>& grid) \n {\n int m = grid.size();\n int n = grid[0].size();\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if((i*j==0 || i==m-1 || j==n-1)&& grid[i][j]==0 && vis[i][j]==0)\n {\n bfs(grid, vis, i, j, m, n);\n } \n }\n }\n int ans = 0;\n for(int i=1;i<m-1;i++)\n {\n for(int j=1;j<n-1;j++)\n {\n if(grid[i][j]==0 && vis[i][j]==0)\n {\n bfs(grid,vis,i,j,m,n);\n ans++;\n }\n }\n }\n return ans;\n }\n};\n```\n\n\n\n**DFS Solution**\n\nTime Complexity:- O(mn), where mn is the total number of cells in the grid\nSpace Complexity:- O(mn), space occupied by visited array\n\n```\nclass Solution {\npublic:\n void dfs(vector<vector<int>>& grid, vector<vector<int>>& vis, int i, int j, int m, int n)\n {\n vis[i][j]=1;\n vector<int> dx{-1,1,0,0};\n vector<int> dy{0,0,1,-1};\n for(int k=0;k<4;k++)\n {\n int X = i+dx[k];\n int Y = j+dy[k];\n if(X>=0 && X<m && Y>=0 && Y<n && grid[X][Y]==0 && vis[X][Y]==0)\n {\n dfs(grid,vis,X,Y,m,n);\n }\n }\n }\n \n int closedIsland(vector<vector<int>>& grid) \n {\n int m = grid.size();\n int n = grid[0].size();\n vector<vector<int>> vis(m,vector<int>(n,0));\n \n \n for(int i=0;i<m;i++)\n {\n for(int j=0;j<n;j++)\n {\n if((i*j==0 || i==m-1 || j==n-1)&& grid[i][j]==0 && vis[i][j]==0)\n {\n dfs(grid, vis, i, j, m, n);\n } \n }\n }\n int ans = 0;\n for(int i=1;i<m-1;i++)\n {\n for(int j=1;j<n-1;j++)\n {\n if(grid[i][j]==0 && vis[i][j]==0)\n {\n dfs(grid,vis,i,j,m,n);\n ans++;\n }\n }\n }\n return ans; \n }\n};\n``` | 9 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Graph', 'Recursion', 'C'] | 3 |
number-of-closed-islands | [Java] DFS | 100% Faster | Clean Code | java-dfs-100-faster-clean-code-by-akbero-lrgv | \nclass Solution {\n public int closedIsland(int[][] grid) {\n \n for(int i = 0; i < grid.length; ++i) {\n if(grid[i][0] == 0) dfs(g | akberovr | NORMAL | 2021-01-21T11:13:58.752688+00:00 | 2021-01-21T11:13:58.752716+00:00 | 1,013 | false | ```\nclass Solution {\n public int closedIsland(int[][] grid) {\n \n for(int i = 0; i < grid.length; ++i) {\n if(grid[i][0] == 0) dfs(grid,i,0);\n if(grid[i][grid[0].length - 1] == 0) dfs(grid,i,grid[0].length - 1);\n }\n \n for(int i = 0; i < grid[0].length; ++i) { \n if(grid[0][i] == 0) dfs(grid, 0, i);\n if(grid[grid.length - 1][i] == 0) dfs(grid, grid.length-1, i);\n \n }\n \n int counter = 0;\n for(int i = 0; i < grid.length; ++i) {\n for(int j = 0; j < grid[0].length; ++j) {\n if(grid[i][j] == 0) {\n dfs(grid,i,j);\n counter++;\n }\n }\n }\n \n return counter;\n }\n \n private void dfs(int[][] grid, int i, int j) {\n if( i > grid.length-1 || j > grid[0].length-1 || i < 0 || j < 0 || grid[i][j] != 0){\n return;\n }\n \n grid[i][j] = -1;\n dfs(grid, i+1, j);\n dfs(grid, i-1, j);\n dfs(grid, i, j+1);\n dfs(grid, i, j-1);\n }\n}\n``` | 9 | 0 | ['Java'] | 2 |
number-of-closed-islands | Java || DFS solution with comments | java-dfs-solution-with-comments-by-kashu-zxld | class Solution {\n \n public int closedIsland(int[][] grid) {\n int num = 0;\n\t\t\n/ \nDFS functions is used twice\n\t1. To label nodes which can r | kashup12 | NORMAL | 2020-10-05T04:57:24.557649+00:00 | 2020-10-05T04:59:18.205500+00:00 | 825 | false | class Solution {\n \n public int closedIsland(int[][] grid) {\n int num = 0;\n\t\t\n/* \nDFS functions is used twice\n*\t1. To label nodes which can reach to boundary\n*\t2. To count all closed islands.\n\t\n*/ \n\t// Calling DFS to label all other nodes which are connected by boundaries\n\t\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[i].length;j++){\n if( i ==0 || j == 0 || i == grid.length-1 || j== grid[i].length-1){\n if (grid[i][j] == 0){\n DFS(grid, i, j); \n }\n }\n }\n }\n\n// Counting all closed islands\n\n for(int i=0;i<grid.length;i++){\n for(int j=0;j<grid[i].length;j++){\n if (grid[i][j] == 0){\n DFS(grid, i, j); \n num++;\n } \n }\n }\n \n return num;\n }\n \n void DFS(int grid[][],int i,int j){\n\t//Base Case\n if (i < 0 || j < 0 || i >= grid.length || j >= grid[i].length || grid[i][j] == 2 || grid[i][j] == 1) return;\n \n\t\t // marking the visited node\n\t\t \n grid[i][j] = 2; \n\t\t\n\t\t// Calling in 4 directions\n \n\t DFS(grid, i + 1, j);\n DFS(grid, i - 1, j);\n DFS(grid, i, j + 1);\n DFS(grid, i, j-1);\n }\n \n} | 9 | 0 | [] | 1 |
number-of-closed-islands | Easy method | easy-method-by-ashish_49-egbs | \n# Approach\nmake all boundary lands to water and after that traversal a simle dfs \n\n\n\n# Code\n\nclass Solution {\npublic:\n void dfs(int rw,int cl,vect | Ashish_49 | NORMAL | 2023-04-06T18:00:01.452901+00:00 | 2023-04-06T18:00:01.452946+00:00 | 37 | false | \n# Approach\nmake all boundary lands to water and after that traversal a simle dfs \n\n\n\n# Code\n```\nclass Solution {\npublic:\n void dfs(int rw,int cl,vector<vector<int>>&vis,vector<vector<int>>& gd,int ar[],int ac[]){\n vis[rw][cl]=1;\n int n=gd.size();\n int m=gd[0].size();\n for(int i=0;i<4;i++){\n int nrw=rw+ar[i];\n int ncl=cl+ac[i];\n if(nrw>=0 && nrw<n && ncl>=0 && ncl<m && !vis[nrw][ncl] && gd[nrw][ncl]==0){\n dfs(nrw,ncl,vis,gd,ar,ac);\n }\n }\n}\n \n int closedIsland(vector<vector<int>>& gd) {\n\n int n=gd.size();\n int m=gd[0].size();\n\n vector<vector<int>>vis(n,vector<int>(m,0));\n int ar[]={-1,0,1,0};\n int ac[]={0,1,0,-1};\n\n // mark the boundary\n\n for(int i=0; i<n; i++){\n if(!vis[i][0] and gd[i][0]==0){\n dfs(i,0,vis,gd,ar,ac);\n }\n if(!vis[i][m-1] and gd[i][m-1]==0){\n dfs(i,m-1, vis, gd, ar,ac);\n }\n }\n for(int j=0;j<m;j++){\n if(!vis[0][j] && gd[0][j]==0){\n dfs(0,j,vis,gd,ar,ac);\n }\n if(!vis[n-1][j] && gd[n-1][j]==0){\n dfs(n-1,j,vis,gd,ar,ac);\n }\n }\n\n\n // after marked the boundary now \nint ct=0;\n for(int i=0; i<n; i++){\n for(int j=0; j<m; j++){\n if(!vis[i][j] && gd[i][j]==0){\n dfs(i,j,vis,gd,ar,ac);\n ct++;\n }\n }\n }\nreturn ct;\n }\n};\n``` | 8 | 0 | ['C++'] | 0 |
number-of-closed-islands | ✅ Java | Easy DFS Solution Explained 📝 | Beginner friendly | Beats 100% | java-easy-dfs-solution-explained-beginne-fy5e | Intuition\nSince we need to find an island is close or not(that is surrounded by water), this would involve exploring all 4 directions so DFS comes to mind\n\nH | nikeMafia | NORMAL | 2023-04-06T03:08:53.628402+00:00 | 2023-05-01T06:32:50.357407+00:00 | 898 | false | # Intuition\nSince we need to find an island is close or not(that is surrounded by water), this would involve exploring all 4 directions so DFS comes to mind\n\nHighly suggest solving this question before looking at the solution if you haven\'t already\nLC 200 : [Number of Islands](https://leetcode.com/problems/number-of-islands/)\n\n---\n\n# Approach\n1) Assuming you solved Number of islands question now you have understanding of how to move in different directions up = row-1, down = row+1, left = col-1, right =col+1\n2) All the boundaries of the grid i.e first row, last row, first col and last col will never form closed island as they are not surrounded by water from atleast one side. So we only traversing grid from i=1 and j=1.\n3) We call dfs for only land(0) i.e grid[i][j]=0 case\n4) First condition in dfs is to check bounds(mentioned in code) i.e the row, col are not overflow out of valid indexes\n5) If we see a water(1) or visited/already explored(-1) then it can probably lead to a closed island mark it true.\n6) Similarly we explore all 4 sides up, down, left, right\n7) We also mask(mark visited) grid element(by marking it -1) before moving onto its 4 directions.\n8) & of all direction returns true that means we found a close island\nrepeat the process for all 0\'s i.e water in grid\n\n\n---\n\n\n- Time complexity:\nO(n^2) Since we are traversing all elements of the grid\n\nHope it is easy to understand.\nLet me know if there is something unclear and i can fix it.\n\nOtherwise, please upvote if you like the solution, it would be encouraging\n\n\n\n# Code\n```\nclass Solution {\n int [][] directions = {{0,1},{0,-1},{1,0},{-1,0}};\n\n public int closedIsland(int[][] grid) {\n int row = grid.length;\n int col = grid[0].length;\n int islands = 0;\n \n for(int i=1; i<row; i++){\n for(int j=1; j<col; j++){\n if(grid[i][j]==0){\n if(dfs(grid, i, j))\n islands++;\n } \n }\n }\n return islands;\n }\n \n // 0 land :: 1 water :: -1 already visited\n private boolean dfs(int [][] grid, int row, int col){\n //check bounds\n if(row<0 || row>=grid.length || col<0 || col>=grid[0].length)\n return false;\n\n // water or already visited grid element can lead to closed island so we return true\n if (grid[row][col] == 1 || grid[row][col] == -1)\n return true;\n \n\n grid[row][col] = -1;\n \n Boolean isClose = true;\n isClose &= dfs(grid, row-1, col);\n isClose &= dfs(grid, row+1, col);\n isClose &= dfs(grid, row, col-1);\n isClose &= dfs(grid, row, col+1);\n\n return isClose;\n }\n}\n``` | 8 | 2 | ['Depth-First Search', 'Java'] | 0 |
number-of-closed-islands | Clean & simple code || C++ || Explained | clean-simple-code-c-explained-by-amankat-x4uw | \n# Approach\nfirst of we will try to visit all the land part (zeros) which are at the edges or connected to edegs of our square , because these island could no | amankatiyar783597 | NORMAL | 2023-04-06T02:25:54.751124+00:00 | 2023-04-06T02:25:54.751157+00:00 | 2,238 | false | \n# Approach\nfirst of we will try to visit all the land part (zeros) which are at the edges or connected to edegs of our square , because these island could not be part of answer and , we will mark them as visted so that we dot not need to visit when we will be collecting answer.\n\n`This piece of code will mark all edges or edges contected lant to visited`\n\n```\nfor(int i=0;i<n;i++){\n if(gr[i][0]==0){\n dfs(gr,i,0);\n }\n if(gr[i][m-1]==0){\n dfs(gr,i,m-1);\n }\n}\nfor(int i=0;i<m;i++){\n if(gr[0][i]==0){\n dfs(gr,0,i);\n }\n if(gr[n-1][i]==0){\n dfs(gr,n-1,i);\n }\n}\n```\nAfter marking them visted we just need to find number of island , this can be done by simply using DFS. even we can use BFS to.\n\n\n# Complexity\n- Time complexity:\nSize of Grid or O(m*n)\n\n- Space complexity:\nsize of grid or O(m*n)\n\n# Code\n```\nclass Solution {\npublic:\n\n void dfs(vector<vector<int>>&gr , int i, int j){\n if(i==gr.size() || j == gr[0].size() || j<0 || i<0 ) return;\n if(gr[i][j]==1) return;\n gr[i][j]=1;\n dfs(gr,i+1,j);\n dfs(gr,i-1,j);\n dfs(gr,i,j-1);\n dfs(gr,i,j+1);\n }\n\n int closedIsland(vector<vector<int>>& gr) {\n int n= gr.size();\n int m = gr[0].size();\n for(int i=0;i<n;i++){\n if(gr[i][0]==0){\n dfs(gr,i,0);\n }\n if(gr[i][m-1]==0){\n dfs(gr,i,m-1);\n }\n }\n for(int i=0;i<m;i++){\n if(gr[0][i]==0){\n dfs(gr,0,i);\n }\n if(gr[n-1][i]==0){\n dfs(gr,n-1,i);\n }\n }\n int c=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(gr[i][j]==0){\n c++;\n dfs(gr,i,j);\n }\n }\n }\n return c;\n }\n};\n``` | 8 | 1 | ['C++'] | 0 |
number-of-closed-islands | C++ | easy explanation | DFS | Striver style | | c-easy-explanation-dfs-striver-style-by-wvynp | This probelm is similar to number of enclaves sum (no.1020). We will be performing the DFS across the boundaries as we know the boundary lands cannot form a clo | avinashyerra | NORMAL | 2023-04-06T09:09:50.145496+00:00 | 2023-04-06T09:09:50.145540+00:00 | 921 | false | This probelm is similar to number of enclaves sum (no.1020). We will be performing the DFS across the boundaries as we know the boundary lands cannot form a closed island, we will maintain a visited vector and mark the boundary zeroes as visited , after marking them as visited the problem reduces to count the number of connected components using DFS we will again run the loop across the grid and check for unvisited zeroes inside the grid( not boundaries) and maintain a count how many times DFS has been called this gives the resultant answer.\n \n\n void dfs(int row,int col,vector<vector<int>>&vis,vector<vector<int>>& grid,int delr[],int delc[]){\n vis[row][col]=1;\n int n=grid.size();\n int m=grid[0].size();\n for(int i=0;i<4;i++){\n int nrow=row+delr[i];\n int ncol=col+delc[i];\n if(nrow>=0 && nrow<n && ncol>=0 && ncol<m && !vis[nrow][ncol] && grid[nrow][ncol]==0){\n dfs(nrow,ncol,vis,grid,delr,delc);\n }\n }\n }\n int closedIsland(vector<vector<int>>& grid) {\n int n=grid.size();\n int m=grid[0].size();\n vector<vector<int>>vis(n,vector<int>(m,0));\n int delr[]={-1,0,1,0};\n int delc[]={0,1,0,-1};\n //marking boundaries\n for(int j=0;j<m;j++){\n if(!vis[0][j] && grid[0][j]==0){\n dfs(0,j,vis,grid,delr,delc);\n }\n if(!vis[n-1][j] && grid[n-1][j]==0){\n dfs(n-1,j,vis,grid,delr,delc);\n }\n }\n for(int i=0;i<n;i++){\n if(!vis[i][0] && grid[i][0]==0){\n dfs(i,0,vis,grid,delr,delc);\n }\n if(!vis[i][m-1] && grid[i][m-1]==0){\n dfs(i,m-1,vis,grid,delr,delc);\n }\n }\n\t\t//finding the count of unvisited zeroes \n int ans=0;\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!vis[i][j] && grid[i][j]==0){\n dfs(i,j,vis,grid,delr,delc);\n ans++;\n }\n }\n }\n return ans;\n }\n\n | 7 | 0 | ['Depth-First Search', 'Recursion', 'C'] | 1 |
number-of-closed-islands | ✅✅ Easy C++ Solution | Beginner friendly | DFS | Recursion | Striver | Clean Codes | easy-c-solution-beginner-friendly-dfs-re-si05 | Intuition\nThe Islands which by any means are NOT connected to boundaries(first row, last row, first coloumn, last coloumn) are our answer.\n Describe your firs | warrior0331 | NORMAL | 2023-04-06T09:02:33.300699+00:00 | 2023-04-06T10:43:41.802819+00:00 | 1,179 | false | # Intuition\nThe Islands which by any means are **NOT** connected to boundaries(first row, last row, first coloumn, last coloumn) are our answer.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBasically we have to find the number of connected components(land) which are not connected to boundaries. \nSimply find the total number of connected components(lands) in the graph using DFS.\nNow, run four loops for the mentioned boundaries and in each loop call DFS again for not visited lands, increase the counter for them as they are the Islands which are by some means connectd to the boundary.\nFinally return the difference between total components and the boundary components.\n\nAfter seeing the code you will get full understanding of the approach.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(NxM)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(NxM)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\nvector<pair<int,int>> moves = {{0,-1},{0,1},{-1,0},{1,0}};\n\nbool isValidIndex(int x, int y, int n, int m){\n if(x>=0 and y>=0 and x<n and y<m) return true;\n else return false;\n}\n\nvoid dfs(int x, int y, vector<vector<int>> &grid, vector<vector<int>> &vis, int n ,int m){\n vis[x][y]=1;\n for(auto p:moves){\n int nX=x+p.first;\n int nY=y+p.second;\n if(isValidIndex(nX,nY,n,m)){\n if(grid[nX][nY]==0 and !vis[nX][nY]){\n dfs(nX,nY,grid,vis,n,m);\n }\n }\n }\n}\n\n int closedIsland(vector<vector<int>>& grid) {\n\n int n=grid.size();\n int m=grid[0].size();\n\n int totalCC=0;\n vector<vector<int>> vis2(n,vector<int> (m,0));\n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(grid[i][j]==0 and !vis2[i][j]){\n totalCC++;\n dfs(i,j,grid,vis2,n,m);\n }\n }\n }\n\n int excludedIslands=0;\n vector<vector<int>> vis(n,vector<int> (m,0));\n for(int i=0;i<m;i++){\n if(grid[0][i]==0 and !vis[0][i]){\n excludedIslands++;\n dfs(0,i,grid,vis,n,m);\n }\n }\n for(int i=0;i<m;i++){\n if(grid[n-1][i]==0 and !vis[n-1][i]){\n excludedIslands++;\n dfs(n-1,i,grid,vis,n,m);\n }\n }\n for(int i=0;i<n;i++){\n if(grid[i][0]==0 and !vis[i][0]){\n excludedIslands++;\n dfs(i,0,grid,vis,n,m);\n }\n }\n for(int i=0;i<n;i++){\n if(grid[i][m-1]==0 and !vis[i][m-1]){\n excludedIslands++;\n dfs(i,m-1,grid,vis,n,m);\n }\n }\n return totalCC-excludedIslands;\n }\n};\n```\n# ***Please upvote if the explanation was useful and easy to understand.***\n***Happy Coding!***\n | 7 | 1 | ['C++'] | 0 |
number-of-closed-islands | Easy to understand solution with comments | easy-to-understand-solution-with-comment-tsnu | JavaScript Solution\n\n// Set constants for the different types of cells in the grid\nconst land = 0;\nconst water = 1;\nconst visitedLand = 2;\n\n// Set up the | emmakuen | NORMAL | 2023-04-06T04:19:07.656676+00:00 | 2023-04-06T04:19:07.656724+00:00 | 973 | false | ## JavaScript Solution\n```\n// Set constants for the different types of cells in the grid\nconst land = 0;\nconst water = 1;\nconst visitedLand = 2;\n\n// Set up the four possible directions to move from a given cell\nconst directions = [\n [1, 0], // Down\n [0, 1], // Right\n [-1, 0], // Up\n [0, -1], // Left\n];\n\n// Define the main function that counts the number of closed islands in the grid\nvar closedIsland = function (grid) {\n // Initialize a counter for the number of closed islands\n let closedIslandCount = 0;\n\n // Loop through every cell in the grid\n for (let row = 0; row < grid.length; row++) {\n for (let col = 0; col < grid[0].length; col++) {\n // If the current cell is land and forms a closed island, increment the counter\n if (grid[row][col] === land && isClosedIsland(row, col)) {\n closedIslandCount++;\n }\n }\n }\n\n // Return the final count of closed islands\n return closedIslandCount;\n\n // Define the helper function that checks if a given cell is part of a closed island\n function isClosedIsland(startRow, startCol) {\n // Mark the starting cell as visited\n grid[startRow][startCol] = visitedLand;\n\n // Initialize a queue to hold cells to visit and a flag to track if the island is closed\n const queue = [[startRow, startCol]];\n let isClosed = true;\n\n // Loop through the queue until it\'s empty\n while (queue.length > 0) {\n // Remove the next cell from the front of the queue and check its neighbors\n const [row, col] = queue.shift();\n for (const [rowDir, colDir] of directions) {\n // Calculate the row and column indices of the neighbor cell\n const nextRow = row + rowDir;\n const nextCol = col + colDir;\n\n // If the neighbor cell is outside the grid, the island is open\n if (\n nextRow >= grid.length ||\n nextRow < 0 ||\n nextCol >= grid[0].length ||\n nextCol < 0\n ) {\n isClosed = false;\n }\n // If the neighbor cell is land and hasn\'t been visited yet, add it to the queue\n else if (grid[nextRow][nextCol] === land) {\n grid[nextRow][nextCol] = visitedLand;\n queue.push([nextRow, nextCol]);\n }\n }\n }\n\n // Return whether the island is closed\n return isClosed;\n }\n};\n``` | 7 | 1 | ['Array', 'Breadth-First Search', 'Queue', 'JavaScript'] | 1 |
number-of-closed-islands | C++ HIGHLY READABLE & COMMENTED CODE | c-highly-readable-commented-code-by-sm32-pnqa | PLZ UPVOTE IF YOU LIKEF IT\n\n```\nclass Solution {\npublic:\n \n void dfs(vector>& grid,int i,int j){\n \n // Just the normal limits check | sm3210 | NORMAL | 2021-07-27T10:49:58.208959+00:00 | 2021-07-27T10:49:58.208990+00:00 | 585 | false | **PLZ UPVOTE IF YOU LIKEF IT**\n\n```\nclass Solution {\npublic:\n \n void dfs(vector<vector<int>>& grid,int i,int j){\n \n // Just the normal limits check and condition check \n if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size() || grid[i][j]==1)\n return;\n \n //update the value from Water To Land\n grid[i][j]=1;\n \n // DFS in all 4 directions\n dfs(grid,i+1,j);\n dfs(grid,i,j+1);\n dfs(grid,i-1,j);\n dfs(grid,i,j-1);\n }\n \n int closedIsland(vector<vector<int>>& grid) {\n int m=grid.size();\n int n=grid[0].size();\n \n // Update all the corners which are of no use from land to water through DFS\n for(int i=0;i<m;i++){\n if(grid[i][0]==0)\n dfs(grid,i,0);\n if(grid[i][n-1]==0)\n dfs(grid,i,n-1);\n }\n // Update all the corners which are of no use from land to water through DFS\n for(int i=0;i<n;i++){\n if(grid[0][i]==0)\n dfs(grid,0,i);\n if(grid[m-1][i]==0)\n dfs(grid,m-1,i);\n }\n \n int count=0;\n \n //Now Count all the island present inside and return answer\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(grid[i][j]==0){\n dfs(grid,i,j);\n count++;\n }\n }\n }\n return count;\n \n }\n}; | 7 | 1 | ['C', 'C++'] | 0 |
number-of-closed-islands | Java DFS 100% | java-dfs-100-by-rchanana-98ez | \n\tclass Solution {\n\t\tpublic int closedIsland(int[][] grid) {\n\t\t\tif (grid.length == 0) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint numIslands = 0;\n\t\t\tf | rchanana | NORMAL | 2020-01-14T22:12:22.777354+00:00 | 2020-01-14T22:12:46.035428+00:00 | 803 | false | \n\tclass Solution {\n\t\tpublic int closedIsland(int[][] grid) {\n\t\t\tif (grid.length == 0) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tint numIslands = 0;\n\t\t\tfor (int i = 0 ; i < grid.length; i++) {\n\t\t\t\tfor (int j = 0; j < grid[0].length; j++) {\n\t\t\t\t\tif(grid[i][j] == 0 && isClosedIsland(grid, i,j)) {\n\t\t\t\t\t\tnumIslands++;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn numIslands;\n\t\t}\n\n\t\tprivate boolean isClosedIsland(int[][] grid, int i, int j) {\n\t\t\tif (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (grid[i][j] == 1) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tgrid[i][j] = 1;\n\t\t\treturn (isClosedIsland(grid, i - 1, j) & isClosedIsland(grid, i + 1, j) & isClosedIsland(grid, i, j - 1) & isClosedIsland(grid, i, j + 1));\n\t\t}\n\t} | 7 | 0 | [] | 2 |
number-of-closed-islands | EASY DFS CODE... ✅ beginner friendly, C++ | easy-dfs-code-beginner-friendly-c-by-xia-vgla | Approach\nhere we apply dfs to each element of grid[i][j].\nif grid is land then only apply dfs\nand cover it with any unique number as i chosed 2313+((200 * j) | XIAO-summer | NORMAL | 2023-04-06T19:26:48.020742+00:00 | 2023-04-06T19:26:48.020776+00:00 | 76 | false | # Approach\nhere we apply dfs to each element of grid[i][j].\nif grid is land then only apply dfs\nand cover it with any unique number as i chosed 2313+((200 * j) + (i))).\nand continue our approach of applying dfs.\neverytime we approach a new entity we updated our count, as taken by flag.\nAnd fiinally we return our count...\n\n# Code\n```\nclass Solution {\npublic:\n\n bool dfs(vector<vector<int>> &grid, int i, int j, int n, int m, int value) {\n if(i < 0 || i >= n || j < 0 || j >= m) return false;\n if(grid[i][j] == 1 || grid[i][j] == value) return true;\n grid[i][j] = value;\n bool ans = dfs(grid, i+1, j, n, m, value) && \n dfs(grid, i-1, j, n, m, value) && \n dfs(grid, i, j+1, n, m, value) && \n dfs(grid, i, j-1, n, m, value);\n return ans;\n }\n\n int closedIsland(vector<vector<int>>& grid) {\n int n = grid.size();\n int m = grid[0].size();\n int count = 0;\n for(int i = 0; i < n; i++) {\n for(int j = 0; j < m; j++) {\n if(grid[i][j] == 0) {\n bool flag = dfs(grid, i, j, n, m, 2313+((200 * j) + (i)));\n if(flag) {\n count++;\n cout << i << " " << j << endl;\n }\n }\n }\n }\n return count;\n }\n};\n``` | 6 | 0 | ['C++'] | 4 |
number-of-closed-islands | Java solution using BFS and DFS with explanation | java-solution-using-bfs-and-dfs-with-exp-f0ip | \nclass Solution {\n public int closedIsland(int[][] grid) {\n int totalRows= grid.length;\n int totalCols= grid[0].length;\n int ans=0; | cherry-singla | NORMAL | 2022-08-25T13:55:52.999420+00:00 | 2022-08-25T13:55:52.999461+00:00 | 649 | false | ```\nclass Solution {\n public int closedIsland(int[][] grid) {\n int totalRows= grid.length;\n int totalCols= grid[0].length;\n int ans=0;\n \n /* \n 1. Iterate over the borders, and see if any island starts from the border itself.\n 2. If starts from border(i.e. cell value is 0), find that island and change the cell values to 1 using DFS/BFS. \n 3. 2nd step will modify the grid and removes the possibility to get open (not closed) islands.\n 4. Now, the problem is modified to find "Number of Islands (Leetcode #200)" using modified grid.\n */\n \n for(int currCol=0; currCol<totalCols; currCol++){\n if(grid[0][currCol]==0) //first row\n bfs(grid, 0, currCol, totalRows, totalCols); \n if(grid[totalRows-1][currCol]==0) //last row\n bfs(grid, totalRows-1, currCol, totalRows, totalCols);\n }\n \n for(int currRow=0; currRow<totalRows; currRow++){\n if(grid[currRow][0]==0) //first column\n bfs(grid, currRow, 0, totalRows, totalCols);\n if(grid[currRow][totalCols-1]==0) //last column\n bfs(grid, currRow, totalCols-1, totalRows, totalCols);\n }\n \n /* Iterate over modified grid and find number of islands */\n for(int currRow=1; currRow<totalRows-1; currRow++){\n for(int currCol=1; currCol<totalCols-1; currCol++){\n if(grid[currRow][currCol]==0){\n bfs(grid, currRow, currCol, totalRows, totalCols);\n ans+=1;\n }\n }\n }\n return ans; \n }\n \n //DFS approach\n private void dfs(int[][]grid, int currRow, int currCol, int m, int n){\n if(!isValidCell(currRow, currCol, m, n, grid))\n return;\n \n grid[currRow][currCol]=1;\n dfs(grid, currRow-1, currCol, m, n); //up\n dfs(grid, currRow+1, currCol, m, n); //down\n dfs(grid, currRow, currCol-1, m, n); //left\n dfs(grid, currRow, currCol+1, m, n); //right\n \n return;\n }\n \n //BFS approach\n private void bfs(int[][]grid, int currRow, int currCol, int m, int n){\n Queue<int[]> queue= new LinkedList<>();\n queue.add(new int[]{currRow, currCol});\n \n while(!queue.isEmpty()){\n //Pop from queue and verify if it\'s valid cell\n int[] currCell= queue.remove();\n int rowNumber= currCell[0];\n int colNumber= currCell[1];\n \n /*If valid cell, then:\n 1. visit cell and mark it visited by changing the value to \'1\'\n 2. add its neighbours to the queue */\n if(isValidCell(rowNumber, colNumber, m, n, grid)){\n grid[rowNumber][colNumber]= 1;\n \n queue.add(new int[]{rowNumber-1,colNumber}); //up\n queue.add(new int[]{rowNumber+1,colNumber}); //down\n queue.add(new int[]{rowNumber,colNumber-1}); //left\n queue.add(new int[]{rowNumber,colNumber+1}); //right\n }\n }\n return;\n }\n \n //method to check base condition\n private boolean isValidCell(int rowNumber,int colNumber, int m, int n, int[][] grid){\n if(rowNumber<0 || rowNumber>=m || colNumber<0 || colNumber>=n|| grid[rowNumber][colNumber]==1)\n return false;\n return true;\n }\n}\n``` | 6 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Recursion', 'Java'] | 0 |
number-of-closed-islands | Easy Javascript solution using DFS | easy-javascript-solution-using-dfs-by-vi-nuz8 | \nvar closedIsland = function(grid) {\n let m=grid.length;\n let n=grid[0].length;\n \n let count=0;\n \n function dfs(x,y,grid){\n if( | vishwanath1 | NORMAL | 2022-02-27T15:16:49.027855+00:00 | 2022-02-27T15:16:49.027888+00:00 | 760 | false | ```\nvar closedIsland = function(grid) {\n let m=grid.length;\n let n=grid[0].length;\n \n let count=0;\n \n function dfs(x,y,grid){\n if(x<0 || x>=grid.length || y<0 || y>=grid[0].length || grid[x][y]==1){\n return;\n }\n \n grid[x][y]=1;\n dfs(x+1,y,grid);\n dfs(x-1,y,grid);\n dfs(x,y+1,grid);\n dfs(x,y-1,grid);\n }\n \n // Exclude connected group of 0s on the corners because they are not closed island.\n for(let i=0;i<m;i++){\n for(let j=0;j<n;j++){\n if(grid[i][j]==0 &&(i==0 || i==m-1 || j==0 || j==n-1)){\n dfs(i,j,grid);\n }\n }\n }\n // Count the number of connected component of 0s on the grid.\n for(let i=1;i<m-1;i++){\n for(let j=1;j<n-1;j++){\n if(grid[i][j]==0){\n dfs(i,j,grid);\n count++;\n }\n }\n }\n \n return count;\n};\n``` | 6 | 0 | ['Depth-First Search', 'JavaScript'] | 1 |
number-of-closed-islands | c++ BFS | c-bfs-by-zhuxiongwei24-hvwj | \n\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int result=0;\n if(grid.empty() || grid[0].empty())\n | zhuxiongwei24 | NORMAL | 2019-11-23T09:21:44.637294+00:00 | 2019-11-23T09:21:44.637336+00:00 | 404 | false | ```\n\nclass Solution {\npublic:\n int closedIsland(vector<vector<int>>& grid) {\n int result=0;\n if(grid.empty() || grid[0].empty())\n return result;\n vector<vector<bool>> visited(grid.size(),vector<bool>(grid[0].size(),false));\n vector<pair<int,int>> directions={{-1,0},{1,0},{0,-1},{0,1}};\n for(int i=0;i<grid.size();i++) {\n for(int j=0;j<grid[0].size();j++) {\n if(grid[i][j]==1 || visited[i][j])\n continue;\n queue<pair<int,int>> q;\n q.push({i,j});\n bool isClosed=true;\n while(!q.empty()) {\n pair<int,int> t=q.front();\n q.pop();\n if(t.first==0 || t.first==grid.size()-1 || t.second==0 || t.second==grid[0].size()-1)\n isClosed=false;\n for(auto dir:directions) {\n int x=t.first+dir.first;\n int y=t.second+dir.second;\n if(x>=0 && x<grid.size() && y>=0 && y<grid[0].size() && grid[x][y]==0 && !visited[x][y]) {\n q.push({x,y});\n visited[x][y]=true;\n }\n }\n }\n if(isClosed)\n result++;\n }\n }\n return result;\n \n }\n};\n``` | 6 | 0 | [] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.