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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
number-of-good-pairs | Easy Solution | easy-solution-by-deepakumar-developer-pn1o | Dart []\nclass Solution {\n int numIdenticalPairs(List<int> nums) {\n int output=0;\n for(var i=0;i<nums.length-1;i++){\n for(var j=i+1;j<nums.len | deepakumar-developer | NORMAL | 2023-12-29T18:02:49.841477+00:00 | 2023-12-29T18:22:07.325894+00:00 | 427 | false | ```Dart []\nclass Solution {\n int numIdenticalPairs(List<int> nums) {\n int output=0;\n for(var i=0;i<nums.length-1;i++){\n for(var j=i+1;j<nums.length;j++){\n if(nums[i] == nums[j] && i < j){\n output++;\n }\n }\n }\n return output;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int output=0;\n for(int i=0;i<nums.size()-1;i++){\n for(int j=i+1;j<nums.size();j++){\n if(nums[i] == nums[j] && i < j){\n output++;\n }\n }\n }\n return output;\n }\n};\n```\n```java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int output=0;\n for(int i=0;i<nums.length-1;i++){\n for(int j=i+1;j<nums.length;j++){\n if(nums[i] == nums[j] && i < j){\n output++;\n }\n }\n }\n return output;\n }\n}\n```\n```python []\nclass Solution(object):\n def numIdenticalPairs(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n output=0;\n for i in range(0,len(nums)-1):\n for j in range(i,len(nums)):\n if(nums[i] == nums[j] and i < j):\n output+=1;\n return output;\n \n```\n```python3 []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n output=0;\n for i in range(0,len(nums)-1):\n for j in range(i,len(nums)):\n if(nums[i] == nums[j] and i < j):\n output+=1;\n return output;\n```\n# If you got a correct answer \n**UPVOTE ME **\n\n\n | 9 | 0 | ['Python', 'C++', 'Java', 'Python3', 'Dart'] | 1 |
number-of-good-pairs | ✅88.44%🔥Easy Solution🔥Array & HashTable | 8844easy-solutionarray-hashtable-by-pych-m31y | C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& A) {\n int ans = 0;\n unordered_map<int, int> cnt;\n for (int | pycharm82 | NORMAL | 2023-10-04T10:44:10.617765+00:00 | 2023-10-04T10:44:10.617786+00:00 | 285 | false | ```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& A) {\n int ans = 0;\n unordered_map<int, int> cnt;\n for (int x: A) {\n ans += cnt[x]++;\n }\n return ans;\n }\n};\n```\n```Java []\nclass Solution {\n public int numIdenticalPairs(int[] A) {\n int ans = 0, cnt[] = new int[101];\n for (int a: A) {\n ans += cnt[a]++;\n }\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n return sum([math.comb(n, 2) for n in collections.Counter(nums).values()]) \n```\n```C# []\n\npublic class Solution\n{\n public int NumIdenticalPairs(int[] A)\n {\n int ans = 0;\n Dictionary<int, int> cnt = new Dictionary<int, int>();\n foreach (int x in A)\n {\n if (cnt.ContainsKey(x))\n ans += cnt[x]++;\n else\n cnt[x] = 1;\n }\n return ans;\n }\n}\n```\n```Go []\npackage main\n\nfunc numIdenticalPairs(A []int) int {\n ans := 0\n cnt := make(map[int]int)\n \n for _, x := range A {\n ans += cnt[x]\n cnt[x]++\n }\n \n return ans\n}\n```\n```PHP []\nclass Solution {\n\n /**\n * @param Integer[] $nums\n * @return Integer\n */\n function numIdenticalPairs($A) {\n $ans = 0;\n $cnt = [];\n \n foreach ($A as $x) {\n $ans += $cnt[$x] ?? 0;\n $cnt[$x] = ($cnt[$x] ?? 0) + 1;\n }\n \n return $ans;\n}\n\n}\n```\n | 9 | 0 | ['C', 'PHP', 'C++', 'Java', 'Go', 'Python3', 'C#'] | 2 |
number-of-good-pairs | CPP 2 Approaches | Brute ->Better | Unordered Map | cpp-2-approaches-brute-better-unordered-c2273 | 1.Brute Force Method\n# Approach\n->Count Each Pair using nested loops\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:O(n2 | saurav_1928 | NORMAL | 2023-10-03T01:39:49.133084+00:00 | 2023-10-03T01:42:29.386487+00:00 | 735 | false | # 1.Brute Force Method\n# Approach\n->Count Each Pair using nested loops\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# 2.Using Unordered Map\n# Approach\n->If count(x)=n, then possible pairs will be (n*(n-1))/2\n->So counted the frequency of each number using unordered map\n->Again traverse thorough map and counted the pairs using above formula\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 brute(vector < int > & nums) {\n int n = nums.size();\n int cnt = 0;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++)\n cnt += (nums[i] == nums[j]);\n }\n return cnt;\n }\n int better(vector < int > & nums) {\n int n = nums.size(), cnt = 0;\n unordered_map < int, int > mp;\n for (auto & it: nums)\n mp[it]++;\n for (auto & pair: mp) {\n n = pair.second;\n cnt += ((n) * (n - 1)) / 2;\n }\n return cnt;\n }\n int numIdenticalPairs(vector < int > & nums) {\n // return brute(nums);\n return better(nums);\n }\n};\n```\n\n\n | 9 | 0 | ['Array', 'Hash Table', 'Math', 'Counting', 'C++'] | 3 |
number-of-good-pairs | [C++] O(n) Easy Solution using unordered map. | c-on-easy-solution-using-unordered-map-b-s896 | We store the count of each number in unordered map, if the count of a number is greater than 1 then we increase the variable res and store the number of possib | shubhamsth | NORMAL | 2022-02-04T18:14:30.741648+00:00 | 2022-02-04T18:14:30.741686+00:00 | 757 | false | We store the count of each number in unordered map, if the count of a number is greater than 1 then we increase the variable res and store the number of possible combinations which satisfy the given condition given in the question (nums[i] == nums[j] and i<j)\n```\nclass Solution {\npublic:\n \n int numIdenticalPairs(vector<int>& nums) {\n int res=0;\n unordered_map<int, int> mp;\n for(int i=0; i<nums.size(); i++){\n mp[nums[i]]++;\n }\n for(auto x:mp){\n if(x.second > 1){\n res += (x.second * (x.second - 1))/2; \n }\n }\n return res;\n }\n};\n``` | 9 | 0 | ['Hash Table', 'C', 'C++'] | 3 |
number-of-good-pairs | Simple O(n) Java Solution || HashMap | simple-on-java-solution-hashmap-by-himan-scgd | Upvote if you LIKE\uD83D\uDE42 \nclass Solution {\n\n public int numIdenticalPairs(int[] nums) {\n HashMap hm = new HashMap<>();\n int count = | himanshuramranjan | NORMAL | 2021-11-29T02:19:15.187627+00:00 | 2021-11-30T09:52:02.191809+00:00 | 604 | false | **Upvote if you LIKE**\uD83D\uDE42 \nclass Solution {\n\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer,Integer> hm = new HashMap<>();\n int count = 0;\n for(int i=0;i<nums.length;i++){\n if(hm.containsKey(nums[i])){\n count += hm.get(nums[i]);\n hm.put(nums[i],hm.get(nums[i])+1);\n }\n else\n hm.put(nums[i],1);\n }\n return count;\n }\n} | 9 | 1 | ['Java'] | 1 |
number-of-good-pairs | C++ 0 ms, faster than 100.00% O(n) solution | c-0-ms-faster-than-10000-on-solution-by-hlrjq | \nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n \n //Using map to store frequencies of each element\n map<int | sj_codebreaker | NORMAL | 2020-09-17T16:52:33.017777+00:00 | 2020-09-17T16:53:32.055486+00:00 | 938 | false | ```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n \n //Using map to store frequencies of each element\n map<int,int> count;\n \n int noOfPairs = 0;\n \n for(int i=0;i<nums.size();i++){\n count[nums[i]]+=1;\n }\n \n //if there are say n 1\'s then idea is that there will\n //will be exactly 1+2+....+(n-1) no. of pairs which is\n //(n)*(n-1)/2\n \n for(auto ele: count){\n noOfPairs+=(ele.second)*(ele.second - 1)/2; \n }\n \n return noOfPairs;\n }\n};\n``` | 9 | 0 | ['C', 'C++'] | 1 |
number-of-good-pairs | Optimal and suboptimal completely Explained with 2 Solutions | optimal-and-suboptimal-completely-explai-nkh9 | \nThis is the bruteforce approach.\n\nTime:O(n^2)\nSpace:O(1)\npython\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n n = le | akhil_ak | NORMAL | 2020-07-12T04:08:14.708171+00:00 | 2020-07-12T04:08:14.708223+00:00 | 854 | false | \nThis is the bruteforce approach.\n\nTime:O(n^2)\nSpace:O(1)\n```python\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n n = len(nums)\n res = 0 \n for i in range(n):\n for j in range(i+1,n):\n if nums[i] == nums[j]:\n res+=1\n return res\n```\n\nThis is the optimal solution which stores the {number,[list of indices of occurence of number]} as an event.\nThen find the number of number of pairs from each event.\nTime:O(n) | Space:O(n)\n\n```python\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n n = len(nums)\n events = collections.defaultdict(list)\n for idx,num in enumerate(nums):\n events[num].append(idx)\n count = lambda x:x*(x-1)//2 if x>1 else 0\n res = 0 \n for event in events:\n indices = events[event]\n length = len(indices)\n ans = count(length)\n res+=ans\n return res\n```\n\nThis is very critical in the interview setting.Dont get satisfied after proposing the first solution.I mean anyone could do the first\nsolution and its pretty naive.Discuss all possible approaches with their Time and space complexities.If you observe,its a tradeoff with memory\nand optimising time in the second solution. In eitherway,both solution are good and we need to choose according to the situation based on time,memory constraints.\n\nThanks for your time :) | 9 | 0 | ['Python', 'Python3'] | 2 |
number-of-good-pairs | C program | c-program-by-vibishraj-mxgg | 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 | Vibishraj | NORMAL | 2024-06-13T04:33:18.462305+00:00 | 2024-06-13T04:33:18.462336+00:00 | 110 | 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```\nint numIdenticalPairs(int* nums, int numsSize) {\n int c=0;\n for(int i=0;i<numsSize-1;i++)\n {\n for(int j=i+1;j<numsSize;j++)\n {\n if(nums[i]==nums[j])\n c++;\n }\n }\n return c;\n}\n``` | 8 | 0 | ['C'] | 3 |
number-of-good-pairs | ✅Simple Java Solutions || ✅Runtime 1ms | simple-java-solutions-runtime-1ms-by-ahm-haj3 | 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 | ahmedna126 | NORMAL | 2023-10-03T13:10:41.666103+00:00 | 2023-11-07T11:34:47.130660+00:00 | 162 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n\n for (int i = 0; i < nums.length; i++)\n {\n for (int j = i+1; j < nums.length; j++)\n {\n if (nums[i] == nums[j])\n count++;\n }\n }\n return count;\n }\n}\n```\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n\n\n | 8 | 0 | ['Java'] | 0 |
number-of-good-pairs | Java | O(N) | 1 Line Logic | Easy | java-on-1-line-logic-easy-by-tejkiran_1-sddy | \nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int ans = 0;\n int[] temp = new int[101];\n \n for (int i = 0; | tejkiran_1 | NORMAL | 2022-10-08T07:03:14.384765+00:00 | 2022-10-08T07:03:14.384808+00:00 | 1,907 | false | ```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int ans = 0;\n int[] temp = new int[101];\n \n for (int i = 0; i < nums.length; i++) {\n ans += temp[nums[i]]++;\n }\n return ans;\n }\n}\n``` | 8 | 0 | ['Array', 'Java'] | 5 |
number-of-good-pairs | Java || Easiest || 100% faster | java-easiest-100-faster-by-siddhantraii-npkl | \nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n\tint answer = 0;\n\tint[] freq = new int[102];\n \n\tfor (int i : nums) {\n\t\tif (f | siddhantraii | NORMAL | 2020-12-26T11:43:45.847886+00:00 | 2020-12-26T11:43:45.847923+00:00 | 977 | false | ```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n\tint answer = 0;\n\tint[] freq = new int[102];\n \n\tfor (int i : nums) {\n\t\tif (freq[i] == 0) freq[i]++;\n\t\telse{\n\t\t\tanswer += freq[i];\n\t\t\tfreq[i]++;\n\t\t}\n\t}\n\treturn answer;\n}\n}\n``` | 8 | 3 | ['Java'] | 3 |
number-of-good-pairs | [Python] 98% with O(n) | python-98-with-on-by-pakilamak-umvy | Solution1: Brute force\nTC= O(n*2)\nSC O(n)\n\nclass Solution(object):\n def numIdenticalPairs(self, nums):\n """\n :type nums: List[int]\n | pakilamak | NORMAL | 2020-10-13T17:56:54.724393+00:00 | 2020-10-20T17:24:48.909680+00:00 | 600 | false | Solution1: Brute force\nTC= O(n*2)\nSC O(n)\n```\nclass Solution(object):\n def numIdenticalPairs(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n count =0\n for i in range(len(nums)):\n for j in range(len(nums)):\n if nums[i]==nums[j] and i<j:\n count +=1\n return count\n```\n\nSolution2 : Optimize in O(n)\n\nTC O(n)\nSC O(1)\n```\nclass Solution(object):\n def numIdenticalPairs(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n \n dic = {}\n count =0\n \n for num in nums:\n if num in dic:\n count +=dic[num]\n dic[num] +=1\n else:\n dic[num] =1\n return count\n \n``` | 8 | 1 | ['Python'] | 1 |
number-of-good-pairs | EASIEST C++ CODE (O(N)) SOLUTION | easiest-c-code-on-solution-by-baibhavsin-mt0l | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nLoop through the input vector:\n\nThe for loop iterates over each element | baibhavsingh07 | NORMAL | 2023-10-03T05:48:01.888263+00:00 | 2023-10-03T05:48:01.888281+00:00 | 653 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nLoop through the input vector:\n\nThe for loop iterates over each element in the input vector a using the index i.\nCheck if the element exists in the map:\n\nInside the loop, there is an if statement that checks if the current element a[i] exists as a key in the map using the map.find(a[i]) function. If it exists (meaning it\'s not equal to map.end()), this means that there are previous occurrences of this element in the vector.\nCount identical pairs:\n\nIf the current element exists in the map, the code increments the count c by the value associated with that element in the map. This is because each time a new occurrence of the same element is encountered, it forms a pair with all the previous occurrences, so the count is increased by the number of previous occurrences.\nUpdate the frequency in the map:\n\nAfter counting the pairs for the current element, the code increments the frequency of the current element in the map by 1. This is done to keep track of how many times this element has been encountered so far.\nContinue the loop:\n\nThe loop continues to the next element in the input vector, repeating steps 3-5 for each element.\nReturn the count \n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& a) {\n int i,c=0;\n\n unordered_map<int,int>map;\n\n for(i=0;i<a.size();i++){\n if(map.find(a[i])!=map.end())\n c+=map[a[i]];\n \n map[a[i]]++;\n }\n return c;\n }\n};\n``` | 7 | 0 | ['Array', 'Hash Table', 'Math', 'C++'] | 2 |
number-of-good-pairs | Simple Solution || Number of Good Pairs | simple-solution-number-of-good-pairs-by-9ixel | 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 | himshrivas | NORMAL | 2023-01-28T15:08:06.168696+00:00 | 2023-01-28T15:08:06.168734+00:00 | 2,110 | 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 numIdenticalPairs(self, nums: List[int]) -> int:\n count=0\n for i in range(len(nums)):\n for j in range(len(nums)):\n if nums[i]==nums[j] and i<j:\n count+=1\n return count\n``` | 7 | 0 | ['Python3'] | 0 |
number-of-good-pairs | ✅ Javascript Solution: Faster than 97.43 % of other submissions || Map || Array Reduce | javascript-solution-faster-than-9743-of-48vkr | Feel free to ask Q\'s...\n#happytohelpu\n\nDo upvote if you find this solution useful. Happy Coding!\n\nRuntime: 58 ms\nMemory Usage: 41.7 MB\n\n\n\n/**\n * @pa | lakshmikant4u | NORMAL | 2022-12-03T18:03:28.080967+00:00 | 2023-04-10T19:33:10.825297+00:00 | 1,882 | false | **Feel free to ask Q\'s...**\n*#happytohelpu*\n\n***Do upvote if you find this solution useful. Happy Coding!***\n\nRuntime: 58 ms\nMemory Usage: 41.7 MB\n\n```\n\n/**\n * @param {number[]} nums\n * @param {Map} map\n * @return {number}\n */\nconst numIdenticalPairs = (nums, map = new Map(), res = 0) => {\n for (let i = 0; i < nums.length; i++) {\n let temp = map.get(nums[i]);\n if (temp) res += temp;\n /** Everytime same value is found in other index it can be paired with \n * existing one so adding previous value to result \n */\n map.set(nums[i], temp ? temp + 1 : 1);\n }\n return res;\n};\n```\n\n\nSolution 2 with Map and Array reduce method a slight variation\n\n```\nconst numIdenticalPairs = (nums, map = new Map()) => nums.reduce((prev, cur) => {\n if (map.get(cur)) {\n prev += map.get(cur);\n map.set(cur, map.get(cur) + 1);\n } else {\n map.set(cur, 1)\n }\n return prev;\n}, 0);\n```\n | 7 | 0 | ['JavaScript'] | 1 |
number-of-good-pairs | C++ Hashmap Solution EXPLAINED | c-hashmap-solution-explained-by-hugsfork-108j | Hello Everyone!\nI hope you find this solution helpful, feel free to comment suggestions and critiques!\n\n\nclass Solution {\npublic:\n int numIdenticalPair | hugsforknife | NORMAL | 2022-10-02T14:48:10.586134+00:00 | 2022-10-02T14:48:10.586186+00:00 | 889 | false | **Hello Everyone!**\nI hope you find this solution helpful, feel free to comment suggestions and critiques!\n\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int, int>mp;\n int ans = 0;\n for (int i = 0; i < nums.size(); ++i){\n //Go through the vector given and increment the map by 1\n\t\t\t// everytime the same number appears. This is counting the \n\t\t\t// frequency of that number\n\t\t\t++mp[nums[i]];\n\t\t\t\n\t\t\t//If the number shows up more than once, then it has atleast one pair\n if (mp[nums[i]] > 1)\n {\n\t\t\t\t//add to the answer the frequency - 1\n\t\t\t\t// (appearing two times means there is one pair, three times is two pairs, etc etc\n ans += mp[nums[i]] - 1; \n }\n }\n\t\t//return the answer\n return ans;\n }\n};\n```\nPlease leave an upvote if you found this solution helpful! | 7 | 0 | ['C'] | 2 |
number-of-good-pairs | Python 1 liner Without using Counter | python-1-liner-without-using-counter-by-riihn | \ndef numIdenticalPairs(self, nums: List[int]) -> int:\n return (sum(i==j for j in nums for i in nums)-len(nums))//2\n | danielwang5 | NORMAL | 2021-03-09T08:50:06.406560+00:00 | 2021-03-09T08:51:32.875616+00:00 | 229 | false | ```\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n return (sum(i==j for j in nums for i in nums)-len(nums))//2\n``` | 7 | 0 | [] | 1 |
number-of-good-pairs | Python 3, faster than 99.48% | python-3-faster-than-9948-by-narasimhag-f9a1 | The solution to this problem uses a small math formula and a hash table. The following is the approach I used,\n\n1. Build a dictionary to store the array items | narasimhag | NORMAL | 2020-12-28T07:08:18.027087+00:00 | 2020-12-28T07:08:52.466875+00:00 | 1,034 | false | The solution to this problem uses a small math formula and a hash table. The following is the approach I used,\n\n1. Build a dictionary to store the array items as keys and the value is a list of indices where this element appears. Ex: nums = [1,2,1,1]. d = { 1: [0,2,3], 2: [1]}. As I am iterating through the array linearly, this automatically guarantees i < j.\n2. In this dicitionary check for the presence of lists whose length is greater than 1, which means the element repeats. In those cases, it is the number of pairs we can form with the elements of that list incrementally. Say the lenght of a list is n, this is equivalent to summing up the numbers upto n-1. \n3. Using Gauss\'s trick, sum of numbers upto n, is n(n+1) / 2. Modifying it slightly for n-1, it is (n-1)n / 2. Add this for each list whose length is greater than 1 to the answer variable. Ex: consider the dictionary d = { 1: [0,2,3], 2: [1]}, for this list 1 has 3 elements, so we add (3-1) * 3 / 2 = 3 to the answer.\n\nFollowing code implements it.\n\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n ans = 0\n d = defaultdict(list)\n for i in range(len(nums)):\n d[nums[i]].append(i)\n # print(d)\n for k,v in d.items():\n n = len(v)\n # print(n)\n if n > 1:\n ans += ((n-1) * n) // 2\n return ans\n```\n\nWhile this is faster than 99.48% python 3 solutions, it doesn\'t perform that well on space. Any suggestions are appreciated. | 7 | 0 | ['Python3'] | 1 |
number-of-good-pairs | C++ 100% faster | c-100-faster-by-cmshih-tar1 | \nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int,int> map;\n int ans=0;\n for(auto n:nums){\ | cmshih | NORMAL | 2020-10-05T04:23:22.380144+00:00 | 2020-10-05T04:23:33.990851+00:00 | 1,151 | false | ```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int,int> map;\n int ans=0;\n for(auto n:nums){\n map[n]++;\n ans+=(map[n]-1);\n }\n return ans;\n }\n};\n``` | 7 | 0 | ['C'] | 3 |
number-of-good-pairs | 🚀Beats 99.17% || 📈Easy solution with O(n) Approach ✔ | beats-9917-easy-solution-with-on-approac-ls5w | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this code is to count the number of good pairs in the given array | anshuP_cs24 | NORMAL | 2023-10-03T02:43:00.921858+00:00 | 2023-10-03T02:58:43.347310+00:00 | 1,519 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to count the number of good pairs in the given array nums. A good pair consists of two elements with the same value, and the goal is to efficiently find and count these pairs.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIn this solution, we consider numbers in the range from 1 to 100 due to the problem\'s constraints. We use an array count to track the counts of each number, initialize goodPairs to count good pairs, and iterate through nums. For each num, we add its current count to goodPairs and increment its count in count. The result is the total count of good pairs in the array.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(N), where N is the length of the nums array. We iterate through the array once to count the good pairs efficiently.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this code is O(1), as the size of the count array is fixed and independent of the input size. It only depends on the given constraint that numbers in the array are in the range from 1 to 100. This makes the solution very memory-efficient.\n\n---\n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n const int maxNum = 100; // Given constraint: 1 <= nums[i] <= 100\n vector<int> count(maxNum + 1, 0); // Initialize an array to store counts\n \n int goodPairs = 0; // Initialize the count of good pairs\n \n // Iterate through the input array and calculate good pairs directly\n for (int num : nums) {\n goodPairs += count[num]; // Add the count of occurrences for the current number\n count[num]++; // Increment the count of the current number\n }\n \n return goodPairs; // Return the total count of good pairs\n }\n};\n``` | 6 | 0 | ['Array', 'Hash Table', 'Math', 'Union Find', 'C', 'Counting', 'Python', 'C++', 'Java', 'Python3'] | 4 |
number-of-good-pairs | Very Simple and Easy to Understand ||c++ || python || java | very-simple-and-easy-to-understand-c-pyt-r5ww | 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 | me_avi | NORMAL | 2023-10-03T02:04:29.452875+00:00 | 2023-10-03T02:04:29.452896+00:00 | 572 | 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```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int i,j,len=nums.size(),count=0;\n for(i=0;i<len;i++)\n {\n j=i+1;\n while(j<len)\n {\n if(nums[i]==nums[j])\n count++;\n j++;\n }\n }\n return count;\n }\n};\n```\n```python []\nclass Solution:\n def numIdenticalPairs(self, nums):\n count = 0\n for i in range(len(nums)):\n j = i + 1\n while j < len(nums):\n if nums[i] == nums[j]:\n count += 1\n j += 1\n return count\n\n```\n```ruby []\npublic class Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n int len = nums.length;\n for (int i = 0; i < len; i++) {\n for (int j = i + 1; j < len; j++) {\n if (nums[i] == nums[j]) {\n count++;\n }\n }\n }\n return count;\n }\n}\n```\n | 6 | 0 | ['Counting', 'Python', 'C++', 'Java'] | 5 |
number-of-good-pairs | C# easy solution. | c-easy-solution-by-aloneguy-fosu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Complexity\n- Time complexity: 82 ms.Beats 76.37% of other solutions.\n Add your ti | aloneguy | NORMAL | 2023-03-10T13:40:55.915542+00:00 | 2023-03-10T13:40:55.915583+00:00 | 476 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Complexity\n- Time complexity: 82 ms.Beats 76.37% of other solutions.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:38.2 MB.Beats 15.19% of other solutions.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int NumIdenticalPairs(int[] nums) {\n int count=0;\n for(int i=0;i<nums.Length-1;i++){\n for(int j=i+1;j<nums.Length;j++)\n if(nums[i]==nums[j])count++;\n }\n return count;\n }\n}\n``` | 6 | 0 | ['Array', 'C#'] | 0 |
number-of-good-pairs | Easy || JAVA || HashMap || Explained | easy-java-hashmap-explained-by-hashcoder-b766 | \n# Approach\n Describe your approach to solving the problem. \nThis Java code defines a method named numIdenticalPairs that takes an array of integers nums and | hashcoderz | NORMAL | 2023-02-14T16:15:43.140394+00:00 | 2023-02-14T16:15:43.140426+00:00 | 1,448 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis Java code defines a method named **numIdenticalPairs** that takes an array of integers nums and returns the number of good pairs of indices **(i, j)** such that **nums[i] == nums[j]** and **i < j**. A good pair is a pair of indices that satisfies the condition.\n\nThe code first creates a hash map to store the count of occurrences of each number in the input array. It then iterates over the map and computes the count of good pairs for each number using the formula **m*(m-1)/2**, where m is the count of occurrences of the number. The total count of good pairs is accumulated in the count variable and returned.\n\nThe time complexity of the code is **O(n)**, where n is the length of the input array, because it uses a hash map to count the occurrences of each number, which takes **O(n)** time, and then iterates over the map, which takes **O(m)** time where m is the number of distinct numbers in the array (which is usually much smaller than n).\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer,Integer> map = new HashMap<>();\n int count = 0;\n int n = nums.length;\n for(int i=0; i<n; i++){\n if(map.containsKey(nums[i]))\n map.put(nums[i],map.get(nums[i])+1);\n else\n map.put(nums[i],1);\n }\n for(Map.Entry<Integer,Integer> e: map.entrySet()){\n if(e.getValue()>0){\n int m = e.getValue();\n count+=(m*(m-1))/2;\n }\n }\n return count;\n }\n}\n```\n## If you find this helpful then pls upvote me.......... | 6 | 0 | ['Array', 'Hash Table', 'Math', 'Counting', 'Java'] | 0 |
number-of-good-pairs | Java Simple Explanation | O(N) time | 0 ms faster than 100% | java-simple-explanation-on-time-0-ms-fas-f6sa | We declared an empty array of size 101 since 101 is the max number given in constraints.\nThe temp array looks like [0, 0, 0, 0, 0, ... , 0] now.\n\nWe are now | akashdeepghosh | NORMAL | 2022-10-26T13:03:33.890946+00:00 | 2022-10-26T13:03:33.890980+00:00 | 441 | false | We declared an empty array of size 101 since 101 is the max number given in constraints.\nThe temp array looks like [0, 0, 0, 0, 0, ... , 0] now.\n\nWe are now looping in the given nums array and going to each element and adding it\'s temp count.\n\nLet\'s understand this by an example.\nGiven `nums = [1,2,3,1,1,3]`\nwhen i=0, we will check nums[i] which is num[0] = 1.\nThen we will go to temp[nums[i]] which is temp[1] = 0 for now. So we will add it to count 0 + 0 = 0.\nThen we will perform temp[1]++ which means we will make the temp array look like [0,1,0,0,0...0]\n\nNow, we will have i =1:\nnums[1]=2\ntemp[2]++\ncount = 0 + 0\nNow the temp array will look like [0, 1, 1, 0, 0, ... , 0]\n\ni = 2\nnums[2] = 3\ntemp[3]++\ncount = 0 + 0\nNow the temp array will look like [0, 1, 1, 1, 0, 0, ... , 0]\n\nNow for i = 3\nnums[3] = 1\ntemp[1]++\ncount = 0 + 1\nNow the temp array will look like [0, 2, 1, 1, 0, 0, ... , 0]\n\nNow for i = 4\nnums[4] = 1\ntemp[1]++\ncount = 1 + 2\nNow the temp array will look like [0, 3, 1, 1, 0, 0, ... , 0]\n\nFor i = 5\nnums[5] = 3\ntemp[3]++\ncount = 3 + 1\nNow the temp array will look like [0, 3, 1, 2, 0, ... , 0]\n\nWe will return count which is 4\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int[] temp = new int[101];\n \n int count = 0;\n \n for (int i = 0; i < nums.length; i++) {\n count += temp[nums[i]]++;\n }\n \n return count;\n }\n}\n``` | 6 | 0 | ['Java'] | 0 |
number-of-good-pairs | ✅Easy Java solution||Simple||Beginner Friendly🔥 | easy-java-solutionsimplebeginner-friendl-252o | If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries | deepVashisth | NORMAL | 2022-09-07T11:34:42.819129+00:00 | 2022-09-07T11:34:42.819165+00:00 | 410 | false | **If you really found my solution helpful please upvote it, as it motivates me to post such kind of codes and help the coding community, if you have some queries or some improvements please feel free to comment and share your views.**\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n for(int i = 0 ; i < nums.length; i ++){\n for(int j = i + 1; j < nums.length; j ++){\n if(nums[i] == nums[j]){\n count++;\n }\n }\n }\n return count;\n }\n}\n```\n**Happy Coding** | 6 | 0 | ['Java'] | 0 |
number-of-good-pairs | Python3 | Hash Table | O(n) | 93.3% Faster, 98.04% memory efficient. | python3-hash-table-on-933-faster-9804-me-f4uv | \n\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n d={}\n c=0\n for i in range(len(nums)):\n if nums[i] in d:\n | atifnawaz13 | NORMAL | 2021-08-04T20:15:16.744660+00:00 | 2021-08-04T20:15:16.744702+00:00 | 513 | false | \n```\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n d={}\n c=0\n for i in range(len(nums)):\n if nums[i] in d:\n d[nums[i]]+=1\n c+=d[nums[i]]\n else:\n d[nums[i]]=0\n return c\n```\nPlease Upvote\nHappy Coding!! | 6 | 0 | ['Python', 'Python3'] | 0 |
number-of-good-pairs | Kotlin 1 line | kotlin-1-line-by-georgcantor-xs9u | \nfun numIdenticalPairs(a: IntArray) = a.mapIndexed { i, n -> a.slice(i + 1..a.lastIndex).count { it == n } }.sum()\n\nApproach 2:\n\nfun numIdenticalPairs(a: I | GeorgCantor | NORMAL | 2021-02-15T08:49:38.808611+00:00 | 2021-07-18T09:58:39.926250+00:00 | 423 | false | ```\nfun numIdenticalPairs(a: IntArray) = a.mapIndexed { i, n -> a.slice(i + 1..a.lastIndex).count { it == n } }.sum()\n```\n**Approach 2:**\n```\nfun numIdenticalPairs(a: IntArray): Int {\n var c = 0\n a.forEachIndexed { i, n -> for (j in i + 1 until a.size) if (n == a[j]) c++ }\n return c\n}\n```\n**Approach 3:**\n```\nfun numIdenticalPairs(nums: IntArray): Int {\n val map = mutableMapOf<Int, Int>()\n var count = 0\n nums.forEach {\n if (map.containsKey(it)) count += map[it]!!\n map[it] = map.getOrDefault(it, 0) + 1\n } \n return count\n}\n``` | 6 | 0 | ['Kotlin'] | 0 |
number-of-good-pairs | JavaScript Solution > 93% Speed using map and counter | javascript-solution-93-speed-using-map-a-zcia | ```/*\n * @param {number[]} nums\n * @return {number}\n /\nvar numIdenticalPairs = function(nums) {\n const map = new Map();\n let pairs = 0;\n\n for ( | gideonbabu | NORMAL | 2021-01-23T18:46:23.542973+00:00 | 2021-01-23T18:46:23.543023+00:00 | 918 | false | ```/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numIdenticalPairs = function(nums) {\n const map = new Map();\n let pairs = 0;\n\n for (let i = 0; i < nums.length; i++) {\n if (map.has(nums[i])) {\n pairs += map.get(nums[i]);\n map.set(nums[i], map.get(nums[i]) + 1);\n } else {\n map.set(nums[i], 1);\n }\n }\n return pairs;\n};\n\nWe can also use for...of instead of traditional for loop | 6 | 0 | ['JavaScript'] | 0 |
number-of-good-pairs | Simple JavaScript solution | simple-javascript-solution-by-medhatisaa-rdil | \nvar numIdenticalPairs = function(nums) {\n let obj = {};\n let counter = 0;\n\n for (val of nums) {\n if (obj[val]) {\n counter | medhatisaac | NORMAL | 2020-11-14T16:19:44.517274+00:00 | 2020-11-14T16:19:44.517303+00:00 | 864 | false | ```\nvar numIdenticalPairs = function(nums) {\n let obj = {};\n let counter = 0;\n\n for (val of nums) {\n if (obj[val]) {\n counter += obj[val];\n obj[val]++;\n } else {\n obj[val] = 1;\n }\n }\n console.log(obj);\n return counter;\n};\n``` | 6 | 0 | ['JavaScript'] | 0 |
number-of-good-pairs | Python3 solution with a single pass and no if-else statements | python3-solution-with-a-single-pass-and-i367q | This solution makes use of a single pass and no if-else statements.\n\n@navinmittal29 Thanks for your suggestion on how to avoid using the if-else statements in | ecampana | NORMAL | 2020-09-09T04:51:14.456237+00:00 | 2020-09-09T04:51:14.456295+00:00 | 534 | false | This solution makes use of a single pass and no if-else statements.\n\n[@navinmittal29](https://leetcode.com/navinmittal29) Thanks for your suggestion on how to avoid using the if-else statements in my previous solution.\n\n\n```\nclass Solution:\n def numIdenticalPairs(self, nums: List[int]) -> int:\n my_count = 0\n my_dict = {}\n \n for n in nums:\n # Check to see if number has already been encountered\n # and increase count by the number of previous instances\n my_count += my_dict.get(n, 0) \n\n # Increase the count of previous observation\n # Or store newly encountered number along with its count\n my_dict[n] = my_dict.get(n, 0) + 1\n \n return my_count\n``` | 6 | 0 | ['Python', 'Python3'] | 0 |
number-of-good-pairs | Simplest Solution with Python 3 | simplest-solution-with-python-3-by-thepy-xag3 | \n def numIdenticalPairs(self, nums: List[int]) -> int:\n set_nums=set(nums)\n good=0\n for x in set_nums:\n n=nums.count(x)\ | thepylama | NORMAL | 2020-07-20T15:10:04.231479+00:00 | 2020-07-20T15:10:04.231516+00:00 | 718 | false | ```\n def numIdenticalPairs(self, nums: List[int]) -> int:\n set_nums=set(nums)\n good=0\n for x in set_nums:\n n=nums.count(x)\n good+=(n*(n-1))/2 \n\t\t\t#finding number of occurences of element and using nC2 to find good pairs \n return int(good)\n``` | 6 | 1 | [] | 4 |
number-of-good-pairs | [Java/Python 3] 4/1 liners O(n) counting codes w/ brief explanation and analysis. | javapython-3-41-liners-on-counting-codes-f1xi | For any given i items, we have C(i, 2) = (i - 1) * i / 2 combination options if choosing pairs from the i elements.\njava\n public int numIdenticalPairs(int[ | rock | NORMAL | 2020-07-12T04:23:12.027843+00:00 | 2020-07-17T17:50:22.200435+00:00 | 824 | false | For any given `i` items, we have `C(i, 2) = (i - 1) * i / 2` combination options if choosing pairs from the `i` elements.\n```java\n public int numIdenticalPairs(int[] nums) {\n int[] cnt = new int[101];\n for (int n : nums)\n ++cnt[n];\n return Arrays.stream(cnt).map(i -> (i - 1) * i / 2).sum();\n }\n```\n```python\n def numIdenticalPairs(self, nums: List[int]) -> int:\n return sum(v * (v - 1) // 2 for v in Counter(nums).values())\n```\n**Analysis:**\n\nTime: `O(n)`, space: `O(R)`, where `R = cnt.length`, the range of the `nums`. | 6 | 0 | [] | 3 |
number-of-good-pairs | Easy and Simple CPP code!💯✅ | easy-and-simple-cpp-code-by-siddharth_si-fqex | Intuition\nThe problem asks us to count the number of "good pairs" in the array, where a pair (i, j) is considered "good" if nums[i] == nums[j] and i < j. Essen | siddharth_sid_k | NORMAL | 2024-08-23T14:21:14.642283+00:00 | 2024-08-23T14:21:14.642312+00:00 | 264 | false | # Intuition\nThe problem asks us to count the number of "good pairs" in the array, where a pair (i, j) is considered "good" if nums[i] == nums[j] and i < j. Essentially, we are looking for identical values at different positions in the array. This problem can be solved using a brute-force approach by comparing each element with every subsequent element in the array.\n\n# Approach\n1. Start by initializing a counter c to zero, which will store the number of good pairs.\n2. Use two nested loops to iterate through the array. The outer loop will go through each element in the array with index i. The inner loop will start from i + 1 to avoid counting the same pair twice or comparing the element with itself.\n3. For every pair of elements nums[i] and nums[j], check if they are identical (nums[i] == nums[j]). If they are, increment the counter c by 1.\n4. After the loops complete, return the value of c, which contains the number of good pairs.\n\n# Complexity\n- Time complexity: **O(n^2)**, where n is the length of the array. This is because we have two nested loops iterating over the array, leading to a quadratic number of comparisons.\n\n- Space complexity: **O(1)** since we only use a constant amount of extra space (just the counter c).\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int c=0,n=nums.size();\n for(int i=0;i<n;i++)\n {\n for(int j=i+1;j<n;j++)\n {\n if(nums[i]==nums[j])\n {\n c+=1;\n }\n }\n }\n return c;\n\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
number-of-good-pairs | ✅Very Easy To Understand✅| 3 Approaches | C++ |✅ Optimal- Beats 100% and Brute Force | very-easy-to-understand-3-approaches-c-o-1823 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe need to find all pairs where nums[i]==nums[j] where i < j basically which indicates | Ritik7 | NORMAL | 2023-10-03T18:49:30.818479+00:00 | 2023-10-03T18:49:30.818509+00:00 | 68 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe need to find all pairs where ```nums[i]==nums[j]``` where ```i < j``` basically which indicates ```{i,j}``` and ```{j,i}``` should be counted once.\n\n- To do this there can be multiple approaches- \n - Bruteforce, Starting from the first index and find all pairs and check for the condition.\n - Using the occurence of every number and applying permutation and combination for all occurences.\n - Making a hash map for all numbers, and if the current number is already present in the map then we know we have found more pairs.(With pictures and Optimal)\n\n# Approach 1: Brute Force\n<!-- Describe your approach to solving the problem. -->\n1. Starting a loop from ``` i = 0 ``` to ```i = nums.size() - 1 ```\n - ``` i ``` is iterated till ```n-1``` because for the last case ```i < j``` and if we don\'t stop ``` i ``` then ```nums[j]``` would be out of bounds and we will get an error.\n2. Starting a nested loop ``` j = i+1 ``` to ``` j = nums.size()```\n - ``` j ``` is initialized by one greater than ``` i ``` so that the condition ``` i < j ``` remains.\n3. Checking for the condition ```nums[i]=nums[j]``` and whenever it is true, adding 1 to the total number of pairs to an INT ```count```, earlier initialized as ``` 0 ```.\n4. Returning ```count``` of the total pairs.\n\n\n# Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int count=0;\n \n for(int i = 0; i < nums.size()-1; i++){\n for(int j = i+1; j < nums.size(); j++){\n if (nums[i]==nums[j]){\n count++;\n }\n }\n }\n return count;\n }\n};\n```\n# Approach 2: Permutation and Combination\n<!-- Describe your approach to solving the problem. -->\n1. Creating an ```unordered_map``` mp.\n2. Running a loop till ```n``` and storing occurence```(value)```of every number```(key)``` from the given array.\n3. Consider this as unique combinations of 2 from this ```integer set {n}```\n - for 1 occurence, 0 pairs\n - for 2 occurence, 1 pairs\n - for 3 occurence, 3 pairs\n - for 4 occurence, 6 pairs\n - for 5 occurence, 10 pairs\n - for 6 occurence, 15 pairs\n- Note the consistent pairs to the occurence as:\n\n where ```n``` is number of occurence of a number.\n4. Solving the above expression for occurence of all numbers.\n5. Adding the solution of every occurence to ```count```, initialized as ```zero```.\n6. Returning ```count```.\n\n# Complexity\n- Time complexity: O(2*n) = O(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 numIdenticalPairs(vector<int>& nums) {\n int count=0;\n unordered_map<int, int> mp;\n\n for(int i=0;i<nums.size();i++){\n mp[nums[i]]++;\n }\n\n for (auto i: mp) {\n count = count + ((i.second * (i.second-1))/2);\n }\n return count;\n }\n};\n```\n\n# Approach 3: Hash Map\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a map ```mp``` which stores the count of each number in the array.\n2. Storing in the map as we go so for ```i```th number everything from ```0``` to ```i-1``` is stored in the map.\n3. Traversing over the array and checking if the current ```nums[i]``` has a value greater than ```0``` which means it is already present in the map.\n4. If it does, adding its occurence till now to ```count```.\n5. Incrementing the count of curr.\n6. Returning count.\n\n# To Understand The Calculation:\n- Let\'s consider an array ```[1,1,1,1]```\n\n\n\n- ```mp[current]``` was ```0``` so just did ```mp[current]++;```\n\n\n\n- ```mp[current]``` was true as it was not equal to zero so we added the previous value of ```mp[current]``` to ```count``` as that is ```1``` and the pairs seen is ```1``` then ```mp[current]++;```.\n\n\n\n- As by traversing to the next same element 2 new pairs are formed and ```mp[current]==2``` , adding that to ```count``` and then ```mp[current]++;```.\n\n\n\n- As by traversing to the next same element 3 new pairs are formed and ```mp[current]==3``` , adding that to ```count``` and then ```mp[current]++;```.\n\n- After traversing and adding frequencies to the count ```6``` is returned.\n\n\n# Complexity\n- Time complexity: O(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 numIdenticalPairs(vector<int>& nums) {\n int n = nums.size();\n int count = 0;\n\n unordered_map<int,int> mp;\n\n for(int i = 0; i < n ;i++){\n int current = nums[i];\n\n if(mp[current]){\n count += mp[current];\n }\n mp[current]++;\n }\n return count;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
number-of-good-pairs | Simple and Easiest Solution for this Question in C++ | simple-and-easiest-solution-for-this-que-7ft9 | Intuition\nThe intuition behind the given code is to find and count the number of identical pairs of elements in a given vector nums. Here\'s the step-by-step i | RaviRanjan940 | NORMAL | 2023-10-03T17:11:40.819891+00:00 | 2023-10-03T17:11:40.819920+00:00 | 51 | false | # Intuition\nThe intuition behind the given code is to find and count the number of identical pairs of elements in a given vector `nums`. Here\'s the step-by-step intuition:\n\n1. **Initialization**: Initialize variables `n` to store the size of the input vector `nums` and `cnt` to keep track of the count of identical pairs. Initially, `cnt` is set to 0.\n\n2. **Nested Loops**: The code uses two nested loops to compare elements in the vector.\n\n - The outer loop (`i`) iterates through each element of the vector, representing one element of a potential pair.\n - The inner loop (`j`) iterates through the remaining elements in the vector, representing the other element of the potential pair.\n\n3. **Comparison**: Within the nested loops, it checks if `nums[i]` is equal to `nums[j]` to determine if the elements at indices `i` and `j` are identical. Additionally, it ensures that `i` is less than `j` to avoid counting the same pair twice.\n\n4. **Counting**: If `nums[i]` and `nums[j]` are equal and `i` is less than `j`, it increments the `cnt` variable by 1. This means it has found an identical pair.\n\n5. **Looping through Pairs**: The nested loops continue to iterate through all possible pairs of elements in the vector, comparing each pair and incrementing `cnt` when an identical pair is found.\n\n6. **Result**: After both loops finish, the function returns the final value of `cnt`, which represents the total count of identical pairs found in the input vector `nums`.\n\nIn summary, the code exhaustively checks all possible pairs of elements in the vector and counts the pairs where the elements are identical. It uses nested loops to achieve this, resulting in a time complexity of O(n^2) due to the two levels of iteration.\n\n# Approach\nThe given code is a C++ function that takes a vector of integers `nums` as input and calculates the number of identical pairs of elements in the vector. It uses a nested loop to compare elements and count the identical pairs. Here\'s a step-by-step breakdown of the code:\n\n1. Declare a function `numIdenticalPairs` that takes a reference to a vector of integers `nums` as its parameter. The function returns an integer, which is the count of identical pairs.\n\n2. Get the size of the input vector `nums` and store it in the variable `n`.\n\n3. Initialize a variable `cnt` to 0. This variable will be used to keep track of the count of identical pairs.\n\n4. Start a nested loop with two variables `i` and `j` to iterate through all pairs of elements in the vector.\n\n - The outer loop (`i`) iterates from 0 to `n-1`, covering all possible starting positions for pairs.\n - The inner loop (`j`) iterates from `i+1` to `n-1`, ensuring that it only compares elements that come after the current `i` element.\n\n5. Inside the nested loops, check if the elements at indices `i` and `j` in the `nums` vector are equal using the condition `nums[i] == nums[j]`. Also, ensure that `i` is less than `j` to avoid counting the same pair twice.\n\n - If the condition is true, increment the `cnt` variable by 1. This means you\'ve found an identical pair.\n\n6. Continue iterating through all possible pairs in the vector, comparing elements and counting identical pairs.\n\n7. Once the loops finish, return the value of `cnt`, which represents the total count of identical pairs found in the input vector `nums`.\n\nThis code has a time complexity of O(n^2) because it uses nested loops to compare all pairs of elements in the vector. It can be optimized to run in O(n) time complexity by using a hash map or an array to count the occurrences of each element and then calculating the identical pairs based on the counts.\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ \n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int n=nums.size();\n int cnt=0;\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n if(nums[i] == nums[j] && i<j){\n cnt++;\n } \n }\n }\n return cnt;\n }\n};\n``` | 5 | 0 | ['C++'] | 0 |
number-of-good-pairs | C/C++ array 0ms Beats 100% | cc-array-0ms-beats-100-by-anwendeng-iit9 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nLet N[x] store the numb | anwendeng | NORMAL | 2023-10-03T05:00:46.778262+00:00 | 2023-10-03T10:38:17.477776+00:00 | 340 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nLet N[x] store the number of occurrencies of x.\nThere are N[x]*(N[x]-1)/2 good pairs for x.\nSumming up\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```C []\nint numIdenticalPairs(int* nums, int numsSize){\n int N[101]={0};\n #pragma unroll\n for(register i=0; i<numsSize; i++)\n N[nums[i]]++;\n int sum=0;\n #pragma unroll\n for(register int x=1; x<=100; x++)\n if (N[x]!=0) sum+=N[x]*(N[x]-1)/2;\n \n return sum;\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n vector<int> N(101, 0);\n #pragma unroll\n for(int x : nums)\n N[x]++;\n int sum=0;\n #pragma unroll\n for(int x=1; x<=100; x++)\n if (N[x]!=0) sum+=N[x]*(N[x]-1)/2;\n \n return sum;\n }\n};\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n``` | 5 | 0 | ['Array', 'C++'] | 1 |
number-of-good-pairs | Find number of good pairs in O(n) | find-number-of-good-pairs-in-on-by-sanke-xodg | Intuition\nTo solve this problem here combinational formula(nCr) is used. \n\n# Approach\nIf we get the count for all the elements from array separately and the | sanketpatil7467 | NORMAL | 2023-10-03T03:05:07.933741+00:00 | 2023-10-03T03:05:07.933767+00:00 | 727 | false | # Intuition\nTo solve this problem here combinational formula(nCr) is used. \n\n# Approach\nIf we get the count for all the elements from array separately and then perform combinational formula on each of them then we get number of good pairs. So to get count of all elements Hashmap is used.\nAt the end we are returning sum of all good pairs of all elements from array.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n Map<Integer, Integer> ans = new HashMap<>();\n\n for (int i = 0; i < nums.length; i++) {\n ans.put(nums[i], ans.getOrDefault(nums[i], 0) + 1);\n }\n\n for (Map.Entry<Integer, Integer> entry : ans.entrySet()) {\n int val = entry.getValue();\n count += (val * (val - 1)) / 2;\n }\n\n return count;\n }\n}\n``` | 5 | 0 | ['Hash Table', 'Java'] | 3 |
number-of-good-pairs | ✔🚀96.90% Beats O(n) Solution ✨📈|| Detailed Explanation || Easy to Understand🚀 | 9690-beats-on-solution-detailed-explanat-j044 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this code is to count the number of good pairs in the given array | saket_1 | NORMAL | 2023-10-03T02:34:25.695757+00:00 | 2023-10-03T05:30:27.803401+00:00 | 904 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this code is to count the number of good pairs in the given array nums. A good pair consists of two elements with the same value, and the goal is to efficiently find and count these pairs.\n\n---\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. We start by recognizing that we only need to consider elements in the range from 1 to 100 because the problem specifies that 1 <= nums[i] <= 100.\n\n2. We initialize an array count of size maxNum + 1 (where maxNum is 100) to store the counts of each possible number in the input array.\n\n3. We initialize a variable goodPairs to keep track of the total number of good pairs.\n\n4. We iterate through the input array nums, and for each number num, we do the following:\n\n5. Add the current count of occurrences for num to goodPairs. This is because for every new occurrence of a number, it forms a good pair with each previous occurrence of the same number.\n- Increment the count of the current number num in the count array.\n6. Finally, we return the goodPairs, which represents the total count of good pairs in the input array.\n\n---\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is O(N), where N is the length of the nums array. We iterate through the array once to count the good pairs efficiently.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this code is O(1), as the size of the count array is fixed and independent of the input size. It only depends on the given constraint that numbers in the array are in the range from 1 to 100. This makes the solution very memory-efficient.\n\n\n---\n\n\n# PLEASE UPVOTE\u2763\uD83D\uDE0D\n---\n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n const int maxNum = 100; // Given constraint: 1 <= nums[i] <= 100\n vector<int> count(maxNum + 1, 0); // Initialize an array to store counts\n \n int goodPairs = 0; // Initialize the count of good pairs\n \n // Iterate through the input array and calculate good pairs directly\n for (int num : nums) {\n goodPairs += count[num]; // Add the count of occurrences for the current number\n count[num]++; // Increment the count of the current number\n }\n \n return goodPairs; // Return the total count of good pairs\n }\n};\n\n``` | 5 | 0 | ['Array', 'Hash Table', 'Linked List', 'Math', 'C', 'Counting', 'Python', 'C++', 'Java', 'Python3'] | 3 |
number-of-good-pairs | 🚀✔99.78% Beats O(n) Solution 📈|| Easy and detailed explanation ever ❣ | 9978-beats-on-solution-easy-and-detailed-6qm1 | Intuition\uD83D\uDE80\n Describe your first thoughts on how to solve this problem. \nThe intuition behind this solution is to count the occurrences of each numb | nikkipriya_78 | NORMAL | 2023-10-03T02:28:31.912708+00:00 | 2023-10-07T13:51:55.866156+00:00 | 956 | false | # Intuition\uD83D\uDE80\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition behind this solution is to count the occurrences of each number in the input array using an unordered map (countMap). Then, for each unique number in the map, we calculate the number of good pairs using a formula and accumulate the counts to find the total number of good pairs in the input array.\n\n---\n\n# Approach\uD83D\uDE80\n<!-- Describe your approach to solving the problem. -->\n1. Initialize an unordered_map countMap to store the count of each unique number in the input array.\n2. Initialize an integer goodPairs to 0, which will keep track of the total number of good pairs.\n3. Iterate through the input array nums, and for each number num, increment its count in countMap.\n4. After counting the occurrences of each number, iterate through countMap using a for-each loop.\n5. For each unique number in the map, calculate the number of good pairs using the formula (count * (count - 1)) / 2, where count is the number of occurrences of that number in the input array.\n6. Add the count of good pairs for each number to the goodPairs variable.\n7. Finally, return the goodPairs, which represents the total count of good pairs in the input array.\n\n---\n\n# Complexity\uD83D\uDE80\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(N), where N is the length of the nums array. The first loop through nums counts the occurrences of each number in O(N) time, and the second loop through countMap has a constant number of iterations based on the unique numbers in the array.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is O(U), where U is the number of unique numbers in the nums array. In the worst case, if all numbers are unique, the space complexity will be O(N) as well because there could be N unique numbers. However, if there are fewer unique numbers, the space complexity will be less than O(N).\n\n---\n\n# Do Upvote if you like the explanation and solution please \u2763\uD83D\uDE0D\u2714\n\n---\n\n# Code\uD83D\uDE80\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n unordered_map<int, int> countMap; // A map to store the count of each number\n \n int goodPairs = 0; // Initialize the count of good pairs\n \n // Iterate through the input array and count occurrences of each number\n for (int num : nums) {\n countMap[num]++;\n }\n \n // Calculate the number of good pairs for each number in the map\n for (auto& pair : countMap) {\n int count = pair.second;\n goodPairs += (count * (count - 1)) / 2; // Calculate good pairs using the formula\n }\n \n return goodPairs; // Return the total count of good pairs\n }\n};\n\n``` | 5 | 0 | ['Array', 'Hash Table', 'Math', 'C', 'Sliding Window', 'Counting', 'Python', 'C++', 'Java', 'Python3'] | 3 |
number-of-good-pairs | C# Simple Solution Beats 100% | c-simple-solution-beats-100-by-apakg-jjm8 | 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 | Apakg | NORMAL | 2023-05-07T18:57:29.218581+00:00 | 2023-05-07T18:57:29.218615+00:00 | 696 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int NumIdenticalPairs(int[] nums) {\n Dictionary<int, int> id = new();\n int ans = 0;\n for (int i = 0; i < nums.Length; i++)\n {\n int c= id.GetValueOrDefault(nums[i],0);\n ans += c;\n id[nums[i]] = c + 1;\n }\n return ans;\n }\n}\n``` | 5 | 0 | ['C#'] | 1 |
number-of-good-pairs | JAVA || O (n log n) || Hashmap used || For beginners || Explained !!! 💡 | java-o-n-log-n-hashmap-used-for-beginner-pwfl | Approach\n- Create a hashmap\n- O(n log n) nested loop setup for finding out pairs\n- If a key == nums[i] does not exist upon finding a pair, push a pair (nums[ | AbirDey | NORMAL | 2023-04-27T13:58:07.259413+00:00 | 2023-04-27T13:58:07.259462+00:00 | 1,920 | false | # Approach\n- Create a hashmap\n- O(n log n) nested loop setup for finding out pairs\n- If a key == nums[i] does not exist upon finding a pair, push a pair (nums[i] , 1)\n- If key exist, increment the value corresponding to the key in the hashmap.\n- for all the key values in the map, return the sum of all the values \n\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n HashMap<Integer, Integer> map = new HashMap<>();\n for(int i = 0;i<nums.length;i++){\n for(int j = i+1;j<nums.length;j++){\n if(nums[i] == nums[j]){\n if(map.containsKey(nums[i]) == true){\n int value = map.get(nums[i]);\n value++;\n map.put(nums[i],value);\n }else{\n map.put(nums[i],1);\n }\n }\n }\n }\n int sum = 0;\n for(int val: map.keySet()){\n sum += map.get(val);\n }\n return sum;\n }\n}\n```\n\n\n | 5 | 0 | ['Hash Table', 'Java'] | 2 |
number-of-good-pairs | Find the number of identical pairs in an array of integers | find-the-number-of-identical-pairs-in-an-polj | Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem is asking to find the number of identical pairs in an array of integers. We | RinatMambetov | NORMAL | 2023-04-04T15:05:21.567412+00:00 | 2023-04-04T15:05:21.567450+00:00 | 2,272 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem is asking to find the number of identical pairs in an array of integers. We can keep track of the frequency of each integer using a hash map, where the keys are the integers and the values are the frequency of occurrence. Then, for each key in the map, we can calculate the number of pairs that can be formed using the formula n * (n-1) / 2, where n is the frequency of the integer. We can then sum up the number of pairs for each integer to get the total number of identical pairs in the array.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe approach used in this solution is to first create a hash map, where we iterate through the input array and keep track of the frequency of each integer. Then, we iterate through the keys in the map and calculate the number of identical pairs that can be formed using the formula mentioned above. Finally, we sum up the number of pairs for each integer to get the total number of identical pairs in the array.\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)$$ -->\nThe time complexity of this solution is O(n), where n is the length of the input array. This is because we iterate through the array once to create the hash map, and then iterate through the keys in the map, which has a maximum length of the number of unique integers in the array. The space complexity is also O(n), since we are using a hash map to store the frequency of each integer in the array.\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar numIdenticalPairs = function (nums) {\n let m = {};\n\n nums.forEach((element) => {\n if (m[element] == undefined) m[element] = 1;\n else m[element]++;\n });\n\n let res = 0;\n\n for (const key in m) {\n if (Object.hasOwnProperty.call(m, key)) {\n const element = m[key];\n if (element > 1) res += element * (element / 2 - 0.5);\n }\n }\n\n return res;\n};\n``` | 5 | 0 | ['JavaScript'] | 1 |
number-of-good-pairs | C++ easy solution. | c-easy-solution-by-aloneguy-sclu | \n\n# Code\n\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int count=0;\n for(int i=0;i<nums.size()-1;i++){\n | aloneguy | NORMAL | 2023-03-12T20:25:37.110806+00:00 | 2023-03-12T20:25:37.110835+00:00 | 444 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int count=0;\n for(int i=0;i<nums.size()-1;i++){\n for(int j=i+1;j<nums.size();j++){\n if(nums[i]==nums[j])count++;\n }\n }\n return count;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
number-of-good-pairs | Beats 100% Java Solution | beats-100-java-solution-by-jaiyadav-aodz | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n\n Has | jaiyadav | NORMAL | 2023-01-01T05:26:55.730708+00:00 | 2023-01-01T05:26:55.730758+00:00 | 1,560 | false | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n\n HashMap<Integer,Integer>mp=new HashMap<>();\n\n int count=0;\n\n for(int i=0;i<nums.length;i++){\n\n if(!mp.containsKey(nums[i])){\n mp.put(nums[i],1);\n }\n else{\n count+=mp.get(nums[i]);\n mp.put(nums[i],mp.get(nums[i])+1);\n }\n\n }\n\n return count;\n\n }\n}\n``` | 5 | 0 | ['Java'] | 1 |
number-of-good-pairs | Using basic combination with bucket array | using-basic-combination-with-bucket-arra-e5ty | Intuition\n(Read the note below)\nSince we have to count the number of pairs using nCr which is n!/(n-r)! * r!\nTaking r = 2, since we are to count the number o | himanshubanerji | NORMAL | 2022-12-29T19:20:32.493199+00:00 | 2022-12-29T19:20:32.493244+00:00 | 855 | false | # Intuition\n(Read the note below)\nSince we have to count the number of pairs using `nCr` which is `n!/(n-r)! * r!`\nTaking `r = 2`, since we are to count the number of pairs\n\n`nC2 = n!/(n-2)! * (2)!`\n\n# Approach\nNow next step was to minimize the value of `nC2` else taking the worst case scenario 100 (max value of nums[i]) it\'ll lead to overflow since 100! is a very big number. \n\nTherefore `nC2 = n! / (n-2)! * 2!`\n`nC2 = n(n-1)(n-2)! / (n-2)! * 2!`\n`nC2 = n(n-1) / 2` _cancelling (n-2)! out_\n\n# Complexity\n- Time complexity: __O(2n)__\n\n- Space complexity: __O(101)__\n\n# Note\nbuc_arr[] is used to store the frequency of each element present in the nums vector.\n\nThe size is taken as 101 as the maximum value of nums[i] is 100 \nTherefore that means `buc_arr[nums[i]]` cannot exceed a value of `buc_arr[100]` therefore size taken as `101` i.e. to accomodate all values from 0 to 100 \n\n# Code\n```cpp\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n // nC2 = n! / (n-2)! x 2!\n // nC2 = n(n-1)(n-2)! / (n-2)! x 2!\n // nC2 = n(n-1) / 2\n\n vector<int> buc_arr(101);\n for(int x: nums)\n buc_arr[x]++;\n \n int sum = 0;\n for(int x: buc_arr) {\n sum += x*(x-1)/2;\n }\n\n return sum;\n\n }\n};\n```\n\n | 5 | 0 | ['Math', 'C++'] | 2 |
number-of-good-pairs | Single loop, O(n) speed, hash table, fast | single-loop-on-speed-hash-table-fast-by-jcsyo | Intuition\n Describe your first thoughts on how to solve this problem. \n\nThe good pair quantites are same as how many identical number already accululated eac | micronew | NORMAL | 2022-12-11T20:59:00.777261+00:00 | 2022-12-11T21:05:46.413718+00:00 | 619 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nThe good pair quantites are same as how many identical number already accululated each time when you encounter the same number. For example, if number 1 appears 4 times already, then the next time you encounter number 1, that will contribute 4 quantites to the good pair. So we only need to record how many times the number appears and save it in a bucket for that number. That is the hash table. \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nTaking advantage of only 100 distinct possible numbers, our hash function can directly map the key to the index of hashmap array\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nSince we only for loop once, it is O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nWe need full size hashmap, O(n) space complexity\n\n# Code\n```\nint numIdenticalPairs(int* nums, int numsSize){\n int hashmap[101] = {0};\n for(int i = 0; i < numsSize; i++){\n hashmap[0]+= hashmap[nums[i]]++;\n }\n return hashmap[0];\n\n}\n``` | 5 | 0 | ['Hash Table', 'C', 'Hash Function'] | 0 |
number-of-good-pairs | [C++] MAP + MATH. O(n) | c-map-math-on-by-rahug-643m | Explanation\ncount the occurrence of the same elements.\nFor each new element a,\nthere will be more count[a] pairs.\nwith A[i] == A[j] and i < j\n\nExplaining | Rahug | NORMAL | 2022-11-02T17:14:51.263447+00:00 | 2022-11-02T17:14:51.263553+00:00 | 1,198 | false | ***Explanation***\ncount the occurrence of the same elements.\nFor each new element a,\nthere will be more count[a] pairs.\nwith *A[i] == A[j]* and *i < j*\n\n***Explaining the logic:***\n1) We can store the ints like a key in map, and the indexes save in the vector of ints like a value in a map. \nFor example 1, it will be like that:\n[\n](http://)[](http://)\n2) It is a fact that, to find the sum of numbers from 1 to n, the formula will be:\n\n**((n)*(n+1))/2**\n3) Then we can iterate trough the map and take the size of vectors and apply that formula to the sizes of vectors in map:\n ``\n int sum = ((i.second.size()-1)*(i.second.size()))/2;\n ``\n 4) and make `ans+=sum`\n\n***C++ code with comments:***\n```\n int numIdenticalPairs(vector<int>& nums) {\n map<int,vector<int>> mp; // creating a map with key - int, and value - vector\n for(int i = 0 ; i < nums.size();i++){\n // For example: key is 1, and we saving the indexes of this number. Example 1:\n // [1]:0,3,4\n // [2]:1\n // and etc...\n mp[nums[i]].push_back(i); \n }\n //declaring the variable to save the numbers of good pairs\n int ans = 0;\n \n for(auto i : mp){\n //using the formula to find the sum of numbers\n // ((n)*(n+1))/2\n // n - the size of the vector\n int sum = ((i.second.size()-1)*(i.second.size()))/2;\n // saving it to the ans\n ans+=sum;\n }\n //returning ans\n return ans;\n }\n```\n***C++ code without comments:***\n```\nint numIdenticalPairs(vector<int> &nums)\n{\n map<int, vector<int>> mp;\n for (int i = 0; i < nums.size(); i++)\n {\n mp[nums[i]].push_back(i);\n }\n int ans = 0;\n for (auto i : mp)\n {\n int sum = ((i.second.size() - 1) * (i.second.size())) / 2;\n\n ans += sum;\n }\n return ans;\n}\n```\n\n***Complexity***\nTime O(N)\nSpace O(N)\n | 5 | 0 | ['Math', 'C'] | 3 |
number-of-good-pairs | ✔️C++|| Explained|| Easy|| Using Permutation | c-explained-easy-using-permutation-by-sr-xr46 | \nThe approach is very simple. Count number of duplicates for each element in a given array and calculate nC2 which is used to select two elements at a time.\n\ | srikrishna0874 | NORMAL | 2022-10-07T08:07:48.431682+00:00 | 2022-10-07T08:07:48.431720+00:00 | 203 | false | ```\nThe approach is very simple. Count number of duplicates for each element in a given array and calculate nC2 which is used to select two elements at a time.\n\nNote: nC2=n*(n-1)/2\n```\n```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n map<int,int> m;\n for(int i=0;i<nums.size();i++) m[nums[i]]++;\n int c=0;\n for(auto i:m)\n {\n int n=i.second;\n c+=n*(n-1)/2;\n }\n return c;\n }\n};\n```\n```\nFeel free to comment if any doubt...\n``` | 5 | 0 | ['C', 'Probability and Statistics'] | 0 |
number-of-good-pairs | Java Solution using HashMap | java-solution-using-hashmap-by-komal_sha-g63a | Time Complexity : O(N)\n\n```\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n HashMap map = new HashMap<>() | Komal_Sharma15 | NORMAL | 2022-09-01T14:43:10.833147+00:00 | 2022-09-01T14:44:11.658345+00:00 | 422 | false | Time Complexity : O(N)\n\n```\n\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int count = 0;\n HashMap<Integer, Integer> map = new HashMap<>();\n for(int i=0; i<nums.length; i++){\n if(map.containsKey(nums[i])){\n count += map.get(nums[i]);\n map.put(nums[i], map.get(nums[i])+1);\n }\n else{\n map.put(nums[i], 1);\n }\n }\n return count;\n }\n} | 5 | 0 | ['Java'] | 2 |
number-of-good-pairs | C++ | O(n) | Best Explanation | Easy Understanding | c-on-best-explanation-easy-understanding-tqcy | Use new version of leetcode to see latex expressions properly\n\n\n// Time Complexity = O(n)\n// Space Complexity = O(n)\n// Runtime : 0ms, faster than 100.00%\ | meteahmetyakar | NORMAL | 2022-08-19T15:42:00.424750+00:00 | 2023-05-17T20:41:47.945379+00:00 | 765 | false | ### ***Use new version of leetcode to see latex expressions properly***\n***\n```\n// Time Complexity = O(n)\n// Space Complexity = O(n)\n// Runtime : 0ms, faster than 100.00%\n// Memory Usage : 7.2 MB, less than 60.74%\n```\n\n```\n int numIdenticalPairs(vector<int>& nums) {\n \n unordered_map<int,int> hashmap;\n int goodPairs = 0;\n \n for(int i=0; i<nums.size(); i++)\n hashtable[nums[i]] += 1;\n \n for(auto element : hashtable)\n goodPairs += element.second * (element.second - 1) / 2;\n \n return goodPairs;\n }\n```\n\nFirst, we find the count of numbers in the array with **hashmap**.\n\nLet our array be [1,2,3,1,1,3,1,1,3]\nWe can specify good pairs as the count of same numbers after them.\nThere are 5 1s in an array, where the positions of the numbers don\'t matter to us because all we\'re looking at are the numbers that come after them that are the same as themselves. Returning to our example, after the first 1 will come 4 more 1s. The second future is 3 after 1, the third future is 2 after 1, and so on until 1.\n\nNow let **a** be the count of 1 in the array. After the first 1 will come a-1 more 1s. The second future is a-2 after 1, the third future is a-3 after 1, and so on until 1.\n\nNow let\'s change our arr a little bit and let our new array be [1,2,3,1,1,3,1,1,3,1,1,3,1,1,1,1,3, \u2026 , 1,1]\nLet **a** be the count of 1s here too\n\n\n\n| Arr | Count of 1s after ***bold-italic*** value (**a** is count of all 1s) |\n|:-:| :-:|\n| [***1***,2,3,1,1,3,1,1,3,1,1,3,1,1,1,1,3, \u2026 , 1,1]| a-1 |\n| [1,2,3,***1***,1,3,1,1,3,1,1,3,1,1,1,1,3, \u2026 , 1,1]| a-2 |\n| [1,2,3,1,***1***,3,1,1,3,1,1,3,1,1,1,1,3, \u2026 , 1,1]| a-3 |\n| ... | |\n| [1,2,3,1,1,3,1,1,3,1,1,3,1,1,1,1,3, \u2026 , ***1***,1]| 1 |\n\n****\nIf check the second column you can see numbers goes to 1 from a-1 so we can specify as\nTotal number of good pairs = $$[(a-1) + (a-2)+(a-3)+...+1]$$\n\n\nIf we use consecutive numbers formula on *Total number of good pairs*\n\n$$\\Large\\frac {n(firstNumber + lastNumber)}{2}$$ $$\\leftarrow$$ this is the **consecutive formula**\n\nin our problem,\n*n* = **a-1**, because when size **a** we start from **a-1** \nfor example 1s count are 5, its sum of good pairs 4+3+2+1. That\u2019s why size is 5-1 = 4, so **a-1**.\n\n*first number* = **a - 1**,\n*last number* = **1**,\n\nIf we substitute the variables\n$$\\Large\\frac {(a-1) * (a-1 + 1)}{2} = \\Large\\frac{(a-1) * a}{2}$$\n\nWith $\\large\\frac{(a-1) * a}{2}$, we calculate the number of good pairs for each different number and return the sum.\n\n**If we use the counts of the numbers we keep in the hashmap in this formula and sum the results, we will find the good pairs in the array.**\n\n\n```\nbool shouldYouUpvote() { return (I helped == true) ? upvote : nothing; }\n```\n\n\n\n\n\n | 5 | 0 | ['Hash Table', 'Math', 'C++'] | 0 |
number-of-good-pairs | Python oneliner solution | python-oneliner-solution-by-trpaslik-qqfk | Here is my python one-liner:\n\npython\n return sum(c * (c - 1) // 2 for c in Counter(nums).values())\n | trpaslik | NORMAL | 2022-05-31T11:09:51.878939+00:00 | 2022-05-31T11:09:51.878969+00:00 | 759 | false | Here is my python one-liner:\n\n```python\n return sum(c * (c - 1) // 2 for c in Counter(nums).values())\n``` | 5 | 0 | ['Python'] | 0 |
number-of-good-pairs | Good 100% faster solution | good-100-faster-solution-by-sourav_17-xxfy | \nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int n = nums.size();\n map<int,int> smap;\n int count =0;\n | sourav_17 | NORMAL | 2021-04-10T06:18:58.386590+00:00 | 2021-04-10T06:18:58.386633+00:00 | 617 | false | ```\nclass Solution {\npublic:\n int numIdenticalPairs(vector<int>& nums) {\n int n = nums.size();\n map<int,int> smap;\n int count =0;\n for(int i =0;i<n;i++)\n {\n count+=smap[nums[i]];\n smap[nums[i]]++;\n }\n return count;\n \n }\n}\n``` | 5 | 0 | ['C', 'C++'] | 0 |
number-of-good-pairs | Java | Hashing | 2 methods | java-hashing-2-methods-by-prashant404-2aki | Method 1: \n>T/S: O(n\xB2)/O(1), where n = size(nums)\n\npublic int numIdenticalPairs(int[] nums) {\n\tvar count = 0;\n\n\tfor (var i = 0; i < nums.length; i++) | prashant404 | NORMAL | 2020-12-22T04:54:04.075167+00:00 | 2023-10-03T07:25:04.331316+00:00 | 798 | false | **Method 1**: \n>T/S: O(n\xB2)/O(1), where n = size(nums)\n```\npublic int numIdenticalPairs(int[] nums) {\n\tvar count = 0;\n\n\tfor (var i = 0; i < nums.length; i++)\n\t\tfor (var j = i + 1; j < nums.length; j++)\n\t\t\tif (nums[i] == nums[j])\n\t\t\t\tcount++;\n\n\treturn count;\n}\n```\n\n**Method 2**: \n>T/S: O(n)/O(n)\n```\npublic int numIdenticalPairs(int[] nums) {\n var count = 0;\n var numByFrequency = new HashMap<Integer, Integer>();\n\n for (var num : nums) {\n count += numByFrequency.getOrDefault(num, 0);\n numByFrequency.compute(num, (k, v) -> v == null ? 1 : ++v);\n }\n\n return count;\n}\n```\n***Please upvote if this helps*** | 5 | 0 | ['Java'] | 1 |
number-of-good-pairs | Python 3 -> 98.52% faster. 3 techniques but only 1 optimal solution | python-3-9852-faster-3-techniques-but-on-v46w | Suggestions to make it better are always welcomed.\n\nThere are 3 ways of doing this:\n1. Use 2 for loops. For every ith element, compare with the remaining i+1 | mybuddy29 | NORMAL | 2020-08-29T23:20:46.713391+00:00 | 2020-08-29T23:20:46.713437+00:00 | 573 | false | **Suggestions to make it better are always welcomed.**\n\nThere are 3 ways of doing this:\n1. Use 2 for loops. For every ith element, compare with the remaining i+1 to n elements. If match is found, increase the count. This is T=O(n2) and S=O(1)\n\n2. Sort the list before processing it. This way all the matching numbers will be near each other. Now searching for the pair can be done using binary search. Assuming sorting is O(n log n) and binary search for every ith element is also O(n log n), overall T = O(n log n) and S = O(1)\n\n3. Using dictionary. Record every elements that we encounter. If the element already exists, then increment it\'s count. We sum the elements that match and return the result. Here T=O(n) at the expense of space, S=O(n)\n\n**Implementation of solution 3:**\n```\ndef numIdenticalPairs(self, nums: List[int]) -> int:\n\tmapping = collections.defaultdict(int)\n\ttotal = 0\n\tfor i in range(len(nums)):\n\t\ttotal += mapping[nums[i]]\n\t\tmapping[nums[i]] += 1\n\treturn total\n```\n\n**If this solution helped, please upvote it for others to take advantage of it and learn their techniques** | 5 | 1 | ['Python', 'Python3'] | 2 |
number-of-good-pairs | Python 3 Solution With defaultdict | python-3-solution-with-defaultdict-by-hs-5owk | \nclass Solution:\n def numIdenticalPairs(self, nums) -> int:\n """\n Given an array of numbers, this program determines the\n number of | hsweiner54 | NORMAL | 2020-07-12T14:44:12.923048+00:00 | 2020-07-12T14:44:12.923085+00:00 | 379 | false | ```\nclass Solution:\n def numIdenticalPairs(self, nums) -> int:\n """\n Given an array of numbers, this program determines the\n number of good pairs [nums[j], nums[k]]. In a good pair,\n j < k and nums[j] = nums[k].\n \n If there are 2 or more ocurrences of a value within nums, then\n there is at least 1 good pair for that value. If there are n\n occurrences of a value, the number of good pairs is:\n \n n!\n ---------------- or n * (n - 1) / 2\n (n - 2)! * 2!\n\n :param nums: array of integers\n :type nums: list[int]\n :return: number of good pairs\n :rtype: int\n """\n counts = defaultdict(int)\n for num in nums:\n counts[num] += 1\n good_pairs = 0\n for count in counts.values():\n if count > 1:\n good_pairs += count * (count - 1) // 2\n return good_pairs\n\n``` | 5 | 1 | ['Python3'] | 0 |
number-of-good-pairs | Python - Faster than 100% of Submission | python-faster-than-100-of-submission-by-mif79 | \n freq={}\n output=0\n for num in nums:\n if not num in freq:\n freq[num]=0\n freq[num]+=1\n \ | azrap | NORMAL | 2020-07-12T09:36:34.731282+00:00 | 2020-07-12T09:36:34.731316+00:00 | 756 | false | ```\n freq={}\n output=0\n for num in nums:\n if not num in freq:\n freq[num]=0\n freq[num]+=1\n \n for num in freq:\n n=freq[num]\n output+=(n*(n-1)//2)\n \n return output\n```\n\n | 5 | 0 | [] | 1 |
number-of-good-pairs | Simple Java Code ☠️ | simple-java-code-by-abhinandannaik1717-vedq | Code\njava []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int n = nums.length;\n HashMap<Integer,Integer> map = new HashMa | abhinandannaik1717 | NORMAL | 2024-08-23T16:57:34.041905+00:00 | 2024-08-23T16:57:34.041935+00:00 | 512 | false | # Code\n```java []\nclass Solution {\n public int numIdenticalPairs(int[] nums) {\n int n = nums.length;\n HashMap<Integer,Integer> map = new HashMap<>();\n int c=0;\n for(int i=0;i<n;i++){\n if(!map.isEmpty() && map.containsKey(nums[i])){\n c+=map.get(nums[i]);\n map.put(nums[i],map.get(nums[i])+1);\n }\n else{\n map.put(nums[i],1);\n }\n }\n return c;\n }\n}\n```\n\n### Explanation \n\nThe provided code efficiently counts the number of "good pairs" in the array `nums` using a HashMap. Here\'s how the logic works:\n\n1. **HashMap Initialization**: A HashMap named `map` is initialized to keep track of the frequency of each number in the array `nums`.\n\n2. **Iterating Through the Array**:\n - We loop through each element in the array `nums`.\n - For each element `nums[i]`, we check if it already exists in the `map`.\n - **If it exists**: This means that there are already some occurrences of `nums[i]` in the array before index `i`. The number of "good pairs" that can be formed with the current element `nums[i]` is equal to the number of times `nums[i]` has been seen so far. We increment the count `c` by the value associated with `nums[i]` in the map.\n - Then, we increment the count of `nums[i]` in the map by 1.\n - **If it does not exist**: We add `nums[i]` to the map with a count of 1.\n\n3. **Counting Good Pairs**:\n - The variable `c` accumulates the total number of "good pairs" as we iterate through the array. By the end of the loop, `c` contains the total number of pairs `(i, j)` such that `nums[i] == nums[j]` and `i < j`.\n\n### Example\n\nLet\'s walk through a quick example:\n\n- **Input**: `nums = [1, 2, 3, 1, 1, 3]`\n- **Initialization**: `map = {}`, `c = 0`\n \n- **Iteration 1**: `nums[0] = 1`\n - `map` is empty, add `1` to `map` with count `1`.\n - `map = {1: 1}`, `c = 0`\n\n- **Iteration 2**: `nums[1] = 2`\n - `map` does not have `2`, add `2` to `map` with count `1`.\n - `map = {1: 1, 2: 1}`, `c = 0`\n\n- **Iteration 3**: `nums[2] = 3`\n - `map` does not have `3`, add `3` to `map` with count `1`.\n - `map = {1: 1, 2: 1, 3: 1}`, `c = 0`\n\n- **Iteration 4**: `nums[3] = 1`\n - `map` has `1` with count `1`. Increment `c` by `1` (because there is 1 previous `1`).\n - Increment count of `1` in `map` to `2`.\n - `map = {1: 2, 2: 1, 3: 1}`, `c = 1`\n\n- **Iteration 5**: `nums[4] = 1`\n - `map` has `1` with count `2`. Increment `c` by `2` (because there are 2 previous `1`s).\n - Increment count of `1` in `map` to `3`.\n - `map = {1: 3, 2: 1, 3: 1}`, `c = 3`\n\n- **Iteration 6**: `nums[5] = 3`\n - `map` has `3` with count `1`. Increment `c` by `1` (because there is 1 previous `3`).\n - Increment count of `3` in `map` to `2`.\n - `map = {1: 3, 2: 1, 3: 2}`, `c = 4`\n\n- **Final Output**: `c = 4`\n\n\n\n### Time Complexity: **O(n)**\n### Space Complexity: **O(n)** \n | 4 | 0 | ['Java'] | 0 |
number-of-good-pairs | 43 ms -----users with Python3 | 43-ms-users-with-python3-by-kawinp-znn6 | 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 | KawinP | NORMAL | 2024-05-27T17:26:19.966891+00:00 | 2024-05-27T17:26:19.966913+00:00 | 1,007 | 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 def numIdenticalPairs(self, nums: List[int]) -> int:\n count = {}\n for num in nums:\n count[num] = count.get(num, 0) + 1\n \n tp = 0\n\n for key in count:\n tp = tp + (count[key] * (count[key] - 1)) // 2\n \n return tp\n\n``` | 4 | 0 | ['Python3'] | 0 |
number-of-good-pairs | ⭐ Let's solve in easy way| Brute force Approach | C++, C, JavaScript ✅ | lets-solve-in-easy-way-brute-force-appro-farj | Approach\nIn the quesiton, Same number creates a good pair.\n\nFor easy to understand,\nGood pair = Two values that are the same form a pair, but their index va | Captain2000 | NORMAL | 2024-04-02T13:35:24.216591+00:00 | 2024-04-06T11:09:48.815979+00:00 | 245 | false | # Approach\nIn the quesiton, Same number creates a good pair.\n\nFor easy to understand,\nGood pair = Two values that are the same form a pair, but their index values are different. \n\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 numIdenticalPairs(vector<int>& nums) {\n int count=0;\n\n for (int i=0; i<nums.size(); i++){\n for (int j=i+1; j<nums.size(); j++){\n if (nums[i] == nums[j]){\n count++;\n }\n }\n }\n return count;\n }\n};\n```\n```c []\nint numIdenticalPairs(int* nums, int numsSize) {\n int count=0;\n\n for (int i=0; i<numsSize; i++){\n for (int j=i+1; j<numsSize; j++){\n if (nums[i] == nums[j]){\n count++;\n }\n }\n }\n return count;\n}\n```\n```javascript []\nvar numIdenticalPairs = function(nums) {\n let count=0;\n\n for (let i=0; i<nums.length; i++){\n for (let j=i+1; j<nums.length; j++){\n if (nums[i] == nums[j]){\n count++;\n }\n }\n }\n return count;\n};\n```\n## Please consider giving me an upvote :)\n\n\n\n\n | 4 | 0 | ['C', 'C++', 'JavaScript'] | 0 |
surrounded-regions | C++ Beginner Friendly | Boundary DFS | inPlace | c-beginner-friendly-boundary-dfs-inplace-ldk2 | \nclass Solution {\npublic:\n void DFS(vector<vector<char>>& board, int i, int j, int m, int n) {\n if(i<0 or j<0 or i>=m or j>=n or board[i][j] != \' | chronoviser | NORMAL | 2020-06-17T08:04:22.754075+00:00 | 2020-06-17T08:04:22.754108+00:00 | 56,589 | false | ```\nclass Solution {\npublic:\n void DFS(vector<vector<char>>& board, int i, int j, int m, int n) {\n if(i<0 or j<0 or i>=m or j>=n or board[i][j] != \'O\') return;\n board[i][j] = \'#\';\n DFS(board, i-1, j, m, n);\n DFS(board, i+1, j, m, n);\n DFS(board, i, j-1, m, n);\n DFS(board, i, j+1, m, n);\n }\n \n void solve(vector<vector<char>>& board) {\n \n //We will use boundary DFS to solve this problem\n \n // Let\'s analyze when an \'O\' cannot be flipped,\n // if it has atleast one \'O\' in it\'s adjacent, AND ultimately this chain of adjacent \'O\'s is connected to some \'O\' which lies on boundary of board\n \n //consider these two cases for clarity :\n /*\n O\'s won\'t be flipped O\'s will be flipped\n [X O X X X] [X X X X X] \n [X O O O X] [X O O O X]\n [X O X X X] [X O X X X] \n [X X X X X] [X X X X X]\n \n So we can conclude if a chain of adjacent O\'s is connected some O on boundary then they cannot be flipped\n \n */\n \n //Steps to Solve :\n //1. Move over the boundary of board, and find O\'s \n //2. Every time we find an O, perform DFS from it\'s position\n //3. In DFS convert all \'O\' to \'#\' (why?? so that we can differentiate which \'O\' can be flipped and which cannot be) \n //4. After all DFSs have been performed, board contains three elements,#,O and X\n //5. \'O\' are left over elements which are not connected to any boundary O, so flip them to \'X\'\n //6. \'#\' are elements which cannot be flipped to \'X\', so flip them back to \'O\'\n //7. finally, Upvote the solution\uD83D\uDE0A \n \n \n int m = board.size();\n \n if(m == 0) return; \n \n int n = board[0].size();\n \n //Moving over firts and last column \n for(int i=0; i<m; i++) {\n if(board[i][0] == \'O\')\n DFS(board, i, 0, m, n);\n if(board[i][n-1] == \'O\')\n DFS(board, i, n-1, m, n);\n }\n \n \n //Moving over first and last row \n for(int j=0; j<n; j++) {\n if(board[0][j] == \'O\')\n DFS(board, 0, j, m, n);\n if(board[m-1][j] == \'O\')\n DFS(board, m-1, j, m, n);\n }\n \n for(int i=0; i<m; i++)\n for(int j=0; j<n; j++)\n {\n if(board[i][j] == \'O\')\n board[i][j] = \'X\';\n if(board[i][j] == \'#\')\n board[i][j] = \'O\';\n }\n }\n};\n``` | 1,588 | 6 | [] | 84 |
surrounded-regions | A really simple and readable C++ solution\uff0conly cost 12ms | a-really-simple-and-readable-c-solutionu-kpel | First, check the four border of the matrix. If there is a element is\n 'O', alter it and all its neighbor 'O' elements to '1'.\n \n \n - Then ,alter all t | sugeladi | NORMAL | 2015-06-27T02:50:31+00:00 | 2018-10-25T23:27:01.864376+00:00 | 97,448 | false | - First, check the four border of the matrix. If there is a element is\n 'O', alter it and all its neighbor 'O' elements to '1'.\n \n \n - Then ,alter all the 'O' to 'X'\n - At last,alter all the '1' to 'O'\n\nFor example:\n\n X X X X X X X X X X X X\n X X O X -> X X O X -> X X X X\n X O X X X 1 X X X O X X\n X O X X X 1 X X X O X X\n \n\n class Solution {\n public:\n \tvoid solve(vector<vector<char>>& board) {\n int i,j;\n int row=board.size();\n if(!row)\n \treturn;\n int col=board[0].size();\n\n \t\tfor(i=0;i<row;i++){\n \t\t\tcheck(board,i,0,row,col);\n \t\t\tif(col>1)\n \t\t\t\tcheck(board,i,col-1,row,col);\n \t\t}\n \t\tfor(j=1;j+1<col;j++){\n \t\t\tcheck(board,0,j,row,col);\n \t\t\tif(row>1)\n \t\t\t\tcheck(board,row-1,j,row,col);\n \t\t}\n \t\tfor(i=0;i<row;i++)\n \t\t\tfor(j=0;j<col;j++)\n \t\t\t\tif(board[i][j]=='O')\n \t\t\t\t\tboard[i][j]='X';\n \t\tfor(i=0;i<row;i++)\n \t\t\tfor(j=0;j<col;j++)\n \t\t\t\tif(board[i][j]=='1')\n \t\t\t\t\tboard[i][j]='O';\n }\n \tvoid check(vector<vector<char> >&vec,int i,int j,int row,int col){\n \t\tif(vec[i][j]=='O'){\n \t\t\tvec[i][j]='1';\n \t\t\tif(i>1)\n \t\t\t\tcheck(vec,i-1,j,row,col);\n \t\t\tif(j>1)\n \t\t\t\tcheck(vec,i,j-1,row,col);\n \t\t\tif(i+1<row)\n \t\t\t\tcheck(vec,i+1,j,row,col);\n \t\t\tif(j+1<col)\n \t\t\t\tcheck(vec,i,j+1,row,col);\n \t\t}\n \t}\n }; | 533 | 15 | ['C++'] | 68 |
surrounded-regions | 9 lines, Python 148 ms | 9-lines-python-148-ms-by-stefanpochmann-i0ps | Phase 1: "Save" every O-region touching the border, changing its cells to 'S'. \nPhase 2: Change every 'S' on the board to 'O' and everything else to 'X'.\n\n | stefanpochmann | NORMAL | 2015-07-14T11:40:54+00:00 | 2018-10-22T07:22:20.456625+00:00 | 50,348 | false | Phase 1: "Save" every O-region touching the border, changing its cells to 'S'. \nPhase 2: Change every 'S' on the board to 'O' and everything else to 'X'.\n\n def solve(self, board):\n if not any(board): return\n \n m, n = len(board), len(board[0])\n save = [ij for k in range(m+n) for ij in ((0, k), (m-1, k), (k, 0), (k, n-1))]\n while save:\n i, j = save.pop()\n if 0 <= i < m and 0 <= j < n and board[i][j] == 'O':\n board[i][j] = 'S'\n save += (i, j-1), (i, j+1), (i-1, j), (i+1, j)\n\n board[:] = [['XO'[c == 'S'] for c in row] for row in board]\n\nIn case you don't like my last line, you could do this instead:\n\n for row in board:\n for i, c in enumerate(row):\n row[i] = 'XO'[c == 'S'] | 292 | 13 | ['Python'] | 41 |
surrounded-regions | Java DFS + boundary cell turning solution, simple and clean code, commented. | java-dfs-boundary-cell-turning-solution-4sf3p | \tpublic void solve(char[][] board) {\n\t\tif (board.length == 0 || board[0].length == 0)\n\t\t\treturn;\n\t\tif (board.length < 2 || board[0].length < 2)\n\t\t | jinwu | NORMAL | 2015-09-22T03:42:59+00:00 | 2018-10-16T01:09:16.140119+00:00 | 76,532 | false | \tpublic void solve(char[][] board) {\n\t\tif (board.length == 0 || board[0].length == 0)\n\t\t\treturn;\n\t\tif (board.length < 2 || board[0].length < 2)\n\t\t\treturn;\n\t\tint m = board.length, n = board[0].length;\n\t\t//Any 'O' connected to a boundary can't be turned to 'X', so ...\n\t\t//Start from first and last column, turn 'O' to '*'.\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tif (board[i][0] == 'O')\n\t\t\t\tboundaryDFS(board, i, 0);\n\t\t\tif (board[i][n-1] == 'O')\n\t\t\t\tboundaryDFS(board, i, n-1);\t\n\t\t}\n\t\t//Start from first and last row, turn '0' to '*'\n\t\tfor (int j = 0; j < n; j++) {\n\t\t\tif (board[0][j] == 'O')\n\t\t\t\tboundaryDFS(board, 0, j);\n\t\t\tif (board[m-1][j] == 'O')\n\t\t\t\tboundaryDFS(board, m-1, j);\t\n\t\t}\n\t\t//post-prcessing, turn 'O' to 'X', '*' back to 'O', keep 'X' intact.\n\t\tfor (int i = 0; i < m; i++) {\n\t\t\tfor (int j = 0; j < n; j++) {\n\t\t\t\tif (board[i][j] == 'O')\n\t\t\t\t\tboard[i][j] = 'X';\n\t\t\t\telse if (board[i][j] == '*')\n\t\t\t\t\tboard[i][j] = 'O';\n\t\t\t}\n\t\t}\n\t}\n\t//Use DFS algo to turn internal however boundary-connected 'O' to '*';\n\tprivate void boundaryDFS(char[][] board, int i, int j) {\n\t\tif (i < 0 || i > board.length - 1 || j <0 || j > board[0].length - 1)\n\t\t\treturn;\n\t\tif (board[i][j] == 'O')\n\t\t\tboard[i][j] = '*';\n\t\tif (i > 1 && board[i-1][j] == 'O')\n\t\t\tboundaryDFS(board, i-1, j);\n\t\tif (i < board.length - 2 && board[i+1][j] == 'O')\n\t\t\tboundaryDFS(board, i+1, j);\n\t\tif (j > 1 && board[i][j-1] == 'O')\n\t\t\tboundaryDFS(board, i, j-1);\n\t\tif (j < board[i].length - 2 && board[i][j+1] == 'O' )\n\t\t\tboundaryDFS(board, i, j+1);\n\t} | 261 | 6 | ['Depth-First Search', 'Java'] | 49 |
surrounded-regions | Easy Explained Solution With 🏞 (Images) | easy-explained-solution-with-images-by-y-n6r6 | \n\n\n\n\n\n\n\n\ncode\npython\nfrom collections import deque\n\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do | yasir991925 | NORMAL | 2021-11-01T07:51:57.859028+00:00 | 2021-11-01T07:52:49.130693+00:00 | 19,458 | false | \n\n\n\n\n\n\n\n\ncode\n```python\nfrom collections import deque\n\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n \n o = "O"\n \n n = len(board) \n m = len(board[0])\n\n Q = deque()\n \n for i in range(n):\n if board[i][0] == o:\n Q.append((i,0))\n if board[i][m-1] == o:\n Q.append((i, m-1))\n \n for j in range(m):\n if board[0][j] == o:\n Q.append((0,j))\n if board[n-1][j] == o:\n Q.append((n-1, j))\n \n def inBounds(i,j):\n return (0 <= i < n) and (0 <= j < m)\n \n while Q:\n i,j = Q.popleft()\n board[i][j] = "#"\n \n for ii, jj in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if not inBounds(ii, jj):\n continue\n if board[ii][jj] != o:\n continue\n Q.append((ii,jj))\n board[ii][jj] = \'#\'\n \n for i in range(n):\n for j in range(m):\n if board[i][j] == o:\n board[i][j] = \'X\'\n elif board[i][j] == \'#\':\n board[i][j] = o\n\n```\n | 242 | 2 | ['C', 'Python', 'Java', 'Python3'] | 19 |
surrounded-regions | Solve it using Union Find | solve-it-using-union-find-by-jinminghe5-hwsv | \n\n class UF\n {\n private:\n \tint id; // id[i] = parent of i\n \tint rank; // rank[i] = rank of subtree rooted at i (cannot be more than | jinminghe5 | NORMAL | 2014-06-15T09:29:41+00:00 | 2018-10-18T08:06:05.849487+00:00 | 61,108 | false | \n\n class UF\n {\n private:\n \tint* id; // id[i] = parent of i\n \tint* rank; // rank[i] = rank of subtree rooted at i (cannot be more than 31)\n \tint count; // number of components\n public:\n \tUF(int N)\n \t{\n \t\tcount = N;\n \t\tid = new int[N];\n \t\trank = new int[N];\n \t\tfor (int i = 0; i < N; i++) {\n \t\t\tid[i] = i;\n \t\t\trank[i] = 0;\n \t\t}\n \t}\n \t~UF()\n \t{\n \t\tdelete [] id;\n \t\tdelete [] rank;\n \t}\n \tint find(int p) {\n \t\twhile (p != id[p]) {\n \t\t\tid[p] = id[id[p]]; // path compression by halving\n \t\t\tp = id[p];\n \t\t}\n \t\treturn p;\n \t}\n \tint getCount() {\n \t\treturn count;\n \t}\n \tbool connected(int p, int q) {\n \t\treturn find(p) == find(q);\n \t}\n \tvoid connect(int p, int q) {\n \t\tint i = find(p);\n \t\tint j = find(q);\n \t\tif (i == j) return;\n \t\tif (rank[i] < rank[j]) id[i] = j;\n \t\telse if (rank[i] > rank[j]) id[j] = i;\n \t\telse {\n \t\t\tid[j] = i;\n \t\t\trank[i]++;\n \t\t}\n \t\tcount--;\n \t}\n };\n \n class Solution {\n public:\n void solve(vector<vector<char>> &board) {\n int n = board.size();\n if(n==0) return;\n int m = board[0].size();\n UF uf = UF(n*m+1);\n \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)&&board[i][j]=='O') // if a 'O' node is on the boundry, connect it to the dummy node\n uf.connect(i*m+j,n*m);\n else if(board[i][j]=='O') // connect a 'O' node to its neighbour 'O' nodes\n {\n if(board[i-1][j]=='O')\n uf.connect(i*m+j,(i-1)*m+j);\n if(board[i+1][j]=='O')\n uf.connect(i*m+j,(i+1)*m+j);\n if(board[i][j-1]=='O')\n uf.connect(i*m+j,i*m+j-1);\n if(board[i][j+1]=='O')\n uf.connect(i*m+j,i*m+j+1);\n }\n }\n }\n \n for(int i=0;i<n;i++){\n for(int j=0;j<m;j++){\n if(!uf.connected(i*m+j,n*m)){ // if a 'O' node is not connected to the dummy node, it is captured\n board[i][j]='X';\n }\n }\n }\n }\n };\n\nHi. So here is my accepted code using **Union Find** data structure. The idea comes from the observation that if a region is NOT captured, it is connected to the boundry. So if we connect all the 'O' nodes on the boundry to a dummy node, and then connect each 'O' node to its neighbour 'O' nodes, then we can tell directly whether a 'O' node is captured by checking whether it is connected to the dummy node.\nFor more about Union Find, the first assignment in the algo1 may help:\nhttps://www.coursera.org/course/algs4partI | 213 | 1 | [] | 36 |
surrounded-regions | Python easy to understand DFS and BFS solutions | python-easy-to-understand-dfs-and-bfs-so-zh4y | \nclass Solution(object):\n # DFS\n def solve1(self, board):\n if not board or not board[0]:\n return \n for i in [0, len(board)- | oldcodingfarmer | NORMAL | 2015-09-10T10:07:56+00:00 | 2020-09-17T16:11:51.620288+00:00 | 27,121 | false | ```\nclass Solution(object):\n # DFS\n def solve1(self, board):\n if not board or not board[0]:\n return \n for i in [0, len(board)-1]:\n for j in range(len(board[0])):\n self.dfs(board, i, j) \n for i in range(len(board)):\n for j in [0, len(board[0])-1]:\n self.dfs(board, i, j)\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == \'O\':\n board[i][j] = \'X\'\n elif board[i][j] == \'.\':\n board[i][j] = \'O\'\n \n def dfs(self, board, i, j):\n if 0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == \'O\':\n board[i][j] = \'.\'\n self.dfs(board, i+1, j)\n self.dfs(board, i-1, j)\n self.dfs(board, i, j+1)\n self.dfs(board, i, j-1)\n \n # BFS\n def solve(self, board):\n queue = collections.deque([])\n for r in range(len(board)):\n for c in range(len(board[0])):\n if (r in [0, len(board)-1] or c in [0, len(board[0])-1]) and board[r][c] == "O":\n queue.append((r, c))\n while queue:\n r, c = queue.popleft()\n if 0<=r<len(board) and 0<=c<len(board[0]) and board[r][c] == "O":\n board[r][c] = "."\n queue.extend([(r-1, c),(r+1, c),(r, c-1),(r, c+1)])\n \n for r in range(len(board)):\n for c in range(len(board[0])):\n if board[r][c] == "O":\n board[r][c] = "X"\n elif board[r][c] == ".":\n board[r][c] = "O"\n``` | 201 | 5 | ['Depth-First Search', 'Breadth-First Search', 'Python'] | 19 |
surrounded-regions | [Python] O(mn), 3 colors dfs, explained | python-omn-3-colors-dfs-explained-by-dba-eenh | In this problem we need to understand, what exactly surrouned by \'X\' means. It actually means that if we start from \'O\' at the border, and we traverse only | dbabichev | NORMAL | 2020-06-17T07:45:28.910212+00:00 | 2020-06-17T10:38:28.590138+00:00 | 7,071 | false | In this problem we need to understand, what exactly surrouned by `\'X\'` means. It actually means that if we start from `\'O\'` at the border, and we traverse only `\'O\'`, only those `\'O\'` are **not surrouned** by `\'X\'`. So the plan is the following:\n\n1. Start dfs or bfs from all `\'O\'`, which are on the border.\n2. When we traverse them, let us color them as `\'T\'`, temporary color.\n3. Now, when we traverse all we wanted, all colors which are not `\'T\'` need to renamed to `\'X\'` and all colors which are `\'T\'` need to be renamed to `\'O\'`, and that is all!\n\n**Compexity**: time complextiy is `O(mn)`, where `m` and `n` are sizes of our board. Additional space complexity can also go upto `O(mn)` to keep stack of recursion.\n\n```\nclass Solution:\n def dfs(self, i, j):\n if i<0 or j<0 or i>=self.M or j>=self.N or self.board[i][j] != "O":\n return\n self.board[i][j] = \'T\'\n neib_list = [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]\n for x, y in neib_list:\n self.dfs(x, y)\n \n def solve(self, board):\n if not board: return 0\n self.board, self.M, self.N = board, len(board), len(board[0])\n \n for i in range(0, self.M):\n self.dfs(i,0)\n self.dfs(i,self.N-1)\n \n for j in range(0, self.N):\n self.dfs(0,j)\n self.dfs(self.M-1,j)\n \n for i,j in product(range(self.M), range(self.N)):\n board[i][j] = "X" if board[i][j] != "T" else "O"\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!** | 140 | 2 | ['Depth-First Search'] | 9 |
surrounded-regions | [Java] Simple and Readable Solution | BFS | java-simple-and-readable-solution-bfs-by-avh5 | Problem statement at a glance: So, a m x n matrix is given with \'O\'s and \'X\'s and we to make all \'O\'s to \'X\'s which are on 4 directions of a \'X\' and t | poojitha_792 | NORMAL | 2021-11-01T12:13:36.930508+00:00 | 2021-11-01T13:02:59.615442+00:00 | 7,654 | false | **Problem statement at a glance**: So, a m x n matrix is given with \'O\'s and \'X\'s and we to make all \'O\'s to \'X\'s which are on 4 directions of a \'X\' and they should not be connected with an \'O\' which is on border.\n**Approach:**\n1) Traverse all borders of the grid and if you find an \'O\', then mark all the connected \'O\'s with any other temporary character(Let\'s say \'1\'). ( We should not convert the \'O\'s which are connected with an \'O\' which is on border. So, first mark those positions with any other character, so that at later we can convert them to \'O\' again). \n2) Now convert all 1\'s to O\'s and O\'s to X\'s.\n\n**Pictorial Representation:**\n\n\n**Time Complexity:** O(N * M), where N is the number of rows of the board and M is the number of columns of the board. We will be traversing the grid two times. So time complexity is O(2 * N * M) ~ O(N * M).\n\n**Space Complexity:** O(N * M). Due to a queue in BFS.\n\n**Code:**\n```\nclass Solution {\n public void bfs(char [][]board,int i,int j)\n {\n // These two arrays are used to traverse four directions of a particular cell.\n int []dx={-1,0,1,0};\n int []dy={0,1,0,-1};\n Queue<ArrayList<Integer>>queue=new LinkedList<>();\n // Add the current cell to queue\n queue.add(new ArrayList<>(Arrays.asList(i,j)));\n // Do BFS until queue is empty\n while(!queue.isEmpty())\n {\n // Retrieve first position in queue\n ArrayList<Integer>temp=queue.poll();\n int curx=(int)temp.get(0);\n int cury=(int)temp.get(1);\n // Mark it as \'1\'\n board[curx][cury]=\'1\';\n // Mark four cells which are connected to current cell to \'1\' if cell has \'O\' and push it to queue.\n for(int i1=0;i1<4;i1++)\n {\n if(curx+dx[i1]<board.length && curx+dx[i1]>=0 && cury+dy[i1]<board[0].length && cury+dy[i1]>=0)\n {\n \n if(board[curx+dx[i1]][cury+dy[i1]]==\'O\'){\n board[curx+dx[i1]][cury+dy[i1]]=\'1\';\n queue.add(new ArrayList<>(Arrays.asList(curx+dx[i1],cury+dy[i1])));\n }\n }\n }\n \n }\n }\n public void solve(char[][] board) {\n \n // Traversing on 1st row\n for(int j=0;j<board[0].length;j++)\n {\n // If we found an \'O\' on border, we need to make all its connected \'O\'s to \'1\'s.\n if(board[0][j]==\'O\')\n {\n bfs(board,0,j); \n }\n }\n // Traversing on last row\n for(int j=0;j<board[0].length;j++)\n {\n // If we found an \'O\' on border, we need to make all its connected \'O\'s to \'1\'s.\n if(board[board.length-1][j]==\'O\')\n bfs(board,board.length-1,j);\n } \n // Traversing on first column\n for(int i=0;i<board.length;i++)\n {\n // If we found an \'O\' on border, we need to make all its connected \'O\'s to \'1\'s.\n if(board[i][0]==\'O\')\n bfs(board,i,0);\n }\n // Traversing on last column\n for(int i=0;i<board.length;i++)\n {\n // If we found an \'O\' on border, we need to make all its connected \'O\'s to \'1\'s.\n if(board[i][board[0].length-1]==\'O\')\n bfs(board,i,board[0].length-1);\n }\n // Traverse the grid again and perform step 2\n for(int i=0;i<board.length;i++)\n {\n for(int j=0;j<board[0].length;j++)\n {\n if(board[i][j]==\'O\')\n board[i][j]=\'X\';\n else if(board[i][j]==\'1\')\n board[i][j]=\'O\';\n }\n }\n }\n}\n```\nThanks for reading! Please upvote and comment if you got a clear idea:) \n | 103 | 6 | ['Breadth-First Search'] | 15 |
surrounded-regions | My BFS solution (C++ 28ms) | my-bfs-solution-c-28ms-by-eaglesky-w8rf | The algorithm is quite simple: Use BFS starting from 'O's on the boundary and mark them as 'B', then iterate over the whole board and mark 'O' as 'X' and 'B' a | eaglesky | NORMAL | 2014-08-27T08:01:57+00:00 | 2014-08-27T08:01:57+00:00 | 36,823 | false | The algorithm is quite simple: Use BFS starting from 'O's on the boundary and mark them as 'B', then iterate over the whole board and mark 'O' as 'X' and 'B' as 'O'. \n\n\n\n void bfsBoundary(vector<vector<char> >& board, int w, int l)\n {\n int width = board.size();\n int length = board[0].size();\n deque<pair<int, int> > q;\n q.push_back(make_pair(w, l));\n board[w][l] = 'B';\n while (!q.empty()) {\n pair<int, int> cur = q.front();\n q.pop_front();\n pair<int, int> adjs[4] = {{cur.first-1, cur.second}, \n {cur.first+1, cur.second}, \n {cur.first, cur.second-1},\n {cur.first, cur.second+1}};\n for (int i = 0; i < 4; ++i)\n {\n int adjW = adjs[i].first;\n int adjL = adjs[i].second;\n if ((adjW >= 0) && (adjW < width) && (adjL >= 0)\n && (adjL < length) \n && (board[adjW][adjL] == 'O')) {\n q.push_back(make_pair(adjW, adjL));\n board[adjW][adjL] = 'B';\n }\n }\n }\n }\n \n void solve(vector<vector<char> > &board) {\n int width = board.size();\n if (width == 0) //Add this to prevent run-time error!\n return;\n int length = board[0].size();\n if (length == 0) // Add this to prevent run-time error!\n return;\n \n for (int i = 0; i < length; ++i)\n {\n if (board[0][i] == 'O')\n bfsBoundary(board, 0, i);\n \n if (board[width-1][i] == 'O')\n bfsBoundary(board, width-1, i);\n }\n \n for (int i = 0; i < width; ++i)\n {\n if (board[i][0] == 'O')\n bfsBoundary(board, i, 0);\n if (board[i][length-1] == 'O')\n bfsBoundary(board, i, length-1);\n }\n \n for (int i = 0; i < width; ++i)\n {\n for (int j = 0; j < length; ++j)\n {\n if (board[i][j] == 'O')\n board[i][j] = 'X';\n else if (board[i][j] == 'B')\n board[i][j] = 'O';\n }\n }\n }\n\nNote that one of the test cases is when the board is empty. So if you don't check it in your code, you will encounter an run-time error. | 97 | 1 | ['Breadth-First Search'] | 31 |
surrounded-regions | Simple BFS solution - easy to understand | simple-bfs-solution-easy-to-understand-b-socy | The idea is to first find all 'O's on the edge, and do BFS from these 'O's. Keep adding 'O's into the queue in the BFS, and mark it as '+'. Since these 'O's are | husqing | NORMAL | 2015-06-05T18:51:08+00:00 | 2018-10-20T02:53:50.736488+00:00 | 19,014 | false | The idea is to first find all 'O's on the edge, and do BFS from these 'O's. Keep adding 'O's into the queue in the BFS, and mark it as '+'. Since these 'O's are found by doing BFS from the 'O's on the edge, it means they are connected to the edge 'O's. so they are the 'O's that will remain as 'O' in the result. \n\nAfter BFS, there are some 'O's can not be reached, they are the 'O's that need to be turned as 'X'.\n\n\n\n\n\n public class Solution {\n public void solve(char[][] board) {\n if (board.length == 0) return;\n \n int rowN = board.length;\n int colN = board[0].length;\n Queue<Point> queue = new LinkedList<Point>();\n \n //get all 'O's on the edge first\n for (int r = 0; r< rowN; r++){\n \tif (board[r][0] == 'O') {\n \t\tboard[r][0] = '+';\n queue.add(new Point(r, 0));\n \t}\n \tif (board[r][colN-1] == 'O') {\n \t\tboard[r][colN-1] = '+';\n queue.add(new Point(r, colN-1));\n \t}\n \t}\n \n for (int c = 0; c< colN; c++){\n \tif (board[0][c] == 'O') {\n \t\tboard[0][c] = '+';\n queue.add(new Point(0, c));\n \t}\n \tif (board[rowN-1][c] == 'O') {\n \t\tboard[rowN-1][c] = '+';\n queue.add(new Point(rowN-1, c));\n \t}\n \t}\n \n \n //BFS for the 'O's, and mark it as '+'\n while (!queue.isEmpty()){\n \tPoint p = queue.poll();\n \tint row = p.x;\n \tint col = p.y;\n \tif (row - 1 >= 0 && board[row-1][col] == 'O') {board[row-1][col] = '+'; queue.add(new Point(row-1, col));}\n \tif (row + 1 < rowN && board[row+1][col] == 'O') {board[row+1][col] = '+'; queue.add(new Point(row+1, col));}\n \tif (col - 1 >= 0 && board[row][col - 1] == 'O') {board[row][col-1] = '+'; queue.add(new Point(row, col-1));}\n if (col + 1 < colN && board[row][col + 1] == 'O') {board[row][col+1] = '+'; queue.add(new Point(row, col+1));} \t \n }\n \n \n //turn all '+' to 'O', and 'O' to 'X'\n for (int i = 0; i<rowN; i++){\n \tfor (int j=0; j<colN; j++){\n \t\tif (board[i][j] == 'O') board[i][j] = 'X';\n \t\tif (board[i][j] == '+') board[i][j] = 'O';\n \t}\n }\n \n \n }\n } | 88 | 3 | ['Breadth-First Search', 'Java'] | 10 |
surrounded-regions | Java Union-Find with Explanations | java-union-find-with-explanations-by-gra-jhmm | Click to see DFS Solution\n\nLogical Thought\nWe aim to find all \'O\'s such that it is on the border or it is connected to an \'O\' on the border. If we regard | gracemeng | NORMAL | 2018-09-05T21:36:37.481111+00:00 | 2018-10-09T06:25:15.012099+00:00 | 4,441 | false | [Click to see DFS Solution](https://leetcode.com/problems/surrounded-regions/discuss/163363/Logical-Thinking-with-Code)\n\n**Logical Thought**\nWe aim to find all \'O\'s such that it is on the border or it is connected to an \'O\' on the border. If we regard \'O\' mentioned above as a `node` (or an `element`), the problem becomes to find the `connected components` (or `disjoint sets`) connected to borders. So-called borders should also be represented as an element, so elements connected to it can be merged with it into a set. That\'s the usage of `dummyBorder`.\n**Pseudo-code**\n```\ninitialize dummyRepresentative\n\nfor O in board\n\tif O is on border\n\t\tunion(dummyBorder, O)\n\telse\n\t\tfor neighbour of O\n\t\t\tif (neighbour is \'O\') \n\t\t\t\tunion(neighbour, O)\n \nfor each cell\n\tif cell is \'O\' && (find(cel) != find(dummyBorder))\n\t\tflip\n```\n**Code**\n```\n private static int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; \n \n public void solve(char[][] board) {\n \n if (board == null || board.length == 0) {\n return;\n } \n \n DisjointSets disjointSets = new DisjointSets(board);\n int rows = board.length, cols = board[0].length;\n int dummyBorder = rows * cols;\n \n for (int x = 0; x < rows; x++) {\n for (int y = 0; y < cols; y++) {\n if (board[x][y] == \'O\') {\n int borderO = x * cols + y;\n if (x == 0 || x == rows - 1 || y == 0 || y == cols - 1) {\n disjointSets.union(dummyBorder, borderO);\n continue;\n }\n for (int[] dir : directions) {\n int nx = x + dir[0];\n int ny = y + dir[1];\n if (nx >= 0 && ny >= 0 && nx < rows && ny < cols && board[nx][ny] == \'O\') {\n int neighbor = nx * cols + ny;\n disjointSets.union(borderO, neighbor);\n }\n }\n }\n }\n }\n \n for (int x = 0; x < rows; x++) {\n for (int y = 0; y < cols; y++) {\n if (board[x][y] == \'O\' && disjointSets.find(x * cols + y) != disjointSets.find(dummyBorder)) {\n board[x][y] = \'X\';\n }\n }\n }\n \n }\n \n class DisjointSets {\n \n int[] parent;\n \n public DisjointSets(char[][] board) {\n \n int rows = board.length, cols = board[0].length;\n parent = new int[rows * cols + 1];\n \n for (int x = 0; x < rows; x++) {\n for (int y = 0; y < cols; y++) { \n if (board[x][y] == \'O\') {\n int id = x * cols + y;\n parent[id] = id;\n }\n }\n }\n parent[rows * cols] = rows * cols;\n }\n \n public int find(int x) {\n \n if (x == parent[x]) {\n return x;\n }\n return parent[x] = find(parent[x]);\n }\n \n public void union(int x, int y) {\n \n int rootX = find(x);\n int rootY = find(y);\n if (rootX != rootY) {\n parent[rootX] = rootY;\n }\n }\n }\n```\n**Trick**\n* We add an element `dummyBorder` to gather all elements connected to borders. \n\nI appreciate your **VOTE UP** (\u02CAo\u0334\u0336\u0337\u0324\u2304o\u0334\u0336\u0337\u0324\u02CB) | 83 | 1 | [] | 13 |
surrounded-regions | Fast and very easy to understand | DFS from borders | O(N) time | O(N) Space | fast-and-very-easy-to-understand-dfs-fro-ym69 | This problem could be solved two ways:\n1. Identify all isolated \'O\' cells and mark them as \'X\' then.\n2. Mark all accessible from boarders \'O\' and then t | dartkron | NORMAL | 2021-11-01T00:55:05.473285+00:00 | 2021-11-01T14:06:48.057423+00:00 | 10,969 | false | This problem could be solved two ways:\n1. Identify all isolated `\'O\'` cells and mark them as `\'X\'` then.\n2. Mark all accessible from boarders `\'O\'` and then turn all inaccessible ones into `\'X\'`.\n\nThis solution is about the **second way**.\n\nTo mark cells as "reachable", algorithm changing their values to `\'R\'` instead of `\'O\'`.\n\n1. Follow through left and right borders of the board and look for `\'O\'` cells. If found recursevly mark all accessible `\'O\'` cells as `\'R\'`.\n2. Follow through top and bottom borders of the board and do the same.\n3. Follow through the whole board and flip `\'O\'` -> `\'X\'` and `\'R\'` -> `\'O\'`\n\n**Time compexity:** `O(N * M), where N is the height of the board and M is the width of the board. Since in the wrost case algorithm processes all cells twice and O(2 * N * M) == O(N * M)`\n**Space complexity:** `O(N * M)` \u2014 only the fixed set of variables of the fixed size is allocated and all \'marks\' are done \'in-place\' **BUT** recursive function calls are stored on the stack and use N * M memory in the worst case. There are no "real" allocations since the stack is allocated when the program starts, but space complexity is about all **used space**. (Thanks for the [@kim_123 comment](https://leetcode.com/problems/surrounded-regions/discuss/1551810/Fast-and-very-easy-to-understand-or-DFS-from-boarders-or-O(N)-time-or-O(1)-Space/1134588) with the clarifications).\n\n<iframe src="https://leetcode.com/playground/mRtTsxAF/shared" frameBorder="0" width="100%" height="850"></iframe>\n\nThank you for reading this! =) | 62 | 2 | ['C', 'Python', 'Go', 'Python3'] | 6 |
surrounded-regions | [ c++ | JAVA ]Clean and simple [ DFS ] [ Explain ] | c-java-clean-and-simple-dfs-explain-by-s-rx3u | The Idea is first to Mark those grid which having value \' O \' are deeply adjacent to the First Row , First Column , Last Row and Last Column !!! \nso we are | suman_cp | NORMAL | 2020-06-17T13:11:19.054396+00:00 | 2020-06-18T05:59:18.927442+00:00 | 4,494 | false | The Idea is first to Mark those grid which having value \' O \' are deeply adjacent to the First Row , First Column , Last Row and Last Column !!! \nso we are going to update those grid by changeing it\'s value \' O\' - > \' P \' [ I am use \' P \' here ,but You can chose any Value except \' X \' and \' O \' ]\nTo make it happend we run DFS from the Borders[ each by one ] Of The board\nThat\'s It ! this is The main Work , and we done it !!!! [ YES ]\n\nnow the remaining grid those having \' O \' value is the grid which we looking for to change from \' O \' - > \' X \' \ndo that change and the Other grid which we update as value \' P \' need to make them \' O \' again\n\n\n \n< < : : : : : This Example would Make It more clear\n\n\nAt last Submit your Code (^ - ^) \n\n\n[ C++ SOLLUTION ] \n```\nclass Solution {\npublic:\n void DFS(vector<vector<char>>& board,int r,int c,int rsize,int csize){\n if(r<0||c<0||r==rsize||c==csize||board[r][c]!=\'O\')return;\n board[r][c] = \'P\';\n DFS(board,r+1,c,rsize,csize);\n DFS(board,r,c+1,rsize,csize);\n DFS(board,r-1,c,rsize,csize);\n DFS(board,r,c-1,rsize,csize);\n }\n void solve(vector<vector<char>>& board) {\n if(board.empty())return;\n int row = board.size(),col = board[0].size();\n for(int i=0;i<col;i++)DFS(board,0,i,row,col),DFS(board,row-1,i,row,col);\n for(int i=0;i<row;i++)DFS(board,i,0,row,col),DFS(board,i,col-1,row,col);\n \n for(int i=0;i<row;i++)\n for(int j=0;j<col;j++)\n if(board[i][j]==\'O\')board[i][j]=\'X\';\n else if(board[i][j]==\'P\')board[i][j]=\'O\';\n }\n};\n```\n\n[ JAVA ]\n```\nclass Solution {\n private void DFS(char[][] board,int r,int c,int rsize,int csize){\n if(r<0||c<0||r==rsize||c==csize||board[r][c]!=\'O\')return;\n board[r][c] = \'P\';\n DFS(board,r+1,c,rsize,csize);\n DFS(board,r,c+1,rsize,csize);\n DFS(board,r-1,c,rsize,csize);\n DFS(board,r,c-1,rsize,csize);\n } \n public void solve(char[][] board) {\n if(board.length==0)return;\n int row = board.length,col = board[0].length;\n \n for(int i=0;i<col;i++){\n DFS(board,0,i,row,col);//for FIRST ROW\n DFS(board,row-1,i,row,col);//for LAST ROW\n }\n for(int i=0;i<row;i++){\n DFS(board,i,0,row,col);//for FIRST COLUMN\n DFS(board,i,col-1,row,col);//for LAST COLUMN\n }\n for(int i=0;i<row;i++)\n for(int j=0;j<col;j++)\n if(board[i][j]==\'O\')board[i][j]=\'X\';\n else if(board[i][j]==\'P\')board[i][j]=\'O\';\n }\n}\n```\n\nIf It\'s Help you please upvote\nfor any suggestion comments there\nThank You | 62 | 2 | ['C', 'Java'] | 3 |
surrounded-regions | JAVA-----------Easy Version To UnderStand!!!!!!!!!!!! | java-easy-version-to-understand-by-hello-t2pw | ----------\n## Use BFS.This problem is similar to Number of Islands. In this problem, only the cells on the boarders can not be surrounded. So we can first merg | helloworld123456 | NORMAL | 2016-01-24T07:46:52+00:00 | 2018-09-30T19:13:14.673320+00:00 | 12,798 | false | ----------\n## Use BFS.This problem is similar to Number of Islands. In this problem, only the cells on the boarders can not be surrounded. So we can first merge those O's on the boarders like in Number of Islands and replace O's with 'B', and then scan the board and replace all O's left (if any). ##\n\n class Point {\n\tint x;\n\tint y;\n\tPoint(int x, int y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n}\n\n public static void solve(char[][] board) {\n\t\tif (board == null || board.length == 0)\n\t\t\treturn;\n\t\tint rows = board.length, columns = board[0].length;\n\t\tint[][] direction = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 } };\n\t\tfor (int i = 0; i < rows; i++)\n\t\t\tfor (int j = 0; j < columns; j++) {\n\t\t\t\tif ((i == 0 || i == rows - 1 || j == 0 || j == columns - 1) && board[i][j] == 'O') {\n\t\t\t\t\tQueue<Point> queue = new LinkedList<>();\n\t\t\t\t\tboard[i][j] = 'B';\n\t\t\t\t\tqueue.offer(new Point(i, j));\n\t\t\t\t\twhile (!queue.isEmpty()) {\n\t\t\t\t\t\tPoint point = queue.poll();\n\t\t\t\t\t\tfor (int k = 0; k < 4; k++) {\n\t\t\t\t\t\t\tint x = direction[k][0] + point.x;\n\t\t\t\t\t\t\tint y = direction[k][1] + point.y;\n\t\t\t\t\t\t\tif (x >= 0 && x < rows && y >= 0 && y < columns && board[x][y] == 'O') {\n\t\t\t\t\t\t\t\tboard[x][y] = 'B';\n\t\t\t\t\t\t\t\tqueue.offer(new Point(x, y));\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\tfor (int i = 0; i < rows; i++)\n\t\t\tfor (int j = 0; j < columns; j++) {\n\t\t\t\tif (board[i][j] == 'B')\n\t\t\t\t\tboard[i][j] = 'O';\n\t\t\t\telse if (board[i][j] == 'O')\n\t\t\t\t\tboard[i][j] = 'X';\n\t\t\t}\n\n\t} | 54 | 2 | [] | 10 |
surrounded-regions | [C++] DFS Easy and clean solution [T: 90% | M: 80%] | c-dfs-easy-and-clean-solution-t-90-m-80-n864e | Please like the post if you found it helpful. And please don\'t downvote. It really demotivates and cancels the purpose of sharing knowledge in the community\n\ | harshit0311 | NORMAL | 2020-06-17T11:28:18.749985+00:00 | 2020-06-17T11:28:18.750015+00:00 | 3,878 | false | ***Please like the post if you found it helpful. And please don\'t downvote. It really demotivates and cancels the purpose of sharing knowledge in the community***\n\nThe idea is to iterate through the edges of the array and check if there is any zero. And if there is, we will check for zeroes in the neighbour. And keep doing this. These zeroes won\'t get there values changed. For simplicity, I changed their values to \'1\'. And now, all the elements having values other than \'1\' will get their values changed to \'X\'.\n\n```\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n if(board.size()==0||board[0].size()==0)return;\n for(int i=0;i<board[0].size();i++){\n if(board[0][i]==\'O\'){dfs(board,0,i);}\n if(board[board.size()-1][i]==\'O\'){dfs(board,board.size()-1,i);}\n }\n for(int i=1;i<board.size()-1;i++){\n if(board[i][0]==\'O\')dfs(board,i,0);\n if(board[i][board[0].size()-1]==\'O\'){dfs(board,i,board[0].size()-1);}\n }\n for(int i=0;i<board.size();i++){\n for(int j=0;j<board[0].size();j++){\n if(board[i][j]!=\'1\')board[i][j]=\'X\';\n if(board[i][j]==\'1\')board[i][j]=\'O\';\n }\n }\n }\n void dfs(vector<vector<char>>& board, int i, int j){\n if(i<0||i>=board.size()||j<0||j>=board[0].size())return;\n if(board[i][j]!=\'O\')return;\n board[i][j]=\'1\';\n dfs(board,i+1,j);\n dfs(board,i,j+1);\n dfs(board,i-1,j);\n dfs(board,i,j-1);\n return;\n }\n};\n``` | 47 | 3 | ['Depth-First Search', 'C', 'C++'] | 0 |
surrounded-regions | Java Very Easy Solution || Hard to forgot this | java-very-easy-solution-hard-to-forgot-t-57xf | Hey Programmers, i try to solve this question using DFS approach.\n\n What I did is, firstly we traverse it\'s top n bottom column\n Then it\'s left n right row | hi-malik | NORMAL | 2021-11-01T05:59:02.909632+00:00 | 2021-11-01T05:59:02.909684+00:00 | 3,050 | false | Hey Programmers, i try to solve this question using DFS approach.\n\n* What I did is, firstly we traverse it\'s top n bottom column\n* Then it\'s left n right row\n* And finally traverse its all then node\nHere\'s how what i mean is :\n\n\n```\nclass Solution {\n public void solve(char[][] board) {\n // Base condition\n if(board.length == 0) return;\n // 1st Loop : Traversing over top column & bottom column, to find any \'O\' present by the boundary\n for(int i = 0; i < board[0].length; i++){\n if(board[0][i] == \'O\'){\n DFS(board, 0, i);\n }\n if(board[board.length - 1][i] == \'O\'){\n DFS(board, board.length - 1, i);\n }\n }\n // 2nd Loop : Traversing over left row & right row, to find any \'O\' present by the boundary\n for(int i = 0; i < board.length; i++){\n if(board[i][0] == \'O\'){\n DFS(board, i, 0);\n }\n if(board[i][board[0].length - 1] == \'O\'){\n DFS(board, i, board[0].length - 1);\n }\n }\n // 3rd Loop : Now in this we will traverse on each n every node & check if they are \'O\' convert into \'X\', if they are \'@\' convert into \'O\'\n for(int i = 0; i < board.length; i++){\n for(int j = 0; j < board[0].length; j++){\n if(board[i][j] == \'O\'){\n board[i][j] = \'X\';\n }\n else if(board[i][j] == \'@\'){\n board[i][j] = \'O\';\n }\n }\n }\n return;\n }\n // This calls helps in convert the \'O\' node present near by the boundary convert them into \'@\'\n public void DFS(char[][] board, int i, int j){\n if(i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != \'O\'){\n return;\n }\n board[i][j] = \'@\';\n DFS(board, i + 1, j);\n DFS(board, i - 1, j);\n DFS(board, i, j + 1);\n DFS(board, i, j - 1);\n }\n}\n```\n* Time Complexity :- BigO(N * M), where N is height and M is width of the board\n* Space Complexity :- BigO(1), as we are not using any kind of extra space\n\nI hope this will help\'s you to understand. Thanks (: | 45 | 0 | ['Java'] | 7 |
surrounded-regions | [Python] Very simple idea; DFS | python-very-simple-idea-dfs-by-jianpingb-5519 | The idea is simple:\n- Start from the boundary, and use DFS (or BFS) to flip the \'O\'s that are connected to the edge to a third symbol (e.g., "Z")\n- Scan the | jianpingbadao | NORMAL | 2021-11-01T01:31:22.214229+00:00 | 2021-11-01T01:31:54.018997+00:00 | 5,319 | false | The idea is simple:\n- Start from the boundary, and use DFS (or BFS) to flip the \'O\'s that are connected to the edge to a third symbol (e.g., "Z")\n- Scan the matrix again to flip the remaining \'O\' to \'X\', and the third symbol back to \'O\'\n\n```python\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n rows = len(board)\n cols = len(board[0])\n \n def dfs(row, col):\n board[row][col] = "Z"\n for dr, dc in (-1, 0), (0, 1), (1, 0), (0, -1):\n nr, nc = row + dr, col + dc\n if nr < 0 or nr >= rows or nc < 0 or nc >= cols or board[nr][nc] != \'O\':\n continue\n dfs(nr, nc)\n\n def flip():\n for row in range(rows):\n for col in range(cols):\n if board[row][col] == "Z":\n board[row][col] = "O"\n elif board[row][col] == "O":\n board[row][col] = "X"\n\n for row in [0, rows - 1]:\n for col in range(cols):\n if board[row][col] == \'O\':\n dfs(row, col)\n\n for col in [0, cols - 1]:\n for row in range(1, rows - 1):\n if board[row][col] == \'O\':\n dfs(row, col)\n\n flip()\n``` | 39 | 2 | ['Depth-First Search', 'Python'] | 7 |
surrounded-regions | My Java O(n^2) accepted solution | my-java-on2-accepted-solution-by-frances-b0te | The idea is pretty simple: a 'O' marked cell cannot be captured whether:\n\n1. It is in contact with the border of the board or\n2. It is adjacent to an unflipp | francesco | NORMAL | 2014-12-29T16:57:54+00:00 | 2018-10-16T16:42:15.589427+00:00 | 9,778 | false | The idea is pretty simple: a 'O' marked cell cannot be captured whether:\n\n1. It is in contact with the border of the board or\n2. It is adjacent to an unflippable cell.\n\nSo the algorithm is straightforward:\n\n 1. Go around the border of the board\n 2. When a 'O' cell is found mark it with 'U' and perform a DFS on its adjacent cells looking for other 'O' marked cells.\n 3. When the entire border is processed scan again the board\n- If a cell is marked as 'O' it wasn't connected to unflippable cell. Hence capture it with 'X'\n- If a cell is marked as 'X' nothing must be done.\n- If a cell is marked as 'U' mark it as 'O' because it was an original 'O' marked cell which satisfied one of the above conditions.\n\nOn a technical side regarding the code:\n\n- In the problem statement it's not specified that the board is rectangular. So different checks must performed when scanning the border.\n- Since a pure recursive search causes stack overflow it's necessary to make the DFS iterative using a stack to simulate recursion.\n\n\npublic class Solution {\n\n static class Pair {\n public int first;\n public int second;\n public Pair(int f, int s) {\n first = f;\n second = s;\n }\n }\n\n public void solve(char[][] board) {\n if(board == null || board.length == 0) {\n return ;\n }\n for(int i = 0; i < board[0].length; ++i) {\n if(board[0][i] == 'O') {\n markUnflippable(board,0,i);\n }\n }\n for(int i = 0; i < board[board.length-1].length; ++i) {\n if(board[board.length-1][i] == 'O') {\n markUnflippable(board,board.length-1,i);\n }\n }\n for(int i = 0 ; i < board.length; ++i) {\n if(board[i][0] == 'O') {\n markUnflippable(board,i,0);\n }\n }\n for(int i =0; i < board.length; ++i) {\n if(board[i][board[i].length-1] == 'O') {\n markUnflippable(board,i,board[i].length-1);\n }\n }\n \n // modify the board\n for(int i = 0; i < board.length; ++i) {\n for(int j = 0; j < board[i].length; ++j) {\n if(board[i][j] == 'O') {\n board[i][j] = 'X';\n } else if(board[i][j] == 'U') {\n board[i][j] = 'O';\n }\n }\n }\n }\n \n public void markUnflippable(char[][] board, int r, int c) {\n int[] dirX = {-1,0,1,0};\n int[] dirY = {0,1,0,-1};\n ArrayDeque<Pair> stack = new ArrayDeque<>();\n stack.push(new Pair(r,c));\n while(!stack.isEmpty()) {\n Pair p = stack.pop();\n board[p.first][p.second] = 'U';\n for(int i = 0; i < dirX.length; ++i) {\n if(p.first + dirX[i] >= 0 && p.first + dirX[i] < board.length && p.second + dirY[i] >= 0 && p.second +dirY[i] < board[p.first + dirX[i]].length && board[p.first+dirX[i]][p.second+dirY[i]] == 'O') {\n stack.push(new Pair(p.first+dirX[i],p.second+dirY[i]));\n }\n }\n }\n }\n} | 39 | 0 | [] | 6 |
surrounded-regions | Java dfs solution | java-dfs-solution-by-lencha-7uba | public void solve(char[][] board) {\n if(board == null || board.length == 0) return;\n for(int i = 0; i < board.length; i++){\n for(int | lencha | NORMAL | 2016-05-14T09:22:36+00:00 | 2016-05-14T09:22:36+00:00 | 5,275 | false | public void solve(char[][] board) {\n if(board == null || board.length == 0) return;\n for(int i = 0; i < board.length; i++){\n for(int j = 0; j < board[0].length; j++){\n if(i == 0 || i == board.length-1 || j == 0 || j == board[0].length-1){\n if(board[i][j] == 'O') dfs(i,j,board);\n }\n }\n }\n for(int i = 0; i < board.length; i++){\n for(int j = 0; j < board[0].length; j++){\n if(board[i][j] == '*') board[i][j] ='O';\n else board[i][j] = 'X';\n }\n }\n return;\n }\n private void dfs(int i,int j,char[][] board){\n if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) return;\n if(board[i][j] == 'X' || board[i][j] == '*') return;\n board[i][j] = '*';\n if(i+1 < board.length)\n dfs(i+1,j,board);\n if(i-1 > 0)\n dfs(i-1,j,board);\n if(j+1 < board[0].length)\n dfs(i,j+1,board);\n if(j-1 > 0)\n dfs(i,j-1,board);\n } | 36 | 2 | ['Depth-First Search'] | 6 |
surrounded-regions | python3 BFS and DFS | python3-bfs-and-dfs-by-nightybear-y6uf | below is my python3 BFS and DFS solutions\n\n\nBFS:\npython\nclass Solution:\n \'\'\'\n Time complexity : O(MXN)\n Space complexity : O(MXN) in worse c | nightybear | NORMAL | 2020-01-09T06:45:42.806154+00:00 | 2021-08-01T16:05:23.243129+00:00 | 4,295 | false | below is my python3 BFS and DFS solutions\n\n\nBFS:\n```python\nclass Solution:\n \'\'\'\n Time complexity : O(MXN)\n Space complexity : O(MXN) in worse case\n\n First, check the four border of the matrix. If there is a element is\n \'O\', alter it and all its neighbor \'O\' elements to \'N\'.\n\n Then ,alter all the \'O\' to \'X\'\n\n At last,alter all the \'N\' to \'O\'\n\n example: \n\n X X X X X X X X X X X X\n X X O X -> X X O X -> X X X X\n X O X X X N X X X O X X\n X O X X X N X X X O X X\n\n \'\'\'\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n if not board or not board[0]:\n return\n R, C = len(board), len(board[0])\n if R <= 2 or C <= 2:\n return\n \n # queue for bfs\n q = deque()\n \n # start from the boarder and replace all O to N\n # put all the boarder value into queue.\n for r in range(R):\n q.append((r, 0))\n q.append((r, C-1))\n\n for c in range(C):\n q.append((0, c))\n q.append((R-1, c))\n \n while q:\n r, c = q.popleft()\n if 0<=r<R and 0<=c<C and board[r][c] == "O":\n # modify the value from O to N\n board[r][c] = "N"\n # append the surrouding cells to queue.\n q.append((r, c+1))\n q.append((r, c-1))\n q.append((r-1, c))\n q.append((r+1, c))\n \n # replace all the O to X, then replace all the N to O\n for r in range(R):\n for c in range(C):\n if board[r][c] == "O":\n board[r][c] = "X"\n if board[r][c] == "N":\n board[r][c] = "O"\n```\n\nDFS:\n\n```python\nclass Solution1:\n\n \'\'\'\n recursion, dfs\n \'\'\'\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n if not board or not board[0]:\n return\n R, C = len(board), len(board[0])\n if R <= 2 or C <= 2:\n return\n \n # start from the boarder and replace all O to N\n # put all the boarder value into queue.\n for r in range(R):\n self.dfs(board, r, 0, R, C)\n self.dfs(board, r, C-1, R, C)\n\n for c in range(C):\n self.dfs(board, 0, c, R, C)\n self.dfs(board, R-1, c, R, C)\n\n # replace all the O to X, then replace all the N to O\n for r in range(R):\n for c in range(C):\n if board[r][c] == "O":\n board[r][c] = "X"\n if board[r][c] == "N":\n board[r][c] = "O"\n \n \n def dfs(self, board, r, c, R, C):\n if 0<=r<R and 0<=c<C and board[r][c] == "O":\n board[r][c] = "N"\n self.dfs(board, r, c+1, R, C)\n self.dfs(board, r, c-1, R, C) \n self.dfs(board, r-1, c, R, C) \n self.dfs(board, r+1, c, R, C) \n``` | 32 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Python', 'Python3'] | 2 |
surrounded-regions | C++ Simple and Easy-to-Understand Clean DFS Solution, Explained | c-simple-and-easy-to-understand-clean-df-mwsa | Idea:\nFirst, we want to save the Os that are not 4-directionally surrounded by Xs. So we go through all edges, DFS each O and change all its connected Os to !. | yehudisk | NORMAL | 2021-11-01T08:42:39.291888+00:00 | 2021-11-01T10:28:27.829324+00:00 | 1,614 | false | **Idea:**\nFirst, we want to save the `O`s that are not 4-directionally surrounded by `X`s. So we go through all edges, DFS each `O` and change all its connected `O`s to `!`.\nAll the remaining `O`s are 4-directionally surrounded by `X`s, so we change all of them to `X`.\nNow, we change back all `!`s to `O`s.\n\n```\nclass Solution {\npublic:\n void DFS(vector<vector<char>>& board, int x, int y, char c) {\n if (x < 0 || x >= board.size() || y < 0 || y >= board[0].size() || board[x][y] != \'O\') return;\n \n board[x][y] = c;\n \n DFS(board, x + 1, y, c);\n DFS(board, x - 1, y, c);\n DFS(board, x, y + 1, c);\n DFS(board, x, y - 1, c);\n }\n \n void solve(vector<vector<char>>& board) {\n int n = board.size(), m = board[0].size();\n \n // Change the \'O\'s connected to border to \'!\'\n for (int i = 0; i < n; i++) {\n if (board[i][0] == \'O\') DFS(board, i, 0, \'!\');\n if (board[i][m-1] == \'O\') DFS(board, i, m-1, \'!\');\n }\n \n for (int i = 0; i < m; i++) {\n if (board[0][i] == \'O\') DFS(board, 0, i, \'!\');\n if (board[n-1][i] == \'O\') DFS(board, n-1, i, \'!\');\n }\n \n // Change all remaining \'O\'s to \'x\' and \'!\' back to \'O\'\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (i && j && i < n - 1 && j < m - 1 && board[i][j] == \'O\') board[i][j] = \'X\';\n if (board[i][j] == \'!\') board[i][j] = \'O\';\n }\n }\n }\n};\n```\n**Like it? please upvote!** | 31 | 1 | ['C'] | 6 |
surrounded-regions | Simplest C++ solution possible (with comments) [Beats 99.5% solution] | simplest-c-solution-possible-with-commen-lir3 | My BFS Solution\n\nclass Solution {\npublic:\n\t// To check whether the indices are present in the matrix. [Like (-1,0) is not present]\n bool isSafe(int i, | not_a_cp_coder | NORMAL | 2020-08-13T13:24:04.913559+00:00 | 2020-08-13T13:24:04.913601+00:00 | 3,152 | false | ## **My BFS Solution**\n```\nclass Solution {\npublic:\n\t// To check whether the indices are present in the matrix. [Like (-1,0) is not present]\n bool isSafe(int i, int j, int m, int n){\n return (i>=0 && i<m && j>=0 && j<n);\n }\n\t// Checks whether the indices are present at the border of the matrix.\n bool isBorder(int i, int j, int m, int n){\n return (i==0 || i==m-1 || j==0 || j==n-1);\n }\n void solve(vector<vector<char>>& board) {\n if(board.size()==0)\n return ;\n\t\t// m is the number of rows.\n int m = board.size();\n\t\t// n is the number of columns\n int n = board[0].size();\n\t\t// Taking queue for BFS.\n queue<pair<int,int>> q;\n\t\t// dir contains the directions in which the checking is to be done.\n vector<pair<int, int>> dir = {{1,0}, {-1,0}, {0, 1}, {0, -1}};\n\t\t// Finding the border elements as \'O\' and converting it into something else.\n\t\t// This is done due to the reason because, they are not to be flipped in the final matrix.\n\t\t// We could check only the border rows and columns but I have instead traversed the whole matrix. You can surely save up some time here.\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(board[i][j]==\'O\' && isBorder(i,j,m,n)){\n\t\t\t\t\t// Converting the \'O\' into \'.\' so, that they can be later changed to \'O\'.\n board[i][j] = \'.\';\n q.push(make_pair(i,j)); \n }\n }\n }\n\t\t// Starting the BFS.\n while(!q.empty()){\n pair<int, int> temp = q.front();\n q.pop();\n\t\t\t// Checking all the directions.\n for(int i=0;i<dir.size();i++){\n int x = temp.first + dir[i].first;\n int y = temp.second + dir[i].second;\n\t\t\t\t// So, the (x,y) must be possible within the matrix and it must not be on the border.\n if(isSafe(x,y,m,n) && !isBorder(x,y, m,n) && board[x][y]==\'O\'){\n board[x][y]= \'.\';\n q.push(make_pair(x,y));\n }\n }\n }\n for(int i=0;i<m;i++)\n for(int j=0;j<n;j++)\n\t\t\t // Just convert the remaining \'O\' into \'X\' as they are not connected to any border \'O\'.\n if(board[i][j]==\'O\')\n board[i][j] = \'X\';\n // Now, convert the \'.\' into \'O\' as they were connected to some border \'O\'.\n\t\t\t\telse if(board[i][j]==\'.\')\n board[i][j] = \'O\';\n }\n};\n```\nIf you have any doubts, do let me know in the **comment** section below.\nIf you like this solution, do **UPVOTE**.\nHappy Coding :) | 30 | 0 | ['Depth-First Search', 'Breadth-First Search', 'C', 'C++'] | 4 |
surrounded-regions | Concise 12ms C++ DFS solution | concise-12ms-c-dfs-solution-by-kenigma-8wit | First check all surrounding rows columns find those 'O' and their neighbors that are also 'O', make them to some other character like '1'. then traverse the who | kenigma | NORMAL | 2016-05-11T21:45:44+00:00 | 2016-05-11T21:45:44+00:00 | 5,303 | false | First check all surrounding rows columns find those 'O' and their neighbors that are also 'O', make them to some other character like '1'. then traverse the whole board, now the 'O' left need to be turned to 'X', and those marked '1' turned back to 'O'\n\nlike this:\n\n X X X X X X X X X X X X\n X O O X ---> X O O X ---> X X X X\n X X O X X X O X X X X X\n X O X X X 1 X X X O X X\n\ncode:\n\n class Solution {\n public:\n void solve(vector<vector<char>>& board) {\n if (board.empty()) return;\n int row = board.size(), col = board[0].size();\n for (int i = 0; i < row; ++i) {\n check(board, i, 0); // first column\n check(board, i, col - 1); // last column\n }\n for (int j = 1; j < col - 1; ++j) {\n check(board, 0, j); // first row\n check(board, row - 1, j); // last row\n }\n for (int i = 0; i < row; ++i)\n for (int j = 0; j < col; ++j)\n if (board[i][j] == 'O') board[i][j] = 'X';\n else if (board[i][j] == '1') board[i][j] = 'O';\n }\n \n void check(vector<vector<char>>& board, int i, int j) {\n if (board[i][j] == 'O') {\n board[i][j] = '1';\n if (i > 1) check(board, i - 1, j);\n if (j > 1) check(board, i, j - 1);\n if (i + 1 < board.size()) check(board, i + 1, j);\n if (j + 1 < board[0].size()) check(board, i, j + 1);\n }\n }\n }; | 29 | 0 | ['C++'] | 9 |
surrounded-regions | [Java] TC: O(M*N) | SC: O(min(M,N) | Linear Space BFS & simple DFS solutions | java-tc-omn-sc-ominmn-linear-space-bfs-s-z2ne | BFS - Iterative Solution (This is a space optimized solution as compared to DFS solution)\n\njava\n/**\n * BFS - Iterative Solution (This is a space optimized s | NarutoBaryonMode | NORMAL | 2021-11-01T10:21:27.442597+00:00 | 2021-11-02T22:41:33.434281+00:00 | 1,301 | false | **BFS - Iterative Solution (This is a space optimized solution as compared to DFS solution)**\n\n```java\n/**\n * BFS - Iterative Solution (This is a space optimized solution as compared to DFS solution)\n *\n * Start from edges and then mark all \'O\' cells that connect to \'O\' cells at edge.\n *\n * Time Complexity: O(M * N)\n * Each cell is visited twice. To set \'#\' and then to set them back to \'O\'.\n *\n * Space Complexity: O(min(M, N)). Space taken by the queue.\n * In worst case, it will be equal to the diagonal of the board which is min(M, N)\n *\n * M = Number of rows. N = Number of columns.\n */\nclass Solution {\n private static final int[][] DIRS = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };\n private static final char NON_CAPTURED = \'#\';\n\n public void solve(char[][] board) {\n if (board == null) {\n throw new IllegalArgumentException("Input board is null");\n }\n if (board.length == 0 || board[0].length == 0) {\n return;\n }\n int m = board.length;\n int n = board[0].length;\n\n for (int i = 0; i < m; i++) {\n if (board[i][0] == \'O\') {\n bfsHelper(board, i, 0);\n }\n\n if (board[i][n - 1] == \'O\') {\n bfsHelper(board, i, n - 1);\n }\n }\n for (int j = 1; j < n - 1; j++) {\n if (board[0][j] == \'O\') {\n bfsHelper(board, 0, j);\n }\n if (board[m - 1][j] == \'O\') {\n bfsHelper(board, m - 1, j);\n }\n }\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n board[i][j] = (board[i][j] == NON_CAPTURED) ? \'O\' : \'X\';\n }\n }\n }\n\n private void bfsHelper(char[][] board, int i, int j) {\n Queue<int[]> queue = new LinkedList<>();\n queue.offer(new int[] { i, j });\n board[i][j] = NON_CAPTURED;\n\n while (!queue.isEmpty()) {\n int[] cur = queue.poll();\n for (int[] d : DIRS) {\n int x = cur[0] + d[0];\n int y = cur[1] + d[1];\n if (x < 0 || y < 0 || x >= board.length || y >= board[0].length || board[x][y] != \'O\') {\n continue;\n }\n queue.offer(new int[] { x, y });\n board[x][y] = NON_CAPTURED;\n }\n\n }\n }\n}\n```\n\n---\n**DFS - Recursive Solution**\n\n```java\n/**\n * DFS - Recursive Solution\n *\n * Start from edges and then mark all \'O\' cells that connect to \'O\' cells at edge.\n *\n * Time Complexity: O(M * N)\n * Each cell is visited twice. To set \'#\' and then to set them back to \'O\'.\n *\n * Space Complexity: O(M * N). Recursion Depth.\n * In worst case if all cells are \'O\' then it will take O(M*N) space.\n *\n * M = Number of rows. N = Number of columns.\n */\nclass Solution {\n private static final int[][] DIRS = { { -1, 0 }, { 0, -1 }, { 0, 1 }, { 1, 0 } };\n private static final char NON_CAPTURED = \'#\';\n\n public void solve(char[][] board) {\n if (board == null) {\n throw new IllegalArgumentException("Input board is null");\n }\n if (board.length == 0 || board[0].length == 0) {\n return;\n }\n int m = board.length;\n int n = board[0].length;\n\n for (int i = 0; i < m; i++) {\n if (board[i][0] == \'O\') {\n dfsHelper(board, i, 0);\n }\n\n if (board[i][n - 1] == \'O\') {\n dfsHelper(board, i, n - 1);\n }\n }\n for (int j = 1; j < n - 1; j++) {\n if (board[0][j] == \'O\') {\n dfsHelper(board, 0, j);\n }\n if (board[m - 1][j] == \'O\') {\n dfsHelper(board, m - 1, j);\n }\n }\n\n for (int i = 0; i < m; i++) {\n for (int j = 0; j < n; j++) {\n board[i][j] = (board[i][j] == NON_CAPTURED) ? \'O\' : \'X\';\n }\n }\n }\n\n private void dfsHelper(char[][] board, int x, int y) {\n if (x < 0 || y < 0 || x >= board.length || y >= board[0].length || board[x][y] != \'O\') {\n return;\n }\n board[x][y] = NON_CAPTURED;\n for (int[] d : DIRS) {\n dfsHelper(board, x + d[0], y + d[1]);\n }\n }\n}\n``` | 27 | 12 | ['Depth-First Search', 'Breadth-First Search', 'Java'] | 1 |
surrounded-regions | Java DFS with Explanations | java-dfs-with-explanations-by-gracemeng-tdmd | Click to see Union-Find Solution\n\nLogical Thinking\nWe aim to set all O\'s which doesn\'t locate at borders or connect to O at borders to X.\nWe mark all O\' | gracemeng | NORMAL | 2018-08-26T00:27:16.186549+00:00 | 2020-04-13T16:21:37.389517+00:00 | 1,851 | false | [Click to see Union-Find Solution](https://leetcode.com/problems/surrounded-regions/discuss/167165/Java-Union-Find-with-Explanations)\n\n**Logical Thinking**\nWe aim to set all O\'s which doesn\'t locate at borders or connect to O at borders to X.\nWe mark all O\'s at borders and apply DFS at each O at boarders to mark all O\'s connected to it. The un-marked O\'s ought to be set X.\n\n**Trick**\nWe search for invalid candidates (and exclude them) rather than search for valid candidates.\n\n**Code**\n```\n private static final int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};\n\n public void solve(char[][] board) {\n if (board.length == 0)\n return;\n \n int rows = board.length, cols = board[0].length;\n \n \n for (int i = 0; i < rows; i++) {\n if (board[i][0] == \'O\')\n markNotSurrounded(i, 0, board);\n if (board[i][cols - 1] == \'O\')\n markNotSurrounded(i, cols - 1, board);\n }\n \n for (int j = 0; j < cols; j++) {\n if (board[0][j] == \'O\')\n markNotSurrounded(0, j, board);\n if (board[rows - 1][j] == \'O\')\n markNotSurrounded(rows - 1, j, board);\n }\n \n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n \n if (board[i][j] == \'*\') // Restores \'*\' to \'O\'\n board[i][j] = \'O\';\n else if (board[i][j] == \'O\') // Captures \'O\' surrounded by \'X\'\n board[i][j] = \'X\';\n }\n }\n }\n \n // Mark \'O\' not surrounded by \'X\' as \'*\'\n private void markNotSurrounded(int x, int y, char[][] board) { \n board[x][y] = \'*\';\n for (int[] dir : directions) {\n int nx = x + dir[0], ny = y + dir[1];\n if (nx >= 0 && nx < board.length\n && ny >= 0 && ny < board[0].length\n && board[nx][ny] == \'O\') {\n markNotSurrounded(nx, ny, board);\n }\n }\n }\n```\n | 27 | 0 | [] | 3 |
surrounded-regions | JavaScript Runtime: faster than 88.14% Memory Usage: less than 100.00% | javascript-runtime-faster-than-8814-memo-0zcu | \nvar solve = function(board) {\n if(board.length ==0) return null \n \n for(var i=0;i<board.length;i++){\n for(var j=0;j<board[0].length;j++){\ | miguelto | NORMAL | 2019-09-24T01:17:10.196271+00:00 | 2019-09-24T01:17:10.196325+00:00 | 3,125 | false | ```\nvar solve = function(board) {\n if(board.length ==0) return null \n \n for(var i=0;i<board.length;i++){\n for(var j=0;j<board[0].length;j++){\n if(board[i][j] == \'O\' && (i==0 || i==board.length-1 || j==0 || j==board[0].length-1)){\n dfs(board,i,j)\n }\n }\n }\n \n for(var i=0;i<board.length;i++){\n for(var j=0;j<board[0].length;j++){\n if(board[i][j]==\'W\'){\n board[i][j]=\'O\'\n }\n else {\n board[i][j]=\'X\'\n }\n }\n }\n \n return board\n};\n\n function dfs(board,i,j){\n if(i<0 || j<0 || i>=board.length || j >=board[0].length || board[i][j]==\'X\' || board[i][j]==\'W\'){\n return \n }\n board[i][j]=\'W\';\n dfs(board,i+1,j)\n dfs(board,i-1,j)\n dfs(board,i,j+1)\n dfs(board,i,j-1)\n return \n }\n ``` | 24 | 0 | ['Depth-First Search', 'JavaScript'] | 3 |
surrounded-regions | DFS | BFS | Easy to understand C++ | Clean code😊 | dfs-bfs-easy-to-understand-c-clean-code-y2jly | Intuition\nStore all the boundary elements which are \'O\' in a data structure like queue or stack mark all the O\'s which are connected to these O\'s and conve | Comrade-in-code | NORMAL | 2023-03-20T05:46:26.888870+00:00 | 2023-03-20T05:47:05.184175+00:00 | 3,807 | false | # Intuition\nStore all the boundary elements which are \'O\' in a data structure like queue or stack mark all the O\'s which are connected to these O\'s and convert all other O\'s to X.\n\n# Approach\nWe can use DFS as well as BFS. I am using BFS int this solution:\n1. First store position of all the O\'s that are present at the boundary in the queue data structue.\n2. Start BFS traversal and mark all the O\'s that are connected to these boundary element.\n3. After completing the whole traversal, check which O\'s are unmarked, that means they are not connected to the boundary element that\'s why they are unmarked.\n4. Now, replace all the umarked O\'s to X.\n\n# Complexity\n- Time complexity: O(m*n) : m: rows, n: columns\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(m*n) : m: rows, n: columns\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n void solve(vector<vector<char>>& b) {\n int m = b.size(), n = b[0].size();\n vector<vector<int>> vis(m, vector<int> (n));\n queue<pair<int, int>> q;\n\n // First store position of all the O\'s that are present at the boundary in the queue data structue\n for(int i=0; i<m; i++)\n for(int j=0; j<n; j++)\n if(i==0 || j==0 || i==m-1 || j==n-1){\n if(b[i][j]==\'O\'){\n q.push({i, j});\n vis[i][j]=1;\n } \n }\n\n // Start BFS traversal and mark all the O\'s that are connected to these boundary element\n while(!q.empty()){\n auto [r, c] = q.front();\n vis[r][c]=1;\n q.pop();\n for(int x=-1; x<=1; x++){\n for(int y=-1; y<=1; y++){\n if(x&&y || (x==0 && y==0)) continue;\n int nrow = r+x, ncol = c+y;\n if(nrow<0 || ncol<0 || nrow>=m || ncol>=n) continue;\n if(vis[nrow][ncol] || b[nrow][ncol]==\'X\') continue;\n vis[nrow][ncol] = 1;\n q.push({nrow, ncol});\n }\n }\n }\n // check which O\'s are unmarked, that means they are not connected to the boundary element that\'s why they are unmarked\n for(int i=0; i<m; i++){\n for(int j=0; j<n; j++){\n if(vis[i][j]==0 && b[i][j]==\'O\') b[i][j] = \'X\';\n }\n }\n\n }\n};\n\n// Please upvote if this solution helped you somehow!\n\n\n``` | 22 | 0 | ['Array', 'Depth-First Search', 'Breadth-First Search', 'Graph', 'C++'] | 1 |
surrounded-regions | Share my clean Java Code | share-my-clean-java-code-by-rainforestin-0frk | public class Solution {\n public void solve(char[][] board) {\n int rown = board.length;\n if (rown==0) return;\n int co | rainforestin | NORMAL | 2015-02-27T18:57:34+00:00 | 2015-02-27T18:57:34+00:00 | 5,853 | false | public class Solution {\n public void solve(char[][] board) {\n int rown = board.length;\n if (rown==0) return;\n int coln = board[0].length;\n for (int row=0; row<rown; ++row) {\n for (int col=0; col<coln; ++col) {\n if (row==0 || row==rown-1 || col==0 || col==coln-1) {\n if (board[row][col]=='O') {\n Queue<Integer> q = new LinkedList<>();\n board[row][col]='1';\n q.add(row*coln+col);\n while (!q.isEmpty()) {\n int cur = q.poll();\n int x = cur/coln;\n int y = cur%coln;\n if (y+1<coln && board[x][y+1]=='O') {\n q.add(cur+1);\n board[x][y+1] = '1';\n }\n if (x+1<rown && board[x+1][y]=='O') {\n q.add(cur+coln);\n board[x+1][y] = '1';\n }\n if (y-1>=0 && board[x][y-1]=='O') {\n q.add(cur-1);\n board[x][y-1] = '1';\n }\n if (x-1>=0 && board[x-1][y]=='O') {\n q.add(cur-coln);\n board[x-1][y] = '1';\n }\n }\n }\n }\n }\n }\n for (int i=0; i<rown; ++i) {\n for (int j=0; j<coln; ++j) {\n if (board[i][j]=='O') {\n board[i][j]='X';\n } else if (board[i][j]=='1') {\n board[i][j]='O';\n }\n }\n }\n }\n } | 22 | 1 | ['Breadth-First Search', 'Queue'] | 2 |
surrounded-regions | [C++] DFS, BFS, and Union Find Solutions. | c-dfs-bfs-and-union-find-solutions-by-ar-ejmi | For DFS and BFS, we have the same idea in solving this problem.\n1. We first go through boarders to check if there is any \'O\'. \n2. If found \'O\' on boarders | arthur960304 | NORMAL | 2019-08-20T10:06:43.149173+00:00 | 2019-08-20T10:09:02.619501+00:00 | 1,588 | false | For **DFS** and **BFS**, we have the same idea in solving this problem.\n1. We first go through boarders to check if there is any `\'O\'`. \n2. If found `\'O\'` on boarders, perform DFS or BFS and make all connected `\'O\'` becomes `\'D\'`.\n3. After that, we go through whole board and mark remaining `\'O\'` as `\'X\'`, and `\'D\'` as `\'O\'`.\n\nFor **Union Find**, we have a different idea.\n1. We go through whole board, if found `\'O\'` and if it is on boarder, connect to `dummy` node.\n2. Otherwise, connect to surrounded `\'O\'`.\n3. Finally, goes through whole board again and check if `\'O\'` is connected to `dummy` node. If yes, then it means this `\'O\'` is not captured.\n\n## **DFS**\n```cpp\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n if(!board.size()) return;\n \n int rows = board.size();\n int cols = board[0].size();\n \n // Go through boarder to find \'O\'\n for(int i=0; i<rows; ++i) {\n DFS(board, i, 0, rows, cols);\n if(cols>1) DFS(board, i, cols-1, rows, cols);\n }\n for(int i=1; i<cols-1; ++i) {\n DFS(board, 0, i, rows, cols);\n if(rows>1) DFS(board, rows-1, i, rows, cols);\n }\n \n // Go through whole board and mark \'O\' as \'X\', \'D\' as \'O\'\n for(int i=0; i<rows; ++i) {\n for(int j=0; j<cols; ++j) {\n if(board[i][j]==\'O\') board[i][j] = \'X\';\n else if(board[i][j]==\'D\') board[i][j] = \'O\';\n }\n }\n }\n \n void DFS(vector<vector<char>>& board, int i, int j, int rows, int cols) {\n if(i<0 || i>=rows || j<0 || j>=cols || board[i][j]==\'X\' || board[i][j]==\'D\') return;\n \n // If current is \'O\', mark as \'D\' and preform DFS\n if(board[i][j]==\'O\') board[i][j] = \'D\';\n \n DFS(board, i-1, j, rows, cols);\n DFS(board, i+1, j, rows, cols);\n DFS(board, i, j-1, rows, cols);\n DFS(board, i, j+1, rows, cols);\n }\n};\n```\n\n## **BFS**\n```cpp\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n if(!board.size()) return;\n \n int rows = board.size();\n int cols = board[0].size();\n \n // Go through boarder to find \'O\'\n for(int i=0; i<rows; ++i) {\n BFS(board, i, 0, rows, cols);\n if(cols>1) BFS(board, i, cols-1, rows, cols);\n }\n for(int i=1; i<cols-1; ++i) {\n BFS(board, 0, i, rows, cols);\n if(rows>1) BFS(board, rows-1, i, rows, cols);\n }\n \n // Go through whole board and mark \'O\' as \'X\', \'D\' as \'O\'\n for(int i=0; i<rows; ++i) {\n for(int j=0; j<cols; ++j) {\n if(board[i][j]==\'O\') board[i][j] = \'X\';\n else if(board[i][j]==\'D\') board[i][j] = \'O\';\n }\n }\n }\n \n void BFS(vector<vector<char>>& board, int i, int j, int rows, int cols) {\n if(board[i][j]!=\'O\') return;\n else board[i][j] = \'D\';\n \n queue<pair<int, int>> myQueue;\n myQueue.push(make_pair(i, j));\n \n while(!myQueue.empty()) {\n int x = myQueue.front().first;\n int y = myQueue.front().second;\n myQueue.pop();\n \n if(x+1<rows && board[x+1][y]==\'O\') {\n myQueue.push(make_pair(x+1, y));\n board[x+1][y] = \'D\';\n }\n if(x-1>0 && board[x-1][y]==\'O\') {\n myQueue.push(make_pair(x-1, y));\n board[x-1][y] = \'D\';\n }\n if(y+1<cols && board[x][y+1]==\'O\') {\n myQueue.push(make_pair(x, y+1));\n board[x][y+1] = \'D\';\n }\n if(y-1>0 && board[x][y-1]==\'O\') {\n myQueue.push(make_pair(x, y-1));\n board[x][y-1] = \'D\';\n }\n }\n }\n};\n```\n\n## **Union Find**\n```cpp\nclass UnionFind {\npublic:\n vector<int> parent;\n \n UnionFind(vector<vector<char>>& board, int m ,int n) {\n // Add dummy node to the tail\n for(int i=0; i<m*n+1; ++i) {\n parent.push_back(i);\n }\n }\n \n int find(int i) {\n if(i == parent[i]) return i;\n return find(parent[i]);\n }\n \n void unite(int i, int j) {\n int pi = find(i);\n int pj = find(j);\n if(pi != pj) parent[pj] = pi;\n }\n \n bool isConnect(int i, int j) {\n return find(i) == find(j);\n }\n};\n\nclass Solution {\npublic:\n void solve(vector<vector<char>>& board) {\n if(!board.size()) return;\n \n int rows = board.size();\n int cols = board[0].size();\n \n UnionFind uf = UnionFind(board, rows, cols);\n int dummy = rows * cols;\n \n for(int i=0; i<rows; ++i) {\n for(int j=0; j<cols; ++j) {\n if(board[i][j]==\'O\') {\n // If \'O\' is on boarder, connect to dummy node\n if(i==0 || i==rows-1 || j==0 || j==cols-1){\n uf.unite(i*cols+j, dummy);\n }\n // Else, connect surrounded \'O\'\n else {\n if(i>0 && board[i-1][j]==\'O\') uf.unite(i*cols+j, (i-1)*cols+j);\n if(i<rows-1 && board[i+1][j]==\'O\') uf.unite(i*cols+j, (i+1)*cols+j);\n if(j>0 && board[i][j-1]==\'O\') uf.unite(i*cols+j, i*cols+j-1);\n if(j<cols-1 && board[i][j+1]==\'O\') uf.unite(i*cols+j, i*cols+j+1);\n }\n }\n }\n }\n \n // Go through whole board check each \'O\' if it is connected to dummy node\n // If no, mark as \'X\'\n for(int i=0; i<rows; ++i) {\n for(int j=0; j<cols; ++j) {\n if(board[i][j]==\'O\'){\n if(uf.isConnect(i*cols+j, dummy) == false) board[i][j] = \'X\';\n }\n }\n }\n }\n};\n``` | 21 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Union Find', 'C'] | 1 |
surrounded-regions | C++ | DFS | Approach explained | c-dfs-approach-explained-by-nidhi_ranjan-hmdx | Approach- We apply dfs on all Os that are on boundary and mark them as #,then we just need to traverse the matrix and flip remaining Os to X as these are the on | nidhi_ranjan | NORMAL | 2021-10-01T15:50:47.942036+00:00 | 2021-10-01T15:50:47.942079+00:00 | 1,534 | false | Approach- We apply dfs on all Os that are on boundary and mark them as #,then we just need to traverse the matrix and flip remaining Os to X as these are the ones that are completely surrounded by X. Also,we flip back the #s to Os.\n\n```\nclass Solution {\npublic:\n void dfs(int i,int j,vector<vector<char>>& board){\n if(i<0 || i>=board.size() || j<0 || j>=board[0].size() || board[i][j]!=\'O\') return;\n if(board[i][j]==\'O\') board[i][j]=\'#\';\n dfs(i+1,j,board);\n dfs(i,j+1,board);\n dfs(i-1,j,board);\n dfs(i,j-1,board); \n}\n \n \n void solve(vector<vector<char>>& board) {\n int m=board.size(),n=board[0].size();\n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if((i==0 || i==m-1 || j==0 || j==n-1) && board[i][j]==\'O\'){\n dfs(i,j,board);\n }\n }\n } \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n if(board[i][j]==\'O\') board[i][j]=\'X\';\n if(board[i][j]==\'#\') board[i][j]=\'O\';\n }\n }\n }\n\n};\n```\nHope you found this useful :) | 20 | 0 | ['Depth-First Search', 'Graph', 'Recursion', 'C', 'C++'] | 1 |
surrounded-regions | Simply Simple Python approach - detailed explanation | simply-simple-python-approach-detailed-e-1d7s | \tclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n "" | limitless_ | NORMAL | 2019-10-29T01:53:33.585288+00:00 | 2019-10-29T01:53:33.585323+00:00 | 2,176 | false | \tclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n \n q = []\n \n r = len(board)\n if r == 0: return\n c = len(board[0])\n if c == 0: return\n \n\t\t# First append all the corner Os and then do bfs on these values to get the \n\t\t# neighbor Os. All Os which are connected to any corner O need to be remain \n\t\t# as O. So replace them with T and then revert it back to O.\n for i in range(r):\n for j in range(c):\n if (i == 0 or j == 0 or i == r - 1 or j == c - 1) and board[i][j] == "O":\n q.append((i,j))\n\n\n while q:\n i, j = q.pop(0)\n board[i][j] = "T"\n for x,y in [(-1, 0), (0, -1), (1, 0), (0, 1)]:\n x_n = i + x\n y_n = j + y\n \n if x_n >= 0 and x_n < r and y_n >= 0 and y_n < c and board[x_n][y_n] == "O":\n q.append((x_n, y_n))\n \n \n for i in range(r):\n for j in range(c): \n if board[i][j] == "O": # Os are the indexes which are covered by Xs\n board[i][j] = "X"\n elif board[i][j] == "T":\n board[i][j] = "O" | 19 | 0 | ['Breadth-First Search', 'Python', 'Python3'] | 5 |
surrounded-regions | Python DFS solution beats 96%, 108 ms | python-dfs-solution-beats-96-108-ms-by-m-9ksg | \nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n\t\n m , n = len(board) , len(board[0]) if m>0 else 0 \n \n d | mike840609 | NORMAL | 2019-05-18T18:09:56.804529+00:00 | 2019-05-18T18:09:56.804609+00:00 | 2,110 | false | ```\nclass Solution:\n def solve(self, board: List[List[str]]) -> None:\n\t\n m , n = len(board) , len(board[0]) if m>0 else 0 \n \n def dfs(i,j): \n if board[i][j] == "O":\n board[i][j] = \'D\'\n for x , y in [(i+1,j), (i-1,j), (i,j+1), (i,j-1)]:\n if 0<=x<m and 0<=y<n:\n dfs(x,y) \n \n for i in range(m):\n dfs(i,0)\n dfs(i,n-1)\n \n for i in range(n):\n dfs(0 ,i)\n dfs(m-1 ,i)\n \n for i in range(m):\n for j in range(n):\n if board[i][j]== \'D\' :\n board[i][j] = "O"\n else:\n board[i][j] = "X"\n``` | 19 | 0 | ['Depth-First Search', 'Python'] | 4 |
surrounded-regions | Clean JavaScript solution | clean-javascript-solution-by-hongbo-miao-ugw2 | Idea\n1) Check four borders. If it is O, change it and all its neighbor to temporary #\n2) Change all O to X\n3) Change all # to O\n\nExample\n\nX X X X X | hongbo-miao | NORMAL | 2018-06-17T06:28:13.359753+00:00 | 2020-06-17T23:29:15.702151+00:00 | 1,130 | false | Idea\n1) Check four borders. If it is O, change it and all its neighbor to temporary #\n2) Change all O to X\n3) Change all # to O\n\nExample\n```\nX X X X X X X X X X X X\nX X O X -> X X O X -> X X X X\nX O X X X # X X X O X X\nX O X X X # X X X O X X\n```\n\n```js\nfunction solve(board) {\n if (!board.length) return;\n\n // change every square connected to left and right borders from O to temporary #\n for (let i = 0; i < board.length; i++) {\n mark(board, i, 0);\n mark(board, i, board[0].length - 1);\n }\n\n // change every square connected to top and bottom borders from O to temporary #\n for (let i = 1; i < board[0].length - 1; i++) {\n mark(board, 0, i);\n mark(board, board.length - 1, i);\n }\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[0].length; j++) {\n // change the rest of O to X\n if (board[i][j] === \'O\') board[i][j] = \'X\';\n\n // change temporary # back to O\n if (board[i][j] === \'#\') board[i][j] = \'O\';\n }\n }\n}\n\nfunction mark(board, i ,j) {\n if (i < 0 || i > board.length - 1 || j < 0 || j > board[0].length - 1) return;\n if (board[i][j] !== \'O\') return;\n\n board[i][j] = \'#\';\n \n mark(board, i - 1, j);\n mark(board, i + 1, j);\n mark(board, i, j - 1);\n mark(board, i, j + 1);\n}\n```\n | 19 | 0 | [] | 3 |
surrounded-regions | Python different simple solutions | python-different-simple-solutions-by-gyh-n2v3 | DFS or BFS:\nPhase 1: Changing every O-region cells to \'D\' which touching the border .\nPhase 2: Change every \'D\' on the board to \'O\' and everything else | gyh75520 | NORMAL | 2019-08-26T07:31:43.184127+00:00 | 2019-08-26T12:44:31.937994+00:00 | 1,524 | false | # DFS or BFS:\nPhase 1: Changing every O-region cells to \'D\' which touching the border .\nPhase 2: Change every \'D\' on the board to \'O\' and everything else to \'X\'.\n```python\n def solve(self, board: List[List[str]]) -> None:\n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == \'O\' and (i in [0,len(board)-1] or j in [0,len(board[0])-1]):\n DFS(i,j) # or BFS(i,j)\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == \'O\':\n board[i][j] = \'X\'\n if board[i][j] == \'D\':\n board[i][j] = \'O\'\n```\nDFS and BFS Implementation\n```python\n def DFS(i,j):\n if 0<=i<len(board) and 0<=j<len(board[0]) and board[i][j] == \'O\':\n board[i][j] = \'D\'\n DFS(i+1,j)\n DFS(i-1,j)\n DFS(i,j+1)\n DFS(i,j-1)\n```\n```python\n def BFS(i,j):\n level = [(i,j)]\n while level:\n temp = []\n for i,j in level: \n if 0<=i<len(board) and 0<=j<len(board[0]) and board[i][j] == \'O\':\n board[i][j] = \'D\'\n temp += [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]\n level = temp\n```\n\nImplementation with deque\n```python\n def DFS(i,j):\n queue = collections.deque([(i,j)])\n while queue:\n i,j = queue.pop()\n if 0<=i<len(board) and 0<=j<len(board[0]) and board[i][j] == \'O\':\n board[i][j] = \'D\'\n queue += [(i+1,j),(i-1,j),(i,j+1),(i,j-1)] \n```\n\n```python\n def BFS(i,j):\n queue = collections.deque([(i,j)])\n while queue:\n i,j = queue.popleft()\n if 0<=i<len(board) and 0<=j<len(board[0]) and board[i][j] == \'O\':\n board[i][j] = \'D\'\n queue += [(i+1,j),(i-1,j),(i,j+1),(i,j-1)]\n```\n\n# UNION FIND:\n```python\n def solve(self, board: List[List[str]]) -> None:\n # iterate cause TLE\n # def find(x):\n # while x!=surround[x]:\n # x = surround[x]\n # return x\n \n def find(x):\n if x != surround[x]:\n surround[x] = find(surround[x])\n return surround[x]\n \n # when union, choose larger node, that\'s the reason I choose {n*m:n*m} represent touching border node\n def union(a,b):\n rootA = find(a)\n rootB = find(b)\n if rootA > rootB:\n surround[rootB] = rootA\n elif rootA < rootB:\n surround[rootA] = rootB\n \n if not board:\n return []\n \n n = len(board)\n m = len(board[0])\n \n # {n*m:n*m} means touching border node\n surround = {i:i for i in range(n*m+1)}\n \n for i in range(len(board)):\n for j in range(len(board[0])):\n if board[i][j] == \'O\':\n # find touching border node\n if i in [0,n-1] or j in [0,m-1]:\n surround[i*m+j] = n*m \n # union with the previous node: board[i-1][j],board[i][j-1]\n if i-1>=0 and board[i-1][j] == \'O\':\n union((i-1)*m+j,i*m+j)\n if j-1>=0 and board[i][j-1] == \'O\':\n union(i*m+j-1,i*m+j)\n \n for i in range(n):\n for j in range(m):\n # if root of node is not the touching border node,set to \'X\'\n if find(i*m+j)!=n*m:\n board[i][j] = \'X\'\n``` | 16 | 0 | ['Depth-First Search', 'Breadth-First Search', 'Union Find', 'Python3'] | 1 |
surrounded-regions | Python DFS Easy solution with comments | python-dfs-easy-solution-with-comments-b-7b35 | \nclass Solution:\n \n def dfs(self,board,i,j):\n \n if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]!=\'O\':\n | JoyRafatAshraf | NORMAL | 2020-04-01T06:58:41.977788+00:00 | 2020-06-17T08:28:51.874847+00:00 | 1,008 | false | ```\nclass Solution:\n \n def dfs(self,board,i,j):\n \n if i<0 or j<0 or i>=len(board) or j>=len(board[0]) or board[i][j]!=\'O\':\n return\n board[i][j]=\'$\' # converting to a dollar sign \n \n self.dfs(board,i+1,j)\n self.dfs(board,i-1,j)\n self.dfs(board,i,j+1)\n self.dfs(board,i,j-1)\n \n def solve(self, board: List[List[str]]) -> None:\n """\n Do not return anything, modify board in-place instead.\n """\n if len(board)==0:\n return None\n \n m=len(board)\n n=len(board[0])\n \n \n for i in range(m): # call dfs on all border \'O\'s and turn them to \'$\'\n for j in range(n):\n if i==0 or i==m-1:\n self.dfs(board,i,j)\n \n if j==0 or j==n-1:\n self.dfs(board,i,j)\n \n \n \n#all border O and others connected them were already converted to $ sign \n#so left out zeros are surely surrounded by \'X\' . Turn all of them to \'X\'\n for i in range(m): \n for j in range(n):\n if board[i][j]==\'O\':\n board[i][j]=\'X\'\n \n# turn the border zeros and their adjacents to their initial form. ie $ -> O \n for i in range(m):\n for j in range(n):\n if board[i][j]==\'$\':\n board[i][j]=\'O\'\n \n \n``` | 14 | 0 | ['Depth-First Search', 'Python', 'Python3'] | 5 |
surrounded-regions | Java 1ms Simple | java-1ms-simple-by-vikrant_pc-tewt | \nclass Solution {\n \n public void solve(char[][] board) {\n if(board.length == 0) return;\n boolean[][] visited;\n visited = new bo | vikrant_pc | NORMAL | 2020-06-17T07:19:18.972026+00:00 | 2020-06-18T06:55:33.738611+00:00 | 1,088 | false | ```\nclass Solution {\n \n public void solve(char[][] board) {\n if(board.length == 0) return;\n boolean[][] visited;\n visited = new boolean[board.length][board[0].length];\n \n for(int i=0;i<board.length;i++) { // Run dfs on left and right borders and change \'0\'s to \'#\'\n dfs(board, i, 0, visited);\n dfs(board, i, board[0].length-1, visited);\n }\n \n for(int j=1;j<board[0].length-1;j++) { // Run dfs on top and bottom borders and change \'0\'s to \'#\'\n dfs(board, 0, j, visited);\n dfs(board, board.length-1, j, visited);\n }\n \n for(int i=0;i<board.length;i++) \n for(int j=0;j<board[0].length;j++) \n if(board[i][j] == \'O\') // Change surrounded \'0\' to \'X\'\n board[i][j] = \'X\';\n else if(board[i][j] == \'#\') // Change \'#\' (not surrounded) back to \'0\'\n board[i][j] = \'O\';\n }\n \n public void dfs(char[][] board,int i,int j,boolean[][] visited) {\n if(i>=0 && i < board.length && j>=0 && j<board[0].length && !visited[i][j] && board[i][j] == \'O\') {\n visited[i][j] = true;\n board[i][j] = \'#\';\n dfs(board,i+1,j,visited);\n dfs(board,i-1,j,visited);\n dfs(board,i,j+1,visited);\n dfs(board,i,j-1,visited);\n }\n }\n}\n``` | 12 | 3 | [] | 1 |
surrounded-regions | C++ solution inspired from the game of I-go(20ms) | c-solution-inspired-from-the-game-of-i-g-2psa | I guess this question is inspired from Chinese traditional sport\u2014I-go. Here the task is to flip all the dead pieces. \n\nMy solution is common: perform BFS | thinkhygmailcom | NORMAL | 2015-01-09T14:31:06+00:00 | 2015-01-09T14:31:06+00:00 | 2,543 | false | I guess this question is inspired from Chinese traditional sport\u2014I-go. Here the task is to flip all the dead pieces. \n\nMy solution is common: perform BFS from live pieces('O') on the edges and mark the live pieces with temporary state '+'. After BFS done, scan the whole board to flip remaining 'O' (dead) cells and recover live pieces('+') to 'O'.\n \n class Solution {\n public:\n int row;\n int col;\n vector<pair<int, int> > move_step; \n \n void bfs(vector<vector<char> > &board, int r, int c) {\n queue<pair<int, int> > qe;\n qe.push({r, c});\n \n while(!qe.empty()) { \n r = qe.front().first;\n c = qe.front().second;\n qe.pop();\n for(int i = 0; i < 4; i++) {\n int rr = r + move_step[i].first;\n int cc = c + move_step[i].second; \n if(rr >= 0 && rr < row\n && cc >= 0 && cc < col\n && board[rr][cc] == 'O') {\n board[rr][cc] = '+';\n qe.push({rr, cc});\n }\n }\n }\n \n return;\n }\n \n void solve(vector<vector<char> > &board) {\n if (board.empty())\n return;\n \n row = board.size(); \n col = board[0].size(); \n \n move_step.resize(4);\n move_step[0] = {0,-1};\n move_step[1] = {0,1};\n move_step[2] = {-1,0};\n move_step[3] = {1,0};\n \n // BFS from four edges and mark non-surrounded(dead) cells with '+' sign\n \n // top edge\n for(int i = 0; i < col; i++) {\n if(board[0][i] == 'O') {\n board[0][i] = '+';\n bfs(board, 0, i);\n }\n }\n \n // bottom edge\n for(int i = 0; i < col; i++) {\n if(board[row-1][i] == 'O') {\n board[row-1][i] = '+';\n bfs(board, row-1, i);\n }\n }\n \n // left edge\n for(int i = 1; i < row-1; i++) {\n if(board[i][0] == 'O') {\n board[i][0] = '+';\n bfs(board, i, 0);\n }\n }\n \n // right edge\n for(int i = 1; i < row-1; i++) {\n if(board[i][col-1] == 'O') {\n board[i][col-1] = '+';\n bfs(board, i, col-1);\n }\n }\n \n // then scan all the cells, recover live cells and flip dead cells \n for(int i = 0; i < row; i++) \n for(int j = 0; j < col; j++) {\n char cur = board[i][j];\n // recover live cell marked with '+' to 'O'\n if(cur == '+') \n board[i][j] = 'O';\n // flip dead cell to '*'\n else if(cur == 'O') \n board[i][j] = 'X';\n }\n \n return;\n }\n }; | 12 | 0 | ['Breadth-First Search', 'Queue'] | 2 |
surrounded-regions | Surrounded Region | ~99% faster | surrounded-region-99-faster-by-gouravnat-2pj1 | 130. Surrounded Regions \n\n\nHi coders \uD83D\uDC4B,\n\n\uD83C\uDFC6 Runtime: 8 ms, faster than 98.69%\n Memory Usage: 10 MB, less than 79.51% \n\uD83E\u | gouravNath | NORMAL | 2021-11-01T07:20:49.954488+00:00 | 2021-11-01T13:09:58.040137+00:00 | 602 | false | <h1><b>130. Surrounded Regions</b></h1><hr>\n\n\nHi coders \uD83D\uDC4B,<br>\n\n\uD83C\uDFC6 Runtime: 8 ms, faster than **98.69%**\n Memory Usage: 10 MB, less than **79.51%** <br>\n\uD83E\uDDE0 APPROACH :\n\t\t\u25B6 Traverse the given board and replace all \u2018O\u2019 with a special character \u2018-\u2018 \n\t\t\u25B6 Traverse four edges of the given board and call **dfs** for every \u2018-\u2018 on edges. \n\t\t The remaining \u2018-\u2018 are the characters that indicate \u2018O\u2019s (in the original board) to be replaced by \u2018X\u2019.\n\t\t\u25B6 Traverse the board and replace all \u2018-\u2018s with \u2018X\u2019s.\n\t\t<br>\n```\nclass Solution {\n\tpublic:\n\t\tvoid dfs(vector<vector<char>>& board, int i, int j)\n\t\t{ \n\t\t\tif(board[i][j] == \'O\'){\n\t\t\t\tboard[i][j] = \'1\';\n\t\t\t\tif(i+1 < board.size()) dfs(board, i+1, j);\n\t\t\t\tif(i > 1) dfs(board, i-1, j);\n\t\t\t\tif(j+1 < board[i].size()) dfs(board, i, j+1);\n\t\t\t\tif(j > 1) dfs(board, i, j-1);\n\t\t\t}\n\t\t}\n\t\tvoid solve(vector<vector<char>>& board) {\n\t\t\tif(board.size() == 0)\n\t\t\t\treturn;\n\t\t\tint row = board.size(), col = board[0].size();\n\t\n\t\t\t// traversing through first row and last row\n\t\t\tfor(int i=0; i<row; i++){\n\t\t\t\tdfs(board, i, 0);\n\t\t\t\tdfs(board, i, col-1);\n\t\t\t}\n\t\t\t//traversing through first col and last col\n\t\t\tfor(int j=1; j<col-1; j++){\n\t\t\t\tdfs(board, 0, j);\n\t\t\t\tdfs(board, row-1, j);\n\t\t\t}\n\t\t\t\n\t\t\tfor (int i = 0; i < row; ++i)\n\t\t\t\tfor (int j = 0; j < col; ++j)\n\t\t\t\t\tif (board[i][j] == \'O\') board[i][j] = \'X\';\n\t\t\t\t\telse if (board[i][j] == \'1\') board[i][j] = \'O\';\n\t\t}\n\t\t// came so far \n\t\t// Please Upvote :-)\n};\n```\n<hr><br>\n\n \u2705 Runtime: 8 ms, faster than *98.69%*\n\t\t Memory Usage: 15.7 MB, less than *10.51%*\n\t\t<br>\uD83E\uDDE0 APPROACH :\n\t\t\u25B6 Here we will use a global seen variable to check if give region is connected to any boundary O\u2019s\n\t\t\u25B6 If Not connected mark all O\u2019s with X\u2019s\n\t\t<br>\t\t\n```\nclass Solution {\n bool seen; \n void mark(vector<vector<char>>& board,int i,int j,int r,int c)\n {\n if(i<0 || i>r-1 || j<0 || j>c-1)\n return;\n if(board[i][j]==\'X\')\n return;\n \n board[i][j] = \'X\';\n mark(board,i-1,j,r,c);\n mark(board,i+1,j,r,c);\n mark(board,i,j-1,r,c);\n mark(board,i,j+1,r,c); \n }\n void dfs(vector<vector<char>>& board,int i,int j,int r,int c,vector<vector<bool>>& visited)\n {\n if(i<0 || i>r-1 || j<0 || j>c-1) // checking for boundary conditions\n return;\n \n if(board[i][j]==\'X\' || visited[i][j]) \n return;\n if(i<=0 || i>=r-1 || j<=0 || j>=c-1) // if it is a boundary element mark seen as true\n seen = true;\n \n visited[i][j] = true;\n dfs(board,i-1,j,r,c,visited);\n dfs(board,i+1,j,r,c,visited);\n dfs(board,i,j-1,r,c,visited);\n dfs(board,i,j+1,r,c,visited);\n }\npublic:\n void solve(vector<vector<char>>& board) { \n int r=board.size();\n if(r<=1)\n return;\n int c=board[0].size();\n if(c<=1)\n return;\n vector<vector<bool>> visited(r,vector<bool>(c,false));\n \n for(int i=1;i<r-1;++i) // *r-1* and *c-1* : as we are not checking the boundary elements\n {\n for(int j=1;j<c-1;++j)\n {\n if(board[i][j]==\'O\' && !visited[i][j])\n {\n seen = false; // on every iteration seen is made False\n dfs(board,i,j,r,c,visited);\n if(seen==false)\n mark(board,i,j,r,c); \n seen = true;\n }\n }\n }\n }\n};\n```\n\n | 11 | 0 | ['Depth-First Search', 'Graph', 'C++'] | 0 |
surrounded-regions | JAVA 100 % FASTER🚀🚀 || STEP BY STEP EXPLAINED😉😉 | java-100-faster-step-by-step-explained-b-cngt | 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 | abhiyadav05 | NORMAL | 2023-07-23T14:01:09.471549+00:00 | 2023-07-23T14:01:09.471567+00:00 | 1,212 | 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)$$ -->O(n * m)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n * m)\n\n\n\n# Code\n```\nclass Solution {\n public void solve(char[][] board) {\n int rows = board.length;\n int cols = board[0].length;\n \n int[] delRows = {-1, 0, 1, 0}; // Array to represent changes in row index to traverse in all four directions\n int[] delCols = {0, 1, 0, -1}; // Array to represent changes in column index to traverse in all four directions\n\n int[][] visited = new int[rows][cols]; // Matrix to keep track of visited cells\n\n // Process first row and last row\n for (int i = 0; i < cols; i++) {\n // Process first row\n if (board[0][i] == \'O\' && visited[0][i] == 0) {\n dfs(0, i, board, visited, delRows, delCols); // Call the dfs method to explore the connected region of \'O\'s\n }\n // Process last row\n if (board[rows - 1][i] == \'O\' && visited[rows - 1][i] == 0) {\n dfs(rows - 1, i, board, visited, delRows, delCols); // Call the dfs method to explore the connected region of \'O\'s\n }\n }\n\n // Process first and last column\n for (int i = 0; i < rows; i++) {\n // Process first column\n if (board[i][0] == \'O\' && visited[i][0] == 0) {\n dfs(i, 0, board, visited, delRows, delCols); // Call the dfs method to explore the connected region of \'O\'s\n }\n // Process last column\n if (board[i][cols - 1] == \'O\' && visited[i][cols - 1] == 0) {\n dfs(i, cols - 1, board, visited, delRows, delCols); // Call the dfs method to explore the connected region of \'O\'s\n }\n }\n\n // Convert surrounded \'O\'s to \'X\'s\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n if (board[i][j] == \'O\' && visited[i][j] == 0) {\n board[i][j] = \'X\'; // Mark the surrounded \'O\'s as \'X\'\n }\n }\n }\n }\n\n // Depth First Search (DFS) method to explore the connected region of \'O\'s\n private static void dfs(int row, int col, char[][] board, int[][] visited, int[] delRows, int[] delCols) {\n visited[row][col] = 1; // Mark the current cell as visited\n\n int rows = board.length;\n int cols = board[0].length;\n\n // Explore all four directions\n for (int i = 0; i < 4; i++) {\n int newRow = row + delRows[i];\n int newCol = col + delCols[i];\n\n // Check if the new cell is within bounds and is an unvisited \'O\'\n if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols\n && board[newRow][newCol] == \'O\' && visited[newRow][newCol] == 0) {\n dfs(newRow, newCol, board, visited, delRows, delCols); // Recursively call dfs for the new cell\n }\n }\n }\n}\n\n``` | 10 | 0 | ['Array', 'Depth-First Search', 'Matrix', 'Java'] | 1 |
surrounded-regions | ✔️ 100% Fastest Swift Solution | 100-fastest-swift-solution-by-sergeylesc-a2zq | \nclass Solution {\n func solve(_ board: inout [[Character]]) {\n let row = board.count\n let col = board[0].count\n var map = Array(rep | sergeyleschev | NORMAL | 2022-04-11T06:39:03.737116+00:00 | 2022-04-11T06:40:45.439586+00:00 | 426 | false | ```\nclass Solution {\n func solve(_ board: inout [[Character]]) {\n let row = board.count\n let col = board[0].count\n var map = Array(repeating: Array(repeating: 0, count: col) , count: row)\n // 1...n\n var index = 1\n var indexs: [Int] = []\n \n for i in 0..<row {\n for j in 0..<col where board[i][j] == "O" && map[i][j] < 1 {\n markRegion(i, j, board, &map, index, &indexs)\n index += 1\n } \n }\n \n for i in 0..<row {\n for j in 0..<col where map[i][j] > 0 && indexs.contains(map[i][j]) == false { board[i][j] = "X" }\n }\n }\n \n\n func markRegion(_ i: Int, _ j: Int, _ board: [[Character]], _ map: inout [[Int]], _ index: Int, _ indexs: inout [Int]) {\n let row = board.count\n let col = board[0].count\n \n if i >= 0 && i < row && j >= 0 && j < col {\n if board[i][j] == "O" && map[i][j] == 0 {\n map[i][j] = index\n markRegion(i + 1, j, board, &map, index, &indexs)\n markRegion(i - 1, j, board, &map, index, &indexs)\n markRegion(i, j - 1, board, &map, index, &indexs)\n markRegion(i, j + 1, board, &map, index, &indexs) \n }\n \n } else {\n indexs.append(index)\n }\n }\n \n}\n```\n\nLet me know in comments if you have any doubts. I will be happy to answer.\n\nPlease upvote if you found the solution useful. | 10 | 0 | ['Swift'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.